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 and link markdown meeting notes (#8629)

gbirman8cd9e28b3eda
diff --git a/.sqlx/query-136e7b98319003c7f61aff7fbdb4aa8b693f9e0d2b0662b1f93068689e200206.json b/.sqlx/query-136e7b98319003c7f61aff7fbdb4aa8b693f9e0d2b0662b1f93068689e200206.json
new file mode 100644
index 0000000000..d0d41844ce
--- /dev/null
+++ b/.sqlx/query-136e7b98319003c7f61aff7fbdb4aa8b693f9e0d2b0662b1f93068689e200206.json
@@ -0,0 +1,28 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT team.id, team.name FROM team\n JOIN team_user member ON member.team_id = team.id WHERE member.user_id = $1\n ORDER BY team.name, team.id\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "name",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ false
+ ]
+ },
+ "hash": "136e7b98319003c7f61aff7fbdb4aa8b693f9e0d2b0662b1f93068689e200206"
+}
diff --git a/.sqlx/query-4da94c34c66bcc713e6d09116d41ec0c297dba6b1baac2364fd65fe0fb38dd04.json b/.sqlx/query-4da94c34c66bcc713e6d09116d41ec0c297dba6b1baac2364fd65fe0fb38dd04.json
new file mode 100644
index 0000000000..ebf5753340
--- /dev/null
+++ b/.sqlx/query-4da94c34c66bcc713e6d09116d41ec0c297dba6b1baac2364fd65fe0fb38dd04.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT EXISTS (SELECT 1 FROM team_user WHERE user_id = $1 AND team_id = $2) AS \"exists!\"",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "exists!",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "4da94c34c66bcc713e6d09116d41ec0c297dba6b1baac2364fd65fe0fb38dd04"
+}
diff --git a/.sqlx/query-57318c4dce85fa85b0de1c2e0f885dc26f0daf4eab3e1fadd393409b9f3261af.json b/.sqlx/query-57318c4dce85fa85b0de1c2e0f885dc26f0daf4eab3e1fadd393409b9f3261af.json
new file mode 100644
index 0000000000..060cbe2781
--- /dev/null
+++ b/.sqlx/query-57318c4dce85fa85b0de1c2e0f885dc26f0daf4eab3e1fadd393409b9f3261af.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT EXISTS (SELECT 1 FROM calendar_event_occurrences WHERE event_id = $1 AND calendar_note_link_key($1, occurrence_key) = calendar_note_link_key($1, $2) AND NOT is_cancelled) AS \"exists!\"",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "exists!",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "57318c4dce85fa85b0de1c2e0f885dc26f0daf4eab3e1fadd393409b9f3261af"
+}
diff --git a/.sqlx/query-718a734ca1b531d26b2ff84915e9633359af1b17a7b0c3fc5026a61fd0549047.json b/.sqlx/query-718a734ca1b531d26b2ff84915e9633359af1b17a7b0c3fc5026a61fd0549047.json
new file mode 100644
index 0000000000..8082335509
--- /dev/null
+++ b/.sqlx/query-718a734ca1b531d26b2ff84915e9633359af1b17a7b0c3fc5026a61fd0549047.json
@@ -0,0 +1,48 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT d.id, d.name, team.id AS \"team_id?\", team.name AS \"team_name?\",\n d.owner = $1 AS \"can_manage!\"\n FROM calendar_event_notes note\n JOIN calendar_events event ON event.id = note.event_id\n JOIN calendar_events requested ON requested.id = $2\n AND requested.ical_uid = event.ical_uid\n AND lower(requested.organizer_email) IS NOT DISTINCT FROM lower(event.organizer_email)\n JOIN \"Document\" d ON d.id = note.document_id AND d.\"deletedAt\" IS NULL AND d.\"fileType\" = 'md'\n LEFT JOIN team ON team.id = note.team_id\n WHERE note.occurrence_key = calendar_note_link_key($2, $3) AND event.status <> 'cancelled'\n AND calendar_note_event_visible($1, note.event_id, note.occurrence_key)\n AND calendar_note_copies_match(requested.id, note.event_id, calendar_note_link_key($2, $3))\n ORDER BY note.created_at, d.id\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "name",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "team_id?",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 3,
+ "name": "team_name?",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 4,
+ "name": "can_manage!",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ false,
+ null
+ ]
+ },
+ "hash": "718a734ca1b531d26b2ff84915e9633359af1b17a7b0c3fc5026a61fd0549047"
+}
diff --git a/.sqlx/query-90f303813158f4ec3b39e4457a7623b1a982f4916f93f6ecf3e9c047cfbf232a.json b/.sqlx/query-90f303813158f4ec3b39e4457a7623b1a982f4916f93f6ecf3e9c047cfbf232a.json
new file mode 100644
index 0000000000..92d7e21ffc
--- /dev/null
+++ b/.sqlx/query-90f303813158f4ec3b39e4457a7623b1a982f4916f93f6ecf3e9c047cfbf232a.json
@@ -0,0 +1,24 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT calendar_note_event_visible($1, $2, calendar_note_link_key($2, $3)) AS \"visible!\"",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "visible!",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "90f303813158f4ec3b39e4457a7623b1a982f4916f93f6ecf3e9c047cfbf232a"
+}
diff --git a/.sqlx/query-ada5231f3d25c542337e68f115f8cc3f13a1340ab17e04bc9d8a5e2ed2f30754.json b/.sqlx/query-ada5231f3d25c542337e68f115f8cc3f13a1340ab17e04bc9d8a5e2ed2f30754.json
new file mode 100644
index 0000000000..1ad6e48fa8
--- /dev/null
+++ b/.sqlx/query-ada5231f3d25c542337e68f115f8cc3f13a1340ab17e04bc9d8a5e2ed2f30754.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n DELETE FROM calendar_event_notes note USING calendar_events event, calendar_events requested\n WHERE note.event_id = event.id AND requested.id = $1\n AND event.ical_uid = requested.ical_uid\n AND lower(event.organizer_email) IS NOT DISTINCT FROM lower(requested.organizer_email)\n AND (note.occurrence_key = $2 OR note.occurrence_key = calendar_note_link_key($1, $2)) AND note.document_id = $3\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "ada5231f3d25c542337e68f115f8cc3f13a1340ab17e04bc9d8a5e2ed2f30754"
+}
diff --git a/.sqlx/query-bb02b8092869f8b1d8a3233316bc98c94ba244e37e31957ad33c2297fc671652.json b/.sqlx/query-bb02b8092869f8b1d8a3233316bc98c94ba244e37e31957ad33c2297fc671652.json
new file mode 100644
index 0000000000..096357e02f
--- /dev/null
+++ b/.sqlx/query-bb02b8092869f8b1d8a3233316bc98c94ba244e37e31957ad33c2297fc671652.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT EXISTS (\n SELECT 1 FROM calendar_event_notes note\n JOIN \"Document\" d ON d.id = note.document_id\n AND d.\"deletedAt\" IS NULL AND d.\"fileType\" = 'md'\n WHERE note.document_id = $1 AND (\n calendar_note_event_visible($2, note.event_id, note.occurrence_key)\n OR EXISTS (\n SELECT 1 FROM team_user member\n WHERE member.team_id = note.team_id AND member.user_id = $2\n )\n )\n ) AS \"visible!\"\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "visible!",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "bb02b8092869f8b1d8a3233316bc98c94ba244e37e31957ad33c2297fc671652"
+}
diff --git a/.sqlx/query-bd3d358ba1c3902d295476a49edd77fd7022d66a70a89342ab4cda3f2c43f989.json b/.sqlx/query-bd3d358ba1c3902d295476a49edd77fd7022d66a70a89342ab4cda3f2c43f989.json
new file mode 100644
index 0000000000..009cac6ece
--- /dev/null
+++ b/.sqlx/query-bd3d358ba1c3902d295476a49edd77fd7022d66a70a89342ab4cda3f2c43f989.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n DELETE FROM calendar_event_notes note USING calendar_events event, calendar_events requested\n WHERE note.event_id = event.id AND requested.id = $1\n AND event.ical_uid = requested.ical_uid\n AND lower(event.organizer_email) IS NOT DISTINCT FROM lower(requested.organizer_email)\n AND note.occurrence_key = calendar_note_link_key($1, $2) AND note.document_id = $3 AND note.event_id <> $1\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "bd3d358ba1c3902d295476a49edd77fd7022d66a70a89342ab4cda3f2c43f989"
+}
diff --git a/.sqlx/query-bf7af6db65b2268e241ce154c32729ffdcb80ecd395827fe003e4bdde55ca349.json b/.sqlx/query-bf7af6db65b2268e241ce154c32729ffdcb80ecd395827fe003e4bdde55ca349.json
new file mode 100644
index 0000000000..0776c3a04d
--- /dev/null
+++ b/.sqlx/query-bf7af6db65b2268e241ce154c32729ffdcb80ecd395827fe003e4bdde55ca349.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT EXISTS (SELECT 1 FROM \"Document\" WHERE id = $1 AND \"fileType\" = 'md' AND \"deletedAt\" IS NULL) AS \"exists!\"",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "exists!",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "bf7af6db65b2268e241ce154c32729ffdcb80ecd395827fe003e4bdde55ca349"
+}
diff --git a/.sqlx/query-dfae0eee308e6c895ea971b451866bae98e3b75a336c1cd2dcae15ea0b63de0d.json b/.sqlx/query-dfae0eee308e6c895ea971b451866bae98e3b75a336c1cd2dcae15ea0b63de0d.json
new file mode 100644
index 0000000000..2b4276a72e
--- /dev/null
+++ b/.sqlx/query-dfae0eee308e6c895ea971b451866bae98e3b75a336c1cd2dcae15ea0b63de0d.json
@@ -0,0 +1,53 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT note.event_id, note.occurrence_key, document.name AS document_name,\n CASE WHEN calendar_note_event_visible($1, note.event_id, note.occurrence_key)\n THEN CASE WHEN event.owner_id = $1 OR EXISTS (\n SELECT 1 FROM macro_user_links delegate\n WHERE delegate.link_id = event.source_link_id AND delegate.primary_macro_id = $1\n ) THEN event.title ELSE 'Shared meeting' END\n ELSE 'Unavailable meeting' END AS \"event_title!\",\n team.id AS \"team_id?\", team.name AS \"team_name?\"\n FROM calendar_event_notes note\n JOIN \"Document\" document ON document.id = note.document_id AND document.owner = $1 AND document.\"deletedAt\" IS NULL\n JOIN calendar_events event ON event.id = note.event_id\n LEFT JOIN team ON team.id = note.team_id\n WHERE note.document_id = $2\n ORDER BY note.created_at, note.event_id, note.occurrence_key\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "event_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "occurrence_key",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "document_name",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "event_title!",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 4,
+ "name": "team_id?",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 5,
+ "name": "team_name?",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ null,
+ false,
+ false
+ ]
+ },
+ "hash": "dfae0eee308e6c895ea971b451866bae98e3b75a336c1cd2dcae15ea0b63de0d"
+}
diff --git a/.sqlx/query-f496ee6f2c6552827ce68aae06f35d662c2c0228d2b80493090c3aa1e3730828.json b/.sqlx/query-f496ee6f2c6552827ce68aae06f35d662c2c0228d2b80493090c3aa1e3730828.json
new file mode 100644
index 0000000000..3d1ea8de54
--- /dev/null
+++ b/.sqlx/query-f496ee6f2c6552827ce68aae06f35d662c2c0228d2b80493090c3aa1e3730828.json
@@ -0,0 +1,18 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO calendar_event_notes (event_id, occurrence_key, document_id, team_id, user_id)\n VALUES ($1, calendar_note_link_key($1, $2), $3, $4, $5)\n ON CONFLICT (event_id, occurrence_key, document_id) DO UPDATE SET team_id = EXCLUDED.team_id, user_id = EXCLUDED.user_id\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Text",
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "f496ee6f2c6552827ce68aae06f35d662c2c0228d2b80493090c3aa1e3730828"
+}
diff --git a/.sqlx/query-fee0bf0248959985bdea594b2a3b2c569d8e6db9620d99a8ca7774f4b1bbaa84.json b/.sqlx/query-fee0bf0248959985bdea594b2a3b2c569d8e6db9620d99a8ca7774f4b1bbaa84.json
new file mode 100644
index 0000000000..1e0156233e
--- /dev/null
+++ b/.sqlx/query-fee0bf0248959985bdea594b2a3b2c569d8e6db9620d99a8ca7774f4b1bbaa84.json
@@ -0,0 +1,29 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT id AS document_id, name FROM \"Document\"\n WHERE owner = $1 AND \"fileType\" = 'md' AND \"deletedAt\" IS NULL\n AND name ILIKE '%' || $2 || '%'\n ORDER BY \"updatedAt\" DESC, id LIMIT 30\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "document_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "name",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ false
+ ]
+ },
+ "hash": "fee0bf0248959985bdea594b2a3b2c569d8e6db9620d99a8ca7774f4b1bbaa84"
+}
diff --git a/Cargo.lock b/Cargo.lock
index 5fd0f8e03e..57cefa5b04 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3744,6 +3744,7 @@ dependencies = [
"chrono",
"chrono-tz",
"email_utils",
+ "entity_access",
"futures",
"macro_authorization",
"macro_db_migrator",
@@ -3816,6 +3817,7 @@ dependencies = [
"email_api_client",
"email_db_client",
"email_utils",
+ "entity_access",
"futures",
"google_token",
"macro_auth",
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.md
index e0e574a81d..de0841c8a9 100644
--- a/apps/web/AGENTS.md
+++ b/apps/web/AGENTS.md
@@ -25,6 +25,17 @@ It exercises the real resize solver, scroll container, and Lexical layout primit
Discussion link scrolling has a backend-free browser regression:
`bunx playwright test --config src/lib/core/messages/browser-test/playwright.config.ts`.
+Meeting-note creation, linking, optional team access, retry, and unlinking have desktop and
+phone browser coverage in `features/calendar-notes`:
+`bunx playwright test --config src/features/calendar-notes/browser-test/playwright.config.ts`.
+The browser fixture uses the real event details popover and mobile drawer over
+sample data; keep notes aligned with those existing surfaces and preserve their
+dialog open guards. Optional note sharing uses existing team memberships.
+Gate event notes and document Share meeting-link controls with
+`enable-calendar-meeting-notes` before mounting their query sources; it defaults
+on in dev and uses PostHog in production.
+See `docs/agent-guide/calendar.md` at the repo root.
+
A frontend dev server runs against the **dev** backend, so this needs no local stack, Docker, Rust build, or `sudo`:
```sh
diff --git a/apps/web/src/components/ui/components/Dialog.tsx b/apps/web/src/components/ui/components/Dialog.tsx
index b3485afd92..8cf1fd526f 100644
--- a/apps/web/src/components/ui/components/Dialog.tsx
+++ b/apps/web/src/components/ui/components/Dialog.tsx
@@ -38,6 +38,8 @@ export type DialogProps = {
visibleScrim?: boolean /* if the scrim is visible */;
/** Desktop opening animation; mobile drawers own their transitions. */
animate?: boolean;
+ /** Constrain children on mobile so their own scroll regions can resize. */
+ contentOwnsScroll?: boolean;
};
export function Dialog(props: DialogProps) {
@@ -83,13 +85,22 @@ function DialogDrawer(props: DialogProps) {
class={cn('mx-auto max-w-[calc(100vw-16px)]', props.class)}
>
<MobileDrawer.Handle aria-hidden="true" />
- <MobileDrawer.ScrollBody>
- {/* Give desktop surfaces their natural height so their size-full
+ <Show
+ when={props.contentOwnsScroll}
+ fallback={
+ <MobileDrawer.ScrollBody>
+ {/* Give desktop surfaces their natural height so their size-full
and overflow-clip styles cannot clip the drawer's scroll body. */}
- <div class="shrink-0 [&>[data-layer]>[data-surface]]:border-0! [&>[data-layer]>[data-surface]]:rounded-none [&>[data-layer]>[data-surface]]:bg-transparent">
+ <div class="shrink-0 [&>[data-layer]>[data-surface]]:border-0! [&>[data-layer]>[data-surface]]:rounded-none [&>[data-layer]>[data-surface]]:bg-transparent">
+ {props.children}
+ </div>
+ </MobileDrawer.ScrollBody>
+ }
+ >
+ <div class="flex min-h-0 flex-auto flex-col">
{props.children}
</div>
- </MobileDrawer.ScrollBody>
+ </Show>
</MobileDrawer.Content>
</MobileDrawer.Portal>
</MobileDrawer>
diff --git a/apps/web/src/components/ui/components/Tooltip.tsx b/apps/web/src/components/ui/components/Tooltip.tsx
index 15ac87ce1b..1e136a69e4 100644
--- a/apps/web/src/components/ui/components/Tooltip.tsx
+++ b/apps/web/src/components/ui/components/Tooltip.tsx
@@ -40,6 +40,8 @@ export function tooltipClasses(options: TooltipClassOptions = {}): string {
}
/**
+ * Informational content never intercepts pointer input to nearby controls.
+ *
* @example
* <Tooltip label="" hotkey={}>
* <div></div>
@@ -142,7 +144,7 @@ export function Tooltip(props: TooltipProps) {
</KobalteTooltip.Trigger>
<Show when={visible()}>
<KobalteTooltip.Portal>
- <KobalteTooltip.Content class="z-tool-tip max-w-[calc(100vw-32px)]">
+ <KobalteTooltip.Content class="pointer-events-none! z-tool-tip max-w-[calc(100vw-32px)]">
<Surface class={tooltipClasses()} depth={3}>
<div class="flex flex-row items-center gap-2">
<div class="text-xs">{props.label}</div>
diff --git a/apps/web/src/features/calendar-notes/browser-test/fixture.tsx b/apps/web/src/features/calendar-notes/browser-test/fixture.tsx
new file mode 100644
index 0000000000..7e6bcd83af
--- /dev/null
+++ b/apps/web/src/features/calendar-notes/browser-test/fixture.tsx
@@ -0,0 +1,213 @@
+import '@fontsource-variable/inter';
+import '../../../index.css';
+import { fireAndForget } from '@core/util/fireAndForget';
+import CalendarIcon from '@phosphor/calendar-blank.svg';
+import { Button, ImperativeDialogHost } from '@ui';
+import { ok } from 'neverthrow';
+import { createSignal, onCleanup, Show } from 'solid-js';
+import { render } from 'solid-js/web';
+import type { CalendarEvent } from '../../calendar/types';
+import { SelectedEventDetails } from '../../calendar-view/components/SelectedEventDetails';
+import { macroDarkTheme } from '../../theme/themes/macro-dark';
+import { macroLightTheme } from '../../theme/themes/macro-light';
+import type { DocumentNoteLink } from '../core/types';
+import { createFakeNotesSource } from '../tests/fake-source';
+import { DocumentNotesView } from '../views/document-notes';
+import { PreviewNotesProvider } from './preview-adapters';
+
+const params = new URLSearchParams(location.search);
+document.documentElement.dataset.themeLight = String(
+ params.get('theme') !== 'dark'
+);
+const theme = params.get('theme') === 'dark' ? macroDarkTheme : macroLightTheme;
+for (const [token, value] of Object.entries(theme.colorTokens)) {
+ document.documentElement.style.setProperty(`--color-${token}`, value);
+}
+
+const calendar = { id: 'calendar-1', name: 'Calendar', color: '#609fe2' };
+const sampleEvent: CalendarEvent = {
+ id: 'weekly-sync',
+ eventId: 'event-1',
+ occurrenceKey: '2026-10-23T14:00:00Z',
+ title: 'Weekly product sync',
+ start: '2026-10-23T14:00:00Z',
+ end: '2026-10-23T14:30:00Z',
+ allDay: false,
+ isCancelled: false,
+ isReadOnly: false,
+ description: 'Review progress, decisions, and next steps.',
+ recurrenceLines: ['RRULE:FREQ=WEEKLY;BYDAY=FR'],
+ guestPolicy: {
+ canModify: false,
+ canInviteOthers: true,
+ canSeeOtherGuests: true,
+ },
+ viewerCan: {
+ editDetails: false,
+ inviteGuests: true,
+ removeGuests: false,
+ setGuestPolicy: false,
+ rsvp: true,
+ organize: false,
+ },
+ attendees: [
+ {
+ email: '[email protected]',
+ isOptional: false,
+ isOrganizer: true,
+ isSelf: false,
+ responseStatus: 'accepted',
+ },
+ {
+ email: '[email protected]',
+ isOptional: false,
+ isOrganizer: false,
+ isSelf: false,
+ responseStatus: 'accepted',
+ },
+ {
+ email: '[email protected]',
+ isOptional: false,
+ isOrganizer: false,
+ isSelf: true,
+ responseStatus: 'accepted',
+ },
+ ],
+ organizerEmail: '[email protected]',
+ sourceCalendarIds: [calendar.id],
+ calendarId: calendar.id,
+ calendar,
+ visibleCalendars: [calendar],
+};
+
+function Fixture() {
+ const [links, setLinks] = createSignal<DocumentNoteLink[]>([
+ {
+ eventId: 'unavailable',
+ occurrenceKey: '2026-10-23T14:00:00Z',
+ eventTitle: 'Unavailable meeting',
+ team: { id: 'macro', name: 'Macro' },
+ },
+ ]);
+ if (params.has('document'))
+ return (
+ <main class="min-h-dvh bg-page px-3 py-10 text-ink">
+ <div class="mx-auto max-w-[480px]">
+ <h1 class="mb-4 text-lg font-semibold">
+ Share: Weekly product notes
+ </h1>
+ <DocumentNotesView
+ source={{
+ links: () => ({ data: links(), pending: false }),
+ retry: async () => {},
+ unlink: async () => {
+ setLinks([]);
+ return ok(undefined);
+ },
+ }}
+ />
+ <p class="mt-4 text-sm">Your document is saved.</p>
+ </div>
+ </main>
+ );
+ const fake = createFakeNotesSource({
+ fail: params.has('fail'),
+ });
+ const teamProjectionKind = params.get('team');
+ const [event, setEvent] = createSignal<CalendarEvent>({
+ ...sampleEvent,
+ teamProjection:
+ teamProjectionKind === 'details' || teamProjectionKind === 'busy'
+ ? { kind: teamProjectionKind, ownerId: 'macro|[email protected]' }
+ : undefined,
+ guestPolicy: {
+ ...sampleEvent.guestPolicy,
+ canSeeOtherGuests: !params.has('hidden'),
+ },
+ });
+ const [selected, setSelected] = createSignal(true);
+ const [boundary, setBoundary] = createSignal<HTMLDivElement>();
+ const [anchor, setAnchor] = createSignal<HTMLButtonElement>();
+ const [message, setMessage] = createSignal('');
+ const onMessage = (event: Event) => {
+ if (event instanceof CustomEvent && typeof event.detail === 'string')
+ setMessage(event.detail);
+ };
+ const onRsvp = (event: Event) => {
+ if (!(event instanceof CustomEvent)) return;
+ const response = event.detail;
+ if (
+ response !== 'accepted' &&
+ response !== 'tentative' &&
+ response !== 'declined'
+ )
+ return;
+ setEvent((current) => ({
+ ...current,
+ attendees: current.attendees.map((attendee) =>
+ attendee.isSelf ? { ...attendee, responseStatus: response } : attendee
+ ),
+ }));
+ };
+ const onRemoteUnlink = (event: Event) => {
+ if (event instanceof CustomEvent && typeof event.detail === 'string') {
+ fireAndForget(
+ fake.source.unlink(event.detail),
+ 'calendar.preview.unlink'
+ );
+ }
+ };
+ document.addEventListener('calendar-preview-message', onMessage);
+ document.addEventListener('calendar-preview-rsvp', onRsvp);
+ document.addEventListener('calendar-preview-unlink', onRemoteUnlink);
+ onCleanup(() => {
+ document.removeEventListener('calendar-preview-message', onMessage);
+ document.removeEventListener('calendar-preview-rsvp', onRsvp);
+ document.removeEventListener('calendar-preview-unlink', onRemoteUnlink);
+ });
+ return (
+ <PreviewNotesProvider source={fake.source}>
+ <main
+ ref={setBoundary}
+ class="relative min-h-dvh bg-page p-4 text-ink sm:p-8"
+ >
+ <div class="flex items-center gap-2 text-sm text-ink-muted">
+ <CalendarIcon class="size-4" /> Friday, October 23
+ </div>
+ <Button
+ ref={setAnchor}
+ variant="outline"
+ size="md"
+ class="mt-5"
+ onClick={() => setSelected(true)}
+ >
+ Weekly product sync
+ </Button>
+ <Show when={message()}>
+ <p
+ role="status"
+ aria-label="Preview action"
+ class="mt-4 text-sm text-ink-muted"
+ >
+ {message()}
+ </p>
+ </Show>
+ <Show when={boundary()}>
+ {(element) => (
+ <SelectedEventDetails
+ boundary={element()}
+ anchor={anchor}
+ event={() => (selected() ? event() : undefined)}
+ timeFormat={() => '12-hour'}
+ onClose={() => setSelected(false)}
+ />
+ )}
+ </Show>
+ <ImperativeDialogHost />
+ </main>
+ </PreviewNotesProvider>
+ );
+}
+
+const root = document.getElementById('root');
+if (root) render(() => <Fixture />, root);
diff --git a/apps/web/src/features/calendar-notes/browser-test/index.html b/apps/web/src/features/calendar-notes/browser-test/index.html
new file mode 100644
index 0000000000..7109c4b797
--- /dev/null
+++ b/apps/web/src/features/calendar-notes/browser-test/index.html
@@ -0,0 +1,5 @@
+<!doctype html>
+<html lang="en" data-modality="keyboard">
+ <head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>Meeting notes</title></head>
+ <body><div id="root"></div><script type="module" src="/fixture.tsx"></script></body>
+</html>
diff --git a/apps/web/src/features/calendar-notes/browser-test/notes.browser.e2e.ts b/apps/web/src/features/calendar-notes/browser-test/notes.browser.e2e.ts
new file mode 100644
index 0000000000..d499ac8053
--- /dev/null
+++ b/apps/web/src/features/calendar-notes/browser-test/notes.browser.e2e.ts
@@ -0,0 +1,408 @@
+import { expect, test } from '@playwright/test';
+
+test('full-detail team viewers can link and open notes without provider actions', async ({
+ page,
+}) => {
+ await page.goto('/?team=details');
+ const notes = page.getByRole('region', { name: 'Meeting notes' });
+ await notes
+ .getByRole('button', { name: 'Link existing', exact: true })
+ .click();
+ const dialog = page.getByRole('dialog', { name: 'Link meeting notes' });
+ await dialog
+ .getByRole('button', { name: 'Weekly product sync', exact: true })
+ .click();
+ await dialog.getByRole('button', { name: 'Link note', exact: true }).click();
+ await notes
+ .getByRole('button', { name: 'Open Weekly product sync', exact: true })
+ .click();
+ await expect(page.getByRole('status', { name: 'Preview action' })).toHaveText(
+ 'Opened Weekly product sync'
+ );
+
+ await page
+ .getByRole('button', { name: 'Weekly product sync', exact: true })
+ .click();
+ await expect(notes).toBeVisible();
+ await expect(
+ page.getByRole('button', { name: 'Yes', exact: true })
+ ).toHaveCount(0);
+ await expect(
+ page.getByRole('button', { name: 'Edit event', exact: true })
+ ).toHaveCount(0);
+
+ await page.goto('/?team=busy');
+ await expect(
+ page.getByRole('button', { name: 'Close event details', exact: true })
+ ).toBeVisible();
+ await expect(notes).toHaveCount(0);
+});
+
+test('a note tooltip does not block selecting a neighboring document', async ({
+ page,
+ isMobile,
+}) => {
+ test.skip(isMobile, 'Touch devices do not show hover tooltips');
+ await page.goto('/');
+ await page
+ .getByRole('button', { name: 'Link existing', exact: true })
+ .click();
+ const dialog = page.getByRole('dialog', { name: 'Link meeting notes' });
+ await dialog
+ .getByRole('button', { name: 'Weekly product sync', exact: true })
+ .hover();
+ await expect(page.getByRole('tooltip', { includeHidden: true })).toHaveText(
+ 'Weekly product sync'
+ );
+ await dialog
+ .getByRole('button', { name: 'Q4 product roadmap', exact: true })
+ .click();
+ await dialog.getByRole('button', { name: 'Link note', exact: true }).click();
+ await expect(dialog).not.toBeVisible();
+ await expect(
+ page.getByRole('button', { name: 'Open Q4 product roadmap', exact: true })
+ ).toBeVisible();
+});
+
+test('create and open multiple notes with meeting access and no team sharing', async ({
+ page,
+}) => {
+ await page.goto('/');
+ const notes = page.getByRole('region', { name: 'Meeting notes' });
+ await notes
+ .getByRole('button', { name: 'Create notes', exact: true })
+ .click();
+ await expect(page.getByRole('status', { name: 'Preview action' })).toHaveText(
+ 'Opened Weekly product sync notes'
+ );
+ await expect(notes).not.toBeVisible();
+ await page
+ .getByRole('button', { name: 'Weekly product sync', exact: true })
+ .click();
+ await expect(
+ notes.getByRole('button', {
+ name: 'Open Weekly product sync notes',
+ exact: true,
+ })
+ ).toHaveCount(1);
+ await expect(notes).not.toContainText('Also shared with Macro');
+ await notes
+ .getByRole('button', { name: 'Create notes', exact: true })
+ .click();
+ await expect(notes).not.toBeVisible();
+ await page
+ .getByRole('button', { name: 'Weekly product sync', exact: true })
+ .click();
+ await expect(
+ notes.getByRole('button', {
+ name: 'Open Weekly product sync notes',
+ exact: true,
+ })
+ ).toHaveCount(2);
+ await expect(
+ notes.getByRole('button', { name: 'Options for Weekly product sync notes' })
+ ).toHaveCount(2);
+});
+
+test('retry linking a newly created note without duplicating the document', async ({
+ page,
+}) => {
+ await page.goto('/?fail=1');
+ const notes = page.getByRole('region', { name: 'Meeting notes' });
+ await notes
+ .getByRole('button', { name: 'Create notes', exact: true })
+ .click();
+ await expect(notes.getByRole('alert')).toContainText('Your note was saved');
+ await expect(
+ notes.getByRole('button', { name: 'Open saved note' })
+ ).toBeVisible();
+ await notes
+ .getByRole('button', { name: 'Retry linking', exact: true })
+ .click();
+ await expect(notes).not.toBeVisible();
+ await page
+ .getByRole('button', { name: 'Weekly product sync', exact: true })
+ .click();
+ await expect(
+ notes.getByRole('button', {
+ name: 'Open Weekly product sync notes',
+ exact: true,
+ })
+ ).toHaveCount(1);
+ await notes.getByRole('button', { name: 'Link existing' }).click();
+ const dialog = page.getByRole('dialog', { name: 'Link meeting notes' });
+ await expect(
+ dialog.getByRole('button', {
+ name: 'Weekly product sync notes',
+ exact: true,
+ })
+ ).toHaveCount(1);
+ await expect(
+ dialog.getByRole('button', {
+ name: 'Weekly product sync notes',
+ exact: true,
+ })
+ ).toBeDisabled();
+});
+
+test('an owner can revoke a missing meeting’s team grant from document sharing', async ({
+ page,
+}) => {
+ await page.goto('/?document=1');
+ const links = page.getByRole('region', { name: 'Meeting links' });
+ await expect(links).toContainText('Unavailable meeting');
+ await expect(links).toContainText('Macro');
+ await links.getByRole('button', { name: 'Unlink', exact: true }).click();
+ await links.getByRole('button', { name: 'Keep link' }).click();
+ await expect(links).toBeVisible();
+ await links.getByRole('button', { name: 'Unlink', exact: true }).click();
+ await links
+ .getByRole('button', { name: 'Unlink meeting', exact: true })
+ .click();
+ await expect(links).not.toBeVisible();
+ await expect(page.getByText('Your document is saved.')).toBeVisible();
+});
+
+test('link a note, optionally share with a team, open it, and unlink it', async ({
+ page,
+}, testInfo) => {
+ await page.goto('/');
+ await page
+ .getByRole('button', { name: 'Link existing', exact: true })
+ .click();
+ const dialog = page.getByRole('dialog', {
+ name: /Link meeting notes|Note access|Unlink meeting notes/,
+ });
+ await expect(
+ dialog.getByRole('button', { name: 'Link note', exact: true })
+ ).toBeDisabled();
+ await dialog
+ .getByRole('textbox', { name: 'Find a markdown document' })
+ .fill('weekly');
+ await dialog
+ .getByRole('button', { name: 'Weekly product sync', exact: true })
+ .click();
+ await expect(
+ dialog.getByRole('checkbox', { name: /Also share with Macro/ })
+ ).not.toBeChecked();
+ await expect(
+ dialog.getByRole('button', { name: 'Link note', exact: true })
+ ).toBeInViewport();
+ await page.screenshot({ path: testInfo.outputPath('link-note.png') });
+ await dialog.getByRole('button', { name: 'Link note', exact: true }).click();
+ await expect(dialog).not.toBeVisible();
+ await page
+ .getByRole('button', { name: 'Options for Weekly product sync' })
+ .click();
+ await page.getByRole('menuitem', { name: 'Manage access' }).click();
+ await dialog.getByText('Also share with Macro').click();
+ await dialog.getByRole('button', { name: 'Save access' }).click();
+ await expect(dialog).not.toBeVisible();
+ await expect(
+ page.getByRole('region', { name: 'Meeting notes' })
+ ).toContainText('Also shared with Macro');
+ await page.screenshot({ path: testInfo.outputPath('linked-note.png') });
+ await page
+ .getByRole('region', { name: 'Meeting notes' })
+ .getByRole('button', { name: 'Open Weekly product sync', exact: true })
+ .click();
+ await expect(page.getByRole('status', { name: 'Preview action' })).toHaveText(
+ 'Opened Weekly product sync'
+ );
+ await page
+ .getByRole('button', { name: 'Weekly product sync', exact: true })
+ .click();
+ await page
+ .getByRole('button', { name: 'Options for Weekly product sync' })
+ .click();
+ await page.getByRole('menuitem', { name: 'Unlink from meeting' }).click();
+ await dialog
+ .getByRole('button', { name: 'Unlink note', exact: true })
+ .click();
+ await expect(
+ page.getByRole('button', { name: 'Link existing', exact: true })
+ ).toBeVisible();
+ await page
+ .getByRole('button', { name: 'Link existing', exact: true })
+ .click();
+ await expect(
+ dialog.getByRole('button', { name: 'Weekly product sync', exact: true })
+ ).toBeEnabled();
+});
+
+test('a failed link preserves the selected document and sharing choice for retry', async ({
+ page,
+}) => {
+ await page.goto('/?fail=1');
+ await page
+ .getByRole('button', { name: 'Link existing', exact: true })
+ .click();
+ const dialog = page.getByRole('dialog', {
+ name: /Link meeting notes|Note access|Unlink meeting notes/,
+ });
+ await dialog
+ .getByRole('button', { name: 'Weekly product sync', exact: true })
+ .click();
+ await dialog.getByText('Also share with Macro').click();
+ await dialog.getByRole('button', { name: 'Link note', exact: true }).click();
+ await expect(dialog.getByRole('alert')).toBeVisible();
+ await expect(
+ dialog.getByRole('button', { name: 'Weekly product sync', exact: true })
+ ).toHaveAttribute('aria-pressed', 'true');
+ await expect(
+ dialog.getByRole('checkbox', { name: /Also share with Macro/ })
+ ).toBeChecked();
+ await dialog.getByRole('button', { name: 'Link note', exact: true }).click();
+ await expect(dialog).not.toBeVisible();
+ await expect(
+ page.getByRole('region', { name: 'Meeting notes' })
+ ).toContainText('Also shared with Macro');
+});
+
+test('removing a note during an open options menu does not block event dismissal', async ({
+ page,
+}) => {
+ await page.goto('/');
+ await page
+ .getByRole('button', { name: 'Link existing', exact: true })
+ .click();
+ const dialog = page.getByRole('dialog', { name: 'Link meeting notes' });
+ await dialog
+ .getByRole('button', { name: 'Weekly product sync', exact: true })
+ .click();
+ await dialog.getByRole('button', { name: 'Link note', exact: true }).click();
+ await page
+ .getByRole('button', { name: 'Options for Weekly product sync' })
+ .click();
+ await expect(
+ page.getByRole('menuitem', { name: 'Manage access' })
+ ).toBeVisible();
+ await page.evaluate(() =>
+ document.dispatchEvent(
+ new CustomEvent('calendar-preview-unlink', { detail: 'weekly' })
+ )
+ );
+ await expect(
+ page.getByRole('menuitem', { name: 'Manage access' })
+ ).not.toBeVisible();
+ await page.keyboard.press('Escape');
+ await expect(
+ page.getByRole('region', { name: 'Meeting notes' })
+ ).not.toBeVisible();
+ await page
+ .getByRole('button', { name: 'Weekly product sync', exact: true })
+ .click();
+ await expect(
+ page.getByRole('region', { name: 'Meeting notes' })
+ ).toBeVisible();
+});
+
+test('short dialogs scroll only the note results and keep context, sharing, and actions visible', async ({
+ page,
+}) => {
+ await page.setViewportSize({
+ width: page.viewportSize()?.width ?? 400,
+ height: 520,
+ });
+ await page.goto('/');
+ await page
+ .getByRole('button', { name: 'Link existing', exact: true })
+ .click();
+ const dialog = page.getByRole('dialog', { name: 'Link meeting notes' });
+ const title = dialog.getByRole('heading', { name: 'Link meeting notes' });
+ const sharing = dialog.getByRole('region', { name: 'Note sharing' });
+ const submit = dialog.getByRole('button', { name: 'Link note', exact: true });
+ const results = dialog.getByRole('region', {
+ name: 'Your markdown documents',
+ });
+ await expect(sharing).toBeInViewport({ ratio: 1 });
+ await expect(submit).toBeInViewport({ ratio: 1 });
+ await dialog.evaluate(async (element) => {
+ await Promise.all(
+ element
+ .getAnimations({ subtree: true })
+ .map((animation) => animation.finished)
+ );
+ });
+ const titleBefore = await title.boundingBox();
+ const sharingBefore = await sharing.boundingBox();
+ await results
+ .getByRole('button', { name: 'Team retrospective', exact: true })
+ .scrollIntoViewIfNeeded();
+ await expect(title).toBeInViewport({ ratio: 1 });
+ await expect(
+ dialog.getByText('Weekly product sync', { exact: true }).first()
+ ).toBeInViewport({ ratio: 1 });
+ expect(await title.boundingBox()).toEqual(titleBefore);
+ expect(await sharing.boundingBox()).toEqual(sharingBefore);
+ await results
+ .getByRole('button', { name: 'Team retrospective', exact: true })
+ .click();
+ await submit.click();
+ await expect(dialog).not.toBeVisible();
+ await expect(
+ page.getByRole('button', { name: 'Open Team retrospective', exact: true })
+ ).toBeVisible();
+});
+
+test('search, dismiss, and reopen reset the unfinished choice', async ({
+ page,
+}) => {
+ await page.goto('/?theme=dark');
+ const trigger = page.getByRole('button', {
+ name: 'Link existing',
+ exact: true,
+ });
+ await trigger.click();
+ const dialog = page.getByRole('dialog', {
+ name: /Link meeting notes|Note access|Unlink meeting notes/,
+ });
+ await dialog.getByRole('textbox').fill('no matching note');
+ await expect(dialog.getByText('No notes match this name.')).toBeVisible();
+ await dialog.getByRole('button', { name: 'Cancel' }).click();
+ await expect(dialog).not.toBeVisible();
+ await trigger.click();
+ await expect(dialog.getByRole('textbox')).toHaveValue('');
+ await expect(
+ dialog.getByRole('button', { name: 'Link note', exact: true })
+ ).toBeDisabled();
+ await expect(dialog.getByRole('checkbox')).not.toBeChecked();
+ await expect(page.locator('body')).toHaveJSProperty(
+ 'scrollWidth',
+ await page.locator('body').evaluate((body) => body.clientWidth)
+ );
+});
+
+test('team selection and failure recovery stay visible in a short viewport', async ({
+ page,
+}) => {
+ await page.setViewportSize({
+ width: page.viewportSize()?.width ?? 400,
+ height: 520,
+ });
+ await page.goto('/?hidden=1&fail=1');
+ await page
+ .getByRole('button', { name: 'Link existing', exact: true })
+ .click();
+ const dialog = page.getByRole('dialog', { name: 'Link meeting notes' });
+ await expect(
+ dialog.getByText(/This meeting hides its guest list/)
+ ).toBeInViewport({ ratio: 1 });
+ await dialog
+ .getByRole('button', { name: 'Weekly product sync', exact: true })
+ .click();
+ await dialog.getByText('Also share with Macro').click();
+ const submit = dialog.getByRole('button', { name: 'Link note', exact: true });
+ await expect(submit).toBeInViewport({ ratio: 1 });
+ await submit.click();
+ await expect(dialog.getByRole('alert')).toBeInViewport({ ratio: 1 });
+ await expect(
+ dialog.getByRole('region', { name: 'Note sharing' })
+ ).toBeInViewport({ ratio: 1 });
+ await expect(submit).toBeInViewport({ ratio: 1 });
+ await submit.click();
+ await expect(dialog).not.toBeVisible();
+ await expect(
+ page.getByRole('region', { name: 'Meeting notes' })
+ ).toContainText('Also shared with Macro');
+});
diff --git a/apps/web/src/features/calendar-notes/browser-test/playwright.config.ts b/apps/web/src/features/calendar-notes/browser-test/playwright.config.ts
new file mode 100644
index 0000000000..6306e366ac
--- /dev/null
+++ b/apps/web/src/features/calendar-notes/browser-test/playwright.config.ts
@@ -0,0 +1,47 @@
+import { fileURLToPath } from 'node:url';
+import { defineConfig, devices } from '@playwright/test';
+
+const directory = fileURLToPath(new URL('.', import.meta.url));
+const webDirectory = fileURLToPath(new URL('../../../../', import.meta.url));
+const port = Number(process.env.CALENDAR_NOTES_BROWSER_PORT ?? 3097);
+export default defineConfig({
+ testDir: directory,
+ testMatch: '*.browser.e2e.ts',
+ outputDir: `${directory}/test-results`,
+ timeout: 45_000,
+ fullyParallel: true,
+ use: {
+ baseURL: `http://127.0.0.1:${port}`,
+ trace: 'retain-on-failure',
+ screenshot: 'only-on-failure',
+ contextOptions: { reducedMotion: 'reduce' },
+ },
+ webServer: {
+ command: `bunx vite --config src/features/calendar-notes/browser-test/vite.config.ts --port ${port}`,
+ cwd: webDirectory,
+ url: `http://127.0.0.1:${port}`,
+ reuseExistingServer: false,
+ timeout: 120_000,
+ },
+ projects: [
+ {
+ name: 'desktop',
+ use: {
+ ...devices['Desktop Chrome'],
+ launchOptions: {
+ executablePath: process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH,
+ },
+ },
+ },
+ {
+ name: 'phone',
+ use: {
+ ...devices['iPhone 13'],
+ defaultBrowserType: 'chromium',
+ launchOptions: {
+ executablePath: process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH,
+ },
+ },
+ },
+ ],
+});
diff --git a/apps/web/src/features/calendar-notes/browser-test/preview-adapters.tsx b/apps/web/src/features/calendar-notes/browser-test/preview-adapters.tsx
new file mode 100644
index 0000000000..c8d2f64ee7
--- /dev/null
+++ b/apps/web/src/features/calendar-notes/browser-test/preview-adapters.tsx
@@ -0,0 +1,114 @@
+import { Avatar } from '@ui';
+import { createContext, type ParentProps, useContext } from 'solid-js';
+import { EventAttendeesSection } from '../../calendar/components/EventDetails';
+import type { CalendarEvent } from '../../calendar/types';
+import type { NotesSource } from '../context/notes-source';
+import { MeetingNotesView } from '../views/meeting-notes';
+
+export { sanitizeCalendarDescription } from '../../calendar/utils/calendar-description-sanitizer';
+export const parseMacroAppLink = () => undefined;
+export const recipientEntityMapper = () => () => undefined;
+
+// Sample sources, identities, and placeholders for unrelated calendar actions.
+// Event details, its popover/drawer, and the notes controls render their real UI.
+const NotesContext = createContext<NotesSource>();
+export function PreviewNotesProvider(
+ props: ParentProps<{ source: NotesSource }>
+) {
+ return (
+ <NotesContext.Provider value={props.source}>
+ {props.children}
+ </NotesContext.Provider>
+ );
+}
+
+function announce(message: string) {
+ document.dispatchEvent(
+ new CustomEvent('calendar-preview-message', { detail: message })
+ );
+}
+
+export function CalendarMeetingNotes(props: {
+ event: CalendarEvent;
+ onOpenDocument: (id: string) => void;
+ onDialogChange: (open: boolean) => void;
+}) {
+ const source = useContext(NotesContext);
+ if (!source) throw new Error('The calendar preview needs a notes source');
+ return (
+ <MeetingNotesView
+ source={source}
+ eventTitle={props.event.title}
+ recurring={props.event.recurrenceLines.length > 0}
+ guestListHidden={!props.event.guestPolicy.canSeeOtherGuests}
+ onOpen={(note) => {
+ announce(`Opened ${note.name}`);
+ props.onOpenDocument(note.documentId);
+ }}
+ onDialogChange={props.onDialogChange}
+ />
+ );
+}
+
+export const useVisibleCalendarsQuery = () => ({ isSuccess: true, data: [] });
+export const useDeleteCalendarEventMutation = () => ({
+ isPending: false,
+ mutate: () => announce('Delete event · Preview only'),
+});
+export const useSplitLayout = () => ({ openWithSplit: () => {} });
+export const useOpenEventComposer = () => () =>
+ announce('Edit event · Preview only');
+export const useForwardEventEmail = () => () =>
+ announce('Forward event · Preview only');
+export const createGuestInviteController = () => ({ editorOpen: () => false });
+export const useCalendarGuestInvitesFlag = () => () => false;
+export const useCalendarMeetingNotesFlag = () => () =>
+ new URLSearchParams(location.search).get('notes') !== 'off';
+export const EventGuests = (props: { event: CalendarEvent }) => (
+ <EventAttendeesSection attendees={props.event.attendees} />
+);
+export const EventJoinRequests = () => null;
+export const TeamEventDetails = () => null;
+export const OutlookRsvpAction = () => null;
+export const copyCalendarEventMention = () =>
+ announce('Copy event · Preview only');
+export const downloadCalendarEventIcs = () =>
+ announce('Download event · Preview only');
+export const openDocument = () => announce('Open document · Preview only');
+export const toast = { success: announce, failure: announce };
+
+export const createCalendarRsvpController = () => ({
+ pending: () => false,
+ error: () => undefined,
+ scopeOpen: () => false,
+ scope: () => 'this_event',
+ setScope: () => {},
+ closeScope: () => {},
+ confirmScope: () => {},
+ respond: (response: string) =>
+ document.dispatchEvent(
+ new CustomEvent('calendar-preview-rsvp', { detail: response })
+ ),
+});
+
+const names: Record<string, string> = {
+ '[email protected]': 'Alex Morgan',
+ '[email protected]': 'Sam Lee',
+ '[email protected]': 'You',
+};
+export const emailToMacroId = (email: string) => email;
+export const getDisplayName = (id?: string) => names[id ?? ''] ?? '';
+export const getInitialsFromName = (name: string) =>
+ name
+ .split(' ')
+ .map((part) => part[0])
+ .join('');
+export function UserIcon(props: { id?: string; email?: string; size?: 'md' }) {
+ return (
+ <Avatar size={props.size ?? 'md'}>
+ <Avatar.Fallback>
+ {getInitialsFromName(getDisplayName(props.id ?? props.email))}
+ </Avatar.Fallback>
+ </Avatar>
+ );
+}
diff --git a/apps/web/src/features/calendar-notes/browser-test/vite.config.ts b/apps/web/src/features/calendar-notes/browser-test/vite.config.ts
new file mode 100644
index 0000000000..1ab4471b9d
--- /dev/null
+++ b/apps/web/src/features/calendar-notes/browser-test/vite.config.ts
@@ -0,0 +1,62 @@
+import { fileURLToPath } from 'node:url';
+import tailwind from '@tailwindcss/vite';
+import { defineConfig } from 'vite';
+import solidPlugin from 'vite-plugin-solid';
+import solidSvg from 'vite-plugin-solid-svg';
+import tsconfigPaths from 'vite-tsconfig-paths';
+
+const directory = fileURLToPath(new URL('.', import.meta.url));
+const webDirectory = fileURLToPath(new URL('../../../../', import.meta.url));
+const workspaceDirectory = fileURLToPath(
+ new URL('../../../../../../', import.meta.url)
+);
+
+const previewAdapters = `${directory}/preview-adapters.tsx`;
+const previewImports = [
+ '@queries/calendar/calendars',
+ '@queries/calendar/mutations',
+ '@components/app/split-layout/layout',
+ '@app/features/calendar-view/components/use-open-event-composer',
+ '@app/features/calendar-view/components/use-forward-event-email',
+ '@app/features/calendar/hooks/create-guest-invite-controller',
+ '@app/features/calendar/hooks/use-calendar-ui-flag',
+ '@app/features/calendar-notes/calendar-meeting-notes',
+ '@app/features/calendar-view/components/EventGuests',
+ '@app/features/calendar-view/components/EventJoinRequests',
+ '@app/features/calendar-team/components/team-event-details',
+ '@app/features/calendar/views/event-replacement',
+ '@app/features/calendar-view/copy-event-mention',
+ '@app/features/calendar-view/download-event-ics',
+ '@core/component/LexicalMarkdown/component/core/BlockLink',
+ '@core/component/UserIcon',
+ '@core/component/Toast/Toast',
+ '@core/user/combinedRecipient',
+ '@core/user',
+ '../utils/calendar-description',
+ '../../calendar/hooks/create-calendar-rsvp-controller',
+];
+
+/** Real event overlays and notes views, with sample data and preview services. */
+export default defineConfig({
+ root: directory,
+ cacheDir: `${directory}/.vite`,
+ plugins: [
+ solidPlugin(),
+ solidSvg({ defaultAsComponent: true }),
+ tsconfigPaths({ projects: [`${webDirectory}/tsconfig.json`] }),
+ tailwind(),
+ ],
+ resolve: {
+ dedupe: ['solid-js'],
+ alias: previewImports.map((find) => ({
+ find,
+ replacement: previewAdapters,
+ })),
+ },
+ server: {
+ host: '127.0.0.1',
+ port: 3097,
+ strictPort: true,
+ fs: { allow: [workspaceDirectory] },
+ },
+});
diff --git a/apps/web/src/features/calendar-notes/calendar-meeting-notes.tsx b/apps/web/src/features/calendar-notes/calendar-meeting-notes.tsx
new file mode 100644
index 0000000000..36ed7d56f7
--- /dev/null
+++ b/apps/web/src/features/calendar-notes/calendar-meeting-notes.tsx
@@ -0,0 +1,41 @@
+import { useUserId } from '@core/context/user';
+import { Show, Suspense } from 'solid-js';
+import type { CalendarEvent } from '../calendar/types';
+import { createNotesSource } from './queries/notes-source';
+import { MeetingNotesView } from './views/meeting-notes';
+
+/** App composition; the view and controller also mount without calendar chrome. */
+export function CalendarMeetingNotes(props: {
+ event: CalendarEvent;
+ onOpenDocument: (documentId: string) => void;
+ onDialogChange: (open: boolean) => void;
+}) {
+ const userId = useUserId();
+ const source = createNotesSource(userId, () => ({
+ eventId: props.event.eventId,
+ occurrenceKey: props.event.occurrenceKey,
+ }));
+ return (
+ <Suspense>
+ <Show
+ when={JSON.stringify([
+ userId(),
+ props.event.eventId,
+ props.event.occurrenceKey,
+ ])}
+ keyed
+ >
+ {(_identity) => (
+ <MeetingNotesView
+ source={source}
+ eventTitle={props.event.title}
+ recurring={props.event.recurrenceLines.length > 0}
+ guestListHidden={!props.event.guestPolicy.canSeeOtherGuests}
+ onOpen={(note) => props.onOpenDocument(note.documentId)}
+ onDialogChange={props.onDialogChange}
+ />
+ )}
+ </Show>
+ </Suspense>
+ );
+}
diff --git a/apps/web/src/features/calendar-notes/components/document-notes-section.tsx b/apps/web/src/features/calendar-notes/components/document-notes-section.tsx
new file mode 100644
index 0000000000..e08d2e067d
--- /dev/null
+++ b/apps/web/src/features/calendar-notes/components/document-notes-section.tsx
@@ -0,0 +1,112 @@
+import CalendarIcon from '@phosphor/calendar-blank.svg';
+import { Button } from '@ui';
+import { For, Show } from 'solid-js';
+import type { DocumentNoteLink, NoteRead } from '../core/types';
+
+export function DocumentNotesSection(props: {
+ state: NoteRead<DocumentNoteLink[]>;
+ selected?: DocumentNoteLink;
+ saving: boolean;
+ error?: string;
+ onSelect: (link: DocumentNoteLink | undefined) => void;
+ onRemove: () => void;
+ onRetry: () => void;
+}) {
+ return (
+ <Show
+ when={
+ props.state.pending || props.state.error || props.state.data?.length
+ }
+ >
+ <section
+ aria-label="Meeting links"
+ class="rounded-3xl bg-dialog p-4 text-sm text-ink"
+ >
+ <h3 class="font-medium">Meeting links</h3>
+ <p class="mt-1 text-xs leading-relaxed text-ink-muted">
+ Access granted through meeting links. Unlink removes these grants and
+ keeps the document.
+ </p>
+ <Show when={props.state.pending}>
+ <p role="status" class="mt-3 text-xs text-ink-muted">
+ Loading meeting access…
+ </p>
+ </Show>
+ <Show when={props.state.error}>
+ <div
+ role="alert"
+ class="mt-3 flex items-center justify-between gap-3 text-xs text-failure"
+ >
+ {props.state.error}
+ <Button size="sm" variant="ghost" onClick={props.onRetry}>
+ Retry
+ </Button>
+ </div>
+ </Show>
+ <For each={props.state.data}>
+ {(link) => (
+ <div class="mt-3 rounded-xl border border-edge-muted p-3">
+ <div class="flex items-start gap-3">
+ <CalendarIcon class="mt-0.5 size-4 shrink-0 text-ink-muted" />
+ <div class="min-w-0 flex-1">
+ <p class="truncate font-medium">{link.eventTitle}</p>
+ <p class="mt-1 text-xs text-ink-muted">
+ {link.occurrenceKey === 'single'
+ ? 'One-time meeting'
+ : link.occurrenceKey.slice(0, 10)}{' '}
+ · Meeting viewers
+ {link.team ? ` + ${link.team.name}` : ''} · Can view
+ </p>
+ </div>
+ <Button
+ variant="ghost"
+ size="sm"
+ disabled={props.saving}
+ onClick={() => props.onSelect(link)}
+ >
+ Unlink
+ </Button>
+ </div>
+ <Show
+ when={
+ props.selected?.eventId === link.eventId &&
+ props.selected?.occurrenceKey === link.occurrenceKey
+ }
+ >
+ <div class="mt-3 border-t border-edge-muted pt-3">
+ <p class="text-xs text-ink-muted">
+ Remove this meeting link and its team access? The document
+ and its other sharing stay the same.
+ </p>
+ <Show when={props.error}>
+ <p role="alert" class="mt-2 text-xs text-failure">
+ {props.error}
+ </p>
+ </Show>
+ <div class="mt-3 flex justify-end gap-2">
+ <Button
+ variant="ghost"
+ size="sm"
+ disabled={props.saving}
+ onClick={() => props.onSelect(undefined)}
+ >
+ Keep link
+ </Button>
+ <Button
+ variant="danger"
+ size="sm"
+ disabled={props.saving}
+ onClick={props.onRemove}
+ >
+ {props.saving ? 'Removing…' : 'Unlink meeting'}
+ </Button>
+ </div>
+ </div>
+ </Show>
+ </div>
+ )}
+ </For>
+ </section>
+ </Show>
+ );
+}
diff --git a/apps/web/src/features/calendar-notes/components/note-dialog.tsx b/apps/web/src/features/calendar-notes/components/note-dialog.tsx
new file mode 100644
index 0000000000..ed7dd5cd34
--- /dev/null
+++ b/apps/web/src/features/calendar-notes/components/note-dialog.tsx
@@ -0,0 +1,288 @@
+import { ListSkeleton } from '@app/components/view-shell/ListSkeleton';
+import CheckIcon from '@phosphor/check.svg';
+import FileTextIcon from '@phosphor/file-text.svg';
+import LinkIcon from '@phosphor/link.svg';
+import MagnifyingGlassIcon from '@phosphor/magnifying-glass.svg';
+import XIcon from '@phosphor/x.svg';
+import { Button, Checkbox, Dialog, InputGroup, Tooltip } from '@ui';
+import { For, Show } from 'solid-js';
+import type {
+ NoteDocument,
+ NotePicker,
+ NoteRead,
+ NoteTeam,
+} from '../core/types';
+
+export function NoteDialog(props: {
+ kind: 'link' | 'sharing' | 'unlink';
+ eventTitle: string;
+ recurring: boolean;
+ guestListHidden?: boolean;
+ picker: NoteRead<NotePicker>;
+ query: string;
+ onQuery: (query: string) => void;
+ selected?: NoteDocument;
+ onSelect: (document: NoteDocument) => void;
+ linkedIds: string[];
+ teamId?: string;
+ currentTeam?: NoteTeam;
+ onTeam: (id: string | undefined) => void;
+ saving: boolean;
+ error?: string;
+ onSave: () => void;
+ onClose: () => void;
+}) {
+ const title = () =>
+ props.kind === 'unlink'
+ ? 'Unlink meeting notes?'
+ : props.kind === 'sharing'
+ ? 'Note access'
+ : 'Link meeting notes';
+ return (
+ <Dialog
+ open
+ onOpenChange={(open) => {
+ if (!open) props.onClose();
+ }}
+ position="center"
+ class="w-[400px]"
+ contentOwnsScroll
+ animate
+ >
+ <div class="relative flex min-h-0 max-h-[calc(100dvh-var(--virtual-keyboard-height,0px)-2rem)] flex-col p-4">
+ <div class="flex min-h-8 shrink-0 items-center justify-between gap-3 pr-8">
+ <Dialog.Title class="text-base font-medium text-ink sm:text-sm">
+ {title()}
+ </Dialog.Title>
+ </div>
+ <Dialog.Description class="mt-1 shrink-0 text-sm leading-relaxed text-ink-muted sm:text-xs">
+ <Show
+ when={props.kind !== 'unlink'}
+ fallback="The document stays in your files. Access granted by this meeting link will be removed; other sharing stays the same."
+ >
+ <span class="flex min-w-0 items-center gap-2">
+ <Tooltip
+ label={props.eventTitle}
+ as="span"
+ class="min-w-0 truncate"
+ >
+ {props.eventTitle}
+ </Tooltip>
+ <Show when={props.recurring}>
+ <span class="shrink-0 text-xs text-ink-extra-muted">
+ · This occurrence
+ </span>
+ </Show>
+ </span>
+ </Show>
+ </Dialog.Description>
+
+ <Show when={props.kind === 'link'}>
+ <div class="mt-3 shrink-0">
+ <InputGroup size="md">
+ <InputGroup.Addon>
+ <MagnifyingGlassIcon class="size-4 text-ink-muted" />
+ </InputGroup.Addon>
+ <InputGroup.Input
+ aria-label="Find a markdown document"
+ placeholder="Find a note…"
+ value={props.query}
+ onInput={(event) => props.onQuery(event.currentTarget.value)}
+ disabled={props.saving}
+ />
+ </InputGroup>
+ </div>
+ <div
+ class="mt-2 flex min-h-0 max-h-48 flex-col gap-1 overflow-y-auto overscroll-contain"
+ role="region"
+ aria-label="Your markdown documents"
+ aria-busy={props.picker.pending}
+ >
+ <Show when={props.picker.pending && !props.picker.data}>
+ <For each={[0, 1, 2]}>
+ {() => <ListSkeleton.Bar class="my-2 h-5 w-3/4" />}
+ </For>
+ </Show>
+ <Show when={props.picker.error}>
+ <p role="alert" class="py-4 text-sm text-failure">
+ {props.picker.error}
+ </p>
+ </Show>
+ <For each={props.picker.data?.documents}>
+ {(document) => {
+ const linked = () =>
+ props.linkedIds.includes(document.documentId);
+ return (
+ <Button
+ variant="ghost"
+ size="md"
+ fullWidth
+ label={document.name}
+ aria-pressed={
+ props.selected?.documentId === document.documentId
+ }
+ disabled={linked() || props.saving}
+ onClick={() => props.onSelect(document)}
+ >
+ <FileTextIcon class="size-4 text-ink-extra-muted" />
+ <span class="min-w-0 flex-1 truncate text-left">
+ {document.name}
+ </span>
+ <Show when={linked()}>
+ <span class="text-xs text-ink-extra-muted">Linked</span>
+ </Show>
+ <Show
+ when={props.selected?.documentId === document.documentId}
+ >
+ <CheckIcon class="size-4" />
+ </Show>
+ </Button>
+ );
+ }}
+ </For>
+ <Show
+ when={
+ props.picker.data?.documents.length === 0 &&
+ !props.picker.pending
+ }
+ >
+ <p class="px-3 py-5 text-center text-sm text-ink-muted">
+ {props.query
+ ? 'No notes match this name.'
+ : 'No markdown documents yet.'}
+ <span class="mt-1 block text-xs text-ink-extra-muted">
+ Only notes you own can be shared with a meeting.
+ </span>
+ </p>
+ </Show>
+ </div>
+ </Show>
+
+ <Show when={props.kind !== 'link' && props.selected}>
+ {(document) => (
+ <div class="mt-3 flex shrink-0 items-center gap-2 rounded-lg bg-ink/4 p-3 text-sm text-ink">
+ <FileTextIcon class="size-4 text-accent" />
+ <Tooltip label={document().name} class="min-w-0 flex-1">
+ <span class="block truncate">{document().name}</span>
+ </Tooltip>
+ </div>
+ )}
+ </Show>
+
+ <Show when={props.kind !== 'unlink'}>
+ <div
+ role="region"
+ aria-label="Note sharing"
+ class="mt-3 shrink-0 border-t border-edge-muted pt-3"
+ >
+ <p class="text-xs leading-relaxed text-ink-muted">
+ Anyone who can see this meeting’s details can read this note.
+ </p>
+ <Show when={props.picker.data?.teams.length}>
+ <div class="mt-3 flex flex-col gap-2">
+ <For each={props.picker.data?.teams}>
+ {(team) => (
+ <Checkbox
+ checked={props.teamId === team.id}
+ onChange={(checked) =>
+ props.onTeam(checked ? team.id : undefined)
+ }
+ disabled={props.saving}
+ class="min-h-9 justify-between gap-3"
+ >
+ <Checkbox.Control />
+ <Checkbox.Label class="flex-1 text-sm text-ink sm:text-xs">
+ Also share with {team.name}
+ <span class="mt-0.5 block text-xs font-normal text-ink-extra-muted">
+ Your team can read this note
+ </span>
+ </Checkbox.Label>
+ </Checkbox>
+ )}
+ </For>
+ </div>
+ </Show>
+ <Show
+ when={
+ props.currentTeam &&
+ props.teamId === props.currentTeam.id &&
+ props.picker.data &&
+ !props.picker.data.teams.some(
+ (team) => team.id === props.teamId
+ )
+ }
+ >
+ <div class="mt-3 rounded-lg border border-edge-muted p-3 text-xs text-ink-muted">
+ <p>
+ {props.currentTeam?.name} still has view access. You no longer
+ belong to this team.
+ </p>
+ <Button
+ variant="ghost"
+ size="sm"
+ class="mt-2"
+ disabled={props.saving}
+ onClick={() => props.onTeam(undefined)}
+ >
+ Remove team access
+ </Button>
+ </div>
+ </Show>
+ <p class="mt-2 text-xs leading-relaxed text-ink-extra-muted">
+ Other document access stays the same.
+ </p>
+ <Show when={props.guestListHidden}>
+ <p class="mt-2 text-xs leading-relaxed text-ink-extra-muted">
+ This meeting hides its guest list. Some guests may need a direct
+ document share.
+ </p>
+ </Show>
+ </div>
+ </Show>
+
+ <Show when={props.error}>
+ <p role="alert" class="mt-3 shrink-0 text-sm text-failure">
+ {props.error}
+ </p>
+ </Show>
+ <div class="mt-4 flex shrink-0 justify-end gap-2">
+ <Button
+ variant="ghost"
+ size="md"
+ onClick={props.onClose}
+ disabled={props.saving}
+ >
+ Cancel
+ </Button>
+ <Button
+ variant={props.kind === 'unlink' ? 'danger' : 'strong'}
+ size="md"
+ onClick={props.onSave}
+ disabled={!props.selected || props.saving}
+ >
+ <Show when={props.kind === 'link'}>
+ <LinkIcon />
+ </Show>
+ {props.saving
+ ? 'Saving…'
+ : props.kind === 'unlink'
+ ? 'Unlink note'
+ : props.kind === 'sharing'
+ ? 'Save access'
+ : 'Link note'}
+ </Button>
+ </div>
+ <Dialog.CloseButton
+ as={Button}
+ variant="ghost"
+ size="icon-sm"
+ label="Close"
+ disabled={props.saving}
+ class="absolute right-4 top-4"
+ >
+ <XIcon />
+ </Dialog.CloseButton>
+ </div>
+ </Dialog>
+ );
+}
diff --git a/apps/web/src/features/calendar-notes/components/notes-section.tsx b/apps/web/src/features/calendar-notes/components/notes-section.tsx
new file mode 100644
index 0000000000..34df1c3c27
--- /dev/null
+++ b/apps/web/src/features/calendar-notes/components/notes-section.tsx
@@ -0,0 +1,186 @@
+import { ListSkeleton } from '@app/components/view-shell/ListSkeleton';
+import CaretDownIcon from '@phosphor/caret-down.svg';
+import FileTextIcon from '@phosphor/file-text.svg';
+import { Button, Dropdown } from '@ui';
+import { For, onCleanup, Show } from 'solid-js';
+import type { MeetingNote, NoteRead } from '../core/types';
+
+export function NotesSection(props: {
+ state: NoteRead<MeetingNote[]>;
+ creating: boolean;
+ createdUnlinked: boolean;
+ createError?: string;
+ onCreate: () => void;
+ onOpenSaved: () => void;
+ dialogOpen: boolean;
+ onMenuChange: (documentId: string, open: boolean) => void;
+ onLink: () => void;
+ onOpen: (note: MeetingNote) => void;
+ onSharing: (note: MeetingNote) => void;
+ onUnlink: (note: MeetingNote) => void;
+ onRetry: () => void;
+}) {
+ const createLabel = () =>
+ props.creating
+ ? props.createdUnlinked
+ ? 'Linking…'
+ : 'Creating…'
+ : props.createdUnlinked
+ ? 'Retry linking'
+ : 'Create notes';
+
+ return (
+ <section
+ aria-label="Meeting notes"
+ class="grid grid-cols-[1.25rem_minmax(0,1fr)] gap-x-4 border-t border-edge-muted px-4 py-3 text-sm text-ink-muted sm:grid-cols-[1rem_minmax(0,1fr)] sm:gap-x-3 sm:text-xs"
+ >
+ <FileTextIcon class="mt-2 size-5 text-ink-extra-muted sm:mt-1.5 sm:size-4" />
+ <div class="min-w-0">
+ <div class="mb-1 flex min-h-7 items-center justify-between gap-2">
+ <div class="flex min-w-0 items-center gap-2">
+ <h3 class="whitespace-nowrap font-medium text-ink">
+ Meeting notes
+ </h3>
+ <Show when={props.state.data?.length}>
+ <span class="text-xs text-ink-extra-muted">
+ {props.state.data?.length}
+ </span>
+ </Show>
+ </div>
+ <Show when={props.state.data}>
+ <div class="flex shrink-0 items-center gap-1">
+ <Button
+ variant={props.state.data?.length ? 'ghost' : 'strong'}
+ size="xs"
+ label={createLabel()}
+ disabled={props.creating}
+ onClick={props.onCreate}
+ >
+ {props.creating || props.createdUnlinked
+ ? createLabel()
+ : 'Create'}
+ </Button>
+ <Button
+ variant="ghost"
+ size="xs"
+ depth={3}
+ label="Link existing"
+ disabled={props.creating}
+ onClick={props.onLink}
+ >
+ Link
+ </Button>
+ </div>
+ </Show>
+ </div>
+ <Show when={props.state.pending && !props.state.data}>
+ <div
+ role="status"
+ aria-label="Loading meeting notes"
+ class="flex flex-col gap-2 py-2"
+ >
+ <ListSkeleton.Bar class="h-4 w-3/4" />
+ <ListSkeleton.Bar class="h-3 w-1/2" />
+ </div>
+ </Show>
+ <Show when={props.state.error}>
+ <div
+ role="alert"
+ class="flex items-center justify-between gap-2 py-2 text-xs text-ink-muted"
+ >
+ <span>{props.state.error}</span>
+ <Button size="sm" variant="outline" onClick={props.onRetry}>
+ Retry
+ </Button>
+ </div>
+ </Show>
+ <div class="flex flex-col gap-1">
+ <For each={props.state.data}>
+ {(note) => {
+ onCleanup(() => props.onMenuChange(note.documentId, false));
+ return (
+ <div class="min-w-0">
+ <div class="flex min-w-0 items-center gap-1">
+ <Button
+ variant="ghost"
+ size="sm"
+ depth={3}
+ class="min-w-0 flex-1"
+ label={`Open ${note.name}`}
+ onClick={() => props.onOpen(note)}
+ >
+ <span class="min-w-0 flex-1 truncate text-left">
+ {note.name}
+ </span>
+ </Button>
+ <Show when={note.canManage}>
+ <Dropdown
+ modal={false}
+ placement="bottom-end"
+ onOpenChange={(open) =>
+ props.onMenuChange(note.documentId, open)
+ }
+ >
+ <Dropdown.Trigger
+ variant="ghost"
+ size="xs"
+ label={`Options for ${note.name}`}
+ disabled={props.creating}
+ >
+ Options
+ <CaretDownIcon />
+ </Dropdown.Trigger>
+ <Dropdown.Content
+ portalScope="local"
+ class="z-nested-action-menu min-w-44"
+ onCloseAutoFocus={(event) => {
+ if (props.dialogOpen) event.preventDefault();
+ }}
+ >
+ <Dropdown.Group>
+ <Dropdown.Item
+ onSelect={() => props.onSharing(note)}
+ >
+ Manage access
+ </Dropdown.Item>
+ <Dropdown.Item
+ onSelect={() => props.onUnlink(note)}
+ >
+ Unlink from meeting
+ </Dropdown.Item>
+ </Dropdown.Group>
+ </Dropdown.Content>
+ </Dropdown>
+ </Show>
+ </div>
+ <Show when={note.team}>
+ {(team) => (
+ <p class="px-2 text-xs text-ink-extra-muted sm:text-xxs">
+ Also shared with {team().name}
+ </p>
+ )}
+ </Show>
+ </div>
+ );
+ }}
+ </For>
+ </div>
+ <Show when={props.createError}>
+ <div role="alert" class="my-2 text-xs text-ink-muted">
+ <p>{props.createError}</p>
+ <Show when={props.createdUnlinked}>
+ <Button
+ variant="ghost"
+ size="sm"
+ disabled={props.creating}
+ onClick={props.onOpenSaved}
+ >
+ Open saved note
+ </Button>
+ </Show>
+ </div>
+ </Show>
+ </div>
+ </section>
+ );
+}
diff --git a/apps/web/src/features/calendar-notes/context/notes-source.ts b/apps/web/src/features/calendar-notes/context/notes-source.ts
new file mode 100644
index 0000000000..7e271e9f10
--- /dev/null
+++ b/apps/web/src/features/calendar-notes/context/notes-source.ts
@@ -0,0 +1,34 @@
+import type { Result } from 'neverthrow';
+import type { Accessor } from 'solid-js';
+import type {
+ DocumentNoteLink,
+ MeetingNote,
+ NoteCreateFailure,
+ NoteDocument,
+ NoteFailure,
+ NotePicker,
+ NoteRead,
+ NoteTarget,
+} from '../core/types';
+
+/** Reactive reads and writes owned by the calendar-note feature. */
+export type NotesSource = {
+ notes: Accessor<NoteRead<MeetingNote[]>>;
+ create: (name: string) => Promise<Result<NoteDocument, NoteCreateFailure>>;
+ picker: (
+ query: Accessor<string>,
+ enabled: Accessor<boolean>
+ ) => Accessor<NoteRead<NotePicker>>;
+ retry: () => Promise<unknown>;
+ link: (
+ documentId: string,
+ teamId?: string
+ ) => Promise<Result<void, NoteFailure>>;
+ unlink: (documentId: string) => Promise<Result<void, NoteFailure>>;
+};
+
+export type DocumentNotesSource = {
+ links: Accessor<NoteRead<DocumentNoteLink[]>>;
+ retry: () => Promise<unknown>;
+ unlink: (target: NoteTarget) => Promise<Result<void, NoteFailure>>;
+};
diff --git a/apps/web/src/features/calendar-notes/core/types.ts b/apps/web/src/features/calendar-notes/core/types.ts
new file mode 100644
index 0000000000..654eea28a8
--- /dev/null
+++ b/apps/web/src/features/calendar-notes/core/types.ts
@@ -0,0 +1,26 @@
+export type NoteDocument = { documentId: string; name: string };
+export type NoteTeam = { id: string; name: string };
+export type MeetingNote = NoteDocument & {
+ team?: NoteTeam;
+ canManage: boolean;
+};
+export type NotePicker = { documents: NoteDocument[]; teams: NoteTeam[] };
+export type NoteTarget = { eventId: string; occurrenceKey: string };
+export type DocumentNoteLink = NoteTarget & {
+ eventTitle: string;
+ team?: NoteTeam;
+};
+export type MeetingAccessState = 'loading' | 'shared' | 'none' | 'error';
+export type NoteFailure =
+ | { kind: 'link_failed'; message: string }
+ | { kind: 'unlink_failed'; message: string };
+
+export type NoteCreateFailure =
+ | { kind: 'create_failed'; message: string }
+ | { kind: 'created_unlinked'; message: string; document: NoteDocument };
+
+export type NoteRead<T> = {
+ data?: T;
+ pending: boolean;
+ error?: string;
+};
diff --git a/apps/web/src/features/calendar-notes/document-meeting-notes.tsx b/apps/web/src/features/calendar-notes/document-meeting-notes.tsx
new file mode 100644
index 0000000000..291858c44c
--- /dev/null
+++ b/apps/web/src/features/calendar-notes/document-meeting-notes.tsx
@@ -0,0 +1,33 @@
+import { useUserId } from '@core/context/user';
+import { createEffect, Show, Suspense } from 'solid-js';
+import type { MeetingAccessState } from './core/types';
+import { createDocumentNotesSource } from './queries/notes-source';
+import { DocumentNotesView } from './views/document-notes';
+
+/** Owner-only meeting grants within the document share panel. */
+export function DocumentMeetingNotes(props: {
+ documentId: string;
+ onAccessState?: (state: MeetingAccessState) => void;
+}) {
+ const userId = useUserId();
+ const source = createDocumentNotesSource(userId, () => props.documentId);
+ createEffect(() => {
+ const state = source.links();
+ props.onAccessState?.(
+ state.error
+ ? 'error'
+ : !state.data
+ ? 'loading'
+ : state.data.length
+ ? 'shared'
+ : 'none'
+ );
+ });
+ return (
+ <Suspense>
+ <Show when={JSON.stringify([userId(), props.documentId])} keyed>
+ {(_identity) => <DocumentNotesView source={source} />}
+ </Show>
+ </Suspense>
+ );
+}
diff --git a/apps/web/src/features/calendar-notes/primitives/create-meeting-note.test.ts b/apps/web/src/features/calendar-notes/primitives/create-meeting-note.test.ts
new file mode 100644
index 0000000000..38100e6b20
--- /dev/null
+++ b/apps/web/src/features/calendar-notes/primitives/create-meeting-note.test.ts
@@ -0,0 +1,117 @@
+import { err, ok, type Result } from 'neverthrow';
+import { createRoot } from 'solid-js';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import type { NoteCreateFailure, NoteDocument } from '../core/types';
+import { createFakeNotesSource } from '../tests/fake-source';
+import { createMeetingNoteAction } from './create-meeting-note';
+
+let dispose = () => {};
+afterEach(() => dispose());
+
+function fixture(fail = false) {
+ return createRoot((cleanup) => {
+ dispose = cleanup;
+ const fake = createFakeNotesSource({ fail });
+ const create = vi.spyOn(fake.source, 'create');
+ const link = vi.spyOn(fake.source, 'link');
+ const onOpen = vi.fn();
+ const action = createMeetingNoteAction({
+ source: fake.source,
+ title: () => 'Weekly product sync',
+ onOpen,
+ });
+ return { ...fake, create, link, onOpen, action };
+ });
+}
+
+describe('creating meeting notes', () => {
+ it('waits for linking before opening and suppresses duplicate clicks', async () => {
+ const { action, create, onOpen } = fixture();
+ let finish = (_result: Result<NoteDocument, NoteCreateFailure>) => {};
+ create.mockReturnValueOnce(
+ new Promise((resolve) => {
+ finish = resolve;
+ })
+ );
+ const creating = action.run();
+ await action.run();
+ expect(create).toHaveBeenCalledExactlyOnceWith('Weekly product sync notes');
+ expect(action.pending()).toBe(true);
+ expect(onOpen).not.toHaveBeenCalled();
+ const document = { documentId: 'saved', name: 'Weekly product sync notes' };
+ finish(ok(document));
+ await creating;
+ expect(onOpen).toHaveBeenCalledExactlyOnceWith(document);
+ expect(action.pending()).toBe(false);
+ });
+
+ it('retries linking the saved document without creating another one', async () => {
+ const { action, create, link, notes, onOpen } = fixture(true);
+ await action.run();
+ expect(action.saved()?.documentId).toBe('created-1');
+ expect(action.error()).toBeDefined();
+ expect(action.pending()).toBe(false);
+ expect(notes()).toEqual([]);
+ expect(onOpen).not.toHaveBeenCalled();
+ await action.run();
+ expect(create).toHaveBeenCalledOnce();
+ expect(link).toHaveBeenNthCalledWith(1, 'created-1');
+ expect(link).toHaveBeenNthCalledWith(2, 'created-1');
+ expect(notes()).toEqual([
+ {
+ documentId: 'created-1',
+ name: 'Weekly product sync notes',
+ canManage: true,
+ },
+ ]);
+ expect(action.saved()).toBeUndefined();
+ expect(action.error()).toBeUndefined();
+ expect(onOpen).toHaveBeenCalledExactlyOnceWith({
+ documentId: 'created-1',
+ name: 'Weekly product sync notes',
+ });
+ });
+
+ it('can open the saved note after linking fails', async () => {
+ const { action, create, onOpen } = fixture(true);
+ await action.run();
+ action.openSaved();
+ expect(create).toHaveBeenCalledOnce();
+ expect(onOpen).toHaveBeenCalledExactlyOnceWith({
+ documentId: 'created-1',
+ name: 'Weekly product sync notes',
+ });
+ });
+
+ it('allows retry after document creation fails without navigating', async () => {
+ const { action, create, link, onOpen } = fixture();
+ create.mockResolvedValueOnce(
+ err({ kind: 'create_failed', message: 'Offline' })
+ );
+ await action.run();
+ expect(action.pending()).toBe(false);
+ expect(action.saved()).toBeUndefined();
+ expect(link).not.toHaveBeenCalled();
+ expect(onOpen).not.toHaveBeenCalled();
+ await action.run();
+ expect(create).toHaveBeenCalledTimes(2);
+ expect(onOpen).toHaveBeenCalledOnce();
+ });
+
+ it('does not navigate after the meeting or account changes', async () => {
+ const { action, create, onOpen } = fixture();
+ let finish = (_result: Result<NoteDocument, NoteCreateFailure>) => {};
+ create.mockReturnValueOnce(
+ new Promise((resolve) => {
+ finish = resolve;
+ })
+ );
+ const creating = action.run();
+ dispose();
+ finish(ok({ documentId: 'saved', name: 'Weekly product sync notes' }));
+ await creating;
+ expect(onOpen).not.toHaveBeenCalled();
+ await action.run();
+ expect(create).toHaveBeenCalledOnce();
+ });
+});
diff --git a/apps/web/src/features/calendar-notes/primitives/create-meeting-note.ts b/apps/web/src/features/calendar-notes/primitives/create-meeting-note.ts
new file mode 100644
index 0000000000..e346486e0b
--- /dev/null
+++ b/apps/web/src/features/calendar-notes/primitives/create-meeting-note.ts
@@ -0,0 +1,57 @@
+import { type Accessor, createSignal, onCleanup } from 'solid-js';
+import type { NotesSource } from '../context/notes-source';
+import type { NoteCreateFailure, NoteDocument } from '../core/types';
+
+/** Create once, retain a saved note if linking fails, and navigate after linking. */
+export function createMeetingNoteAction(options: {
+ source: NotesSource;
+ title: Accessor<string>;
+ onOpen: (document: NoteDocument) => void;
+}) {
+ const [pending, setPending] = createSignal(false);
+ const [saved, setSaved] = createSignal<NoteDocument>();
+ const [error, setError] = createSignal<string>();
+ let disposed = false;
+ onCleanup(() => {
+ disposed = true;
+ });
+
+ async function run() {
+ if (pending() || disposed) return;
+ setPending(true);
+ setError(undefined);
+ const document = saved();
+ const result = document
+ ? (await options.source.link(document.documentId))
+ .map(() => document)
+ .mapErr(
+ (failure): NoteCreateFailure => ({
+ kind: 'created_unlinked',
+ document,
+ message: failure.message,
+ })
+ )
+ : await options.source.create(`${options.title()} notes`);
+ if (disposed) return;
+ setPending(false);
+ if (result.isErr()) {
+ setError(result.error.message);
+ if (result.error.kind === 'created_unlinked')
+ setSaved(result.error.document);
+ return;
+ }
+ setSaved(undefined);
+ options.onOpen(result.value);
+ }
+
+ return {
+ pending,
+ saved,
+ error,
+ run,
+ openSaved: () => {
+ const document = saved();
+ if (document && !pending() && !disposed) options.onOpen(document);
+ },
+ };
+}
diff --git a/apps/web/src/features/calendar-notes/primitives/document-notes-controller.ts b/apps/web/src/features/calendar-notes/primitives/document-notes-controller.ts
new file mode 100644
index 0000000000..5a2fe95edf
--- /dev/null
+++ b/apps/web/src/features/calendar-notes/primitives/document-notes-controller.ts
@@ -0,0 +1,29 @@
+import { createSignal, onCleanup } from 'solid-js';
+import type { DocumentNotesSource } from '../context/notes-source';
+import type { DocumentNoteLink } from '../core/types';
+
+export function createDocumentNotesController(source: DocumentNotesSource) {
+ const [selected, setSelected] = createSignal<DocumentNoteLink>();
+ const [saving, setSaving] = createSignal(false);
+ const [error, setError] = createSignal<string>();
+ let disposed = false;
+ onCleanup(() => {
+ disposed = true;
+ });
+ function select(link: DocumentNoteLink | undefined) {
+ if (saving()) return;
+ setSelected(link);
+ setError(undefined);
+ }
+ async function remove() {
+ const link = selected();
+ if (!link || saving()) return;
+ setSaving(true);
+ const result = await source.unlink(link);
+ if (disposed) return;
+ setSaving(false);
+ if (result.isErr()) setError(result.error.message);
+ else select(undefined);
+ }
+ return { selected, saving, error, select, remove };
+}
diff --git a/apps/web/src/features/calendar-notes/primitives/notes-controller.ts b/apps/web/src/features/calendar-notes/primitives/notes-controller.ts
new file mode 100644
index 0000000000..98357eae89
--- /dev/null
+++ b/apps/web/src/features/calendar-notes/primitives/notes-controller.ts
@@ -0,0 +1,94 @@
+import { createSignal, onCleanup } from 'solid-js';
+import type { NotesSource } from '../context/notes-source';
+import type { MeetingNote, NoteDocument } from '../core/types';
+
+type NoteDialog =
+ | { kind: 'link' }
+ | { kind: 'sharing' | 'unlink'; note: MeetingNote };
+
+export function createNotesController(
+ source: NotesSource,
+ onDialogChange: (open: boolean) => void
+) {
+ const [dialog, setDialog] = createSignal<NoteDialog>();
+ const [query, setQuery] = createSignal('');
+ const [selected, setSelected] = createSignal<NoteDocument>();
+ const [teamId, setTeamId] = createSignal<string>();
+ const [saving, setSaving] = createSignal(false);
+ const [error, setError] = createSignal<string>();
+ let menuDocumentId: string | undefined;
+ let disposed = false;
+ onCleanup(() => {
+ disposed = true;
+ onDialogChange(false);
+ });
+ const picker = source.picker(
+ query,
+ () => !!dialog() && dialog()?.kind !== 'unlink'
+ );
+
+ function reportOpen() {
+ if (disposed) return;
+ onDialogChange(!!menuDocumentId || !!dialog());
+ }
+
+ function open(next: NoteDialog) {
+ if (saving()) return;
+ setQuery('');
+ setError(undefined);
+ setSelected(next.kind === 'link' ? undefined : next.note);
+ setTeamId(next.kind === 'link' ? undefined : next.note.team?.id);
+ setDialog(next);
+ reportOpen();
+ }
+
+ function close() {
+ if (saving()) return;
+ setDialog(undefined);
+ reportOpen();
+ }
+
+ async function save() {
+ const active = dialog();
+ const document = selected();
+ if (!active || !document || saving()) return;
+ setSaving(true);
+ setError(undefined);
+ const result =
+ active.kind === 'unlink'
+ ? await source.unlink(document.documentId)
+ : await source.link(document.documentId, teamId());
+ if (disposed || dialog() !== active) return;
+ setSaving(false);
+ if (result.isErr()) {
+ setError(result.error.message);
+ return;
+ }
+ close();
+ }
+
+ return {
+ dialog,
+ query,
+ setQuery,
+ selected,
+ setSelected,
+ teamId,
+ setTeamId,
+ saving,
+ error,
+ picker,
+ setMenuOpen: (documentId: string, open: boolean) => {
+ if (open) menuDocumentId = documentId;
+ else if (menuDocumentId === documentId) menuDocumentId = undefined;
+ reportOpen();
+ },
+ close,
+ save,
+ openLink: () => open({ kind: 'link' }),
+ openSharing: (note: MeetingNote) => open({ kind: 'sharing', note }),
+ openUnlink: (note: MeetingNote) => open({ kind: 'unlink', note }),
+ };
+}
+
+export type NotesController = ReturnType<typeof createNotesController>;
diff --git a/apps/web/src/features/calendar-notes/queries/keys.ts b/apps/web/src/features/calendar-notes/queries/keys.ts
new file mode 100644
index 0000000000..f38d7b9157
--- /dev/null
+++ b/apps/web/src/features/calendar-notes/queries/keys.ts
@@ -0,0 +1,11 @@
+import { createQueryKeys } from '@lukemorales/query-key-factory';
+import type { NoteTarget } from '../core/types';
+
+export const notesKeys = createQueryKeys('calendar-notes', {
+ notes: (userId: string | undefined, target: NoteTarget) => [userId, target],
+ documents: (userId: string | undefined, query: string) => [userId, query],
+ documentLinks: (userId: string | undefined, documentId: string) => [
+ userId,
+ documentId,
+ ],
+});
diff --git a/apps/web/src/features/calendar-notes/queries/notes-source.test.tsx b/apps/web/src/features/calendar-notes/queries/notes-source.test.tsx
new file mode 100644
index 0000000000..d8bc180b79
--- /dev/null
+++ b/apps/web/src/features/calendar-notes/queries/notes-source.test.tsx
@@ -0,0 +1,114 @@
+import { createMarkdownFile } from '@core/util/create';
+import { queryClient } from '@queries/client';
+import { calendarNotesClient } from '@service-calendar/notes';
+import { QueryClientProvider } from '@tanstack/solid-query';
+import { err, ok } from 'neverthrow';
+import { createComponent, createRoot, createSignal } from 'solid-js';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import type { NotesSource } from '../context/notes-source';
+import { createNotesSource } from './notes-source';
+
+vi.mock('@core/util/create', () => ({ createMarkdownFile: vi.fn() }));
+vi.mock('@service-calendar/notes', () => ({
+ calendarNotesClient: { list: vi.fn(), link: vi.fn() },
+}));
+vi.mock('@queries/client', async () => {
+ const { QueryClient } = await import('@tanstack/solid-query');
+ return {
+ queryClient: new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ }),
+ };
+});
+
+let dispose = () => {};
+beforeEach(() => {
+ vi.mocked(calendarNotesClient.list).mockResolvedValue(ok([]));
+ vi.mocked(calendarNotesClient.link).mockResolvedValue(ok({}));
+});
+afterEach(() => {
+ dispose();
+ queryClient.clear();
+ vi.resetAllMocks();
+});
+
+function mountSource() {
+ const [user, setUser] = createSignal<string | undefined>('owner');
+ const [target, setTarget] = createSignal({
+ eventId: 'event-a',
+ occurrenceKey: '2026-10-23T14:00:00Z',
+ });
+ let source: NotesSource | undefined;
+ function Probe() {
+ source = createNotesSource(user, target);
+ return null;
+ }
+ createRoot((cleanup) => {
+ dispose = cleanup;
+ createComponent(QueryClientProvider, {
+ client: queryClient,
+ get children() {
+ return createComponent(Probe, {});
+ },
+ });
+ });
+ if (!source) throw new Error('Notes source did not mount');
+ return { source, setUser, setTarget };
+}
+
+it('links to the original occurrence when selection changes during creation', async () => {
+ let finish = (_id: string) => {};
+ vi.mocked(createMarkdownFile).mockReturnValueOnce(
+ new Promise((resolve) => {
+ finish = resolve;
+ })
+ );
+ const { source, setTarget } = mountSource();
+ const creating = source.create('Weekly sync notes');
+ expect(createMarkdownFile).toHaveBeenCalledOnce();
+ setTarget({ eventId: 'event-b', occurrenceKey: '2026-10-30T14:00:00Z' });
+ finish('created-document');
+ expect((await creating).isOk()).toBe(true);
+ expect(calendarNotesClient.link).toHaveBeenCalledExactlyOnceWith(
+ 'event-a',
+ '2026-10-23T14:00:00Z',
+ 'created-document',
+ { teamId: null }
+ );
+});
+
+it('does not link a newly created document under a different account', async () => {
+ let finish = (_id: string) => {};
+ vi.mocked(createMarkdownFile).mockReturnValueOnce(
+ new Promise((resolve) => {
+ finish = resolve;
+ })
+ );
+ const { source, setUser } = mountSource();
+ const creating = source.create('Weekly sync notes');
+ setUser('another-owner');
+ finish('created-document');
+ const result = await creating;
+ expect(result.isErr()).toBe(true);
+ if (result.isErr())
+ expect(result.error).toMatchObject({
+ kind: 'created_unlinked',
+ document: { documentId: 'created-document' },
+ });
+ expect(calendarNotesClient.link).not.toHaveBeenCalled();
+});
+
+it('preserves the created document when the server rejects linking', async () => {
+ vi.mocked(createMarkdownFile).mockResolvedValueOnce('created-document');
+ vi.mocked(calendarNotesClient.link).mockResolvedValueOnce(
+ err([{ code: 'FORBIDDEN', message: 'Meeting access changed' }])
+ );
+ const { source } = mountSource();
+ const result = await source.create('Weekly sync notes');
+ expect(result.isErr()).toBe(true);
+ if (result.isErr())
+ expect(result.error).toMatchObject({
+ kind: 'created_unlinked',
+ document: { documentId: 'created-document', name: 'Weekly sync notes' },
+ });
+});
diff --git a/apps/web/src/features/calendar-notes/queries/notes-source.ts b/apps/web/src/features/calendar-notes/queries/notes-source.ts
new file mode 100644
index 0000000000..db6d0d6a3a
--- /dev/null
+++ b/apps/web/src/features/calendar-notes/queries/notes-source.ts
@@ -0,0 +1,244 @@
+import { createMarkdownFile } from '@core/util/create';
+import { catchToResult, throwOnErr } from '@core/util/result';
+import { Telemetry } from '@macro-inc/observability';
+import { queryClient } from '@queries/client';
+import { queryReadyGate } from '@queries/gate';
+import { calendarNotesClient } from '@service-calendar/notes';
+import { createDebouncedMemo } from '@solid-primitives/memo';
+import { useMutation, useQuery } from '@tanstack/solid-query';
+import { err, ok } from 'neverthrow';
+import type { Accessor } from 'solid-js';
+import type { DocumentNotesSource, NotesSource } from '../context/notes-source';
+import type {
+ MeetingNote,
+ NoteCreateFailure,
+ NoteFailure,
+ NoteTarget,
+} from '../core/types';
+import { notesKeys } from './keys';
+
+function notesOptions(userId: string | undefined, target: NoteTarget) {
+ return {
+ queryKey: notesKeys.notes(userId, target).queryKey,
+ queryFn: async ({
+ signal,
+ }: {
+ signal: AbortSignal;
+ }): Promise<MeetingNote[]> => {
+ const notes = await throwOnErr(() =>
+ calendarNotesClient.list(target.eventId, target.occurrenceKey, signal)
+ );
+ return notes.map((note) => ({ ...note, team: note.team ?? undefined }));
+ },
+ enabled: !!userId,
+ staleTime: 0,
+ gcTime: 0,
+ refetchInterval: 30_000,
+ refetchOnWindowFocus: true,
+ };
+}
+
+function pickerOptions(
+ userId: string | undefined,
+ query: string,
+ enabled: boolean
+) {
+ return {
+ queryKey: notesKeys.documents(userId, query).queryKey,
+ queryFn: ({ signal }: { signal: AbortSignal }) =>
+ throwOnErr(() => calendarNotesClient.documents(query, signal)),
+ enabled: !!userId && enabled,
+ staleTime: 0,
+ gcTime: 0,
+ };
+}
+
+type NoteWrite = NoteTarget & { documentId: string; teamId?: string };
+
+function linkNote(input: NoteWrite) {
+ return Telemetry.span('calendar.notes.link', async (span) => {
+ span.setAttr('event.id', input.eventId);
+ span.setAttr('document.id', input.documentId);
+ await throwOnErr(() =>
+ calendarNotesClient.link(
+ input.eventId,
+ input.occurrenceKey,
+ input.documentId,
+ { teamId: input.teamId ?? null }
+ )
+ );
+ });
+}
+
+function unlinkNote(input: NoteWrite) {
+ return Telemetry.span('calendar.notes.unlink', async (span) => {
+ span.setAttr('event.id', input.eventId);
+ span.setAttr('document.id', input.documentId);
+ await throwOnErr(() =>
+ calendarNotesClient.unlink(
+ input.eventId,
+ input.occurrenceKey,
+ input.documentId
+ )
+ );
+ });
+}
+
+function refreshNotes() {
+ // The same meeting can be open through several inbox copies with distinct IDs.
+ return Promise.all([
+ queryClient.invalidateQueries({ queryKey: notesKeys.notes._def }),
+ queryClient.invalidateQueries({ queryKey: notesKeys.documentLinks._def }),
+ ]);
+}
+
+export function createNotesSource(
+ userId: Accessor<string | undefined>,
+ target: Accessor<NoteTarget>
+): NotesSource {
+ const notes = useQuery(() => notesOptions(userId(), target()));
+ const link = useMutation(() => ({
+ mutationFn: linkNote,
+ onSuccess: refreshNotes,
+ }));
+ const unlink = useMutation(() => ({
+ mutationFn: unlinkNote,
+ onSuccess: refreshNotes,
+ }));
+ return {
+ notes: () => ({
+ data: queryReadyGate(notes) ? notes.data : undefined,
+ pending: notes.isPending,
+ error: notes.isError ? 'Couldn’t load meeting notes.' : undefined,
+ }),
+ async create(name) {
+ // Capture the occurrence and account before document creation yields.
+ const destination = { ...target() };
+ const owner = userId();
+ return Telemetry.span('calendar.notes.create', async (span) => {
+ span.setAttr('event.id', destination.eventId);
+ const created = await catchToResult(() =>
+ createMarkdownFile({
+ title: name,
+ source: 'calendar_notes',
+ })
+ );
+ if (created.isErr() || !created.value) {
+ span.setAttr('calendar.notes.outcome', 'create_failed');
+ span.error('Meeting note creation failed');
+ return err({
+ kind: 'create_failed',
+ message: 'Couldn’t create the note. Please try again.',
+ } satisfies NoteCreateFailure);
+ }
+ const document = { documentId: created.value, name };
+ span.setAttr('document.id', document.documentId);
+ if (userId() !== owner) {
+ span.setAttr('calendar.notes.outcome', 'account_changed');
+ span.error('Account changed before meeting note linking');
+ return err({
+ kind: 'created_unlinked',
+ document,
+ message:
+ 'Your note was saved, but your account changed before it could be linked.',
+ } satisfies NoteCreateFailure);
+ }
+ const linked = await catchToResult(() =>
+ link.mutateAsync({ ...destination, documentId: document.documentId })
+ );
+ if (linked.isErr()) {
+ span.setAttr('calendar.notes.outcome', 'created_unlinked');
+ span.error('Created meeting note could not be linked');
+ return err({
+ kind: 'created_unlinked',
+ document,
+ message:
+ 'Your note was saved, but couldn’t be linked to this meeting. Retry linking or open the saved note.',
+ } satisfies NoteCreateFailure);
+ }
+ span.setAttr('calendar.notes.outcome', 'linked');
+ return ok(document);
+ });
+ },
+ picker(query, enabled) {
+ const debounced = createDebouncedMemo(query, 180);
+ const picker = useQuery(() =>
+ pickerOptions(userId(), debounced(), enabled())
+ );
+ return () => ({
+ data: queryReadyGate(picker) ? picker.data : undefined,
+ pending: picker.isPending,
+ error: picker.isError
+ ? 'Couldn’t load your notes. Try again.'
+ : undefined,
+ });
+ },
+ retry: () => notes.refetch(),
+ async link(documentId, teamId) {
+ const input = { ...target(), documentId, teamId };
+ return (await catchToResult(() => link.mutateAsync(input))).mapErr(
+ (): NoteFailure => ({
+ kind: 'link_failed',
+ message:
+ 'Couldn’t save this link. Check that you still own the note and can view the meeting, then try again.',
+ })
+ );
+ },
+ async unlink(documentId) {
+ const input = { ...target(), documentId };
+ return (await catchToResult(() => unlink.mutateAsync(input))).mapErr(
+ (): NoteFailure => ({
+ kind: 'unlink_failed',
+ message:
+ 'Couldn’t unlink this note. Your document is safe. Please try again.',
+ })
+ );
+ },
+ };
+}
+
+function documentLinksOptions(userId: string | undefined, documentId: string) {
+ return {
+ queryKey: notesKeys.documentLinks(userId, documentId).queryKey,
+ queryFn: async ({ signal }: { signal: AbortSignal }) => {
+ const links = await throwOnErr(() =>
+ calendarNotesClient.documentLinks(documentId, signal)
+ );
+ return links.map((link) => ({ ...link, team: link.team ?? undefined }));
+ },
+ enabled: !!userId,
+ staleTime: 0,
+ gcTime: 0,
+ };
+}
+
+export function createDocumentNotesSource(
+ userId: Accessor<string | undefined>,
+ documentId: Accessor<string>
+): DocumentNotesSource {
+ const links = useQuery(() => documentLinksOptions(userId(), documentId()));
+ const unlink = useMutation(() => ({
+ mutationFn: unlinkNote,
+ onSuccess: refreshNotes,
+ }));
+ return {
+ links: () => ({
+ data: queryReadyGate(links) ? links.data : undefined,
+ pending: links.isPending,
+ error: links.isError ? 'Couldn’t load meeting access.' : undefined,
+ }),
+ retry: () => links.refetch(),
+ async unlink(target) {
+ return (
+ await catchToResult(() =>
+ unlink.mutateAsync({ ...target, documentId: documentId() })
+ )
+ ).mapErr(
+ (): NoteFailure => ({
+ kind: 'unlink_failed',
+ message: 'Couldn’t remove this meeting link. Please try again.',
+ })
+ );
+ },
+ };
+}
diff --git a/apps/web/src/features/calendar-notes/tests/fake-source.ts b/apps/web/src/features/calendar-notes/tests/fake-source.ts
new file mode 100644
index 0000000000..8fe3880372
--- /dev/null
+++ b/apps/web/src/features/calendar-notes/tests/fake-source.ts
@@ -0,0 +1,72 @@
+import { err, ok } from 'neverthrow';
+import { createSignal } from 'solid-js';
+import type { NotesSource } from '../context/notes-source';
+import type { MeetingNote, NoteDocument } from '../core/types';
+
+export function createFakeNotesSource(options: { fail?: boolean } = {}) {
+ const documents: NoteDocument[] = [
+ { documentId: 'weekly', name: 'Weekly product sync' },
+ { documentId: 'roadmap', name: 'Q4 product roadmap' },
+ { documentId: 'research', name: 'Customer research · October' },
+ { documentId: 'retro', name: 'Team retrospective' },
+ ];
+ const team = { id: 'macro', name: 'Macro' };
+ const [notes, setNotes] = createSignal<MeetingNote[]>([]);
+ const [fail, setFail] = createSignal(options.fail ?? false);
+ let createdCount = 0;
+ const source: NotesSource = {
+ notes: () => ({ data: notes(), pending: false }),
+ picker: (query) => () => ({
+ data: {
+ documents: documents.filter((doc) =>
+ doc.name.toLowerCase().includes(query().toLowerCase())
+ ),
+ teams: [team],
+ },
+ pending: false,
+ }),
+ retry: async () => {},
+ async create(name) {
+ const document = { documentId: `created-${++createdCount}`, name };
+ documents.push(document);
+ const linked = await source.link(document.documentId);
+ if (linked.isErr()) {
+ return err({
+ kind: 'created_unlinked',
+ document,
+ message:
+ 'Your note was saved, but couldn’t be linked to this meeting. Retry linking or open the saved note.',
+ });
+ }
+ return ok(document);
+ },
+ async link(documentId, teamId) {
+ if (fail()) {
+ setFail(false);
+ return err({
+ kind: 'link_failed',
+ message: 'Couldn’t save this link. Please try again.',
+ });
+ }
+ const document = documents.find((doc) => doc.documentId === documentId);
+ if (!document)
+ return err({ kind: 'link_failed', message: 'Document not found' });
+ setNotes((current) => [
+ ...current.filter((note) => note.documentId !== documentId),
+ {
+ ...document,
+ team: teamId ? team : undefined,
+ canManage: true,
+ },
+ ]);
+ return ok(undefined);
+ },
+ async unlink(documentId) {
+ setNotes((current) =>
+ current.filter((note) => note.documentId !== documentId)
+ );
+ return ok(undefined);
+ },
+ };
+ return { source, notes };
+}
diff --git a/apps/web/src/features/calendar-notes/views/document-notes.tsx b/apps/web/src/features/calendar-notes/views/document-notes.tsx
new file mode 100644
index 0000000000..cd5fac5401
--- /dev/null
+++ b/apps/web/src/features/calendar-notes/views/document-notes.tsx
@@ -0,0 +1,23 @@
+import { fireAndForget } from '@core/util/fireAndForget';
+import { DocumentNotesSection } from '../components/document-notes-section';
+import type { DocumentNotesSource } from '../context/notes-source';
+import { createDocumentNotesController } from '../primitives/document-notes-controller';
+
+export function DocumentNotesView(props: { source: DocumentNotesSource }) {
+ const controller = createDocumentNotesController(props.source);
+ return (
+ <DocumentNotesSection
+ state={props.source.links()}
+ selected={controller.selected()}
+ saving={controller.saving()}
+ error={controller.error()}
+ onSelect={controller.select}
+ onRemove={() =>
+ fireAndForget(controller.remove(), 'calendar.notes.revoke')
+ }
+ onRetry={() =>
+ fireAndForget(props.source.retry(), 'calendar.notes.retry')
+ }
+ />
+ );
+}
diff --git a/apps/web/src/features/calendar-notes/views/meeting-notes.tsx b/apps/web/src/features/calendar-notes/views/meeting-notes.tsx
new file mode 100644
index 0000000000..386a327a66
--- /dev/null
+++ b/apps/web/src/features/calendar-notes/views/meeting-notes.tsx
@@ -0,0 +1,75 @@
+import { fireAndForget } from '@core/util/fireAndForget';
+import { Show } from 'solid-js';
+import { NoteDialog } from '../components/note-dialog';
+import { NotesSection } from '../components/notes-section';
+import type { NotesSource } from '../context/notes-source';
+import type { MeetingNote } from '../core/types';
+import { createMeetingNoteAction } from '../primitives/create-meeting-note';
+import { createNotesController } from '../primitives/notes-controller';
+
+export function MeetingNotesView(props: {
+ source: NotesSource;
+ eventTitle: string;
+ recurring: boolean;
+ guestListHidden?: boolean;
+ onOpen: (note: MeetingNote) => void;
+ onDialogChange: (open: boolean) => void;
+}) {
+ const controller = createNotesController(props.source, props.onDialogChange);
+ const creation = createMeetingNoteAction({
+ source: props.source,
+ title: () => props.eventTitle,
+ onOpen: (document) => props.onOpen({ ...document, canManage: true }),
+ });
+ return (
+ <>
+ <NotesSection
+ state={props.source.notes()}
+ creating={creation.pending()}
+ createdUnlinked={!!creation.saved()}
+ createError={creation.error()}
+ onCreate={() => fireAndForget(creation.run(), 'calendar.notes.create')}
+ onOpenSaved={creation.openSaved}
+ dialogOpen={!!controller.dialog()}
+ onMenuChange={controller.setMenuOpen}
+ onLink={controller.openLink}
+ onOpen={props.onOpen}
+ onSharing={controller.openSharing}
+ onUnlink={controller.openUnlink}
+ onRetry={() =>
+ fireAndForget(props.source.retry(), 'calendar.notes.retry')
+ }
+ />
+ <Show when={controller.dialog()}>
+ {(dialog) => (
+ <NoteDialog
+ kind={dialog().kind}
+ eventTitle={props.eventTitle}
+ recurring={props.recurring}
+ guestListHidden={props.guestListHidden}
+ picker={controller.picker()}
+ query={controller.query()}
+ onQuery={controller.setQuery}
+ selected={controller.selected()}
+ onSelect={controller.setSelected}
+ linkedIds={
+ props.source.notes().data?.map((note) => note.documentId) ?? []
+ }
+ teamId={controller.teamId()}
+ currentTeam={(() => {
+ const active = dialog();
+ return active.kind === 'link' ? undefined : active.note.team;
+ })()}
+ onTeam={controller.setTeamId}
+ saving={controller.saving()}
+ error={controller.error()}
+ onSave={() =>
+ fireAndForget(controller.save(), 'calendar.notes.save')
+ }
+ onClose={controller.close}
+ />
+ )}
+ </Show>
+ </>
+ );
+}
diff --git a/apps/web/src/features/calendar-view/components/SelectedEventDetails.test.tsx b/apps/web/src/features/calendar-view/components/SelectedEventDetails.test.tsx
index cd460fe0f4..cadacf4f09 100644
--- a/apps/web/src/features/calendar-view/components/SelectedEventDetails.test.tsx
+++ b/apps/web/src/features/calendar-view/components/SelectedEventDetails.test.tsx
@@ -3,19 +3,25 @@
*/
import type { CalendarEvent } from '@app/features/calendar/types';
+import { createSplitAutofocus } from '@components/app/split-layout/utils/createSplitAutofocus';
import { cleanup, render, screen } from '@solidjs/testing-library';
import userEvent from '@testing-library/user-event';
import { ImperativeDialogHost } from '@ui';
+import { createSignal } from 'solid-js';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { SelectedEventDetails } from './SelectedEventDetails';
const mocks = vi.hoisted(() => ({
mobile: false,
openComposer: vi.fn(),
+ openDocument: vi.fn(),
deleteEvent: vi.fn(),
}));
vi.mock('@core/mobile/isMobile', () => ({ isMobile: () => mocks.mobile }));
+vi.mock('@components/app/split-layout/layout', () => ({
+ useSplitLayout: () => ({ openWithSplit: mocks.openDocument }),
+}));
vi.mock('@queries/calendar/calendars', () => ({
useVisibleCalendarsQuery: () => ({ isSuccess: true, data: [] }),
}));
@@ -42,9 +48,17 @@ vi.mock('@app/features/calendar/hooks/create-guest-invite-controller', () => ({
}));
vi.mock('@app/features/calendar/hooks/use-calendar-ui-flag', () => ({
useCalendarGuestInvitesFlag: () => () => false,
+ useCalendarMeetingNotesFlag: () => () => true,
+}));
+// The sections have their own tests; exercise the overlay's actions and
+// navigation/focus handoff here.
+vi.mock('@app/features/calendar-notes/calendar-meeting-notes', () => ({
+ CalendarMeetingNotes: (props: { onOpenDocument: (id: string) => void }) => (
+ <button onClick={() => props.onOpenDocument('note-1')}>
+ Open linked note
+ </button>
+ ),
}));
-// The sections below the header have their own tests; this one is about the
-// header's actions.
vi.mock('@app/features/calendar/components/EventDetails', () => ({
EventDetails: () => null,
}));
@@ -120,20 +134,26 @@ function event(overrides: Partial<CalendarEvent> = {}): CalendarEvent {
function showDetails(selected: CalendarEvent) {
const boundary = document.createElement('div');
- const anchor = document.createElement('div');
+ const anchor = document.createElement('button');
+ const [selection, setSelection] = createSignal<CalendarEvent | undefined>(
+ selected
+ );
+ anchor.textContent = 'Open event details';
+ anchor.onclick = () => setSelection(selected);
document.body.append(boundary, anchor);
render(() => (
<>
<SelectedEventDetails
boundary={boundary}
anchor={() => anchor}
- event={() => selected}
+ event={selection}
timeFormat={() => '12-hour'}
- onClose={vi.fn()}
+ onClose={() => setSelection(undefined)}
/>
<ImperativeDialogHost />
</>
));
+ return anchor;
}
beforeEach(() => {
@@ -148,6 +168,55 @@ afterEach(() => {
vi.unstubAllGlobals();
});
+describe('desktop focus handoff', () => {
+ beforeEach(() => {
+ mocks.mobile = false;
+ });
+
+ it('lets a note that finishes mounting after dismissal claim focus', async () => {
+ const user = userEvent.setup();
+ const anchor = showDetails(event());
+ const [noteElement, setNoteElement] = createSignal<HTMLElement | null>(
+ null
+ );
+ render(() => {
+ createSplitAutofocus({ element: noteElement, enabled: () => true });
+ return null;
+ });
+
+ for (let attempt = 0; attempt < 2; attempt++) {
+ if (attempt > 0) await user.click(anchor);
+ await user.click(
+ screen.getByRole('button', { name: 'Open linked note' })
+ );
+ expect(mocks.openDocument).toHaveBeenCalledWith(
+ { type: 'md', id: 'note-1' },
+ { preferNewSplit: true }
+ );
+
+ const note = document.createElement('div');
+ note.tabIndex = -1;
+ document.body.append(note);
+ setNoteElement(note);
+ await Promise.resolve();
+ expect(document.activeElement).toBe(note);
+ }
+ });
+
+ it('returns focus to the event on ordinary dismissal and reopening', async () => {
+ const user = userEvent.setup();
+ const anchor = showDetails(event());
+
+ for (let attempt = 0; attempt < 2; attempt++) {
+ if (attempt > 0) await user.click(anchor);
+ await user.click(
+ screen.getByRole('button', { name: 'Close event details' })
+ );
+ expect(document.activeElement).toBe(anchor);
+ }
+ });
+});
+
describe.each([
['desktop popover', false],
['phone drawer', true],
diff --git a/apps/web/src/features/calendar-view/components/SelectedEventDetails.tsx b/apps/web/src/features/calendar-view/components/SelectedEventDetails.tsx
index 4abc627905..f345462b55 100644
--- a/apps/web/src/features/calendar-view/components/SelectedEventDetails.tsx
+++ b/apps/web/src/features/calendar-view/components/SelectedEventDetails.tsx
@@ -1,7 +1,10 @@
import { hasEveryoneElseDeclined } from '@app/features/calendar/components/EventContent';
import { EventDetails } from '@app/features/calendar/components/EventDetails';
import { createGuestInviteController } from '@app/features/calendar/hooks/create-guest-invite-controller';
-import { useCalendarGuestInvitesFlag } from '@app/features/calendar/hooks/use-calendar-ui-flag';
+import {
+ useCalendarGuestInvitesFlag,
+ useCalendarMeetingNotesFlag,
+} from '@app/features/calendar/hooks/use-calendar-ui-flag';
import {
type CalendarEvent,
type CalendarTimeFormat,
@@ -13,6 +16,7 @@ import {
} from '@app/features/calendar/utils/event-interaction';
import { eventEmailRecipients } from '@app/features/calendar/utils/guest-emails';
import { handleOpenEventOutsidePress } from '@app/features/calendar/utils/open-event-outside-press';
+import { CalendarMeetingNotes } from '@app/features/calendar-notes/calendar-meeting-notes';
import { TeamEventDetails } from '@app/features/calendar-team/components/team-event-details';
import { EventGuests } from '@app/features/calendar-view/components/EventGuests';
import { EventJoinRequests } from '@app/features/calendar-view/components/EventJoinRequests';
@@ -22,6 +26,7 @@ import { useOpenEventComposer } from '@app/features/calendar-view/components/use
import { copyCalendarEventMention } from '@app/features/calendar-view/copy-event-mention';
import { downloadCalendarEventIcs } from '@app/features/calendar-view/download-event-ics';
import { MobileDrawer } from '@components/app/mobile/MobileDrawer';
+import { useSplitLayout } from '@components/app/split-layout/layout';
import { toast } from '@core/component/Toast/Toast';
import { isMobile } from '@core/mobile/isMobile';
import { openExternalUrl } from '@core/util/url';
@@ -177,6 +182,10 @@ function EveryoneElseDeclinedNotice(props: {
}
function EventDetailsDrawer(props: EventDetailsOverlayProps) {
+ const meetingNotesEnabled = useCalendarMeetingNotesFlag();
+ const [notesOpen, setNotesOpen] = createSignal(false);
+ let content: HTMLDivElement | undefined;
+ const { openWithSplit } = useSplitLayout();
const openEventComposer = useOpenEventComposer();
const deleteDialog = useDeleteEventDialog({
event: () => props.event,
@@ -204,15 +213,25 @@ function EventDetailsDrawer(props: EventDetailsOverlayProps) {
side="bottom"
open
onOpenChange={(open) => {
- if (!open && (deleteDialog.isOpen() || invites.editorOpen())) return;
+ if (
+ !open &&
+ (deleteDialog.isOpen() || invites.editorOpen() || notesOpen())
+ )
+ return;
props.onOpenChange(open);
}}
preventScroll={false}
preventScrollbarShift={false}
+ trapFocus={!notesOpen()}
+ onInitialFocus={(event) => {
+ if (notesOpen() || content?.contains(document.activeElement))
+ event.preventDefault();
+ }}
>
<MobileDrawer.Portal>
<MobileDrawer.Overlay />
<MobileDrawer.Content
+ ref={content}
aria-label={props.event.title}
class="overflow-hidden"
>
@@ -316,6 +335,23 @@ function EventDetailsDrawer(props: EventDetailsOverlayProps) {
/>
</Show>
</div>
+ <Show
+ when={
+ meetingNotesEnabled() &&
+ props.event.teamProjection?.kind !== 'busy' &&
+ !props.event.isCancelled &&
+ !props.event.isSnapshot
+ }
+ >
+ <CalendarMeetingNotes
+ event={props.event}
+ onDialogChange={setNotesOpen}
+ onOpenDocument={(id) => {
+ openWithSplit({ type: 'md', id }, { preferNewSplit: false });
+ props.onOpenChange(false);
+ }}
+ />
+ </Show>
<Show when={!props.event.teamProjection}>
<EventGuests
event={props.event}
@@ -450,6 +486,10 @@ function DeleteEventDialog(
* scroll within 32rem or the available height; the RSVP row stays pinned.
*/
function EventDetailsPopover(props: EventDetailsPopoverProps) {
+ const meetingNotesEnabled = useCalendarMeetingNotesFlag();
+ const [notesOpen, setNotesOpen] = createSignal(false);
+ let openingDocument = false;
+ const { openWithSplit } = useSplitLayout();
const openEventComposer = useOpenEventComposer();
const deleteDialog = useDeleteEventDialog({
event: () => props.event,
@@ -480,7 +520,11 @@ function EventDetailsPopover(props: EventDetailsPopoverProps) {
onOpenChange={(open) => {
// Keep the popover mounted while its delete dialog or guest editor
// is open.
- if (!open && (deleteDialog.isOpen() || invites.editorOpen())) return;
+ if (
+ !open &&
+ (deleteDialog.isOpen() || invites.editorOpen() || notesOpen())
+ )
+ return;
props.onOpenChange(open);
}}
placement="right-start"
@@ -512,7 +556,8 @@ function EventDetailsPopover(props: EventDetailsPopoverProps) {
event.preventDefault();
}}
onCloseAutoFocus={(event) => {
- const shouldRestoreFocus = !event.defaultPrevented;
+ const shouldRestoreFocus =
+ !openingDocument && !event.defaultPrevented;
event.preventDefault();
if (shouldRestoreFocus && props.anchor.isConnected) {
props.anchor.focus();
@@ -622,6 +667,27 @@ function EventDetailsPopover(props: EventDetailsPopoverProps) {
/>
</Show>
</div>
+ <Show
+ when={
+ meetingNotesEnabled() &&
+ props.event.teamProjection?.kind !== 'busy' &&
+ !props.event.isCancelled &&
+ !props.event.isSnapshot
+ }
+ >
+ <CalendarMeetingNotes
+ event={props.event}
+ onDialogChange={setNotesOpen}
+ onOpenDocument={(id) => {
+ openingDocument = true;
+ openWithSplit(
+ { type: 'md', id },
+ { preferNewSplit: true }
+ );
+ props.onOpenChange(false);
+ }}
+ />
+ </Show>
<Show when={!props.event.teamProjection}>
<EventGuests
event={props.event}
diff --git a/apps/web/src/features/calendar/hooks/use-calendar-ui-flag.ts b/apps/web/src/features/calendar/hooks/use-calendar-ui-flag.ts
index 3569d11a73..4a29850894 100644
--- a/apps/web/src/features/calendar/hooks/use-calendar-ui-flag.ts
+++ b/apps/web/src/features/calendar/hooks/use-calendar-ui-flag.ts
@@ -2,6 +2,7 @@ import { useFeatureFlag } from '@app/lib/analytics/posthog';
import {
enableCalendarAddSharedEvent,
enableCalendarGuestInvites,
+ enableCalendarMeetingNotes,
enableCalendarPromptMobile,
enableCalendarPromptWeb,
enableCalendarSearchUi,
@@ -17,6 +18,11 @@ export function useCalendarUiFlag(): Accessor<boolean> {
return () => flag().enabled;
}
+export function useCalendarMeetingNotesFlag(): Accessor<boolean> {
+ const flag = useFeatureFlag(enableCalendarMeetingNotes);
+ return () => flag().enabled;
+}
+
/**
* Whether the calendar search UI (Search-view calendar type/rows and the
* in-calendar keyword search) is enabled. A sub-feature of the calendar UI, so
diff --git a/apps/web/src/lib/core/component/TopBar/ShareButton.test.tsx b/apps/web/src/lib/core/component/TopBar/ShareButton.test.tsx
index f5413602d9..96d8acf665 100644
--- a/apps/web/src/lib/core/component/TopBar/ShareButton.test.tsx
+++ b/apps/web/src/lib/core/component/TopBar/ShareButton.test.tsx
@@ -1,7 +1,7 @@
import { ForwardToChannel } from '@core/component/ForwardToChannel';
import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';
import { err, ok } from 'neverthrow';
-import { createSignal, For, type JSX } from 'solid-js';
+import { createSignal, For, type JSX, onCleanup } from 'solid-js';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { Permissions } from '../SharePermissions';
import {
@@ -11,6 +11,28 @@ import {
shareLevelsFor,
} from './ShareButton';
+vi.mock('@app/features/calendar-notes/document-meeting-notes', () => ({
+ DocumentMeetingNotes: (props: {
+ documentId: string;
+ onAccessState?: (state: 'shared' | 'none') => void;
+ }) => {
+ mocks.mountMeetingNotes(props.documentId);
+ onCleanup(mocks.unmountMeetingNotes);
+ props.onAccessState?.(
+ props.documentId === 'meeting-note' ? 'shared' : 'none'
+ );
+ return (
+ <section aria-label="Meeting links">
+ Meeting links for {props.documentId}
+ </section>
+ );
+ },
+}));
+
+vi.mock('@app/lib/analytics/posthog', () => ({
+ useFeatureFlag: () => () => mocks.meetingNotesFlag(),
+}));
+
// Share's request workflow has its own source and lifecycle suites. Keep these
// existing sharing tests independent of a live QueryClient and backend.
vi.mock('@app/features/access-requests/access-requests', async (original) => ({
@@ -43,6 +65,9 @@ const ME = 'macro|[email protected]';
const SOMEONE_ELSE = 'macro|[email protected]';
const mocks = vi.hoisted(() => ({
+ meetingNotesFlag: () => ({ enabled: true, loading: false }),
+ mountMeetingNotes: vi.fn(),
+ unmountMeetingNotes: vi.fn(),
sendToChannel: vi.fn(),
sendToUsers: vi.fn(),
graphql: false,
@@ -385,6 +410,7 @@ vi.mock('@ui', async () => {
});
beforeEach(() => {
vi.clearAllMocks();
+ mocks.meetingNotesFlag = () => ({ enabled: true, loading: false });
mocks.inBlock = true;
mocks.blockEditPermissionEnabled = true;
mocks.mobile = false;
@@ -420,6 +446,99 @@ beforeEach(() => {
});
});
afterEach(cleanup);
+
+describe('document meeting-link management', () => {
+ it.each([false, true])(
+ 'gates the meeting source without implying grants were revoked (mobile: %s)',
+ async (mobile) => {
+ mocks.mobile = mobile;
+ const [flag, setFlag] = createSignal({ enabled: false, loading: true });
+ const [documentId, setDocumentId] = createSignal('meeting-note');
+ mocks.meetingNotesFlag = flag;
+ render(() => (
+ <ShareModal
+ id={documentId()}
+ name="Notes"
+ owner={ME}
+ itemType="document"
+ blockAlias="md"
+ userPermissions={Permissions.OWNER}
+ open
+ onOpenChange={vi.fn()}
+ />
+ ));
+ if (mobile)
+ await fireEvent.click(screen.getByRole('tab', { name: /^Link$/ }));
+ expect(mocks.mountMeetingNotes).not.toHaveBeenCalled();
+ expect(screen.getByText('Checking access…')).toBeDefined();
+ expect(screen.queryByText('Just me')).toBeNull();
+
+ setFlag({ enabled: false, loading: false });
+ expect(mocks.mountMeetingNotes).not.toHaveBeenCalled();
+ expect(screen.getByText('Restricted')).toBeDefined();
+ expect(screen.queryByText('Just me')).toBeNull();
+
+ setFlag({ enabled: true, loading: false });
+ expect(mocks.mountMeetingNotes).toHaveBeenCalledExactlyOnceWith(
+ 'meeting-note'
+ );
+ expect(screen.getByText('Shared')).toBeDefined();
+
+ setFlag({ enabled: false, loading: false });
+ expect(mocks.unmountMeetingNotes).toHaveBeenCalledOnce();
+ expect(screen.getByText('Shared')).toBeDefined();
+ expect(screen.queryByText('Just me')).toBeNull();
+
+ setDocumentId('another-note');
+ expect(screen.queryByText('Shared')).toBeNull();
+ expect(screen.getByText('Restricted')).toBeDefined();
+ expect(mocks.mountMeetingNotes).toHaveBeenCalledTimes(1);
+ setFlag({ enabled: true, loading: false });
+ expect(mocks.mountMeetingNotes).toHaveBeenLastCalledWith('another-note');
+ expect(screen.getByText('Just me')).toBeDefined();
+ }
+ );
+ it.each([false, true])(
+ 'is reachable by the document owner (mobile: %s)',
+ async (mobile) => {
+ mocks.mobile = mobile;
+ render(() => (
+ <ShareModal
+ id="meeting-note"
+ name="Notes"
+ owner={ME}
+ itemType="document"
+ blockAlias="md"
+ userPermissions={Permissions.OWNER}
+ open
+ onOpenChange={vi.fn()}
+ />
+ ));
+ if (mobile)
+ await fireEvent.click(screen.getByRole('tab', { name: /^Link$/ }));
+ expect(
+ (await screen.findByRole('region', { name: 'Meeting links' }))
+ .textContent
+ ).toContain('meeting-note');
+ expect(screen.queryByText('Just me')).toBeNull();
+ }
+ );
+ it('does not request another owner’s meeting links', () => {
+ render(() => (
+ <ShareModal
+ id="meeting-note"
+ name="Notes"
+ owner={SOMEONE_ELSE}
+ itemType="document"
+ blockAlias="md"
+ userPermissions={Permissions.CAN_VIEW}
+ open
+ onOpenChange={vi.fn()}
+ />
+ ));
+ expect(screen.queryByRole('region', { name: 'Meeting links' })).toBeNull();
+ });
+});
function mountShare(isOwner: boolean) {
const onOpenChange = vi.fn();
const onCopyLink = mocks.copyLink;
diff --git a/apps/web/src/lib/core/component/TopBar/ShareButton.tsx b/apps/web/src/lib/core/component/TopBar/ShareButton.tsx
index 19ee0a52f1..0b6150ed61 100644
--- a/apps/web/src/lib/core/component/TopBar/ShareButton.tsx
+++ b/apps/web/src/lib/core/component/TopBar/ShareButton.tsx
@@ -11,6 +11,8 @@ import {
ShareRequestIcon,
useShareRequestTrigger,
} from '@app/features/access-requests/share-request-trigger';
+import type { MeetingAccessState } from '@app/features/calendar-notes/core/types';
+import { DocumentMeetingNotes } from '@app/features/calendar-notes/document-meeting-notes';
import {
fetchPipelineSharePermissions,
updatePipelineSharePermissions,
@@ -18,6 +20,7 @@ import {
} from '@app/features/crm/sharing-adapter';
import { projectRouteId } from '@app/features/projects/core/route';
import { useAnalytics } from '@app/lib/analytics/analytics-context';
+import { useFeatureFlag } from '@app/lib/analytics/posthog';
import { useChannelParticipants } from '@channel/use-channel-participants';
import { HeaderActionButton } from '@components/app/HeaderActionButton';
import { HeaderActionGroup } from '@components/app/HeaderActionGroup';
@@ -45,6 +48,7 @@ import { UserIcon } from '@core/component/UserIcon';
import {
ENABLE_MARKDOWN_COMMENTS,
ENABLE_MARKDOWN_LIVE_COLLABORATION,
+ enableCalendarMeetingNotes,
} from '@core/constant/featureFlags';
import { useUserId } from '@core/context/user';
import clickOutside from '@core/directive/clickOutside';
@@ -414,6 +418,7 @@ interface LinkSharingControlsProps {
linkShare: LinkShare | null | undefined;
linkShareAccessLevel: AccessLevel | null | undefined;
hasExplicitShares: boolean;
+ meetingAccess?: MeetingAccessState | 'unknown';
setLinkShareScope: (scope: LinkShareScope) => void;
setLinkShareAccessLevel: (accessLevel: AccessLevel | null) => void;
copyLink: () => void;
@@ -486,12 +491,42 @@ function TeamAccessSection(props: { teamShare: TeamShareControls }) {
function LinkSharingControls(props: LinkSharingControlsProps) {
const scope = () => getLinkShareScope(props.linkShare);
const scopeCopy = () => getLinkShareScopeCopy(scope());
- const shareStatus = () =>
- getShareStatus(
+ const shareStatus = () => {
+ const status = getShareStatus(
props.linkShare,
- props.hasExplicitShares,
+ props.hasExplicitShares || props.meetingAccess === 'shared',
props.teamShare?.accessLevel
);
+ if (status.label === 'Shared' && props.meetingAccess === 'shared') {
+ return {
+ ...status,
+ tooltip: props.hasExplicitShares
+ ? 'Shared with specific people or channels and through meeting links.'
+ : 'Shared through meeting links with meeting viewers and any teams selected there.',
+ };
+ }
+ if (status.label !== 'Just me') return status;
+ if (props.meetingAccess === 'unknown') {
+ return {
+ label: 'Restricted',
+ tooltip: 'Only people with access can open this link.',
+ };
+ }
+ if (props.meetingAccess === 'loading') {
+ return {
+ label: 'Checking access…',
+ tooltip: 'Meeting links may grant additional access.',
+ };
+ }
+ if (props.meetingAccess === 'error') {
+ return {
+ label: 'Check meeting access',
+ tooltip:
+ 'Meeting links may grant additional access. See Meeting links.',
+ };
+ }
+ return status;
+ };
return (
<div class="flex flex-col gap-3 p-4 text-sm text-ink">
@@ -552,6 +587,9 @@ function LinkSharingControls(props: LinkSharingControlsProps) {
}
interface MobileShareDrawerProps {
+ meetingNotesEnabled: boolean;
+ meetingAccess?: MeetingAccessState | 'unknown';
+ onMeetingAccessState: (state: MeetingAccessState) => void;
requests: SharingSource;
requestLevels: readonly AccessLevel[];
editPermissionEnabled?: boolean;
@@ -585,6 +623,7 @@ interface MobileShareDrawerProps {
}
function MobileShareDrawer(props: MobileShareDrawerProps) {
+ const userId = useUserId();
const [activeTab, setActiveTab] = createSignal<string>();
const wrappedSetOpen = (open: boolean) => {
@@ -821,6 +860,7 @@ function MobileShareDrawer(props: MobileShareDrawerProps) {
when={props.linkSharing}
fallback={
<LinkSharingControls
+ meetingAccess={props.meetingAccess}
editPermissionEnabled={props.editPermissionEnabled}
linkShare={props.linkShare}
linkShareAccessLevel={props.linkShareAccessLevel}
@@ -839,6 +879,20 @@ function MobileShareDrawer(props: MobileShareDrawerProps) {
<Dynamic component={props.linkSharing} />
</div>
</Show>
+ <Show
+ when={
+ props.meetingNotesEnabled &&
+ props.blockAlias === 'md' &&
+ props.itemType === 'document' &&
+ !!userId() &&
+ props.owner === userId()
+ }
+ >
+ <DocumentMeetingNotes
+ documentId={props.id}
+ onAccessState={props.onMeetingAccessState}
+ />
+ </Show>
</Show>
<Show
when={
@@ -860,6 +914,7 @@ function MobileShareDrawer(props: MobileShareDrawerProps) {
}
export function ShareModal(props: ShareModalProps) {
+ const meetingNotesFlag = useFeatureFlag(enableCalendarMeetingNotes);
const requests = useShareRequests(
() => shareEntity(props.itemType, props.id),
() => props.open
@@ -906,6 +961,36 @@ export function ShareModal(props: ShareModalProps) {
? permissionsBlockResource[1].refetch
: refetchFallback;
const userId = useUserId();
+ const [meetingAccessSnapshot, setMeetingAccessSnapshot] = createSignal<{
+ documentId: string;
+ userId: string | undefined;
+ state: MeetingAccessState;
+ }>();
+ const setMeetingAccess = (state: MeetingAccessState) =>
+ setMeetingAccessSnapshot({ documentId: props.id, userId: userId(), state });
+ const meetingAccess = (): MeetingAccessState => {
+ const snapshot = meetingAccessSnapshot();
+ return snapshot?.documentId === props.id && snapshot.userId === userId()
+ ? snapshot.state
+ : 'loading';
+ };
+ const canManageMeetingLinks = () =>
+ props.blockAlias === 'md' &&
+ props.itemType === 'document' &&
+ !!userId() &&
+ (props.owner ?? requests.state()?.owner) === userId();
+ const meetingAccessForSharing = ():
+ | MeetingAccessState
+ | 'unknown'
+ | undefined => {
+ if (!canManageMeetingLinks()) return undefined;
+ // Turning off the UI does not revoke grants. Keep known sharing visible and
+ // avoid claiming privacy when the gated source cannot check saved links.
+ if (meetingAccess() === 'shared') return 'shared';
+ const flag = meetingNotesFlag();
+ if (flag.loading) return 'loading';
+ return flag.enabled ? meetingAccess() : 'unknown';
+ };
// Like a document, a pipeline is shared by anyone who can edit it. Only its
// owner changes team access, which `teamShareControls` still requires.
const canSharePipeline = () =>
@@ -1526,6 +1611,9 @@ export function ShareModal(props: ShareModalProps) {
when={!isMobile()}
fallback={
<MobileShareDrawer
+ meetingNotesEnabled={meetingNotesFlag().enabled}
+ meetingAccess={meetingAccessForSharing()}
+ onMeetingAccessState={setMeetingAccess}
requests={requests}
requestLevels={requestLevels()}
directPeopleIds={props.directPeopleIds}
@@ -1812,6 +1900,21 @@ export function ShareModal(props: ShareModalProps) {
</Show>
{/* Card 3: Link sharing — plain border */}
+ <Show
+ when={
+ props.open &&
+ meetingNotesFlag().enabled &&
+ props.blockAlias === 'md' &&
+ props.itemType === 'document' &&
+ !!userId() &&
+ (props.owner ?? requests.state()?.owner) === userId()
+ }
+ >
+ <DocumentMeetingNotes
+ documentId={props.id}
+ onAccessState={setMeetingAccess}
+ />
+ </Show>
<Show
when={
props.linkSharing ||
@@ -1829,6 +1932,7 @@ export function ShareModal(props: ShareModalProps) {
when={props.linkSharing}
fallback={
<LinkSharingControls
+ meetingAccess={meetingAccessForSharing()}
editPermissionEnabled={editPermissionEnabled()}
linkShare={linkShare()}
linkShareAccessLevel={linkShareAccessLevel()}
diff --git a/apps/web/src/lib/core/constant/featureFlags.ts b/apps/web/src/lib/core/constant/featureFlags.ts
index 8499211a07..046cfa7645 100644
--- a/apps/web/src/lib/core/constant/featureFlags.ts
+++ b/apps/web/src/lib/core/constant/featureFlags.ts
@@ -609,6 +609,15 @@ export const enableCalendarUi = defineFlag({
default: onInDev,
});
+// Calendar meeting notes and document-side meeting-link management. On in dev;
+// production uses PostHog's internal-user rollout. This is a UI rollout, not
+// an authorization check: saved meeting grants remain enforced by the service.
+export const enableCalendarMeetingNotes = defineFlag({
+ key: 'enable-calendar-meeting-notes',
+ env: 'ENABLE_CALENDAR_MEETING_NOTES',
+ default: onInDev,
+});
+
// Calendar event search UI: the Search view's Calendar type (and calendar
// rows) plus the in-calendar keyword search. A sub-feature of the calendar UI
// — opening a hit needs the calendar block — so it only takes effect where
diff --git a/apps/web/src/lib/service-clients/service-calendar/generated/client.ts b/apps/web/src/lib/service-clients/service-calendar/generated/client.ts
index 78b6e2ab15..c57c2aa320 100644
--- a/apps/web/src/lib/service-clients/service-calendar/generated/client.ts
+++ b/apps/web/src/lib/service-clients/service-calendar/generated/client.ts
@@ -16,12 +16,20 @@ import type {
CopyCalendarEventRequest,
CreateCalendarEventRequest,
DeleteCalendarEventParams,
+ DocumentNoteLink,
+ EventNotesParams,
InviteCalendarEventGuestsRequest,
+ LinkEventNoteParams,
+ LinkNoteRequest,
ListCalendarsResponse,
+ MeetingNote,
+ NoteDocumentsParams,
+ NotePicker,
PrepareCalendarReplacementRequest,
RespondToJoinRequestRequest,
RsvpCalendarEventRequest,
TeamCalendarSharingBody,
+ UnlinkEventNoteParams,
UpdateCalendarEventRequest,
} from './schemas';
@@ -590,6 +598,169 @@ export const inviteCalendarEventGuests = async (
} as inviteCalendarEventGuestsResponse;
};
+/**
+ * @summary List notes visible through this meeting occurrence.
+ */
+export type eventNotesResponse200 = {
+ data: MeetingNote[];
+ status: 200;
+};
+
+export type eventNotesResponseSuccess = eventNotesResponse200 & {
+ headers: Headers;
+};
+
+export type eventNotesResponse = eventNotesResponseSuccess;
+
+export const getEventNotesUrl = (eventId: string, params: EventNotesParams) => {
+ const normalizedParams = new URLSearchParams();
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : value.toString());
+ }
+ });
+
+ const stringifiedParams = normalizedParams.toString();
+
+ return stringifiedParams.length > 0
+ ? `/events/${eventId}/notes?${stringifiedParams}`
+ : `/events/${eventId}/notes`;
+};
+
+export const eventNotes = async (
+ eventId: string,
+ params: EventNotesParams,
+ options?: RequestInit
+): Promise<eventNotesResponse> => {
+ const res = await fetch(getEventNotesUrl(eventId, params), {
+ ...options,
+ method: 'GET',
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: eventNotesResponse['data'] = body ? JSON.parse(body) : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as eventNotesResponse;
+};
+
+/**
+ * @summary Idempotently link a markdown document and its optional team audience.
+ */
+export type linkEventNoteResponse204 = {
+ data: void;
+ status: 204;
+};
+
+export type linkEventNoteResponseSuccess = linkEventNoteResponse204 & {
+ headers: Headers;
+};
+
+export type linkEventNoteResponse = linkEventNoteResponseSuccess;
+
+export const getLinkEventNoteUrl = (
+ eventId: string,
+ documentId: string,
+ params: LinkEventNoteParams
+) => {
+ const normalizedParams = new URLSearchParams();
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : value.toString());
+ }
+ });
+
+ const stringifiedParams = normalizedParams.toString();
+
+ return stringifiedParams.length > 0
+ ? `/events/${eventId}/notes/${documentId}?${stringifiedParams}`
+ : `/events/${eventId}/notes/${documentId}`;
+};
+
+export const linkEventNote = async (
+ eventId: string,
+ documentId: string,
+ linkNoteRequest: LinkNoteRequest,
+ params: LinkEventNoteParams,
+ options?: RequestInit
+): Promise<linkEventNoteResponse> => {
+ const res = await fetch(getLinkEventNoteUrl(eventId, documentId, params), {
+ ...options,
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(linkNoteRequest),
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: linkEventNoteResponse['data'] = body ? JSON.parse(body) : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as linkEventNoteResponse;
+};
+
+/**
+ * @summary Remove this meeting's grant without deleting the document.
+ */
+export type unlinkEventNoteResponse204 = {
+ data: void;
+ status: 204;
+};
+
+export type unlinkEventNoteResponseSuccess = unlinkEventNoteResponse204 & {
+ headers: Headers;
+};
+
+export type unlinkEventNoteResponse = unlinkEventNoteResponseSuccess;
+
+export const getUnlinkEventNoteUrl = (
+ eventId: string,
+ documentId: string,
+ params: UnlinkEventNoteParams
+) => {
+ const normalizedParams = new URLSearchParams();
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : value.toString());
+ }
+ });
+
+ const stringifiedParams = normalizedParams.toString();
+
+ return stringifiedParams.length > 0
+ ? `/events/${eventId}/notes/${documentId}?${stringifiedParams}`
+ : `/events/${eventId}/notes/${documentId}`;
+};
+
+export const unlinkEventNote = async (
+ eventId: string,
+ documentId: string,
+ params: UnlinkEventNoteParams,
+ options?: RequestInit
+): Promise<unlinkEventNoteResponse> => {
+ const res = await fetch(getUnlinkEventNoteUrl(eventId, documentId, params), {
+ ...options,
+ method: 'DELETE',
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: unlinkEventNoteResponse['data'] = body ? JSON.parse(body) : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as unlinkEventNoteResponse;
+};
+
/**
* @summary Resolve an authorized event's provider link for Outlook-only actions.
*/
@@ -904,6 +1075,92 @@ export const respondToJoinRequest = async (
} as respondToJoinRequestResponse;
};
+/**
+ * @summary Suggest the caller's markdown documents and extra team audiences.
+ */
+export type noteDocumentsResponse200 = {
+ data: NotePicker;
+ status: 200;
+};
+
+export type noteDocumentsResponseSuccess = noteDocumentsResponse200 & {
+ headers: Headers;
+};
+
+export type noteDocumentsResponse = noteDocumentsResponseSuccess;
+
+export const getNoteDocumentsUrl = (params?: NoteDocumentsParams) => {
+ const normalizedParams = new URLSearchParams();
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : value.toString());
+ }
+ });
+
+ const stringifiedParams = normalizedParams.toString();
+
+ return stringifiedParams.length > 0
+ ? `/meeting-notes/documents?${stringifiedParams}`
+ : `/meeting-notes/documents`;
+};
+
+export const noteDocuments = async (
+ params?: NoteDocumentsParams,
+ options?: RequestInit
+): Promise<noteDocumentsResponse> => {
+ const res = await fetch(getNoteDocumentsUrl(params), {
+ ...options,
+ method: 'GET',
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: noteDocumentsResponse['data'] = body ? JSON.parse(body) : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as noteDocumentsResponse;
+};
+
+/**
+ * @summary List an owned document's meeting grants, including unavailable meetings.
+ */
+export type documentNoteLinksResponse200 = {
+ data: DocumentNoteLink[];
+ status: 200;
+};
+
+export type documentNoteLinksResponseSuccess = documentNoteLinksResponse200 & {
+ headers: Headers;
+};
+
+export type documentNoteLinksResponse = documentNoteLinksResponseSuccess;
+
+export const getDocumentNoteLinksUrl = (documentId: string) => {
+ return `/meeting-notes/documents/${documentId}/links`;
+};
+
+export const documentNoteLinks = async (
+ documentId: string,
+ options?: RequestInit
+): Promise<documentNoteLinksResponse> => {
+ const res = await fetch(getDocumentNoteLinksUrl(documentId), {
+ ...options,
+ method: 'GET',
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: documentNoteLinksResponse['data'] = body ? JSON.parse(body) : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as documentNoteLinksResponse;
+};
+
/**
* @summary Read saved progress without performing a provider mutation.
*/
diff --git a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/documentNoteLink.ts b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/documentNoteLink.ts
new file mode 100644
index 0000000000..7ae0e2f6be
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/documentNoteLink.ts
@@ -0,0 +1,22 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * calendar_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { DocumentNoteLinkTeam } from './documentNoteLinkTeam';
+
+/**
+ * An owner's durable sharing link, including meetings they can no longer open.
+ */
+export interface DocumentNoteLink {
+ /** Current name of the owned markdown document. */
+ documentName: string;
+ /** Linked calendar copy. */
+ eventId: string;
+ /** Current title, or a safe placeholder when meeting details are unavailable. */
+ eventTitle: string;
+ /** Original occurrence start, or `single` for a one-time meeting. */
+ occurrenceKey: string;
+ team?: DocumentNoteLinkTeam;
+}
diff --git a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/documentNoteLinkTeam.ts b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/documentNoteLinkTeam.ts
new file mode 100644
index 0000000000..09e2a6a074
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/documentNoteLinkTeam.ts
@@ -0,0 +1,9 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * calendar_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { NoteTeam } from './noteTeam';
+
+export type DocumentNoteLinkTeam = null | NoteTeam;
diff --git a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/eventNotesParams.ts b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/eventNotesParams.ts
new file mode 100644
index 0000000000..6aa872b90f
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/eventNotesParams.ts
@@ -0,0 +1,13 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * calendar_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type EventNotesParams = {
+ /**
+ * Stable occurrence key returned by the calendar read API.
+ */
+ occurrenceKey: string;
+};
diff --git a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/index.ts
index 1b445f2265..1e5ad914d0 100644
--- a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/index.ts
+++ b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/index.ts
@@ -64,6 +64,9 @@ export * from './createCalendarEventRequestReminders';
export * from './createCalendarEventRequestTransparency';
export * from './createCalendarEventRequestVisibility';
export * from './deleteCalendarEventParams';
+export * from './documentNoteLink';
+export * from './documentNoteLinkTeam';
+export * from './eventNotesParams';
export * from './eventReminderOverride';
export * from './eventReminders';
export * from './eventStatus';
@@ -81,7 +84,16 @@ export * from './inviteCalendarEventGuestsRequest';
export * from './inviteCalendarEventGuestsRequestCalendarId';
export * from './inviteCalendarEventGuestsRequestRecurrenceId';
export * from './inviteCalendarEventGuestsRequestScope';
+export * from './linkEventNoteParams';
+export * from './linkNoteRequest';
+export * from './linkNoteRequestTeamId';
export * from './listCalendarsResponse';
+export * from './meetingNote';
+export * from './meetingNoteTeam';
+export * from './noteDocument';
+export * from './noteDocumentsParams';
+export * from './notePicker';
+export * from './noteTeam';
export * from './outOfOfficeAutoDeclineMode';
export * from './outOfOfficeProperties';
export * from './outOfOfficePropertiesDeclineMessage';
@@ -102,6 +114,7 @@ export * from './rsvpCalendarEventRequestRespondingEmail';
export * from './rsvpCalendarEventRequestScope';
export * from './teamCalendarSharing';
export * from './teamCalendarSharingBody';
+export * from './unlinkEventNoteParams';
export * from './updateCalendarEventRequest';
export * from './updateCalendarEventRequestAttendees';
export * from './updateCalendarEventRequestCalendarId';
diff --git a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/linkEventNoteParams.ts b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/linkEventNoteParams.ts
new file mode 100644
index 0000000000..8ed305d0da
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/linkEventNoteParams.ts
@@ -0,0 +1,13 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * calendar_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type LinkEventNoteParams = {
+ /**
+ * Stable occurrence key returned by the calendar read API.
+ */
+ occurrenceKey: string;
+};
diff --git a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/linkNoteRequest.ts b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/linkNoteRequest.ts
new file mode 100644
index 0000000000..0aef5bab5b
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/linkNoteRequest.ts
@@ -0,0 +1,15 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * calendar_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { LinkNoteRequestTeamId } from './linkNoteRequestTeamId';
+
+/**
+ * Optional additional view access for one team.
+ */
+export interface LinkNoteRequest {
+ /** Null means the meeting audience only. */
+ teamId?: LinkNoteRequestTeamId;
+}
diff --git a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/linkNoteRequestTeamId.ts b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/linkNoteRequestTeamId.ts
new file mode 100644
index 0000000000..228647427b
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/linkNoteRequestTeamId.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * calendar_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Null means the meeting audience only.
+ */
+export type LinkNoteRequestTeamId = string | null;
diff --git a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/meetingNote.ts b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/meetingNote.ts
new file mode 100644
index 0000000000..0b512301e7
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/meetingNote.ts
@@ -0,0 +1,20 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * calendar_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { MeetingNoteTeam } from './meetingNoteTeam';
+
+/**
+ * One linked document and the extra access this link grants.
+ */
+export interface MeetingNote {
+ /** Whether this viewer can change this document's sharing. */
+ canManage: boolean;
+ /** Markdown document identity. */
+ documentId: string;
+ /** Current document name. */
+ name: string;
+ team?: MeetingNoteTeam;
+}
diff --git a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/meetingNoteTeam.ts b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/meetingNoteTeam.ts
new file mode 100644
index 0000000000..67e210f94c
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/meetingNoteTeam.ts
@@ -0,0 +1,9 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * calendar_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { NoteTeam } from './noteTeam';
+
+export type MeetingNoteTeam = null | NoteTeam;
diff --git a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/noteDocument.ts b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/noteDocument.ts
new file mode 100644
index 0000000000..e532b93f98
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/noteDocument.ts
@@ -0,0 +1,16 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * calendar_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * A document available in the note picker.
+ */
+export interface NoteDocument {
+ /** Markdown document identity. */
+ documentId: string;
+ /** Current document name, never a copied title. */
+ name: string;
+}
diff --git a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/noteDocumentsParams.ts b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/noteDocumentsParams.ts
new file mode 100644
index 0000000000..150efcf598
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/noteDocumentsParams.ts
@@ -0,0 +1,13 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * calendar_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type NoteDocumentsParams = {
+ /**
+ * Empty returns recent documents.
+ */
+ query?: string;
+};
diff --git a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/notePicker.ts b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/notePicker.ts
new file mode 100644
index 0000000000..a5b94c1750
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/notePicker.ts
@@ -0,0 +1,18 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * calendar_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { NoteDocument } from './noteDocument';
+import type { NoteTeam } from './noteTeam';
+
+/**
+ * Picker results; only documents whose owner is the caller are suggested.
+ */
+export interface NotePicker {
+ /** At most 30 matching markdown documents, most recently updated first. */
+ documents: NoteDocument[];
+ /** Teams the caller currently belongs to. */
+ teams: NoteTeam[];
+}
diff --git a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/noteTeam.ts b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/noteTeam.ts
new file mode 100644
index 0000000000..dc55becc9a
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/noteTeam.ts
@@ -0,0 +1,16 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * calendar_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * An additional team audience, separate from the meeting's audience.
+ */
+export interface NoteTeam {
+ /** Team identity. */
+ id: string;
+ /** Display name. */
+ name: string;
+}
diff --git a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/unlinkEventNoteParams.ts b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/unlinkEventNoteParams.ts
new file mode 100644
index 0000000000..96ee8fedaa
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/unlinkEventNoteParams.ts
@@ -0,0 +1,13 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * calendar_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type UnlinkEventNoteParams = {
+ /**
+ * Stable occurrence key returned by the calendar read API.
+ */
+ occurrenceKey: string;
+};
diff --git a/apps/web/src/lib/service-clients/service-calendar/notes.ts b/apps/web/src/lib/service-clients/service-calendar/notes.ts
new file mode 100644
index 0000000000..4458d56f84
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-calendar/notes.ts
@@ -0,0 +1,49 @@
+import { SERVER_HOSTS } from '@core/constant/servers';
+import { fetchWithToken } from '@core/util/fetchWithToken';
+import type {
+ DocumentNoteLink,
+ LinkNoteRequest,
+ MeetingNote,
+ NotePicker,
+} from './generated/schemas';
+
+const host = SERVER_HOSTS['calendar-service'];
+
+export const calendarNotesClient = {
+ documentLinks(documentId: string, signal?: AbortSignal) {
+ return fetchWithToken<DocumentNoteLink[]>(
+ `${host}/meeting-notes/documents/${encodeURIComponent(documentId)}/links`,
+ { signal }
+ );
+ },
+ list(eventId: string, occurrenceKey: string, signal?: AbortSignal) {
+ const query = new URLSearchParams({ occurrenceKey });
+ return fetchWithToken<MeetingNote[]>(
+ `${host}/events/${encodeURIComponent(eventId)}/notes?${query}`,
+ { signal }
+ );
+ },
+ documents(query: string, signal?: AbortSignal) {
+ return fetchWithToken<NotePicker>(
+ `${host}/meeting-notes/documents?${new URLSearchParams({ query })}`,
+ { signal }
+ );
+ },
+ link(
+ eventId: string,
+ occurrenceKey: string,
+ documentId: string,
+ body: LinkNoteRequest
+ ) {
+ return fetchWithToken<Record<string, never>>(
+ `${host}/events/${encodeURIComponent(eventId)}/notes/${encodeURIComponent(documentId)}?${new URLSearchParams({ occurrenceKey })}`,
+ { method: 'PUT', body: JSON.stringify(body) }
+ );
+ },
+ unlink(eventId: string, occurrenceKey: string, documentId: string) {
+ return fetchWithToken<Record<string, never>>(
+ `${host}/events/${encodeURIComponent(eventId)}/notes/${encodeURIComponent(documentId)}?${new URLSearchParams({ occurrenceKey })}`,
+ { method: 'DELETE' }
+ );
+ },
+};
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 2a7ce3e2e2..f6fe893dee 100644
--- a/apps/web/src/lib/service-clients/service-calendar/openapi.json
+++ b/apps/web/src/lib/service-clients/service-calendar/openapi.json
@@ -540,6 +540,136 @@
}
}
},
+ "/events/{event_id}/notes": {
+ "get": {
+ "tags": ["calendar_events"],
+ "summary": "List notes visible through this meeting occurrence.",
+ "operationId": "event_notes",
+ "parameters": [
+ {
+ "name": "event_id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ },
+ {
+ "name": "occurrenceKey",
+ "in": "query",
+ "description": "Stable occurrence key returned by the calendar read API.",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/MeetingNote"
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/events/{event_id}/notes/{document_id}": {
+ "put": {
+ "tags": ["calendar_events"],
+ "summary": "Idempotently link a markdown document and its optional team audience.",
+ "operationId": "link_event_note",
+ "parameters": [
+ {
+ "name": "event_id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ },
+ {
+ "name": "document_id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ },
+ {
+ "name": "occurrenceKey",
+ "in": "query",
+ "description": "Stable occurrence key returned by the calendar read API.",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/LinkNoteRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "204": {
+ "description": ""
+ }
+ }
+ },
+ "delete": {
+ "tags": ["calendar_events"],
+ "summary": "Remove this meeting's grant without deleting the document.",
+ "operationId": "unlink_event_note",
+ "parameters": [
+ {
+ "name": "event_id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ },
+ {
+ "name": "document_id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ },
+ {
+ "name": "occurrenceKey",
+ "in": "query",
+ "description": "Stable occurrence key returned by the calendar read API.",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "204": {
+ "description": ""
+ }
+ }
+ }
+ },
"/events/{event_id}/provider-url": {
"get": {
"tags": ["calendar_events"],
@@ -836,6 +966,68 @@
}
}
},
+ "/meeting-notes/documents": {
+ "get": {
+ "tags": ["calendar_events"],
+ "summary": "Suggest the caller's markdown documents and extra team audiences.",
+ "operationId": "note_documents",
+ "parameters": [
+ {
+ "name": "query",
+ "in": "query",
+ "description": "Empty returns recent documents.",
+ "required": false,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/NotePicker"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/meeting-notes/documents/{document_id}/links": {
+ "get": {
+ "tags": ["calendar_events"],
+ "summary": "List an owned document's meeting grants, including unavailable meetings.",
+ "operationId": "document_note_links",
+ "parameters": [
+ {
+ "name": "document_id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/DocumentNoteLink"
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/replacements/{operation_id}": {
"get": {
"tags": ["calendar_events"],
@@ -1737,6 +1929,41 @@
}
}
},
+ "DocumentNoteLink": {
+ "type": "object",
+ "description": "An owner's durable sharing link, including meetings they can no longer open.",
+ "required": ["documentName", "eventId", "occurrenceKey", "eventTitle"],
+ "properties": {
+ "documentName": {
+ "type": "string",
+ "description": "Current name of the owned markdown document."
+ },
+ "eventId": {
+ "type": "string",
+ "format": "uuid",
+ "description": "Linked calendar copy."
+ },
+ "eventTitle": {
+ "type": "string",
+ "description": "Current title, or a safe placeholder when meeting details are unavailable."
+ },
+ "occurrenceKey": {
+ "type": "string",
+ "description": "Original occurrence start, or `single` for a one-time meeting."
+ },
+ "team": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/NoteTeam",
+ "description": "Independent optional team audience."
+ }
+ ]
+ }
+ }
+ },
"EventReminderOverride": {
"type": "object",
"description": "One 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.",
@@ -1903,6 +2130,17 @@
}
}
},
+ "LinkNoteRequest": {
+ "type": "object",
+ "description": "Optional additional view access for one team.",
+ "properties": {
+ "teamId": {
+ "type": ["string", "null"],
+ "format": "uuid",
+ "description": "Null means the meeting audience only."
+ }
+ }
+ },
"ListCalendarsResponse": {
"type": "object",
"description": "Calendars visible to the requester across connected and delegated inboxes.",
@@ -1917,6 +2155,88 @@
}
}
},
+ "MeetingNote": {
+ "type": "object",
+ "description": "One linked document and the extra access this link grants.",
+ "required": ["documentId", "name", "canManage"],
+ "properties": {
+ "canManage": {
+ "type": "boolean",
+ "description": "Whether this viewer can change this document's sharing."
+ },
+ "documentId": {
+ "type": "string",
+ "description": "Markdown document identity."
+ },
+ "name": {
+ "type": "string",
+ "description": "Current document name."
+ },
+ "team": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/NoteTeam",
+ "description": "Optional extra team view grant."
+ }
+ ]
+ }
+ }
+ },
+ "NoteDocument": {
+ "type": "object",
+ "description": "A document available in the note picker.",
+ "required": ["documentId", "name"],
+ "properties": {
+ "documentId": {
+ "type": "string",
+ "description": "Markdown document identity."
+ },
+ "name": {
+ "type": "string",
+ "description": "Current document name, never a copied title."
+ }
+ }
+ },
+ "NotePicker": {
+ "type": "object",
+ "description": "Picker results; only documents whose owner is the caller are suggested.",
+ "required": ["documents", "teams"],
+ "properties": {
+ "documents": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/NoteDocument"
+ },
+ "description": "At most 30 matching markdown documents, most recently updated first."
+ },
+ "teams": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/NoteTeam"
+ },
+ "description": "Teams the caller currently belongs to."
+ }
+ }
+ },
+ "NoteTeam": {
+ "type": "object",
+ "description": "An additional team audience, separate from the meeting's audience.",
+ "required": ["id", "name"],
+ "properties": {
+ "id": {
+ "type": "string",
+ "format": "uuid",
+ "description": "Team identity."
+ },
+ "name": {
+ "type": "string",
+ "description": "Display name."
+ }
+ }
+ },
"OutOfOfficeAutoDeclineMode": {
"type": "string",
"description": "How an out-of-office event responds to conflicting invitations, mirroring\nGoogle's `autoDeclineMode`.",
diff --git a/apps/web/src/vite-env.d.ts b/apps/web/src/vite-env.d.ts
index acd963d693..2ffd1cdfe8 100644
--- a/apps/web/src/vite-env.d.ts
+++ b/apps/web/src/vite-env.d.ts
@@ -14,6 +14,7 @@ interface ImportMetaEnv {
/** `true` logs each `perfMark` as a `[perf]` console line. */
readonly VITE_PERF_LOG?: string;
readonly VITE_ENABLE_REMINDERS?: string;
+ readonly VITE_ENABLE_CALENDAR_MEETING_NOTES?: string;
readonly VITE_DISABLE_BROWSER_TURSO_CACHE?: string;
}
diff --git a/crates/agent_code_mode/src/domain/documentation.json b/crates/agent_code_mode/src/domain/documentation.json
index e990359d26..b4f14227ce 100644
--- a/crates/agent_code_mode/src/domain/documentation.json
+++ b/crates/agent_code_mode/src/domain/documentation.json
@@ -68,8 +68,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### availabilityCalendars()\n\n> **availabilityCalendars**(): `Promise`\\<\\{ `calendar`: [`Calendar`](../../calendar/classes/Calendar.md); `contributesToAvailability`: `boolean`; `isPrimary`: `boolean`; `name`: `string`; \\}[]\\>\n\nCalendar availability settings, each referring to a typed calendar.\n\n#### Returns\n\n`Promise`\\<\\{ `calendar`: [`Calendar`](../../calendar/classes/Calendar.md); `contributesToAvailability`: `boolean`; `isPrimary`: `boolean`; `name`: `string`; \\}[]\\>\n\n***\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\n### occurrences()\n\n> **occurrences**(`options`): `AsyncGenerator`\\<\\{ `event`: [`CalendarEvent`](../../event/classes/CalendarEvent.md); `occurrence`: [`CalendarOccurrence`](../../../../../generated/storage/types.gen/type-aliases/CalendarOccurrence.md); \\}, `any`, `any`\\>\n\nCalendar occurrences in a viewport, automatically paginated.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `options` | `Omit`\\<[`ListOccurrencesData`](../../../../../generated/storage/types.gen/type-aliases/ListOccurrencesData.md)\\[`\"query\"`\\], `\"cursor\"`\\> |\n\n#### Returns\n\n`AsyncGenerator`\\<\\{ `event`: [`CalendarEvent`](../../event/classes/CalendarEvent.md); `occurrence`: [`CalendarOccurrence`](../../../../../generated/storage/types.gen/type-aliases/CalendarOccurrence.md); \\}, `any`, `any`\\>\n\n***\n\n### replacement()\n\n> **replacement**(`operationId`): [`CalendarReplacement`](../../replacement/classes/CalendarReplacement.md)\n\nRecover a saved replacement, including after its original event was retired.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `operationId` | `string` |\n\n#### Returns\n\n[`CalendarReplacement`](../../replacement/classes/CalendarReplacement.md)\n\n***\n\n### setTeamSharing()\n\n> **setTeamSharing**(`sharing`): `Promise`\\<[`TeamCalendarSharing`](../../../../../generated/calendar/types.gen/type-aliases/TeamCalendarSharing.md)\\>\n\nReplace the team calendar sharing preference.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `sharing` | [`TeamCalendarSharing`](../../../../../generated/calendar/types.gen/type-aliases/TeamCalendarSharing.md) |\n\n#### Returns\n\n`Promise`\\<[`TeamCalendarSharing`](../../../../../generated/calendar/types.gen/type-aliases/TeamCalendarSharing.md)\\>\n\n***\n\n### teamOutOfOffice()\n\n> **teamOutOfOffice**(`options`): `Promise`\\<\\{ `hasMore`: `boolean`; `items`: \\{ `event`: [`CalendarEvent`](../../event/classes/CalendarEvent.md); `occurrenceKey`: `string`; `owner`: [`User`](../../../users/user/classes/User.md); `time`: [`EventTime`](../../../../../generated/storage/types.gen/type-aliases/EventTime.md); `title`: `string` \\| `undefined`; \\}[]; \\}\\>\n\nTeammates' out-of-office occurrences in a bounded viewport. Check hasMore for truncation.\n\n#### Parameters\n\n| Parameter | Type | Description |\n| ------ | ------ | ------ |\n| `options` | \\{ `end`: `string`; `endDate?`: `string`; `limit?`: `number`; `start`: `string`; `startDate?`: `string`; \\} | - |\n| `options.end` | `string` | Exclusive UTC viewport end. |\n| `options.endDate?` | `string` | Exclusive local date boundary for all-day events. |\n| `options.limit?` | `number` | Maximum number of occurrences, from 1 through 2,000. |\n| `options.start` | `string` | Inclusive UTC viewport start. |\n| `options.startDate?` | `string` | Inclusive local date boundary for all-day events. |\n\n#### Returns\n\n`Promise`\\<\\{ `hasMore`: `boolean`; `items`: \\{ `event`: [`CalendarEvent`](../../event/classes/CalendarEvent.md); `occurrenceKey`: `string`; `owner`: [`User`](../../../users/user/classes/User.md); `time`: [`EventTime`](../../../../../generated/storage/types.gen/type-aliases/EventTime.md); `title`: `string` \\| `undefined`; \\}[]; \\}\\>\n\n***\n\n### teamPage()\n\n> **teamPage**(`options`): `Promise`\\<\\{ `items`: (\\{ `contributesToAvailability`: `boolean`; `id`: `string`; `kind`: `\"busy\"`; `owner`: [`User`](../../../users/user/classes/User.md); `time`: [`EventTime`](../../../../../generated/storage/types.gen/type-aliases/EventTime.md); \\} \\| \\{ `contributesToAvailability`: `boolean`; `details`: [`TeamCalendarDetails`](../../../../../generated/storage/types.gen/type-aliases/TeamCalendarDetails.md); `id`: `string`; `kind`: `\"details\"`; `owner`: [`User`](../../../users/user/classes/User.md); `time`: [`EventTime`](../../../../../generated/storage/types.gen/type-aliases/EventTime.md); \\})[]; `members`: \\{ `coverage`: [`TeamCalendarCoverage`](../../../../../generated/storage/types.gen/type-aliases/TeamCalendarCoverage.md); `sharing`: [`TeamCalendarSharing`](../../../../../generated/storage/types.gen/type-aliases/TeamCalendarSharing.md); `user`: [`User`](../../../users/user/classes/User.md); \\}[]; `nextCursor`: `string` \\| `undefined`; \\}\\>\n\nA page of team availability, including its roster and continuation cursor.\n\n#### Parameters\n\n| Parameter | Type | Description |\n| ------ | ------ | ------ |\n| `options` | \\{ `cursor?`: `string` \\| `null`; `end`: `string`; `limit?`: `number` \\| `null`; `start`: `string`; \\} | - |\n| `options.cursor?` | `string` \\| `null` | Continuation returned by the preceding page. |\n| `options.end` | `string` | Exclusive instant. |\n| `options.limit?` | `number` \\| `null` | Maximum source occurrences, at most 2,000. Zero returns the roster only. |\n| `options.start` | `string` | Inclusive instant. |\n\n#### Returns\n\n`Promise`\\<\\{ `items`: (\\{ `contributesToAvailability`: `boolean`; `id`: `string`; `kind`: `\"busy\"`; `owner`: [`User`](../../../users/user/classes/User.md); `time`: [`EventTime`](../../../../../generated/storage/types.gen/type-aliases/EventTime.md); \\} \\| \\{ `contributesToAvailability`: `boolean`; `details`: [`TeamCalendarDetails`](../../../../../generated/storage/types.gen/type-aliases/TeamCalendarDetails.md); `id`: `string`; `kind`: `\"details\"`; `owner`: [`User`](../../../users/user/classes/User.md); `time`: [`EventTime`](../../../../../generated/storage/types.gen/type-aliases/EventTime.md); \\})[]; `members`: \\{ `coverage`: [`TeamCalendarCoverage`](../../../../../generated/storage/types.gen/type-aliases/TeamCalendarCoverage.md); `sharing`: [`TeamCalendarSharing`](../../../../../generated/storage/types.gen/type-aliases/TeamCalendarSharing.md); `user`: [`User`](../../../users/user/classes/User.md); \\}[]; `nextCursor`: `string` \\| `undefined`; \\}\\>\n\n***\n\n### teamSharing()\n\n> **teamSharing**(): `Promise`\\<[`TeamCalendarSharing`](../../../../../generated/calendar/types.gen/type-aliases/TeamCalendarSharing.md)\\>\n\nCurrent sharing preference for the team calendar.\n\n#### Returns\n\n`Promise`\\<[`TeamCalendarSharing`](../../../../../generated/calendar/types.gen/type-aliases/TeamCalendarSharing.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-guestpolicy\"></a> `guestPolicy?` | [`GuestPolicy`](../../../../../generated/calendar/types.gen/type-aliases/GuestPolicy.md) | What guests may do; omit for Google's defaults. Google calendars only. |\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 an 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/CalendarCapabilities.md -->\n# Type Alias: CalendarCapabilities\n\n> **CalendarCapabilities** = \\{ `autoDecline`: `boolean`; `conferenceProvider?`: `null` \\| [`ConferenceProvider`](ConferenceProvider.md); `customRecurrence`: `boolean`; `emailReminders`: `boolean`; `guestPolicy`: `boolean`; `removeConference`: `boolean`; `resetRsvp`: `boolean`; \\}\n\nActual provider capabilities used by calendar editors.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-autodecline\"></a> `autoDecline` | `boolean` | Whether event-level automatic invitation declines are supported. |\n| <a id=\"property-conferenceprovider\"></a> `conferenceProvider?` | `null` \\| [`ConferenceProvider`](ConferenceProvider.md) | - |\n| <a id=\"property-customrecurrence\"></a> `customRecurrence` | `boolean` | Whether arbitrary RFC 5545 recurrence properties can be written. |\n| <a id=\"property-emailreminders\"></a> `emailReminders` | `boolean` | Whether email reminders are delivered by the provider or Macro. |\n| <a id=\"property-guestpolicy\"></a> `guestPolicy` | `boolean` | Whether the organizer can set what guests may do. |\n| <a id=\"property-removeconference\"></a> `removeConference` | `boolean` | Whether an existing conference can be detached. |\n| <a id=\"property-resetrsvp\"></a> `resetRsvp` | `boolean` | Whether an attendee can reset their RSVP to unanswered. |\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); `guestPolicy`: [`GuestPolicy`](GuestPolicy.md); `icalUid`: `string`; `id`: `string`; `isReadOnly`: `boolean`; `isSnapshot`: `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`; `viewerCan`: [`ViewerCapabilities`](ViewerCapabilities.md); `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-guestpolicy\"></a> `guestPolicy` | [`GuestPolicy`](GuestPolicy.md) | What the organizer lets guests do: the canonical copy's values, or Google's defaults for an event synced before the policy was modeled. |\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-issnapshot\"></a> `isSnapshot` | `boolean` | Whether this is a snapshot of a meeting shared with the owner, which Macro added to their calendar as a private copy: the meeting's changes never reach it, and nothing done to it reaches the meeting. |\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-viewercan\"></a> `viewerCan` | [`ViewerCapabilities`](ViewerCapabilities.md) | What the viewing requester may do with the event. Resolved only on the read path, alongside each attendee's `is_self`; nothing when no viewer is known. Source projections never store it. |\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/CalendarGuestInputBody.md -->\n# Type Alias: CalendarGuestInputBody\n\n> **CalendarGuestInputBody** = \\{ `email`: `string`; `optional?`: `boolean`; \\}\n\nA guest added to an event.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-email\"></a> `email` | `string` | Guest email address. |\n| <a id=\"property-optional\"></a> `optional?` | `boolean` | Whether attendance is optional. |\n\n\n<!-- generated/calendar/types.gen/type-aliases/CalendarProvider.md -->\n# Type Alias: CalendarProvider\n\n> **CalendarProvider** = `\"google\"` \\| `\"outlook\"`\n\nProvider selected from the persisted calendar account and email binding.\n\n\n<!-- generated/calendar/types.gen/type-aliases/CalendarReplacementView.md -->\n# Type Alias: CalendarReplacementView\n\n> **CalendarReplacementView** = \\{ `attendeeCount`: `number`; `completedSteps`: `number`; `event?`: `null` \\| [`CalendarEvent`](CalendarEvent.md); `isSeries`: `boolean`; `operationId`: `string`; `providerUrl?`: `string` \\| `null`; `removeConference`: `boolean`; `replacementUrl?`: `string` \\| `null`; `status`: [`ReplacementStatus`](ReplacementStatus.md); `time`: [`EventTime`](EventTime.md); `title`: `string`; `totalSteps`: `number`; \\}\n\nSafe preview and recovery response; never exposes the opaque provider snapshot.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-attendeecount\"></a> `attendeeCount` | `number` | Guest count for cancellation and reinvitation confirmation. |\n| <a id=\"property-completedsteps\"></a> `completedSteps` | `number` | Number of completed provider steps. |\n| <a id=\"property-event\"></a> `event?` | `null` \\| [`CalendarEvent`](CalendarEvent.md) | - |\n| <a id=\"property-isseries\"></a> `isSeries` | `boolean` | Entire recurring series, including exceptions, is replaced. |\n| <a id=\"property-operationid\"></a> `operationId` | `string` | Use this identity when confirming or checking progress. |\n| <a id=\"property-providerurl\"></a> `providerUrl?` | `string` \\| `null` | Original event for manual review. |\n| <a id=\"property-removeconference\"></a> `removeConference` | `boolean` | The provider conference is removed. |\n| <a id=\"property-replacementurl\"></a> `replacementUrl?` | `string` \\| `null` | New provider event, when creation was confirmed. |\n| <a id=\"property-status\"></a> `status` | [`ReplacementStatus`](ReplacementStatus.md) | Current durable state. |\n| <a id=\"property-time\"></a> `time` | [`EventTime`](EventTime.md) | Frozen time. |\n| <a id=\"property-title\"></a> `title` | `string` | Frozen title. |\n| <a id=\"property-totalsteps\"></a> `totalSteps` | `number` | Number of provider steps in this operation. |\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** = `\"provider_default\"` \\| `\"microsoft_teams\"` \\| `\"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** = `\"microsoft_teams\"` \\| `\"google_meet\"` \\| `\"other\"`\n\nThe conferencing system backing an event's join URL.\n\nCalendars can create Google Meet or Microsoft Teams according to their\ncapabilities. Imported third-party conferences are labeled separately.\nOmitting a conference change preserves the current conference; explicit\nchanges still require provider and calendar capability validation.\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/GuestPolicy.md -->\n# Type Alias: GuestPolicy\n\n> **GuestPolicy** = \\{ `canInviteOthers`: `boolean`; `canModify`: `boolean`; `canSeeOtherGuests`: `boolean`; \\}\n\nThe switches an organizer sets on an event to bound what its guests may\ndo. Google omits a switch from the payload while it holds its default.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-caninviteothers\"></a> `canInviteOthers` | `boolean` | Whether guests may invite others. |\n| <a id=\"property-canmodify\"></a> `canModify` | `boolean` | Whether guests may change the event, including its guest list. |\n| <a id=\"property-canseeotherguests\"></a> `canSeeOtherGuests` | `boolean` | Whether guests may see the guest list. |\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/ReplacementStatus.md -->\n# Type Alias: ReplacementStatus\n\n> **ReplacementStatus** = `\"needs_confirmation\"` \\| `\"in_progress\"` \\| `\"complete\"`\n\nUser-visible workflow state.\n\n\n<!-- generated/calendar/types.gen/type-aliases/TeamCalendarSharing.md -->\n# Type Alias: TeamCalendarSharing\n\n> **TeamCalendarSharing** = `\"all\"` \\| `\"busy_only\"` \\| `\"none\"`\n\nWhat a user exposes through their team membership.\n\n\n<!-- generated/calendar/types.gen/type-aliases/ViewerCapabilities.md -->\n# Type Alias: ViewerCapabilities\n\n> **ViewerCapabilities** = \\{ `editDetails`: `boolean`; `inviteGuests`: `boolean`; `organize`: `boolean`; `removeGuests`: `boolean`; `rsvp`: `boolean`; `setGuestPolicy`: `boolean`; \\}\n\nWhat the viewing requester may do with an event.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-editdetails\"></a> `editDetails` | `boolean` | Change the event's details (title, time, description, conference). |\n| <a id=\"property-inviteguests\"></a> `inviteGuests` | `boolean` | Add guests. |\n| <a id=\"property-organize\"></a> `organize` | `boolean` | Act as the event's organizer: replace its whole guest list and manage its conferencing. |\n| <a id=\"property-removeguests\"></a> `removeGuests` | `boolean` | Remove guests. |\n| <a id=\"property-rsvp\"></a> `rsvp` | `boolean` | Answer the invitation. |\n| <a id=\"property-setguestpolicy\"></a> `setGuestPolicy` | `boolean` | Change the event's guest policy, which only Google calendars have. |\n\n\n<!-- generated/calendar/types.gen/type-aliases/VisibleCalendar.md -->\n# Type Alias: VisibleCalendar\n\n> **VisibleCalendar** = \\{ `capabilities`: [`CalendarCapabilities`](CalendarCapabilities.md); `color?`: `string` \\| `null`; `defaultReminders`: [`EventReminderOverride`](EventReminderOverride.md)[]; `emailAddress`: `string`; `emailLinkId`: `string`; `id`: `string`; `isPrimary`: `boolean`; `isSubscription`: `boolean`; `isWritable`: `boolean`; `name`: `string`; `provider`: [`CalendarProvider`](CalendarProvider.md); `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-capabilities\"></a> `capabilities` | [`CalendarCapabilities`](CalendarCapabilities.md) | Provider features available on this actual calendar. |\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-provider\"></a> `provider` | [`CalendarProvider`](CalendarProvider.md) | Calendar provider, for display and reconnect routing. |\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<!-- generated/storage/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/storage/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/storage/types.gen/type-aliases/CalendarOccurrence.md -->\n# Type Alias: CalendarOccurrence\n\n> **CalendarOccurrence** = \\{ `eventId`: `string`; `isCancelled`: `boolean`; `occurrenceKey`: `string`; `recurrenceId?`: `string` \\| `null`; `time`: [`EventTime`](EventTime.md); \\}\n\nA materialized recurrence instance optimized for range queries.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-eventid\"></a> `eventId` | `string` | Owning event entity. |\n| <a id=\"property-iscancelled\"></a> `isCancelled` | `boolean` | Whether the instance was cancelled. |\n| <a id=\"property-occurrencekey\"></a> `occurrenceKey` | `string` | Stable key within the event. |\n| <a id=\"property-recurrenceid\"></a> `recurrenceId?` | `string` \\| `null` | Provider recurrence identifier, when applicable. |\n| <a id=\"property-time\"></a> `time` | [`EventTime`](EventTime.md) | Instance time. |\n\n\n<!-- generated/storage/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/storage/types.gen/type-aliases/ListOccurrencesData.md -->\n# Type Alias: ListOccurrencesData\n\n> **ListOccurrencesData** = \\{ `body?`: `never`; `path?`: `never`; `query`: \\{ `cursor?`: `string`; `end`: `string`; `endDate?`: `string`; `limit?`: `number`; `start`: `string`; `startDate?`: `string`; \\}; `url`: `\"/calendar-events\"`; \\}\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-body\"></a> `body?` | `never` | - |\n| <a id=\"property-path\"></a> `path?` | `never` | - |\n| <a id=\"property-query\"></a> `query` | \\{ `cursor?`: `string`; `end`: `string`; `endDate?`: `string`; `limit?`: `number`; `start`: `string`; `startDate?`: `string`; \\} | - |\n| `query.cursor?` | `string` | Opaque continuation cursor returned by the previous page. |\n| `query.end` | `string` | Exclusive UTC viewport end. |\n| `query.endDate?` | `string` | Exclusive local date boundary for all-day events. |\n| `query.limit?` | `number` | Maximum number of occurrences, from 1 through 2,000. |\n| `query.start` | `string` | Inclusive UTC viewport start. |\n| `query.startDate?` | `string` | Inclusive local date boundary for all-day events. |\n| <a id=\"property-url\"></a> `url` | `\"/calendar-events\"` | - |\n\n\n<!-- generated/storage/types.gen/type-aliases/TeamCalendarCoverage.md -->\n# Type Alias: TeamCalendarCoverage\n\n> **TeamCalendarCoverage** = `\"ready\"` \\| `\"unavailable\"` \\| `\"hidden\"`\n\nWhether a member's calendar projection can establish availability.\n\n\n<!-- generated/storage/types.gen/type-aliases/TeamCalendarDetails.md -->\n# Type Alias: TeamCalendarDetails\n\n> **TeamCalendarDetails** = \\{ `attendees`: [`CalendarAttendee`](CalendarAttendee.md)[]; `calendarName`: `string`; `conferenceUrl?`: `string` \\| `null`; `description?`: `string` \\| `null`; `location?`: `string` \\| `null`; `organizerEmail?`: `string` \\| `null`; `organizerName?`: `string` \\| `null`; `title`: `string`; \\}\n\nSafe details from a single authorized source.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-attendees\"></a> `attendees` | [`CalendarAttendee`](CalendarAttendee.md)[] | Attendees; self flags are relative to the requesting viewer. |\n| <a id=\"property-calendarname\"></a> `calendarName` | `string` | Source calendar name, shown only with details. |\n| <a id=\"property-conferenceurl\"></a> `conferenceUrl?` | `string` \\| `null` | Join URL, if supplied by this source. |\n| <a id=\"property-description\"></a> `description?` | `string` \\| `null` | Body, if supplied by this source. |\n| <a id=\"property-location\"></a> `location?` | `string` \\| `null` | Location, if supplied by this source. |\n| <a id=\"property-organizeremail\"></a> `organizerEmail?` | `string` \\| `null` | Organizer address from this source. |\n| <a id=\"property-organizername\"></a> `organizerName?` | `string` \\| `null` | Organizer name from this source. |\n| <a id=\"property-title\"></a> `title` | `string` | Display title. |\n\n\n<!-- generated/storage/types.gen/type-aliases/TeamCalendarSharing.md -->\n# Type Alias: TeamCalendarSharing\n\n> **TeamCalendarSharing** = `\"all\"` \\| `\"busy_only\"` \\| `\"none\"`\n\nWhat a user exposes through their team membership.\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### setContributesToAvailability()\n\n> **setContributesToAvailability**(`contributesToAvailability`): `Promise`\\<`void`\\>\n\nSet whether this calendar contributes to the caller's availability.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `contributesToAvailability` | `boolean` |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\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-guestpolicy\"></a> `guestPolicy` | `readonly` | () => `Promise`\\<[`GuestPolicy`](../../../../../generated/calendar/types.gen/type-aliases/GuestPolicy.md)\\> | What the organizer lets guests do: modify, invite others, see the guest list. | - |\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| <a id=\"property-viewercan\"></a> `viewerCan` | `readonly` | () => `Promise`\\<[`ViewerCapabilities`](../../../../../generated/calendar/types.gen/type-aliases/ViewerCapabilities.md)\\> | What the connected account may do with this event under its guest policy. | - |\n\n## Methods\n\n### addToCalendar()\n\n> **addToCalendar**(`options?`): `Promise`\\<`CalendarEvent`\\>\n\nAdd a snapshot of an event shared with one of the requester's\nchannels to one of their Google calendars, and return a handle to the\nsynced snapshot. The snapshot keeps the meeting's iCalendar UID and\norganizer, lists only the requester as a guest, and carries no join link;\nnobody is notified, and answers or guests on it never reach the meeting.\nRefused with `already_on_calendar` when the meeting is already on one of\ntheir calendars, and with `copy_refused` when Google will not import it.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `options?` | \\{ `calendar?`: [`Calendar`](../../calendar/classes/Calendar.md); \\} |\n| `options.calendar?` | [`Calendar`](../../calendar/classes/Calendar.md) |\n\n#### Returns\n\n`Promise`\\<`CalendarEvent`\\>\n\n***\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### ics()\n\n> **ics**(): `Promise`\\<`string`\\>\n\nThe event as an iCalendar (`.ics`) document: its series, title,\ndescription, location and organizer, never its guests or join link.\nAvailable for the requester's own events and ones shared with a channel\nthey belong to.\n\n#### Returns\n\n`Promise`\\<`string`\\>\n\n***\n\n### inviteGuests()\n\n> **inviteGuests**(`options`): `Promise`\\<`CalendarEvent`\\>\n\nAdd guests without touching anyone already invited, and return a handle\nto the synced record. The organizer may, and so may a guest the organizer\nlets invite others (see [CalendarEvent.viewerCan](#property-viewercan)); Google emails\nthe new guests.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `options` | [`InviteGuestsOptions`](../interfaces/InviteGuestsOptions.md) |\n\n#### Returns\n\n`Promise`\\<`CalendarEvent`\\>\n\n***\n\n### prepareReplacement()\n\n> **prepareReplacement**(`options`): `Promise`\\<[`CalendarReplacement`](../../replacement/classes/CalendarReplacement.md)\\>\n\nPreview an organizer replacement without cancelling or sending invitations.\nReview replacement.status() before explicitly calling replacement.confirm().\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `options` | \\{ `calendar?`: [`Calendar`](../../calendar/classes/Calendar.md); `recurrenceId?`: `string`; `removeConference`: `boolean`; \\} |\n| `options.calendar?` | [`Calendar`](../../calendar/classes/Calendar.md) |\n| `options.recurrenceId?` | `string` |\n| `options.removeConference` | `boolean` |\n\n#### Returns\n\n`Promise`\\<[`CalendarReplacement`](../../replacement/classes/CalendarReplacement.md)\\>\n\n***\n\n### providerUrl()\n\n> **providerUrl**(`options?`): `Promise`\\<`string` \\| `undefined`\\>\n\nOpen this calendar copy in its provider for actions unavailable through its API.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `options?` | \\{ `calendar?`: [`Calendar`](../../calendar/classes/Calendar.md); `recurrenceId?`: `string`; \\} |\n| `options.calendar?` | [`Calendar`](../../calendar/classes/Calendar.md) |\n| `options.recurrenceId?` | `string` |\n\n#### Returns\n\n`Promise`\\<`string` \\| `undefined`\\>\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/InviteGuestsOptions.md -->\n# Interface: InviteGuestsOptions\n\nGuests to add and how much of a recurring series gains them.\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 written, for a multi-calendar event. Omit to write the canonical copy. |\n| <a id=\"property-guests\"></a> `guests` | [`CalendarGuestInputBody`](../../../../../generated/calendar/types.gen/type-aliases/CalendarGuestInputBody.md)[] | Guests to add; anyone already on the event is skipped. |\n| <a id=\"property-recurrenceid\"></a> `recurrenceId?` | `string` | Original-start key of the occurrence the guests are added to. |\n| <a id=\"property-scope\"></a> `scope?` | [`CalendarUpdateScopeParam`](../../../../../generated/calendar/types.gen/type-aliases/CalendarUpdateScopeParam.md) | How much of a recurring series gains the guests. Omit to let `recurrenceId` decide. |\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) | Provider conference change; omit to retain it. Outlook removal requires a separately confirmed replacement via prepareReplacement(). |\n| <a id=\"property-description\"></a> `description?` | `string` | Replacement description; an empty string clears it. |\n| <a id=\"property-guestpolicy\"></a> `guestPolicy?` | [`GuestPolicy`](../../../../../generated/calendar/types.gen/type-aliases/GuestPolicy.md) | Replacement guest policy; only the organizer of a Google event may change it (`viewerCan.setGuestPolicy`). It applies to the whole series, so an update scoped to one occurrence (`scope: 'this_event'`, or a `recurrenceId`) that changes it is rejected; use scope `'all'`. |\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### availabilityCalendars()\n\n> **availabilityCalendars**(): `Promise`\\<\\{ `calendar`: [`Calendar`](../../calendar/classes/Calendar.md); `contributesToAvailability`: `boolean`; `isPrimary`: `boolean`; `name`: `string`; \\}[]\\>\n\nCalendar availability settings, each referring to a typed calendar.\n\n#### Returns\n\n`Promise`\\<\\{ `calendar`: [`Calendar`](../../calendar/classes/Calendar.md); `contributesToAvailability`: `boolean`; `isPrimary`: `boolean`; `name`: `string`; \\}[]\\>\n\n***\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\n### occurrences()\n\n> **occurrences**(`options`): `AsyncGenerator`\\<\\{ `event`: [`CalendarEvent`](../../event/classes/CalendarEvent.md); `occurrence`: [`CalendarOccurrence`](../../../../../generated/storage/types.gen/type-aliases/CalendarOccurrence.md); \\}, `any`, `any`\\>\n\nCalendar occurrences in a viewport, automatically paginated.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `options` | `Omit`\\<[`ListOccurrencesData`](../../../../../generated/storage/types.gen/type-aliases/ListOccurrencesData.md)\\[`\"query\"`\\], `\"cursor\"`\\> |\n\n#### Returns\n\n`AsyncGenerator`\\<\\{ `event`: [`CalendarEvent`](../../event/classes/CalendarEvent.md); `occurrence`: [`CalendarOccurrence`](../../../../../generated/storage/types.gen/type-aliases/CalendarOccurrence.md); \\}, `any`, `any`\\>\n\n***\n\n### replacement()\n\n> **replacement**(`operationId`): [`CalendarReplacement`](../../replacement/classes/CalendarReplacement.md)\n\nRecover a saved replacement, including after its original event was retired.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `operationId` | `string` |\n\n#### Returns\n\n[`CalendarReplacement`](../../replacement/classes/CalendarReplacement.md)\n\n***\n\n### setTeamSharing()\n\n> **setTeamSharing**(`sharing`): `Promise`\\<[`TeamCalendarSharing`](../../../../../generated/calendar/types.gen/type-aliases/TeamCalendarSharing.md)\\>\n\nReplace the team calendar sharing preference.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `sharing` | [`TeamCalendarSharing`](../../../../../generated/calendar/types.gen/type-aliases/TeamCalendarSharing.md) |\n\n#### Returns\n\n`Promise`\\<[`TeamCalendarSharing`](../../../../../generated/calendar/types.gen/type-aliases/TeamCalendarSharing.md)\\>\n\n***\n\n### teamOutOfOffice()\n\n> **teamOutOfOffice**(`options`): `Promise`\\<\\{ `hasMore`: `boolean`; `items`: \\{ `event`: [`CalendarEvent`](../../event/classes/CalendarEvent.md); `occurrenceKey`: `string`; `owner`: [`User`](../../../users/user/classes/User.md); `time`: [`EventTime`](../../../../../generated/storage/types.gen/type-aliases/EventTime.md); `title`: `string` \\| `undefined`; \\}[]; \\}\\>\n\nTeammates' out-of-office occurrences in a bounded viewport. Check hasMore for truncation.\n\n#### Parameters\n\n| Parameter | Type | Description |\n| ------ | ------ | ------ |\n| `options` | \\{ `end`: `string`; `endDate?`: `string`; `limit?`: `number`; `start`: `string`; `startDate?`: `string`; \\} | - |\n| `options.end` | `string` | Exclusive UTC viewport end. |\n| `options.endDate?` | `string` | Exclusive local date boundary for all-day events. |\n| `options.limit?` | `number` | Maximum number of occurrences, from 1 through 2,000. |\n| `options.start` | `string` | Inclusive UTC viewport start. |\n| `options.startDate?` | `string` | Inclusive local date boundary for all-day events. |\n\n#### Returns\n\n`Promise`\\<\\{ `hasMore`: `boolean`; `items`: \\{ `event`: [`CalendarEvent`](../../event/classes/CalendarEvent.md); `occurrenceKey`: `string`; `owner`: [`User`](../../../users/user/classes/User.md); `time`: [`EventTime`](../../../../../generated/storage/types.gen/type-aliases/EventTime.md); `title`: `string` \\| `undefined`; \\}[]; \\}\\>\n\n***\n\n### teamPage()\n\n> **teamPage**(`options`): `Promise`\\<\\{ `items`: (\\{ `contributesToAvailability`: `boolean`; `id`: `string`; `kind`: `\"busy\"`; `owner`: [`User`](../../../users/user/classes/User.md); `time`: [`EventTime`](../../../../../generated/storage/types.gen/type-aliases/EventTime.md); \\} \\| \\{ `contributesToAvailability`: `boolean`; `details`: [`TeamCalendarDetails`](../../../../../generated/storage/types.gen/type-aliases/TeamCalendarDetails.md); `id`: `string`; `kind`: `\"details\"`; `owner`: [`User`](../../../users/user/classes/User.md); `time`: [`EventTime`](../../../../../generated/storage/types.gen/type-aliases/EventTime.md); \\})[]; `members`: \\{ `coverage`: [`TeamCalendarCoverage`](../../../../../generated/storage/types.gen/type-aliases/TeamCalendarCoverage.md); `sharing`: [`TeamCalendarSharing`](../../../../../generated/storage/types.gen/type-aliases/TeamCalendarSharing.md); `user`: [`User`](../../../users/user/classes/User.md); \\}[]; `nextCursor`: `string` \\| `undefined`; \\}\\>\n\nA page of team availability, including its roster and continuation cursor.\n\n#### Parameters\n\n| Parameter | Type | Description |\n| ------ | ------ | ------ |\n| `options` | \\{ `cursor?`: `string` \\| `null`; `end`: `string`; `limit?`: `number` \\| `null`; `start`: `string`; \\} | - |\n| `options.cursor?` | `string` \\| `null` | Continuation returned by the preceding page. |\n| `options.end` | `string` | Exclusive instant. |\n| `options.limit?` | `number` \\| `null` | Maximum source occurrences, at most 2,000. Zero returns the roster only. |\n| `options.start` | `string` | Inclusive instant. |\n\n#### Returns\n\n`Promise`\\<\\{ `items`: (\\{ `contributesToAvailability`: `boolean`; `id`: `string`; `kind`: `\"busy\"`; `owner`: [`User`](../../../users/user/classes/User.md); `time`: [`EventTime`](../../../../../generated/storage/types.gen/type-aliases/EventTime.md); \\} \\| \\{ `contributesToAvailability`: `boolean`; `details`: [`TeamCalendarDetails`](../../../../../generated/storage/types.gen/type-aliases/TeamCalendarDetails.md); `id`: `string`; `kind`: `\"details\"`; `owner`: [`User`](../../../users/user/classes/User.md); `time`: [`EventTime`](../../../../../generated/storage/types.gen/type-aliases/EventTime.md); \\})[]; `members`: \\{ `coverage`: [`TeamCalendarCoverage`](../../../../../generated/storage/types.gen/type-aliases/TeamCalendarCoverage.md); `sharing`: [`TeamCalendarSharing`](../../../../../generated/storage/types.gen/type-aliases/TeamCalendarSharing.md); `user`: [`User`](../../../users/user/classes/User.md); \\}[]; `nextCursor`: `string` \\| `undefined`; \\}\\>\n\n***\n\n### teamSharing()\n\n> **teamSharing**(): `Promise`\\<[`TeamCalendarSharing`](../../../../../generated/calendar/types.gen/type-aliases/TeamCalendarSharing.md)\\>\n\nCurrent sharing preference for the team calendar.\n\n#### Returns\n\n`Promise`\\<[`TeamCalendarSharing`](../../../../../generated/calendar/types.gen/type-aliases/TeamCalendarSharing.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-guestpolicy\"></a> `guestPolicy?` | [`GuestPolicy`](../../../../../generated/calendar/types.gen/type-aliases/GuestPolicy.md) | What guests may do; omit for Google's defaults. Google calendars only. |\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 an 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\n\n<!-- src/entities/calendar/replacement/classes/CalendarReplacement.md -->\n# Class: CalendarReplacement\n\nDurable organizer replacement, recoverable even after the original event is retired.\n\n## Constructors\n\n### Constructor\n\n> **new CalendarReplacement**(`client`, `id`): `CalendarReplacement`\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `id` | `string` |\n\n#### Returns\n\n`CalendarReplacement`\n\n## Properties\n\n| Property | Modifier | Type |\n| ------ | ------ | ------ |\n| <a id=\"property-id\"></a> `id` | `readonly` | `string` |\n\n## Methods\n\n### confirm()\n\n> **confirm**(): `Promise`\\<[`CalendarReplacementView`](../../../../../generated/calendar/types.gen/type-aliases/CalendarReplacementView.md)\\>\n\nConfirm the reviewed cancellation and reinvitation, or resume that same operation.\nPresent the preview and obtain the organizer's confirmation before the first call.\n\n#### Returns\n\n`Promise`\\<[`CalendarReplacementView`](../../../../../generated/calendar/types.gen/type-aliases/CalendarReplacementView.md)\\>\n\n***\n\n### discard()\n\n> **discard**(): `Promise`\\<`void`\\>\n\nDiscard an unconfirmed preview. Confirmed operations must be recovered, not discarded.\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### status()\n\n> **status**(): `Promise`\\<[`CalendarReplacementView`](../../../../../generated/calendar/types.gen/type-aliases/CalendarReplacementView.md)\\>\n\nRead progress without initiating provider writes.\n\n#### Returns\n\n`Promise`\\<[`CalendarReplacementView`](../../../../../generated/calendar/types.gen/type-aliases/CalendarReplacementView.md)\\>\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### availabilityCalendars()\n\n> **availabilityCalendars**(): `Promise`\\<\\{ `calendar`: [`Calendar`](../../calendar/classes/Calendar.md); `contributesToAvailability`: `boolean`; `isPrimary`: `boolean`; `name`: `string`; \\}[]\\>\n\nCalendar availability settings, each referring to a typed calendar.\n\n#### Returns\n\n`Promise`\\<\\{ `calendar`: [`Calendar`](../../calendar/classes/Calendar.md); `contributesToAvailability`: `boolean`; `isPrimary`: `boolean`; `name`: `string`; \\}[]\\>\n\n***\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\n### noteDocuments()\n\n> **noteDocuments**(`query?`): `Promise`\\<\\{ `documents`: \\{ `document`: [`Document`](../../../documents/document/classes/Document.md); `name`: `string`; \\}[]; `teams`: \\{ `name`: `string`; `team`: [`Team`](../../../teams/team/classes/Team.md); \\}[]; \\}\\>\n\nFind up to 30 owned markdown documents for meeting notes, plus available extra team audiences.\n\n#### Parameters\n\n| Parameter | Type | Default value |\n| ------ | ------ | ------ |\n| `query?` | `string` | `''` |\n\n#### Returns\n\n`Promise`\\<\\{ `documents`: \\{ `document`: [`Document`](../../../documents/document/classes/Document.md); `name`: `string`; \\}[]; `teams`: \\{ `name`: `string`; `team`: [`Team`](../../../teams/team/classes/Team.md); \\}[]; \\}\\>\n\n***\n\n### occurrences()\n\n> **occurrences**(`options`): `AsyncGenerator`\\<\\{ `event`: [`CalendarEvent`](../../event/classes/CalendarEvent.md); `occurrence`: [`CalendarOccurrence`](../../../../../generated/storage/types.gen/type-aliases/CalendarOccurrence.md); \\}, `any`, `any`\\>\n\nCalendar occurrences in a viewport, automatically paginated.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `options` | `Omit`\\<[`ListOccurrencesData`](../../../../../generated/storage/types.gen/type-aliases/ListOccurrencesData.md)\\[`\"query\"`\\], `\"cursor\"`\\> |\n\n#### Returns\n\n`AsyncGenerator`\\<\\{ `event`: [`CalendarEvent`](../../event/classes/CalendarEvent.md); `occurrence`: [`CalendarOccurrence`](../../../../../generated/storage/types.gen/type-aliases/CalendarOccurrence.md); \\}, `any`, `any`\\>\n\n***\n\n### replacement()\n\n> **replacement**(`operationId`): [`CalendarReplacement`](../../replacement/classes/CalendarReplacement.md)\n\nRecover a saved replacement, including after its original event was retired.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `operationId` | `string` |\n\n#### Returns\n\n[`CalendarReplacement`](../../replacement/classes/CalendarReplacement.md)\n\n***\n\n### setTeamSharing()\n\n> **setTeamSharing**(`sharing`): `Promise`\\<[`TeamCalendarSharing`](../../../../../generated/calendar/types.gen/type-aliases/TeamCalendarSharing.md)\\>\n\nReplace the team calendar sharing preference.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `sharing` | [`TeamCalendarSharing`](../../../../../generated/calendar/types.gen/type-aliases/TeamCalendarSharing.md) |\n\n#### Returns\n\n`Promise`\\<[`TeamCalendarSharing`](../../../../../generated/calendar/types.gen/type-aliases/TeamCalendarSharing.md)\\>\n\n***\n\n### teamOutOfOffice()\n\n> **teamOutOfOffice**(`options`): `Promise`\\<\\{ `hasMore`: `boolean`; `items`: \\{ `event`: [`CalendarEvent`](../../event/classes/CalendarEvent.md); `occurrenceKey`: `string`; `owner`: [`User`](../../../users/user/classes/User.md); `time`: [`EventTime`](../../../../../generated/storage/types.gen/type-aliases/EventTime.md); `title`: `string` \\| `undefined`; \\}[]; \\}\\>\n\nTeammates' out-of-office occurrences in a bounded viewport. Check hasMore for truncation.\n\n#### Parameters\n\n| Parameter | Type | Description |\n| ------ | ------ | ------ |\n| `options` | \\{ `end`: `string`; `endDate?`: `string`; `limit?`: `number`; `start`: `string`; `startDate?`: `string`; \\} | - |\n| `options.end` | `string` | Exclusive UTC viewport end. |\n| `options.endDate?` | `string` | Exclusive local date boundary for all-day events. |\n| `options.limit?` | `number` | Maximum number of occurrences, from 1 through 2,000. |\n| `options.start` | `string` | Inclusive UTC viewport start. |\n| `options.startDate?` | `string` | Inclusive local date boundary for all-day events. |\n\n#### Returns\n\n`Promise`\\<\\{ `hasMore`: `boolean`; `items`: \\{ `event`: [`CalendarEvent`](../../event/classes/CalendarEvent.md); `occurrenceKey`: `string`; `owner`: [`User`](../../../users/user/classes/User.md); `time`: [`EventTime`](../../../../../generated/storage/types.gen/type-aliases/EventTime.md); `title`: `string` \\| `undefined`; \\}[]; \\}\\>\n\n***\n\n### teamPage()\n\n> **teamPage**(`options`): `Promise`\\<\\{ `items`: (\\{ `contributesToAvailability`: `boolean`; `id`: `string`; `kind`: `\"busy\"`; `owner`: [`User`](../../../users/user/classes/User.md); `time`: [`EventTime`](../../../../../generated/storage/types.gen/type-aliases/EventTime.md); \\} \\| \\{ `contributesToAvailability`: `boolean`; `details`: [`TeamCalendarDetails`](../../../../../generated/storage/types.gen/type-aliases/TeamCalendarDetails.md); `id`: `string`; `kind`: `\"details\"`; `owner`: [`User`](../../../users/user/classes/User.md); `time`: [`EventTime`](../../../../../generated/storage/types.gen/type-aliases/EventTime.md); \\})[]; `members`: \\{ `coverage`: [`TeamCalendarCoverage`](../../../../../generated/storage/types.gen/type-aliases/TeamCalendarCoverage.md); `sharing`: [`TeamCalendarSharing`](../../../../../generated/storage/types.gen/type-aliases/TeamCalendarSharing.md); `user`: [`User`](../../../users/user/classes/User.md); \\}[]; `nextCursor`: `string` \\| `undefined`; \\}\\>\n\nA page of team availability, including its roster and continuation cursor.\n\n#### Parameters\n\n| Parameter | Type | Description |\n| ------ | ------ | ------ |\n| `options` | \\{ `cursor?`: `string` \\| `null`; `end`: `string`; `limit?`: `number` \\| `null`; `start`: `string`; \\} | - |\n| `options.cursor?` | `string` \\| `null` | Continuation returned by the preceding page. |\n| `options.end` | `string` | Exclusive instant. |\n| `options.limit?` | `number` \\| `null` | Maximum source occurrences, at most 2,000. Zero returns the roster only. |\n| `options.start` | `string` | Inclusive instant. |\n\n#### Returns\n\n`Promise`\\<\\{ `items`: (\\{ `contributesToAvailability`: `boolean`; `id`: `string`; `kind`: `\"busy\"`; `owner`: [`User`](../../../users/user/classes/User.md); `time`: [`EventTime`](../../../../../generated/storage/types.gen/type-aliases/EventTime.md); \\} \\| \\{ `contributesToAvailability`: `boolean`; `details`: [`TeamCalendarDetails`](../../../../../generated/storage/types.gen/type-aliases/TeamCalendarDetails.md); `id`: `string`; `kind`: `\"details\"`; `owner`: [`User`](../../../users/user/classes/User.md); `time`: [`EventTime`](../../../../../generated/storage/types.gen/type-aliases/EventTime.md); \\})[]; `members`: \\{ `coverage`: [`TeamCalendarCoverage`](../../../../../generated/storage/types.gen/type-aliases/TeamCalendarCoverage.md); `sharing`: [`TeamCalendarSharing`](../../../../../generated/storage/types.gen/type-aliases/TeamCalendarSharing.md); `user`: [`User`](../../../users/user/classes/User.md); \\}[]; `nextCursor`: `string` \\| `undefined`; \\}\\>\n\n***\n\n### teamSharing()\n\n> **teamSharing**(): `Promise`\\<[`TeamCalendarSharing`](../../../../../generated/calendar/types.gen/type-aliases/TeamCalendarSharing.md)\\>\n\nCurrent sharing preference for the team calendar.\n\n#### Returns\n\n`Promise`\\<[`TeamCalendarSharing`](../../../../../generated/calendar/types.gen/type-aliases/TeamCalendarSharing.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-guestpolicy\"></a> `guestPolicy?` | [`GuestPolicy`](../../../../../generated/calendar/types.gen/type-aliases/GuestPolicy.md) | What guests may do; omit for Google's defaults. Google calendars only. |\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 an 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/CalendarCapabilities.md -->\n# Type Alias: CalendarCapabilities\n\n> **CalendarCapabilities** = \\{ `autoDecline`: `boolean`; `conferenceProvider?`: `null` \\| [`ConferenceProvider`](ConferenceProvider.md); `customRecurrence`: `boolean`; `emailReminders`: `boolean`; `guestPolicy`: `boolean`; `removeConference`: `boolean`; `resetRsvp`: `boolean`; \\}\n\nActual provider capabilities used by calendar editors.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-autodecline\"></a> `autoDecline` | `boolean` | Whether event-level automatic invitation declines are supported. |\n| <a id=\"property-conferenceprovider\"></a> `conferenceProvider?` | `null` \\| [`ConferenceProvider`](ConferenceProvider.md) | - |\n| <a id=\"property-customrecurrence\"></a> `customRecurrence` | `boolean` | Whether arbitrary RFC 5545 recurrence properties can be written. |\n| <a id=\"property-emailreminders\"></a> `emailReminders` | `boolean` | Whether email reminders are delivered by the provider or Macro. |\n| <a id=\"property-guestpolicy\"></a> `guestPolicy` | `boolean` | Whether the organizer can set what guests may do. |\n| <a id=\"property-removeconference\"></a> `removeConference` | `boolean` | Whether an existing conference can be detached. |\n| <a id=\"property-resetrsvp\"></a> `resetRsvp` | `boolean` | Whether an attendee can reset their RSVP to unanswered. |\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); `guestPolicy`: [`GuestPolicy`](GuestPolicy.md); `icalUid`: `string`; `id`: `string`; `isReadOnly`: `boolean`; `isSnapshot`: `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`; `viewerCan`: [`ViewerCapabilities`](ViewerCapabilities.md); `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-guestpolicy\"></a> `guestPolicy` | [`GuestPolicy`](GuestPolicy.md) | What the organizer lets guests do: the canonical copy's values, or Google's defaults for an event synced before the policy was modeled. |\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-issnapshot\"></a> `isSnapshot` | `boolean` | Whether this is a snapshot of a meeting shared with the owner, which Macro added to their calendar as a private copy: the meeting's changes never reach it, and nothing done to it reaches the meeting. |\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-viewercan\"></a> `viewerCan` | [`ViewerCapabilities`](ViewerCapabilities.md) | What the viewing requester may do with the event. Resolved only on the read path, alongside each attendee's `is_self`; nothing when no viewer is known. Source projections never store it. |\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/CalendarGuestInputBody.md -->\n# Type Alias: CalendarGuestInputBody\n\n> **CalendarGuestInputBody** = \\{ `email`: `string`; `optional?`: `boolean`; \\}\n\nA guest added to an event.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-email\"></a> `email` | `string` | Guest email address. |\n| <a id=\"property-optional\"></a> `optional?` | `boolean` | Whether attendance is optional. |\n\n\n<!-- generated/calendar/types.gen/type-aliases/CalendarProvider.md -->\n# Type Alias: CalendarProvider\n\n> **CalendarProvider** = `\"google\"` \\| `\"outlook\"`\n\nProvider selected from the persisted calendar account and email binding.\n\n\n<!-- generated/calendar/types.gen/type-aliases/CalendarReplacementView.md -->\n# Type Alias: CalendarReplacementView\n\n> **CalendarReplacementView** = \\{ `attendeeCount`: `number`; `completedSteps`: `number`; `event?`: `null` \\| [`CalendarEvent`](CalendarEvent.md); `isSeries`: `boolean`; `operationId`: `string`; `providerUrl?`: `string` \\| `null`; `removeConference`: `boolean`; `replacementUrl?`: `string` \\| `null`; `status`: [`ReplacementStatus`](ReplacementStatus.md); `time`: [`EventTime`](EventTime.md); `title`: `string`; `totalSteps`: `number`; \\}\n\nSafe preview and recovery response; never exposes the opaque provider snapshot.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-attendeecount\"></a> `attendeeCount` | `number` | Guest count for cancellation and reinvitation confirmation. |\n| <a id=\"property-completedsteps\"></a> `completedSteps` | `number` | Number of completed provider steps. |\n| <a id=\"property-event\"></a> `event?` | `null` \\| [`CalendarEvent`](CalendarEvent.md) | - |\n| <a id=\"property-isseries\"></a> `isSeries` | `boolean` | Entire recurring series, including exceptions, is replaced. |\n| <a id=\"property-operationid\"></a> `operationId` | `string` | Use this identity when confirming or checking progress. |\n| <a id=\"property-providerurl\"></a> `providerUrl?` | `string` \\| `null` | Original event for manual review. |\n| <a id=\"property-removeconference\"></a> `removeConference` | `boolean` | The provider conference is removed. |\n| <a id=\"property-replacementurl\"></a> `replacementUrl?` | `string` \\| `null` | New provider event, when creation was confirmed. |\n| <a id=\"property-status\"></a> `status` | [`ReplacementStatus`](ReplacementStatus.md) | Current durable state. |\n| <a id=\"property-time\"></a> `time` | [`EventTime`](EventTime.md) | Frozen time. |\n| <a id=\"property-title\"></a> `title` | `string` | Frozen title. |\n| <a id=\"property-totalsteps\"></a> `totalSteps` | `number` | Number of provider steps in this operation. |\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** = `\"provider_default\"` \\| `\"microsoft_teams\"` \\| `\"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** = `\"microsoft_teams\"` \\| `\"google_meet\"` \\| `\"other\"`\n\nThe conferencing system backing an event's join URL.\n\nCalendars can create Google Meet or Microsoft Teams according to their\ncapabilities. Imported third-party conferences are labeled separately.\nOmitting a conference change preserves the current conference; explicit\nchanges still require provider and calendar capability validation.\n\n\n<!-- generated/calendar/types.gen/type-aliases/DocumentNoteLink.md -->\n# Type Alias: DocumentNoteLink\n\n> **DocumentNoteLink** = \\{ `documentName`: `string`; `eventId`: `string`; `eventTitle`: `string`; `occurrenceKey`: `string`; `team?`: `null` \\| [`NoteTeam`](NoteTeam.md); \\}\n\nAn owner's durable sharing link, including meetings they can no longer open.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-documentname\"></a> `documentName` | `string` | Current name of the owned markdown document. |\n| <a id=\"property-eventid\"></a> `eventId` | `string` | Linked calendar copy. |\n| <a id=\"property-eventtitle\"></a> `eventTitle` | `string` | Current title, or a safe placeholder when meeting details are unavailable. |\n| <a id=\"property-occurrencekey\"></a> `occurrenceKey` | `string` | Original occurrence start, or `single` for a one-time meeting. |\n| <a id=\"property-team\"></a> `team?` | `null` \\| [`NoteTeam`](NoteTeam.md) | - |\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/GuestPolicy.md -->\n# Type Alias: GuestPolicy\n\n> **GuestPolicy** = \\{ `canInviteOthers`: `boolean`; `canModify`: `boolean`; `canSeeOtherGuests`: `boolean`; \\}\n\nThe switches an organizer sets on an event to bound what its guests may\ndo. Google omits a switch from the payload while it holds its default.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-caninviteothers\"></a> `canInviteOthers` | `boolean` | Whether guests may invite others. |\n| <a id=\"property-canmodify\"></a> `canModify` | `boolean` | Whether guests may change the event, including its guest list. |\n| <a id=\"property-canseeotherguests\"></a> `canSeeOtherGuests` | `boolean` | Whether guests may see the guest list. |\n\n\n<!-- generated/calendar/types.gen/type-aliases/MeetingNote.md -->\n# Type Alias: MeetingNote\n\n> **MeetingNote** = \\{ `canManage`: `boolean`; `documentId`: `string`; `name`: `string`; `team?`: `null` \\| [`NoteTeam`](NoteTeam.md); \\}\n\nOne linked document and the extra access this link grants.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-canmanage\"></a> `canManage` | `boolean` | Whether this viewer can change this document's sharing. |\n| <a id=\"property-documentid\"></a> `documentId` | `string` | Markdown document identity. |\n| <a id=\"property-name\"></a> `name` | `string` | Current document name. |\n| <a id=\"property-team\"></a> `team?` | `null` \\| [`NoteTeam`](NoteTeam.md) | - |\n\n\n<!-- generated/calendar/types.gen/type-aliases/NoteTeam.md -->\n# Type Alias: NoteTeam\n\n> **NoteTeam** = \\{ `id`: `string`; `name`: `string`; \\}\n\nAn additional team audience, separate from the meeting's audience.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-id\"></a> `id` | `string` | Team identity. |\n| <a id=\"property-name\"></a> `name` | `string` | Display name. |\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/ReplacementStatus.md -->\n# Type Alias: ReplacementStatus\n\n> **ReplacementStatus** = `\"needs_confirmation\"` \\| `\"in_progress\"` \\| `\"complete\"`\n\nUser-visible workflow state.\n\n\n<!-- generated/calendar/types.gen/type-aliases/TeamCalendarSharing.md -->\n# Type Alias: TeamCalendarSharing\n\n> **TeamCalendarSharing** = `\"all\"` \\| `\"busy_only\"` \\| `\"none\"`\n\nWhat a user exposes through their team membership.\n\n\n<!-- generated/calendar/types.gen/type-aliases/ViewerCapabilities.md -->\n# Type Alias: ViewerCapabilities\n\n> **ViewerCapabilities** = \\{ `editDetails`: `boolean`; `inviteGuests`: `boolean`; `organize`: `boolean`; `removeGuests`: `boolean`; `rsvp`: `boolean`; `setGuestPolicy`: `boolean`; \\}\n\nWhat the viewing requester may do with an event.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-editdetails\"></a> `editDetails` | `boolean` | Change the event's details (title, time, description, conference). |\n| <a id=\"property-inviteguests\"></a> `inviteGuests` | `boolean` | Add guests. |\n| <a id=\"property-organize\"></a> `organize` | `boolean` | Act as the event's organizer: replace its whole guest list and manage its conferencing. |\n| <a id=\"property-removeguests\"></a> `removeGuests` | `boolean` | Remove guests. |\n| <a id=\"property-rsvp\"></a> `rsvp` | `boolean` | Answer the invitation. |\n| <a id=\"property-setguestpolicy\"></a> `setGuestPolicy` | `boolean` | Change the event's guest policy, which only Google calendars have. |\n\n\n<!-- generated/calendar/types.gen/type-aliases/VisibleCalendar.md -->\n# Type Alias: VisibleCalendar\n\n> **VisibleCalendar** = \\{ `capabilities`: [`CalendarCapabilities`](CalendarCapabilities.md); `color?`: `string` \\| `null`; `defaultReminders`: [`EventReminderOverride`](EventReminderOverride.md)[]; `emailAddress`: `string`; `emailLinkId`: `string`; `id`: `string`; `isPrimary`: `boolean`; `isSubscription`: `boolean`; `isWritable`: `boolean`; `name`: `string`; `provider`: [`CalendarProvider`](CalendarProvider.md); `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-capabilities\"></a> `capabilities` | [`CalendarCapabilities`](CalendarCapabilities.md) | Provider features available on this actual calendar. |\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-provider\"></a> `provider` | [`CalendarProvider`](CalendarProvider.md) | Calendar provider, for display and reconnect routing. |\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<!-- generated/storage/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/storage/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/storage/types.gen/type-aliases/CalendarOccurrence.md -->\n# Type Alias: CalendarOccurrence\n\n> **CalendarOccurrence** = \\{ `eventId`: `string`; `isCancelled`: `boolean`; `occurrenceKey`: `string`; `recurrenceId?`: `string` \\| `null`; `time`: [`EventTime`](EventTime.md); \\}\n\nA materialized recurrence instance optimized for range queries.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-eventid\"></a> `eventId` | `string` | Owning event entity. |\n| <a id=\"property-iscancelled\"></a> `isCancelled` | `boolean` | Whether the instance was cancelled. |\n| <a id=\"property-occurrencekey\"></a> `occurrenceKey` | `string` | Stable key within the event. |\n| <a id=\"property-recurrenceid\"></a> `recurrenceId?` | `string` \\| `null` | Provider recurrence identifier, when applicable. |\n| <a id=\"property-time\"></a> `time` | [`EventTime`](EventTime.md) | Instance time. |\n\n\n<!-- generated/storage/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/storage/types.gen/type-aliases/ListOccurrencesData.md -->\n# Type Alias: ListOccurrencesData\n\n> **ListOccurrencesData** = \\{ `body?`: `never`; `path?`: `never`; `query`: \\{ `cursor?`: `string`; `end`: `string`; `endDate?`: `string`; `limit?`: `number`; `start`: `string`; `startDate?`: `string`; \\}; `url`: `\"/calendar-events\"`; \\}\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-body\"></a> `body?` | `never` | - |\n| <a id=\"property-path\"></a> `path?` | `never` | - |\n| <a id=\"property-query\"></a> `query` | \\{ `cursor?`: `string`; `end`: `string`; `endDate?`: `string`; `limit?`: `number`; `start`: `string`; `startDate?`: `string`; \\} | - |\n| `query.cursor?` | `string` | Opaque continuation cursor returned by the previous page. |\n| `query.end` | `string` | Exclusive UTC viewport end. |\n| `query.endDate?` | `string` | Exclusive local date boundary for all-day events. |\n| `query.limit?` | `number` | Maximum number of occurrences, from 1 through 2,000. |\n| `query.start` | `string` | Inclusive UTC viewport start. |\n| `query.startDate?` | `string` | Inclusive local date boundary for all-day events. |\n| <a id=\"property-url\"></a> `url` | `\"/calendar-events\"` | - |\n\n\n<!-- generated/storage/types.gen/type-aliases/TeamCalendarCoverage.md -->\n# Type Alias: TeamCalendarCoverage\n\n> **TeamCalendarCoverage** = `\"ready\"` \\| `\"unavailable\"` \\| `\"hidden\"`\n\nWhether a member's calendar projection can establish availability.\n\n\n<!-- generated/storage/types.gen/type-aliases/TeamCalendarDetails.md -->\n# Type Alias: TeamCalendarDetails\n\n> **TeamCalendarDetails** = \\{ `attendees`: [`CalendarAttendee`](CalendarAttendee.md)[]; `calendarName`: `string`; `conferenceUrl?`: `string` \\| `null`; `description?`: `string` \\| `null`; `location?`: `string` \\| `null`; `organizerEmail?`: `string` \\| `null`; `organizerName?`: `string` \\| `null`; `title`: `string`; \\}\n\nSafe details from a single authorized source.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-attendees\"></a> `attendees` | [`CalendarAttendee`](CalendarAttendee.md)[] | Attendees; self flags are relative to the requesting viewer. |\n| <a id=\"property-calendarname\"></a> `calendarName` | `string` | Source calendar name, shown only with details. |\n| <a id=\"property-conferenceurl\"></a> `conferenceUrl?` | `string` \\| `null` | Join URL, if supplied by this source. |\n| <a id=\"property-description\"></a> `description?` | `string` \\| `null` | Body, if supplied by this source. |\n| <a id=\"property-location\"></a> `location?` | `string` \\| `null` | Location, if supplied by this source. |\n| <a id=\"property-organizeremail\"></a> `organizerEmail?` | `string` \\| `null` | Organizer address from this source. |\n| <a id=\"property-organizername\"></a> `organizerName?` | `string` \\| `null` | Organizer name from this source. |\n| <a id=\"property-title\"></a> `title` | `string` | Display title. |\n\n\n<!-- generated/storage/types.gen/type-aliases/TeamCalendarSharing.md -->\n# Type Alias: TeamCalendarSharing\n\n> **TeamCalendarSharing** = `\"all\"` \\| `\"busy_only\"` \\| `\"none\"`\n\nWhat a user exposes through their team membership.\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### setContributesToAvailability()\n\n> **setContributesToAvailability**(`contributesToAvailability`): `Promise`\\<`void`\\>\n\nSet whether this calendar contributes to the caller's availability.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `contributesToAvailability` | `boolean` |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\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-guestpolicy\"></a> `guestPolicy` | `readonly` | () => `Promise`\\<[`GuestPolicy`](../../../../../generated/calendar/types.gen/type-aliases/GuestPolicy.md)\\> | What the organizer lets guests do: modify, invite others, see the guest list. | - |\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| <a id=\"property-viewercan\"></a> `viewerCan` | `readonly` | () => `Promise`\\<[`ViewerCapabilities`](../../../../../generated/calendar/types.gen/type-aliases/ViewerCapabilities.md)\\> | What the connected account may do with this event under its guest policy. | - |\n\n## Methods\n\n### addToCalendar()\n\n> **addToCalendar**(`options?`): `Promise`\\<`CalendarEvent`\\>\n\nAdd a snapshot of an event shared with one of the requester's\nchannels to one of their Google calendars, and return a handle to the\nsynced snapshot. The snapshot keeps the meeting's iCalendar UID and\norganizer, lists only the requester as a guest, and carries no join link;\nnobody is notified, and answers or guests on it never reach the meeting.\nRefused with `already_on_calendar` when the meeting is already on one of\ntheir calendars, and with `copy_refused` when Google will not import it.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `options?` | \\{ `calendar?`: [`Calendar`](../../calendar/classes/Calendar.md); \\} |\n| `options.calendar?` | [`Calendar`](../../calendar/classes/Calendar.md) |\n\n#### Returns\n\n`Promise`\\<`CalendarEvent`\\>\n\n***\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### ics()\n\n> **ics**(): `Promise`\\<`string`\\>\n\nThe event as an iCalendar (`.ics`) document: its series, title,\ndescription, location and organizer, never its guests or join link.\nAvailable for the requester's own events and ones shared with a channel\nthey belong to.\n\n#### Returns\n\n`Promise`\\<`string`\\>\n\n***\n\n### inviteGuests()\n\n> **inviteGuests**(`options`): `Promise`\\<`CalendarEvent`\\>\n\nAdd guests without touching anyone already invited, and return a handle\nto the synced record. The organizer may, and so may a guest the organizer\nlets invite others (see [CalendarEvent.viewerCan](#property-viewercan)); Google emails\nthe new guests.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `options` | [`InviteGuestsOptions`](../interfaces/InviteGuestsOptions.md) |\n\n#### Returns\n\n`Promise`\\<`CalendarEvent`\\>\n\n***\n\n### linkNote()\n\n> **linkNote**(`document`, `occurrence`, `options?`): `Promise`\\<[`CalendarNote`](../../note/classes/CalendarNote.md)\\>\n\nLink a markdown document you own. Meeting-detail viewers gain read access;\nan optional team gains read access too. Editing and other sharing are preserved.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `document` | [`Document`](../../../documents/document/classes/Document.md) |\n| `occurrence` | [`CalendarOccurrence`](../../../../../generated/storage/types.gen/type-aliases/CalendarOccurrence.md) |\n| `options?` | \\{ `team?`: [`Team`](../../../teams/team/classes/Team.md); \\} |\n| `options.team?` | [`Team`](../../../teams/team/classes/Team.md) |\n\n#### Returns\n\n`Promise`\\<[`CalendarNote`](../../note/classes/CalendarNote.md)\\>\n\n***\n\n### notes()\n\n> **notes**(`occurrence`): `Promise`\\<[`CalendarNote`](../../note/classes/CalendarNote.md)[]\\>\n\nNotes linked to a specific occurrence returned by `calendar.occurrences()`.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `occurrence` | [`CalendarOccurrence`](../../../../../generated/storage/types.gen/type-aliases/CalendarOccurrence.md) |\n\n#### Returns\n\n`Promise`\\<[`CalendarNote`](../../note/classes/CalendarNote.md)[]\\>\n\n***\n\n### prepareReplacement()\n\n> **prepareReplacement**(`options`): `Promise`\\<[`CalendarReplacement`](../../replacement/classes/CalendarReplacement.md)\\>\n\nPreview an organizer replacement without cancelling or sending invitations.\nReview replacement.status() before explicitly calling replacement.confirm().\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `options` | \\{ `calendar?`: [`Calendar`](../../calendar/classes/Calendar.md); `recurrenceId?`: `string`; `removeConference`: `boolean`; \\} |\n| `options.calendar?` | [`Calendar`](../../calendar/classes/Calendar.md) |\n| `options.recurrenceId?` | `string` |\n| `options.removeConference` | `boolean` |\n\n#### Returns\n\n`Promise`\\<[`CalendarReplacement`](../../replacement/classes/CalendarReplacement.md)\\>\n\n***\n\n### providerUrl()\n\n> **providerUrl**(`options?`): `Promise`\\<`string` \\| `undefined`\\>\n\nOpen this calendar copy in its provider for actions unavailable through its API.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `options?` | \\{ `calendar?`: [`Calendar`](../../calendar/classes/Calendar.md); `recurrenceId?`: `string`; \\} |\n| `options.calendar?` | [`Calendar`](../../calendar/classes/Calendar.md) |\n| `options.recurrenceId?` | `string` |\n\n#### Returns\n\n`Promise`\\<`string` \\| `undefined`\\>\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/InviteGuestsOptions.md -->\n# Interface: InviteGuestsOptions\n\nGuests to add and how much of a recurring series gains them.\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 written, for a multi-calendar event. Omit to write the canonical copy. |\n| <a id=\"property-guests\"></a> `guests` | [`CalendarGuestInputBody`](../../../../../generated/calendar/types.gen/type-aliases/CalendarGuestInputBody.md)[] | Guests to add; anyone already on the event is skipped. |\n| <a id=\"property-recurrenceid\"></a> `recurrenceId?` | `string` | Original-start key of the occurrence the guests are added to. |\n| <a id=\"property-scope\"></a> `scope?` | [`CalendarUpdateScopeParam`](../../../../../generated/calendar/types.gen/type-aliases/CalendarUpdateScopeParam.md) | How much of a recurring series gains the guests. Omit to let `recurrenceId` decide. |\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) | Provider conference change; omit to retain it. Outlook removal requires a separately confirmed replacement via prepareReplacement(). |\n| <a id=\"property-description\"></a> `description?` | `string` | Replacement description; an empty string clears it. |\n| <a id=\"property-guestpolicy\"></a> `guestPolicy?` | [`GuestPolicy`](../../../../../generated/calendar/types.gen/type-aliases/GuestPolicy.md) | Replacement guest policy; only the organizer of a Google event may change it (`viewerCan.setGuestPolicy`). It applies to the whole series, so an update scoped to one occurrence (`scope: 'this_event'`, or a `recurrenceId`) that changes it is rejected; use scope `'all'`. |\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### availabilityCalendars()\n\n> **availabilityCalendars**(): `Promise`\\<\\{ `calendar`: [`Calendar`](../../calendar/classes/Calendar.md); `contributesToAvailability`: `boolean`; `isPrimary`: `boolean`; `name`: `string`; \\}[]\\>\n\nCalendar availability settings, each referring to a typed calendar.\n\n#### Returns\n\n`Promise`\\<\\{ `calendar`: [`Calendar`](../../calendar/classes/Calendar.md); `contributesToAvailability`: `boolean`; `isPrimary`: `boolean`; `name`: `string`; \\}[]\\>\n\n***\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\n### noteDocuments()\n\n> **noteDocuments**(`query?`): `Promise`\\<\\{ `documents`: \\{ `document`: [`Document`](../../../documents/document/classes/Document.md); `name`: `string`; \\}[]; `teams`: \\{ `name`: `string`; `team`: [`Team`](../../../teams/team/classes/Team.md); \\}[]; \\}\\>\n\nFind up to 30 owned markdown documents for meeting notes, plus available extra team audiences.\n\n#### Parameters\n\n| Parameter | Type | Default value |\n| ------ | ------ | ------ |\n| `query?` | `string` | `''` |\n\n#### Returns\n\n`Promise`\\<\\{ `documents`: \\{ `document`: [`Document`](../../../documents/document/classes/Document.md); `name`: `string`; \\}[]; `teams`: \\{ `name`: `string`; `team`: [`Team`](../../../teams/team/classes/Team.md); \\}[]; \\}\\>\n\n***\n\n### occurrences()\n\n> **occurrences**(`options`): `AsyncGenerator`\\<\\{ `event`: [`CalendarEvent`](../../event/classes/CalendarEvent.md); `occurrence`: [`CalendarOccurrence`](../../../../../generated/storage/types.gen/type-aliases/CalendarOccurrence.md); \\}, `any`, `any`\\>\n\nCalendar occurrences in a viewport, automatically paginated.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `options` | `Omit`\\<[`ListOccurrencesData`](../../../../../generated/storage/types.gen/type-aliases/ListOccurrencesData.md)\\[`\"query\"`\\], `\"cursor\"`\\> |\n\n#### Returns\n\n`AsyncGenerator`\\<\\{ `event`: [`CalendarEvent`](../../event/classes/CalendarEvent.md); `occurrence`: [`CalendarOccurrence`](../../../../../generated/storage/types.gen/type-aliases/CalendarOccurrence.md); \\}, `any`, `any`\\>\n\n***\n\n### replacement()\n\n> **replacement**(`operationId`): [`CalendarReplacement`](../../replacement/classes/CalendarReplacement.md)\n\nRecover a saved replacement, including after its original event was retired.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `operationId` | `string` |\n\n#### Returns\n\n[`CalendarReplacement`](../../replacement/classes/CalendarReplacement.md)\n\n***\n\n### setTeamSharing()\n\n> **setTeamSharing**(`sharing`): `Promise`\\<[`TeamCalendarSharing`](../../../../../generated/calendar/types.gen/type-aliases/TeamCalendarSharing.md)\\>\n\nReplace the team calendar sharing preference.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `sharing` | [`TeamCalendarSharing`](../../../../../generated/calendar/types.gen/type-aliases/TeamCalendarSharing.md) |\n\n#### Returns\n\n`Promise`\\<[`TeamCalendarSharing`](../../../../../generated/calendar/types.gen/type-aliases/TeamCalendarSharing.md)\\>\n\n***\n\n### teamOutOfOffice()\n\n> **teamOutOfOffice**(`options`): `Promise`\\<\\{ `hasMore`: `boolean`; `items`: \\{ `event`: [`CalendarEvent`](../../event/classes/CalendarEvent.md); `occurrenceKey`: `string`; `owner`: [`User`](../../../users/user/classes/User.md); `time`: [`EventTime`](../../../../../generated/storage/types.gen/type-aliases/EventTime.md); `title`: `string` \\| `undefined`; \\}[]; \\}\\>\n\nTeammates' out-of-office occurrences in a bounded viewport. Check hasMore for truncation.\n\n#### Parameters\n\n| Parameter | Type | Description |\n| ------ | ------ | ------ |\n| `options` | \\{ `end`: `string`; `endDate?`: `string`; `limit?`: `number`; `start`: `string`; `startDate?`: `string`; \\} | - |\n| `options.end` | `string` | Exclusive UTC viewport end. |\n| `options.endDate?` | `string` | Exclusive local date boundary for all-day events. |\n| `options.limit?` | `number` | Maximum number of occurrences, from 1 through 2,000. |\n| `options.start` | `string` | Inclusive UTC viewport start. |\n| `options.startDate?` | `string` | Inclusive local date boundary for all-day events. |\n\n#### Returns\n\n`Promise`\\<\\{ `hasMore`: `boolean`; `items`: \\{ `event`: [`CalendarEvent`](../../event/classes/CalendarEvent.md); `occurrenceKey`: `string`; `owner`: [`User`](../../../users/user/classes/User.md); `time`: [`EventTime`](../../../../../generated/storage/types.gen/type-aliases/EventTime.md); `title`: `string` \\| `undefined`; \\}[]; \\}\\>\n\n***\n\n### teamPage()\n\n> **teamPage**(`options`): `Promise`\\<\\{ `items`: (\\{ `contributesToAvailability`: `boolean`; `id`: `string`; `kind`: `\"busy\"`; `owner`: [`User`](../../../users/user/classes/User.md); `time`: [`EventTime`](../../../../../generated/storage/types.gen/type-aliases/EventTime.md); \\} \\| \\{ `contributesToAvailability`: `boolean`; `details`: [`TeamCalendarDetails`](../../../../../generated/storage/types.gen/type-aliases/TeamCalendarDetails.md); `id`: `string`; `kind`: `\"details\"`; `owner`: [`User`](../../../users/user/classes/User.md); `time`: [`EventTime`](../../../../../generated/storage/types.gen/type-aliases/EventTime.md); \\})[]; `members`: \\{ `coverage`: [`TeamCalendarCoverage`](../../../../../generated/storage/types.gen/type-aliases/TeamCalendarCoverage.md); `sharing`: [`TeamCalendarSharing`](../../../../../generated/storage/types.gen/type-aliases/TeamCalendarSharing.md); `user`: [`User`](../../../users/user/classes/User.md); \\}[]; `nextCursor`: `string` \\| `undefined`; \\}\\>\n\nA page of team availability, including its roster and continuation cursor.\n\n#### Parameters\n\n| Parameter | Type | Description |\n| ------ | ------ | ------ |\n| `options` | \\{ `cursor?`: `string` \\| `null`; `end`: `string`; `limit?`: `number` \\| `null`; `start`: `string`; \\} | - |\n| `options.cursor?` | `string` \\| `null` | Continuation returned by the preceding page. |\n| `options.end` | `string` | Exclusive instant. |\n| `options.limit?` | `number` \\| `null` | Maximum source occurrences, at most 2,000. Zero returns the roster only. |\n| `options.start` | `string` | Inclusive instant. |\n\n#### Returns\n\n`Promise`\\<\\{ `items`: (\\{ `contributesToAvailability`: `boolean`; `id`: `string`; `kind`: `\"busy\"`; `owner`: [`User`](../../../users/user/classes/User.md); `time`: [`EventTime`](../../../../../generated/storage/types.gen/type-aliases/EventTime.md); \\} \\| \\{ `contributesToAvailability`: `boolean`; `details`: [`TeamCalendarDetails`](../../../../../generated/storage/types.gen/type-aliases/TeamCalendarDetails.md); `id`: `string`; `kind`: `\"details\"`; `owner`: [`User`](../../../users/user/classes/User.md); `time`: [`EventTime`](../../../../../generated/storage/types.gen/type-aliases/EventTime.md); \\})[]; `members`: \\{ `coverage`: [`TeamCalendarCoverage`](../../../../../generated/storage/types.gen/type-aliases/TeamCalendarCoverage.md); `sharing`: [`TeamCalendarSharing`](../../../../../generated/storage/types.gen/type-aliases/TeamCalendarSharing.md); `user`: [`User`](../../../users/user/classes/User.md); \\}[]; `nextCursor`: `string` \\| `undefined`; \\}\\>\n\n***\n\n### teamSharing()\n\n> **teamSharing**(): `Promise`\\<[`TeamCalendarSharing`](../../../../../generated/calendar/types.gen/type-aliases/TeamCalendarSharing.md)\\>\n\nCurrent sharing preference for the team calendar.\n\n#### Returns\n\n`Promise`\\<[`TeamCalendarSharing`](../../../../../generated/calendar/types.gen/type-aliases/TeamCalendarSharing.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-guestpolicy\"></a> `guestPolicy?` | [`GuestPolicy`](../../../../../generated/calendar/types.gen/type-aliases/GuestPolicy.md) | What guests may do; omit for Google's defaults. Google calendars only. |\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 an 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\n\n<!-- src/entities/calendar/note/classes/CalendarNote.md -->\n# Class: CalendarNote\n\nA markdown document linked to one meeting occurrence, with view-only access.\n\n## Extends\n\n- [`MacroEntity`](../../../entity/classes/MacroEntity.md)\\<[`MeetingNote`](../../../../../generated/calendar/types.gen/type-aliases/MeetingNote.md)\\>\n\n## Properties\n\n| Property | Modifier | Type | Description | Inherited from |\n| ------ | ------ | ------ | ------ | ------ |\n| <a id=\"property-canmanage\"></a> `canManage` | `readonly` | () => `Promise`\\<`boolean`\\> | Whether the caller may change this link's sharing. | - |\n| <a id=\"property-document\"></a> `document` | `readonly` | () => `Promise`\\<[`Document`](../../../documents/document/classes/Document.md)\\> | The original markdown document; unlinking never deletes it. | - |\n| <a id=\"property-event\"></a> `event` | `readonly` | [`CalendarEvent`](../../event/classes/CalendarEvent.md) | - | - |\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-name\"></a> `name` | `readonly` | () => `Promise`\\<`string`\\> | Current document name. | - |\n| <a id=\"property-occurrence\"></a> `occurrence` | `readonly` | `Pick`\\<[`CalendarOccurrence`](../../../../../generated/storage/types.gen/type-aliases/CalendarOccurrence.md), `\"eventId\"` \\| `\"occurrenceKey\"`\\> | - | - |\n| <a id=\"property-team\"></a> `team` | `readonly` | () => `Promise`\\<[`Team`](../../../teams/team/classes/Team.md) \\| `undefined`\\> | Optional extra team audience. Meeting-detail viewers already have view access. | - |\n\n## Methods\n\n### setTeam()\n\n> **setTeam**(`team?`): `Promise`\\<`void`\\>\n\nChange the extra team view grant; omit the team to remove it. Requires document ownership.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `team?` | [`Team`](../../../teams/team/classes/Team.md) |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### toJSON()\n\n> **toJSON**(): \\{ `detail?`: [`MeetingNote`](../../../../../generated/calendar/types.gen/type-aliases/MeetingNote.md); `id`: `string`; \\}\n\n#### Returns\n\n\\{ `detail?`: [`MeetingNote`](../../../../../generated/calendar/types.gen/type-aliases/MeetingNote.md); `id`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `detail?` | [`MeetingNote`](../../../../../generated/calendar/types.gen/type-aliases/MeetingNote.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### unlink()\n\n> **unlink**(): `Promise`\\<`void`\\>\n\nRemove this occurrence's link and view grants, preserving the document and other sharing.\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### forDocument()\n\n> `static` **forDocument**(`client`, `event`, `occurrence`, `document`): `CalendarNote`\n\nConstruct a handle for a document already linked to this occurrence.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `event` | [`CalendarEvent`](../../event/classes/CalendarEvent.md) |\n| `occurrence` | [`CalendarOccurrence`](../../../../../generated/storage/types.gen/type-aliases/CalendarOccurrence.md) |\n| `document` | [`Document`](../../../documents/document/classes/Document.md) |\n\n#### Returns\n\n`CalendarNote`\n\n***\n\n### fromDocumentLink()\n\n> `static` **fromDocumentLink**(`client`, `document`, `link`): `CalendarNote`\n\nSeed an owner-visible link that can be revoked even if the meeting is unavailable.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `document` | [`Document`](../../../documents/document/classes/Document.md) |\n| `link` | [`DocumentNoteLink`](../../../../../generated/calendar/types.gen/type-aliases/DocumentNoteLink.md) |\n\n#### Returns\n\n`CalendarNote`\n\n***\n\n### fromRecord()\n\n> `static` **fromRecord**(`client`, `event`, `occurrence`, `record`): `CalendarNote`\n\nSeed a handle with a record returned by the meeting-note API.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `event` | [`CalendarEvent`](../../event/classes/CalendarEvent.md) |\n| `occurrence` | [`CalendarOccurrence`](../../../../../generated/storage/types.gen/type-aliases/CalendarOccurrence.md) |\n| `record` | [`MeetingNote`](../../../../../generated/calendar/types.gen/type-aliases/MeetingNote.md) |\n\n#### Returns\n\n`CalendarNote`\n\n\n<!-- src/entities/calendar/replacement/classes/CalendarReplacement.md -->\n# Class: CalendarReplacement\n\nDurable organizer replacement, recoverable even after the original event is retired.\n\n## Constructors\n\n### Constructor\n\n> **new CalendarReplacement**(`client`, `id`): `CalendarReplacement`\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `id` | `string` |\n\n#### Returns\n\n`CalendarReplacement`\n\n## Properties\n\n| Property | Modifier | Type |\n| ------ | ------ | ------ |\n| <a id=\"property-id\"></a> `id` | `readonly` | `string` |\n\n## Methods\n\n### confirm()\n\n> **confirm**(): `Promise`\\<[`CalendarReplacementView`](../../../../../generated/calendar/types.gen/type-aliases/CalendarReplacementView.md)\\>\n\nConfirm the reviewed cancellation and reinvitation, or resume that same operation.\nPresent the preview and obtain the organizer's confirmation before the first call.\n\n#### Returns\n\n`Promise`\\<[`CalendarReplacementView`](../../../../../generated/calendar/types.gen/type-aliases/CalendarReplacementView.md)\\>\n\n***\n\n### discard()\n\n> **discard**(): `Promise`\\<`void`\\>\n\nDiscard an unconfirmed preview. Confirmed operations must be recovered, not discarded.\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### status()\n\n> **status**(): `Promise`\\<[`CalendarReplacementView`](../../../../../generated/calendar/types.gen/type-aliases/CalendarReplacementView.md)\\>\n\nRead progress without initiating provider writes.\n\n#### Returns\n\n`Promise`\\<[`CalendarReplacementView`](../../../../../generated/calendar/types.gen/type-aliases/CalendarReplacementView.md)\\>\n"
},
{
"name": "calls",
@@ -99,7 +99,7 @@
"name": "documents",
"description": "Search, read, create, and manage documents and tasks.",
"overview": "<!-- src/entities/documents/namespace/classes/DocumentNamespace.md -->\n# Class: DocumentNamespace\n\n## Constructors\n\n### Constructor\n\n> **new DocumentNamespace**(`client`): `DocumentNamespace`\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n\n#### Returns\n\n`DocumentNamespace`\n\n## Methods\n\n### byId()\n\n> **byId**(`id`): [`Document`](../../document/classes/Document.md)\n\nA handle to a document by id. Details load on first access.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `id` | `string` |\n\n#### Returns\n\n[`Document`](../../document/classes/Document.md)\n\n***\n\n### byTeamSlug()\n\n> **byTeamSlug**(`slug`): `Promise`\\<[`Document`](../../document/classes/Document.md)\\>\n\nResolve a team task reference such as ENG-42.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `slug` | `string` |\n\n#### Returns\n\n`Promise`\\<[`Document`](../../document/classes/Document.md)\\>\n\n***\n\n### create()\n\n> **create**(`opts`): `Promise`\\<[`Document`](../../document/classes/Document.md)\\>\n\nCreate a markdown document.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `opts` | \\{ `markdown?`: `string`; `name`: `string`; `project?`: [`Project`](../../../projects/project/classes/Project.md); \\} |\n| `opts.markdown?` | `string` |\n| `opts.name` | `string` |\n| `opts.project?` | [`Project`](../../../projects/project/classes/Project.md) |\n\n#### Returns\n\n`Promise`\\<[`Document`](../../document/classes/Document.md)\\>\n\n***\n\n### createSkill()\n\n> **createSkill**(`opts`): `Promise`\\<[`Document`](../../document/classes/Document.md)\\>\n\nCreate a skill: markdown instructions that AI reads and follows.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `opts` | \\{ `markdown?`: `string`; `name`: `string`; `project?`: [`Project`](../../../projects/project/classes/Project.md); \\} |\n| `opts.markdown?` | `string` |\n| `opts.name` | `string` |\n| `opts.project?` | [`Project`](../../../projects/project/classes/Project.md) |\n\n#### Returns\n\n`Promise`\\<[`Document`](../../document/classes/Document.md)\\>\n\n***\n\n### createSnippet()\n\n> **createSnippet**(`opts`): `Promise`\\<[`Document`](../../document/classes/Document.md)\\>\n\nCreate a snippet: a reusable markdown document.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `opts` | \\{ `markdown?`: `string`; `name`: `string`; `project?`: [`Project`](../../../projects/project/classes/Project.md); \\} |\n| `opts.markdown?` | `string` |\n| `opts.name` | `string` |\n| `opts.project?` | [`Project`](../../../projects/project/classes/Project.md) |\n\n#### Returns\n\n`Promise`\\<[`Document`](../../document/classes/Document.md)\\>\n\n***\n\n### createUpload()\n\n> **createUpload**(`options`): `Promise`\\<\\{ `content`: [`DocumentContent`](../../../../../generated/storage/types.gen/type-aliases/DocumentContent.md); `contentType`: `string`; `document`: [`Document`](../../document/classes/Document.md); `uploadUrl`: `string` \\| `undefined`; \\}\\>\n\nReserve a binary document and return upload instructions. Upload content before saving.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `options` | \\{ `attachment?`: [`EmailAttachment`](../../../email/attachment/classes/EmailAttachment.md); `branchedFrom?`: [`Document`](../../document/classes/Document.md); `fileType?`: `string`; `isTask?`: `boolean`; `mimeType?`: `string`; `name`: `string`; `project?`: [`Project`](../../../projects/project/classes/Project.md); `sha`: `string`; `team?`: [`Team`](../../../teams/team/classes/Team.md); \\} |\n| `options.attachment?` | [`EmailAttachment`](../../../email/attachment/classes/EmailAttachment.md) |\n| `options.branchedFrom?` | [`Document`](../../document/classes/Document.md) |\n| `options.fileType?` | `string` |\n| `options.isTask?` | `boolean` |\n| `options.mimeType?` | `string` |\n| `options.name` | `string` |\n| `options.project?` | [`Project`](../../../projects/project/classes/Project.md) |\n| `options.sha` | `string` |\n| `options.team?` | [`Team`](../../../teams/team/classes/Team.md) |\n\n#### Returns\n\n`Promise`\\<\\{ `content`: [`DocumentContent`](../../../../../generated/storage/types.gen/type-aliases/DocumentContent.md); `contentType`: `string`; `document`: [`Document`](../../document/classes/Document.md); `uploadUrl`: `string` \\| `undefined`; \\}\\>\n\n***\n\n### recent()\n\n> **recent**(`opts?`): `AsyncGenerator`\\<[`Document`](../../document/classes/Document.md)\\>\n\nThe user's recent documents, most recent first, auto-paginated.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `opts?` | \\{ `fileType?`: `string`; `pageSize?`: `number`; \\} |\n| `opts.fileType?` | `string` |\n| `opts.pageSize?` | `number` |\n\n#### Returns\n\n`AsyncGenerator`\\<[`Document`](../../document/classes/Document.md)\\>\n\n***\n\n### recentlyDeleted()\n\n> **recentlyDeleted**(): `Promise`\\<[`Document`](../../document/classes/Document.md)[]\\>\n\nThe user's recently soft-deleted documents.\n\n#### Returns\n\n`Promise`\\<[`Document`](../../document/classes/Document.md)[]\\>\n\n***\n\n### search()\n\n> **search**(`query`, `opts?`): `AsyncGenerator`\\<[`Document`](../../document/classes/Document.md)\\>\n\nSearch documents by name and content, most relevant first, auto-paginated.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `query` | `string` |\n| `opts?` | [`SearchOpts`](../../../search/interfaces/SearchOpts.md) |\n\n#### Returns\n\n`AsyncGenerator`\\<[`Document`](../../document/classes/Document.md)\\>\n\n***\n\n### systemSkills()\n\n> **systemSkills**(): `Promise`\\<[`SystemSkill`](../../system-skill/classes/SystemSkill.md)[]\\>\n\nThe built-in system skills: static AI instructions with no document\nbehind them. Unlike user skills they cannot be opened or edited.\n\n#### Returns\n\n`Promise`\\<[`SystemSkill`](../../system-skill/classes/SystemSkill.md)[]\\>\n\n***\n\n### validatePermissionsToken()\n\n> **validatePermissionsToken**(`token`): `Promise`\\<\\{ `accessLevel`: [`AccessLevel`](../../../../../generated/storage/types.gen/type-aliases/AccessLevel.md); `document`: [`Document`](../../document/classes/Document.md); `expiresAt`: `number`; `issuer`: `string`; `user`: [`User`](../../../users/user/classes/User.md) \\| `undefined`; \\}\\>\n\nValidate a permissions token, returning its document and optional user handles.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `token` | `string` |\n\n#### Returns\n\n`Promise`\\<\\{ `accessLevel`: [`AccessLevel`](../../../../../generated/storage/types.gen/type-aliases/AccessLevel.md); `document`: [`Document`](../../document/classes/Document.md); `expiresAt`: `number`; `issuer`: `string`; `user`: [`User`](../../../users/user/classes/User.md) \\| `undefined`; \\}\\>\n",
- "documentation": "# Macro SDK: documents\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/properties/types.gen/type-aliases/BulkUpdateEntityPropertyOptionsResponse.md -->\n# Type Alias: BulkUpdateEntityPropertyOptionsResponse\n\n> **BulkUpdateEntityPropertyOptionsResponse** = \\{ `properties`: [`EntityPropertyOptionSelectionResponse`](EntityPropertyOptionSelectionResponse.md)[]; \\}\n\nResponse for a bulk option update: each property's reconciled final ids.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-properties\"></a> `properties` | [`EntityPropertyOptionSelectionResponse`](EntityPropertyOptionSelectionResponse.md)[] | The final option ids per updated property. |\n\n\n<!-- generated/properties/types.gen/type-aliases/DataType.md -->\n# Type Alias: DataType\n\n> **DataType** = `\"BOOLEAN\"` \\| `\"DATE\"` \\| `\"NUMBER\"` \\| `\"STRING\"` \\| `\"SELECT_NUMBER\"` \\| `\"SELECT_STRING\"` \\| `\"TAG\"` \\| `\"ENTITY\"` \\| `\"LINK\"`\n\nData type for property values, determining storage and validation.\n\n\n<!-- generated/properties/types.gen/type-aliases/EntityProperty.md -->\n# Type Alias: EntityProperty\n\n> **EntityProperty** = \\{ `created_at`: `string`; `entity_id`: `string`; `entity_type`: [`EntityType`](EntityType.md); `id`: `string`; `property_definition_id`: `string`; `updated_at`: `string`; \\}\n\nAssignment of a property definition to a specific entity (service representation).\n\n## Properties\n\n| Property | Type |\n| ------ | ------ |\n| <a id=\"property-created_at\"></a> `created_at` | `string` |\n| <a id=\"property-entity_id\"></a> `entity_id` | `string` |\n| <a id=\"property-entity_type\"></a> `entity_type` | [`EntityType`](EntityType.md) |\n| <a id=\"property-id\"></a> `id` | `string` |\n| <a id=\"property-property_definition_id\"></a> `property_definition_id` | `string` |\n| <a id=\"property-updated_at\"></a> `updated_at` | `string` |\n\n\n<!-- generated/properties/types.gen/type-aliases/EntityPropertyOptionSelectionResponse.md -->\n# Type Alias: EntityPropertyOptionSelectionResponse\n\n> **EntityPropertyOptionSelectionResponse** = \\{ `option_ids`: `string`[]; `property_id`: `string`; \\}\n\nThe reconciled final option ids stored for one property after a bulk update.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-option_ids\"></a> `option_ids` | `string`[] | The final option ids the server persisted, in stored order. |\n| <a id=\"property-property_id\"></a> `property_id` | `string` | The property definition the options belong to. |\n\n\n<!-- generated/properties/types.gen/type-aliases/EntityPropertyWithDefinition.md -->\n# Type Alias: EntityPropertyWithDefinition\n\n> **EntityPropertyWithDefinition** = \\{ `definition`: [`PropertyDefinition`](PropertyDefinition.md); `options?`: [`PropertyOption`](PropertyOption.md)[] \\| `null`; `property`: [`EntityProperty`](EntityProperty.md); `value?`: `null` \\| [`PropertyValue`](PropertyValue.md); \\}\n\nEntity property with its definition, value, and options (service representation).\n\n## Properties\n\n| Property | Type |\n| ------ | ------ |\n| <a id=\"property-definition\"></a> `definition` | [`PropertyDefinition`](PropertyDefinition.md) |\n| <a id=\"property-options\"></a> `options?` | [`PropertyOption`](PropertyOption.md)[] \\| `null` |\n| <a id=\"property-property\"></a> `property` | [`EntityProperty`](EntityProperty.md) |\n| <a id=\"property-value\"></a> `value?` | `null` \\| [`PropertyValue`](PropertyValue.md) |\n\n\n<!-- generated/properties/types.gen/type-aliases/EntityReference.md -->\n# Type Alias: EntityReference\n\n> **EntityReference** = \\{ `entity_id`: `string`; `entity_type`: [`EntityType`](EntityType.md); `specific_message_id?`: `string` \\| `null`; \\}\n\nEntity reference for entity-type property values.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-entity_id\"></a> `entity_id` | `string` | - |\n| <a id=\"property-entity_type\"></a> `entity_type` | [`EntityType`](EntityType.md) | - |\n| <a id=\"property-specific_message_id\"></a> `specific_message_id?` | `string` \\| `null` | For CHANNEL, CHAT, THREAD entity types - optional specific message ID. This allows referencing a specific message within a thread/channel/chat. |\n\n\n<!-- generated/properties/types.gen/type-aliases/EntityType.md -->\n# Type Alias: EntityType\n\n> **EntityType** = `\"CALENDAR_EVENT\"` \\| `\"CALL_RECORD\"` \\| `\"CHANNEL\"` \\| `\"CHAT\"` \\| `\"COMPANY\"` \\| `\"DATABASE_ROW\"` \\| `\"CONTACT\"` \\| `\"DOCUMENT\"` \\| `\"INITIATIVE\"` \\| `\"PROJECT\"` \\| `\"TASK\"` \\| `\"THREAD\"` \\| `\"USER\"`\n\nType of entity that can be referenced by entity properties.\n\n\n<!-- generated/properties/types.gen/type-aliases/PropertyDefinition.md -->\n# Type Alias: PropertyDefinition\n\n> **PropertyDefinition** = \\{ `created_at`: `string`; `data_type`: [`DataType`](DataType.md); `display_name`: `string`; `id`: `string`; `is_metadata`: `boolean`; `is_multi_select`: `boolean`; `is_system`: `boolean`; `owner`: [`PropertyOwner`](PropertyOwner.md); `specific_entity_type`: `null` \\| [`EntityType`](EntityType.md); `updated_at`: `string`; \\}\n\nProperty definition model (service representation).\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-created_at\"></a> `created_at` | `string` | - |\n| <a id=\"property-data_type\"></a> `data_type` | [`DataType`](DataType.md) | - |\n| <a id=\"property-display_name\"></a> `display_name` | `string` | - |\n| <a id=\"property-id\"></a> `id` | `string` | - |\n| <a id=\"property-is_metadata\"></a> `is_metadata` | `boolean` | Flag to indicate if this is a system-generated metadata property. Not stored in database - computed at service layer. |\n| <a id=\"property-is_multi_select\"></a> `is_multi_select` | `boolean` | - |\n| <a id=\"property-is_system\"></a> `is_system` | `boolean` | Flag to indicate if this is a system property (stored in DB). |\n| <a id=\"property-owner\"></a> `owner` | [`PropertyOwner`](PropertyOwner.md) | - |\n| <a id=\"property-specific_entity_type\"></a> `specific_entity_type` | `null` \\| [`EntityType`](EntityType.md) | - |\n| <a id=\"property-updated_at\"></a> `updated_at` | `string` | - |\n\n\n<!-- generated/properties/types.gen/type-aliases/PropertyOption.md -->\n# Type Alias: PropertyOption\n\n> **PropertyOption** = \\{ `color`: `string` \\| `null`; `created_at`: `string`; `display_order`: `number`; `id`: `string`; `property_definition_id`: `string`; `updated_at`: `string`; `value`: [`PropertyOptionValue`](PropertyOptionValue.md); \\}\n\nA selectable option for select-type properties (service representation).\n\n## Properties\n\n| Property | Type |\n| ------ | ------ |\n| <a id=\"property-color\"></a> `color` | `string` \\| `null` |\n| <a id=\"property-created_at\"></a> `created_at` | `string` |\n| <a id=\"property-display_order\"></a> `display_order` | `number` |\n| <a id=\"property-id\"></a> `id` | `string` |\n| <a id=\"property-property_definition_id\"></a> `property_definition_id` | `string` |\n| <a id=\"property-updated_at\"></a> `updated_at` | `string` |\n| <a id=\"property-value\"></a> `value` | [`PropertyOptionValue`](PropertyOptionValue.md) |\n\n\n<!-- generated/properties/types.gen/type-aliases/PropertyOptionValue.md -->\n# Type Alias: PropertyOptionValue\n\n> **PropertyOptionValue** = \\{ `type`: `\"string\"`; `value`: `string`; \\} \\| \\{ `type`: `\"number\"`; `value`: `number`; \\}\n\nThe value of a property option - either a string or a number.\n\n## Union Members\n\n### Type Literal\n\n\\{ `type`: `\"string\"`; `value`: `string`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `type` | `\"string\"` | - |\n| `value` | `string` | String value for SelectString properties |\n\n***\n\n### Type Literal\n\n\\{ `type`: `\"number\"`; `value`: `number`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `type` | `\"number\"` | - |\n| `value` | `number` | Number value for SelectNumber properties |\n\n\n<!-- generated/properties/types.gen/type-aliases/PropertyOwner.md -->\n# Type Alias: PropertyOwner\n\n> **PropertyOwner** = \\{ `scope`: `\"user\"`; `user_id`: `string`; \\} \\| \\{ `scope`: `\"team\"`; `team_id`: `string`; \\} \\| \\{ `database_id`: `string`; `scope`: `\"database\"`; \\} \\| \\{ `scope`: `\"system\"`; \\}\n\nDefines who owns a property - user-scoped, team-scoped, database-scoped, or system.\n\n\n<!-- generated/properties/types.gen/type-aliases/PropertyTargetEntityType.md -->\n# Type Alias: PropertyTargetEntityType\n\n> **PropertyTargetEntityType** = `\"CALL_RECORD\"` \\| `\"CHANNEL\"` \\| `\"CHAT\"` \\| `\"COMPANY\"` \\| `\"DATABASE_ROW\"` \\| `\"DOCUMENT\"` \\| `\"INITIATIVE\"` \\| `\"PROJECT\"` \\| `\"THREAD\"` \\| `\"USER\"`\n\nCanonical type of an entity receiving properties.\n\nTasks are documents at API boundaries. `Task` intentionally does not exist\nhere; task classification is resolved by the properties domain from the\ndocument subtype.\n\n\n<!-- generated/properties/types.gen/type-aliases/PropertyTargetReference.md -->\n# Type Alias: PropertyTargetReference\n\n> **PropertyTargetReference** = \\{ `entity_id`: `string`; `entity_type`: [`PropertyTargetEntityType`](PropertyTargetEntityType.md); \\}\n\nCanonical reference to an entity receiving properties.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-entity_id\"></a> `entity_id` | `string` | Entity identifier. |\n| <a id=\"property-entity_type\"></a> `entity_type` | [`PropertyTargetEntityType`](PropertyTargetEntityType.md) | Canonical entity type. |\n\n\n<!-- generated/properties/types.gen/type-aliases/PropertyValue.md -->\n# Type Alias: PropertyValue\n\n> **PropertyValue** = \\{ `type`: `\"Boolean\"`; `value`: `boolean`; \\} \\| \\{ `type`: `\"Number\"`; `value`: `number`; \\} \\| \\{ `type`: `\"String\"`; `value`: `string`; \\} \\| \\{ `type`: `\"Date\"`; `value`: `string`; \\} \\| \\{ `type`: `\"SelectOption\"`; `value`: `string`[]; \\} \\| \\{ `type`: `\"EntityReference\"`; `value`: [`EntityReference`](EntityReference.md)[]; \\} \\| \\{ `type`: `\"Link\"`; `value`: `string`[]; \\}\n\nProperty value (service representation).\n\nRepresents the actual value stored for an entity property.\nThis is serialized to/from JSONB in the database.\n\n## Union Members\n\n### Type Literal\n\n\\{ `type`: `\"Boolean\"`; `value`: `boolean`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `type` | `\"Boolean\"` | - |\n| `value` | `boolean` | Boolean value Serializes as: {\"type\": \"Boolean\", \"value\": true} |\n\n***\n\n### Type Literal\n\n\\{ `type`: `\"Number\"`; `value`: `number`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `type` | `\"Number\"` | - |\n| `value` | `number` | Numeric value Serializes as: {\"type\": \"Number\", \"value\": 42.5} |\n\n***\n\n### Type Literal\n\n\\{ `type`: `\"String\"`; `value`: `string`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `type` | `\"String\"` | - |\n| `value` | `string` | String value Serializes as: {\"type\": \"String\", \"value\": \"text\"} |\n\n***\n\n### Type Literal\n\n\\{ `type`: `\"Date\"`; `value`: `string`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `type` | `\"Date\"` | - |\n| `value` | `string` | Date/timestamp value Serializes as: {\"type\": \"Date\", \"value\": \"2025-01-01T00:00:00Z\"} |\n\n***\n\n### Type Literal\n\n\\{ `type`: `\"SelectOption\"`; `value`: `string`[]; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `type` | `\"SelectOption\"` | - |\n| `value` | `string`[] | Select option(s) - always an array (check is_multi_select to determine if single or multi) Single-select: {\"type\": \"SelectOption\", \"value\": [\"uuid\"]} (length 0 or 1) Multi-select: {\"type\": \"SelectOption\", \"value\": [\"uuid1\", \"uuid2\", ...]} (length 0+) |\n\n***\n\n### Type Literal\n\n\\{ `type`: `\"EntityReference\"`; `value`: [`EntityReference`](EntityReference.md)[]; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `type` | `\"EntityReference\"` | - |\n| `value` | [`EntityReference`](EntityReference.md)[] | Entity reference(s) - always an array (check is_multi_select to determine if single or multi) Single-select: {\"type\": \"EntityReference\", \"value\": [{...}]} (length 0 or 1) Multi-select: {\"type\": \"EntityReference\", \"value\": [{...}, {...}, ...]} (length 0+) |\n\n***\n\n### Type Literal\n\n\\{ `type`: `\"Link\"`; `value`: `string`[]; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `type` | `\"Link\"` | - |\n| `value` | `string`[] | Link value(s) - always an array (check is_multi_select to determine if single or multi) Single-select: {\"type\": \"Link\", \"value\": [\"https://example.com\"]} (length 0 or 1) Multi-select: {\"type\": \"Link\", \"value\": [\"https://example.com\", \"https://other.com\"]} (length 0+) |\n\n\n<!-- generated/properties/types.gen/type-aliases/SetPropertyValue.md -->\n# Type Alias: SetPropertyValue\n\n> **SetPropertyValue** = \\{ `type`: `\"boolean\"`; `value`: `boolean`; \\} \\| \\{ `type`: `\"date\"`; `value`: `string`; \\} \\| \\{ `type`: `\"number\"`; `value`: `number`; \\} \\| \\{ `type`: `\"string\"`; `value`: `string`; \\} \\| \\{ `option_id`: `string`; `type`: `\"select_option\"`; \\} \\| \\{ `option_ids`: `string`[]; `type`: `\"multi_select_option\"`; \\} \\| \\{ `reference`: [`EntityReference`](EntityReference.md); `type`: `\"entity_reference\"`; \\} \\| \\{ `references`: [`EntityReference`](EntityReference.md)[]; `type`: `\"multi_entity_reference\"`; \\} \\| \\{ `type`: `\"link\"`; `url`: `string`; \\} \\| \\{ `type`: `\"multi_link\"`; `urls`: `string`[]; \\}\n\nType-safe enum for setting entity property values - provides compile-time validation.\n\n\n<!-- generated/storage/types.gen/type-aliases/AccessLevel.md -->\n# Type Alias: AccessLevel\n\n> **AccessLevel** = `\"view\"` \\| `\"comment\"` \\| `\"edit\"` \\| `\"owner\"`\n\nOrdered from least to most access top -> bottom\n\n\n<!-- generated/storage/types.gen/type-aliases/Anchor.md -->\n# Type Alias: Anchor\n\n> **Anchor** = [`PdfAnchor`](PdfAnchor.md)\n\n\n<!-- generated/storage/types.gen/type-aliases/BomPart.md -->\n# Type Alias: BomPart\n\n> **BomPart** = \\{ `id`: `string`; `path`: `string`; `sha`: `string`; \\}\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-id\"></a> `id` | `string` | The uuid of the bom part |\n| <a id=\"property-path\"></a> `path` | `string` | The file path of the bom part content |\n| <a id=\"property-sha\"></a> `sha` | `string` | The sha of the bom part content There is an index on sha for more performant queries based on it. |\n\n\n<!-- generated/storage/types.gen/type-aliases/BotSenderProfile.md -->\n# Type Alias: BotSenderProfile\n\n> **BotSenderProfile** = \\{ `avatar_url?`: `string` \\| `null`; `name`: `string`; \\}\n\nPublic bot profile attached to bot-authored messages.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-avatar_url\"></a> `avatar_url?` | `string` \\| `null` | Bot avatar URL. |\n| <a id=\"property-name\"></a> `name` | `string` | Bot display name. |\n\n\n<!-- generated/storage/types.gen/type-aliases/ChannelSharePermission.md -->\n# Type Alias: ChannelSharePermission\n\n> **ChannelSharePermission** = \\{ `access_level`: [`AccessLevel`](AccessLevel.md); `channel_id`: `string`; \\}\n\nThe channel share permission\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-access_level\"></a> `access_level` | [`AccessLevel`](AccessLevel.md) | The access level for the channel |\n| <a id=\"property-channel_id\"></a> `channel_id` | `string` | The channel id |\n\n\n<!-- generated/storage/types.gen/type-aliases/CountedReaction.md -->\n# Type Alias: CountedReaction\n\n> **CountedReaction** = \\{ `emoji`: `string`; `users`: `string`[]; \\}\n\nReaction emoji and the users who added it.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-emoji\"></a> `emoji` | `string` | Emoji being reacted with. |\n| <a id=\"property-users\"></a> `users` | `string`[] | User identifiers. |\n\n\n<!-- generated/storage/types.gen/type-aliases/DocumentContent.md -->\n# Type Alias: DocumentContent\n\n> **DocumentContent** = \\{ `location?`: `null` \\| [`DocumentContentLocation`](DocumentContentLocation.md); `state`: [`DocumentContentState`](DocumentContentState.md); \\}\n\nAPI-visible content lifecycle and location metadata.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-location\"></a> `location?` | `null` \\| [`DocumentContentLocation`](DocumentContentLocation.md) | - |\n| <a id=\"property-state\"></a> `state` | [`DocumentContentState`](DocumentContentState.md) | The current lifecycle state of the content. |\n\n\n<!-- generated/storage/types.gen/type-aliases/DocumentContentLocation.md -->\n# Type Alias: DocumentContentLocation\n\n> **DocumentContentLocation** = `\"object_storage\"` \\| `\"sync_service\"` \\| `\"docx_bom_parts\"` \\| `\"converted_pdf\"` \\| `\"unknown\"`\n\nWhere document content is, or is expected to be, read from.\n\n\n<!-- generated/storage/types.gen/type-aliases/DocumentContentState.md -->\n# Type Alias: DocumentContentState\n\n> **DocumentContentState** = `\"unknown\"` \\| `\"pending\"` \\| `\"ready\"`\n\nAPI-visible content lifecycle state derived from current document metadata.\n\n\n<!-- generated/storage/types.gen/type-aliases/DocumentId.md -->\n# Type Alias: DocumentId\n\n> **DocumentId** = `string`\n\nA validated document identifier. Historical document ids need not be UUIDs.\n\n\n<!-- generated/storage/types.gen/type-aliases/DocumentMetadata.md -->\n# Type Alias: DocumentMetadata\n\n> **DocumentMetadata** = \\{ `branchedFromId?`: `string` \\| `null`; `branchedFromVersionId?`: `number` \\| `null`; `createdAt?`: `string` \\| `null`; `deletedAt?`: `string` \\| `null`; `documentBom?`: [`BomPart`](BomPart.md)[] \\| `null`; `documentFamilyId?`: `number` \\| `null`; `documentId`: `string`; `documentName`: `string`; `documentVersionId`: `number`; `fileType?`: `string` \\| `null`; `modificationData?`: `unknown`; `owner`: `string`; `projectId?`: `string` \\| `null`; `projectName?`: `string` \\| `null`; `sha?`: `string` \\| `null`; `subType?`: `null` \\| [`DocumentSubType`](DocumentSubType.md); `updatedAt?`: `string` \\| `null`; \\}\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-branchedfromid\"></a> `branchedFromId?` | `string` \\| `null` | The id of the document this document branched from |\n| <a id=\"property-branchedfromversionid\"></a> `branchedFromVersionId?` | `number` \\| `null` | The id of the version this document branched from This could be either DocumentInstance or DocumentBom id depending on the file type |\n| <a id=\"property-createdat\"></a> `createdAt?` | `string` \\| `null` | The time the document was created |\n| <a id=\"property-deletedat\"></a> `deletedAt?` | `string` \\| `null` | The time the document was deleted |\n| <a id=\"property-documentbom\"></a> `documentBom?` | [`BomPart`](BomPart.md)[] \\| `null` | If the document is a DOCX document and unzipped, the document_bom will be present |\n| <a id=\"property-documentfamilyid\"></a> `documentFamilyId?` | `number` \\| `null` | The id of the document family this document belongs to |\n| <a id=\"property-documentid\"></a> `documentId` | `string` | The document id |\n| <a id=\"property-documentname\"></a> `documentName` | `string` | The name of the document |\n| <a id=\"property-documentversionid\"></a> `documentVersionId` | `number` | The version of the document This could be the document_instance_id or document_bom_id depending on the file type |\n| <a id=\"property-filetype\"></a> `fileType?` | `string` \\| `null` | The file type of the document (file extension) |\n| <a id=\"property-modificationdata\"></a> `modificationData?` | `unknown` | The modification data for the document instance. This is only used for PDF documents. |\n| <a id=\"property-owner\"></a> `owner` | `string` | The owner of the document |\n| <a id=\"property-projectid\"></a> `projectId?` | `string` \\| `null` | The id of the project that this document belongs to |\n| <a id=\"property-projectname\"></a> `projectName?` | `string` \\| `null` | The name of the project that this document belongs to |\n| <a id=\"property-sha\"></a> `sha?` | `string` \\| `null` | If the document is a PDF, this is the SHA of the pdf If the document is a DOCX, this will not be present |\n| <a id=\"property-subtype\"></a> `subType?` | `null` \\| [`DocumentSubType`](DocumentSubType.md) | - |\n| <a id=\"property-updatedat\"></a> `updatedAt?` | `string` \\| `null` | The time the document instance / document BOM was updated |\n\n\n<!-- generated/storage/types.gen/type-aliases/DocumentMetadataWithContent.md -->\n# Type Alias: DocumentMetadataWithContent\n\n> **DocumentMetadataWithContent** = [`DocumentMetadata`](DocumentMetadata.md) & \\{ `content`: [`DocumentContent`](DocumentContent.md); `teamId?`: `string` \\| `null`; `teamTaskId?`: `number` \\| `null`; \\}\n\nFull document metadata plus content lifecycle metadata.\n\n## Type Declaration\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `content` | [`DocumentContent`](DocumentContent.md) | Content lifecycle and location metadata. |\n| `teamId?` | `string` \\| `null` | The team this task number is scoped to, for task documents. |\n| `teamTaskId?` | `number` \\| `null` | The task number assigned within the team, for task documents. |\n\n\n<!-- generated/storage/types.gen/type-aliases/DocumentResponseMetadata.md -->\n# Type Alias: DocumentResponseMetadata\n\n> **DocumentResponseMetadata** = \\{ `branchedFromId?`: `string` \\| `null`; `branchedFromVersionId?`: `number` \\| `null`; `createdAt?`: `string` \\| `null`; `documentBom?`: [`BomPart`](BomPart.md)[] \\| `null`; `documentFamilyId?`: `number` \\| `null`; `documentId`: `string`; `documentName`: `string`; `documentVersionId`: `number`; `fileType?`: `string` \\| `null`; `modificationData?`: `unknown`; `owner`: `string`; `sha?`: `string` \\| `null`; `subType?`: `null` \\| [`DocumentSubType`](DocumentSubType.md); `updatedAt?`: `string` \\| `null`; \\}\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-branchedfromid\"></a> `branchedFromId?` | `string` \\| `null` | The id of the document this document branched from |\n| <a id=\"property-branchedfromversionid\"></a> `branchedFromVersionId?` | `number` \\| `null` | The id of the version this document branched from This could be either DocumentInstance or DocumentBom id depending on the file type |\n| <a id=\"property-createdat\"></a> `createdAt?` | `string` \\| `null` | The time the document was created |\n| <a id=\"property-documentbom\"></a> `documentBom?` | [`BomPart`](BomPart.md)[] \\| `null` | If the document is a DOCX document, the document_bom will be present |\n| <a id=\"property-documentfamilyid\"></a> `documentFamilyId?` | `number` \\| `null` | The id of the document family this document belongs to |\n| <a id=\"property-documentid\"></a> `documentId` | `string` | The document id |\n| <a id=\"property-documentname\"></a> `documentName` | `string` | The name of the document |\n| <a id=\"property-documentversionid\"></a> `documentVersionId` | `number` | The version of the document This could be the document_instance_id or document_bom_id depending on the file type |\n| <a id=\"property-filetype\"></a> `fileType?` | `string` \\| `null` | The file type of the document |\n| <a id=\"property-modificationdata\"></a> `modificationData?` | `unknown` | The modification data for the document instance. This is only used for PDF documents. |\n| <a id=\"property-owner\"></a> `owner` | `string` | The owner of the document |\n| <a id=\"property-sha\"></a> `sha?` | `string` \\| `null` | If the document is a PDF, this is the SHA of the pdf If the document is a DOCX, this will not be present |\n| <a id=\"property-subtype\"></a> `subType?` | `null` \\| [`DocumentSubType`](DocumentSubType.md) | - |\n| <a id=\"property-updatedat\"></a> `updatedAt?` | `string` \\| `null` | The time the document instance / document BOM was updated |\n\n\n<!-- generated/storage/types.gen/type-aliases/DocumentSubType.md -->\n# Type Alias: DocumentSubType\n\n> **DocumentSubType** = `\"task\"` \\| `\"snippet\"` \\| `\"skill\"` \\| `\"initiative_description\"`\n\nThe document sub type enum represents all values of document sub types.\nThese values should match the `document_sub_type_value` table in macrodb.\n\nWire, database, and `Display` spellings are all `snake_case` so a\nmulti-word variant serializes identically in every system.\n\n\n<!-- generated/storage/types.gen/type-aliases/DocumentTeamShareResponse.md -->\n# Type Alias: DocumentTeamShareResponse\n\n> **DocumentTeamShareResponse** = \\{ `sharedWithTeam`: `boolean`; `teamId?`: `string` \\| `null`; \\}\n\nThe team-share state of a document. The team is resolved from the document\nowner's team membership.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-sharedwithteam\"></a> `sharedWithTeam` | `boolean` | Whether explicit team sharing is enabled; inherited team access does not count. |\n| <a id=\"property-teamid\"></a> `teamId?` | `string` \\| `null` | The owner's team the document is (or would be) shared with. `None` when the owner does not belong to a team. |\n\n\n<!-- generated/storage/types.gen/type-aliases/EditPdfPlaceableCommentAnchorRequest.md -->\n# Type Alias: EditPdfPlaceableCommentAnchorRequest\n\n> **EditPdfPlaceableCommentAnchorRequest** = \\{ `allowableEdits?`: `unknown`; `heightPct?`: `number` \\| `null`; `originalIndex?`: `number` \\| `null`; `originalPage?`: `number` \\| `null`; `page?`: `number` \\| `null`; `rotation?`: `number` \\| `null`; `shouldLockOnSave?`: `boolean` \\| `null`; `uuid`: `string`; `wasDeleted?`: `boolean` \\| `null`; `wasEdited?`: `boolean` \\| `null`; `widthPct?`: `number` \\| `null`; `xPct?`: `number` \\| `null`; `yPct?`: `number` \\| `null`; \\}\n\n## Properties\n\n| Property | Type |\n| ------ | ------ |\n| <a id=\"property-allowableedits\"></a> `allowableEdits?` | `unknown` |\n| <a id=\"property-heightpct\"></a> `heightPct?` | `number` \\| `null` |\n| <a id=\"property-originalindex\"></a> `originalIndex?` | `number` \\| `null` |\n| <a id=\"property-originalpage\"></a> `originalPage?` | `number` \\| `null` |\n| <a id=\"property-page\"></a> `page?` | `number` \\| `null` |\n| <a id=\"property-rotation\"></a> `rotation?` | `number` \\| `null` |\n| <a id=\"property-shouldlockonsave\"></a> `shouldLockOnSave?` | `boolean` \\| `null` |\n| <a id=\"property-uuid\"></a> `uuid` | `string` |\n| <a id=\"property-wasdeleted\"></a> `wasDeleted?` | `boolean` \\| `null` |\n| <a id=\"property-wasedited\"></a> `wasEdited?` | `boolean` \\| `null` |\n| <a id=\"property-widthpct\"></a> `widthPct?` | `number` \\| `null` |\n| <a id=\"property-xpct\"></a> `xPct?` | `number` \\| `null` |\n| <a id=\"property-ypct\"></a> `yPct?` | `number` \\| `null` |\n\n\n<!-- generated/storage/types.gen/type-aliases/EntityPermission.md -->\n# Type Alias: EntityPermission\n\n> **EntityPermission** = \\{ `access_level`: [`AccessLevel`](AccessLevel.md); `type`: `\"access_level\"`; \\} \\| \\{ `type`: `\"channel_view_only\"`; \\} \\| \\{ `role`: [`ParticipantRole`](ParticipantRole.md); `type`: `\"channel_role\"`; \\} \\| \\{ `role`: [`TeamRole`](TeamRole.md); `type`: `\"team_role\"`; \\}\n\nA user's permission for an entity, discriminated by entity kind.\n\nItems (documents, chats, projects, threads) use access levels.\nChannels use view-only permission or participant roles.\n\n## Union Members\n\n### Type Literal\n\n\\{ `access_level`: [`AccessLevel`](AccessLevel.md); `type`: `\"access_level\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `access_level` | [`AccessLevel`](AccessLevel.md) | The access level the user has. |\n| `type` | `\"access_level\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `type`: `\"channel_view_only\"`; \\}\n\n***\n\n### Type Literal\n\n\\{ `role`: [`ParticipantRole`](ParticipantRole.md); `type`: `\"channel_role\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `role` | [`ParticipantRole`](ParticipantRole.md) | The role the user has in the channel. |\n| `type` | `\"channel_role\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `role`: [`TeamRole`](TeamRole.md); `type`: `\"team_role\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `role` | [`TeamRole`](TeamRole.md) | The role the user has in the team. |\n| `type` | `\"team_role\"` | - |\n\n\n<!-- generated/storage/types.gen/type-aliases/GetDocumentResponseData.md -->\n# Type Alias: GetDocumentResponseData\n\n> **GetDocumentResponseData** = \\{ `documentMetadata`: [`DocumentMetadata`](DocumentMetadata.md); `userAccessLevel`: [`AccessLevel`](AccessLevel.md); `viewLocation?`: `string` \\| `null`; \\}\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-documentmetadata\"></a> `documentMetadata` | [`DocumentMetadata`](DocumentMetadata.md) | The metadata of the document |\n| <a id=\"property-useraccesslevel\"></a> `userAccessLevel` | [`AccessLevel`](AccessLevel.md) | The users level of access to the document |\n| <a id=\"property-viewlocation\"></a> `viewLocation?` | `string` \\| `null` | The users view location if there is one |\n\n\n<!-- generated/storage/types.gen/type-aliases/GithubPullRequest.md -->\n# Type Alias: GithubPullRequest\n\n> **GithubPullRequest** = \\{ `additions?`: `number` \\| `null`; `checks?`: [`GithubPullRequestCheckRun`](GithubPullRequestCheckRun.md)[] \\| `null`; `comments?`: [`GithubPullRequestComment`](GithubPullRequestComment.md)[] \\| `null`; `deletions?`: `number` \\| `null`; `displayName`: `string`; `foreignEntityId?`: `string` \\| `null`; `githubKey`: `string`; `name?`: `string` \\| `null`; `number`: `number`; `owner`: `string`; `repo`: `string`; `status?`: `string` \\| `null`; `url`: `string`; \\}\n\nDisplay-ready data for a GitHub pull request associated with a task.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-additions\"></a> `additions?` | `number` \\| `null` | The number of added lines in the pull request, when enrichment data is available. |\n| <a id=\"property-checks\"></a> `checks?` | [`GithubPullRequestCheckRun`](GithubPullRequestCheckRun.md)[] \\| `null` | Check runs collected from the pull request head commit, when enrichment data is available. |\n| <a id=\"property-comments\"></a> `comments?` | [`GithubPullRequestComment`](GithubPullRequestComment.md)[] \\| `null` | Comments collected from the pull request, when enrichment data is available. |\n| <a id=\"property-deletions\"></a> `deletions?` | `number` \\| `null` | The number of deleted lines in the pull request, when enrichment data is available. |\n| <a id=\"property-displayname\"></a> `displayName` | `string` | A compact label suitable for display in the UI. |\n| <a id=\"property-foreignentityid\"></a> `foreignEntityId?` | `string` \\| `null` | The internal `foreign_entity.id` UUID for the GitHub pull request row. |\n| <a id=\"property-githubkey\"></a> `githubKey` | `string` | The stored GitHub association key, in `owner/repo/pull/number` format. |\n| <a id=\"property-name\"></a> `name?` | `string` \\| `null` | The GitHub pull request title, when enrichment data is available. |\n| <a id=\"property-number\"></a> `number` | `number` | The GitHub pull request number. |\n| <a id=\"property-owner\"></a> `owner` | `string` | The GitHub repository owner or organization. |\n| <a id=\"property-repo\"></a> `repo` | `string` | The GitHub repository name. |\n| <a id=\"property-status\"></a> `status?` | `string` \\| `null` | The GitHub pull request status, when enrichment data is available. |\n| <a id=\"property-url\"></a> `url` | `string` | The public GitHub URL for the pull request. |\n\n\n<!-- generated/storage/types.gen/type-aliases/GithubPullRequestCheckRun.md -->\n# Type Alias: GithubPullRequestCheckRun\n\n> **GithubPullRequestCheckRun** = \\{ `completedAt?`: `string` \\| `null`; `conclusion?`: `string` \\| `null`; `id`: `number`; `name`: `string`; `startedAt?`: `string` \\| `null`; `status`: `string`; `url?`: `string` \\| `null`; \\}\n\nA check run associated with a GitHub pull request.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-completedat\"></a> `completedAt?` | `string` \\| `null` | When the check run completed, when available. |\n| <a id=\"property-conclusion\"></a> `conclusion?` | `string` \\| `null` | The raw GitHub check run conclusion, when the run has completed. |\n| <a id=\"property-id\"></a> `id` | `number` | The unique GitHub identifier for the check run. |\n| <a id=\"property-name\"></a> `name` | `string` | The check run name. |\n| <a id=\"property-startedat\"></a> `startedAt?` | `string` \\| `null` | When the check run started, when available. |\n| <a id=\"property-status\"></a> `status` | `string` | The raw GitHub check run status. |\n| <a id=\"property-url\"></a> `url?` | `string` \\| `null` | The public GitHub URL for the check run, when available. |\n\n\n<!-- generated/storage/types.gen/type-aliases/GithubPullRequestComment.md -->\n# Type Alias: GithubPullRequestComment\n\n> **GithubPullRequestComment** = \\{ `authorAssociation?`: `string` \\| `null`; `authorId?`: `number` \\| `null`; `authorLogin?`: `string` \\| `null`; `body`: `string`; `createdAt?`: `string` \\| `null`; `id`: `number`; `inReplyToId?`: `number` \\| `null`; `line?`: `number` \\| `null`; `originalLine?`: `number` \\| `null`; `path?`: `string` \\| `null`; `pullRequestReviewId?`: `number` \\| `null`; `source`: `string`; `updatedAt?`: `string` \\| `null`; `url?`: `string` \\| `null`; \\}\n\nA comment associated with a GitHub pull request.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-authorassociation\"></a> `authorAssociation?` | `string` \\| `null` | GitHub's relationship label for the author, when available. |\n| <a id=\"property-authorid\"></a> `authorId?` | `number` \\| `null` | The stable numeric GitHub user id for the comment author, when available. |\n| <a id=\"property-authorlogin\"></a> `authorLogin?` | `string` \\| `null` | The GitHub login for the comment author, when available. |\n| <a id=\"property-body\"></a> `body` | `string` | The comment or review body text. |\n| <a id=\"property-createdat\"></a> `createdAt?` | `string` \\| `null` | When the comment was created or the review was submitted. |\n| <a id=\"property-id\"></a> `id` | `number` | The unique GitHub identifier for the comment or review. |\n| <a id=\"property-inreplytoid\"></a> `inReplyToId?` | `number` \\| `null` | The id of the comment this one replies to, when it is part of a review thread. Only ever present on `review_comment` sources. |\n| <a id=\"property-line\"></a> `line?` | `number` \\| `null` | The line in the current diff the comment is anchored to. Cleared by GitHub when later commits outdate the comment's diff. |\n| <a id=\"property-originalline\"></a> `originalLine?` | `number` \\| `null` | The line the comment was originally anchored to, kept even when the diff has since changed. |\n| <a id=\"property-path\"></a> `path?` | `string` \\| `null` | The repository-relative file path the review comment is anchored to. Only ever present on `review_comment` sources. |\n| <a id=\"property-pullrequestreviewid\"></a> `pullRequestReviewId?` | `number` \\| `null` | The id of the pull request review this comment was submitted with. Only ever present on `review_comment` sources. |\n| <a id=\"property-source\"></a> `source` | `string` | The GitHub source for the comment, such as `issue_comment` or `review_comment`. |\n| <a id=\"property-updatedat\"></a> `updatedAt?` | `string` \\| `null` | When the comment or review was last updated. |\n| <a id=\"property-url\"></a> `url?` | `string` \\| `null` | The public GitHub URL for the comment or review, when available. |\n\n\n<!-- generated/storage/types.gen/type-aliases/HighlightType.md -->\n# Type Alias: HighlightType\n\n> **HighlightType** = `1` \\| `2` \\| `3`\n\n\n<!-- generated/storage/types.gen/type-aliases/ImportedAuthor.md -->\n# Type Alias: ImportedAuthor\n\n> **ImportedAuthor** = \\{ `name`: `string`; \\}\n\nDisplay attribution for a comment imported from an external document.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-name\"></a> `name` | `string` | Original author text; never interpreted as an authenticated principal. |\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkShare.md -->\n# Type Alias: LinkShare\n\n> **LinkShare** = `\"PUBLIC\"` \\| `\"TEAM\"`\n\nDefines who can access an item through its share link.\n\n\n<!-- generated/storage/types.gen/type-aliases/Message.md -->\n# Type Alias: Message\n\n> **Message** = \\{ `attachments`: [`MessageAttachment`](MessageAttachment.md)[]; `bot_profile?`: `null` \\| [`BotSenderProfile`](BotSenderProfile.md); `content`: `string`; `created_at`: `string`; `deleted_at?`: `string` \\| `null`; `edited_at?`: `string` \\| `null`; `guest_name?`: `string` \\| `null`; `id`: `string`; `imported_author?`: `null` \\| [`ImportedAuthor`](ImportedAuthor.md); `mentions`: [`SimpleMention`](SimpleMention.md)[]; `parent`: [`MessageParent`](MessageParent.md); `reactions`: [`CountedReaction`](CountedReaction.md)[]; `sender_id`: `string`; `thread_id?`: `string` \\| `null`; `triggered_by?`: `string` \\| `null`; `updated_at`: `string`; \\}\n\nShared message representation for channel timelines and entity discussions.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-attachments\"></a> `attachments` | [`MessageAttachment`](MessageAttachment.md)[] | Attached entities. |\n| <a id=\"property-bot_profile\"></a> `bot_profile?` | `null` \\| [`BotSenderProfile`](BotSenderProfile.md) | - |\n| <a id=\"property-content\"></a> `content` | `string` | Macro Markdown body. |\n| <a id=\"property-created_at\"></a> `created_at` | `string` | Creation time. |\n| <a id=\"property-deleted_at\"></a> `deleted_at?` | `string` \\| `null` | Message tombstone, independent of thread deletion. |\n| <a id=\"property-edited_at\"></a> `edited_at?` | `string` \\| `null` | Last content edit, if any. |\n| <a id=\"property-guest_name\"></a> `guest_name?` | `string` \\| `null` | Display name of a verified call guest, retained after the call ends. |\n| <a id=\"property-id\"></a> `id` | `string` | Message UUID. |\n| <a id=\"property-imported_author\"></a> `imported_author?` | `null` \\| [`ImportedAuthor`](ImportedAuthor.md) | - |\n| <a id=\"property-mentions\"></a> `mentions` | [`SimpleMention`](SimpleMention.md)[] | Tracked mentions, retained when a caller changes attachments only. |\n| <a id=\"property-parent\"></a> `parent` | [`MessageParent`](MessageParent.md) | Entity that owns this conversation. |\n| <a id=\"property-reactions\"></a> `reactions` | [`CountedReaction`](CountedReaction.md)[] | Aggregated reactions. |\n| <a id=\"property-sender_id\"></a> `sender_id` | `string` | Authenticated actor or owner of imported content. |\n| <a id=\"property-thread_id\"></a> `thread_id?` | `string` \\| `null` | Root message UUID for replies; absent on roots. |\n| <a id=\"property-triggered_by\"></a> `triggered_by?` | `string` \\| `null` | User who triggered a bot-authored message. |\n| <a id=\"property-updated_at\"></a> `updated_at` | `string` | Last persisted update. |\n\n\n<!-- generated/storage/types.gen/type-aliases/MessageAttachment.md -->\n# Type Alias: MessageAttachment\n\n> **MessageAttachment** = \\{ `created_at`: `string`; `entity_id`: `string`; `entity_type`: `string`; `height?`: `number` \\| `null`; `id`: `string`; `width?`: `number` \\| `null`; \\}\n\nAn entity attached to a message.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-created_at\"></a> `created_at` | `string` | When the attachment was added. |\n| <a id=\"property-entity_id\"></a> `entity_id` | `string` | Attached entity identifier. |\n| <a id=\"property-entity_type\"></a> `entity_type` | `string` | Attached entity type. |\n| <a id=\"property-height\"></a> `height?` | `number` \\| `null` | Optional media height. |\n| <a id=\"property-id\"></a> `id` | `string` | Attachment UUID. |\n| <a id=\"property-width\"></a> `width?` | `number` \\| `null` | Optional media width. |\n\n\n<!-- generated/storage/types.gen/type-aliases/MessageCursor.md -->\n# Type Alias: MessageCursor\n\n> **MessageCursor** = \\{ `created_at`: `string`; `id`: `string`; \\}\n\nCursor for a chronological parent timeline.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-created_at\"></a> `created_at` | `string` | Last message creation time or activity occurrence time. |\n| <a id=\"property-id\"></a> `id` | `string` | Last entry UUID, used to break timestamp ties across both sources. |\n\n\n<!-- generated/storage/types.gen/type-aliases/MessageParent.md -->\n# Type Alias: MessageParent\n\n> **MessageParent** = \\{ `id`: `string`; `type`: `\"channel\"`; \\} \\| \\{ `id`: [`DocumentId`](DocumentId.md); `type`: `\"document\"`; \\} \\| \\{ `id`: `string`; `type`: `\"initiative\"`; \\} \\| \\{ `id`: `string`; `type`: `\"crm_company\"`; \\} \\| \\{ `id`: `string`; `type`: `\"crm_contact\"`; \\} \\| \\{ `id`: `string`; `type`: `\"call\"`; \\}\n\nThe entity whose permissions and lifecycle govern a message.\n\n## Union Members\n\n### Type Literal\n\n\\{ `id`: `string`; `type`: `\"channel\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `id` | `string` | A channel, including direct messages. |\n| `type` | `\"channel\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `id`: [`DocumentId`](DocumentId.md); `type`: `\"document\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `id` | [`DocumentId`](DocumentId.md) | A document, including tasks and PDFs. |\n| `type` | `\"document\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `id`: `string`; `type`: `\"initiative\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `id` | `string` | An initiative, presented as a project in the application. |\n| `type` | `\"initiative\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `id`: `string`; `type`: `\"crm_company\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `id` | `string` | A CRM company. |\n| `type` | `\"crm_company\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `id`: `string`; `type`: `\"crm_contact\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `id` | `string` | A CRM contact. |\n| `type` | `\"crm_contact\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `id`: `string`; `type`: `\"call\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `id` | `string` | A video call and its persistent chat thread. |\n| `type` | `\"call\"` | - |\n\n\n<!-- generated/storage/types.gen/type-aliases/ParticipantRole.md -->\n# Type Alias: ParticipantRole\n\n> **ParticipantRole** = `\"owner\"` \\| `\"admin\"` \\| `\"member\"`\n\nThe role a user has within a channel.\n\n\n<!-- generated/storage/types.gen/type-aliases/PdfAnchor.md -->\n# Type Alias: PdfAnchor\n\n> **PdfAnchor** = [`PdfPlaceableCommentAnchor`](PdfPlaceableCommentAnchor.md) & \\{ `anchorType`: `\"placeable\"`; \\} \\| [`PdfHighlightAnchor`](PdfHighlightAnchor.md) & \\{ `anchorType`: `\"highlight\"`; \\}\n\n\n<!-- generated/storage/types.gen/type-aliases/PdfHighlightAnchor.md -->\n# Type Alias: PdfHighlightAnchor\n\n> **PdfHighlightAnchor** = \\{ `alpha`: `number`; `blue`: `number`; `createdAt?`: `string` \\| `null`; `deletedAt?`: `string` \\| `null`; `documentId`: `string`; `green`: `number`; `highlightRects`: [`PdfHighlightRect`](PdfHighlightRect.md)[]; `highlightType`: [`HighlightType`](HighlightType.md); `owner`: `string`; `page`: `number`; `pageViewportHeight`: `number`; `pageViewportWidth`: `number`; `red`: `number`; `rootId?`: `string` \\| `null`; `text`: `string`; `updatedAt?`: `string` \\| `null`; `uuid`: `string`; \\}\n\n## Properties\n\n| Property | Type |\n| ------ | ------ |\n| <a id=\"property-alpha\"></a> `alpha` | `number` |\n| <a id=\"property-blue\"></a> `blue` | `number` |\n| <a id=\"property-createdat\"></a> `createdAt?` | `string` \\| `null` |\n| <a id=\"property-deletedat\"></a> `deletedAt?` | `string` \\| `null` |\n| <a id=\"property-documentid\"></a> `documentId` | `string` |\n| <a id=\"property-green\"></a> `green` | `number` |\n| <a id=\"property-highlightrects\"></a> `highlightRects` | [`PdfHighlightRect`](PdfHighlightRect.md)[] |\n| <a id=\"property-highlighttype\"></a> `highlightType` | [`HighlightType`](HighlightType.md) |\n| <a id=\"property-owner\"></a> `owner` | `string` |\n| <a id=\"property-page\"></a> `page` | `number` |\n| <a id=\"property-pageviewportheight\"></a> `pageViewportHeight` | `number` |\n| <a id=\"property-pageviewportwidth\"></a> `pageViewportWidth` | `number` |\n| <a id=\"property-red\"></a> `red` | `number` |\n| <a id=\"property-rootid\"></a> `rootId?` | `string` \\| `null` |\n| <a id=\"property-text\"></a> `text` | `string` |\n| <a id=\"property-updatedat\"></a> `updatedAt?` | `string` \\| `null` |\n| <a id=\"property-uuid\"></a> `uuid` | `string` |\n\n\n<!-- generated/storage/types.gen/type-aliases/PdfHighlightAnchorRequest.md -->\n# Type Alias: PdfHighlightAnchorRequest\n\n> **PdfHighlightAnchorRequest** = \\{ `alpha`: `number`; `blue`: `number`; `green`: `number`; `highlightRects`: [`PdfHighlightRectAnchorRequest`](PdfHighlightRectAnchorRequest.md)[]; `highlightType`: [`HighlightType`](HighlightType.md); `page`: `number`; `pageViewportHeight`: `number`; `pageViewportWidth`: `number`; `red`: `number`; `text`: `string`; `uuid?`: `string` \\| `null`; \\}\n\n## Properties\n\n| Property | Type |\n| ------ | ------ |\n| <a id=\"property-alpha\"></a> `alpha` | `number` |\n| <a id=\"property-blue\"></a> `blue` | `number` |\n| <a id=\"property-green\"></a> `green` | `number` |\n| <a id=\"property-highlightrects\"></a> `highlightRects` | [`PdfHighlightRectAnchorRequest`](PdfHighlightRectAnchorRequest.md)[] |\n| <a id=\"property-highlighttype\"></a> `highlightType` | [`HighlightType`](HighlightType.md) |\n| <a id=\"property-page\"></a> `page` | `number` |\n| <a id=\"property-pageviewportheight\"></a> `pageViewportHeight` | `number` |\n| <a id=\"property-pageviewportwidth\"></a> `pageViewportWidth` | `number` |\n| <a id=\"property-red\"></a> `red` | `number` |\n| <a id=\"property-text\"></a> `text` | `string` |\n| <a id=\"property-uuid\"></a> `uuid?` | `string` \\| `null` |\n\n\n<!-- generated/storage/types.gen/type-aliases/PdfHighlightRect.md -->\n# Type Alias: PdfHighlightRect\n\n> **PdfHighlightRect** = \\{ `height`: `number`; `id`: `number`; `left`: `number`; `top`: `number`; `width`: `number`; \\}\n\n## Properties\n\n| Property | Type |\n| ------ | ------ |\n| <a id=\"property-height\"></a> `height` | `number` |\n| <a id=\"property-id\"></a> `id` | `number` |\n| <a id=\"property-left\"></a> `left` | `number` |\n| <a id=\"property-top\"></a> `top` | `number` |\n| <a id=\"property-width\"></a> `width` | `number` |\n\n\n<!-- generated/storage/types.gen/type-aliases/PdfHighlightRectAnchorRequest.md -->\n# Type Alias: PdfHighlightRectAnchorRequest\n\n> **PdfHighlightRectAnchorRequest** = \\{ `height`: `number`; `left`: `number`; `top`: `number`; `width`: `number`; \\}\n\n## Properties\n\n| Property | Type |\n| ------ | ------ |\n| <a id=\"property-height\"></a> `height` | `number` |\n| <a id=\"property-left\"></a> `left` | `number` |\n| <a id=\"property-top\"></a> `top` | `number` |\n| <a id=\"property-width\"></a> `width` | `number` |\n\n\n<!-- generated/storage/types.gen/type-aliases/PdfPlaceableCommentAnchor.md -->\n# Type Alias: PdfPlaceableCommentAnchor\n\n> **PdfPlaceableCommentAnchor** = \\{ `allowableEdits?`: `unknown`; `documentId`: `string`; `heightPct`: `number`; `originalIndex`: `number`; `originalPage`: `number`; `owner`: `string`; `page`: `number`; `rootId?`: `string` \\| `null`; `rotation`: `number`; `shouldLockOnSave`: `boolean`; `uuid`: `string`; `wasDeleted`: `boolean`; `wasEdited`: `boolean`; `widthPct`: `number`; `xPct`: `number`; `yPct`: `number`; \\}\n\n## Properties\n\n| Property | Type |\n| ------ | ------ |\n| <a id=\"property-allowableedits\"></a> `allowableEdits?` | `unknown` |\n| <a id=\"property-documentid\"></a> `documentId` | `string` |\n| <a id=\"property-heightpct\"></a> `heightPct` | `number` |\n| <a id=\"property-originalindex\"></a> `originalIndex` | `number` |\n| <a id=\"property-originalpage\"></a> `originalPage` | `number` |\n| <a id=\"property-owner\"></a> `owner` | `string` |\n| <a id=\"property-page\"></a> `page` | `number` |\n| <a id=\"property-rootid\"></a> `rootId?` | `string` \\| `null` |\n| <a id=\"property-rotation\"></a> `rotation` | `number` |\n| <a id=\"property-shouldlockonsave\"></a> `shouldLockOnSave` | `boolean` |\n| <a id=\"property-uuid\"></a> `uuid` | `string` |\n| <a id=\"property-wasdeleted\"></a> `wasDeleted` | `boolean` |\n| <a id=\"property-wasedited\"></a> `wasEdited` | `boolean` |\n| <a id=\"property-widthpct\"></a> `widthPct` | `number` |\n| <a id=\"property-xpct\"></a> `xPct` | `number` |\n| <a id=\"property-ypct\"></a> `yPct` | `number` |\n\n\n<!-- generated/storage/types.gen/type-aliases/PreSaveDocumentResponseData.md -->\n# Type Alias: PreSaveDocumentResponseData\n\n> **PreSaveDocumentResponseData** = \\{ `presignedUrls`: [`PresignedUrl`](PresignedUrl.md)[]; \\}\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-presignedurls\"></a> `presignedUrls` | [`PresignedUrl`](PresignedUrl.md)[] | Contains any presigned urls you need to upload specific bom parts with. |\n\n\n<!-- generated/storage/types.gen/type-aliases/PresignedUrl.md -->\n# Type Alias: PresignedUrl\n\n> **PresignedUrl** = \\{ `presignedUrl`: `string`; `sha`: `string`; \\}\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-presignedurl\"></a> `presignedUrl` | `string` | The presigned url used to upload the sha |\n| <a id=\"property-sha\"></a> `sha` | `string` | The sha of the item |\n\n\n<!-- generated/storage/types.gen/type-aliases/SaveBomPart.md -->\n# Type Alias: SaveBomPart\n\n> **SaveBomPart** = \\{ `path`: `string`; `sha`: `string`; \\}\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-path\"></a> `path` | `string` | The file path of the bom part content |\n| <a id=\"property-sha\"></a> `sha` | `string` | The sha of the bom part content There is an index on sha for more performant queries based on it. |\n\n\n<!-- generated/storage/types.gen/type-aliases/SaveDocumentRequest.md -->\n# Type Alias: SaveDocumentRequest\n\n> **SaveDocumentRequest** = \\{ `modificationData?`: `unknown`; `newBom?`: [`SaveBomPart`](SaveBomPart.md)[] \\| `null`; `sha?`: `string` \\| `null`; \\}\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-modificationdata\"></a> `modificationData?` | `unknown` | The modification data for the document instance. Used to store highlights and other overlays onto a static file |\n| <a id=\"property-newbom\"></a> `newBom?` | [`SaveBomPart`](SaveBomPart.md)[] \\| `null` | **DOCX ONLY** The updated BOM for the document. Containing the file path and the sha. |\n| <a id=\"property-sha\"></a> `sha?` | `string` \\| `null` | The sha of the new document. This is used to generate a presigned url to upload the new document content to s3. |\n\n\n<!-- generated/storage/types.gen/type-aliases/SaveDocumentResponseData.md -->\n# Type Alias: SaveDocumentResponseData\n\n> **SaveDocumentResponseData** = \\{ `documentMetadata`: [`DocumentResponseMetadata`](DocumentResponseMetadata.md); `presignedUrl?`: `string` \\| `null`; \\}\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-documentmetadata\"></a> `documentMetadata` | [`DocumentResponseMetadata`](DocumentResponseMetadata.md) | The updated document metadata |\n| <a id=\"property-presignedurl\"></a> `presignedUrl?` | `string` \\| `null` | If the document is an editable file, we provide a presigned url to save the updated file to. |\n\n\n<!-- generated/storage/types.gen/type-aliases/SharePermissionV2.md -->\n# Type Alias: SharePermissionV2\n\n> **SharePermissionV2** = \\{ `channelSharePermissions?`: [`ChannelSharePermission`](ChannelSharePermission.md)[] \\| `null`; `id`: `string`; `linkShare?`: `null` \\| [`LinkShare`](LinkShare.md); `linkShareAccessLevel?`: `null` \\| [`AccessLevel`](AccessLevel.md); `owner`: `string`; `teamShareAccessLevel?`: `null` \\| [`AccessLevel`](AccessLevel.md); \\}\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-channelsharepermissions\"></a> `channelSharePermissions?` | [`ChannelSharePermission`](ChannelSharePermission.md)[] \\| `null` | The channel share permissions for the item |\n| <a id=\"property-id\"></a> `id` | `string` | The share permission id |\n| <a id=\"property-linkshare\"></a> `linkShare?` | `null` \\| [`LinkShare`](LinkShare.md) | - |\n| <a id=\"property-linkshareaccesslevel\"></a> `linkShareAccessLevel?` | `null` \\| [`AccessLevel`](AccessLevel.md) | - |\n| <a id=\"property-owner\"></a> `owner` | `string` | The owner of the item |\n| <a id=\"property-teamshareaccesslevel\"></a> `teamShareAccessLevel?` | `null` \\| [`AccessLevel`](AccessLevel.md) | - |\n\n\n<!-- generated/storage/types.gen/type-aliases/SimpleMention.md -->\n# Type Alias: SimpleMention\n\n> **SimpleMention** = \\{ `entity_id`: `string`; `entity_type`: `string`; \\}\n\nA mention tracked in a message body.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-entity_id\"></a> `entity_id` | `string` | Mentioned entity identifier. |\n| <a id=\"property-entity_type\"></a> `entity_type` | `string` | Mentioned entity type. |\n\n\n<!-- generated/storage/types.gen/type-aliases/TeamRole.md -->\n# Type Alias: TeamRole\n\n> **TeamRole** = `\"member\"` \\| `\"admin\"` \\| `\"owner\"`\n\nThe role a user has within a team.\n\nOrdered least to most privileged so comparisons reflect access strength.\n\n\n<!-- generated/storage/types.gen/type-aliases/ThreadAnchor.md -->\n# Type Alias: ThreadAnchor\n\n> **ThreadAnchor** = \\{ `mark_id`: `string`; `marked_text?`: `string` \\| `null`; `type`: `\"markdown\"`; \\} \\| \\{ `anchor_id`: `string`; `marked_text?`: `string` \\| `null`; `type`: `\"pdf_highlight\"`; \\} \\| \\{ `anchor_id`: `string`; `type`: `\"pdf_placeable\"`; \\} \\| \\{ `range`: `string`; `sheetId`: `string`; `sheetName`: `string`; `type`: `\"spreadsheet\"`; \\} \\| \\{ `nodeId?`: `string` \\| `null`; `pageId`: `string`; `type`: `\"fig\"`; `x`: `number`; `y`: `number`; \\}\n\nA thread's location within its document. PDF geometry remains annotation-owned.\n\n## Union Members\n\n### Type Literal\n\n\\{ `mark_id`: `string`; `marked_text?`: `string` \\| `null`; `type`: `\"markdown\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `mark_id` | `string` | Mark UUID serialized in the document. |\n| `marked_text?` | `string` \\| `null` | The marked text as it read when the discussion was created, already trimmed and bounded. Absent on threads created or imported before snapshots were captured: the text a mark covers cannot be recovered from the mark id alone. |\n| `type` | `\"markdown\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `anchor_id`: `string`; `marked_text?`: `string` \\| `null`; `type`: `\"pdf_highlight\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `anchor_id` | `string` | Highlight annotation UUID. |\n| `marked_text?` | `string` \\| `null` | The text the highlight covers, trimmed and bounded like a markdown snapshot. The highlight owns it and it can be edited there, so it is read from the highlight whenever the thread is, never stored on the thread. Absent when the highlight carries no text. |\n| `type` | `\"pdf_highlight\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `anchor_id`: `string`; `type`: `\"pdf_placeable\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `anchor_id` | `string` | Placeable annotation UUID. |\n| `type` | `\"pdf_placeable\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `range`: `string`; `sheetId`: `string`; `sheetName`: `string`; `type`: `\"spreadsheet\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `range` | `string` | A1 cell or range, such as B4 or B4:C9. |\n| `sheetId` | `string` | Stable sheet identity within the workbook. |\n| `sheetName` | `string` | Sheet name when the discussion was created. |\n| `type` | `\"spreadsheet\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `nodeId?`: `string` \\| `null`; `pageId`: `string`; `type`: `\"fig\"`; `x`: `number`; `y`: `number`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `nodeId?` | `string` \\| `null` | Layer the pin follows; absent for a pin on the bare canvas. |\n| `pageId` | `string` | Page (canvas) the pin is on. |\n| `type` | `\"fig\"` | - |\n| `x` | `number` | Horizontal offset from the layer's origin, or the page's when the pin is on no layer, in design units. |\n| `y` | `number` | Vertical offset, measured like `x`. |\n\n\n<!-- generated/storage/types.gen/type-aliases/ThreadState.md -->\n# Type Alias: ThreadState\n\n> **ThreadState** = \\{ `anchor?`: `null` \\| [`ThreadAnchor`](ThreadAnchor.md); `created_at`: `string`; `deleted_at?`: `string` \\| `null`; `resolved`: `boolean`; `root_id`: `string`; `updated_at`: `string`; `user_id`: `string`; \\}\n\nState belonging to a whole thread, keyed by its root message.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-anchor\"></a> `anchor?` | `null` \\| [`ThreadAnchor`](ThreadAnchor.md) | - |\n| <a id=\"property-created_at\"></a> `created_at` | `string` | Creation time of the discussion. |\n| <a id=\"property-deleted_at\"></a> `deleted_at?` | `string` \\| `null` | Explicit deletion of the entire thread, distinct from root deletion. |\n| <a id=\"property-resolved\"></a> `resolved` | `boolean` | Whether this discussion has been resolved. |\n| <a id=\"property-root_id\"></a> `root_id` | `string` | Root message UUID; there is no separate thread identity. |\n| <a id=\"property-updated_at\"></a> `updated_at` | `string` | Last state change. |\n| <a id=\"property-user_id\"></a> `user_id` | `string` | User who owns this discussion, including imported discussions. |\n\n\n<!-- src/entities/documents/anchor/classes/DocumentAnchor.md -->\n# Class: DocumentAnchor\n\nA PDF annotation scoped to its document.\n\n## Extends\n\n- [`MacroEntity`](../../../entity/classes/MacroEntity.md)\\<[`Anchor`](../../../../../generated/storage/types.gen/type-aliases/Anchor.md)\\>\n\n## Properties\n\n| Property | Modifier | Type | Description | Inherited from |\n| ------ | ------ | ------ | ------ | ------ |\n| <a id=\"property-document\"></a> `document` | `readonly` | [`Document`](../../document/classes/Document.md) | Owning document. | - |\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-kind\"></a> `kind` | `readonly` | () => `Promise`\\<`\"highlight\"` \\| `\"placeable\"`\\> | Annotation kind. | - |\n| <a id=\"property-page\"></a> `page` | `readonly` | () => `Promise`\\<`number`\\> | Page containing the annotation. | - |\n\n## Methods\n\n### delete()\n\n> **delete**(): `Promise`\\<`void`\\>\n\nDelete a standalone highlight annotation.\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### edit()\n\n> **edit**(`options`): `Promise`\\<`void`\\>\n\nEdit a placeable comment's position and display settings.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `options` | `Omit`\\<[`EditPdfPlaceableCommentAnchorRequest`](../../../../../generated/storage/types.gen/type-aliases/EditPdfPlaceableCommentAnchorRequest.md), `\"uuid\"`\\> |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### toJSON()\n\n> **toJSON**(): \\{ `detail?`: [`PdfAnchor`](../../../../../generated/storage/types.gen/type-aliases/PdfAnchor.md); `documentId`: `string`; `id`: `string`; \\}\n\nSerialize identity with its owning resource.\n\n#### Returns\n\n\\{ `detail?`: [`PdfAnchor`](../../../../../generated/storage/types.gen/type-aliases/PdfAnchor.md); `documentId`: `string`; `id`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `detail?` | [`PdfAnchor`](../../../../../generated/storage/types.gen/type-aliases/PdfAnchor.md) |\n| `documentId` | `string` |\n| `id` | `string` |\n\n#### Overrides\n\n[`MacroEntity`](../../../entity/classes/MacroEntity.md).[`toJSON`](../../../entity/classes/MacroEntity.md#tojson)\n\n***\n\n### byId()\n\n> `static` **byId**(`client`, `document`, `id`): `DocumentAnchor`\n\nConstruct a document scoped annotation handle.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `document` | [`Document`](../../document/classes/Document.md) |\n| `id` | `string` |\n\n#### Returns\n\n`DocumentAnchor`\n\n***\n\n### from()\n\n> `static` **from**(`client`, `document`, `record`): `DocumentAnchor`\n\nSeed an annotation from a document annotation listing.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `document` | [`Document`](../../document/classes/Document.md) |\n| `record` | [`PdfAnchor`](../../../../../generated/storage/types.gen/type-aliases/PdfAnchor.md) |\n\n#### Returns\n\n`DocumentAnchor`\n\n\n<!-- src/entities/documents/comment/classes/Comment.md -->\n# Class: Comment\n\nA comment on a document: a document-parent message, addressed by its\ndocument and message UUID. Its record and mutations are the ones channel\nmessages use.\n\n## Extends\n\n- [`MacroEntity`](../../../entity/classes/MacroEntity.md)\\<[`Message`](../../../../../generated/storage/types.gen/type-aliases/Message.md)\\>\n\n## Properties\n\n| Property | Modifier | Type | Description | Inherited from |\n| ------ | ------ | ------ | ------ | ------ |\n| <a id=\"property-createdat\"></a> `createdAt` | `readonly` | () => `Promise`\\<`string`\\> | When the comment was created. | - |\n| <a id=\"property-documentid\"></a> `documentId` | `readonly` | `string` | The document this comment belongs to. | - |\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-text\"></a> `text` | `readonly` | () => `Promise`\\<`string`\\> | The comment's text. | - |\n| <a id=\"property-updatedat\"></a> `updatedAt` | `readonly` | () => `Promise`\\<`string`\\> | When the comment was last updated. | - |\n\n## Methods\n\n### author()\n\n> **author**(): `Promise`\\<[`User`](../../../users/user/classes/User.md)\\>\n\nThe user who wrote this comment.\n\n#### Returns\n\n`Promise`\\<[`User`](../../../users/user/classes/User.md)\\>\n\n***\n\n### delete()\n\n> **delete**(): `Promise`\\<`void`\\>\n\nDelete this comment.\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### document()\n\n> **document**(): [`Document`](../../document/classes/Document.md)\n\nThe document this comment is on.\n\n#### Returns\n\n[`Document`](../../document/classes/Document.md)\n\n***\n\n### edit()\n\n> **edit**(`body`): `Promise`\\<`Comment`\\>\n\nReplace the comment's text.\n\n#### Parameters\n\n| Parameter | Type | Description |\n| ------ | ------ | ------ |\n| `body` | `string` \\| [`RichMessage`](../../../../mentions/interfaces/RichMessage.md) | Plain text, or a rich body composed with msg. |\n\n#### Returns\n\n`Promise`\\<`Comment`\\>\n\n***\n\n### reply()\n\n> **reply**(`body`): `Promise`\\<`Comment`\\>\n\nReply in this comment's thread.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `body` | `string` \\| [`RichMessage`](../../../../mentions/interfaces/RichMessage.md) |\n\n#### Returns\n\n`Promise`\\<`Comment`\\>\n\n***\n\n### threadId()\n\n> **threadId**(): `Promise`\\<`string`\\>\n\nThe id of the thread this comment belongs to: its root, or itself for a root.\n\n#### Returns\n\n`Promise`\\<`string`\\>\n\n***\n\n### toJSON()\n\n> **toJSON**(): \\{ `detail?`: [`Message`](../../../../../generated/storage/types.gen/type-aliases/Message.md); `id`: `string`; \\}\n\n#### Returns\n\n\\{ `detail?`: [`Message`](../../../../../generated/storage/types.gen/type-aliases/Message.md); `id`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `detail?` | [`Message`](../../../../../generated/storage/types.gen/type-aliases/Message.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`, `documentId`, `id`): `Comment`\n\nA handle to a comment by id. Fields load on first access.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `documentId` | `string` |\n| `id` | `string` |\n\n#### Returns\n\n`Comment`\n\n***\n\n### from()\n\n> `static` **from**(`client`, `documentId`, `record`): `Comment`\n\nBuild a comment from a message record (pre-seeded, no fetch).\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `documentId` | `string` |\n| `record` | [`Message`](../../../../../generated/storage/types.gen/type-aliases/Message.md) |\n\n#### Returns\n\n`Comment`\n\n\n<!-- src/entities/documents/document/classes/Document.md -->\n# Class: Document\n\nA Macro document. Can be dropped into a msg template to render an\ninline link to the document.\n\n## Extends\n\n- [`PropertiedEntity`](../../../entity/classes/PropertiedEntity.md)\\<`DocumentDetail`\\>\n\n## Extended by\n\n- [`Task`](../../../tasks/task/classes/Task.md)\n\n## Implements\n\n- [`Mentionable`](../../../../mentions/interfaces/Mentionable.md)\n\n## Properties\n\n| Property | Modifier | Type | Default value | Description | Overrides | Inherited from |\n| ------ | ------ | ------ | ------ | ------ | ------ | ------ |\n| <a id=\"property-access\"></a> `access` | `readonly` | [`EntityAccess`](../../../sharing/access/classes/EntityAccess.md) | `...` | Access requests and direct user grants. | - | - |\n| <a id=\"property-branchedfrom\"></a> `branchedFrom` | `readonly` | () => `Promise`\\<`Document` \\| `undefined`\\> | `...` | The document this one was branched from, if any. | - | - |\n| <a id=\"property-createdat\"></a> `createdAt` | `readonly` | () => `Promise`\\<`string` \\| `undefined`\\> | `...` | When the document was created. | - | - |\n| <a id=\"property-deletedat\"></a> `deletedAt` | `readonly` | () => `Promise`\\<`string` \\| `undefined`\\> | `...` | When the document was deleted, if it has been. | - | - |\n| <a id=\"property-entitytype\"></a> `entityType` | `readonly` | `\"document\"` | `'document'` | Favorites identify documents as `document`. | [`PropertiedEntity`](../../../entity/classes/PropertiedEntity.md).[`entityType`](../../../entity/classes/PropertiedEntity.md#property-entitytype) | - |\n| <a id=\"property-filetype\"></a> `fileType` | `readonly` | () => `Promise`\\<`string` \\| `undefined`\\> | `...` | The document's file type (e.g. `md`, `pdf`, `docx`). | - | - |\n| <a id=\"property-id\"></a> `id` | `public readonly` | `string` | `undefined` | - | - | [`PropertiedEntity`](../../../entity/classes/PropertiedEntity.md).[`id`](../../../entity/classes/PropertiedEntity.md#property-id) |\n| <a id=\"property-name\"></a> `name` | `readonly` | () => `Promise`\\<`string`\\> | `...` | The document's display name. | - | - |\n| <a id=\"property-owner\"></a> `owner` | `readonly` | () => `Promise`\\<[`User`](../../../users/user/classes/User.md)\\> | `...` | The user who owns the document. | - | - |\n| <a id=\"property-project\"></a> `project` | `readonly` | () => `Promise`\\<[`Project`](../../../projects/project/classes/Project.md) \\| `undefined`\\> | `...` | The project this document belongs to, if any. | - | - |\n| <a id=\"property-updatedat\"></a> `updatedAt` | `readonly` | () => `Promise`\\<`string` \\| `undefined`\\> | `...` | When the document was last updated. | - | - |\n| <a id=\"property-search\"></a> `search` | `static` | (`client`, `query`, `searchOpts?`) => `AsyncGenerator`\\<`Document`\\> | `...` | Search documents by name and content, most relevant first, auto-paginated. | - | - |\n\n## Methods\n\n### anchors()\n\n> **anchors**(): `Promise`\\<[`DocumentAnchor`](../../anchor/classes/DocumentAnchor.md)[]\\>\n\nPDF annotations in this document.\n\n#### Returns\n\n`Promise`\\<[`DocumentAnchor`](../../anchor/classes/DocumentAnchor.md)[]\\>\n\n***\n\n### branchName()\n\n> **branchName**(): `Promise`\\<`string`\\>\n\nThe git branch name derived for the document (task documents).\n\n#### Returns\n\n`Promise`\\<`string`\\>\n\n***\n\n### comment()\n\n> **comment**(`body`, `opts?`): `Promise`\\<[`Comment`](../../comment/classes/Comment.md)\\>\n\nAdd a comment. Starts a new unanchored thread, or replies to an existing\none when `threadId` (the thread's root comment id) is given.\n\n#### Parameters\n\n| Parameter | Type | Description |\n| ------ | ------ | ------ |\n| `body` | `string` \\| [`RichMessage`](../../../../mentions/interfaces/RichMessage.md) | Plain text, or a rich body composed with msg. |\n| `opts?` | \\{ `threadId?`: `string`; \\} | - |\n| `opts.threadId?` | `string` | - |\n\n#### Returns\n\n`Promise`\\<[`Comment`](../../comment/classes/Comment.md)\\>\n\nThe created comment.\n\n***\n\n### comments()\n\n> **comments**(): `Promise`\\<[`CommentThread`](../interfaces/CommentThread.md)[]\\>\n\nThe document's live comment threads, each with its comments, newest thread first.\n\n#### Returns\n\n`Promise`\\<[`CommentThread`](../interfaces/CommentThread.md)[]\\>\n\n***\n\n### content()\n\n> **content**(): `Promise`\\<`string`\\>\n\nCurrent Markdown for native documents, extracted text for PDF/Word,\nor raw file content for other formats. Native reads include live edits.\n\n#### Returns\n\n`Promise`\\<`string`\\>\n\n***\n\n### copy()\n\n> **copy**(`opts`): `Promise`\\<`Document`\\>\n\nCopy the document under a new name, optionally from a specific version.\nReturns a handle to the new document.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `opts` | \\{ `name`: `string`; `versionId?`: `number`; \\} |\n| `opts.name` | `string` |\n| `opts.versionId?` | `number` |\n\n#### Returns\n\n`Promise`\\<`Document`\\>\n\n***\n\n### createHighlight()\n\n> **createHighlight**(`options`): `Promise`\\<[`DocumentAnchor`](../../anchor/classes/DocumentAnchor.md)\\>\n\nCreate a standalone PDF highlight.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `options` | `Omit`\\<[`PdfHighlightAnchorRequest`](../../../../../generated/storage/types.gen/type-aliases/PdfHighlightAnchorRequest.md), `\"uuid\"`\\> |\n\n#### Returns\n\n`Promise`\\<[`DocumentAnchor`](../../anchor/classes/DocumentAnchor.md)\\>\n\n***\n\n### delete()\n\n> **delete**(`opts?`): `Promise`\\<`void`\\>\n\nDelete the document. Soft by default (reversible with [restore](#restore));\npass `permanent: true` to delete irreversibly.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `opts?` | \\{ `permanent?`: `boolean`; \\} |\n| `opts.permanent?` | `boolean` |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### deleteProperty()\n\n> **deleteProperty**(`assignment`): `Promise`\\<`void`\\>\n\nRemove a property from this entity, given its [properties](#properties) entry.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `assignment` | [`EntityPropertyWithDefinition`](../../../../../generated/properties/types.gen/type-aliases/EntityPropertyWithDefinition.md) |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n#### Inherited from\n\n[`PropertiedEntity`](../../../entity/classes/PropertiedEntity.md).[`deleteProperty`](../../../entity/classes/PropertiedEntity.md#deleteproperty)\n\n***\n\n### favorite()\n\n> **favorite**(): `Promise`\\<`Document`\\>\n\nAdd this entity to the user's favorites. Returns this handle for chaining.\nPlain unwrap: favoriting alters the user's favorites collection, not this\nentity's own detail, so there's nothing cached to invalidate.\n\n#### Returns\n\n`Promise`\\<`Document`\\>\n\n#### Inherited from\n\n[`PropertiedEntity`](../../../entity/classes/PropertiedEntity.md).[`favorite`](../../../entity/classes/PropertiedEntity.md#favorite)\n\n***\n\n### githubPullRequests()\n\n> **githubPullRequests**(): `Promise`\\<[`GithubPullRequest`](../../../../../generated/storage/types.gen/type-aliases/GithubPullRequest.md)[]\\>\n\nGitHub pull requests associated with the document.\n\n#### Returns\n\n`Promise`\\<[`GithubPullRequest`](../../../../../generated/storage/types.gen/type-aliases/GithubPullRequest.md)[]\\>\n\n***\n\n### messageThreadById()\n\n> **messageThreadById**(`id`): [`MessageThread`](../../../messages/thread/classes/MessageThread.md)\n\nA shared message thread scoped to this resource.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `id` | `string` |\n\n#### Returns\n\n[`MessageThread`](../../../messages/thread/classes/MessageThread.md)\n\n***\n\n### move()\n\n> **move**(`project`): `Promise`\\<`void`\\>\n\nMove the document into a project (or out of one, with `null`).\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `project` | [`Project`](../../../projects/project/classes/Project.md) \\| `null` |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### permission()\n\n> **permission**(): `Promise`\\<\\{ `permission`: [`EntityPermission`](../../../../../generated/storage/types.gen/type-aliases/EntityPermission.md); `status`: `\"access\"`; \\} \\| \\{ `status`: `\"no_access\"`; \\}\\>\n\nRead the caller's effective permission on this entity.\n\n#### Returns\n\n`Promise`\\<\\{ `permission`: [`EntityPermission`](../../../../../generated/storage/types.gen/type-aliases/EntityPermission.md); `status`: `\"access\"`; \\} \\| \\{ `status`: `\"no_access\"`; \\}\\>\n\n#### Inherited from\n\n[`PropertiedEntity`](../../../entity/classes/PropertiedEntity.md).[`permission`](../../../entity/classes/PropertiedEntity.md#permission)\n\n***\n\n### permissionsToken()\n\n> **permissionsToken**(): `Promise`\\<`string`\\>\n\nMint a scoped permissions token.\n\n#### Returns\n\n`Promise`\\<`string`\\>\n\n***\n\n### prepareSave()\n\n> **prepareSave**(`parts`): `Promise`\\<[`PreSaveDocumentResponseData`](../../../../../generated/storage/types.gen/type-aliases/PreSaveDocumentResponseData.md)\\>\n\nPrepare multipart content saving and return the service's upload instructions.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `parts` | [`SaveBomPart`](../../../../../generated/storage/types.gen/type-aliases/SaveBomPart.md)[] |\n\n#### Returns\n\n`Promise`\\<[`PreSaveDocumentResponseData`](../../../../../generated/storage/types.gen/type-aliases/PreSaveDocumentResponseData.md)\\>\n\n***\n\n### properties()\n\n> **properties**(`opts?`): `Promise`\\<[`EntityPropertyWithDefinition`](../../../../../generated/properties/types.gen/type-aliases/EntityPropertyWithDefinition.md)[]\\>\n\nThe properties set on this entity, each with its definition, value, and options.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `opts?` | \\{ `includeMetadata?`: `boolean`; \\} |\n| `opts.includeMetadata?` | `boolean` |\n\n#### Returns\n\n`Promise`\\<[`EntityPropertyWithDefinition`](../../../../../generated/properties/types.gen/type-aliases/EntityPropertyWithDefinition.md)[]\\>\n\n#### Inherited from\n\n[`PropertiedEntity`](../../../entity/classes/PropertiedEntity.md).[`properties`](../../../entity/classes/PropertiedEntity.md#properties)\n\n***\n\n### propertyReference()\n\n> **propertyReference**(): [`PropertyTargetReference`](../../../../../generated/properties/types.gen/type-aliases/PropertyTargetReference.md)\n\nThis entity's reference for bulk property operations.\n\n#### Returns\n\n[`PropertyTargetReference`](../../../../../generated/properties/types.gen/type-aliases/PropertyTargetReference.md)\n\n#### Inherited from\n\n[`PropertiedEntity`](../../../entity/classes/PropertiedEntity.md).[`propertyReference`](../../../entity/classes/PropertiedEntity.md#propertyreference)\n\n***\n\n### rename()\n\n> **rename**(`name`): `Promise`\\<`void`\\>\n\nRename the document.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `name` | `string` |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### restore()\n\n> **restore**(): `Promise`\\<`void`\\>\n\nRestore a soft-deleted document.\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### save()\n\n> **save**(`options`): `Promise`\\<[`SaveDocumentResponseData`](../../../../../generated/storage/types.gen/type-aliases/SaveDocumentResponseData.md)\\>\n\nCommit uploaded content. Does not retry uncertain writes.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `options` | [`SaveDocumentRequest`](../../../../../generated/storage/types.gen/type-aliases/SaveDocumentRequest.md) |\n\n#### Returns\n\n`Promise`\\<[`SaveDocumentResponseData`](../../../../../generated/storage/types.gen/type-aliases/SaveDocumentResponseData.md)\\>\n\n***\n\n### setProperty()\n\n> **setProperty**(`property`, `value?`): `Promise`\\<`void`\\>\n\nSet a property value on this entity, or attach the property without a\nvalue when `value` is omitted.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `property` | [`PropertyDefinition`](../../../properties/property-definition/classes/PropertyDefinition.md) |\n| `value?` | [`SetPropertyValue`](../../../../../generated/properties/types.gen/type-aliases/SetPropertyValue.md) |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n#### Inherited from\n\n[`PropertiedEntity`](../../../entity/classes/PropertiedEntity.md).[`setProperty`](../../../entity/classes/PropertiedEntity.md#setproperty)\n\n***\n\n### setTeamShare()\n\n> **setTeamShare**(`shared`): `Promise`\\<`void`\\>\n\nShare the document with the owner's team, or unshare it.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `shared` | `boolean` |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### sharePermissions()\n\n> **sharePermissions**(): `Promise`\\<[`SharePermissionV2`](../../../../../generated/storage/types.gen/type-aliases/SharePermissionV2.md)\\>\n\nSharing configuration.\n\n#### Returns\n\n`Promise`\\<[`SharePermissionV2`](../../../../../generated/storage/types.gen/type-aliases/SharePermissionV2.md)\\>\n\n***\n\n### shortId()\n\n> **shortId**(): `Promise`\\<`string`\\>\n\nThe document's short id (used in compact links and branch names).\n\n#### Returns\n\n`Promise`\\<`string`\\>\n\n***\n\n### simpleSave()\n\n> **simpleSave**(): `Promise`\\<[`SaveDocumentResponseData`](../../../../../generated/storage/types.gen/type-aliases/SaveDocumentResponseData.md)\\>\n\nCommit a simple document save.\n\n#### Returns\n\n`Promise`\\<[`SaveDocumentResponseData`](../../../../../generated/storage/types.gen/type-aliases/SaveDocumentResponseData.md)\\>\n\n***\n\n### teamShare()\n\n> **teamShare**(): `Promise`\\<[`DocumentTeamShareResponse`](../../../../../generated/storage/types.gen/type-aliases/DocumentTeamShareResponse.md)\\>\n\nWhether the document is shared with the owner's team, and which team.\n\n#### Returns\n\n`Promise`\\<[`DocumentTeamShareResponse`](../../../../../generated/storage/types.gen/type-aliases/DocumentTeamShareResponse.md)\\>\n\n***\n\n### timelinePage()\n\n> **timelinePage**(`selection?`): `Promise`\\<\\{ `entries`: (\\{ `activity`: \\{ `action`: `string`; `actor`: [`User`](../../../users/user/classes/User.md); `actor_id`: `string`; `id`: `string`; `occurred_at`: `string`; `payload?`: `unknown`; \\}; `message?`: `undefined`; `type`: `\"activity\"`; \\} \\| \\{ `activity?`: `undefined`; `message`: [`Comment`](../../comment/classes/Comment.md); `type`: `\"message\"`; \\})[]; `nextCursor`: [`MessageCursor`](../../../../../generated/storage/types.gen/type-aliases/MessageCursor.md) \\| `undefined`; `previousCursor`: [`MessageCursor`](../../../../../generated/storage/types.gen/type-aliases/MessageCursor.md) \\| `undefined`; \\}\\>\n\nA mixed message and activity timeline page.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `selection?` | [`TimelineOptions`](../../../messages/thread/interfaces/TimelineOptions.md)\\<[`Comment`](../../comment/classes/Comment.md)\\> |\n\n#### Returns\n\n`Promise`\\<\\{ `entries`: (\\{ `activity`: \\{ `action`: `string`; `actor`: [`User`](../../../users/user/classes/User.md); `actor_id`: `string`; `id`: `string`; `occurred_at`: `string`; `payload?`: `unknown`; \\}; `message?`: `undefined`; `type`: `\"activity\"`; \\} \\| \\{ `activity?`: `undefined`; `message`: [`Comment`](../../comment/classes/Comment.md); `type`: `\"message\"`; \\})[]; `nextCursor`: [`MessageCursor`](../../../../../generated/storage/types.gen/type-aliases/MessageCursor.md) \\| `undefined`; `previousCursor`: [`MessageCursor`](../../../../../generated/storage/types.gen/type-aliases/MessageCursor.md) \\| `undefined`; \\}\\>\n\n***\n\n### toJSON()\n\n> **toJSON**(): \\{ `detail?`: [`DocumentMetadataWithContent`](../../../../../generated/storage/types.gen/type-aliases/DocumentMetadataWithContent.md); `id`: `string`; \\}\n\n#### Returns\n\n\\{ `detail?`: [`DocumentMetadataWithContent`](../../../../../generated/storage/types.gen/type-aliases/DocumentMetadataWithContent.md); `id`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `detail?` | [`DocumentMetadataWithContent`](../../../../../generated/storage/types.gen/type-aliases/DocumentMetadataWithContent.md) |\n| `id` | `string` |\n\n#### Inherited from\n\n[`PropertiedEntity`](../../../entity/classes/PropertiedEntity.md).[`toJSON`](../../../entity/classes/PropertiedEntity.md#tojson)\n\n***\n\n### toMention()\n\n> **toMention**(): [`MentionPart`](../../../../mentions/interfaces/MentionPart.md)\n\n#### Returns\n\n[`MentionPart`](../../../../mentions/interfaces/MentionPart.md)\n\n#### Implementation of\n\n[`Mentionable`](../../../../mentions/interfaces/Mentionable.md).[`toMention`](../../../../mentions/interfaces/Mentionable.md#tomention)\n\n***\n\n### unfavorite()\n\n> **unfavorite**(): `Promise`\\<`Document`\\>\n\nRemove this entity from the user's favorites. Returns this handle for chaining.\n\n#### Returns\n\n`Promise`\\<`Document`\\>\n\n#### Inherited from\n\n[`PropertiedEntity`](../../../entity/classes/PropertiedEntity.md).[`unfavorite`](../../../entity/classes/PropertiedEntity.md#unfavorite)\n\n***\n\n### updatePropertyOptions()\n\n> **updatePropertyOptions**(`changes`): `Promise`\\<[`BulkUpdateEntityPropertyOptionsResponse`](../../../../../generated/properties/types.gen/type-aliases/BulkUpdateEntityPropertyOptionsResponse.md)\\>\n\nApply multi-select option deltas atomically across this entity's properties.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `changes` | [`PropertyOptionDelta`](../../../entity/interfaces/PropertyOptionDelta.md)[] |\n\n#### Returns\n\n`Promise`\\<[`BulkUpdateEntityPropertyOptionsResponse`](../../../../../generated/properties/types.gen/type-aliases/BulkUpdateEntityPropertyOptionsResponse.md)\\>\n\n#### Inherited from\n\n[`PropertiedEntity`](../../../entity/classes/PropertiedEntity.md).[`updatePropertyOptions`](../../../entity/classes/PropertiedEntity.md#updatepropertyoptions)\n\n***\n\n### version()\n\n> **version**(`version`): [`DocumentVersion`](../../version/classes/DocumentVersion.md)\n\nA handle to an immutable version.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `version` | `number` |\n\n#### Returns\n\n[`DocumentVersion`](../../version/classes/DocumentVersion.md)\n\n***\n\n### webUrl()\n\n> **webUrl**(): `string`\n\nThe document's URL in the Macro web app.\n\n#### Returns\n\n`string`\n\n***\n\n### byId()\n\n> `static` **byId**(`client`, `id`): `Document`\n\nA handle to a document by id. Details load on first access.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `id` | `string` |\n\n#### Returns\n\n`Document`\n\n***\n\n### create()\n\n> `static` **create**(`client`, `opts`): `Promise`\\<`Document`\\>\n\nCreate a markdown document.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `opts` | \\{ `markdown?`: `string`; `name`: `string`; `project?`: [`Project`](../../../projects/project/classes/Project.md); \\} |\n| `opts.markdown?` | `string` |\n| `opts.name` | `string` |\n| `opts.project?` | [`Project`](../../../projects/project/classes/Project.md) |\n\n#### Returns\n\n`Promise`\\<`Document`\\>\n\n***\n\n### createSkill()\n\n> `static` **createSkill**(`client`, `opts`): `Promise`\\<`Document`\\>\n\nCreate a skill: a markdown document containing instructions that AI reads\nand follows when the skill is referenced in an AI input.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `opts` | \\{ `markdown?`: `string`; `name`: `string`; `project?`: [`Project`](../../../projects/project/classes/Project.md); \\} |\n| `opts.markdown?` | `string` |\n| `opts.name` | `string` |\n| `opts.project?` | [`Project`](../../../projects/project/classes/Project.md) |\n\n#### Returns\n\n`Promise`\\<`Document`\\>\n\n***\n\n### createSnippet()\n\n> `static` **createSnippet**(`client`, `opts`): `Promise`\\<`Document`\\>\n\nCreate a snippet: a reusable markdown document that can be inserted into\nany markdown area.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `opts` | \\{ `markdown?`: `string`; `name`: `string`; `project?`: [`Project`](../../../projects/project/classes/Project.md); \\} |\n| `opts.markdown?` | `string` |\n| `opts.name` | `string` |\n| `opts.project?` | [`Project`](../../../projects/project/classes/Project.md) |\n\n#### Returns\n\n`Promise`\\<`Document`\\>\n\n***\n\n### recent()\n\n> `static` **recent**(`client`, `opts?`): `AsyncGenerator`\\<`Document`\\>\n\nThe user's recent documents, most recent first, auto-paginated.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `opts?` | \\{ `fileType?`: `string`; `pageSize?`: `number`; \\} |\n| `opts.fileType?` | `string` |\n| `opts.pageSize?` | `number` |\n\n#### Returns\n\n`AsyncGenerator`\\<`Document`\\>\n\n***\n\n### recentlyDeleted()\n\n> `static` **recentlyDeleted**(`client`): `Promise`\\<`Document`[]\\>\n\nThe user's recently soft-deleted documents. The underlying endpoint also\nreturns deleted chats and projects; those are filtered out here.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n\n#### Returns\n\n`Promise`\\<`Document`[]\\>\n\n\n<!-- src/entities/documents/document/interfaces/CommentThread.md -->\n# Interface: CommentThread\n\nOne of a document's comment threads: its state and its comments.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-comments\"></a> `comments` | [`Comment`](../../comment/classes/Comment.md)[] | The root comment followed by its replies, in order. |\n| <a id=\"property-thread\"></a> `thread` | [`ThreadState`](../../../../../generated/storage/types.gen/type-aliases/ThreadState.md) | The thread state: root id, resolved flag, owner, anchor, timestamps. |\n\n\n<!-- src/entities/documents/namespace/classes/DocumentNamespace.md -->\n# Class: DocumentNamespace\n\n## Constructors\n\n### Constructor\n\n> **new DocumentNamespace**(`client`): `DocumentNamespace`\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n\n#### Returns\n\n`DocumentNamespace`\n\n## Methods\n\n### byId()\n\n> **byId**(`id`): [`Document`](../../document/classes/Document.md)\n\nA handle to a document by id. Details load on first access.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `id` | `string` |\n\n#### Returns\n\n[`Document`](../../document/classes/Document.md)\n\n***\n\n### byTeamSlug()\n\n> **byTeamSlug**(`slug`): `Promise`\\<[`Document`](../../document/classes/Document.md)\\>\n\nResolve a team task reference such as ENG-42.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `slug` | `string` |\n\n#### Returns\n\n`Promise`\\<[`Document`](../../document/classes/Document.md)\\>\n\n***\n\n### create()\n\n> **create**(`opts`): `Promise`\\<[`Document`](../../document/classes/Document.md)\\>\n\nCreate a markdown document.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `opts` | \\{ `markdown?`: `string`; `name`: `string`; `project?`: [`Project`](../../../projects/project/classes/Project.md); \\} |\n| `opts.markdown?` | `string` |\n| `opts.name` | `string` |\n| `opts.project?` | [`Project`](../../../projects/project/classes/Project.md) |\n\n#### Returns\n\n`Promise`\\<[`Document`](../../document/classes/Document.md)\\>\n\n***\n\n### createSkill()\n\n> **createSkill**(`opts`): `Promise`\\<[`Document`](../../document/classes/Document.md)\\>\n\nCreate a skill: markdown instructions that AI reads and follows.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `opts` | \\{ `markdown?`: `string`; `name`: `string`; `project?`: [`Project`](../../../projects/project/classes/Project.md); \\} |\n| `opts.markdown?` | `string` |\n| `opts.name` | `string` |\n| `opts.project?` | [`Project`](../../../projects/project/classes/Project.md) |\n\n#### Returns\n\n`Promise`\\<[`Document`](../../document/classes/Document.md)\\>\n\n***\n\n### createSnippet()\n\n> **createSnippet**(`opts`): `Promise`\\<[`Document`](../../document/classes/Document.md)\\>\n\nCreate a snippet: a reusable markdown document.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `opts` | \\{ `markdown?`: `string`; `name`: `string`; `project?`: [`Project`](../../../projects/project/classes/Project.md); \\} |\n| `opts.markdown?` | `string` |\n| `opts.name` | `string` |\n| `opts.project?` | [`Project`](../../../projects/project/classes/Project.md) |\n\n#### Returns\n\n`Promise`\\<[`Document`](../../document/classes/Document.md)\\>\n\n***\n\n### createUpload()\n\n> **createUpload**(`options`): `Promise`\\<\\{ `content`: [`DocumentContent`](../../../../../generated/storage/types.gen/type-aliases/DocumentContent.md); `contentType`: `string`; `document`: [`Document`](../../document/classes/Document.md); `uploadUrl`: `string` \\| `undefined`; \\}\\>\n\nReserve a binary document and return upload instructions. Upload content before saving.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `options` | \\{ `attachment?`: [`EmailAttachment`](../../../email/attachment/classes/EmailAttachment.md); `branchedFrom?`: [`Document`](../../document/classes/Document.md); `fileType?`: `string`; `isTask?`: `boolean`; `mimeType?`: `string`; `name`: `string`; `project?`: [`Project`](../../../projects/project/classes/Project.md); `sha`: `string`; `team?`: [`Team`](../../../teams/team/classes/Team.md); \\} |\n| `options.attachment?` | [`EmailAttachment`](../../../email/attachment/classes/EmailAttachment.md) |\n| `options.branchedFrom?` | [`Document`](../../document/classes/Document.md) |\n| `options.fileType?` | `string` |\n| `options.isTask?` | `boolean` |\n| `options.mimeType?` | `string` |\n| `options.name` | `string` |\n| `options.project?` | [`Project`](../../../projects/project/classes/Project.md) |\n| `options.sha` | `string` |\n| `options.team?` | [`Team`](../../../teams/team/classes/Team.md) |\n\n#### Returns\n\n`Promise`\\<\\{ `content`: [`DocumentContent`](../../../../../generated/storage/types.gen/type-aliases/DocumentContent.md); `contentType`: `string`; `document`: [`Document`](../../document/classes/Document.md); `uploadUrl`: `string` \\| `undefined`; \\}\\>\n\n***\n\n### recent()\n\n> **recent**(`opts?`): `AsyncGenerator`\\<[`Document`](../../document/classes/Document.md)\\>\n\nThe user's recent documents, most recent first, auto-paginated.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `opts?` | \\{ `fileType?`: `string`; `pageSize?`: `number`; \\} |\n| `opts.fileType?` | `string` |\n| `opts.pageSize?` | `number` |\n\n#### Returns\n\n`AsyncGenerator`\\<[`Document`](../../document/classes/Document.md)\\>\n\n***\n\n### recentlyDeleted()\n\n> **recentlyDeleted**(): `Promise`\\<[`Document`](../../document/classes/Document.md)[]\\>\n\nThe user's recently soft-deleted documents.\n\n#### Returns\n\n`Promise`\\<[`Document`](../../document/classes/Document.md)[]\\>\n\n***\n\n### search()\n\n> **search**(`query`, `opts?`): `AsyncGenerator`\\<[`Document`](../../document/classes/Document.md)\\>\n\nSearch documents by name and content, most relevant first, auto-paginated.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `query` | `string` |\n| `opts?` | [`SearchOpts`](../../../search/interfaces/SearchOpts.md) |\n\n#### Returns\n\n`AsyncGenerator`\\<[`Document`](../../document/classes/Document.md)\\>\n\n***\n\n### systemSkills()\n\n> **systemSkills**(): `Promise`\\<[`SystemSkill`](../../system-skill/classes/SystemSkill.md)[]\\>\n\nThe built-in system skills: static AI instructions with no document\nbehind them. Unlike user skills they cannot be opened or edited.\n\n#### Returns\n\n`Promise`\\<[`SystemSkill`](../../system-skill/classes/SystemSkill.md)[]\\>\n\n***\n\n### validatePermissionsToken()\n\n> **validatePermissionsToken**(`token`): `Promise`\\<\\{ `accessLevel`: [`AccessLevel`](../../../../../generated/storage/types.gen/type-aliases/AccessLevel.md); `document`: [`Document`](../../document/classes/Document.md); `expiresAt`: `number`; `issuer`: `string`; `user`: [`User`](../../../users/user/classes/User.md) \\| `undefined`; \\}\\>\n\nValidate a permissions token, returning its document and optional user handles.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `token` | `string` |\n\n#### Returns\n\n`Promise`\\<\\{ `accessLevel`: [`AccessLevel`](../../../../../generated/storage/types.gen/type-aliases/AccessLevel.md); `document`: [`Document`](../../document/classes/Document.md); `expiresAt`: `number`; `issuer`: `string`; `user`: [`User`](../../../users/user/classes/User.md) \\| `undefined`; \\}\\>\n\n\n<!-- src/entities/documents/system-skill/classes/SystemSkill.md -->\n# Class: SystemSkill\n\nA built-in system skill: static, code-defined AI instructions that surface\nto AI like skill documents but have no document behind them. System skills\ncannot be opened, edited, or deleted; reference them in AI inputs by id the\nsame way as skill documents.\n\n## Properties\n\n| Property | Modifier | Type | Description |\n| ------ | ------ | ------ | ------ |\n| <a id=\"property-id\"></a> `id` | `readonly` | `string` | The well-known id the skill is referenced by in mentions and AI tools. |\n| <a id=\"property-name\"></a> `name` | `readonly` | `string` | The skill's display name. |\n\n## Methods\n\n### list()\n\n> `static` **list**(`client`): `Promise`\\<`SystemSkill`[]\\>\n\nThe built-in system skills, in display order.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n\n#### Returns\n\n`Promise`\\<`SystemSkill`[]\\>\n\n\n<!-- src/entities/documents/version/classes/DocumentVersion.md -->\n# Class: DocumentVersion\n\nAn immutable document version, scoped to its document.\n\n## Properties\n\n| Property | Modifier | Type | Description |\n| ------ | ------ | ------ | ------ |\n| <a id=\"property-document\"></a> `document` | `readonly` | [`Document`](../../document/classes/Document.md) | Parent document. |\n| <a id=\"property-id\"></a> `id` | `readonly` | `number` | Version number. |\n\n## Methods\n\n### read()\n\n> **read**(): `Promise`\\<[`GetDocumentResponseData`](../../../../../generated/storage/types.gen/type-aliases/GetDocumentResponseData.md)\\>\n\nVersion metadata and the caller's access.\n\n#### Returns\n\n`Promise`\\<[`GetDocumentResponseData`](../../../../../generated/storage/types.gen/type-aliases/GetDocumentResponseData.md)\\>\n\n***\n\n### toJSON()\n\n> **toJSON**(): \\{ `documentId`: `string`; `id`: `number`; \\}\n\nSerialize only scoped identity.\n\n#### Returns\n\n\\{ `documentId`: `string`; `id`: `number`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `documentId` | `string` |\n| `id` | `number` |\n\n***\n\n### byId()\n\n> `static` **byId**(`client`, `document`, `id`): `DocumentVersion`\n\nConstruct a version handle.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `document` | [`Document`](../../document/classes/Document.md) |\n| `id` | `number` |\n\n#### Returns\n\n`DocumentVersion`\n"
+ "documentation": "# Macro SDK: documents\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/properties/types.gen/type-aliases/BulkUpdateEntityPropertyOptionsResponse.md -->\n# Type Alias: BulkUpdateEntityPropertyOptionsResponse\n\n> **BulkUpdateEntityPropertyOptionsResponse** = \\{ `properties`: [`EntityPropertyOptionSelectionResponse`](EntityPropertyOptionSelectionResponse.md)[]; \\}\n\nResponse for a bulk option update: each property's reconciled final ids.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-properties\"></a> `properties` | [`EntityPropertyOptionSelectionResponse`](EntityPropertyOptionSelectionResponse.md)[] | The final option ids per updated property. |\n\n\n<!-- generated/properties/types.gen/type-aliases/DataType.md -->\n# Type Alias: DataType\n\n> **DataType** = `\"BOOLEAN\"` \\| `\"DATE\"` \\| `\"NUMBER\"` \\| `\"STRING\"` \\| `\"SELECT_NUMBER\"` \\| `\"SELECT_STRING\"` \\| `\"TAG\"` \\| `\"ENTITY\"` \\| `\"LINK\"`\n\nData type for property values, determining storage and validation.\n\n\n<!-- generated/properties/types.gen/type-aliases/EntityProperty.md -->\n# Type Alias: EntityProperty\n\n> **EntityProperty** = \\{ `created_at`: `string`; `entity_id`: `string`; `entity_type`: [`EntityType`](EntityType.md); `id`: `string`; `property_definition_id`: `string`; `updated_at`: `string`; \\}\n\nAssignment of a property definition to a specific entity (service representation).\n\n## Properties\n\n| Property | Type |\n| ------ | ------ |\n| <a id=\"property-created_at\"></a> `created_at` | `string` |\n| <a id=\"property-entity_id\"></a> `entity_id` | `string` |\n| <a id=\"property-entity_type\"></a> `entity_type` | [`EntityType`](EntityType.md) |\n| <a id=\"property-id\"></a> `id` | `string` |\n| <a id=\"property-property_definition_id\"></a> `property_definition_id` | `string` |\n| <a id=\"property-updated_at\"></a> `updated_at` | `string` |\n\n\n<!-- generated/properties/types.gen/type-aliases/EntityPropertyOptionSelectionResponse.md -->\n# Type Alias: EntityPropertyOptionSelectionResponse\n\n> **EntityPropertyOptionSelectionResponse** = \\{ `option_ids`: `string`[]; `property_id`: `string`; \\}\n\nThe reconciled final option ids stored for one property after a bulk update.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-option_ids\"></a> `option_ids` | `string`[] | The final option ids the server persisted, in stored order. |\n| <a id=\"property-property_id\"></a> `property_id` | `string` | The property definition the options belong to. |\n\n\n<!-- generated/properties/types.gen/type-aliases/EntityPropertyWithDefinition.md -->\n# Type Alias: EntityPropertyWithDefinition\n\n> **EntityPropertyWithDefinition** = \\{ `definition`: [`PropertyDefinition`](PropertyDefinition.md); `options?`: [`PropertyOption`](PropertyOption.md)[] \\| `null`; `property`: [`EntityProperty`](EntityProperty.md); `value?`: `null` \\| [`PropertyValue`](PropertyValue.md); \\}\n\nEntity property with its definition, value, and options (service representation).\n\n## Properties\n\n| Property | Type |\n| ------ | ------ |\n| <a id=\"property-definition\"></a> `definition` | [`PropertyDefinition`](PropertyDefinition.md) |\n| <a id=\"property-options\"></a> `options?` | [`PropertyOption`](PropertyOption.md)[] \\| `null` |\n| <a id=\"property-property\"></a> `property` | [`EntityProperty`](EntityProperty.md) |\n| <a id=\"property-value\"></a> `value?` | `null` \\| [`PropertyValue`](PropertyValue.md) |\n\n\n<!-- generated/properties/types.gen/type-aliases/EntityReference.md -->\n# Type Alias: EntityReference\n\n> **EntityReference** = \\{ `entity_id`: `string`; `entity_type`: [`EntityType`](EntityType.md); `specific_message_id?`: `string` \\| `null`; \\}\n\nEntity reference for entity-type property values.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-entity_id\"></a> `entity_id` | `string` | - |\n| <a id=\"property-entity_type\"></a> `entity_type` | [`EntityType`](EntityType.md) | - |\n| <a id=\"property-specific_message_id\"></a> `specific_message_id?` | `string` \\| `null` | For CHANNEL, CHAT, THREAD entity types - optional specific message ID. This allows referencing a specific message within a thread/channel/chat. |\n\n\n<!-- generated/properties/types.gen/type-aliases/EntityType.md -->\n# Type Alias: EntityType\n\n> **EntityType** = `\"CALENDAR_EVENT\"` \\| `\"CALL_RECORD\"` \\| `\"CHANNEL\"` \\| `\"CHAT\"` \\| `\"COMPANY\"` \\| `\"DATABASE_ROW\"` \\| `\"CONTACT\"` \\| `\"DOCUMENT\"` \\| `\"INITIATIVE\"` \\| `\"PROJECT\"` \\| `\"TASK\"` \\| `\"THREAD\"` \\| `\"USER\"`\n\nType of entity that can be referenced by entity properties.\n\n\n<!-- generated/properties/types.gen/type-aliases/PropertyDefinition.md -->\n# Type Alias: PropertyDefinition\n\n> **PropertyDefinition** = \\{ `created_at`: `string`; `data_type`: [`DataType`](DataType.md); `display_name`: `string`; `id`: `string`; `is_metadata`: `boolean`; `is_multi_select`: `boolean`; `is_system`: `boolean`; `owner`: [`PropertyOwner`](PropertyOwner.md); `specific_entity_type`: `null` \\| [`EntityType`](EntityType.md); `updated_at`: `string`; \\}\n\nProperty definition model (service representation).\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-created_at\"></a> `created_at` | `string` | - |\n| <a id=\"property-data_type\"></a> `data_type` | [`DataType`](DataType.md) | - |\n| <a id=\"property-display_name\"></a> `display_name` | `string` | - |\n| <a id=\"property-id\"></a> `id` | `string` | - |\n| <a id=\"property-is_metadata\"></a> `is_metadata` | `boolean` | Flag to indicate if this is a system-generated metadata property. Not stored in database - computed at service layer. |\n| <a id=\"property-is_multi_select\"></a> `is_multi_select` | `boolean` | - |\n| <a id=\"property-is_system\"></a> `is_system` | `boolean` | Flag to indicate if this is a system property (stored in DB). |\n| <a id=\"property-owner\"></a> `owner` | [`PropertyOwner`](PropertyOwner.md) | - |\n| <a id=\"property-specific_entity_type\"></a> `specific_entity_type` | `null` \\| [`EntityType`](EntityType.md) | - |\n| <a id=\"property-updated_at\"></a> `updated_at` | `string` | - |\n\n\n<!-- generated/properties/types.gen/type-aliases/PropertyOption.md -->\n# Type Alias: PropertyOption\n\n> **PropertyOption** = \\{ `color`: `string` \\| `null`; `created_at`: `string`; `display_order`: `number`; `id`: `string`; `property_definition_id`: `string`; `updated_at`: `string`; `value`: [`PropertyOptionValue`](PropertyOptionValue.md); \\}\n\nA selectable option for select-type properties (service representation).\n\n## Properties\n\n| Property | Type |\n| ------ | ------ |\n| <a id=\"property-color\"></a> `color` | `string` \\| `null` |\n| <a id=\"property-created_at\"></a> `created_at` | `string` |\n| <a id=\"property-display_order\"></a> `display_order` | `number` |\n| <a id=\"property-id\"></a> `id` | `string` |\n| <a id=\"property-property_definition_id\"></a> `property_definition_id` | `string` |\n| <a id=\"property-updated_at\"></a> `updated_at` | `string` |\n| <a id=\"property-value\"></a> `value` | [`PropertyOptionValue`](PropertyOptionValue.md) |\n\n\n<!-- generated/properties/types.gen/type-aliases/PropertyOptionValue.md -->\n# Type Alias: PropertyOptionValue\n\n> **PropertyOptionValue** = \\{ `type`: `\"string\"`; `value`: `string`; \\} \\| \\{ `type`: `\"number\"`; `value`: `number`; \\}\n\nThe value of a property option - either a string or a number.\n\n## Union Members\n\n### Type Literal\n\n\\{ `type`: `\"string\"`; `value`: `string`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `type` | `\"string\"` | - |\n| `value` | `string` | String value for SelectString properties |\n\n***\n\n### Type Literal\n\n\\{ `type`: `\"number\"`; `value`: `number`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `type` | `\"number\"` | - |\n| `value` | `number` | Number value for SelectNumber properties |\n\n\n<!-- generated/properties/types.gen/type-aliases/PropertyOwner.md -->\n# Type Alias: PropertyOwner\n\n> **PropertyOwner** = \\{ `scope`: `\"user\"`; `user_id`: `string`; \\} \\| \\{ `scope`: `\"team\"`; `team_id`: `string`; \\} \\| \\{ `database_id`: `string`; `scope`: `\"database\"`; \\} \\| \\{ `scope`: `\"system\"`; \\}\n\nDefines who owns a property - user-scoped, team-scoped, database-scoped, or system.\n\n\n<!-- generated/properties/types.gen/type-aliases/PropertyTargetEntityType.md -->\n# Type Alias: PropertyTargetEntityType\n\n> **PropertyTargetEntityType** = `\"CALL_RECORD\"` \\| `\"CHANNEL\"` \\| `\"CHAT\"` \\| `\"COMPANY\"` \\| `\"DATABASE_ROW\"` \\| `\"DOCUMENT\"` \\| `\"INITIATIVE\"` \\| `\"PROJECT\"` \\| `\"THREAD\"` \\| `\"USER\"`\n\nCanonical type of an entity receiving properties.\n\nTasks are documents at API boundaries. `Task` intentionally does not exist\nhere; task classification is resolved by the properties domain from the\ndocument subtype.\n\n\n<!-- generated/properties/types.gen/type-aliases/PropertyTargetReference.md -->\n# Type Alias: PropertyTargetReference\n\n> **PropertyTargetReference** = \\{ `entity_id`: `string`; `entity_type`: [`PropertyTargetEntityType`](PropertyTargetEntityType.md); \\}\n\nCanonical reference to an entity receiving properties.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-entity_id\"></a> `entity_id` | `string` | Entity identifier. |\n| <a id=\"property-entity_type\"></a> `entity_type` | [`PropertyTargetEntityType`](PropertyTargetEntityType.md) | Canonical entity type. |\n\n\n<!-- generated/properties/types.gen/type-aliases/PropertyValue.md -->\n# Type Alias: PropertyValue\n\n> **PropertyValue** = \\{ `type`: `\"Boolean\"`; `value`: `boolean`; \\} \\| \\{ `type`: `\"Number\"`; `value`: `number`; \\} \\| \\{ `type`: `\"String\"`; `value`: `string`; \\} \\| \\{ `type`: `\"Date\"`; `value`: `string`; \\} \\| \\{ `type`: `\"SelectOption\"`; `value`: `string`[]; \\} \\| \\{ `type`: `\"EntityReference\"`; `value`: [`EntityReference`](EntityReference.md)[]; \\} \\| \\{ `type`: `\"Link\"`; `value`: `string`[]; \\}\n\nProperty value (service representation).\n\nRepresents the actual value stored for an entity property.\nThis is serialized to/from JSONB in the database.\n\n## Union Members\n\n### Type Literal\n\n\\{ `type`: `\"Boolean\"`; `value`: `boolean`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `type` | `\"Boolean\"` | - |\n| `value` | `boolean` | Boolean value Serializes as: {\"type\": \"Boolean\", \"value\": true} |\n\n***\n\n### Type Literal\n\n\\{ `type`: `\"Number\"`; `value`: `number`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `type` | `\"Number\"` | - |\n| `value` | `number` | Numeric value Serializes as: {\"type\": \"Number\", \"value\": 42.5} |\n\n***\n\n### Type Literal\n\n\\{ `type`: `\"String\"`; `value`: `string`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `type` | `\"String\"` | - |\n| `value` | `string` | String value Serializes as: {\"type\": \"String\", \"value\": \"text\"} |\n\n***\n\n### Type Literal\n\n\\{ `type`: `\"Date\"`; `value`: `string`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `type` | `\"Date\"` | - |\n| `value` | `string` | Date/timestamp value Serializes as: {\"type\": \"Date\", \"value\": \"2025-01-01T00:00:00Z\"} |\n\n***\n\n### Type Literal\n\n\\{ `type`: `\"SelectOption\"`; `value`: `string`[]; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `type` | `\"SelectOption\"` | - |\n| `value` | `string`[] | Select option(s) - always an array (check is_multi_select to determine if single or multi) Single-select: {\"type\": \"SelectOption\", \"value\": [\"uuid\"]} (length 0 or 1) Multi-select: {\"type\": \"SelectOption\", \"value\": [\"uuid1\", \"uuid2\", ...]} (length 0+) |\n\n***\n\n### Type Literal\n\n\\{ `type`: `\"EntityReference\"`; `value`: [`EntityReference`](EntityReference.md)[]; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `type` | `\"EntityReference\"` | - |\n| `value` | [`EntityReference`](EntityReference.md)[] | Entity reference(s) - always an array (check is_multi_select to determine if single or multi) Single-select: {\"type\": \"EntityReference\", \"value\": [{...}]} (length 0 or 1) Multi-select: {\"type\": \"EntityReference\", \"value\": [{...}, {...}, ...]} (length 0+) |\n\n***\n\n### Type Literal\n\n\\{ `type`: `\"Link\"`; `value`: `string`[]; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `type` | `\"Link\"` | - |\n| `value` | `string`[] | Link value(s) - always an array (check is_multi_select to determine if single or multi) Single-select: {\"type\": \"Link\", \"value\": [\"https://example.com\"]} (length 0 or 1) Multi-select: {\"type\": \"Link\", \"value\": [\"https://example.com\", \"https://other.com\"]} (length 0+) |\n\n\n<!-- generated/properties/types.gen/type-aliases/SetPropertyValue.md -->\n# Type Alias: SetPropertyValue\n\n> **SetPropertyValue** = \\{ `type`: `\"boolean\"`; `value`: `boolean`; \\} \\| \\{ `type`: `\"date\"`; `value`: `string`; \\} \\| \\{ `type`: `\"number\"`; `value`: `number`; \\} \\| \\{ `type`: `\"string\"`; `value`: `string`; \\} \\| \\{ `option_id`: `string`; `type`: `\"select_option\"`; \\} \\| \\{ `option_ids`: `string`[]; `type`: `\"multi_select_option\"`; \\} \\| \\{ `reference`: [`EntityReference`](EntityReference.md); `type`: `\"entity_reference\"`; \\} \\| \\{ `references`: [`EntityReference`](EntityReference.md)[]; `type`: `\"multi_entity_reference\"`; \\} \\| \\{ `type`: `\"link\"`; `url`: `string`; \\} \\| \\{ `type`: `\"multi_link\"`; `urls`: `string`[]; \\}\n\nType-safe enum for setting entity property values - provides compile-time validation.\n\n\n<!-- generated/storage/types.gen/type-aliases/AccessLevel.md -->\n# Type Alias: AccessLevel\n\n> **AccessLevel** = `\"view\"` \\| `\"comment\"` \\| `\"edit\"` \\| `\"owner\"`\n\nOrdered from least to most access top -> bottom\n\n\n<!-- generated/storage/types.gen/type-aliases/Anchor.md -->\n# Type Alias: Anchor\n\n> **Anchor** = [`PdfAnchor`](PdfAnchor.md)\n\n\n<!-- generated/storage/types.gen/type-aliases/BomPart.md -->\n# Type Alias: BomPart\n\n> **BomPart** = \\{ `id`: `string`; `path`: `string`; `sha`: `string`; \\}\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-id\"></a> `id` | `string` | The uuid of the bom part |\n| <a id=\"property-path\"></a> `path` | `string` | The file path of the bom part content |\n| <a id=\"property-sha\"></a> `sha` | `string` | The sha of the bom part content There is an index on sha for more performant queries based on it. |\n\n\n<!-- generated/storage/types.gen/type-aliases/BotSenderProfile.md -->\n# Type Alias: BotSenderProfile\n\n> **BotSenderProfile** = \\{ `avatar_url?`: `string` \\| `null`; `name`: `string`; \\}\n\nPublic bot profile attached to bot-authored messages.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-avatar_url\"></a> `avatar_url?` | `string` \\| `null` | Bot avatar URL. |\n| <a id=\"property-name\"></a> `name` | `string` | Bot display name. |\n\n\n<!-- generated/storage/types.gen/type-aliases/ChannelSharePermission.md -->\n# Type Alias: ChannelSharePermission\n\n> **ChannelSharePermission** = \\{ `access_level`: [`AccessLevel`](AccessLevel.md); `channel_id`: `string`; \\}\n\nThe channel share permission\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-access_level\"></a> `access_level` | [`AccessLevel`](AccessLevel.md) | The access level for the channel |\n| <a id=\"property-channel_id\"></a> `channel_id` | `string` | The channel id |\n\n\n<!-- generated/storage/types.gen/type-aliases/CountedReaction.md -->\n# Type Alias: CountedReaction\n\n> **CountedReaction** = \\{ `emoji`: `string`; `users`: `string`[]; \\}\n\nReaction emoji and the users who added it.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-emoji\"></a> `emoji` | `string` | Emoji being reacted with. |\n| <a id=\"property-users\"></a> `users` | `string`[] | User identifiers. |\n\n\n<!-- generated/storage/types.gen/type-aliases/DocumentContent.md -->\n# Type Alias: DocumentContent\n\n> **DocumentContent** = \\{ `location?`: `null` \\| [`DocumentContentLocation`](DocumentContentLocation.md); `state`: [`DocumentContentState`](DocumentContentState.md); \\}\n\nAPI-visible content lifecycle and location metadata.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-location\"></a> `location?` | `null` \\| [`DocumentContentLocation`](DocumentContentLocation.md) | - |\n| <a id=\"property-state\"></a> `state` | [`DocumentContentState`](DocumentContentState.md) | The current lifecycle state of the content. |\n\n\n<!-- generated/storage/types.gen/type-aliases/DocumentContentLocation.md -->\n# Type Alias: DocumentContentLocation\n\n> **DocumentContentLocation** = `\"object_storage\"` \\| `\"sync_service\"` \\| `\"docx_bom_parts\"` \\| `\"converted_pdf\"` \\| `\"unknown\"`\n\nWhere document content is, or is expected to be, read from.\n\n\n<!-- generated/storage/types.gen/type-aliases/DocumentContentState.md -->\n# Type Alias: DocumentContentState\n\n> **DocumentContentState** = `\"unknown\"` \\| `\"pending\"` \\| `\"ready\"`\n\nAPI-visible content lifecycle state derived from current document metadata.\n\n\n<!-- generated/storage/types.gen/type-aliases/DocumentId.md -->\n# Type Alias: DocumentId\n\n> **DocumentId** = `string`\n\nA validated document identifier. Historical document ids need not be UUIDs.\n\n\n<!-- generated/storage/types.gen/type-aliases/DocumentMetadata.md -->\n# Type Alias: DocumentMetadata\n\n> **DocumentMetadata** = \\{ `branchedFromId?`: `string` \\| `null`; `branchedFromVersionId?`: `number` \\| `null`; `createdAt?`: `string` \\| `null`; `deletedAt?`: `string` \\| `null`; `documentBom?`: [`BomPart`](BomPart.md)[] \\| `null`; `documentFamilyId?`: `number` \\| `null`; `documentId`: `string`; `documentName`: `string`; `documentVersionId`: `number`; `fileType?`: `string` \\| `null`; `modificationData?`: `unknown`; `owner`: `string`; `projectId?`: `string` \\| `null`; `projectName?`: `string` \\| `null`; `sha?`: `string` \\| `null`; `subType?`: `null` \\| [`DocumentSubType`](DocumentSubType.md); `updatedAt?`: `string` \\| `null`; \\}\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-branchedfromid\"></a> `branchedFromId?` | `string` \\| `null` | The id of the document this document branched from |\n| <a id=\"property-branchedfromversionid\"></a> `branchedFromVersionId?` | `number` \\| `null` | The id of the version this document branched from This could be either DocumentInstance or DocumentBom id depending on the file type |\n| <a id=\"property-createdat\"></a> `createdAt?` | `string` \\| `null` | The time the document was created |\n| <a id=\"property-deletedat\"></a> `deletedAt?` | `string` \\| `null` | The time the document was deleted |\n| <a id=\"property-documentbom\"></a> `documentBom?` | [`BomPart`](BomPart.md)[] \\| `null` | If the document is a DOCX document and unzipped, the document_bom will be present |\n| <a id=\"property-documentfamilyid\"></a> `documentFamilyId?` | `number` \\| `null` | The id of the document family this document belongs to |\n| <a id=\"property-documentid\"></a> `documentId` | `string` | The document id |\n| <a id=\"property-documentname\"></a> `documentName` | `string` | The name of the document |\n| <a id=\"property-documentversionid\"></a> `documentVersionId` | `number` | The version of the document This could be the document_instance_id or document_bom_id depending on the file type |\n| <a id=\"property-filetype\"></a> `fileType?` | `string` \\| `null` | The file type of the document (file extension) |\n| <a id=\"property-modificationdata\"></a> `modificationData?` | `unknown` | The modification data for the document instance. This is only used for PDF documents. |\n| <a id=\"property-owner\"></a> `owner` | `string` | The owner of the document |\n| <a id=\"property-projectid\"></a> `projectId?` | `string` \\| `null` | The id of the project that this document belongs to |\n| <a id=\"property-projectname\"></a> `projectName?` | `string` \\| `null` | The name of the project that this document belongs to |\n| <a id=\"property-sha\"></a> `sha?` | `string` \\| `null` | If the document is a PDF, this is the SHA of the pdf If the document is a DOCX, this will not be present |\n| <a id=\"property-subtype\"></a> `subType?` | `null` \\| [`DocumentSubType`](DocumentSubType.md) | - |\n| <a id=\"property-updatedat\"></a> `updatedAt?` | `string` \\| `null` | The time the document instance / document BOM was updated |\n\n\n<!-- generated/storage/types.gen/type-aliases/DocumentMetadataWithContent.md -->\n# Type Alias: DocumentMetadataWithContent\n\n> **DocumentMetadataWithContent** = [`DocumentMetadata`](DocumentMetadata.md) & \\{ `content`: [`DocumentContent`](DocumentContent.md); `teamId?`: `string` \\| `null`; `teamTaskId?`: `number` \\| `null`; \\}\n\nFull document metadata plus content lifecycle metadata.\n\n## Type Declaration\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `content` | [`DocumentContent`](DocumentContent.md) | Content lifecycle and location metadata. |\n| `teamId?` | `string` \\| `null` | The team this task number is scoped to, for task documents. |\n| `teamTaskId?` | `number` \\| `null` | The task number assigned within the team, for task documents. |\n\n\n<!-- generated/storage/types.gen/type-aliases/DocumentResponseMetadata.md -->\n# Type Alias: DocumentResponseMetadata\n\n> **DocumentResponseMetadata** = \\{ `branchedFromId?`: `string` \\| `null`; `branchedFromVersionId?`: `number` \\| `null`; `createdAt?`: `string` \\| `null`; `documentBom?`: [`BomPart`](BomPart.md)[] \\| `null`; `documentFamilyId?`: `number` \\| `null`; `documentId`: `string`; `documentName`: `string`; `documentVersionId`: `number`; `fileType?`: `string` \\| `null`; `modificationData?`: `unknown`; `owner`: `string`; `sha?`: `string` \\| `null`; `subType?`: `null` \\| [`DocumentSubType`](DocumentSubType.md); `updatedAt?`: `string` \\| `null`; \\}\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-branchedfromid\"></a> `branchedFromId?` | `string` \\| `null` | The id of the document this document branched from |\n| <a id=\"property-branchedfromversionid\"></a> `branchedFromVersionId?` | `number` \\| `null` | The id of the version this document branched from This could be either DocumentInstance or DocumentBom id depending on the file type |\n| <a id=\"property-createdat\"></a> `createdAt?` | `string` \\| `null` | The time the document was created |\n| <a id=\"property-documentbom\"></a> `documentBom?` | [`BomPart`](BomPart.md)[] \\| `null` | If the document is a DOCX document, the document_bom will be present |\n| <a id=\"property-documentfamilyid\"></a> `documentFamilyId?` | `number` \\| `null` | The id of the document family this document belongs to |\n| <a id=\"property-documentid\"></a> `documentId` | `string` | The document id |\n| <a id=\"property-documentname\"></a> `documentName` | `string` | The name of the document |\n| <a id=\"property-documentversionid\"></a> `documentVersionId` | `number` | The version of the document This could be the document_instance_id or document_bom_id depending on the file type |\n| <a id=\"property-filetype\"></a> `fileType?` | `string` \\| `null` | The file type of the document |\n| <a id=\"property-modificationdata\"></a> `modificationData?` | `unknown` | The modification data for the document instance. This is only used for PDF documents. |\n| <a id=\"property-owner\"></a> `owner` | `string` | The owner of the document |\n| <a id=\"property-sha\"></a> `sha?` | `string` \\| `null` | If the document is a PDF, this is the SHA of the pdf If the document is a DOCX, this will not be present |\n| <a id=\"property-subtype\"></a> `subType?` | `null` \\| [`DocumentSubType`](DocumentSubType.md) | - |\n| <a id=\"property-updatedat\"></a> `updatedAt?` | `string` \\| `null` | The time the document instance / document BOM was updated |\n\n\n<!-- generated/storage/types.gen/type-aliases/DocumentSubType.md -->\n# Type Alias: DocumentSubType\n\n> **DocumentSubType** = `\"task\"` \\| `\"snippet\"` \\| `\"skill\"` \\| `\"initiative_description\"`\n\nThe document sub type enum represents all values of document sub types.\nThese values should match the `document_sub_type_value` table in macrodb.\n\nWire, database, and `Display` spellings are all `snake_case` so a\nmulti-word variant serializes identically in every system.\n\n\n<!-- generated/storage/types.gen/type-aliases/DocumentTeamShareResponse.md -->\n# Type Alias: DocumentTeamShareResponse\n\n> **DocumentTeamShareResponse** = \\{ `sharedWithTeam`: `boolean`; `teamId?`: `string` \\| `null`; \\}\n\nThe team-share state of a document. The team is resolved from the document\nowner's team membership.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-sharedwithteam\"></a> `sharedWithTeam` | `boolean` | Whether explicit team sharing is enabled; inherited team access does not count. |\n| <a id=\"property-teamid\"></a> `teamId?` | `string` \\| `null` | The owner's team the document is (or would be) shared with. `None` when the owner does not belong to a team. |\n\n\n<!-- generated/storage/types.gen/type-aliases/EditPdfPlaceableCommentAnchorRequest.md -->\n# Type Alias: EditPdfPlaceableCommentAnchorRequest\n\n> **EditPdfPlaceableCommentAnchorRequest** = \\{ `allowableEdits?`: `unknown`; `heightPct?`: `number` \\| `null`; `originalIndex?`: `number` \\| `null`; `originalPage?`: `number` \\| `null`; `page?`: `number` \\| `null`; `rotation?`: `number` \\| `null`; `shouldLockOnSave?`: `boolean` \\| `null`; `uuid`: `string`; `wasDeleted?`: `boolean` \\| `null`; `wasEdited?`: `boolean` \\| `null`; `widthPct?`: `number` \\| `null`; `xPct?`: `number` \\| `null`; `yPct?`: `number` \\| `null`; \\}\n\n## Properties\n\n| Property | Type |\n| ------ | ------ |\n| <a id=\"property-allowableedits\"></a> `allowableEdits?` | `unknown` |\n| <a id=\"property-heightpct\"></a> `heightPct?` | `number` \\| `null` |\n| <a id=\"property-originalindex\"></a> `originalIndex?` | `number` \\| `null` |\n| <a id=\"property-originalpage\"></a> `originalPage?` | `number` \\| `null` |\n| <a id=\"property-page\"></a> `page?` | `number` \\| `null` |\n| <a id=\"property-rotation\"></a> `rotation?` | `number` \\| `null` |\n| <a id=\"property-shouldlockonsave\"></a> `shouldLockOnSave?` | `boolean` \\| `null` |\n| <a id=\"property-uuid\"></a> `uuid` | `string` |\n| <a id=\"property-wasdeleted\"></a> `wasDeleted?` | `boolean` \\| `null` |\n| <a id=\"property-wasedited\"></a> `wasEdited?` | `boolean` \\| `null` |\n| <a id=\"property-widthpct\"></a> `widthPct?` | `number` \\| `null` |\n| <a id=\"property-xpct\"></a> `xPct?` | `number` \\| `null` |\n| <a id=\"property-ypct\"></a> `yPct?` | `number` \\| `null` |\n\n\n<!-- generated/storage/types.gen/type-aliases/EntityPermission.md -->\n# Type Alias: EntityPermission\n\n> **EntityPermission** = \\{ `access_level`: [`AccessLevel`](AccessLevel.md); `type`: `\"access_level\"`; \\} \\| \\{ `type`: `\"channel_view_only\"`; \\} \\| \\{ `role`: [`ParticipantRole`](ParticipantRole.md); `type`: `\"channel_role\"`; \\} \\| \\{ `role`: [`TeamRole`](TeamRole.md); `type`: `\"team_role\"`; \\}\n\nA user's permission for an entity, discriminated by entity kind.\n\nItems (documents, chats, projects, threads) use access levels.\nChannels use view-only permission or participant roles.\n\n## Union Members\n\n### Type Literal\n\n\\{ `access_level`: [`AccessLevel`](AccessLevel.md); `type`: `\"access_level\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `access_level` | [`AccessLevel`](AccessLevel.md) | The access level the user has. |\n| `type` | `\"access_level\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `type`: `\"channel_view_only\"`; \\}\n\n***\n\n### Type Literal\n\n\\{ `role`: [`ParticipantRole`](ParticipantRole.md); `type`: `\"channel_role\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `role` | [`ParticipantRole`](ParticipantRole.md) | The role the user has in the channel. |\n| `type` | `\"channel_role\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `role`: [`TeamRole`](TeamRole.md); `type`: `\"team_role\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `role` | [`TeamRole`](TeamRole.md) | The role the user has in the team. |\n| `type` | `\"team_role\"` | - |\n\n\n<!-- generated/storage/types.gen/type-aliases/GetDocumentResponseData.md -->\n# Type Alias: GetDocumentResponseData\n\n> **GetDocumentResponseData** = \\{ `documentMetadata`: [`DocumentMetadata`](DocumentMetadata.md); `userAccessLevel`: [`AccessLevel`](AccessLevel.md); `viewLocation?`: `string` \\| `null`; \\}\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-documentmetadata\"></a> `documentMetadata` | [`DocumentMetadata`](DocumentMetadata.md) | The metadata of the document |\n| <a id=\"property-useraccesslevel\"></a> `userAccessLevel` | [`AccessLevel`](AccessLevel.md) | The users level of access to the document |\n| <a id=\"property-viewlocation\"></a> `viewLocation?` | `string` \\| `null` | The users view location if there is one |\n\n\n<!-- generated/storage/types.gen/type-aliases/GithubPullRequest.md -->\n# Type Alias: GithubPullRequest\n\n> **GithubPullRequest** = \\{ `additions?`: `number` \\| `null`; `checks?`: [`GithubPullRequestCheckRun`](GithubPullRequestCheckRun.md)[] \\| `null`; `comments?`: [`GithubPullRequestComment`](GithubPullRequestComment.md)[] \\| `null`; `deletions?`: `number` \\| `null`; `displayName`: `string`; `foreignEntityId?`: `string` \\| `null`; `githubKey`: `string`; `name?`: `string` \\| `null`; `number`: `number`; `owner`: `string`; `repo`: `string`; `status?`: `string` \\| `null`; `url`: `string`; \\}\n\nDisplay-ready data for a GitHub pull request associated with a task.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-additions\"></a> `additions?` | `number` \\| `null` | The number of added lines in the pull request, when enrichment data is available. |\n| <a id=\"property-checks\"></a> `checks?` | [`GithubPullRequestCheckRun`](GithubPullRequestCheckRun.md)[] \\| `null` | Check runs collected from the pull request head commit, when enrichment data is available. |\n| <a id=\"property-comments\"></a> `comments?` | [`GithubPullRequestComment`](GithubPullRequestComment.md)[] \\| `null` | Comments collected from the pull request, when enrichment data is available. |\n| <a id=\"property-deletions\"></a> `deletions?` | `number` \\| `null` | The number of deleted lines in the pull request, when enrichment data is available. |\n| <a id=\"property-displayname\"></a> `displayName` | `string` | A compact label suitable for display in the UI. |\n| <a id=\"property-foreignentityid\"></a> `foreignEntityId?` | `string` \\| `null` | The internal `foreign_entity.id` UUID for the GitHub pull request row. |\n| <a id=\"property-githubkey\"></a> `githubKey` | `string` | The stored GitHub association key, in `owner/repo/pull/number` format. |\n| <a id=\"property-name\"></a> `name?` | `string` \\| `null` | The GitHub pull request title, when enrichment data is available. |\n| <a id=\"property-number\"></a> `number` | `number` | The GitHub pull request number. |\n| <a id=\"property-owner\"></a> `owner` | `string` | The GitHub repository owner or organization. |\n| <a id=\"property-repo\"></a> `repo` | `string` | The GitHub repository name. |\n| <a id=\"property-status\"></a> `status?` | `string` \\| `null` | The GitHub pull request status, when enrichment data is available. |\n| <a id=\"property-url\"></a> `url` | `string` | The public GitHub URL for the pull request. |\n\n\n<!-- generated/storage/types.gen/type-aliases/GithubPullRequestCheckRun.md -->\n# Type Alias: GithubPullRequestCheckRun\n\n> **GithubPullRequestCheckRun** = \\{ `completedAt?`: `string` \\| `null`; `conclusion?`: `string` \\| `null`; `id`: `number`; `name`: `string`; `startedAt?`: `string` \\| `null`; `status`: `string`; `url?`: `string` \\| `null`; \\}\n\nA check run associated with a GitHub pull request.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-completedat\"></a> `completedAt?` | `string` \\| `null` | When the check run completed, when available. |\n| <a id=\"property-conclusion\"></a> `conclusion?` | `string` \\| `null` | The raw GitHub check run conclusion, when the run has completed. |\n| <a id=\"property-id\"></a> `id` | `number` | The unique GitHub identifier for the check run. |\n| <a id=\"property-name\"></a> `name` | `string` | The check run name. |\n| <a id=\"property-startedat\"></a> `startedAt?` | `string` \\| `null` | When the check run started, when available. |\n| <a id=\"property-status\"></a> `status` | `string` | The raw GitHub check run status. |\n| <a id=\"property-url\"></a> `url?` | `string` \\| `null` | The public GitHub URL for the check run, when available. |\n\n\n<!-- generated/storage/types.gen/type-aliases/GithubPullRequestComment.md -->\n# Type Alias: GithubPullRequestComment\n\n> **GithubPullRequestComment** = \\{ `authorAssociation?`: `string` \\| `null`; `authorId?`: `number` \\| `null`; `authorLogin?`: `string` \\| `null`; `body`: `string`; `createdAt?`: `string` \\| `null`; `id`: `number`; `inReplyToId?`: `number` \\| `null`; `line?`: `number` \\| `null`; `originalLine?`: `number` \\| `null`; `path?`: `string` \\| `null`; `pullRequestReviewId?`: `number` \\| `null`; `source`: `string`; `updatedAt?`: `string` \\| `null`; `url?`: `string` \\| `null`; \\}\n\nA comment associated with a GitHub pull request.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-authorassociation\"></a> `authorAssociation?` | `string` \\| `null` | GitHub's relationship label for the author, when available. |\n| <a id=\"property-authorid\"></a> `authorId?` | `number` \\| `null` | The stable numeric GitHub user id for the comment author, when available. |\n| <a id=\"property-authorlogin\"></a> `authorLogin?` | `string` \\| `null` | The GitHub login for the comment author, when available. |\n| <a id=\"property-body\"></a> `body` | `string` | The comment or review body text. |\n| <a id=\"property-createdat\"></a> `createdAt?` | `string` \\| `null` | When the comment was created or the review was submitted. |\n| <a id=\"property-id\"></a> `id` | `number` | The unique GitHub identifier for the comment or review. |\n| <a id=\"property-inreplytoid\"></a> `inReplyToId?` | `number` \\| `null` | The id of the comment this one replies to, when it is part of a review thread. Only ever present on `review_comment` sources. |\n| <a id=\"property-line\"></a> `line?` | `number` \\| `null` | The line in the current diff the comment is anchored to. Cleared by GitHub when later commits outdate the comment's diff. |\n| <a id=\"property-originalline\"></a> `originalLine?` | `number` \\| `null` | The line the comment was originally anchored to, kept even when the diff has since changed. |\n| <a id=\"property-path\"></a> `path?` | `string` \\| `null` | The repository-relative file path the review comment is anchored to. Only ever present on `review_comment` sources. |\n| <a id=\"property-pullrequestreviewid\"></a> `pullRequestReviewId?` | `number` \\| `null` | The id of the pull request review this comment was submitted with. Only ever present on `review_comment` sources. |\n| <a id=\"property-source\"></a> `source` | `string` | The GitHub source for the comment, such as `issue_comment` or `review_comment`. |\n| <a id=\"property-updatedat\"></a> `updatedAt?` | `string` \\| `null` | When the comment or review was last updated. |\n| <a id=\"property-url\"></a> `url?` | `string` \\| `null` | The public GitHub URL for the comment or review, when available. |\n\n\n<!-- generated/storage/types.gen/type-aliases/HighlightType.md -->\n# Type Alias: HighlightType\n\n> **HighlightType** = `1` \\| `2` \\| `3`\n\n\n<!-- generated/storage/types.gen/type-aliases/ImportedAuthor.md -->\n# Type Alias: ImportedAuthor\n\n> **ImportedAuthor** = \\{ `name`: `string`; \\}\n\nDisplay attribution for a comment imported from an external document.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-name\"></a> `name` | `string` | Original author text; never interpreted as an authenticated principal. |\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkShare.md -->\n# Type Alias: LinkShare\n\n> **LinkShare** = `\"PUBLIC\"` \\| `\"TEAM\"`\n\nDefines who can access an item through its share link.\n\n\n<!-- generated/storage/types.gen/type-aliases/Message.md -->\n# Type Alias: Message\n\n> **Message** = \\{ `attachments`: [`MessageAttachment`](MessageAttachment.md)[]; `bot_profile?`: `null` \\| [`BotSenderProfile`](BotSenderProfile.md); `content`: `string`; `created_at`: `string`; `deleted_at?`: `string` \\| `null`; `edited_at?`: `string` \\| `null`; `guest_name?`: `string` \\| `null`; `id`: `string`; `imported_author?`: `null` \\| [`ImportedAuthor`](ImportedAuthor.md); `mentions`: [`SimpleMention`](SimpleMention.md)[]; `parent`: [`MessageParent`](MessageParent.md); `reactions`: [`CountedReaction`](CountedReaction.md)[]; `sender_id`: `string`; `thread_id?`: `string` \\| `null`; `triggered_by?`: `string` \\| `null`; `updated_at`: `string`; \\}\n\nShared message representation for channel timelines and entity discussions.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-attachments\"></a> `attachments` | [`MessageAttachment`](MessageAttachment.md)[] | Attached entities. |\n| <a id=\"property-bot_profile\"></a> `bot_profile?` | `null` \\| [`BotSenderProfile`](BotSenderProfile.md) | - |\n| <a id=\"property-content\"></a> `content` | `string` | Macro Markdown body. |\n| <a id=\"property-created_at\"></a> `created_at` | `string` | Creation time. |\n| <a id=\"property-deleted_at\"></a> `deleted_at?` | `string` \\| `null` | Message tombstone, independent of thread deletion. |\n| <a id=\"property-edited_at\"></a> `edited_at?` | `string` \\| `null` | Last content edit, if any. |\n| <a id=\"property-guest_name\"></a> `guest_name?` | `string` \\| `null` | Display name of a verified call guest, retained after the call ends. |\n| <a id=\"property-id\"></a> `id` | `string` | Message UUID. |\n| <a id=\"property-imported_author\"></a> `imported_author?` | `null` \\| [`ImportedAuthor`](ImportedAuthor.md) | - |\n| <a id=\"property-mentions\"></a> `mentions` | [`SimpleMention`](SimpleMention.md)[] | Tracked mentions, retained when a caller changes attachments only. |\n| <a id=\"property-parent\"></a> `parent` | [`MessageParent`](MessageParent.md) | Entity that owns this conversation. |\n| <a id=\"property-reactions\"></a> `reactions` | [`CountedReaction`](CountedReaction.md)[] | Aggregated reactions. |\n| <a id=\"property-sender_id\"></a> `sender_id` | `string` | Authenticated actor or owner of imported content. |\n| <a id=\"property-thread_id\"></a> `thread_id?` | `string` \\| `null` | Root message UUID for replies; absent on roots. |\n| <a id=\"property-triggered_by\"></a> `triggered_by?` | `string` \\| `null` | User who triggered a bot-authored message. |\n| <a id=\"property-updated_at\"></a> `updated_at` | `string` | Last persisted update. |\n\n\n<!-- generated/storage/types.gen/type-aliases/MessageAttachment.md -->\n# Type Alias: MessageAttachment\n\n> **MessageAttachment** = \\{ `created_at`: `string`; `entity_id`: `string`; `entity_type`: `string`; `height?`: `number` \\| `null`; `id`: `string`; `width?`: `number` \\| `null`; \\}\n\nAn entity attached to a message.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-created_at\"></a> `created_at` | `string` | When the attachment was added. |\n| <a id=\"property-entity_id\"></a> `entity_id` | `string` | Attached entity identifier. |\n| <a id=\"property-entity_type\"></a> `entity_type` | `string` | Attached entity type. |\n| <a id=\"property-height\"></a> `height?` | `number` \\| `null` | Optional media height. |\n| <a id=\"property-id\"></a> `id` | `string` | Attachment UUID. |\n| <a id=\"property-width\"></a> `width?` | `number` \\| `null` | Optional media width. |\n\n\n<!-- generated/storage/types.gen/type-aliases/MessageCursor.md -->\n# Type Alias: MessageCursor\n\n> **MessageCursor** = \\{ `created_at`: `string`; `id`: `string`; \\}\n\nCursor for a chronological parent timeline.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-created_at\"></a> `created_at` | `string` | Last message creation time or activity occurrence time. |\n| <a id=\"property-id\"></a> `id` | `string` | Last entry UUID, used to break timestamp ties across both sources. |\n\n\n<!-- generated/storage/types.gen/type-aliases/MessageParent.md -->\n# Type Alias: MessageParent\n\n> **MessageParent** = \\{ `id`: `string`; `type`: `\"channel\"`; \\} \\| \\{ `id`: [`DocumentId`](DocumentId.md); `type`: `\"document\"`; \\} \\| \\{ `id`: `string`; `type`: `\"initiative\"`; \\} \\| \\{ `id`: `string`; `type`: `\"crm_company\"`; \\} \\| \\{ `id`: `string`; `type`: `\"crm_contact\"`; \\} \\| \\{ `id`: `string`; `type`: `\"call\"`; \\}\n\nThe entity whose permissions and lifecycle govern a message.\n\n## Union Members\n\n### Type Literal\n\n\\{ `id`: `string`; `type`: `\"channel\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `id` | `string` | A channel, including direct messages. |\n| `type` | `\"channel\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `id`: [`DocumentId`](DocumentId.md); `type`: `\"document\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `id` | [`DocumentId`](DocumentId.md) | A document, including tasks and PDFs. |\n| `type` | `\"document\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `id`: `string`; `type`: `\"initiative\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `id` | `string` | An initiative, presented as a project in the application. |\n| `type` | `\"initiative\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `id`: `string`; `type`: `\"crm_company\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `id` | `string` | A CRM company. |\n| `type` | `\"crm_company\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `id`: `string`; `type`: `\"crm_contact\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `id` | `string` | A CRM contact. |\n| `type` | `\"crm_contact\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `id`: `string`; `type`: `\"call\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `id` | `string` | A video call and its persistent chat thread. |\n| `type` | `\"call\"` | - |\n\n\n<!-- generated/storage/types.gen/type-aliases/ParticipantRole.md -->\n# Type Alias: ParticipantRole\n\n> **ParticipantRole** = `\"owner\"` \\| `\"admin\"` \\| `\"member\"`\n\nThe role a user has within a channel.\n\n\n<!-- generated/storage/types.gen/type-aliases/PdfAnchor.md -->\n# Type Alias: PdfAnchor\n\n> **PdfAnchor** = [`PdfPlaceableCommentAnchor`](PdfPlaceableCommentAnchor.md) & \\{ `anchorType`: `\"placeable\"`; \\} \\| [`PdfHighlightAnchor`](PdfHighlightAnchor.md) & \\{ `anchorType`: `\"highlight\"`; \\}\n\n\n<!-- generated/storage/types.gen/type-aliases/PdfHighlightAnchor.md -->\n# Type Alias: PdfHighlightAnchor\n\n> **PdfHighlightAnchor** = \\{ `alpha`: `number`; `blue`: `number`; `createdAt?`: `string` \\| `null`; `deletedAt?`: `string` \\| `null`; `documentId`: `string`; `green`: `number`; `highlightRects`: [`PdfHighlightRect`](PdfHighlightRect.md)[]; `highlightType`: [`HighlightType`](HighlightType.md); `owner`: `string`; `page`: `number`; `pageViewportHeight`: `number`; `pageViewportWidth`: `number`; `red`: `number`; `rootId?`: `string` \\| `null`; `text`: `string`; `updatedAt?`: `string` \\| `null`; `uuid`: `string`; \\}\n\n## Properties\n\n| Property | Type |\n| ------ | ------ |\n| <a id=\"property-alpha\"></a> `alpha` | `number` |\n| <a id=\"property-blue\"></a> `blue` | `number` |\n| <a id=\"property-createdat\"></a> `createdAt?` | `string` \\| `null` |\n| <a id=\"property-deletedat\"></a> `deletedAt?` | `string` \\| `null` |\n| <a id=\"property-documentid\"></a> `documentId` | `string` |\n| <a id=\"property-green\"></a> `green` | `number` |\n| <a id=\"property-highlightrects\"></a> `highlightRects` | [`PdfHighlightRect`](PdfHighlightRect.md)[] |\n| <a id=\"property-highlighttype\"></a> `highlightType` | [`HighlightType`](HighlightType.md) |\n| <a id=\"property-owner\"></a> `owner` | `string` |\n| <a id=\"property-page\"></a> `page` | `number` |\n| <a id=\"property-pageviewportheight\"></a> `pageViewportHeight` | `number` |\n| <a id=\"property-pageviewportwidth\"></a> `pageViewportWidth` | `number` |\n| <a id=\"property-red\"></a> `red` | `number` |\n| <a id=\"property-rootid\"></a> `rootId?` | `string` \\| `null` |\n| <a id=\"property-text\"></a> `text` | `string` |\n| <a id=\"property-updatedat\"></a> `updatedAt?` | `string` \\| `null` |\n| <a id=\"property-uuid\"></a> `uuid` | `string` |\n\n\n<!-- generated/storage/types.gen/type-aliases/PdfHighlightAnchorRequest.md -->\n# Type Alias: PdfHighlightAnchorRequest\n\n> **PdfHighlightAnchorRequest** = \\{ `alpha`: `number`; `blue`: `number`; `green`: `number`; `highlightRects`: [`PdfHighlightRectAnchorRequest`](PdfHighlightRectAnchorRequest.md)[]; `highlightType`: [`HighlightType`](HighlightType.md); `page`: `number`; `pageViewportHeight`: `number`; `pageViewportWidth`: `number`; `red`: `number`; `text`: `string`; `uuid?`: `string` \\| `null`; \\}\n\n## Properties\n\n| Property | Type |\n| ------ | ------ |\n| <a id=\"property-alpha\"></a> `alpha` | `number` |\n| <a id=\"property-blue\"></a> `blue` | `number` |\n| <a id=\"property-green\"></a> `green` | `number` |\n| <a id=\"property-highlightrects\"></a> `highlightRects` | [`PdfHighlightRectAnchorRequest`](PdfHighlightRectAnchorRequest.md)[] |\n| <a id=\"property-highlighttype\"></a> `highlightType` | [`HighlightType`](HighlightType.md) |\n| <a id=\"property-page\"></a> `page` | `number` |\n| <a id=\"property-pageviewportheight\"></a> `pageViewportHeight` | `number` |\n| <a id=\"property-pageviewportwidth\"></a> `pageViewportWidth` | `number` |\n| <a id=\"property-red\"></a> `red` | `number` |\n| <a id=\"property-text\"></a> `text` | `string` |\n| <a id=\"property-uuid\"></a> `uuid?` | `string` \\| `null` |\n\n\n<!-- generated/storage/types.gen/type-aliases/PdfHighlightRect.md -->\n# Type Alias: PdfHighlightRect\n\n> **PdfHighlightRect** = \\{ `height`: `number`; `id`: `number`; `left`: `number`; `top`: `number`; `width`: `number`; \\}\n\n## Properties\n\n| Property | Type |\n| ------ | ------ |\n| <a id=\"property-height\"></a> `height` | `number` |\n| <a id=\"property-id\"></a> `id` | `number` |\n| <a id=\"property-left\"></a> `left` | `number` |\n| <a id=\"property-top\"></a> `top` | `number` |\n| <a id=\"property-width\"></a> `width` | `number` |\n\n\n<!-- generated/storage/types.gen/type-aliases/PdfHighlightRectAnchorRequest.md -->\n# Type Alias: PdfHighlightRectAnchorRequest\n\n> **PdfHighlightRectAnchorRequest** = \\{ `height`: `number`; `left`: `number`; `top`: `number`; `width`: `number`; \\}\n\n## Properties\n\n| Property | Type |\n| ------ | ------ |\n| <a id=\"property-height\"></a> `height` | `number` |\n| <a id=\"property-left\"></a> `left` | `number` |\n| <a id=\"property-top\"></a> `top` | `number` |\n| <a id=\"property-width\"></a> `width` | `number` |\n\n\n<!-- generated/storage/types.gen/type-aliases/PdfPlaceableCommentAnchor.md -->\n# Type Alias: PdfPlaceableCommentAnchor\n\n> **PdfPlaceableCommentAnchor** = \\{ `allowableEdits?`: `unknown`; `documentId`: `string`; `heightPct`: `number`; `originalIndex`: `number`; `originalPage`: `number`; `owner`: `string`; `page`: `number`; `rootId?`: `string` \\| `null`; `rotation`: `number`; `shouldLockOnSave`: `boolean`; `uuid`: `string`; `wasDeleted`: `boolean`; `wasEdited`: `boolean`; `widthPct`: `number`; `xPct`: `number`; `yPct`: `number`; \\}\n\n## Properties\n\n| Property | Type |\n| ------ | ------ |\n| <a id=\"property-allowableedits\"></a> `allowableEdits?` | `unknown` |\n| <a id=\"property-documentid\"></a> `documentId` | `string` |\n| <a id=\"property-heightpct\"></a> `heightPct` | `number` |\n| <a id=\"property-originalindex\"></a> `originalIndex` | `number` |\n| <a id=\"property-originalpage\"></a> `originalPage` | `number` |\n| <a id=\"property-owner\"></a> `owner` | `string` |\n| <a id=\"property-page\"></a> `page` | `number` |\n| <a id=\"property-rootid\"></a> `rootId?` | `string` \\| `null` |\n| <a id=\"property-rotation\"></a> `rotation` | `number` |\n| <a id=\"property-shouldlockonsave\"></a> `shouldLockOnSave` | `boolean` |\n| <a id=\"property-uuid\"></a> `uuid` | `string` |\n| <a id=\"property-wasdeleted\"></a> `wasDeleted` | `boolean` |\n| <a id=\"property-wasedited\"></a> `wasEdited` | `boolean` |\n| <a id=\"property-widthpct\"></a> `widthPct` | `number` |\n| <a id=\"property-xpct\"></a> `xPct` | `number` |\n| <a id=\"property-ypct\"></a> `yPct` | `number` |\n\n\n<!-- generated/storage/types.gen/type-aliases/PreSaveDocumentResponseData.md -->\n# Type Alias: PreSaveDocumentResponseData\n\n> **PreSaveDocumentResponseData** = \\{ `presignedUrls`: [`PresignedUrl`](PresignedUrl.md)[]; \\}\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-presignedurls\"></a> `presignedUrls` | [`PresignedUrl`](PresignedUrl.md)[] | Contains any presigned urls you need to upload specific bom parts with. |\n\n\n<!-- generated/storage/types.gen/type-aliases/PresignedUrl.md -->\n# Type Alias: PresignedUrl\n\n> **PresignedUrl** = \\{ `presignedUrl`: `string`; `sha`: `string`; \\}\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-presignedurl\"></a> `presignedUrl` | `string` | The presigned url used to upload the sha |\n| <a id=\"property-sha\"></a> `sha` | `string` | The sha of the item |\n\n\n<!-- generated/storage/types.gen/type-aliases/SaveBomPart.md -->\n# Type Alias: SaveBomPart\n\n> **SaveBomPart** = \\{ `path`: `string`; `sha`: `string`; \\}\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-path\"></a> `path` | `string` | The file path of the bom part content |\n| <a id=\"property-sha\"></a> `sha` | `string` | The sha of the bom part content There is an index on sha for more performant queries based on it. |\n\n\n<!-- generated/storage/types.gen/type-aliases/SaveDocumentRequest.md -->\n# Type Alias: SaveDocumentRequest\n\n> **SaveDocumentRequest** = \\{ `modificationData?`: `unknown`; `newBom?`: [`SaveBomPart`](SaveBomPart.md)[] \\| `null`; `sha?`: `string` \\| `null`; \\}\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-modificationdata\"></a> `modificationData?` | `unknown` | The modification data for the document instance. Used to store highlights and other overlays onto a static file |\n| <a id=\"property-newbom\"></a> `newBom?` | [`SaveBomPart`](SaveBomPart.md)[] \\| `null` | **DOCX ONLY** The updated BOM for the document. Containing the file path and the sha. |\n| <a id=\"property-sha\"></a> `sha?` | `string` \\| `null` | The sha of the new document. This is used to generate a presigned url to upload the new document content to s3. |\n\n\n<!-- generated/storage/types.gen/type-aliases/SaveDocumentResponseData.md -->\n# Type Alias: SaveDocumentResponseData\n\n> **SaveDocumentResponseData** = \\{ `documentMetadata`: [`DocumentResponseMetadata`](DocumentResponseMetadata.md); `presignedUrl?`: `string` \\| `null`; \\}\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-documentmetadata\"></a> `documentMetadata` | [`DocumentResponseMetadata`](DocumentResponseMetadata.md) | The updated document metadata |\n| <a id=\"property-presignedurl\"></a> `presignedUrl?` | `string` \\| `null` | If the document is an editable file, we provide a presigned url to save the updated file to. |\n\n\n<!-- generated/storage/types.gen/type-aliases/SharePermissionV2.md -->\n# Type Alias: SharePermissionV2\n\n> **SharePermissionV2** = \\{ `channelSharePermissions?`: [`ChannelSharePermission`](ChannelSharePermission.md)[] \\| `null`; `id`: `string`; `linkShare?`: `null` \\| [`LinkShare`](LinkShare.md); `linkShareAccessLevel?`: `null` \\| [`AccessLevel`](AccessLevel.md); `owner`: `string`; `teamShareAccessLevel?`: `null` \\| [`AccessLevel`](AccessLevel.md); \\}\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-channelsharepermissions\"></a> `channelSharePermissions?` | [`ChannelSharePermission`](ChannelSharePermission.md)[] \\| `null` | The channel share permissions for the item |\n| <a id=\"property-id\"></a> `id` | `string` | The share permission id |\n| <a id=\"property-linkshare\"></a> `linkShare?` | `null` \\| [`LinkShare`](LinkShare.md) | - |\n| <a id=\"property-linkshareaccesslevel\"></a> `linkShareAccessLevel?` | `null` \\| [`AccessLevel`](AccessLevel.md) | - |\n| <a id=\"property-owner\"></a> `owner` | `string` | The owner of the item |\n| <a id=\"property-teamshareaccesslevel\"></a> `teamShareAccessLevel?` | `null` \\| [`AccessLevel`](AccessLevel.md) | - |\n\n\n<!-- generated/storage/types.gen/type-aliases/SimpleMention.md -->\n# Type Alias: SimpleMention\n\n> **SimpleMention** = \\{ `entity_id`: `string`; `entity_type`: `string`; \\}\n\nA mention tracked in a message body.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-entity_id\"></a> `entity_id` | `string` | Mentioned entity identifier. |\n| <a id=\"property-entity_type\"></a> `entity_type` | `string` | Mentioned entity type. |\n\n\n<!-- generated/storage/types.gen/type-aliases/TeamRole.md -->\n# Type Alias: TeamRole\n\n> **TeamRole** = `\"member\"` \\| `\"admin\"` \\| `\"owner\"`\n\nThe role a user has within a team.\n\nOrdered least to most privileged so comparisons reflect access strength.\n\n\n<!-- generated/storage/types.gen/type-aliases/ThreadAnchor.md -->\n# Type Alias: ThreadAnchor\n\n> **ThreadAnchor** = \\{ `mark_id`: `string`; `marked_text?`: `string` \\| `null`; `type`: `\"markdown\"`; \\} \\| \\{ `anchor_id`: `string`; `marked_text?`: `string` \\| `null`; `type`: `\"pdf_highlight\"`; \\} \\| \\{ `anchor_id`: `string`; `type`: `\"pdf_placeable\"`; \\} \\| \\{ `range`: `string`; `sheetId`: `string`; `sheetName`: `string`; `type`: `\"spreadsheet\"`; \\} \\| \\{ `nodeId?`: `string` \\| `null`; `pageId`: `string`; `type`: `\"fig\"`; `x`: `number`; `y`: `number`; \\}\n\nA thread's location within its document. PDF geometry remains annotation-owned.\n\n## Union Members\n\n### Type Literal\n\n\\{ `mark_id`: `string`; `marked_text?`: `string` \\| `null`; `type`: `\"markdown\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `mark_id` | `string` | Mark UUID serialized in the document. |\n| `marked_text?` | `string` \\| `null` | The marked text as it read when the discussion was created, already trimmed and bounded. Absent on threads created or imported before snapshots were captured: the text a mark covers cannot be recovered from the mark id alone. |\n| `type` | `\"markdown\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `anchor_id`: `string`; `marked_text?`: `string` \\| `null`; `type`: `\"pdf_highlight\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `anchor_id` | `string` | Highlight annotation UUID. |\n| `marked_text?` | `string` \\| `null` | The text the highlight covers, trimmed and bounded like a markdown snapshot. The highlight owns it and it can be edited there, so it is read from the highlight whenever the thread is, never stored on the thread. Absent when the highlight carries no text. |\n| `type` | `\"pdf_highlight\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `anchor_id`: `string`; `type`: `\"pdf_placeable\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `anchor_id` | `string` | Placeable annotation UUID. |\n| `type` | `\"pdf_placeable\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `range`: `string`; `sheetId`: `string`; `sheetName`: `string`; `type`: `\"spreadsheet\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `range` | `string` | A1 cell or range, such as B4 or B4:C9. |\n| `sheetId` | `string` | Stable sheet identity within the workbook. |\n| `sheetName` | `string` | Sheet name when the discussion was created. |\n| `type` | `\"spreadsheet\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `nodeId?`: `string` \\| `null`; `pageId`: `string`; `type`: `\"fig\"`; `x`: `number`; `y`: `number`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `nodeId?` | `string` \\| `null` | Layer the pin follows; absent for a pin on the bare canvas. |\n| `pageId` | `string` | Page (canvas) the pin is on. |\n| `type` | `\"fig\"` | - |\n| `x` | `number` | Horizontal offset from the layer's origin, or the page's when the pin is on no layer, in design units. |\n| `y` | `number` | Vertical offset, measured like `x`. |\n\n\n<!-- generated/storage/types.gen/type-aliases/ThreadState.md -->\n# Type Alias: ThreadState\n\n> **ThreadState** = \\{ `anchor?`: `null` \\| [`ThreadAnchor`](ThreadAnchor.md); `created_at`: `string`; `deleted_at?`: `string` \\| `null`; `resolved`: `boolean`; `root_id`: `string`; `updated_at`: `string`; `user_id`: `string`; \\}\n\nState belonging to a whole thread, keyed by its root message.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-anchor\"></a> `anchor?` | `null` \\| [`ThreadAnchor`](ThreadAnchor.md) | - |\n| <a id=\"property-created_at\"></a> `created_at` | `string` | Creation time of the discussion. |\n| <a id=\"property-deleted_at\"></a> `deleted_at?` | `string` \\| `null` | Explicit deletion of the entire thread, distinct from root deletion. |\n| <a id=\"property-resolved\"></a> `resolved` | `boolean` | Whether this discussion has been resolved. |\n| <a id=\"property-root_id\"></a> `root_id` | `string` | Root message UUID; there is no separate thread identity. |\n| <a id=\"property-updated_at\"></a> `updated_at` | `string` | Last state change. |\n| <a id=\"property-user_id\"></a> `user_id` | `string` | User who owns this discussion, including imported discussions. |\n\n\n<!-- src/entities/documents/anchor/classes/DocumentAnchor.md -->\n# Class: DocumentAnchor\n\nA PDF annotation scoped to its document.\n\n## Extends\n\n- [`MacroEntity`](../../../entity/classes/MacroEntity.md)\\<[`Anchor`](../../../../../generated/storage/types.gen/type-aliases/Anchor.md)\\>\n\n## Properties\n\n| Property | Modifier | Type | Description | Inherited from |\n| ------ | ------ | ------ | ------ | ------ |\n| <a id=\"property-document\"></a> `document` | `readonly` | [`Document`](../../document/classes/Document.md) | Owning document. | - |\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-kind\"></a> `kind` | `readonly` | () => `Promise`\\<`\"highlight\"` \\| `\"placeable\"`\\> | Annotation kind. | - |\n| <a id=\"property-page\"></a> `page` | `readonly` | () => `Promise`\\<`number`\\> | Page containing the annotation. | - |\n\n## Methods\n\n### delete()\n\n> **delete**(): `Promise`\\<`void`\\>\n\nDelete a standalone highlight annotation.\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### edit()\n\n> **edit**(`options`): `Promise`\\<`void`\\>\n\nEdit a placeable comment's position and display settings.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `options` | `Omit`\\<[`EditPdfPlaceableCommentAnchorRequest`](../../../../../generated/storage/types.gen/type-aliases/EditPdfPlaceableCommentAnchorRequest.md), `\"uuid\"`\\> |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### toJSON()\n\n> **toJSON**(): \\{ `detail?`: [`PdfAnchor`](../../../../../generated/storage/types.gen/type-aliases/PdfAnchor.md); `documentId`: `string`; `id`: `string`; \\}\n\nSerialize identity with its owning resource.\n\n#### Returns\n\n\\{ `detail?`: [`PdfAnchor`](../../../../../generated/storage/types.gen/type-aliases/PdfAnchor.md); `documentId`: `string`; `id`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `detail?` | [`PdfAnchor`](../../../../../generated/storage/types.gen/type-aliases/PdfAnchor.md) |\n| `documentId` | `string` |\n| `id` | `string` |\n\n#### Overrides\n\n[`MacroEntity`](../../../entity/classes/MacroEntity.md).[`toJSON`](../../../entity/classes/MacroEntity.md#tojson)\n\n***\n\n### byId()\n\n> `static` **byId**(`client`, `document`, `id`): `DocumentAnchor`\n\nConstruct a document scoped annotation handle.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `document` | [`Document`](../../document/classes/Document.md) |\n| `id` | `string` |\n\n#### Returns\n\n`DocumentAnchor`\n\n***\n\n### from()\n\n> `static` **from**(`client`, `document`, `record`): `DocumentAnchor`\n\nSeed an annotation from a document annotation listing.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `document` | [`Document`](../../document/classes/Document.md) |\n| `record` | [`PdfAnchor`](../../../../../generated/storage/types.gen/type-aliases/PdfAnchor.md) |\n\n#### Returns\n\n`DocumentAnchor`\n\n\n<!-- src/entities/documents/comment/classes/Comment.md -->\n# Class: Comment\n\nA comment on a document: a document-parent message, addressed by its\ndocument and message UUID. Its record and mutations are the ones channel\nmessages use.\n\n## Extends\n\n- [`MacroEntity`](../../../entity/classes/MacroEntity.md)\\<[`Message`](../../../../../generated/storage/types.gen/type-aliases/Message.md)\\>\n\n## Properties\n\n| Property | Modifier | Type | Description | Inherited from |\n| ------ | ------ | ------ | ------ | ------ |\n| <a id=\"property-createdat\"></a> `createdAt` | `readonly` | () => `Promise`\\<`string`\\> | When the comment was created. | - |\n| <a id=\"property-documentid\"></a> `documentId` | `readonly` | `string` | The document this comment belongs to. | - |\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-text\"></a> `text` | `readonly` | () => `Promise`\\<`string`\\> | The comment's text. | - |\n| <a id=\"property-updatedat\"></a> `updatedAt` | `readonly` | () => `Promise`\\<`string`\\> | When the comment was last updated. | - |\n\n## Methods\n\n### author()\n\n> **author**(): `Promise`\\<[`User`](../../../users/user/classes/User.md)\\>\n\nThe user who wrote this comment.\n\n#### Returns\n\n`Promise`\\<[`User`](../../../users/user/classes/User.md)\\>\n\n***\n\n### delete()\n\n> **delete**(): `Promise`\\<`void`\\>\n\nDelete this comment.\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### document()\n\n> **document**(): [`Document`](../../document/classes/Document.md)\n\nThe document this comment is on.\n\n#### Returns\n\n[`Document`](../../document/classes/Document.md)\n\n***\n\n### edit()\n\n> **edit**(`body`): `Promise`\\<`Comment`\\>\n\nReplace the comment's text.\n\n#### Parameters\n\n| Parameter | Type | Description |\n| ------ | ------ | ------ |\n| `body` | `string` \\| [`RichMessage`](../../../../mentions/interfaces/RichMessage.md) | Plain text, or a rich body composed with msg. |\n\n#### Returns\n\n`Promise`\\<`Comment`\\>\n\n***\n\n### reply()\n\n> **reply**(`body`): `Promise`\\<`Comment`\\>\n\nReply in this comment's thread.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `body` | `string` \\| [`RichMessage`](../../../../mentions/interfaces/RichMessage.md) |\n\n#### Returns\n\n`Promise`\\<`Comment`\\>\n\n***\n\n### threadId()\n\n> **threadId**(): `Promise`\\<`string`\\>\n\nThe id of the thread this comment belongs to: its root, or itself for a root.\n\n#### Returns\n\n`Promise`\\<`string`\\>\n\n***\n\n### toJSON()\n\n> **toJSON**(): \\{ `detail?`: [`Message`](../../../../../generated/storage/types.gen/type-aliases/Message.md); `id`: `string`; \\}\n\n#### Returns\n\n\\{ `detail?`: [`Message`](../../../../../generated/storage/types.gen/type-aliases/Message.md); `id`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `detail?` | [`Message`](../../../../../generated/storage/types.gen/type-aliases/Message.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`, `documentId`, `id`): `Comment`\n\nA handle to a comment by id. Fields load on first access.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `documentId` | `string` |\n| `id` | `string` |\n\n#### Returns\n\n`Comment`\n\n***\n\n### from()\n\n> `static` **from**(`client`, `documentId`, `record`): `Comment`\n\nBuild a comment from a message record (pre-seeded, no fetch).\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `documentId` | `string` |\n| `record` | [`Message`](../../../../../generated/storage/types.gen/type-aliases/Message.md) |\n\n#### Returns\n\n`Comment`\n\n\n<!-- src/entities/documents/document/classes/Document.md -->\n# Class: Document\n\nA Macro document. Can be dropped into a msg template to render an\ninline link to the document.\n\n## Extends\n\n- [`PropertiedEntity`](../../../entity/classes/PropertiedEntity.md)\\<`DocumentDetail`\\>\n\n## Extended by\n\n- [`Task`](../../../tasks/task/classes/Task.md)\n\n## Implements\n\n- [`Mentionable`](../../../../mentions/interfaces/Mentionable.md)\n\n## Properties\n\n| Property | Modifier | Type | Default value | Description | Overrides | Inherited from |\n| ------ | ------ | ------ | ------ | ------ | ------ | ------ |\n| <a id=\"property-access\"></a> `access` | `readonly` | [`EntityAccess`](../../../sharing/access/classes/EntityAccess.md) | `...` | Access requests and direct user grants. | - | - |\n| <a id=\"property-branchedfrom\"></a> `branchedFrom` | `readonly` | () => `Promise`\\<`Document` \\| `undefined`\\> | `...` | The document this one was branched from, if any. | - | - |\n| <a id=\"property-createdat\"></a> `createdAt` | `readonly` | () => `Promise`\\<`string` \\| `undefined`\\> | `...` | When the document was created. | - | - |\n| <a id=\"property-deletedat\"></a> `deletedAt` | `readonly` | () => `Promise`\\<`string` \\| `undefined`\\> | `...` | When the document was deleted, if it has been. | - | - |\n| <a id=\"property-entitytype\"></a> `entityType` | `readonly` | `\"document\"` | `'document'` | Favorites identify documents as `document`. | [`PropertiedEntity`](../../../entity/classes/PropertiedEntity.md).[`entityType`](../../../entity/classes/PropertiedEntity.md#property-entitytype) | - |\n| <a id=\"property-filetype\"></a> `fileType` | `readonly` | () => `Promise`\\<`string` \\| `undefined`\\> | `...` | The document's file type (e.g. `md`, `pdf`, `docx`). | - | - |\n| <a id=\"property-id\"></a> `id` | `public readonly` | `string` | `undefined` | - | - | [`PropertiedEntity`](../../../entity/classes/PropertiedEntity.md).[`id`](../../../entity/classes/PropertiedEntity.md#property-id) |\n| <a id=\"property-name\"></a> `name` | `readonly` | () => `Promise`\\<`string`\\> | `...` | The document's display name. | - | - |\n| <a id=\"property-owner\"></a> `owner` | `readonly` | () => `Promise`\\<[`User`](../../../users/user/classes/User.md)\\> | `...` | The user who owns the document. | - | - |\n| <a id=\"property-project\"></a> `project` | `readonly` | () => `Promise`\\<[`Project`](../../../projects/project/classes/Project.md) \\| `undefined`\\> | `...` | The project this document belongs to, if any. | - | - |\n| <a id=\"property-updatedat\"></a> `updatedAt` | `readonly` | () => `Promise`\\<`string` \\| `undefined`\\> | `...` | When the document was last updated. | - | - |\n| <a id=\"property-search\"></a> `search` | `static` | (`client`, `query`, `searchOpts?`) => `AsyncGenerator`\\<`Document`\\> | `...` | Search documents by name and content, most relevant first, auto-paginated. | - | - |\n\n## Methods\n\n### anchors()\n\n> **anchors**(): `Promise`\\<[`DocumentAnchor`](../../anchor/classes/DocumentAnchor.md)[]\\>\n\nPDF annotations in this document.\n\n#### Returns\n\n`Promise`\\<[`DocumentAnchor`](../../anchor/classes/DocumentAnchor.md)[]\\>\n\n***\n\n### branchName()\n\n> **branchName**(): `Promise`\\<`string`\\>\n\nThe git branch name derived for the document (task documents).\n\n#### Returns\n\n`Promise`\\<`string`\\>\n\n***\n\n### comment()\n\n> **comment**(`body`, `opts?`): `Promise`\\<[`Comment`](../../comment/classes/Comment.md)\\>\n\nAdd a comment. Starts a new unanchored thread, or replies to an existing\none when `threadId` (the thread's root comment id) is given.\n\n#### Parameters\n\n| Parameter | Type | Description |\n| ------ | ------ | ------ |\n| `body` | `string` \\| [`RichMessage`](../../../../mentions/interfaces/RichMessage.md) | Plain text, or a rich body composed with msg. |\n| `opts?` | \\{ `threadId?`: `string`; \\} | - |\n| `opts.threadId?` | `string` | - |\n\n#### Returns\n\n`Promise`\\<[`Comment`](../../comment/classes/Comment.md)\\>\n\nThe created comment.\n\n***\n\n### comments()\n\n> **comments**(): `Promise`\\<[`CommentThread`](../interfaces/CommentThread.md)[]\\>\n\nThe document's live comment threads, each with its comments, newest thread first.\n\n#### Returns\n\n`Promise`\\<[`CommentThread`](../interfaces/CommentThread.md)[]\\>\n\n***\n\n### content()\n\n> **content**(): `Promise`\\<`string`\\>\n\nCurrent Markdown for native documents, extracted text for PDF/Word,\nor raw file content for other formats. Native reads include live edits.\n\n#### Returns\n\n`Promise`\\<`string`\\>\n\n***\n\n### copy()\n\n> **copy**(`opts`): `Promise`\\<`Document`\\>\n\nCopy the document under a new name, optionally from a specific version.\nReturns a handle to the new document.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `opts` | \\{ `name`: `string`; `versionId?`: `number`; \\} |\n| `opts.name` | `string` |\n| `opts.versionId?` | `number` |\n\n#### Returns\n\n`Promise`\\<`Document`\\>\n\n***\n\n### createHighlight()\n\n> **createHighlight**(`options`): `Promise`\\<[`DocumentAnchor`](../../anchor/classes/DocumentAnchor.md)\\>\n\nCreate a standalone PDF highlight.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `options` | `Omit`\\<[`PdfHighlightAnchorRequest`](../../../../../generated/storage/types.gen/type-aliases/PdfHighlightAnchorRequest.md), `\"uuid\"`\\> |\n\n#### Returns\n\n`Promise`\\<[`DocumentAnchor`](../../anchor/classes/DocumentAnchor.md)\\>\n\n***\n\n### delete()\n\n> **delete**(`opts?`): `Promise`\\<`void`\\>\n\nDelete the document. Soft by default (reversible with [restore](#restore));\npass `permanent: true` to delete irreversibly.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `opts?` | \\{ `permanent?`: `boolean`; \\} |\n| `opts.permanent?` | `boolean` |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### deleteProperty()\n\n> **deleteProperty**(`assignment`): `Promise`\\<`void`\\>\n\nRemove a property from this entity, given its [properties](#properties) entry.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `assignment` | [`EntityPropertyWithDefinition`](../../../../../generated/properties/types.gen/type-aliases/EntityPropertyWithDefinition.md) |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n#### Inherited from\n\n[`PropertiedEntity`](../../../entity/classes/PropertiedEntity.md).[`deleteProperty`](../../../entity/classes/PropertiedEntity.md#deleteproperty)\n\n***\n\n### favorite()\n\n> **favorite**(): `Promise`\\<`Document`\\>\n\nAdd this entity to the user's favorites. Returns this handle for chaining.\nPlain unwrap: favoriting alters the user's favorites collection, not this\nentity's own detail, so there's nothing cached to invalidate.\n\n#### Returns\n\n`Promise`\\<`Document`\\>\n\n#### Inherited from\n\n[`PropertiedEntity`](../../../entity/classes/PropertiedEntity.md).[`favorite`](../../../entity/classes/PropertiedEntity.md#favorite)\n\n***\n\n### githubPullRequests()\n\n> **githubPullRequests**(): `Promise`\\<[`GithubPullRequest`](../../../../../generated/storage/types.gen/type-aliases/GithubPullRequest.md)[]\\>\n\nGitHub pull requests associated with the document.\n\n#### Returns\n\n`Promise`\\<[`GithubPullRequest`](../../../../../generated/storage/types.gen/type-aliases/GithubPullRequest.md)[]\\>\n\n***\n\n### meetingNotes()\n\n> **meetingNotes**(): `Promise`\\<\\{ `eventTitle`: `string`; `note`: [`CalendarNote`](../../../calendar/note/classes/CalendarNote.md); \\}[]\\>\n\nOwner-only meeting grants, including unavailable meetings. Unlink a returned note to revoke its meeting/team access.\n\n#### Returns\n\n`Promise`\\<\\{ `eventTitle`: `string`; `note`: [`CalendarNote`](../../../calendar/note/classes/CalendarNote.md); \\}[]\\>\n\n***\n\n### messageThreadById()\n\n> **messageThreadById**(`id`): [`MessageThread`](../../../messages/thread/classes/MessageThread.md)\n\nA shared message thread scoped to this resource.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `id` | `string` |\n\n#### Returns\n\n[`MessageThread`](../../../messages/thread/classes/MessageThread.md)\n\n***\n\n### move()\n\n> **move**(`project`): `Promise`\\<`void`\\>\n\nMove the document into a project (or out of one, with `null`).\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `project` | [`Project`](../../../projects/project/classes/Project.md) \\| `null` |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### permission()\n\n> **permission**(): `Promise`\\<\\{ `permission`: [`EntityPermission`](../../../../../generated/storage/types.gen/type-aliases/EntityPermission.md); `status`: `\"access\"`; \\} \\| \\{ `status`: `\"no_access\"`; \\}\\>\n\nRead the caller's effective permission on this entity.\n\n#### Returns\n\n`Promise`\\<\\{ `permission`: [`EntityPermission`](../../../../../generated/storage/types.gen/type-aliases/EntityPermission.md); `status`: `\"access\"`; \\} \\| \\{ `status`: `\"no_access\"`; \\}\\>\n\n#### Inherited from\n\n[`PropertiedEntity`](../../../entity/classes/PropertiedEntity.md).[`permission`](../../../entity/classes/PropertiedEntity.md#permission)\n\n***\n\n### permissionsToken()\n\n> **permissionsToken**(): `Promise`\\<`string`\\>\n\nMint a scoped permissions token.\n\n#### Returns\n\n`Promise`\\<`string`\\>\n\n***\n\n### prepareSave()\n\n> **prepareSave**(`parts`): `Promise`\\<[`PreSaveDocumentResponseData`](../../../../../generated/storage/types.gen/type-aliases/PreSaveDocumentResponseData.md)\\>\n\nPrepare multipart content saving and return the service's upload instructions.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `parts` | [`SaveBomPart`](../../../../../generated/storage/types.gen/type-aliases/SaveBomPart.md)[] |\n\n#### Returns\n\n`Promise`\\<[`PreSaveDocumentResponseData`](../../../../../generated/storage/types.gen/type-aliases/PreSaveDocumentResponseData.md)\\>\n\n***\n\n### properties()\n\n> **properties**(`opts?`): `Promise`\\<[`EntityPropertyWithDefinition`](../../../../../generated/properties/types.gen/type-aliases/EntityPropertyWithDefinition.md)[]\\>\n\nThe properties set on this entity, each with its definition, value, and options.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `opts?` | \\{ `includeMetadata?`: `boolean`; \\} |\n| `opts.includeMetadata?` | `boolean` |\n\n#### Returns\n\n`Promise`\\<[`EntityPropertyWithDefinition`](../../../../../generated/properties/types.gen/type-aliases/EntityPropertyWithDefinition.md)[]\\>\n\n#### Inherited from\n\n[`PropertiedEntity`](../../../entity/classes/PropertiedEntity.md).[`properties`](../../../entity/classes/PropertiedEntity.md#properties)\n\n***\n\n### propertyReference()\n\n> **propertyReference**(): [`PropertyTargetReference`](../../../../../generated/properties/types.gen/type-aliases/PropertyTargetReference.md)\n\nThis entity's reference for bulk property operations.\n\n#### Returns\n\n[`PropertyTargetReference`](../../../../../generated/properties/types.gen/type-aliases/PropertyTargetReference.md)\n\n#### Inherited from\n\n[`PropertiedEntity`](../../../entity/classes/PropertiedEntity.md).[`propertyReference`](../../../entity/classes/PropertiedEntity.md#propertyreference)\n\n***\n\n### rename()\n\n> **rename**(`name`): `Promise`\\<`void`\\>\n\nRename the document.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `name` | `string` |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### restore()\n\n> **restore**(): `Promise`\\<`void`\\>\n\nRestore a soft-deleted document.\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### save()\n\n> **save**(`options`): `Promise`\\<[`SaveDocumentResponseData`](../../../../../generated/storage/types.gen/type-aliases/SaveDocumentResponseData.md)\\>\n\nCommit uploaded content. Does not retry uncertain writes.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `options` | [`SaveDocumentRequest`](../../../../../generated/storage/types.gen/type-aliases/SaveDocumentRequest.md) |\n\n#### Returns\n\n`Promise`\\<[`SaveDocumentResponseData`](../../../../../generated/storage/types.gen/type-aliases/SaveDocumentResponseData.md)\\>\n\n***\n\n### setProperty()\n\n> **setProperty**(`property`, `value?`): `Promise`\\<`void`\\>\n\nSet a property value on this entity, or attach the property without a\nvalue when `value` is omitted.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `property` | [`PropertyDefinition`](../../../properties/property-definition/classes/PropertyDefinition.md) |\n| `value?` | [`SetPropertyValue`](../../../../../generated/properties/types.gen/type-aliases/SetPropertyValue.md) |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n#### Inherited from\n\n[`PropertiedEntity`](../../../entity/classes/PropertiedEntity.md).[`setProperty`](../../../entity/classes/PropertiedEntity.md#setproperty)\n\n***\n\n### setTeamShare()\n\n> **setTeamShare**(`shared`): `Promise`\\<`void`\\>\n\nShare the document with the owner's team, or unshare it.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `shared` | `boolean` |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### sharePermissions()\n\n> **sharePermissions**(): `Promise`\\<[`SharePermissionV2`](../../../../../generated/storage/types.gen/type-aliases/SharePermissionV2.md)\\>\n\nSharing configuration.\n\n#### Returns\n\n`Promise`\\<[`SharePermissionV2`](../../../../../generated/storage/types.gen/type-aliases/SharePermissionV2.md)\\>\n\n***\n\n### shortId()\n\n> **shortId**(): `Promise`\\<`string`\\>\n\nThe document's short id (used in compact links and branch names).\n\n#### Returns\n\n`Promise`\\<`string`\\>\n\n***\n\n### simpleSave()\n\n> **simpleSave**(): `Promise`\\<[`SaveDocumentResponseData`](../../../../../generated/storage/types.gen/type-aliases/SaveDocumentResponseData.md)\\>\n\nCommit a simple document save.\n\n#### Returns\n\n`Promise`\\<[`SaveDocumentResponseData`](../../../../../generated/storage/types.gen/type-aliases/SaveDocumentResponseData.md)\\>\n\n***\n\n### teamShare()\n\n> **teamShare**(): `Promise`\\<[`DocumentTeamShareResponse`](../../../../../generated/storage/types.gen/type-aliases/DocumentTeamShareResponse.md)\\>\n\nWhether the document is shared with the owner's team, and which team.\n\n#### Returns\n\n`Promise`\\<[`DocumentTeamShareResponse`](../../../../../generated/storage/types.gen/type-aliases/DocumentTeamShareResponse.md)\\>\n\n***\n\n### timelinePage()\n\n> **timelinePage**(`selection?`): `Promise`\\<\\{ `entries`: (\\{ `activity`: \\{ `action`: `string`; `actor`: [`User`](../../../users/user/classes/User.md); `actor_id`: `string`; `id`: `string`; `occurred_at`: `string`; `payload?`: `unknown`; \\}; `message?`: `undefined`; `type`: `\"activity\"`; \\} \\| \\{ `activity?`: `undefined`; `message`: [`Comment`](../../comment/classes/Comment.md); `type`: `\"message\"`; \\})[]; `nextCursor`: [`MessageCursor`](../../../../../generated/storage/types.gen/type-aliases/MessageCursor.md) \\| `undefined`; `previousCursor`: [`MessageCursor`](../../../../../generated/storage/types.gen/type-aliases/MessageCursor.md) \\| `undefined`; \\}\\>\n\nA mixed message and activity timeline page.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `selection?` | [`TimelineOptions`](../../../messages/thread/interfaces/TimelineOptions.md)\\<[`Comment`](../../comment/classes/Comment.md)\\> |\n\n#### Returns\n\n`Promise`\\<\\{ `entries`: (\\{ `activity`: \\{ `action`: `string`; `actor`: [`User`](../../../users/user/classes/User.md); `actor_id`: `string`; `id`: `string`; `occurred_at`: `string`; `payload?`: `unknown`; \\}; `message?`: `undefined`; `type`: `\"activity\"`; \\} \\| \\{ `activity?`: `undefined`; `message`: [`Comment`](../../comment/classes/Comment.md); `type`: `\"message\"`; \\})[]; `nextCursor`: [`MessageCursor`](../../../../../generated/storage/types.gen/type-aliases/MessageCursor.md) \\| `undefined`; `previousCursor`: [`MessageCursor`](../../../../../generated/storage/types.gen/type-aliases/MessageCursor.md) \\| `undefined`; \\}\\>\n\n***\n\n### toJSON()\n\n> **toJSON**(): \\{ `detail?`: [`DocumentMetadataWithContent`](../../../../../generated/storage/types.gen/type-aliases/DocumentMetadataWithContent.md); `id`: `string`; \\}\n\n#### Returns\n\n\\{ `detail?`: [`DocumentMetadataWithContent`](../../../../../generated/storage/types.gen/type-aliases/DocumentMetadataWithContent.md); `id`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `detail?` | [`DocumentMetadataWithContent`](../../../../../generated/storage/types.gen/type-aliases/DocumentMetadataWithContent.md) |\n| `id` | `string` |\n\n#### Inherited from\n\n[`PropertiedEntity`](../../../entity/classes/PropertiedEntity.md).[`toJSON`](../../../entity/classes/PropertiedEntity.md#tojson)\n\n***\n\n### toMention()\n\n> **toMention**(): [`MentionPart`](../../../../mentions/interfaces/MentionPart.md)\n\n#### Returns\n\n[`MentionPart`](../../../../mentions/interfaces/MentionPart.md)\n\n#### Implementation of\n\n[`Mentionable`](../../../../mentions/interfaces/Mentionable.md).[`toMention`](../../../../mentions/interfaces/Mentionable.md#tomention)\n\n***\n\n### unfavorite()\n\n> **unfavorite**(): `Promise`\\<`Document`\\>\n\nRemove this entity from the user's favorites. Returns this handle for chaining.\n\n#### Returns\n\n`Promise`\\<`Document`\\>\n\n#### Inherited from\n\n[`PropertiedEntity`](../../../entity/classes/PropertiedEntity.md).[`unfavorite`](../../../entity/classes/PropertiedEntity.md#unfavorite)\n\n***\n\n### updatePropertyOptions()\n\n> **updatePropertyOptions**(`changes`): `Promise`\\<[`BulkUpdateEntityPropertyOptionsResponse`](../../../../../generated/properties/types.gen/type-aliases/BulkUpdateEntityPropertyOptionsResponse.md)\\>\n\nApply multi-select option deltas atomically across this entity's properties.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `changes` | [`PropertyOptionDelta`](../../../entity/interfaces/PropertyOptionDelta.md)[] |\n\n#### Returns\n\n`Promise`\\<[`BulkUpdateEntityPropertyOptionsResponse`](../../../../../generated/properties/types.gen/type-aliases/BulkUpdateEntityPropertyOptionsResponse.md)\\>\n\n#### Inherited from\n\n[`PropertiedEntity`](../../../entity/classes/PropertiedEntity.md).[`updatePropertyOptions`](../../../entity/classes/PropertiedEntity.md#updatepropertyoptions)\n\n***\n\n### version()\n\n> **version**(`version`): [`DocumentVersion`](../../version/classes/DocumentVersion.md)\n\nA handle to an immutable version.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `version` | `number` |\n\n#### Returns\n\n[`DocumentVersion`](../../version/classes/DocumentVersion.md)\n\n***\n\n### webUrl()\n\n> **webUrl**(): `string`\n\nThe document's URL in the Macro web app.\n\n#### Returns\n\n`string`\n\n***\n\n### byId()\n\n> `static` **byId**(`client`, `id`): `Document`\n\nA handle to a document by id. Details load on first access.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `id` | `string` |\n\n#### Returns\n\n`Document`\n\n***\n\n### create()\n\n> `static` **create**(`client`, `opts`): `Promise`\\<`Document`\\>\n\nCreate a markdown document.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `opts` | \\{ `markdown?`: `string`; `name`: `string`; `project?`: [`Project`](../../../projects/project/classes/Project.md); \\} |\n| `opts.markdown?` | `string` |\n| `opts.name` | `string` |\n| `opts.project?` | [`Project`](../../../projects/project/classes/Project.md) |\n\n#### Returns\n\n`Promise`\\<`Document`\\>\n\n***\n\n### createSkill()\n\n> `static` **createSkill**(`client`, `opts`): `Promise`\\<`Document`\\>\n\nCreate a skill: a markdown document containing instructions that AI reads\nand follows when the skill is referenced in an AI input.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `opts` | \\{ `markdown?`: `string`; `name`: `string`; `project?`: [`Project`](../../../projects/project/classes/Project.md); \\} |\n| `opts.markdown?` | `string` |\n| `opts.name` | `string` |\n| `opts.project?` | [`Project`](../../../projects/project/classes/Project.md) |\n\n#### Returns\n\n`Promise`\\<`Document`\\>\n\n***\n\n### createSnippet()\n\n> `static` **createSnippet**(`client`, `opts`): `Promise`\\<`Document`\\>\n\nCreate a snippet: a reusable markdown document that can be inserted into\nany markdown area.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `opts` | \\{ `markdown?`: `string`; `name`: `string`; `project?`: [`Project`](../../../projects/project/classes/Project.md); \\} |\n| `opts.markdown?` | `string` |\n| `opts.name` | `string` |\n| `opts.project?` | [`Project`](../../../projects/project/classes/Project.md) |\n\n#### Returns\n\n`Promise`\\<`Document`\\>\n\n***\n\n### recent()\n\n> `static` **recent**(`client`, `opts?`): `AsyncGenerator`\\<`Document`\\>\n\nThe user's recent documents, most recent first, auto-paginated.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `opts?` | \\{ `fileType?`: `string`; `pageSize?`: `number`; \\} |\n| `opts.fileType?` | `string` |\n| `opts.pageSize?` | `number` |\n\n#### Returns\n\n`AsyncGenerator`\\<`Document`\\>\n\n***\n\n### recentlyDeleted()\n\n> `static` **recentlyDeleted**(`client`): `Promise`\\<`Document`[]\\>\n\nThe user's recently soft-deleted documents. The underlying endpoint also\nreturns deleted chats and projects; those are filtered out here.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n\n#### Returns\n\n`Promise`\\<`Document`[]\\>\n\n\n<!-- src/entities/documents/document/interfaces/CommentThread.md -->\n# Interface: CommentThread\n\nOne of a document's comment threads: its state and its comments.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-comments\"></a> `comments` | [`Comment`](../../comment/classes/Comment.md)[] | The root comment followed by its replies, in order. |\n| <a id=\"property-thread\"></a> `thread` | [`ThreadState`](../../../../../generated/storage/types.gen/type-aliases/ThreadState.md) | The thread state: root id, resolved flag, owner, anchor, timestamps. |\n\n\n<!-- src/entities/documents/namespace/classes/DocumentNamespace.md -->\n# Class: DocumentNamespace\n\n## Constructors\n\n### Constructor\n\n> **new DocumentNamespace**(`client`): `DocumentNamespace`\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n\n#### Returns\n\n`DocumentNamespace`\n\n## Methods\n\n### byId()\n\n> **byId**(`id`): [`Document`](../../document/classes/Document.md)\n\nA handle to a document by id. Details load on first access.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `id` | `string` |\n\n#### Returns\n\n[`Document`](../../document/classes/Document.md)\n\n***\n\n### byTeamSlug()\n\n> **byTeamSlug**(`slug`): `Promise`\\<[`Document`](../../document/classes/Document.md)\\>\n\nResolve a team task reference such as ENG-42.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `slug` | `string` |\n\n#### Returns\n\n`Promise`\\<[`Document`](../../document/classes/Document.md)\\>\n\n***\n\n### create()\n\n> **create**(`opts`): `Promise`\\<[`Document`](../../document/classes/Document.md)\\>\n\nCreate a markdown document.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `opts` | \\{ `markdown?`: `string`; `name`: `string`; `project?`: [`Project`](../../../projects/project/classes/Project.md); \\} |\n| `opts.markdown?` | `string` |\n| `opts.name` | `string` |\n| `opts.project?` | [`Project`](../../../projects/project/classes/Project.md) |\n\n#### Returns\n\n`Promise`\\<[`Document`](../../document/classes/Document.md)\\>\n\n***\n\n### createSkill()\n\n> **createSkill**(`opts`): `Promise`\\<[`Document`](../../document/classes/Document.md)\\>\n\nCreate a skill: markdown instructions that AI reads and follows.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `opts` | \\{ `markdown?`: `string`; `name`: `string`; `project?`: [`Project`](../../../projects/project/classes/Project.md); \\} |\n| `opts.markdown?` | `string` |\n| `opts.name` | `string` |\n| `opts.project?` | [`Project`](../../../projects/project/classes/Project.md) |\n\n#### Returns\n\n`Promise`\\<[`Document`](../../document/classes/Document.md)\\>\n\n***\n\n### createSnippet()\n\n> **createSnippet**(`opts`): `Promise`\\<[`Document`](../../document/classes/Document.md)\\>\n\nCreate a snippet: a reusable markdown document.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `opts` | \\{ `markdown?`: `string`; `name`: `string`; `project?`: [`Project`](../../../projects/project/classes/Project.md); \\} |\n| `opts.markdown?` | `string` |\n| `opts.name` | `string` |\n| `opts.project?` | [`Project`](../../../projects/project/classes/Project.md) |\n\n#### Returns\n\n`Promise`\\<[`Document`](../../document/classes/Document.md)\\>\n\n***\n\n### createUpload()\n\n> **createUpload**(`options`): `Promise`\\<\\{ `content`: [`DocumentContent`](../../../../../generated/storage/types.gen/type-aliases/DocumentContent.md); `contentType`: `string`; `document`: [`Document`](../../document/classes/Document.md); `uploadUrl`: `string` \\| `undefined`; \\}\\>\n\nReserve a binary document and return upload instructions. Upload content before saving.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `options` | \\{ `attachment?`: [`EmailAttachment`](../../../email/attachment/classes/EmailAttachment.md); `branchedFrom?`: [`Document`](../../document/classes/Document.md); `fileType?`: `string`; `isTask?`: `boolean`; `mimeType?`: `string`; `name`: `string`; `project?`: [`Project`](../../../projects/project/classes/Project.md); `sha`: `string`; `team?`: [`Team`](../../../teams/team/classes/Team.md); \\} |\n| `options.attachment?` | [`EmailAttachment`](../../../email/attachment/classes/EmailAttachment.md) |\n| `options.branchedFrom?` | [`Document`](../../document/classes/Document.md) |\n| `options.fileType?` | `string` |\n| `options.isTask?` | `boolean` |\n| `options.mimeType?` | `string` |\n| `options.name` | `string` |\n| `options.project?` | [`Project`](../../../projects/project/classes/Project.md) |\n| `options.sha` | `string` |\n| `options.team?` | [`Team`](../../../teams/team/classes/Team.md) |\n\n#### Returns\n\n`Promise`\\<\\{ `content`: [`DocumentContent`](../../../../../generated/storage/types.gen/type-aliases/DocumentContent.md); `contentType`: `string`; `document`: [`Document`](../../document/classes/Document.md); `uploadUrl`: `string` \\| `undefined`; \\}\\>\n\n***\n\n### recent()\n\n> **recent**(`opts?`): `AsyncGenerator`\\<[`Document`](../../document/classes/Document.md)\\>\n\nThe user's recent documents, most recent first, auto-paginated.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `opts?` | \\{ `fileType?`: `string`; `pageSize?`: `number`; \\} |\n| `opts.fileType?` | `string` |\n| `opts.pageSize?` | `number` |\n\n#### Returns\n\n`AsyncGenerator`\\<[`Document`](../../document/classes/Document.md)\\>\n\n***\n\n### recentlyDeleted()\n\n> **recentlyDeleted**(): `Promise`\\<[`Document`](../../document/classes/Document.md)[]\\>\n\nThe user's recently soft-deleted documents.\n\n#### Returns\n\n`Promise`\\<[`Document`](../../document/classes/Document.md)[]\\>\n\n***\n\n### search()\n\n> **search**(`query`, `opts?`): `AsyncGenerator`\\<[`Document`](../../document/classes/Document.md)\\>\n\nSearch documents by name and content, most relevant first, auto-paginated.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `query` | `string` |\n| `opts?` | [`SearchOpts`](../../../search/interfaces/SearchOpts.md) |\n\n#### Returns\n\n`AsyncGenerator`\\<[`Document`](../../document/classes/Document.md)\\>\n\n***\n\n### systemSkills()\n\n> **systemSkills**(): `Promise`\\<[`SystemSkill`](../../system-skill/classes/SystemSkill.md)[]\\>\n\nThe built-in system skills: static AI instructions with no document\nbehind them. Unlike user skills they cannot be opened or edited.\n\n#### Returns\n\n`Promise`\\<[`SystemSkill`](../../system-skill/classes/SystemSkill.md)[]\\>\n\n***\n\n### validatePermissionsToken()\n\n> **validatePermissionsToken**(`token`): `Promise`\\<\\{ `accessLevel`: [`AccessLevel`](../../../../../generated/storage/types.gen/type-aliases/AccessLevel.md); `document`: [`Document`](../../document/classes/Document.md); `expiresAt`: `number`; `issuer`: `string`; `user`: [`User`](../../../users/user/classes/User.md) \\| `undefined`; \\}\\>\n\nValidate a permissions token, returning its document and optional user handles.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `token` | `string` |\n\n#### Returns\n\n`Promise`\\<\\{ `accessLevel`: [`AccessLevel`](../../../../../generated/storage/types.gen/type-aliases/AccessLevel.md); `document`: [`Document`](../../document/classes/Document.md); `expiresAt`: `number`; `issuer`: `string`; `user`: [`User`](../../../users/user/classes/User.md) \\| `undefined`; \\}\\>\n\n\n<!-- src/entities/documents/system-skill/classes/SystemSkill.md -->\n# Class: SystemSkill\n\nA built-in system skill: static, code-defined AI instructions that surface\nto AI like skill documents but have no document behind them. System skills\ncannot be opened, edited, or deleted; reference them in AI inputs by id the\nsame way as skill documents.\n\n## Properties\n\n| Property | Modifier | Type | Description |\n| ------ | ------ | ------ | ------ |\n| <a id=\"property-id\"></a> `id` | `readonly` | `string` | The well-known id the skill is referenced by in mentions and AI tools. |\n| <a id=\"property-name\"></a> `name` | `readonly` | `string` | The skill's display name. |\n\n## Methods\n\n### list()\n\n> `static` **list**(`client`): `Promise`\\<`SystemSkill`[]\\>\n\nThe built-in system skills, in display order.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n\n#### Returns\n\n`Promise`\\<`SystemSkill`[]\\>\n\n\n<!-- src/entities/documents/version/classes/DocumentVersion.md -->\n# Class: DocumentVersion\n\nAn immutable document version, scoped to its document.\n\n## Properties\n\n| Property | Modifier | Type | Description |\n| ------ | ------ | ------ | ------ |\n| <a id=\"property-document\"></a> `document` | `readonly` | [`Document`](../../document/classes/Document.md) | Parent document. |\n| <a id=\"property-id\"></a> `id` | `readonly` | `number` | Version number. |\n\n## Methods\n\n### read()\n\n> **read**(): `Promise`\\<[`GetDocumentResponseData`](../../../../../generated/storage/types.gen/type-aliases/GetDocumentResponseData.md)\\>\n\nVersion metadata and the caller's access.\n\n#### Returns\n\n`Promise`\\<[`GetDocumentResponseData`](../../../../../generated/storage/types.gen/type-aliases/GetDocumentResponseData.md)\\>\n\n***\n\n### toJSON()\n\n> **toJSON**(): \\{ `documentId`: `string`; `id`: `number`; \\}\n\nSerialize only scoped identity.\n\n#### Returns\n\n\\{ `documentId`: `string`; `id`: `number`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `documentId` | `string` |\n| `id` | `number` |\n\n***\n\n### byId()\n\n> `static` **byId**(`client`, `document`, `id`): `DocumentVersion`\n\nConstruct a version handle.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `document` | [`Document`](../../document/classes/Document.md) |\n| `id` | `number` |\n\n#### Returns\n\n`DocumentVersion`\n"
},
{
"name": "email",
@@ -153,7 +153,7 @@
"name": "tasks",
"description": "Search, create, and update tasks.",
"overview": "<!-- src/entities/tasks/namespace/classes/TaskNamespace.md -->\n# Class: TaskNamespace\n\n## Constructors\n\n### Constructor\n\n> **new TaskNamespace**(`client`): `TaskNamespace`\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n\n#### Returns\n\n`TaskNamespace`\n\n## Methods\n\n### byId()\n\n> **byId**(`id`): [`Task`](../../task/classes/Task.md)\n\nA handle to a task by document id. Details load on first access.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `id` | `string` |\n\n#### Returns\n\n[`Task`](../../task/classes/Task.md)\n\n***\n\n### create()\n\n> **create**(`opts`): `Promise`\\<[`Task`](../../task/classes/Task.md)\\>\n\nCreate a task.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `opts` | \\{ `markdown?`: `string`; `name`: `string`; `project?`: [`Project`](../../../projects/project/classes/Project.md); `shareWithTeam?`: `boolean`; `team?`: [`Team`](../../../teams/team/classes/Team.md); \\} |\n| `opts.markdown?` | `string` |\n| `opts.name` | `string` |\n| `opts.project?` | [`Project`](../../../projects/project/classes/Project.md) |\n| `opts.shareWithTeam?` | `boolean` |\n| `opts.team?` | [`Team`](../../../teams/team/classes/Team.md) |\n\n#### Returns\n\n`Promise`\\<[`Task`](../../task/classes/Task.md)\\>\n\n***\n\n### forPullRequest()\n\n> **forPullRequest**(`url`): `Promise`\\<[`Task`](../../task/classes/Task.md)[]\\>\n\nThe tasks the GitHub pull request at `url` references, oldest link first.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `url` | `string` |\n\n#### Returns\n\n`Promise`\\<[`Task`](../../task/classes/Task.md)[]\\>\n\n***\n\n### search()\n\n> **search**(`query`, `opts?`): `AsyncGenerator`\\<[`Task`](../../task/classes/Task.md)\\>\n\nSearch tasks by name and content, most relevant first, auto-paginated.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `query` | `string` |\n| `opts?` | [`SearchOpts`](../../../search/interfaces/SearchOpts.md) |\n\n#### Returns\n\n`AsyncGenerator`\\<[`Task`](../../task/classes/Task.md)\\>\n",
- "documentation": "# Macro SDK: tasks\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/properties/types.gen/type-aliases/BulkUpdateEntityPropertyOptionsResponse.md -->\n# Type Alias: BulkUpdateEntityPropertyOptionsResponse\n\n> **BulkUpdateEntityPropertyOptionsResponse** = \\{ `properties`: [`EntityPropertyOptionSelectionResponse`](EntityPropertyOptionSelectionResponse.md)[]; \\}\n\nResponse for a bulk option update: each property's reconciled final ids.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-properties\"></a> `properties` | [`EntityPropertyOptionSelectionResponse`](EntityPropertyOptionSelectionResponse.md)[] | The final option ids per updated property. |\n\n\n<!-- generated/properties/types.gen/type-aliases/DataType.md -->\n# Type Alias: DataType\n\n> **DataType** = `\"BOOLEAN\"` \\| `\"DATE\"` \\| `\"NUMBER\"` \\| `\"STRING\"` \\| `\"SELECT_NUMBER\"` \\| `\"SELECT_STRING\"` \\| `\"TAG\"` \\| `\"ENTITY\"` \\| `\"LINK\"`\n\nData type for property values, determining storage and validation.\n\n\n<!-- generated/properties/types.gen/type-aliases/EntityProperty.md -->\n# Type Alias: EntityProperty\n\n> **EntityProperty** = \\{ `created_at`: `string`; `entity_id`: `string`; `entity_type`: [`EntityType`](EntityType.md); `id`: `string`; `property_definition_id`: `string`; `updated_at`: `string`; \\}\n\nAssignment of a property definition to a specific entity (service representation).\n\n## Properties\n\n| Property | Type |\n| ------ | ------ |\n| <a id=\"property-created_at\"></a> `created_at` | `string` |\n| <a id=\"property-entity_id\"></a> `entity_id` | `string` |\n| <a id=\"property-entity_type\"></a> `entity_type` | [`EntityType`](EntityType.md) |\n| <a id=\"property-id\"></a> `id` | `string` |\n| <a id=\"property-property_definition_id\"></a> `property_definition_id` | `string` |\n| <a id=\"property-updated_at\"></a> `updated_at` | `string` |\n\n\n<!-- generated/properties/types.gen/type-aliases/EntityPropertyOptionSelectionResponse.md -->\n# Type Alias: EntityPropertyOptionSelectionResponse\n\n> **EntityPropertyOptionSelectionResponse** = \\{ `option_ids`: `string`[]; `property_id`: `string`; \\}\n\nThe reconciled final option ids stored for one property after a bulk update.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-option_ids\"></a> `option_ids` | `string`[] | The final option ids the server persisted, in stored order. |\n| <a id=\"property-property_id\"></a> `property_id` | `string` | The property definition the options belong to. |\n\n\n<!-- generated/properties/types.gen/type-aliases/EntityPropertyWithDefinition.md -->\n# Type Alias: EntityPropertyWithDefinition\n\n> **EntityPropertyWithDefinition** = \\{ `definition`: [`PropertyDefinition`](PropertyDefinition.md); `options?`: [`PropertyOption`](PropertyOption.md)[] \\| `null`; `property`: [`EntityProperty`](EntityProperty.md); `value?`: `null` \\| [`PropertyValue`](PropertyValue.md); \\}\n\nEntity property with its definition, value, and options (service representation).\n\n## Properties\n\n| Property | Type |\n| ------ | ------ |\n| <a id=\"property-definition\"></a> `definition` | [`PropertyDefinition`](PropertyDefinition.md) |\n| <a id=\"property-options\"></a> `options?` | [`PropertyOption`](PropertyOption.md)[] \\| `null` |\n| <a id=\"property-property\"></a> `property` | [`EntityProperty`](EntityProperty.md) |\n| <a id=\"property-value\"></a> `value?` | `null` \\| [`PropertyValue`](PropertyValue.md) |\n\n\n<!-- generated/properties/types.gen/type-aliases/EntityReference.md -->\n# Type Alias: EntityReference\n\n> **EntityReference** = \\{ `entity_id`: `string`; `entity_type`: [`EntityType`](EntityType.md); `specific_message_id?`: `string` \\| `null`; \\}\n\nEntity reference for entity-type property values.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-entity_id\"></a> `entity_id` | `string` | - |\n| <a id=\"property-entity_type\"></a> `entity_type` | [`EntityType`](EntityType.md) | - |\n| <a id=\"property-specific_message_id\"></a> `specific_message_id?` | `string` \\| `null` | For CHANNEL, CHAT, THREAD entity types - optional specific message ID. This allows referencing a specific message within a thread/channel/chat. |\n\n\n<!-- generated/properties/types.gen/type-aliases/EntityType.md -->\n# Type Alias: EntityType\n\n> **EntityType** = `\"CALENDAR_EVENT\"` \\| `\"CALL_RECORD\"` \\| `\"CHANNEL\"` \\| `\"CHAT\"` \\| `\"COMPANY\"` \\| `\"DATABASE_ROW\"` \\| `\"CONTACT\"` \\| `\"DOCUMENT\"` \\| `\"INITIATIVE\"` \\| `\"PROJECT\"` \\| `\"TASK\"` \\| `\"THREAD\"` \\| `\"USER\"`\n\nType of entity that can be referenced by entity properties.\n\n\n<!-- generated/properties/types.gen/type-aliases/PropertyDefinition.md -->\n# Type Alias: PropertyDefinition\n\n> **PropertyDefinition** = \\{ `created_at`: `string`; `data_type`: [`DataType`](DataType.md); `display_name`: `string`; `id`: `string`; `is_metadata`: `boolean`; `is_multi_select`: `boolean`; `is_system`: `boolean`; `owner`: [`PropertyOwner`](PropertyOwner.md); `specific_entity_type`: `null` \\| [`EntityType`](EntityType.md); `updated_at`: `string`; \\}\n\nProperty definition model (service representation).\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-created_at\"></a> `created_at` | `string` | - |\n| <a id=\"property-data_type\"></a> `data_type` | [`DataType`](DataType.md) | - |\n| <a id=\"property-display_name\"></a> `display_name` | `string` | - |\n| <a id=\"property-id\"></a> `id` | `string` | - |\n| <a id=\"property-is_metadata\"></a> `is_metadata` | `boolean` | Flag to indicate if this is a system-generated metadata property. Not stored in database - computed at service layer. |\n| <a id=\"property-is_multi_select\"></a> `is_multi_select` | `boolean` | - |\n| <a id=\"property-is_system\"></a> `is_system` | `boolean` | Flag to indicate if this is a system property (stored in DB). |\n| <a id=\"property-owner\"></a> `owner` | [`PropertyOwner`](PropertyOwner.md) | - |\n| <a id=\"property-specific_entity_type\"></a> `specific_entity_type` | `null` \\| [`EntityType`](EntityType.md) | - |\n| <a id=\"property-updated_at\"></a> `updated_at` | `string` | - |\n\n\n<!-- generated/properties/types.gen/type-aliases/PropertyOption.md -->\n# Type Alias: PropertyOption\n\n> **PropertyOption** = \\{ `color`: `string` \\| `null`; `created_at`: `string`; `display_order`: `number`; `id`: `string`; `property_definition_id`: `string`; `updated_at`: `string`; `value`: [`PropertyOptionValue`](PropertyOptionValue.md); \\}\n\nA selectable option for select-type properties (service representation).\n\n## Properties\n\n| Property | Type |\n| ------ | ------ |\n| <a id=\"property-color\"></a> `color` | `string` \\| `null` |\n| <a id=\"property-created_at\"></a> `created_at` | `string` |\n| <a id=\"property-display_order\"></a> `display_order` | `number` |\n| <a id=\"property-id\"></a> `id` | `string` |\n| <a id=\"property-property_definition_id\"></a> `property_definition_id` | `string` |\n| <a id=\"property-updated_at\"></a> `updated_at` | `string` |\n| <a id=\"property-value\"></a> `value` | [`PropertyOptionValue`](PropertyOptionValue.md) |\n\n\n<!-- generated/properties/types.gen/type-aliases/PropertyOptionValue.md -->\n# Type Alias: PropertyOptionValue\n\n> **PropertyOptionValue** = \\{ `type`: `\"string\"`; `value`: `string`; \\} \\| \\{ `type`: `\"number\"`; `value`: `number`; \\}\n\nThe value of a property option - either a string or a number.\n\n## Union Members\n\n### Type Literal\n\n\\{ `type`: `\"string\"`; `value`: `string`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `type` | `\"string\"` | - |\n| `value` | `string` | String value for SelectString properties |\n\n***\n\n### Type Literal\n\n\\{ `type`: `\"number\"`; `value`: `number`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `type` | `\"number\"` | - |\n| `value` | `number` | Number value for SelectNumber properties |\n\n\n<!-- generated/properties/types.gen/type-aliases/PropertyOwner.md -->\n# Type Alias: PropertyOwner\n\n> **PropertyOwner** = \\{ `scope`: `\"user\"`; `user_id`: `string`; \\} \\| \\{ `scope`: `\"team\"`; `team_id`: `string`; \\} \\| \\{ `database_id`: `string`; `scope`: `\"database\"`; \\} \\| \\{ `scope`: `\"system\"`; \\}\n\nDefines who owns a property - user-scoped, team-scoped, database-scoped, or system.\n\n\n<!-- generated/properties/types.gen/type-aliases/PropertyTargetEntityType.md -->\n# Type Alias: PropertyTargetEntityType\n\n> **PropertyTargetEntityType** = `\"CALL_RECORD\"` \\| `\"CHANNEL\"` \\| `\"CHAT\"` \\| `\"COMPANY\"` \\| `\"DATABASE_ROW\"` \\| `\"DOCUMENT\"` \\| `\"INITIATIVE\"` \\| `\"PROJECT\"` \\| `\"THREAD\"` \\| `\"USER\"`\n\nCanonical type of an entity receiving properties.\n\nTasks are documents at API boundaries. `Task` intentionally does not exist\nhere; task classification is resolved by the properties domain from the\ndocument subtype.\n\n\n<!-- generated/properties/types.gen/type-aliases/PropertyTargetReference.md -->\n# Type Alias: PropertyTargetReference\n\n> **PropertyTargetReference** = \\{ `entity_id`: `string`; `entity_type`: [`PropertyTargetEntityType`](PropertyTargetEntityType.md); \\}\n\nCanonical reference to an entity receiving properties.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-entity_id\"></a> `entity_id` | `string` | Entity identifier. |\n| <a id=\"property-entity_type\"></a> `entity_type` | [`PropertyTargetEntityType`](PropertyTargetEntityType.md) | Canonical entity type. |\n\n\n<!-- generated/properties/types.gen/type-aliases/PropertyValue.md -->\n# Type Alias: PropertyValue\n\n> **PropertyValue** = \\{ `type`: `\"Boolean\"`; `value`: `boolean`; \\} \\| \\{ `type`: `\"Number\"`; `value`: `number`; \\} \\| \\{ `type`: `\"String\"`; `value`: `string`; \\} \\| \\{ `type`: `\"Date\"`; `value`: `string`; \\} \\| \\{ `type`: `\"SelectOption\"`; `value`: `string`[]; \\} \\| \\{ `type`: `\"EntityReference\"`; `value`: [`EntityReference`](EntityReference.md)[]; \\} \\| \\{ `type`: `\"Link\"`; `value`: `string`[]; \\}\n\nProperty value (service representation).\n\nRepresents the actual value stored for an entity property.\nThis is serialized to/from JSONB in the database.\n\n## Union Members\n\n### Type Literal\n\n\\{ `type`: `\"Boolean\"`; `value`: `boolean`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `type` | `\"Boolean\"` | - |\n| `value` | `boolean` | Boolean value Serializes as: {\"type\": \"Boolean\", \"value\": true} |\n\n***\n\n### Type Literal\n\n\\{ `type`: `\"Number\"`; `value`: `number`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `type` | `\"Number\"` | - |\n| `value` | `number` | Numeric value Serializes as: {\"type\": \"Number\", \"value\": 42.5} |\n\n***\n\n### Type Literal\n\n\\{ `type`: `\"String\"`; `value`: `string`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `type` | `\"String\"` | - |\n| `value` | `string` | String value Serializes as: {\"type\": \"String\", \"value\": \"text\"} |\n\n***\n\n### Type Literal\n\n\\{ `type`: `\"Date\"`; `value`: `string`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `type` | `\"Date\"` | - |\n| `value` | `string` | Date/timestamp value Serializes as: {\"type\": \"Date\", \"value\": \"2025-01-01T00:00:00Z\"} |\n\n***\n\n### Type Literal\n\n\\{ `type`: `\"SelectOption\"`; `value`: `string`[]; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `type` | `\"SelectOption\"` | - |\n| `value` | `string`[] | Select option(s) - always an array (check is_multi_select to determine if single or multi) Single-select: {\"type\": \"SelectOption\", \"value\": [\"uuid\"]} (length 0 or 1) Multi-select: {\"type\": \"SelectOption\", \"value\": [\"uuid1\", \"uuid2\", ...]} (length 0+) |\n\n***\n\n### Type Literal\n\n\\{ `type`: `\"EntityReference\"`; `value`: [`EntityReference`](EntityReference.md)[]; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `type` | `\"EntityReference\"` | - |\n| `value` | [`EntityReference`](EntityReference.md)[] | Entity reference(s) - always an array (check is_multi_select to determine if single or multi) Single-select: {\"type\": \"EntityReference\", \"value\": [{...}]} (length 0 or 1) Multi-select: {\"type\": \"EntityReference\", \"value\": [{...}, {...}, ...]} (length 0+) |\n\n***\n\n### Type Literal\n\n\\{ `type`: `\"Link\"`; `value`: `string`[]; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `type` | `\"Link\"` | - |\n| `value` | `string`[] | Link value(s) - always an array (check is_multi_select to determine if single or multi) Single-select: {\"type\": \"Link\", \"value\": [\"https://example.com\"]} (length 0 or 1) Multi-select: {\"type\": \"Link\", \"value\": [\"https://example.com\", \"https://other.com\"]} (length 0+) |\n\n\n<!-- generated/properties/types.gen/type-aliases/SetPropertyValue.md -->\n# Type Alias: SetPropertyValue\n\n> **SetPropertyValue** = \\{ `type`: `\"boolean\"`; `value`: `boolean`; \\} \\| \\{ `type`: `\"date\"`; `value`: `string`; \\} \\| \\{ `type`: `\"number\"`; `value`: `number`; \\} \\| \\{ `type`: `\"string\"`; `value`: `string`; \\} \\| \\{ `option_id`: `string`; `type`: `\"select_option\"`; \\} \\| \\{ `option_ids`: `string`[]; `type`: `\"multi_select_option\"`; \\} \\| \\{ `reference`: [`EntityReference`](EntityReference.md); `type`: `\"entity_reference\"`; \\} \\| \\{ `references`: [`EntityReference`](EntityReference.md)[]; `type`: `\"multi_entity_reference\"`; \\} \\| \\{ `type`: `\"link\"`; `url`: `string`; \\} \\| \\{ `type`: `\"multi_link\"`; `urls`: `string`[]; \\}\n\nType-safe enum for setting entity property values - provides compile-time validation.\n\n\n<!-- generated/storage/types.gen/type-aliases/AccessLevel.md -->\n# Type Alias: AccessLevel\n\n> **AccessLevel** = `\"view\"` \\| `\"comment\"` \\| `\"edit\"` \\| `\"owner\"`\n\nOrdered from least to most access top -> bottom\n\n\n<!-- generated/storage/types.gen/type-aliases/BomPart.md -->\n# Type Alias: BomPart\n\n> **BomPart** = \\{ `id`: `string`; `path`: `string`; `sha`: `string`; \\}\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-id\"></a> `id` | `string` | The uuid of the bom part |\n| <a id=\"property-path\"></a> `path` | `string` | The file path of the bom part content |\n| <a id=\"property-sha\"></a> `sha` | `string` | The sha of the bom part content There is an index on sha for more performant queries based on it. |\n\n\n<!-- generated/storage/types.gen/type-aliases/ChannelSharePermission.md -->\n# Type Alias: ChannelSharePermission\n\n> **ChannelSharePermission** = \\{ `access_level`: [`AccessLevel`](AccessLevel.md); `channel_id`: `string`; \\}\n\nThe channel share permission\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-access_level\"></a> `access_level` | [`AccessLevel`](AccessLevel.md) | The access level for the channel |\n| <a id=\"property-channel_id\"></a> `channel_id` | `string` | The channel id |\n\n\n<!-- generated/storage/types.gen/type-aliases/DocumentContent.md -->\n# Type Alias: DocumentContent\n\n> **DocumentContent** = \\{ `location?`: `null` \\| [`DocumentContentLocation`](DocumentContentLocation.md); `state`: [`DocumentContentState`](DocumentContentState.md); \\}\n\nAPI-visible content lifecycle and location metadata.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-location\"></a> `location?` | `null` \\| [`DocumentContentLocation`](DocumentContentLocation.md) | - |\n| <a id=\"property-state\"></a> `state` | [`DocumentContentState`](DocumentContentState.md) | The current lifecycle state of the content. |\n\n\n<!-- generated/storage/types.gen/type-aliases/DocumentContentLocation.md -->\n# Type Alias: DocumentContentLocation\n\n> **DocumentContentLocation** = `\"object_storage\"` \\| `\"sync_service\"` \\| `\"docx_bom_parts\"` \\| `\"converted_pdf\"` \\| `\"unknown\"`\n\nWhere document content is, or is expected to be, read from.\n\n\n<!-- generated/storage/types.gen/type-aliases/DocumentContentState.md -->\n# Type Alias: DocumentContentState\n\n> **DocumentContentState** = `\"unknown\"` \\| `\"pending\"` \\| `\"ready\"`\n\nAPI-visible content lifecycle state derived from current document metadata.\n\n\n<!-- generated/storage/types.gen/type-aliases/DocumentMetadata.md -->\n# Type Alias: DocumentMetadata\n\n> **DocumentMetadata** = \\{ `branchedFromId?`: `string` \\| `null`; `branchedFromVersionId?`: `number` \\| `null`; `createdAt?`: `string` \\| `null`; `deletedAt?`: `string` \\| `null`; `documentBom?`: [`BomPart`](BomPart.md)[] \\| `null`; `documentFamilyId?`: `number` \\| `null`; `documentId`: `string`; `documentName`: `string`; `documentVersionId`: `number`; `fileType?`: `string` \\| `null`; `modificationData?`: `unknown`; `owner`: `string`; `projectId?`: `string` \\| `null`; `projectName?`: `string` \\| `null`; `sha?`: `string` \\| `null`; `subType?`: `null` \\| [`DocumentSubType`](DocumentSubType.md); `updatedAt?`: `string` \\| `null`; \\}\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-branchedfromid\"></a> `branchedFromId?` | `string` \\| `null` | The id of the document this document branched from |\n| <a id=\"property-branchedfromversionid\"></a> `branchedFromVersionId?` | `number` \\| `null` | The id of the version this document branched from This could be either DocumentInstance or DocumentBom id depending on the file type |\n| <a id=\"property-createdat\"></a> `createdAt?` | `string` \\| `null` | The time the document was created |\n| <a id=\"property-deletedat\"></a> `deletedAt?` | `string` \\| `null` | The time the document was deleted |\n| <a id=\"property-documentbom\"></a> `documentBom?` | [`BomPart`](BomPart.md)[] \\| `null` | If the document is a DOCX document and unzipped, the document_bom will be present |\n| <a id=\"property-documentfamilyid\"></a> `documentFamilyId?` | `number` \\| `null` | The id of the document family this document belongs to |\n| <a id=\"property-documentid\"></a> `documentId` | `string` | The document id |\n| <a id=\"property-documentname\"></a> `documentName` | `string` | The name of the document |\n| <a id=\"property-documentversionid\"></a> `documentVersionId` | `number` | The version of the document This could be the document_instance_id or document_bom_id depending on the file type |\n| <a id=\"property-filetype\"></a> `fileType?` | `string` \\| `null` | The file type of the document (file extension) |\n| <a id=\"property-modificationdata\"></a> `modificationData?` | `unknown` | The modification data for the document instance. This is only used for PDF documents. |\n| <a id=\"property-owner\"></a> `owner` | `string` | The owner of the document |\n| <a id=\"property-projectid\"></a> `projectId?` | `string` \\| `null` | The id of the project that this document belongs to |\n| <a id=\"property-projectname\"></a> `projectName?` | `string` \\| `null` | The name of the project that this document belongs to |\n| <a id=\"property-sha\"></a> `sha?` | `string` \\| `null` | If the document is a PDF, this is the SHA of the pdf If the document is a DOCX, this will not be present |\n| <a id=\"property-subtype\"></a> `subType?` | `null` \\| [`DocumentSubType`](DocumentSubType.md) | - |\n| <a id=\"property-updatedat\"></a> `updatedAt?` | `string` \\| `null` | The time the document instance / document BOM was updated |\n\n\n<!-- generated/storage/types.gen/type-aliases/DocumentMetadataWithContent.md -->\n# Type Alias: DocumentMetadataWithContent\n\n> **DocumentMetadataWithContent** = [`DocumentMetadata`](DocumentMetadata.md) & \\{ `content`: [`DocumentContent`](DocumentContent.md); `teamId?`: `string` \\| `null`; `teamTaskId?`: `number` \\| `null`; \\}\n\nFull document metadata plus content lifecycle metadata.\n\n## Type Declaration\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `content` | [`DocumentContent`](DocumentContent.md) | Content lifecycle and location metadata. |\n| `teamId?` | `string` \\| `null` | The team this task number is scoped to, for task documents. |\n| `teamTaskId?` | `number` \\| `null` | The task number assigned within the team, for task documents. |\n\n\n<!-- generated/storage/types.gen/type-aliases/DocumentResponseMetadata.md -->\n# Type Alias: DocumentResponseMetadata\n\n> **DocumentResponseMetadata** = \\{ `branchedFromId?`: `string` \\| `null`; `branchedFromVersionId?`: `number` \\| `null`; `createdAt?`: `string` \\| `null`; `documentBom?`: [`BomPart`](BomPart.md)[] \\| `null`; `documentFamilyId?`: `number` \\| `null`; `documentId`: `string`; `documentName`: `string`; `documentVersionId`: `number`; `fileType?`: `string` \\| `null`; `modificationData?`: `unknown`; `owner`: `string`; `sha?`: `string` \\| `null`; `subType?`: `null` \\| [`DocumentSubType`](DocumentSubType.md); `updatedAt?`: `string` \\| `null`; \\}\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-branchedfromid\"></a> `branchedFromId?` | `string` \\| `null` | The id of the document this document branched from |\n| <a id=\"property-branchedfromversionid\"></a> `branchedFromVersionId?` | `number` \\| `null` | The id of the version this document branched from This could be either DocumentInstance or DocumentBom id depending on the file type |\n| <a id=\"property-createdat\"></a> `createdAt?` | `string` \\| `null` | The time the document was created |\n| <a id=\"property-documentbom\"></a> `documentBom?` | [`BomPart`](BomPart.md)[] \\| `null` | If the document is a DOCX document, the document_bom will be present |\n| <a id=\"property-documentfamilyid\"></a> `documentFamilyId?` | `number` \\| `null` | The id of the document family this document belongs to |\n| <a id=\"property-documentid\"></a> `documentId` | `string` | The document id |\n| <a id=\"property-documentname\"></a> `documentName` | `string` | The name of the document |\n| <a id=\"property-documentversionid\"></a> `documentVersionId` | `number` | The version of the document This could be the document_instance_id or document_bom_id depending on the file type |\n| <a id=\"property-filetype\"></a> `fileType?` | `string` \\| `null` | The file type of the document |\n| <a id=\"property-modificationdata\"></a> `modificationData?` | `unknown` | The modification data for the document instance. This is only used for PDF documents. |\n| <a id=\"property-owner\"></a> `owner` | `string` | The owner of the document |\n| <a id=\"property-sha\"></a> `sha?` | `string` \\| `null` | If the document is a PDF, this is the SHA of the pdf If the document is a DOCX, this will not be present |\n| <a id=\"property-subtype\"></a> `subType?` | `null` \\| [`DocumentSubType`](DocumentSubType.md) | - |\n| <a id=\"property-updatedat\"></a> `updatedAt?` | `string` \\| `null` | The time the document instance / document BOM was updated |\n\n\n<!-- generated/storage/types.gen/type-aliases/DocumentSubType.md -->\n# Type Alias: DocumentSubType\n\n> **DocumentSubType** = `\"task\"` \\| `\"snippet\"` \\| `\"skill\"` \\| `\"initiative_description\"`\n\nThe document sub type enum represents all values of document sub types.\nThese values should match the `document_sub_type_value` table in macrodb.\n\nWire, database, and `Display` spellings are all `snake_case` so a\nmulti-word variant serializes identically in every system.\n\n\n<!-- generated/storage/types.gen/type-aliases/DocumentTeamShareResponse.md -->\n# Type Alias: DocumentTeamShareResponse\n\n> **DocumentTeamShareResponse** = \\{ `sharedWithTeam`: `boolean`; `teamId?`: `string` \\| `null`; \\}\n\nThe team-share state of a document. The team is resolved from the document\nowner's team membership.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-sharedwithteam\"></a> `sharedWithTeam` | `boolean` | Whether explicit team sharing is enabled; inherited team access does not count. |\n| <a id=\"property-teamid\"></a> `teamId?` | `string` \\| `null` | The owner's team the document is (or would be) shared with. `None` when the owner does not belong to a team. |\n\n\n<!-- generated/storage/types.gen/type-aliases/EntityPermission.md -->\n# Type Alias: EntityPermission\n\n> **EntityPermission** = \\{ `access_level`: [`AccessLevel`](AccessLevel.md); `type`: `\"access_level\"`; \\} \\| \\{ `type`: `\"channel_view_only\"`; \\} \\| \\{ `role`: [`ParticipantRole`](ParticipantRole.md); `type`: `\"channel_role\"`; \\} \\| \\{ `role`: [`TeamRole`](TeamRole.md); `type`: `\"team_role\"`; \\}\n\nA user's permission for an entity, discriminated by entity kind.\n\nItems (documents, chats, projects, threads) use access levels.\nChannels use view-only permission or participant roles.\n\n## Union Members\n\n### Type Literal\n\n\\{ `access_level`: [`AccessLevel`](AccessLevel.md); `type`: `\"access_level\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `access_level` | [`AccessLevel`](AccessLevel.md) | The access level the user has. |\n| `type` | `\"access_level\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `type`: `\"channel_view_only\"`; \\}\n\n***\n\n### Type Literal\n\n\\{ `role`: [`ParticipantRole`](ParticipantRole.md); `type`: `\"channel_role\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `role` | [`ParticipantRole`](ParticipantRole.md) | The role the user has in the channel. |\n| `type` | `\"channel_role\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `role`: [`TeamRole`](TeamRole.md); `type`: `\"team_role\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `role` | [`TeamRole`](TeamRole.md) | The role the user has in the team. |\n| `type` | `\"team_role\"` | - |\n\n\n<!-- generated/storage/types.gen/type-aliases/GithubPullRequest.md -->\n# Type Alias: GithubPullRequest\n\n> **GithubPullRequest** = \\{ `additions?`: `number` \\| `null`; `checks?`: [`GithubPullRequestCheckRun`](GithubPullRequestCheckRun.md)[] \\| `null`; `comments?`: [`GithubPullRequestComment`](GithubPullRequestComment.md)[] \\| `null`; `deletions?`: `number` \\| `null`; `displayName`: `string`; `foreignEntityId?`: `string` \\| `null`; `githubKey`: `string`; `name?`: `string` \\| `null`; `number`: `number`; `owner`: `string`; `repo`: `string`; `status?`: `string` \\| `null`; `url`: `string`; \\}\n\nDisplay-ready data for a GitHub pull request associated with a task.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-additions\"></a> `additions?` | `number` \\| `null` | The number of added lines in the pull request, when enrichment data is available. |\n| <a id=\"property-checks\"></a> `checks?` | [`GithubPullRequestCheckRun`](GithubPullRequestCheckRun.md)[] \\| `null` | Check runs collected from the pull request head commit, when enrichment data is available. |\n| <a id=\"property-comments\"></a> `comments?` | [`GithubPullRequestComment`](GithubPullRequestComment.md)[] \\| `null` | Comments collected from the pull request, when enrichment data is available. |\n| <a id=\"property-deletions\"></a> `deletions?` | `number` \\| `null` | The number of deleted lines in the pull request, when enrichment data is available. |\n| <a id=\"property-displayname\"></a> `displayName` | `string` | A compact label suitable for display in the UI. |\n| <a id=\"property-foreignentityid\"></a> `foreignEntityId?` | `string` \\| `null` | The internal `foreign_entity.id` UUID for the GitHub pull request row. |\n| <a id=\"property-githubkey\"></a> `githubKey` | `string` | The stored GitHub association key, in `owner/repo/pull/number` format. |\n| <a id=\"property-name\"></a> `name?` | `string` \\| `null` | The GitHub pull request title, when enrichment data is available. |\n| <a id=\"property-number\"></a> `number` | `number` | The GitHub pull request number. |\n| <a id=\"property-owner\"></a> `owner` | `string` | The GitHub repository owner or organization. |\n| <a id=\"property-repo\"></a> `repo` | `string` | The GitHub repository name. |\n| <a id=\"property-status\"></a> `status?` | `string` \\| `null` | The GitHub pull request status, when enrichment data is available. |\n| <a id=\"property-url\"></a> `url` | `string` | The public GitHub URL for the pull request. |\n\n\n<!-- generated/storage/types.gen/type-aliases/GithubPullRequestCheckRun.md -->\n# Type Alias: GithubPullRequestCheckRun\n\n> **GithubPullRequestCheckRun** = \\{ `completedAt?`: `string` \\| `null`; `conclusion?`: `string` \\| `null`; `id`: `number`; `name`: `string`; `startedAt?`: `string` \\| `null`; `status`: `string`; `url?`: `string` \\| `null`; \\}\n\nA check run associated with a GitHub pull request.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-completedat\"></a> `completedAt?` | `string` \\| `null` | When the check run completed, when available. |\n| <a id=\"property-conclusion\"></a> `conclusion?` | `string` \\| `null` | The raw GitHub check run conclusion, when the run has completed. |\n| <a id=\"property-id\"></a> `id` | `number` | The unique GitHub identifier for the check run. |\n| <a id=\"property-name\"></a> `name` | `string` | The check run name. |\n| <a id=\"property-startedat\"></a> `startedAt?` | `string` \\| `null` | When the check run started, when available. |\n| <a id=\"property-status\"></a> `status` | `string` | The raw GitHub check run status. |\n| <a id=\"property-url\"></a> `url?` | `string` \\| `null` | The public GitHub URL for the check run, when available. |\n\n\n<!-- generated/storage/types.gen/type-aliases/GithubPullRequestComment.md -->\n# Type Alias: GithubPullRequestComment\n\n> **GithubPullRequestComment** = \\{ `authorAssociation?`: `string` \\| `null`; `authorId?`: `number` \\| `null`; `authorLogin?`: `string` \\| `null`; `body`: `string`; `createdAt?`: `string` \\| `null`; `id`: `number`; `inReplyToId?`: `number` \\| `null`; `line?`: `number` \\| `null`; `originalLine?`: `number` \\| `null`; `path?`: `string` \\| `null`; `pullRequestReviewId?`: `number` \\| `null`; `source`: `string`; `updatedAt?`: `string` \\| `null`; `url?`: `string` \\| `null`; \\}\n\nA comment associated with a GitHub pull request.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-authorassociation\"></a> `authorAssociation?` | `string` \\| `null` | GitHub's relationship label for the author, when available. |\n| <a id=\"property-authorid\"></a> `authorId?` | `number` \\| `null` | The stable numeric GitHub user id for the comment author, when available. |\n| <a id=\"property-authorlogin\"></a> `authorLogin?` | `string` \\| `null` | The GitHub login for the comment author, when available. |\n| <a id=\"property-body\"></a> `body` | `string` | The comment or review body text. |\n| <a id=\"property-createdat\"></a> `createdAt?` | `string` \\| `null` | When the comment was created or the review was submitted. |\n| <a id=\"property-id\"></a> `id` | `number` | The unique GitHub identifier for the comment or review. |\n| <a id=\"property-inreplytoid\"></a> `inReplyToId?` | `number` \\| `null` | The id of the comment this one replies to, when it is part of a review thread. Only ever present on `review_comment` sources. |\n| <a id=\"property-line\"></a> `line?` | `number` \\| `null` | The line in the current diff the comment is anchored to. Cleared by GitHub when later commits outdate the comment's diff. |\n| <a id=\"property-originalline\"></a> `originalLine?` | `number` \\| `null` | The line the comment was originally anchored to, kept even when the diff has since changed. |\n| <a id=\"property-path\"></a> `path?` | `string` \\| `null` | The repository-relative file path the review comment is anchored to. Only ever present on `review_comment` sources. |\n| <a id=\"property-pullrequestreviewid\"></a> `pullRequestReviewId?` | `number` \\| `null` | The id of the pull request review this comment was submitted with. Only ever present on `review_comment` sources. |\n| <a id=\"property-source\"></a> `source` | `string` | The GitHub source for the comment, such as `issue_comment` or `review_comment`. |\n| <a id=\"property-updatedat\"></a> `updatedAt?` | `string` \\| `null` | When the comment or review was last updated. |\n| <a id=\"property-url\"></a> `url?` | `string` \\| `null` | The public GitHub URL for the comment or review, when available. |\n\n\n<!-- generated/storage/types.gen/type-aliases/HighlightType.md -->\n# Type Alias: HighlightType\n\n> **HighlightType** = `1` \\| `2` \\| `3`\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkShare.md -->\n# Type Alias: LinkShare\n\n> **LinkShare** = `\"PUBLIC\"` \\| `\"TEAM\"`\n\nDefines who can access an item through its share link.\n\n\n<!-- generated/storage/types.gen/type-aliases/MessageCursor.md -->\n# Type Alias: MessageCursor\n\n> **MessageCursor** = \\{ `created_at`: `string`; `id`: `string`; \\}\n\nCursor for a chronological parent timeline.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-created_at\"></a> `created_at` | `string` | Last message creation time or activity occurrence time. |\n| <a id=\"property-id\"></a> `id` | `string` | Last entry UUID, used to break timestamp ties across both sources. |\n\n\n<!-- generated/storage/types.gen/type-aliases/ParticipantRole.md -->\n# Type Alias: ParticipantRole\n\n> **ParticipantRole** = `\"owner\"` \\| `\"admin\"` \\| `\"member\"`\n\nThe role a user has within a channel.\n\n\n<!-- generated/storage/types.gen/type-aliases/PdfHighlightAnchorRequest.md -->\n# Type Alias: PdfHighlightAnchorRequest\n\n> **PdfHighlightAnchorRequest** = \\{ `alpha`: `number`; `blue`: `number`; `green`: `number`; `highlightRects`: [`PdfHighlightRectAnchorRequest`](PdfHighlightRectAnchorRequest.md)[]; `highlightType`: [`HighlightType`](HighlightType.md); `page`: `number`; `pageViewportHeight`: `number`; `pageViewportWidth`: `number`; `red`: `number`; `text`: `string`; `uuid?`: `string` \\| `null`; \\}\n\n## Properties\n\n| Property | Type |\n| ------ | ------ |\n| <a id=\"property-alpha\"></a> `alpha` | `number` |\n| <a id=\"property-blue\"></a> `blue` | `number` |\n| <a id=\"property-green\"></a> `green` | `number` |\n| <a id=\"property-highlightrects\"></a> `highlightRects` | [`PdfHighlightRectAnchorRequest`](PdfHighlightRectAnchorRequest.md)[] |\n| <a id=\"property-highlighttype\"></a> `highlightType` | [`HighlightType`](HighlightType.md) |\n| <a id=\"property-page\"></a> `page` | `number` |\n| <a id=\"property-pageviewportheight\"></a> `pageViewportHeight` | `number` |\n| <a id=\"property-pageviewportwidth\"></a> `pageViewportWidth` | `number` |\n| <a id=\"property-red\"></a> `red` | `number` |\n| <a id=\"property-text\"></a> `text` | `string` |\n| <a id=\"property-uuid\"></a> `uuid?` | `string` \\| `null` |\n\n\n<!-- generated/storage/types.gen/type-aliases/PdfHighlightRectAnchorRequest.md -->\n# Type Alias: PdfHighlightRectAnchorRequest\n\n> **PdfHighlightRectAnchorRequest** = \\{ `height`: `number`; `left`: `number`; `top`: `number`; `width`: `number`; \\}\n\n## Properties\n\n| Property | Type |\n| ------ | ------ |\n| <a id=\"property-height\"></a> `height` | `number` |\n| <a id=\"property-left\"></a> `left` | `number` |\n| <a id=\"property-top\"></a> `top` | `number` |\n| <a id=\"property-width\"></a> `width` | `number` |\n\n\n<!-- generated/storage/types.gen/type-aliases/PreSaveDocumentResponseData.md -->\n# Type Alias: PreSaveDocumentResponseData\n\n> **PreSaveDocumentResponseData** = \\{ `presignedUrls`: [`PresignedUrl`](PresignedUrl.md)[]; \\}\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-presignedurls\"></a> `presignedUrls` | [`PresignedUrl`](PresignedUrl.md)[] | Contains any presigned urls you need to upload specific bom parts with. |\n\n\n<!-- generated/storage/types.gen/type-aliases/PresignedUrl.md -->\n# Type Alias: PresignedUrl\n\n> **PresignedUrl** = \\{ `presignedUrl`: `string`; `sha`: `string`; \\}\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-presignedurl\"></a> `presignedUrl` | `string` | The presigned url used to upload the sha |\n| <a id=\"property-sha\"></a> `sha` | `string` | The sha of the item |\n\n\n<!-- generated/storage/types.gen/type-aliases/SaveBomPart.md -->\n# Type Alias: SaveBomPart\n\n> **SaveBomPart** = \\{ `path`: `string`; `sha`: `string`; \\}\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-path\"></a> `path` | `string` | The file path of the bom part content |\n| <a id=\"property-sha\"></a> `sha` | `string` | The sha of the bom part content There is an index on sha for more performant queries based on it. |\n\n\n<!-- generated/storage/types.gen/type-aliases/SaveDocumentRequest.md -->\n# Type Alias: SaveDocumentRequest\n\n> **SaveDocumentRequest** = \\{ `modificationData?`: `unknown`; `newBom?`: [`SaveBomPart`](SaveBomPart.md)[] \\| `null`; `sha?`: `string` \\| `null`; \\}\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-modificationdata\"></a> `modificationData?` | `unknown` | The modification data for the document instance. Used to store highlights and other overlays onto a static file |\n| <a id=\"property-newbom\"></a> `newBom?` | [`SaveBomPart`](SaveBomPart.md)[] \\| `null` | **DOCX ONLY** The updated BOM for the document. Containing the file path and the sha. |\n| <a id=\"property-sha\"></a> `sha?` | `string` \\| `null` | The sha of the new document. This is used to generate a presigned url to upload the new document content to s3. |\n\n\n<!-- generated/storage/types.gen/type-aliases/SaveDocumentResponseData.md -->\n# Type Alias: SaveDocumentResponseData\n\n> **SaveDocumentResponseData** = \\{ `documentMetadata`: [`DocumentResponseMetadata`](DocumentResponseMetadata.md); `presignedUrl?`: `string` \\| `null`; \\}\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-documentmetadata\"></a> `documentMetadata` | [`DocumentResponseMetadata`](DocumentResponseMetadata.md) | The updated document metadata |\n| <a id=\"property-presignedurl\"></a> `presignedUrl?` | `string` \\| `null` | If the document is an editable file, we provide a presigned url to save the updated file to. |\n\n\n<!-- generated/storage/types.gen/type-aliases/SharePermissionV2.md -->\n# Type Alias: SharePermissionV2\n\n> **SharePermissionV2** = \\{ `channelSharePermissions?`: [`ChannelSharePermission`](ChannelSharePermission.md)[] \\| `null`; `id`: `string`; `linkShare?`: `null` \\| [`LinkShare`](LinkShare.md); `linkShareAccessLevel?`: `null` \\| [`AccessLevel`](AccessLevel.md); `owner`: `string`; `teamShareAccessLevel?`: `null` \\| [`AccessLevel`](AccessLevel.md); \\}\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-channelsharepermissions\"></a> `channelSharePermissions?` | [`ChannelSharePermission`](ChannelSharePermission.md)[] \\| `null` | The channel share permissions for the item |\n| <a id=\"property-id\"></a> `id` | `string` | The share permission id |\n| <a id=\"property-linkshare\"></a> `linkShare?` | `null` \\| [`LinkShare`](LinkShare.md) | - |\n| <a id=\"property-linkshareaccesslevel\"></a> `linkShareAccessLevel?` | `null` \\| [`AccessLevel`](AccessLevel.md) | - |\n| <a id=\"property-owner\"></a> `owner` | `string` | The owner of the item |\n| <a id=\"property-teamshareaccesslevel\"></a> `teamShareAccessLevel?` | `null` \\| [`AccessLevel`](AccessLevel.md) | - |\n\n\n<!-- generated/storage/types.gen/type-aliases/TeamRole.md -->\n# Type Alias: TeamRole\n\n> **TeamRole** = `\"member\"` \\| `\"admin\"` \\| `\"owner\"`\n\nThe role a user has within a team.\n\nOrdered least to most privileged so comparisons reflect access strength.\n\n\n<!-- src/entities/tasks/namespace/classes/TaskNamespace.md -->\n# Class: TaskNamespace\n\n## Constructors\n\n### Constructor\n\n> **new TaskNamespace**(`client`): `TaskNamespace`\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n\n#### Returns\n\n`TaskNamespace`\n\n## Methods\n\n### byId()\n\n> **byId**(`id`): [`Task`](../../task/classes/Task.md)\n\nA handle to a task by document id. Details load on first access.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `id` | `string` |\n\n#### Returns\n\n[`Task`](../../task/classes/Task.md)\n\n***\n\n### create()\n\n> **create**(`opts`): `Promise`\\<[`Task`](../../task/classes/Task.md)\\>\n\nCreate a task.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `opts` | \\{ `markdown?`: `string`; `name`: `string`; `project?`: [`Project`](../../../projects/project/classes/Project.md); `shareWithTeam?`: `boolean`; `team?`: [`Team`](../../../teams/team/classes/Team.md); \\} |\n| `opts.markdown?` | `string` |\n| `opts.name` | `string` |\n| `opts.project?` | [`Project`](../../../projects/project/classes/Project.md) |\n| `opts.shareWithTeam?` | `boolean` |\n| `opts.team?` | [`Team`](../../../teams/team/classes/Team.md) |\n\n#### Returns\n\n`Promise`\\<[`Task`](../../task/classes/Task.md)\\>\n\n***\n\n### forPullRequest()\n\n> **forPullRequest**(`url`): `Promise`\\<[`Task`](../../task/classes/Task.md)[]\\>\n\nThe tasks the GitHub pull request at `url` references, oldest link first.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `url` | `string` |\n\n#### Returns\n\n`Promise`\\<[`Task`](../../task/classes/Task.md)[]\\>\n\n***\n\n### search()\n\n> **search**(`query`, `opts?`): `AsyncGenerator`\\<[`Task`](../../task/classes/Task.md)\\>\n\nSearch tasks by name and content, most relevant first, auto-paginated.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `query` | `string` |\n| `opts?` | [`SearchOpts`](../../../search/interfaces/SearchOpts.md) |\n\n#### Returns\n\n`AsyncGenerator`\\<[`Task`](../../task/classes/Task.md)\\>\n\n\n<!-- src/entities/tasks/task/classes/Task.md -->\n# Class: Task\n\nA Macro task: a document with sub-type `task`. Inherits the full document\nsurface ([Document.rename](../../../documents/document/classes/Document.md#rename), move, delete, restore, content, events)\nand adds task-specific state.\n\n## Extends\n\n- [`Document`](../../../documents/document/classes/Document.md)\n\n## Properties\n\n| Property | Modifier | Type | Default value | Description | Overrides | Inherited from |\n| ------ | ------ | ------ | ------ | ------ | ------ | ------ |\n| <a id=\"property-access\"></a> `access` | `readonly` | [`EntityAccess`](../../../sharing/access/classes/EntityAccess.md) | `...` | Access requests and direct user grants. | - | [`Document`](../../../documents/document/classes/Document.md).[`access`](../../../documents/document/classes/Document.md#property-access) |\n| <a id=\"property-branchedfrom\"></a> `branchedFrom` | `readonly` | () => `Promise`\\<[`Document`](../../../documents/document/classes/Document.md) \\| `undefined`\\> | `...` | The document this one was branched from, if any. | - | [`Document`](../../../documents/document/classes/Document.md).[`branchedFrom`](../../../documents/document/classes/Document.md#property-branchedfrom) |\n| <a id=\"property-createdat\"></a> `createdAt` | `readonly` | () => `Promise`\\<`string` \\| `undefined`\\> | `...` | When the document was created. | - | [`Document`](../../../documents/document/classes/Document.md).[`createdAt`](../../../documents/document/classes/Document.md#property-createdat) |\n| <a id=\"property-deletedat\"></a> `deletedAt` | `readonly` | () => `Promise`\\<`string` \\| `undefined`\\> | `...` | When the document was deleted, if it has been. | - | [`Document`](../../../documents/document/classes/Document.md).[`deletedAt`](../../../documents/document/classes/Document.md#property-deletedat) |\n| <a id=\"property-entitytype\"></a> `entityType` | `readonly` | `\"document\"` | `'document'` | Favorites identify documents as `document`. | - | [`Document`](../../../documents/document/classes/Document.md).[`entityType`](../../../documents/document/classes/Document.md#property-entitytype) |\n| <a id=\"property-filetype\"></a> `fileType` | `readonly` | () => `Promise`\\<`string` \\| `undefined`\\> | `...` | The document's file type (e.g. `md`, `pdf`, `docx`). | - | [`Document`](../../../documents/document/classes/Document.md).[`fileType`](../../../documents/document/classes/Document.md#property-filetype) |\n| <a id=\"property-id\"></a> `id` | `public readonly` | `string` | `undefined` | - | - | [`Document`](../../../documents/document/classes/Document.md).[`id`](../../../documents/document/classes/Document.md#property-id) |\n| <a id=\"property-name\"></a> `name` | `readonly` | () => `Promise`\\<`string`\\> | `...` | The document's display name. | - | [`Document`](../../../documents/document/classes/Document.md).[`name`](../../../documents/document/classes/Document.md#property-name) |\n| <a id=\"property-owner\"></a> `owner` | `readonly` | () => `Promise`\\<[`User`](../../../users/user/classes/User.md)\\> | `...` | The user who owns the document. | - | [`Document`](../../../documents/document/classes/Document.md).[`owner`](../../../documents/document/classes/Document.md#property-owner) |\n| <a id=\"property-project\"></a> `project` | `readonly` | () => `Promise`\\<[`Project`](../../../projects/project/classes/Project.md) \\| `undefined`\\> | `...` | The project this document belongs to, if any. | - | [`Document`](../../../documents/document/classes/Document.md).[`project`](../../../documents/document/classes/Document.md#property-project) |\n| <a id=\"property-updatedat\"></a> `updatedAt` | `readonly` | () => `Promise`\\<`string` \\| `undefined`\\> | `...` | When the document was last updated. | - | [`Document`](../../../documents/document/classes/Document.md).[`updatedAt`](../../../documents/document/classes/Document.md#property-updatedat) |\n| <a id=\"property-search\"></a> `search` | `static` | (`client`, `query`, `searchOpts?`) => `AsyncGenerator`\\<`Task`\\> | `...` | Search tasks by name and content, most relevant first, auto-paginated. | [`Document`](../../../documents/document/classes/Document.md).[`search`](../../../documents/document/classes/Document.md#property-search) | - |\n\n## Methods\n\n### anchors()\n\n> **anchors**(): `Promise`\\<[`DocumentAnchor`](../../../documents/anchor/classes/DocumentAnchor.md)[]\\>\n\nPDF annotations in this document.\n\n#### Returns\n\n`Promise`\\<[`DocumentAnchor`](../../../documents/anchor/classes/DocumentAnchor.md)[]\\>\n\n#### Inherited from\n\n[`Document`](../../../documents/document/classes/Document.md).[`anchors`](../../../documents/document/classes/Document.md#anchors)\n\n***\n\n### branchName()\n\n> **branchName**(): `Promise`\\<`string`\\>\n\nThe git branch name derived for the document (task documents).\n\n#### Returns\n\n`Promise`\\<`string`\\>\n\n#### Inherited from\n\n[`Document`](../../../documents/document/classes/Document.md).[`branchName`](../../../documents/document/classes/Document.md#branchname)\n\n***\n\n### comment()\n\n> **comment**(`body`, `opts?`): `Promise`\\<[`Comment`](../../../documents/comment/classes/Comment.md)\\>\n\nAdd a comment. Starts a new unanchored thread, or replies to an existing\none when `threadId` (the thread's root comment id) is given.\n\n#### Parameters\n\n| Parameter | Type | Description |\n| ------ | ------ | ------ |\n| `body` | `string` \\| [`RichMessage`](../../../../mentions/interfaces/RichMessage.md) | Plain text, or a rich body composed with msg. |\n| `opts?` | \\{ `threadId?`: `string`; \\} | - |\n| `opts.threadId?` | `string` | - |\n\n#### Returns\n\n`Promise`\\<[`Comment`](../../../documents/comment/classes/Comment.md)\\>\n\nThe created comment.\n\n#### Inherited from\n\n[`Document`](../../../documents/document/classes/Document.md).[`comment`](../../../documents/document/classes/Document.md#comment)\n\n***\n\n### comments()\n\n> **comments**(): `Promise`\\<[`CommentThread`](../../../documents/document/interfaces/CommentThread.md)[]\\>\n\nThe document's live comment threads, each with its comments, newest thread first.\n\n#### Returns\n\n`Promise`\\<[`CommentThread`](../../../documents/document/interfaces/CommentThread.md)[]\\>\n\n#### Inherited from\n\n[`Document`](../../../documents/document/classes/Document.md).[`comments`](../../../documents/document/classes/Document.md#comments)\n\n***\n\n### completed()\n\n> **completed**(): `Promise`\\<`boolean` \\| `undefined`\\>\n\nWhether the task is completed (its Status property is \"Completed\");\n`undefined` if the document is not a task.\n\n#### Returns\n\n`Promise`\\<`boolean` \\| `undefined`\\>\n\n***\n\n### content()\n\n> **content**(): `Promise`\\<`string`\\>\n\nCurrent Markdown for native documents, extracted text for PDF/Word,\nor raw file content for other formats. Native reads include live edits.\n\n#### Returns\n\n`Promise`\\<`string`\\>\n\n#### Inherited from\n\n[`Document`](../../../documents/document/classes/Document.md).[`content`](../../../documents/document/classes/Document.md#content)\n\n***\n\n### copy()\n\n> **copy**(`opts`): `Promise`\\<[`Document`](../../../documents/document/classes/Document.md)\\>\n\nCopy the document under a new name, optionally from a specific version.\nReturns a handle to the new document.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `opts` | \\{ `name`: `string`; `versionId?`: `number`; \\} |\n| `opts.name` | `string` |\n| `opts.versionId?` | `number` |\n\n#### Returns\n\n`Promise`\\<[`Document`](../../../documents/document/classes/Document.md)\\>\n\n#### Inherited from\n\n[`Document`](../../../documents/document/classes/Document.md).[`copy`](../../../documents/document/classes/Document.md#copy)\n\n***\n\n### createHighlight()\n\n> **createHighlight**(`options`): `Promise`\\<[`DocumentAnchor`](../../../documents/anchor/classes/DocumentAnchor.md)\\>\n\nCreate a standalone PDF highlight.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `options` | `Omit`\\<[`PdfHighlightAnchorRequest`](../../../../../generated/storage/types.gen/type-aliases/PdfHighlightAnchorRequest.md), `\"uuid\"`\\> |\n\n#### Returns\n\n`Promise`\\<[`DocumentAnchor`](../../../documents/anchor/classes/DocumentAnchor.md)\\>\n\n#### Inherited from\n\n[`Document`](../../../documents/document/classes/Document.md).[`createHighlight`](../../../documents/document/classes/Document.md#createhighlight)\n\n***\n\n### delete()\n\n> **delete**(`opts?`): `Promise`\\<`void`\\>\n\nDelete the document. Soft by default (reversible with [restore](../../../documents/document/classes/Document.md#restore));\npass `permanent: true` to delete irreversibly.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `opts?` | \\{ `permanent?`: `boolean`; \\} |\n| `opts.permanent?` | `boolean` |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n#### Inherited from\n\n[`Document`](../../../documents/document/classes/Document.md).[`delete`](../../../documents/document/classes/Document.md#delete)\n\n***\n\n### deleteProperty()\n\n> **deleteProperty**(`assignment`): `Promise`\\<`void`\\>\n\nRemove a property from this entity, given its [properties](#properties) entry.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `assignment` | [`EntityPropertyWithDefinition`](../../../../../generated/properties/types.gen/type-aliases/EntityPropertyWithDefinition.md) |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n#### Inherited from\n\n[`Document`](../../../documents/document/classes/Document.md).[`deleteProperty`](../../../documents/document/classes/Document.md#deleteproperty)\n\n***\n\n### favorite()\n\n> **favorite**(): `Promise`\\<`Task`\\>\n\nAdd this entity to the user's favorites. Returns this handle for chaining.\nPlain unwrap: favoriting alters the user's favorites collection, not this\nentity's own detail, so there's nothing cached to invalidate.\n\n#### Returns\n\n`Promise`\\<`Task`\\>\n\n#### Inherited from\n\n[`Document`](../../../documents/document/classes/Document.md).[`favorite`](../../../documents/document/classes/Document.md#favorite)\n\n***\n\n### githubPullRequests()\n\n> **githubPullRequests**(): `Promise`\\<[`GithubPullRequest`](../../../../../generated/storage/types.gen/type-aliases/GithubPullRequest.md)[]\\>\n\nGitHub pull requests associated with the document.\n\n#### Returns\n\n`Promise`\\<[`GithubPullRequest`](../../../../../generated/storage/types.gen/type-aliases/GithubPullRequest.md)[]\\>\n\n#### Inherited from\n\n[`Document`](../../../documents/document/classes/Document.md).[`githubPullRequests`](../../../documents/document/classes/Document.md#githubpullrequests)\n\n***\n\n### messageThreadById()\n\n> **messageThreadById**(`id`): [`MessageThread`](../../../messages/thread/classes/MessageThread.md)\n\nA shared message thread scoped to this resource.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `id` | `string` |\n\n#### Returns\n\n[`MessageThread`](../../../messages/thread/classes/MessageThread.md)\n\n#### Inherited from\n\n[`Document`](../../../documents/document/classes/Document.md).[`messageThreadById`](../../../documents/document/classes/Document.md#messagethreadbyid)\n\n***\n\n### move()\n\n> **move**(`project`): `Promise`\\<`void`\\>\n\nMove the document into a project (or out of one, with `null`).\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `project` | [`Project`](../../../projects/project/classes/Project.md) \\| `null` |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n#### Inherited from\n\n[`Document`](../../../documents/document/classes/Document.md).[`move`](../../../documents/document/classes/Document.md#move)\n\n***\n\n### permission()\n\n> **permission**(): `Promise`\\<\\{ `permission`: [`EntityPermission`](../../../../../generated/storage/types.gen/type-aliases/EntityPermission.md); `status`: `\"access\"`; \\} \\| \\{ `status`: `\"no_access\"`; \\}\\>\n\nRead the caller's effective permission on this entity.\n\n#### Returns\n\n`Promise`\\<\\{ `permission`: [`EntityPermission`](../../../../../generated/storage/types.gen/type-aliases/EntityPermission.md); `status`: `\"access\"`; \\} \\| \\{ `status`: `\"no_access\"`; \\}\\>\n\n#### Inherited from\n\n[`Document`](../../../documents/document/classes/Document.md).[`permission`](../../../documents/document/classes/Document.md#permission)\n\n***\n\n### permissionsToken()\n\n> **permissionsToken**(): `Promise`\\<`string`\\>\n\nMint a scoped permissions token.\n\n#### Returns\n\n`Promise`\\<`string`\\>\n\n#### Inherited from\n\n[`Document`](../../../documents/document/classes/Document.md).[`permissionsToken`](../../../documents/document/classes/Document.md#permissionstoken)\n\n***\n\n### prepareSave()\n\n> **prepareSave**(`parts`): `Promise`\\<[`PreSaveDocumentResponseData`](../../../../../generated/storage/types.gen/type-aliases/PreSaveDocumentResponseData.md)\\>\n\nPrepare multipart content saving and return the service's upload instructions.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `parts` | [`SaveBomPart`](../../../../../generated/storage/types.gen/type-aliases/SaveBomPart.md)[] |\n\n#### Returns\n\n`Promise`\\<[`PreSaveDocumentResponseData`](../../../../../generated/storage/types.gen/type-aliases/PreSaveDocumentResponseData.md)\\>\n\n#### Inherited from\n\n[`Document`](../../../documents/document/classes/Document.md).[`prepareSave`](../../../documents/document/classes/Document.md#preparesave)\n\n***\n\n### properties()\n\n> **properties**(`opts?`): `Promise`\\<[`EntityPropertyWithDefinition`](../../../../../generated/properties/types.gen/type-aliases/EntityPropertyWithDefinition.md)[]\\>\n\nThe properties set on this entity, each with its definition, value, and options.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `opts?` | \\{ `includeMetadata?`: `boolean`; \\} |\n| `opts.includeMetadata?` | `boolean` |\n\n#### Returns\n\n`Promise`\\<[`EntityPropertyWithDefinition`](../../../../../generated/properties/types.gen/type-aliases/EntityPropertyWithDefinition.md)[]\\>\n\n#### Inherited from\n\n[`Document`](../../../documents/document/classes/Document.md).[`properties`](../../../documents/document/classes/Document.md#properties)\n\n***\n\n### propertyReference()\n\n> **propertyReference**(): [`PropertyTargetReference`](../../../../../generated/properties/types.gen/type-aliases/PropertyTargetReference.md)\n\nThis entity's reference for bulk property operations.\n\n#### Returns\n\n[`PropertyTargetReference`](../../../../../generated/properties/types.gen/type-aliases/PropertyTargetReference.md)\n\n#### Inherited from\n\n[`Document`](../../../documents/document/classes/Document.md).[`propertyReference`](../../../documents/document/classes/Document.md#propertyreference)\n\n***\n\n### rename()\n\n> **rename**(`name`): `Promise`\\<`void`\\>\n\nRename the document.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `name` | `string` |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n#### Inherited from\n\n[`Document`](../../../documents/document/classes/Document.md).[`rename`](../../../documents/document/classes/Document.md#rename)\n\n***\n\n### restore()\n\n> **restore**(): `Promise`\\<`void`\\>\n\nRestore a soft-deleted document.\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n#### Inherited from\n\n[`Document`](../../../documents/document/classes/Document.md).[`restore`](../../../documents/document/classes/Document.md#restore)\n\n***\n\n### save()\n\n> **save**(`options`): `Promise`\\<[`SaveDocumentResponseData`](../../../../../generated/storage/types.gen/type-aliases/SaveDocumentResponseData.md)\\>\n\nCommit uploaded content. Does not retry uncertain writes.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `options` | [`SaveDocumentRequest`](../../../../../generated/storage/types.gen/type-aliases/SaveDocumentRequest.md) |\n\n#### Returns\n\n`Promise`\\<[`SaveDocumentResponseData`](../../../../../generated/storage/types.gen/type-aliases/SaveDocumentResponseData.md)\\>\n\n#### Inherited from\n\n[`Document`](../../../documents/document/classes/Document.md).[`save`](../../../documents/document/classes/Document.md#save)\n\n***\n\n### setProperty()\n\n> **setProperty**(`property`, `value?`): `Promise`\\<`void`\\>\n\nSet a property value on this entity, or attach the property without a\nvalue when `value` is omitted.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `property` | [`PropertyDefinition`](../../../properties/property-definition/classes/PropertyDefinition.md) |\n| `value?` | [`SetPropertyValue`](../../../../../generated/properties/types.gen/type-aliases/SetPropertyValue.md) |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n#### Inherited from\n\n[`Document`](../../../documents/document/classes/Document.md).[`setProperty`](../../../documents/document/classes/Document.md#setproperty)\n\n***\n\n### setTeamShare()\n\n> **setTeamShare**(`shared`): `Promise`\\<`void`\\>\n\nShare the document with the owner's team, or unshare it.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `shared` | `boolean` |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n#### Inherited from\n\n[`Document`](../../../documents/document/classes/Document.md).[`setTeamShare`](../../../documents/document/classes/Document.md#setteamshare)\n\n***\n\n### sharePermissions()\n\n> **sharePermissions**(): `Promise`\\<[`SharePermissionV2`](../../../../../generated/storage/types.gen/type-aliases/SharePermissionV2.md)\\>\n\nSharing configuration.\n\n#### Returns\n\n`Promise`\\<[`SharePermissionV2`](../../../../../generated/storage/types.gen/type-aliases/SharePermissionV2.md)\\>\n\n#### Inherited from\n\n[`Document`](../../../documents/document/classes/Document.md).[`sharePermissions`](../../../documents/document/classes/Document.md#sharepermissions)\n\n***\n\n### shortId()\n\n> **shortId**(): `Promise`\\<`string`\\>\n\nThe document's short id (used in compact links and branch names).\n\n#### Returns\n\n`Promise`\\<`string`\\>\n\n#### Inherited from\n\n[`Document`](../../../documents/document/classes/Document.md).[`shortId`](../../../documents/document/classes/Document.md#shortid)\n\n***\n\n### simpleSave()\n\n> **simpleSave**(): `Promise`\\<[`SaveDocumentResponseData`](../../../../../generated/storage/types.gen/type-aliases/SaveDocumentResponseData.md)\\>\n\nCommit a simple document save.\n\n#### Returns\n\n`Promise`\\<[`SaveDocumentResponseData`](../../../../../generated/storage/types.gen/type-aliases/SaveDocumentResponseData.md)\\>\n\n#### Inherited from\n\n[`Document`](../../../documents/document/classes/Document.md).[`simpleSave`](../../../documents/document/classes/Document.md#simplesave)\n\n***\n\n### teamShare()\n\n> **teamShare**(): `Promise`\\<[`DocumentTeamShareResponse`](../../../../../generated/storage/types.gen/type-aliases/DocumentTeamShareResponse.md)\\>\n\nWhether the document is shared with the owner's team, and which team.\n\n#### Returns\n\n`Promise`\\<[`DocumentTeamShareResponse`](../../../../../generated/storage/types.gen/type-aliases/DocumentTeamShareResponse.md)\\>\n\n#### Inherited from\n\n[`Document`](../../../documents/document/classes/Document.md).[`teamShare`](../../../documents/document/classes/Document.md#teamshare)\n\n***\n\n### timelinePage()\n\n> **timelinePage**(`selection?`): `Promise`\\<\\{ `entries`: (\\{ `activity`: \\{ `action`: `string`; `actor`: [`User`](../../../users/user/classes/User.md); `actor_id`: `string`; `id`: `string`; `occurred_at`: `string`; `payload?`: `unknown`; \\}; `message?`: `undefined`; `type`: `\"activity\"`; \\} \\| \\{ `activity?`: `undefined`; `message`: [`Comment`](../../../documents/comment/classes/Comment.md); `type`: `\"message\"`; \\})[]; `nextCursor`: [`MessageCursor`](../../../../../generated/storage/types.gen/type-aliases/MessageCursor.md) \\| `undefined`; `previousCursor`: [`MessageCursor`](../../../../../generated/storage/types.gen/type-aliases/MessageCursor.md) \\| `undefined`; \\}\\>\n\nA mixed message and activity timeline page.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `selection?` | [`TimelineOptions`](../../../messages/thread/interfaces/TimelineOptions.md)\\<[`Comment`](../../../documents/comment/classes/Comment.md)\\> |\n\n#### Returns\n\n`Promise`\\<\\{ `entries`: (\\{ `activity`: \\{ `action`: `string`; `actor`: [`User`](../../../users/user/classes/User.md); `actor_id`: `string`; `id`: `string`; `occurred_at`: `string`; `payload?`: `unknown`; \\}; `message?`: `undefined`; `type`: `\"activity\"`; \\} \\| \\{ `activity?`: `undefined`; `message`: [`Comment`](../../../documents/comment/classes/Comment.md); `type`: `\"message\"`; \\})[]; `nextCursor`: [`MessageCursor`](../../../../../generated/storage/types.gen/type-aliases/MessageCursor.md) \\| `undefined`; `previousCursor`: [`MessageCursor`](../../../../../generated/storage/types.gen/type-aliases/MessageCursor.md) \\| `undefined`; \\}\\>\n\n#### Inherited from\n\n[`Document`](../../../documents/document/classes/Document.md).[`timelinePage`](../../../documents/document/classes/Document.md#timelinepage)\n\n***\n\n### toJSON()\n\n> **toJSON**(): \\{ `detail?`: [`DocumentMetadataWithContent`](../../../../../generated/storage/types.gen/type-aliases/DocumentMetadataWithContent.md); `id`: `string`; \\}\n\n#### Returns\n\n\\{ `detail?`: [`DocumentMetadataWithContent`](../../../../../generated/storage/types.gen/type-aliases/DocumentMetadataWithContent.md); `id`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `detail?` | [`DocumentMetadataWithContent`](../../../../../generated/storage/types.gen/type-aliases/DocumentMetadataWithContent.md) |\n| `id` | `string` |\n\n#### Inherited from\n\n[`Document`](../../../documents/document/classes/Document.md).[`toJSON`](../../../documents/document/classes/Document.md#tojson)\n\n***\n\n### toMention()\n\n> **toMention**(): [`MentionPart`](../../../../mentions/interfaces/MentionPart.md)\n\n#### Returns\n\n[`MentionPart`](../../../../mentions/interfaces/MentionPart.md)\n\n#### Inherited from\n\n[`Document`](../../../documents/document/classes/Document.md).[`toMention`](../../../documents/document/classes/Document.md#tomention)\n\n***\n\n### unfavorite()\n\n> **unfavorite**(): `Promise`\\<`Task`\\>\n\nRemove this entity from the user's favorites. Returns this handle for chaining.\n\n#### Returns\n\n`Promise`\\<`Task`\\>\n\n#### Inherited from\n\n[`Document`](../../../documents/document/classes/Document.md).[`unfavorite`](../../../documents/document/classes/Document.md#unfavorite)\n\n***\n\n### updatePropertyOptions()\n\n> **updatePropertyOptions**(`changes`): `Promise`\\<[`BulkUpdateEntityPropertyOptionsResponse`](../../../../../generated/properties/types.gen/type-aliases/BulkUpdateEntityPropertyOptionsResponse.md)\\>\n\nApply multi-select option deltas atomically across this entity's properties.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `changes` | [`PropertyOptionDelta`](../../../entity/interfaces/PropertyOptionDelta.md)[] |\n\n#### Returns\n\n`Promise`\\<[`BulkUpdateEntityPropertyOptionsResponse`](../../../../../generated/properties/types.gen/type-aliases/BulkUpdateEntityPropertyOptionsResponse.md)\\>\n\n#### Inherited from\n\n[`Document`](../../../documents/document/classes/Document.md).[`updatePropertyOptions`](../../../documents/document/classes/Document.md#updatepropertyoptions)\n\n***\n\n### version()\n\n> **version**(`version`): [`DocumentVersion`](../../../documents/version/classes/DocumentVersion.md)\n\nA handle to an immutable version.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `version` | `number` |\n\n#### Returns\n\n[`DocumentVersion`](../../../documents/version/classes/DocumentVersion.md)\n\n#### Inherited from\n\n[`Document`](../../../documents/document/classes/Document.md).[`version`](../../../documents/document/classes/Document.md#version)\n\n***\n\n### webUrl()\n\n> **webUrl**(): `string`\n\nThe task's URL in the Macro web app.\n\n#### Returns\n\n`string`\n\n#### Overrides\n\n[`Document`](../../../documents/document/classes/Document.md).[`webUrl`](../../../documents/document/classes/Document.md#weburl)\n\n***\n\n### byId()\n\n> `static` **byId**(`client`, `id`): `Task`\n\nA handle to a task by document id. Details load on first access.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `id` | `string` |\n\n#### Returns\n\n`Task`\n\n#### Overrides\n\n[`Document`](../../../documents/document/classes/Document.md).[`byId`](../../../documents/document/classes/Document.md#byid)\n\n***\n\n### create()\n\n> `static` **create**(`client`, `opts`): `Promise`\\<`Task`\\>\n\nCreate a task. `team` scopes the team task number and may be omitted\nwhen the creator belongs to exactly one team; `shareWithTeam` defaults\nto true.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `opts` | \\{ `markdown?`: `string`; `name`: `string`; `project?`: [`Project`](../../../projects/project/classes/Project.md); `shareWithTeam?`: `boolean`; `team?`: [`Team`](../../../teams/team/classes/Team.md); \\} |\n| `opts.markdown?` | `string` |\n| `opts.name` | `string` |\n| `opts.project?` | [`Project`](../../../projects/project/classes/Project.md) |\n| `opts.shareWithTeam?` | `boolean` |\n| `opts.team?` | [`Team`](../../../teams/team/classes/Team.md) |\n\n#### Returns\n\n`Promise`\\<`Task`\\>\n\n#### Overrides\n\n[`Document`](../../../documents/document/classes/Document.md).[`create`](../../../documents/document/classes/Document.md#create)\n\n***\n\n### createSkill()\n\n> `static` **createSkill**(`client`, `opts`): `Promise`\\<[`Document`](../../../documents/document/classes/Document.md)\\>\n\nCreate a skill: a markdown document containing instructions that AI reads\nand follows when the skill is referenced in an AI input.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `opts` | \\{ `markdown?`: `string`; `name`: `string`; `project?`: [`Project`](../../../projects/project/classes/Project.md); \\} |\n| `opts.markdown?` | `string` |\n| `opts.name` | `string` |\n| `opts.project?` | [`Project`](../../../projects/project/classes/Project.md) |\n\n#### Returns\n\n`Promise`\\<[`Document`](../../../documents/document/classes/Document.md)\\>\n\n#### Inherited from\n\n[`Document`](../../../documents/document/classes/Document.md).[`createSkill`](../../../documents/document/classes/Document.md#createskill)\n\n***\n\n### createSnippet()\n\n> `static` **createSnippet**(`client`, `opts`): `Promise`\\<[`Document`](../../../documents/document/classes/Document.md)\\>\n\nCreate a snippet: a reusable markdown document that can be inserted into\nany markdown area.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `opts` | \\{ `markdown?`: `string`; `name`: `string`; `project?`: [`Project`](../../../projects/project/classes/Project.md); \\} |\n| `opts.markdown?` | `string` |\n| `opts.name` | `string` |\n| `opts.project?` | [`Project`](../../../projects/project/classes/Project.md) |\n\n#### Returns\n\n`Promise`\\<[`Document`](../../../documents/document/classes/Document.md)\\>\n\n#### Inherited from\n\n[`Document`](../../../documents/document/classes/Document.md).[`createSnippet`](../../../documents/document/classes/Document.md#createsnippet)\n\n***\n\n### forPullRequest()\n\n> `static` **forPullRequest**(`client`, `url`): `Promise`\\<`Task`[]\\>\n\nThe tasks the GitHub pull request at `url` references (as `MACRO-<id>` in\nits text, branch, or comments), oldest link first. Empty when the caller\ncannot see the pull request; tasks the caller cannot open still appear.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `url` | `string` |\n\n#### Returns\n\n`Promise`\\<`Task`[]\\>\n\n***\n\n### recent()\n\n> `static` **recent**(`client`, `opts?`): `AsyncGenerator`\\<[`Document`](../../../documents/document/classes/Document.md)\\>\n\nThe user's recent documents, most recent first, auto-paginated.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `opts?` | \\{ `fileType?`: `string`; `pageSize?`: `number`; \\} |\n| `opts.fileType?` | `string` |\n| `opts.pageSize?` | `number` |\n\n#### Returns\n\n`AsyncGenerator`\\<[`Document`](../../../documents/document/classes/Document.md)\\>\n\n#### Inherited from\n\n[`Document`](../../../documents/document/classes/Document.md).[`recent`](../../../documents/document/classes/Document.md#recent)\n\n***\n\n### recentlyDeleted()\n\n> `static` **recentlyDeleted**(`client`): `Promise`\\<[`Document`](../../../documents/document/classes/Document.md)[]\\>\n\nThe user's recently soft-deleted documents. The underlying endpoint also\nreturns deleted chats and projects; those are filtered out here.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n\n#### Returns\n\n`Promise`\\<[`Document`](../../../documents/document/classes/Document.md)[]\\>\n\n#### Inherited from\n\n[`Document`](../../../documents/document/classes/Document.md).[`recentlyDeleted`](../../../documents/document/classes/Document.md#recentlydeleted)\n"
+ "documentation": "# Macro SDK: tasks\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/properties/types.gen/type-aliases/BulkUpdateEntityPropertyOptionsResponse.md -->\n# Type Alias: BulkUpdateEntityPropertyOptionsResponse\n\n> **BulkUpdateEntityPropertyOptionsResponse** = \\{ `properties`: [`EntityPropertyOptionSelectionResponse`](EntityPropertyOptionSelectionResponse.md)[]; \\}\n\nResponse for a bulk option update: each property's reconciled final ids.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-properties\"></a> `properties` | [`EntityPropertyOptionSelectionResponse`](EntityPropertyOptionSelectionResponse.md)[] | The final option ids per updated property. |\n\n\n<!-- generated/properties/types.gen/type-aliases/DataType.md -->\n# Type Alias: DataType\n\n> **DataType** = `\"BOOLEAN\"` \\| `\"DATE\"` \\| `\"NUMBER\"` \\| `\"STRING\"` \\| `\"SELECT_NUMBER\"` \\| `\"SELECT_STRING\"` \\| `\"TAG\"` \\| `\"ENTITY\"` \\| `\"LINK\"`\n\nData type for property values, determining storage and validation.\n\n\n<!-- generated/properties/types.gen/type-aliases/EntityProperty.md -->\n# Type Alias: EntityProperty\n\n> **EntityProperty** = \\{ `created_at`: `string`; `entity_id`: `string`; `entity_type`: [`EntityType`](EntityType.md); `id`: `string`; `property_definition_id`: `string`; `updated_at`: `string`; \\}\n\nAssignment of a property definition to a specific entity (service representation).\n\n## Properties\n\n| Property | Type |\n| ------ | ------ |\n| <a id=\"property-created_at\"></a> `created_at` | `string` |\n| <a id=\"property-entity_id\"></a> `entity_id` | `string` |\n| <a id=\"property-entity_type\"></a> `entity_type` | [`EntityType`](EntityType.md) |\n| <a id=\"property-id\"></a> `id` | `string` |\n| <a id=\"property-property_definition_id\"></a> `property_definition_id` | `string` |\n| <a id=\"property-updated_at\"></a> `updated_at` | `string` |\n\n\n<!-- generated/properties/types.gen/type-aliases/EntityPropertyOptionSelectionResponse.md -->\n# Type Alias: EntityPropertyOptionSelectionResponse\n\n> **EntityPropertyOptionSelectionResponse** = \\{ `option_ids`: `string`[]; `property_id`: `string`; \\}\n\nThe reconciled final option ids stored for one property after a bulk update.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-option_ids\"></a> `option_ids` | `string`[] | The final option ids the server persisted, in stored order. |\n| <a id=\"property-property_id\"></a> `property_id` | `string` | The property definition the options belong to. |\n\n\n<!-- generated/properties/types.gen/type-aliases/EntityPropertyWithDefinition.md -->\n# Type Alias: EntityPropertyWithDefinition\n\n> **EntityPropertyWithDefinition** = \\{ `definition`: [`PropertyDefinition`](PropertyDefinition.md); `options?`: [`PropertyOption`](PropertyOption.md)[] \\| `null`; `property`: [`EntityProperty`](EntityProperty.md); `value?`: `null` \\| [`PropertyValue`](PropertyValue.md); \\}\n\nEntity property with its definition, value, and options (service representation).\n\n## Properties\n\n| Property | Type |\n| ------ | ------ |\n| <a id=\"property-definition\"></a> `definition` | [`PropertyDefinition`](PropertyDefinition.md) |\n| <a id=\"property-options\"></a> `options?` | [`PropertyOption`](PropertyOption.md)[] \\| `null` |\n| <a id=\"property-property\"></a> `property` | [`EntityProperty`](EntityProperty.md) |\n| <a id=\"property-value\"></a> `value?` | `null` \\| [`PropertyValue`](PropertyValue.md) |\n\n\n<!-- generated/properties/types.gen/type-aliases/EntityReference.md -->\n# Type Alias: EntityReference\n\n> **EntityReference** = \\{ `entity_id`: `string`; `entity_type`: [`EntityType`](EntityType.md); `specific_message_id?`: `string` \\| `null`; \\}\n\nEntity reference for entity-type property values.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-entity_id\"></a> `entity_id` | `string` | - |\n| <a id=\"property-entity_type\"></a> `entity_type` | [`EntityType`](EntityType.md) | - |\n| <a id=\"property-specific_message_id\"></a> `specific_message_id?` | `string` \\| `null` | For CHANNEL, CHAT, THREAD entity types - optional specific message ID. This allows referencing a specific message within a thread/channel/chat. |\n\n\n<!-- generated/properties/types.gen/type-aliases/EntityType.md -->\n# Type Alias: EntityType\n\n> **EntityType** = `\"CALENDAR_EVENT\"` \\| `\"CALL_RECORD\"` \\| `\"CHANNEL\"` \\| `\"CHAT\"` \\| `\"COMPANY\"` \\| `\"DATABASE_ROW\"` \\| `\"CONTACT\"` \\| `\"DOCUMENT\"` \\| `\"INITIATIVE\"` \\| `\"PROJECT\"` \\| `\"TASK\"` \\| `\"THREAD\"` \\| `\"USER\"`\n\nType of entity that can be referenced by entity properties.\n\n\n<!-- generated/properties/types.gen/type-aliases/PropertyDefinition.md -->\n# Type Alias: PropertyDefinition\n\n> **PropertyDefinition** = \\{ `created_at`: `string`; `data_type`: [`DataType`](DataType.md); `display_name`: `string`; `id`: `string`; `is_metadata`: `boolean`; `is_multi_select`: `boolean`; `is_system`: `boolean`; `owner`: [`PropertyOwner`](PropertyOwner.md); `specific_entity_type`: `null` \\| [`EntityType`](EntityType.md); `updated_at`: `string`; \\}\n\nProperty definition model (service representation).\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-created_at\"></a> `created_at` | `string` | - |\n| <a id=\"property-data_type\"></a> `data_type` | [`DataType`](DataType.md) | - |\n| <a id=\"property-display_name\"></a> `display_name` | `string` | - |\n| <a id=\"property-id\"></a> `id` | `string` | - |\n| <a id=\"property-is_metadata\"></a> `is_metadata` | `boolean` | Flag to indicate if this is a system-generated metadata property. Not stored in database - computed at service layer. |\n| <a id=\"property-is_multi_select\"></a> `is_multi_select` | `boolean` | - |\n| <a id=\"property-is_system\"></a> `is_system` | `boolean` | Flag to indicate if this is a system property (stored in DB). |\n| <a id=\"property-owner\"></a> `owner` | [`PropertyOwner`](PropertyOwner.md) | - |\n| <a id=\"property-specific_entity_type\"></a> `specific_entity_type` | `null` \\| [`EntityType`](EntityType.md) | - |\n| <a id=\"property-updated_at\"></a> `updated_at` | `string` | - |\n\n\n<!-- generated/properties/types.gen/type-aliases/PropertyOption.md -->\n# Type Alias: PropertyOption\n\n> **PropertyOption** = \\{ `color`: `string` \\| `null`; `created_at`: `string`; `display_order`: `number`; `id`: `string`; `property_definition_id`: `string`; `updated_at`: `string`; `value`: [`PropertyOptionValue`](PropertyOptionValue.md); \\}\n\nA selectable option for select-type properties (service representation).\n\n## Properties\n\n| Property | Type |\n| ------ | ------ |\n| <a id=\"property-color\"></a> `color` | `string` \\| `null` |\n| <a id=\"property-created_at\"></a> `created_at` | `string` |\n| <a id=\"property-display_order\"></a> `display_order` | `number` |\n| <a id=\"property-id\"></a> `id` | `string` |\n| <a id=\"property-property_definition_id\"></a> `property_definition_id` | `string` |\n| <a id=\"property-updated_at\"></a> `updated_at` | `string` |\n| <a id=\"property-value\"></a> `value` | [`PropertyOptionValue`](PropertyOptionValue.md) |\n\n\n<!-- generated/properties/types.gen/type-aliases/PropertyOptionValue.md -->\n# Type Alias: PropertyOptionValue\n\n> **PropertyOptionValue** = \\{ `type`: `\"string\"`; `value`: `string`; \\} \\| \\{ `type`: `\"number\"`; `value`: `number`; \\}\n\nThe value of a property option - either a string or a number.\n\n## Union Members\n\n### Type Literal\n\n\\{ `type`: `\"string\"`; `value`: `string`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `type` | `\"string\"` | - |\n| `value` | `string` | String value for SelectString properties |\n\n***\n\n### Type Literal\n\n\\{ `type`: `\"number\"`; `value`: `number`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `type` | `\"number\"` | - |\n| `value` | `number` | Number value for SelectNumber properties |\n\n\n<!-- generated/properties/types.gen/type-aliases/PropertyOwner.md -->\n# Type Alias: PropertyOwner\n\n> **PropertyOwner** = \\{ `scope`: `\"user\"`; `user_id`: `string`; \\} \\| \\{ `scope`: `\"team\"`; `team_id`: `string`; \\} \\| \\{ `database_id`: `string`; `scope`: `\"database\"`; \\} \\| \\{ `scope`: `\"system\"`; \\}\n\nDefines who owns a property - user-scoped, team-scoped, database-scoped, or system.\n\n\n<!-- generated/properties/types.gen/type-aliases/PropertyTargetEntityType.md -->\n# Type Alias: PropertyTargetEntityType\n\n> **PropertyTargetEntityType** = `\"CALL_RECORD\"` \\| `\"CHANNEL\"` \\| `\"CHAT\"` \\| `\"COMPANY\"` \\| `\"DATABASE_ROW\"` \\| `\"DOCUMENT\"` \\| `\"INITIATIVE\"` \\| `\"PROJECT\"` \\| `\"THREAD\"` \\| `\"USER\"`\n\nCanonical type of an entity receiving properties.\n\nTasks are documents at API boundaries. `Task` intentionally does not exist\nhere; task classification is resolved by the properties domain from the\ndocument subtype.\n\n\n<!-- generated/properties/types.gen/type-aliases/PropertyTargetReference.md -->\n# Type Alias: PropertyTargetReference\n\n> **PropertyTargetReference** = \\{ `entity_id`: `string`; `entity_type`: [`PropertyTargetEntityType`](PropertyTargetEntityType.md); \\}\n\nCanonical reference to an entity receiving properties.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-entity_id\"></a> `entity_id` | `string` | Entity identifier. |\n| <a id=\"property-entity_type\"></a> `entity_type` | [`PropertyTargetEntityType`](PropertyTargetEntityType.md) | Canonical entity type. |\n\n\n<!-- generated/properties/types.gen/type-aliases/PropertyValue.md -->\n# Type Alias: PropertyValue\n\n> **PropertyValue** = \\{ `type`: `\"Boolean\"`; `value`: `boolean`; \\} \\| \\{ `type`: `\"Number\"`; `value`: `number`; \\} \\| \\{ `type`: `\"String\"`; `value`: `string`; \\} \\| \\{ `type`: `\"Date\"`; `value`: `string`; \\} \\| \\{ `type`: `\"SelectOption\"`; `value`: `string`[]; \\} \\| \\{ `type`: `\"EntityReference\"`; `value`: [`EntityReference`](EntityReference.md)[]; \\} \\| \\{ `type`: `\"Link\"`; `value`: `string`[]; \\}\n\nProperty value (service representation).\n\nRepresents the actual value stored for an entity property.\nThis is serialized to/from JSONB in the database.\n\n## Union Members\n\n### Type Literal\n\n\\{ `type`: `\"Boolean\"`; `value`: `boolean`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `type` | `\"Boolean\"` | - |\n| `value` | `boolean` | Boolean value Serializes as: {\"type\": \"Boolean\", \"value\": true} |\n\n***\n\n### Type Literal\n\n\\{ `type`: `\"Number\"`; `value`: `number`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `type` | `\"Number\"` | - |\n| `value` | `number` | Numeric value Serializes as: {\"type\": \"Number\", \"value\": 42.5} |\n\n***\n\n### Type Literal\n\n\\{ `type`: `\"String\"`; `value`: `string`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `type` | `\"String\"` | - |\n| `value` | `string` | String value Serializes as: {\"type\": \"String\", \"value\": \"text\"} |\n\n***\n\n### Type Literal\n\n\\{ `type`: `\"Date\"`; `value`: `string`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `type` | `\"Date\"` | - |\n| `value` | `string` | Date/timestamp value Serializes as: {\"type\": \"Date\", \"value\": \"2025-01-01T00:00:00Z\"} |\n\n***\n\n### Type Literal\n\n\\{ `type`: `\"SelectOption\"`; `value`: `string`[]; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `type` | `\"SelectOption\"` | - |\n| `value` | `string`[] | Select option(s) - always an array (check is_multi_select to determine if single or multi) Single-select: {\"type\": \"SelectOption\", \"value\": [\"uuid\"]} (length 0 or 1) Multi-select: {\"type\": \"SelectOption\", \"value\": [\"uuid1\", \"uuid2\", ...]} (length 0+) |\n\n***\n\n### Type Literal\n\n\\{ `type`: `\"EntityReference\"`; `value`: [`EntityReference`](EntityReference.md)[]; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `type` | `\"EntityReference\"` | - |\n| `value` | [`EntityReference`](EntityReference.md)[] | Entity reference(s) - always an array (check is_multi_select to determine if single or multi) Single-select: {\"type\": \"EntityReference\", \"value\": [{...}]} (length 0 or 1) Multi-select: {\"type\": \"EntityReference\", \"value\": [{...}, {...}, ...]} (length 0+) |\n\n***\n\n### Type Literal\n\n\\{ `type`: `\"Link\"`; `value`: `string`[]; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `type` | `\"Link\"` | - |\n| `value` | `string`[] | Link value(s) - always an array (check is_multi_select to determine if single or multi) Single-select: {\"type\": \"Link\", \"value\": [\"https://example.com\"]} (length 0 or 1) Multi-select: {\"type\": \"Link\", \"value\": [\"https://example.com\", \"https://other.com\"]} (length 0+) |\n\n\n<!-- generated/properties/types.gen/type-aliases/SetPropertyValue.md -->\n# Type Alias: SetPropertyValue\n\n> **SetPropertyValue** = \\{ `type`: `\"boolean\"`; `value`: `boolean`; \\} \\| \\{ `type`: `\"date\"`; `value`: `string`; \\} \\| \\{ `type`: `\"number\"`; `value`: `number`; \\} \\| \\{ `type`: `\"string\"`; `value`: `string`; \\} \\| \\{ `option_id`: `string`; `type`: `\"select_option\"`; \\} \\| \\{ `option_ids`: `string`[]; `type`: `\"multi_select_option\"`; \\} \\| \\{ `reference`: [`EntityReference`](EntityReference.md); `type`: `\"entity_reference\"`; \\} \\| \\{ `references`: [`EntityReference`](EntityReference.md)[]; `type`: `\"multi_entity_reference\"`; \\} \\| \\{ `type`: `\"link\"`; `url`: `string`; \\} \\| \\{ `type`: `\"multi_link\"`; `urls`: `string`[]; \\}\n\nType-safe enum for setting entity property values - provides compile-time validation.\n\n\n<!-- generated/storage/types.gen/type-aliases/AccessLevel.md -->\n# Type Alias: AccessLevel\n\n> **AccessLevel** = `\"view\"` \\| `\"comment\"` \\| `\"edit\"` \\| `\"owner\"`\n\nOrdered from least to most access top -> bottom\n\n\n<!-- generated/storage/types.gen/type-aliases/BomPart.md -->\n# Type Alias: BomPart\n\n> **BomPart** = \\{ `id`: `string`; `path`: `string`; `sha`: `string`; \\}\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-id\"></a> `id` | `string` | The uuid of the bom part |\n| <a id=\"property-path\"></a> `path` | `string` | The file path of the bom part content |\n| <a id=\"property-sha\"></a> `sha` | `string` | The sha of the bom part content There is an index on sha for more performant queries based on it. |\n\n\n<!-- generated/storage/types.gen/type-aliases/ChannelSharePermission.md -->\n# Type Alias: ChannelSharePermission\n\n> **ChannelSharePermission** = \\{ `access_level`: [`AccessLevel`](AccessLevel.md); `channel_id`: `string`; \\}\n\nThe channel share permission\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-access_level\"></a> `access_level` | [`AccessLevel`](AccessLevel.md) | The access level for the channel |\n| <a id=\"property-channel_id\"></a> `channel_id` | `string` | The channel id |\n\n\n<!-- generated/storage/types.gen/type-aliases/DocumentContent.md -->\n# Type Alias: DocumentContent\n\n> **DocumentContent** = \\{ `location?`: `null` \\| [`DocumentContentLocation`](DocumentContentLocation.md); `state`: [`DocumentContentState`](DocumentContentState.md); \\}\n\nAPI-visible content lifecycle and location metadata.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-location\"></a> `location?` | `null` \\| [`DocumentContentLocation`](DocumentContentLocation.md) | - |\n| <a id=\"property-state\"></a> `state` | [`DocumentContentState`](DocumentContentState.md) | The current lifecycle state of the content. |\n\n\n<!-- generated/storage/types.gen/type-aliases/DocumentContentLocation.md -->\n# Type Alias: DocumentContentLocation\n\n> **DocumentContentLocation** = `\"object_storage\"` \\| `\"sync_service\"` \\| `\"docx_bom_parts\"` \\| `\"converted_pdf\"` \\| `\"unknown\"`\n\nWhere document content is, or is expected to be, read from.\n\n\n<!-- generated/storage/types.gen/type-aliases/DocumentContentState.md -->\n# Type Alias: DocumentContentState\n\n> **DocumentContentState** = `\"unknown\"` \\| `\"pending\"` \\| `\"ready\"`\n\nAPI-visible content lifecycle state derived from current document metadata.\n\n\n<!-- generated/storage/types.gen/type-aliases/DocumentMetadata.md -->\n# Type Alias: DocumentMetadata\n\n> **DocumentMetadata** = \\{ `branchedFromId?`: `string` \\| `null`; `branchedFromVersionId?`: `number` \\| `null`; `createdAt?`: `string` \\| `null`; `deletedAt?`: `string` \\| `null`; `documentBom?`: [`BomPart`](BomPart.md)[] \\| `null`; `documentFamilyId?`: `number` \\| `null`; `documentId`: `string`; `documentName`: `string`; `documentVersionId`: `number`; `fileType?`: `string` \\| `null`; `modificationData?`: `unknown`; `owner`: `string`; `projectId?`: `string` \\| `null`; `projectName?`: `string` \\| `null`; `sha?`: `string` \\| `null`; `subType?`: `null` \\| [`DocumentSubType`](DocumentSubType.md); `updatedAt?`: `string` \\| `null`; \\}\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-branchedfromid\"></a> `branchedFromId?` | `string` \\| `null` | The id of the document this document branched from |\n| <a id=\"property-branchedfromversionid\"></a> `branchedFromVersionId?` | `number` \\| `null` | The id of the version this document branched from This could be either DocumentInstance or DocumentBom id depending on the file type |\n| <a id=\"property-createdat\"></a> `createdAt?` | `string` \\| `null` | The time the document was created |\n| <a id=\"property-deletedat\"></a> `deletedAt?` | `string` \\| `null` | The time the document was deleted |\n| <a id=\"property-documentbom\"></a> `documentBom?` | [`BomPart`](BomPart.md)[] \\| `null` | If the document is a DOCX document and unzipped, the document_bom will be present |\n| <a id=\"property-documentfamilyid\"></a> `documentFamilyId?` | `number` \\| `null` | The id of the document family this document belongs to |\n| <a id=\"property-documentid\"></a> `documentId` | `string` | The document id |\n| <a id=\"property-documentname\"></a> `documentName` | `string` | The name of the document |\n| <a id=\"property-documentversionid\"></a> `documentVersionId` | `number` | The version of the document This could be the document_instance_id or document_bom_id depending on the file type |\n| <a id=\"property-filetype\"></a> `fileType?` | `string` \\| `null` | The file type of the document (file extension) |\n| <a id=\"property-modificationdata\"></a> `modificationData?` | `unknown` | The modification data for the document instance. This is only used for PDF documents. |\n| <a id=\"property-owner\"></a> `owner` | `string` | The owner of the document |\n| <a id=\"property-projectid\"></a> `projectId?` | `string` \\| `null` | The id of the project that this document belongs to |\n| <a id=\"property-projectname\"></a> `projectName?` | `string` \\| `null` | The name of the project that this document belongs to |\n| <a id=\"property-sha\"></a> `sha?` | `string` \\| `null` | If the document is a PDF, this is the SHA of the pdf If the document is a DOCX, this will not be present |\n| <a id=\"property-subtype\"></a> `subType?` | `null` \\| [`DocumentSubType`](DocumentSubType.md) | - |\n| <a id=\"property-updatedat\"></a> `updatedAt?` | `string` \\| `null` | The time the document instance / document BOM was updated |\n\n\n<!-- generated/storage/types.gen/type-aliases/DocumentMetadataWithContent.md -->\n# Type Alias: DocumentMetadataWithContent\n\n> **DocumentMetadataWithContent** = [`DocumentMetadata`](DocumentMetadata.md) & \\{ `content`: [`DocumentContent`](DocumentContent.md); `teamId?`: `string` \\| `null`; `teamTaskId?`: `number` \\| `null`; \\}\n\nFull document metadata plus content lifecycle metadata.\n\n## Type Declaration\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `content` | [`DocumentContent`](DocumentContent.md) | Content lifecycle and location metadata. |\n| `teamId?` | `string` \\| `null` | The team this task number is scoped to, for task documents. |\n| `teamTaskId?` | `number` \\| `null` | The task number assigned within the team, for task documents. |\n\n\n<!-- generated/storage/types.gen/type-aliases/DocumentResponseMetadata.md -->\n# Type Alias: DocumentResponseMetadata\n\n> **DocumentResponseMetadata** = \\{ `branchedFromId?`: `string` \\| `null`; `branchedFromVersionId?`: `number` \\| `null`; `createdAt?`: `string` \\| `null`; `documentBom?`: [`BomPart`](BomPart.md)[] \\| `null`; `documentFamilyId?`: `number` \\| `null`; `documentId`: `string`; `documentName`: `string`; `documentVersionId`: `number`; `fileType?`: `string` \\| `null`; `modificationData?`: `unknown`; `owner`: `string`; `sha?`: `string` \\| `null`; `subType?`: `null` \\| [`DocumentSubType`](DocumentSubType.md); `updatedAt?`: `string` \\| `null`; \\}\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-branchedfromid\"></a> `branchedFromId?` | `string` \\| `null` | The id of the document this document branched from |\n| <a id=\"property-branchedfromversionid\"></a> `branchedFromVersionId?` | `number` \\| `null` | The id of the version this document branched from This could be either DocumentInstance or DocumentBom id depending on the file type |\n| <a id=\"property-createdat\"></a> `createdAt?` | `string` \\| `null` | The time the document was created |\n| <a id=\"property-documentbom\"></a> `documentBom?` | [`BomPart`](BomPart.md)[] \\| `null` | If the document is a DOCX document, the document_bom will be present |\n| <a id=\"property-documentfamilyid\"></a> `documentFamilyId?` | `number` \\| `null` | The id of the document family this document belongs to |\n| <a id=\"property-documentid\"></a> `documentId` | `string` | The document id |\n| <a id=\"property-documentname\"></a> `documentName` | `string` | The name of the document |\n| <a id=\"property-documentversionid\"></a> `documentVersionId` | `number` | The version of the document This could be the document_instance_id or document_bom_id depending on the file type |\n| <a id=\"property-filetype\"></a> `fileType?` | `string` \\| `null` | The file type of the document |\n| <a id=\"property-modificationdata\"></a> `modificationData?` | `unknown` | The modification data for the document instance. This is only used for PDF documents. |\n| <a id=\"property-owner\"></a> `owner` | `string` | The owner of the document |\n| <a id=\"property-sha\"></a> `sha?` | `string` \\| `null` | If the document is a PDF, this is the SHA of the pdf If the document is a DOCX, this will not be present |\n| <a id=\"property-subtype\"></a> `subType?` | `null` \\| [`DocumentSubType`](DocumentSubType.md) | - |\n| <a id=\"property-updatedat\"></a> `updatedAt?` | `string` \\| `null` | The time the document instance / document BOM was updated |\n\n\n<!-- generated/storage/types.gen/type-aliases/DocumentSubType.md -->\n# Type Alias: DocumentSubType\n\n> **DocumentSubType** = `\"task\"` \\| `\"snippet\"` \\| `\"skill\"` \\| `\"initiative_description\"`\n\nThe document sub type enum represents all values of document sub types.\nThese values should match the `document_sub_type_value` table in macrodb.\n\nWire, database, and `Display` spellings are all `snake_case` so a\nmulti-word variant serializes identically in every system.\n\n\n<!-- generated/storage/types.gen/type-aliases/DocumentTeamShareResponse.md -->\n# Type Alias: DocumentTeamShareResponse\n\n> **DocumentTeamShareResponse** = \\{ `sharedWithTeam`: `boolean`; `teamId?`: `string` \\| `null`; \\}\n\nThe team-share state of a document. The team is resolved from the document\nowner's team membership.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-sharedwithteam\"></a> `sharedWithTeam` | `boolean` | Whether explicit team sharing is enabled; inherited team access does not count. |\n| <a id=\"property-teamid\"></a> `teamId?` | `string` \\| `null` | The owner's team the document is (or would be) shared with. `None` when the owner does not belong to a team. |\n\n\n<!-- generated/storage/types.gen/type-aliases/EntityPermission.md -->\n# Type Alias: EntityPermission\n\n> **EntityPermission** = \\{ `access_level`: [`AccessLevel`](AccessLevel.md); `type`: `\"access_level\"`; \\} \\| \\{ `type`: `\"channel_view_only\"`; \\} \\| \\{ `role`: [`ParticipantRole`](ParticipantRole.md); `type`: `\"channel_role\"`; \\} \\| \\{ `role`: [`TeamRole`](TeamRole.md); `type`: `\"team_role\"`; \\}\n\nA user's permission for an entity, discriminated by entity kind.\n\nItems (documents, chats, projects, threads) use access levels.\nChannels use view-only permission or participant roles.\n\n## Union Members\n\n### Type Literal\n\n\\{ `access_level`: [`AccessLevel`](AccessLevel.md); `type`: `\"access_level\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `access_level` | [`AccessLevel`](AccessLevel.md) | The access level the user has. |\n| `type` | `\"access_level\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `type`: `\"channel_view_only\"`; \\}\n\n***\n\n### Type Literal\n\n\\{ `role`: [`ParticipantRole`](ParticipantRole.md); `type`: `\"channel_role\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `role` | [`ParticipantRole`](ParticipantRole.md) | The role the user has in the channel. |\n| `type` | `\"channel_role\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `role`: [`TeamRole`](TeamRole.md); `type`: `\"team_role\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `role` | [`TeamRole`](TeamRole.md) | The role the user has in the team. |\n| `type` | `\"team_role\"` | - |\n\n\n<!-- generated/storage/types.gen/type-aliases/GithubPullRequest.md -->\n# Type Alias: GithubPullRequest\n\n> **GithubPullRequest** = \\{ `additions?`: `number` \\| `null`; `checks?`: [`GithubPullRequestCheckRun`](GithubPullRequestCheckRun.md)[] \\| `null`; `comments?`: [`GithubPullRequestComment`](GithubPullRequestComment.md)[] \\| `null`; `deletions?`: `number` \\| `null`; `displayName`: `string`; `foreignEntityId?`: `string` \\| `null`; `githubKey`: `string`; `name?`: `string` \\| `null`; `number`: `number`; `owner`: `string`; `repo`: `string`; `status?`: `string` \\| `null`; `url`: `string`; \\}\n\nDisplay-ready data for a GitHub pull request associated with a task.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-additions\"></a> `additions?` | `number` \\| `null` | The number of added lines in the pull request, when enrichment data is available. |\n| <a id=\"property-checks\"></a> `checks?` | [`GithubPullRequestCheckRun`](GithubPullRequestCheckRun.md)[] \\| `null` | Check runs collected from the pull request head commit, when enrichment data is available. |\n| <a id=\"property-comments\"></a> `comments?` | [`GithubPullRequestComment`](GithubPullRequestComment.md)[] \\| `null` | Comments collected from the pull request, when enrichment data is available. |\n| <a id=\"property-deletions\"></a> `deletions?` | `number` \\| `null` | The number of deleted lines in the pull request, when enrichment data is available. |\n| <a id=\"property-displayname\"></a> `displayName` | `string` | A compact label suitable for display in the UI. |\n| <a id=\"property-foreignentityid\"></a> `foreignEntityId?` | `string` \\| `null` | The internal `foreign_entity.id` UUID for the GitHub pull request row. |\n| <a id=\"property-githubkey\"></a> `githubKey` | `string` | The stored GitHub association key, in `owner/repo/pull/number` format. |\n| <a id=\"property-name\"></a> `name?` | `string` \\| `null` | The GitHub pull request title, when enrichment data is available. |\n| <a id=\"property-number\"></a> `number` | `number` | The GitHub pull request number. |\n| <a id=\"property-owner\"></a> `owner` | `string` | The GitHub repository owner or organization. |\n| <a id=\"property-repo\"></a> `repo` | `string` | The GitHub repository name. |\n| <a id=\"property-status\"></a> `status?` | `string` \\| `null` | The GitHub pull request status, when enrichment data is available. |\n| <a id=\"property-url\"></a> `url` | `string` | The public GitHub URL for the pull request. |\n\n\n<!-- generated/storage/types.gen/type-aliases/GithubPullRequestCheckRun.md -->\n# Type Alias: GithubPullRequestCheckRun\n\n> **GithubPullRequestCheckRun** = \\{ `completedAt?`: `string` \\| `null`; `conclusion?`: `string` \\| `null`; `id`: `number`; `name`: `string`; `startedAt?`: `string` \\| `null`; `status`: `string`; `url?`: `string` \\| `null`; \\}\n\nA check run associated with a GitHub pull request.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-completedat\"></a> `completedAt?` | `string` \\| `null` | When the check run completed, when available. |\n| <a id=\"property-conclusion\"></a> `conclusion?` | `string` \\| `null` | The raw GitHub check run conclusion, when the run has completed. |\n| <a id=\"property-id\"></a> `id` | `number` | The unique GitHub identifier for the check run. |\n| <a id=\"property-name\"></a> `name` | `string` | The check run name. |\n| <a id=\"property-startedat\"></a> `startedAt?` | `string` \\| `null` | When the check run started, when available. |\n| <a id=\"property-status\"></a> `status` | `string` | The raw GitHub check run status. |\n| <a id=\"property-url\"></a> `url?` | `string` \\| `null` | The public GitHub URL for the check run, when available. |\n\n\n<!-- generated/storage/types.gen/type-aliases/GithubPullRequestComment.md -->\n# Type Alias: GithubPullRequestComment\n\n> **GithubPullRequestComment** = \\{ `authorAssociation?`: `string` \\| `null`; `authorId?`: `number` \\| `null`; `authorLogin?`: `string` \\| `null`; `body`: `string`; `createdAt?`: `string` \\| `null`; `id`: `number`; `inReplyToId?`: `number` \\| `null`; `line?`: `number` \\| `null`; `originalLine?`: `number` \\| `null`; `path?`: `string` \\| `null`; `pullRequestReviewId?`: `number` \\| `null`; `source`: `string`; `updatedAt?`: `string` \\| `null`; `url?`: `string` \\| `null`; \\}\n\nA comment associated with a GitHub pull request.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-authorassociation\"></a> `authorAssociation?` | `string` \\| `null` | GitHub's relationship label for the author, when available. |\n| <a id=\"property-authorid\"></a> `authorId?` | `number` \\| `null` | The stable numeric GitHub user id for the comment author, when available. |\n| <a id=\"property-authorlogin\"></a> `authorLogin?` | `string` \\| `null` | The GitHub login for the comment author, when available. |\n| <a id=\"property-body\"></a> `body` | `string` | The comment or review body text. |\n| <a id=\"property-createdat\"></a> `createdAt?` | `string` \\| `null` | When the comment was created or the review was submitted. |\n| <a id=\"property-id\"></a> `id` | `number` | The unique GitHub identifier for the comment or review. |\n| <a id=\"property-inreplytoid\"></a> `inReplyToId?` | `number` \\| `null` | The id of the comment this one replies to, when it is part of a review thread. Only ever present on `review_comment` sources. |\n| <a id=\"property-line\"></a> `line?` | `number` \\| `null` | The line in the current diff the comment is anchored to. Cleared by GitHub when later commits outdate the comment's diff. |\n| <a id=\"property-originalline\"></a> `originalLine?` | `number` \\| `null` | The line the comment was originally anchored to, kept even when the diff has since changed. |\n| <a id=\"property-path\"></a> `path?` | `string` \\| `null` | The repository-relative file path the review comment is anchored to. Only ever present on `review_comment` sources. |\n| <a id=\"property-pullrequestreviewid\"></a> `pullRequestReviewId?` | `number` \\| `null` | The id of the pull request review this comment was submitted with. Only ever present on `review_comment` sources. |\n| <a id=\"property-source\"></a> `source` | `string` | The GitHub source for the comment, such as `issue_comment` or `review_comment`. |\n| <a id=\"property-updatedat\"></a> `updatedAt?` | `string` \\| `null` | When the comment or review was last updated. |\n| <a id=\"property-url\"></a> `url?` | `string` \\| `null` | The public GitHub URL for the comment or review, when available. |\n\n\n<!-- generated/storage/types.gen/type-aliases/HighlightType.md -->\n# Type Alias: HighlightType\n\n> **HighlightType** = `1` \\| `2` \\| `3`\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkShare.md -->\n# Type Alias: LinkShare\n\n> **LinkShare** = `\"PUBLIC\"` \\| `\"TEAM\"`\n\nDefines who can access an item through its share link.\n\n\n<!-- generated/storage/types.gen/type-aliases/MessageCursor.md -->\n# Type Alias: MessageCursor\n\n> **MessageCursor** = \\{ `created_at`: `string`; `id`: `string`; \\}\n\nCursor for a chronological parent timeline.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-created_at\"></a> `created_at` | `string` | Last message creation time or activity occurrence time. |\n| <a id=\"property-id\"></a> `id` | `string` | Last entry UUID, used to break timestamp ties across both sources. |\n\n\n<!-- generated/storage/types.gen/type-aliases/ParticipantRole.md -->\n# Type Alias: ParticipantRole\n\n> **ParticipantRole** = `\"owner\"` \\| `\"admin\"` \\| `\"member\"`\n\nThe role a user has within a channel.\n\n\n<!-- generated/storage/types.gen/type-aliases/PdfHighlightAnchorRequest.md -->\n# Type Alias: PdfHighlightAnchorRequest\n\n> **PdfHighlightAnchorRequest** = \\{ `alpha`: `number`; `blue`: `number`; `green`: `number`; `highlightRects`: [`PdfHighlightRectAnchorRequest`](PdfHighlightRectAnchorRequest.md)[]; `highlightType`: [`HighlightType`](HighlightType.md); `page`: `number`; `pageViewportHeight`: `number`; `pageViewportWidth`: `number`; `red`: `number`; `text`: `string`; `uuid?`: `string` \\| `null`; \\}\n\n## Properties\n\n| Property | Type |\n| ------ | ------ |\n| <a id=\"property-alpha\"></a> `alpha` | `number` |\n| <a id=\"property-blue\"></a> `blue` | `number` |\n| <a id=\"property-green\"></a> `green` | `number` |\n| <a id=\"property-highlightrects\"></a> `highlightRects` | [`PdfHighlightRectAnchorRequest`](PdfHighlightRectAnchorRequest.md)[] |\n| <a id=\"property-highlighttype\"></a> `highlightType` | [`HighlightType`](HighlightType.md) |\n| <a id=\"property-page\"></a> `page` | `number` |\n| <a id=\"property-pageviewportheight\"></a> `pageViewportHeight` | `number` |\n| <a id=\"property-pageviewportwidth\"></a> `pageViewportWidth` | `number` |\n| <a id=\"property-red\"></a> `red` | `number` |\n| <a id=\"property-text\"></a> `text` | `string` |\n| <a id=\"property-uuid\"></a> `uuid?` | `string` \\| `null` |\n\n\n<!-- generated/storage/types.gen/type-aliases/PdfHighlightRectAnchorRequest.md -->\n# Type Alias: PdfHighlightRectAnchorRequest\n\n> **PdfHighlightRectAnchorRequest** = \\{ `height`: `number`; `left`: `number`; `top`: `number`; `width`: `number`; \\}\n\n## Properties\n\n| Property | Type |\n| ------ | ------ |\n| <a id=\"property-height\"></a> `height` | `number` |\n| <a id=\"property-left\"></a> `left` | `number` |\n| <a id=\"property-top\"></a> `top` | `number` |\n| <a id=\"property-width\"></a> `width` | `number` |\n\n\n<!-- generated/storage/types.gen/type-aliases/PreSaveDocumentResponseData.md -->\n# Type Alias: PreSaveDocumentResponseData\n\n> **PreSaveDocumentResponseData** = \\{ `presignedUrls`: [`PresignedUrl`](PresignedUrl.md)[]; \\}\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-presignedurls\"></a> `presignedUrls` | [`PresignedUrl`](PresignedUrl.md)[] | Contains any presigned urls you need to upload specific bom parts with. |\n\n\n<!-- generated/storage/types.gen/type-aliases/PresignedUrl.md -->\n# Type Alias: PresignedUrl\n\n> **PresignedUrl** = \\{ `presignedUrl`: `string`; `sha`: `string`; \\}\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-presignedurl\"></a> `presignedUrl` | `string` | The presigned url used to upload the sha |\n| <a id=\"property-sha\"></a> `sha` | `string` | The sha of the item |\n\n\n<!-- generated/storage/types.gen/type-aliases/SaveBomPart.md -->\n# Type Alias: SaveBomPart\n\n> **SaveBomPart** = \\{ `path`: `string`; `sha`: `string`; \\}\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-path\"></a> `path` | `string` | The file path of the bom part content |\n| <a id=\"property-sha\"></a> `sha` | `string` | The sha of the bom part content There is an index on sha for more performant queries based on it. |\n\n\n<!-- generated/storage/types.gen/type-aliases/SaveDocumentRequest.md -->\n# Type Alias: SaveDocumentRequest\n\n> **SaveDocumentRequest** = \\{ `modificationData?`: `unknown`; `newBom?`: [`SaveBomPart`](SaveBomPart.md)[] \\| `null`; `sha?`: `string` \\| `null`; \\}\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-modificationdata\"></a> `modificationData?` | `unknown` | The modification data for the document instance. Used to store highlights and other overlays onto a static file |\n| <a id=\"property-newbom\"></a> `newBom?` | [`SaveBomPart`](SaveBomPart.md)[] \\| `null` | **DOCX ONLY** The updated BOM for the document. Containing the file path and the sha. |\n| <a id=\"property-sha\"></a> `sha?` | `string` \\| `null` | The sha of the new document. This is used to generate a presigned url to upload the new document content to s3. |\n\n\n<!-- generated/storage/types.gen/type-aliases/SaveDocumentResponseData.md -->\n# Type Alias: SaveDocumentResponseData\n\n> **SaveDocumentResponseData** = \\{ `documentMetadata`: [`DocumentResponseMetadata`](DocumentResponseMetadata.md); `presignedUrl?`: `string` \\| `null`; \\}\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-documentmetadata\"></a> `documentMetadata` | [`DocumentResponseMetadata`](DocumentResponseMetadata.md) | The updated document metadata |\n| <a id=\"property-presignedurl\"></a> `presignedUrl?` | `string` \\| `null` | If the document is an editable file, we provide a presigned url to save the updated file to. |\n\n\n<!-- generated/storage/types.gen/type-aliases/SharePermissionV2.md -->\n# Type Alias: SharePermissionV2\n\n> **SharePermissionV2** = \\{ `channelSharePermissions?`: [`ChannelSharePermission`](ChannelSharePermission.md)[] \\| `null`; `id`: `string`; `linkShare?`: `null` \\| [`LinkShare`](LinkShare.md); `linkShareAccessLevel?`: `null` \\| [`AccessLevel`](AccessLevel.md); `owner`: `string`; `teamShareAccessLevel?`: `null` \\| [`AccessLevel`](AccessLevel.md); \\}\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-channelsharepermissions\"></a> `channelSharePermissions?` | [`ChannelSharePermission`](ChannelSharePermission.md)[] \\| `null` | The channel share permissions for the item |\n| <a id=\"property-id\"></a> `id` | `string` | The share permission id |\n| <a id=\"property-linkshare\"></a> `linkShare?` | `null` \\| [`LinkShare`](LinkShare.md) | - |\n| <a id=\"property-linkshareaccesslevel\"></a> `linkShareAccessLevel?` | `null` \\| [`AccessLevel`](AccessLevel.md) | - |\n| <a id=\"property-owner\"></a> `owner` | `string` | The owner of the item |\n| <a id=\"property-teamshareaccesslevel\"></a> `teamShareAccessLevel?` | `null` \\| [`AccessLevel`](AccessLevel.md) | - |\n\n\n<!-- generated/storage/types.gen/type-aliases/TeamRole.md -->\n# Type Alias: TeamRole\n\n> **TeamRole** = `\"member\"` \\| `\"admin\"` \\| `\"owner\"`\n\nThe role a user has within a team.\n\nOrdered least to most privileged so comparisons reflect access strength.\n\n\n<!-- src/entities/tasks/namespace/classes/TaskNamespace.md -->\n# Class: TaskNamespace\n\n## Constructors\n\n### Constructor\n\n> **new TaskNamespace**(`client`): `TaskNamespace`\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n\n#### Returns\n\n`TaskNamespace`\n\n## Methods\n\n### byId()\n\n> **byId**(`id`): [`Task`](../../task/classes/Task.md)\n\nA handle to a task by document id. Details load on first access.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `id` | `string` |\n\n#### Returns\n\n[`Task`](../../task/classes/Task.md)\n\n***\n\n### create()\n\n> **create**(`opts`): `Promise`\\<[`Task`](../../task/classes/Task.md)\\>\n\nCreate a task.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `opts` | \\{ `markdown?`: `string`; `name`: `string`; `project?`: [`Project`](../../../projects/project/classes/Project.md); `shareWithTeam?`: `boolean`; `team?`: [`Team`](../../../teams/team/classes/Team.md); \\} |\n| `opts.markdown?` | `string` |\n| `opts.name` | `string` |\n| `opts.project?` | [`Project`](../../../projects/project/classes/Project.md) |\n| `opts.shareWithTeam?` | `boolean` |\n| `opts.team?` | [`Team`](../../../teams/team/classes/Team.md) |\n\n#### Returns\n\n`Promise`\\<[`Task`](../../task/classes/Task.md)\\>\n\n***\n\n### forPullRequest()\n\n> **forPullRequest**(`url`): `Promise`\\<[`Task`](../../task/classes/Task.md)[]\\>\n\nThe tasks the GitHub pull request at `url` references, oldest link first.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `url` | `string` |\n\n#### Returns\n\n`Promise`\\<[`Task`](../../task/classes/Task.md)[]\\>\n\n***\n\n### search()\n\n> **search**(`query`, `opts?`): `AsyncGenerator`\\<[`Task`](../../task/classes/Task.md)\\>\n\nSearch tasks by name and content, most relevant first, auto-paginated.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `query` | `string` |\n| `opts?` | [`SearchOpts`](../../../search/interfaces/SearchOpts.md) |\n\n#### Returns\n\n`AsyncGenerator`\\<[`Task`](../../task/classes/Task.md)\\>\n\n\n<!-- src/entities/tasks/task/classes/Task.md -->\n# Class: Task\n\nA Macro task: a document with sub-type `task`. Inherits the full document\nsurface ([Document.rename](../../../documents/document/classes/Document.md#rename), move, delete, restore, content, events)\nand adds task-specific state.\n\n## Extends\n\n- [`Document`](../../../documents/document/classes/Document.md)\n\n## Properties\n\n| Property | Modifier | Type | Default value | Description | Overrides | Inherited from |\n| ------ | ------ | ------ | ------ | ------ | ------ | ------ |\n| <a id=\"property-access\"></a> `access` | `readonly` | [`EntityAccess`](../../../sharing/access/classes/EntityAccess.md) | `...` | Access requests and direct user grants. | - | [`Document`](../../../documents/document/classes/Document.md).[`access`](../../../documents/document/classes/Document.md#property-access) |\n| <a id=\"property-branchedfrom\"></a> `branchedFrom` | `readonly` | () => `Promise`\\<[`Document`](../../../documents/document/classes/Document.md) \\| `undefined`\\> | `...` | The document this one was branched from, if any. | - | [`Document`](../../../documents/document/classes/Document.md).[`branchedFrom`](../../../documents/document/classes/Document.md#property-branchedfrom) |\n| <a id=\"property-createdat\"></a> `createdAt` | `readonly` | () => `Promise`\\<`string` \\| `undefined`\\> | `...` | When the document was created. | - | [`Document`](../../../documents/document/classes/Document.md).[`createdAt`](../../../documents/document/classes/Document.md#property-createdat) |\n| <a id=\"property-deletedat\"></a> `deletedAt` | `readonly` | () => `Promise`\\<`string` \\| `undefined`\\> | `...` | When the document was deleted, if it has been. | - | [`Document`](../../../documents/document/classes/Document.md).[`deletedAt`](../../../documents/document/classes/Document.md#property-deletedat) |\n| <a id=\"property-entitytype\"></a> `entityType` | `readonly` | `\"document\"` | `'document'` | Favorites identify documents as `document`. | - | [`Document`](../../../documents/document/classes/Document.md).[`entityType`](../../../documents/document/classes/Document.md#property-entitytype) |\n| <a id=\"property-filetype\"></a> `fileType` | `readonly` | () => `Promise`\\<`string` \\| `undefined`\\> | `...` | The document's file type (e.g. `md`, `pdf`, `docx`). | - | [`Document`](../../../documents/document/classes/Document.md).[`fileType`](../../../documents/document/classes/Document.md#property-filetype) |\n| <a id=\"property-id\"></a> `id` | `public readonly` | `string` | `undefined` | - | - | [`Document`](../../../documents/document/classes/Document.md).[`id`](../../../documents/document/classes/Document.md#property-id) |\n| <a id=\"property-name\"></a> `name` | `readonly` | () => `Promise`\\<`string`\\> | `...` | The document's display name. | - | [`Document`](../../../documents/document/classes/Document.md).[`name`](../../../documents/document/classes/Document.md#property-name) |\n| <a id=\"property-owner\"></a> `owner` | `readonly` | () => `Promise`\\<[`User`](../../../users/user/classes/User.md)\\> | `...` | The user who owns the document. | - | [`Document`](../../../documents/document/classes/Document.md).[`owner`](../../../documents/document/classes/Document.md#property-owner) |\n| <a id=\"property-project\"></a> `project` | `readonly` | () => `Promise`\\<[`Project`](../../../projects/project/classes/Project.md) \\| `undefined`\\> | `...` | The project this document belongs to, if any. | - | [`Document`](../../../documents/document/classes/Document.md).[`project`](../../../documents/document/classes/Document.md#property-project) |\n| <a id=\"property-updatedat\"></a> `updatedAt` | `readonly` | () => `Promise`\\<`string` \\| `undefined`\\> | `...` | When the document was last updated. | - | [`Document`](../../../documents/document/classes/Document.md).[`updatedAt`](../../../documents/document/classes/Document.md#property-updatedat) |\n| <a id=\"property-search\"></a> `search` | `static` | (`client`, `query`, `searchOpts?`) => `AsyncGenerator`\\<`Task`\\> | `...` | Search tasks by name and content, most relevant first, auto-paginated. | [`Document`](../../../documents/document/classes/Document.md).[`search`](../../../documents/document/classes/Document.md#property-search) | - |\n\n## Methods\n\n### anchors()\n\n> **anchors**(): `Promise`\\<[`DocumentAnchor`](../../../documents/anchor/classes/DocumentAnchor.md)[]\\>\n\nPDF annotations in this document.\n\n#### Returns\n\n`Promise`\\<[`DocumentAnchor`](../../../documents/anchor/classes/DocumentAnchor.md)[]\\>\n\n#### Inherited from\n\n[`Document`](../../../documents/document/classes/Document.md).[`anchors`](../../../documents/document/classes/Document.md#anchors)\n\n***\n\n### branchName()\n\n> **branchName**(): `Promise`\\<`string`\\>\n\nThe git branch name derived for the document (task documents).\n\n#### Returns\n\n`Promise`\\<`string`\\>\n\n#### Inherited from\n\n[`Document`](../../../documents/document/classes/Document.md).[`branchName`](../../../documents/document/classes/Document.md#branchname)\n\n***\n\n### comment()\n\n> **comment**(`body`, `opts?`): `Promise`\\<[`Comment`](../../../documents/comment/classes/Comment.md)\\>\n\nAdd a comment. Starts a new unanchored thread, or replies to an existing\none when `threadId` (the thread's root comment id) is given.\n\n#### Parameters\n\n| Parameter | Type | Description |\n| ------ | ------ | ------ |\n| `body` | `string` \\| [`RichMessage`](../../../../mentions/interfaces/RichMessage.md) | Plain text, or a rich body composed with msg. |\n| `opts?` | \\{ `threadId?`: `string`; \\} | - |\n| `opts.threadId?` | `string` | - |\n\n#### Returns\n\n`Promise`\\<[`Comment`](../../../documents/comment/classes/Comment.md)\\>\n\nThe created comment.\n\n#### Inherited from\n\n[`Document`](../../../documents/document/classes/Document.md).[`comment`](../../../documents/document/classes/Document.md#comment)\n\n***\n\n### comments()\n\n> **comments**(): `Promise`\\<[`CommentThread`](../../../documents/document/interfaces/CommentThread.md)[]\\>\n\nThe document's live comment threads, each with its comments, newest thread first.\n\n#### Returns\n\n`Promise`\\<[`CommentThread`](../../../documents/document/interfaces/CommentThread.md)[]\\>\n\n#### Inherited from\n\n[`Document`](../../../documents/document/classes/Document.md).[`comments`](../../../documents/document/classes/Document.md#comments)\n\n***\n\n### completed()\n\n> **completed**(): `Promise`\\<`boolean` \\| `undefined`\\>\n\nWhether the task is completed (its Status property is \"Completed\");\n`undefined` if the document is not a task.\n\n#### Returns\n\n`Promise`\\<`boolean` \\| `undefined`\\>\n\n***\n\n### content()\n\n> **content**(): `Promise`\\<`string`\\>\n\nCurrent Markdown for native documents, extracted text for PDF/Word,\nor raw file content for other formats. Native reads include live edits.\n\n#### Returns\n\n`Promise`\\<`string`\\>\n\n#### Inherited from\n\n[`Document`](../../../documents/document/classes/Document.md).[`content`](../../../documents/document/classes/Document.md#content)\n\n***\n\n### copy()\n\n> **copy**(`opts`): `Promise`\\<[`Document`](../../../documents/document/classes/Document.md)\\>\n\nCopy the document under a new name, optionally from a specific version.\nReturns a handle to the new document.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `opts` | \\{ `name`: `string`; `versionId?`: `number`; \\} |\n| `opts.name` | `string` |\n| `opts.versionId?` | `number` |\n\n#### Returns\n\n`Promise`\\<[`Document`](../../../documents/document/classes/Document.md)\\>\n\n#### Inherited from\n\n[`Document`](../../../documents/document/classes/Document.md).[`copy`](../../../documents/document/classes/Document.md#copy)\n\n***\n\n### createHighlight()\n\n> **createHighlight**(`options`): `Promise`\\<[`DocumentAnchor`](../../../documents/anchor/classes/DocumentAnchor.md)\\>\n\nCreate a standalone PDF highlight.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `options` | `Omit`\\<[`PdfHighlightAnchorRequest`](../../../../../generated/storage/types.gen/type-aliases/PdfHighlightAnchorRequest.md), `\"uuid\"`\\> |\n\n#### Returns\n\n`Promise`\\<[`DocumentAnchor`](../../../documents/anchor/classes/DocumentAnchor.md)\\>\n\n#### Inherited from\n\n[`Document`](../../../documents/document/classes/Document.md).[`createHighlight`](../../../documents/document/classes/Document.md#createhighlight)\n\n***\n\n### delete()\n\n> **delete**(`opts?`): `Promise`\\<`void`\\>\n\nDelete the document. Soft by default (reversible with [restore](../../../documents/document/classes/Document.md#restore));\npass `permanent: true` to delete irreversibly.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `opts?` | \\{ `permanent?`: `boolean`; \\} |\n| `opts.permanent?` | `boolean` |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n#### Inherited from\n\n[`Document`](../../../documents/document/classes/Document.md).[`delete`](../../../documents/document/classes/Document.md#delete)\n\n***\n\n### deleteProperty()\n\n> **deleteProperty**(`assignment`): `Promise`\\<`void`\\>\n\nRemove a property from this entity, given its [properties](#properties) entry.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `assignment` | [`EntityPropertyWithDefinition`](../../../../../generated/properties/types.gen/type-aliases/EntityPropertyWithDefinition.md) |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n#### Inherited from\n\n[`Document`](../../../documents/document/classes/Document.md).[`deleteProperty`](../../../documents/document/classes/Document.md#deleteproperty)\n\n***\n\n### favorite()\n\n> **favorite**(): `Promise`\\<`Task`\\>\n\nAdd this entity to the user's favorites. Returns this handle for chaining.\nPlain unwrap: favoriting alters the user's favorites collection, not this\nentity's own detail, so there's nothing cached to invalidate.\n\n#### Returns\n\n`Promise`\\<`Task`\\>\n\n#### Inherited from\n\n[`Document`](../../../documents/document/classes/Document.md).[`favorite`](../../../documents/document/classes/Document.md#favorite)\n\n***\n\n### githubPullRequests()\n\n> **githubPullRequests**(): `Promise`\\<[`GithubPullRequest`](../../../../../generated/storage/types.gen/type-aliases/GithubPullRequest.md)[]\\>\n\nGitHub pull requests associated with the document.\n\n#### Returns\n\n`Promise`\\<[`GithubPullRequest`](../../../../../generated/storage/types.gen/type-aliases/GithubPullRequest.md)[]\\>\n\n#### Inherited from\n\n[`Document`](../../../documents/document/classes/Document.md).[`githubPullRequests`](../../../documents/document/classes/Document.md#githubpullrequests)\n\n***\n\n### meetingNotes()\n\n> **meetingNotes**(): `Promise`\\<\\{ `eventTitle`: `string`; `note`: [`CalendarNote`](../../../calendar/note/classes/CalendarNote.md); \\}[]\\>\n\nOwner-only meeting grants, including unavailable meetings. Unlink a returned note to revoke its meeting/team access.\n\n#### Returns\n\n`Promise`\\<\\{ `eventTitle`: `string`; `note`: [`CalendarNote`](../../../calendar/note/classes/CalendarNote.md); \\}[]\\>\n\n#### Inherited from\n\n[`Document`](../../../documents/document/classes/Document.md).[`meetingNotes`](../../../documents/document/classes/Document.md#meetingnotes)\n\n***\n\n### messageThreadById()\n\n> **messageThreadById**(`id`): [`MessageThread`](../../../messages/thread/classes/MessageThread.md)\n\nA shared message thread scoped to this resource.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `id` | `string` |\n\n#### Returns\n\n[`MessageThread`](../../../messages/thread/classes/MessageThread.md)\n\n#### Inherited from\n\n[`Document`](../../../documents/document/classes/Document.md).[`messageThreadById`](../../../documents/document/classes/Document.md#messagethreadbyid)\n\n***\n\n### move()\n\n> **move**(`project`): `Promise`\\<`void`\\>\n\nMove the document into a project (or out of one, with `null`).\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `project` | [`Project`](../../../projects/project/classes/Project.md) \\| `null` |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n#### Inherited from\n\n[`Document`](../../../documents/document/classes/Document.md).[`move`](../../../documents/document/classes/Document.md#move)\n\n***\n\n### permission()\n\n> **permission**(): `Promise`\\<\\{ `permission`: [`EntityPermission`](../../../../../generated/storage/types.gen/type-aliases/EntityPermission.md); `status`: `\"access\"`; \\} \\| \\{ `status`: `\"no_access\"`; \\}\\>\n\nRead the caller's effective permission on this entity.\n\n#### Returns\n\n`Promise`\\<\\{ `permission`: [`EntityPermission`](../../../../../generated/storage/types.gen/type-aliases/EntityPermission.md); `status`: `\"access\"`; \\} \\| \\{ `status`: `\"no_access\"`; \\}\\>\n\n#### Inherited from\n\n[`Document`](../../../documents/document/classes/Document.md).[`permission`](../../../documents/document/classes/Document.md#permission)\n\n***\n\n### permissionsToken()\n\n> **permissionsToken**(): `Promise`\\<`string`\\>\n\nMint a scoped permissions token.\n\n#### Returns\n\n`Promise`\\<`string`\\>\n\n#### Inherited from\n\n[`Document`](../../../documents/document/classes/Document.md).[`permissionsToken`](../../../documents/document/classes/Document.md#permissionstoken)\n\n***\n\n### prepareSave()\n\n> **prepareSave**(`parts`): `Promise`\\<[`PreSaveDocumentResponseData`](../../../../../generated/storage/types.gen/type-aliases/PreSaveDocumentResponseData.md)\\>\n\nPrepare multipart content saving and return the service's upload instructions.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `parts` | [`SaveBomPart`](../../../../../generated/storage/types.gen/type-aliases/SaveBomPart.md)[] |\n\n#### Returns\n\n`Promise`\\<[`PreSaveDocumentResponseData`](../../../../../generated/storage/types.gen/type-aliases/PreSaveDocumentResponseData.md)\\>\n\n#### Inherited from\n\n[`Document`](../../../documents/document/classes/Document.md).[`prepareSave`](../../../documents/document/classes/Document.md#preparesave)\n\n***\n\n### properties()\n\n> **properties**(`opts?`): `Promise`\\<[`EntityPropertyWithDefinition`](../../../../../generated/properties/types.gen/type-aliases/EntityPropertyWithDefinition.md)[]\\>\n\nThe properties set on this entity, each with its definition, value, and options.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `opts?` | \\{ `includeMetadata?`: `boolean`; \\} |\n| `opts.includeMetadata?` | `boolean` |\n\n#### Returns\n\n`Promise`\\<[`EntityPropertyWithDefinition`](../../../../../generated/properties/types.gen/type-aliases/EntityPropertyWithDefinition.md)[]\\>\n\n#### Inherited from\n\n[`Document`](../../../documents/document/classes/Document.md).[`properties`](../../../documents/document/classes/Document.md#properties)\n\n***\n\n### propertyReference()\n\n> **propertyReference**(): [`PropertyTargetReference`](../../../../../generated/properties/types.gen/type-aliases/PropertyTargetReference.md)\n\nThis entity's reference for bulk property operations.\n\n#### Returns\n\n[`PropertyTargetReference`](../../../../../generated/properties/types.gen/type-aliases/PropertyTargetReference.md)\n\n#### Inherited from\n\n[`Document`](../../../documents/document/classes/Document.md).[`propertyReference`](../../../documents/document/classes/Document.md#propertyreference)\n\n***\n\n### rename()\n\n> **rename**(`name`): `Promise`\\<`void`\\>\n\nRename the document.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `name` | `string` |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n#### Inherited from\n\n[`Document`](../../../documents/document/classes/Document.md).[`rename`](../../../documents/document/classes/Document.md#rename)\n\n***\n\n### restore()\n\n> **restore**(): `Promise`\\<`void`\\>\n\nRestore a soft-deleted document.\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n#### Inherited from\n\n[`Document`](../../../documents/document/classes/Document.md).[`restore`](../../../documents/document/classes/Document.md#restore)\n\n***\n\n### save()\n\n> **save**(`options`): `Promise`\\<[`SaveDocumentResponseData`](../../../../../generated/storage/types.gen/type-aliases/SaveDocumentResponseData.md)\\>\n\nCommit uploaded content. Does not retry uncertain writes.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `options` | [`SaveDocumentRequest`](../../../../../generated/storage/types.gen/type-aliases/SaveDocumentRequest.md) |\n\n#### Returns\n\n`Promise`\\<[`SaveDocumentResponseData`](../../../../../generated/storage/types.gen/type-aliases/SaveDocumentResponseData.md)\\>\n\n#### Inherited from\n\n[`Document`](../../../documents/document/classes/Document.md).[`save`](../../../documents/document/classes/Document.md#save)\n\n***\n\n### setProperty()\n\n> **setProperty**(`property`, `value?`): `Promise`\\<`void`\\>\n\nSet a property value on this entity, or attach the property without a\nvalue when `value` is omitted.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `property` | [`PropertyDefinition`](../../../properties/property-definition/classes/PropertyDefinition.md) |\n| `value?` | [`SetPropertyValue`](../../../../../generated/properties/types.gen/type-aliases/SetPropertyValue.md) |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n#### Inherited from\n\n[`Document`](../../../documents/document/classes/Document.md).[`setProperty`](../../../documents/document/classes/Document.md#setproperty)\n\n***\n\n### setTeamShare()\n\n> **setTeamShare**(`shared`): `Promise`\\<`void`\\>\n\nShare the document with the owner's team, or unshare it.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `shared` | `boolean` |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n#### Inherited from\n\n[`Document`](../../../documents/document/classes/Document.md).[`setTeamShare`](../../../documents/document/classes/Document.md#setteamshare)\n\n***\n\n### sharePermissions()\n\n> **sharePermissions**(): `Promise`\\<[`SharePermissionV2`](../../../../../generated/storage/types.gen/type-aliases/SharePermissionV2.md)\\>\n\nSharing configuration.\n\n#### Returns\n\n`Promise`\\<[`SharePermissionV2`](../../../../../generated/storage/types.gen/type-aliases/SharePermissionV2.md)\\>\n\n#### Inherited from\n\n[`Document`](../../../documents/document/classes/Document.md).[`sharePermissions`](../../../documents/document/classes/Document.md#sharepermissions)\n\n***\n\n### shortId()\n\n> **shortId**(): `Promise`\\<`string`\\>\n\nThe document's short id (used in compact links and branch names).\n\n#### Returns\n\n`Promise`\\<`string`\\>\n\n#### Inherited from\n\n[`Document`](../../../documents/document/classes/Document.md).[`shortId`](../../../documents/document/classes/Document.md#shortid)\n\n***\n\n### simpleSave()\n\n> **simpleSave**(): `Promise`\\<[`SaveDocumentResponseData`](../../../../../generated/storage/types.gen/type-aliases/SaveDocumentResponseData.md)\\>\n\nCommit a simple document save.\n\n#### Returns\n\n`Promise`\\<[`SaveDocumentResponseData`](../../../../../generated/storage/types.gen/type-aliases/SaveDocumentResponseData.md)\\>\n\n#### Inherited from\n\n[`Document`](../../../documents/document/classes/Document.md).[`simpleSave`](../../../documents/document/classes/Document.md#simplesave)\n\n***\n\n### teamShare()\n\n> **teamShare**(): `Promise`\\<[`DocumentTeamShareResponse`](../../../../../generated/storage/types.gen/type-aliases/DocumentTeamShareResponse.md)\\>\n\nWhether the document is shared with the owner's team, and which team.\n\n#### Returns\n\n`Promise`\\<[`DocumentTeamShareResponse`](../../../../../generated/storage/types.gen/type-aliases/DocumentTeamShareResponse.md)\\>\n\n#### Inherited from\n\n[`Document`](../../../documents/document/classes/Document.md).[`teamShare`](../../../documents/document/classes/Document.md#teamshare)\n\n***\n\n### timelinePage()\n\n> **timelinePage**(`selection?`): `Promise`\\<\\{ `entries`: (\\{ `activity`: \\{ `action`: `string`; `actor`: [`User`](../../../users/user/classes/User.md); `actor_id`: `string`; `id`: `string`; `occurred_at`: `string`; `payload?`: `unknown`; \\}; `message?`: `undefined`; `type`: `\"activity\"`; \\} \\| \\{ `activity?`: `undefined`; `message`: [`Comment`](../../../documents/comment/classes/Comment.md); `type`: `\"message\"`; \\})[]; `nextCursor`: [`MessageCursor`](../../../../../generated/storage/types.gen/type-aliases/MessageCursor.md) \\| `undefined`; `previousCursor`: [`MessageCursor`](../../../../../generated/storage/types.gen/type-aliases/MessageCursor.md) \\| `undefined`; \\}\\>\n\nA mixed message and activity timeline page.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `selection?` | [`TimelineOptions`](../../../messages/thread/interfaces/TimelineOptions.md)\\<[`Comment`](../../../documents/comment/classes/Comment.md)\\> |\n\n#### Returns\n\n`Promise`\\<\\{ `entries`: (\\{ `activity`: \\{ `action`: `string`; `actor`: [`User`](../../../users/user/classes/User.md); `actor_id`: `string`; `id`: `string`; `occurred_at`: `string`; `payload?`: `unknown`; \\}; `message?`: `undefined`; `type`: `\"activity\"`; \\} \\| \\{ `activity?`: `undefined`; `message`: [`Comment`](../../../documents/comment/classes/Comment.md); `type`: `\"message\"`; \\})[]; `nextCursor`: [`MessageCursor`](../../../../../generated/storage/types.gen/type-aliases/MessageCursor.md) \\| `undefined`; `previousCursor`: [`MessageCursor`](../../../../../generated/storage/types.gen/type-aliases/MessageCursor.md) \\| `undefined`; \\}\\>\n\n#### Inherited from\n\n[`Document`](../../../documents/document/classes/Document.md).[`timelinePage`](../../../documents/document/classes/Document.md#timelinepage)\n\n***\n\n### toJSON()\n\n> **toJSON**(): \\{ `detail?`: [`DocumentMetadataWithContent`](../../../../../generated/storage/types.gen/type-aliases/DocumentMetadataWithContent.md); `id`: `string`; \\}\n\n#### Returns\n\n\\{ `detail?`: [`DocumentMetadataWithContent`](../../../../../generated/storage/types.gen/type-aliases/DocumentMetadataWithContent.md); `id`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `detail?` | [`DocumentMetadataWithContent`](../../../../../generated/storage/types.gen/type-aliases/DocumentMetadataWithContent.md) |\n| `id` | `string` |\n\n#### Inherited from\n\n[`Document`](../../../documents/document/classes/Document.md).[`toJSON`](../../../documents/document/classes/Document.md#tojson)\n\n***\n\n### toMention()\n\n> **toMention**(): [`MentionPart`](../../../../mentions/interfaces/MentionPart.md)\n\n#### Returns\n\n[`MentionPart`](../../../../mentions/interfaces/MentionPart.md)\n\n#### Inherited from\n\n[`Document`](../../../documents/document/classes/Document.md).[`toMention`](../../../documents/document/classes/Document.md#tomention)\n\n***\n\n### unfavorite()\n\n> **unfavorite**(): `Promise`\\<`Task`\\>\n\nRemove this entity from the user's favorites. Returns this handle for chaining.\n\n#### Returns\n\n`Promise`\\<`Task`\\>\n\n#### Inherited from\n\n[`Document`](../../../documents/document/classes/Document.md).[`unfavorite`](../../../documents/document/classes/Document.md#unfavorite)\n\n***\n\n### updatePropertyOptions()\n\n> **updatePropertyOptions**(`changes`): `Promise`\\<[`BulkUpdateEntityPropertyOptionsResponse`](../../../../../generated/properties/types.gen/type-aliases/BulkUpdateEntityPropertyOptionsResponse.md)\\>\n\nApply multi-select option deltas atomically across this entity's properties.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `changes` | [`PropertyOptionDelta`](../../../entity/interfaces/PropertyOptionDelta.md)[] |\n\n#### Returns\n\n`Promise`\\<[`BulkUpdateEntityPropertyOptionsResponse`](../../../../../generated/properties/types.gen/type-aliases/BulkUpdateEntityPropertyOptionsResponse.md)\\>\n\n#### Inherited from\n\n[`Document`](../../../documents/document/classes/Document.md).[`updatePropertyOptions`](../../../documents/document/classes/Document.md#updatepropertyoptions)\n\n***\n\n### version()\n\n> **version**(`version`): [`DocumentVersion`](../../../documents/version/classes/DocumentVersion.md)\n\nA handle to an immutable version.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `version` | `number` |\n\n#### Returns\n\n[`DocumentVersion`](../../../documents/version/classes/DocumentVersion.md)\n\n#### Inherited from\n\n[`Document`](../../../documents/document/classes/Document.md).[`version`](../../../documents/document/classes/Document.md#version)\n\n***\n\n### webUrl()\n\n> **webUrl**(): `string`\n\nThe task's URL in the Macro web app.\n\n#### Returns\n\n`string`\n\n#### Overrides\n\n[`Document`](../../../documents/document/classes/Document.md).[`webUrl`](../../../documents/document/classes/Document.md#weburl)\n\n***\n\n### byId()\n\n> `static` **byId**(`client`, `id`): `Task`\n\nA handle to a task by document id. Details load on first access.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `id` | `string` |\n\n#### Returns\n\n`Task`\n\n#### Overrides\n\n[`Document`](../../../documents/document/classes/Document.md).[`byId`](../../../documents/document/classes/Document.md#byid)\n\n***\n\n### create()\n\n> `static` **create**(`client`, `opts`): `Promise`\\<`Task`\\>\n\nCreate a task. `team` scopes the team task number and may be omitted\nwhen the creator belongs to exactly one team; `shareWithTeam` defaults\nto true.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `opts` | \\{ `markdown?`: `string`; `name`: `string`; `project?`: [`Project`](../../../projects/project/classes/Project.md); `shareWithTeam?`: `boolean`; `team?`: [`Team`](../../../teams/team/classes/Team.md); \\} |\n| `opts.markdown?` | `string` |\n| `opts.name` | `string` |\n| `opts.project?` | [`Project`](../../../projects/project/classes/Project.md) |\n| `opts.shareWithTeam?` | `boolean` |\n| `opts.team?` | [`Team`](../../../teams/team/classes/Team.md) |\n\n#### Returns\n\n`Promise`\\<`Task`\\>\n\n#### Overrides\n\n[`Document`](../../../documents/document/classes/Document.md).[`create`](../../../documents/document/classes/Document.md#create)\n\n***\n\n### createSkill()\n\n> `static` **createSkill**(`client`, `opts`): `Promise`\\<[`Document`](../../../documents/document/classes/Document.md)\\>\n\nCreate a skill: a markdown document containing instructions that AI reads\nand follows when the skill is referenced in an AI input.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `opts` | \\{ `markdown?`: `string`; `name`: `string`; `project?`: [`Project`](../../../projects/project/classes/Project.md); \\} |\n| `opts.markdown?` | `string` |\n| `opts.name` | `string` |\n| `opts.project?` | [`Project`](../../../projects/project/classes/Project.md) |\n\n#### Returns\n\n`Promise`\\<[`Document`](../../../documents/document/classes/Document.md)\\>\n\n#### Inherited from\n\n[`Document`](../../../documents/document/classes/Document.md).[`createSkill`](../../../documents/document/classes/Document.md#createskill)\n\n***\n\n### createSnippet()\n\n> `static` **createSnippet**(`client`, `opts`): `Promise`\\<[`Document`](../../../documents/document/classes/Document.md)\\>\n\nCreate a snippet: a reusable markdown document that can be inserted into\nany markdown area.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `opts` | \\{ `markdown?`: `string`; `name`: `string`; `project?`: [`Project`](../../../projects/project/classes/Project.md); \\} |\n| `opts.markdown?` | `string` |\n| `opts.name` | `string` |\n| `opts.project?` | [`Project`](../../../projects/project/classes/Project.md) |\n\n#### Returns\n\n`Promise`\\<[`Document`](../../../documents/document/classes/Document.md)\\>\n\n#### Inherited from\n\n[`Document`](../../../documents/document/classes/Document.md).[`createSnippet`](../../../documents/document/classes/Document.md#createsnippet)\n\n***\n\n### forPullRequest()\n\n> `static` **forPullRequest**(`client`, `url`): `Promise`\\<`Task`[]\\>\n\nThe tasks the GitHub pull request at `url` references (as `MACRO-<id>` in\nits text, branch, or comments), oldest link first. Empty when the caller\ncannot see the pull request; tasks the caller cannot open still appear.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `url` | `string` |\n\n#### Returns\n\n`Promise`\\<`Task`[]\\>\n\n***\n\n### recent()\n\n> `static` **recent**(`client`, `opts?`): `AsyncGenerator`\\<[`Document`](../../../documents/document/classes/Document.md)\\>\n\nThe user's recent documents, most recent first, auto-paginated.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `opts?` | \\{ `fileType?`: `string`; `pageSize?`: `number`; \\} |\n| `opts.fileType?` | `string` |\n| `opts.pageSize?` | `number` |\n\n#### Returns\n\n`AsyncGenerator`\\<[`Document`](../../../documents/document/classes/Document.md)\\>\n\n#### Inherited from\n\n[`Document`](../../../documents/document/classes/Document.md).[`recent`](../../../documents/document/classes/Document.md#recent)\n\n***\n\n### recentlyDeleted()\n\n> `static` **recentlyDeleted**(`client`): `Promise`\\<[`Document`](../../../documents/document/classes/Document.md)[]\\>\n\nThe user's recently soft-deleted documents. The underlying endpoint also\nreturns deleted chats and projects; those are filtered out here.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n\n#### Returns\n\n`Promise`\\<[`Document`](../../../documents/document/classes/Document.md)[]\\>\n\n#### Inherited from\n\n[`Document`](../../../documents/document/classes/Document.md).[`recentlyDeleted`](../../../documents/document/classes/Document.md#recentlydeleted)\n"
},
{
"name": "teams",
@@ -177,6 +177,6 @@
"name": "core",
"description": "SDK construction, entity handles, lazy fields, search options, events and shared types.",
"overview": "<!-- src/config/interfaces/MacroOpts.md -->\n# Interface: MacroOpts\n\nOptions passed to `new Macro(opts)` and stored on `MacroClient`.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-auth\"></a> `auth?` | [`MacroAuth`](../type-aliases/MacroAuth.md) | How to authenticate. Takes precedence over `token`. Falls back to `MACRO_API_KEY` (a user API key or bearer token) or `MACRO_BOT_TOKEN` (bot). |\n| <a id=\"property-env\"></a> `env?` | [`Env`](../type-aliases/Env.md) | Which Macro environment to talk to. Falls back to the MACRO_ENV env var, then `'prod'`. |\n| <a id=\"property-hosts\"></a> `hosts?` | `Partial`\\<`Record`\\<[`ServiceName`](../type-aliases/ServiceName.md), `string`\\>\\> | Override individual service hosts (e.g. point one at localhost). |\n| <a id=\"property-onrequest\"></a> `onRequest?` | (`event`) => `void` | Optional generated API operation events; excludes arguments, URLs and response data. |\n| <a id=\"property-requestedas\"></a> `requestedAs?` | `string` | User id the bot acts for, sent as `x-macro-bot-for-macro-user-id` on every request. Bot auth only. Set via `macro.requestedAs(user)` rather than directly. |\n| <a id=\"property-token\"></a> `token?` | [`TokenSource`](../type-aliases/TokenSource.md) | Shorthand for `auth: { type: 'user', token }`. Accepts a Settings API key (`mak_…`) or a bearer token. |\n| <a id=\"property-webappurl\"></a> `webAppUrl?` | `string` | Override the web app base URL (e.g. for local frontend dev). Also reads MACRO_WEB_URL. |\n| <a id=\"property-webhooksecret\"></a> `webhookSecret?` | `string` | Signing secret for verifying incoming persisted-webhook deliveries. Required only for `macro.events.webhook()` / `macro.events.handle()`. SSE via `macro.events.listen()` uses the API token and does not need this. Falls back to MACRO_WEBHOOK_SECRET. |\n| <a id=\"property-wsverify\"></a> `wsVerify?` | `string` | - |\n\n\n<!-- src/config/type-aliases/BotScope.md -->\n# Type Alias: BotScope\n\n> **BotScope** = `\"user\"` \\| `\"team\"`\n\nAccess scope for bot-authenticated requests. `user` acts with the\nrequested-as user's access (requires `requestedAs`); `team` acts with the\nbot's owning team's access (team-owned bots only).\n\n\n<!-- src/config/type-aliases/Env.md -->\n# Type Alias: Env\n\n> **Env** = `\"dev\"` \\| `\"prod\"` \\| `\"local\"`\n\n\n<!-- src/config/type-aliases/MacroAuth.md -->\n# Type Alias: MacroAuth\n\n> **MacroAuth** = \\{ `apiKey?`: `never`; `token`: [`TokenSource`](TokenSource.md); `type`: `\"user\"`; \\} \\| \\{ `apiKey`: `string`; `token?`: `never`; `type`: `\"user\"`; \\} \\| \\{ `scope?`: [`BotScope`](BotScope.md); `token`: [`TokenSource`](TokenSource.md); `type`: `\"bot\"`; \\}\n\nHow the SDK authenticates with Macro.\n\nA user has exactly one of two credential fields.\n\n- `token`: a bearer token, or a `mak_` API key. The SDK picks the header\n from the prefix at send time.\n- `apiKey`: a Settings → API Keys key, always sent as\n `x-macro-user-api-key`. Not prefix-checked, so keys that predate the\n `mak_` prefix work here.\n\nA bot uses an `mbot_` token as `x-macro-bot-token` plus\n`x-macro-bot-scope`, defaulting to `user` when `requestedAs` is set and\n`team` otherwise.\n\n\n<!-- src/config/type-aliases/ServiceName.md -->\n# Type Alias: ServiceName\n\n> **ServiceName** = `\"agent-harness\"` \\| `\"storage\"` \\| `\"auth\"` \\| `\"email\"` \\| `\"calendar\"` \\| `\"cognition\"` \\| `\"notification\"` \\| `\"properties\"` \\| `\"search\"` \\| `\"scheduled-action\"` \\| `\"static-files\"` \\| `\"connection\"` \\| `\"contacts\"` \\| `\"unfurl\"`\n\nThe backend services the SDK talks to. Note `search` and `properties` are\nserved on the storage host, so they point there.\n\n\n<!-- src/config/type-aliases/TokenSource.md -->\n# Type Alias: TokenSource\n\n> **TokenSource** = `string` \\| (() => `string` \\| `Promise`\\<`string`\\>)\n\nA credential string, or a (possibly async) function that returns one.\n\n\n<!-- src/config/variables/HOSTS.md -->\n# Variable: HOSTS\n\n> `const` **HOSTS**: `Record`\\<[`Env`](../type-aliases/Env.md), `Record`\\<[`ServiceName`](../type-aliases/ServiceName.md), `string`\\>\\>\n\n\n<!-- src/config/variables/WEB_APP_URLS.md -->\n# Variable: WEB\\_APP\\_URLS\n\n> `const` **WEB\\_APP\\_URLS**: `Record`\\<[`Env`](../type-aliases/Env.md), `string`\\>\n\n\n<!-- src/macro/classes/Macro.md -->\n# Class: Macro\\<T\\>\n\n## Type Parameters\n\n| Type Parameter | Default type |\n| ------ | ------ |\n| <a id=\"type-parameter-t\"></a> `T` *extends* [`MacroOpts`](../../config/interfaces/MacroOpts.md) | [`MacroOpts`](../../config/interfaces/MacroOpts.md) |\n\n## Constructors\n\n### Constructor\n\n> **new Macro**\\<`T`\\>(`opts`): `Macro`\\<`T`\\>\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `opts` | `T` |\n\n#### Returns\n\n`Macro`\\<`T`\\>\n\n## Properties\n\n| Property | Modifier | Type | Description |\n| ------ | ------ | ------ | ------ |\n| <a id=\"property-_client\"></a> `_client` | `readonly` | `MacroClient` | Direct access to the underlying hey-api service clients. |\n| <a id=\"property-agents\"></a> `agents` | `readonly` | [`AgentNamespace`](../../entities/agents/namespace/classes/AgentNamespace.md) | agents resources and operations. |\n| <a id=\"property-agentsessions\"></a> `agentSessions` | `readonly` | [`AgentSessionNamespace`](../../entities/agent-sessions/namespace/classes/AgentSessionNamespace.md) | - |\n| <a id=\"property-ai\"></a> `ai` | `readonly` | [`AiNamespace`](../../entities/ai/namespace/classes/AiNamespace.md) | - |\n| <a id=\"property-apikeys\"></a> `apiKeys` | `readonly` | [`ApiKeyNamespace`](../../entities/api-keys/namespace/classes/ApiKeyNamespace.md) | apiKeys resources and operations. |\n| <a id=\"property-bots\"></a> `bots` | `readonly` | [`BotsNamespace`](../../entities/bots/namespace/classes/BotsNamespace.md) | - |\n| <a id=\"property-calendar\"></a> `calendar` | `readonly` | [`CalendarNamespace`](../../entities/calendar/namespace/classes/CalendarNamespace.md) | - |\n| <a id=\"property-calls\"></a> `calls` | `readonly` | [`CallRecordNamespace`](../../entities/calls/namespace/classes/CallRecordNamespace.md) | - |\n| <a id=\"property-channels\"></a> `channels` | `readonly` | [`ChannelNamespace`](../../entities/channels/namespace/classes/ChannelNamespace.md) | - |\n| <a id=\"property-crm\"></a> `crm` | `readonly` | [`CrmNamespace`](../../entities/crm/namespace/classes/CrmNamespace.md) | - |\n| <a id=\"property-databases\"></a> `databases` | `readonly` | [`DatabaseNamespace`](../../entities/databases/namespace/classes/DatabaseNamespace.md) | - |\n| <a id=\"property-documents\"></a> `documents` | `readonly` | [`DocumentNamespace`](../../entities/documents/namespace/classes/DocumentNamespace.md) | - |\n| <a id=\"property-email\"></a> `email` | `readonly` | [`EmailNamespace`](../../entities/email/namespace/classes/EmailNamespace.md) | - |\n| <a id=\"property-entitymentions\"></a> `entityMentions` | `readonly` | [`EntityMentionNamespace`](../../entities/entity-mentions/namespace/classes/EntityMentionNamespace.md) | entityMentions resources and operations. |\n| <a id=\"property-events\"></a> `events` | `readonly` | [`MacroEvents`](../../events/receiver/classes/MacroEvents.md) | - |\n| <a id=\"property-favorites\"></a> `favorites` | `readonly` | [`FavoritesNamespace`](../../entities/favorites/namespace/classes/FavoritesNamespace.md) | - |\n| <a id=\"property-foreignentities\"></a> `foreignEntities` | `readonly` | [`ForeignEntityNamespace`](../../entities/foreign/namespace/classes/ForeignEntityNamespace.md) | - |\n| <a id=\"property-forms\"></a> `forms` | `readonly` | [`FormNamespace`](../../entities/forms/namespace/classes/FormNamespace.md) | Build forms and submit answers without granting respondents database access. |\n| <a id=\"property-githubpullrequests\"></a> `githubPullRequests` | `readonly` | [`GithubPullRequestNamespace`](../../entities/github-pull-requests/namespace/classes/GithubPullRequestNamespace.md) | githubPullRequests resources and operations. |\n| <a id=\"property-harnesses\"></a> `harnesses` | `readonly` | [`HarnessNamespace`](../../entities/harnesses/namespace/classes/HarnessNamespace.md) | harnesses resources and operations. |\n| <a id=\"property-initiatives\"></a> `initiatives` | `readonly` | [`InitiativeNamespace`](../../entities/initiatives/namespace/classes/InitiativeNamespace.md) | initiatives resources and operations. |\n| <a id=\"property-meetings\"></a> `meetings` | `readonly` | [`MeetingNamespace`](../../entities/meetings/namespace/classes/MeetingNamespace.md) | meetings resources and operations. |\n| <a id=\"property-notifications\"></a> `notifications` | `readonly` | [`NotificationNamespace`](../../entities/notifications/namespace/classes/NotificationNamespace.md) | - |\n| <a id=\"property-pins\"></a> `pins` | `readonly` | [`PinsNamespace`](../../entities/pins/namespace/classes/PinsNamespace.md) | - |\n| <a id=\"property-projects\"></a> `projects` | `readonly` | [`ProjectNamespace`](../../entities/projects/namespace/classes/ProjectNamespace.md) | - |\n| <a id=\"property-properties\"></a> `properties` | `readonly` | [`PropertiesNamespace`](../../entities/properties/namespace/classes/PropertiesNamespace.md) | - |\n| <a id=\"property-routines\"></a> `routines` | `readonly` | [`RoutineNamespace`](../../entities/routines/namespace/classes/RoutineNamespace.md) | routines resources and operations. |\n| <a id=\"property-tasks\"></a> `tasks` | `readonly` | [`TaskNamespace`](../../entities/tasks/namespace/classes/TaskNamespace.md) | - |\n| <a id=\"property-teams\"></a> `teams` | `readonly` | [`TeamNamespace`](../../entities/teams/namespace/classes/TeamNamespace.md) | - |\n| <a id=\"property-unfurls\"></a> `unfurls` | `readonly` | [`UnfurlNamespace`](../../entities/unfurls/namespace/classes/UnfurlNamespace.md) | unfurls resources and operations. |\n| <a id=\"property-users\"></a> `users` | `readonly` | [`UserNamespace`](../../entities/users/namespace/classes/UserNamespace.md) | - |\n| <a id=\"property-webappurl\"></a> `webAppUrl` | `readonly` | `string` | Base URL of the Macro web app, used to build entity URLs. |\n| <a id=\"property-webhooks\"></a> `webhooks` | `readonly` | [`WebhooksNamespace`](../../entities/webhooks/namespace/classes/WebhooksNamespace.md) | - |\n\n## Methods\n\n### myPrincipalId()\n\n> **myPrincipalId**(): `Promise`\\<`string`\\>\n\nThe authenticated caller's mentionable principal — `bot|<uuid>` for bot\nauth, `macro|<email>` for user auth — fetched once and cached.\n\n#### Returns\n\n`Promise`\\<`string`\\>\n\n***\n\n### requestedAs()\n\n> **requestedAs**(`user`): `Macro`\\<`T`\\>\n\nClone of this SDK acting on behalf of `user` (sent as\n`x-macro-bot-for-macro-user-id`). Bot auth only — throws for user auth,\nsince a user token always acts as its own user.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `user` | [`User`](../../entities/users/user/classes/User.md) |\n\n#### Returns\n\n`Macro`\\<`T`\\>\n\n\n<!-- src/macro/type-aliases/RequestActivity.md -->\n# Type Alias: RequestActivity\n\n> **RequestActivity** = \\{ `id`: `number`; `operation`: `string`; `service`: `string`; `status`: `\"started\"` \\| `\"completed\"` \\| `\"failed\"`; \\}\n\nA generated SDK operation lifecycle. Contains no arguments, URLs or response data.\n\n## Properties\n\n| Property | Type |\n| ------ | ------ |\n| <a id=\"property-id\"></a> `id` | `number` |\n| <a id=\"property-operation\"></a> `operation` | `string` |\n| <a id=\"property-service\"></a> `service` | `string` |\n| <a id=\"property-status\"></a> `status` | `\"started\"` \\| `\"completed\"` \\| `\"failed\"` |\n",
- "documentation": "# Macro SDK: core\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/properties/types.gen/type-aliases/BulkUpdateEntityPropertyOptionsResponse.md -->\n# Type Alias: BulkUpdateEntityPropertyOptionsResponse\n\n> **BulkUpdateEntityPropertyOptionsResponse** = \\{ `properties`: [`EntityPropertyOptionSelectionResponse`](EntityPropertyOptionSelectionResponse.md)[]; \\}\n\nResponse for a bulk option update: each property's reconciled final ids.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-properties\"></a> `properties` | [`EntityPropertyOptionSelectionResponse`](EntityPropertyOptionSelectionResponse.md)[] | The final option ids per updated property. |\n\n\n<!-- generated/properties/types.gen/type-aliases/DataType.md -->\n# Type Alias: DataType\n\n> **DataType** = `\"BOOLEAN\"` \\| `\"DATE\"` \\| `\"NUMBER\"` \\| `\"STRING\"` \\| `\"SELECT_NUMBER\"` \\| `\"SELECT_STRING\"` \\| `\"TAG\"` \\| `\"ENTITY\"` \\| `\"LINK\"`\n\nData type for property values, determining storage and validation.\n\n\n<!-- generated/properties/types.gen/type-aliases/EntityProperty.md -->\n# Type Alias: EntityProperty\n\n> **EntityProperty** = \\{ `created_at`: `string`; `entity_id`: `string`; `entity_type`: [`EntityType`](EntityType.md); `id`: `string`; `property_definition_id`: `string`; `updated_at`: `string`; \\}\n\nAssignment of a property definition to a specific entity (service representation).\n\n## Properties\n\n| Property | Type |\n| ------ | ------ |\n| <a id=\"property-created_at\"></a> `created_at` | `string` |\n| <a id=\"property-entity_id\"></a> `entity_id` | `string` |\n| <a id=\"property-entity_type\"></a> `entity_type` | [`EntityType`](EntityType.md) |\n| <a id=\"property-id\"></a> `id` | `string` |\n| <a id=\"property-property_definition_id\"></a> `property_definition_id` | `string` |\n| <a id=\"property-updated_at\"></a> `updated_at` | `string` |\n\n\n<!-- generated/properties/types.gen/type-aliases/EntityPropertyOptionSelectionResponse.md -->\n# Type Alias: EntityPropertyOptionSelectionResponse\n\n> **EntityPropertyOptionSelectionResponse** = \\{ `option_ids`: `string`[]; `property_id`: `string`; \\}\n\nThe reconciled final option ids stored for one property after a bulk update.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-option_ids\"></a> `option_ids` | `string`[] | The final option ids the server persisted, in stored order. |\n| <a id=\"property-property_id\"></a> `property_id` | `string` | The property definition the options belong to. |\n\n\n<!-- generated/properties/types.gen/type-aliases/EntityPropertyWithDefinition.md -->\n# Type Alias: EntityPropertyWithDefinition\n\n> **EntityPropertyWithDefinition** = \\{ `definition`: [`PropertyDefinition`](PropertyDefinition.md); `options?`: [`PropertyOption`](PropertyOption.md)[] \\| `null`; `property`: [`EntityProperty`](EntityProperty.md); `value?`: `null` \\| [`PropertyValue`](PropertyValue.md); \\}\n\nEntity property with its definition, value, and options (service representation).\n\n## Properties\n\n| Property | Type |\n| ------ | ------ |\n| <a id=\"property-definition\"></a> `definition` | [`PropertyDefinition`](PropertyDefinition.md) |\n| <a id=\"property-options\"></a> `options?` | [`PropertyOption`](PropertyOption.md)[] \\| `null` |\n| <a id=\"property-property\"></a> `property` | [`EntityProperty`](EntityProperty.md) |\n| <a id=\"property-value\"></a> `value?` | `null` \\| [`PropertyValue`](PropertyValue.md) |\n\n\n<!-- generated/properties/types.gen/type-aliases/EntityReference.md -->\n# Type Alias: EntityReference\n\n> **EntityReference** = \\{ `entity_id`: `string`; `entity_type`: [`EntityType`](EntityType.md); `specific_message_id?`: `string` \\| `null`; \\}\n\nEntity reference for entity-type property values.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-entity_id\"></a> `entity_id` | `string` | - |\n| <a id=\"property-entity_type\"></a> `entity_type` | [`EntityType`](EntityType.md) | - |\n| <a id=\"property-specific_message_id\"></a> `specific_message_id?` | `string` \\| `null` | For CHANNEL, CHAT, THREAD entity types - optional specific message ID. This allows referencing a specific message within a thread/channel/chat. |\n\n\n<!-- generated/properties/types.gen/type-aliases/EntityType.md -->\n# Type Alias: EntityType\n\n> **EntityType** = `\"CALENDAR_EVENT\"` \\| `\"CALL_RECORD\"` \\| `\"CHANNEL\"` \\| `\"CHAT\"` \\| `\"COMPANY\"` \\| `\"DATABASE_ROW\"` \\| `\"CONTACT\"` \\| `\"DOCUMENT\"` \\| `\"INITIATIVE\"` \\| `\"PROJECT\"` \\| `\"TASK\"` \\| `\"THREAD\"` \\| `\"USER\"`\n\nType of entity that can be referenced by entity properties.\n\n\n<!-- generated/properties/types.gen/type-aliases/PropertyDefinition.md -->\n# Type Alias: PropertyDefinition\n\n> **PropertyDefinition** = \\{ `created_at`: `string`; `data_type`: [`DataType`](DataType.md); `display_name`: `string`; `id`: `string`; `is_metadata`: `boolean`; `is_multi_select`: `boolean`; `is_system`: `boolean`; `owner`: [`PropertyOwner`](PropertyOwner.md); `specific_entity_type`: `null` \\| [`EntityType`](EntityType.md); `updated_at`: `string`; \\}\n\nProperty definition model (service representation).\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-created_at\"></a> `created_at` | `string` | - |\n| <a id=\"property-data_type\"></a> `data_type` | [`DataType`](DataType.md) | - |\n| <a id=\"property-display_name\"></a> `display_name` | `string` | - |\n| <a id=\"property-id\"></a> `id` | `string` | - |\n| <a id=\"property-is_metadata\"></a> `is_metadata` | `boolean` | Flag to indicate if this is a system-generated metadata property. Not stored in database - computed at service layer. |\n| <a id=\"property-is_multi_select\"></a> `is_multi_select` | `boolean` | - |\n| <a id=\"property-is_system\"></a> `is_system` | `boolean` | Flag to indicate if this is a system property (stored in DB). |\n| <a id=\"property-owner\"></a> `owner` | [`PropertyOwner`](PropertyOwner.md) | - |\n| <a id=\"property-specific_entity_type\"></a> `specific_entity_type` | `null` \\| [`EntityType`](EntityType.md) | - |\n| <a id=\"property-updated_at\"></a> `updated_at` | `string` | - |\n\n\n<!-- generated/properties/types.gen/type-aliases/PropertyOption.md -->\n# Type Alias: PropertyOption\n\n> **PropertyOption** = \\{ `color`: `string` \\| `null`; `created_at`: `string`; `display_order`: `number`; `id`: `string`; `property_definition_id`: `string`; `updated_at`: `string`; `value`: [`PropertyOptionValue`](PropertyOptionValue.md); \\}\n\nA selectable option for select-type properties (service representation).\n\n## Properties\n\n| Property | Type |\n| ------ | ------ |\n| <a id=\"property-color\"></a> `color` | `string` \\| `null` |\n| <a id=\"property-created_at\"></a> `created_at` | `string` |\n| <a id=\"property-display_order\"></a> `display_order` | `number` |\n| <a id=\"property-id\"></a> `id` | `string` |\n| <a id=\"property-property_definition_id\"></a> `property_definition_id` | `string` |\n| <a id=\"property-updated_at\"></a> `updated_at` | `string` |\n| <a id=\"property-value\"></a> `value` | [`PropertyOptionValue`](PropertyOptionValue.md) |\n\n\n<!-- generated/properties/types.gen/type-aliases/PropertyOptionValue.md -->\n# Type Alias: PropertyOptionValue\n\n> **PropertyOptionValue** = \\{ `type`: `\"string\"`; `value`: `string`; \\} \\| \\{ `type`: `\"number\"`; `value`: `number`; \\}\n\nThe value of a property option - either a string or a number.\n\n## Union Members\n\n### Type Literal\n\n\\{ `type`: `\"string\"`; `value`: `string`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `type` | `\"string\"` | - |\n| `value` | `string` | String value for SelectString properties |\n\n***\n\n### Type Literal\n\n\\{ `type`: `\"number\"`; `value`: `number`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `type` | `\"number\"` | - |\n| `value` | `number` | Number value for SelectNumber properties |\n\n\n<!-- generated/properties/types.gen/type-aliases/PropertyOwner.md -->\n# Type Alias: PropertyOwner\n\n> **PropertyOwner** = \\{ `scope`: `\"user\"`; `user_id`: `string`; \\} \\| \\{ `scope`: `\"team\"`; `team_id`: `string`; \\} \\| \\{ `database_id`: `string`; `scope`: `\"database\"`; \\} \\| \\{ `scope`: `\"system\"`; \\}\n\nDefines who owns a property - user-scoped, team-scoped, database-scoped, or system.\n\n\n<!-- generated/properties/types.gen/type-aliases/PropertyTargetEntityType.md -->\n# Type Alias: PropertyTargetEntityType\n\n> **PropertyTargetEntityType** = `\"CALL_RECORD\"` \\| `\"CHANNEL\"` \\| `\"CHAT\"` \\| `\"COMPANY\"` \\| `\"DATABASE_ROW\"` \\| `\"DOCUMENT\"` \\| `\"INITIATIVE\"` \\| `\"PROJECT\"` \\| `\"THREAD\"` \\| `\"USER\"`\n\nCanonical type of an entity receiving properties.\n\nTasks are documents at API boundaries. `Task` intentionally does not exist\nhere; task classification is resolved by the properties domain from the\ndocument subtype.\n\n\n<!-- generated/properties/types.gen/type-aliases/PropertyTargetReference.md -->\n# Type Alias: PropertyTargetReference\n\n> **PropertyTargetReference** = \\{ `entity_id`: `string`; `entity_type`: [`PropertyTargetEntityType`](PropertyTargetEntityType.md); \\}\n\nCanonical reference to an entity receiving properties.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-entity_id\"></a> `entity_id` | `string` | Entity identifier. |\n| <a id=\"property-entity_type\"></a> `entity_type` | [`PropertyTargetEntityType`](PropertyTargetEntityType.md) | Canonical entity type. |\n\n\n<!-- generated/properties/types.gen/type-aliases/PropertyValue.md -->\n# Type Alias: PropertyValue\n\n> **PropertyValue** = \\{ `type`: `\"Boolean\"`; `value`: `boolean`; \\} \\| \\{ `type`: `\"Number\"`; `value`: `number`; \\} \\| \\{ `type`: `\"String\"`; `value`: `string`; \\} \\| \\{ `type`: `\"Date\"`; `value`: `string`; \\} \\| \\{ `type`: `\"SelectOption\"`; `value`: `string`[]; \\} \\| \\{ `type`: `\"EntityReference\"`; `value`: [`EntityReference`](EntityReference.md)[]; \\} \\| \\{ `type`: `\"Link\"`; `value`: `string`[]; \\}\n\nProperty value (service representation).\n\nRepresents the actual value stored for an entity property.\nThis is serialized to/from JSONB in the database.\n\n## Union Members\n\n### Type Literal\n\n\\{ `type`: `\"Boolean\"`; `value`: `boolean`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `type` | `\"Boolean\"` | - |\n| `value` | `boolean` | Boolean value Serializes as: {\"type\": \"Boolean\", \"value\": true} |\n\n***\n\n### Type Literal\n\n\\{ `type`: `\"Number\"`; `value`: `number`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `type` | `\"Number\"` | - |\n| `value` | `number` | Numeric value Serializes as: {\"type\": \"Number\", \"value\": 42.5} |\n\n***\n\n### Type Literal\n\n\\{ `type`: `\"String\"`; `value`: `string`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `type` | `\"String\"` | - |\n| `value` | `string` | String value Serializes as: {\"type\": \"String\", \"value\": \"text\"} |\n\n***\n\n### Type Literal\n\n\\{ `type`: `\"Date\"`; `value`: `string`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `type` | `\"Date\"` | - |\n| `value` | `string` | Date/timestamp value Serializes as: {\"type\": \"Date\", \"value\": \"2025-01-01T00:00:00Z\"} |\n\n***\n\n### Type Literal\n\n\\{ `type`: `\"SelectOption\"`; `value`: `string`[]; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `type` | `\"SelectOption\"` | - |\n| `value` | `string`[] | Select option(s) - always an array (check is_multi_select to determine if single or multi) Single-select: {\"type\": \"SelectOption\", \"value\": [\"uuid\"]} (length 0 or 1) Multi-select: {\"type\": \"SelectOption\", \"value\": [\"uuid1\", \"uuid2\", ...]} (length 0+) |\n\n***\n\n### Type Literal\n\n\\{ `type`: `\"EntityReference\"`; `value`: [`EntityReference`](EntityReference.md)[]; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `type` | `\"EntityReference\"` | - |\n| `value` | [`EntityReference`](EntityReference.md)[] | Entity reference(s) - always an array (check is_multi_select to determine if single or multi) Single-select: {\"type\": \"EntityReference\", \"value\": [{...}]} (length 0 or 1) Multi-select: {\"type\": \"EntityReference\", \"value\": [{...}, {...}, ...]} (length 0+) |\n\n***\n\n### Type Literal\n\n\\{ `type`: `\"Link\"`; `value`: `string`[]; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `type` | `\"Link\"` | - |\n| `value` | `string`[] | Link value(s) - always an array (check is_multi_select to determine if single or multi) Single-select: {\"type\": \"Link\", \"value\": [\"https://example.com\"]} (length 0 or 1) Multi-select: {\"type\": \"Link\", \"value\": [\"https://example.com\", \"https://other.com\"]} (length 0+) |\n\n\n<!-- generated/properties/types.gen/type-aliases/SetPropertyValue.md -->\n# Type Alias: SetPropertyValue\n\n> **SetPropertyValue** = \\{ `type`: `\"boolean\"`; `value`: `boolean`; \\} \\| \\{ `type`: `\"date\"`; `value`: `string`; \\} \\| \\{ `type`: `\"number\"`; `value`: `number`; \\} \\| \\{ `type`: `\"string\"`; `value`: `string`; \\} \\| \\{ `option_id`: `string`; `type`: `\"select_option\"`; \\} \\| \\{ `option_ids`: `string`[]; `type`: `\"multi_select_option\"`; \\} \\| \\{ `reference`: [`EntityReference`](EntityReference.md); `type`: `\"entity_reference\"`; \\} \\| \\{ `references`: [`EntityReference`](EntityReference.md)[]; `type`: `\"multi_entity_reference\"`; \\} \\| \\{ `type`: `\"link\"`; `url`: `string`; \\} \\| \\{ `type`: `\"multi_link\"`; `urls`: `string`[]; \\}\n\nType-safe enum for setting entity property values - provides compile-time validation.\n\n\n<!-- generated/search/types.gen/type-aliases/AgentSessionFilters.md -->\n# Type Alias: AgentSessionFilters\n\n> **AgentSessionFilters** = \\{ `ids?`: `string`[]; `include?`: `boolean`; `owners?`: `string`[]; \\}\n\nFilters for agent sessions.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-ids\"></a> `ids?` | `string`[] | Agent session ids to filter by. Empty to include all accessible sessions. |\n| <a id=\"property-include\"></a> `include?` | `boolean` | Opt this query into agent sessions at all. Agent sessions are off by default — see [`crate::ast::agent_session::AgentSessionLiteral::Include`]. Asking for specific `ids` or `owners` also opts in. |\n| <a id=\"property-owners\"></a> `owners?` | `string`[] | Filter by session owner principal — a user ('macro\\|[email protected]'), a bot ('bot\\|<uuid>'), or a team (a bare hyphenated uuid). Empty to include every owner. |\n\n\n<!-- generated/search/types.gen/type-aliases/CalendarEventFilters.md -->\n# Type Alias: CalendarEventFilters\n\n> **CalendarEventFilters** = \\{ `attendees?`: `string`[]; `calendar_event_ids?`: `string`[]; `ends_after?`: `string` \\| `null`; `organizers?`: `string`[]; `starts_before?`: `string` \\| `null`; `statuses?`: `string`[]; \\}\n\nFilters for canonical calendar-event entities.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-attendees\"></a> `attendees?` | `string`[] | Attendee email addresses. |\n| <a id=\"property-calendar_event_ids\"></a> `calendar_event_ids?` | `string`[] | Canonical event ids. |\n| <a id=\"property-ends_after\"></a> `ends_after?` | `string` \\| `null` | Include master events ending after this instant. |\n| <a id=\"property-organizers\"></a> `organizers?` | `string`[] | Organizer email addresses. |\n| <a id=\"property-starts_before\"></a> `starts_before?` | `string` \\| `null` | Include master events starting before this instant. |\n| <a id=\"property-statuses\"></a> `statuses?` | `string`[] | Event statuses such as `confirmed`, `tentative`, or `cancelled`. |\n\n\n<!-- generated/search/types.gen/type-aliases/CallFilters.md -->\n# Type Alias: CallFilters\n\n> **CallFilters** = \\{ `attended?`: `boolean` \\| `null`; `call_ids?`: `string`[]; `channel_ids?`: `string`[]; `speaker_ids?`: `string`[]; `status?`: `null` \\| [`CallStatus`](CallStatus.md); \\}\n\nFilters for call records.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-attended\"></a> `attended?` | `boolean` \\| `null` | Legacy filter by whether the requesting user attended the call. Prefer [`CallFilters::status`] for new callers. `None` = no filter, `Some(true)` = only calls the user joined, `Some(false)` = only calls the user did not join. |\n| <a id=\"property-call_ids\"></a> `call_ids?` | `string`[] | Call record IDs to filter by. Empty to include all calls. |\n| <a id=\"property-channel_ids\"></a> `channel_ids?` | `string`[] | Channel IDs to filter calls by. Empty to include all calls. |\n| <a id=\"property-speaker_ids\"></a> `speaker_ids?` | `string`[] | Speaker macro user ids. Empty to include all. |\n| <a id=\"property-status\"></a> `status?` | `null` \\| [`CallStatus`](CallStatus.md) | - |\n\n\n<!-- generated/search/types.gen/type-aliases/CallStatus.md -->\n# Type Alias: CallStatus\n\n> **CallStatus** = `\"ATTENDED\"` \\| `\"MISSED\"` \\| `\"UNATTENDED\"`\n\nViewer-relative attendance status for a call record.\nSerializes as `ATTENDED`, `MISSED`, or `UNATTENDED`.\n\n\n<!-- generated/search/types.gen/type-aliases/ChannelFilters.md -->\n# Type Alias: ChannelFilters\n\n> **ChannelFilters** = \\{ `channel_ids?`: `string`[]; `channel_types?`: `string`[]; `importance?`: `boolean` \\| `null`; `is_participant?`: `boolean` \\| `null`; `mentions?`: `string`[]; `notification_filters?`: [`NotificationFilters`](NotificationFilters.md); `org_id?`: `number` \\| `null`; `sender_ids?`: `string`[]; `team_id?`: `string` \\| `null`; `thread_ids?`: `string`[]; \\}\n\nThe channel message filters used to filter down what channel messages you search over.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-channel_ids\"></a> `channel_ids?` | `string`[] | Channel IDs to search within. Examples: ['general']. Empty to search all accessible channels. |\n| <a id=\"property-channel_types\"></a> `channel_types?` | `string`[] | Channel types to filter by. Examples: ['public'], ['direct_message', 'private']. Empty to search all channel types. |\n| <a id=\"property-importance\"></a> `importance?` | `boolean` \\| `null` | Filter by channel importance. None to ignore, true to pass through (no clause), false to short-circuit and return nothing. |\n| <a id=\"property-is_participant\"></a> `is_participant?` | `boolean` \\| `null` | Filter by whether the requesting user is an active participant of the channel. Presence of this filter also widens the candidate set to team channels of the user's teams that they have not joined, so `false` matches those channels. None to ignore (participant channels only, today's default). |\n| <a id=\"property-mentions\"></a> `mentions?` | `string`[] | Channel user mentions to search for. Examples: ['@username']. Empty if not filtering by mentions. |\n| <a id=\"property-notification_filters\"></a> `notification_filters?` | [`NotificationFilters`](NotificationFilters.md) | Filter by channel notification state. |\n| <a id=\"property-org_id\"></a> `org_id?` | `number` \\| `null` | Channel organization ID to search within. Empty to ignore organization filtering. |\n| <a id=\"property-sender_ids\"></a> `sender_ids?` | `string`[] | Sender IDs to search within. Examples: ['user1']. Empty to search all accessible senders. |\n| <a id=\"property-team_id\"></a> `team_id?` | `string` \\| `null` | Channel team ID to search within. Empty to ignore team filtering. |\n| <a id=\"property-thread_ids\"></a> `thread_ids?` | `string`[] | Channel thread IDs to search within. Examples: ['thread123']. Empty to search all threads. |\n\n\n<!-- generated/search/types.gen/type-aliases/ChannelThreadFilters.md -->\n# Type Alias: ChannelThreadFilters\n\n> **ChannelThreadFilters** = \\{ `channel_ids?`: `string`[]; `participant_ids?`: `string`[]; `root_sender_ids?`: `string`[]; `thread_ids?`: `string`[]; \\}\n\nThe channel thread filters used to filter down channel-thread entities.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-channel_ids\"></a> `channel_ids?` | `string`[] | Channel IDs containing the thread. Empty to include threads from all accessible channels. |\n| <a id=\"property-participant_ids\"></a> `participant_ids?` | `string`[] | Thread participant user IDs. A participant is the root message sender, anyone who replied in the thread, or anyone @-mentioned in the thread (group mentions like **Here** count through their per-user expansion at send time). Empty to include threads regardless of participants. |\n| <a id=\"property-root_sender_ids\"></a> `root_sender_ids?` | `string`[] | Sender IDs for the root thread message. Empty to include all root senders. |\n| <a id=\"property-thread_ids\"></a> `thread_ids?` | `string`[] | Channel thread parent message IDs to include. Empty to include all accessible threads. |\n\n\n<!-- generated/search/types.gen/type-aliases/ChatFilters.md -->\n# Type Alias: ChatFilters\n\n> **ChatFilters** = \\{ `chat_ids?`: `string`[]; `importance?`: `boolean` \\| `null`; `notification_filters?`: [`NotificationFilters`](NotificationFilters.md); `owners?`: `string`[]; `project_ids?`: `string`[]; `role?`: `string`[]; \\}\n\nThe chat filters used to filter down what chats you search over.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-chat_ids\"></a> `chat_ids?` | `string`[] | Chat ids to search over. Examples: ['chat1'], ['chat1', 'chat2']. When provided, chat search will only match results on these chats. Empty to search all accessible chats. |\n| <a id=\"property-importance\"></a> `importance?` | `boolean` \\| `null` | Filter by chat importance. None to ignore, true to pass through (no clause), false to short-circuit and return nothing. |\n| <a id=\"property-notification_filters\"></a> `notification_filters?` | [`NotificationFilters`](NotificationFilters.md) | Filter by chat notification state. |\n| <a id=\"property-owners\"></a> `owners?` | `string`[] | Filter by chat owner principal — a user ('macro\\|[email protected]'), a bot ('bot\\|<uuid>'), or a team (a bare hyphenated uuid). Examples: ['macro\\|[email protected]'], ['macro\\|[email protected]', 'bot\\|0199...']. Empty to search all owners. |\n| <a id=\"property-project_ids\"></a> `project_ids?` | `string`[] | A list of project ids to search within. Examples: ['project1']. Empty to ignore project filtering. |\n| <a id=\"property-role\"></a> `role?` | `string`[] | Chat message roles to search. Examples: ['user'], ['assistant']. Empty to search all roles. |\n\n\n<!-- generated/search/types.gen/type-aliases/CrmCompanyFilters.md -->\n# Type Alias: CrmCompanyFilters\n\n> **CrmCompanyFilters** = \\{ `company_ids?`: `string`[]; `hidden?`: `boolean` \\| `null`; \\}\n\nThe crm company filters used to narrow which CRM companies appear in soup.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-company_ids\"></a> `company_ids?` | `string`[] | CRM company ids to filter by. Examples: ['11111111-...']. Empty to include all of the team's visible CRM companies. |\n| <a id=\"property-hidden\"></a> `hidden?` | `boolean` \\| `null` | Optional `crm_companies.hidden` filter. `None` = visible only (default for back-compat with non-admin callers). `Some(false)` = visible only (explicit). `Some(true)` = hidden only — requires admin/owner team role; enforced by the CRM service from the caller's team receipt. |\n\n\n<!-- generated/search/types.gen/type-aliases/DocumentFilters.md -->\n# Type Alias: DocumentFilters\n\n> **DocumentFilters** = \\{ `document_ids?`: `string`[]; `file_types?`: `string`[]; `importance?`: `boolean` \\| `null`; `is_email_attachment?`: `boolean` \\| `null`; `notification_filters?`: [`NotificationFilters`](NotificationFilters.md); `owners?`: `string`[]; `project_ids?`: `string`[]; `sub_types?`: `string`[]; `task_filters?`: [`TaskFilters`](TaskFilters.md); \\}\n\nThe document filters used to filter down what documents you search over.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-document_ids\"></a> `document_ids?` | `string`[] | Document ids to search over. Examples: ['doc1'], ['doc1', 'doc2']. Empty to search all accessible documents. |\n| <a id=\"property-file_types\"></a> `file_types?` | `string`[] | Document file types to search. Examples: ['pdf'], ['md', 'txt']. Empty to search all file types. |\n| <a id=\"property-importance\"></a> `importance?` | `boolean` \\| `null` | Filter by document importance. None to ignore, true to pass through (no clause), false to short-circuit and return nothing. |\n| <a id=\"property-is_email_attachment\"></a> `is_email_attachment?` | `boolean` \\| `null` | Filter by email attachment status. true = only email attachments, false = only non-email attachments, None = both. |\n| <a id=\"property-notification_filters\"></a> `notification_filters?` | [`NotificationFilters`](NotificationFilters.md) | Filter by document notification state. |\n| <a id=\"property-owners\"></a> `owners?` | `string`[] | Filter by document owner principal — a user ('macro\\|[email protected]'), a bot ('bot\\|<uuid>'), or a team (a bare hyphenated uuid). Examples: ['macro\\|[email protected]'], ['macro\\|[email protected]', 'bot\\|0199...']. Empty to search all owners. |\n| <a id=\"property-project_ids\"></a> `project_ids?` | `string`[] | A list of project ids to search within. Examples: ['project1']. filtering. Empty to ignore project filtering. |\n| <a id=\"property-sub_types\"></a> `sub_types?` | `string`[] | Filter by document sub type. Examples: ['task']. Empty to search all sub types. |\n| <a id=\"property-task_filters\"></a> `task_filters?` | [`TaskFilters`](TaskFilters.md) | Task-specific filters that only apply to task subtype documents. |\n\n\n<!-- generated/search/types.gen/type-aliases/EmailFilters.md -->\n# Type Alias: EmailFilters\n\n> **EmailFilters** = \\{ `bcc?`: `string`[]; `calendar_only?`: `boolean` \\| `null`; `cc?`: `string`[]; `crm_addresses?`: `string`[]; `crm_domains?`: `string`[]; `email_thread_ids?`: `string`[]; `exclude_labels?`: `string`[]; `importance?`: `boolean` \\| `null`; `include_labels?`: `string`[]; `is_read?`: `boolean` \\| `null`; `link_ids?`: `string`[]; `notification_filters?`: [`NotificationFilters`](NotificationFilters.md); `project_ids?`: `string`[]; `recipients?`: `string`[]; `senders?`: `string`[]; `shared?`: [`SharedEmailFilter`](SharedEmailFilter.md); \\}\n\nThe email filters used to filter down what emails you search over.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-bcc\"></a> `bcc?` | `string`[] | Email BCC addresses to filter by. Examples: ['[email protected]']. Empty if not filtering by BCC. |\n| <a id=\"property-calendar_only\"></a> `calendar_only?` | `boolean` \\| `null` | When `Some(true)`, only include threads that have at least one message with an iCalendar attachment (`.ics` filename or `application/ics` mime type). `Some(false)` and `None` apply no constraint. |\n| <a id=\"property-cc\"></a> `cc?` | `string`[] | Email CC addresses to filter by. Examples: ['[email protected]']. Empty if not filtering by CC. |\n| <a id=\"property-crm_addresses\"></a> `crm_addresses?` | `string`[] | CRM-scoped address filter. When non-empty, expands visibility to every teammate's mailbox and restricts to threads involving any of these fully-qualified addresses. Each address is authorized against `crm_contacts` + `crm_companies` (contact must not be hidden, company must not be hidden, `email_sync` must be true). Mutually exclusive with `crm_domains`. |\n| <a id=\"property-crm_domains\"></a> `crm_domains?` | `string`[] | CRM-scoped domain filter. When non-empty, expands visibility to every teammate's mailbox and restricts to threads involving any of these domains (in any of sender/cc/bcc/recipient). Each domain is authorized against `crm_domains` + `crm_companies` (must exist for the caller's team, company must not be hidden, `email_sync` must be true). Mutually exclusive with `crm_addresses`. |\n| <a id=\"property-email_thread_ids\"></a> `email_thread_ids?` | `string`[] | Email thread IDs to filter by. Examples: ['thread-uuid-1']. Empty to search all threads. |\n| <a id=\"property-exclude_labels\"></a> `exclude_labels?` | `string`[] | Exclude emails that have any of these labels. Supports both Gmail system labels (e.g. \"CATEGORY_PROMOTIONS\") and user-created labels. Empty to not exclude any labels. Note: SPAM and TRASH emails are not indexed in OpenSearch, so they are already excluded by default. |\n| <a id=\"property-importance\"></a> `importance?` | `boolean` \\| `null` | Filter by email importance. None to not filter. True to show only important emails (drafts, personal, sent, or uncategorized). False to show only unimportant emails (those categorized as promotions, social, updates, or forums). |\n| <a id=\"property-include_labels\"></a> `include_labels?` | `string`[] | Only include emails that have at least one of these labels. Supports both Gmail system labels (e.g. \"INBOX\", \"CATEGORY_PROMOTIONS\") and user-created labels (e.g. \"github\"). Empty to not filter by included labels. Note: SPAM and TRASH emails are not indexed in OpenSearch, so they will never appear in results regardless of this filter. |\n| <a id=\"property-is_read\"></a> `is_read?` | `boolean` \\| `null` | Filter by the email thread's read flag, independently of notification state. |\n| <a id=\"property-link_ids\"></a> `link_ids?` | `string`[] | Restrict to specific inboxes by email_links.id. Empty means \"any inbox the caller can access\" (soup expands to the full set at the router edge). |\n| <a id=\"property-notification_filters\"></a> `notification_filters?` | [`NotificationFilters`](NotificationFilters.md) | Filter by email notification state. |\n| <a id=\"property-project_ids\"></a> `project_ids?` | `string`[] | A list of project ids to search within. Empty to ignore project filtering. |\n| <a id=\"property-recipients\"></a> `recipients?` | `string`[] | Email Recipient addresses to filter by. Examples: ['[email protected]']. Empty if not filtering by Recipient. |\n| <a id=\"property-senders\"></a> `senders?` | `string`[] | Email sender addresses to filter by. Examples: ['[email protected]']. Empty to search all senders. |\n| <a id=\"property-shared\"></a> `shared?` | [`SharedEmailFilter`](SharedEmailFilter.md) | Controls whether shared email threads are included in results. Defaults to \"exclude\" (only the user's own threads). |\n\n\n<!-- generated/search/types.gen/type-aliases/EntityFilters.md -->\n# Type Alias: EntityFilters\n\n> **EntityFilters** = \\{ `agent_session_filters?`: [`AgentSessionFilters`](AgentSessionFilters.md); `calendar_event_filters?`: [`CalendarEventFilters`](CalendarEventFilters.md); `call_filters?`: [`CallFilters`](CallFilters.md); `channel_filters?`: [`ChannelFilters`](ChannelFilters.md); `channel_thread_filters?`: [`ChannelThreadFilters`](ChannelThreadFilters.md); `chat_filters?`: [`ChatFilters`](ChatFilters.md); `crm_company_filters?`: [`CrmCompanyFilters`](CrmCompanyFilters.md); `document_filters?`: [`DocumentFilters`](DocumentFilters.md); `email_filters?`: [`EmailFilters`](EmailFilters.md); `favorites_only?`: `boolean` \\| `null`; `foreign_entity_filters?`: [`ForeignEntityFilters`](ForeignEntityFilters.md); `initiative_filters?`: [`InitiativeFilters`](InitiativeFilters.md); `project_filters?`: [`ProjectFilters`](ProjectFilters.md); `property_filters?`: [`PropertyFilter`](PropertyFilter.md)[]; `tag_filter_mode?`: [`TagFilterMode`](TagFilterMode.md); `tag_option_ids?`: `string`[]; \\}\n\na bundle of all of the filters for each entity type\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-agent_session_filters\"></a> `agent_session_filters?` | [`AgentSessionFilters`](AgentSessionFilters.md) | the bundled [AgentSessionFilters] |\n| <a id=\"property-calendar_event_filters\"></a> `calendar_event_filters?` | [`CalendarEventFilters`](CalendarEventFilters.md) | the bundled [CalendarEventFilters] |\n| <a id=\"property-call_filters\"></a> `call_filters?` | [`CallFilters`](CallFilters.md) | the bundled [CallFilters] |\n| <a id=\"property-channel_filters\"></a> `channel_filters?` | [`ChannelFilters`](ChannelFilters.md) | the bundled [ChannelFilters] |\n| <a id=\"property-channel_thread_filters\"></a> `channel_thread_filters?` | [`ChannelThreadFilters`](ChannelThreadFilters.md) | the bundled [ChannelThreadFilters] |\n| <a id=\"property-chat_filters\"></a> `chat_filters?` | [`ChatFilters`](ChatFilters.md) | the bundled [ChatFilters] |\n| <a id=\"property-crm_company_filters\"></a> `crm_company_filters?` | [`CrmCompanyFilters`](CrmCompanyFilters.md) | the bundled [CrmCompanyFilters] |\n| <a id=\"property-document_filters\"></a> `document_filters?` | [`DocumentFilters`](DocumentFilters.md) | the bundled [DocumentFilters] |\n| <a id=\"property-email_filters\"></a> `email_filters?` | [`EmailFilters`](EmailFilters.md) | the bundled [EmailFilters] |\n| <a id=\"property-favorites_only\"></a> `favorites_only?` | `boolean` \\| `null` | Restrict results to the authenticated viewer's favorites when true. |\n| <a id=\"property-foreign_entity_filters\"></a> `foreign_entity_filters?` | [`ForeignEntityFilters`](ForeignEntityFilters.md) | the bundled [ForeignEntityFilters] |\n| <a id=\"property-initiative_filters\"></a> `initiative_filters?` | [`InitiativeFilters`](InitiativeFilters.md) | Initiative filters. Initiatives are opt-in. |\n| <a id=\"property-project_filters\"></a> `project_filters?` | [`ProjectFilters`](ProjectFilters.md) | the bundled [ProjectFilters] |\n| <a id=\"property-property_filters\"></a> `property_filters?` | [`PropertyFilter`](PropertyFilter.md)[] | property-based filters applied across entity types |\n| <a id=\"property-tag_filter_mode\"></a> `tag_filter_mode?` | [`TagFilterMode`](TagFilterMode.md) | How the `tag_option_ids` combine: `any` (default) matches entities holding at least one selected tag, `all` requires every selected tag. |\n| <a id=\"property-tag_option_ids\"></a> `tag_option_ids?` | `string`[] | tag option ids matched against `properties.values`, OR'd together across all tag definitions. Option ids are globally unique, so the match ignores the owning definition id (personal and team tags combine into one OR). |\n\n\n<!-- generated/search/types.gen/type-aliases/ForeignEntityFilters.md -->\n# Type Alias: ForeignEntityFilters\n\n> **ForeignEntityFilters** = \\{ `foreign_entity_ids?`: `string`[]; `foreign_entity_sources?`: `string`[]; `ids?`: `string`[]; `includes_me?`: `boolean`; `notification_filters?`: [`NotificationFilters`](NotificationFilters.md); \\}\n\nFilters for foreign entity records.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-foreign_entity_ids\"></a> `foreign_entity_ids?` | `string`[] | External entity identifiers to filter by. Empty to include all external IDs. |\n| <a id=\"property-foreign_entity_sources\"></a> `foreign_entity_sources?` | `string`[] | External source names to filter by. Empty to include all sources. |\n| <a id=\"property-ids\"></a> `ids?` | `string`[] | Internal foreign entity record IDs to filter by. Empty to include all records. |\n| <a id=\"property-includes_me\"></a> `includes_me?` | `boolean` | When true, only return foreign entities whose metadata lists the requesting user as a participant (GitHub `involves:me` semantics for `github_pull_request` records). False or absent applies no filter. Serialized in filter ASTs as the `\"me\"` literal. |\n| <a id=\"property-notification_filters\"></a> `notification_filters?` | [`NotificationFilters`](NotificationFilters.md) | Filter by the notification state of the foreign entity (e.g. whether the requesting user's GitHub PR notification is done/seen). |\n\n\n<!-- generated/search/types.gen/type-aliases/InitiativeFilters.md -->\n# Type Alias: InitiativeFilters\n\n> **InitiativeFilters** = \\{ `due_after?`: `string` \\| `null`; `due_before?`: `string` \\| `null`; `include?`: `boolean`; `initiative_ids?`: `string`[]; `name?`: `string` \\| `null`; `owners?`: `string`[]; \\}\n\nFilters for initiatives.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-due_after\"></a> `due_after?` | `string` \\| `null` | Inclusive lower due-date bound. |\n| <a id=\"property-due_before\"></a> `due_before?` | `string` \\| `null` | Inclusive upper due-date bound. |\n| <a id=\"property-include\"></a> `include?` | `boolean` | Opt this query into initiatives at all. Initiatives are off by default — see [`crate::ast::initiative::InitiativeLiteral::Include`]. Asking for specific `initiative_ids` or `owners` also opts in. |\n| <a id=\"property-initiative_ids\"></a> `initiative_ids?` | `string`[] | Initiative ids to filter by. Empty to include all accessible initiatives. |\n| <a id=\"property-name\"></a> `name?` | `string` \\| `null` | Case-insensitive name substring. |\n| <a id=\"property-owners\"></a> `owners?` | `string`[] | Filter by initiative owner principal — a user ('macro\\|[email protected]'), a bot ('bot\\|<uuid>'), or a team (a bare hyphenated uuid). Empty to include every owner. |\n\n\n<!-- generated/search/types.gen/type-aliases/NotificationFilters.md -->\n# Type Alias: NotificationFilters\n\n> **NotificationFilters** = \\{ `states?`: [`NotificationState`](NotificationState.md)[]; \\}\n\nNotification-level filters that apply to an entity type.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-states\"></a> `states?` | [`NotificationState`](NotificationState.md)[] | Include entities with a non-deleted notification in any of these exact states. Empty means no notification restriction. Active means `[unseen, seen]`. |\n\n\n<!-- generated/search/types.gen/type-aliases/NotificationState.md -->\n# Type Alias: NotificationState\n\n> **NotificationState** = `\"unseen\"` \\| `\"seen\"` \\| `\"done\"`\n\nThe mutually exclusive lifecycle states of a user's notification.\n\n\n<!-- generated/search/types.gen/type-aliases/ProjectFilters.md -->\n# Type Alias: ProjectFilters\n\n> **ProjectFilters** = \\{ `importance?`: `boolean` \\| `null`; `include_root?`: `boolean`; `notification_filters?`: [`NotificationFilters`](NotificationFilters.md); `owners?`: `string`[]; `project_ids?`: `string`[]; \\}\n\nThe project filters used to filter down what projects you search over.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-importance\"></a> `importance?` | `boolean` \\| `null` | Filter by project importance. None to ignore, true to pass through (no clause), false to short-circuit and return nothing. |\n| <a id=\"property-include_root\"></a> `include_root?` | `boolean` | When true, `project_ids` also matches the projects themselves in addition to their children. |\n| <a id=\"property-notification_filters\"></a> `notification_filters?` | [`NotificationFilters`](NotificationFilters.md) | Filter by project notification state. |\n| <a id=\"property-owners\"></a> `owners?` | `string`[] | Filter by project owner principal — a user ('macro\\|[email protected]'), a bot ('bot\\|<uuid>'), or a team (a bare hyphenated uuid). Examples: ['macro\\|[email protected]'], ['macro\\|[email protected]', 'bot\\|0199...']. Empty to search all owners. |\n| <a id=\"property-project_ids\"></a> `project_ids?` | `string`[] | Project IDs to search within. Examples: ['project1']. Empty to search all accessible projects. By default matches children of these projects; set `include_root` to also match the projects themselves. |\n\n\n<!-- generated/search/types.gen/type-aliases/PropertyFilter.md -->\n# Type Alias: PropertyFilter\n\n> **PropertyFilter** = \\{ `entity_ids?`: `string`[]; `entity_type?`: `string` \\| `null`; `option_ids?`: `string`[]; `property_definition_id`: `string`; \\}\n\nA single property-based filter condition.\n\nEach filter targets a specific property definition on entities of a given type,\nmatching against select option UUIDs or entity reference IDs.\nMultiple values within a single filter are OR'd together.\nMultiple filters are AND'd together.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-entity_ids\"></a> `entity_ids?` | `string`[] | Entity reference IDs to match. Multiple values are OR'd together. |\n| <a id=\"property-entity_type\"></a> `entity_type?` | `string` \\| `null` | The entity type for the property lookup (e.g., \"TASK\", \"DOCUMENT\", \"PROJECT\"). When None, matches across all entity types. |\n| <a id=\"property-option_ids\"></a> `option_ids?` | `string`[] | Select option UUIDs to match. Multiple values are OR'd together. |\n| <a id=\"property-property_definition_id\"></a> `property_definition_id` | `string` | The UUID of the property definition to filter on. |\n\n\n<!-- generated/search/types.gen/type-aliases/SharedEmailFilter.md -->\n# Type Alias: SharedEmailFilter\n\n> **SharedEmailFilter** = `\"exclude\"` \\| `\"include\"` \\| `\"only\"`\n\nControls whether shared email threads are included in results.\n\n\n<!-- generated/search/types.gen/type-aliases/TagFilterMode.md -->\n# Type Alias: TagFilterMode\n\n> **TagFilterMode** = `\"any\"` \\| `\"all\"`\n\nHow multiple `tag_option_ids` combine when filtering.\n\n\n<!-- generated/search/types.gen/type-aliases/TaskFilters.md -->\n# Type Alias: TaskFilters\n\n> **TaskFilters** = \\{ `include_cbm_atm_nc?`: `boolean` \\| `null`; \\}\n\nTask-only filters nested under document filters.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-include_cbm_atm_nc\"></a> `include_cbm_atm_nc?` | `boolean` \\| `null` | Include tasks that are created by me, assigned to me, and not completed, even when they do not match other document filters. |\n\n\n<!-- generated/storage/types.gen/type-aliases/AccessLevel.md -->\n# Type Alias: AccessLevel\n\n> **AccessLevel** = `\"view\"` \\| `\"comment\"` \\| `\"edit\"` \\| `\"owner\"`\n\nOrdered from least to most access top -> bottom\n\n\n<!-- generated/storage/types.gen/type-aliases/AccessRequest.md -->\n# Type Alias: AccessRequest\n\n> **AccessRequest** = \\{ `createdAt`: `string`; `grantedLevel?`: `null` \\| [`AccessLevel`](AccessLevel.md); `id`: `string`; `requestedLevel`: [`AccessLevel`](AccessLevel.md); `requesterId`: `string`; `resolvedAt?`: `string` \\| `null`; `retryAfter?`: `string` \\| `null`; `revision`: `number`; `status`: [`RequestStatus`](RequestStatus.md); `updatedAt`: `string`; \\}\n\nLatest request for one person and one entity.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-createdat\"></a> `createdAt` | `string` | Start of this request attempt. |\n| <a id=\"property-grantedlevel\"></a> `grantedLevel?` | `null` \\| [`AccessLevel`](AccessLevel.md) | - |\n| <a id=\"property-id\"></a> `id` | `string` | Stable request identity across revisions. |\n| <a id=\"property-requestedlevel\"></a> `requestedLevel` | [`AccessLevel`](AccessLevel.md) | Requested upgrade. |\n| <a id=\"property-requesterid\"></a> `requesterId` | `string` | Person requesting access. |\n| <a id=\"property-resolvedat\"></a> `resolvedAt?` | `string` \\| `null` | When the request stopped being pending. |\n| <a id=\"property-retryafter\"></a> `retryAfter?` | `string` \\| `null` | Earliest next submission or level change; cancellation preserves this deadline. Submissions wait one minute, denials wait 24 hours, and approval clears it. |\n| <a id=\"property-revision\"></a> `revision` | `number` | Optimistic concurrency token. |\n| <a id=\"property-status\"></a> `status` | [`RequestStatus`](RequestStatus.md) | Current outcome. |\n| <a id=\"property-updatedat\"></a> `updatedAt` | `string` | Most recent change. |\n\n\n<!-- generated/storage/types.gen/type-aliases/EntityPermission.md -->\n# Type Alias: EntityPermission\n\n> **EntityPermission** = \\{ `access_level`: [`AccessLevel`](AccessLevel.md); `type`: `\"access_level\"`; \\} \\| \\{ `type`: `\"channel_view_only\"`; \\} \\| \\{ `role`: [`ParticipantRole`](ParticipantRole.md); `type`: `\"channel_role\"`; \\} \\| \\{ `role`: [`TeamRole`](TeamRole.md); `type`: `\"team_role\"`; \\}\n\nA user's permission for an entity, discriminated by entity kind.\n\nItems (documents, chats, projects, threads) use access levels.\nChannels use view-only permission or participant roles.\n\n## Union Members\n\n### Type Literal\n\n\\{ `access_level`: [`AccessLevel`](AccessLevel.md); `type`: `\"access_level\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `access_level` | [`AccessLevel`](AccessLevel.md) | The access level the user has. |\n| `type` | `\"access_level\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `type`: `\"channel_view_only\"`; \\}\n\n***\n\n### Type Literal\n\n\\{ `role`: [`ParticipantRole`](ParticipantRole.md); `type`: `\"channel_role\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `role` | [`ParticipantRole`](ParticipantRole.md) | The role the user has in the channel. |\n| `type` | `\"channel_role\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `role`: [`TeamRole`](TeamRole.md); `type`: `\"team_role\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `role` | [`TeamRole`](TeamRole.md) | The role the user has in the team. |\n| `type` | `\"team_role\"` | - |\n\n\n<!-- generated/storage/types.gen/type-aliases/FavoriteEntityRef.md -->\n# Type Alias: FavoriteEntityRef\n\n> **FavoriteEntityRef** = \\{ `entityId`: `string`; `entityType`: `\"user\"` \\| `\"chat\"` \\| `\"channel\"` \\| `\"channel_message\"` \\| `\"document\"` \\| `\"project\"` \\| `\"email_thread\"` \\| `\"calendar_event\"` \\| `\"team\"` \\| `\"call\"` \\| `\"foreign_entity\"` \\| `\"static_file\"` \\| `\"crm_company\"` \\| `\"crm_contact\"` \\| `\"crm_pipeline\"` \\| `\"reminder\"` \\| `\"skill\"` \\| `\"agent_session\"` \\| `\"scheduled_action\"` \\| `\"initiative\"` \\| `\"database\"` \\| `\"database_row\"` \\| `\"form\"`; \\}\n\nA reference to a favorited entity.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-entityid\"></a> `entityId` | `string` | The id of the favorited entity. |\n| <a id=\"property-entitytype\"></a> `entityType` | `\"user\"` \\| `\"chat\"` \\| `\"channel\"` \\| `\"channel_message\"` \\| `\"document\"` \\| `\"project\"` \\| `\"email_thread\"` \\| `\"calendar_event\"` \\| `\"team\"` \\| `\"call\"` \\| `\"foreign_entity\"` \\| `\"static_file\"` \\| `\"crm_company\"` \\| `\"crm_contact\"` \\| `\"crm_pipeline\"` \\| `\"reminder\"` \\| `\"skill\"` \\| `\"agent_session\"` \\| `\"scheduled_action\"` \\| `\"initiative\"` \\| `\"database\"` \\| `\"database_row\"` \\| `\"form\"` | The type of the favorited entity. |\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkShare.md -->\n# Type Alias: LinkShare\n\n> **LinkShare** = `\"PUBLIC\"` \\| `\"TEAM\"`\n\nDefines who can access an item through its share link.\n\n\n<!-- generated/storage/types.gen/type-aliases/MessageCursor.md -->\n# Type Alias: MessageCursor\n\n> **MessageCursor** = \\{ `created_at`: `string`; `id`: `string`; \\}\n\nCursor for a chronological parent timeline.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-created_at\"></a> `created_at` | `string` | Last message creation time or activity occurrence time. |\n| <a id=\"property-id\"></a> `id` | `string` | Last entry UUID, used to break timestamp ties across both sources. |\n\n\n<!-- generated/storage/types.gen/type-aliases/MessageDirection.md -->\n# Type Alias: MessageDirection\n\n> **MessageDirection** = `\"older\"` \\| `\"newer\"`\n\nDirection through a parent timeline, retaining channel cursor semantics.\n\n\n<!-- generated/storage/types.gen/type-aliases/ParticipantRole.md -->\n# Type Alias: ParticipantRole\n\n> **ParticipantRole** = `\"owner\"` \\| `\"admin\"` \\| `\"member\"`\n\nThe role a user has within a channel.\n\n\n<!-- generated/storage/types.gen/type-aliases/RequestStatus.md -->\n# Type Alias: RequestStatus\n\n> **RequestStatus** = `\"pending\"` \\| `\"granted\"` \\| `\"denied\"` \\| `\"cancelled\"`\n\nDurable outcome; reading a notification never changes it.\n\n\n<!-- generated/storage/types.gen/type-aliases/ResolveRequest.md -->\n# Type Alias: ResolveRequest\n\n> **ResolveRequest** = \\{ `grantedLevel?`: `null` \\| [`AccessLevel`](AccessLevel.md); `revision`: `number`; \\}\n\nOwner's decision; omission of a granted level means deny.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-grantedlevel\"></a> `grantedLevel?` | `null` \\| [`AccessLevel`](AccessLevel.md) | - |\n| <a id=\"property-revision\"></a> `revision` | `number` | Request revision being reviewed. |\n\n\n<!-- generated/storage/types.gen/type-aliases/ShareEntityType.md -->\n# Type Alias: ShareEntityType\n\n> **ShareEntityType** = `\"document\"` \\| `\"chat\"` \\| `\"project\"` \\| `\"initiative\"` \\| `\"database\"` \\| `\"call\"` \\| `\"email_thread\"` \\| `\"agent_session\"`\n\nAn entity type with an existing Share surface.\n\n\n<!-- generated/storage/types.gen/type-aliases/SimpleMention.md -->\n# Type Alias: SimpleMention\n\n> **SimpleMention** = \\{ `entity_id`: `string`; `entity_type`: `string`; \\}\n\nA mention tracked in a message body.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-entity_id\"></a> `entity_id` | `string` | Mentioned entity identifier. |\n| <a id=\"property-entity_type\"></a> `entity_type` | `string` | Mentioned entity type. |\n\n\n<!-- generated/storage/types.gen/type-aliases/TeamRole.md -->\n# Type Alias: TeamRole\n\n> **TeamRole** = `\"member\"` \\| `\"admin\"` \\| `\"owner\"`\n\nThe role a user has within a team.\n\nOrdered least to most privileged so comparisons reflect access strength.\n\n\n<!-- generated/storage/types.gen/type-aliases/ThreadAnchor.md -->\n# Type Alias: ThreadAnchor\n\n> **ThreadAnchor** = \\{ `mark_id`: `string`; `marked_text?`: `string` \\| `null`; `type`: `\"markdown\"`; \\} \\| \\{ `anchor_id`: `string`; `marked_text?`: `string` \\| `null`; `type`: `\"pdf_highlight\"`; \\} \\| \\{ `anchor_id`: `string`; `type`: `\"pdf_placeable\"`; \\} \\| \\{ `range`: `string`; `sheetId`: `string`; `sheetName`: `string`; `type`: `\"spreadsheet\"`; \\} \\| \\{ `nodeId?`: `string` \\| `null`; `pageId`: `string`; `type`: `\"fig\"`; `x`: `number`; `y`: `number`; \\}\n\nA thread's location within its document. PDF geometry remains annotation-owned.\n\n## Union Members\n\n### Type Literal\n\n\\{ `mark_id`: `string`; `marked_text?`: `string` \\| `null`; `type`: `\"markdown\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `mark_id` | `string` | Mark UUID serialized in the document. |\n| `marked_text?` | `string` \\| `null` | The marked text as it read when the discussion was created, already trimmed and bounded. Absent on threads created or imported before snapshots were captured: the text a mark covers cannot be recovered from the mark id alone. |\n| `type` | `\"markdown\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `anchor_id`: `string`; `marked_text?`: `string` \\| `null`; `type`: `\"pdf_highlight\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `anchor_id` | `string` | Highlight annotation UUID. |\n| `marked_text?` | `string` \\| `null` | The text the highlight covers, trimmed and bounded like a markdown snapshot. The highlight owns it and it can be edited there, so it is read from the highlight whenever the thread is, never stored on the thread. Absent when the highlight carries no text. |\n| `type` | `\"pdf_highlight\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `anchor_id`: `string`; `type`: `\"pdf_placeable\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `anchor_id` | `string` | Placeable annotation UUID. |\n| `type` | `\"pdf_placeable\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `range`: `string`; `sheetId`: `string`; `sheetName`: `string`; `type`: `\"spreadsheet\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `range` | `string` | A1 cell or range, such as B4 or B4:C9. |\n| `sheetId` | `string` | Stable sheet identity within the workbook. |\n| `sheetName` | `string` | Sheet name when the discussion was created. |\n| `type` | `\"spreadsheet\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `nodeId?`: `string` \\| `null`; `pageId`: `string`; `type`: `\"fig\"`; `x`: `number`; `y`: `number`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `nodeId?` | `string` \\| `null` | Layer the pin follows; absent for a pin on the bare canvas. |\n| `pageId` | `string` | Page (canvas) the pin is on. |\n| `type` | `\"fig\"` | - |\n| `x` | `number` | Horizontal offset from the layer's origin, or the page's when the pin is on no layer, in design units. |\n| `y` | `number` | Vertical offset, measured like `x`. |\n\n\n<!-- generated/storage/types.gen/type-aliases/ThreadState.md -->\n# Type Alias: ThreadState\n\n> **ThreadState** = \\{ `anchor?`: `null` \\| [`ThreadAnchor`](ThreadAnchor.md); `created_at`: `string`; `deleted_at?`: `string` \\| `null`; `resolved`: `boolean`; `root_id`: `string`; `updated_at`: `string`; `user_id`: `string`; \\}\n\nState belonging to a whole thread, keyed by its root message.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-anchor\"></a> `anchor?` | `null` \\| [`ThreadAnchor`](ThreadAnchor.md) | - |\n| <a id=\"property-created_at\"></a> `created_at` | `string` | Creation time of the discussion. |\n| <a id=\"property-deleted_at\"></a> `deleted_at?` | `string` \\| `null` | Explicit deletion of the entire thread, distinct from root deletion. |\n| <a id=\"property-resolved\"></a> `resolved` | `boolean` | Whether this discussion has been resolved. |\n| <a id=\"property-root_id\"></a> `root_id` | `string` | Root message UUID; there is no separate thread identity. |\n| <a id=\"property-updated_at\"></a> `updated_at` | `string` | Last state change. |\n| <a id=\"property-user_id\"></a> `user_id` | `string` | User who owns this discussion, including imported discussions. |\n\n\n<!-- generated/storage/types.gen/type-aliases/UpdateChannelSharePermission.md -->\n# Type Alias: UpdateChannelSharePermission\n\n> **UpdateChannelSharePermission** = \\{ `accessLevel?`: `null` \\| [`AccessLevel`](AccessLevel.md); `channelId`: `string`; `operation`: [`UpdateOperation`](UpdateOperation.md); \\}\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-accesslevel\"></a> `accessLevel?` | `null` \\| [`AccessLevel`](AccessLevel.md) | - |\n| <a id=\"property-channelid\"></a> `channelId` | `string` | The channel id |\n| <a id=\"property-operation\"></a> `operation` | [`UpdateOperation`](UpdateOperation.md) | The type of operation to be performed on the chanel share permission You can add, remove or replace and existing permission |\n\n\n<!-- generated/storage/types.gen/type-aliases/UpdateOperation.md -->\n# Type Alias: UpdateOperation\n\n> **UpdateOperation** = `\"add\"` \\| `\"remove\"` \\| `\"replace\"`\n\n\n<!-- generated/storage/types.gen/type-aliases/UpdateSharePermissionRequestV2.md -->\n# Type Alias: UpdateSharePermissionRequestV2\n\n> **UpdateSharePermissionRequestV2** = \\{ `channelSharePermissions?`: [`UpdateChannelSharePermission`](UpdateChannelSharePermission.md)[] \\| `null`; `linkShare?`: `null` \\| [`LinkShare`](LinkShare.md); `linkShareAccessLevel?`: `null` \\| [`AccessLevel`](AccessLevel.md); `teamShareAccessLevel?`: `null` \\| [`AccessLevel`](AccessLevel.md); \\}\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-channelsharepermissions\"></a> `channelSharePermissions?` | [`UpdateChannelSharePermission`](UpdateChannelSharePermission.md)[] \\| `null` | Any channel share permissions to be created/updated/removed |\n| <a id=\"property-linkshare\"></a> `linkShare?` | `null` \\| [`LinkShare`](LinkShare.md) | - |\n| <a id=\"property-linkshareaccesslevel\"></a> `linkShareAccessLevel?` | `null` \\| [`AccessLevel`](AccessLevel.md) | - |\n| <a id=\"property-teamshareaccesslevel\"></a> `teamShareAccessLevel?` | `null` \\| [`AccessLevel`](AccessLevel.md) | - |\n\n\n<!-- generated/storage/types.gen/type-aliases/WebhookFilter.md -->\n# Type Alias: WebhookFilter\n\n> **WebhookFilter** = \\{ `events`: `string`[]; `ids?`: `string`[] \\| `null`; \\}\n\nEvent and optional entity-id constraints used to match webhook deliveries.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-events\"></a> `events` | `string`[] | Event names matched by this filter. |\n| <a id=\"property-ids\"></a> `ids?` | `string`[] \\| `null` | Entity ids matched by this filter. When absent, the filter matches all entity ids. |\n\n\n<!-- generated/storage/types.gen/type-aliases/WebhookScope.md -->\n# Type Alias: WebhookScope\n\n> **WebhookScope** = `\"user\"` \\| `\"team\"`\n\nScope that owns a newly-created webhook.\n\nClients serialize this, so both derives are used. `Display`/`FromStr`\nspell the same names as serde, for query strings and config values.\n\n\n<!-- src/config/interfaces/MacroOpts.md -->\n# Interface: MacroOpts\n\nOptions passed to `new Macro(opts)` and stored on `MacroClient`.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-auth\"></a> `auth?` | [`MacroAuth`](../type-aliases/MacroAuth.md) | How to authenticate. Takes precedence over `token`. Falls back to `MACRO_API_KEY` (a user API key or bearer token) or `MACRO_BOT_TOKEN` (bot). |\n| <a id=\"property-env\"></a> `env?` | [`Env`](../type-aliases/Env.md) | Which Macro environment to talk to. Falls back to the MACRO_ENV env var, then `'prod'`. |\n| <a id=\"property-hosts\"></a> `hosts?` | `Partial`\\<`Record`\\<[`ServiceName`](../type-aliases/ServiceName.md), `string`\\>\\> | Override individual service hosts (e.g. point one at localhost). |\n| <a id=\"property-onrequest\"></a> `onRequest?` | (`event`) => `void` | Optional generated API operation events; excludes arguments, URLs and response data. |\n| <a id=\"property-requestedas\"></a> `requestedAs?` | `string` | User id the bot acts for, sent as `x-macro-bot-for-macro-user-id` on every request. Bot auth only. Set via `macro.requestedAs(user)` rather than directly. |\n| <a id=\"property-token\"></a> `token?` | [`TokenSource`](../type-aliases/TokenSource.md) | Shorthand for `auth: { type: 'user', token }`. Accepts a Settings API key (`mak_…`) or a bearer token. |\n| <a id=\"property-webappurl\"></a> `webAppUrl?` | `string` | Override the web app base URL (e.g. for local frontend dev). Also reads MACRO_WEB_URL. |\n| <a id=\"property-webhooksecret\"></a> `webhookSecret?` | `string` | Signing secret for verifying incoming persisted-webhook deliveries. Required only for `macro.events.webhook()` / `macro.events.handle()`. SSE via `macro.events.listen()` uses the API token and does not need this. Falls back to MACRO_WEBHOOK_SECRET. |\n| <a id=\"property-wsverify\"></a> `wsVerify?` | `string` | - |\n\n\n<!-- src/config/type-aliases/BotScope.md -->\n# Type Alias: BotScope\n\n> **BotScope** = `\"user\"` \\| `\"team\"`\n\nAccess scope for bot-authenticated requests. `user` acts with the\nrequested-as user's access (requires `requestedAs`); `team` acts with the\nbot's owning team's access (team-owned bots only).\n\n\n<!-- src/config/type-aliases/Env.md -->\n# Type Alias: Env\n\n> **Env** = `\"dev\"` \\| `\"prod\"` \\| `\"local\"`\n\n\n<!-- src/config/type-aliases/MacroAuth.md -->\n# Type Alias: MacroAuth\n\n> **MacroAuth** = \\{ `apiKey?`: `never`; `token`: [`TokenSource`](TokenSource.md); `type`: `\"user\"`; \\} \\| \\{ `apiKey`: `string`; `token?`: `never`; `type`: `\"user\"`; \\} \\| \\{ `scope?`: [`BotScope`](BotScope.md); `token`: [`TokenSource`](TokenSource.md); `type`: `\"bot\"`; \\}\n\nHow the SDK authenticates with Macro.\n\nA user has exactly one of two credential fields.\n\n- `token`: a bearer token, or a `mak_` API key. The SDK picks the header\n from the prefix at send time.\n- `apiKey`: a Settings → API Keys key, always sent as\n `x-macro-user-api-key`. Not prefix-checked, so keys that predate the\n `mak_` prefix work here.\n\nA bot uses an `mbot_` token as `x-macro-bot-token` plus\n`x-macro-bot-scope`, defaulting to `user` when `requestedAs` is set and\n`team` otherwise.\n\n\n<!-- src/config/type-aliases/ServiceName.md -->\n# Type Alias: ServiceName\n\n> **ServiceName** = `\"agent-harness\"` \\| `\"storage\"` \\| `\"auth\"` \\| `\"email\"` \\| `\"calendar\"` \\| `\"cognition\"` \\| `\"notification\"` \\| `\"properties\"` \\| `\"search\"` \\| `\"scheduled-action\"` \\| `\"static-files\"` \\| `\"connection\"` \\| `\"contacts\"` \\| `\"unfurl\"`\n\nThe backend services the SDK talks to. Note `search` and `properties` are\nserved on the storage host, so they point there.\n\n\n<!-- src/config/type-aliases/TokenSource.md -->\n# Type Alias: TokenSource\n\n> **TokenSource** = `string` \\| (() => `string` \\| `Promise`\\<`string`\\>)\n\nA credential string, or a (possibly async) function that returns one.\n\n\n<!-- src/config/variables/HOSTS.md -->\n# Variable: HOSTS\n\n> `const` **HOSTS**: `Record`\\<[`Env`](../type-aliases/Env.md), `Record`\\<[`ServiceName`](../type-aliases/ServiceName.md), `string`\\>\\>\n\n\n<!-- src/config/variables/WEB_APP_URLS.md -->\n# Variable: WEB\\_APP\\_URLS\n\n> `const` **WEB\\_APP\\_URLS**: `Record`\\<[`Env`](../type-aliases/Env.md), `string`\\>\n\n\n<!-- src/entities/entity/classes/FavoritableEntity.md -->\n# Abstract Class: FavoritableEntity\\<Detail\\>\n\nAn entity the favorites API can address, and so can be (un)favorited.\n\n## Extends\n\n- [`MacroEntity`](MacroEntity.md)\\<`Detail`\\>\n\n## Extended by\n\n- [`CallRecord`](../../calls/call-record/classes/CallRecord.md)\n- [`Message`](../../channels/message/classes/Message.md)\n- [`Contact`](../../crm/contact/classes/Contact.md)\n- [`PropertiedEntity`](PropertiedEntity.md)\n- [`ForeignEntity`](../../foreign/foreign-entity/classes/ForeignEntity.md)\n\n## Type Parameters\n\n| Type Parameter |\n| ------ |\n| <a id=\"type-parameter-detail\"></a> `Detail` |\n\n## Implements\n\n- [`Favoritable`](../interfaces/Favoritable.md)\n\n## Properties\n\n| Property | Modifier | Type | Description | Inherited from |\n| ------ | ------ | ------ | ------ | ------ |\n| <a id=\"property-entitytype\"></a> `entityType` | `abstract readonly` | `\"project\"` \\| `\"user\"` \\| `\"team\"` \\| `\"chat\"` \\| `\"channel\"` \\| `\"channel_message\"` \\| `\"document\"` \\| `\"email_thread\"` \\| `\"calendar_event\"` \\| `\"call\"` \\| `\"foreign_entity\"` \\| `\"static_file\"` \\| `\"crm_company\"` \\| `\"crm_contact\"` \\| `\"crm_pipeline\"` \\| `\"reminder\"` \\| `\"skill\"` \\| `\"agent_session\"` \\| `\"scheduled_action\"` \\| `\"initiative\"` \\| `\"database\"` \\| `\"database_row\"` \\| `\"form\"` | How the entity-addressed APIs (favorites) identify this entity's type. | - |\n| <a id=\"property-id\"></a> `id` | `public readonly` | `string` | - | [`MacroEntity`](MacroEntity.md).[`id`](MacroEntity.md#property-id) |\n\n## Methods\n\n### favorite()\n\n> **favorite**(): `Promise`\\<`FavoritableEntity`\\<`Detail`\\>\\>\n\nAdd this entity to the user's favorites. Returns this handle for chaining.\nPlain unwrap: favoriting alters the user's favorites collection, not this\nentity's own detail, so there's nothing cached to invalidate.\n\n#### Returns\n\n`Promise`\\<`FavoritableEntity`\\<`Detail`\\>\\>\n\n#### Implementation of\n\n[`Favoritable`](../interfaces/Favoritable.md).[`favorite`](../interfaces/Favoritable.md#favorite)\n\n***\n\n### permission()\n\n> **permission**(): `Promise`\\<\\{ `permission`: [`EntityPermission`](../../../../generated/storage/types.gen/type-aliases/EntityPermission.md); `status`: `\"access\"`; \\} \\| \\{ `status`: `\"no_access\"`; \\}\\>\n\nRead the caller's effective permission on this entity.\n\n#### Returns\n\n`Promise`\\<\\{ `permission`: [`EntityPermission`](../../../../generated/storage/types.gen/type-aliases/EntityPermission.md); `status`: `\"access\"`; \\} \\| \\{ `status`: `\"no_access\"`; \\}\\>\n\n***\n\n### toJSON()\n\n> **toJSON**(): \\{ `detail?`: `Detail`; `id`: `string`; \\}\n\n#### Returns\n\n\\{ `detail?`: `Detail`; `id`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `detail?` | `Detail` |\n| `id` | `string` |\n\n#### Inherited from\n\n[`MacroEntity`](MacroEntity.md).[`toJSON`](MacroEntity.md#tojson)\n\n***\n\n### unfavorite()\n\n> **unfavorite**(): `Promise`\\<`FavoritableEntity`\\<`Detail`\\>\\>\n\nRemove this entity from the user's favorites. Returns this handle for chaining.\n\n#### Returns\n\n`Promise`\\<`FavoritableEntity`\\<`Detail`\\>\\>\n\n#### Implementation of\n\n[`Favoritable`](../interfaces/Favoritable.md).[`unfavorite`](../interfaces/Favoritable.md#unfavorite)\n\n\n<!-- src/entities/entity/classes/MacroEntity.md -->\n# Abstract Class: MacroEntity\\<Detail\\>\n\nBase for entity handles: a free-to-construct `(client, id)` pair whose\ndetail record loads lazily on first field access and is dropped after any\nmutation. Subclasses implement fetch and build their surface from\nfield and mutate.\n\n## Extended by\n\n- [`AgentSession`](../../agent-sessions/agent-session/classes/AgentSession.md)\n- [`CodeExecution`](../../agent-sessions/code-execution/classes/CodeExecution.md)\n- [`SessionReview`](../../agent-sessions/review/classes/SessionReview.md)\n- [`Agent`](../../agents/agent/classes/Agent.md)\n- [`UserApiKey`](../../api-keys/api-key/classes/UserApiKey.md)\n- [`Calendar`](../../calendar/calendar/classes/Calendar.md)\n- [`CalendarEvent`](../../calendar/event/classes/CalendarEvent.md)\n- [`CallMessage`](../../calls/message/classes/CallMessage.md)\n- [`ChatMessage`](../../chats/generation/classes/ChatMessage.md)\n- [`CrmComment`](../../crm/comment/classes/CrmComment.md)\n- [`CrmPipeline`](../../crm/pipeline/classes/CrmPipeline.md)\n- [`PipelineTable`](../../crm/pipeline/classes/PipelineTable.md)\n- [`PipelineRow`](../../crm/pipeline/classes/PipelineRow.md)\n- [`PipelineColumn`](../../crm/pipeline/classes/PipelineColumn.md)\n- [`Database`](../../databases/database/classes/Database.md)\n- [`DocumentAnchor`](../../documents/anchor/classes/DocumentAnchor.md)\n- [`Comment`](../../documents/comment/classes/Comment.md)\n- [`EmailAttachment`](../../email/attachment/classes/EmailAttachment.md)\n- [`EmailFilter`](../../email/filter/classes/EmailFilter.md)\n- [`Label`](../../email/label/classes/Label.md)\n- [`Link`](../../email/link/classes/Link.md)\n- [`EmailMessage`](../../email/message/classes/EmailMessage.md)\n- [`FavoritableEntity`](FavoritableEntity.md)\n- [`Form`](../../forms/form/classes/Form.md)\n- [`GithubPullRequest`](../../github-pull-requests/pull-request/classes/GithubPullRequest.md)\n- [`Harness`](../../harnesses/harness/classes/Harness.md)\n- [`HarnessPairing`](../../harnesses/pairing/classes/HarnessPairing.md)\n- [`Initiative`](../../initiatives/initiative/classes/Initiative.md)\n- [`Meeting`](../../meetings/meeting/classes/Meeting.md)\n- [`MessageThread`](../../messages/thread/classes/MessageThread.md)\n- [`Notification`](../../notifications/notification/classes/Notification.md)\n- [`Routine`](../../routines/routine/classes/Routine.md)\n- [`AccessRequest`](../../sharing/access/classes/AccessRequest.md)\n- [`Team`](../../teams/team/classes/Team.md)\n- [`Webhook`](../../webhooks/webhook/classes/Webhook.md)\n\n## Type Parameters\n\n| Type Parameter |\n| ------ |\n| <a id=\"type-parameter-detail\"></a> `Detail` |\n\n## Properties\n\n| Property | Modifier | Type |\n| ------ | ------ | ------ |\n| <a id=\"property-id\"></a> `id` | `public readonly` | `string` |\n\n## Methods\n\n### toJSON()\n\n> **toJSON**(): \\{ `detail?`: `Detail`; `id`: `string`; \\}\n\n#### Returns\n\n\\{ `detail?`: `Detail`; `id`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `detail?` | `Detail` |\n| `id` | `string` |\n\n\n<!-- src/entities/entity/classes/PropertiedEntity.md -->\n# Abstract Class: PropertiedEntity\\<Detail\\>\n\nA favoritable entity that also carries user-defined properties.\n\n## Extends\n\n- [`FavoritableEntity`](FavoritableEntity.md)\\<`Detail`\\>\n\n## Extended by\n\n- [`Channel`](../../channels/channel/classes/Channel.md)\n- [`Chat`](../../chats/chat/classes/Chat.md)\n- [`Company`](../../crm/company/classes/Company.md)\n- [`Document`](../../documents/document/classes/Document.md)\n- [`EmailThread`](../../email/thread/classes/EmailThread.md)\n- [`Project`](../../projects/project/classes/Project.md)\n- [`User`](../../users/user/classes/User.md)\n\n## Type Parameters\n\n| Type Parameter |\n| ------ |\n| <a id=\"type-parameter-detail\"></a> `Detail` |\n\n## Implements\n\n- [`Propertied`](../interfaces/Propertied.md)\n\n## Properties\n\n| Property | Modifier | Type | Description | Inherited from |\n| ------ | ------ | ------ | ------ | ------ |\n| <a id=\"property-entitytype\"></a> `entityType` | `abstract readonly` | `\"project\"` \\| `\"user\"` \\| `\"team\"` \\| `\"chat\"` \\| `\"channel\"` \\| `\"channel_message\"` \\| `\"document\"` \\| `\"email_thread\"` \\| `\"calendar_event\"` \\| `\"call\"` \\| `\"foreign_entity\"` \\| `\"static_file\"` \\| `\"crm_company\"` \\| `\"crm_contact\"` \\| `\"crm_pipeline\"` \\| `\"reminder\"` \\| `\"skill\"` \\| `\"agent_session\"` \\| `\"scheduled_action\"` \\| `\"initiative\"` \\| `\"database\"` \\| `\"database_row\"` \\| `\"form\"` | How the entity-addressed APIs (favorites) identify this entity's type. | [`FavoritableEntity`](FavoritableEntity.md).[`entityType`](FavoritableEntity.md#property-entitytype) |\n| <a id=\"property-id\"></a> `id` | `public readonly` | `string` | - | [`FavoritableEntity`](FavoritableEntity.md).[`id`](FavoritableEntity.md#property-id) |\n\n## Methods\n\n### deleteProperty()\n\n> **deleteProperty**(`assignment`): `Promise`\\<`void`\\>\n\nRemove a property from this entity, given its [properties](#properties) entry.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `assignment` | [`EntityPropertyWithDefinition`](../../../../generated/properties/types.gen/type-aliases/EntityPropertyWithDefinition.md) |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n#### Implementation of\n\n[`Propertied`](../interfaces/Propertied.md).[`deleteProperty`](../interfaces/Propertied.md#deleteproperty)\n\n***\n\n### favorite()\n\n> **favorite**(): `Promise`\\<`PropertiedEntity`\\<`Detail`\\>\\>\n\nAdd this entity to the user's favorites. Returns this handle for chaining.\nPlain unwrap: favoriting alters the user's favorites collection, not this\nentity's own detail, so there's nothing cached to invalidate.\n\n#### Returns\n\n`Promise`\\<`PropertiedEntity`\\<`Detail`\\>\\>\n\n#### Implementation of\n\n[`Propertied`](../interfaces/Propertied.md).[`favorite`](../interfaces/Propertied.md#favorite)\n\n#### Inherited from\n\n[`FavoritableEntity`](FavoritableEntity.md).[`favorite`](FavoritableEntity.md#favorite)\n\n***\n\n### permission()\n\n> **permission**(): `Promise`\\<\\{ `permission`: [`EntityPermission`](../../../../generated/storage/types.gen/type-aliases/EntityPermission.md); `status`: `\"access\"`; \\} \\| \\{ `status`: `\"no_access\"`; \\}\\>\n\nRead the caller's effective permission on this entity.\n\n#### Returns\n\n`Promise`\\<\\{ `permission`: [`EntityPermission`](../../../../generated/storage/types.gen/type-aliases/EntityPermission.md); `status`: `\"access\"`; \\} \\| \\{ `status`: `\"no_access\"`; \\}\\>\n\n#### Inherited from\n\n[`FavoritableEntity`](FavoritableEntity.md).[`permission`](FavoritableEntity.md#permission)\n\n***\n\n### properties()\n\n> **properties**(`opts?`): `Promise`\\<[`EntityPropertyWithDefinition`](../../../../generated/properties/types.gen/type-aliases/EntityPropertyWithDefinition.md)[]\\>\n\nThe properties set on this entity, each with its definition, value, and options.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `opts?` | \\{ `includeMetadata?`: `boolean`; \\} |\n| `opts.includeMetadata?` | `boolean` |\n\n#### Returns\n\n`Promise`\\<[`EntityPropertyWithDefinition`](../../../../generated/properties/types.gen/type-aliases/EntityPropertyWithDefinition.md)[]\\>\n\n#### Implementation of\n\n[`Propertied`](../interfaces/Propertied.md).[`properties`](../interfaces/Propertied.md#properties)\n\n***\n\n### propertyReference()\n\n> **propertyReference**(): [`PropertyTargetReference`](../../../../generated/properties/types.gen/type-aliases/PropertyTargetReference.md)\n\nThis entity's reference for bulk property operations.\n\n#### Returns\n\n[`PropertyTargetReference`](../../../../generated/properties/types.gen/type-aliases/PropertyTargetReference.md)\n\n***\n\n### setProperty()\n\n> **setProperty**(`property`, `value?`): `Promise`\\<`void`\\>\n\nSet a property value on this entity, or attach the property without a\nvalue when `value` is omitted.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `property` | [`PropertyDefinition`](../../properties/property-definition/classes/PropertyDefinition.md) |\n| `value?` | [`SetPropertyValue`](../../../../generated/properties/types.gen/type-aliases/SetPropertyValue.md) |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n#### Implementation of\n\n[`Propertied`](../interfaces/Propertied.md).[`setProperty`](../interfaces/Propertied.md#setproperty)\n\n***\n\n### toJSON()\n\n> **toJSON**(): \\{ `detail?`: `Detail`; `id`: `string`; \\}\n\n#### Returns\n\n\\{ `detail?`: `Detail`; `id`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `detail?` | `Detail` |\n| `id` | `string` |\n\n#### Inherited from\n\n[`FavoritableEntity`](FavoritableEntity.md).[`toJSON`](FavoritableEntity.md#tojson)\n\n***\n\n### unfavorite()\n\n> **unfavorite**(): `Promise`\\<`PropertiedEntity`\\<`Detail`\\>\\>\n\nRemove this entity from the user's favorites. Returns this handle for chaining.\n\n#### Returns\n\n`Promise`\\<`PropertiedEntity`\\<`Detail`\\>\\>\n\n#### Implementation of\n\n[`Propertied`](../interfaces/Propertied.md).[`unfavorite`](../interfaces/Propertied.md#unfavorite)\n\n#### Inherited from\n\n[`FavoritableEntity`](FavoritableEntity.md).[`unfavorite`](FavoritableEntity.md#unfavorite)\n\n***\n\n### updatePropertyOptions()\n\n> **updatePropertyOptions**(`changes`): `Promise`\\<[`BulkUpdateEntityPropertyOptionsResponse`](../../../../generated/properties/types.gen/type-aliases/BulkUpdateEntityPropertyOptionsResponse.md)\\>\n\nApply multi-select option deltas atomically across this entity's properties.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `changes` | [`PropertyOptionDelta`](../interfaces/PropertyOptionDelta.md)[] |\n\n#### Returns\n\n`Promise`\\<[`BulkUpdateEntityPropertyOptionsResponse`](../../../../generated/properties/types.gen/type-aliases/BulkUpdateEntityPropertyOptionsResponse.md)\\>\n\n\n<!-- src/entities/entity/interfaces/Favoritable.md -->\n# Interface: Favoritable\n\nAn entity that can be added to and removed from the user's favorites.\n\n## Extended by\n\n- [`Propertied`](Propertied.md)\n\n## Methods\n\n### favorite()\n\n> **favorite**(): `Promise`\\<`Favoritable`\\>\n\n#### Returns\n\n`Promise`\\<`Favoritable`\\>\n\n***\n\n### unfavorite()\n\n> **unfavorite**(): `Promise`\\<`Favoritable`\\>\n\n#### Returns\n\n`Promise`\\<`Favoritable`\\>\n\n\n<!-- src/entities/entity/interfaces/Propertied.md -->\n# Interface: Propertied\n\nA favoritable entity that also carries user-defined properties.\n\n## Extends\n\n- [`Favoritable`](Favoritable.md)\n\n## Methods\n\n### deleteProperty()\n\n> **deleteProperty**(`assignment`): `Promise`\\<`void`\\>\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `assignment` | [`EntityPropertyWithDefinition`](../../../../generated/properties/types.gen/type-aliases/EntityPropertyWithDefinition.md) |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### favorite()\n\n> **favorite**(): `Promise`\\<`Propertied`\\>\n\n#### Returns\n\n`Promise`\\<`Propertied`\\>\n\n#### Inherited from\n\n[`Favoritable`](Favoritable.md).[`favorite`](Favoritable.md#favorite)\n\n***\n\n### properties()\n\n> **properties**(`opts?`): `Promise`\\<[`EntityPropertyWithDefinition`](../../../../generated/properties/types.gen/type-aliases/EntityPropertyWithDefinition.md)[]\\>\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `opts?` | \\{ `includeMetadata?`: `boolean`; \\} |\n| `opts.includeMetadata?` | `boolean` |\n\n#### Returns\n\n`Promise`\\<[`EntityPropertyWithDefinition`](../../../../generated/properties/types.gen/type-aliases/EntityPropertyWithDefinition.md)[]\\>\n\n***\n\n### setProperty()\n\n> **setProperty**(`property`, `value?`): `Promise`\\<`void`\\>\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `property` | [`PropertyDefinition`](../../properties/property-definition/classes/PropertyDefinition.md) |\n| `value?` | [`SetPropertyValue`](../../../../generated/properties/types.gen/type-aliases/SetPropertyValue.md) |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### unfavorite()\n\n> **unfavorite**(): `Promise`\\<`Propertied`\\>\n\n#### Returns\n\n`Promise`\\<`Propertied`\\>\n\n#### Inherited from\n\n[`Favoritable`](Favoritable.md).[`unfavorite`](Favoritable.md#unfavorite)\n\n\n<!-- src/entities/entity/interfaces/PropertyOptionDelta.md -->\n# Interface: PropertyOptionDelta\n\nA delta to apply to one multi-select property.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-add\"></a> `add?` | [`PropertyOption`](../../properties/property-option/classes/PropertyOption.md)[] | Options to add to the property's current selection. |\n| <a id=\"property-property\"></a> `property` | [`PropertyDefinition`](../../properties/property-definition/classes/PropertyDefinition.md) | The multi-select property definition to update. |\n| <a id=\"property-remove\"></a> `remove?` | [`PropertyOption`](../../properties/property-option/classes/PropertyOption.md)[] | Options to remove from the property's current selection. |\n\n\n<!-- src/entities/entity/type-aliases/MacroEntityType.md -->\n# Type Alias: MacroEntityType\n\n> **MacroEntityType** = [`FavoriteEntityRef`](../../../../generated/storage/types.gen/type-aliases/FavoriteEntityRef.md)\\[`\"entityType\"`\\]\n\nHow the entity-addressed APIs (favorites) identify an entity's type.\n\n\n<!-- src/entities/messages/thread/classes/MessageThread.md -->\n# Class: MessageThread\n\nA shared message thread with resolution and deletion operations.\n\n## Extends\n\n- [`MacroEntity`](../../../entity/classes/MacroEntity.md)\\<[`ThreadState`](../../../../../generated/storage/types.gen/type-aliases/ThreadState.md)\\>\n\n## Properties\n\n| Property | Modifier | Type | Description | Inherited from |\n| ------ | ------ | ------ | ------ | ------ |\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-parent\"></a> `parent` | `readonly` | [`MessageParent`](../type-aliases/MessageParent.md) | The entity containing this thread. | - |\n| <a id=\"property-resolved\"></a> `resolved` | `readonly` | () => `Promise`\\<`boolean`\\> | Whether the thread is resolved. | - |\n\n## Methods\n\n### delete()\n\n> **delete**(`nonce?`): `Promise`\\<`void`\\>\n\nDelete the entire thread, including replies.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `nonce?` | `string` |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### toJSON()\n\n> **toJSON**(): \\{ `detail?`: [`ThreadState`](../../../../../generated/storage/types.gen/type-aliases/ThreadState.md); `id`: `string`; `parentId`: `string`; `parentType`: `\"channel\"` \\| `\"document\"` \\| `\"call\"` \\| `\"crm_company\"` \\| `\"crm_contact\"`; \\}\n\nSerialize identity with its owning resource.\n\n#### Returns\n\n\\{ `detail?`: [`ThreadState`](../../../../../generated/storage/types.gen/type-aliases/ThreadState.md); `id`: `string`; `parentId`: `string`; `parentType`: `\"channel\"` \\| `\"document\"` \\| `\"call\"` \\| `\"crm_company\"` \\| `\"crm_contact\"`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `detail?` | [`ThreadState`](../../../../../generated/storage/types.gen/type-aliases/ThreadState.md) |\n| `id` | `string` |\n| `parentId` | `string` |\n| `parentType` | `\"channel\"` \\| `\"document\"` \\| `\"call\"` \\| `\"crm_company\"` \\| `\"crm_contact\"` |\n\n#### Overrides\n\n[`MacroEntity`](../../../entity/classes/MacroEntity.md).[`toJSON`](../../../entity/classes/MacroEntity.md#tojson)\n\n***\n\n### update()\n\n> **update**(`options`): `Promise`\\<`void`\\>\n\nResolve the thread or detach its annotation anchor.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `options` | \\{ `detachAnchor?`: `boolean`; `nonce?`: `string`; `resolved?`: `boolean`; \\} |\n| `options.detachAnchor?` | `boolean` |\n| `options.nonce?` | `string` |\n| `options.resolved?` | `boolean` |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### byId()\n\n> `static` **byId**(`client`, `parent`, `id`): `MessageThread`\n\nConstruct a scoped thread handle.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `parent` | [`MessageParent`](../type-aliases/MessageParent.md) |\n| `id` | `string` |\n\n#### Returns\n\n`MessageThread`\n\n\n<!-- src/entities/messages/thread/functions/timeline.md -->\n# Function: timeline()\n\n> **timeline**\\<`TMessage`\\>(`client`, `parent`, `map`, `selection?`): `Promise`\\<\\{ `entries`: (\\{ `activity`: \\{ `action`: `string`; `actor`: [`User`](../../../users/user/classes/User.md); `actor_id`: `string`; `id`: `string`; `occurred_at`: `string`; `payload?`: `unknown`; \\}; `message?`: `undefined`; `type`: `\"activity\"`; \\} \\| \\{ `activity?`: `undefined`; `message`: `TMessage`; `type`: `\"message\"`; \\})[]; `nextCursor`: [`MessageCursor`](../../../../../generated/storage/types.gen/type-aliases/MessageCursor.md) \\| `undefined`; `previousCursor`: [`MessageCursor`](../../../../../generated/storage/types.gen/type-aliases/MessageCursor.md) \\| `undefined`; \\}\\>\n\nA bounded mixed message/activity page with typed message handles.\n\n## Type Parameters\n\n| Type Parameter |\n| ------ |\n| <a id=\"type-parameter-tmessage\"></a> `TMessage` *extends* [`TimelineMessage`](../type-aliases/TimelineMessage.md) |\n\n## Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `parent` | [`MessageParent`](../type-aliases/MessageParent.md) |\n| `map` | (`record`) => `TMessage` |\n| `selection?` | [`TimelineOptions`](../interfaces/TimelineOptions.md)\\<`TMessage`\\> |\n\n## Returns\n\n`Promise`\\<\\{ `entries`: (\\{ `activity`: \\{ `action`: `string`; `actor`: [`User`](../../../users/user/classes/User.md); `actor_id`: `string`; `id`: `string`; `occurred_at`: `string`; `payload?`: `unknown`; \\}; `message?`: `undefined`; `type`: `\"activity\"`; \\} \\| \\{ `activity?`: `undefined`; `message`: `TMessage`; `type`: `\"message\"`; \\})[]; `nextCursor`: [`MessageCursor`](../../../../../generated/storage/types.gen/type-aliases/MessageCursor.md) \\| `undefined`; `previousCursor`: [`MessageCursor`](../../../../../generated/storage/types.gen/type-aliases/MessageCursor.md) \\| `undefined`; \\}\\>\n\n\n<!-- src/entities/messages/thread/interfaces/TimelineOptions.md -->\n# Interface: TimelineOptions\\<TMessage\\>\n\nTimeline selection with typed message references and camel case options.\n\n## Type Parameters\n\n| Type Parameter | Default type |\n| ------ | ------ |\n| <a id=\"type-parameter-tmessage\"></a> `TMessage` *extends* [`TimelineMessage`](../type-aliases/TimelineMessage.md) | [`TimelineMessage`](../type-aliases/TimelineMessage.md) |\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-activityafter\"></a> `activityAfter?` | `string` | Inclusive activity lower bound. |\n| <a id=\"property-activitybefore\"></a> `activityBefore?` | `string` | Exclusive activity upper bound. |\n| <a id=\"property-anchored\"></a> `anchored?` | `boolean` | Select anchored threads. |\n| <a id=\"property-around\"></a> `around?` | `TMessage` | Fetch around this message. |\n| <a id=\"property-cursor\"></a> `cursor?` | [`MessageCursor`](../../../../../generated/storage/types.gen/type-aliases/MessageCursor.md) \\| `null` | Opaque continuation cursor from a previous page. |\n| <a id=\"property-direction\"></a> `direction?` | [`MessageDirection`](../../../../../generated/storage/types.gen/type-aliases/MessageDirection.md) | Page direction. |\n| <a id=\"property-includedeletedthreads\"></a> `includeDeletedThreads?` | `boolean` | Include deleted threads. |\n| <a id=\"property-limit\"></a> `limit?` | `number` | Page size. |\n| <a id=\"property-messages\"></a> `messages?` | `TMessage`[] | Restrict selection to these messages. |\n\n\n<!-- src/entities/messages/thread/type-aliases/MessageParent.md -->\n# Type Alias: MessageParent\n\n> **MessageParent** = \\{ `entity`: [`Channel`](../../../channels/channel/classes/Channel.md); `type`: `\"channel\"`; \\} \\| \\{ `entity`: [`Document`](../../../documents/document/classes/Document.md); `type`: `\"document\"`; \\} \\| \\{ `entity`: [`Company`](../../../crm/company/classes/Company.md); `type`: `\"crm_company\"`; \\} \\| \\{ `entity`: [`Contact`](../../../crm/contact/classes/Contact.md); `type`: `\"crm_contact\"`; \\} \\| \\{ `entity`: [`CallRecord`](../../../calls/call-record/classes/CallRecord.md); `type`: `\"call\"`; \\}\n\nThe typed parent of a shared message thread.\n\n\n<!-- src/entities/messages/thread/type-aliases/TimelineMessage.md -->\n# Type Alias: TimelineMessage\n\n> **TimelineMessage** = [`Message`](../../../channels/message/classes/Message.md) \\| [`Comment`](../../../documents/comment/classes/Comment.md) \\| [`CrmComment`](../../../crm/comment/classes/CrmComment.md) \\| [`CallMessage`](../../../calls/message/classes/CallMessage.md)\n\nA message handle accepted by a mixed timeline selector.\n\n\n<!-- src/entities/reference/type-aliases/EntityReference.md -->\n# Type Alias: EntityReference\n\n> **EntityReference** = \\{ `entity`: [`User`](../../users/user/classes/User.md); `type`: `\"user\"`; \\} \\| \\{ `entity`: [`Team`](../../teams/team/classes/Team.md); `type`: `\"team\"`; \\} \\| \\{ `entity`: [`Document`](../../documents/document/classes/Document.md); `type`: `\"document\"`; \\} \\| \\{ `entity`: [`Chat`](../../chats/chat/classes/Chat.md); `type`: `\"chat\"`; \\} \\| \\{ `entity`: [`Channel`](../../channels/channel/classes/Channel.md); `type`: `\"channel\"`; \\} \\| \\{ `entity`: [`Message`](../../channels/message/classes/Message.md); `type`: `\"channel_message\"`; \\} \\| \\{ `entity`: [`Project`](../../projects/project/classes/Project.md); `type`: `\"project\"`; \\} \\| \\{ `entity`: [`EmailThread`](../../email/thread/classes/EmailThread.md); `type`: `\"email_thread\"`; \\} \\| \\{ `entity`: [`CalendarEvent`](../../calendar/event/classes/CalendarEvent.md); `type`: `\"calendar_event\"`; \\} \\| \\{ `entity`: [`CallRecord`](../../calls/call-record/classes/CallRecord.md); `type`: `\"call\"`; \\} \\| \\{ `entity`: [`ForeignEntity`](../../foreign/foreign-entity/classes/ForeignEntity.md); `type`: `\"foreign_entity\"`; \\} \\| \\{ `entity`: [`Company`](../../crm/company/classes/Company.md); `type`: `\"crm_company\"`; \\} \\| \\{ `entity`: [`Contact`](../../crm/contact/classes/Contact.md); `type`: `\"crm_contact\"`; \\} \\| \\{ `entity`: [`CrmPipeline`](../../crm/pipeline/classes/CrmPipeline.md); `type`: `\"crm_pipeline\"`; \\} \\| \\{ `entity`: [`AgentSession`](../../agent-sessions/agent-session/classes/AgentSession.md); `type`: `\"agent_session\"`; \\} \\| \\{ `entity`: [`Routine`](../../routines/routine/classes/Routine.md); `type`: `\"scheduled_action\"`; \\} \\| \\{ `entity`: [`Initiative`](../../initiatives/initiative/classes/Initiative.md); `type`: `\"initiative\"`; \\} \\| \\{ `entity`: [`Database`](../../databases/database/classes/Database.md); `type`: `\"database\"`; \\} \\| \\{ `entity`: [`DatabaseRow`](../../databases/row/classes/DatabaseRow.md); `type`: `\"database_row\"`; \\} \\| \\{ `entity`: [`Form`](../../forms/form/classes/Form.md); `type`: `\"form\"`; \\}\n\nTyped entity references accepted by cross-resource APIs.\n\n\n<!-- src/entities/search/functions/entitySearch.md -->\n# Function: entitySearch()\n\n> **entitySearch**\\<`T`, `K`\\>(`opts`): (`client`, `query`, `searchOpts?`) => `AsyncGenerator`\\<`T`\\>\n\nBuild a `search(client, query, opts?)` function for one entity type: unified\nsearch hits narrowed to `type`, each mapped through `make`.\nMost relevant first, auto-paginated.\n\n## Type Parameters\n\n| Type Parameter |\n| ------ |\n| <a id=\"type-parameter-t\"></a> `T` |\n| <a id=\"type-parameter-k\"></a> `K` *extends* `\"email\"` \\| `\"project\"` \\| `\"chat\"` \\| `\"channel\"` \\| `\"document\"` \\| `\"call\"` \\| `\"company\"` \\| `\"calendarEvent\"` \\| `\"agentSession\"` \\| `\"channelMessage\"` |\n\n## Parameters\n\n| Parameter | Type | Description |\n| ------ | ------ | ------ |\n| `opts` | \\{ `filters?`: [`EntityFilters`](../../../../generated/search/types.gen/type-aliases/EntityFilters.md); `includeCrm?`: `boolean`; `make`: (`client`, `hit`) => `T`; `type`: `K`; \\} | - |\n| `opts.filters?` | [`EntityFilters`](../../../../generated/search/types.gen/type-aliases/EntityFilters.md) | - |\n| `opts.includeCrm?` | `boolean` | Opt in to CRM results (off by default server-side; required for company hits). |\n| `opts.make` | (`client`, `hit`) => `T` | - |\n| `opts.type` | `K` | - |\n\n## Returns\n\n(`client`, `query`, `searchOpts?`) => `AsyncGenerator`\\<`T`\\>\n\n\n<!-- src/entities/search/interfaces/SearchOpts.md -->\n# Interface: SearchOpts\n\n## Properties\n\n| Property | Type |\n| ------ | ------ |\n| <a id=\"property-pagesize\"></a> `pageSize?` | `number` |\n| <a id=\"property-searchon\"></a> `searchOn?` | [`SearchOn`](../type-aliases/SearchOn.md) |\n\n\n<!-- src/entities/search/type-aliases/SearchOn.md -->\n# Type Alias: SearchOn\n\n> **SearchOn** = `\"name\"` \\| `\"content\"` \\| `\"name_content\"`\n\n\n<!-- src/entities/sharing/access/classes/AccessRequest.md -->\n# Class: AccessRequest\n\nOne access request; resolutions preserve optimistic concurrency.\n\n## Extends\n\n- [`MacroEntity`](../../../entity/classes/MacroEntity.md)\\<[`AccessRequest`](../../../../../generated/storage/types.gen/type-aliases/AccessRequest.md)\\>\n\n## Properties\n\n| Property | Modifier | Type | Description | Inherited from |\n| ------ | ------ | ------ | ------ | ------ |\n| <a id=\"property-access\"></a> `access` | `readonly` | [`EntityAccess`](EntityAccess.md) | Entity access surface owning the request. | - |\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-requestedlevel\"></a> `requestedLevel` | `readonly` | () => `Promise`\\<[`AccessLevel`](../../../../../generated/storage/types.gen/type-aliases/AccessLevel.md)\\> | Requested access. | - |\n| <a id=\"property-requester\"></a> `requester` | `readonly` | () => `Promise`\\<[`User`](../../../users/user/classes/User.md)\\> | Requesting user. | - |\n| <a id=\"property-revision\"></a> `revision` | `readonly` | () => `Promise`\\<`number`\\> | Request revision. | - |\n| <a id=\"property-status\"></a> `status` | `readonly` | () => `Promise`\\<[`RequestStatus`](../../../../../generated/storage/types.gen/type-aliases/RequestStatus.md)\\> | Current request state. | - |\n\n## Methods\n\n### resolve()\n\n> **resolve**(`grantedLevel?`): `Promise`\\<`void`\\>\n\nApprove with an access level, or decline by omitting it.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `grantedLevel?` | [`AccessLevel`](../../../../../generated/storage/types.gen/type-aliases/AccessLevel.md) |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### toJSON()\n\n> **toJSON**(): \\{ `detail?`: [`AccessRequest`](../../../../../generated/storage/types.gen/type-aliases/AccessRequest.md); `id`: `string`; \\}\n\n#### Returns\n\n\\{ `detail?`: [`AccessRequest`](../../../../../generated/storage/types.gen/type-aliases/AccessRequest.md); `id`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `detail?` | [`AccessRequest`](../../../../../generated/storage/types.gen/type-aliases/AccessRequest.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### from()\n\n> `static` **from**(`client`, `access`, `record`): `AccessRequest`\n\nSeed a request from a state or submission response.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `access` | [`EntityAccess`](EntityAccess.md) |\n| `record` | [`AccessRequest`](../../../../../generated/storage/types.gen/type-aliases/AccessRequest.md) |\n\n#### Returns\n\n`AccessRequest`\n\n\n<!-- src/entities/sharing/access/classes/EntityAccess.md -->\n# Class: EntityAccess\n\nAccess requests and direct grants scoped to a shareable entity.\n\n## Constructors\n\n### Constructor\n\n> **new EntityAccess**(`client`, `entityType`, `entity`): `EntityAccess`\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `entityType` | [`ShareEntityType`](../../../../../generated/storage/types.gen/type-aliases/ShareEntityType.md) |\n| `entity` | \\{ `id`: `string`; \\} |\n| `entity.id` | `string` |\n\n#### Returns\n\n`EntityAccess`\n\n## Methods\n\n### cancel()\n\n> **cancel**(`revision`): `Promise`\\<`void`\\>\n\nCancel the caller's own request at its observed revision.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `revision` | `number` |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### direct()\n\n> **direct**(): `Promise`\\<\\{ `accessLevel`: [`AccessLevel`](../../../../../generated/storage/types.gen/type-aliases/AccessLevel.md); `user`: [`User`](../../../users/user/classes/User.md); \\}[]\\>\n\nDirect grants expressed as user handles.\n\n#### Returns\n\n`Promise`\\<\\{ `accessLevel`: [`AccessLevel`](../../../../../generated/storage/types.gen/type-aliases/AccessLevel.md); `user`: [`User`](../../../users/user/classes/User.md); \\}[]\\>\n\n***\n\n### grant()\n\n> **grant**(`user`, `accessLevel?`): `Promise`\\<`void`\\>\n\nGrant direct access, or remove it by omitting the access level.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `user` | [`User`](../../../users/user/classes/User.md) |\n| `accessLevel?` | [`AccessLevel`](../../../../../generated/storage/types.gen/type-aliases/AccessLevel.md) |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### remove()\n\n> **remove**(`user`): `Promise`\\<`void`\\>\n\nRemove one user's direct grant.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `user` | [`User`](../../../users/user/classes/User.md) |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### resolve()\n\n> **resolve**(`request`, `resolution`): `Promise`\\<[`AccessRequest`](../../../../../generated/storage/types.gen/type-aliases/AccessRequest.md)\\>\n\nResolve a request belonging to this entity at an observed revision.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `request` | [`AccessRequest`](AccessRequest.md) |\n| `resolution` | [`ResolveRequest`](../../../../../generated/storage/types.gen/type-aliases/ResolveRequest.md) |\n\n#### Returns\n\n`Promise`\\<[`AccessRequest`](../../../../../generated/storage/types.gen/type-aliases/AccessRequest.md)\\>\n\n***\n\n### state()\n\n> **state**(`offset?`): `Promise`\\<\\{ `accessLevel`: [`AccessLevel`](../../../../../generated/storage/types.gen/type-aliases/AccessLevel.md) \\| `undefined`; `canReview`: `boolean`; `mine`: [`AccessRequest`](AccessRequest.md) \\| `undefined`; `nextOffset`: `number` \\| `undefined`; `owner`: [`User`](../../../users/user/classes/User.md) \\| `undefined`; `pendingCount`: `number`; `requests`: [`AccessRequest`](AccessRequest.md)[]; `supportedLevels`: [`AccessLevel`](../../../../../generated/storage/types.gen/type-aliases/AccessLevel.md)[]; \\}\\>\n\nA page of access requests, including the caller's own request and review rights.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `offset?` | `number` |\n\n#### Returns\n\n`Promise`\\<\\{ `accessLevel`: [`AccessLevel`](../../../../../generated/storage/types.gen/type-aliases/AccessLevel.md) \\| `undefined`; `canReview`: `boolean`; `mine`: [`AccessRequest`](AccessRequest.md) \\| `undefined`; `nextOffset`: `number` \\| `undefined`; `owner`: [`User`](../../../users/user/classes/User.md) \\| `undefined`; `pendingCount`: `number`; `requests`: [`AccessRequest`](AccessRequest.md)[]; `supportedLevels`: [`AccessLevel`](../../../../../generated/storage/types.gen/type-aliases/AccessLevel.md)[]; \\}\\>\n\n***\n\n### submit()\n\n> **submit**(`requestedLevel`, `revision?`): `Promise`\\<[`AccessRequest`](AccessRequest.md)\\>\n\nRequest access, optionally naming the revision of an earlier request.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `requestedLevel` | [`AccessLevel`](../../../../../generated/storage/types.gen/type-aliases/AccessLevel.md) |\n| `revision?` | `number` |\n\n#### Returns\n\n`Promise`\\<[`AccessRequest`](AccessRequest.md)\\>\n\n***\n\n### toJSON()\n\n> **toJSON**(): \\{ `entity_id`: `string`; `entity_type`: [`ShareEntityType`](../../../../../generated/storage/types.gen/type-aliases/ShareEntityType.md); \\}\n\nSerialize the entity reference without credentials.\n\n#### Returns\n\n\\{ `entity_id`: `string`; `entity_type`: [`ShareEntityType`](../../../../../generated/storage/types.gen/type-aliases/ShareEntityType.md); \\}\n\n| Name | Type |\n| ------ | ------ |\n| `entity_id` | `string` |\n| `entity_type` | [`ShareEntityType`](../../../../../generated/storage/types.gen/type-aliases/ShareEntityType.md) |\n\n\n<!-- src/entities/sharing/permissions/functions/sharePermissionBody.md -->\n# Function: sharePermissionBody()\n\n> **sharePermissionBody**(`options`): [`UpdateSharePermissionRequestV2`](../../../../../generated/storage/types.gen/type-aliases/UpdateSharePermissionRequestV2.md)\n\nConvert sharing options into the generated backend contract.\n\n## Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `options` | [`SharePermissionOptions`](../type-aliases/SharePermissionOptions.md) |\n\n## Returns\n\n[`UpdateSharePermissionRequestV2`](../../../../../generated/storage/types.gen/type-aliases/UpdateSharePermissionRequestV2.md)\n\n\n<!-- src/entities/sharing/permissions/type-aliases/SharePermissionOptions.md -->\n# Type Alias: SharePermissionOptions\n\n> **SharePermissionOptions** = `Omit`\\<[`UpdateSharePermissionRequestV2`](../../../../../generated/storage/types.gen/type-aliases/UpdateSharePermissionRequestV2.md), `\"channelSharePermissions\"`\\> & \\{ `channelSharePermissions?`: \\{ `accessLevel?`: [`AccessLevel`](../../../../../generated/storage/types.gen/type-aliases/AccessLevel.md); `channel`: [`Channel`](../../../channels/channel/classes/Channel.md); `operation`: [`UpdateChannelSharePermission`](../../../../../generated/storage/types.gen/type-aliases/UpdateChannelSharePermission.md)\\[`\"operation\"`\\]; \\}[] \\| `null`; \\}\n\nSharing updates reference channels by handle. Null clears the corresponding grant collection.\n\n## Type Declaration\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `channelSharePermissions?` | \\{ `accessLevel?`: [`AccessLevel`](../../../../../generated/storage/types.gen/type-aliases/AccessLevel.md); `channel`: [`Channel`](../../../channels/channel/classes/Channel.md); `operation`: [`UpdateChannelSharePermission`](../../../../../generated/storage/types.gen/type-aliases/UpdateChannelSharePermission.md)\\[`\"operation\"`\\]; \\}[] \\| `null` | Channel grants to create or replace. |\n\n\n<!-- src/events/receiver/classes/MacroEvents.md -->\n# Class: MacroEvents\n\nPer-instance event receiver. Subscribe with [MacroEvents.on](#on), then\neither [MacroEvents.listen](#listen) (SSE, the default) or mount\n[MacroEvents.webhook](#webhook) at a persisted webhook URL.\n\nObtain via `macro.events` — do not construct directly.\n\n## Constructors\n\n### Constructor\n\n> **new MacroEvents**(`client`, `secret?`): `MacroEvents`\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `secret?` | `string` |\n\n#### Returns\n\n`MacroEvents`\n\n## Methods\n\n### handle()\n\n> **handle**(`rawBody`, `headers`): `Promise`\\<`void`\\>\n\nFeed a raw webhook delivery in: verifies the signature, parses, and\ndispatches to matching handlers.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `rawBody` | `string` |\n| `headers` | `DeliveryHeaders` |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n#### Throws\n\nif no signing secret was configured, or if the\n signature is missing or invalid.\n\n***\n\n### listen()\n\n> **listen**(`opts?`): `Promise`\\<() => `void`\\>\n\nOpen a live Server-Sent Events stream of matching broker events. This is\nthe default way to receive events — no public URL or signing secret\nrequired. Delivery is best-effort: events published before the\nconnection, while disconnected, or dropped for a slow subscriber are\nmissed; there is no replay.\n\nFilters default to the event names currently registered with [on](#on).\nThe stream uses those filters for its lifetime; later `.on` / unsubscribe\ncalls do not change what the server sends.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `opts?` | [`ListenOptions`](../interfaces/ListenOptions.md) |\n\n#### Returns\n\n`Promise`\\<() => `void`\\>\n\nA function that closes the stream.\n\n***\n\n### on()\n\n> **on**\\<`E`\\>(`event`, `handler`): () => `void`\n\nSubscribe to an event across all entities.\n\n#### Type Parameters\n\n| Type Parameter |\n| ------ |\n| <a id=\"type-parameter-e\"></a> `E` *extends* `\"agent_session.opened\"` \\| `\"agent_session.turn_started\"` \\| `\"agent_session.turn_ended\"` \\| `\"agent_session.command_rejected\"` \\| `\"agent_session.settled\"` \\| `\"agent_session.waiting_for_input\"` \\| `\"agent_session.input_received\"` \\| `\"agent_session.mentioned\"` \\| `\"agent_session.stopped\"` \\| `\"agent_session.renamed\"` \\| `\"agent_session.deleted\"` \\| `\"channel.picture_changed\"` \\| `\"channel.created\"` \\| `\"channel.updated\"` \\| `\"channel.deleted\"` \\| `\"channel.participant_added\"` \\| `\"channel.participant_removed\"` \\| `\"document.created\"` \\| `\"document.updated\"` \\| `\"document.deleted\"` \\| `\"document.content_uploaded\"` \\| `\"document.sync_content_updated\"` \\| `\"document.purged\"` \\| `\"document.copied\"` \\| `\"document.interaction\"` \\| `\"message.posted\"` \\| `\"message.patched\"` \\| `\"message.deleted\"` \\| `\"message.mentioned\"` \\| `\"message.attachment_created\"` \\| `\"message.attachment_removed\"` |\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `event` | `E` |\n| `handler` | `EventHandler`\\<`E`\\> |\n\n#### Returns\n\nAn unsubscribe function.\n\n() => `void`\n\n***\n\n### onSelfMention()\n\n> **onSelfMention**(`handler`): () => `void`\n\nSubscribe to @-mentions of the authenticated caller: `message.mentioned`\ndeliveries whose mentioned entity is this bot (bot auth) or this user\n(user auth), in channels and in document comments alike.\n\n`message.mentioned` deliveries cover every mention the stream's (or\nwebhook's) workspace can access (its `ids` filter holds channel or\ndocument ids); picking out \"me\" happens here, client-side. The caller's\nidentity is resolved lazily (once) on the first delivery.\n\nFor SSE, register this handler before [listen](#listen) so the derived\nfilters include `message.mentioned`. For persisted webhooks, register the\nwebhook separately, e.g. `macro.webhooks.create({ filters: [{ events:\n['message.mentioned'] }], … })`.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `handler` | `EventHandler`\\<`\"message.mentioned\"`\\> |\n\n#### Returns\n\nAn unsubscribe function.\n\n() => `void`\n\n***\n\n### webhook()\n\n> **webhook**(): (`req`) => `Promise`\\<`Response`\\>\n\nA Fetch-style handler to mount at your persisted webhook route.\n\nRequires `webhookSecret` (or `MACRO_WEBHOOK_SECRET`).\n\n#### Returns\n\n(`req`) => `Promise`\\<`Response`\\>\n\n#### Example\n\n```ts\napp.post('/webhook', macro.events.webhook()); // Hono\n```\n\n\n<!-- src/events/receiver/interfaces/ListenOptions.md -->\n# Interface: ListenOptions\n\nOptions for [MacroEvents.listen](../classes/MacroEvents.md#listen).\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-filters\"></a> `filters?` | [`WebhookFilter`](../../../../generated/storage/types.gen/type-aliases/WebhookFilter.md)[] | Event/entity-id filters, identical to persisted webhook `filters`. Defaults to one filter covering every event currently registered with [MacroEvents.on](../classes/MacroEvents.md#on). |\n| <a id=\"property-scope\"></a> `scope?` | [`WebhookScope`](../../../../generated/storage/types.gen/type-aliases/WebhookScope.md) | Personal or team workspace whose webhook lifecycle events are delivered. Defaults to `'user'`. |\n| <a id=\"property-signal\"></a> `signal?` | `AbortSignal` | Abort the stream. |\n\n\n<!-- src/macro/classes/Macro.md -->\n# Class: Macro\\<T\\>\n\n## Type Parameters\n\n| Type Parameter | Default type |\n| ------ | ------ |\n| <a id=\"type-parameter-t\"></a> `T` *extends* [`MacroOpts`](../../config/interfaces/MacroOpts.md) | [`MacroOpts`](../../config/interfaces/MacroOpts.md) |\n\n## Constructors\n\n### Constructor\n\n> **new Macro**\\<`T`\\>(`opts`): `Macro`\\<`T`\\>\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `opts` | `T` |\n\n#### Returns\n\n`Macro`\\<`T`\\>\n\n## Properties\n\n| Property | Modifier | Type | Description |\n| ------ | ------ | ------ | ------ |\n| <a id=\"property-_client\"></a> `_client` | `readonly` | `MacroClient` | Direct access to the underlying hey-api service clients. |\n| <a id=\"property-agents\"></a> `agents` | `readonly` | [`AgentNamespace`](../../entities/agents/namespace/classes/AgentNamespace.md) | agents resources and operations. |\n| <a id=\"property-agentsessions\"></a> `agentSessions` | `readonly` | [`AgentSessionNamespace`](../../entities/agent-sessions/namespace/classes/AgentSessionNamespace.md) | - |\n| <a id=\"property-ai\"></a> `ai` | `readonly` | [`AiNamespace`](../../entities/ai/namespace/classes/AiNamespace.md) | - |\n| <a id=\"property-apikeys\"></a> `apiKeys` | `readonly` | [`ApiKeyNamespace`](../../entities/api-keys/namespace/classes/ApiKeyNamespace.md) | apiKeys resources and operations. |\n| <a id=\"property-bots\"></a> `bots` | `readonly` | [`BotsNamespace`](../../entities/bots/namespace/classes/BotsNamespace.md) | - |\n| <a id=\"property-calendar\"></a> `calendar` | `readonly` | [`CalendarNamespace`](../../entities/calendar/namespace/classes/CalendarNamespace.md) | - |\n| <a id=\"property-calls\"></a> `calls` | `readonly` | [`CallRecordNamespace`](../../entities/calls/namespace/classes/CallRecordNamespace.md) | - |\n| <a id=\"property-channels\"></a> `channels` | `readonly` | [`ChannelNamespace`](../../entities/channels/namespace/classes/ChannelNamespace.md) | - |\n| <a id=\"property-crm\"></a> `crm` | `readonly` | [`CrmNamespace`](../../entities/crm/namespace/classes/CrmNamespace.md) | - |\n| <a id=\"property-databases\"></a> `databases` | `readonly` | [`DatabaseNamespace`](../../entities/databases/namespace/classes/DatabaseNamespace.md) | - |\n| <a id=\"property-documents\"></a> `documents` | `readonly` | [`DocumentNamespace`](../../entities/documents/namespace/classes/DocumentNamespace.md) | - |\n| <a id=\"property-email\"></a> `email` | `readonly` | [`EmailNamespace`](../../entities/email/namespace/classes/EmailNamespace.md) | - |\n| <a id=\"property-entitymentions\"></a> `entityMentions` | `readonly` | [`EntityMentionNamespace`](../../entities/entity-mentions/namespace/classes/EntityMentionNamespace.md) | entityMentions resources and operations. |\n| <a id=\"property-events\"></a> `events` | `readonly` | [`MacroEvents`](../../events/receiver/classes/MacroEvents.md) | - |\n| <a id=\"property-favorites\"></a> `favorites` | `readonly` | [`FavoritesNamespace`](../../entities/favorites/namespace/classes/FavoritesNamespace.md) | - |\n| <a id=\"property-foreignentities\"></a> `foreignEntities` | `readonly` | [`ForeignEntityNamespace`](../../entities/foreign/namespace/classes/ForeignEntityNamespace.md) | - |\n| <a id=\"property-forms\"></a> `forms` | `readonly` | [`FormNamespace`](../../entities/forms/namespace/classes/FormNamespace.md) | Build forms and submit answers without granting respondents database access. |\n| <a id=\"property-githubpullrequests\"></a> `githubPullRequests` | `readonly` | [`GithubPullRequestNamespace`](../../entities/github-pull-requests/namespace/classes/GithubPullRequestNamespace.md) | githubPullRequests resources and operations. |\n| <a id=\"property-harnesses\"></a> `harnesses` | `readonly` | [`HarnessNamespace`](../../entities/harnesses/namespace/classes/HarnessNamespace.md) | harnesses resources and operations. |\n| <a id=\"property-initiatives\"></a> `initiatives` | `readonly` | [`InitiativeNamespace`](../../entities/initiatives/namespace/classes/InitiativeNamespace.md) | initiatives resources and operations. |\n| <a id=\"property-meetings\"></a> `meetings` | `readonly` | [`MeetingNamespace`](../../entities/meetings/namespace/classes/MeetingNamespace.md) | meetings resources and operations. |\n| <a id=\"property-notifications\"></a> `notifications` | `readonly` | [`NotificationNamespace`](../../entities/notifications/namespace/classes/NotificationNamespace.md) | - |\n| <a id=\"property-pins\"></a> `pins` | `readonly` | [`PinsNamespace`](../../entities/pins/namespace/classes/PinsNamespace.md) | - |\n| <a id=\"property-projects\"></a> `projects` | `readonly` | [`ProjectNamespace`](../../entities/projects/namespace/classes/ProjectNamespace.md) | - |\n| <a id=\"property-properties\"></a> `properties` | `readonly` | [`PropertiesNamespace`](../../entities/properties/namespace/classes/PropertiesNamespace.md) | - |\n| <a id=\"property-routines\"></a> `routines` | `readonly` | [`RoutineNamespace`](../../entities/routines/namespace/classes/RoutineNamespace.md) | routines resources and operations. |\n| <a id=\"property-tasks\"></a> `tasks` | `readonly` | [`TaskNamespace`](../../entities/tasks/namespace/classes/TaskNamespace.md) | - |\n| <a id=\"property-teams\"></a> `teams` | `readonly` | [`TeamNamespace`](../../entities/teams/namespace/classes/TeamNamespace.md) | - |\n| <a id=\"property-unfurls\"></a> `unfurls` | `readonly` | [`UnfurlNamespace`](../../entities/unfurls/namespace/classes/UnfurlNamespace.md) | unfurls resources and operations. |\n| <a id=\"property-users\"></a> `users` | `readonly` | [`UserNamespace`](../../entities/users/namespace/classes/UserNamespace.md) | - |\n| <a id=\"property-webappurl\"></a> `webAppUrl` | `readonly` | `string` | Base URL of the Macro web app, used to build entity URLs. |\n| <a id=\"property-webhooks\"></a> `webhooks` | `readonly` | [`WebhooksNamespace`](../../entities/webhooks/namespace/classes/WebhooksNamespace.md) | - |\n\n## Methods\n\n### myPrincipalId()\n\n> **myPrincipalId**(): `Promise`\\<`string`\\>\n\nThe authenticated caller's mentionable principal — `bot|<uuid>` for bot\nauth, `macro|<email>` for user auth — fetched once and cached.\n\n#### Returns\n\n`Promise`\\<`string`\\>\n\n***\n\n### requestedAs()\n\n> **requestedAs**(`user`): `Macro`\\<`T`\\>\n\nClone of this SDK acting on behalf of `user` (sent as\n`x-macro-bot-for-macro-user-id`). Bot auth only — throws for user auth,\nsince a user token always acts as its own user.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `user` | [`User`](../../entities/users/user/classes/User.md) |\n\n#### Returns\n\n`Macro`\\<`T`\\>\n\n\n<!-- src/macro/type-aliases/RequestActivity.md -->\n# Type Alias: RequestActivity\n\n> **RequestActivity** = \\{ `id`: `number`; `operation`: `string`; `service`: `string`; `status`: `\"started\"` \\| `\"completed\"` \\| `\"failed\"`; \\}\n\nA generated SDK operation lifecycle. Contains no arguments, URLs or response data.\n\n## Properties\n\n| Property | Type |\n| ------ | ------ |\n| <a id=\"property-id\"></a> `id` | `number` |\n| <a id=\"property-operation\"></a> `operation` | `string` |\n| <a id=\"property-service\"></a> `service` | `string` |\n| <a id=\"property-status\"></a> `status` | `\"started\"` \\| `\"completed\"` \\| `\"failed\"` |\n\n\n<!-- src/mentions/functions/msg.md -->\n# Function: msg()\n\n> **msg**(`strings`, ...`values`): [`RichMessage`](../interfaces/RichMessage.md)\n\nCompose a rich message. Interpolate mentions (a User, Document,\n[here](../variables/here.md), …) or plain strings. Each mention writes its `<m-*>` tag into the\ncontent *and* adds itself to `mentions[]`, so the two can never drift; strings\nare inserted as-is, so markdown like `**bold**` passes through untouched.\n\n## Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `strings` | `TemplateStringsArray` |\n| ...`values` | [`Interpolation`](../type-aliases/Interpolation.md)[] |\n\n## Returns\n\n[`RichMessage`](../interfaces/RichMessage.md)\n\n## Example\n\n```ts\nchannel.send(msg`Hey ${user}, see ${doc}. cc ${here}`);\nchannel.send(msg`Status: ${status} — see ${doc}`);\n```\n\n\n<!-- src/mentions/functions/toBody.md -->\n# Function: toBody()\n\n> **toBody**(`body`): [`RichMessage`](../interfaces/RichMessage.md)\n\nNormalize a plain string or a [RichMessage](../interfaces/RichMessage.md) to the wire shape.\n\n## Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `body` | `string` \\| [`RichMessage`](../interfaces/RichMessage.md) |\n\n## Returns\n\n[`RichMessage`](../interfaces/RichMessage.md)\n\n\n<!-- src/mentions/functions/wrapXml.md -->\n# Function: wrapXml()\n\n> **wrapXml**(`tag`, `data`): `string`\n\nSerialize a mention node to its `<tag>{json}</tag>` wire form.\n\n## Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `tag` | `string` |\n| `data` | `unknown` |\n\n## Returns\n\n`string`\n\n\n<!-- src/mentions/interfaces/MentionPart.md -->\n# Interface: MentionPart\n\nThe two things a mentionable entity contributes to a message.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-mention\"></a> `mention` | [`SimpleMention`](../../../generated/storage/types.gen/type-aliases/SimpleMention.md) | The parallel entry the backend uses for notifications and permissions. |\n| <a id=\"property-tag\"></a> `tag` | `string` | The `<m-*>` tag written into the message content. |\n\n\n<!-- src/mentions/interfaces/Mentionable.md -->\n# Interface: Mentionable\n\nAnything that can be dropped into a [msg](../functions/msg.md) template as a mention.\n\n## Methods\n\n### toMention()\n\n> **toMention**(): [`MentionPart`](MentionPart.md)\n\n#### Returns\n\n[`MentionPart`](MentionPart.md)\n\n\n<!-- src/mentions/interfaces/RichMessage.md -->\n# Interface: RichMessage\n\nA composed message body: content with embedded tags, and the matching mentions.\n\n## Properties\n\n| Property | Type |\n| ------ | ------ |\n| <a id=\"property-content\"></a> `content` | `string` |\n| <a id=\"property-mentions\"></a> `mentions` | [`SimpleMention`](../../../generated/storage/types.gen/type-aliases/SimpleMention.md)[] |\n\n\n<!-- src/mentions/type-aliases/Interpolation.md -->\n# Type Alias: Interpolation\n\n> **Interpolation** = [`Mentionable`](../interfaces/Mentionable.md) \\| `string` \\| `number`\n\nWhat may be interpolated into a [msg](../functions/msg.md) template: a mention, or plain text.\n\n\n<!-- src/mentions/variables/here.md -->\n# Variable: here\n\n> `const` **here**: [`Mentionable`](../interfaces/Mentionable.md)\n\nThe `@here` group mention.\n\n\n<!-- src/utils/lazy/classes/Lazy.md -->\n# Class: Lazy\\<T\\>\n\nA value fetched on first access and cached thereafter. Powers thin entity\nhandles: construction is free, the record is loaded lazily the first time a\nfield is read, and concurrent reads share one in-flight request. Pass a\n`seed` when the record is already known (from a list or an event) to skip the\nfetch entirely.\n\n## Type Parameters\n\n| Type Parameter |\n| ------ |\n| <a id=\"type-parameter-t\"></a> `T` |\n\n## Constructors\n\n### Constructor\n\n> **new Lazy**\\<`T`\\>(`loader`, `seed?`): `Lazy`\\<`T`\\>\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `loader` | () => `Promise`\\<`T`\\> |\n| `seed?` | `T` |\n\n#### Returns\n\n`Lazy`\\<`T`\\>\n\n## Methods\n\n### clear()\n\n> **clear**(): `void`\n\nDrop the cached value so the next read refetches.\n\n#### Returns\n\n`void`\n\n***\n\n### get()\n\n> **get**(): `Promise`\\<`T`\\>\n\n#### Returns\n\n`Promise`\\<`T`\\>\n\n***\n\n### peek()\n\n> **peek**(): `T` \\| `undefined`\n\nThe cached value, if already loaded — never triggers a fetch.\n\n#### Returns\n\n`T` \\| `undefined`\n\n\n<!-- src/utils/pagination/functions/paginate.md -->\n# Function: paginate()\n\n> **paginate**\\<`T`, `Cursor`\\>(`fetchPage`): `AsyncGenerator`\\<`T`\\>\n\nAsync generator over a cursor-paginated API. Iterate with `for await`.\nCursors are plain JSON values (strings or small objects), so a page whose\nnext cursor serialises identically to the one it was fetched with means the\nserver is not advancing; the generator throws instead of looping forever.\n\n## Type Parameters\n\n| Type Parameter | Default type |\n| ------ | ------ |\n| <a id=\"type-parameter-t\"></a> `T` | - |\n| <a id=\"type-parameter-cursor\"></a> `Cursor` | `string` |\n\n## Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `fetchPage` | (`cursor?`) => `Promise`\\<[`Page`](../interfaces/Page.md)\\<`T`, `Cursor`\\>\\> |\n\n## Returns\n\n`AsyncGenerator`\\<`T`\\>\n\n\n<!-- src/utils/pagination/interfaces/Page.md -->\n# Interface: Page\\<T, Cursor\\>\n\nOne page of a cursor-paginated list.\n\n## Type Parameters\n\n| Type Parameter | Default type |\n| ------ | ------ |\n| <a id=\"type-parameter-t\"></a> `T` | - |\n| <a id=\"type-parameter-cursor\"></a> `Cursor` | `string` |\n\n## Properties\n\n| Property | Type |\n| ------ | ------ |\n| <a id=\"property-items\"></a> `items` | `T`[] |\n| <a id=\"property-nextcursor\"></a> `nextCursor?` | `Cursor` \\| `null` |\n\n\n<!-- src/utils/unwrap/classes/MacroApiError.md -->\n# Class: MacroApiError\n\nA non-2xx HTTP response (Macro API, or a raw fetch like presigned downloads).\n\n## Extends\n\n- [`MacroError`](MacroError.md)\n\n## Extended by\n\n- [`MacroOpRefusedError`](../../../entities/databases/database/classes/MacroOpRefusedError.md)\n\n## Constructors\n\n### Constructor\n\n> **new MacroApiError**(`status`, `data`): `MacroApiError`\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `status` | `number` |\n| `data` | `unknown` |\n\n#### Returns\n\n`MacroApiError`\n\n#### Overrides\n\n[`MacroError`](MacroError.md).[`constructor`](MacroError.md#constructor)\n\n## Properties\n\n| Property | Modifier | Type |\n| ------ | ------ | ------ |\n| <a id=\"property-data\"></a> `data` | `readonly` | `unknown` |\n| <a id=\"property-status\"></a> `status` | `readonly` | `number` |\n\n\n<!-- src/utils/unwrap/classes/MacroError.md -->\n# Class: MacroError\n\nBase for every error the SDK throws.\n\n## Extends\n\n- `Error`\n\n## Extended by\n\n- [`MacroApiError`](MacroApiError.md)\n- [`MacroNotFoundError`](MacroNotFoundError.md)\n\n## Constructors\n\n### Constructor\n\n> **new MacroError**(`message`): `MacroError`\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `message` | `string` |\n\n#### Returns\n\n`MacroError`\n\n#### Overrides\n\n`Error.constructor`\n\n\n<!-- src/utils/unwrap/classes/MacroNotFoundError.md -->\n# Class: MacroNotFoundError\n\nThe API succeeded but the addressed entity doesn't exist in the result.\n\n## Extends\n\n- [`MacroError`](MacroError.md)\n\n## Constructors\n\n### Constructor\n\n> **new MacroNotFoundError**(`message`): `MacroNotFoundError`\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `message` | `string` |\n\n#### Returns\n\n`MacroNotFoundError`\n\n#### Overrides\n\n[`MacroError`](MacroError.md).[`constructor`](MacroError.md#constructor)\n\n\n<!-- src/utils/unwrap/functions/unwrap.md -->\n# Function: unwrap()\n\n> **unwrap**\\<`TData`, `TError`\\>(`res`): `TData`\n\nTurn a hey-api `{ data, error, response? }` result into either the success\npayload or a thrown MacroApiError.\n\n## Type Parameters\n\n| Type Parameter |\n| ------ |\n| <a id=\"type-parameter-tdata\"></a> `TData` |\n| <a id=\"type-parameter-terror\"></a> `TError` |\n\n## Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `res` | \\{ `data?`: `TData`; `error?`: `TError`; `response?`: `Response`; \\} |\n| `res.data?` | `TData` |\n| `res.error?` | `TError` |\n| `res.response?` | `Response` |\n\n## Returns\n\n`TData`\n"
+ "documentation": "# Macro SDK: core\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/properties/types.gen/type-aliases/BulkUpdateEntityPropertyOptionsResponse.md -->\n# Type Alias: BulkUpdateEntityPropertyOptionsResponse\n\n> **BulkUpdateEntityPropertyOptionsResponse** = \\{ `properties`: [`EntityPropertyOptionSelectionResponse`](EntityPropertyOptionSelectionResponse.md)[]; \\}\n\nResponse for a bulk option update: each property's reconciled final ids.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-properties\"></a> `properties` | [`EntityPropertyOptionSelectionResponse`](EntityPropertyOptionSelectionResponse.md)[] | The final option ids per updated property. |\n\n\n<!-- generated/properties/types.gen/type-aliases/DataType.md -->\n# Type Alias: DataType\n\n> **DataType** = `\"BOOLEAN\"` \\| `\"DATE\"` \\| `\"NUMBER\"` \\| `\"STRING\"` \\| `\"SELECT_NUMBER\"` \\| `\"SELECT_STRING\"` \\| `\"TAG\"` \\| `\"ENTITY\"` \\| `\"LINK\"`\n\nData type for property values, determining storage and validation.\n\n\n<!-- generated/properties/types.gen/type-aliases/EntityProperty.md -->\n# Type Alias: EntityProperty\n\n> **EntityProperty** = \\{ `created_at`: `string`; `entity_id`: `string`; `entity_type`: [`EntityType`](EntityType.md); `id`: `string`; `property_definition_id`: `string`; `updated_at`: `string`; \\}\n\nAssignment of a property definition to a specific entity (service representation).\n\n## Properties\n\n| Property | Type |\n| ------ | ------ |\n| <a id=\"property-created_at\"></a> `created_at` | `string` |\n| <a id=\"property-entity_id\"></a> `entity_id` | `string` |\n| <a id=\"property-entity_type\"></a> `entity_type` | [`EntityType`](EntityType.md) |\n| <a id=\"property-id\"></a> `id` | `string` |\n| <a id=\"property-property_definition_id\"></a> `property_definition_id` | `string` |\n| <a id=\"property-updated_at\"></a> `updated_at` | `string` |\n\n\n<!-- generated/properties/types.gen/type-aliases/EntityPropertyOptionSelectionResponse.md -->\n# Type Alias: EntityPropertyOptionSelectionResponse\n\n> **EntityPropertyOptionSelectionResponse** = \\{ `option_ids`: `string`[]; `property_id`: `string`; \\}\n\nThe reconciled final option ids stored for one property after a bulk update.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-option_ids\"></a> `option_ids` | `string`[] | The final option ids the server persisted, in stored order. |\n| <a id=\"property-property_id\"></a> `property_id` | `string` | The property definition the options belong to. |\n\n\n<!-- generated/properties/types.gen/type-aliases/EntityPropertyWithDefinition.md -->\n# Type Alias: EntityPropertyWithDefinition\n\n> **EntityPropertyWithDefinition** = \\{ `definition`: [`PropertyDefinition`](PropertyDefinition.md); `options?`: [`PropertyOption`](PropertyOption.md)[] \\| `null`; `property`: [`EntityProperty`](EntityProperty.md); `value?`: `null` \\| [`PropertyValue`](PropertyValue.md); \\}\n\nEntity property with its definition, value, and options (service representation).\n\n## Properties\n\n| Property | Type |\n| ------ | ------ |\n| <a id=\"property-definition\"></a> `definition` | [`PropertyDefinition`](PropertyDefinition.md) |\n| <a id=\"property-options\"></a> `options?` | [`PropertyOption`](PropertyOption.md)[] \\| `null` |\n| <a id=\"property-property\"></a> `property` | [`EntityProperty`](EntityProperty.md) |\n| <a id=\"property-value\"></a> `value?` | `null` \\| [`PropertyValue`](PropertyValue.md) |\n\n\n<!-- generated/properties/types.gen/type-aliases/EntityReference.md -->\n# Type Alias: EntityReference\n\n> **EntityReference** = \\{ `entity_id`: `string`; `entity_type`: [`EntityType`](EntityType.md); `specific_message_id?`: `string` \\| `null`; \\}\n\nEntity reference for entity-type property values.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-entity_id\"></a> `entity_id` | `string` | - |\n| <a id=\"property-entity_type\"></a> `entity_type` | [`EntityType`](EntityType.md) | - |\n| <a id=\"property-specific_message_id\"></a> `specific_message_id?` | `string` \\| `null` | For CHANNEL, CHAT, THREAD entity types - optional specific message ID. This allows referencing a specific message within a thread/channel/chat. |\n\n\n<!-- generated/properties/types.gen/type-aliases/EntityType.md -->\n# Type Alias: EntityType\n\n> **EntityType** = `\"CALENDAR_EVENT\"` \\| `\"CALL_RECORD\"` \\| `\"CHANNEL\"` \\| `\"CHAT\"` \\| `\"COMPANY\"` \\| `\"DATABASE_ROW\"` \\| `\"CONTACT\"` \\| `\"DOCUMENT\"` \\| `\"INITIATIVE\"` \\| `\"PROJECT\"` \\| `\"TASK\"` \\| `\"THREAD\"` \\| `\"USER\"`\n\nType of entity that can be referenced by entity properties.\n\n\n<!-- generated/properties/types.gen/type-aliases/PropertyDefinition.md -->\n# Type Alias: PropertyDefinition\n\n> **PropertyDefinition** = \\{ `created_at`: `string`; `data_type`: [`DataType`](DataType.md); `display_name`: `string`; `id`: `string`; `is_metadata`: `boolean`; `is_multi_select`: `boolean`; `is_system`: `boolean`; `owner`: [`PropertyOwner`](PropertyOwner.md); `specific_entity_type`: `null` \\| [`EntityType`](EntityType.md); `updated_at`: `string`; \\}\n\nProperty definition model (service representation).\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-created_at\"></a> `created_at` | `string` | - |\n| <a id=\"property-data_type\"></a> `data_type` | [`DataType`](DataType.md) | - |\n| <a id=\"property-display_name\"></a> `display_name` | `string` | - |\n| <a id=\"property-id\"></a> `id` | `string` | - |\n| <a id=\"property-is_metadata\"></a> `is_metadata` | `boolean` | Flag to indicate if this is a system-generated metadata property. Not stored in database - computed at service layer. |\n| <a id=\"property-is_multi_select\"></a> `is_multi_select` | `boolean` | - |\n| <a id=\"property-is_system\"></a> `is_system` | `boolean` | Flag to indicate if this is a system property (stored in DB). |\n| <a id=\"property-owner\"></a> `owner` | [`PropertyOwner`](PropertyOwner.md) | - |\n| <a id=\"property-specific_entity_type\"></a> `specific_entity_type` | `null` \\| [`EntityType`](EntityType.md) | - |\n| <a id=\"property-updated_at\"></a> `updated_at` | `string` | - |\n\n\n<!-- generated/properties/types.gen/type-aliases/PropertyOption.md -->\n# Type Alias: PropertyOption\n\n> **PropertyOption** = \\{ `color`: `string` \\| `null`; `created_at`: `string`; `display_order`: `number`; `id`: `string`; `property_definition_id`: `string`; `updated_at`: `string`; `value`: [`PropertyOptionValue`](PropertyOptionValue.md); \\}\n\nA selectable option for select-type properties (service representation).\n\n## Properties\n\n| Property | Type |\n| ------ | ------ |\n| <a id=\"property-color\"></a> `color` | `string` \\| `null` |\n| <a id=\"property-created_at\"></a> `created_at` | `string` |\n| <a id=\"property-display_order\"></a> `display_order` | `number` |\n| <a id=\"property-id\"></a> `id` | `string` |\n| <a id=\"property-property_definition_id\"></a> `property_definition_id` | `string` |\n| <a id=\"property-updated_at\"></a> `updated_at` | `string` |\n| <a id=\"property-value\"></a> `value` | [`PropertyOptionValue`](PropertyOptionValue.md) |\n\n\n<!-- generated/properties/types.gen/type-aliases/PropertyOptionValue.md -->\n# Type Alias: PropertyOptionValue\n\n> **PropertyOptionValue** = \\{ `type`: `\"string\"`; `value`: `string`; \\} \\| \\{ `type`: `\"number\"`; `value`: `number`; \\}\n\nThe value of a property option - either a string or a number.\n\n## Union Members\n\n### Type Literal\n\n\\{ `type`: `\"string\"`; `value`: `string`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `type` | `\"string\"` | - |\n| `value` | `string` | String value for SelectString properties |\n\n***\n\n### Type Literal\n\n\\{ `type`: `\"number\"`; `value`: `number`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `type` | `\"number\"` | - |\n| `value` | `number` | Number value for SelectNumber properties |\n\n\n<!-- generated/properties/types.gen/type-aliases/PropertyOwner.md -->\n# Type Alias: PropertyOwner\n\n> **PropertyOwner** = \\{ `scope`: `\"user\"`; `user_id`: `string`; \\} \\| \\{ `scope`: `\"team\"`; `team_id`: `string`; \\} \\| \\{ `database_id`: `string`; `scope`: `\"database\"`; \\} \\| \\{ `scope`: `\"system\"`; \\}\n\nDefines who owns a property - user-scoped, team-scoped, database-scoped, or system.\n\n\n<!-- generated/properties/types.gen/type-aliases/PropertyTargetEntityType.md -->\n# Type Alias: PropertyTargetEntityType\n\n> **PropertyTargetEntityType** = `\"CALL_RECORD\"` \\| `\"CHANNEL\"` \\| `\"CHAT\"` \\| `\"COMPANY\"` \\| `\"DATABASE_ROW\"` \\| `\"DOCUMENT\"` \\| `\"INITIATIVE\"` \\| `\"PROJECT\"` \\| `\"THREAD\"` \\| `\"USER\"`\n\nCanonical type of an entity receiving properties.\n\nTasks are documents at API boundaries. `Task` intentionally does not exist\nhere; task classification is resolved by the properties domain from the\ndocument subtype.\n\n\n<!-- generated/properties/types.gen/type-aliases/PropertyTargetReference.md -->\n# Type Alias: PropertyTargetReference\n\n> **PropertyTargetReference** = \\{ `entity_id`: `string`; `entity_type`: [`PropertyTargetEntityType`](PropertyTargetEntityType.md); \\}\n\nCanonical reference to an entity receiving properties.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-entity_id\"></a> `entity_id` | `string` | Entity identifier. |\n| <a id=\"property-entity_type\"></a> `entity_type` | [`PropertyTargetEntityType`](PropertyTargetEntityType.md) | Canonical entity type. |\n\n\n<!-- generated/properties/types.gen/type-aliases/PropertyValue.md -->\n# Type Alias: PropertyValue\n\n> **PropertyValue** = \\{ `type`: `\"Boolean\"`; `value`: `boolean`; \\} \\| \\{ `type`: `\"Number\"`; `value`: `number`; \\} \\| \\{ `type`: `\"String\"`; `value`: `string`; \\} \\| \\{ `type`: `\"Date\"`; `value`: `string`; \\} \\| \\{ `type`: `\"SelectOption\"`; `value`: `string`[]; \\} \\| \\{ `type`: `\"EntityReference\"`; `value`: [`EntityReference`](EntityReference.md)[]; \\} \\| \\{ `type`: `\"Link\"`; `value`: `string`[]; \\}\n\nProperty value (service representation).\n\nRepresents the actual value stored for an entity property.\nThis is serialized to/from JSONB in the database.\n\n## Union Members\n\n### Type Literal\n\n\\{ `type`: `\"Boolean\"`; `value`: `boolean`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `type` | `\"Boolean\"` | - |\n| `value` | `boolean` | Boolean value Serializes as: {\"type\": \"Boolean\", \"value\": true} |\n\n***\n\n### Type Literal\n\n\\{ `type`: `\"Number\"`; `value`: `number`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `type` | `\"Number\"` | - |\n| `value` | `number` | Numeric value Serializes as: {\"type\": \"Number\", \"value\": 42.5} |\n\n***\n\n### Type Literal\n\n\\{ `type`: `\"String\"`; `value`: `string`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `type` | `\"String\"` | - |\n| `value` | `string` | String value Serializes as: {\"type\": \"String\", \"value\": \"text\"} |\n\n***\n\n### Type Literal\n\n\\{ `type`: `\"Date\"`; `value`: `string`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `type` | `\"Date\"` | - |\n| `value` | `string` | Date/timestamp value Serializes as: {\"type\": \"Date\", \"value\": \"2025-01-01T00:00:00Z\"} |\n\n***\n\n### Type Literal\n\n\\{ `type`: `\"SelectOption\"`; `value`: `string`[]; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `type` | `\"SelectOption\"` | - |\n| `value` | `string`[] | Select option(s) - always an array (check is_multi_select to determine if single or multi) Single-select: {\"type\": \"SelectOption\", \"value\": [\"uuid\"]} (length 0 or 1) Multi-select: {\"type\": \"SelectOption\", \"value\": [\"uuid1\", \"uuid2\", ...]} (length 0+) |\n\n***\n\n### Type Literal\n\n\\{ `type`: `\"EntityReference\"`; `value`: [`EntityReference`](EntityReference.md)[]; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `type` | `\"EntityReference\"` | - |\n| `value` | [`EntityReference`](EntityReference.md)[] | Entity reference(s) - always an array (check is_multi_select to determine if single or multi) Single-select: {\"type\": \"EntityReference\", \"value\": [{...}]} (length 0 or 1) Multi-select: {\"type\": \"EntityReference\", \"value\": [{...}, {...}, ...]} (length 0+) |\n\n***\n\n### Type Literal\n\n\\{ `type`: `\"Link\"`; `value`: `string`[]; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `type` | `\"Link\"` | - |\n| `value` | `string`[] | Link value(s) - always an array (check is_multi_select to determine if single or multi) Single-select: {\"type\": \"Link\", \"value\": [\"https://example.com\"]} (length 0 or 1) Multi-select: {\"type\": \"Link\", \"value\": [\"https://example.com\", \"https://other.com\"]} (length 0+) |\n\n\n<!-- generated/properties/types.gen/type-aliases/SetPropertyValue.md -->\n# Type Alias: SetPropertyValue\n\n> **SetPropertyValue** = \\{ `type`: `\"boolean\"`; `value`: `boolean`; \\} \\| \\{ `type`: `\"date\"`; `value`: `string`; \\} \\| \\{ `type`: `\"number\"`; `value`: `number`; \\} \\| \\{ `type`: `\"string\"`; `value`: `string`; \\} \\| \\{ `option_id`: `string`; `type`: `\"select_option\"`; \\} \\| \\{ `option_ids`: `string`[]; `type`: `\"multi_select_option\"`; \\} \\| \\{ `reference`: [`EntityReference`](EntityReference.md); `type`: `\"entity_reference\"`; \\} \\| \\{ `references`: [`EntityReference`](EntityReference.md)[]; `type`: `\"multi_entity_reference\"`; \\} \\| \\{ `type`: `\"link\"`; `url`: `string`; \\} \\| \\{ `type`: `\"multi_link\"`; `urls`: `string`[]; \\}\n\nType-safe enum for setting entity property values - provides compile-time validation.\n\n\n<!-- generated/search/types.gen/type-aliases/AgentSessionFilters.md -->\n# Type Alias: AgentSessionFilters\n\n> **AgentSessionFilters** = \\{ `ids?`: `string`[]; `include?`: `boolean`; `owners?`: `string`[]; \\}\n\nFilters for agent sessions.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-ids\"></a> `ids?` | `string`[] | Agent session ids to filter by. Empty to include all accessible sessions. |\n| <a id=\"property-include\"></a> `include?` | `boolean` | Opt this query into agent sessions at all. Agent sessions are off by default — see [`crate::ast::agent_session::AgentSessionLiteral::Include`]. Asking for specific `ids` or `owners` also opts in. |\n| <a id=\"property-owners\"></a> `owners?` | `string`[] | Filter by session owner principal — a user ('macro\\|[email protected]'), a bot ('bot\\|<uuid>'), or a team (a bare hyphenated uuid). Empty to include every owner. |\n\n\n<!-- generated/search/types.gen/type-aliases/CalendarEventFilters.md -->\n# Type Alias: CalendarEventFilters\n\n> **CalendarEventFilters** = \\{ `attendees?`: `string`[]; `calendar_event_ids?`: `string`[]; `ends_after?`: `string` \\| `null`; `organizers?`: `string`[]; `starts_before?`: `string` \\| `null`; `statuses?`: `string`[]; \\}\n\nFilters for canonical calendar-event entities.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-attendees\"></a> `attendees?` | `string`[] | Attendee email addresses. |\n| <a id=\"property-calendar_event_ids\"></a> `calendar_event_ids?` | `string`[] | Canonical event ids. |\n| <a id=\"property-ends_after\"></a> `ends_after?` | `string` \\| `null` | Include master events ending after this instant. |\n| <a id=\"property-organizers\"></a> `organizers?` | `string`[] | Organizer email addresses. |\n| <a id=\"property-starts_before\"></a> `starts_before?` | `string` \\| `null` | Include master events starting before this instant. |\n| <a id=\"property-statuses\"></a> `statuses?` | `string`[] | Event statuses such as `confirmed`, `tentative`, or `cancelled`. |\n\n\n<!-- generated/search/types.gen/type-aliases/CallFilters.md -->\n# Type Alias: CallFilters\n\n> **CallFilters** = \\{ `attended?`: `boolean` \\| `null`; `call_ids?`: `string`[]; `channel_ids?`: `string`[]; `speaker_ids?`: `string`[]; `status?`: `null` \\| [`CallStatus`](CallStatus.md); \\}\n\nFilters for call records.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-attended\"></a> `attended?` | `boolean` \\| `null` | Legacy filter by whether the requesting user attended the call. Prefer [`CallFilters::status`] for new callers. `None` = no filter, `Some(true)` = only calls the user joined, `Some(false)` = only calls the user did not join. |\n| <a id=\"property-call_ids\"></a> `call_ids?` | `string`[] | Call record IDs to filter by. Empty to include all calls. |\n| <a id=\"property-channel_ids\"></a> `channel_ids?` | `string`[] | Channel IDs to filter calls by. Empty to include all calls. |\n| <a id=\"property-speaker_ids\"></a> `speaker_ids?` | `string`[] | Speaker macro user ids. Empty to include all. |\n| <a id=\"property-status\"></a> `status?` | `null` \\| [`CallStatus`](CallStatus.md) | - |\n\n\n<!-- generated/search/types.gen/type-aliases/CallStatus.md -->\n# Type Alias: CallStatus\n\n> **CallStatus** = `\"ATTENDED\"` \\| `\"MISSED\"` \\| `\"UNATTENDED\"`\n\nViewer-relative attendance status for a call record.\nSerializes as `ATTENDED`, `MISSED`, or `UNATTENDED`.\n\n\n<!-- generated/search/types.gen/type-aliases/ChannelFilters.md -->\n# Type Alias: ChannelFilters\n\n> **ChannelFilters** = \\{ `channel_ids?`: `string`[]; `channel_types?`: `string`[]; `importance?`: `boolean` \\| `null`; `is_participant?`: `boolean` \\| `null`; `mentions?`: `string`[]; `notification_filters?`: [`NotificationFilters`](NotificationFilters.md); `org_id?`: `number` \\| `null`; `sender_ids?`: `string`[]; `team_id?`: `string` \\| `null`; `thread_ids?`: `string`[]; \\}\n\nThe channel message filters used to filter down what channel messages you search over.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-channel_ids\"></a> `channel_ids?` | `string`[] | Channel IDs to search within. Examples: ['general']. Empty to search all accessible channels. |\n| <a id=\"property-channel_types\"></a> `channel_types?` | `string`[] | Channel types to filter by. Examples: ['public'], ['direct_message', 'private']. Empty to search all channel types. |\n| <a id=\"property-importance\"></a> `importance?` | `boolean` \\| `null` | Filter by channel importance. None to ignore, true to pass through (no clause), false to short-circuit and return nothing. |\n| <a id=\"property-is_participant\"></a> `is_participant?` | `boolean` \\| `null` | Filter by whether the requesting user is an active participant of the channel. Presence of this filter also widens the candidate set to team channels of the user's teams that they have not joined, so `false` matches those channels. None to ignore (participant channels only, today's default). |\n| <a id=\"property-mentions\"></a> `mentions?` | `string`[] | Channel user mentions to search for. Examples: ['@username']. Empty if not filtering by mentions. |\n| <a id=\"property-notification_filters\"></a> `notification_filters?` | [`NotificationFilters`](NotificationFilters.md) | Filter by channel notification state. |\n| <a id=\"property-org_id\"></a> `org_id?` | `number` \\| `null` | Channel organization ID to search within. Empty to ignore organization filtering. |\n| <a id=\"property-sender_ids\"></a> `sender_ids?` | `string`[] | Sender IDs to search within. Examples: ['user1']. Empty to search all accessible senders. |\n| <a id=\"property-team_id\"></a> `team_id?` | `string` \\| `null` | Channel team ID to search within. Empty to ignore team filtering. |\n| <a id=\"property-thread_ids\"></a> `thread_ids?` | `string`[] | Channel thread IDs to search within. Examples: ['thread123']. Empty to search all threads. |\n\n\n<!-- generated/search/types.gen/type-aliases/ChannelThreadFilters.md -->\n# Type Alias: ChannelThreadFilters\n\n> **ChannelThreadFilters** = \\{ `channel_ids?`: `string`[]; `participant_ids?`: `string`[]; `root_sender_ids?`: `string`[]; `thread_ids?`: `string`[]; \\}\n\nThe channel thread filters used to filter down channel-thread entities.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-channel_ids\"></a> `channel_ids?` | `string`[] | Channel IDs containing the thread. Empty to include threads from all accessible channels. |\n| <a id=\"property-participant_ids\"></a> `participant_ids?` | `string`[] | Thread participant user IDs. A participant is the root message sender, anyone who replied in the thread, or anyone @-mentioned in the thread (group mentions like **Here** count through their per-user expansion at send time). Empty to include threads regardless of participants. |\n| <a id=\"property-root_sender_ids\"></a> `root_sender_ids?` | `string`[] | Sender IDs for the root thread message. Empty to include all root senders. |\n| <a id=\"property-thread_ids\"></a> `thread_ids?` | `string`[] | Channel thread parent message IDs to include. Empty to include all accessible threads. |\n\n\n<!-- generated/search/types.gen/type-aliases/ChatFilters.md -->\n# Type Alias: ChatFilters\n\n> **ChatFilters** = \\{ `chat_ids?`: `string`[]; `importance?`: `boolean` \\| `null`; `notification_filters?`: [`NotificationFilters`](NotificationFilters.md); `owners?`: `string`[]; `project_ids?`: `string`[]; `role?`: `string`[]; \\}\n\nThe chat filters used to filter down what chats you search over.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-chat_ids\"></a> `chat_ids?` | `string`[] | Chat ids to search over. Examples: ['chat1'], ['chat1', 'chat2']. When provided, chat search will only match results on these chats. Empty to search all accessible chats. |\n| <a id=\"property-importance\"></a> `importance?` | `boolean` \\| `null` | Filter by chat importance. None to ignore, true to pass through (no clause), false to short-circuit and return nothing. |\n| <a id=\"property-notification_filters\"></a> `notification_filters?` | [`NotificationFilters`](NotificationFilters.md) | Filter by chat notification state. |\n| <a id=\"property-owners\"></a> `owners?` | `string`[] | Filter by chat owner principal — a user ('macro\\|[email protected]'), a bot ('bot\\|<uuid>'), or a team (a bare hyphenated uuid). Examples: ['macro\\|[email protected]'], ['macro\\|[email protected]', 'bot\\|0199...']. Empty to search all owners. |\n| <a id=\"property-project_ids\"></a> `project_ids?` | `string`[] | A list of project ids to search within. Examples: ['project1']. Empty to ignore project filtering. |\n| <a id=\"property-role\"></a> `role?` | `string`[] | Chat message roles to search. Examples: ['user'], ['assistant']. Empty to search all roles. |\n\n\n<!-- generated/search/types.gen/type-aliases/CrmCompanyFilters.md -->\n# Type Alias: CrmCompanyFilters\n\n> **CrmCompanyFilters** = \\{ `company_ids?`: `string`[]; `hidden?`: `boolean` \\| `null`; \\}\n\nThe crm company filters used to narrow which CRM companies appear in soup.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-company_ids\"></a> `company_ids?` | `string`[] | CRM company ids to filter by. Examples: ['11111111-...']. Empty to include all of the team's visible CRM companies. |\n| <a id=\"property-hidden\"></a> `hidden?` | `boolean` \\| `null` | Optional `crm_companies.hidden` filter. `None` = visible only (default for back-compat with non-admin callers). `Some(false)` = visible only (explicit). `Some(true)` = hidden only — requires admin/owner team role; enforced by the CRM service from the caller's team receipt. |\n\n\n<!-- generated/search/types.gen/type-aliases/DocumentFilters.md -->\n# Type Alias: DocumentFilters\n\n> **DocumentFilters** = \\{ `document_ids?`: `string`[]; `file_types?`: `string`[]; `importance?`: `boolean` \\| `null`; `is_email_attachment?`: `boolean` \\| `null`; `notification_filters?`: [`NotificationFilters`](NotificationFilters.md); `owners?`: `string`[]; `project_ids?`: `string`[]; `sub_types?`: `string`[]; `task_filters?`: [`TaskFilters`](TaskFilters.md); \\}\n\nThe document filters used to filter down what documents you search over.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-document_ids\"></a> `document_ids?` | `string`[] | Document ids to search over. Examples: ['doc1'], ['doc1', 'doc2']. Empty to search all accessible documents. |\n| <a id=\"property-file_types\"></a> `file_types?` | `string`[] | Document file types to search. Examples: ['pdf'], ['md', 'txt']. Empty to search all file types. |\n| <a id=\"property-importance\"></a> `importance?` | `boolean` \\| `null` | Filter by document importance. None to ignore, true to pass through (no clause), false to short-circuit and return nothing. |\n| <a id=\"property-is_email_attachment\"></a> `is_email_attachment?` | `boolean` \\| `null` | Filter by email attachment status. true = only email attachments, false = only non-email attachments, None = both. |\n| <a id=\"property-notification_filters\"></a> `notification_filters?` | [`NotificationFilters`](NotificationFilters.md) | Filter by document notification state. |\n| <a id=\"property-owners\"></a> `owners?` | `string`[] | Filter by document owner principal — a user ('macro\\|[email protected]'), a bot ('bot\\|<uuid>'), or a team (a bare hyphenated uuid). Examples: ['macro\\|[email protected]'], ['macro\\|[email protected]', 'bot\\|0199...']. Empty to search all owners. |\n| <a id=\"property-project_ids\"></a> `project_ids?` | `string`[] | A list of project ids to search within. Examples: ['project1']. filtering. Empty to ignore project filtering. |\n| <a id=\"property-sub_types\"></a> `sub_types?` | `string`[] | Filter by document sub type. Examples: ['task']. Empty to search all sub types. |\n| <a id=\"property-task_filters\"></a> `task_filters?` | [`TaskFilters`](TaskFilters.md) | Task-specific filters that only apply to task subtype documents. |\n\n\n<!-- generated/search/types.gen/type-aliases/EmailFilters.md -->\n# Type Alias: EmailFilters\n\n> **EmailFilters** = \\{ `bcc?`: `string`[]; `calendar_only?`: `boolean` \\| `null`; `cc?`: `string`[]; `crm_addresses?`: `string`[]; `crm_domains?`: `string`[]; `email_thread_ids?`: `string`[]; `exclude_labels?`: `string`[]; `importance?`: `boolean` \\| `null`; `include_labels?`: `string`[]; `is_read?`: `boolean` \\| `null`; `link_ids?`: `string`[]; `notification_filters?`: [`NotificationFilters`](NotificationFilters.md); `project_ids?`: `string`[]; `recipients?`: `string`[]; `senders?`: `string`[]; `shared?`: [`SharedEmailFilter`](SharedEmailFilter.md); \\}\n\nThe email filters used to filter down what emails you search over.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-bcc\"></a> `bcc?` | `string`[] | Email BCC addresses to filter by. Examples: ['[email protected]']. Empty if not filtering by BCC. |\n| <a id=\"property-calendar_only\"></a> `calendar_only?` | `boolean` \\| `null` | When `Some(true)`, only include threads that have at least one message with an iCalendar attachment (`.ics` filename or `application/ics` mime type). `Some(false)` and `None` apply no constraint. |\n| <a id=\"property-cc\"></a> `cc?` | `string`[] | Email CC addresses to filter by. Examples: ['[email protected]']. Empty if not filtering by CC. |\n| <a id=\"property-crm_addresses\"></a> `crm_addresses?` | `string`[] | CRM-scoped address filter. When non-empty, expands visibility to every teammate's mailbox and restricts to threads involving any of these fully-qualified addresses. Each address is authorized against `crm_contacts` + `crm_companies` (contact must not be hidden, company must not be hidden, `email_sync` must be true). Mutually exclusive with `crm_domains`. |\n| <a id=\"property-crm_domains\"></a> `crm_domains?` | `string`[] | CRM-scoped domain filter. When non-empty, expands visibility to every teammate's mailbox and restricts to threads involving any of these domains (in any of sender/cc/bcc/recipient). Each domain is authorized against `crm_domains` + `crm_companies` (must exist for the caller's team, company must not be hidden, `email_sync` must be true). Mutually exclusive with `crm_addresses`. |\n| <a id=\"property-email_thread_ids\"></a> `email_thread_ids?` | `string`[] | Email thread IDs to filter by. Examples: ['thread-uuid-1']. Empty to search all threads. |\n| <a id=\"property-exclude_labels\"></a> `exclude_labels?` | `string`[] | Exclude emails that have any of these labels. Supports both Gmail system labels (e.g. \"CATEGORY_PROMOTIONS\") and user-created labels. Empty to not exclude any labels. Note: SPAM and TRASH emails are not indexed in OpenSearch, so they are already excluded by default. |\n| <a id=\"property-importance\"></a> `importance?` | `boolean` \\| `null` | Filter by email importance. None to not filter. True to show only important emails (drafts, personal, sent, or uncategorized). False to show only unimportant emails (those categorized as promotions, social, updates, or forums). |\n| <a id=\"property-include_labels\"></a> `include_labels?` | `string`[] | Only include emails that have at least one of these labels. Supports both Gmail system labels (e.g. \"INBOX\", \"CATEGORY_PROMOTIONS\") and user-created labels (e.g. \"github\"). Empty to not filter by included labels. Note: SPAM and TRASH emails are not indexed in OpenSearch, so they will never appear in results regardless of this filter. |\n| <a id=\"property-is_read\"></a> `is_read?` | `boolean` \\| `null` | Filter by the email thread's read flag, independently of notification state. |\n| <a id=\"property-link_ids\"></a> `link_ids?` | `string`[] | Restrict to specific inboxes by email_links.id. Empty means \"any inbox the caller can access\" (soup expands to the full set at the router edge). |\n| <a id=\"property-notification_filters\"></a> `notification_filters?` | [`NotificationFilters`](NotificationFilters.md) | Filter by email notification state. |\n| <a id=\"property-project_ids\"></a> `project_ids?` | `string`[] | A list of project ids to search within. Empty to ignore project filtering. |\n| <a id=\"property-recipients\"></a> `recipients?` | `string`[] | Email Recipient addresses to filter by. Examples: ['[email protected]']. Empty if not filtering by Recipient. |\n| <a id=\"property-senders\"></a> `senders?` | `string`[] | Email sender addresses to filter by. Examples: ['[email protected]']. Empty to search all senders. |\n| <a id=\"property-shared\"></a> `shared?` | [`SharedEmailFilter`](SharedEmailFilter.md) | Controls whether shared email threads are included in results. Defaults to \"exclude\" (only the user's own threads). |\n\n\n<!-- generated/search/types.gen/type-aliases/EntityFilters.md -->\n# Type Alias: EntityFilters\n\n> **EntityFilters** = \\{ `agent_session_filters?`: [`AgentSessionFilters`](AgentSessionFilters.md); `calendar_event_filters?`: [`CalendarEventFilters`](CalendarEventFilters.md); `call_filters?`: [`CallFilters`](CallFilters.md); `channel_filters?`: [`ChannelFilters`](ChannelFilters.md); `channel_thread_filters?`: [`ChannelThreadFilters`](ChannelThreadFilters.md); `chat_filters?`: [`ChatFilters`](ChatFilters.md); `crm_company_filters?`: [`CrmCompanyFilters`](CrmCompanyFilters.md); `document_filters?`: [`DocumentFilters`](DocumentFilters.md); `email_filters?`: [`EmailFilters`](EmailFilters.md); `favorites_only?`: `boolean` \\| `null`; `foreign_entity_filters?`: [`ForeignEntityFilters`](ForeignEntityFilters.md); `initiative_filters?`: [`InitiativeFilters`](InitiativeFilters.md); `project_filters?`: [`ProjectFilters`](ProjectFilters.md); `property_filters?`: [`PropertyFilter`](PropertyFilter.md)[]; `tag_filter_mode?`: [`TagFilterMode`](TagFilterMode.md); `tag_option_ids?`: `string`[]; \\}\n\na bundle of all of the filters for each entity type\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-agent_session_filters\"></a> `agent_session_filters?` | [`AgentSessionFilters`](AgentSessionFilters.md) | the bundled [AgentSessionFilters] |\n| <a id=\"property-calendar_event_filters\"></a> `calendar_event_filters?` | [`CalendarEventFilters`](CalendarEventFilters.md) | the bundled [CalendarEventFilters] |\n| <a id=\"property-call_filters\"></a> `call_filters?` | [`CallFilters`](CallFilters.md) | the bundled [CallFilters] |\n| <a id=\"property-channel_filters\"></a> `channel_filters?` | [`ChannelFilters`](ChannelFilters.md) | the bundled [ChannelFilters] |\n| <a id=\"property-channel_thread_filters\"></a> `channel_thread_filters?` | [`ChannelThreadFilters`](ChannelThreadFilters.md) | the bundled [ChannelThreadFilters] |\n| <a id=\"property-chat_filters\"></a> `chat_filters?` | [`ChatFilters`](ChatFilters.md) | the bundled [ChatFilters] |\n| <a id=\"property-crm_company_filters\"></a> `crm_company_filters?` | [`CrmCompanyFilters`](CrmCompanyFilters.md) | the bundled [CrmCompanyFilters] |\n| <a id=\"property-document_filters\"></a> `document_filters?` | [`DocumentFilters`](DocumentFilters.md) | the bundled [DocumentFilters] |\n| <a id=\"property-email_filters\"></a> `email_filters?` | [`EmailFilters`](EmailFilters.md) | the bundled [EmailFilters] |\n| <a id=\"property-favorites_only\"></a> `favorites_only?` | `boolean` \\| `null` | Restrict results to the authenticated viewer's favorites when true. |\n| <a id=\"property-foreign_entity_filters\"></a> `foreign_entity_filters?` | [`ForeignEntityFilters`](ForeignEntityFilters.md) | the bundled [ForeignEntityFilters] |\n| <a id=\"property-initiative_filters\"></a> `initiative_filters?` | [`InitiativeFilters`](InitiativeFilters.md) | Initiative filters. Initiatives are opt-in. |\n| <a id=\"property-project_filters\"></a> `project_filters?` | [`ProjectFilters`](ProjectFilters.md) | the bundled [ProjectFilters] |\n| <a id=\"property-property_filters\"></a> `property_filters?` | [`PropertyFilter`](PropertyFilter.md)[] | property-based filters applied across entity types |\n| <a id=\"property-tag_filter_mode\"></a> `tag_filter_mode?` | [`TagFilterMode`](TagFilterMode.md) | How the `tag_option_ids` combine: `any` (default) matches entities holding at least one selected tag, `all` requires every selected tag. |\n| <a id=\"property-tag_option_ids\"></a> `tag_option_ids?` | `string`[] | tag option ids matched against `properties.values`, OR'd together across all tag definitions. Option ids are globally unique, so the match ignores the owning definition id (personal and team tags combine into one OR). |\n\n\n<!-- generated/search/types.gen/type-aliases/ForeignEntityFilters.md -->\n# Type Alias: ForeignEntityFilters\n\n> **ForeignEntityFilters** = \\{ `foreign_entity_ids?`: `string`[]; `foreign_entity_sources?`: `string`[]; `ids?`: `string`[]; `includes_me?`: `boolean`; `notification_filters?`: [`NotificationFilters`](NotificationFilters.md); \\}\n\nFilters for foreign entity records.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-foreign_entity_ids\"></a> `foreign_entity_ids?` | `string`[] | External entity identifiers to filter by. Empty to include all external IDs. |\n| <a id=\"property-foreign_entity_sources\"></a> `foreign_entity_sources?` | `string`[] | External source names to filter by. Empty to include all sources. |\n| <a id=\"property-ids\"></a> `ids?` | `string`[] | Internal foreign entity record IDs to filter by. Empty to include all records. |\n| <a id=\"property-includes_me\"></a> `includes_me?` | `boolean` | When true, only return foreign entities whose metadata lists the requesting user as a participant (GitHub `involves:me` semantics for `github_pull_request` records). False or absent applies no filter. Serialized in filter ASTs as the `\"me\"` literal. |\n| <a id=\"property-notification_filters\"></a> `notification_filters?` | [`NotificationFilters`](NotificationFilters.md) | Filter by the notification state of the foreign entity (e.g. whether the requesting user's GitHub PR notification is done/seen). |\n\n\n<!-- generated/search/types.gen/type-aliases/InitiativeFilters.md -->\n# Type Alias: InitiativeFilters\n\n> **InitiativeFilters** = \\{ `due_after?`: `string` \\| `null`; `due_before?`: `string` \\| `null`; `include?`: `boolean`; `initiative_ids?`: `string`[]; `name?`: `string` \\| `null`; `owners?`: `string`[]; \\}\n\nFilters for initiatives.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-due_after\"></a> `due_after?` | `string` \\| `null` | Inclusive lower due-date bound. |\n| <a id=\"property-due_before\"></a> `due_before?` | `string` \\| `null` | Inclusive upper due-date bound. |\n| <a id=\"property-include\"></a> `include?` | `boolean` | Opt this query into initiatives at all. Initiatives are off by default — see [`crate::ast::initiative::InitiativeLiteral::Include`]. Asking for specific `initiative_ids` or `owners` also opts in. |\n| <a id=\"property-initiative_ids\"></a> `initiative_ids?` | `string`[] | Initiative ids to filter by. Empty to include all accessible initiatives. |\n| <a id=\"property-name\"></a> `name?` | `string` \\| `null` | Case-insensitive name substring. |\n| <a id=\"property-owners\"></a> `owners?` | `string`[] | Filter by initiative owner principal — a user ('macro\\|[email protected]'), a bot ('bot\\|<uuid>'), or a team (a bare hyphenated uuid). Empty to include every owner. |\n\n\n<!-- generated/search/types.gen/type-aliases/NotificationFilters.md -->\n# Type Alias: NotificationFilters\n\n> **NotificationFilters** = \\{ `states?`: [`NotificationState`](NotificationState.md)[]; \\}\n\nNotification-level filters that apply to an entity type.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-states\"></a> `states?` | [`NotificationState`](NotificationState.md)[] | Include entities with a non-deleted notification in any of these exact states. Empty means no notification restriction. Active means `[unseen, seen]`. |\n\n\n<!-- generated/search/types.gen/type-aliases/NotificationState.md -->\n# Type Alias: NotificationState\n\n> **NotificationState** = `\"unseen\"` \\| `\"seen\"` \\| `\"done\"`\n\nThe mutually exclusive lifecycle states of a user's notification.\n\n\n<!-- generated/search/types.gen/type-aliases/ProjectFilters.md -->\n# Type Alias: ProjectFilters\n\n> **ProjectFilters** = \\{ `importance?`: `boolean` \\| `null`; `include_root?`: `boolean`; `notification_filters?`: [`NotificationFilters`](NotificationFilters.md); `owners?`: `string`[]; `project_ids?`: `string`[]; \\}\n\nThe project filters used to filter down what projects you search over.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-importance\"></a> `importance?` | `boolean` \\| `null` | Filter by project importance. None to ignore, true to pass through (no clause), false to short-circuit and return nothing. |\n| <a id=\"property-include_root\"></a> `include_root?` | `boolean` | When true, `project_ids` also matches the projects themselves in addition to their children. |\n| <a id=\"property-notification_filters\"></a> `notification_filters?` | [`NotificationFilters`](NotificationFilters.md) | Filter by project notification state. |\n| <a id=\"property-owners\"></a> `owners?` | `string`[] | Filter by project owner principal — a user ('macro\\|[email protected]'), a bot ('bot\\|<uuid>'), or a team (a bare hyphenated uuid). Examples: ['macro\\|[email protected]'], ['macro\\|[email protected]', 'bot\\|0199...']. Empty to search all owners. |\n| <a id=\"property-project_ids\"></a> `project_ids?` | `string`[] | Project IDs to search within. Examples: ['project1']. Empty to search all accessible projects. By default matches children of these projects; set `include_root` to also match the projects themselves. |\n\n\n<!-- generated/search/types.gen/type-aliases/PropertyFilter.md -->\n# Type Alias: PropertyFilter\n\n> **PropertyFilter** = \\{ `entity_ids?`: `string`[]; `entity_type?`: `string` \\| `null`; `option_ids?`: `string`[]; `property_definition_id`: `string`; \\}\n\nA single property-based filter condition.\n\nEach filter targets a specific property definition on entities of a given type,\nmatching against select option UUIDs or entity reference IDs.\nMultiple values within a single filter are OR'd together.\nMultiple filters are AND'd together.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-entity_ids\"></a> `entity_ids?` | `string`[] | Entity reference IDs to match. Multiple values are OR'd together. |\n| <a id=\"property-entity_type\"></a> `entity_type?` | `string` \\| `null` | The entity type for the property lookup (e.g., \"TASK\", \"DOCUMENT\", \"PROJECT\"). When None, matches across all entity types. |\n| <a id=\"property-option_ids\"></a> `option_ids?` | `string`[] | Select option UUIDs to match. Multiple values are OR'd together. |\n| <a id=\"property-property_definition_id\"></a> `property_definition_id` | `string` | The UUID of the property definition to filter on. |\n\n\n<!-- generated/search/types.gen/type-aliases/SharedEmailFilter.md -->\n# Type Alias: SharedEmailFilter\n\n> **SharedEmailFilter** = `\"exclude\"` \\| `\"include\"` \\| `\"only\"`\n\nControls whether shared email threads are included in results.\n\n\n<!-- generated/search/types.gen/type-aliases/TagFilterMode.md -->\n# Type Alias: TagFilterMode\n\n> **TagFilterMode** = `\"any\"` \\| `\"all\"`\n\nHow multiple `tag_option_ids` combine when filtering.\n\n\n<!-- generated/search/types.gen/type-aliases/TaskFilters.md -->\n# Type Alias: TaskFilters\n\n> **TaskFilters** = \\{ `include_cbm_atm_nc?`: `boolean` \\| `null`; \\}\n\nTask-only filters nested under document filters.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-include_cbm_atm_nc\"></a> `include_cbm_atm_nc?` | `boolean` \\| `null` | Include tasks that are created by me, assigned to me, and not completed, even when they do not match other document filters. |\n\n\n<!-- generated/storage/types.gen/type-aliases/AccessLevel.md -->\n# Type Alias: AccessLevel\n\n> **AccessLevel** = `\"view\"` \\| `\"comment\"` \\| `\"edit\"` \\| `\"owner\"`\n\nOrdered from least to most access top -> bottom\n\n\n<!-- generated/storage/types.gen/type-aliases/AccessRequest.md -->\n# Type Alias: AccessRequest\n\n> **AccessRequest** = \\{ `createdAt`: `string`; `grantedLevel?`: `null` \\| [`AccessLevel`](AccessLevel.md); `id`: `string`; `requestedLevel`: [`AccessLevel`](AccessLevel.md); `requesterId`: `string`; `resolvedAt?`: `string` \\| `null`; `retryAfter?`: `string` \\| `null`; `revision`: `number`; `status`: [`RequestStatus`](RequestStatus.md); `updatedAt`: `string`; \\}\n\nLatest request for one person and one entity.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-createdat\"></a> `createdAt` | `string` | Start of this request attempt. |\n| <a id=\"property-grantedlevel\"></a> `grantedLevel?` | `null` \\| [`AccessLevel`](AccessLevel.md) | - |\n| <a id=\"property-id\"></a> `id` | `string` | Stable request identity across revisions. |\n| <a id=\"property-requestedlevel\"></a> `requestedLevel` | [`AccessLevel`](AccessLevel.md) | Requested upgrade. |\n| <a id=\"property-requesterid\"></a> `requesterId` | `string` | Person requesting access. |\n| <a id=\"property-resolvedat\"></a> `resolvedAt?` | `string` \\| `null` | When the request stopped being pending. |\n| <a id=\"property-retryafter\"></a> `retryAfter?` | `string` \\| `null` | Earliest next submission or level change; cancellation preserves this deadline. Submissions wait one minute, denials wait 24 hours, and approval clears it. |\n| <a id=\"property-revision\"></a> `revision` | `number` | Optimistic concurrency token. |\n| <a id=\"property-status\"></a> `status` | [`RequestStatus`](RequestStatus.md) | Current outcome. |\n| <a id=\"property-updatedat\"></a> `updatedAt` | `string` | Most recent change. |\n\n\n<!-- generated/storage/types.gen/type-aliases/EntityPermission.md -->\n# Type Alias: EntityPermission\n\n> **EntityPermission** = \\{ `access_level`: [`AccessLevel`](AccessLevel.md); `type`: `\"access_level\"`; \\} \\| \\{ `type`: `\"channel_view_only\"`; \\} \\| \\{ `role`: [`ParticipantRole`](ParticipantRole.md); `type`: `\"channel_role\"`; \\} \\| \\{ `role`: [`TeamRole`](TeamRole.md); `type`: `\"team_role\"`; \\}\n\nA user's permission for an entity, discriminated by entity kind.\n\nItems (documents, chats, projects, threads) use access levels.\nChannels use view-only permission or participant roles.\n\n## Union Members\n\n### Type Literal\n\n\\{ `access_level`: [`AccessLevel`](AccessLevel.md); `type`: `\"access_level\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `access_level` | [`AccessLevel`](AccessLevel.md) | The access level the user has. |\n| `type` | `\"access_level\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `type`: `\"channel_view_only\"`; \\}\n\n***\n\n### Type Literal\n\n\\{ `role`: [`ParticipantRole`](ParticipantRole.md); `type`: `\"channel_role\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `role` | [`ParticipantRole`](ParticipantRole.md) | The role the user has in the channel. |\n| `type` | `\"channel_role\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `role`: [`TeamRole`](TeamRole.md); `type`: `\"team_role\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `role` | [`TeamRole`](TeamRole.md) | The role the user has in the team. |\n| `type` | `\"team_role\"` | - |\n\n\n<!-- generated/storage/types.gen/type-aliases/FavoriteEntityRef.md -->\n# Type Alias: FavoriteEntityRef\n\n> **FavoriteEntityRef** = \\{ `entityId`: `string`; `entityType`: `\"user\"` \\| `\"chat\"` \\| `\"channel\"` \\| `\"channel_message\"` \\| `\"document\"` \\| `\"project\"` \\| `\"email_thread\"` \\| `\"calendar_event\"` \\| `\"team\"` \\| `\"call\"` \\| `\"foreign_entity\"` \\| `\"static_file\"` \\| `\"crm_company\"` \\| `\"crm_contact\"` \\| `\"crm_pipeline\"` \\| `\"reminder\"` \\| `\"skill\"` \\| `\"agent_session\"` \\| `\"scheduled_action\"` \\| `\"initiative\"` \\| `\"database\"` \\| `\"database_row\"` \\| `\"form\"`; \\}\n\nA reference to a favorited entity.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-entityid\"></a> `entityId` | `string` | The id of the favorited entity. |\n| <a id=\"property-entitytype\"></a> `entityType` | `\"user\"` \\| `\"chat\"` \\| `\"channel\"` \\| `\"channel_message\"` \\| `\"document\"` \\| `\"project\"` \\| `\"email_thread\"` \\| `\"calendar_event\"` \\| `\"team\"` \\| `\"call\"` \\| `\"foreign_entity\"` \\| `\"static_file\"` \\| `\"crm_company\"` \\| `\"crm_contact\"` \\| `\"crm_pipeline\"` \\| `\"reminder\"` \\| `\"skill\"` \\| `\"agent_session\"` \\| `\"scheduled_action\"` \\| `\"initiative\"` \\| `\"database\"` \\| `\"database_row\"` \\| `\"form\"` | The type of the favorited entity. |\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkShare.md -->\n# Type Alias: LinkShare\n\n> **LinkShare** = `\"PUBLIC\"` \\| `\"TEAM\"`\n\nDefines who can access an item through its share link.\n\n\n<!-- generated/storage/types.gen/type-aliases/MessageCursor.md -->\n# Type Alias: MessageCursor\n\n> **MessageCursor** = \\{ `created_at`: `string`; `id`: `string`; \\}\n\nCursor for a chronological parent timeline.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-created_at\"></a> `created_at` | `string` | Last message creation time or activity occurrence time. |\n| <a id=\"property-id\"></a> `id` | `string` | Last entry UUID, used to break timestamp ties across both sources. |\n\n\n<!-- generated/storage/types.gen/type-aliases/MessageDirection.md -->\n# Type Alias: MessageDirection\n\n> **MessageDirection** = `\"older\"` \\| `\"newer\"`\n\nDirection through a parent timeline, retaining channel cursor semantics.\n\n\n<!-- generated/storage/types.gen/type-aliases/ParticipantRole.md -->\n# Type Alias: ParticipantRole\n\n> **ParticipantRole** = `\"owner\"` \\| `\"admin\"` \\| `\"member\"`\n\nThe role a user has within a channel.\n\n\n<!-- generated/storage/types.gen/type-aliases/RequestStatus.md -->\n# Type Alias: RequestStatus\n\n> **RequestStatus** = `\"pending\"` \\| `\"granted\"` \\| `\"denied\"` \\| `\"cancelled\"`\n\nDurable outcome; reading a notification never changes it.\n\n\n<!-- generated/storage/types.gen/type-aliases/ResolveRequest.md -->\n# Type Alias: ResolveRequest\n\n> **ResolveRequest** = \\{ `grantedLevel?`: `null` \\| [`AccessLevel`](AccessLevel.md); `revision`: `number`; \\}\n\nOwner's decision; omission of a granted level means deny.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-grantedlevel\"></a> `grantedLevel?` | `null` \\| [`AccessLevel`](AccessLevel.md) | - |\n| <a id=\"property-revision\"></a> `revision` | `number` | Request revision being reviewed. |\n\n\n<!-- generated/storage/types.gen/type-aliases/ShareEntityType.md -->\n# Type Alias: ShareEntityType\n\n> **ShareEntityType** = `\"document\"` \\| `\"chat\"` \\| `\"project\"` \\| `\"initiative\"` \\| `\"database\"` \\| `\"call\"` \\| `\"email_thread\"` \\| `\"agent_session\"`\n\nAn entity type with an existing Share surface.\n\n\n<!-- generated/storage/types.gen/type-aliases/SimpleMention.md -->\n# Type Alias: SimpleMention\n\n> **SimpleMention** = \\{ `entity_id`: `string`; `entity_type`: `string`; \\}\n\nA mention tracked in a message body.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-entity_id\"></a> `entity_id` | `string` | Mentioned entity identifier. |\n| <a id=\"property-entity_type\"></a> `entity_type` | `string` | Mentioned entity type. |\n\n\n<!-- generated/storage/types.gen/type-aliases/TeamRole.md -->\n# Type Alias: TeamRole\n\n> **TeamRole** = `\"member\"` \\| `\"admin\"` \\| `\"owner\"`\n\nThe role a user has within a team.\n\nOrdered least to most privileged so comparisons reflect access strength.\n\n\n<!-- generated/storage/types.gen/type-aliases/ThreadAnchor.md -->\n# Type Alias: ThreadAnchor\n\n> **ThreadAnchor** = \\{ `mark_id`: `string`; `marked_text?`: `string` \\| `null`; `type`: `\"markdown\"`; \\} \\| \\{ `anchor_id`: `string`; `marked_text?`: `string` \\| `null`; `type`: `\"pdf_highlight\"`; \\} \\| \\{ `anchor_id`: `string`; `type`: `\"pdf_placeable\"`; \\} \\| \\{ `range`: `string`; `sheetId`: `string`; `sheetName`: `string`; `type`: `\"spreadsheet\"`; \\} \\| \\{ `nodeId?`: `string` \\| `null`; `pageId`: `string`; `type`: `\"fig\"`; `x`: `number`; `y`: `number`; \\}\n\nA thread's location within its document. PDF geometry remains annotation-owned.\n\n## Union Members\n\n### Type Literal\n\n\\{ `mark_id`: `string`; `marked_text?`: `string` \\| `null`; `type`: `\"markdown\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `mark_id` | `string` | Mark UUID serialized in the document. |\n| `marked_text?` | `string` \\| `null` | The marked text as it read when the discussion was created, already trimmed and bounded. Absent on threads created or imported before snapshots were captured: the text a mark covers cannot be recovered from the mark id alone. |\n| `type` | `\"markdown\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `anchor_id`: `string`; `marked_text?`: `string` \\| `null`; `type`: `\"pdf_highlight\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `anchor_id` | `string` | Highlight annotation UUID. |\n| `marked_text?` | `string` \\| `null` | The text the highlight covers, trimmed and bounded like a markdown snapshot. The highlight owns it and it can be edited there, so it is read from the highlight whenever the thread is, never stored on the thread. Absent when the highlight carries no text. |\n| `type` | `\"pdf_highlight\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `anchor_id`: `string`; `type`: `\"pdf_placeable\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `anchor_id` | `string` | Placeable annotation UUID. |\n| `type` | `\"pdf_placeable\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `range`: `string`; `sheetId`: `string`; `sheetName`: `string`; `type`: `\"spreadsheet\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `range` | `string` | A1 cell or range, such as B4 or B4:C9. |\n| `sheetId` | `string` | Stable sheet identity within the workbook. |\n| `sheetName` | `string` | Sheet name when the discussion was created. |\n| `type` | `\"spreadsheet\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `nodeId?`: `string` \\| `null`; `pageId`: `string`; `type`: `\"fig\"`; `x`: `number`; `y`: `number`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `nodeId?` | `string` \\| `null` | Layer the pin follows; absent for a pin on the bare canvas. |\n| `pageId` | `string` | Page (canvas) the pin is on. |\n| `type` | `\"fig\"` | - |\n| `x` | `number` | Horizontal offset from the layer's origin, or the page's when the pin is on no layer, in design units. |\n| `y` | `number` | Vertical offset, measured like `x`. |\n\n\n<!-- generated/storage/types.gen/type-aliases/ThreadState.md -->\n# Type Alias: ThreadState\n\n> **ThreadState** = \\{ `anchor?`: `null` \\| [`ThreadAnchor`](ThreadAnchor.md); `created_at`: `string`; `deleted_at?`: `string` \\| `null`; `resolved`: `boolean`; `root_id`: `string`; `updated_at`: `string`; `user_id`: `string`; \\}\n\nState belonging to a whole thread, keyed by its root message.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-anchor\"></a> `anchor?` | `null` \\| [`ThreadAnchor`](ThreadAnchor.md) | - |\n| <a id=\"property-created_at\"></a> `created_at` | `string` | Creation time of the discussion. |\n| <a id=\"property-deleted_at\"></a> `deleted_at?` | `string` \\| `null` | Explicit deletion of the entire thread, distinct from root deletion. |\n| <a id=\"property-resolved\"></a> `resolved` | `boolean` | Whether this discussion has been resolved. |\n| <a id=\"property-root_id\"></a> `root_id` | `string` | Root message UUID; there is no separate thread identity. |\n| <a id=\"property-updated_at\"></a> `updated_at` | `string` | Last state change. |\n| <a id=\"property-user_id\"></a> `user_id` | `string` | User who owns this discussion, including imported discussions. |\n\n\n<!-- generated/storage/types.gen/type-aliases/UpdateChannelSharePermission.md -->\n# Type Alias: UpdateChannelSharePermission\n\n> **UpdateChannelSharePermission** = \\{ `accessLevel?`: `null` \\| [`AccessLevel`](AccessLevel.md); `channelId`: `string`; `operation`: [`UpdateOperation`](UpdateOperation.md); \\}\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-accesslevel\"></a> `accessLevel?` | `null` \\| [`AccessLevel`](AccessLevel.md) | - |\n| <a id=\"property-channelid\"></a> `channelId` | `string` | The channel id |\n| <a id=\"property-operation\"></a> `operation` | [`UpdateOperation`](UpdateOperation.md) | The type of operation to be performed on the chanel share permission You can add, remove or replace and existing permission |\n\n\n<!-- generated/storage/types.gen/type-aliases/UpdateOperation.md -->\n# Type Alias: UpdateOperation\n\n> **UpdateOperation** = `\"add\"` \\| `\"remove\"` \\| `\"replace\"`\n\n\n<!-- generated/storage/types.gen/type-aliases/UpdateSharePermissionRequestV2.md -->\n# Type Alias: UpdateSharePermissionRequestV2\n\n> **UpdateSharePermissionRequestV2** = \\{ `channelSharePermissions?`: [`UpdateChannelSharePermission`](UpdateChannelSharePermission.md)[] \\| `null`; `linkShare?`: `null` \\| [`LinkShare`](LinkShare.md); `linkShareAccessLevel?`: `null` \\| [`AccessLevel`](AccessLevel.md); `teamShareAccessLevel?`: `null` \\| [`AccessLevel`](AccessLevel.md); \\}\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-channelsharepermissions\"></a> `channelSharePermissions?` | [`UpdateChannelSharePermission`](UpdateChannelSharePermission.md)[] \\| `null` | Any channel share permissions to be created/updated/removed |\n| <a id=\"property-linkshare\"></a> `linkShare?` | `null` \\| [`LinkShare`](LinkShare.md) | - |\n| <a id=\"property-linkshareaccesslevel\"></a> `linkShareAccessLevel?` | `null` \\| [`AccessLevel`](AccessLevel.md) | - |\n| <a id=\"property-teamshareaccesslevel\"></a> `teamShareAccessLevel?` | `null` \\| [`AccessLevel`](AccessLevel.md) | - |\n\n\n<!-- generated/storage/types.gen/type-aliases/WebhookFilter.md -->\n# Type Alias: WebhookFilter\n\n> **WebhookFilter** = \\{ `events`: `string`[]; `ids?`: `string`[] \\| `null`; \\}\n\nEvent and optional entity-id constraints used to match webhook deliveries.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-events\"></a> `events` | `string`[] | Event names matched by this filter. |\n| <a id=\"property-ids\"></a> `ids?` | `string`[] \\| `null` | Entity ids matched by this filter. When absent, the filter matches all entity ids. |\n\n\n<!-- generated/storage/types.gen/type-aliases/WebhookScope.md -->\n# Type Alias: WebhookScope\n\n> **WebhookScope** = `\"user\"` \\| `\"team\"`\n\nScope that owns a newly-created webhook.\n\nClients serialize this, so both derives are used. `Display`/`FromStr`\nspell the same names as serde, for query strings and config values.\n\n\n<!-- src/config/interfaces/MacroOpts.md -->\n# Interface: MacroOpts\n\nOptions passed to `new Macro(opts)` and stored on `MacroClient`.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-auth\"></a> `auth?` | [`MacroAuth`](../type-aliases/MacroAuth.md) | How to authenticate. Takes precedence over `token`. Falls back to `MACRO_API_KEY` (a user API key or bearer token) or `MACRO_BOT_TOKEN` (bot). |\n| <a id=\"property-env\"></a> `env?` | [`Env`](../type-aliases/Env.md) | Which Macro environment to talk to. Falls back to the MACRO_ENV env var, then `'prod'`. |\n| <a id=\"property-hosts\"></a> `hosts?` | `Partial`\\<`Record`\\<[`ServiceName`](../type-aliases/ServiceName.md), `string`\\>\\> | Override individual service hosts (e.g. point one at localhost). |\n| <a id=\"property-onrequest\"></a> `onRequest?` | (`event`) => `void` | Optional generated API operation events; excludes arguments, URLs and response data. |\n| <a id=\"property-requestedas\"></a> `requestedAs?` | `string` | User id the bot acts for, sent as `x-macro-bot-for-macro-user-id` on every request. Bot auth only. Set via `macro.requestedAs(user)` rather than directly. |\n| <a id=\"property-token\"></a> `token?` | [`TokenSource`](../type-aliases/TokenSource.md) | Shorthand for `auth: { type: 'user', token }`. Accepts a Settings API key (`mak_…`) or a bearer token. |\n| <a id=\"property-webappurl\"></a> `webAppUrl?` | `string` | Override the web app base URL (e.g. for local frontend dev). Also reads MACRO_WEB_URL. |\n| <a id=\"property-webhooksecret\"></a> `webhookSecret?` | `string` | Signing secret for verifying incoming persisted-webhook deliveries. Required only for `macro.events.webhook()` / `macro.events.handle()`. SSE via `macro.events.listen()` uses the API token and does not need this. Falls back to MACRO_WEBHOOK_SECRET. |\n| <a id=\"property-wsverify\"></a> `wsVerify?` | `string` | - |\n\n\n<!-- src/config/type-aliases/BotScope.md -->\n# Type Alias: BotScope\n\n> **BotScope** = `\"user\"` \\| `\"team\"`\n\nAccess scope for bot-authenticated requests. `user` acts with the\nrequested-as user's access (requires `requestedAs`); `team` acts with the\nbot's owning team's access (team-owned bots only).\n\n\n<!-- src/config/type-aliases/Env.md -->\n# Type Alias: Env\n\n> **Env** = `\"dev\"` \\| `\"prod\"` \\| `\"local\"`\n\n\n<!-- src/config/type-aliases/MacroAuth.md -->\n# Type Alias: MacroAuth\n\n> **MacroAuth** = \\{ `apiKey?`: `never`; `token`: [`TokenSource`](TokenSource.md); `type`: `\"user\"`; \\} \\| \\{ `apiKey`: `string`; `token?`: `never`; `type`: `\"user\"`; \\} \\| \\{ `scope?`: [`BotScope`](BotScope.md); `token`: [`TokenSource`](TokenSource.md); `type`: `\"bot\"`; \\}\n\nHow the SDK authenticates with Macro.\n\nA user has exactly one of two credential fields.\n\n- `token`: a bearer token, or a `mak_` API key. The SDK picks the header\n from the prefix at send time.\n- `apiKey`: a Settings → API Keys key, always sent as\n `x-macro-user-api-key`. Not prefix-checked, so keys that predate the\n `mak_` prefix work here.\n\nA bot uses an `mbot_` token as `x-macro-bot-token` plus\n`x-macro-bot-scope`, defaulting to `user` when `requestedAs` is set and\n`team` otherwise.\n\n\n<!-- src/config/type-aliases/ServiceName.md -->\n# Type Alias: ServiceName\n\n> **ServiceName** = `\"agent-harness\"` \\| `\"storage\"` \\| `\"auth\"` \\| `\"email\"` \\| `\"calendar\"` \\| `\"cognition\"` \\| `\"notification\"` \\| `\"properties\"` \\| `\"search\"` \\| `\"scheduled-action\"` \\| `\"static-files\"` \\| `\"connection\"` \\| `\"contacts\"` \\| `\"unfurl\"`\n\nThe backend services the SDK talks to. Note `search` and `properties` are\nserved on the storage host, so they point there.\n\n\n<!-- src/config/type-aliases/TokenSource.md -->\n# Type Alias: TokenSource\n\n> **TokenSource** = `string` \\| (() => `string` \\| `Promise`\\<`string`\\>)\n\nA credential string, or a (possibly async) function that returns one.\n\n\n<!-- src/config/variables/HOSTS.md -->\n# Variable: HOSTS\n\n> `const` **HOSTS**: `Record`\\<[`Env`](../type-aliases/Env.md), `Record`\\<[`ServiceName`](../type-aliases/ServiceName.md), `string`\\>\\>\n\n\n<!-- src/config/variables/WEB_APP_URLS.md -->\n# Variable: WEB\\_APP\\_URLS\n\n> `const` **WEB\\_APP\\_URLS**: `Record`\\<[`Env`](../type-aliases/Env.md), `string`\\>\n\n\n<!-- src/entities/entity/classes/FavoritableEntity.md -->\n# Abstract Class: FavoritableEntity\\<Detail\\>\n\nAn entity the favorites API can address, and so can be (un)favorited.\n\n## Extends\n\n- [`MacroEntity`](MacroEntity.md)\\<`Detail`\\>\n\n## Extended by\n\n- [`CallRecord`](../../calls/call-record/classes/CallRecord.md)\n- [`Message`](../../channels/message/classes/Message.md)\n- [`Contact`](../../crm/contact/classes/Contact.md)\n- [`PropertiedEntity`](PropertiedEntity.md)\n- [`ForeignEntity`](../../foreign/foreign-entity/classes/ForeignEntity.md)\n\n## Type Parameters\n\n| Type Parameter |\n| ------ |\n| <a id=\"type-parameter-detail\"></a> `Detail` |\n\n## Implements\n\n- [`Favoritable`](../interfaces/Favoritable.md)\n\n## Properties\n\n| Property | Modifier | Type | Description | Inherited from |\n| ------ | ------ | ------ | ------ | ------ |\n| <a id=\"property-entitytype\"></a> `entityType` | `abstract readonly` | `\"project\"` \\| `\"user\"` \\| `\"team\"` \\| `\"chat\"` \\| `\"channel\"` \\| `\"channel_message\"` \\| `\"document\"` \\| `\"email_thread\"` \\| `\"calendar_event\"` \\| `\"call\"` \\| `\"foreign_entity\"` \\| `\"static_file\"` \\| `\"crm_company\"` \\| `\"crm_contact\"` \\| `\"crm_pipeline\"` \\| `\"reminder\"` \\| `\"skill\"` \\| `\"agent_session\"` \\| `\"scheduled_action\"` \\| `\"initiative\"` \\| `\"database\"` \\| `\"database_row\"` \\| `\"form\"` | How the entity-addressed APIs (favorites) identify this entity's type. | - |\n| <a id=\"property-id\"></a> `id` | `public readonly` | `string` | - | [`MacroEntity`](MacroEntity.md).[`id`](MacroEntity.md#property-id) |\n\n## Methods\n\n### favorite()\n\n> **favorite**(): `Promise`\\<`FavoritableEntity`\\<`Detail`\\>\\>\n\nAdd this entity to the user's favorites. Returns this handle for chaining.\nPlain unwrap: favoriting alters the user's favorites collection, not this\nentity's own detail, so there's nothing cached to invalidate.\n\n#### Returns\n\n`Promise`\\<`FavoritableEntity`\\<`Detail`\\>\\>\n\n#### Implementation of\n\n[`Favoritable`](../interfaces/Favoritable.md).[`favorite`](../interfaces/Favoritable.md#favorite)\n\n***\n\n### permission()\n\n> **permission**(): `Promise`\\<\\{ `permission`: [`EntityPermission`](../../../../generated/storage/types.gen/type-aliases/EntityPermission.md); `status`: `\"access\"`; \\} \\| \\{ `status`: `\"no_access\"`; \\}\\>\n\nRead the caller's effective permission on this entity.\n\n#### Returns\n\n`Promise`\\<\\{ `permission`: [`EntityPermission`](../../../../generated/storage/types.gen/type-aliases/EntityPermission.md); `status`: `\"access\"`; \\} \\| \\{ `status`: `\"no_access\"`; \\}\\>\n\n***\n\n### toJSON()\n\n> **toJSON**(): \\{ `detail?`: `Detail`; `id`: `string`; \\}\n\n#### Returns\n\n\\{ `detail?`: `Detail`; `id`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `detail?` | `Detail` |\n| `id` | `string` |\n\n#### Inherited from\n\n[`MacroEntity`](MacroEntity.md).[`toJSON`](MacroEntity.md#tojson)\n\n***\n\n### unfavorite()\n\n> **unfavorite**(): `Promise`\\<`FavoritableEntity`\\<`Detail`\\>\\>\n\nRemove this entity from the user's favorites. Returns this handle for chaining.\n\n#### Returns\n\n`Promise`\\<`FavoritableEntity`\\<`Detail`\\>\\>\n\n#### Implementation of\n\n[`Favoritable`](../interfaces/Favoritable.md).[`unfavorite`](../interfaces/Favoritable.md#unfavorite)\n\n\n<!-- src/entities/entity/classes/MacroEntity.md -->\n# Abstract Class: MacroEntity\\<Detail\\>\n\nBase for entity handles: a free-to-construct `(client, id)` pair whose\ndetail record loads lazily on first field access and is dropped after any\nmutation. Subclasses implement fetch and build their surface from\nfield and mutate.\n\n## Extended by\n\n- [`AgentSession`](../../agent-sessions/agent-session/classes/AgentSession.md)\n- [`CodeExecution`](../../agent-sessions/code-execution/classes/CodeExecution.md)\n- [`SessionReview`](../../agent-sessions/review/classes/SessionReview.md)\n- [`Agent`](../../agents/agent/classes/Agent.md)\n- [`UserApiKey`](../../api-keys/api-key/classes/UserApiKey.md)\n- [`Calendar`](../../calendar/calendar/classes/Calendar.md)\n- [`CalendarEvent`](../../calendar/event/classes/CalendarEvent.md)\n- [`CalendarNote`](../../calendar/note/classes/CalendarNote.md)\n- [`CallMessage`](../../calls/message/classes/CallMessage.md)\n- [`ChatMessage`](../../chats/generation/classes/ChatMessage.md)\n- [`CrmComment`](../../crm/comment/classes/CrmComment.md)\n- [`CrmPipeline`](../../crm/pipeline/classes/CrmPipeline.md)\n- [`PipelineTable`](../../crm/pipeline/classes/PipelineTable.md)\n- [`PipelineRow`](../../crm/pipeline/classes/PipelineRow.md)\n- [`PipelineColumn`](../../crm/pipeline/classes/PipelineColumn.md)\n- [`Database`](../../databases/database/classes/Database.md)\n- [`DocumentAnchor`](../../documents/anchor/classes/DocumentAnchor.md)\n- [`Comment`](../../documents/comment/classes/Comment.md)\n- [`EmailAttachment`](../../email/attachment/classes/EmailAttachment.md)\n- [`EmailFilter`](../../email/filter/classes/EmailFilter.md)\n- [`Label`](../../email/label/classes/Label.md)\n- [`Link`](../../email/link/classes/Link.md)\n- [`EmailMessage`](../../email/message/classes/EmailMessage.md)\n- [`FavoritableEntity`](FavoritableEntity.md)\n- [`Form`](../../forms/form/classes/Form.md)\n- [`GithubPullRequest`](../../github-pull-requests/pull-request/classes/GithubPullRequest.md)\n- [`Harness`](../../harnesses/harness/classes/Harness.md)\n- [`HarnessPairing`](../../harnesses/pairing/classes/HarnessPairing.md)\n- [`Initiative`](../../initiatives/initiative/classes/Initiative.md)\n- [`Meeting`](../../meetings/meeting/classes/Meeting.md)\n- [`MessageThread`](../../messages/thread/classes/MessageThread.md)\n- [`Notification`](../../notifications/notification/classes/Notification.md)\n- [`Routine`](../../routines/routine/classes/Routine.md)\n- [`AccessRequest`](../../sharing/access/classes/AccessRequest.md)\n- [`Team`](../../teams/team/classes/Team.md)\n- [`Webhook`](../../webhooks/webhook/classes/Webhook.md)\n\n## Type Parameters\n\n| Type Parameter |\n| ------ |\n| <a id=\"type-parameter-detail\"></a> `Detail` |\n\n## Properties\n\n| Property | Modifier | Type |\n| ------ | ------ | ------ |\n| <a id=\"property-id\"></a> `id` | `public readonly` | `string` |\n\n## Methods\n\n### toJSON()\n\n> **toJSON**(): \\{ `detail?`: `Detail`; `id`: `string`; \\}\n\n#### Returns\n\n\\{ `detail?`: `Detail`; `id`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `detail?` | `Detail` |\n| `id` | `string` |\n\n\n<!-- src/entities/entity/classes/PropertiedEntity.md -->\n# Abstract Class: PropertiedEntity\\<Detail\\>\n\nA favoritable entity that also carries user-defined properties.\n\n## Extends\n\n- [`FavoritableEntity`](FavoritableEntity.md)\\<`Detail`\\>\n\n## Extended by\n\n- [`Channel`](../../channels/channel/classes/Channel.md)\n- [`Chat`](../../chats/chat/classes/Chat.md)\n- [`Company`](../../crm/company/classes/Company.md)\n- [`Document`](../../documents/document/classes/Document.md)\n- [`EmailThread`](../../email/thread/classes/EmailThread.md)\n- [`Project`](../../projects/project/classes/Project.md)\n- [`User`](../../users/user/classes/User.md)\n\n## Type Parameters\n\n| Type Parameter |\n| ------ |\n| <a id=\"type-parameter-detail\"></a> `Detail` |\n\n## Implements\n\n- [`Propertied`](../interfaces/Propertied.md)\n\n## Properties\n\n| Property | Modifier | Type | Description | Inherited from |\n| ------ | ------ | ------ | ------ | ------ |\n| <a id=\"property-entitytype\"></a> `entityType` | `abstract readonly` | `\"project\"` \\| `\"user\"` \\| `\"team\"` \\| `\"chat\"` \\| `\"channel\"` \\| `\"channel_message\"` \\| `\"document\"` \\| `\"email_thread\"` \\| `\"calendar_event\"` \\| `\"call\"` \\| `\"foreign_entity\"` \\| `\"static_file\"` \\| `\"crm_company\"` \\| `\"crm_contact\"` \\| `\"crm_pipeline\"` \\| `\"reminder\"` \\| `\"skill\"` \\| `\"agent_session\"` \\| `\"scheduled_action\"` \\| `\"initiative\"` \\| `\"database\"` \\| `\"database_row\"` \\| `\"form\"` | How the entity-addressed APIs (favorites) identify this entity's type. | [`FavoritableEntity`](FavoritableEntity.md).[`entityType`](FavoritableEntity.md#property-entitytype) |\n| <a id=\"property-id\"></a> `id` | `public readonly` | `string` | - | [`FavoritableEntity`](FavoritableEntity.md).[`id`](FavoritableEntity.md#property-id) |\n\n## Methods\n\n### deleteProperty()\n\n> **deleteProperty**(`assignment`): `Promise`\\<`void`\\>\n\nRemove a property from this entity, given its [properties](#properties) entry.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `assignment` | [`EntityPropertyWithDefinition`](../../../../generated/properties/types.gen/type-aliases/EntityPropertyWithDefinition.md) |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n#### Implementation of\n\n[`Propertied`](../interfaces/Propertied.md).[`deleteProperty`](../interfaces/Propertied.md#deleteproperty)\n\n***\n\n### favorite()\n\n> **favorite**(): `Promise`\\<`PropertiedEntity`\\<`Detail`\\>\\>\n\nAdd this entity to the user's favorites. Returns this handle for chaining.\nPlain unwrap: favoriting alters the user's favorites collection, not this\nentity's own detail, so there's nothing cached to invalidate.\n\n#### Returns\n\n`Promise`\\<`PropertiedEntity`\\<`Detail`\\>\\>\n\n#### Implementation of\n\n[`Propertied`](../interfaces/Propertied.md).[`favorite`](../interfaces/Propertied.md#favorite)\n\n#### Inherited from\n\n[`FavoritableEntity`](FavoritableEntity.md).[`favorite`](FavoritableEntity.md#favorite)\n\n***\n\n### permission()\n\n> **permission**(): `Promise`\\<\\{ `permission`: [`EntityPermission`](../../../../generated/storage/types.gen/type-aliases/EntityPermission.md); `status`: `\"access\"`; \\} \\| \\{ `status`: `\"no_access\"`; \\}\\>\n\nRead the caller's effective permission on this entity.\n\n#### Returns\n\n`Promise`\\<\\{ `permission`: [`EntityPermission`](../../../../generated/storage/types.gen/type-aliases/EntityPermission.md); `status`: `\"access\"`; \\} \\| \\{ `status`: `\"no_access\"`; \\}\\>\n\n#### Inherited from\n\n[`FavoritableEntity`](FavoritableEntity.md).[`permission`](FavoritableEntity.md#permission)\n\n***\n\n### properties()\n\n> **properties**(`opts?`): `Promise`\\<[`EntityPropertyWithDefinition`](../../../../generated/properties/types.gen/type-aliases/EntityPropertyWithDefinition.md)[]\\>\n\nThe properties set on this entity, each with its definition, value, and options.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `opts?` | \\{ `includeMetadata?`: `boolean`; \\} |\n| `opts.includeMetadata?` | `boolean` |\n\n#### Returns\n\n`Promise`\\<[`EntityPropertyWithDefinition`](../../../../generated/properties/types.gen/type-aliases/EntityPropertyWithDefinition.md)[]\\>\n\n#### Implementation of\n\n[`Propertied`](../interfaces/Propertied.md).[`properties`](../interfaces/Propertied.md#properties)\n\n***\n\n### propertyReference()\n\n> **propertyReference**(): [`PropertyTargetReference`](../../../../generated/properties/types.gen/type-aliases/PropertyTargetReference.md)\n\nThis entity's reference for bulk property operations.\n\n#### Returns\n\n[`PropertyTargetReference`](../../../../generated/properties/types.gen/type-aliases/PropertyTargetReference.md)\n\n***\n\n### setProperty()\n\n> **setProperty**(`property`, `value?`): `Promise`\\<`void`\\>\n\nSet a property value on this entity, or attach the property without a\nvalue when `value` is omitted.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `property` | [`PropertyDefinition`](../../properties/property-definition/classes/PropertyDefinition.md) |\n| `value?` | [`SetPropertyValue`](../../../../generated/properties/types.gen/type-aliases/SetPropertyValue.md) |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n#### Implementation of\n\n[`Propertied`](../interfaces/Propertied.md).[`setProperty`](../interfaces/Propertied.md#setproperty)\n\n***\n\n### toJSON()\n\n> **toJSON**(): \\{ `detail?`: `Detail`; `id`: `string`; \\}\n\n#### Returns\n\n\\{ `detail?`: `Detail`; `id`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `detail?` | `Detail` |\n| `id` | `string` |\n\n#### Inherited from\n\n[`FavoritableEntity`](FavoritableEntity.md).[`toJSON`](FavoritableEntity.md#tojson)\n\n***\n\n### unfavorite()\n\n> **unfavorite**(): `Promise`\\<`PropertiedEntity`\\<`Detail`\\>\\>\n\nRemove this entity from the user's favorites. Returns this handle for chaining.\n\n#### Returns\n\n`Promise`\\<`PropertiedEntity`\\<`Detail`\\>\\>\n\n#### Implementation of\n\n[`Propertied`](../interfaces/Propertied.md).[`unfavorite`](../interfaces/Propertied.md#unfavorite)\n\n#### Inherited from\n\n[`FavoritableEntity`](FavoritableEntity.md).[`unfavorite`](FavoritableEntity.md#unfavorite)\n\n***\n\n### updatePropertyOptions()\n\n> **updatePropertyOptions**(`changes`): `Promise`\\<[`BulkUpdateEntityPropertyOptionsResponse`](../../../../generated/properties/types.gen/type-aliases/BulkUpdateEntityPropertyOptionsResponse.md)\\>\n\nApply multi-select option deltas atomically across this entity's properties.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `changes` | [`PropertyOptionDelta`](../interfaces/PropertyOptionDelta.md)[] |\n\n#### Returns\n\n`Promise`\\<[`BulkUpdateEntityPropertyOptionsResponse`](../../../../generated/properties/types.gen/type-aliases/BulkUpdateEntityPropertyOptionsResponse.md)\\>\n\n\n<!-- src/entities/entity/interfaces/Favoritable.md -->\n# Interface: Favoritable\n\nAn entity that can be added to and removed from the user's favorites.\n\n## Extended by\n\n- [`Propertied`](Propertied.md)\n\n## Methods\n\n### favorite()\n\n> **favorite**(): `Promise`\\<`Favoritable`\\>\n\n#### Returns\n\n`Promise`\\<`Favoritable`\\>\n\n***\n\n### unfavorite()\n\n> **unfavorite**(): `Promise`\\<`Favoritable`\\>\n\n#### Returns\n\n`Promise`\\<`Favoritable`\\>\n\n\n<!-- src/entities/entity/interfaces/Propertied.md -->\n# Interface: Propertied\n\nA favoritable entity that also carries user-defined properties.\n\n## Extends\n\n- [`Favoritable`](Favoritable.md)\n\n## Methods\n\n### deleteProperty()\n\n> **deleteProperty**(`assignment`): `Promise`\\<`void`\\>\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `assignment` | [`EntityPropertyWithDefinition`](../../../../generated/properties/types.gen/type-aliases/EntityPropertyWithDefinition.md) |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### favorite()\n\n> **favorite**(): `Promise`\\<`Propertied`\\>\n\n#### Returns\n\n`Promise`\\<`Propertied`\\>\n\n#### Inherited from\n\n[`Favoritable`](Favoritable.md).[`favorite`](Favoritable.md#favorite)\n\n***\n\n### properties()\n\n> **properties**(`opts?`): `Promise`\\<[`EntityPropertyWithDefinition`](../../../../generated/properties/types.gen/type-aliases/EntityPropertyWithDefinition.md)[]\\>\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `opts?` | \\{ `includeMetadata?`: `boolean`; \\} |\n| `opts.includeMetadata?` | `boolean` |\n\n#### Returns\n\n`Promise`\\<[`EntityPropertyWithDefinition`](../../../../generated/properties/types.gen/type-aliases/EntityPropertyWithDefinition.md)[]\\>\n\n***\n\n### setProperty()\n\n> **setProperty**(`property`, `value?`): `Promise`\\<`void`\\>\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `property` | [`PropertyDefinition`](../../properties/property-definition/classes/PropertyDefinition.md) |\n| `value?` | [`SetPropertyValue`](../../../../generated/properties/types.gen/type-aliases/SetPropertyValue.md) |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### unfavorite()\n\n> **unfavorite**(): `Promise`\\<`Propertied`\\>\n\n#### Returns\n\n`Promise`\\<`Propertied`\\>\n\n#### Inherited from\n\n[`Favoritable`](Favoritable.md).[`unfavorite`](Favoritable.md#unfavorite)\n\n\n<!-- src/entities/entity/interfaces/PropertyOptionDelta.md -->\n# Interface: PropertyOptionDelta\n\nA delta to apply to one multi-select property.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-add\"></a> `add?` | [`PropertyOption`](../../properties/property-option/classes/PropertyOption.md)[] | Options to add to the property's current selection. |\n| <a id=\"property-property\"></a> `property` | [`PropertyDefinition`](../../properties/property-definition/classes/PropertyDefinition.md) | The multi-select property definition to update. |\n| <a id=\"property-remove\"></a> `remove?` | [`PropertyOption`](../../properties/property-option/classes/PropertyOption.md)[] | Options to remove from the property's current selection. |\n\n\n<!-- src/entities/entity/type-aliases/MacroEntityType.md -->\n# Type Alias: MacroEntityType\n\n> **MacroEntityType** = [`FavoriteEntityRef`](../../../../generated/storage/types.gen/type-aliases/FavoriteEntityRef.md)\\[`\"entityType\"`\\]\n\nHow the entity-addressed APIs (favorites) identify an entity's type.\n\n\n<!-- src/entities/messages/thread/classes/MessageThread.md -->\n# Class: MessageThread\n\nA shared message thread with resolution and deletion operations.\n\n## Extends\n\n- [`MacroEntity`](../../../entity/classes/MacroEntity.md)\\<[`ThreadState`](../../../../../generated/storage/types.gen/type-aliases/ThreadState.md)\\>\n\n## Properties\n\n| Property | Modifier | Type | Description | Inherited from |\n| ------ | ------ | ------ | ------ | ------ |\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-parent\"></a> `parent` | `readonly` | [`MessageParent`](../type-aliases/MessageParent.md) | The entity containing this thread. | - |\n| <a id=\"property-resolved\"></a> `resolved` | `readonly` | () => `Promise`\\<`boolean`\\> | Whether the thread is resolved. | - |\n\n## Methods\n\n### delete()\n\n> **delete**(`nonce?`): `Promise`\\<`void`\\>\n\nDelete the entire thread, including replies.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `nonce?` | `string` |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### toJSON()\n\n> **toJSON**(): \\{ `detail?`: [`ThreadState`](../../../../../generated/storage/types.gen/type-aliases/ThreadState.md); `id`: `string`; `parentId`: `string`; `parentType`: `\"channel\"` \\| `\"document\"` \\| `\"call\"` \\| `\"crm_company\"` \\| `\"crm_contact\"`; \\}\n\nSerialize identity with its owning resource.\n\n#### Returns\n\n\\{ `detail?`: [`ThreadState`](../../../../../generated/storage/types.gen/type-aliases/ThreadState.md); `id`: `string`; `parentId`: `string`; `parentType`: `\"channel\"` \\| `\"document\"` \\| `\"call\"` \\| `\"crm_company\"` \\| `\"crm_contact\"`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `detail?` | [`ThreadState`](../../../../../generated/storage/types.gen/type-aliases/ThreadState.md) |\n| `id` | `string` |\n| `parentId` | `string` |\n| `parentType` | `\"channel\"` \\| `\"document\"` \\| `\"call\"` \\| `\"crm_company\"` \\| `\"crm_contact\"` |\n\n#### Overrides\n\n[`MacroEntity`](../../../entity/classes/MacroEntity.md).[`toJSON`](../../../entity/classes/MacroEntity.md#tojson)\n\n***\n\n### update()\n\n> **update**(`options`): `Promise`\\<`void`\\>\n\nResolve the thread or detach its annotation anchor.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `options` | \\{ `detachAnchor?`: `boolean`; `nonce?`: `string`; `resolved?`: `boolean`; \\} |\n| `options.detachAnchor?` | `boolean` |\n| `options.nonce?` | `string` |\n| `options.resolved?` | `boolean` |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### byId()\n\n> `static` **byId**(`client`, `parent`, `id`): `MessageThread`\n\nConstruct a scoped thread handle.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `parent` | [`MessageParent`](../type-aliases/MessageParent.md) |\n| `id` | `string` |\n\n#### Returns\n\n`MessageThread`\n\n\n<!-- src/entities/messages/thread/functions/timeline.md -->\n# Function: timeline()\n\n> **timeline**\\<`TMessage`\\>(`client`, `parent`, `map`, `selection?`): `Promise`\\<\\{ `entries`: (\\{ `activity`: \\{ `action`: `string`; `actor`: [`User`](../../../users/user/classes/User.md); `actor_id`: `string`; `id`: `string`; `occurred_at`: `string`; `payload?`: `unknown`; \\}; `message?`: `undefined`; `type`: `\"activity\"`; \\} \\| \\{ `activity?`: `undefined`; `message`: `TMessage`; `type`: `\"message\"`; \\})[]; `nextCursor`: [`MessageCursor`](../../../../../generated/storage/types.gen/type-aliases/MessageCursor.md) \\| `undefined`; `previousCursor`: [`MessageCursor`](../../../../../generated/storage/types.gen/type-aliases/MessageCursor.md) \\| `undefined`; \\}\\>\n\nA bounded mixed message/activity page with typed message handles.\n\n## Type Parameters\n\n| Type Parameter |\n| ------ |\n| <a id=\"type-parameter-tmessage\"></a> `TMessage` *extends* [`TimelineMessage`](../type-aliases/TimelineMessage.md) |\n\n## Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `parent` | [`MessageParent`](../type-aliases/MessageParent.md) |\n| `map` | (`record`) => `TMessage` |\n| `selection?` | [`TimelineOptions`](../interfaces/TimelineOptions.md)\\<`TMessage`\\> |\n\n## Returns\n\n`Promise`\\<\\{ `entries`: (\\{ `activity`: \\{ `action`: `string`; `actor`: [`User`](../../../users/user/classes/User.md); `actor_id`: `string`; `id`: `string`; `occurred_at`: `string`; `payload?`: `unknown`; \\}; `message?`: `undefined`; `type`: `\"activity\"`; \\} \\| \\{ `activity?`: `undefined`; `message`: `TMessage`; `type`: `\"message\"`; \\})[]; `nextCursor`: [`MessageCursor`](../../../../../generated/storage/types.gen/type-aliases/MessageCursor.md) \\| `undefined`; `previousCursor`: [`MessageCursor`](../../../../../generated/storage/types.gen/type-aliases/MessageCursor.md) \\| `undefined`; \\}\\>\n\n\n<!-- src/entities/messages/thread/interfaces/TimelineOptions.md -->\n# Interface: TimelineOptions\\<TMessage\\>\n\nTimeline selection with typed message references and camel case options.\n\n## Type Parameters\n\n| Type Parameter | Default type |\n| ------ | ------ |\n| <a id=\"type-parameter-tmessage\"></a> `TMessage` *extends* [`TimelineMessage`](../type-aliases/TimelineMessage.md) | [`TimelineMessage`](../type-aliases/TimelineMessage.md) |\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-activityafter\"></a> `activityAfter?` | `string` | Inclusive activity lower bound. |\n| <a id=\"property-activitybefore\"></a> `activityBefore?` | `string` | Exclusive activity upper bound. |\n| <a id=\"property-anchored\"></a> `anchored?` | `boolean` | Select anchored threads. |\n| <a id=\"property-around\"></a> `around?` | `TMessage` | Fetch around this message. |\n| <a id=\"property-cursor\"></a> `cursor?` | [`MessageCursor`](../../../../../generated/storage/types.gen/type-aliases/MessageCursor.md) \\| `null` | Opaque continuation cursor from a previous page. |\n| <a id=\"property-direction\"></a> `direction?` | [`MessageDirection`](../../../../../generated/storage/types.gen/type-aliases/MessageDirection.md) | Page direction. |\n| <a id=\"property-includedeletedthreads\"></a> `includeDeletedThreads?` | `boolean` | Include deleted threads. |\n| <a id=\"property-limit\"></a> `limit?` | `number` | Page size. |\n| <a id=\"property-messages\"></a> `messages?` | `TMessage`[] | Restrict selection to these messages. |\n\n\n<!-- src/entities/messages/thread/type-aliases/MessageParent.md -->\n# Type Alias: MessageParent\n\n> **MessageParent** = \\{ `entity`: [`Channel`](../../../channels/channel/classes/Channel.md); `type`: `\"channel\"`; \\} \\| \\{ `entity`: [`Document`](../../../documents/document/classes/Document.md); `type`: `\"document\"`; \\} \\| \\{ `entity`: [`Company`](../../../crm/company/classes/Company.md); `type`: `\"crm_company\"`; \\} \\| \\{ `entity`: [`Contact`](../../../crm/contact/classes/Contact.md); `type`: `\"crm_contact\"`; \\} \\| \\{ `entity`: [`CallRecord`](../../../calls/call-record/classes/CallRecord.md); `type`: `\"call\"`; \\}\n\nThe typed parent of a shared message thread.\n\n\n<!-- src/entities/messages/thread/type-aliases/TimelineMessage.md -->\n# Type Alias: TimelineMessage\n\n> **TimelineMessage** = [`Message`](../../../channels/message/classes/Message.md) \\| [`Comment`](../../../documents/comment/classes/Comment.md) \\| [`CrmComment`](../../../crm/comment/classes/CrmComment.md) \\| [`CallMessage`](../../../calls/message/classes/CallMessage.md)\n\nA message handle accepted by a mixed timeline selector.\n\n\n<!-- src/entities/reference/type-aliases/EntityReference.md -->\n# Type Alias: EntityReference\n\n> **EntityReference** = \\{ `entity`: [`User`](../../users/user/classes/User.md); `type`: `\"user\"`; \\} \\| \\{ `entity`: [`Team`](../../teams/team/classes/Team.md); `type`: `\"team\"`; \\} \\| \\{ `entity`: [`Document`](../../documents/document/classes/Document.md); `type`: `\"document\"`; \\} \\| \\{ `entity`: [`Chat`](../../chats/chat/classes/Chat.md); `type`: `\"chat\"`; \\} \\| \\{ `entity`: [`Channel`](../../channels/channel/classes/Channel.md); `type`: `\"channel\"`; \\} \\| \\{ `entity`: [`Message`](../../channels/message/classes/Message.md); `type`: `\"channel_message\"`; \\} \\| \\{ `entity`: [`Project`](../../projects/project/classes/Project.md); `type`: `\"project\"`; \\} \\| \\{ `entity`: [`EmailThread`](../../email/thread/classes/EmailThread.md); `type`: `\"email_thread\"`; \\} \\| \\{ `entity`: [`CalendarEvent`](../../calendar/event/classes/CalendarEvent.md); `type`: `\"calendar_event\"`; \\} \\| \\{ `entity`: [`CallRecord`](../../calls/call-record/classes/CallRecord.md); `type`: `\"call\"`; \\} \\| \\{ `entity`: [`ForeignEntity`](../../foreign/foreign-entity/classes/ForeignEntity.md); `type`: `\"foreign_entity\"`; \\} \\| \\{ `entity`: [`Company`](../../crm/company/classes/Company.md); `type`: `\"crm_company\"`; \\} \\| \\{ `entity`: [`Contact`](../../crm/contact/classes/Contact.md); `type`: `\"crm_contact\"`; \\} \\| \\{ `entity`: [`CrmPipeline`](../../crm/pipeline/classes/CrmPipeline.md); `type`: `\"crm_pipeline\"`; \\} \\| \\{ `entity`: [`AgentSession`](../../agent-sessions/agent-session/classes/AgentSession.md); `type`: `\"agent_session\"`; \\} \\| \\{ `entity`: [`Routine`](../../routines/routine/classes/Routine.md); `type`: `\"scheduled_action\"`; \\} \\| \\{ `entity`: [`Initiative`](../../initiatives/initiative/classes/Initiative.md); `type`: `\"initiative\"`; \\} \\| \\{ `entity`: [`Database`](../../databases/database/classes/Database.md); `type`: `\"database\"`; \\} \\| \\{ `entity`: [`DatabaseRow`](../../databases/row/classes/DatabaseRow.md); `type`: `\"database_row\"`; \\} \\| \\{ `entity`: [`Form`](../../forms/form/classes/Form.md); `type`: `\"form\"`; \\}\n\nTyped entity references accepted by cross-resource APIs.\n\n\n<!-- src/entities/search/functions/entitySearch.md -->\n# Function: entitySearch()\n\n> **entitySearch**\\<`T`, `K`\\>(`opts`): (`client`, `query`, `searchOpts?`) => `AsyncGenerator`\\<`T`\\>\n\nBuild a `search(client, query, opts?)` function for one entity type: unified\nsearch hits narrowed to `type`, each mapped through `make`.\nMost relevant first, auto-paginated.\n\n## Type Parameters\n\n| Type Parameter |\n| ------ |\n| <a id=\"type-parameter-t\"></a> `T` |\n| <a id=\"type-parameter-k\"></a> `K` *extends* `\"email\"` \\| `\"project\"` \\| `\"chat\"` \\| `\"channel\"` \\| `\"document\"` \\| `\"call\"` \\| `\"company\"` \\| `\"calendarEvent\"` \\| `\"agentSession\"` \\| `\"channelMessage\"` |\n\n## Parameters\n\n| Parameter | Type | Description |\n| ------ | ------ | ------ |\n| `opts` | \\{ `filters?`: [`EntityFilters`](../../../../generated/search/types.gen/type-aliases/EntityFilters.md); `includeCrm?`: `boolean`; `make`: (`client`, `hit`) => `T`; `type`: `K`; \\} | - |\n| `opts.filters?` | [`EntityFilters`](../../../../generated/search/types.gen/type-aliases/EntityFilters.md) | - |\n| `opts.includeCrm?` | `boolean` | Opt in to CRM results (off by default server-side; required for company hits). |\n| `opts.make` | (`client`, `hit`) => `T` | - |\n| `opts.type` | `K` | - |\n\n## Returns\n\n(`client`, `query`, `searchOpts?`) => `AsyncGenerator`\\<`T`\\>\n\n\n<!-- src/entities/search/interfaces/SearchOpts.md -->\n# Interface: SearchOpts\n\n## Properties\n\n| Property | Type |\n| ------ | ------ |\n| <a id=\"property-pagesize\"></a> `pageSize?` | `number` |\n| <a id=\"property-searchon\"></a> `searchOn?` | [`SearchOn`](../type-aliases/SearchOn.md) |\n\n\n<!-- src/entities/search/type-aliases/SearchOn.md -->\n# Type Alias: SearchOn\n\n> **SearchOn** = `\"name\"` \\| `\"content\"` \\| `\"name_content\"`\n\n\n<!-- src/entities/sharing/access/classes/AccessRequest.md -->\n# Class: AccessRequest\n\nOne access request; resolutions preserve optimistic concurrency.\n\n## Extends\n\n- [`MacroEntity`](../../../entity/classes/MacroEntity.md)\\<[`AccessRequest`](../../../../../generated/storage/types.gen/type-aliases/AccessRequest.md)\\>\n\n## Properties\n\n| Property | Modifier | Type | Description | Inherited from |\n| ------ | ------ | ------ | ------ | ------ |\n| <a id=\"property-access\"></a> `access` | `readonly` | [`EntityAccess`](EntityAccess.md) | Entity access surface owning the request. | - |\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-requestedlevel\"></a> `requestedLevel` | `readonly` | () => `Promise`\\<[`AccessLevel`](../../../../../generated/storage/types.gen/type-aliases/AccessLevel.md)\\> | Requested access. | - |\n| <a id=\"property-requester\"></a> `requester` | `readonly` | () => `Promise`\\<[`User`](../../../users/user/classes/User.md)\\> | Requesting user. | - |\n| <a id=\"property-revision\"></a> `revision` | `readonly` | () => `Promise`\\<`number`\\> | Request revision. | - |\n| <a id=\"property-status\"></a> `status` | `readonly` | () => `Promise`\\<[`RequestStatus`](../../../../../generated/storage/types.gen/type-aliases/RequestStatus.md)\\> | Current request state. | - |\n\n## Methods\n\n### resolve()\n\n> **resolve**(`grantedLevel?`): `Promise`\\<`void`\\>\n\nApprove with an access level, or decline by omitting it.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `grantedLevel?` | [`AccessLevel`](../../../../../generated/storage/types.gen/type-aliases/AccessLevel.md) |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### toJSON()\n\n> **toJSON**(): \\{ `detail?`: [`AccessRequest`](../../../../../generated/storage/types.gen/type-aliases/AccessRequest.md); `id`: `string`; \\}\n\n#### Returns\n\n\\{ `detail?`: [`AccessRequest`](../../../../../generated/storage/types.gen/type-aliases/AccessRequest.md); `id`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `detail?` | [`AccessRequest`](../../../../../generated/storage/types.gen/type-aliases/AccessRequest.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### from()\n\n> `static` **from**(`client`, `access`, `record`): `AccessRequest`\n\nSeed a request from a state or submission response.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `access` | [`EntityAccess`](EntityAccess.md) |\n| `record` | [`AccessRequest`](../../../../../generated/storage/types.gen/type-aliases/AccessRequest.md) |\n\n#### Returns\n\n`AccessRequest`\n\n\n<!-- src/entities/sharing/access/classes/EntityAccess.md -->\n# Class: EntityAccess\n\nAccess requests and direct grants scoped to a shareable entity.\n\n## Constructors\n\n### Constructor\n\n> **new EntityAccess**(`client`, `entityType`, `entity`): `EntityAccess`\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `entityType` | [`ShareEntityType`](../../../../../generated/storage/types.gen/type-aliases/ShareEntityType.md) |\n| `entity` | \\{ `id`: `string`; \\} |\n| `entity.id` | `string` |\n\n#### Returns\n\n`EntityAccess`\n\n## Methods\n\n### cancel()\n\n> **cancel**(`revision`): `Promise`\\<`void`\\>\n\nCancel the caller's own request at its observed revision.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `revision` | `number` |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### direct()\n\n> **direct**(): `Promise`\\<\\{ `accessLevel`: [`AccessLevel`](../../../../../generated/storage/types.gen/type-aliases/AccessLevel.md); `user`: [`User`](../../../users/user/classes/User.md); \\}[]\\>\n\nDirect grants expressed as user handles.\n\n#### Returns\n\n`Promise`\\<\\{ `accessLevel`: [`AccessLevel`](../../../../../generated/storage/types.gen/type-aliases/AccessLevel.md); `user`: [`User`](../../../users/user/classes/User.md); \\}[]\\>\n\n***\n\n### grant()\n\n> **grant**(`user`, `accessLevel?`): `Promise`\\<`void`\\>\n\nGrant direct access, or remove it by omitting the access level.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `user` | [`User`](../../../users/user/classes/User.md) |\n| `accessLevel?` | [`AccessLevel`](../../../../../generated/storage/types.gen/type-aliases/AccessLevel.md) |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### remove()\n\n> **remove**(`user`): `Promise`\\<`void`\\>\n\nRemove one user's direct grant.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `user` | [`User`](../../../users/user/classes/User.md) |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### resolve()\n\n> **resolve**(`request`, `resolution`): `Promise`\\<[`AccessRequest`](../../../../../generated/storage/types.gen/type-aliases/AccessRequest.md)\\>\n\nResolve a request belonging to this entity at an observed revision.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `request` | [`AccessRequest`](AccessRequest.md) |\n| `resolution` | [`ResolveRequest`](../../../../../generated/storage/types.gen/type-aliases/ResolveRequest.md) |\n\n#### Returns\n\n`Promise`\\<[`AccessRequest`](../../../../../generated/storage/types.gen/type-aliases/AccessRequest.md)\\>\n\n***\n\n### state()\n\n> **state**(`offset?`): `Promise`\\<\\{ `accessLevel`: [`AccessLevel`](../../../../../generated/storage/types.gen/type-aliases/AccessLevel.md) \\| `undefined`; `canReview`: `boolean`; `mine`: [`AccessRequest`](AccessRequest.md) \\| `undefined`; `nextOffset`: `number` \\| `undefined`; `owner`: [`User`](../../../users/user/classes/User.md) \\| `undefined`; `pendingCount`: `number`; `requests`: [`AccessRequest`](AccessRequest.md)[]; `supportedLevels`: [`AccessLevel`](../../../../../generated/storage/types.gen/type-aliases/AccessLevel.md)[]; \\}\\>\n\nA page of access requests, including the caller's own request and review rights.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `offset?` | `number` |\n\n#### Returns\n\n`Promise`\\<\\{ `accessLevel`: [`AccessLevel`](../../../../../generated/storage/types.gen/type-aliases/AccessLevel.md) \\| `undefined`; `canReview`: `boolean`; `mine`: [`AccessRequest`](AccessRequest.md) \\| `undefined`; `nextOffset`: `number` \\| `undefined`; `owner`: [`User`](../../../users/user/classes/User.md) \\| `undefined`; `pendingCount`: `number`; `requests`: [`AccessRequest`](AccessRequest.md)[]; `supportedLevels`: [`AccessLevel`](../../../../../generated/storage/types.gen/type-aliases/AccessLevel.md)[]; \\}\\>\n\n***\n\n### submit()\n\n> **submit**(`requestedLevel`, `revision?`): `Promise`\\<[`AccessRequest`](AccessRequest.md)\\>\n\nRequest access, optionally naming the revision of an earlier request.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `requestedLevel` | [`AccessLevel`](../../../../../generated/storage/types.gen/type-aliases/AccessLevel.md) |\n| `revision?` | `number` |\n\n#### Returns\n\n`Promise`\\<[`AccessRequest`](AccessRequest.md)\\>\n\n***\n\n### toJSON()\n\n> **toJSON**(): \\{ `entity_id`: `string`; `entity_type`: [`ShareEntityType`](../../../../../generated/storage/types.gen/type-aliases/ShareEntityType.md); \\}\n\nSerialize the entity reference without credentials.\n\n#### Returns\n\n\\{ `entity_id`: `string`; `entity_type`: [`ShareEntityType`](../../../../../generated/storage/types.gen/type-aliases/ShareEntityType.md); \\}\n\n| Name | Type |\n| ------ | ------ |\n| `entity_id` | `string` |\n| `entity_type` | [`ShareEntityType`](../../../../../generated/storage/types.gen/type-aliases/ShareEntityType.md) |\n\n\n<!-- src/entities/sharing/permissions/functions/sharePermissionBody.md -->\n# Function: sharePermissionBody()\n\n> **sharePermissionBody**(`options`): [`UpdateSharePermissionRequestV2`](../../../../../generated/storage/types.gen/type-aliases/UpdateSharePermissionRequestV2.md)\n\nConvert sharing options into the generated backend contract.\n\n## Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `options` | [`SharePermissionOptions`](../type-aliases/SharePermissionOptions.md) |\n\n## Returns\n\n[`UpdateSharePermissionRequestV2`](../../../../../generated/storage/types.gen/type-aliases/UpdateSharePermissionRequestV2.md)\n\n\n<!-- src/entities/sharing/permissions/type-aliases/SharePermissionOptions.md -->\n# Type Alias: SharePermissionOptions\n\n> **SharePermissionOptions** = `Omit`\\<[`UpdateSharePermissionRequestV2`](../../../../../generated/storage/types.gen/type-aliases/UpdateSharePermissionRequestV2.md), `\"channelSharePermissions\"`\\> & \\{ `channelSharePermissions?`: \\{ `accessLevel?`: [`AccessLevel`](../../../../../generated/storage/types.gen/type-aliases/AccessLevel.md); `channel`: [`Channel`](../../../channels/channel/classes/Channel.md); `operation`: [`UpdateChannelSharePermission`](../../../../../generated/storage/types.gen/type-aliases/UpdateChannelSharePermission.md)\\[`\"operation\"`\\]; \\}[] \\| `null`; \\}\n\nSharing updates reference channels by handle. Null clears the corresponding grant collection.\n\n## Type Declaration\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `channelSharePermissions?` | \\{ `accessLevel?`: [`AccessLevel`](../../../../../generated/storage/types.gen/type-aliases/AccessLevel.md); `channel`: [`Channel`](../../../channels/channel/classes/Channel.md); `operation`: [`UpdateChannelSharePermission`](../../../../../generated/storage/types.gen/type-aliases/UpdateChannelSharePermission.md)\\[`\"operation\"`\\]; \\}[] \\| `null` | Channel grants to create or replace. |\n\n\n<!-- src/events/receiver/classes/MacroEvents.md -->\n# Class: MacroEvents\n\nPer-instance event receiver. Subscribe with [MacroEvents.on](#on), then\neither [MacroEvents.listen](#listen) (SSE, the default) or mount\n[MacroEvents.webhook](#webhook) at a persisted webhook URL.\n\nObtain via `macro.events` — do not construct directly.\n\n## Constructors\n\n### Constructor\n\n> **new MacroEvents**(`client`, `secret?`): `MacroEvents`\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `secret?` | `string` |\n\n#### Returns\n\n`MacroEvents`\n\n## Methods\n\n### handle()\n\n> **handle**(`rawBody`, `headers`): `Promise`\\<`void`\\>\n\nFeed a raw webhook delivery in: verifies the signature, parses, and\ndispatches to matching handlers.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `rawBody` | `string` |\n| `headers` | `DeliveryHeaders` |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n#### Throws\n\nif no signing secret was configured, or if the\n signature is missing or invalid.\n\n***\n\n### listen()\n\n> **listen**(`opts?`): `Promise`\\<() => `void`\\>\n\nOpen a live Server-Sent Events stream of matching broker events. This is\nthe default way to receive events — no public URL or signing secret\nrequired. Delivery is best-effort: events published before the\nconnection, while disconnected, or dropped for a slow subscriber are\nmissed; there is no replay.\n\nFilters default to the event names currently registered with [on](#on).\nThe stream uses those filters for its lifetime; later `.on` / unsubscribe\ncalls do not change what the server sends.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `opts?` | [`ListenOptions`](../interfaces/ListenOptions.md) |\n\n#### Returns\n\n`Promise`\\<() => `void`\\>\n\nA function that closes the stream.\n\n***\n\n### on()\n\n> **on**\\<`E`\\>(`event`, `handler`): () => `void`\n\nSubscribe to an event across all entities.\n\n#### Type Parameters\n\n| Type Parameter |\n| ------ |\n| <a id=\"type-parameter-e\"></a> `E` *extends* `\"agent_session.opened\"` \\| `\"agent_session.turn_started\"` \\| `\"agent_session.turn_ended\"` \\| `\"agent_session.command_rejected\"` \\| `\"agent_session.settled\"` \\| `\"agent_session.waiting_for_input\"` \\| `\"agent_session.input_received\"` \\| `\"agent_session.mentioned\"` \\| `\"agent_session.stopped\"` \\| `\"agent_session.renamed\"` \\| `\"agent_session.deleted\"` \\| `\"channel.picture_changed\"` \\| `\"channel.created\"` \\| `\"channel.updated\"` \\| `\"channel.deleted\"` \\| `\"channel.participant_added\"` \\| `\"channel.participant_removed\"` \\| `\"document.created\"` \\| `\"document.updated\"` \\| `\"document.deleted\"` \\| `\"document.content_uploaded\"` \\| `\"document.sync_content_updated\"` \\| `\"document.purged\"` \\| `\"document.copied\"` \\| `\"document.interaction\"` \\| `\"message.posted\"` \\| `\"message.patched\"` \\| `\"message.deleted\"` \\| `\"message.mentioned\"` \\| `\"message.attachment_created\"` \\| `\"message.attachment_removed\"` |\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `event` | `E` |\n| `handler` | `EventHandler`\\<`E`\\> |\n\n#### Returns\n\nAn unsubscribe function.\n\n() => `void`\n\n***\n\n### onSelfMention()\n\n> **onSelfMention**(`handler`): () => `void`\n\nSubscribe to @-mentions of the authenticated caller: `message.mentioned`\ndeliveries whose mentioned entity is this bot (bot auth) or this user\n(user auth), in channels and in document comments alike.\n\n`message.mentioned` deliveries cover every mention the stream's (or\nwebhook's) workspace can access (its `ids` filter holds channel or\ndocument ids); picking out \"me\" happens here, client-side. The caller's\nidentity is resolved lazily (once) on the first delivery.\n\nFor SSE, register this handler before [listen](#listen) so the derived\nfilters include `message.mentioned`. For persisted webhooks, register the\nwebhook separately, e.g. `macro.webhooks.create({ filters: [{ events:\n['message.mentioned'] }], … })`.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `handler` | `EventHandler`\\<`\"message.mentioned\"`\\> |\n\n#### Returns\n\nAn unsubscribe function.\n\n() => `void`\n\n***\n\n### webhook()\n\n> **webhook**(): (`req`) => `Promise`\\<`Response`\\>\n\nA Fetch-style handler to mount at your persisted webhook route.\n\nRequires `webhookSecret` (or `MACRO_WEBHOOK_SECRET`).\n\n#### Returns\n\n(`req`) => `Promise`\\<`Response`\\>\n\n#### Example\n\n```ts\napp.post('/webhook', macro.events.webhook()); // Hono\n```\n\n\n<!-- src/events/receiver/interfaces/ListenOptions.md -->\n# Interface: ListenOptions\n\nOptions for [MacroEvents.listen](../classes/MacroEvents.md#listen).\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-filters\"></a> `filters?` | [`WebhookFilter`](../../../../generated/storage/types.gen/type-aliases/WebhookFilter.md)[] | Event/entity-id filters, identical to persisted webhook `filters`. Defaults to one filter covering every event currently registered with [MacroEvents.on](../classes/MacroEvents.md#on). |\n| <a id=\"property-scope\"></a> `scope?` | [`WebhookScope`](../../../../generated/storage/types.gen/type-aliases/WebhookScope.md) | Personal or team workspace whose webhook lifecycle events are delivered. Defaults to `'user'`. |\n| <a id=\"property-signal\"></a> `signal?` | `AbortSignal` | Abort the stream. |\n\n\n<!-- src/macro/classes/Macro.md -->\n# Class: Macro\\<T\\>\n\n## Type Parameters\n\n| Type Parameter | Default type |\n| ------ | ------ |\n| <a id=\"type-parameter-t\"></a> `T` *extends* [`MacroOpts`](../../config/interfaces/MacroOpts.md) | [`MacroOpts`](../../config/interfaces/MacroOpts.md) |\n\n## Constructors\n\n### Constructor\n\n> **new Macro**\\<`T`\\>(`opts`): `Macro`\\<`T`\\>\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `opts` | `T` |\n\n#### Returns\n\n`Macro`\\<`T`\\>\n\n## Properties\n\n| Property | Modifier | Type | Description |\n| ------ | ------ | ------ | ------ |\n| <a id=\"property-_client\"></a> `_client` | `readonly` | `MacroClient` | Direct access to the underlying hey-api service clients. |\n| <a id=\"property-agents\"></a> `agents` | `readonly` | [`AgentNamespace`](../../entities/agents/namespace/classes/AgentNamespace.md) | agents resources and operations. |\n| <a id=\"property-agentsessions\"></a> `agentSessions` | `readonly` | [`AgentSessionNamespace`](../../entities/agent-sessions/namespace/classes/AgentSessionNamespace.md) | - |\n| <a id=\"property-ai\"></a> `ai` | `readonly` | [`AiNamespace`](../../entities/ai/namespace/classes/AiNamespace.md) | - |\n| <a id=\"property-apikeys\"></a> `apiKeys` | `readonly` | [`ApiKeyNamespace`](../../entities/api-keys/namespace/classes/ApiKeyNamespace.md) | apiKeys resources and operations. |\n| <a id=\"property-bots\"></a> `bots` | `readonly` | [`BotsNamespace`](../../entities/bots/namespace/classes/BotsNamespace.md) | - |\n| <a id=\"property-calendar\"></a> `calendar` | `readonly` | [`CalendarNamespace`](../../entities/calendar/namespace/classes/CalendarNamespace.md) | - |\n| <a id=\"property-calls\"></a> `calls` | `readonly` | [`CallRecordNamespace`](../../entities/calls/namespace/classes/CallRecordNamespace.md) | - |\n| <a id=\"property-channels\"></a> `channels` | `readonly` | [`ChannelNamespace`](../../entities/channels/namespace/classes/ChannelNamespace.md) | - |\n| <a id=\"property-crm\"></a> `crm` | `readonly` | [`CrmNamespace`](../../entities/crm/namespace/classes/CrmNamespace.md) | - |\n| <a id=\"property-databases\"></a> `databases` | `readonly` | [`DatabaseNamespace`](../../entities/databases/namespace/classes/DatabaseNamespace.md) | - |\n| <a id=\"property-documents\"></a> `documents` | `readonly` | [`DocumentNamespace`](../../entities/documents/namespace/classes/DocumentNamespace.md) | - |\n| <a id=\"property-email\"></a> `email` | `readonly` | [`EmailNamespace`](../../entities/email/namespace/classes/EmailNamespace.md) | - |\n| <a id=\"property-entitymentions\"></a> `entityMentions` | `readonly` | [`EntityMentionNamespace`](../../entities/entity-mentions/namespace/classes/EntityMentionNamespace.md) | entityMentions resources and operations. |\n| <a id=\"property-events\"></a> `events` | `readonly` | [`MacroEvents`](../../events/receiver/classes/MacroEvents.md) | - |\n| <a id=\"property-favorites\"></a> `favorites` | `readonly` | [`FavoritesNamespace`](../../entities/favorites/namespace/classes/FavoritesNamespace.md) | - |\n| <a id=\"property-foreignentities\"></a> `foreignEntities` | `readonly` | [`ForeignEntityNamespace`](../../entities/foreign/namespace/classes/ForeignEntityNamespace.md) | - |\n| <a id=\"property-forms\"></a> `forms` | `readonly` | [`FormNamespace`](../../entities/forms/namespace/classes/FormNamespace.md) | Build forms and submit answers without granting respondents database access. |\n| <a id=\"property-githubpullrequests\"></a> `githubPullRequests` | `readonly` | [`GithubPullRequestNamespace`](../../entities/github-pull-requests/namespace/classes/GithubPullRequestNamespace.md) | githubPullRequests resources and operations. |\n| <a id=\"property-harnesses\"></a> `harnesses` | `readonly` | [`HarnessNamespace`](../../entities/harnesses/namespace/classes/HarnessNamespace.md) | harnesses resources and operations. |\n| <a id=\"property-initiatives\"></a> `initiatives` | `readonly` | [`InitiativeNamespace`](../../entities/initiatives/namespace/classes/InitiativeNamespace.md) | initiatives resources and operations. |\n| <a id=\"property-meetings\"></a> `meetings` | `readonly` | [`MeetingNamespace`](../../entities/meetings/namespace/classes/MeetingNamespace.md) | meetings resources and operations. |\n| <a id=\"property-notifications\"></a> `notifications` | `readonly` | [`NotificationNamespace`](../../entities/notifications/namespace/classes/NotificationNamespace.md) | - |\n| <a id=\"property-pins\"></a> `pins` | `readonly` | [`PinsNamespace`](../../entities/pins/namespace/classes/PinsNamespace.md) | - |\n| <a id=\"property-projects\"></a> `projects` | `readonly` | [`ProjectNamespace`](../../entities/projects/namespace/classes/ProjectNamespace.md) | - |\n| <a id=\"property-properties\"></a> `properties` | `readonly` | [`PropertiesNamespace`](../../entities/properties/namespace/classes/PropertiesNamespace.md) | - |\n| <a id=\"property-routines\"></a> `routines` | `readonly` | [`RoutineNamespace`](../../entities/routines/namespace/classes/RoutineNamespace.md) | routines resources and operations. |\n| <a id=\"property-tasks\"></a> `tasks` | `readonly` | [`TaskNamespace`](../../entities/tasks/namespace/classes/TaskNamespace.md) | - |\n| <a id=\"property-teams\"></a> `teams` | `readonly` | [`TeamNamespace`](../../entities/teams/namespace/classes/TeamNamespace.md) | - |\n| <a id=\"property-unfurls\"></a> `unfurls` | `readonly` | [`UnfurlNamespace`](../../entities/unfurls/namespace/classes/UnfurlNamespace.md) | unfurls resources and operations. |\n| <a id=\"property-users\"></a> `users` | `readonly` | [`UserNamespace`](../../entities/users/namespace/classes/UserNamespace.md) | - |\n| <a id=\"property-webappurl\"></a> `webAppUrl` | `readonly` | `string` | Base URL of the Macro web app, used to build entity URLs. |\n| <a id=\"property-webhooks\"></a> `webhooks` | `readonly` | [`WebhooksNamespace`](../../entities/webhooks/namespace/classes/WebhooksNamespace.md) | - |\n\n## Methods\n\n### myPrincipalId()\n\n> **myPrincipalId**(): `Promise`\\<`string`\\>\n\nThe authenticated caller's mentionable principal — `bot|<uuid>` for bot\nauth, `macro|<email>` for user auth — fetched once and cached.\n\n#### Returns\n\n`Promise`\\<`string`\\>\n\n***\n\n### requestedAs()\n\n> **requestedAs**(`user`): `Macro`\\<`T`\\>\n\nClone of this SDK acting on behalf of `user` (sent as\n`x-macro-bot-for-macro-user-id`). Bot auth only — throws for user auth,\nsince a user token always acts as its own user.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `user` | [`User`](../../entities/users/user/classes/User.md) |\n\n#### Returns\n\n`Macro`\\<`T`\\>\n\n\n<!-- src/macro/type-aliases/RequestActivity.md -->\n# Type Alias: RequestActivity\n\n> **RequestActivity** = \\{ `id`: `number`; `operation`: `string`; `service`: `string`; `status`: `\"started\"` \\| `\"completed\"` \\| `\"failed\"`; \\}\n\nA generated SDK operation lifecycle. Contains no arguments, URLs or response data.\n\n## Properties\n\n| Property | Type |\n| ------ | ------ |\n| <a id=\"property-id\"></a> `id` | `number` |\n| <a id=\"property-operation\"></a> `operation` | `string` |\n| <a id=\"property-service\"></a> `service` | `string` |\n| <a id=\"property-status\"></a> `status` | `\"started\"` \\| `\"completed\"` \\| `\"failed\"` |\n\n\n<!-- src/mentions/functions/msg.md -->\n# Function: msg()\n\n> **msg**(`strings`, ...`values`): [`RichMessage`](../interfaces/RichMessage.md)\n\nCompose a rich message. Interpolate mentions (a User, Document,\n[here](../variables/here.md), …) or plain strings. Each mention writes its `<m-*>` tag into the\ncontent *and* adds itself to `mentions[]`, so the two can never drift; strings\nare inserted as-is, so markdown like `**bold**` passes through untouched.\n\n## Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `strings` | `TemplateStringsArray` |\n| ...`values` | [`Interpolation`](../type-aliases/Interpolation.md)[] |\n\n## Returns\n\n[`RichMessage`](../interfaces/RichMessage.md)\n\n## Example\n\n```ts\nchannel.send(msg`Hey ${user}, see ${doc}. cc ${here}`);\nchannel.send(msg`Status: ${status} — see ${doc}`);\n```\n\n\n<!-- src/mentions/functions/toBody.md -->\n# Function: toBody()\n\n> **toBody**(`body`): [`RichMessage`](../interfaces/RichMessage.md)\n\nNormalize a plain string or a [RichMessage](../interfaces/RichMessage.md) to the wire shape.\n\n## Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `body` | `string` \\| [`RichMessage`](../interfaces/RichMessage.md) |\n\n## Returns\n\n[`RichMessage`](../interfaces/RichMessage.md)\n\n\n<!-- src/mentions/functions/wrapXml.md -->\n# Function: wrapXml()\n\n> **wrapXml**(`tag`, `data`): `string`\n\nSerialize a mention node to its `<tag>{json}</tag>` wire form.\n\n## Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `tag` | `string` |\n| `data` | `unknown` |\n\n## Returns\n\n`string`\n\n\n<!-- src/mentions/interfaces/MentionPart.md -->\n# Interface: MentionPart\n\nThe two things a mentionable entity contributes to a message.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-mention\"></a> `mention` | [`SimpleMention`](../../../generated/storage/types.gen/type-aliases/SimpleMention.md) | The parallel entry the backend uses for notifications and permissions. |\n| <a id=\"property-tag\"></a> `tag` | `string` | The `<m-*>` tag written into the message content. |\n\n\n<!-- src/mentions/interfaces/Mentionable.md -->\n# Interface: Mentionable\n\nAnything that can be dropped into a [msg](../functions/msg.md) template as a mention.\n\n## Methods\n\n### toMention()\n\n> **toMention**(): [`MentionPart`](MentionPart.md)\n\n#### Returns\n\n[`MentionPart`](MentionPart.md)\n\n\n<!-- src/mentions/interfaces/RichMessage.md -->\n# Interface: RichMessage\n\nA composed message body: content with embedded tags, and the matching mentions.\n\n## Properties\n\n| Property | Type |\n| ------ | ------ |\n| <a id=\"property-content\"></a> `content` | `string` |\n| <a id=\"property-mentions\"></a> `mentions` | [`SimpleMention`](../../../generated/storage/types.gen/type-aliases/SimpleMention.md)[] |\n\n\n<!-- src/mentions/type-aliases/Interpolation.md -->\n# Type Alias: Interpolation\n\n> **Interpolation** = [`Mentionable`](../interfaces/Mentionable.md) \\| `string` \\| `number`\n\nWhat may be interpolated into a [msg](../functions/msg.md) template: a mention, or plain text.\n\n\n<!-- src/mentions/variables/here.md -->\n# Variable: here\n\n> `const` **here**: [`Mentionable`](../interfaces/Mentionable.md)\n\nThe `@here` group mention.\n\n\n<!-- src/utils/lazy/classes/Lazy.md -->\n# Class: Lazy\\<T\\>\n\nA value fetched on first access and cached thereafter. Powers thin entity\nhandles: construction is free, the record is loaded lazily the first time a\nfield is read, and concurrent reads share one in-flight request. Pass a\n`seed` when the record is already known (from a list or an event) to skip the\nfetch entirely.\n\n## Type Parameters\n\n| Type Parameter |\n| ------ |\n| <a id=\"type-parameter-t\"></a> `T` |\n\n## Constructors\n\n### Constructor\n\n> **new Lazy**\\<`T`\\>(`loader`, `seed?`): `Lazy`\\<`T`\\>\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `loader` | () => `Promise`\\<`T`\\> |\n| `seed?` | `T` |\n\n#### Returns\n\n`Lazy`\\<`T`\\>\n\n## Methods\n\n### clear()\n\n> **clear**(): `void`\n\nDrop the cached value so the next read refetches.\n\n#### Returns\n\n`void`\n\n***\n\n### get()\n\n> **get**(): `Promise`\\<`T`\\>\n\n#### Returns\n\n`Promise`\\<`T`\\>\n\n***\n\n### peek()\n\n> **peek**(): `T` \\| `undefined`\n\nThe cached value, if already loaded — never triggers a fetch.\n\n#### Returns\n\n`T` \\| `undefined`\n\n\n<!-- src/utils/pagination/functions/paginate.md -->\n# Function: paginate()\n\n> **paginate**\\<`T`, `Cursor`\\>(`fetchPage`): `AsyncGenerator`\\<`T`\\>\n\nAsync generator over a cursor-paginated API. Iterate with `for await`.\nCursors are plain JSON values (strings or small objects), so a page whose\nnext cursor serialises identically to the one it was fetched with means the\nserver is not advancing; the generator throws instead of looping forever.\n\n## Type Parameters\n\n| Type Parameter | Default type |\n| ------ | ------ |\n| <a id=\"type-parameter-t\"></a> `T` | - |\n| <a id=\"type-parameter-cursor\"></a> `Cursor` | `string` |\n\n## Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `fetchPage` | (`cursor?`) => `Promise`\\<[`Page`](../interfaces/Page.md)\\<`T`, `Cursor`\\>\\> |\n\n## Returns\n\n`AsyncGenerator`\\<`T`\\>\n\n\n<!-- src/utils/pagination/interfaces/Page.md -->\n# Interface: Page\\<T, Cursor\\>\n\nOne page of a cursor-paginated list.\n\n## Type Parameters\n\n| Type Parameter | Default type |\n| ------ | ------ |\n| <a id=\"type-parameter-t\"></a> `T` | - |\n| <a id=\"type-parameter-cursor\"></a> `Cursor` | `string` |\n\n## Properties\n\n| Property | Type |\n| ------ | ------ |\n| <a id=\"property-items\"></a> `items` | `T`[] |\n| <a id=\"property-nextcursor\"></a> `nextCursor?` | `Cursor` \\| `null` |\n\n\n<!-- src/utils/unwrap/classes/MacroApiError.md -->\n# Class: MacroApiError\n\nA non-2xx HTTP response (Macro API, or a raw fetch like presigned downloads).\n\n## Extends\n\n- [`MacroError`](MacroError.md)\n\n## Extended by\n\n- [`MacroOpRefusedError`](../../../entities/databases/database/classes/MacroOpRefusedError.md)\n\n## Constructors\n\n### Constructor\n\n> **new MacroApiError**(`status`, `data`): `MacroApiError`\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `status` | `number` |\n| `data` | `unknown` |\n\n#### Returns\n\n`MacroApiError`\n\n#### Overrides\n\n[`MacroError`](MacroError.md).[`constructor`](MacroError.md#constructor)\n\n## Properties\n\n| Property | Modifier | Type |\n| ------ | ------ | ------ |\n| <a id=\"property-data\"></a> `data` | `readonly` | `unknown` |\n| <a id=\"property-status\"></a> `status` | `readonly` | `number` |\n\n\n<!-- src/utils/unwrap/classes/MacroError.md -->\n# Class: MacroError\n\nBase for every error the SDK throws.\n\n## Extends\n\n- `Error`\n\n## Extended by\n\n- [`MacroApiError`](MacroApiError.md)\n- [`MacroNotFoundError`](MacroNotFoundError.md)\n\n## Constructors\n\n### Constructor\n\n> **new MacroError**(`message`): `MacroError`\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `message` | `string` |\n\n#### Returns\n\n`MacroError`\n\n#### Overrides\n\n`Error.constructor`\n\n\n<!-- src/utils/unwrap/classes/MacroNotFoundError.md -->\n# Class: MacroNotFoundError\n\nThe API succeeded but the addressed entity doesn't exist in the result.\n\n## Extends\n\n- [`MacroError`](MacroError.md)\n\n## Constructors\n\n### Constructor\n\n> **new MacroNotFoundError**(`message`): `MacroNotFoundError`\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `message` | `string` |\n\n#### Returns\n\n`MacroNotFoundError`\n\n#### Overrides\n\n[`MacroError`](MacroError.md).[`constructor`](MacroError.md#constructor)\n\n\n<!-- src/utils/unwrap/functions/unwrap.md -->\n# Function: unwrap()\n\n> **unwrap**\\<`TData`, `TError`\\>(`res`): `TData`\n\nTurn a hey-api `{ data, error, response? }` result into either the success\npayload or a thrown MacroApiError.\n\n## Type Parameters\n\n| Type Parameter |\n| ------ |\n| <a id=\"type-parameter-tdata\"></a> `TData` |\n| <a id=\"type-parameter-terror\"></a> `TError` |\n\n## Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `res` | \\{ `data?`: `TData`; `error?`: `TError`; `response?`: `Response`; \\} |\n| `res.data?` | `TData` |\n| `res.error?` | `TError` |\n| `res.response?` | `Response` |\n\n## Returns\n\n`TData`\n"
}
]
diff --git a/crates/agent_code_mode/src/domain/operations.json b/crates/agent_code_mode/src/domain/operations.json
index 9f7009f964..c32c63a4be 100644
--- a/crates/agent_code_mode/src/domain/operations.json
+++ b/crates/agent_code_mode/src/domain/operations.json
@@ -149,11 +149,16 @@
"calendar.updateCalendarEvent": "Update Calendar Event",
"calendar.copyCalendarEvent": "Copy Calendar Event",
"calendar.inviteCalendarEventGuests": "Invite Calendar Event Guests",
+ "calendar.eventNotes": "Event Notes",
+ "calendar.unlinkEventNote": "Unlink Event Note",
+ "calendar.linkEventNote": "Link Event Note",
"calendar.calendarEventProviderUrl": "Calendar Event Provider Url",
"calendar.prepareCalendarReplacement": "Prepare Calendar Replacement",
"calendar.rsvpCalendarEvent": "Rsvp Calendar Event",
"calendar.healthHandler": "Health",
"calendar.respondToJoinRequest": "Respond To Join Request",
+ "calendar.noteDocuments": "Note Documents",
+ "calendar.documentNoteLinks": "Document Note Links",
"calendar.discardCalendarReplacement": "Discard Calendar Replacement",
"calendar.calendarReplacementStatus": "Calendar Replacement Status",
"calendar.confirmCalendarReplacement": "Confirm Calendar Replacement",
diff --git a/crates/calendar_events/AGENTS.md b/crates/calendar_events/AGENTS.md
index 9215991dbf..6ab1c74816 100644
--- a/crates/calendar_events/AGENTS.md
+++ b/crates/calendar_events/AGENTS.md
@@ -15,6 +15,8 @@ reminder dispatch, team availability, and provider/Postgres persistence.
- `src/domain/capabilities.rs`: Google's organizer-set `GuestPolicy` and the
`ViewerCapabilities` every read surface exposes as `viewerCan`.
- `src/domain/team_availability.rs` + `src/domain/team.rs`: team sharing/availability.
+- `src/domain/notes.rs`, `src/outbound/pg_notes.rs`, `src/inbound/notes_router.rs`:
+ occurrence-scoped markdown links and optional team view access (feature `notes`).
- `src/outbound/google.rs`, `src/outbound/pg.rs`: Google Calendar and Postgres adapters.
- `src/outbound/pg/outlook.rs`: durable Outlook synchronization; preserve
provider-specific coverage on discovery.
@@ -50,9 +52,15 @@ reminder dispatch, team availability, and provider/Postgres persistence.
## Checks
- `cargo test -p calendar_events` (`SQLX_OFFLINE` unset).
+- `cargo test -p calendar_events --features notes,postgres` covers meeting-note
+ policy and its document-access integration against a migrated local MacroDB.
## Gotchas
+- Keep note links separate from sync-owned occurrence rows; require a live
+ occurrence and corroborated inbox copies for inherited view access. A document
+ owner can unlink after losing meeting access. See
+ [meeting-note access](../../docs/architecture/calendar-meeting-notes.md).
- `CalendarEvent` is the stable Macro entity; external calendars and email
invitations are sources feeding it, and recurrence instances are queryable
occurrence projections, not separate events — don't model them as new entities.
diff --git a/crates/calendar_events/Cargo.toml b/crates/calendar_events/Cargo.toml
index d873870747..79176a6ab1 100644
--- a/crates/calendar_events/Cargo.toml
+++ b/crates/calendar_events/Cargo.toml
@@ -6,6 +6,7 @@ version = "0.1.0"
[features]
default = []
+notes = ["dep:entity_access"]
outlook = ["dep:tokio"]
# The AI toolset adapter exposing calendar CRUD to agents.
ai_tools = ["dep:ai_toolset", "dep:anyhow", "dep:async-trait", "dep:schemars"]
@@ -45,6 +46,7 @@ call = { path = "../call", default-features = false, features = [
chrono = { workspace = true }
chrono-tz = { workspace = true }
email_utils = { path = "../email_utils" }
+entity_access = { path = "../entity_access", default-features = false, features = ["ports"], optional = true }
futures = { workspace = true }
macro_authorization = { path = "../macro_authorization", default-features = false, features = [
"axum",
@@ -72,6 +74,7 @@ uuid = { workspace = true }
workspace-hack = { version = "0.1", path = "../workspace-hack" }
[dev-dependencies]
+entity_access = { path = "../entity_access", default-features = false, features = ["outbound", "ports"] }
macro_db_migrator = { path = "../macro_db_migrator" }
macro_user_id = { path = "../macro_user_id" }
tokio = { workspace = true }
diff --git a/crates/calendar_events/src/domain/mod.rs b/crates/calendar_events/src/domain/mod.rs
index 396c504072..4be45c3875 100644
--- a/crates/calendar_events/src/domain/mod.rs
+++ b/crates/calendar_events/src/domain/mod.rs
@@ -20,6 +20,9 @@ pub mod meeting_links;
pub mod models;
/// User-initiated calendar mutation policy.
pub mod mutations;
+/// Markdown documents linked to a meeting occurrence.
+#[cfg(feature = "notes")]
+pub mod notes;
/// Domain ports.
pub mod ports;
/// Calendar reminder dispatch policy.
diff --git a/crates/calendar_events/src/domain/notes.rs b/crates/calendar_events/src/domain/notes.rs
new file mode 100644
index 0000000000..0968b4541e
--- /dev/null
+++ b/crates/calendar_events/src/domain/notes.rs
@@ -0,0 +1,318 @@
+//! Meeting-note links and their view-only, live audience.
+
+use entity_access::domain::models::{EntityAccessReceipt, EntityType, OwnerAccessLevel};
+use serde::{Deserialize, Serialize};
+use uuid::Uuid;
+
+/// One occurrence, shared across the calendar copies of the same meeting.
+#[derive(Clone, Debug)]
+pub struct NoteTarget {
+ /// A calendar copy the caller can see.
+ pub event_id: Uuid,
+ /// Calendar occurrence key; one-time meetings normalize to a stable event key.
+ pub occurrence_key: String,
+}
+
+/// An additional team audience, separate from the meeting's audience.
+#[derive(Clone, Debug, Serialize, Deserialize)]
+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
+#[serde(rename_all = "camelCase")]
+pub struct NoteTeam {
+ /// Team identity.
+ pub id: Uuid,
+ /// Display name.
+ pub name: String,
+}
+
+/// A document available in the note picker.
+#[derive(Clone, Debug, Serialize, Deserialize)]
+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
+#[serde(rename_all = "camelCase")]
+pub struct NoteDocument {
+ /// Markdown document identity.
+ pub document_id: String,
+ /// Current document name, never a copied title.
+ pub name: String,
+}
+
+/// One linked document and the extra access this link grants.
+#[derive(Clone, Debug, Serialize, Deserialize)]
+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
+#[serde(rename_all = "camelCase")]
+pub struct MeetingNote {
+ /// Markdown document identity.
+ pub document_id: String,
+ /// Current document name.
+ pub name: String,
+ /// Optional extra team view grant.
+ pub team: Option<NoteTeam>,
+ /// Whether this viewer can change this document's sharing.
+ pub can_manage: bool,
+}
+
+/// Picker results; only documents whose owner is the caller are suggested.
+#[derive(Clone, Debug, Serialize, Deserialize)]
+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
+#[serde(rename_all = "camelCase")]
+pub struct NotePicker {
+ /// At most 30 matching markdown documents, most recently updated first.
+ pub documents: Vec<NoteDocument>,
+ /// Teams the caller currently belongs to.
+ pub teams: Vec<NoteTeam>,
+}
+
+/// An owner's durable sharing link, including meetings they can no longer open.
+#[derive(Clone, Debug, Serialize, Deserialize)]
+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
+#[serde(rename_all = "camelCase")]
+pub struct DocumentNoteLink {
+ /// Current name of the owned markdown document.
+ pub document_name: String,
+ /// Linked calendar copy.
+ pub event_id: Uuid,
+ /// Original occurrence start, or `single` for a one-time meeting.
+ pub occurrence_key: String,
+ /// Current title, or a safe placeholder when meeting details are unavailable.
+ pub event_title: String,
+ /// Independent optional team audience.
+ pub team: Option<NoteTeam>,
+}
+
+/// Failures with safe, user-facing semantics.
+#[derive(Debug, thiserror::Error)]
+pub enum NoteError {
+ /// The meeting is missing, cancelled, or not visible in detail.
+ #[error("This meeting is no longer available")]
+ NotFound,
+ /// Sharing requires document ownership and current team membership.
+ #[error("You do not have permission to share these notes")]
+ Forbidden,
+ /// Only live markdown documents can be linked.
+ #[error("Choose a markdown document")]
+ NotMarkdown,
+ /// Invalid or excessive input.
+ #[error("Invalid meeting notes request")]
+ InvalidInput,
+ /// An infrastructure operation failed.
+ #[error("Meeting notes could not be saved")]
+ Internal(rootcause::Report),
+}
+
+/// Persistence facts and atomic link writes.
+pub trait NoteRepository: Send + Sync + 'static {
+ /// Adapter error.
+ type Err: std::error::Error + Send + Sync + 'static;
+ /// All links on the caller's document, even after meeting access is lost.
+ fn document_links(
+ &self,
+ user: &str,
+ document: &str,
+ ) -> impl Future<Output = Result<Vec<DocumentNoteLink>, Self::Err>> + Send;
+ /// Current full-detail access; busy-only projections never qualify.
+ fn visible(
+ &self,
+ user: &str,
+ target: &NoteTarget,
+ ) -> impl Future<Output = Result<bool, Self::Err>> + Send;
+ /// Whether a live, materialized occurrence exists for a new link.
+ fn occurrence_exists(
+ &self,
+ target: &NoteTarget,
+ ) -> impl Future<Output = Result<bool, Self::Err>> + Send;
+ /// Whether the document exists, is live, and is markdown.
+ fn is_markdown(&self, document: &str) -> impl Future<Output = Result<bool, Self::Err>> + Send;
+ /// Current membership in the optional extra audience.
+ fn team_member(
+ &self,
+ user: &str,
+ team: Uuid,
+ ) -> impl Future<Output = Result<bool, Self::Err>> + Send;
+ /// Notes from every copy of the same meeting and occurrence.
+ fn list(
+ &self,
+ user: &str,
+ target: &NoteTarget,
+ ) -> impl Future<Output = Result<Vec<MeetingNote>, Self::Err>> + Send;
+ /// Owned markdown suggestions and current teams.
+ fn picker(
+ &self,
+ user: &str,
+ query: &str,
+ ) -> impl Future<Output = Result<NotePicker, Self::Err>> + Send;
+ /// Replace this document's link atomically, including across calendar copies.
+ fn link(
+ &self,
+ user: &str,
+ target: &NoteTarget,
+ document: &str,
+ team: Option<Uuid>,
+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;
+ /// Remove this document's link from all copies; leave the document intact.
+ fn unlink(
+ &self,
+ target: &NoteTarget,
+ document: &str,
+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;
+}
+
+/// Inbound contract; mutation receipts prove ownership before granting access.
+pub trait MeetingNotesService: Send + Sync + 'static {
+ /// List an owned document's durable calendar sharing grants.
+ fn document_links(
+ &self,
+ receipt: EntityAccessReceipt<OwnerAccessLevel>,
+ ) -> impl Future<Output = Result<Vec<DocumentNoteLink>, NoteError>> + Send;
+ /// Read notes using the current meeting audience.
+ fn list(
+ &self,
+ user: &str,
+ target: NoteTarget,
+ ) -> impl Future<Output = Result<Vec<MeetingNote>, NoteError>> + Send;
+ /// Find documents the user can share.
+ fn picker(
+ &self,
+ user: &str,
+ query: &str,
+ ) -> impl Future<Output = Result<NotePicker, NoteError>> + Send;
+ /// Link notes, or update their optional team audience.
+ fn link(
+ &self,
+ receipt: EntityAccessReceipt<OwnerAccessLevel>,
+ target: NoteTarget,
+ team: Option<Uuid>,
+ ) -> impl Future<Output = Result<(), NoteError>> + Send;
+ /// Unlink without deleting the notes or touching other grants.
+ fn unlink(
+ &self,
+ receipt: EntityAccessReceipt<OwnerAccessLevel>,
+ target: NoteTarget,
+ ) -> impl Future<Output = Result<(), NoteError>> + Send;
+}
+
+/// Calendar note policy, independent from transport and storage.
+pub struct MeetingNotes<R> {
+ repo: R,
+}
+
+impl<R: NoteRepository> MeetingNotes<R> {
+ /// Compose the repository with meeting-note policy.
+ pub fn new(repo: R) -> Self {
+ Self { repo }
+ }
+
+ async fn authorize(&self, user: &str, target: &NoteTarget) -> Result<(), NoteError> {
+ validate_target(target)?;
+ if !self.repo.visible(user, target).await.map_err(internal)? {
+ return Err(NoteError::NotFound);
+ }
+ Ok(())
+ }
+}
+
+fn validate_target(target: &NoteTarget) -> Result<(), NoteError> {
+ if target.occurrence_key.is_empty() || target.occurrence_key.len() > 100 {
+ return Err(NoteError::InvalidInput);
+ }
+ Ok(())
+}
+
+fn internal(error: impl std::error::Error + Send + Sync + 'static) -> NoteError {
+ NoteError::Internal(rootcause::Report::new(error).into_dynamic())
+}
+
+impl<R: NoteRepository> MeetingNotesService for MeetingNotes<R> {
+ #[tracing::instrument(name = "calendar.notes.document_links", skip_all, fields(document_id = %receipt.entity().entity_id), err)]
+ async fn document_links(
+ &self,
+ receipt: EntityAccessReceipt<OwnerAccessLevel>,
+ ) -> Result<Vec<DocumentNoteLink>, NoteError> {
+ let user = receipt
+ .get_authenticated_user()
+ .map_err(|_| NoteError::Forbidden)?;
+ if receipt.entity().entity_type != EntityType::Document {
+ return Err(NoteError::Forbidden);
+ }
+ self.repo
+ .document_links(user.as_ref(), &receipt.entity().entity_id)
+ .await
+ .map_err(internal)
+ }
+ #[tracing::instrument(name = "calendar.notes.list", skip_all, fields(event_id = %target.event_id), err)]
+ async fn list(&self, user: &str, target: NoteTarget) -> Result<Vec<MeetingNote>, NoteError> {
+ self.authorize(user, &target).await?;
+ self.repo.list(user, &target).await.map_err(internal)
+ }
+
+ #[tracing::instrument(name = "calendar.notes.picker", skip_all, err)]
+ async fn picker(&self, user: &str, query: &str) -> Result<NotePicker, NoteError> {
+ if query.len() > 200 {
+ return Err(NoteError::InvalidInput);
+ }
+ self.repo.picker(user, query.trim()).await.map_err(internal)
+ }
+
+ #[tracing::instrument(name = "calendar.notes.link", skip_all, fields(event_id = %target.event_id, document_id = %receipt.entity().entity_id), err)]
+ async fn link(
+ &self,
+ receipt: EntityAccessReceipt<OwnerAccessLevel>,
+ target: NoteTarget,
+ team: Option<Uuid>,
+ ) -> Result<(), NoteError> {
+ let user = receipt
+ .get_authenticated_user()
+ .map_err(|_| NoteError::Forbidden)?;
+ if receipt.entity().entity_type != EntityType::Document {
+ return Err(NoteError::Forbidden);
+ }
+ self.authorize(user.as_ref(), &target).await?;
+ if !self
+ .repo
+ .occurrence_exists(&target)
+ .await
+ .map_err(internal)?
+ {
+ return Err(NoteError::NotFound);
+ }
+ let document = &receipt.entity().entity_id;
+ if !self.repo.is_markdown(document).await.map_err(internal)? {
+ return Err(NoteError::NotMarkdown);
+ }
+ if let Some(team) = team
+ && !self
+ .repo
+ .team_member(user.as_ref(), team)
+ .await
+ .map_err(internal)?
+ {
+ return Err(NoteError::Forbidden);
+ }
+ self.repo
+ .link(user.as_ref(), &target, document, team)
+ .await
+ .map_err(internal)
+ }
+
+ #[tracing::instrument(name = "calendar.notes.unlink", skip_all, fields(event_id = %target.event_id, document_id = %receipt.entity().entity_id), err)]
+ async fn unlink(
+ &self,
+ receipt: EntityAccessReceipt<OwnerAccessLevel>,
+ target: NoteTarget,
+ ) -> Result<(), NoteError> {
+ receipt
+ .get_authenticated_user()
+ .map_err(|_| NoteError::Forbidden)?;
+ if receipt.entity().entity_type != EntityType::Document {
+ return Err(NoteError::Forbidden);
+ }
+ // A document owner must still be able to revoke sharing after the
+ // meeting is cancelled or they lose access to its calendar.
+ validate_target(&target)?;
+ self.repo
+ .unlink(&target, &receipt.entity().entity_id)
+ .await
+ .map_err(internal)
+ }
+}
+
+#[cfg(test)]
+mod test;
diff --git a/crates/calendar_events/src/domain/notes/test.rs b/crates/calendar_events/src/domain/notes/test.rs
new file mode 100644
index 0000000000..c83b3a1072
--- /dev/null
+++ b/crates/calendar_events/src/domain/notes/test.rs
@@ -0,0 +1,145 @@
+use super::*;
+use macro_user_id::user_id::MacroUserIdStr;
+use std::sync::atomic::{AtomicUsize, Ordering};
+
+struct Repo {
+ visible: bool,
+ markdown: bool,
+ member: bool,
+ writes: AtomicUsize,
+}
+
+impl NoteRepository for Repo {
+ type Err = std::io::Error;
+ async fn document_links(&self, _: &str, _: &str) -> Result<Vec<DocumentNoteLink>, Self::Err> {
+ Ok(vec![])
+ }
+ async fn visible(&self, _: &str, _: &NoteTarget) -> Result<bool, Self::Err> {
+ Ok(self.visible)
+ }
+ async fn occurrence_exists(&self, _: &NoteTarget) -> Result<bool, Self::Err> {
+ Ok(true)
+ }
+ async fn is_markdown(&self, _: &str) -> Result<bool, Self::Err> {
+ Ok(self.markdown)
+ }
+ async fn team_member(&self, _: &str, _: Uuid) -> Result<bool, Self::Err> {
+ Ok(self.member)
+ }
+ async fn list(&self, _: &str, _: &NoteTarget) -> Result<Vec<MeetingNote>, Self::Err> {
+ Ok(vec![])
+ }
+ async fn picker(&self, _: &str, _: &str) -> Result<NotePicker, Self::Err> {
+ Ok(NotePicker {
+ documents: vec![],
+ teams: vec![],
+ })
+ }
+ async fn link(
+ &self,
+ _: &str,
+ _: &NoteTarget,
+ _: &str,
+ _: Option<Uuid>,
+ ) -> Result<(), Self::Err> {
+ self.writes.fetch_add(1, Ordering::SeqCst);
+ Ok(())
+ }
+ async fn unlink(&self, _: &NoteTarget, _: &str) -> Result<(), Self::Err> {
+ self.writes.fetch_add(1, Ordering::SeqCst);
+ Ok(())
+ }
+}
+
+#[tokio::test]
+async fn sharing_requires_visible_meeting_markdown_and_membership_in_extra_team() {
+ let target = NoteTarget {
+ event_id: Uuid::now_v7(),
+ occurrence_key: "2026-07-24T14:00:00+00:00".into(),
+ };
+ for (visible, markdown, member, extra_team, expected) in [
+ (false, true, true, None, "meeting"),
+ (true, false, true, None, "markdown"),
+ (true, true, false, Some(Uuid::now_v7()), "team"),
+ (true, true, false, None, "allowed"),
+ (true, true, true, Some(Uuid::now_v7()), "allowed"),
+ ] {
+ let service = MeetingNotes::new(Repo {
+ visible,
+ markdown,
+ member,
+ writes: AtomicUsize::new(0),
+ });
+ let receipt = EntityAccessReceipt::dangerously_assert_authenticated_user(
+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
+ "019f85aa-984e-7022-a018-4a242bcafe23",
+ EntityType::Document,
+ );
+ let result = service.link(receipt, target.clone(), extra_team).await;
+ match expected {
+ "meeting" => assert!(matches!(result, Err(NoteError::NotFound))),
+ "markdown" => assert!(matches!(result, Err(NoteError::NotMarkdown))),
+ "team" => assert!(matches!(result, Err(NoteError::Forbidden))),
+ _ => assert!(result.is_ok()),
+ }
+ assert_eq!(
+ service.repo.writes.load(Ordering::SeqCst),
+ usize::from(expected == "allowed")
+ );
+ }
+}
+
+#[tokio::test]
+async fn unrelated_owner_receipt_cannot_share_a_document() {
+ let service = MeetingNotes::new(Repo {
+ visible: true,
+ markdown: true,
+ member: true,
+ writes: AtomicUsize::new(0),
+ });
+ let receipt = EntityAccessReceipt::dangerously_assert_authenticated_user(
+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
+ "019f85aa-984e-7022-a018-4a242bcafe23",
+ EntityType::Project,
+ );
+ assert!(matches!(
+ service
+ .link(
+ receipt,
+ NoteTarget {
+ event_id: Uuid::now_v7(),
+ occurrence_key: "2026-07-24".into()
+ },
+ None
+ )
+ .await,
+ Err(NoteError::Forbidden)
+ ));
+ assert_eq!(service.repo.writes.load(Ordering::SeqCst), 0);
+}
+
+#[tokio::test]
+async fn an_owner_can_revoke_sharing_after_losing_meeting_access() {
+ let service = MeetingNotes::new(Repo {
+ visible: false,
+ markdown: true,
+ member: false,
+ writes: AtomicUsize::new(0),
+ });
+ let receipt = EntityAccessReceipt::dangerously_assert_authenticated_user(
+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
+ "019f85aa-984e-7022-a018-4a242bcafe23",
+ EntityType::Document,
+ );
+ service
+ .unlink(
+ receipt,
+ NoteTarget {
+ event_id: Uuid::now_v7(),
+ occurrence_key: "2026-07-24".into(),
+ },
+ )
+ .await
+ .unwrap();
+ assert_eq!(service.repo.writes.load(Ordering::SeqCst), 1);
+}
diff --git a/crates/calendar_events/src/inbound/mod.rs b/crates/calendar_events/src/inbound/mod.rs
index 73a7ddf0e4..11e4c7be52 100644
--- a/crates/calendar_events/src/inbound/mod.rs
+++ b/crates/calendar_events/src/inbound/mod.rs
@@ -3,6 +3,9 @@
/// Axum routes for authenticated calendar queries.
#[cfg(feature = "inbound")]
pub mod axum_router;
+/// Markdown meeting-note links.
+#[cfg(all(feature = "inbound", feature = "notes"))]
+pub mod notes_router;
/// Queue worker driving calendar reminder dispatch.
#[cfg(feature = "dispatch")]
diff --git a/crates/calendar_events/src/inbound/notes_router.rs b/crates/calendar_events/src/inbound/notes_router.rs
new file mode 100644
index 0000000000..78674d62b9
--- /dev/null
+++ b/crates/calendar_events/src/inbound/notes_router.rs
@@ -0,0 +1,305 @@
+//! HTTP transport for meeting notes; policy lives in the domain service.
+
+use crate::domain::notes::{
+ DocumentNoteLink, MeetingNote, MeetingNotesService, NoteError, NotePicker, NoteTarget,
+};
+use axum::{
+ Json, Router,
+ extract::{FromRef, Path, Query, State},
+ http::{StatusCode, header},
+ response::{IntoResponse, Response},
+ routing::{get, put},
+};
+use entity_access::domain::{
+ models::{AccessError, EntityType, OwnerAccessLevel},
+ ports::EntityAccessService,
+};
+use macro_authorization::{
+ MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState, UserOrInternal,
+};
+use serde::Deserialize;
+use std::sync::Arc;
+use uuid::Uuid;
+
+/// Composed meeting-note, access, and authentication services.
+pub struct NotesRouterState<S, E, A> {
+ service: Arc<S>,
+ access: Arc<E>,
+ auth: MacroAuthorizationState<A>,
+}
+
+impl<S, E, A> Clone for NotesRouterState<S, E, A> {
+ fn clone(&self) -> Self {
+ Self {
+ service: self.service.clone(),
+ access: self.access.clone(),
+ auth: self.auth.clone(),
+ }
+ }
+}
+
+impl<S, E, A> NotesRouterState<S, E, A> {
+ /// Supply concrete services at the composition root.
+ pub fn new(service: Arc<S>, access: Arc<E>, auth: MacroAuthorizationState<A>) -> Self {
+ Self {
+ service,
+ access,
+ auth,
+ }
+ }
+}
+
+impl<S, E, A> FromRef<NotesRouterState<S, E, A>> for MacroAuthorizationState<A> {
+ fn from_ref(state: &NotesRouterState<S, E, A>) -> Self {
+ state.auth.clone()
+ }
+}
+
+/// Authenticated note reads and owner-authorized link writes.
+pub fn notes_router<
+ S: MeetingNotesService,
+ E: EntityAccessService,
+ A: MacroAuthorizationService,
+ T: Send + Sync + 'static,
+>(
+ state: NotesRouterState<S, E, A>,
+) -> Router<T> {
+ Router::new()
+ .route("/meeting-notes/documents", get(note_documents::<S, E, A>))
+ .route(
+ "/meeting-notes/documents/{document_id}/links",
+ get(document_note_links::<S, E, A>),
+ )
+ .route("/events/{event_id}/notes", get(event_notes::<S, E, A>))
+ .route(
+ "/events/{event_id}/notes/{document_id}",
+ put(link_event_note::<S, E, A>).delete(unlink_event_note::<S, E, A>),
+ )
+ .layer(axum::middleware::map_response(
+ |mut response: Response| async move {
+ response.headers_mut().insert(
+ header::CACHE_CONTROL,
+ header::HeaderValue::from_static("private, no-store"),
+ );
+ response
+ },
+ ))
+ .with_state(state)
+}
+
+/// Original occurrence key; independent of a later reschedule.
+#[derive(Deserialize, utoipa::IntoParams)]
+#[serde(rename_all = "camelCase")]
+pub struct NotesQuery {
+ /// Stable occurrence key returned by the calendar read API.
+ pub occurrence_key: String,
+}
+
+/// Name fragment for owned markdown suggestions.
+#[derive(Deserialize, utoipa::IntoParams)]
+pub struct NoteDocumentsQuery {
+ /// Empty returns recent documents.
+ #[serde(default)]
+ pub query: String,
+}
+
+/// Optional additional view access for one team.
+#[derive(Deserialize, utoipa::ToSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct LinkNoteRequest {
+ /// Null means the meeting audience only.
+ pub team_id: Option<Uuid>,
+}
+
+/// Safe HTTP error mapping for note policy failures.
+pub struct NotesApiError(NoteError);
+
+impl From<NoteError> for NotesApiError {
+ fn from(error: NoteError) -> Self {
+ Self(error)
+ }
+}
+
+impl From<AccessError> for NotesApiError {
+ fn from(error: AccessError) -> Self {
+ Self(match error {
+ AccessError::Unavailable(report) | AccessError::Internal(report) => {
+ NoteError::Internal(report)
+ }
+ AccessError::BadRequest(_) => NoteError::InvalidInput,
+ AccessError::NotFound(_) => NoteError::NotFound,
+ AccessError::Unauthorized | AccessError::UnauthorizedWithMessage(_) => {
+ NoteError::Forbidden
+ }
+ })
+ }
+}
+
+impl IntoResponse for NotesApiError {
+ fn into_response(self) -> Response {
+ let status = match &self.0 {
+ NoteError::NotFound => StatusCode::NOT_FOUND,
+ NoteError::Forbidden => StatusCode::FORBIDDEN,
+ NoteError::NotMarkdown | NoteError::InvalidInput => StatusCode::BAD_REQUEST,
+ NoteError::Internal(error) => {
+ tracing::error!(error=?error, "meeting notes request failed");
+ StatusCode::INTERNAL_SERVER_ERROR
+ }
+ };
+ (
+ status,
+ Json(serde_json::json!({"message": self.0.to_string()})),
+ )
+ .into_response()
+ }
+}
+
+/// List notes visible through this meeting occurrence.
+#[utoipa::path(get, path="/events/{event_id}/notes", params(("event_id" = Uuid, Path), NotesQuery), responses((status=200, body=Vec<MeetingNote>)), tag="calendar_events")]
+pub async fn event_notes<
+ S: MeetingNotesService,
+ E: EntityAccessService,
+ A: MacroAuthorizationService,
+>(
+ State(state): State<NotesRouterState<S, E, A>>,
+ user: MacroAuthorizationExtractor<A, UserOrInternal>,
+ Path(event_id): Path<Uuid>,
+ Query(query): Query<NotesQuery>,
+) -> Result<Json<Vec<MeetingNote>>, NotesApiError> {
+ Ok(Json(
+ state
+ .service
+ .list(
+ user.authorization.user.macro_user_id.as_ref(),
+ NoteTarget {
+ event_id,
+ occurrence_key: query.occurrence_key,
+ },
+ )
+ .await?,
+ ))
+}
+
+/// Suggest the caller's markdown documents and extra team audiences.
+#[utoipa::path(get, path="/meeting-notes/documents", params(NoteDocumentsQuery), responses((status=200, body=NotePicker)), tag="calendar_events")]
+pub async fn note_documents<
+ S: MeetingNotesService,
+ E: EntityAccessService,
+ A: MacroAuthorizationService,
+>(
+ State(state): State<NotesRouterState<S, E, A>>,
+ user: MacroAuthorizationExtractor<A, UserOrInternal>,
+ Query(query): Query<NoteDocumentsQuery>,
+) -> Result<Json<NotePicker>, NotesApiError> {
+ Ok(Json(
+ state
+ .service
+ .picker(user.authorization.user.macro_user_id.as_ref(), &query.query)
+ .await?,
+ ))
+}
+
+/// List an owned document's meeting grants, including unavailable meetings.
+#[utoipa::path(get, path="/meeting-notes/documents/{document_id}/links", params(("document_id" = String, Path)), responses((status=200, body=Vec<DocumentNoteLink>)), tag="calendar_events")]
+pub async fn document_note_links<
+ S: MeetingNotesService,
+ E: EntityAccessService,
+ A: MacroAuthorizationService,
+>(
+ State(state): State<NotesRouterState<S, E, A>>,
+ user: MacroAuthorizationExtractor<A, UserOrInternal>,
+ Path(document_id): Path<String>,
+) -> Result<Json<Vec<DocumentNoteLink>>, NotesApiError> {
+ let receipt = state
+ .access
+ .generate_entity_access_receipt::<OwnerAccessLevel>(
+ &user.authorization.user.macro_user_id,
+ user.authorization
+ .user
+ .user_context
+ .organization_id
+ .map(i64::from),
+ &document_id,
+ EntityType::Document,
+ )
+ .await?;
+ Ok(Json(state.service.document_links(receipt).await?))
+}
+
+/// Idempotently link a markdown document and its optional team audience.
+#[utoipa::path(put, path="/events/{event_id}/notes/{document_id}", params(("event_id" = Uuid, Path), ("document_id" = String, Path), NotesQuery), request_body=LinkNoteRequest, responses((status=204)), tag="calendar_events")]
+pub async fn link_event_note<
+ S: MeetingNotesService,
+ E: EntityAccessService,
+ A: MacroAuthorizationService,
+>(
+ State(state): State<NotesRouterState<S, E, A>>,
+ user: MacroAuthorizationExtractor<A, UserOrInternal>,
+ Path((event_id, document_id)): Path<(Uuid, String)>,
+ Query(query): Query<NotesQuery>,
+ Json(body): Json<LinkNoteRequest>,
+) -> Result<StatusCode, NotesApiError> {
+ let receipt = state
+ .access
+ .generate_entity_access_receipt::<OwnerAccessLevel>(
+ &user.authorization.user.macro_user_id,
+ user.authorization
+ .user
+ .user_context
+ .organization_id
+ .map(i64::from),
+ &document_id,
+ EntityType::Document,
+ )
+ .await?;
+ state
+ .service
+ .link(
+ receipt,
+ NoteTarget {
+ event_id,
+ occurrence_key: query.occurrence_key,
+ },
+ body.team_id,
+ )
+ .await?;
+ Ok(StatusCode::NO_CONTENT)
+}
+
+/// Remove this meeting's grant without deleting the document.
+#[utoipa::path(delete, path="/events/{event_id}/notes/{document_id}", params(("event_id" = Uuid, Path), ("document_id" = String, Path), NotesQuery), responses((status=204)), tag="calendar_events")]
+pub async fn unlink_event_note<
+ S: MeetingNotesService,
+ E: EntityAccessService,
+ A: MacroAuthorizationService,
+>(
+ State(state): State<NotesRouterState<S, E, A>>,
+ user: MacroAuthorizationExtractor<A, UserOrInternal>,
+ Path((event_id, document_id)): Path<(Uuid, String)>,
+ Query(query): Query<NotesQuery>,
+) -> Result<StatusCode, NotesApiError> {
+ let receipt = state
+ .access
+ .generate_entity_access_receipt::<OwnerAccessLevel>(
+ &user.authorization.user.macro_user_id,
+ user.authorization
+ .user
+ .user_context
+ .organization_id
+ .map(i64::from),
+ &document_id,
+ EntityType::Document,
+ )
+ .await?;
+ state
+ .service
+ .unlink(
+ receipt,
+ NoteTarget {
+ event_id,
+ occurrence_key: query.occurrence_key,
+ },
+ )
+ .await?;
+ Ok(StatusCode::NO_CONTENT)
+}
diff --git a/crates/calendar_events/src/outbound/mod.rs b/crates/calendar_events/src/outbound/mod.rs
index b9579573b7..d256e54f66 100644
--- a/crates/calendar_events/src/outbound/mod.rs
+++ b/crates/calendar_events/src/outbound/mod.rs
@@ -15,6 +15,9 @@ pub mod notification_notifier;
/// PostgreSQL calendar repository.
#[cfg(feature = "postgres")]
pub mod pg;
+/// PostgreSQL meeting-note links and audience facts.
+#[cfg(all(feature = "postgres", feature = "notes"))]
+pub mod pg_notes;
/// PostgreSQL facts for team-calendar sharing.
#[cfg(feature = "postgres")]
pub mod pg_team;
diff --git a/crates/calendar_events/src/outbound/pg/test.rs b/crates/calendar_events/src/outbound/pg/test.rs
index 84ee7bc841..20e53dc776 100644
--- a/crates/calendar_events/src/outbound/pg/test.rs
+++ b/crates/calendar_events/src/outbound/pg/test.rs
@@ -7220,6 +7220,8 @@ mod details;
mod export;
mod invitations;
mod join_requests;
+#[cfg(feature = "notes")]
+mod notes;
mod source_access;
mod replacement;
diff --git a/crates/calendar_events/src/outbound/pg/test/notes.rs b/crates/calendar_events/src/outbound/pg/test/notes.rs
new file mode 100644
index 0000000000..37e7cbeceb
--- /dev/null
+++ b/crates/calendar_events/src/outbound/pg/test/notes.rs
@@ -0,0 +1,586 @@
+use super::*;
+use crate::domain::notes::{NoteRepository, NoteTarget};
+use crate::outbound::pg_notes::PgNoteRepository;
+use entity_access::{
+ domain::{models::AccessLevel, ports::AccessRepository},
+ outbound::PgAccessRepository,
+};
+use macro_user_id::user_id::MacroUserIdStr;
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn a_one_time_meeting_keeps_its_notes_after_a_provider_reschedule(pool: PgPool) {
+ let owner = "macro|[email protected]";
+ let viewer = "macro|[email protected]";
+ for user in [owner, viewer] {
+ insert_user(&pool, user).await;
+ }
+ let calendar = PgCalendarRepository::new(pool.clone());
+ let link = insert_link(&pool, owner).await;
+ let mut event = timed_upsert(
+ owner,
+ link,
+ provider_ids(&calendar, link).await,
+ "one-time-note",
+ "Planning",
+ 1,
+ );
+ event.event.recurrence_lines.clear();
+ event.occurrences.truncate(1);
+ let original = NoteTarget {
+ event_id: event.event.id,
+ occurrence_key: event.occurrences[0].occurrence_key.clone(),
+ };
+ calendar.upsert_event_fixture(event.clone()).await.unwrap();
+ let channel = insert_channel(&pool, owner, &[owner, viewer]).await;
+ sqlx::query!("INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level) VALUES ($1, 'calendar_event', $2, 'channel', 'view')", original.event_id, channel.to_string()).execute(&pool).await.unwrap();
+ let document = Uuid::now_v7().to_string();
+ sqlx::query!(
+ "INSERT INTO \"Document\" (id, name, owner, \"fileType\") VALUES ($1, 'Notes', $2, 'md')",
+ document,
+ owner
+ )
+ .execute(&pool)
+ .await
+ .unwrap();
+ let notes = PgNoteRepository::new(pool.clone());
+ notes.link(owner, &original, &document, None).await.unwrap();
+
+ let starts_at = Utc.with_ymd_and_hms(2026, 7, 26, 16, 0, 0).unwrap();
+ event.event.sequence += 1;
+ event.event.updated_at += Duration::minutes(1);
+ event.event.time = EventTime::Timed {
+ starts_at,
+ ends_at: starts_at + Duration::hours(1),
+ time_zone: Some("UTC".into()),
+ };
+ event.occurrences[0].time = event.event.time.clone();
+ event.occurrences[0].occurrence_key = starts_at.to_rfc3339();
+ let moved = NoteTarget {
+ event_id: original.event_id,
+ occurrence_key: event.occurrences[0].occurrence_key.clone(),
+ };
+ calendar.upsert_event_fixture(event).await.unwrap();
+
+ assert_eq!(notes.list(viewer, &moved).await.unwrap().len(), 1);
+ let viewer_id = MacroUserIdStr::parse_from_str(viewer).unwrap();
+ assert_eq!(
+ PgAccessRepository::new(pool.clone())
+ .get_document_access(&document, Some(&viewer_id))
+ .await
+ .unwrap(),
+ Some(AccessLevel::View)
+ );
+ assert_eq!(
+ notes.document_links(owner, &document).await.unwrap()[0].occurrence_key,
+ "single"
+ );
+ // A previously returned handle remains able to revoke after the move.
+ notes.unlink(&original, &document).await.unwrap();
+ assert!(notes.list(viewer, &moved).await.unwrap().is_empty());
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn converting_a_series_to_one_time_does_not_revive_another_instances_grants(pool: PgPool) {
+ let owner = "macro|[email protected]";
+ let viewer = "macro|[email protected]";
+ for user in [owner, viewer] {
+ insert_user(&pool, user).await;
+ }
+ let calendar = PgCalendarRepository::new(pool.clone());
+ let link = insert_link(&pool, owner).await;
+ let mut event = timed_upsert(
+ owner,
+ link,
+ provider_ids(&calendar, link).await,
+ "converted-note",
+ "Planning",
+ 1,
+ );
+ let original = NoteTarget {
+ event_id: event.event.id,
+ occurrence_key: event.occurrences[0].occurrence_key.clone(),
+ };
+ calendar.upsert_event_fixture(event.clone()).await.unwrap();
+ let channel = insert_channel(&pool, owner, &[owner, viewer]).await;
+ sqlx::query!("INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level) VALUES ($1, 'calendar_event', $2, 'channel', 'view')", original.event_id, channel.to_string()).execute(&pool).await.unwrap();
+ let document = Uuid::now_v7().to_string();
+ sqlx::query!(
+ "INSERT INTO \"Document\" (id, name, owner, \"fileType\") VALUES ($1, 'Notes', $2, 'md')",
+ document,
+ owner
+ )
+ .execute(&pool)
+ .await
+ .unwrap();
+ let notes = PgNoteRepository::new(pool.clone());
+ notes.link(owner, &original, &document, None).await.unwrap();
+ event.event.recurrence_lines.clear();
+ event.occurrences.remove(0);
+ event.event.time = event.occurrences[0].time.clone();
+ event.event.sequence += 1;
+ event.event.updated_at += Duration::minutes(1);
+ calendar.upsert_event_fixture(event).await.unwrap();
+ let viewer_id = MacroUserIdStr::parse_from_str(viewer).unwrap();
+ assert_eq!(
+ PgAccessRepository::new(pool.clone())
+ .get_document_access(&document, Some(&viewer_id))
+ .await
+ .unwrap(),
+ None
+ );
+ notes.unlink(&original, &document).await.unwrap();
+ assert!(
+ notes
+ .document_links(owner, &document)
+ .await
+ .unwrap()
+ .is_empty()
+ );
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn notes_follow_real_guests_reject_forged_copies_and_revoke_without_deleting_documents(
+ pool: PgPool,
+) {
+ let owner = "macro|[email protected]";
+ let guest = "macro|[email protected]";
+ let stranger = "macro|[email protected]";
+ for user in [owner, guest, stranger] {
+ insert_user(&pool, user).await;
+ }
+ let calendar = PgCalendarRepository::new(pool.clone());
+ let notes = PgNoteRepository::new(pool.clone());
+ let access = PgAccessRepository::new(pool.clone());
+ let owner_link = insert_link(&pool, owner).await;
+ let guest_link = insert_link(&pool, guest).await;
+ let stranger_link = insert_link(&pool, stranger).await;
+ sqlx::query!(
+ "UPDATE email_links SET email_address = '[email protected]' WHERE id = $1",
+ owner_link
+ )
+ .execute(&pool)
+ .await
+ .unwrap();
+ sqlx::query!(
+ "UPDATE email_links SET email_address = '[email protected]' WHERE id = $1",
+ guest_link
+ )
+ .execute(&pool)
+ .await
+ .unwrap();
+ let original = timed_upsert(
+ owner,
+ owner_link,
+ provider_ids(&calendar, owner_link).await,
+ "notes-meeting",
+ "Planning",
+ 1,
+ );
+ let target = NoteTarget {
+ event_id: original.event.id,
+ occurrence_key: original.occurrences[0].occurrence_key.clone(),
+ };
+ calendar.upsert_event_fixture(original).await.unwrap();
+ let guest_copy = timed_upsert(
+ guest,
+ guest_link,
+ provider_ids(&calendar, guest_link).await,
+ "notes-meeting",
+ "Planning",
+ 1,
+ );
+ let guest_event = guest_copy.event.id;
+ calendar.upsert_event_fixture(guest_copy).await.unwrap();
+ let forged = timed_upsert(
+ stranger,
+ stranger_link,
+ provider_ids(&calendar, stranger_link).await,
+ "notes-meeting",
+ "Forged",
+ 1,
+ );
+ let forged_target = NoteTarget {
+ event_id: forged.event.id,
+ occurrence_key: target.occurrence_key.clone(),
+ };
+ calendar.upsert_event_fixture(forged).await.unwrap();
+ let document = Uuid::now_v7().to_string();
+ sqlx::query!("INSERT INTO \"Document\" (id, name, owner, \"fileType\") VALUES ($1, 'Meeting notes', $2, 'md')", document, owner).execute(&pool).await.unwrap();
+ notes.link(owner, &target, &document, None).await.unwrap();
+ notes.link(owner, &target, &document, None).await.unwrap();
+ assert_eq!(notes.list(guest, &target).await.unwrap().len(), 1);
+ let guest_id = MacroUserIdStr::parse_from_str(guest).unwrap();
+ let stranger_id = MacroUserIdStr::parse_from_str(stranger).unwrap();
+ assert_eq!(
+ access
+ .get_document_access(&document, Some(&guest_id))
+ .await
+ .unwrap(),
+ Some(AccessLevel::View)
+ );
+ assert_eq!(
+ access
+ .get_document_access(&document, Some(&stranger_id))
+ .await
+ .unwrap(),
+ None
+ );
+ assert!(
+ notes
+ .list(stranger, &forged_target)
+ .await
+ .unwrap()
+ .is_empty()
+ );
+ assert_eq!(
+ access.get_document_access(&document, None).await.unwrap(),
+ None
+ );
+ let injected = Uuid::now_v7().to_string();
+ sqlx::query!("INSERT INTO \"Document\" (id, name, owner, \"fileType\") VALUES ($1, 'Injected notes', $2, 'md')", injected, stranger).execute(&pool).await.unwrap();
+ notes
+ .link(stranger, &forged_target, &injected, None)
+ .await
+ .unwrap();
+ let owner_id = MacroUserIdStr::parse_from_str(owner).unwrap();
+ assert_eq!(
+ access
+ .get_document_access(&injected, Some(&owner_id))
+ .await
+ .unwrap(),
+ None
+ );
+ assert_eq!(notes.list(owner, &target).await.unwrap().len(), 1);
+ let fake_channel = insert_channel(&pool, stranger, &[stranger, owner]).await;
+ sqlx::query!("INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level) VALUES ($1, 'calendar_event', $2, 'channel', 'view')", forged_target.event_id, fake_channel.to_string()).execute(&pool).await.unwrap();
+ assert!(notes.visible(owner, &forged_target).await.unwrap());
+ assert_eq!(notes.list(owner, &target).await.unwrap().len(), 1);
+ let another = NoteTarget {
+ event_id: target.event_id,
+ occurrence_key: "2026-07-25T14:00:00+00:00".into(),
+ };
+ assert!(notes.list(guest, &another).await.unwrap().is_empty());
+
+ sqlx::query!(
+ "UPDATE calendar_events SET is_snapshot = true WHERE id = $1",
+ guest_event
+ )
+ .execute(&pool)
+ .await
+ .unwrap();
+ assert_eq!(
+ access
+ .get_document_access(&document, Some(&guest_id))
+ .await
+ .unwrap(),
+ None
+ );
+ sqlx::query!(
+ "UPDATE calendar_events SET is_snapshot = false WHERE id = $1",
+ guest_event
+ )
+ .execute(&pool)
+ .await
+ .unwrap();
+ sqlx::query!("INSERT INTO calendar_event_overrides (event_id, recurrence_id, original_starts_at, starts_at, ends_at, attendees_overridden) SELECT event_id, occurrence_key, starts_at, starts_at, ends_at, true FROM calendar_event_occurrences WHERE event_id = $1 AND occurrence_key = $2", target.event_id, target.occurrence_key).execute(&pool).await.unwrap();
+ sqlx::query!("UPDATE calendar_event_occurrences SET recurrence_id = occurrence_key WHERE event_id = $1 AND occurrence_key = $2", target.event_id, target.occurrence_key).execute(&pool).await.unwrap();
+ assert_eq!(
+ access
+ .get_document_access(&document, Some(&guest_id))
+ .await
+ .unwrap(),
+ None
+ );
+ sqlx::query!(
+ "UPDATE calendar_event_overrides SET attendees_overridden = false WHERE event_id = $1",
+ target.event_id
+ )
+ .execute(&pool)
+ .await
+ .unwrap();
+ assert_eq!(
+ access
+ .get_document_access(&document, Some(&guest_id))
+ .await
+ .unwrap(),
+ Some(AccessLevel::View)
+ );
+ sqlx::query!(
+ "DELETE FROM calendar_event_attendees WHERE event_id = $1",
+ target.event_id
+ )
+ .execute(&pool)
+ .await
+ .unwrap();
+ assert_eq!(
+ access
+ .get_document_access(&document, Some(&guest_id))
+ .await
+ .unwrap(),
+ None
+ );
+
+ // Provider sync removes cancelled instances instead of retaining tombstones.
+ sqlx::query!(
+ "DELETE FROM calendar_event_occurrences WHERE event_id = $1 AND occurrence_key = $2",
+ target.event_id,
+ target.occurrence_key
+ )
+ .execute(&pool)
+ .await
+ .unwrap();
+ assert!(!notes.visible(owner, &target).await.unwrap());
+ notes.unlink(&target, &document).await.unwrap();
+ notes.unlink(&target, &document).await.unwrap();
+ assert!(notes.list(owner, &target).await.unwrap().is_empty());
+ assert!(notes.is_markdown(&document).await.unwrap());
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn channel_note_access_observes_membership_and_private_occurrences(pool: PgPool) {
+ let owner = "macro|[email protected]";
+ let viewer = "macro|[email protected]";
+ for user in [owner, viewer] {
+ insert_user(&pool, user).await;
+ }
+ let calendar = PgCalendarRepository::new(pool.clone());
+ let link = insert_link(&pool, owner).await;
+ let event = timed_upsert(
+ owner,
+ link,
+ provider_ids(&calendar, link).await,
+ "channel-note",
+ "Planning",
+ 1,
+ );
+ let target = NoteTarget {
+ event_id: event.event.id,
+ occurrence_key: event.occurrences[0].occurrence_key.clone(),
+ };
+ calendar.upsert_event_fixture(event).await.unwrap();
+ let channel = insert_channel(&pool, owner, &[owner, viewer]).await;
+ sqlx::query!("INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level) VALUES ($1, 'calendar_event', $2, 'channel', 'view')", target.event_id, channel.to_string()).execute(&pool).await.unwrap();
+ let notes = PgNoteRepository::new(pool.clone());
+ assert!(notes.visible(viewer, &target).await.unwrap());
+ let overrides =
+ serde_json::json!([{ "recurrenceId": target.occurrence_key, "visibility": "private" }]);
+ sqlx::query!("UPDATE calendar_event_sources SET normalized_payload = jsonb_set(jsonb_set(normalized_payload, '{occurrences,0,recurrenceId}', to_jsonb($2::text)), '{overrides}', $3) WHERE event_id = $1", target.event_id, target.occurrence_key, overrides).execute(&pool).await.unwrap();
+ assert!(!notes.visible(viewer, &target).await.unwrap());
+ sqlx::query!("UPDATE calendar_event_sources SET normalized_payload = jsonb_set(normalized_payload, '{overrides}', '[]') WHERE event_id = $1", target.event_id).execute(&pool).await.unwrap();
+ assert!(notes.visible(viewer, &target).await.unwrap());
+ sqlx::query!("UPDATE comms_channel_participants SET left_at = now() WHERE channel_id = $1 AND user_id = $2", channel, viewer).execute(&pool).await.unwrap();
+ assert!(!notes.visible(viewer, &target).await.unwrap());
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn optional_team_grants_follow_membership_and_leave_other_document_permissions_intact(
+ pool: PgPool,
+) {
+ let owner = "macro|[email protected]";
+ let teammate = "macro|[email protected]";
+ let team = insert_team(&pool, owner, &[owner, teammate]).await;
+ let link = insert_link(&pool, owner).await;
+ let calendar = PgCalendarRepository::new(pool.clone());
+ let event = timed_upsert(
+ owner,
+ link,
+ provider_ids(&calendar, link).await,
+ "team-note",
+ "Planning",
+ 1,
+ );
+ let target = NoteTarget {
+ event_id: event.event.id,
+ occurrence_key: event.occurrences[0].occurrence_key.clone(),
+ };
+ calendar.upsert_event_fixture(event).await.unwrap();
+ let document = Uuid::now_v7();
+ let document_id = document.to_string();
+ sqlx::query!(
+ "INSERT INTO \"Document\" (id, name, owner, \"fileType\") VALUES ($1, 'Notes', $2, 'md')",
+ document_id,
+ owner
+ )
+ .execute(&pool)
+ .await
+ .unwrap();
+ let notes = PgNoteRepository::new(pool.clone());
+ let access = PgAccessRepository::new(pool.clone());
+ let user = MacroUserIdStr::parse_from_str(teammate).unwrap();
+ notes
+ .link(owner, &target, &document_id, None)
+ .await
+ .unwrap();
+ assert_eq!(
+ access
+ .get_document_access(&document_id, Some(&user))
+ .await
+ .unwrap(),
+ None
+ );
+ notes
+ .link(owner, &target, &document_id, Some(team))
+ .await
+ .unwrap();
+ assert_eq!(
+ access
+ .get_document_access(&document_id, Some(&user))
+ .await
+ .unwrap(),
+ Some(AccessLevel::View)
+ );
+ sqlx::query!(
+ "UPDATE calendar_events SET status = 'cancelled' WHERE id = $1",
+ target.event_id
+ )
+ .execute(&pool)
+ .await
+ .unwrap();
+ let links = notes.document_links(owner, &document_id).await.unwrap();
+ assert_eq!(links.len(), 1);
+ assert_eq!(links[0].event_title, "Unavailable meeting");
+ assert_eq!(links[0].team.as_ref().unwrap().id, team);
+ assert!(
+ notes
+ .document_links(teammate, &document_id)
+ .await
+ .unwrap()
+ .is_empty()
+ );
+ let service = crate::domain::notes::MeetingNotes::new(PgNoteRepository::new(pool.clone()));
+ let receipt =
+ entity_access::domain::models::EntityAccessReceipt::dangerously_assert_authenticated_user(
+ MacroUserIdStr::parse_from_str(owner).unwrap(),
+ &document_id,
+ entity_access::domain::models::EntityType::Document,
+ );
+ crate::domain::notes::MeetingNotesService::unlink(&service, receipt, target.clone())
+ .await
+ .unwrap();
+ assert!(
+ notes
+ .document_links(owner, &document_id)
+ .await
+ .unwrap()
+ .is_empty()
+ );
+ assert_eq!(
+ access
+ .get_document_access(&document_id, Some(&user))
+ .await
+ .unwrap(),
+ None
+ );
+ sqlx::query!(
+ "UPDATE calendar_events SET status = 'confirmed' WHERE id = $1",
+ target.event_id
+ )
+ .execute(&pool)
+ .await
+ .unwrap();
+ notes
+ .link(owner, &target, &document_id, Some(team))
+ .await
+ .unwrap();
+ sqlx::query!("DELETE FROM team_user WHERE user_id = $1", teammate)
+ .execute(&pool)
+ .await
+ .unwrap();
+ assert_eq!(
+ access
+ .get_document_access(&document_id, Some(&user))
+ .await
+ .unwrap(),
+ None
+ );
+ sqlx::query!("INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level) VALUES ($1, 'document', $2, 'user', 'edit')", document, teammate).execute(&pool).await.unwrap();
+ notes.unlink(&target, &document_id).await.unwrap();
+ assert_eq!(
+ access
+ .get_document_access(&document_id, Some(&user))
+ .await
+ .unwrap(),
+ Some(AccessLevel::Edit)
+ );
+ assert!(notes.is_markdown(&document_id).await.unwrap());
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn team_detail_access_is_live_and_busy_only_never_reveals_notes(pool: PgPool) {
+ let owner = "macro|[email protected]";
+ let viewer = "macro|[email protected]";
+ insert_team(&pool, owner, &[owner, viewer]).await;
+ let calendar = PgCalendarRepository::new(pool.clone());
+ let link = insert_link(&pool, owner).await;
+ let (account, calendar_id) = provider_ids(&calendar, link).await;
+ let event = timed_upsert(
+ owner,
+ link,
+ (account, calendar_id),
+ "detail-note",
+ "Planning",
+ 1,
+ );
+ let target = NoteTarget {
+ event_id: event.event.id,
+ occurrence_key: event.occurrences[0].occurrence_key.clone(),
+ };
+ calendar.upsert_event_fixture(event).await.unwrap();
+ sqlx::query!(
+ "UPDATE calendars SET synced_at=now(), snapshot_normalization_version=1 WHERE id=$1",
+ calendar_id
+ )
+ .execute(&pool)
+ .await
+ .unwrap();
+ sqlx::query!(
+ "UPDATE calendars SET snapshot_normalization_version=1 WHERE id=$1",
+ calendar_id
+ )
+ .execute(&pool)
+ .await
+ .unwrap();
+ sqlx::query!(
+ "UPDATE calendar_accounts SET sync_status='ready', last_synced_at=now() WHERE id=$1",
+ account
+ )
+ .execute(&pool)
+ .await
+ .unwrap();
+ let notes = PgNoteRepository::new(pool.clone());
+ assert!(!notes.visible(viewer, &target).await.unwrap());
+ sqlx::query!(
+ "INSERT INTO calendar_team_sharing (user_id, sharing) VALUES ($1, 'all')",
+ owner
+ )
+ .execute(&pool)
+ .await
+ .unwrap();
+ assert!(notes.visible(viewer, &target).await.unwrap());
+ let document = Uuid::now_v7().to_string();
+ sqlx::query!(
+ "INSERT INTO \"Document\" (id, name, owner, \"fileType\") VALUES ($1, 'Notes', $2, 'md')",
+ document,
+ viewer
+ )
+ .execute(&pool)
+ .await
+ .unwrap();
+ notes.link(viewer, &target, &document, None).await.unwrap();
+ assert_eq!(
+ notes.document_links(viewer, &document).await.unwrap()[0].event_title,
+ "Shared meeting"
+ );
+ sqlx::query!("UPDATE calendar_event_sources SET normalized_payload = jsonb_set(normalized_payload, '{event,visibility}', '\"private\"') WHERE event_id=$1", target.event_id).execute(&pool).await.unwrap();
+ assert!(!notes.visible(viewer, &target).await.unwrap());
+ sqlx::query!("UPDATE calendar_event_sources SET normalized_payload = jsonb_set(normalized_payload, '{event,visibility}', '\"default\"') WHERE event_id=$1", target.event_id).execute(&pool).await.unwrap();
+ assert!(notes.visible(viewer, &target).await.unwrap());
+ sqlx::query!(
+ "UPDATE calendar_accounts SET last_synced_at=now()-interval '16 minutes' WHERE id=$1",
+ account
+ )
+ .execute(&pool)
+ .await
+ .unwrap();
+ assert!(!notes.visible(viewer, &target).await.unwrap());
+}
diff --git a/crates/calendar_events/src/outbound/pg_notes.rs b/crates/calendar_events/src/outbound/pg_notes.rs
new file mode 100644
index 0000000000..e71823ac54
--- /dev/null
+++ b/crates/calendar_events/src/outbound/pg_notes.rs
@@ -0,0 +1,192 @@
+//! PostgreSQL adapter for durable meeting-note links.
+
+use crate::domain::notes::*;
+use sqlx::PgPool;
+use uuid::Uuid;
+
+/// Calendar-owned note-link storage.
+pub struct PgNoteRepository {
+ pool: PgPool,
+}
+
+impl PgNoteRepository {
+ /// Use the primary database so permission changes are immediately visible.
+ pub fn new(pool: PgPool) -> Self {
+ Self { pool }
+ }
+}
+
+impl NoteRepository for PgNoteRepository {
+ type Err = sqlx::Error;
+
+ async fn document_links(
+ &self,
+ user: &str,
+ document: &str,
+ ) -> Result<Vec<DocumentNoteLink>, Self::Err> {
+ let rows = sqlx::query!(r#"
+ SELECT note.event_id, note.occurrence_key, document.name AS document_name,
+ CASE WHEN calendar_note_event_visible($1, note.event_id, note.occurrence_key)
+ THEN CASE WHEN event.owner_id = $1 OR EXISTS (
+ SELECT 1 FROM macro_user_links delegate
+ WHERE delegate.link_id = event.source_link_id AND delegate.primary_macro_id = $1
+ ) THEN event.title ELSE 'Shared meeting' END
+ ELSE 'Unavailable meeting' END AS "event_title!",
+ team.id AS "team_id?", team.name AS "team_name?"
+ FROM calendar_event_notes note
+ JOIN "Document" document ON document.id = note.document_id AND document.owner = $1 AND document."deletedAt" IS NULL
+ JOIN calendar_events event ON event.id = note.event_id
+ LEFT JOIN team ON team.id = note.team_id
+ WHERE note.document_id = $2
+ ORDER BY note.created_at, note.event_id, note.occurrence_key
+ "#, user, document).fetch_all(&self.pool).await?;
+ Ok(rows
+ .into_iter()
+ .map(|row| DocumentNoteLink {
+ document_name: row.document_name,
+ event_id: row.event_id,
+ occurrence_key: row.occurrence_key,
+ event_title: row.event_title,
+ team: row
+ .team_id
+ .zip(row.team_name)
+ .map(|(id, name)| NoteTeam { id, name }),
+ })
+ .collect())
+ }
+
+ async fn visible(&self, user: &str, target: &NoteTarget) -> Result<bool, Self::Err> {
+ sqlx::query_scalar!(
+ "SELECT calendar_note_event_visible($1, $2, calendar_note_link_key($2, $3)) AS \"visible!\"",
+ user, target.event_id, target.occurrence_key,
+ ).fetch_one(&self.pool).await
+ }
+
+ async fn occurrence_exists(&self, target: &NoteTarget) -> Result<bool, Self::Err> {
+ sqlx::query_scalar!(
+ "SELECT EXISTS (SELECT 1 FROM calendar_event_occurrences WHERE event_id = $1 AND calendar_note_link_key($1, occurrence_key) = calendar_note_link_key($1, $2) AND NOT is_cancelled) AS \"exists!\"",
+ target.event_id, target.occurrence_key,
+ ).fetch_one(&self.pool).await
+ }
+
+ async fn is_markdown(&self, document: &str) -> Result<bool, Self::Err> {
+ sqlx::query_scalar!(
+ "SELECT EXISTS (SELECT 1 FROM \"Document\" WHERE id = $1 AND \"fileType\" = 'md' AND \"deletedAt\" IS NULL) AS \"exists!\"",
+ document,
+ ).fetch_one(&self.pool).await
+ }
+
+ async fn team_member(&self, user: &str, team: Uuid) -> Result<bool, Self::Err> {
+ sqlx::query_scalar!(
+ "SELECT EXISTS (SELECT 1 FROM team_user WHERE user_id = $1 AND team_id = $2) AS \"exists!\"",
+ user, team,
+ ).fetch_one(&self.pool).await
+ }
+
+ async fn list(&self, user: &str, target: &NoteTarget) -> Result<Vec<MeetingNote>, Self::Err> {
+ let rows = sqlx::query!(r#"
+ SELECT d.id, d.name, team.id AS "team_id?", team.name AS "team_name?",
+ d.owner = $1 AS "can_manage!"
+ FROM calendar_event_notes note
+ JOIN calendar_events event ON event.id = note.event_id
+ JOIN calendar_events requested ON requested.id = $2
+ AND requested.ical_uid = event.ical_uid
+ AND lower(requested.organizer_email) IS NOT DISTINCT FROM lower(event.organizer_email)
+ JOIN "Document" d ON d.id = note.document_id AND d."deletedAt" IS NULL AND d."fileType" = 'md'
+ LEFT JOIN team ON team.id = note.team_id
+ WHERE note.occurrence_key = calendar_note_link_key($2, $3) AND event.status <> 'cancelled'
+ AND calendar_note_event_visible($1, note.event_id, note.occurrence_key)
+ AND calendar_note_copies_match(requested.id, note.event_id, calendar_note_link_key($2, $3))
+ ORDER BY note.created_at, d.id
+ "#, user, target.event_id, target.occurrence_key).fetch_all(&self.pool).await?;
+ Ok(rows
+ .into_iter()
+ .map(|row| MeetingNote {
+ document_id: row.id,
+ name: row.name,
+ team: row
+ .team_id
+ .zip(row.team_name)
+ .map(|(id, name)| NoteTeam { id, name }),
+ can_manage: row.can_manage,
+ })
+ .collect())
+ }
+
+ async fn picker(&self, user: &str, query: &str) -> Result<NotePicker, Self::Err> {
+ let documents = sqlx::query_as!(
+ NoteDocument,
+ r#"
+ SELECT id AS document_id, name FROM "Document"
+ WHERE owner = $1 AND "fileType" = 'md' AND "deletedAt" IS NULL
+ AND name ILIKE '%' || $2 || '%'
+ ORDER BY "updatedAt" DESC, id LIMIT 30
+ "#,
+ user,
+ query
+ )
+ .fetch_all(&self.pool)
+ .await?;
+ let teams = sqlx::query_as!(
+ NoteTeam,
+ r#"
+ SELECT team.id, team.name FROM team
+ JOIN team_user member ON member.team_id = team.id WHERE member.user_id = $1
+ ORDER BY team.name, team.id
+ "#,
+ user
+ )
+ .fetch_all(&self.pool)
+ .await?;
+ Ok(NotePicker { documents, teams })
+ }
+
+ async fn link(
+ &self,
+ user: &str,
+ target: &NoteTarget,
+ document: &str,
+ team: Option<Uuid>,
+ ) -> Result<(), Self::Err> {
+ let mut tx = self.pool.begin().await?;
+ // A document can be linked from two inbox copies concurrently. Serialize
+ // its link writes so retries never leave duplicate or conflicting grants.
+ sqlx::query!(
+ "SELECT pg_advisory_xact_lock(hashtextextended($1, 0))",
+ document
+ )
+ .execute(&mut *tx)
+ .await?;
+ sqlx::query!(r#"
+ DELETE FROM calendar_event_notes note USING calendar_events event, calendar_events requested
+ WHERE note.event_id = event.id AND requested.id = $1
+ AND event.ical_uid = requested.ical_uid
+ AND lower(event.organizer_email) IS NOT DISTINCT FROM lower(requested.organizer_email)
+ AND note.occurrence_key = calendar_note_link_key($1, $2) AND note.document_id = $3 AND note.event_id <> $1
+ "#, target.event_id, target.occurrence_key, document).execute(&mut *tx).await?;
+ sqlx::query!(r#"
+ INSERT INTO calendar_event_notes (event_id, occurrence_key, document_id, team_id, user_id)
+ VALUES ($1, calendar_note_link_key($1, $2), $3, $4, $5)
+ ON CONFLICT (event_id, occurrence_key, document_id) DO UPDATE SET team_id = EXCLUDED.team_id, user_id = EXCLUDED.user_id
+ "#, target.event_id, target.occurrence_key, document, team, user).execute(&mut *tx).await?;
+ tx.commit().await
+ }
+
+ async fn unlink(&self, target: &NoteTarget, document: &str) -> Result<(), Self::Err> {
+ let mut tx = self.pool.begin().await?;
+ sqlx::query!(
+ "SELECT pg_advisory_xact_lock(hashtextextended($1, 0))",
+ document
+ )
+ .execute(&mut *tx)
+ .await?;
+ sqlx::query!(r#"
+ DELETE FROM calendar_event_notes note USING calendar_events event, calendar_events requested
+ WHERE note.event_id = event.id AND requested.id = $1
+ AND event.ical_uid = requested.ical_uid
+ AND lower(event.organizer_email) IS NOT DISTINCT FROM lower(requested.organizer_email)
+ AND (note.occurrence_key = $2 OR note.occurrence_key = calendar_note_link_key($1, $2)) AND note.document_id = $3
+ "#, target.event_id, target.occurrence_key, document).execute(&mut *tx).await?;
+ tx.commit().await
+ }
+}
diff --git a/crates/code_execution/src/outbound/deno/sdk.mjs b/crates/code_execution/src/outbound/deno/sdk.mjs
index 253ac3bcd8..71aed5515c 100644
--- a/crates/code_execution/src/outbound/deno/sdk.mjs
+++ b/crates/code_execution/src/outbound/deno/sdk.mjs
@@ -1,62 +1,62 @@
// Generated by packages/code-mode-sdk/scripts/generate.ts.
-async function bO($,O,j){if(!Number.isInteger(O)||O<1)throw RangeError(`concurrency limit must be a positive integer, got ${O}`);let x=Array($.length),S=0,K=async()=>{while(S<$.length){let X=S;S+=1,x[X]=await j($[X])}},Z=Array.from({length:Math.min(O,$.length)},K);return await Promise.all(Z),x}class V${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*a($){let O;do{let j=await $(O),x=j.nextCursor??void 0;if(O!==void 0&&x!==void 0&&JSON.stringify(x)===JSON.stringify(O))throw Error("Pagination cursor did not advance");yield*j.items,O=x}while(O!==void 0)}class b extends Error{constructor($){super($);this.name="MacroError"}}class SO extends b{status;data;constructor($,O){super(`Macro API error ${$}`);this.status=$;this.data=O;this.name="MacroApiError"}}class w extends b{constructor($){super($);this.name="MacroNotFoundError"}}function Q($){if($.error!==void 0)throw new SO($.response?.status??0,$.error);return $.data}class A{client;id;detail;constructor($,O,j){this.client=$;this.id=O;this.detail=new V$(()=>this.fetch(),j)}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=Q(await $(this.client));return this.detail.clear(),O}}class F$ extends A{async permission(){return Q(await this.client.storage.getEntityPermission({path:{entity_type:this.entityType,entity_id:this.id}}))}async favorite(){return Q(await this.client.storage.addFavorite({body:{entityId:this.id,entityType:this.entityType}})),this}async unfavorite(){return Q(await this.client.storage.removeFavoriteByEntity({path:{entity_type:this.entityType,entity_id:this.id}})),this}}class S$ extends F${propertyReference(){return{entity_type:this.propertyEntityType,entity_id:this.id}}async properties($){let{properties:O}=Q(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){Q(await this.client.properties.setEntityProperty({path:{...this.propertyReference(),property_id:$.id},body:{value:O??null}}))}async updatePropertyOptions($){return Q(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((j)=>j.id)}:{},...O.remove?{remove_option_ids:O.remove.map((j)=>j.id)}:{}}))}}))}async deleteProperty($){Q(await this.client.properties.deleteEntityProperty({path:{entity_property_id:$.property.id}}))}}function l$($,O){return`<${$}>${JSON.stringify(O)}</${$}>`}function H6($){return typeof $==="object"&&$!==null&&typeof $.toMention==="function"}var R6={toMention:()=>({tag:l$("m-group-mention",{groupAlias:"here"}),mention:{entity_type:"group",entity_id:"here"}})};function D6($,...O){let j="",x=[];for(let[S,K]of $.entries()){j+=K;let Z=O[S];if(Z===void 0)continue;if(H6(Z)){let X=Z.toMention();j+=X.tag,x.push(X.mention)}else j+=String(Z)}return{content:j,mentions:C6(x)}}function C6($){let O=new Set;return $.filter((j)=>{let x=`${j.entity_type}:${j.entity_id}`;if(O.has(x))return!1;return O.add(x),!0})}function $$($){return typeof $==="string"?{content:$,mentions:[]}:$}class W$ extends A{static byId($,O){return new W$($,O)}static from($,O){return new W$($,O.id,O)}async fetch(){let $=Q(await this.client.storage.listHarnesses()).find((O)=>O.id===this.id);if(!$)throw new w(`Harness ${this.id} is unavailable`);return $}name=this.field("name");connected=this.field("connected");kind=this.field("kind");async delete(){await this.mutate(($)=>$.storage.deleteHarness({path:{harness_id:this.id}}))}}class U$ extends A{static byId($,O){return new U$($,O)}static from($,O){return new U$($,O.bot.id,O)}async fetch(){let $=Q(await this.client.storage.listAgents()).find((O)=>O.bot.id===this.id);if(!$)throw new w(`Agent ${this.id} is unavailable`);return $}name=this.mappedField("bot",($)=>$.name);instructions=this.field("instructions");defaultModel=this.field("default_model");channels=this.mappedField("channel_ids",($)=>$.map((O)=>f.byId(this.client,O)));host=this.mappedField("harness_id",($)=>$?W$.byId(this.client,$):void 0);async update($){await this.mutate((O)=>O.storage.updateAgent({path:{agent_id:this.id},body:Fx($)}))}}function Fx($){let{channels:O,team:j,host:x,autoAcceptPermissions:S,avatarUrl:K,channelScope:Z,defaultModel:X,isCoding:G,...L}=$;return{...L,channel_ids:O?.map((Y)=>Y.id),team_id:j?.id,harness_id:x?.id,auto_accept_permissions:S,avatar_url:K,channel_scope:Z,default_model:X,is_coding:G}}async function Xj($,O,j){let{channelId:x,thread:S}=_6(O);if(await M6($)){let{id:Z}=Q(await $.storage.entityMessageCreate({path:{parent_type:"channel",parent_id:x},body:{content:j.content,mentions:j.mentions,attachments:[],thread_id:S?.rootId??null,nonce:crypto.randomUUID()}}));return Z}if(S)throw new b("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}=Q(await $.storage.postChannelBotWebhook({path:{channel_id:x},body:{content:j.content},headers:{"x-macro-bot-scope":"user"}}));return K}function _6($){return"rootId"in $?{channelId:$.channelId,thread:$}:{channelId:$.id}}async function M6($){if($.authConfig.type!=="bot"||$.hasActingUser())return!0;let{owner:O}=await $.selfBot();return O?.type==="team"}class g${client;channelId;rootId;constructor($,O,j){this.client=$;this.channelId=O;this.rootId=j}toJSON(){return{channelId:this.channelId,rootId:this.rootId}}channel(){return f.byId(this.client,this.channelId)}root(){return e.byId(this.client,this.channelId,this.rootId)}async replies(){let{replies:$}=Q(await this.client.storage.entityMessageGetThread({path:{parent_type:"channel",parent_id:this.channelId,id:this.rootId}}));return $.map((O)=>e.from(this.client,this.channelId,O))}async reply($){let O=await Xj(this.client,this,$$($));return e.byId(this.client,this.channelId,O)}}class e extends F${channelId;mentions;entityType="channel_message";constructor($,O,j,x=[],S){super($,j,S);this.channelId=O;this.mentions=x}get path(){return{parent_type:"channel",parent_id:this.channelId,id:this.id}}async fetch(){return Q(await this.client.storage.entityMessageGetMessage({path:this.path}))}static byId($,O,j,x=[]){return new e($,O,j,x)}static from($,O,j){return new e($,O,j.id,j.mentions,j)}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 g$(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:j}=$$($);return await this.mutate((x)=>x.storage.entityMessageEdit({path:this.path,body:{content:O,mentions:j}})),this}async delete(){await this.mutate(($)=>$.storage.entityMessageDeleteMessage({path:this.path}))}async reply($){return this.thread().reply($)}}class Gj{client;channel;record;constructor($,O,j){this.client=$;this.channel=O;this.record=j}agent(){return U$.byId(this.client,this.record.botId)}sessions(){return this.record.sessions.map(($)=>({session:i.byId(this.client,$.sessionId),isCurrent:$.isCurrent,createdAt:$.createdAt}))}turns(){return this.record.turns.map(($)=>new Ex(this.client,this,$))}async startFresh($){Q(await this.client.agentHarness.startFreshAgentConversation({path:{channel_id:this.channel.id,bot_id:this.record.botId},body:{sessionId:$.id}}))}toJSON(){return{channelId:this.channel.id,agentId:this.record.botId}}}class Ex{client;conversation;record;constructor($,O,j){this.client=$;this.conversation=O;this.record=j}source(){return e.byId(this.client,this.conversation.channel.id,this.record.sourceMessageId)}session(){return i.byId(this.client,this.record.sessionId)}async retry($){Q(await this.client.agentHarness.retryAgentConversationTurn({path:{channel_id:this.conversation.channel.id,bot_id:this.conversation.agent().id,source:this.record.sourceMessageId},body:{actionId:$}}))}toJSON(){return{channelId:this.conversation.channel.id,sourceMessageId:this.record.sourceMessageId}}}class B$ extends A{parent;toJSON(){return{...super.toJSON(),parentType:this.parent.type,parentId:this.parent.entity.id}}constructor($,O,j){super($,j);this.parent=O}static byId($,O,j){return new B$($,O,j)}get path(){return{parent_type:this.parent.type,parent_id:this.parent.entity.id,id:this.id}}async fetch(){return Q(await this.client.storage.entityMessageGetThread({path:this.path})).state}resolved=this.field("resolved");async update($){let O={resolved:$.resolved,detach_anchor:$.detachAnchor,nonce:$.nonce};await this.mutate((j)=>j.storage.entityMessagePatchThread({path:this.path,body:O}))}async delete($){await this.mutate((O)=>O.storage.entityMessageDeleteThread({path:this.path,query:{nonce:$}}))}}async function E$($,O,j,x){for(let K of[...x?.messages??[],...x?.around?[x.around]:[]]){let Z="channelId"in K?{type:"channel",id:K.channelId}:("documentId"in K)?{type:"document",id:K.documentId}:("callId"in K)?{type:"call",id:K.callId}:K.parent;if(Z.type!==O.type||Z.id!==O.entity.id)throw Error("Timeline message belongs to another resource")}let S=Q(await $.storage.messageTimelineEntries({path:{parent_type:O.type,parent_id:O.entity.id},query:{selection:x?JSON.stringify({cursor:x.cursor,around:x.around?.id,ids:x.messages?.map((K)=>K.id),activity_after:x.activityAfter,activity_before:x.activityBefore,anchored:x.anchored,direction:x.direction,include_deleted_threads:x.includeDeletedThreads,limit:x.limit}):void 0}}));return{entries:S.entries.map((K)=>{if(K.type==="activity")return{type:"activity",activity:{...K.activity,actor:M.byId($,K.activity.actor_id)}};return{type:"message",message:j(K.message)}}),nextCursor:S.next_cursor??void 0,previousCursor:S.previous_cursor??void 0}}var A6=50;function j$($){let{filters:O,type:j,make:x,includeCrm:S}=$;return(K,Z,X)=>{let G=X?.searchOn??"name_content",L=X?.pageSize??A6;return a(async(Y)=>{let{results:J,next_cursor:T}=Q(await K.search.unifiedSearch({body:{query:Z,match_type:"partial",search_on:G,...O?{filters:O}:{},...S?{include_crm:!0}:{}},query:{page_size:L,...Y?{cursor:Y}:{}}}));return{items:J.filter((W)=>W.type===j).map((W)=>x(K,W)),nextCursor:T}})}}class ZO{client;channel;record;constructor($,O,j){this.client=$;this.channel=O;this.record=j}get id(){return this.record.id}user(){return M.byId(this.client,this.record.user_id)}createdAt(){return this.record.created_at}async recordInteraction($){return new ZO(this.client,this.channel,Q(await this.client.storage.postActivity({body:{activity_type:$,channel_id:this.channel.id}})))}toJSON(){return this.record}}class f extends S${async recordActivity($){return new ZO(this.client,this,Q(await this.client.storage.postActivity({body:{activity_type:$,channel_id:this.id}})))}async setPicture($){await this.mutate((O)=>O.storage.setChannelPicture({path:{channel_id:this.id},body:{profile_picture_id:$?.id??null}}))}messageThreadById($){return B$.byId(this.client,{type:"channel",entity:this},$)}timelinePage($){return E$(this.client,{type:"channel",entity:this},(O)=>e.from(this.client,this.id,O),$)}async agentConversations(){return Q(await this.client.agentHarness.listAgentConversations({path:{channel_id:this.id}})).conversations.map(($)=>new Gj(this.client,this,$))}entityType="channel";propertyEntityType="CHANNEL";async fetch(){return Q(await this.client.storage.getChannel({path:{channel_id:this.id}}))}static byId($,O){return new f($,O)}static async dm($,O){let{channel_id:j}=Q(await $.storage.getOrCreateDm({body:{recipient_id:O.id}}));return new f($,j)}static async private($,O){let{channel_id:j}=Q(await $.storage.getOrCreatePrivate({body:{recipients:O.map((x)=>x.id)}}));return new f($,j)}static async create($,O){let{id:j}=Q(await $.storage.createChannel({body:{channel_type:O.type,name:O.name??null,participants:(O.participants??[]).map((x)=>x.id),team_id:O.team?.id??null}}));return new f($,j)}name=this.field("channel_name");type=this.field("channel_type");async send($,O){let j=await Xj(this.client,O?.thread??this,$$($));return e.byId(this.client,this.id,j)}messages($){return this.timeline({limit:$?.pageSize})}messagesAfter($,O){return this.timeline({activity_after:$ instanceof Date?$.toISOString():$,limit:O?.pageSize})}timeline($){return a(async(O)=>{let j=Q(await this.client.storage.messageTimeline({path:{parent_type:"channel",parent_id:this.id},query:{selection:JSON.stringify({...$,cursor:O})}}));return{items:j.items.map((x)=>e.from(this.client,this.id,x)),nextCursor:j.next_cursor}})}message($){return e.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:$}=Q(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 Q(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((j)=>j.id)}}))}async removeParticipants($){await this.mutate((O)=>O.storage.removeParticipants({path:{channel_id:this.id},body:{participants:$.map((j)=>j.id)}}))}async typing($,O){Q(await this.client.storage.entityMessageTyping({path:{parent_type:"channel",parent_id:this.id},body:{active:$==="start",thread_id:O?.thread?.rootId??null}}))}attachments($){return a(async(O)=>{let j=Q(await this.client.storage.getChannelAttachments({path:{channel_id:this.id},query:{...$?.pageSize?{limit:$.pageSize}:{},...$?.type?{attachment_type:$.type}:{},...O?{cursor:O}:{}}}));return{items:j.items,nextCursor:j.next_cursor}})}webUrl(){return`${this.client.webAppUrl}/app/channel/${this.id}`}static search=j$({type:"channel",make:($,O)=>new f($,O.channel_id)})}class M extends S${entityType="user";propertyEntityType="USER";async fetch(){let{names:$}=Q(await this.client.auth.getUserNamesWithEmail({body:{user_ids:[this.id]}})),O=$.find((j)=>j.id===this.id);if(!O)throw new w(`user ${this.id} not found`);return O}static byId($,O){return new M($,O)}static async me($){let{user_id:O}=Q(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:l$("m-user-mention",{userId:this.id}),mention:{entity_type:"user",entity_id:this.id}}}}class o{client;entityType;entity;constructor($,O,j){this.client=$;this.entityType=O;this.entity=j}get path(){return{entity_type:this.entityType,entity_id:this.entity.id}}async state($){let O=Q(await this.client.storage.accessRequestsState({path:this.path,query:{offset:$}}));return{accessLevel:O.accessLevel??void 0,canReview:O.canReview,owner:O.owner?M.byId(this.client,O.owner):void 0,pendingCount:O.pendingCount,supportedLevels:O.supportedLevels,nextOffset:O.nextOffset??void 0,mine:O.mine?WO.from(this.client,this,O.mine):void 0,requests:O.requests.map((j)=>WO.from(this.client,this,j))}}async submit($,O){return WO.from(this.client,this,Q(await this.client.storage.accessRequestsSubmit({path:this.path,body:{requestedLevel:$,revision:O}})))}async cancel($){Q(await this.client.storage.accessRequestsCancel({path:this.path,query:{revision:$}}))}async direct(){return Q(await this.client.storage.accessRequestsDirect({path:this.path})).map(($)=>({user:M.byId(this.client,$.userId),accessLevel:$.accessLevel}))}async grant($,O){Q(await this.client.storage.accessRequestsSetDirect({path:{...this.path,user_id:$.id},body:{accessLevel:O}}))}async remove($){Q(await this.client.storage.accessRequestsRemoveDirect({path:{...this.path,user_id:$.id}}))}async resolve($,O){let j=$.access.toJSON();if(j.entity_type!==this.entityType||j.entity_id!==this.entity.id)throw Error("Access request belongs to another entity");return Q(await this.client.storage.accessRequestsResolve({path:{...this.path,request_id:$.id},body:O}))}toJSON(){return this.path}}class WO extends A{access;resolvedRecord;constructor($,O,j){super($,j.id,j);this.access=O}static from($,O,j){return new WO($,O,j)}async fetch(){if(this.resolvedRecord)return this.resolvedRecord;let $;do{let O=await this.access.state($),j=[O.mine,...O.requests].find((x)=>x?.id===this.id);if(j)return j.detail.get();$=O.nextOffset}while($!==void 0);throw new w(`Access request ${this.id} is unavailable`)}revision=this.field("revision");status=this.field("status");requestedLevel=this.field("requestedLevel");requester=this.mappedField("requesterId",($)=>M.byId(this.client,$));async resolve($){this.resolvedRecord=await this.access.resolve(this,{revision:await this.revision(),grantedLevel:$}),this.detail.clear()}}function r$($){return{...$,channelSharePermissions:$.channelSharePermissions===void 0||$.channelSharePermissions===null?$.channelSharePermissions:$.channelSharePermissions.map((O)=>({channelId:O.channel.id,accessLevel:O.accessLevel,operation:O.operation}))}}class L$ extends A{parent;constructor($,O,j,x){super($,j,x);this.parent=O}static byId($,O,j){return new L$($,O,j)}static fromRecord($,O,j){return new L$($,O,j.id,j)}static async create($,O,j){return L$.createForSession($,O.session(),j,O)}static async createForSession($,O,j,x){let S=Q(await $.agentHarness.createSessionReview({path:{session_id:O.id},body:{...j,executionId:x?.id??null}}));return L$.fromRecord($,O,S)}static async list($,O){return Q(await $.agentHarness.listExecutionReviews({path:{session_id:O.session().id,execution_id:O.id}})).map((x)=>L$.fromRecord($,O.session(),x))}async fetch(){return Q(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 wx($,{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((j)=>j.agentHarness.decideSessionReview({path:{session_id:this.parent.id,review_id:this.id},body:{...$,revision:O}}))}}class wx{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 kO extends A{parent;constructor($,O,j){super($,O);this.parent=j}static byId($,O,j){return new kO($,j,O)}async fetch(){return Q(await this.client.agentHarness.getCodeExecution({path:{session_id:this.parent.id,execution_id:this.id}}))}reviews={create:($)=>L$.create(this.client,this,$),list:()=>L$.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 Kj{client;sessionId;dto;constructor($,O,j){this.client=$;this.sessionId=O;this.dto=j}static from($,O,j){return new Kj($,O,j)}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 Q(await this.client.agentHarness.editQueuedAction({path:{session_id:this.sessionId,action_id:this.actionId},body:{prompt:$}})),this.dto={...this.dto,prompt:$},this}async steer(){Q(await this.client.agentHarness.steerQueuedAction({path:{session_id:this.sessionId,action_id:this.actionId}}))}async remove(){Q(await this.client.agentHarness.removeQueuedAction({path:{session_id:this.sessionId,action_id:this.actionId}}))}}class gO{client;session;id;constructor($,O,j){this.client=$;this.session=O;this.id=j}static byId($,O,j){return new gO($,O,j)}async answer($){return Q(await this.client.agentHarness.answerAgentSessionToolApproval({path:{session_id:this.session.id,approval_id:this.id},body:{answer:$}}))}toJSON(){return{id:this.id,sessionId:this.session.id}}}class i extends A{access=new o(this.client,"agent_session",this);toolApprovalById($){return gO.byId(this.client,this,$)}async sharePermissions(){return Q(await this.client.agentHarness.getAgentSessionPermissions({path:{session_id:this.id}}))}async updateSharePermissions($){return this.mutate((O)=>O.agentHarness.updateAgentSessionPermissions({path:{session_id:this.id},body:r$($)}))}static byId($,O){return new i($,O)}static async createManaged($,O){let{session:j}=Q(await $.agentHarness.createAgentSession({body:{prompt:O?.prompt,instructions:O?.instructions,model:O?.model,repoUrl:O?.repoUrl,repoBranch:O?.repoBranch}}));return new i($,j.id,j)}static async repositories($){let{repositories:O}=Q(await $.agentHarness.listAgentRepositories());return O.map((j)=>({url:j.url,defaultBranch:j.defaultBranch??void 0}))}static async repositoryBranches($,O){let{branches:j}=Q(await $.agentHarness.listAgentRepositoryBranches({query:{repoUrl:O}}));return j}async fetch(){return Q(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:j}=Q(await $.agentHarness.agentSessionsForPullRequest({body:{url:O}}));return j.map((x)=>i.byId($,x))}async pullRequests(){let{pullRequests:$}=Q(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($){Q(await this.client.agentHarness.linkAgentSessionPullRequest({path:{session_id:this.id},body:{url:$}}))}async unlinkPullRequest($){Q(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((j)=>j.agentHarness.putAgentSessionSandboxSize({path:{session_id:this.id},body:{size:$}}));return O}static async defaultSandboxSize($){return Q(await $.agentHarness.getAgentSandboxSize()).size}static async setDefaultSandboxSize($,O){return Q(await $.agentHarness.putAgentSandboxSize({body:{size:O}})).size}static async codingPreferences($){return Q(await $.agentHarness.getAgentCodingPreferences())}static async setCodingPreferences($,O){return Q(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:$}=Q(await this.client.agentHarness.getAgentSessionQueue({path:{session_id:this.id}}));return $.map((O)=>Kj.from(this.client,this.id,O))}async changes(){return Q(await this.client.agentHarness.getAgentSessionChanges({path:{session_id:this.id}}))}async changesPatch(){return Q(await this.client.agentHarness.getAgentSessionChangesPatch({path:{session_id:this.id}})).patch}async refreshChanges(){return this.mutate(($)=>$.agentHarness.refreshAgentSessionChanges({path:{session_id:this.id}}))}async foldedLog(){let{bot:$,messages:O}=Q(await this.client.agentHarness.getAgentSessionFoldedLog({path:{session_id:this.id}}));return{bot:$,messages:O}}async log(){return Q(await this.client.agentHarness.getAgentSessionLog({path:{session_id:this.id}}))}reviews={create:($)=>L$.createForSession(this.client,this,$),byId:($)=>L$.byId(this.client,this,$)};codeExecutions={byId:($)=>kO.byId(this.client,this,$)};async delete(){await this.mutate(($)=>$.agentHarness.deleteAgentSession({path:{session_id:this.id}}))}}class qx{client;constructor($){this.client=$}byId($){return i.byId(this.client,$)}createManaged($){return i.createManaged(this.client,$)}repositories(){return i.repositories(this.client)}repositoryBranches($){return i.repositoryBranches(this.client,$)}forPullRequest($){return i.forPullRequest(this.client,$)}defaultSandboxSize(){return i.defaultSandboxSize(this.client)}setDefaultSandboxSize($){return i.setDefaultSandboxSize(this.client,$)}codingPreferences(){return i.codingPreferences(this.client)}setCodingPreferences($){return i.setCodingPreferences(this.client,$)}}class fx{client;constructor($){this.client=$}byId($){return U$.byId(this.client,$)}async list(){return Q(await this.client.storage.listAgents()).map(($)=>U$.from(this.client,$))}async create($){return U$.from(this.client,Q(await this.client.storage.createAgent({body:Fx($)})))}}class bx{client;async usage($={}){let{users:O,...j}=$;return Q(await this.client.cognition.getUsageHandler({body:{...j,include_users:O?.map((x)=>x.id)}}))}constructor($){this.client=$}async structuredCompletion($){return Q(await this.client.cognition.structuredCompletion({body:$}))}async decide($){return Q(await this.client.cognition.decisions({body:$}))}}class p$ extends A{static byId($,O){return new p$($,O)}static from($,O){return new p$($,O.id,{id:O.id,name:O.name,createdAt:O.createdAt})}async fetch(){let $=Q(await this.client.storage.listUserApiKeys()).keys.find((O)=>O.id===this.id);if(!$)throw new w(`API key ${this.id} is unavailable`);return $}name=this.field("name");createdAt=this.field("createdAt");async delete(){await this.mutate(($)=>$.storage.deleteUserApiKey({path:{id:this.id}}))}}class kx{client;constructor($){this.client=$}byId($){return p$.byId(this.client,$)}async list(){return Q(await this.client.storage.listUserApiKeys()).keys.map(($)=>p$.from(this.client,$))}async create($){let O=Q(await this.client.storage.createUserApiKey({body:{name:$}}));return{key:p$.from(this.client,O),secret:O.key}}async tokenForEmail($){return Q(await this.client.auth.macroApiToken({query:{email:$}}))}}class yO{client;constructor($){this.client=$}async me(){if(this.client.authConfig.type!=="bot")throw new b("bots.me() requires bot auth — a user API key has no bot identity");return Q(await this.client.storage.getSelfBot())}async channels(){if(this.client.authConfig.type!=="bot")throw new b("bots.channels() requires bot auth — a user API key has no bot identity");let $=await this.me();return Q(await this.client.storage.listBotChannels({path:{bot_id:$.id}}))}async myPrincipalId(){if(this.client.authConfig.type!=="bot")throw new b("bots.myPrincipalId() requires bot auth — a user API key has no bot identity");return this.client.myPrincipalId()}}class z$ extends A{async fetch(){let{links:$}=Q(await this.client.email.listLinks()),O=$.find((j)=>j.id===this.id);if(!O)throw new w(`email link ${this.id} not found`);return O}static byId($,O){return new z$($,O)}static async list($){let{links:O}=Q(await $.email.listLinks());return O.map((j)=>new z$($,j.id,j))}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");async settingsOperations(){return Q(await this.client.email.mailboxSettingsOperations({headers:{"X-Email-Link-Id":this.id}}))}}class y$ extends A{async setContributesToAvailability($){await this.mutate((O)=>O.calendar.setAvailabilityCalendar({path:{calendar_id:this.id},body:{contributesToAvailability:$}}))}async fetch(){let{calendars:$}=Q(await this.client.calendar.listCalendars()),O=$.find((j)=>j.id===this.id);if(!O)throw new w(`calendar ${this.id} not found`);return O}static byId($,O){return new y$($,O)}static async list($){let{calendars:O}=Q(await $.calendar.listCalendars());return O.map((j)=>new y$($,j.id,j))}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",($)=>z$.byId(this.client,$))}class vO{client;id;constructor($,O){this.client=$;this.id=O}async status(){return Q(await this.client.calendar.calendarReplacementStatus({path:{operation_id:this.id}}))}async confirm(){return Q(await this.client.calendar.confirmCalendarReplacement({path:{operation_id:this.id}}))}async discard(){Q(await this.client.calendar.discardCalendarReplacement({path:{operation_id:this.id}}))}}class K$ extends A{async fetch(){throw new b(`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 K$($,O)}static fromRecord($,O){return new K$($,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");guestPolicy=this.field("guestPolicy");viewerCan=this.field("viewerCan");calendar=this.mappedField("calendarId",($)=>$?y$.byId(this.client,$):void 0);record(){return this.detail.get()}async update($){let O=await this.mutate((j)=>j.calendar.updateCalendarEvent({path:{event_id:this.id},body:P6($)}));return K$.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 prepareReplacement($){let O=Q(await this.client.calendar.prepareCalendarReplacement({path:{event_id:this.id},body:{removeConference:$.removeConference,recurrenceId:$.recurrenceId,calendarId:$.calendar?.id}}));return new vO(this.client,O.operationId)}async providerUrl($={}){return Q(await this.client.calendar.calendarEventProviderUrl({path:{event_id:this.id},query:{recurrenceId:$.recurrenceId,calendarId:$.calendar?.id}})).url??void 0}async inviteGuests($){let O=await this.mutate((j)=>j.calendar.inviteCalendarEventGuests({path:{event_id:this.id},body:{guests:$.guests,scope:$.scope,recurrenceId:$.recurrenceId,calendarId:$.calendar?.id}}));return K$.fromRecord(this.client,O)}async addToCalendar($={}){let O=await this.mutate((j)=>j.calendar.copyCalendarEvent({path:{event_id:this.id},body:{calendarId:$.calendar?.id}}));return K$.fromRecord(this.client,O)}async ics(){return Q(await this.client.storage.eventIcs({path:{event_id:this.id}}))}async rsvp($){let O=await this.mutate((j)=>j.calendar.rsvpCalendarEvent({path:{event_id:this.id},body:{response:$.response,scope:$.scope,recurrenceId:$.recurrenceId,calendarId:$.calendar?.id}}));return K$.fromRecord(this.client,O)}}function P6($){return{title:$.title,description:$.description,location:$.location,time:$.time,attendees:$.attendees,recurrenceLines:$.recurrenceLines,visibility:$.visibility,transparency:$.transparency,reminders:$.reminders,conference:$.conference,outOfOffice:$.outOfOffice,guestPolicy:$.guestPolicy,scope:$.scope,recurrenceId:$.recurrenceId,calendarId:$.calendar?.id}}class gx{client;async availabilityCalendars(){return Q(await this.client.calendar.getAvailabilityCalendars()).calendars.map(($)=>({calendar:y$.byId(this.client,$.calendarId),name:$.name,isPrimary:$.isPrimary,contributesToAvailability:$.contributesToAvailability}))}async teamSharing(){return Q(await this.client.calendar.getTeamSharing()).sharing}async setTeamSharing($){return Q(await this.client.calendar.setTeamSharing({body:{sharing:$}})).sharing}occurrences($){return a(async(O)=>{let j=Q(await this.client.storage.listOccurrences({query:{...$,cursor:O}}));return{items:j.items.map((x)=>({event:K$.fromRecord(this.client,x.event),occurrence:x.occurrence})),nextCursor:j.nextCursor}})}async teamPage($){let O=Q(await this.client.storage.listTeamCalendar({query:$}));return{items:O.items.map(({ownerId:j,...x})=>({...x,owner:M.byId(this.client,j)})),members:O.members.map((j)=>({user:M.byId(this.client,j.userId),sharing:j.sharing,coverage:j.coverage})),nextCursor:O.nextCursor??void 0}}async teamOutOfOffice($){let O=Q(await this.client.storage.listTeamOutOfOffice({query:$}));return{items:O.items.map((j)=>({event:K$.byId(this.client,j.eventId),owner:M.byId(this.client,j.ownerId),occurrenceKey:j.occurrenceKey,time:j.time,title:j.title??void 0})),hasMore:O.hasMore}}constructor($){this.client=$}calendars(){return y$.list(this.client)}calendar($){return y$.byId(this.client,$)}event($){return K$.byId(this.client,$)}replacement($){return new vO(this.client,$)}async createEvent($){let O=Q(await this.client.calendar.createCalendarEvent({body:F6($)}));return K$.fromRecord(this.client,O)}}function F6($){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,guestPolicy:$.guestPolicy,calendarId:$.calendar?.id,emailLinkId:$.emailLink?.id}}class I$ extends A{lookupToken;constructor($,O,j){super($,O,j);this.lookupToken=j?.shareToken}static byId($,O){return new I$($,O)}static from($,O){return new I$($,O.id,O)}async fetch(){if(this.lookupToken)return Q(await this.client.storage.meetingLookup({path:{token:this.lookupToken}}));let $=Q(await this.client.storage.meetingList()).meetings.find((O)=>O.id===this.id);if(!$)throw new w(`Meeting ${this.id} is unavailable`);return this.lookupToken=$.shareToken,$}title=this.field("title");scheduledStart=this.field("scheduledStart");scheduledEnd=this.field("scheduledEnd");channel=this.mappedField("channelId",($)=>$?f.byId(this.client,$):void 0);call=this.mappedField("callId",($)=>$?Y$.byId(this.client,$):void 0);async update($){await this.mutate((O)=>O.storage.meetingUpdate({path:{meeting_id:this.id},body:$}))}async cancel(){await this.mutate(($)=>$.storage.meetingCancel({path:{meeting_id:this.id}}))}async invitePermissions(){return Q(await this.client.storage.meetingInvitePermissions({path:{token:(await this.detail.get()).shareToken}}))}async invite($){Q(await this.client.storage.meetingInvite({path:{token:(await this.detail.get()).shareToken},body:{email:$}}))}async inviteUsers($){Q(await this.client.storage.meetingInviteUsers({path:{token:(await this.detail.get()).shareToken},body:{userIds:$.map((O)=>O.id)}}))}async webUrl(){return`${this.client.webAppUrl}/app/meet/join/${encodeURIComponent((await this.detail.get()).shareToken)}`}}class v$ extends A{callId;constructor($,O,j,x){super($,j,x);this.callId=O}get path(){return{parent_type:"call",parent_id:this.callId,id:this.id}}async fetch(){return Q(await this.client.storage.entityMessageGetMessage({path:this.path}))}static byId($,O,j){return new v$($,O,j)}static from($,O,j){return new v$($,O,j.id,j)}content=this.field("content");createdAt=this.field("created_at");updatedAt=this.field("updated_at");call(){return Y$.byId(this.client,this.callId)}async author(){return M.byId(this.client,(await this.detail.get()).sender_id)}async reply($){let O=Q(await this.client.storage.entityMessageCreate({path:{parent_type:"call",parent_id:this.callId},body:{...$$($),thread_id:this.callId}}));return v$.from(this.client,this.callId,O)}async edit($){let{content:O,mentions:j}=$$($);return await this.mutate((x)=>x.storage.entityMessageEdit({path:this.path,body:{content:O,mentions:j}})),this}async delete(){await this.mutate(($)=>$.storage.entityMessageDeleteMessage({path:this.path}))}}class Y$ extends F${messageThreadById($){return B$.byId(this.client,{type:"call",entity:this},$)}timelinePage($){return E$(this.client,{type:"call",entity:this},(O)=>v$.from(this.client,this.id,O),$)}access=new o(this.client,"call",this);async meeting(){return I$.from(this.client,Q(await this.client.storage.meetingShare({path:{call_id:this.id}})))}async editTranscript($){await this.mutate((O)=>O.storage.editCallTranscript({path:{call_id:this.id},body:{assignments:$}}))}async toggleTeamShare(){return this.mutate(($)=>$.storage.toggleShareWithTeam({path:{call_id:this.id}}))}entityType="call";async fetch(){return Q(await this.client.storage.getCallRecord({path:{call_id:this.id}}))}static byId($,O){return new Y$($,O)}message($){return v$.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=j$({filters:{call_filters:{}},type:"call",make:($,O)=>new Y$($,O.call_id)})}class yx{client;constructor($){this.client=$}byId($){return Y$.byId(this.client,$)}search($,O){return Y$.search(this.client,$,O)}}class vx{client;constructor($){this.client=$}async list(){let{labels:$}=Q(await this.client.storage.listChannelLabels());return $}async create($,O=[]){return Q(await this.client.storage.createChannelLabel({body:{name:$,channelIds:O.map((j)=>j.id)}}))}async createSmartTag($,O){return Q(await this.client.storage.createChannelLabel({body:{name:$,rule:O}}))}async previewSmartTag($){return Q(await this.client.storage.previewSmartTag({body:$}))}async updateSmartTag($,O,j){return Q(await this.client.storage.renameChannelLabel({path:{label_id:$.id},body:{name:O,rule:j}}))}async rename($,O){return Q(await this.client.storage.renameChannelLabel({path:{label_id:$.id},body:{name:O}}))}async delete($){Q(await this.client.storage.deleteChannelLabel({path:{label_id:$.id}}))}async setLabel($,O){Q(await this.client.storage.setChannelLabel({path:{channel_id:$.id},body:{labelId:O?.id??null}}))}}class hx{client;async activity(){return Q(await this.client.storage.getActivity()).map(($)=>new ZO(this.client,f.byId(this.client,$.channel_id),$))}labels;constructor($){this.client=$;this.labels=new vx($)}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:$}=Q(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:j}=Q(await this.client.storage.getChannels()),x=$.toLowerCase();for(let S of j)if(S.name?.toLowerCase().includes(x))yield f.byId(this.client,S.id.toString())}else yield*f.search(this.client,$,O)}}class n extends S${async sharePermissions(){return Q(await this.client.storage.getProjectPermissionsV2({path:{id:this.id}}))}async accessLevel(){return Q(await this.client.storage.getProjectUserAccessLevel({path:{id:this.id}}))}access=new o(this.client,"project",this);entityType="project";propertyEntityType="PROJECT";async fetch(){let{data:$}=Q(await this.client.storage.getProjectHandler({path:{id:this.id}}));return $.projectMetadata}static byId($,O){return new n($,O)}static async create($,O){let{data:j}=Q(await $.storage.createProjectHandler({body:{name:O.name,projectParentId:O.parent?.id??null}}));return new n($,j.id,j)}name=this.field("name");parent=this.mappedField("parentId",($)=>$?n.byId(this.client,$):void 0);createdAt=this.field("createdAt");async items(){let{data:$}=Q(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=j$({filters:{project_filters:{}},type:"project",make:($,O)=>new n($,O.id)})}class hO{client;chat;id;message;constructor($,O,j,x){this.client=$;this.chat=O;this.id=j;this.message=x}static byId($,O,j,x){return new hO($,O,j,x)}async stop(){Q(await this.client.cognition.stopChatStream({body:{chat_id:this.chat.id,stream_id:this.id}}))}toJSON(){return{id:this.id,chatId:this.chat.id,messageId:this.message.id}}}class mO extends A{chat;constructor($,O,j){super($,j);this.chat=O}static byId($,O,j){return new mO($,O,j)}async fetch(){let $=Q(await this.client.cognition.getChat({path:{chat_id:this.chat.id}})).chat.messages.find((O)=>O.id===this.id);if(!$)throw new w(`Chat message ${this.id} is not yet available`);return $}content=this.field("content");role=this.field("role");async refresh(){this.detail.clear(),await this.detail.get()}toJSON(){return{...super.toJSON(),chatId:this.chat.id}}}class Z$ extends S${async send($){let{attachments:O,additionalInstructions:j,...x}=$,S=await this.mutate((Z)=>Z.cognition.sendChatMessage({body:{...x,chat_id:this.id,additional_instructions:j,attachments:O?.map((X)=>({entity_id:X.entity.id,entity_type:X.type}))}})),K=Z$.byId(this.client,S.chat_id);return hO.byId(this.client,K,S.stream_id,mO.byId(this.client,K,S.message_id))}access=new o(this.client,"chat",this);entityType="chat";propertyEntityType="CHAT";async fetch(){let{chat:$}=Q(await this.client.cognition.getChat({path:{chat_id:this.id}}));return $}static byId($,O){return new Z$($,O)}static async create($,O){let{id:j}=Q(await $.cognition.createChat({body:{name:O?.name??null,projectId:O?.project?.id??null}}));return new Z$($,j)}name=this.field("name");model=this.field("model");project=this.mappedField("projectId",($)=>$?n.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 Z$(this.client,$)}async restore(){await this.mutate(($)=>$.cognition.revertDeleteChat({path:{chat_id:this.id}}))}async history(){let{conversation:$}=Q(await this.client.cognition.getChatHistoryHandler({path:{chat_id:this.id}}));return $}webUrl(){return`${this.client.webAppUrl}/app/chat/${this.id}`}static search=j$({filters:{chat_filters:{}},type:"chat",make:($,O)=>new Z$($,O.chat_id)});toMention(){return{tag:l$("m-document-mention",{documentId:this.id,documentName:this.detail.peek()?.name??"",blockName:"chat",blockParams:{}}),mention:{entity_type:"chat",entity_id:this.id}}}}class mx{client;constructor($){this.client=$}byId($){return Z$.byId(this.client,$)}create($){return Z$.create(this.client,$)}search($,O){return Z$.search(this.client,$,O)}}class T$ extends A{async fetch(){let O=Q(await this.client.auth.getUserTeams()).find((j)=>j.id===this.id);if(!O)throw new w(`team ${this.id} not found`);return O}static byId($,O){return new T$($,O)}static async current($){let O=Q(await $.auth.getTeam());if(!O)throw new w("caller has no current team");return new T$($,O.team.id,O.team)}static async list($){return Q(await $.auth.getUserTeams()).map((j)=>new T$($,j.id,j))}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 $=Q(await this.client.auth.getTeam());if(!$||$.team.id!==this.id)throw new b("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 E6=8;class _$ extends A{parent;constructor($,O,j,x){super($,j,x);this.parent=O}get path(){return{parent_type:this.parent.type,parent_id:this.parent.id,id:this.id}}async fetch(){return Q(await this.client.storage.entityMessageGetMessage({path:this.path}))}static byId($,O,j){return new _$($,O,j)}static from($,O,j){return new _$($,O,j.id,j)}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 cO(this.client,this.parent,$,{threadId:await this.threadId()})}async edit($){let{content:O,mentions:j}=$$($);return await this.mutate((x)=>x.storage.entityMessageEdit({path:this.path,body:{content:O,mentions:j}})),this}async delete(){await this.mutate(($)=>$.storage.entityMessageDeleteMessage({path:this.path}))}}async function Yj($,O){let j={parent_type:O.type,parent_id:O.id},x=a(async(K)=>{let Z=Q(await $.storage.messageTimeline({path:j,query:{selection:JSON.stringify({limit:100,cursor:K})}}));return{items:Z.items,nextCursor:Z.next_cursor}}),S=[];for await(let K of x)S.push(K);return bO(S,E6,async(K)=>{let{state:Z,root:X,replies:G}=Q(await $.storage.entityMessageGetThread({path:{...j,id:K.id}}));return{thread:Z,comments:[X,...G].map((L)=>_$.from($,O,L))}})}async function cO($,O,j,x){let S=Q(await $.storage.entityMessageCreate({path:{parent_type:O.type,parent_id:O.id},body:{...$$(j),thread_id:x?.threadId??null}}));return _$.from($,O,S)}class w$ extends F${messageThreadById($){return B$.byId(this.client,{type:"crm_contact",entity:this},$)}timelinePage($){return E$(this.client,{type:"crm_contact",entity:this},(O)=>_$.from(this.client,{type:"crm_contact",id:this.id},O),$)}entityType="crm_contact";async fetch(){return Q(await this.client.storage.getContact({path:{contact_id:this.id}}))}static byId($,O){return new w$($,O)}static from($,O){return new w$($,O.id,O)}name=this.field("name");email=this.field("email");company=this.mappedField("companyId",($)=>q$.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 Yj(this.client,this.commentParent)}async comment($,O){return cO(this.client,this.commentParent,$,O)}commentById($){return _$.byId(this.client,this.commentParent,$)}}class q$ extends S${messageThreadById($){return B$.byId(this.client,{type:"crm_company",entity:this},$)}timelinePage($){return E$(this.client,{type:"crm_company",entity:this},(O)=>_$.from(this.client,{type:"crm_company",id:this.id},O),$)}entityType="crm_company";propertyEntityType="COMPANY";async fetch(){return Q(await this.client.storage.getCompany({path:{company_id:this.id}}))}static byId($,O){return new q$($,O)}static from($,O){return new q$($,O.id,O)}name=this.field("name");description=this.field("description");hidden=this.field("hidden");emailSync=this.field("emailSync");team=this.mappedField("teamId",($)=>T$.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 Q(await this.client.storage.listCompanyContacts({path:{company_id:this.id}})).map((O)=>w$.from(this.client,O))}static search=j$({filters:{crm_company_filters:{}},type:"company",includeCrm:!0,make:($,O)=>new q$($,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((j)=>j.storage.createCrmContact({path:{company_id:this.id},body:$}));return w$.from(this.client,O)}get commentParent(){return{type:"crm_company",id:this.id}}async comments(){return Yj(this.client,this.commentParent)}async comment($,O){return cO(this.client,this.commentParent,$,O)}commentById($){return _$.byId(this.client,this.commentParent,$)}}class a$ extends A{tableDetail=new V$(async()=>Q(await this.client.storage.getCrmPipelineTable({path:{id:this.id}})));static byId($,O){return new a$($,O)}static from($,O){return new a$($,O.id,O)}async fetch(){return Q(await this.client.storage.getCrmPipeline({path:{id:this.id}}))}name=this.field("name");recordType=this.field("recordType");accessLevel=this.field("grant");sharing=this.field("sharing");owner=this.mappedField("userId",($)=>M.byId(this.client,$));team=this.mappedField("teamId",($)=>T$.byId(this.client,$));async rename($){await this.mutate((O)=>O.storage.renameCrmPipeline({path:{id:this.id},body:{name:$}}))}async setSharing($){if($===void 0)throw Error("Sharing is required");await this.mutate((O)=>O.storage.shareCrmPipeline({path:{id:this.id},body:{sharing:$}}))}async setTrashed($){await this.mutate((O)=>O.storage.trashCrmPipeline({path:{id:this.id},body:{trashed:$}}))}async sharePermissions(){return Q(await this.client.storage.getCrmPipelinePermissions({path:{id:this.id}}))}async updateSharePermissions($){return this.mutate((O)=>O.storage.updateCrmPipelinePermissions({path:{id:this.id},body:r$($)}))}async table(){return Qj.from(this.client,this,await this.tableRecord())}tableRecord(){return this.tableDetail.get()}rows(){return a(async($)=>{let O=Q(await this.client.storage.getCrmPipelineRows({path:{id:this.id},query:{after:$}}));return{items:O.rows.map((j)=>XO.from(this.client,this,j)),nextCursor:O.next}})}queryRows($={}){if($.rows?.some((O)=>O.pipeline.id!==this.id))throw Error("Rows belong to another pipeline");return a(async(O)=>{let j=Q(await this.client.storage.queryCrmPipelineRows({path:{id:this.id},body:{after:O,query:$.query,rowIds:$.rows?.map((x)=>x.id)}}));return{items:j.rows.map((x)=>XO.from(this.client,this,x)),nextCursor:j.next}})}async applyOps($,O){if(O?.baseVersions?.some((S)=>S.table.pipeline.id!==this.id))throw Error("Table belongs to another pipeline");let j={ops:$,baseVersions:O?.baseVersions?Object.fromEntries(O.baseVersions.map((S)=>[S.table.id,S.version])):void 0},x=await this.mutate((S)=>S.storage.applyCrmPipelineOps({path:{id:this.id},body:j}));return this.tableDetail.clear(),x}}class Qj extends A{pipeline;toJSON(){return{...super.toJSON(),pipelineId:this.pipeline.id}}constructor($,O,j){super($,j.table.id,j);this.pipeline=O}static from($,O,j){return new Qj($,O,j)}fetch(){return this.pipeline.tableRecord()}async columns(){return(await this.pipeline.tableRecord()).columns.map(($)=>Jj.from(this.client,this,$))}async version(){return(await this.pipeline.tableRecord()).table.version}rowById($){return XO.byId(this.client,this.pipeline,$)}rows(){return this.pipeline.rows()}}class XO extends A{pipeline;toJSON(){return{...super.toJSON(),pipelineId:this.pipeline.id}}constructor($,O,j,x){super($,j,x);this.pipeline=O}static byId($,O,j){return new XO($,O,j)}static from($,O,j){return new XO($,O,j.rowId,j)}async fetch(){for await(let $ of this.pipeline.queryRows({rows:[this]}))if($.id===this.id)return $.detail.get();throw new w(`Pipeline row ${this.id} is unavailable`)}cells=this.field("cells");async refresh(){this.detail.clear(),await this.detail.get()}}class Jj extends A{table;toJSON(){return{...super.toJSON(),pipelineId:this.table.pipeline.id,tableId:this.table.id}}constructor($,O,j){super($,j.column.id,j);this.table=O}static from($,O,j){return new Jj($,O,j)}async fetch(){let $=(await this.table.pipeline.tableRecord()).columns.find((O)=>O.column.id===this.id);if(!$)throw new w(`Pipeline column ${this.id} is unavailable`);return $}async writable(){return(await this.fetch()).writable}async name(){return(await this.fetch()).column.display_name??(await this.fetch()).definition.definition.display_name}}class cx{client;constructor($){this.client=$}byId($){return a$.byId(this.client,$)}async list(){return Q(await this.client.storage.listCrmPipelines()).map(($)=>a$.from(this.client,$))}async create($){return a$.from(this.client,Q(await this.client.storage.createCrmPipeline({body:$})))}}class ux{client;pipelines;constructor($){this.client=$;this.pipelines=new cx($)}companyById($){return q$.byId(this.client,$)}contactById($){return w$.byId(this.client,$)}async contactByEmail($){let{contact:O}=Q(await this.client.storage.getContactByEmail({query:{email:$}}));return O?w$.from(this.client,O):void 0}async searchContacts($,O={}){let{contacts:j}=Q(await this.client.storage.searchContacts({query:{query:$,limit:O.limit}}));return j.map((x)=>w$.from(this.client,x))}async createCompany($){return q$.from(this.client,Q(await this.client.storage.createCrmCompany({body:$})))}async settings(){return Q(await this.client.storage.getCrmTeamSettings())}async updateSettings($){return Q(await this.client.storage.putCrmTeamSettings({body:$}))}async setStages($){return Q(await this.client.storage.putCrmTeamStages({body:$}))}async resetStages(){Q(await this.client.storage.resetCrmTeamStages())}searchCompanies($){return q$.search(this.client,$)}}var G$=Symbol.for("@ts-pattern/matcher"),P1=Symbol.for("@ts-pattern/isVariadic");var dx=($)=>Boolean($&&typeof $=="object"),Vj=($)=>$&&!!$[G$],s=($,O,j)=>{if(Vj($)){let x=$[G$](),{matched:S,selections:K}=x.match(O);return S&&K&&Object.keys(K).forEach((Z)=>j(Z,K[Z])),S}if(dx($)){if(!dx(O))return!1;if(Array.isArray($)){if(!Array.isArray(O))return!1;let x=[],S=[],K=[];for(let Z of $.keys()){let X=$[Z];Vj(X)&&X[P1]?K.push(X):K.length?S.push(X):x.push(X)}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<x.length+S.length)return!1;let Z=O.slice(0,x.length),X=S.length===0?[]:O.slice(-S.length),G=O.slice(x.length,S.length===0?1/0:-S.length);return x.every((L,Y)=>s(L,Z[Y],j))&&S.every((L,Y)=>s(L,X[Y],j))&&(K.length===0||s(K[0],G,j))}return $.length===O.length&&$.every((Z,X)=>s(Z,O[X],j))}return Reflect.ownKeys($).every((x)=>{let S=$[x];return((x in O)||Vj(K=S)&&K[G$]().matcherType==="optional")&&s(S,O[x],j);var K})}return Object.is(O,$)},X$=($)=>{var O,j,x;return dx($)?Vj($)?(O=(j=(x=$[G$]()).getSelectionKeys)==null?void 0:j.call(x))!=null?O:[]:Array.isArray($)?uO($,X$):uO(Object.values($),X$):[]},uO=($,O)=>$.reduce((j,x)=>j.concat(O(x)),[]);function w6(...$){if($.length===1){let[O]=$;return(j)=>s(O,j,()=>{})}if($.length===2){let[O,j]=$;return s(O,j,()=>{})}throw Error(`isMatching wasn't given the right number of arguments: expected 1 or 2, received ${$.length}.`)}function t($){return Object.assign($,{optional:()=>px($),and:(O)=>u($,O),or:(O)=>F1($,O),select:(O)=>O===void 0?dO($):dO(O,$)})}function lx($){return Object.assign(((O)=>Object.assign(O,{[Symbol.iterator](){let j=0,x=[{value:Object.assign(O,{[P1]:!0}),done:!1},{done:!0,value:void 0}];return{next:()=>{var S;return(S=x[j++])!=null?S:x.at(-1)}}}}))($),{optional:()=>lx(px($)),select:(O)=>lx(O===void 0?dO($):dO(O,$))})}function px($){return t({[G$]:()=>({match:(O)=>{let j={},x=(S,K)=>{j[S]=K};return O===void 0?(X$($).forEach((S)=>x(S,void 0)),{matched:!0,selections:j}):{matched:s($,O,x),selections:j}},getSelectionKeys:()=>X$($),matcherType:"optional"})})}var q6=($,O)=>{for(let j of $)if(!O(j))return!1;return!0},f6=($,O)=>{for(let[j,x]of $.entries())if(!O(x,j))return!1;return!0},b6=($,O)=>{let j=Reflect.ownKeys($);for(let x of j)if(!O(x,$[x]))return!1;return!0};function u(...$){return t({[G$]:()=>({match:(O)=>{let j={},x=(S,K)=>{j[S]=K};return{matched:$.every((S)=>s(S,O,x)),selections:j}},getSelectionKeys:()=>uO($,X$),matcherType:"and"})})}function F1(...$){return t({[G$]:()=>({match:(O)=>{let j={},x=(S,K)=>{j[S]=K};return uO($,X$).forEach((S)=>x(S,void 0)),{matched:$.some((S)=>s(S,O,x)),selections:j}},getSelectionKeys:()=>uO($,X$),matcherType:"or"})})}function m($){return{[G$]:()=>({match:(O)=>({matched:Boolean($(O))})})}}function dO(...$){let O=typeof $[0]=="string"?$[0]:void 0,j=$.length===2?$[1]:typeof $[0]=="string"?void 0:$[0];return t({[G$]:()=>({match:(x)=>{let S={[O!=null?O:"@ts-pattern/anonymous-select-key"]:x};return{matched:j===void 0||s(j,x,(K,Z)=>{S[K]=Z}),selections:S}},getSelectionKeys:()=>[O!=null?O:"@ts-pattern/anonymous-select-key"].concat(j===void 0?[]:X$(j))})})}function E1($){return!0}function f$($){return typeof $=="number"}function i$($){return typeof $=="string"}function n$($){return typeof $=="bigint"}var w1=t(m(E1)),k6=t(m(E1)),g6=w1,s$=($)=>Object.assign(t($),{startsWith:(O)=>{return s$(u($,(j=O,m((x)=>i$(x)&&x.startsWith(j)))));var j},endsWith:(O)=>{return s$(u($,(j=O,m((x)=>i$(x)&&x.endsWith(j)))));var j},minLength:(O)=>s$(u($,((j)=>m((x)=>i$(x)&&x.length>=j))(O))),length:(O)=>s$(u($,((j)=>m((x)=>i$(x)&&x.length===j))(O))),maxLength:(O)=>s$(u($,((j)=>m((x)=>i$(x)&&x.length<=j))(O))),includes:(O)=>{return s$(u($,(j=O,m((x)=>i$(x)&&x.includes(j)))));var j},regex:(O)=>{return s$(u($,(j=O,m((x)=>i$(x)&&Boolean(x.match(j))))));var j}}),A1=s$(m(i$)),b$=($)=>Object.assign(t($),{between:(O,j)=>b$(u($,((x,S)=>m((K)=>f$(K)&&x<=K&&S>=K))(O,j))),lt:(O)=>b$(u($,((j)=>m((x)=>f$(x)&&x<j))(O))),gt:(O)=>b$(u($,((j)=>m((x)=>f$(x)&&x>j))(O))),lte:(O)=>b$(u($,((j)=>m((x)=>f$(x)&&x<=j))(O))),gte:(O)=>b$(u($,((j)=>m((x)=>f$(x)&&x>=j))(O))),int:()=>b$(u($,m((O)=>f$(O)&&Number.isInteger(O)))),finite:()=>b$(u($,m((O)=>f$(O)&&Number.isFinite(O)))),positive:()=>b$(u($,m((O)=>f$(O)&&O>0))),negative:()=>b$(u($,m((O)=>f$(O)&&O<0)))}),y6=b$(m(f$)),t$=($)=>Object.assign(t($),{between:(O,j)=>t$(u($,((x,S)=>m((K)=>n$(K)&&x<=K&&S>=K))(O,j))),lt:(O)=>t$(u($,((j)=>m((x)=>n$(x)&&x<j))(O))),gt:(O)=>t$(u($,((j)=>m((x)=>n$(x)&&x>j))(O))),lte:(O)=>t$(u($,((j)=>m((x)=>n$(x)&&x<=j))(O))),gte:(O)=>t$(u($,((j)=>m((x)=>n$(x)&&x>=j))(O))),positive:()=>t$(u($,m((O)=>n$(O)&&O>0))),negative:()=>t$(u($,m((O)=>n$(O)&&O<0)))}),v6=t$(m(n$)),h6=t(m(function($){return typeof $=="boolean"})),m6=t(m(function($){return typeof $=="symbol"})),c6=t(m(function($){return $==null})),u6=t(m(function($){return $!=null})),x$={__proto__:null,matcher:G$,optional:px,array:function(...$){return lx({[G$]:()=>({match:(O)=>{if(!Array.isArray(O))return{matched:!1};if($.length===0)return{matched:!0};let j=$[0],x={};if(O.length===0)return X$(j).forEach((K)=>{x[K]=[]}),{matched:!0,selections:x};let S=(K,Z)=>{x[K]=(x[K]||[]).concat([Z])};return{matched:O.every((K)=>s(j,K,S)),selections:x}},getSelectionKeys:()=>$.length===0?[]:X$($[0])})})},set:function(...$){return t({[G$]:()=>({match:(O)=>{if(!(O instanceof Set))return{matched:!1};let j={};if(O.size===0)return{matched:!0,selections:j};if($.length===0)return{matched:!0};let x=(K,Z)=>{j[K]=(j[K]||[]).concat([Z])},S=$[0];return{matched:q6(O,(K)=>s(S,K,x)),selections:j}},getSelectionKeys:()=>$.length===0?[]:X$($[0])})})},map:function(...$){return t({[G$]:()=>({match:(O)=>{if(!(O instanceof Map))return{matched:!1};let j={};if(O.size===0)return{matched:!0,selections:j};let x=(X,G)=>{j[X]=(j[X]||[]).concat([G])};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,Z]=$;return{matched:f6(O,(X,G)=>{let L=s(K,G,x),Y=s(Z,X,x);return L&&Y}),selections:j}},getSelectionKeys:()=>$.length===0?[]:[...X$($[0]),...X$($[1])]})})},record:function(...$){return t({[G$]:()=>({match:(O)=>{if(O===null||typeof O!="object"||Array.isArray(O))return{matched:!1};var j;if($.length===0)throw Error(`\`P.record\` wasn't given enough arguments. Expected (value) or (key, value), received ${(j=$[0])==null?void 0:j.toString()}`);let x={},S=(X,G)=>{x[X]=(x[X]||[]).concat([G])},[K,Z]=$.length===1?[A1,$[0]]:$;return{matched:b6(O,(X,G)=>{let L=typeof X!="string"||Number.isNaN(Number(X))?null:Number(X),Y=L!==null&&s(K,L,S),J=s(K,X,S),T=s(Z,G,S);return(J||Y)&&T}),selections:x}},getSelectionKeys:()=>$.length===0?[]:[...X$($[0]),...X$($[1])]})})},intersection:u,union:F1,not:function($){return t({[G$]:()=>({match:(O)=>({matched:!s($,O,()=>{})}),getSelectionKeys:()=>[],matcherType:"not"})})},when:m,select:dO,any:w1,unknown:k6,_:g6,string:A1,number:y6,bigint:v6,boolean:h6,symbol:m6,nullish:c6,nonNullable:u6,instanceOf:function($){return t(m(function(O){return(j)=>j instanceof O}($)))},shape:function($){return t(m(w6($)))}};class q1 extends Error{constructor($){let O;try{O=JSON.stringify($)}catch(j){O=$}super(`Pattern matching error: no pattern matches value ${O}`),this.input=void 0,this.input=$}}var rx={matched:!1,value:void 0};function c($){return new Wj($,rx)}class Wj{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],j=[$[0]],x;$.length===3&&typeof $[1]=="function"?x=$[1]:$.length>2&&j.push(...$.slice(1,$.length-1));let S=!1,K={},Z=(G,L)=>{S=!0,K[G]=L},X=!j.some((G)=>s(G,this.input,Z))||x&&!Boolean(x(this.input))?rx:{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 Wj(this.input,X)}when($,O){if(this.state.matched)return this;let j=Boolean($(this.input));return new Wj(this.input,j?{matched:!0,value:O(this.input,this.input)}:rx)}otherwise($){return this.state.matched?this.state.value:$(this.input)}exhaustive($=d6){return this.state.matched?this.state.value:$(this.input)}run(){return this.exhaustive()}returnType(){return this}narrow(){return this}}function d6($){throw new q1($)}var ax,l6=new Uint8Array(16);function Bj(){if(!ax){if(typeof crypto>"u"||!crypto.getRandomValues)throw Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");ax=crypto.getRandomValues.bind(crypto)}return ax(l6)}var O$=[];for(let $=0;$<256;++$)O$.push(($+256).toString(16).slice(1));function f1($,O=0){return(O$[$[O+0]]+O$[$[O+1]]+O$[$[O+2]]+O$[$[O+3]]+"-"+O$[$[O+4]]+O$[$[O+5]]+"-"+O$[$[O+6]]+O$[$[O+7]]+"-"+O$[$[O+8]]+O$[$[O+9]]+"-"+O$[$[O+10]]+O$[$[O+11]]+O$[$[O+12]]+O$[$[O+13]]+O$[$[O+14]]+O$[$[O+15]]).toLowerCase()}var ix={};function r6($,O,j){let x;if($)x=b1($.random??$.rng?.()??Bj(),$.msecs,$.seq,O,j);else{let S=Date.now(),K=Bj();p6(ix,S,K),x=b1(K,ix.msecs,ix.seq,O,j)}return O??f1(x)}function p6($,O,j){if($.msecs??=-1/0,$.seq??=0,O>$.msecs)$.seq=j[6]<<23|j[7]<<16|j[8]<<8|j[9],$.msecs=O;else if($.seq=$.seq+1|0,$.seq===0)$.msecs++;return $}function b1($,O,j,x,S=0){if($.length<16)throw Error("Random bytes length must be >= 16");if(!x)x=new Uint8Array(16),S=0;else if(S<0||S+16>x.length)throw RangeError(`UUID byte range ${S}:${S+15} is out of buffer bounds`);return O??=Date.now(),j??=$[6]*127<<24|$[7]<<16|$[8]<<8|$[9],x[S++]=O/1099511627776&255,x[S++]=O/4294967296&255,x[S++]=O/16777216&255,x[S++]=O/65536&255,x[S++]=O/256&255,x[S++]=O&255,x[S++]=112|j>>>28&15,x[S++]=j>>>20&255,x[S++]=128|j>>>14&63,x[S++]=j>>>6&255,x[S++]=j<<2&255|$[10]&3,x[S++]=$[11],x[S++]=$[12],x[S++]=$[13],x[S++]=$[14],x[S++]=$[15],x}var h$=r6;class M${table;id;constructor($,O){this.table=$;this.id=O}static byId($,O){return new M$($,O)}async detail(){let{columns:$}=await this.table.detail(),O=$.find((j)=>j.column.id===this.id);if(!O)throw new w(`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 A${table;id;constructor($,O){this.table=$;this.id=O}static byId($,O){return new A$($,O)}history(){return this.table.database.rowHistory(this)}toJSON(){return{id:this.id,tableId:this.table.id}}}class Lj{table;id;constructor($,O){this.table=$;this.id=O}static byId($,O){return new Lj($,O)}async detail(){let{views:$}=await this.table.detail(),O=$.find((j)=>j.id===this.id);if(!O)throw new w(`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 Q${database;id;constructor($,O){this.database=$;this.id=O}static byId($,O){return new Q$($,O)}async detail(){let{tables:$}=await this.database.schema(),O=$.find((j)=>j.table.id===this.id);if(!O)throw new w(`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)=>M$.byId(this,O.column.id))}addColumn($){return this.database.addColumn(this,$)}async reorderColumns($){return await this.database.reorderColumns(this,$),this}row($){return A$.byId(this,$)}async views(){let{views:$}=await this.detail();return $.map((O)=>Lj.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}}}async function Nj($,O,j,x={}){let S=Q(await $.storage.queryDatabases({body:{sql:j,databaseId:x.database?.id,baseVersions:Object.fromEntries((x.baseVersions??[]).map(({table:Y,version:J})=>[Y.id,J]))}})),K=new Map;for(let Y of[x.database,...(x.baseVersions??[]).map(({table:J})=>J.database)]){if(!Y)continue;let J=K.get(Y.id);if(J)J.add(Y);else K.set(Y.id,new Set([Y]))}let Z=(Y)=>{let J=K.get(Y)?.values().next().value;if(J)return J;let T=O($,Y);return K.set(Y,new Set([T])),T},X=(Y)=>{let J=S.tableDatabases[Y];if(!J)throw Error(`SQL response is missing the owner of table ${Y}`);return Q$.byId(Z(J),Y)},G=new Set(Object.keys(S.newVersions).map((Y)=>X(Y).database.id));if(S.statement.kind==="schema")G.add(S.statement.databaseId);for(let Y of G)for(let J of K.get(Y)??[])J.invalidateSchema();let L=c(S.statement).with({kind:"select"},(Y)=>Y).with({kind:"schema"},({databaseId:Y,summary:J})=>({kind:"schema",database:Z(Y),summary:J})).with({kind:"insert"},{kind:"update"},{kind:"delete"},({kind:Y,tableId:J,tableName:T})=>({kind:Y,table:X(J),tableName:T})).with({kind:"alterColumnType"},({tableId:Y,tableName:J,columnId:T,columnName:z,to:W})=>{let V=X(Y);return{kind:"alterColumnType",table:V,tableName:J,column:M$.byId(V,T),columnName:z,to:W}}).exhaustive();return{result:S.result?a6(S.result,X,S.tableDatabases):void 0,changesApplied:S.changesApplied,insertedRows:L.kind==="insert"?S.insertedRowIds.map((Y)=>A$.byId(L.table,Y)):[],newVersions:Object.entries(S.newVersions).map(([Y,J])=>({table:X(Y),version:J})),readVersions:Object.entries(S.readVersions).map(([Y,J])=>({table:X(Y),version:J})),truncatedTables:S.truncatedTables,statement:L}}function a6($,O,j){let x=$.sourceTable&&j[$.sourceTable]?O($.sourceTable):void 0;return{columns:$.columns.map(({relatedTable:S,...K})=>({...K,relatedTable:S&&j[S]?O(S):void 0})),rows:$.rows,sourceTable:x,rowHandles:x?$.rowIds.map((S)=>A$.byId(x,S)):[]}}class Uj{table;id;createdBy;record;constructor($,O,j,x){this.table=$;this.id=O;this.createdBy=j;this.record=x}static fromRecord($,O,j){return new Uj($,j.id,O,j)}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 tx extends SO{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 zj($){return c($).with({type:"relation"},({table:O})=>({type:"relation",database:O.database.id,table:O.id})).with({type:x$.not("relation")},(O)=>O).exhaustive()}var i6={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 n6($){return c($).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})=>i6[O]).with({type:"relation"},()=>"Relation").exhaustive(()=>"Column")}function nx($){return $.map((O)=>({id:h$(),label:O}))}function k1($,O,j){return $?.kind===O&&"change"in $&&$.change.kind===j}function sx($){return c($).with({kind:"reorder_tables"},({kind:O})=>O).with({kind:x$.union("table","column","rows","view")},({kind:O,change:j})=>`${O}.${j.kind}`).exhaustive(()=>"unknown")}function m$($,O,j){let[x]=$;if($.length!==1||!k1(x,O,j))throw new b(`expected one ${O}.${j} result, got ${$.map(sx).join(", ")||"none"}`);return x}class J$ extends A{access=new o(this.client,"database",this);async fetch(){return Q(await this.client.storage.getDatabase({path:{id:this.id}}))}assertOwns($,O){if(O.id!==this.id)throw new b(`${$} does not belong to database ${this.id}`)}static byId($,O){return new J$($,O)}static async create($,O){let j=Q(await $.storage.createDatabase({body:{name:O.name}}));return new J$($,j.id)}static async list($){return Q(await $.storage.listDatabases()).map((j)=>new J$($,j.database.id))}query($,O){return Nj(this.client,J$.byId,$,{...O,database:this})}invalidateSchema(){this.detail.clear()}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)=>Q$.byId(this,O.table.id)));async table($){let{tables:O}=await this.schema(),j=O.find((x)=>x.table.name===$);return j?Q$.byId(this,j.table.id):void 0}async createTable($){let{table:O}=m$(await this.applyOps([{kind:"table",table:h$(),change:{kind:"create",name:$.name}}]),"table","created");return Q$.byId(this,O)}async applyOps($,O={}){let j={ops:$};if(O.baseVersions!==void 0){for(let{table:S}of O.baseVersions)this.assertOwns(`table ${S.id}`,S.database);j.baseVersions=Object.fromEntries(O.baseVersions.map(({table:S,version:K})=>[S.id,K]))}let{results:x}=await this.mutate(async(S)=>{let K=await S.storage.applyDatabaseOps({path:{id:this.id},body:j});if(K.error!==void 0&&"op"in K.error)throw new tx(K.response?.status??0,K.error);return K});return x}async reorderTables($){for(let x of $)this.assertOwns(`table ${x.id}`,x.database);let O=await this.applyOps([{kind:"reorder_tables",order:$.map((x)=>x.id)}]),[j]=O;if(O.length!==1||j?.kind!=="reorder_tables")throw new b(`expected one reorder_tables result, got ${O.map(sx).join(", ")||"none"}`);return j.tables.map(({table:x})=>Q$.byId(this,x))}async deleteTable($){this.assertOwns(`table ${$.id}`,$.database),m$(await this.applyOps([{kind:"table",table:$.id,change:{kind:"delete"}}]),"table","deleted")}async columnCasts($){return this.assertOwns(`column ${$.id}`,$.table.database),Q(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}=Q(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}=Q(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((j)=>j.storage.importDatabaseTable({path:{id:this.id},body:$}));return Q$.byId(this,O.id)}webhookOf($){return Uj.fromRecord(Q$.byId(this,$.tableId),M.byId(this.client,$.createdBy),$)}async webhooks(){let{webhooks:$}=Q(await this.client.storage.listDatabaseWebhooks({path:{id:this.id}}));return $.map((O)=>this.webhookOf(O))}async createWebhook($){this.assertOwns("table",$.database);let O=Q(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),Q(await this.client.storage.deleteDatabaseWebhook({path:{id:this.id,webhook_id:$.id}}))}async sharePermissions(){return Q(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 j=await $.table.version();return m$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"change_type",to:zj(O.to)}}],{baseVersions:[{table:$.table,version:j}]}),"column","type_changed")}async columnConversion($,O){return this.assertOwns(`column ${$.id}`,$.table.database),Q(await this.client.storage.convertDatabaseColumn({path:{id:this.id,table_id:$.table.id,column_id:$.id},body:{to:zj(O)}}))}async convertColumnIntoNewColumn($,O){let j=await this.columnConversion($,O.to),x=O.name??`${await $.name()} (${n6(O.to)})`,S=h$(),K=[{kind:"column",table:$.table.id,column:S,change:{kind:"create",definition:{source:"new",name:x,type:zj(O.to),options:nx(j.options)},after:$.id}}];if(j.cells.length>0)K.push({kind:"rows",table:$.table.id,change:{kind:"update",changes:{kind:"per_row",rows:j.cells.map(({row:X,value:G})=>({row:X,cells:[{column:S,value:G}]}))}}});let[Z]=await this.applyOps(K,{baseVersions:[{table:$.table,version:j.tableVersion}]});if(!k1(Z,"column","created"))throw new b(`expected a column.created result, got ${Z?sx(Z):"none"}`);return M$.byId($.table,Z.column)}async deleteColumn($){this.assertOwns(`column ${$.id}`,$.table.database);let O=await $.table.version(),{tableVersion:j}=m$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"delete"}}],{baseVersions:[{table:$.table,version:O}]}),"column","deleted");return j}async reorderColumns($,O){this.assertOwns(`table ${$.id}`,$.database);for(let S of O)if(S.table.id!==$.id)throw new b(`column ${S.id} does not belong to table ${$.id}`);let j=await $.version(),{tableVersion:x}=m$(await this.applyOps([{kind:"table",table:$.id,change:{kind:"reorder_columns",order:O.map((S)=>S.id)}}],{baseVersions:[{table:$,version:j}]}),"table","columns_reordered");if(x===void 0)throw new b(`table ${$.id} reordered its columns without a version`);return x}async renameTable($,O){this.assertOwns(`table ${$.id}`,$.database);let j=await $.name(),{tableVersion:x}=m$(await this.applyOps([{kind:"table",table:$.id,change:{kind:"rename",name:O,previousName:j}}]),"table","renamed");if(x===void 0)throw new b(`table ${$.id} was renamed without a version`);return x}async renameColumn($,O){this.assertOwns(`column ${$.id}`,$.table.database);let j=await $.name(),{tableVersion:x}=m$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"rename",name:O,previousName:j}}]),"column","renamed");return x}async inferColumnType($,O){return this.assertOwns(`column ${$.id}`,$.table.database),this.mutate((j)=>j.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 b(`column ${O.after.id} does not belong to table ${$.id}`);let j="property"in O?{source:"existing",property:O.property.id}:{source:"new",name:O.name,type:zj(O.type),...O.options!==void 0?{options:nx(O.options)}:{},...O.inferType!==void 0?{inferType:O.inferType}:{}},{column:x}=m$(await this.applyOps([{kind:"column",table:$.id,column:h$(),change:{kind:"create",definition:j,...O.after!==void 0?{after:O.after.id}:{}}}]),"column","created");return M$.byId($,x)}async addColumnOptions($,O){return this.assertOwns(`column ${$.id}`,$.table.database),m$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"add_options",options:nx(O)}}]),"column","options_added")}}class ex{client;constructor($){this.client=$}query($,O){return Nj(this.client,J$.byId,$,O)}byId($){return J$.byId(this.client,$)}create($){return J$.create(this.client,$)}list(){return J$.list(this.client)}}class GO extends A{document;toJSON(){return{...super.toJSON(),documentId:this.document.id}}constructor($,O,j,x){super($,j,x);this.document=O}static byId($,O,j){return new GO($,O,j)}static from($,O,j){return new GO($,O,j.uuid,j)}async fetch(){let $=Q(await this.client.storage.getDocumentAnchors({path:{document_id:this.document.id}})).data.find((O)=>O.uuid===this.id);if(!$)throw new w(`Annotation ${this.id} is unavailable`);return $}kind=this.field("anchorType");page=this.field("page");async edit($){if(await this.kind()!=="placeable")throw Error("Only placeable comment annotations can be edited");await this.mutate((O)=>O.storage.editAnchor({body:{...$,uuid:this.id,anchorType:"free-comment",fileType:"pdf"}}))}async delete(){if(await this.kind()!=="highlight")throw Error("Only standalone highlights can be deleted with this endpoint");await this.mutate(($)=>$.storage.deleteAnchor({body:{uuid:this.id,anchorType:"highlight",fileType:"pdf"}}))}}class c$ extends A{documentId;constructor($,O,j,x){super($,j,x);this.documentId=O}get path(){return{parent_type:"document",parent_id:this.documentId,id:this.id}}async fetch(){return Q(await this.client.storage.entityMessageGetMessage({path:this.path}))}static byId($,O,j){return new c$($,O,j)}static from($,O,j){return new c$($,O,j.id,j)}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 q.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:j}=$$($);return await this.mutate((x)=>x.storage.entityMessageEdit({path:this.path,body:{content:O,mentions:j}})),this}async delete(){await this.mutate(($)=>$.storage.entityMessageDeleteMessage({path:this.path}))}}class lO{client;document;id;detail;constructor($,O,j){this.client=$;this.document=O;this.id=j;this.detail=new V$(async()=>Q(await this.client.storage.getDocumentVersion({path:{document_id:O.id,document_version_id:j}})).data)}static byId($,O,j){return new lO($,O,j)}read(){return this.detail.get()}toJSON(){return{id:this.id,documentId:this.document.id}}}var s6=8;class q extends S${async anchors(){return Q(await this.client.storage.getDocumentAnchors({path:{document_id:this.id}})).data.map(($)=>GO.from(this.client,this,$))}async createHighlight($){return GO.from(this.client,this,Q(await this.client.storage.createAnchor({path:{document_id:this.id},body:{...$,fileType:"pdf",anchorType:"highlight"}})))}version($){return lO.byId(this.client,this,$)}async sharePermissions(){return Q(await this.client.storage.getDocumentPermissionsV2({path:{document_id:this.id}})).documentPermissions}async permissionsToken(){return Q(await this.client.storage.getDocumentPermissionsToken({path:{document_id:this.id}})).token}async prepareSave($){return Q(await this.client.storage.presaveDocumentHandler({path:{document_id:this.id},body:{newBom:$}})).data}async save($){return(await this.mutate((O)=>O.storage.saveDocumentHandler({path:{document_id:this.id},body:$}))).data}async simpleSave(){return(await this.mutate(($)=>$.storage.simpleSave({path:{document_id:this.id}}))).data}messageThreadById($){return B$.byId(this.client,{type:"document",entity:this},$)}timelinePage($){return E$(this.client,{type:"document",entity:this},(O)=>c$.from(this.client,this.id,O),$)}access=new o(this.client,"document",this);async fetch(){let{data:$}=Q(await this.client.storage.getDocument({path:{document_id:this.id}}));return $.documentMetadata}static byId($,O){return new q($,O)}static async create($,O){let{documentId:j}=Q(await $.storage.createMarkdownHandler({body:{documentName:O.name,markdown:O.markdown??null,projectId:O.project?.id??null}}));return new q($,j)}static async createSnippet($,O){let{documentId:j}=Q(await $.storage.createSnippetHandler({body:{snippetName:O.name,markdown:O.markdown??null,projectId:O.project?.id??null}}));return new q($,j)}static async createSkill($,O){let{documentId:j}=Q(await $.storage.createSkillHandler({body:{skillName:O.name,markdown:O.markdown??null,projectId:O.project?.id??null}}));return new q($,j)}static recent($,O){let j=O?.pageSize??50;return a(async(x)=>{let S=Q(await $.storage.getUserDocumentsHandler({query:{limit:j,offset:x?Number(x):0,...O?.fileType!==void 0?{file_type:O.fileType}:{}}})),K=S.data?.next_offset;return{items:(S.data?.documents??[]).map((Z)=>new q($,Z.documentId)),nextCursor:K!=null?String(K):null}})}static async recentlyDeleted($){let{data:O}=Q(await $.storage.recentlyDeleted({}));return O.items.filter((j)=>j.type==="document").map((j)=>new q($,j.id))}entityType="document";propertyEntityType="DOCUMENT";name=this.field("documentName");fileType=this.field("fileType");project=this.mappedField("projectId",($)=>$?n.byId(this.client,$):void 0);owner=this.mappedField("owner",($)=>M.byId(this.client,$));branchedFrom=this.mappedField("branchedFromId",($)=>$?q.byId(this.client,$):void 0);createdAt=this.field("createdAt");updatedAt=this.field("updatedAt");deletedAt=this.field("deletedAt");async content(){let{text:$}=Q(await this.client.storage.getDocumentTextContent({path:{document_id:this.id}}));if($!==null)return $;let{presigned_url:O}=Q(await this.client.storage.exportDocument({path:{document_id:this.id}})),j=await fetch(O);if(!j.ok)throw new SO(j.status,{message:"failed to download document content"});return j.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}=Q(await this.client.storage.copyDocument({path:{document_id:this.id},query:$.versionId!==void 0?{version_id:$.versionId}:void 0,body:{documentName:$.name}}));return new q(this.client,O.documentMetadata.documentId)}async comments(){let $={parent_type:"document",parent_id:this.id},O=a(async(x)=>{let S=Q(await this.client.storage.messageTimeline({path:$,query:{selection:JSON.stringify({limit:100,cursor:x})}}));return{items:S.items,nextCursor:S.next_cursor}}),j=[];for await(let x of O)j.push(x);return bO(j,s6,async(x)=>{let{state:S,root:K,replies:Z}=Q(await this.client.storage.entityMessageGetThread({path:{...$,id:x.id}}));return{thread:S,comments:[K,...Z].map((X)=>c$.from(this.client,this.id,X))}})}async comment($,O){let j=await this.mutate((x)=>x.storage.entityMessageCreate({path:{parent_type:"document",parent_id:this.id},body:{...$$($),thread_id:O?.threadId??null}}));return c$.from(this.client,this.id,j)}async shortId(){return Q(await this.client.storage.getDocumentShortId({path:{document_id:this.id}}))}async teamShare(){return Q(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:$}=Q(await this.client.storage.getDocumentGithubPullRequests({path:{document_id:this.id}}));return $}async branchName(){let{branchName:$}=Q(await this.client.storage.getDocumentBranchName({path:{document_id:this.id}}));return $}webUrl(){return`${this.client.webAppUrl}/app/md/${this.id}`}static search=j$({filters:{document_filters:{}},type:"document",make:($,O)=>new q($,O.document_id)});toMention(){let $=this.detail.peek();return{tag:l$("m-document-mention",{documentId:this.id,documentName:$?.documentName??"",blockName:$?.fileType??"md"}),mention:{entity_type:"document",entity_id:this.id}}}}class Ij{id;name;constructor($,O){this.id=$;this.name=O}static async list($){let{skills:O}=Q(await $.storage.getSystemSkillsHandler());return O.map((j)=>new Ij(j.id,j.name))}}class ox{client;async byTeamSlug($){let O=Q(await this.client.storage.getDocumentByTeamSlug({path:{slug:$}}));if(typeof O!=="object"||O===null||!("data"in O)||typeof O.data!=="object"||O.data===null||!("documentMetadata"in O.data)||typeof O.data.documentMetadata!=="object"||O.data.documentMetadata===null||!("documentId"in O.data.documentMetadata)||typeof O.data.documentMetadata.documentId!=="string")throw Error("Invalid team task document response");return q.byId(this.client,O.data.documentMetadata.documentId)}async validatePermissionsToken($){let O=Q(await this.client.storage.validateDocumentPermissionsToken({body:{token:$}}));return{document:q.byId(this.client,O.document_id),user:O.user_id?M.byId(this.client,O.user_id):void 0,accessLevel:O.access_level,expiresAt:O.exp,issuer:O.iss}}async createUpload($){let O={documentName:$.name,sha:$.sha,fileType:$.fileType,mimeType:$.mimeType,projectId:$.project?.id,teamId:$.team?.id,branchedFromId:$.branchedFrom?.id,emailAttachmentId:$.attachment?.id,isTask:$.isTask},j=Q(await this.client.storage.createDocument({body:O})).data;return{document:q.byId(this.client,j.documentMetadata.documentId),uploadUrl:j.presignedUrl??void 0,contentType:j.contentType,content:j.documentMetadata.content}}constructor($){this.client=$}byId($){return q.byId(this.client,$)}create($){return q.create(this.client,$)}createSnippet($){return q.createSnippet(this.client,$)}createSkill($){return q.createSkill(this.client,$)}systemSkills(){return Ij.list(this.client)}search($,O){return q.search(this.client,$,O)}recent($){return q.recent(this.client,$)}recentlyDeleted(){return q.recentlyDeleted(this.client)}}class KO extends A{async fetch(){let{attachment:$}=Q(await this.client.email.getAttachment({path:{id:this.id}}));return $}static byId($,O){return new KO($,O)}static from($,O){return new KO($,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:$}=Q(await this.client.email.getAttachmentDocumentId({path:{id:this.id}}));return q.byId(this.client,$)}}class H$ extends S${access=new o(this.client,"email_thread",this);async followup(){return Q(await this.client.storage.getEmailFollowup({path:{thread_id:this.id}}))}async setFollowup($){return Q(await this.client.storage.setEmailFollowup({path:{thread_id:this.id},body:$}))}async calendarInvitations(){return Q(await this.client.email.getThreadCalendarInvitations({path:{thread_id:this.id}}))}async update($){await this.mutate((O)=>O.storage.editThreadV2({path:{thread_id:this.id},body:{projectId:$.project===void 0?void 0:$.project?.id??null,sharePermission:$.sharePermission?r$($.sharePermission):void 0}}))}entityType="email_thread";propertyEntityType="THREAD";async fetch(){let{thread:$}=Q(await this.client.email.getThread({path:{thread_id:this.id},query:{limit:100}}));return $}static byId($,O){return new H$($,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",($)=>z$.byId(this.client,$));project=this.mappedField("project_id",($)=>$?n.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 j of $)for(let x of[j.from,...j.to,...j.cc,...j.bcc])if(x&&!O.has(x.email))O.set(x.email,x);return[...O.values()]}async messages($){return Q(await this.client.email.getThreadMessagesHandler({path:{id:this.id},query:{...$?.since?{since:$.since}:{},...$?.limit?{limit:$.limit}:{}}})).map((j)=>R$.from(this.client,j))}async attachments(){let{messages:$}=await this.detail.get();return $.flatMap((O)=>O.attachments.map((j)=>KO.from(this.client,j)))}async reply($){let O=$.subject??await this.subject()??"",{message:j}=await this.mutate((x)=>x.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 j.db_id?R$.byId(this.client,j.db_id):void 0}async archive($=!0){await this.mutate((O)=>O.email.archiveThread({path:{id:this.id},body:{value:$}}))}async updateState($){await this.mutate((O)=>O.email.updateThreadState({path:{id:this.id},body:$}))}async operations(){return Q(await this.client.email.threadOperations({path:{id:this.id}}))}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=j$({filters:{email_filters:{}},type:"email",make:($,O)=>new H$($,O.thread_id)})}class R$ extends A{async fetch(){return Q(await this.client.email.getMessage({path:{id:this.id}}))}static byId($,O){return new R$($,O)}static from($,O){return new R$($,O.db_id,O)}static async send($,O){let{message:j}=Q(await $.email.sendMessage({body:{message:{to:O.to,cc:O.cc??null,bcc:O.bcc??null,subject:O.subject,body_text:O.bodyText}}}));return j.db_id?R$.byId($,j.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",($)=>z$.byId(this.client,$));async operationStatus(){return Q(await this.client.email.messageOperationStatus({path:{id:this.id}}))}async resolveOperation($){await this.mutate((O)=>O.email.resolveMessageOperation({path:{id:this.id},body:$}))}async completeDraftAttachment($,O=0){let j=await this.link();await this.mutate((x)=>x.email.completeDraftAttachment({path:{id:this.id,attachment_id:$},query:{draft_generation:O},headers:{"X-Email-Link-Id":j.id}}))}async transferDraft($){let O=await this.detail.get();return this.mutate((j)=>j.email.transferDraft({path:{id:this.id},body:{...$,draft_generation:$.draft_generation??O.draft_generation??0},headers:{"X-Email-Link-Id":O.link_id}}))}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 H$.byId(this.client,(await this.detail.get()).thread_db_id)}}class YO extends R${async draftContext(){let $=await this.detail.get();return{headers:{"X-Email-Link-Id":$.link_id},query:{draft_generation:$.draft_generation??0}}}static byId($,O){return new YO($,O)}draftGeneration=this.field("draft_generation");async update($){let{headers:O,query:j}=await this.draftContext();await this.mutate((x)=>x.email.createDraft({headers:O,body:{draft:{...$0($),db_id:this.id,draft_generation:$.draftGeneration??j.draft_generation}}}))}async delete(){let{headers:$,query:O}=await this.draftContext();await this.mutate((j)=>j.email.deleteDraft({path:{id:this.id},headers:$,query:O}))}async schedule($,O){let{headers:j,query:x}=await this.draftContext();await this.mutate((S)=>S.email.upsertScheduledMessage({path:{id:this.id},headers:j,query:x,body:{send_time:$,include_signature:O?.includeSignature}}))}async unschedule(){let{headers:$,query:O}=await this.draftContext();await this.mutate((j)=>j.email.deleteScheduledDraft({path:{message_id:this.id},headers:$,query:O}))}async addAttachment($){let O={file_name:$.fileName,sha:$.sha,size:$.size,upload_id:$.uploadId},{headers:j,query:x}=await this.draftContext(),S=await this.mutate((K)=>K.email.addDraftAttachment({path:{id:this.id},headers:j,query:x,body:O}));return{attachment:rO.byId(this.client,this,S.attachment_id,!1,x.draft_generation),uploadUrl:S.upload_url,contentType:S.content_type}}async forwardAttachment($){let{headers:O,query:j}=await this.draftContext(),x=await this.mutate((S)=>S.email.addForwardedAttachment({path:{id:this.id},headers:O,query:j,body:{attachment_id:$.id}}));return rO.byId(this.client,this,x.attachment_id,!0,j.draft_generation)}async removeAttachment($){if($.draft.id!==this.id)throw Error("Attachment belongs to another draft");let{headers:O}=await this.draftContext(),j={draft_generation:$.draftGeneration};if($.forwarded)await this.mutate((x)=>x.email.removeForwardedAttachment({path:{id:this.id,attachment_id:$.id},headers:O,query:j}));else await this.mutate((x)=>x.email.removeDraftAttachment({path:{id:this.id,attachment_id:$.id},headers:O,query:j}))}async verifyAttachment($){if($.draft.id!==this.id||$.forwarded)throw Error("Expected an uploaded attachment on this draft");await this.completeDraftAttachment($.id,$.draftGeneration)}}class rO{draft;id;forwarded;draftGeneration;constructor($,O,j,x){this.draft=$;this.id=O;this.forwarded=j;this.draftGeneration=x}static byId($,O,j,x=!1,S=0){return new rO(O,j,x,S)}complete(){return this.draft.verifyAttachment(this)}remove(){return this.draft.removeAttachment(this)}toJSON(){return{id:this.id,draftId:this.draft.id,forwarded:this.forwarded,draftGeneration:this.draftGeneration}}}function $0($){let{bodyText:O,bodyHtml:j,bodyMacro:x,headers:S,includeSignature:K,draftGeneration:Z,thread:X,replyingTo:G,...L}=$;return{...L,body_text:O,body_html:j===void 0?void 0:btoa(Array.from(new TextEncoder().encode(j),(Y)=>String.fromCharCode(Y)).join("")).replaceAll("+","-").replaceAll("/","_").replaceAll("=",""),body_macro:x,headers_json:S,include_signature:K,draft_generation:Z,thread_db_id:X?.id,replying_to_id:G?.id}}class QO extends A{inbox;constructor($,O,j,x){super($,O,j);this.inbox=x}get headers(){return this.inbox?{"X-Email-Link-Id":this.inbox.id}:void 0}static byId($,O,j){return new QO($,O,void 0,j)}static from($,O,j){return new QO($,O.id,O,j)}async fetch(){let $=Q(await this.client.email.listEmailFilters({headers:this.headers})).filters.find((O)=>O.id===this.id);if(!$)throw new w(`Email filter ${this.id} is unavailable`);return $}emailAddress=this.field("email_address");emailDomain=this.field("email_domain");isImportant=this.field("is_important");async setImportant($){let O=await this.detail.get();await this.mutate((j)=>j.email.upsertEmailFilter({headers:this.headers,body:{email_address:O.email_address,email_domain:O.email_domain,is_important:$}}))}async delete(){await this.mutate(($)=>$.email.deleteEmailFilter({path:{id:this.id},headers:this.headers}))}}class e$ extends A{async fetch(){let{labels:$}=Q(await this.client.email.listLabels()),O=$.find((j)=>j.id===this.id);if(!O)throw new w(`label ${this.id} not found`);return O}static byId($,O){return new e$($,O)}static async list($){let{labels:O}=Q(await $.email.listLabels());return O.map((j)=>new e$($,j.id,j))}static async create($,O){let{label:j}=Q(await $.email.createLabel({body:{label_name:O}}));if(!j.id)throw new b("created label has no id");return new e$($,j.id)}async delete(){Q(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 O0{client;async createDraft($,O){let j=Q(await this.client.email.createDraft({body:{draft:$0($)},headers:O?{"X-Email-Link-Id":O.id}:void 0}));if(!j.draft.db_id)throw Error("Draft response has no message id");return YO.byId(this.client,j.draft.db_id)}draftById($){return YO.byId(this.client,$)}async*scheduled($){let O=$?.pageSize??100;if(!Number.isInteger(O)||O<1)throw Error("pageSize must be positive");let j=Math.min(O,1000);for(let x=0;;x+=j){let S=Q(await this.client.email.getScheduledMessages({query:{offset:x,limit:j},headers:$?.inbox?{"X-Email-Link-Id":$.inbox.id}:void 0}));for(let K of S.messages)yield YO.byId(this.client,K.db_id);if(S.messages.length<j)return}}async filters($){return Q(await this.client.email.listEmailFilters({headers:$?{"X-Email-Link-Id":$.id}:void 0})).filters.map((O)=>QO.from(this.client,O,$))}async upsertFilter($,O){return QO.from(this.client,Q(await this.client.email.upsertEmailFilter({headers:O?{"X-Email-Link-Id":O.id}:void 0,body:{email_address:$.emailAddress,email_domain:$.emailDomain,is_important:$.isImportant}})).filter,O)}async contacts(){return Q(await this.client.email.listContacts()).contacts}reminders($){let{inboxes:O,...j}=$??{};return a(async(x)=>{let S=Q(await this.client.storage.listEmailReminders({query:{...j,inboxIds:O?.map((K)=>K.id),cursor:x}}));return{items:S.items.map(({threadId:K,...Z})=>({...Z,thread:H$.byId(this.client,K)})),nextCursor:S.nextCursor}})}constructor($){this.client=$}byId($){return H$.byId(this.client,$)}message($){return R$.byId(this.client,$)}attachment($){return KO.byId(this.client,$)}link($){return z$.byId(this.client,$)}links(){return z$.list(this.client)}async connectionProviders(){return Q(await this.client.auth.emailConnectionProviders())}async recoverDraftTransfer($){return Q(await this.client.email.recoverDraftTransfer({path:{id:$}}))}send($){return R$.send(this.client,$)}search($,O){return H$.search(this.client,$,O)}inbox($){return a(async(O)=>{let j=Q(await this.client.email.previewsInboxCursor({path:{view:"inbox"},query:{...$?.pageSize?{limit:$.pageSize}:{},...$?.sort?{sort_method:$.sort}:{},...O?{cursor:O}:{}}}));return{items:j.items.map((x)=>H$.byId(this.client,x.id)),nextCursor:j.next_cursor}})}label($){return e$.byId(this.client,$)}labels(){return e$.list(this.client)}createLabel($){return e$.create(this.client,$)}async deleteLabel($){Q(await this.client.email.deleteLabel({path:{id:$.id}}))}async blockSender($){Q(await this.client.email.blockSender({body:{email_address:$}}))}async unblockSender($){Q(await this.client.email.unblockSender({body:{email_address:$}}))}async blockedSenders(){return Q(await this.client.email.listBlockedSenders()).blocked_emails}}class BO{client;id;constructor($,O){this.client=$;this.id=O}static byId($,O){return new BO($,O)}async delete(){Q(await this.client.storage.deleteEntityMention({path:{mention_id:this.id}}))}toJSON(){return{id:this.id}}}class j0{client;constructor($){this.client=$}byId($){return BO.byId(this.client,$)}async create($,O){let j=Q(await this.client.storage.createEntityMention({body:{source_entity_id:$.entity.id,source_entity_type:$.type,entity_id:O.entity.id,entity_type:O.type}}));return BO.byId(this.client,j.id)}}class x0{client;constructor($){this.client=$}async list($={}){let{favorites:O}=Q(await this.client.storage.listFavorites({query:{entityType:$.entityTypes,entityId:$.entityIds}}));return O}async add($){return Q(await this.client.storage.addFavorite({body:{entityId:$.id,entityType:$.entityType}}))}async remove($){Q(await this.client.storage.removeFavoriteByEntity({path:{entity_type:$.entityType,entity_id:$.id}}))}async reorder($){Q(await this.client.storage.reorderFavorites({body:{favorites:$}}))}}class o$ extends F${entityType="foreign_entity";async fetch(){return Q(await this.client.storage.getForeignEntity({path:{id:this.id}}))}static byId($,O){return new o$($,O)}static fromRecord($,O){return new o$($,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 g1({login:$,...O}){return{...O,login:$??void 0}}class S0{client;constructor($){this.client=$}byId($){return o$.byId(this.client,$)}async bySource($,O){return o$.fromRecord(this.client,Q(await this.client.storage.getForeignEntityBySource({path:{source:$,foreign_entity_id:O}})))}async githubPullRequestFacets(){let{repositories:$,authors:O,assignees:j,labels:x}=Q(await this.client.storage.getGithubPullRequestFacets());return{repositories:$,authors:O.map(g1),assignees:j.map(g1),labels:x.map(({color:S,...K})=>({...K,color:S??void 0}))}}}class u${form;id;constructor($,O){this.form=$;this.id=O}static byId($,O){return new u$($,O)}async detail(){let O=(await this.form.schema()).sections.flatMap((j)=>j.kind==="questions"?j.questions:[]).find((j)=>j.id===this.id);if(!O)throw new w(`question ${this.id} is not on form ${this.form.id}`);return O}async title(){return(await this.detail()).title}async column(){return M$.byId(await this.form.table(),(await this.detail()).column)}async options(){return(await this.detail()).options.map(($)=>JO.byId(this,$.id))}}class JO{question;id;constructor($,O){this.question=$;this.id=O}static byId($,O){return new JO($,O)}async detail(){let $=(await this.question.detail()).options.find((O)=>O.id===this.id);if(!$)throw new w(`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 LO{form;id;detail;constructor($,O,j){this.form=$;this.id=O;this.detail=new V$(()=>this.load(),j)}async load(){let $=await this.form.myResponse();if($.response.id!==this.id)throw new w(`response ${this.id} is not your current response`);return $}static byId($,O,j){return new LO($,O,j)}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 V$(()=>this.load(),$),this}}class d${form;id;constructor($,O){this.form=$;this.id=O}static byId($,O){return new d$($,O)}async detail(){let $=(await this.form.schema()).sections.find((O)=>O.id===this.id);if(!$)throw new w(`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)=>u$.byId(this.form,O.id)):[]}}class Tj{entityType;id;constructor($,O){this.entityType=$;this.id=O}static byId($,O){return new Tj($,O)}}class k$ extends A{async fetch(){return Q(await this.client.storage.getForm({path:{id:this.id}}))}static byId($,O){return new k$($,O)}static async create($,O){let j=Q(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 k$($,j.form.id,j)}static async list($,O){if(!O)return Q(await $.storage.listAccessibleForms()).map(({form:S})=>new k$($,S.id));return Q(await $.storage.listForms({query:{databaseId:O.id}})).map((x)=>new k$($,x.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",($)=>J$.byId(this.client,$.databaseId));table=this.mappedField("form",($)=>Q$.byId(J$.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(($)=>d$.byId(this,$.id))}async questions(){return(await this.detail.get()).sections.flatMap(($)=>$.kind==="questions"?$.questions.map((O)=>u$.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 b(`question or section does not belong to form ${this.id}`)}async replaceLayout($){let O=await this.table(),j=(Z)=>{if(Z.table.id!==O.id||Z.table.database.id!==O.database.id)throw new b(`column does not belong to form ${this.id}'s table`);return Z.id},x=(Z)=>({conjunction:Z.conjunction,conditions:Z.conditions.map((X)=>c(X).with({kind:"group"},(G)=>({kind:"group",...x(G)})).with({kind:"condition"},(G)=>({kind:"condition",column:j(G.column),test:c(G.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:x$.union("presence","text","number","date","checkbox")},(L)=>L).exhaustive()})).exhaustive())}),S={sections:$.map((Z)=>{if(Z.section)this.assertOwns(Z.section);let X={id:Z.section?.id??h$(),title:Z.title,description:Z.description??""};return c(Z).with({kind:"booking"},(G)=>({...X,kind:"booking",target:G.target})).with({kind:"gate"},(G)=>({...X,kind:"gate",rules:x(G.rules),message:G.message})).with({kind:"questions"},(G)=>({...X,kind:"questions",questions:G.questions.map((L)=>{if(L.question)this.assertOwns(L.question);return{id:L.question?.id??h$(),column:j(L.column),helpText:L.helpText??"",required:L.required??!1,widget:L.widget??null}})})).exhaustive()})},K=await this.mutate((Z)=>Z.storage.putFormLayout({path:{id:this.id},body:S}));return{form:this,publicationError:K.publicationError}}wireAnswers($){return $.map(({question:O,value:j})=>{this.assertOwns(O);let x=c(j).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 b("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:Z})=>({entityType:K,entityId:Z.id}))})).with({type:x$.union("text","number","boolean","date","link","clear")},(S)=>S).exhaustive();return{question:O.id,value:x}})}unlockedBooking($){return $?{...$,section:d$.byId(this,$.section)}:void 0}async outcome($,O){return c($).with({outcome:"stopped"},(j)=>({...j,section:d$.byId(this,j.section)})).with({outcome:"submitted"},async(j)=>{let x=A$.byId(await this.table(),j.row),S=this.unlockedBooking(j.booking);return{outcome:"submitted",response:LO.byId(this,j.response,{status:"submitted",row:x,answers:O,booking:S}),row:x,...S?{booking:S}:{}}}).exhaustive()}async submit($){let O={answers:this.wireAnswers($)};return this.outcome(Q(await this.client.storage.submitFormResponse({path:{id:this.id},body:O})),$)}async editResponse($){let O={answers:this.wireAnswers($)};return this.outcome(Q(await this.client.storage.editMyFormResponse({path:{id:this.id},body:O})),$)}async myResponse(){let $=Q(await this.client.storage.getMyFormResponse({path:{id:this.id}})),O=await this.table(),j=await Promise.all($.answers.map(async(K)=>{let Z=u$.byId(this,K.question),X=await c(K.value).with({type:"options"},(G)=>({type:"options",value:G.value.map((L)=>{if(!("id"in L))throw new b("stored form answers must reference options by id");return JO.byId(Z,L.id)})})).with({type:"entities"},(G)=>({type:"entities",value:G.value.map((L)=>({entityType:L.entityType,entity:Tj.byId(L.entityType,L.entityId)}))})).with({type:"rows"},async(G)=>{let L=await Z.detail();if(L.kind.type!=="relation")throw new b("row answer requires a relation question");let Y=Q$.byId(J$.byId(this.client,L.kind.database),L.kind.table);return{type:"rows",value:G.value.map((J)=>A$.byId(Y,J))}}).with({type:x$.union("text","number","boolean","date","link","clear")},(G)=>G).exhaustive(()=>{throw new b(`answer to question ${Z.id} has a type this SDK doesn't know`)});return{question:Z,value:X}})),x=$.response.row?A$.byId(O,$.response.row):void 0,S=this.unlockedBooking($.booking);return{...S?{booking:S}:{},response:LO.byId(this,$.response.id,{status:$.response.status,row:x,answers:j,booking:S}),status:$.response.status,stoppedAtSection:$.response.stoppedAtSection?d$.byId(this,$.response.stoppedAtSection):void 0,row:x,submittedAt:$.response.submittedAt,updatedAt:$.response.updatedAt,answers:j}}async responseSummary(){let $=Q(await this.client.storage.getFormResponseSummary({path:{id:this.id}}));return{...$,stoppedBySection:$.stoppedBySection.map((O)=>({section:d$.byId(this,O.section),count:O.count}))}}async tally(){return Q(await this.client.storage.getFormTally({path:{id:this.id}})).questions.map((O)=>{let j=u$.byId(this,O.question);return{question:j,responses:O.responses,buckets:O.buckets.flatMap((x)=>c(x.value).with({kind:"option"},(S)=>[{count:x.count,value:{kind:"option",option:JO.byId(j,S.option)}}]).with({kind:"checkbox"},(S)=>[{count:x.count,value:S}]).exhaustive((S)=>{return console.warn("macro sdk: unknown form tally bucket",S),[]}))}})}async sharePermissions(){return Q(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 Z0{client;constructor($){this.client=$}byId($){return k$.byId(this.client,$)}create($){return k$.create(this.client,$)}list($){return k$.list(this.client,$)}}class NO extends A{static byId($,O){return new NO($,O)}async fetch(){return Q(await this.client.storage.getGithubPullRequest({path:{id:this.id}}))}title=this.field("title");url=this.field("url");status=this.field("status");async changes(){let $=Q(await this.client.storage.getGithubPullRequestChanges({path:{id:this.id}}));return{changeset:$.changeset?new X0(this.client,this,$.changeset):void 0,error:$.error??void 0}}}class X0{client;pullRequest;record;constructor($,O,j){this.client=$;this.pullRequest=O;this.record=j}get id(){return this.record.id}async patch(){return Q(await this.client.storage.getGithubPullRequestChangesPatch({path:{id:this.pullRequest.id},query:{changeset:this.id}})).patch}toJSON(){return{pullRequestId:this.pullRequest.id,...this.record}}}class G0{client;constructor($){this.client=$}byId($){return NO.byId(this.client,$)}forEntity($){return NO.byId(this.client,$.id)}}class UO extends A{static byId($,O){return new UO($,O)}async fetch(){return Q(await this.client.storage.getHarnessPairing({path:{code:this.id}}))}name=this.field("requested_name");expiresAt=this.field("expires_at");async approve($){let O={name:$?.name,team_id:$?.team?.id,allow_permission_bypass:$?.allowPermissionBypass};return W$.from(this.client,await this.mutate((j)=>j.storage.approveHarnessPairing({path:{code:this.id},body:O})))}}class pO{client;id;constructor($,O){this.client=$;this.id=O}static byId($,O){return new pO($,O)}async claim($){let O=Q(await this.client.storage.claimHarnessPairing({path:{pairing_id:this.id},body:{device_secret:$}}));return"harness"in O?{harness:W$.from(this.client,O.harness),token:O.token}:void 0}toJSON(){return{id:this.id}}}class K0{client;constructor($){this.client=$}byId($){return W$.byId(this.client,$)}async list(){return Q(await this.client.storage.listHarnesses()).map(($)=>W$.from(this.client,$))}async me(){return W$.from(this.client,Q(await this.client.storage.getSelfHarness()))}async deleteSelf(){Q(await this.client.storage.deleteSelfHarness())}async agents(){return Q(await this.client.storage.listHarnessAgents()).map(($)=>U$.byId(this.client,$.bot_id))}async sessions(){return Q(await this.client.storage.listHarnessSessions()).map(($)=>i.byId(this.client,$.session_id))}pairing($){return UO.byId(this.client,$)}async createPairing($){let O=Q(await this.client.storage.createHarnessPairing({body:$}));return{pairing:UO.byId(this.client,O.code),device:pO.byId(this.client,O.pairing_id),deviceSecret:O.device_secret,expiresAt:O.expires_at,pollIntervalSeconds:O.poll_interval_seconds}}}var t6="00000001-0000-0000-0000-000000000002",e6="00000001-0000-0000-0002-000000000004";function o6($){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 q{static byId($,O){return new D$($,O)}static async create($,O){let{documentId:j}=Q(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$($,j)}static async forPullRequest($,O){let j=o6(O),{pullRequests:x}=Q(await $.storage.getGithubPullRequestTasks({body:{githubKeys:[j]}}));return(x[0]?.taskIds??[]).map((S)=>new D$($,S))}async completed(){let{subType:$}=await this.detail.get();if($!=="task")return;let j=(await this.properties()).find((x)=>x.definition.id===t6)?.value;return j?.type==="SelectOption"&&j.value.includes(e6)}webUrl(){return`${this.client.webAppUrl}/app/task/${this.id}`}static search=j$({filters:{document_filters:{sub_types:["task"],task_filters:{}}},type:"document",make:($,O)=>new D$($,O.document_id)})}class $O extends A{access=new o(this.client,"initiative",this);static byId($,O){return new $O($,O)}static from($,O){return new $O($,O.id,O)}async fetch(){return Q(await this.client.storage.getInitiative({path:{initiative_id:this.id}}))}name=this.field("name");owner=this.mappedField("ownerId",($)=>M.byId(this.client,$));members=this.mappedField("memberIds",($)=>$.map((O)=>M.byId(this.client,O)));tasks=this.mappedField("taskIds",($)=>$.map((O)=>D$.byId(this.client,O)));accessLevel=this.field("userAccessLevel");sharePermissions=this.field("sharePermission");async update($){await this.mutate((O)=>O.storage.updateInitiative({path:{initiative_id:this.id},body:{name:$.name,memberIds:$.members?.map((j)=>j.id),sharePermission:$.sharePermission?r$($.sharePermission):void 0}}))}async delete(){await this.mutate(($)=>$.storage.deleteInitiative({path:{initiative_id:this.id}}))}}class Y0{client;constructor($){this.client=$}byId($){return $O.byId(this.client,$)}async list(){return Q(await this.client.storage.listInitiatives()).initiatives.map(($)=>$O.byId(this.client,$.id))}async create($){return $O.from(this.client,Q(await this.client.storage.createInitiative({body:{name:$.name,description:$.description,memberIds:$.members?.map((O)=>O.id),shareWithTeam:$.shareWithTeam,propertyValues:$.propertyValues}})))}}class Q0{client;constructor($){this.client=$}byId($){return I$.byId(this.client,$)}async create($){return I$.from(this.client,Q(await this.client.storage.meetingCreate({body:$})))}async list(){return Q(await this.client.storage.meetingList()).meetings.map(($)=>I$.from(this.client,$))}async active(){return Q(await this.client.storage.meetingListActive()).meetings.map(($)=>I$.from(this.client,$))}async lookup($){return I$.from(this.client,Q(await this.client.storage.meetingLookup({path:{token:$}})))}}class VO extends A{async fetch(){return Q(await this.client.notification.getTypedNotificationById({path:{notification_id:this.id}}))}static byId($,O){return new VO($,O)}static from($,O){return new VO($,O.id,O)}static list($,O){return a(async(j)=>{let x=Q(await $.notification.listTypedNotifications({query:{...O?.pageSize?{limit:O.pageSize}:{},...O?.states!==void 0?{states:O.states.join(",")}:{},...j?{cursor:j}:{}}}));return{items:x.items.map((S)=>VO.from($,S)),nextCursor:x.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 J0{client;constructor($){this.client=$}byId($){return VO.byId(this.client,$)}list($){return VO.list(this.client,$)}async markSeen($){Q(await this.client.notification.bulkMarkNotificationsSeen({body:{notificationIds:$}}))}async markDone($){Q(await this.client.notification.bulkMarkNotificationsDone({body:{notificationIds:$}}))}async delete($){Q(await this.client.notification.bulkDeleteUserNotificationsV2({body:{notificationIds:$}}))}async preferences(){return Q(await this.client.notification.getNotificationTypePreferences())}async enableType($){Q(await this.client.notification.enableNotificationType({path:{notification_event_type:$}}))}async disableType($){Q(await this.client.notification.disableNotificationType({path:{notification_event_type:$}}))}}class V0{client;constructor($){this.client=$}async list(){let{data:$}=Q(await this.client.storage.getPinsHandler({}));return $?.recent??[]}async add($,O){Q(await this.client.storage.addPinHandler({path:{pinned_item_id:$.id},body:{pinType:$.entityType,pinIndex:O.index}}))}async remove($){Q(await this.client.storage.removePinHandler({path:{pinned_item_id:$.id},body:{pinType:$.entityType}}))}async reorder($){Q(await this.client.storage.reorderPinsHandler({body:$}))}}class W0{client;constructor($){this.client=$}byId($){return n.byId(this.client,$)}create($){return n.create(this.client,$)}search($,O){return n.search(this.client,$,O)}}class zO{client;definitionId;id;record;constructor($,O,j,x){this.client=$;this.definitionId=O;this.id=j;this.record=x}static from($,O,j){return new zO($,O,j.id,j)}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=Q(await this.client.properties.updatePropertyOption({path:{definition_id:this.definitionId,option_id:this.id},body:$})),this}async delete(){Q(await this.client.properties.deletePropertyOption({path:{definition_id:this.definitionId,option_id:this.id}}))}}class OO{client;id;detail;constructor($,O,j){this.client=$;this.id=O;this.detail=new V$(()=>this.fetch(),j)}async fetch(){return Q(await this.client.properties.getPropertyDefinition({path:{definition_id:this.id}}))}static async create($,O){let j=Q(await $.properties.createPropertyDefinition({body:{display_name:O.displayName,scope:O.scope,data_type:O.dataType}}));return new OO($,j.id,j)}static byId($,O){return new OO($,O)}static fromRecord($,O){return new OO($,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 Q(await this.client.properties.deletePropertyDefinition({path:{definition_id:this.id}}))}async options(){return Q(await this.client.properties.getPropertyOptions({path:{definition_id:this.id}})).map((O)=>zO.from(this.client,this.id,O))}async addOption($){let O=Q(await this.client.properties.addPropertyOption({path:{definition_id:this.id},body:$}));return zO.from(this.client,this.id,O)}async updateOption($,O){let j=Q(await this.client.properties.updatePropertyOption({path:{definition_id:this.id,option_id:$.id},body:O}));return zO.from(this.client,this.id,j)}async deleteOption($){return Q(await this.client.properties.deletePropertyOption({path:{definition_id:this.id,option_id:$.id}}))}}class B0{client;constructor($){this.client=$}async list($){return Q(await this.client.properties.listProperties({query:{scope:$?.scope??"all",...$?.forEntityType!==void 0?{for_entity_type:$.forEntityType}:{}}})).map((j)=>{let x="definition"in j?j.definition:j;return OO.fromRecord(this.client,x)})}create($){return OO.create(this.client,$)}definition($){return OO.byId(this.client,$)}async bulkEntityProperties($){return Q(await this.client.properties.getBulkEntityProperties({body:$}))}async updateEntityPropertyOptions($,O){return Q(await this.client.properties.bulkUpdateEntitiesPropertyOptions({body:{entities:$.map((x)=>x.propertyReference()),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)}:{}}})).results}async addEntityPropertyOption($){return Q(await this.client.properties.addEntityPropertyOption({path:{...$.entity.propertyReference(),property_id:$.property.id,option_id:$.option.id}}))}async removeEntityPropertyOption($){return Q(await this.client.properties.removeEntityPropertyOption({path:{...$.entity.propertyReference(),property_id:$.property.id,option_id:$.option.id}}))}async tags(){return Q(await this.client.properties.listTags({}))}}function L0($){return c($).with({type:"cron"},(O)=>O).with({type:"events"},(O)=>({type:"events",filters:O.filters.map(({entities:j,...x})=>({...x,ids:j?.map((S)=>S.entity.id)}))})).exhaustive()}function $7($){return c($).with({type:"multiple"},(O)=>({type:"multiple",triggers:O.triggers.map(L0)})).with({type:"cron"},L0).with({type:"events"},L0).exhaustive()}class jO extends A{static byId($,O){return new jO($,O)}static from($,O){if(!O.id)throw Error("Routine response has no id");return new jO($,O.id,O)}async fetch(){return Q(await this.client.scheduledAction.getScheduledAction({path:{id:this.id}}))}name=this.field("name");trigger=this.field("trigger");enabled=this.field("enabled");runVisibility=this.field("run_visibility");nextRunAt=this.field("next_run_at");revision=this.field("configuration_revision");owner=this.mappedField("owner",($)=>M.byId(this.client,$));async update($){await this.mutate((O)=>O.scheduledAction.updateScheduledAction({path:{id:this.id},body:U0($)}))}async setEnabled($){await this.mutate((O)=>O.scheduledAction.setScheduledActionEnabled({path:{id:this.id},body:{enabled:$}}))}async execute(){let $=Q(await this.client.scheduledAction.executeScheduledActionNow({path:{id:this.id}}));if($.resource)return c($.resource).with({type:"agent"},(O)=>i.byId(this.client,O.id)).with({type:"chat"},(O)=>Z$.byId(this.client,O.id)).exhaustive();return $.chat_id?Z$.byId(this.client,$.chat_id):void 0}async history(){return Q(await this.client.scheduledAction.listScheduledActionHistory({path:{id:this.id}})).map(($)=>new N0(this,$))}async delete(){await this.mutate(($)=>$.scheduledAction.deleteScheduledAction({path:{id:this.id}}))}}class N0{routine;record;constructor($,O){this.routine=$;this.record=O}get id(){return this.record.id??void 0}toJSON(){return{routine:this.routine.id,...this.record}}}function U0($){let O={prompt:$.prompt,user_prompt:$.userPrompt,model:$.model,agent:$.agent?{bot_id:$.agent.id}:void 0};return{kind:"Agent",name:$.name,enabled:$.enabled,run_visibility:$.runVisibility,trigger:$7($.trigger),task:{...O}}}class z0{client;constructor($){this.client=$}byId($){return jO.byId(this.client,$)}async create($){return jO.from(this.client,Q(await this.client.scheduledAction.createScheduledAction({body:{...U0($),enabled:$.enabled??!0}})))}async list($){return Q(await this.client.scheduledAction.listScheduledActions({query:{include_events:$?.includeEvents}})).map((O)=>jO.from(this.client,O))}}class I0{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 T0{client;constructor($){this.client=$}byId($){return T$.byId(this.client,$)}current(){return T$.current(this.client)}list(){return T$.list(this.client)}}class H0{client;constructor($){this.client=$}async get($){return Q(await this.client.unfurl.getUnfurl({query:{url:$}}))}async bulk($){return Q(await this.client.unfurl.getUnfurlBulk({body:{url_list:$}}))}}class R0{client;constructor($){this.client=$}byId($){return M.byId(this.client,$)}me(){return M.me(this.client)}}class xO extends A{signingSecret;constructor($,O,j,x){super($,O,j);this.signingSecret=x}async fetch(){return Q(await this.client.storage.getWebhook({path:{webhook_id:this.id}}))}static async create($,O){let j=Q(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 xO($,j.id,j,j.signing_secret)}static byId($,O){return new xO($,O)}static fromRecord($,O){return new xO($,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 D0{client;constructor($){this.client=$}create($){return xO.create(this.client,$)}byId($){return xO.byId(this.client,$)}async list(){let{webhooks:$}=Q(await this.client.storage.listWebhooks());return $.map((O)=>xO.fromRecord(this.client,O))}}function C0($){if("properties"in $.data)return $.data.properties;if($.tag==="calendarEvent")return $.data.extra.properties;return[]}function y1($,O,j){let x=[];for(let S of C0(O)){if(S.definition.data_type!=="TAG"||S.value?.type!=="SelectOption")continue;for(let K of S.value.value){let Z=j.get(K);if(Z&&!x.some((X)=>X.label===Z.label&&X.scope===Z.scope))x.push(Z)}}switch(O.tag){case"document":return{type:"document",id:O.data.id,entity:q.byId($,O.data.id),snapshot:O,tags:x,name:O.data.name,fileType:O.data.fileType,subType:O.data.subType?.type};case"chat":return{type:"ai_chat",id:O.data.id,entity:Z$.byId($,O.data.id),snapshot:O,tags:x,name:O.data.name};case"project":return{type:"project",id:O.data.id,entity:n.byId($,O.data.id),snapshot:O,tags:x,name:O.data.name};case"emailThread":return{type:"email",id:O.data.id,entity:H$.byId($,O.data.id),snapshot:O,tags:x,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:x,name:O.data.channel.name};case"channelThread":return{type:"channel_thread",id:O.data.id,entity:new g$($,O.data.channel_id,O.data.id),snapshot:O,tags:x,channelId:O.data.channel_id};case"call":return{type:"call",id:O.data.callId,entity:Y$.byId($,O.data.callId),snapshot:O,tags:x,createdBy:O.data.createdBy};case"calendarEvent":return{type:"calendar_event",id:O.data.id,entity:K$.byId($,O.data.id),snapshot:O,tags:x,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:o$.byId($,O.data.id),snapshot:O,tags:x,foreignEntityId:O.data.foreignEntityId,foreignEntitySource:O.data.foreignEntitySource,metadata:O.data.metadata};default:throw Error(`Unexpected workspace entity type: ${O.tag}`)}}var v1="00000000-0000-0000-0000-000000000000",_0={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"]},Hj=($)=>$.replace(/[A-Z]/g,(O)=>O.toLowerCase()),h1=($,O)=>$==null?O:{"&":[$,O]};function M0($,O){if(!$||typeof $!=="object"||Array.isArray($))throw Error(`Invalid workspace ${O}: expected a filter expression.`);let j=Object.entries($),x=j[0];if(j.length!==1||x===void 0)throw Error(`Invalid workspace ${O}: use exactly one of l, &, |, !.`);let[S,K]=x;if(S==="l")return;if(S==="!"){M0(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((Z,X)=>{M0(Z,`${O}.${S}[${X}]`)})}class Rj{client;tagSets;constructor($){this.client=$}sets(){return this.tagSets??=this.client.properties.listTags({}).then(Q),this.tagSets}async tagMap(){let $=new Map;for(let O of await this.sets())for(let j of O.options)if(j.value.type==="string")$.set(j.id,{label:j.value.value,scope:O.scope==="user"?"personal":"team"});return $}async body($){for(let[S,K,Z]of[["sortBy",$.sortBy,["recently_viewed","recently_updated","recently_created"]],["emailPreset",$.emailPreset,["signal"]],["tagsMatch",$.tagsMatch,["any","all"]]])if(K!==void 0&&!Z.includes(K))throw Error(`Invalid workspace ${S}: ${K}`);if($.includeTypes!==void 0&&(!Array.isArray($.includeTypes)||$.includeTypes.some((S)=>!Object.hasOwn(_0,S))))throw Error(`Invalid workspace includeTypes. Supported values: ${Object.keys(_0).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)M0($[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:v1}},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 j=$.inbox?.trim();if(j){let{links:S}=Q(await this.client.email.listLinks()),K=S.filter((X)=>Hj(X.email_address)===Hj(j)),Z=K[0];if(!Z)throw Error(`No connected inbox matches "${j}". Connected inboxes: ${S.map((X)=>X.email_address).join(", ")}.`);if(K.length>1)throw Error(`Multiple connected inboxes match "${j}"; cannot pick one.`);O.ef=h1(O.ef,{l:{Owner:Z.id}})}let x=$.includeTypes??($.emailPreset==="signal"?["email"]:void 0);if(x?.length){for(let[S,[K,Z]]of Object.entries(_0))if(!x.includes(S))O[K]={l:{[Z]:v1}}}if($.tags?.length){let S=(await this.sets()).flatMap((G)=>{let L=G.definition;if(!L)return[];return G.options.flatMap((Y)=>Y.value.type==="string"?[{id:Y.id,definitionId:L.id,label:Y.value.value,scope:G.scope==="user"?"personal":"team"}]:[])}),K=new Map;for(let G of $.tags){let L=S.filter((Y)=>Hj(Y.label)===Hj(G.label.trim())&&(!G.scope||Y.scope===G.scope));if(!L.length)throw Error(`Unknown tag "${G.label}". Available tags: ${S.map((Y)=>`${Y.label} (${Y.scope})`).join(", ")}.`);if($.tagsMatch==="all"&&L.length>1)throw Error(`Tag "${G.label}" is ambiguous; specify personal or team scope.`);for(let Y of L)K.set(Y.id,Y)}let X=[...K.values()].map((G)=>({l:{pd:G.definitionId,v:{so:G.id}}})).reduce((G,L)=>G===void 0?L:{[$.tagsMatch==="all"?"&":"|"]:[G,L]},void 0);O.propf=h1(O.propf,X)}return O}}class A0{client;constructor($){this.client=$}async page($={}){let O=new Rj(this.client);return this.fetch(O,await O.body($),$.cursor)}async*list($={}){let O=new Rj(this.client),j=await O.body($);yield*a((x)=>this.fetch(O,j,x))}async fetch($,O,j){let x=Q(await this.client.storage.postItemsSoupAst({body:O,query:j?{cursor:j}:void 0})),K=x.items.some((Z)=>C0(Z).some((X)=>X.definition.data_type==="TAG"))?await $.tagMap():new Map;return{items:x.items.map((Z)=>y1(this.client,Z,K)),nextCursor:x.next_cursor,hasMore:x.next_cursor!=null}}}function m1({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:G,url:L,...Y}){let J,T=G??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=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(J!==void 0)P.set("Last-Event-ID",J);try{let D={redirect:"follow",...Y,body:Y.serializedBody,headers:P,signal:I},C=new Request(L,D);if($)C=await $(L,D);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="",k=()=>{try{H.cancel()}catch{}};I.addEventListener("abort",k);try{while(!0){let{done:d,value:l}=await H.read();if(d)break;U+=l,U=U.replace(/\r\n?/g,`
-`);let g=U.split(`
+async function gO($,O,j){if(!Number.isInteger(O)||O<1)throw RangeError(`concurrency limit must be a positive integer, got ${O}`);let x=Array($.length),S=0,K=async()=>{while(S<$.length){let X=S;S+=1,x[X]=await j($[X])}},Z=Array.from({length:Math.min(O,$.length)},K);return await Promise.all(Z),x}class W${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*a($){let O;do{let j=await $(O),x=j.nextCursor??void 0;if(O!==void 0&&x!==void 0&&JSON.stringify(x)===JSON.stringify(O))throw Error("Pagination cursor did not advance");yield*j.items,O=x}while(O!==void 0)}class f extends Error{constructor($){super($);this.name="MacroError"}}class ZO extends f{status;data;constructor($,O){super(`Macro API error ${$}`);this.status=$;this.data=O;this.name="MacroApiError"}}class E extends f{constructor($){super($);this.name="MacroNotFoundError"}}function Q($){if($.error!==void 0)throw new ZO($.response?.status??0,$.error);return $.data}class M{client;id;detail;constructor($,O,j){this.client=$;this.id=O;this.detail=new W$(()=>this.fetch(),j)}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=Q(await $(this.client));return this.detail.clear(),O}}class F$ extends M{async permission(){return Q(await this.client.storage.getEntityPermission({path:{entity_type:this.entityType,entity_id:this.id}}))}async favorite(){return Q(await this.client.storage.addFavorite({body:{entityId:this.id,entityType:this.entityType}})),this}async unfavorite(){return Q(await this.client.storage.removeFavoriteByEntity({path:{entity_type:this.entityType,entity_id:this.id}})),this}}class X$ extends F${propertyReference(){return{entity_type:this.propertyEntityType,entity_id:this.id}}async properties($){let{properties:O}=Q(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){Q(await this.client.properties.setEntityProperty({path:{...this.propertyReference(),property_id:$.id},body:{value:O??null}}))}async updatePropertyOptions($){return Q(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((j)=>j.id)}:{},...O.remove?{remove_option_ids:O.remove.map((j)=>j.id)}:{}}))}}))}async deleteProperty($){Q(await this.client.properties.deleteEntityProperty({path:{entity_property_id:$.property.id}}))}}function r$($,O){return`<${$}>${JSON.stringify(O)}</${$}>`}function R6($){return typeof $==="object"&&$!==null&&typeof $.toMention==="function"}var D6={toMention:()=>({tag:r$("m-group-mention",{groupAlias:"here"}),mention:{entity_type:"group",entity_id:"here"}})};function C6($,...O){let j="",x=[];for(let[S,K]of $.entries()){j+=K;let Z=O[S];if(Z===void 0)continue;if(R6(Z)){let X=Z.toMention();j+=X.tag,x.push(X.mention)}else j+=String(Z)}return{content:j,mentions:_6(x)}}function _6($){let O=new Set;return $.filter((j)=>{let x=`${j.entity_type}:${j.entity_id}`;if(O.has(x))return!1;return O.add(x),!0})}function $$($){return typeof $==="string"?{content:$,mentions:[]}:$}class B$ extends M{static byId($,O){return new B$($,O)}static from($,O){return new B$($,O.id,O)}async fetch(){let $=Q(await this.client.storage.listHarnesses()).find((O)=>O.id===this.id);if(!$)throw new E(`Harness ${this.id} is unavailable`);return $}name=this.field("name");connected=this.field("connected");kind=this.field("kind");async delete(){await this.mutate(($)=>$.storage.deleteHarness({path:{harness_id:this.id}}))}}class z$ extends M{static byId($,O){return new z$($,O)}static from($,O){return new z$($,O.bot.id,O)}async fetch(){let $=Q(await this.client.storage.listAgents()).find((O)=>O.bot.id===this.id);if(!$)throw new E(`Agent ${this.id} is unavailable`);return $}name=this.mappedField("bot",($)=>$.name);instructions=this.field("instructions");defaultModel=this.field("default_model");channels=this.mappedField("channel_ids",($)=>$.map((O)=>b.byId(this.client,O)));host=this.mappedField("harness_id",($)=>$?B$.byId(this.client,$):void 0);async update($){await this.mutate((O)=>O.storage.updateAgent({path:{agent_id:this.id},body:Ex($)}))}}function Ex($){let{channels:O,team:j,host:x,autoAcceptPermissions:S,avatarUrl:K,channelScope:Z,defaultModel:X,isCoding:G,...L}=$;return{...L,channel_ids:O?.map((Y)=>Y.id),team_id:j?.id,harness_id:x?.id,auto_accept_permissions:S,avatar_url:K,channel_scope:Z,default_model:X,is_coding:G}}async function Gj($,O,j){let{channelId:x,thread:S}=A6(O);if(await M6($)){let{id:Z}=Q(await $.storage.entityMessageCreate({path:{parent_type:"channel",parent_id:x},body:{content:j.content,mentions:j.mentions,attachments:[],thread_id:S?.rootId??null,nonce:crypto.randomUUID()}}));return Z}if(S)throw new f("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}=Q(await $.storage.postChannelBotWebhook({path:{channel_id:x},body:{content:j.content},headers:{"x-macro-bot-scope":"user"}}));return K}function A6($){return"rootId"in $?{channelId:$.channelId,thread:$}:{channelId:$.id}}async function M6($){if($.authConfig.type!=="bot"||$.hasActingUser())return!0;let{owner:O}=await $.selfBot();return O?.type==="team"}class y${client;channelId;rootId;constructor($,O,j){this.client=$;this.channelId=O;this.rootId=j}toJSON(){return{channelId:this.channelId,rootId:this.rootId}}channel(){return b.byId(this.client,this.channelId)}root(){return e.byId(this.client,this.channelId,this.rootId)}async replies(){let{replies:$}=Q(await this.client.storage.entityMessageGetThread({path:{parent_type:"channel",parent_id:this.channelId,id:this.rootId}}));return $.map((O)=>e.from(this.client,this.channelId,O))}async reply($){let O=await Gj(this.client,this,$$($));return e.byId(this.client,this.channelId,O)}}class e extends F${channelId;mentions;entityType="channel_message";constructor($,O,j,x=[],S){super($,j,S);this.channelId=O;this.mentions=x}get path(){return{parent_type:"channel",parent_id:this.channelId,id:this.id}}async fetch(){return Q(await this.client.storage.entityMessageGetMessage({path:this.path}))}static byId($,O,j,x=[]){return new e($,O,j,x)}static from($,O,j){return new e($,O,j.id,j.mentions,j)}content=this.field("content");createdAt=this.field("created_at");editedAt=this.field("edited_at");updatedAt=this.field("updated_at");async author(){return A.byId(this.client,(await this.detail.get()).sender_id)}channel(){return b.byId(this.client,this.channelId)}thread(){return new y$(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:j}=$$($);return await this.mutate((x)=>x.storage.entityMessageEdit({path:this.path,body:{content:O,mentions:j}})),this}async delete(){await this.mutate(($)=>$.storage.entityMessageDeleteMessage({path:this.path}))}async reply($){return this.thread().reply($)}}class Kj{client;channel;record;constructor($,O,j){this.client=$;this.channel=O;this.record=j}agent(){return z$.byId(this.client,this.record.botId)}sessions(){return this.record.sessions.map(($)=>({session:i.byId(this.client,$.sessionId),isCurrent:$.isCurrent,createdAt:$.createdAt}))}turns(){return this.record.turns.map(($)=>new wx(this.client,this,$))}async startFresh($){Q(await this.client.agentHarness.startFreshAgentConversation({path:{channel_id:this.channel.id,bot_id:this.record.botId},body:{sessionId:$.id}}))}toJSON(){return{channelId:this.channel.id,agentId:this.record.botId}}}class wx{client;conversation;record;constructor($,O,j){this.client=$;this.conversation=O;this.record=j}source(){return e.byId(this.client,this.conversation.channel.id,this.record.sourceMessageId)}session(){return i.byId(this.client,this.record.sessionId)}async retry($){Q(await this.client.agentHarness.retryAgentConversationTurn({path:{channel_id:this.conversation.channel.id,bot_id:this.conversation.agent().id,source:this.record.sourceMessageId},body:{actionId:$}}))}toJSON(){return{channelId:this.conversation.channel.id,sourceMessageId:this.record.sourceMessageId}}}class L$ extends M{parent;toJSON(){return{...super.toJSON(),parentType:this.parent.type,parentId:this.parent.entity.id}}constructor($,O,j){super($,j);this.parent=O}static byId($,O,j){return new L$($,O,j)}get path(){return{parent_type:this.parent.type,parent_id:this.parent.entity.id,id:this.id}}async fetch(){return Q(await this.client.storage.entityMessageGetThread({path:this.path})).state}resolved=this.field("resolved");async update($){let O={resolved:$.resolved,detach_anchor:$.detachAnchor,nonce:$.nonce};await this.mutate((j)=>j.storage.entityMessagePatchThread({path:this.path,body:O}))}async delete($){await this.mutate((O)=>O.storage.entityMessageDeleteThread({path:this.path,query:{nonce:$}}))}}async function E$($,O,j,x){for(let K of[...x?.messages??[],...x?.around?[x.around]:[]]){let Z="channelId"in K?{type:"channel",id:K.channelId}:("documentId"in K)?{type:"document",id:K.documentId}:("callId"in K)?{type:"call",id:K.callId}:K.parent;if(Z.type!==O.type||Z.id!==O.entity.id)throw Error("Timeline message belongs to another resource")}let S=Q(await $.storage.messageTimelineEntries({path:{parent_type:O.type,parent_id:O.entity.id},query:{selection:x?JSON.stringify({cursor:x.cursor,around:x.around?.id,ids:x.messages?.map((K)=>K.id),activity_after:x.activityAfter,activity_before:x.activityBefore,anchored:x.anchored,direction:x.direction,include_deleted_threads:x.includeDeletedThreads,limit:x.limit}):void 0}}));return{entries:S.entries.map((K)=>{if(K.type==="activity")return{type:"activity",activity:{...K.activity,actor:A.byId($,K.activity.actor_id)}};return{type:"message",message:j(K.message)}}),nextCursor:S.next_cursor??void 0,previousCursor:S.previous_cursor??void 0}}var P6=50;function j$($){let{filters:O,type:j,make:x,includeCrm:S}=$;return(K,Z,X)=>{let G=X?.searchOn??"name_content",L=X?.pageSize??P6;return a(async(Y)=>{let{results:J,next_cursor:T}=Q(await K.search.unifiedSearch({body:{query:Z,match_type:"partial",search_on:G,...O?{filters:O}:{},...S?{include_crm:!0}:{}},query:{page_size:L,...Y?{cursor:Y}:{}}}));return{items:J.filter((W)=>W.type===j).map((W)=>x(K,W)),nextCursor:T}})}}class XO{client;channel;record;constructor($,O,j){this.client=$;this.channel=O;this.record=j}get id(){return this.record.id}user(){return A.byId(this.client,this.record.user_id)}createdAt(){return this.record.created_at}async recordInteraction($){return new XO(this.client,this.channel,Q(await this.client.storage.postActivity({body:{activity_type:$,channel_id:this.channel.id}})))}toJSON(){return this.record}}class b extends X${async recordActivity($){return new XO(this.client,this,Q(await this.client.storage.postActivity({body:{activity_type:$,channel_id:this.id}})))}async setPicture($){await this.mutate((O)=>O.storage.setChannelPicture({path:{channel_id:this.id},body:{profile_picture_id:$?.id??null}}))}messageThreadById($){return L$.byId(this.client,{type:"channel",entity:this},$)}timelinePage($){return E$(this.client,{type:"channel",entity:this},(O)=>e.from(this.client,this.id,O),$)}async agentConversations(){return Q(await this.client.agentHarness.listAgentConversations({path:{channel_id:this.id}})).conversations.map(($)=>new Kj(this.client,this,$))}entityType="channel";propertyEntityType="CHANNEL";async fetch(){return Q(await this.client.storage.getChannel({path:{channel_id:this.id}}))}static byId($,O){return new b($,O)}static async dm($,O){let{channel_id:j}=Q(await $.storage.getOrCreateDm({body:{recipient_id:O.id}}));return new b($,j)}static async private($,O){let{channel_id:j}=Q(await $.storage.getOrCreatePrivate({body:{recipients:O.map((x)=>x.id)}}));return new b($,j)}static async create($,O){let{id:j}=Q(await $.storage.createChannel({body:{channel_type:O.type,name:O.name??null,participants:(O.participants??[]).map((x)=>x.id),team_id:O.team?.id??null}}));return new b($,j)}name=this.field("channel_name");type=this.field("channel_type");async send($,O){let j=await Gj(this.client,O?.thread??this,$$($));return e.byId(this.client,this.id,j)}messages($){return this.timeline({limit:$?.pageSize})}messagesAfter($,O){return this.timeline({activity_after:$ instanceof Date?$.toISOString():$,limit:O?.pageSize})}timeline($){return a(async(O)=>{let j=Q(await this.client.storage.messageTimeline({path:{parent_type:"channel",parent_id:this.id},query:{selection:JSON.stringify({...$,cursor:O})}}));return{items:j.items.map((x)=>e.from(this.client,this.id,x)),nextCursor:j.next_cursor}})}message($){return e.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:$}=Q(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 Q(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((j)=>j.id)}}))}async removeParticipants($){await this.mutate((O)=>O.storage.removeParticipants({path:{channel_id:this.id},body:{participants:$.map((j)=>j.id)}}))}async typing($,O){Q(await this.client.storage.entityMessageTyping({path:{parent_type:"channel",parent_id:this.id},body:{active:$==="start",thread_id:O?.thread?.rootId??null}}))}attachments($){return a(async(O)=>{let j=Q(await this.client.storage.getChannelAttachments({path:{channel_id:this.id},query:{...$?.pageSize?{limit:$.pageSize}:{},...$?.type?{attachment_type:$.type}:{},...O?{cursor:O}:{}}}));return{items:j.items,nextCursor:j.next_cursor}})}webUrl(){return`${this.client.webAppUrl}/app/channel/${this.id}`}static search=j$({type:"channel",make:($,O)=>new b($,O.channel_id)})}class A extends X${entityType="user";propertyEntityType="USER";async fetch(){let{names:$}=Q(await this.client.auth.getUserNamesWithEmail({body:{user_ids:[this.id]}})),O=$.find((j)=>j.id===this.id);if(!O)throw new E(`user ${this.id} not found`);return O}static byId($,O){return new A($,O)}static async me($){let{user_id:O}=Q(await $.auth.getUserInfo());return new A($,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 b.dm(this.client,this)}toMention(){return{tag:r$("m-user-mention",{userId:this.id}),mention:{entity_type:"user",entity_id:this.id}}}}class o{client;entityType;entity;constructor($,O,j){this.client=$;this.entityType=O;this.entity=j}get path(){return{entity_type:this.entityType,entity_id:this.entity.id}}async state($){let O=Q(await this.client.storage.accessRequestsState({path:this.path,query:{offset:$}}));return{accessLevel:O.accessLevel??void 0,canReview:O.canReview,owner:O.owner?A.byId(this.client,O.owner):void 0,pendingCount:O.pendingCount,supportedLevels:O.supportedLevels,nextOffset:O.nextOffset??void 0,mine:O.mine?BO.from(this.client,this,O.mine):void 0,requests:O.requests.map((j)=>BO.from(this.client,this,j))}}async submit($,O){return BO.from(this.client,this,Q(await this.client.storage.accessRequestsSubmit({path:this.path,body:{requestedLevel:$,revision:O}})))}async cancel($){Q(await this.client.storage.accessRequestsCancel({path:this.path,query:{revision:$}}))}async direct(){return Q(await this.client.storage.accessRequestsDirect({path:this.path})).map(($)=>({user:A.byId(this.client,$.userId),accessLevel:$.accessLevel}))}async grant($,O){Q(await this.client.storage.accessRequestsSetDirect({path:{...this.path,user_id:$.id},body:{accessLevel:O}}))}async remove($){Q(await this.client.storage.accessRequestsRemoveDirect({path:{...this.path,user_id:$.id}}))}async resolve($,O){let j=$.access.toJSON();if(j.entity_type!==this.entityType||j.entity_id!==this.entity.id)throw Error("Access request belongs to another entity");return Q(await this.client.storage.accessRequestsResolve({path:{...this.path,request_id:$.id},body:O}))}toJSON(){return this.path}}class BO extends M{access;resolvedRecord;constructor($,O,j){super($,j.id,j);this.access=O}static from($,O,j){return new BO($,O,j)}async fetch(){if(this.resolvedRecord)return this.resolvedRecord;let $;do{let O=await this.access.state($),j=[O.mine,...O.requests].find((x)=>x?.id===this.id);if(j)return j.detail.get();$=O.nextOffset}while($!==void 0);throw new E(`Access request ${this.id} is unavailable`)}revision=this.field("revision");status=this.field("status");requestedLevel=this.field("requestedLevel");requester=this.mappedField("requesterId",($)=>A.byId(this.client,$));async resolve($){this.resolvedRecord=await this.access.resolve(this,{revision:await this.revision(),grantedLevel:$}),this.detail.clear()}}function p$($){return{...$,channelSharePermissions:$.channelSharePermissions===void 0||$.channelSharePermissions===null?$.channelSharePermissions:$.channelSharePermissions.map((O)=>({channelId:O.channel.id,accessLevel:O.accessLevel,operation:O.operation}))}}class U$ extends M{parent;constructor($,O,j,x){super($,j,x);this.parent=O}static byId($,O,j){return new U$($,O,j)}static fromRecord($,O,j){return new U$($,O,j.id,j)}static async create($,O,j){return U$.createForSession($,O.session(),j,O)}static async createForSession($,O,j,x){let S=Q(await $.agentHarness.createSessionReview({path:{session_id:O.id},body:{...j,executionId:x?.id??null}}));return U$.fromRecord($,O,S)}static async list($,O){return Q(await $.agentHarness.listExecutionReviews({path:{session_id:O.session().id,execution_id:O.id}})).map((x)=>U$.fromRecord($,O.session(),x))}async fetch(){return Q(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 qx($,{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((j)=>j.agentHarness.decideSessionReview({path:{session_id:this.parent.id,review_id:this.id},body:{...$,revision:O}}))}}class qx{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 kO extends M{parent;constructor($,O,j){super($,O);this.parent=j}static byId($,O,j){return new kO($,j,O)}async fetch(){return Q(await this.client.agentHarness.getCodeExecution({path:{session_id:this.parent.id,execution_id:this.id}}))}reviews={create:($)=>U$.create(this.client,this,$),list:()=>U$.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 Yj{client;sessionId;dto;constructor($,O,j){this.client=$;this.sessionId=O;this.dto=j}static from($,O,j){return new Yj($,O,j)}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 Q(await this.client.agentHarness.editQueuedAction({path:{session_id:this.sessionId,action_id:this.actionId},body:{prompt:$}})),this.dto={...this.dto,prompt:$},this}async steer(){Q(await this.client.agentHarness.steerQueuedAction({path:{session_id:this.sessionId,action_id:this.actionId}}))}async remove(){Q(await this.client.agentHarness.removeQueuedAction({path:{session_id:this.sessionId,action_id:this.actionId}}))}}class yO{client;session;id;constructor($,O,j){this.client=$;this.session=O;this.id=j}static byId($,O,j){return new yO($,O,j)}async answer($){return Q(await this.client.agentHarness.answerAgentSessionToolApproval({path:{session_id:this.session.id,approval_id:this.id},body:{answer:$}}))}toJSON(){return{id:this.id,sessionId:this.session.id}}}class i extends M{access=new o(this.client,"agent_session",this);toolApprovalById($){return yO.byId(this.client,this,$)}async sharePermissions(){return Q(await this.client.agentHarness.getAgentSessionPermissions({path:{session_id:this.id}}))}async updateSharePermissions($){return this.mutate((O)=>O.agentHarness.updateAgentSessionPermissions({path:{session_id:this.id},body:p$($)}))}static byId($,O){return new i($,O)}static async createManaged($,O){let{session:j}=Q(await $.agentHarness.createAgentSession({body:{prompt:O?.prompt,instructions:O?.instructions,model:O?.model,repoUrl:O?.repoUrl,repoBranch:O?.repoBranch}}));return new i($,j.id,j)}static async repositories($){let{repositories:O}=Q(await $.agentHarness.listAgentRepositories());return O.map((j)=>({url:j.url,defaultBranch:j.defaultBranch??void 0}))}static async repositoryBranches($,O){let{branches:j}=Q(await $.agentHarness.listAgentRepositoryBranches({query:{repoUrl:O}}));return j}async fetch(){return Q(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:j}=Q(await $.agentHarness.agentSessionsForPullRequest({body:{url:O}}));return j.map((x)=>i.byId($,x))}async pullRequests(){let{pullRequests:$}=Q(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?A.byId(this.client,O.linkedBy):void 0,createdAt:O.createdAt}))}async linkPullRequest($){Q(await this.client.agentHarness.linkAgentSessionPullRequest({path:{session_id:this.id},body:{url:$}}))}async unlinkPullRequest($){Q(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((j)=>j.agentHarness.putAgentSessionSandboxSize({path:{session_id:this.id},body:{size:$}}));return O}static async defaultSandboxSize($){return Q(await $.agentHarness.getAgentSandboxSize()).size}static async setDefaultSandboxSize($,O){return Q(await $.agentHarness.putAgentSandboxSize({body:{size:O}})).size}static async codingPreferences($){return Q(await $.agentHarness.getAgentCodingPreferences())}static async setCodingPreferences($,O){return Q(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:$}=Q(await this.client.agentHarness.getAgentSessionQueue({path:{session_id:this.id}}));return $.map((O)=>Yj.from(this.client,this.id,O))}async changes(){return Q(await this.client.agentHarness.getAgentSessionChanges({path:{session_id:this.id}}))}async changesPatch(){return Q(await this.client.agentHarness.getAgentSessionChangesPatch({path:{session_id:this.id}})).patch}async refreshChanges(){return this.mutate(($)=>$.agentHarness.refreshAgentSessionChanges({path:{session_id:this.id}}))}async foldedLog(){let{bot:$,messages:O}=Q(await this.client.agentHarness.getAgentSessionFoldedLog({path:{session_id:this.id}}));return{bot:$,messages:O}}async log(){return Q(await this.client.agentHarness.getAgentSessionLog({path:{session_id:this.id}}))}reviews={create:($)=>U$.createForSession(this.client,this,$),byId:($)=>U$.byId(this.client,this,$)};codeExecutions={byId:($)=>kO.byId(this.client,this,$)};async delete(){await this.mutate(($)=>$.agentHarness.deleteAgentSession({path:{session_id:this.id}}))}}class fx{client;constructor($){this.client=$}byId($){return i.byId(this.client,$)}createManaged($){return i.createManaged(this.client,$)}repositories(){return i.repositories(this.client)}repositoryBranches($){return i.repositoryBranches(this.client,$)}forPullRequest($){return i.forPullRequest(this.client,$)}defaultSandboxSize(){return i.defaultSandboxSize(this.client)}setDefaultSandboxSize($){return i.setDefaultSandboxSize(this.client,$)}codingPreferences(){return i.codingPreferences(this.client)}setCodingPreferences($){return i.setCodingPreferences(this.client,$)}}class bx{client;constructor($){this.client=$}byId($){return z$.byId(this.client,$)}async list(){return Q(await this.client.storage.listAgents()).map(($)=>z$.from(this.client,$))}async create($){return z$.from(this.client,Q(await this.client.storage.createAgent({body:Ex($)})))}}class gx{client;async usage($={}){let{users:O,...j}=$;return Q(await this.client.cognition.getUsageHandler({body:{...j,include_users:O?.map((x)=>x.id)}}))}constructor($){this.client=$}async structuredCompletion($){return Q(await this.client.cognition.structuredCompletion({body:$}))}async decide($){return Q(await this.client.cognition.decisions({body:$}))}}class a$ extends M{static byId($,O){return new a$($,O)}static from($,O){return new a$($,O.id,{id:O.id,name:O.name,createdAt:O.createdAt})}async fetch(){let $=Q(await this.client.storage.listUserApiKeys()).keys.find((O)=>O.id===this.id);if(!$)throw new E(`API key ${this.id} is unavailable`);return $}name=this.field("name");createdAt=this.field("createdAt");async delete(){await this.mutate(($)=>$.storage.deleteUserApiKey({path:{id:this.id}}))}}class kx{client;constructor($){this.client=$}byId($){return a$.byId(this.client,$)}async list(){return Q(await this.client.storage.listUserApiKeys()).keys.map(($)=>a$.from(this.client,$))}async create($){let O=Q(await this.client.storage.createUserApiKey({body:{name:$}}));return{key:a$.from(this.client,O),secret:O.key}}async tokenForEmail($){return Q(await this.client.auth.macroApiToken({query:{email:$}}))}}class vO{client;constructor($){this.client=$}async me(){if(this.client.authConfig.type!=="bot")throw new f("bots.me() requires bot auth — a user API key has no bot identity");return Q(await this.client.storage.getSelfBot())}async channels(){if(this.client.authConfig.type!=="bot")throw new f("bots.channels() requires bot auth — a user API key has no bot identity");let $=await this.me();return Q(await this.client.storage.listBotChannels({path:{bot_id:$.id}}))}async myPrincipalId(){if(this.client.authConfig.type!=="bot")throw new f("bots.myPrincipalId() requires bot auth — a user API key has no bot identity");return this.client.myPrincipalId()}}class x$ extends M{async fetch(){let O=Q(await this.client.auth.getUserTeams()).find((j)=>j.id===this.id);if(!O)throw new E(`team ${this.id} not found`);return O}static byId($,O){return new x$($,O)}static async current($){let O=Q(await $.auth.getTeam());if(!O)throw new E("caller has no current team");return new x$($,O.team.id,O.team)}static async list($){return Q(await $.auth.getUserTeams()).map((j)=>new x$($,j.id,j))}name=this.field("name");slug=this.field("slug");defaultLinkShare=this.field("default_link_share");owner=this.mappedField("owner_id",($)=>A.byId(this.client,$));async members(){let $=Q(await this.client.auth.getTeam());if(!$||$.team.id!==this.id)throw new f("members are only available for the current team (see Team.current)");return $.members.map((O)=>({user:A.byId(this.client,O.user_id),role:O.role}))}}class I$ extends M{async fetch(){let{links:$}=Q(await this.client.email.listLinks()),O=$.find((j)=>j.id===this.id);if(!O)throw new E(`email link ${this.id} not found`);return O}static byId($,O){return new I$($,O)}static async list($){let{links:O}=Q(await $.email.listLinks());return O.map((j)=>new I$($,j.id,j))}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");async settingsOperations(){return Q(await this.client.email.mailboxSettingsOperations({headers:{"X-Email-Link-Id":this.id}}))}}class v$ extends M{async setContributesToAvailability($){await this.mutate((O)=>O.calendar.setAvailabilityCalendar({path:{calendar_id:this.id},body:{contributesToAvailability:$}}))}async fetch(){let{calendars:$}=Q(await this.client.calendar.listCalendars()),O=$.find((j)=>j.id===this.id);if(!O)throw new E(`calendar ${this.id} not found`);return O}static byId($,O){return new v$($,O)}static async list($){let{calendars:O}=Q(await $.calendar.listCalendars());return O.map((j)=>new v$($,j.id,j))}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",($)=>I$.byId(this.client,$))}class hO{client;id;constructor($,O){this.client=$;this.id=O}async status(){return Q(await this.client.calendar.calendarReplacementStatus({path:{operation_id:this.id}}))}async confirm(){return Q(await this.client.calendar.confirmCalendarReplacement({path:{operation_id:this.id}}))}async discard(){Q(await this.client.calendar.discardCalendarReplacement({path:{operation_id:this.id}}))}}class S$ extends M{async notes($){return this.requireOwnOccurrence($),Q(await this.client.calendar.eventNotes({path:{event_id:this.id},query:{occurrenceKey:$.occurrenceKey}})).map((j)=>w$.fromRecord(this.client,this,$,j))}async linkNote($,O,j={}){return this.requireOwnOccurrence(O),Q(await this.client.calendar.linkEventNote({path:{event_id:this.id,document_id:$.id},query:{occurrenceKey:O.occurrenceKey},body:{teamId:j.team?.id??null}})),w$.forDocument(this.client,this,O,$)}requireOwnOccurrence($){if($.eventId!==this.id)throw new f("The occurrence belongs to a different event")}async fetch(){throw new f(`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 S$($,O)}static fromRecord($,O){return new S$($,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");guestPolicy=this.field("guestPolicy");viewerCan=this.field("viewerCan");calendar=this.mappedField("calendarId",($)=>$?v$.byId(this.client,$):void 0);record(){return this.detail.get()}async update($){let O=await this.mutate((j)=>j.calendar.updateCalendarEvent({path:{event_id:this.id},body:F6($)}));return S$.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 prepareReplacement($){let O=Q(await this.client.calendar.prepareCalendarReplacement({path:{event_id:this.id},body:{removeConference:$.removeConference,recurrenceId:$.recurrenceId,calendarId:$.calendar?.id}}));return new hO(this.client,O.operationId)}async providerUrl($={}){return Q(await this.client.calendar.calendarEventProviderUrl({path:{event_id:this.id},query:{recurrenceId:$.recurrenceId,calendarId:$.calendar?.id}})).url??void 0}async inviteGuests($){let O=await this.mutate((j)=>j.calendar.inviteCalendarEventGuests({path:{event_id:this.id},body:{guests:$.guests,scope:$.scope,recurrenceId:$.recurrenceId,calendarId:$.calendar?.id}}));return S$.fromRecord(this.client,O)}async addToCalendar($={}){let O=await this.mutate((j)=>j.calendar.copyCalendarEvent({path:{event_id:this.id},body:{calendarId:$.calendar?.id}}));return S$.fromRecord(this.client,O)}async ics(){return Q(await this.client.storage.eventIcs({path:{event_id:this.id}}))}async rsvp($){let O=await this.mutate((j)=>j.calendar.rsvpCalendarEvent({path:{event_id:this.id},body:{response:$.response,scope:$.scope,recurrenceId:$.recurrenceId,calendarId:$.calendar?.id}}));return S$.fromRecord(this.client,O)}}function F6($){return{title:$.title,description:$.description,location:$.location,time:$.time,attendees:$.attendees,recurrenceLines:$.recurrenceLines,visibility:$.visibility,transparency:$.transparency,reminders:$.reminders,conference:$.conference,outOfOffice:$.outOfOffice,guestPolicy:$.guestPolicy,scope:$.scope,recurrenceId:$.recurrenceId,calendarId:$.calendar?.id}}class w$ extends M{event;occurrence;fromDocument;constructor($,O,j,x,S,K=!1){super($,x.id,S);this.event=O;this.occurrence=j;this.fromDocument=K;if(j.eventId!==O.id)throw new f("Choose an occurrence belonging to this event")}static fromDocumentLink($,O,j){return new w$($,S$.byId($,j.eventId),j,O,{documentId:O.id,name:j.documentName,team:j.team,canManage:!0},!0)}static forDocument($,O,j,x){return new w$($,O,j,x)}static fromRecord($,O,j,x){return new w$($,O,j,q.byId($,x.documentId),x)}async fetch(){if(this.fromDocument){let x=Q(await this.client.calendar.documentNoteLinks({path:{document_id:this.id}})).find((S)=>S.eventId===this.event.id&&S.occurrenceKey===this.occurrence.occurrenceKey);if(!x)throw new E("This meeting link has been removed");return{documentId:this.id,name:x.documentName,team:x.team,canManage:!0}}let O=Q(await this.client.calendar.eventNotes({path:{event_id:this.event.id},query:{occurrenceKey:this.occurrence.occurrenceKey}})).find((j)=>j.documentId===this.id);if(!O)throw new E("This document is no longer linked to the meeting");return O}document=this.mappedField("documentId",($)=>q.byId(this.client,$));name=this.field("name");team=this.mappedField("team",($)=>$?x$.byId(this.client,$.id):void 0);canManage=this.field("canManage");async setTeam($){await this.mutate((O)=>O.calendar.linkEventNote({path:{event_id:this.event.id,document_id:this.id},query:{occurrenceKey:this.occurrence.occurrenceKey},body:{teamId:$?.id??null}}))}async unlink(){await this.mutate(($)=>$.calendar.unlinkEventNote({path:{event_id:this.event.id,document_id:this.id},query:{occurrenceKey:this.occurrence.occurrenceKey}}))}}class n extends X${async sharePermissions(){return Q(await this.client.storage.getProjectPermissionsV2({path:{id:this.id}}))}async accessLevel(){return Q(await this.client.storage.getProjectUserAccessLevel({path:{id:this.id}}))}access=new o(this.client,"project",this);entityType="project";propertyEntityType="PROJECT";async fetch(){let{data:$}=Q(await this.client.storage.getProjectHandler({path:{id:this.id}}));return $.projectMetadata}static byId($,O){return new n($,O)}static async create($,O){let{data:j}=Q(await $.storage.createProjectHandler({body:{name:O.name,projectParentId:O.parent?.id??null}}));return new n($,j.id,j)}name=this.field("name");parent=this.mappedField("parentId",($)=>$?n.byId(this.client,$):void 0);createdAt=this.field("createdAt");async items(){let{data:$}=Q(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=j$({filters:{project_filters:{}},type:"project",make:($,O)=>new n($,O.id)})}class GO extends M{document;toJSON(){return{...super.toJSON(),documentId:this.document.id}}constructor($,O,j,x){super($,j,x);this.document=O}static byId($,O,j){return new GO($,O,j)}static from($,O,j){return new GO($,O,j.uuid,j)}async fetch(){let $=Q(await this.client.storage.getDocumentAnchors({path:{document_id:this.document.id}})).data.find((O)=>O.uuid===this.id);if(!$)throw new E(`Annotation ${this.id} is unavailable`);return $}kind=this.field("anchorType");page=this.field("page");async edit($){if(await this.kind()!=="placeable")throw Error("Only placeable comment annotations can be edited");await this.mutate((O)=>O.storage.editAnchor({body:{...$,uuid:this.id,anchorType:"free-comment",fileType:"pdf"}}))}async delete(){if(await this.kind()!=="highlight")throw Error("Only standalone highlights can be deleted with this endpoint");await this.mutate(($)=>$.storage.deleteAnchor({body:{uuid:this.id,anchorType:"highlight",fileType:"pdf"}}))}}class h$ extends M{documentId;constructor($,O,j,x){super($,j,x);this.documentId=O}get path(){return{parent_type:"document",parent_id:this.documentId,id:this.id}}async fetch(){return Q(await this.client.storage.entityMessageGetMessage({path:this.path}))}static byId($,O,j){return new h$($,O,j)}static from($,O,j){return new h$($,O,j.id,j)}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 q.byId(this.client,this.documentId)}async author(){return A.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:j}=$$($);return await this.mutate((x)=>x.storage.entityMessageEdit({path:this.path,body:{content:O,mentions:j}})),this}async delete(){await this.mutate(($)=>$.storage.entityMessageDeleteMessage({path:this.path}))}}class mO{client;document;id;detail;constructor($,O,j){this.client=$;this.document=O;this.id=j;this.detail=new W$(async()=>Q(await this.client.storage.getDocumentVersion({path:{document_id:O.id,document_version_id:j}})).data)}static byId($,O,j){return new mO($,O,j)}read(){return this.detail.get()}toJSON(){return{id:this.id,documentId:this.document.id}}}var E6=8;class q extends X${async meetingNotes(){return Q(await this.client.calendar.documentNoteLinks({path:{document_id:this.id}})).map((O)=>({note:w$.fromDocumentLink(this.client,this,O),eventTitle:O.eventTitle}))}async anchors(){return Q(await this.client.storage.getDocumentAnchors({path:{document_id:this.id}})).data.map(($)=>GO.from(this.client,this,$))}async createHighlight($){return GO.from(this.client,this,Q(await this.client.storage.createAnchor({path:{document_id:this.id},body:{...$,fileType:"pdf",anchorType:"highlight"}})))}version($){return mO.byId(this.client,this,$)}async sharePermissions(){return Q(await this.client.storage.getDocumentPermissionsV2({path:{document_id:this.id}})).documentPermissions}async permissionsToken(){return Q(await this.client.storage.getDocumentPermissionsToken({path:{document_id:this.id}})).token}async prepareSave($){return Q(await this.client.storage.presaveDocumentHandler({path:{document_id:this.id},body:{newBom:$}})).data}async save($){return(await this.mutate((O)=>O.storage.saveDocumentHandler({path:{document_id:this.id},body:$}))).data}async simpleSave(){return(await this.mutate(($)=>$.storage.simpleSave({path:{document_id:this.id}}))).data}messageThreadById($){return L$.byId(this.client,{type:"document",entity:this},$)}timelinePage($){return E$(this.client,{type:"document",entity:this},(O)=>h$.from(this.client,this.id,O),$)}access=new o(this.client,"document",this);async fetch(){let{data:$}=Q(await this.client.storage.getDocument({path:{document_id:this.id}}));return $.documentMetadata}static byId($,O){return new q($,O)}static async create($,O){let{documentId:j}=Q(await $.storage.createMarkdownHandler({body:{documentName:O.name,markdown:O.markdown??null,projectId:O.project?.id??null}}));return new q($,j)}static async createSnippet($,O){let{documentId:j}=Q(await $.storage.createSnippetHandler({body:{snippetName:O.name,markdown:O.markdown??null,projectId:O.project?.id??null}}));return new q($,j)}static async createSkill($,O){let{documentId:j}=Q(await $.storage.createSkillHandler({body:{skillName:O.name,markdown:O.markdown??null,projectId:O.project?.id??null}}));return new q($,j)}static recent($,O){let j=O?.pageSize??50;return a(async(x)=>{let S=Q(await $.storage.getUserDocumentsHandler({query:{limit:j,offset:x?Number(x):0,...O?.fileType!==void 0?{file_type:O.fileType}:{}}})),K=S.data?.next_offset;return{items:(S.data?.documents??[]).map((Z)=>new q($,Z.documentId)),nextCursor:K!=null?String(K):null}})}static async recentlyDeleted($){let{data:O}=Q(await $.storage.recentlyDeleted({}));return O.items.filter((j)=>j.type==="document").map((j)=>new q($,j.id))}entityType="document";propertyEntityType="DOCUMENT";name=this.field("documentName");fileType=this.field("fileType");project=this.mappedField("projectId",($)=>$?n.byId(this.client,$):void 0);owner=this.mappedField("owner",($)=>A.byId(this.client,$));branchedFrom=this.mappedField("branchedFromId",($)=>$?q.byId(this.client,$):void 0);createdAt=this.field("createdAt");updatedAt=this.field("updatedAt");deletedAt=this.field("deletedAt");async content(){let{text:$}=Q(await this.client.storage.getDocumentTextContent({path:{document_id:this.id}}));if($!==null)return $;let{presigned_url:O}=Q(await this.client.storage.exportDocument({path:{document_id:this.id}})),j=await fetch(O);if(!j.ok)throw new ZO(j.status,{message:"failed to download document content"});return j.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}=Q(await this.client.storage.copyDocument({path:{document_id:this.id},query:$.versionId!==void 0?{version_id:$.versionId}:void 0,body:{documentName:$.name}}));return new q(this.client,O.documentMetadata.documentId)}async comments(){let $={parent_type:"document",parent_id:this.id},O=a(async(x)=>{let S=Q(await this.client.storage.messageTimeline({path:$,query:{selection:JSON.stringify({limit:100,cursor:x})}}));return{items:S.items,nextCursor:S.next_cursor}}),j=[];for await(let x of O)j.push(x);return gO(j,E6,async(x)=>{let{state:S,root:K,replies:Z}=Q(await this.client.storage.entityMessageGetThread({path:{...$,id:x.id}}));return{thread:S,comments:[K,...Z].map((X)=>h$.from(this.client,this.id,X))}})}async comment($,O){let j=await this.mutate((x)=>x.storage.entityMessageCreate({path:{parent_type:"document",parent_id:this.id},body:{...$$($),thread_id:O?.threadId??null}}));return h$.from(this.client,this.id,j)}async shortId(){return Q(await this.client.storage.getDocumentShortId({path:{document_id:this.id}}))}async teamShare(){return Q(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:$}=Q(await this.client.storage.getDocumentGithubPullRequests({path:{document_id:this.id}}));return $}async branchName(){let{branchName:$}=Q(await this.client.storage.getDocumentBranchName({path:{document_id:this.id}}));return $}webUrl(){return`${this.client.webAppUrl}/app/md/${this.id}`}static search=j$({filters:{document_filters:{}},type:"document",make:($,O)=>new q($,O.document_id)});toMention(){let $=this.detail.peek();return{tag:r$("m-document-mention",{documentId:this.id,documentName:$?.documentName??"",blockName:$?.fileType??"md"}),mention:{entity_type:"document",entity_id:this.id}}}}class yx{client;async noteDocuments($=""){let O=Q(await this.client.calendar.noteDocuments({query:{query:$}}));return{documents:O.documents.map((j)=>({document:q.byId(this.client,j.documentId),name:j.name})),teams:O.teams.map((j)=>({team:x$.byId(this.client,j.id),name:j.name}))}}async availabilityCalendars(){return Q(await this.client.calendar.getAvailabilityCalendars()).calendars.map(($)=>({calendar:v$.byId(this.client,$.calendarId),name:$.name,isPrimary:$.isPrimary,contributesToAvailability:$.contributesToAvailability}))}async teamSharing(){return Q(await this.client.calendar.getTeamSharing()).sharing}async setTeamSharing($){return Q(await this.client.calendar.setTeamSharing({body:{sharing:$}})).sharing}occurrences($){return a(async(O)=>{let j=Q(await this.client.storage.listOccurrences({query:{...$,cursor:O}}));return{items:j.items.map((x)=>({event:S$.fromRecord(this.client,x.event),occurrence:x.occurrence})),nextCursor:j.nextCursor}})}async teamPage($){let O=Q(await this.client.storage.listTeamCalendar({query:$}));return{items:O.items.map(({ownerId:j,...x})=>({...x,owner:A.byId(this.client,j)})),members:O.members.map((j)=>({user:A.byId(this.client,j.userId),sharing:j.sharing,coverage:j.coverage})),nextCursor:O.nextCursor??void 0}}async teamOutOfOffice($){let O=Q(await this.client.storage.listTeamOutOfOffice({query:$}));return{items:O.items.map((j)=>({event:S$.byId(this.client,j.eventId),owner:A.byId(this.client,j.ownerId),occurrenceKey:j.occurrenceKey,time:j.time,title:j.title??void 0})),hasMore:O.hasMore}}constructor($){this.client=$}calendars(){return v$.list(this.client)}calendar($){return v$.byId(this.client,$)}event($){return S$.byId(this.client,$)}replacement($){return new hO(this.client,$)}async createEvent($){let O=Q(await this.client.calendar.createCalendarEvent({body:w6($)}));return S$.fromRecord(this.client,O)}}function w6($){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,guestPolicy:$.guestPolicy,calendarId:$.calendar?.id,emailLinkId:$.emailLink?.id}}class T$ extends M{lookupToken;constructor($,O,j){super($,O,j);this.lookupToken=j?.shareToken}static byId($,O){return new T$($,O)}static from($,O){return new T$($,O.id,O)}async fetch(){if(this.lookupToken)return Q(await this.client.storage.meetingLookup({path:{token:this.lookupToken}}));let $=Q(await this.client.storage.meetingList()).meetings.find((O)=>O.id===this.id);if(!$)throw new E(`Meeting ${this.id} is unavailable`);return this.lookupToken=$.shareToken,$}title=this.field("title");scheduledStart=this.field("scheduledStart");scheduledEnd=this.field("scheduledEnd");channel=this.mappedField("channelId",($)=>$?b.byId(this.client,$):void 0);call=this.mappedField("callId",($)=>$?Q$.byId(this.client,$):void 0);async update($){await this.mutate((O)=>O.storage.meetingUpdate({path:{meeting_id:this.id},body:$}))}async cancel(){await this.mutate(($)=>$.storage.meetingCancel({path:{meeting_id:this.id}}))}async invitePermissions(){return Q(await this.client.storage.meetingInvitePermissions({path:{token:(await this.detail.get()).shareToken}}))}async invite($){Q(await this.client.storage.meetingInvite({path:{token:(await this.detail.get()).shareToken},body:{email:$}}))}async inviteUsers($){Q(await this.client.storage.meetingInviteUsers({path:{token:(await this.detail.get()).shareToken},body:{userIds:$.map((O)=>O.id)}}))}async webUrl(){return`${this.client.webAppUrl}/app/meet/join/${encodeURIComponent((await this.detail.get()).shareToken)}`}}class m$ extends M{callId;constructor($,O,j,x){super($,j,x);this.callId=O}get path(){return{parent_type:"call",parent_id:this.callId,id:this.id}}async fetch(){return Q(await this.client.storage.entityMessageGetMessage({path:this.path}))}static byId($,O,j){return new m$($,O,j)}static from($,O,j){return new m$($,O,j.id,j)}content=this.field("content");createdAt=this.field("created_at");updatedAt=this.field("updated_at");call(){return Q$.byId(this.client,this.callId)}async author(){return A.byId(this.client,(await this.detail.get()).sender_id)}async reply($){let O=Q(await this.client.storage.entityMessageCreate({path:{parent_type:"call",parent_id:this.callId},body:{...$$($),thread_id:this.callId}}));return m$.from(this.client,this.callId,O)}async edit($){let{content:O,mentions:j}=$$($);return await this.mutate((x)=>x.storage.entityMessageEdit({path:this.path,body:{content:O,mentions:j}})),this}async delete(){await this.mutate(($)=>$.storage.entityMessageDeleteMessage({path:this.path}))}}class Q$ extends F${messageThreadById($){return L$.byId(this.client,{type:"call",entity:this},$)}timelinePage($){return E$(this.client,{type:"call",entity:this},(O)=>m$.from(this.client,this.id,O),$)}access=new o(this.client,"call",this);async meeting(){return T$.from(this.client,Q(await this.client.storage.meetingShare({path:{call_id:this.id}})))}async editTranscript($){await this.mutate((O)=>O.storage.editCallTranscript({path:{call_id:this.id},body:{assignments:$}}))}async toggleTeamShare(){return this.mutate(($)=>$.storage.toggleShareWithTeam({path:{call_id:this.id}}))}entityType="call";async fetch(){return Q(await this.client.storage.getCallRecord({path:{call_id:this.id}}))}static byId($,O){return new Q$($,O)}message($){return m$.byId(this.client,this.id,$)}name=this.field("customName");channel=this.mappedField("channelId",($)=>$?b.byId(this.client,$):void 0);channelName=this.field("channelName");creator=this.mappedField("createdBy",($)=>A.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=j$({filters:{call_filters:{}},type:"call",make:($,O)=>new Q$($,O.call_id)})}class vx{client;constructor($){this.client=$}byId($){return Q$.byId(this.client,$)}search($,O){return Q$.search(this.client,$,O)}}class hx{client;constructor($){this.client=$}async list(){let{labels:$}=Q(await this.client.storage.listChannelLabels());return $}async create($,O=[]){return Q(await this.client.storage.createChannelLabel({body:{name:$,channelIds:O.map((j)=>j.id)}}))}async createSmartTag($,O){return Q(await this.client.storage.createChannelLabel({body:{name:$,rule:O}}))}async previewSmartTag($){return Q(await this.client.storage.previewSmartTag({body:$}))}async updateSmartTag($,O,j){return Q(await this.client.storage.renameChannelLabel({path:{label_id:$.id},body:{name:O,rule:j}}))}async rename($,O){return Q(await this.client.storage.renameChannelLabel({path:{label_id:$.id},body:{name:O}}))}async delete($){Q(await this.client.storage.deleteChannelLabel({path:{label_id:$.id}}))}async setLabel($,O){Q(await this.client.storage.setChannelLabel({path:{channel_id:$.id},body:{labelId:O?.id??null}}))}}class mx{client;async activity(){return Q(await this.client.storage.getActivity()).map(($)=>new XO(this.client,b.byId(this.client,$.channel_id),$))}labels;constructor($){this.client=$;this.labels=new hx($)}byId($){return b.byId(this.client,$)}async dm($){return b.dm(this.client,$)}async private($){return b.private(this.client,$)}async create($){return b.create(this.client,$)}async list(){let{items:$}=Q(await this.client.storage.getChannels());return $.map((O)=>b.byId(this.client,O.id.toString()))}async*search($,O){if(!O?.searchOn||O.searchOn==="name"){let{items:j}=Q(await this.client.storage.getChannels()),x=$.toLowerCase();for(let S of j)if(S.name?.toLowerCase().includes(x))yield b.byId(this.client,S.id.toString())}else yield*b.search(this.client,$,O)}}class cO{client;chat;id;message;constructor($,O,j,x){this.client=$;this.chat=O;this.id=j;this.message=x}static byId($,O,j,x){return new cO($,O,j,x)}async stop(){Q(await this.client.cognition.stopChatStream({body:{chat_id:this.chat.id,stream_id:this.id}}))}toJSON(){return{id:this.id,chatId:this.chat.id,messageId:this.message.id}}}class uO extends M{chat;constructor($,O,j){super($,j);this.chat=O}static byId($,O,j){return new uO($,O,j)}async fetch(){let $=Q(await this.client.cognition.getChat({path:{chat_id:this.chat.id}})).chat.messages.find((O)=>O.id===this.id);if(!$)throw new E(`Chat message ${this.id} is not yet available`);return $}content=this.field("content");role=this.field("role");async refresh(){this.detail.clear(),await this.detail.get()}toJSON(){return{...super.toJSON(),chatId:this.chat.id}}}class G$ extends X${async send($){let{attachments:O,additionalInstructions:j,...x}=$,S=await this.mutate((Z)=>Z.cognition.sendChatMessage({body:{...x,chat_id:this.id,additional_instructions:j,attachments:O?.map((X)=>({entity_id:X.entity.id,entity_type:X.type}))}})),K=G$.byId(this.client,S.chat_id);return cO.byId(this.client,K,S.stream_id,uO.byId(this.client,K,S.message_id))}access=new o(this.client,"chat",this);entityType="chat";propertyEntityType="CHAT";async fetch(){let{chat:$}=Q(await this.client.cognition.getChat({path:{chat_id:this.id}}));return $}static byId($,O){return new G$($,O)}static async create($,O){let{id:j}=Q(await $.cognition.createChat({body:{name:O?.name??null,projectId:O?.project?.id??null}}));return new G$($,j)}name=this.field("name");model=this.field("model");project=this.mappedField("projectId",($)=>$?n.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 G$(this.client,$)}async restore(){await this.mutate(($)=>$.cognition.revertDeleteChat({path:{chat_id:this.id}}))}async history(){let{conversation:$}=Q(await this.client.cognition.getChatHistoryHandler({path:{chat_id:this.id}}));return $}webUrl(){return`${this.client.webAppUrl}/app/chat/${this.id}`}static search=j$({filters:{chat_filters:{}},type:"chat",make:($,O)=>new G$($,O.chat_id)});toMention(){return{tag:r$("m-document-mention",{documentId:this.id,documentName:this.detail.peek()?.name??"",blockName:"chat",blockParams:{}}),mention:{entity_type:"chat",entity_id:this.id}}}}class cx{client;constructor($){this.client=$}byId($){return G$.byId(this.client,$)}create($){return G$.create(this.client,$)}search($,O){return G$.search(this.client,$,O)}}var q6=8;class _$ extends M{parent;constructor($,O,j,x){super($,j,x);this.parent=O}get path(){return{parent_type:this.parent.type,parent_id:this.parent.id,id:this.id}}async fetch(){return Q(await this.client.storage.entityMessageGetMessage({path:this.path}))}static byId($,O,j){return new _$($,O,j)}static from($,O,j){return new _$($,O,j.id,j)}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 A.byId(this.client,(await this.detail.get()).sender_id)}async reply($){return dO(this.client,this.parent,$,{threadId:await this.threadId()})}async edit($){let{content:O,mentions:j}=$$($);return await this.mutate((x)=>x.storage.entityMessageEdit({path:this.path,body:{content:O,mentions:j}})),this}async delete(){await this.mutate(($)=>$.storage.entityMessageDeleteMessage({path:this.path}))}}async function Qj($,O){let j={parent_type:O.type,parent_id:O.id},x=a(async(K)=>{let Z=Q(await $.storage.messageTimeline({path:j,query:{selection:JSON.stringify({limit:100,cursor:K})}}));return{items:Z.items,nextCursor:Z.next_cursor}}),S=[];for await(let K of x)S.push(K);return gO(S,q6,async(K)=>{let{state:Z,root:X,replies:G}=Q(await $.storage.entityMessageGetThread({path:{...j,id:K.id}}));return{thread:Z,comments:[X,...G].map((L)=>_$.from($,O,L))}})}async function dO($,O,j,x){let S=Q(await $.storage.entityMessageCreate({path:{parent_type:O.type,parent_id:O.id},body:{...$$(j),thread_id:x?.threadId??null}}));return _$.from($,O,S)}class q$ extends F${messageThreadById($){return L$.byId(this.client,{type:"crm_contact",entity:this},$)}timelinePage($){return E$(this.client,{type:"crm_contact",entity:this},(O)=>_$.from(this.client,{type:"crm_contact",id:this.id},O),$)}entityType="crm_contact";async fetch(){return Q(await this.client.storage.getContact({path:{contact_id:this.id}}))}static byId($,O){return new q$($,O)}static from($,O){return new q$($,O.id,O)}name=this.field("name");email=this.field("email");company=this.mappedField("companyId",($)=>f$.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 Qj(this.client,this.commentParent)}async comment($,O){return dO(this.client,this.commentParent,$,O)}commentById($){return _$.byId(this.client,this.commentParent,$)}}class f$ extends X${messageThreadById($){return L$.byId(this.client,{type:"crm_company",entity:this},$)}timelinePage($){return E$(this.client,{type:"crm_company",entity:this},(O)=>_$.from(this.client,{type:"crm_company",id:this.id},O),$)}entityType="crm_company";propertyEntityType="COMPANY";async fetch(){return Q(await this.client.storage.getCompany({path:{company_id:this.id}}))}static byId($,O){return new f$($,O)}static from($,O){return new f$($,O.id,O)}name=this.field("name");description=this.field("description");hidden=this.field("hidden");emailSync=this.field("emailSync");team=this.mappedField("teamId",($)=>x$.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 Q(await this.client.storage.listCompanyContacts({path:{company_id:this.id}})).map((O)=>q$.from(this.client,O))}static search=j$({filters:{crm_company_filters:{}},type:"company",includeCrm:!0,make:($,O)=>new f$($,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((j)=>j.storage.createCrmContact({path:{company_id:this.id},body:$}));return q$.from(this.client,O)}get commentParent(){return{type:"crm_company",id:this.id}}async comments(){return Qj(this.client,this.commentParent)}async comment($,O){return dO(this.client,this.commentParent,$,O)}commentById($){return _$.byId(this.client,this.commentParent,$)}}class i$ extends M{tableDetail=new W$(async()=>Q(await this.client.storage.getCrmPipelineTable({path:{id:this.id}})));static byId($,O){return new i$($,O)}static from($,O){return new i$($,O.id,O)}async fetch(){return Q(await this.client.storage.getCrmPipeline({path:{id:this.id}}))}name=this.field("name");recordType=this.field("recordType");accessLevel=this.field("grant");sharing=this.field("sharing");owner=this.mappedField("userId",($)=>A.byId(this.client,$));team=this.mappedField("teamId",($)=>x$.byId(this.client,$));async rename($){await this.mutate((O)=>O.storage.renameCrmPipeline({path:{id:this.id},body:{name:$}}))}async setSharing($){if($===void 0)throw Error("Sharing is required");await this.mutate((O)=>O.storage.shareCrmPipeline({path:{id:this.id},body:{sharing:$}}))}async setTrashed($){await this.mutate((O)=>O.storage.trashCrmPipeline({path:{id:this.id},body:{trashed:$}}))}async sharePermissions(){return Q(await this.client.storage.getCrmPipelinePermissions({path:{id:this.id}}))}async updateSharePermissions($){return this.mutate((O)=>O.storage.updateCrmPipelinePermissions({path:{id:this.id},body:p$($)}))}async table(){return Jj.from(this.client,this,await this.tableRecord())}tableRecord(){return this.tableDetail.get()}rows(){return a(async($)=>{let O=Q(await this.client.storage.getCrmPipelineRows({path:{id:this.id},query:{after:$}}));return{items:O.rows.map((j)=>KO.from(this.client,this,j)),nextCursor:O.next}})}queryRows($={}){if($.rows?.some((O)=>O.pipeline.id!==this.id))throw Error("Rows belong to another pipeline");return a(async(O)=>{let j=Q(await this.client.storage.queryCrmPipelineRows({path:{id:this.id},body:{after:O,query:$.query,rowIds:$.rows?.map((x)=>x.id)}}));return{items:j.rows.map((x)=>KO.from(this.client,this,x)),nextCursor:j.next}})}async applyOps($,O){if(O?.baseVersions?.some((S)=>S.table.pipeline.id!==this.id))throw Error("Table belongs to another pipeline");let j={ops:$,baseVersions:O?.baseVersions?Object.fromEntries(O.baseVersions.map((S)=>[S.table.id,S.version])):void 0},x=await this.mutate((S)=>S.storage.applyCrmPipelineOps({path:{id:this.id},body:j}));return this.tableDetail.clear(),x}}class Jj extends M{pipeline;toJSON(){return{...super.toJSON(),pipelineId:this.pipeline.id}}constructor($,O,j){super($,j.table.id,j);this.pipeline=O}static from($,O,j){return new Jj($,O,j)}fetch(){return this.pipeline.tableRecord()}async columns(){return(await this.pipeline.tableRecord()).columns.map(($)=>Vj.from(this.client,this,$))}async version(){return(await this.pipeline.tableRecord()).table.version}rowById($){return KO.byId(this.client,this.pipeline,$)}rows(){return this.pipeline.rows()}}class KO extends M{pipeline;toJSON(){return{...super.toJSON(),pipelineId:this.pipeline.id}}constructor($,O,j,x){super($,j,x);this.pipeline=O}static byId($,O,j){return new KO($,O,j)}static from($,O,j){return new KO($,O,j.rowId,j)}async fetch(){for await(let $ of this.pipeline.queryRows({rows:[this]}))if($.id===this.id)return $.detail.get();throw new E(`Pipeline row ${this.id} is unavailable`)}cells=this.field("cells");async refresh(){this.detail.clear(),await this.detail.get()}}class Vj extends M{table;toJSON(){return{...super.toJSON(),pipelineId:this.table.pipeline.id,tableId:this.table.id}}constructor($,O,j){super($,j.column.id,j);this.table=O}static from($,O,j){return new Vj($,O,j)}async fetch(){let $=(await this.table.pipeline.tableRecord()).columns.find((O)=>O.column.id===this.id);if(!$)throw new E(`Pipeline column ${this.id} is unavailable`);return $}async writable(){return(await this.fetch()).writable}async name(){return(await this.fetch()).column.display_name??(await this.fetch()).definition.definition.display_name}}class ux{client;constructor($){this.client=$}byId($){return i$.byId(this.client,$)}async list(){return Q(await this.client.storage.listCrmPipelines()).map(($)=>i$.from(this.client,$))}async create($){return i$.from(this.client,Q(await this.client.storage.createCrmPipeline({body:$})))}}class dx{client;pipelines;constructor($){this.client=$;this.pipelines=new ux($)}companyById($){return f$.byId(this.client,$)}contactById($){return q$.byId(this.client,$)}async contactByEmail($){let{contact:O}=Q(await this.client.storage.getContactByEmail({query:{email:$}}));return O?q$.from(this.client,O):void 0}async searchContacts($,O={}){let{contacts:j}=Q(await this.client.storage.searchContacts({query:{query:$,limit:O.limit}}));return j.map((x)=>q$.from(this.client,x))}async createCompany($){return f$.from(this.client,Q(await this.client.storage.createCrmCompany({body:$})))}async settings(){return Q(await this.client.storage.getCrmTeamSettings())}async updateSettings($){return Q(await this.client.storage.putCrmTeamSettings({body:$}))}async setStages($){return Q(await this.client.storage.putCrmTeamStages({body:$}))}async resetStages(){Q(await this.client.storage.resetCrmTeamStages())}searchCompanies($){return f$.search(this.client,$)}}var Y$=Symbol.for("@ts-pattern/matcher"),F1=Symbol.for("@ts-pattern/isVariadic");var lx=($)=>Boolean($&&typeof $=="object"),Wj=($)=>$&&!!$[Y$],s=($,O,j)=>{if(Wj($)){let x=$[Y$](),{matched:S,selections:K}=x.match(O);return S&&K&&Object.keys(K).forEach((Z)=>j(Z,K[Z])),S}if(lx($)){if(!lx(O))return!1;if(Array.isArray($)){if(!Array.isArray(O))return!1;let x=[],S=[],K=[];for(let Z of $.keys()){let X=$[Z];Wj(X)&&X[F1]?K.push(X):K.length?S.push(X):x.push(X)}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<x.length+S.length)return!1;let Z=O.slice(0,x.length),X=S.length===0?[]:O.slice(-S.length),G=O.slice(x.length,S.length===0?1/0:-S.length);return x.every((L,Y)=>s(L,Z[Y],j))&&S.every((L,Y)=>s(L,X[Y],j))&&(K.length===0||s(K[0],G,j))}return $.length===O.length&&$.every((Z,X)=>s(Z,O[X],j))}return Reflect.ownKeys($).every((x)=>{let S=$[x];return((x in O)||Wj(K=S)&&K[Y$]().matcherType==="optional")&&s(S,O[x],j);var K})}return Object.is(O,$)},K$=($)=>{var O,j,x;return lx($)?Wj($)?(O=(j=(x=$[Y$]()).getSelectionKeys)==null?void 0:j.call(x))!=null?O:[]:Array.isArray($)?lO($,K$):lO(Object.values($),K$):[]},lO=($,O)=>$.reduce((j,x)=>j.concat(O(x)),[]);function f6(...$){if($.length===1){let[O]=$;return(j)=>s(O,j,()=>{})}if($.length===2){let[O,j]=$;return s(O,j,()=>{})}throw Error(`isMatching wasn't given the right number of arguments: expected 1 or 2, received ${$.length}.`)}function t($){return Object.assign($,{optional:()=>ax($),and:(O)=>u($,O),or:(O)=>E1($,O),select:(O)=>O===void 0?rO($):rO(O,$)})}function rx($){return Object.assign(((O)=>Object.assign(O,{[Symbol.iterator](){let j=0,x=[{value:Object.assign(O,{[F1]:!0}),done:!1},{done:!0,value:void 0}];return{next:()=>{var S;return(S=x[j++])!=null?S:x.at(-1)}}}}))($),{optional:()=>rx(ax($)),select:(O)=>rx(O===void 0?rO($):rO(O,$))})}function ax($){return t({[Y$]:()=>({match:(O)=>{let j={},x=(S,K)=>{j[S]=K};return O===void 0?(K$($).forEach((S)=>x(S,void 0)),{matched:!0,selections:j}):{matched:s($,O,x),selections:j}},getSelectionKeys:()=>K$($),matcherType:"optional"})})}var b6=($,O)=>{for(let j of $)if(!O(j))return!1;return!0},g6=($,O)=>{for(let[j,x]of $.entries())if(!O(x,j))return!1;return!0},k6=($,O)=>{let j=Reflect.ownKeys($);for(let x of j)if(!O(x,$[x]))return!1;return!0};function u(...$){return t({[Y$]:()=>({match:(O)=>{let j={},x=(S,K)=>{j[S]=K};return{matched:$.every((S)=>s(S,O,x)),selections:j}},getSelectionKeys:()=>lO($,K$),matcherType:"and"})})}function E1(...$){return t({[Y$]:()=>({match:(O)=>{let j={},x=(S,K)=>{j[S]=K};return lO($,K$).forEach((S)=>x(S,void 0)),{matched:$.some((S)=>s(S,O,x)),selections:j}},getSelectionKeys:()=>lO($,K$),matcherType:"or"})})}function m($){return{[Y$]:()=>({match:(O)=>({matched:Boolean($(O))})})}}function rO(...$){let O=typeof $[0]=="string"?$[0]:void 0,j=$.length===2?$[1]:typeof $[0]=="string"?void 0:$[0];return t({[Y$]:()=>({match:(x)=>{let S={[O!=null?O:"@ts-pattern/anonymous-select-key"]:x};return{matched:j===void 0||s(j,x,(K,Z)=>{S[K]=Z}),selections:S}},getSelectionKeys:()=>[O!=null?O:"@ts-pattern/anonymous-select-key"].concat(j===void 0?[]:K$(j))})})}function w1($){return!0}function b$($){return typeof $=="number"}function n$($){return typeof $=="string"}function s$($){return typeof $=="bigint"}var q1=t(m(w1)),y6=t(m(w1)),v6=q1,t$=($)=>Object.assign(t($),{startsWith:(O)=>{return t$(u($,(j=O,m((x)=>n$(x)&&x.startsWith(j)))));var j},endsWith:(O)=>{return t$(u($,(j=O,m((x)=>n$(x)&&x.endsWith(j)))));var j},minLength:(O)=>t$(u($,((j)=>m((x)=>n$(x)&&x.length>=j))(O))),length:(O)=>t$(u($,((j)=>m((x)=>n$(x)&&x.length===j))(O))),maxLength:(O)=>t$(u($,((j)=>m((x)=>n$(x)&&x.length<=j))(O))),includes:(O)=>{return t$(u($,(j=O,m((x)=>n$(x)&&x.includes(j)))));var j},regex:(O)=>{return t$(u($,(j=O,m((x)=>n$(x)&&Boolean(x.match(j))))));var j}}),P1=t$(m(n$)),g$=($)=>Object.assign(t($),{between:(O,j)=>g$(u($,((x,S)=>m((K)=>b$(K)&&x<=K&&S>=K))(O,j))),lt:(O)=>g$(u($,((j)=>m((x)=>b$(x)&&x<j))(O))),gt:(O)=>g$(u($,((j)=>m((x)=>b$(x)&&x>j))(O))),lte:(O)=>g$(u($,((j)=>m((x)=>b$(x)&&x<=j))(O))),gte:(O)=>g$(u($,((j)=>m((x)=>b$(x)&&x>=j))(O))),int:()=>g$(u($,m((O)=>b$(O)&&Number.isInteger(O)))),finite:()=>g$(u($,m((O)=>b$(O)&&Number.isFinite(O)))),positive:()=>g$(u($,m((O)=>b$(O)&&O>0))),negative:()=>g$(u($,m((O)=>b$(O)&&O<0)))}),h6=g$(m(b$)),e$=($)=>Object.assign(t($),{between:(O,j)=>e$(u($,((x,S)=>m((K)=>s$(K)&&x<=K&&S>=K))(O,j))),lt:(O)=>e$(u($,((j)=>m((x)=>s$(x)&&x<j))(O))),gt:(O)=>e$(u($,((j)=>m((x)=>s$(x)&&x>j))(O))),lte:(O)=>e$(u($,((j)=>m((x)=>s$(x)&&x<=j))(O))),gte:(O)=>e$(u($,((j)=>m((x)=>s$(x)&&x>=j))(O))),positive:()=>e$(u($,m((O)=>s$(O)&&O>0))),negative:()=>e$(u($,m((O)=>s$(O)&&O<0)))}),m6=e$(m(s$)),c6=t(m(function($){return typeof $=="boolean"})),u6=t(m(function($){return typeof $=="symbol"})),d6=t(m(function($){return $==null})),l6=t(m(function($){return $!=null})),Z$={__proto__:null,matcher:Y$,optional:ax,array:function(...$){return rx({[Y$]:()=>({match:(O)=>{if(!Array.isArray(O))return{matched:!1};if($.length===0)return{matched:!0};let j=$[0],x={};if(O.length===0)return K$(j).forEach((K)=>{x[K]=[]}),{matched:!0,selections:x};let S=(K,Z)=>{x[K]=(x[K]||[]).concat([Z])};return{matched:O.every((K)=>s(j,K,S)),selections:x}},getSelectionKeys:()=>$.length===0?[]:K$($[0])})})},set:function(...$){return t({[Y$]:()=>({match:(O)=>{if(!(O instanceof Set))return{matched:!1};let j={};if(O.size===0)return{matched:!0,selections:j};if($.length===0)return{matched:!0};let x=(K,Z)=>{j[K]=(j[K]||[]).concat([Z])},S=$[0];return{matched:b6(O,(K)=>s(S,K,x)),selections:j}},getSelectionKeys:()=>$.length===0?[]:K$($[0])})})},map:function(...$){return t({[Y$]:()=>({match:(O)=>{if(!(O instanceof Map))return{matched:!1};let j={};if(O.size===0)return{matched:!0,selections:j};let x=(X,G)=>{j[X]=(j[X]||[]).concat([G])};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,Z]=$;return{matched:g6(O,(X,G)=>{let L=s(K,G,x),Y=s(Z,X,x);return L&&Y}),selections:j}},getSelectionKeys:()=>$.length===0?[]:[...K$($[0]),...K$($[1])]})})},record:function(...$){return t({[Y$]:()=>({match:(O)=>{if(O===null||typeof O!="object"||Array.isArray(O))return{matched:!1};var j;if($.length===0)throw Error(`\`P.record\` wasn't given enough arguments. Expected (value) or (key, value), received ${(j=$[0])==null?void 0:j.toString()}`);let x={},S=(X,G)=>{x[X]=(x[X]||[]).concat([G])},[K,Z]=$.length===1?[P1,$[0]]:$;return{matched:k6(O,(X,G)=>{let L=typeof X!="string"||Number.isNaN(Number(X))?null:Number(X),Y=L!==null&&s(K,L,S),J=s(K,X,S),T=s(Z,G,S);return(J||Y)&&T}),selections:x}},getSelectionKeys:()=>$.length===0?[]:[...K$($[0]),...K$($[1])]})})},intersection:u,union:E1,not:function($){return t({[Y$]:()=>({match:(O)=>({matched:!s($,O,()=>{})}),getSelectionKeys:()=>[],matcherType:"not"})})},when:m,select:rO,any:q1,unknown:y6,_:v6,string:P1,number:h6,bigint:m6,boolean:c6,symbol:u6,nullish:d6,nonNullable:l6,instanceOf:function($){return t(m(function(O){return(j)=>j instanceof O}($)))},shape:function($){return t(m(f6($)))}};class f1 extends Error{constructor($){let O;try{O=JSON.stringify($)}catch(j){O=$}super(`Pattern matching error: no pattern matches value ${O}`),this.input=void 0,this.input=$}}var px={matched:!1,value:void 0};function c($){return new Bj($,px)}class Bj{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],j=[$[0]],x;$.length===3&&typeof $[1]=="function"?x=$[1]:$.length>2&&j.push(...$.slice(1,$.length-1));let S=!1,K={},Z=(G,L)=>{S=!0,K[G]=L},X=!j.some((G)=>s(G,this.input,Z))||x&&!Boolean(x(this.input))?px:{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 Bj(this.input,X)}when($,O){if(this.state.matched)return this;let j=Boolean($(this.input));return new Bj(this.input,j?{matched:!0,value:O(this.input,this.input)}:px)}otherwise($){return this.state.matched?this.state.value:$(this.input)}exhaustive($=r6){return this.state.matched?this.state.value:$(this.input)}run(){return this.exhaustive()}returnType(){return this}narrow(){return this}}function r6($){throw new f1($)}var ix,p6=new Uint8Array(16);function Lj(){if(!ix){if(typeof crypto>"u"||!crypto.getRandomValues)throw Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");ix=crypto.getRandomValues.bind(crypto)}return ix(p6)}var O$=[];for(let $=0;$<256;++$)O$.push(($+256).toString(16).slice(1));function b1($,O=0){return(O$[$[O+0]]+O$[$[O+1]]+O$[$[O+2]]+O$[$[O+3]]+"-"+O$[$[O+4]]+O$[$[O+5]]+"-"+O$[$[O+6]]+O$[$[O+7]]+"-"+O$[$[O+8]]+O$[$[O+9]]+"-"+O$[$[O+10]]+O$[$[O+11]]+O$[$[O+12]]+O$[$[O+13]]+O$[$[O+14]]+O$[$[O+15]]).toLowerCase()}var nx={};function a6($,O,j){let x;if($)x=g1($.random??$.rng?.()??Lj(),$.msecs,$.seq,O,j);else{let S=Date.now(),K=Lj();i6(nx,S,K),x=g1(K,nx.msecs,nx.seq,O,j)}return O??b1(x)}function i6($,O,j){if($.msecs??=-1/0,$.seq??=0,O>$.msecs)$.seq=j[6]<<23|j[7]<<16|j[8]<<8|j[9],$.msecs=O;else if($.seq=$.seq+1|0,$.seq===0)$.msecs++;return $}function g1($,O,j,x,S=0){if($.length<16)throw Error("Random bytes length must be >= 16");if(!x)x=new Uint8Array(16),S=0;else if(S<0||S+16>x.length)throw RangeError(`UUID byte range ${S}:${S+15} is out of buffer bounds`);return O??=Date.now(),j??=$[6]*127<<24|$[7]<<16|$[8]<<8|$[9],x[S++]=O/1099511627776&255,x[S++]=O/4294967296&255,x[S++]=O/16777216&255,x[S++]=O/65536&255,x[S++]=O/256&255,x[S++]=O&255,x[S++]=112|j>>>28&15,x[S++]=j>>>20&255,x[S++]=128|j>>>14&63,x[S++]=j>>>6&255,x[S++]=j<<2&255|$[10]&3,x[S++]=$[11],x[S++]=$[12],x[S++]=$[13],x[S++]=$[14],x[S++]=$[15],x}var c$=a6;class A${table;id;constructor($,O){this.table=$;this.id=O}static byId($,O){return new A$($,O)}async detail(){let{columns:$}=await this.table.detail(),O=$.find((j)=>j.column.id===this.id);if(!O)throw new E(`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 M${table;id;constructor($,O){this.table=$;this.id=O}static byId($,O){return new M$($,O)}history(){return this.table.database.rowHistory(this)}toJSON(){return{id:this.id,tableId:this.table.id}}}class Uj{table;id;constructor($,O){this.table=$;this.id=O}static byId($,O){return new Uj($,O)}async detail(){let{views:$}=await this.table.detail(),O=$.find((j)=>j.id===this.id);if(!O)throw new E(`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 J${database;id;constructor($,O){this.database=$;this.id=O}static byId($,O){return new J$($,O)}async detail(){let{tables:$}=await this.database.schema(),O=$.find((j)=>j.table.id===this.id);if(!O)throw new E(`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)=>A$.byId(this,O.column.id))}addColumn($){return this.database.addColumn(this,$)}async reorderColumns($){return await this.database.reorderColumns(this,$),this}row($){return M$.byId(this,$)}async views(){let{views:$}=await this.detail();return $.map((O)=>Uj.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}}}async function Nj($,O,j,x={}){let S=Q(await $.storage.queryDatabases({body:{sql:j,databaseId:x.database?.id,baseVersions:Object.fromEntries((x.baseVersions??[]).map(({table:Y,version:J})=>[Y.id,J]))}})),K=new Map;for(let Y of[x.database,...(x.baseVersions??[]).map(({table:J})=>J.database)]){if(!Y)continue;let J=K.get(Y.id);if(J)J.add(Y);else K.set(Y.id,new Set([Y]))}let Z=(Y)=>{let J=K.get(Y)?.values().next().value;if(J)return J;let T=O($,Y);return K.set(Y,new Set([T])),T},X=(Y)=>{let J=S.tableDatabases[Y];if(!J)throw Error(`SQL response is missing the owner of table ${Y}`);return J$.byId(Z(J),Y)},G=new Set(Object.keys(S.newVersions).map((Y)=>X(Y).database.id));if(S.statement.kind==="schema")G.add(S.statement.databaseId);for(let Y of G)for(let J of K.get(Y)??[])J.invalidateSchema();let L=c(S.statement).with({kind:"select"},(Y)=>Y).with({kind:"schema"},({databaseId:Y,summary:J})=>({kind:"schema",database:Z(Y),summary:J})).with({kind:"insert"},{kind:"update"},{kind:"delete"},({kind:Y,tableId:J,tableName:T})=>({kind:Y,table:X(J),tableName:T})).with({kind:"alterColumnType"},({tableId:Y,tableName:J,columnId:T,columnName:z,to:W})=>{let V=X(Y);return{kind:"alterColumnType",table:V,tableName:J,column:A$.byId(V,T),columnName:z,to:W}}).exhaustive();return{result:S.result?n6(S.result,X,S.tableDatabases):void 0,changesApplied:S.changesApplied,insertedRows:L.kind==="insert"?S.insertedRowIds.map((Y)=>M$.byId(L.table,Y)):[],newVersions:Object.entries(S.newVersions).map(([Y,J])=>({table:X(Y),version:J})),readVersions:Object.entries(S.readVersions).map(([Y,J])=>({table:X(Y),version:J})),truncatedTables:S.truncatedTables,statement:L}}function n6($,O,j){let x=$.sourceTable&&j[$.sourceTable]?O($.sourceTable):void 0;return{columns:$.columns.map(({relatedTable:S,...K})=>({...K,relatedTable:S&&j[S]?O(S):void 0})),rows:$.rows,sourceTable:x,rowHandles:x?$.rowIds.map((S)=>M$.byId(x,S)):[]}}class zj{table;id;createdBy;record;constructor($,O,j,x){this.table=$;this.id=O;this.createdBy=j;this.record=x}static fromRecord($,O,j){return new zj($,j.id,O,j)}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 ex extends ZO{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 Ij($){return c($).with({type:"relation"},({table:O})=>({type:"relation",database:O.database.id,table:O.id})).with({type:Z$.not("relation")},(O)=>O).exhaustive()}var s6={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 t6($){return c($).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})=>s6[O]).with({type:"relation"},()=>"Relation").exhaustive(()=>"Column")}function sx($){return $.map((O)=>({id:c$(),label:O}))}function k1($,O,j){return $?.kind===O&&"change"in $&&$.change.kind===j}function tx($){return c($).with({kind:"reorder_tables"},({kind:O})=>O).with({kind:Z$.union("table","column","rows","view")},({kind:O,change:j})=>`${O}.${j.kind}`).exhaustive(()=>"unknown")}function u$($,O,j){let[x]=$;if($.length!==1||!k1(x,O,j))throw new f(`expected one ${O}.${j} result, got ${$.map(tx).join(", ")||"none"}`);return x}class V$ extends M{access=new o(this.client,"database",this);async fetch(){return Q(await this.client.storage.getDatabase({path:{id:this.id}}))}assertOwns($,O){if(O.id!==this.id)throw new f(`${$} does not belong to database ${this.id}`)}static byId($,O){return new V$($,O)}static async create($,O){let j=Q(await $.storage.createDatabase({body:{name:O.name}}));return new V$($,j.id)}static async list($){return Q(await $.storage.listDatabases()).map((j)=>new V$($,j.database.id))}query($,O){return Nj(this.client,V$.byId,$,{...O,database:this})}invalidateSchema(){this.detail.clear()}schema(){return this.detail.get()}name=this.mappedField("database",($)=>$.name);owner=this.mappedField("database",($)=>A.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)=>J$.byId(this,O.table.id)));async table($){let{tables:O}=await this.schema(),j=O.find((x)=>x.table.name===$);return j?J$.byId(this,j.table.id):void 0}async createTable($){let{table:O}=u$(await this.applyOps([{kind:"table",table:c$(),change:{kind:"create",name:$.name}}]),"table","created");return J$.byId(this,O)}async applyOps($,O={}){let j={ops:$};if(O.baseVersions!==void 0){for(let{table:S}of O.baseVersions)this.assertOwns(`table ${S.id}`,S.database);j.baseVersions=Object.fromEntries(O.baseVersions.map(({table:S,version:K})=>[S.id,K]))}let{results:x}=await this.mutate(async(S)=>{let K=await S.storage.applyDatabaseOps({path:{id:this.id},body:j});if(K.error!==void 0&&"op"in K.error)throw new ex(K.response?.status??0,K.error);return K});return x}async reorderTables($){for(let x of $)this.assertOwns(`table ${x.id}`,x.database);let O=await this.applyOps([{kind:"reorder_tables",order:$.map((x)=>x.id)}]),[j]=O;if(O.length!==1||j?.kind!=="reorder_tables")throw new f(`expected one reorder_tables result, got ${O.map(tx).join(", ")||"none"}`);return j.tables.map(({table:x})=>J$.byId(this,x))}async deleteTable($){this.assertOwns(`table ${$.id}`,$.database),u$(await this.applyOps([{kind:"table",table:$.id,change:{kind:"delete"}}]),"table","deleted")}async columnCasts($){return this.assertOwns(`column ${$.id}`,$.table.database),Q(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}=Q(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}=Q(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((j)=>j.storage.importDatabaseTable({path:{id:this.id},body:$}));return J$.byId(this,O.id)}webhookOf($){return zj.fromRecord(J$.byId(this,$.tableId),A.byId(this.client,$.createdBy),$)}async webhooks(){let{webhooks:$}=Q(await this.client.storage.listDatabaseWebhooks({path:{id:this.id}}));return $.map((O)=>this.webhookOf(O))}async createWebhook($){this.assertOwns("table",$.database);let O=Q(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),Q(await this.client.storage.deleteDatabaseWebhook({path:{id:this.id,webhook_id:$.id}}))}async sharePermissions(){return Q(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 j=await $.table.version();return u$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"change_type",to:Ij(O.to)}}],{baseVersions:[{table:$.table,version:j}]}),"column","type_changed")}async columnConversion($,O){return this.assertOwns(`column ${$.id}`,$.table.database),Q(await this.client.storage.convertDatabaseColumn({path:{id:this.id,table_id:$.table.id,column_id:$.id},body:{to:Ij(O)}}))}async convertColumnIntoNewColumn($,O){let j=await this.columnConversion($,O.to),x=O.name??`${await $.name()} (${t6(O.to)})`,S=c$(),K=[{kind:"column",table:$.table.id,column:S,change:{kind:"create",definition:{source:"new",name:x,type:Ij(O.to),options:sx(j.options)},after:$.id}}];if(j.cells.length>0)K.push({kind:"rows",table:$.table.id,change:{kind:"update",changes:{kind:"per_row",rows:j.cells.map(({row:X,value:G})=>({row:X,cells:[{column:S,value:G}]}))}}});let[Z]=await this.applyOps(K,{baseVersions:[{table:$.table,version:j.tableVersion}]});if(!k1(Z,"column","created"))throw new f(`expected a column.created result, got ${Z?tx(Z):"none"}`);return A$.byId($.table,Z.column)}async deleteColumn($){this.assertOwns(`column ${$.id}`,$.table.database);let O=await $.table.version(),{tableVersion:j}=u$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"delete"}}],{baseVersions:[{table:$.table,version:O}]}),"column","deleted");return j}async reorderColumns($,O){this.assertOwns(`table ${$.id}`,$.database);for(let S of O)if(S.table.id!==$.id)throw new f(`column ${S.id} does not belong to table ${$.id}`);let j=await $.version(),{tableVersion:x}=u$(await this.applyOps([{kind:"table",table:$.id,change:{kind:"reorder_columns",order:O.map((S)=>S.id)}}],{baseVersions:[{table:$,version:j}]}),"table","columns_reordered");if(x===void 0)throw new f(`table ${$.id} reordered its columns without a version`);return x}async renameTable($,O){this.assertOwns(`table ${$.id}`,$.database);let j=await $.name(),{tableVersion:x}=u$(await this.applyOps([{kind:"table",table:$.id,change:{kind:"rename",name:O,previousName:j}}]),"table","renamed");if(x===void 0)throw new f(`table ${$.id} was renamed without a version`);return x}async renameColumn($,O){this.assertOwns(`column ${$.id}`,$.table.database);let j=await $.name(),{tableVersion:x}=u$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"rename",name:O,previousName:j}}]),"column","renamed");return x}async inferColumnType($,O){return this.assertOwns(`column ${$.id}`,$.table.database),this.mutate((j)=>j.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 f(`column ${O.after.id} does not belong to table ${$.id}`);let j="property"in O?{source:"existing",property:O.property.id}:{source:"new",name:O.name,type:Ij(O.type),...O.options!==void 0?{options:sx(O.options)}:{},...O.inferType!==void 0?{inferType:O.inferType}:{}},{column:x}=u$(await this.applyOps([{kind:"column",table:$.id,column:c$(),change:{kind:"create",definition:j,...O.after!==void 0?{after:O.after.id}:{}}}]),"column","created");return A$.byId($,x)}async addColumnOptions($,O){return this.assertOwns(`column ${$.id}`,$.table.database),u$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"add_options",options:sx(O)}}]),"column","options_added")}}class ox{client;constructor($){this.client=$}query($,O){return Nj(this.client,V$.byId,$,O)}byId($){return V$.byId(this.client,$)}create($){return V$.create(this.client,$)}list(){return V$.list(this.client)}}class Tj{id;name;constructor($,O){this.id=$;this.name=O}static async list($){let{skills:O}=Q(await $.storage.getSystemSkillsHandler());return O.map((j)=>new Tj(j.id,j.name))}}class $0{client;async byTeamSlug($){let O=Q(await this.client.storage.getDocumentByTeamSlug({path:{slug:$}}));if(typeof O!=="object"||O===null||!("data"in O)||typeof O.data!=="object"||O.data===null||!("documentMetadata"in O.data)||typeof O.data.documentMetadata!=="object"||O.data.documentMetadata===null||!("documentId"in O.data.documentMetadata)||typeof O.data.documentMetadata.documentId!=="string")throw Error("Invalid team task document response");return q.byId(this.client,O.data.documentMetadata.documentId)}async validatePermissionsToken($){let O=Q(await this.client.storage.validateDocumentPermissionsToken({body:{token:$}}));return{document:q.byId(this.client,O.document_id),user:O.user_id?A.byId(this.client,O.user_id):void 0,accessLevel:O.access_level,expiresAt:O.exp,issuer:O.iss}}async createUpload($){let O={documentName:$.name,sha:$.sha,fileType:$.fileType,mimeType:$.mimeType,projectId:$.project?.id,teamId:$.team?.id,branchedFromId:$.branchedFrom?.id,emailAttachmentId:$.attachment?.id,isTask:$.isTask},j=Q(await this.client.storage.createDocument({body:O})).data;return{document:q.byId(this.client,j.documentMetadata.documentId),uploadUrl:j.presignedUrl??void 0,contentType:j.contentType,content:j.documentMetadata.content}}constructor($){this.client=$}byId($){return q.byId(this.client,$)}create($){return q.create(this.client,$)}createSnippet($){return q.createSnippet(this.client,$)}createSkill($){return q.createSkill(this.client,$)}systemSkills(){return Tj.list(this.client)}search($,O){return q.search(this.client,$,O)}recent($){return q.recent(this.client,$)}recentlyDeleted(){return q.recentlyDeleted(this.client)}}class YO extends M{async fetch(){let{attachment:$}=Q(await this.client.email.getAttachment({path:{id:this.id}}));return $}static byId($,O){return new YO($,O)}static from($,O){return new YO($,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:$}=Q(await this.client.email.getAttachmentDocumentId({path:{id:this.id}}));return q.byId(this.client,$)}}class H$ extends X${access=new o(this.client,"email_thread",this);async followup(){return Q(await this.client.storage.getEmailFollowup({path:{thread_id:this.id}}))}async setFollowup($){return Q(await this.client.storage.setEmailFollowup({path:{thread_id:this.id},body:$}))}async calendarInvitations(){return Q(await this.client.email.getThreadCalendarInvitations({path:{thread_id:this.id}}))}async update($){await this.mutate((O)=>O.storage.editThreadV2({path:{thread_id:this.id},body:{projectId:$.project===void 0?void 0:$.project?.id??null,sharePermission:$.sharePermission?p$($.sharePermission):void 0}}))}entityType="email_thread";propertyEntityType="THREAD";async fetch(){let{thread:$}=Q(await this.client.email.getThread({path:{thread_id:this.id},query:{limit:100}}));return $}static byId($,O){return new H$($,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",($)=>I$.byId(this.client,$));project=this.mappedField("project_id",($)=>$?n.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 j of $)for(let x of[j.from,...j.to,...j.cc,...j.bcc])if(x&&!O.has(x.email))O.set(x.email,x);return[...O.values()]}async messages($){return Q(await this.client.email.getThreadMessagesHandler({path:{id:this.id},query:{...$?.since?{since:$.since}:{},...$?.limit?{limit:$.limit}:{}}})).map((j)=>R$.from(this.client,j))}async attachments(){let{messages:$}=await this.detail.get();return $.flatMap((O)=>O.attachments.map((j)=>YO.from(this.client,j)))}async reply($){let O=$.subject??await this.subject()??"",{message:j}=await this.mutate((x)=>x.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 j.db_id?R$.byId(this.client,j.db_id):void 0}async archive($=!0){await this.mutate((O)=>O.email.archiveThread({path:{id:this.id},body:{value:$}}))}async updateState($){await this.mutate((O)=>O.email.updateThreadState({path:{id:this.id},body:$}))}async operations(){return Q(await this.client.email.threadOperations({path:{id:this.id}}))}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=j$({filters:{email_filters:{}},type:"email",make:($,O)=>new H$($,O.thread_id)})}class R$ extends M{async fetch(){return Q(await this.client.email.getMessage({path:{id:this.id}}))}static byId($,O){return new R$($,O)}static from($,O){return new R$($,O.db_id,O)}static async send($,O){let{message:j}=Q(await $.email.sendMessage({body:{message:{to:O.to,cc:O.cc??null,bcc:O.bcc??null,subject:O.subject,body_text:O.bodyText}}}));return j.db_id?R$.byId($,j.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",($)=>I$.byId(this.client,$));async operationStatus(){return Q(await this.client.email.messageOperationStatus({path:{id:this.id}}))}async resolveOperation($){await this.mutate((O)=>O.email.resolveMessageOperation({path:{id:this.id},body:$}))}async completeDraftAttachment($,O=0){let j=await this.link();await this.mutate((x)=>x.email.completeDraftAttachment({path:{id:this.id,attachment_id:$},query:{draft_generation:O},headers:{"X-Email-Link-Id":j.id}}))}async transferDraft($){let O=await this.detail.get();return this.mutate((j)=>j.email.transferDraft({path:{id:this.id},body:{...$,draft_generation:$.draft_generation??O.draft_generation??0},headers:{"X-Email-Link-Id":O.link_id}}))}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 H$.byId(this.client,(await this.detail.get()).thread_db_id)}}class QO extends R${async draftContext(){let $=await this.detail.get();return{headers:{"X-Email-Link-Id":$.link_id},query:{draft_generation:$.draft_generation??0}}}static byId($,O){return new QO($,O)}draftGeneration=this.field("draft_generation");async update($){let{headers:O,query:j}=await this.draftContext();await this.mutate((x)=>x.email.createDraft({headers:O,body:{draft:{...O0($),db_id:this.id,draft_generation:$.draftGeneration??j.draft_generation}}}))}async delete(){let{headers:$,query:O}=await this.draftContext();await this.mutate((j)=>j.email.deleteDraft({path:{id:this.id},headers:$,query:O}))}async schedule($,O){let{headers:j,query:x}=await this.draftContext();await this.mutate((S)=>S.email.upsertScheduledMessage({path:{id:this.id},headers:j,query:x,body:{send_time:$,include_signature:O?.includeSignature}}))}async unschedule(){let{headers:$,query:O}=await this.draftContext();await this.mutate((j)=>j.email.deleteScheduledDraft({path:{message_id:this.id},headers:$,query:O}))}async addAttachment($){let O={file_name:$.fileName,sha:$.sha,size:$.size,upload_id:$.uploadId},{headers:j,query:x}=await this.draftContext(),S=await this.mutate((K)=>K.email.addDraftAttachment({path:{id:this.id},headers:j,query:x,body:O}));return{attachment:pO.byId(this.client,this,S.attachment_id,!1,x.draft_generation),uploadUrl:S.upload_url,contentType:S.content_type}}async forwardAttachment($){let{headers:O,query:j}=await this.draftContext(),x=await this.mutate((S)=>S.email.addForwardedAttachment({path:{id:this.id},headers:O,query:j,body:{attachment_id:$.id}}));return pO.byId(this.client,this,x.attachment_id,!0,j.draft_generation)}async removeAttachment($){if($.draft.id!==this.id)throw Error("Attachment belongs to another draft");let{headers:O}=await this.draftContext(),j={draft_generation:$.draftGeneration};if($.forwarded)await this.mutate((x)=>x.email.removeForwardedAttachment({path:{id:this.id,attachment_id:$.id},headers:O,query:j}));else await this.mutate((x)=>x.email.removeDraftAttachment({path:{id:this.id,attachment_id:$.id},headers:O,query:j}))}async verifyAttachment($){if($.draft.id!==this.id||$.forwarded)throw Error("Expected an uploaded attachment on this draft");await this.completeDraftAttachment($.id,$.draftGeneration)}}class pO{draft;id;forwarded;draftGeneration;constructor($,O,j,x){this.draft=$;this.id=O;this.forwarded=j;this.draftGeneration=x}static byId($,O,j,x=!1,S=0){return new pO(O,j,x,S)}complete(){return this.draft.verifyAttachment(this)}remove(){return this.draft.removeAttachment(this)}toJSON(){return{id:this.id,draftId:this.draft.id,forwarded:this.forwarded,draftGeneration:this.draftGeneration}}}function O0($){let{bodyText:O,bodyHtml:j,bodyMacro:x,headers:S,includeSignature:K,draftGeneration:Z,thread:X,replyingTo:G,...L}=$;return{...L,body_text:O,body_html:j===void 0?void 0:btoa(Array.from(new TextEncoder().encode(j),(Y)=>String.fromCharCode(Y)).join("")).replaceAll("+","-").replaceAll("/","_").replaceAll("=",""),body_macro:x,headers_json:S,include_signature:K,draft_generation:Z,thread_db_id:X?.id,replying_to_id:G?.id}}class JO extends M{inbox;constructor($,O,j,x){super($,O,j);this.inbox=x}get headers(){return this.inbox?{"X-Email-Link-Id":this.inbox.id}:void 0}static byId($,O,j){return new JO($,O,void 0,j)}static from($,O,j){return new JO($,O.id,O,j)}async fetch(){let $=Q(await this.client.email.listEmailFilters({headers:this.headers})).filters.find((O)=>O.id===this.id);if(!$)throw new E(`Email filter ${this.id} is unavailable`);return $}emailAddress=this.field("email_address");emailDomain=this.field("email_domain");isImportant=this.field("is_important");async setImportant($){let O=await this.detail.get();await this.mutate((j)=>j.email.upsertEmailFilter({headers:this.headers,body:{email_address:O.email_address,email_domain:O.email_domain,is_important:$}}))}async delete(){await this.mutate(($)=>$.email.deleteEmailFilter({path:{id:this.id},headers:this.headers}))}}class o$ extends M{async fetch(){let{labels:$}=Q(await this.client.email.listLabels()),O=$.find((j)=>j.id===this.id);if(!O)throw new E(`label ${this.id} not found`);return O}static byId($,O){return new o$($,O)}static async list($){let{labels:O}=Q(await $.email.listLabels());return O.map((j)=>new o$($,j.id,j))}static async create($,O){let{label:j}=Q(await $.email.createLabel({body:{label_name:O}}));if(!j.id)throw new f("created label has no id");return new o$($,j.id)}async delete(){Q(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 j0{client;async createDraft($,O){let j=Q(await this.client.email.createDraft({body:{draft:O0($)},headers:O?{"X-Email-Link-Id":O.id}:void 0}));if(!j.draft.db_id)throw Error("Draft response has no message id");return QO.byId(this.client,j.draft.db_id)}draftById($){return QO.byId(this.client,$)}async*scheduled($){let O=$?.pageSize??100;if(!Number.isInteger(O)||O<1)throw Error("pageSize must be positive");let j=Math.min(O,1000);for(let x=0;;x+=j){let S=Q(await this.client.email.getScheduledMessages({query:{offset:x,limit:j},headers:$?.inbox?{"X-Email-Link-Id":$.inbox.id}:void 0}));for(let K of S.messages)yield QO.byId(this.client,K.db_id);if(S.messages.length<j)return}}async filters($){return Q(await this.client.email.listEmailFilters({headers:$?{"X-Email-Link-Id":$.id}:void 0})).filters.map((O)=>JO.from(this.client,O,$))}async upsertFilter($,O){return JO.from(this.client,Q(await this.client.email.upsertEmailFilter({headers:O?{"X-Email-Link-Id":O.id}:void 0,body:{email_address:$.emailAddress,email_domain:$.emailDomain,is_important:$.isImportant}})).filter,O)}async contacts(){return Q(await this.client.email.listContacts()).contacts}reminders($){let{inboxes:O,...j}=$??{};return a(async(x)=>{let S=Q(await this.client.storage.listEmailReminders({query:{...j,inboxIds:O?.map((K)=>K.id),cursor:x}}));return{items:S.items.map(({threadId:K,...Z})=>({...Z,thread:H$.byId(this.client,K)})),nextCursor:S.nextCursor}})}constructor($){this.client=$}byId($){return H$.byId(this.client,$)}message($){return R$.byId(this.client,$)}attachment($){return YO.byId(this.client,$)}link($){return I$.byId(this.client,$)}links(){return I$.list(this.client)}async connectionProviders(){return Q(await this.client.auth.emailConnectionProviders())}async recoverDraftTransfer($){return Q(await this.client.email.recoverDraftTransfer({path:{id:$}}))}send($){return R$.send(this.client,$)}search($,O){return H$.search(this.client,$,O)}inbox($){return a(async(O)=>{let j=Q(await this.client.email.previewsInboxCursor({path:{view:"inbox"},query:{...$?.pageSize?{limit:$.pageSize}:{},...$?.sort?{sort_method:$.sort}:{},...O?{cursor:O}:{}}}));return{items:j.items.map((x)=>H$.byId(this.client,x.id)),nextCursor:j.next_cursor}})}label($){return o$.byId(this.client,$)}labels(){return o$.list(this.client)}createLabel($){return o$.create(this.client,$)}async deleteLabel($){Q(await this.client.email.deleteLabel({path:{id:$.id}}))}async blockSender($){Q(await this.client.email.blockSender({body:{email_address:$}}))}async unblockSender($){Q(await this.client.email.unblockSender({body:{email_address:$}}))}async blockedSenders(){return Q(await this.client.email.listBlockedSenders()).blocked_emails}}class LO{client;id;constructor($,O){this.client=$;this.id=O}static byId($,O){return new LO($,O)}async delete(){Q(await this.client.storage.deleteEntityMention({path:{mention_id:this.id}}))}toJSON(){return{id:this.id}}}class x0{client;constructor($){this.client=$}byId($){return LO.byId(this.client,$)}async create($,O){let j=Q(await this.client.storage.createEntityMention({body:{source_entity_id:$.entity.id,source_entity_type:$.type,entity_id:O.entity.id,entity_type:O.type}}));return LO.byId(this.client,j.id)}}class S0{client;constructor($){this.client=$}async list($={}){let{favorites:O}=Q(await this.client.storage.listFavorites({query:{entityType:$.entityTypes,entityId:$.entityIds}}));return O}async add($){return Q(await this.client.storage.addFavorite({body:{entityId:$.id,entityType:$.entityType}}))}async remove($){Q(await this.client.storage.removeFavoriteByEntity({path:{entity_type:$.entityType,entity_id:$.id}}))}async reorder($){Q(await this.client.storage.reorderFavorites({body:{favorites:$}}))}}class $O extends F${entityType="foreign_entity";async fetch(){return Q(await this.client.storage.getForeignEntity({path:{id:this.id}}))}static byId($,O){return new $O($,O)}static fromRecord($,O){return new $O($,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 y1({login:$,...O}){return{...O,login:$??void 0}}class Z0{client;constructor($){this.client=$}byId($){return $O.byId(this.client,$)}async bySource($,O){return $O.fromRecord(this.client,Q(await this.client.storage.getForeignEntityBySource({path:{source:$,foreign_entity_id:O}})))}async githubPullRequestFacets(){let{repositories:$,authors:O,assignees:j,labels:x}=Q(await this.client.storage.getGithubPullRequestFacets());return{repositories:$,authors:O.map(y1),assignees:j.map(y1),labels:x.map(({color:S,...K})=>({...K,color:S??void 0}))}}}class d${form;id;constructor($,O){this.form=$;this.id=O}static byId($,O){return new d$($,O)}async detail(){let O=(await this.form.schema()).sections.flatMap((j)=>j.kind==="questions"?j.questions:[]).find((j)=>j.id===this.id);if(!O)throw new E(`question ${this.id} is not on form ${this.form.id}`);return O}async title(){return(await this.detail()).title}async column(){return A$.byId(await this.form.table(),(await this.detail()).column)}async options(){return(await this.detail()).options.map(($)=>VO.byId(this,$.id))}}class VO{question;id;constructor($,O){this.question=$;this.id=O}static byId($,O){return new VO($,O)}async detail(){let $=(await this.question.detail()).options.find((O)=>O.id===this.id);if(!$)throw new E(`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 UO{form;id;detail;constructor($,O,j){this.form=$;this.id=O;this.detail=new W$(()=>this.load(),j)}async load(){let $=await this.form.myResponse();if($.response.id!==this.id)throw new E(`response ${this.id} is not your current response`);return $}static byId($,O,j){return new UO($,O,j)}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 W$(()=>this.load(),$),this}}class l${form;id;constructor($,O){this.form=$;this.id=O}static byId($,O){return new l$($,O)}async detail(){let $=(await this.form.schema()).sections.find((O)=>O.id===this.id);if(!$)throw new E(`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)=>d$.byId(this.form,O.id)):[]}}class Hj{entityType;id;constructor($,O){this.entityType=$;this.id=O}static byId($,O){return new Hj($,O)}}class k$ extends M{async fetch(){return Q(await this.client.storage.getForm({path:{id:this.id}}))}static byId($,O){return new k$($,O)}static async create($,O){let j=Q(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 k$($,j.form.id,j)}static async list($,O){if(!O)return Q(await $.storage.listAccessibleForms()).map(({form:S})=>new k$($,S.id));return Q(await $.storage.listForms({query:{databaseId:O.id}})).map((x)=>new k$($,x.id))}schema(){return this.detail.get()}name=this.mappedField("form",($)=>$.name);description=this.mappedField("form",($)=>$.description);owner=this.mappedField("form",($)=>A.byId(this.client,$.ownerId));database=this.mappedField("form",($)=>V$.byId(this.client,$.databaseId));table=this.mappedField("form",($)=>J$.byId(V$.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(($)=>l$.byId(this,$.id))}async questions(){return(await this.detail.get()).sections.flatMap(($)=>$.kind==="questions"?$.questions.map((O)=>d$.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 f(`question or section does not belong to form ${this.id}`)}async replaceLayout($){let O=await this.table(),j=(Z)=>{if(Z.table.id!==O.id||Z.table.database.id!==O.database.id)throw new f(`column does not belong to form ${this.id}'s table`);return Z.id},x=(Z)=>({conjunction:Z.conjunction,conditions:Z.conditions.map((X)=>c(X).with({kind:"group"},(G)=>({kind:"group",...x(G)})).with({kind:"condition"},(G)=>({kind:"condition",column:j(G.column),test:c(G.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:Z$.union("presence","text","number","date","checkbox")},(L)=>L).exhaustive()})).exhaustive())}),S={sections:$.map((Z)=>{if(Z.section)this.assertOwns(Z.section);let X={id:Z.section?.id??c$(),title:Z.title,description:Z.description??""};return c(Z).with({kind:"booking"},(G)=>({...X,kind:"booking",target:G.target})).with({kind:"gate"},(G)=>({...X,kind:"gate",rules:x(G.rules),message:G.message})).with({kind:"questions"},(G)=>({...X,kind:"questions",questions:G.questions.map((L)=>{if(L.question)this.assertOwns(L.question);return{id:L.question?.id??c$(),column:j(L.column),helpText:L.helpText??"",required:L.required??!1,widget:L.widget??null}})})).exhaustive()})},K=await this.mutate((Z)=>Z.storage.putFormLayout({path:{id:this.id},body:S}));return{form:this,publicationError:K.publicationError}}wireAnswers($){return $.map(({question:O,value:j})=>{this.assertOwns(O);let x=c(j).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 f("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:Z})=>({entityType:K,entityId:Z.id}))})).with({type:Z$.union("text","number","boolean","date","link","clear")},(S)=>S).exhaustive();return{question:O.id,value:x}})}unlockedBooking($){return $?{...$,section:l$.byId(this,$.section)}:void 0}async outcome($,O){return c($).with({outcome:"stopped"},(j)=>({...j,section:l$.byId(this,j.section)})).with({outcome:"submitted"},async(j)=>{let x=M$.byId(await this.table(),j.row),S=this.unlockedBooking(j.booking);return{outcome:"submitted",response:UO.byId(this,j.response,{status:"submitted",row:x,answers:O,booking:S}),row:x,...S?{booking:S}:{}}}).exhaustive()}async submit($){let O={answers:this.wireAnswers($)};return this.outcome(Q(await this.client.storage.submitFormResponse({path:{id:this.id},body:O})),$)}async editResponse($){let O={answers:this.wireAnswers($)};return this.outcome(Q(await this.client.storage.editMyFormResponse({path:{id:this.id},body:O})),$)}async myResponse(){let $=Q(await this.client.storage.getMyFormResponse({path:{id:this.id}})),O=await this.table(),j=await Promise.all($.answers.map(async(K)=>{let Z=d$.byId(this,K.question),X=await c(K.value).with({type:"options"},(G)=>({type:"options",value:G.value.map((L)=>{if(!("id"in L))throw new f("stored form answers must reference options by id");return VO.byId(Z,L.id)})})).with({type:"entities"},(G)=>({type:"entities",value:G.value.map((L)=>({entityType:L.entityType,entity:Hj.byId(L.entityType,L.entityId)}))})).with({type:"rows"},async(G)=>{let L=await Z.detail();if(L.kind.type!=="relation")throw new f("row answer requires a relation question");let Y=J$.byId(V$.byId(this.client,L.kind.database),L.kind.table);return{type:"rows",value:G.value.map((J)=>M$.byId(Y,J))}}).with({type:Z$.union("text","number","boolean","date","link","clear")},(G)=>G).exhaustive(()=>{throw new f(`answer to question ${Z.id} has a type this SDK doesn't know`)});return{question:Z,value:X}})),x=$.response.row?M$.byId(O,$.response.row):void 0,S=this.unlockedBooking($.booking);return{...S?{booking:S}:{},response:UO.byId(this,$.response.id,{status:$.response.status,row:x,answers:j,booking:S}),status:$.response.status,stoppedAtSection:$.response.stoppedAtSection?l$.byId(this,$.response.stoppedAtSection):void 0,row:x,submittedAt:$.response.submittedAt,updatedAt:$.response.updatedAt,answers:j}}async responseSummary(){let $=Q(await this.client.storage.getFormResponseSummary({path:{id:this.id}}));return{...$,stoppedBySection:$.stoppedBySection.map((O)=>({section:l$.byId(this,O.section),count:O.count}))}}async tally(){return Q(await this.client.storage.getFormTally({path:{id:this.id}})).questions.map((O)=>{let j=d$.byId(this,O.question);return{question:j,responses:O.responses,buckets:O.buckets.flatMap((x)=>c(x.value).with({kind:"option"},(S)=>[{count:x.count,value:{kind:"option",option:VO.byId(j,S.option)}}]).with({kind:"checkbox"},(S)=>[{count:x.count,value:S}]).exhaustive((S)=>{return console.warn("macro sdk: unknown form tally bucket",S),[]}))}})}async sharePermissions(){return Q(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 X0{client;constructor($){this.client=$}byId($){return k$.byId(this.client,$)}create($){return k$.create(this.client,$)}list($){return k$.list(this.client,$)}}class NO extends M{static byId($,O){return new NO($,O)}async fetch(){return Q(await this.client.storage.getGithubPullRequest({path:{id:this.id}}))}title=this.field("title");url=this.field("url");status=this.field("status");async changes(){let $=Q(await this.client.storage.getGithubPullRequestChanges({path:{id:this.id}}));return{changeset:$.changeset?new G0(this.client,this,$.changeset):void 0,error:$.error??void 0}}}class G0{client;pullRequest;record;constructor($,O,j){this.client=$;this.pullRequest=O;this.record=j}get id(){return this.record.id}async patch(){return Q(await this.client.storage.getGithubPullRequestChangesPatch({path:{id:this.pullRequest.id},query:{changeset:this.id}})).patch}toJSON(){return{pullRequestId:this.pullRequest.id,...this.record}}}class K0{client;constructor($){this.client=$}byId($){return NO.byId(this.client,$)}forEntity($){return NO.byId(this.client,$.id)}}class zO extends M{static byId($,O){return new zO($,O)}async fetch(){return Q(await this.client.storage.getHarnessPairing({path:{code:this.id}}))}name=this.field("requested_name");expiresAt=this.field("expires_at");async approve($){let O={name:$?.name,team_id:$?.team?.id,allow_permission_bypass:$?.allowPermissionBypass};return B$.from(this.client,await this.mutate((j)=>j.storage.approveHarnessPairing({path:{code:this.id},body:O})))}}class aO{client;id;constructor($,O){this.client=$;this.id=O}static byId($,O){return new aO($,O)}async claim($){let O=Q(await this.client.storage.claimHarnessPairing({path:{pairing_id:this.id},body:{device_secret:$}}));return"harness"in O?{harness:B$.from(this.client,O.harness),token:O.token}:void 0}toJSON(){return{id:this.id}}}class Y0{client;constructor($){this.client=$}byId($){return B$.byId(this.client,$)}async list(){return Q(await this.client.storage.listHarnesses()).map(($)=>B$.from(this.client,$))}async me(){return B$.from(this.client,Q(await this.client.storage.getSelfHarness()))}async deleteSelf(){Q(await this.client.storage.deleteSelfHarness())}async agents(){return Q(await this.client.storage.listHarnessAgents()).map(($)=>z$.byId(this.client,$.bot_id))}async sessions(){return Q(await this.client.storage.listHarnessSessions()).map(($)=>i.byId(this.client,$.session_id))}pairing($){return zO.byId(this.client,$)}async createPairing($){let O=Q(await this.client.storage.createHarnessPairing({body:$}));return{pairing:zO.byId(this.client,O.code),device:aO.byId(this.client,O.pairing_id),deviceSecret:O.device_secret,expiresAt:O.expires_at,pollIntervalSeconds:O.poll_interval_seconds}}}var e6="00000001-0000-0000-0000-000000000002",o6="00000001-0000-0000-0002-000000000004";function $7($){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 q{static byId($,O){return new D$($,O)}static async create($,O){let{documentId:j}=Q(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$($,j)}static async forPullRequest($,O){let j=$7(O),{pullRequests:x}=Q(await $.storage.getGithubPullRequestTasks({body:{githubKeys:[j]}}));return(x[0]?.taskIds??[]).map((S)=>new D$($,S))}async completed(){let{subType:$}=await this.detail.get();if($!=="task")return;let j=(await this.properties()).find((x)=>x.definition.id===e6)?.value;return j?.type==="SelectOption"&&j.value.includes(o6)}webUrl(){return`${this.client.webAppUrl}/app/task/${this.id}`}static search=j$({filters:{document_filters:{sub_types:["task"],task_filters:{}}},type:"document",make:($,O)=>new D$($,O.document_id)})}class OO extends M{access=new o(this.client,"initiative",this);static byId($,O){return new OO($,O)}static from($,O){return new OO($,O.id,O)}async fetch(){return Q(await this.client.storage.getInitiative({path:{initiative_id:this.id}}))}name=this.field("name");owner=this.mappedField("ownerId",($)=>A.byId(this.client,$));members=this.mappedField("memberIds",($)=>$.map((O)=>A.byId(this.client,O)));tasks=this.mappedField("taskIds",($)=>$.map((O)=>D$.byId(this.client,O)));accessLevel=this.field("userAccessLevel");sharePermissions=this.field("sharePermission");async update($){await this.mutate((O)=>O.storage.updateInitiative({path:{initiative_id:this.id},body:{name:$.name,memberIds:$.members?.map((j)=>j.id),sharePermission:$.sharePermission?p$($.sharePermission):void 0}}))}async delete(){await this.mutate(($)=>$.storage.deleteInitiative({path:{initiative_id:this.id}}))}}class Q0{client;constructor($){this.client=$}byId($){return OO.byId(this.client,$)}async list(){return Q(await this.client.storage.listInitiatives()).initiatives.map(($)=>OO.byId(this.client,$.id))}async create($){return OO.from(this.client,Q(await this.client.storage.createInitiative({body:{name:$.name,description:$.description,memberIds:$.members?.map((O)=>O.id),shareWithTeam:$.shareWithTeam,propertyValues:$.propertyValues}})))}}class J0{client;constructor($){this.client=$}byId($){return T$.byId(this.client,$)}async create($){return T$.from(this.client,Q(await this.client.storage.meetingCreate({body:$})))}async list(){return Q(await this.client.storage.meetingList()).meetings.map(($)=>T$.from(this.client,$))}async active(){return Q(await this.client.storage.meetingListActive()).meetings.map(($)=>T$.from(this.client,$))}async lookup($){return T$.from(this.client,Q(await this.client.storage.meetingLookup({path:{token:$}})))}}class WO extends M{async fetch(){return Q(await this.client.notification.getTypedNotificationById({path:{notification_id:this.id}}))}static byId($,O){return new WO($,O)}static from($,O){return new WO($,O.id,O)}static list($,O){return a(async(j)=>{let x=Q(await $.notification.listTypedNotifications({query:{...O?.pageSize?{limit:O.pageSize}:{},...O?.states!==void 0?{states:O.states.join(",")}:{},...j?{cursor:j}:{}}}));return{items:x.items.map((S)=>WO.from($,S)),nextCursor:x.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",($)=>A.byId(this.client,$));sender=this.mappedField("sender_id",($)=>$?A.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 V0{client;constructor($){this.client=$}byId($){return WO.byId(this.client,$)}list($){return WO.list(this.client,$)}async markSeen($){Q(await this.client.notification.bulkMarkNotificationsSeen({body:{notificationIds:$}}))}async markDone($){Q(await this.client.notification.bulkMarkNotificationsDone({body:{notificationIds:$}}))}async delete($){Q(await this.client.notification.bulkDeleteUserNotificationsV2({body:{notificationIds:$}}))}async preferences(){return Q(await this.client.notification.getNotificationTypePreferences())}async enableType($){Q(await this.client.notification.enableNotificationType({path:{notification_event_type:$}}))}async disableType($){Q(await this.client.notification.disableNotificationType({path:{notification_event_type:$}}))}}class W0{client;constructor($){this.client=$}async list(){let{data:$}=Q(await this.client.storage.getPinsHandler({}));return $?.recent??[]}async add($,O){Q(await this.client.storage.addPinHandler({path:{pinned_item_id:$.id},body:{pinType:$.entityType,pinIndex:O.index}}))}async remove($){Q(await this.client.storage.removePinHandler({path:{pinned_item_id:$.id},body:{pinType:$.entityType}}))}async reorder($){Q(await this.client.storage.reorderPinsHandler({body:$}))}}class B0{client;constructor($){this.client=$}byId($){return n.byId(this.client,$)}create($){return n.create(this.client,$)}search($,O){return n.search(this.client,$,O)}}class IO{client;definitionId;id;record;constructor($,O,j,x){this.client=$;this.definitionId=O;this.id=j;this.record=x}static from($,O,j){return new IO($,O,j.id,j)}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=Q(await this.client.properties.updatePropertyOption({path:{definition_id:this.definitionId,option_id:this.id},body:$})),this}async delete(){Q(await this.client.properties.deletePropertyOption({path:{definition_id:this.definitionId,option_id:this.id}}))}}class jO{client;id;detail;constructor($,O,j){this.client=$;this.id=O;this.detail=new W$(()=>this.fetch(),j)}async fetch(){return Q(await this.client.properties.getPropertyDefinition({path:{definition_id:this.id}}))}static async create($,O){let j=Q(await $.properties.createPropertyDefinition({body:{display_name:O.displayName,scope:O.scope,data_type:O.dataType}}));return new jO($,j.id,j)}static byId($,O){return new jO($,O)}static fromRecord($,O){return new jO($,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 Q(await this.client.properties.deletePropertyDefinition({path:{definition_id:this.id}}))}async options(){return Q(await this.client.properties.getPropertyOptions({path:{definition_id:this.id}})).map((O)=>IO.from(this.client,this.id,O))}async addOption($){let O=Q(await this.client.properties.addPropertyOption({path:{definition_id:this.id},body:$}));return IO.from(this.client,this.id,O)}async updateOption($,O){let j=Q(await this.client.properties.updatePropertyOption({path:{definition_id:this.id,option_id:$.id},body:O}));return IO.from(this.client,this.id,j)}async deleteOption($){return Q(await this.client.properties.deletePropertyOption({path:{definition_id:this.id,option_id:$.id}}))}}class L0{client;constructor($){this.client=$}async list($){return Q(await this.client.properties.listProperties({query:{scope:$?.scope??"all",...$?.forEntityType!==void 0?{for_entity_type:$.forEntityType}:{}}})).map((j)=>{let x="definition"in j?j.definition:j;return jO.fromRecord(this.client,x)})}create($){return jO.create(this.client,$)}definition($){return jO.byId(this.client,$)}async bulkEntityProperties($){return Q(await this.client.properties.getBulkEntityProperties({body:$}))}async updateEntityPropertyOptions($,O){return Q(await this.client.properties.bulkUpdateEntitiesPropertyOptions({body:{entities:$.map((x)=>x.propertyReference()),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)}:{}}})).results}async addEntityPropertyOption($){return Q(await this.client.properties.addEntityPropertyOption({path:{...$.entity.propertyReference(),property_id:$.property.id,option_id:$.option.id}}))}async removeEntityPropertyOption($){return Q(await this.client.properties.removeEntityPropertyOption({path:{...$.entity.propertyReference(),property_id:$.property.id,option_id:$.option.id}}))}async tags(){return Q(await this.client.properties.listTags({}))}}function U0($){return c($).with({type:"cron"},(O)=>O).with({type:"events"},(O)=>({type:"events",filters:O.filters.map(({entities:j,...x})=>({...x,ids:j?.map((S)=>S.entity.id)}))})).exhaustive()}function O7($){return c($).with({type:"multiple"},(O)=>({type:"multiple",triggers:O.triggers.map(U0)})).with({type:"cron"},U0).with({type:"events"},U0).exhaustive()}class xO extends M{static byId($,O){return new xO($,O)}static from($,O){if(!O.id)throw Error("Routine response has no id");return new xO($,O.id,O)}async fetch(){return Q(await this.client.scheduledAction.getScheduledAction({path:{id:this.id}}))}name=this.field("name");trigger=this.field("trigger");enabled=this.field("enabled");runVisibility=this.field("run_visibility");nextRunAt=this.field("next_run_at");revision=this.field("configuration_revision");owner=this.mappedField("owner",($)=>A.byId(this.client,$));async update($){await this.mutate((O)=>O.scheduledAction.updateScheduledAction({path:{id:this.id},body:z0($)}))}async setEnabled($){await this.mutate((O)=>O.scheduledAction.setScheduledActionEnabled({path:{id:this.id},body:{enabled:$}}))}async execute(){let $=Q(await this.client.scheduledAction.executeScheduledActionNow({path:{id:this.id}}));if($.resource)return c($.resource).with({type:"agent"},(O)=>i.byId(this.client,O.id)).with({type:"chat"},(O)=>G$.byId(this.client,O.id)).exhaustive();return $.chat_id?G$.byId(this.client,$.chat_id):void 0}async history(){return Q(await this.client.scheduledAction.listScheduledActionHistory({path:{id:this.id}})).map(($)=>new N0(this,$))}async delete(){await this.mutate(($)=>$.scheduledAction.deleteScheduledAction({path:{id:this.id}}))}}class N0{routine;record;constructor($,O){this.routine=$;this.record=O}get id(){return this.record.id??void 0}toJSON(){return{routine:this.routine.id,...this.record}}}function z0($){let O={prompt:$.prompt,user_prompt:$.userPrompt,model:$.model,agent:$.agent?{bot_id:$.agent.id}:void 0};return{kind:"Agent",name:$.name,enabled:$.enabled,run_visibility:$.runVisibility,trigger:O7($.trigger),task:{...O}}}class I0{client;constructor($){this.client=$}byId($){return xO.byId(this.client,$)}async create($){return xO.from(this.client,Q(await this.client.scheduledAction.createScheduledAction({body:{...z0($),enabled:$.enabled??!0}})))}async list($){return Q(await this.client.scheduledAction.listScheduledActions({query:{include_events:$?.includeEvents}})).map((O)=>xO.from(this.client,O))}}class T0{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 H0{client;constructor($){this.client=$}byId($){return x$.byId(this.client,$)}current(){return x$.current(this.client)}list(){return x$.list(this.client)}}class R0{client;constructor($){this.client=$}async get($){return Q(await this.client.unfurl.getUnfurl({query:{url:$}}))}async bulk($){return Q(await this.client.unfurl.getUnfurlBulk({body:{url_list:$}}))}}class D0{client;constructor($){this.client=$}byId($){return A.byId(this.client,$)}me(){return A.me(this.client)}}class SO extends M{signingSecret;constructor($,O,j,x){super($,O,j);this.signingSecret=x}async fetch(){return Q(await this.client.storage.getWebhook({path:{webhook_id:this.id}}))}static async create($,O){let j=Q(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 SO($,j.id,j,j.signing_secret)}static byId($,O){return new SO($,O)}static fromRecord($,O){return new SO($,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",($)=>A.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 C0{client;constructor($){this.client=$}create($){return SO.create(this.client,$)}byId($){return SO.byId(this.client,$)}async list(){let{webhooks:$}=Q(await this.client.storage.listWebhooks());return $.map((O)=>SO.fromRecord(this.client,O))}}function _0($){if("properties"in $.data)return $.data.properties;if($.tag==="calendarEvent")return $.data.extra.properties;return[]}function v1($,O,j){let x=[];for(let S of _0(O)){if(S.definition.data_type!=="TAG"||S.value?.type!=="SelectOption")continue;for(let K of S.value.value){let Z=j.get(K);if(Z&&!x.some((X)=>X.label===Z.label&&X.scope===Z.scope))x.push(Z)}}switch(O.tag){case"document":return{type:"document",id:O.data.id,entity:q.byId($,O.data.id),snapshot:O,tags:x,name:O.data.name,fileType:O.data.fileType,subType:O.data.subType?.type};case"chat":return{type:"ai_chat",id:O.data.id,entity:G$.byId($,O.data.id),snapshot:O,tags:x,name:O.data.name};case"project":return{type:"project",id:O.data.id,entity:n.byId($,O.data.id),snapshot:O,tags:x,name:O.data.name};case"emailThread":return{type:"email",id:O.data.id,entity:H$.byId($,O.data.id),snapshot:O,tags:x,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:b.byId($,O.data.channel.id),snapshot:O,tags:x,name:O.data.channel.name};case"channelThread":return{type:"channel_thread",id:O.data.id,entity:new y$($,O.data.channel_id,O.data.id),snapshot:O,tags:x,channelId:O.data.channel_id};case"call":return{type:"call",id:O.data.callId,entity:Q$.byId($,O.data.callId),snapshot:O,tags:x,createdBy:O.data.createdBy};case"calendarEvent":return{type:"calendar_event",id:O.data.id,entity:S$.byId($,O.data.id),snapshot:O,tags:x,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:$O.byId($,O.data.id),snapshot:O,tags:x,foreignEntityId:O.data.foreignEntityId,foreignEntitySource:O.data.foreignEntitySource,metadata:O.data.metadata};default:throw Error(`Unexpected workspace entity type: ${O.tag}`)}}var h1="00000000-0000-0000-0000-000000000000",A0={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"]},Rj=($)=>$.replace(/[A-Z]/g,(O)=>O.toLowerCase()),m1=($,O)=>$==null?O:{"&":[$,O]};function M0($,O){if(!$||typeof $!=="object"||Array.isArray($))throw Error(`Invalid workspace ${O}: expected a filter expression.`);let j=Object.entries($),x=j[0];if(j.length!==1||x===void 0)throw Error(`Invalid workspace ${O}: use exactly one of l, &, |, !.`);let[S,K]=x;if(S==="l")return;if(S==="!"){M0(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((Z,X)=>{M0(Z,`${O}.${S}[${X}]`)})}class Dj{client;tagSets;constructor($){this.client=$}sets(){return this.tagSets??=this.client.properties.listTags({}).then(Q),this.tagSets}async tagMap(){let $=new Map;for(let O of await this.sets())for(let j of O.options)if(j.value.type==="string")$.set(j.id,{label:j.value.value,scope:O.scope==="user"?"personal":"team"});return $}async body($){for(let[S,K,Z]of[["sortBy",$.sortBy,["recently_viewed","recently_updated","recently_created"]],["emailPreset",$.emailPreset,["signal"]],["tagsMatch",$.tagsMatch,["any","all"]]])if(K!==void 0&&!Z.includes(K))throw Error(`Invalid workspace ${S}: ${K}`);if($.includeTypes!==void 0&&(!Array.isArray($.includeTypes)||$.includeTypes.some((S)=>!Object.hasOwn(A0,S))))throw Error(`Invalid workspace includeTypes. Supported values: ${Object.keys(A0).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)M0($[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:h1}},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 j=$.inbox?.trim();if(j){let{links:S}=Q(await this.client.email.listLinks()),K=S.filter((X)=>Rj(X.email_address)===Rj(j)),Z=K[0];if(!Z)throw Error(`No connected inbox matches "${j}". Connected inboxes: ${S.map((X)=>X.email_address).join(", ")}.`);if(K.length>1)throw Error(`Multiple connected inboxes match "${j}"; cannot pick one.`);O.ef=m1(O.ef,{l:{Owner:Z.id}})}let x=$.includeTypes??($.emailPreset==="signal"?["email"]:void 0);if(x?.length){for(let[S,[K,Z]]of Object.entries(A0))if(!x.includes(S))O[K]={l:{[Z]:h1}}}if($.tags?.length){let S=(await this.sets()).flatMap((G)=>{let L=G.definition;if(!L)return[];return G.options.flatMap((Y)=>Y.value.type==="string"?[{id:Y.id,definitionId:L.id,label:Y.value.value,scope:G.scope==="user"?"personal":"team"}]:[])}),K=new Map;for(let G of $.tags){let L=S.filter((Y)=>Rj(Y.label)===Rj(G.label.trim())&&(!G.scope||Y.scope===G.scope));if(!L.length)throw Error(`Unknown tag "${G.label}". Available tags: ${S.map((Y)=>`${Y.label} (${Y.scope})`).join(", ")}.`);if($.tagsMatch==="all"&&L.length>1)throw Error(`Tag "${G.label}" is ambiguous; specify personal or team scope.`);for(let Y of L)K.set(Y.id,Y)}let X=[...K.values()].map((G)=>({l:{pd:G.definitionId,v:{so:G.id}}})).reduce((G,L)=>G===void 0?L:{[$.tagsMatch==="all"?"&":"|"]:[G,L]},void 0);O.propf=m1(O.propf,X)}return O}}class P0{client;constructor($){this.client=$}async page($={}){let O=new Dj(this.client);return this.fetch(O,await O.body($),$.cursor)}async*list($={}){let O=new Dj(this.client),j=await O.body($);yield*a((x)=>this.fetch(O,j,x))}async fetch($,O,j){let x=Q(await this.client.storage.postItemsSoupAst({body:O,query:j?{cursor:j}:void 0})),K=x.items.some((Z)=>_0(Z).some((X)=>X.definition.data_type==="TAG"))?await $.tagMap():new Map;return{items:x.items.map((Z)=>v1(this.client,Z,K)),nextCursor:x.next_cursor,hasMore:x.next_cursor!=null}}}function c1({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:G,url:L,...Y}){let J,T=G??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=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(J!==void 0)P.set("Last-Event-ID",J);try{let D={redirect:"follow",...Y,body:Y.serializedBody,headers:P,signal:I},C=new Request(L,D);if($)C=await $(L,D);let U=await(Y.fetch??globalThis.fetch)(C);if(!U.ok)throw Error(`SSE failed: ${U.status} ${U.statusText}`);if(!U.body)throw Error("No body in SSE response");let H=U.body.pipeThrough(new TextDecoderStream).getReader(),N="",g=()=>{try{H.cancel()}catch{}};I.addEventListener("abort",g);try{while(!0){let{done:d,value:l}=await H.read();if(d)break;N+=l,N=N.replace(/\r\n?/g,`
+`);let k=N.split(`
-`);U=g.pop()??"";for(let r of g){let p=r.split(`
+`);N=k.pop()??"";for(let r of k){let p=r.split(`
`),F=[],y;for(let R of p)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))y=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let h=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(h))V=h}let _,v=!1;if(F.length){let R=F.join(`
-`);try{_=JSON.parse(R),v=!0}catch{_=R}}if(v){if(S)await S(_);if(x)_=await x(_)}if(j?.({data:_,event:y,id:J,retry:V}),F.length)yield _}}}finally{I.removeEventListener("abort",k),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let C=Math.min(V*2**(B-1),X??30000);await T(C)}}}()}}var O7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},j7=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},x7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},Dj=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((G)=>encodeURIComponent(G))).join(j7(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=O7(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return IO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},IO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},Cj=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let G=[];Object.entries(S).forEach(([Y,J])=>{G=[...G,Y,$?J:encodeURIComponent(J)]});let L=G.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=x7(x),X=Object.entries(S).map(([G,L])=>IO({allowReserved:$,name:x==="deepObject"?`${j}[${G}]`:G,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var S7=/\{[^{}]+\}/g,Z7=({path:$,url:O})=>{let j=O,x=O.match(S7);if(x)for(let S of x){let K=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))K=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let G=$[Z];if(G===void 0||G===null)continue;if(Array.isArray(G)){j=j.replace(S,Dj({explode:K,name:Z,style:X,value:G}));continue}if(typeof G==="object"){j=j.replace(S,Cj({explode:K,name:Z,style:X,value:G,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${IO({name:Z,value:G})}`);continue}let L=encodeURIComponent(X==="label"?`.${G}`:G);j=j.replace(S,L)}return j},c1=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=Z7({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function P0($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var u1=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var d1={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var l1=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let G=Dj({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(G)S.push(G)}else if(typeof Z==="object"){let G=Cj({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(G)S.push(G)}else{let G=IO({allowReserved:X.allowReserved,name:K,value:Z});if(G)S.push(G)}}return S.join("&")}},r1=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},X7=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function p1($){for(let O of $.security??[]){if(X7($,O.name))continue;let j=await u1(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var F0=($)=>c1({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:l1($.querySerializer),url:$.url}),E0=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=Mj($.headers,O.headers),j},G7=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},Mj=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?G7(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class _j{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var a1=()=>({error:new _j,request:new _j,response:new _j}),K7=l1({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),Y7={"Content-Type":"application/json"},aO=($={})=>({...d1,headers:Y7,parseAs:"auto",querySerializer:K7,...$});var w0=($={})=>{let O=E0(aO(),$),j=()=>({...O}),x=(Y)=>{return O=E0(O,Y),j()},S=a1(),K=async(Y)=>{let J={...O,...Y,fetch:Y.fetch??O.fetch??globalThis.fetch,headers:Mj(O.headers,Y.headers),serializedBody:void 0};if(J.security)await p1(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let T=J,z=F0(T);return{opts:T,url:z}},Z=async(Y)=>{let J=Y.throwOnError??O.throwOnError,T=Y.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(Y),I={redirect:"follow",...V,body:P0(V)};z=new Request(B,I);for(let N of S.request.fns)if(N)z=await N(z,V);let P=V.fetch;W=await P(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?r1(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await W[N]();break;case"json":{let U=await W.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let C=await W.text(),E;try{E=JSON.parse(C)}catch{}throw E??C}catch(V){let B=V;for(let I of S.error.fns)if(I)B=await I(B,W,z,Y);if(B=B||{},J)throw B;return T==="data"?void 0:{error:B,request:z,response:W}}},X=(Y)=>(J)=>Z({...J,method:Y}),G=(Y)=>async(J)=>{let{opts:T,url:z}=await K(J);return m1({...T,body:T.body,method:Y,onRequest:async(W,V)=>{let B=new Request(W,V);for(let I of S.request.fns)if(I)B=await I(B,T);return B},serializedBody:P0(T),url:z})};return{buildUrl:(Y)=>F0({...O,...Y}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:G("CONNECT"),delete:G("DELETE"),get:G("GET"),head:G("HEAD"),options:G("OPTIONS"),patch:G("PATCH"),post:G("POST"),put:G("PUT"),trace:G("TRACE")},trace:X("TRACE")}};var i1=w0(aO());class n1{client;constructor($){this.client=$?.client??i1}}class s1{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class Aj extends n1{static __registry=new s1;constructor($){super($);Aj.__registry.set(this,$?.key)}discoverAgentCapabilitiesHandler($){return($.client??this.client).post({security:[{scheme:"bearer",type:"http"}],url:"/agent-capabilities/discover",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAgentCodingPreferences($){return($?.client??this.client).get({url:"/agent-coding-preferences",...$})}putAgentCodingPreferences($){return($.client??this.client).put({url:"/agent-coding-preferences",...$,headers:{"Content-Type":"application/json",...$.headers}})}listAgentConversations($){return($.client??this.client).get({security:[{scheme:"bearer",type:"http"}],url:"/agent-conversations/{channel_id}",...$})}startFreshAgentConversation($){return($.client??this.client).post({security:[{scheme:"bearer",type:"http"}],url:"/agent-conversations/{channel_id}/{bot_id}/start-fresh",...$,headers:{"Content-Type":"application/json",...$.headers}})}retryAgentConversationTurn($){return($.client??this.client).post({security:[{scheme:"bearer",type:"http"}],url:"/agent-conversations/{channel_id}/{bot_id}/turns/{source}/retry",...$,headers:{"Content-Type":"application/json",...$.headers}})}loadAgentModelsHandler($){return($.client??this.client).post({security:[{scheme:"bearer",type:"http"}],url:"/agent-models/load",...$,headers:{"Content-Type":"application/json",...$.headers}})}listAgentRepositories($){return($?.client??this.client).get({security:[{scheme:"bearer",type:"http"}],url:"/agent-repositories",...$})}listAgentRepositoryBranches($){return($.client??this.client).get({security:[{scheme:"bearer",type:"http"}],url:"/agent-repositories/branches",...$})}getAgentSandboxSize($){return($?.client??this.client).get({url:"/agent-sandbox-size",...$})}putAgentSandboxSize($){return($.client??this.client).put({url:"/agent-sandbox-size",...$,headers:{"Content-Type":"application/json",...$.headers}})}createAgentSession($){return($.client??this.client).post({url:"/agent-sessions",...$,headers:{"Content-Type":"application/json",...$.headers}})}agentSessionsForPullRequest($){return($.client??this.client).post({url:"/agent-sessions/by-pull-request",...$,headers:{"Content-Type":"application/json",...$.headers}})}agentSessionsForPullRequests($){return($.client??this.client).post({url:"/agent-sessions/by-pull-requests",...$,headers:{"Content-Type":"application/json",...$.headers}})}previewAgentSessions($){return($.client??this.client).post({url:"/agent-sessions/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}warmAgentSessionHandler($){return($.client??this.client).post({url:"/agent-sessions/warm",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteAgentSession($){return($.client??this.client).delete({url:"/agent-sessions/{session_id}",...$})}getAgentSession($){return($.client??this.client).get({url:"/agent-sessions/{session_id}",...$})}setAgentSessionArchived($){return($.client??this.client).put({url:"/agent-sessions/{session_id}/archived",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAgentSessionChanges($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/changes",...$})}getAgentSessionChangesPatch($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/changes/patch",...$})}refreshAgentSessionChanges($){return($.client??this.client).post({url:"/agent-sessions/{session_id}/changes/refresh",...$})}getCodeExecution($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/code-executions/{execution_id}",...$})}listExecutionReviews($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/code-executions/{execution_id}/reviews",...$})}controlAgentSession($){return($.client??this.client).post({url:"/agent-sessions/{session_id}/control",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAgentSessionLog($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/log",...$})}getAgentSessionFoldedLog($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/log/folded",...$})}renameAgentSession($){return($.client??this.client).put({url:"/agent-sessions/{session_id}/name",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAgentSessionPermissions($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/permissions",...$})}updateAgentSessionPermissions($){return($.client??this.client).patch({url:"/agent-sessions/{session_id}/permissions",...$,headers:{"Content-Type":"application/json",...$.headers}})}unlinkAgentSessionPullRequest($){return($.client??this.client).delete({url:"/agent-sessions/{session_id}/pull-requests",...$})}listAgentSessionPullRequests($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/pull-requests",...$})}linkAgentSessionPullRequest($){return($.client??this.client).put({url:"/agent-sessions/{session_id}/pull-requests",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAgentSessionQueue($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/queue",...$})}removeQueuedAction($){return($.client??this.client).delete({url:"/agent-sessions/{session_id}/queue/{action_id}",...$})}editQueuedAction($){return($.client??this.client).put({url:"/agent-sessions/{session_id}/queue/{action_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}steerQueuedAction($){return($.client??this.client).post({url:"/agent-sessions/{session_id}/queue/{action_id}/steer",...$})}createSessionReview($){return($.client??this.client).post({url:"/agent-sessions/{session_id}/reviews",...$,headers:{"Content-Type":"application/json",...$.headers}})}getSessionReview($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/reviews/{review_id}",...$})}decideSessionReview($){return($.client??this.client).post({url:"/agent-sessions/{session_id}/reviews/{review_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}putAgentSessionSandboxSize($){return($.client??this.client).put({url:"/agent-sessions/{session_id}/sandbox-size",...$,headers:{"Content-Type":"application/json",...$.headers}})}answerAgentSessionToolApproval($){return($.client??this.client).post({url:"/agent-sessions/{session_id}/tool-approvals/{approval_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}}function t1({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:G,url:L,...Y}){let J,T=G??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=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(J!==void 0)P.set("Last-Event-ID",J);try{let D={redirect:"follow",...Y,body:Y.serializedBody,headers:P,signal:I},C=new Request(L,D);if($)C=await $(L,D);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="",k=()=>{try{H.cancel()}catch{}};I.addEventListener("abort",k);try{while(!0){let{done:d,value:l}=await H.read();if(d)break;U+=l,U=U.replace(/\r\n?/g,`
-`);let g=U.split(`
+`);try{_=JSON.parse(R),v=!0}catch{_=R}}if(v){if(S)await S(_);if(x)_=await x(_)}if(j?.({data:_,event:y,id:J,retry:V}),F.length)yield _}}}finally{I.removeEventListener("abort",g),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let C=Math.min(V*2**(B-1),X??30000);await T(C)}}}()}}var j7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},x7=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},S7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},Cj=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((G)=>encodeURIComponent(G))).join(x7(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=j7(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return TO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},TO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},_j=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let G=[];Object.entries(S).forEach(([Y,J])=>{G=[...G,Y,$?J:encodeURIComponent(J)]});let L=G.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=S7(x),X=Object.entries(S).map(([G,L])=>TO({allowReserved:$,name:x==="deepObject"?`${j}[${G}]`:G,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var Z7=/\{[^{}]+\}/g,X7=({path:$,url:O})=>{let j=O,x=O.match(Z7);if(x)for(let S of x){let K=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))K=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let G=$[Z];if(G===void 0||G===null)continue;if(Array.isArray(G)){j=j.replace(S,Cj({explode:K,name:Z,style:X,value:G}));continue}if(typeof G==="object"){j=j.replace(S,_j({explode:K,name:Z,style:X,value:G,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${TO({name:Z,value:G})}`);continue}let L=encodeURIComponent(X==="label"?`.${G}`:G);j=j.replace(S,L)}return j},u1=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=X7({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function F0($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var d1=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var l1={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var r1=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let G=Cj({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(G)S.push(G)}else if(typeof Z==="object"){let G=_j({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(G)S.push(G)}else{let G=TO({allowReserved:X.allowReserved,name:K,value:Z});if(G)S.push(G)}}return S.join("&")}},p1=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},G7=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function a1($){for(let O of $.security??[]){if(G7($,O.name))continue;let j=await d1(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var E0=($)=>u1({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:r1($.querySerializer),url:$.url}),w0=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=Mj($.headers,O.headers),j},K7=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},Mj=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?K7(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class Aj{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var i1=()=>({error:new Aj,request:new Aj,response:new Aj}),Y7=r1({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),Q7={"Content-Type":"application/json"},iO=($={})=>({...l1,headers:Q7,parseAs:"auto",querySerializer:Y7,...$});var q0=($={})=>{let O=w0(iO(),$),j=()=>({...O}),x=(Y)=>{return O=w0(O,Y),j()},S=i1(),K=async(Y)=>{let J={...O,...Y,fetch:Y.fetch??O.fetch??globalThis.fetch,headers:Mj(O.headers,Y.headers),serializedBody:void 0};if(J.security)await a1(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let T=J,z=E0(T);return{opts:T,url:z}},Z=async(Y)=>{let J=Y.throwOnError??O.throwOnError,T=Y.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(Y),I={redirect:"follow",...V,body:F0(V)};z=new Request(B,I);for(let U of S.request.fns)if(U)z=await U(z,V);let P=V.fetch;W=await P(z);for(let U of S.response.fns)if(U)W=await U(W,z,V);let D={request:z,response:W};if(W.ok){let U=(V.parseAs==="auto"?p1(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let N;switch(U){case"arrayBuffer":case"blob":case"text":N=await W[U]();break;case"formData":N=new FormData;break;case"stream":N=W.body;break;case"json":default:N={};break}return V.responseStyle==="data"?N:{data:N,...D}}let H;switch(U){case"arrayBuffer":case"blob":case"formData":case"text":H=await W[U]();break;case"json":{let N=await W.text();H=N?JSON.parse(N):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(U==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let C=await W.text(),w;try{w=JSON.parse(C)}catch{}throw w??C}catch(V){let B=V;for(let I of S.error.fns)if(I)B=await I(B,W,z,Y);if(B=B||{},J)throw B;return T==="data"?void 0:{error:B,request:z,response:W}}},X=(Y)=>(J)=>Z({...J,method:Y}),G=(Y)=>async(J)=>{let{opts:T,url:z}=await K(J);return c1({...T,body:T.body,method:Y,onRequest:async(W,V)=>{let B=new Request(W,V);for(let I of S.request.fns)if(I)B=await I(B,T);return B},serializedBody:F0(T),url:z})};return{buildUrl:(Y)=>E0({...O,...Y}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:G("CONNECT"),delete:G("DELETE"),get:G("GET"),head:G("HEAD"),options:G("OPTIONS"),patch:G("PATCH"),post:G("POST"),put:G("PUT"),trace:G("TRACE")},trace:X("TRACE")}};var n1=q0(iO());class s1{client;constructor($){this.client=$?.client??n1}}class t1{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class Pj extends s1{static __registry=new t1;constructor($){super($);Pj.__registry.set(this,$?.key)}discoverAgentCapabilitiesHandler($){return($.client??this.client).post({security:[{scheme:"bearer",type:"http"}],url:"/agent-capabilities/discover",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAgentCodingPreferences($){return($?.client??this.client).get({url:"/agent-coding-preferences",...$})}putAgentCodingPreferences($){return($.client??this.client).put({url:"/agent-coding-preferences",...$,headers:{"Content-Type":"application/json",...$.headers}})}listAgentConversations($){return($.client??this.client).get({security:[{scheme:"bearer",type:"http"}],url:"/agent-conversations/{channel_id}",...$})}startFreshAgentConversation($){return($.client??this.client).post({security:[{scheme:"bearer",type:"http"}],url:"/agent-conversations/{channel_id}/{bot_id}/start-fresh",...$,headers:{"Content-Type":"application/json",...$.headers}})}retryAgentConversationTurn($){return($.client??this.client).post({security:[{scheme:"bearer",type:"http"}],url:"/agent-conversations/{channel_id}/{bot_id}/turns/{source}/retry",...$,headers:{"Content-Type":"application/json",...$.headers}})}loadAgentModelsHandler($){return($.client??this.client).post({security:[{scheme:"bearer",type:"http"}],url:"/agent-models/load",...$,headers:{"Content-Type":"application/json",...$.headers}})}listAgentRepositories($){return($?.client??this.client).get({security:[{scheme:"bearer",type:"http"}],url:"/agent-repositories",...$})}listAgentRepositoryBranches($){return($.client??this.client).get({security:[{scheme:"bearer",type:"http"}],url:"/agent-repositories/branches",...$})}getAgentSandboxSize($){return($?.client??this.client).get({url:"/agent-sandbox-size",...$})}putAgentSandboxSize($){return($.client??this.client).put({url:"/agent-sandbox-size",...$,headers:{"Content-Type":"application/json",...$.headers}})}createAgentSession($){return($.client??this.client).post({url:"/agent-sessions",...$,headers:{"Content-Type":"application/json",...$.headers}})}agentSessionsForPullRequest($){return($.client??this.client).post({url:"/agent-sessions/by-pull-request",...$,headers:{"Content-Type":"application/json",...$.headers}})}agentSessionsForPullRequests($){return($.client??this.client).post({url:"/agent-sessions/by-pull-requests",...$,headers:{"Content-Type":"application/json",...$.headers}})}previewAgentSessions($){return($.client??this.client).post({url:"/agent-sessions/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}warmAgentSessionHandler($){return($.client??this.client).post({url:"/agent-sessions/warm",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteAgentSession($){return($.client??this.client).delete({url:"/agent-sessions/{session_id}",...$})}getAgentSession($){return($.client??this.client).get({url:"/agent-sessions/{session_id}",...$})}setAgentSessionArchived($){return($.client??this.client).put({url:"/agent-sessions/{session_id}/archived",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAgentSessionChanges($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/changes",...$})}getAgentSessionChangesPatch($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/changes/patch",...$})}refreshAgentSessionChanges($){return($.client??this.client).post({url:"/agent-sessions/{session_id}/changes/refresh",...$})}getCodeExecution($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/code-executions/{execution_id}",...$})}listExecutionReviews($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/code-executions/{execution_id}/reviews",...$})}controlAgentSession($){return($.client??this.client).post({url:"/agent-sessions/{session_id}/control",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAgentSessionLog($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/log",...$})}getAgentSessionFoldedLog($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/log/folded",...$})}renameAgentSession($){return($.client??this.client).put({url:"/agent-sessions/{session_id}/name",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAgentSessionPermissions($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/permissions",...$})}updateAgentSessionPermissions($){return($.client??this.client).patch({url:"/agent-sessions/{session_id}/permissions",...$,headers:{"Content-Type":"application/json",...$.headers}})}unlinkAgentSessionPullRequest($){return($.client??this.client).delete({url:"/agent-sessions/{session_id}/pull-requests",...$})}listAgentSessionPullRequests($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/pull-requests",...$})}linkAgentSessionPullRequest($){return($.client??this.client).put({url:"/agent-sessions/{session_id}/pull-requests",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAgentSessionQueue($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/queue",...$})}removeQueuedAction($){return($.client??this.client).delete({url:"/agent-sessions/{session_id}/queue/{action_id}",...$})}editQueuedAction($){return($.client??this.client).put({url:"/agent-sessions/{session_id}/queue/{action_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}steerQueuedAction($){return($.client??this.client).post({url:"/agent-sessions/{session_id}/queue/{action_id}/steer",...$})}createSessionReview($){return($.client??this.client).post({url:"/agent-sessions/{session_id}/reviews",...$,headers:{"Content-Type":"application/json",...$.headers}})}getSessionReview($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/reviews/{review_id}",...$})}decideSessionReview($){return($.client??this.client).post({url:"/agent-sessions/{session_id}/reviews/{review_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}putAgentSessionSandboxSize($){return($.client??this.client).put({url:"/agent-sessions/{session_id}/sandbox-size",...$,headers:{"Content-Type":"application/json",...$.headers}})}answerAgentSessionToolApproval($){return($.client??this.client).post({url:"/agent-sessions/{session_id}/tool-approvals/{approval_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}}function e1({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:G,url:L,...Y}){let J,T=G??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=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(J!==void 0)P.set("Last-Event-ID",J);try{let D={redirect:"follow",...Y,body:Y.serializedBody,headers:P,signal:I},C=new Request(L,D);if($)C=await $(L,D);let U=await(Y.fetch??globalThis.fetch)(C);if(!U.ok)throw Error(`SSE failed: ${U.status} ${U.statusText}`);if(!U.body)throw Error("No body in SSE response");let H=U.body.pipeThrough(new TextDecoderStream).getReader(),N="",g=()=>{try{H.cancel()}catch{}};I.addEventListener("abort",g);try{while(!0){let{done:d,value:l}=await H.read();if(d)break;N+=l,N=N.replace(/\r\n?/g,`
+`);let k=N.split(`
-`);U=g.pop()??"";for(let r of g){let p=r.split(`
+`);N=k.pop()??"";for(let r of k){let p=r.split(`
`),F=[],y;for(let R of p)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))y=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let h=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(h))V=h}let _,v=!1;if(F.length){let R=F.join(`
-`);try{_=JSON.parse(R),v=!0}catch{_=R}}if(v){if(S)await S(_);if(x)_=await x(_)}if(j?.({data:_,event:y,id:J,retry:V}),F.length)yield _}}}finally{I.removeEventListener("abort",k),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let C=Math.min(V*2**(B-1),X??30000);await T(C)}}}()}}var Q7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},J7=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},V7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},Pj=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((G)=>encodeURIComponent(G))).join(J7(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=Q7(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return TO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},TO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},Fj=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let G=[];Object.entries(S).forEach(([Y,J])=>{G=[...G,Y,$?J:encodeURIComponent(J)]});let L=G.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=V7(x),X=Object.entries(S).map(([G,L])=>TO({allowReserved:$,name:x==="deepObject"?`${j}[${G}]`:G,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var W7=/\{[^{}]+\}/g,B7=({path:$,url:O})=>{let j=O,x=O.match(W7);if(x)for(let S of x){let K=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))K=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let G=$[Z];if(G===void 0||G===null)continue;if(Array.isArray(G)){j=j.replace(S,Pj({explode:K,name:Z,style:X,value:G}));continue}if(typeof G==="object"){j=j.replace(S,Fj({explode:K,name:Z,style:X,value:G,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${TO({name:Z,value:G})}`);continue}let L=encodeURIComponent(X==="label"?`.${G}`:G);j=j.replace(S,L)}return j},e1=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=B7({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function q0($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var o1=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var $S={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var OS=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let G=Pj({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(G)S.push(G)}else if(typeof Z==="object"){let G=Fj({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(G)S.push(G)}else{let G=TO({allowReserved:X.allowReserved,name:K,value:Z});if(G)S.push(G)}}return S.join("&")}},jS=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},L7=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function xS($){for(let O of $.security??[]){if(L7($,O.name))continue;let j=await o1(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var f0=($)=>e1({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:OS($.querySerializer),url:$.url}),b0=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=wj($.headers,O.headers),j},N7=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},wj=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?N7(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class Ej{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var SS=()=>({error:new Ej,request:new Ej,response:new Ej}),U7=OS({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),z7={"Content-Type":"application/json"},iO=($={})=>({...$S,headers:z7,parseAs:"auto",querySerializer:U7,...$});var k0=($={})=>{let O=b0(iO(),$),j=()=>({...O}),x=(Y)=>{return O=b0(O,Y),j()},S=SS(),K=async(Y)=>{let J={...O,...Y,fetch:Y.fetch??O.fetch??globalThis.fetch,headers:wj(O.headers,Y.headers),serializedBody:void 0};if(J.security)await xS(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let T=J,z=f0(T);return{opts:T,url:z}},Z=async(Y)=>{let J=Y.throwOnError??O.throwOnError,T=Y.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(Y),I={redirect:"follow",...V,body:q0(V)};z=new Request(B,I);for(let N of S.request.fns)if(N)z=await N(z,V);let P=V.fetch;W=await P(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?jS(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await W[N]();break;case"json":{let U=await W.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let C=await W.text(),E;try{E=JSON.parse(C)}catch{}throw E??C}catch(V){let B=V;for(let I of S.error.fns)if(I)B=await I(B,W,z,Y);if(B=B||{},J)throw B;return T==="data"?void 0:{error:B,request:z,response:W}}},X=(Y)=>(J)=>Z({...J,method:Y}),G=(Y)=>async(J)=>{let{opts:T,url:z}=await K(J);return t1({...T,body:T.body,method:Y,onRequest:async(W,V)=>{let B=new Request(W,V);for(let I of S.request.fns)if(I)B=await I(B,T);return B},serializedBody:q0(T),url:z})};return{buildUrl:(Y)=>f0({...O,...Y}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:G("CONNECT"),delete:G("DELETE"),get:G("GET"),head:G("HEAD"),options:G("OPTIONS"),patch:G("PATCH"),post:G("POST"),put:G("PUT"),trace:G("TRACE")},trace:X("TRACE")}};var ZS=k0(iO());class XS{client;constructor($){this.client=$?.client??ZS}}class GS{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class qj extends XS{static __registry=new GS;constructor($){super($);qj.__registry.set(this,$?.key)}updateAiBillingAutoReload($){return($.client??this.client).patch({url:"/ai-billing/auto-reload",...$,headers:{"Content-Type":"application/json",...$.headers}})}createAiCreditCheckout($){return($.client??this.client).post({url:"/ai-billing/credits/checkout",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateAiBillingOverage($){return($.client??this.client).patch({url:"/ai-billing/overage",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAiBillingPlans($){return($?.client??this.client).get({url:"/ai-billing/plans",...$})}getAiBillingSummary($){return($?.client??this.client).get({url:"/ai-billing/summary",...$})}disconnectCodex($){return($?.client??this.client).delete({url:"/codex",...$})}getCodexConnection($){return($?.client??this.client).get({url:"/codex",...$})}configureCodex($){return($.client??this.client).put({url:"/codex/config",...$,headers:{"Content-Type":"application/json",...$.headers}})}listCodexEnvironments($){return($?.client??this.client).get({url:"/codex/environments",...$})}startCodexLogin($){return($?.client??this.client).post({url:"/codex/login",...$})}cancelCodexLogin($){return($.client??this.client).delete({url:"/codex/login/{attempt_id}",...$})}pollCodexLogin($){return($.client??this.client).get({url:"/codex/login/{attempt_id}",...$})}deleteCursorApiKey($){return($?.client??this.client).delete({url:"/cursor-api-key",...$})}getCursorApiKey($){return($?.client??this.client).get({url:"/cursor-api-key",...$})}putCursorApiKey($){return($.client??this.client).put({url:"/cursor-api-key",...$,headers:{"Content-Type":"application/json",...$.headers}})}putCursorDefaultModel($){return($.client??this.client).put({url:"/cursor-api-key/default-model",...$,headers:{"Content-Type":"application/json",...$.headers}})}listCursorModels($){return($?.client??this.client).get({url:"/cursor-api-key/models",...$})}verifyFusionauthUserEmail($){return($.client??this.client).get({url:"/email/fusionauth/verify/{verification_id}",...$})}resendFusionauthVerifyUserEmail($){return($.client??this.client).post({url:"/email/fusionauth_resend",...$,headers:{"Content-Type":"application/json",...$.headers}})}generateEmailLink($){return($.client??this.client).post({url:"/email/generate/link",...$,headers:{"Content-Type":"application/json",...$.headers}})}verifyEmailLink($){return($.client??this.client).get({url:"/email/verify/{verification_id}",...$})}setGithubPullRequestDraft($){return($.client??this.client).post({url:"/github_pull_requests/draft",...$,headers:{"Content-Type":"application/json",...$.headers}})}enrichGithubPullRequests($){return($.client??this.client).post({url:"/github_pull_requests/enrich",...$,headers:{"Content-Type":"application/json",...$.headers}})}mergeGithubPullRequest($){return($.client??this.client).post({url:"/github_pull_requests/merge",...$,headers:{"Content-Type":"application/json",...$.headers}})}getGithubPullRequestMergeability($){return($.client??this.client).post({url:"/github_pull_requests/mergeability",...$,headers:{"Content-Type":"application/json",...$.headers}})}listGtmInviteLinks($){return($?.client??this.client).get({url:"/gtm-invite/links",...$})}createGtmInviteLink($){return($.client??this.client).post({url:"/gtm-invite/links",...$,headers:{"Content-Type":"application/json",...$.headers}})}revokeGtmInviteLink($){return($.client??this.client).delete({url:"/gtm-invite/links/{id}",...$})}getGtmInviteOffer($){return($?.client??this.client).get({url:"/gtm-invite/offer",...$})}resolveGtmInviteLink($){return($.client??this.client).get({url:"/gtm-invite/public/{token}",...$})}redeemGtmInviteLink($){return($.client??this.client).post({url:"/gtm-invite/redeem",...$,headers:{"Content-Type":"application/json",...$.headers}})}healthHandler($){return($?.client??this.client).get({url:"/health",...$})}macroApiToken($){return($.client??this.client).get({url:"/jwt/macro_api_token",...$})}refresh($){return($?.client??this.client).post({url:"/jwt/refresh",...$})}createInProgressLink($){return($?.client??this.client).post({url:"/link",...$})}emailConnectionProviders($){return($?.client??this.client).get({url:"/link/email/providers",...$})}deleteGithubLink($){return($?.client??this.client).delete({url:"/link/github",...$})}initGithubLink($){return($.client??this.client).post({url:"/link/github",...$})}checkGithubLinkStatus($){return($?.client??this.client).get({url:"/link/github/status",...$})}initGmailLink($){return($.client??this.client).post({url:"/link/gmail",...$})}checkGmailLinkStatus($){return($?.client??this.client).get({url:"/link/gmail/status",...$})}initOutlookLink($){return($?.client??this.client).post({url:"/link/outlook",...$})}appleLogin($){return($.client??this.client).post({url:"/login/apple",...$,headers:{"Content-Type":"application/json",...$.headers}})}passwordLogin($){return($.client??this.client).post({url:"/login/password",...$,headers:{"Content-Type":"application/json",...$.headers}})}passwordlessLogin($){return($.client??this.client).post({url:"/login/passwordless",...$,headers:{"Content-Type":"application/json",...$.headers}})}ssoLogin($){return($.client??this.client).get({url:"/login/sso",...$})}logout($){return($?.client??this.client).post({url:"/logout",...$})}createMergeRequest($){return($.client??this.client).post({url:"/merge",...$,headers:{"Content-Type":"application/json",...$.headers}})}verifyMergeRequest($){return($.client??this.client).get({url:"/merge/verify/{code}",...$})}sendMobileWelcomeEmail($){return($.client??this.client).post({url:"/mobile-welcome-email",...$,headers:{"Content-Type":"application/json",...$.headers}})}passwordlessCallback($){return($.client??this.client).get({url:"/oauth/passwordless/{code}",...$})}oauthRedirect($){return($?.client??this.client).get({url:"/oauth/redirect",...$})}oauth2Callback($){return($.client??this.client).get({url:"/oauth2/{provider}/callback",...$})}getPermissions($){return($?.client??this.client).get({url:"/permissions",...$})}getUserPermissions($){return($?.client??this.client).get({url:"/permissions/me",...$})}getReferralCode($){return($?.client??this.client).get({url:"/referral/code",...$})}sendReferralCode($){return($.client??this.client).post({url:"/referral/send",...$,headers:{"Content-Type":"application/json",...$.headers}})}sessionCreation($){return($?.client??this.client).post({url:"/session",...$})}sessionLogin($){return($.client??this.client).get({url:"/session/login/{session_code}",...$})}deleteTeam($){return($?.client??this.client).delete({url:"/team",...$})}getTeam($){return($?.client??this.client).get({url:"/team",...$})}patchTeam($){return($.client??this.client).patch({url:"/team",...$,headers:{"Content-Type":"application/json",...$.headers}})}createTeam($){return($.client??this.client).post({url:"/team",...$,headers:{"Content-Type":"application/json",...$.headers}})}toggleTeamAutoJoinDomain($){return($?.client??this.client).post({url:"/team/auto-join-domain/toggle",...$})}patchTeamCrmSettings($){return($.client??this.client).patch({url:"/team/crm",...$,headers:{"Content-Type":"application/json",...$.headers}})}inviteToTeam($){return($.client??this.client).post({url:"/team/invite",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteTeamInviteLink($){return($?.client??this.client).delete({url:"/team/invite-link",...$})}getTeamInviteLink($){return($?.client??this.client).get({url:"/team/invite-link",...$})}createTeamInviteLink($){return($?.client??this.client).post({url:"/team/invite-link",...$})}joinTeamByInviteLink($){return($.client??this.client).post({url:"/team/invite-link/join",...$,headers:{"Content-Type":"application/json",...$.headers}})}getTeamByInviteLink($){return($.client??this.client).post({url:"/team/invite-link/team",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteTeamInviteHandler($){return($.client??this.client).delete({url:"/team/invite/{team_invite_id}",...$})}getTeamInvites($){return($?.client??this.client).get({url:"/team/invites",...$})}rejectInvitation($){return($.client??this.client).delete({url:"/team/join/{team_invite_id}",...$})}joinTeam($){return($.client??this.client).get({url:"/team/join/{team_invite_id}",...$})}patchTeamMemberPlan($){return($.client??this.client).patch({url:"/team/members/{member_user_id}/plan",...$,headers:{"Content-Type":"application/json",...$.headers}})}toggleTeamNonAdminInvites($){return($?.client??this.client).post({url:"/team/non-admin-invites/toggle",...$})}removeUserFromTeam($){return($.client??this.client).delete({url:"/team/remove/{remove_user_id}",...$})}getUserTeams($){return($?.client??this.client).get({url:"/team/user",...$})}getUserInvites($){return($?.client??this.client).get({url:"/team/user/invites",...$})}getUserNames($){return($.client??this.client).post({url:"/user/get_names",...$,headers:{"Content-Type":"application/json",...$.headers}})}getUserNamesWithEmail($){return($.client??this.client).post({url:"/user/get_names_with_email",...$,headers:{"Content-Type":"application/json",...$.headers}})}patchUserGroup($){return($.client??this.client).patch({url:"/user/group",...$,headers:{"Content-Type":"application/json",...$.headers}})}getLegacyUserPermissions($){return($?.client??this.client).get({url:"/user/legacy_user_permissions",...$})}getUserLinkExists($){return($.client??this.client).get({url:"/user/link_exists",...$})}deleteUser($){return($?.client??this.client).delete({url:"/user/me",...$})}getUserInfo($){return($?.client??this.client).get({url:"/user/me",...$})}getUserName($){return($?.client??this.client).get({url:"/user/name",...$})}putUserName($){return($?.client??this.client).put({url:"/user/name",...$})}patchUserOnboarding($){return($.client??this.client).patch({url:"/user/onboarding",...$,headers:{"Content-Type":"application/json",...$.headers}})}getUserOrganization($){return($?.client??this.client).get({url:"/user/organization",...$})}putProfilePicture($){return($.client??this.client).put({url:"/user/profile_picture",...$})}postProfilePictures($){return($.client??this.client).post({url:"/user/profile_pictures",...$,headers:{"Content-Type":"application/json",...$.headers}})}getUserQuota($){return($?.client??this.client).get({url:"/user/quota",...$})}createCheckoutSessionV2($){return($.client??this.client).post({url:"/user/stripe/checkoutv2",...$,headers:{"Content-Type":"application/json",...$.headers}})}getSubscriptionStatus($){return($?.client??this.client).get({url:"/user/stripe/plan",...$})}changePlan($){return($.client??this.client).post({url:"/user/stripe/plan",...$,headers:{"Content-Type":"application/json",...$.headers}})}createPortalSession($){return($.client??this.client).post({url:"/user/stripe/portal",...$,headers:{"Content-Type":"application/json",...$.headers}})}getTrialEligibility($){return($?.client??this.client).get({url:"/user/stripe/trial_eligibility",...$})}patchUserTutorial($){return($.client??this.client).patch({url:"/user/tutorial",...$,headers:{"Content-Type":"application/json",...$.headers}})}}function KS({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:G,url:L,...Y}){let J,T=G??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=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(J!==void 0)P.set("Last-Event-ID",J);try{let D={redirect:"follow",...Y,body:Y.serializedBody,headers:P,signal:I},C=new Request(L,D);if($)C=await $(L,D);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="",k=()=>{try{H.cancel()}catch{}};I.addEventListener("abort",k);try{while(!0){let{done:d,value:l}=await H.read();if(d)break;U+=l,U=U.replace(/\r\n?/g,`
-`);let g=U.split(`
+`);try{_=JSON.parse(R),v=!0}catch{_=R}}if(v){if(S)await S(_);if(x)_=await x(_)}if(j?.({data:_,event:y,id:J,retry:V}),F.length)yield _}}}finally{I.removeEventListener("abort",g),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let C=Math.min(V*2**(B-1),X??30000);await T(C)}}}()}}var J7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},V7=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},W7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},Fj=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((G)=>encodeURIComponent(G))).join(V7(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=J7(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return HO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},HO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},Ej=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let G=[];Object.entries(S).forEach(([Y,J])=>{G=[...G,Y,$?J:encodeURIComponent(J)]});let L=G.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=W7(x),X=Object.entries(S).map(([G,L])=>HO({allowReserved:$,name:x==="deepObject"?`${j}[${G}]`:G,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var B7=/\{[^{}]+\}/g,L7=({path:$,url:O})=>{let j=O,x=O.match(B7);if(x)for(let S of x){let K=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))K=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let G=$[Z];if(G===void 0||G===null)continue;if(Array.isArray(G)){j=j.replace(S,Fj({explode:K,name:Z,style:X,value:G}));continue}if(typeof G==="object"){j=j.replace(S,Ej({explode:K,name:Z,style:X,value:G,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${HO({name:Z,value:G})}`);continue}let L=encodeURIComponent(X==="label"?`.${G}`:G);j=j.replace(S,L)}return j},o1=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=L7({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function f0($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var $S=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var OS={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var jS=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let G=Fj({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(G)S.push(G)}else if(typeof Z==="object"){let G=Ej({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(G)S.push(G)}else{let G=HO({allowReserved:X.allowReserved,name:K,value:Z});if(G)S.push(G)}}return S.join("&")}},xS=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},U7=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function SS($){for(let O of $.security??[]){if(U7($,O.name))continue;let j=await $S(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var b0=($)=>o1({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:jS($.querySerializer),url:$.url}),g0=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=qj($.headers,O.headers),j},N7=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},qj=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?N7(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class wj{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var ZS=()=>({error:new wj,request:new wj,response:new wj}),z7=jS({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),I7={"Content-Type":"application/json"},nO=($={})=>({...OS,headers:I7,parseAs:"auto",querySerializer:z7,...$});var k0=($={})=>{let O=g0(nO(),$),j=()=>({...O}),x=(Y)=>{return O=g0(O,Y),j()},S=ZS(),K=async(Y)=>{let J={...O,...Y,fetch:Y.fetch??O.fetch??globalThis.fetch,headers:qj(O.headers,Y.headers),serializedBody:void 0};if(J.security)await SS(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let T=J,z=b0(T);return{opts:T,url:z}},Z=async(Y)=>{let J=Y.throwOnError??O.throwOnError,T=Y.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(Y),I={redirect:"follow",...V,body:f0(V)};z=new Request(B,I);for(let U of S.request.fns)if(U)z=await U(z,V);let P=V.fetch;W=await P(z);for(let U of S.response.fns)if(U)W=await U(W,z,V);let D={request:z,response:W};if(W.ok){let U=(V.parseAs==="auto"?xS(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let N;switch(U){case"arrayBuffer":case"blob":case"text":N=await W[U]();break;case"formData":N=new FormData;break;case"stream":N=W.body;break;case"json":default:N={};break}return V.responseStyle==="data"?N:{data:N,...D}}let H;switch(U){case"arrayBuffer":case"blob":case"formData":case"text":H=await W[U]();break;case"json":{let N=await W.text();H=N?JSON.parse(N):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(U==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let C=await W.text(),w;try{w=JSON.parse(C)}catch{}throw w??C}catch(V){let B=V;for(let I of S.error.fns)if(I)B=await I(B,W,z,Y);if(B=B||{},J)throw B;return T==="data"?void 0:{error:B,request:z,response:W}}},X=(Y)=>(J)=>Z({...J,method:Y}),G=(Y)=>async(J)=>{let{opts:T,url:z}=await K(J);return e1({...T,body:T.body,method:Y,onRequest:async(W,V)=>{let B=new Request(W,V);for(let I of S.request.fns)if(I)B=await I(B,T);return B},serializedBody:f0(T),url:z})};return{buildUrl:(Y)=>b0({...O,...Y}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:G("CONNECT"),delete:G("DELETE"),get:G("GET"),head:G("HEAD"),options:G("OPTIONS"),patch:G("PATCH"),post:G("POST"),put:G("PUT"),trace:G("TRACE")},trace:X("TRACE")}};var XS=k0(nO());class GS{client;constructor($){this.client=$?.client??XS}}class KS{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class fj extends GS{static __registry=new KS;constructor($){super($);fj.__registry.set(this,$?.key)}updateAiBillingAutoReload($){return($.client??this.client).patch({url:"/ai-billing/auto-reload",...$,headers:{"Content-Type":"application/json",...$.headers}})}createAiCreditCheckout($){return($.client??this.client).post({url:"/ai-billing/credits/checkout",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateAiBillingOverage($){return($.client??this.client).patch({url:"/ai-billing/overage",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAiBillingPlans($){return($?.client??this.client).get({url:"/ai-billing/plans",...$})}getAiBillingSummary($){return($?.client??this.client).get({url:"/ai-billing/summary",...$})}disconnectCodex($){return($?.client??this.client).delete({url:"/codex",...$})}getCodexConnection($){return($?.client??this.client).get({url:"/codex",...$})}configureCodex($){return($.client??this.client).put({url:"/codex/config",...$,headers:{"Content-Type":"application/json",...$.headers}})}listCodexEnvironments($){return($?.client??this.client).get({url:"/codex/environments",...$})}startCodexLogin($){return($?.client??this.client).post({url:"/codex/login",...$})}cancelCodexLogin($){return($.client??this.client).delete({url:"/codex/login/{attempt_id}",...$})}pollCodexLogin($){return($.client??this.client).get({url:"/codex/login/{attempt_id}",...$})}deleteCursorApiKey($){return($?.client??this.client).delete({url:"/cursor-api-key",...$})}getCursorApiKey($){return($?.client??this.client).get({url:"/cursor-api-key",...$})}putCursorApiKey($){return($.client??this.client).put({url:"/cursor-api-key",...$,headers:{"Content-Type":"application/json",...$.headers}})}putCursorDefaultModel($){return($.client??this.client).put({url:"/cursor-api-key/default-model",...$,headers:{"Content-Type":"application/json",...$.headers}})}listCursorModels($){return($?.client??this.client).get({url:"/cursor-api-key/models",...$})}verifyFusionauthUserEmail($){return($.client??this.client).get({url:"/email/fusionauth/verify/{verification_id}",...$})}resendFusionauthVerifyUserEmail($){return($.client??this.client).post({url:"/email/fusionauth_resend",...$,headers:{"Content-Type":"application/json",...$.headers}})}generateEmailLink($){return($.client??this.client).post({url:"/email/generate/link",...$,headers:{"Content-Type":"application/json",...$.headers}})}verifyEmailLink($){return($.client??this.client).get({url:"/email/verify/{verification_id}",...$})}setGithubPullRequestDraft($){return($.client??this.client).post({url:"/github_pull_requests/draft",...$,headers:{"Content-Type":"application/json",...$.headers}})}enrichGithubPullRequests($){return($.client??this.client).post({url:"/github_pull_requests/enrich",...$,headers:{"Content-Type":"application/json",...$.headers}})}mergeGithubPullRequest($){return($.client??this.client).post({url:"/github_pull_requests/merge",...$,headers:{"Content-Type":"application/json",...$.headers}})}getGithubPullRequestMergeability($){return($.client??this.client).post({url:"/github_pull_requests/mergeability",...$,headers:{"Content-Type":"application/json",...$.headers}})}listGtmInviteLinks($){return($?.client??this.client).get({url:"/gtm-invite/links",...$})}createGtmInviteLink($){return($.client??this.client).post({url:"/gtm-invite/links",...$,headers:{"Content-Type":"application/json",...$.headers}})}revokeGtmInviteLink($){return($.client??this.client).delete({url:"/gtm-invite/links/{id}",...$})}getGtmInviteOffer($){return($?.client??this.client).get({url:"/gtm-invite/offer",...$})}resolveGtmInviteLink($){return($.client??this.client).get({url:"/gtm-invite/public/{token}",...$})}redeemGtmInviteLink($){return($.client??this.client).post({url:"/gtm-invite/redeem",...$,headers:{"Content-Type":"application/json",...$.headers}})}healthHandler($){return($?.client??this.client).get({url:"/health",...$})}macroApiToken($){return($.client??this.client).get({url:"/jwt/macro_api_token",...$})}refresh($){return($?.client??this.client).post({url:"/jwt/refresh",...$})}createInProgressLink($){return($?.client??this.client).post({url:"/link",...$})}emailConnectionProviders($){return($?.client??this.client).get({url:"/link/email/providers",...$})}deleteGithubLink($){return($?.client??this.client).delete({url:"/link/github",...$})}initGithubLink($){return($.client??this.client).post({url:"/link/github",...$})}checkGithubLinkStatus($){return($?.client??this.client).get({url:"/link/github/status",...$})}initGmailLink($){return($.client??this.client).post({url:"/link/gmail",...$})}checkGmailLinkStatus($){return($?.client??this.client).get({url:"/link/gmail/status",...$})}initOutlookLink($){return($?.client??this.client).post({url:"/link/outlook",...$})}appleLogin($){return($.client??this.client).post({url:"/login/apple",...$,headers:{"Content-Type":"application/json",...$.headers}})}passwordLogin($){return($.client??this.client).post({url:"/login/password",...$,headers:{"Content-Type":"application/json",...$.headers}})}passwordlessLogin($){return($.client??this.client).post({url:"/login/passwordless",...$,headers:{"Content-Type":"application/json",...$.headers}})}ssoLogin($){return($.client??this.client).get({url:"/login/sso",...$})}logout($){return($?.client??this.client).post({url:"/logout",...$})}createMergeRequest($){return($.client??this.client).post({url:"/merge",...$,headers:{"Content-Type":"application/json",...$.headers}})}verifyMergeRequest($){return($.client??this.client).get({url:"/merge/verify/{code}",...$})}sendMobileWelcomeEmail($){return($.client??this.client).post({url:"/mobile-welcome-email",...$,headers:{"Content-Type":"application/json",...$.headers}})}passwordlessCallback($){return($.client??this.client).get({url:"/oauth/passwordless/{code}",...$})}oauthRedirect($){return($?.client??this.client).get({url:"/oauth/redirect",...$})}oauth2Callback($){return($.client??this.client).get({url:"/oauth2/{provider}/callback",...$})}getPermissions($){return($?.client??this.client).get({url:"/permissions",...$})}getUserPermissions($){return($?.client??this.client).get({url:"/permissions/me",...$})}getReferralCode($){return($?.client??this.client).get({url:"/referral/code",...$})}sendReferralCode($){return($.client??this.client).post({url:"/referral/send",...$,headers:{"Content-Type":"application/json",...$.headers}})}sessionCreation($){return($?.client??this.client).post({url:"/session",...$})}sessionLogin($){return($.client??this.client).get({url:"/session/login/{session_code}",...$})}deleteTeam($){return($?.client??this.client).delete({url:"/team",...$})}getTeam($){return($?.client??this.client).get({url:"/team",...$})}patchTeam($){return($.client??this.client).patch({url:"/team",...$,headers:{"Content-Type":"application/json",...$.headers}})}createTeam($){return($.client??this.client).post({url:"/team",...$,headers:{"Content-Type":"application/json",...$.headers}})}toggleTeamAutoJoinDomain($){return($?.client??this.client).post({url:"/team/auto-join-domain/toggle",...$})}patchTeamCrmSettings($){return($.client??this.client).patch({url:"/team/crm",...$,headers:{"Content-Type":"application/json",...$.headers}})}inviteToTeam($){return($.client??this.client).post({url:"/team/invite",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteTeamInviteLink($){return($?.client??this.client).delete({url:"/team/invite-link",...$})}getTeamInviteLink($){return($?.client??this.client).get({url:"/team/invite-link",...$})}createTeamInviteLink($){return($?.client??this.client).post({url:"/team/invite-link",...$})}joinTeamByInviteLink($){return($.client??this.client).post({url:"/team/invite-link/join",...$,headers:{"Content-Type":"application/json",...$.headers}})}getTeamByInviteLink($){return($.client??this.client).post({url:"/team/invite-link/team",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteTeamInviteHandler($){return($.client??this.client).delete({url:"/team/invite/{team_invite_id}",...$})}getTeamInvites($){return($?.client??this.client).get({url:"/team/invites",...$})}rejectInvitation($){return($.client??this.client).delete({url:"/team/join/{team_invite_id}",...$})}joinTeam($){return($.client??this.client).get({url:"/team/join/{team_invite_id}",...$})}patchTeamMemberPlan($){return($.client??this.client).patch({url:"/team/members/{member_user_id}/plan",...$,headers:{"Content-Type":"application/json",...$.headers}})}toggleTeamNonAdminInvites($){return($?.client??this.client).post({url:"/team/non-admin-invites/toggle",...$})}removeUserFromTeam($){return($.client??this.client).delete({url:"/team/remove/{remove_user_id}",...$})}getUserTeams($){return($?.client??this.client).get({url:"/team/user",...$})}getUserInvites($){return($?.client??this.client).get({url:"/team/user/invites",...$})}getUserNames($){return($.client??this.client).post({url:"/user/get_names",...$,headers:{"Content-Type":"application/json",...$.headers}})}getUserNamesWithEmail($){return($.client??this.client).post({url:"/user/get_names_with_email",...$,headers:{"Content-Type":"application/json",...$.headers}})}patchUserGroup($){return($.client??this.client).patch({url:"/user/group",...$,headers:{"Content-Type":"application/json",...$.headers}})}getLegacyUserPermissions($){return($?.client??this.client).get({url:"/user/legacy_user_permissions",...$})}getUserLinkExists($){return($.client??this.client).get({url:"/user/link_exists",...$})}deleteUser($){return($?.client??this.client).delete({url:"/user/me",...$})}getUserInfo($){return($?.client??this.client).get({url:"/user/me",...$})}getUserName($){return($?.client??this.client).get({url:"/user/name",...$})}putUserName($){return($?.client??this.client).put({url:"/user/name",...$})}patchUserOnboarding($){return($.client??this.client).patch({url:"/user/onboarding",...$,headers:{"Content-Type":"application/json",...$.headers}})}getUserOrganization($){return($?.client??this.client).get({url:"/user/organization",...$})}putProfilePicture($){return($.client??this.client).put({url:"/user/profile_picture",...$})}postProfilePictures($){return($.client??this.client).post({url:"/user/profile_pictures",...$,headers:{"Content-Type":"application/json",...$.headers}})}getUserQuota($){return($?.client??this.client).get({url:"/user/quota",...$})}createCheckoutSessionV2($){return($.client??this.client).post({url:"/user/stripe/checkoutv2",...$,headers:{"Content-Type":"application/json",...$.headers}})}getSubscriptionStatus($){return($?.client??this.client).get({url:"/user/stripe/plan",...$})}changePlan($){return($.client??this.client).post({url:"/user/stripe/plan",...$,headers:{"Content-Type":"application/json",...$.headers}})}createPortalSession($){return($.client??this.client).post({url:"/user/stripe/portal",...$,headers:{"Content-Type":"application/json",...$.headers}})}getTrialEligibility($){return($?.client??this.client).get({url:"/user/stripe/trial_eligibility",...$})}patchUserTutorial($){return($.client??this.client).patch({url:"/user/tutorial",...$,headers:{"Content-Type":"application/json",...$.headers}})}}function YS({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:G,url:L,...Y}){let J,T=G??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=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(J!==void 0)P.set("Last-Event-ID",J);try{let D={redirect:"follow",...Y,body:Y.serializedBody,headers:P,signal:I},C=new Request(L,D);if($)C=await $(L,D);let U=await(Y.fetch??globalThis.fetch)(C);if(!U.ok)throw Error(`SSE failed: ${U.status} ${U.statusText}`);if(!U.body)throw Error("No body in SSE response");let H=U.body.pipeThrough(new TextDecoderStream).getReader(),N="",g=()=>{try{H.cancel()}catch{}};I.addEventListener("abort",g);try{while(!0){let{done:d,value:l}=await H.read();if(d)break;N+=l,N=N.replace(/\r\n?/g,`
+`);let k=N.split(`
-`);U=g.pop()??"";for(let r of g){let p=r.split(`
+`);N=k.pop()??"";for(let r of k){let p=r.split(`
`),F=[],y;for(let R of p)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))y=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let h=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(h))V=h}let _,v=!1;if(F.length){let R=F.join(`
-`);try{_=JSON.parse(R),v=!0}catch{_=R}}if(v){if(S)await S(_);if(x)_=await x(_)}if(j?.({data:_,event:y,id:J,retry:V}),F.length)yield _}}}finally{I.removeEventListener("abort",k),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let C=Math.min(V*2**(B-1),X??30000);await T(C)}}}()}}var I7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},T7=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},H7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},fj=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((G)=>encodeURIComponent(G))).join(T7(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=I7(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return HO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},HO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},bj=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let G=[];Object.entries(S).forEach(([Y,J])=>{G=[...G,Y,$?J:encodeURIComponent(J)]});let L=G.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=H7(x),X=Object.entries(S).map(([G,L])=>HO({allowReserved:$,name:x==="deepObject"?`${j}[${G}]`:G,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var R7=/\{[^{}]+\}/g,D7=({path:$,url:O})=>{let j=O,x=O.match(R7);if(x)for(let S of x){let K=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))K=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let G=$[Z];if(G===void 0||G===null)continue;if(Array.isArray(G)){j=j.replace(S,fj({explode:K,name:Z,style:X,value:G}));continue}if(typeof G==="object"){j=j.replace(S,bj({explode:K,name:Z,style:X,value:G,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${HO({name:Z,value:G})}`);continue}let L=encodeURIComponent(X==="label"?`.${G}`:G);j=j.replace(S,L)}return j},YS=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=D7({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function g0($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var QS=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var JS={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var VS=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let G=fj({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(G)S.push(G)}else if(typeof Z==="object"){let G=bj({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(G)S.push(G)}else{let G=HO({allowReserved:X.allowReserved,name:K,value:Z});if(G)S.push(G)}}return S.join("&")}},WS=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},C7=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function BS($){for(let O of $.security??[]){if(C7($,O.name))continue;let j=await QS(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var y0=($)=>YS({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:VS($.querySerializer),url:$.url}),v0=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=gj($.headers,O.headers),j},_7=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},gj=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?_7(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class kj{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var LS=()=>({error:new kj,request:new kj,response:new kj}),M7=VS({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),A7={"Content-Type":"application/json"},nO=($={})=>({...JS,headers:A7,parseAs:"auto",querySerializer:M7,...$});var h0=($={})=>{let O=v0(nO(),$),j=()=>({...O}),x=(Y)=>{return O=v0(O,Y),j()},S=LS(),K=async(Y)=>{let J={...O,...Y,fetch:Y.fetch??O.fetch??globalThis.fetch,headers:gj(O.headers,Y.headers),serializedBody:void 0};if(J.security)await BS(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let T=J,z=y0(T);return{opts:T,url:z}},Z=async(Y)=>{let J=Y.throwOnError??O.throwOnError,T=Y.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(Y),I={redirect:"follow",...V,body:g0(V)};z=new Request(B,I);for(let N of S.request.fns)if(N)z=await N(z,V);let P=V.fetch;W=await P(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?WS(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await W[N]();break;case"json":{let U=await W.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let C=await W.text(),E;try{E=JSON.parse(C)}catch{}throw E??C}catch(V){let B=V;for(let I of S.error.fns)if(I)B=await I(B,W,z,Y);if(B=B||{},J)throw B;return T==="data"?void 0:{error:B,request:z,response:W}}},X=(Y)=>(J)=>Z({...J,method:Y}),G=(Y)=>async(J)=>{let{opts:T,url:z}=await K(J);return KS({...T,body:T.body,method:Y,onRequest:async(W,V)=>{let B=new Request(W,V);for(let I of S.request.fns)if(I)B=await I(B,T);return B},serializedBody:g0(T),url:z})};return{buildUrl:(Y)=>y0({...O,...Y}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:G("CONNECT"),delete:G("DELETE"),get:G("GET"),head:G("HEAD"),options:G("OPTIONS"),patch:G("PATCH"),post:G("POST"),put:G("PUT"),trace:G("TRACE")},trace:X("TRACE")}};var NS=h0(nO());class US{client;constructor($){this.client=$?.client??NS}}class zS{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class yj extends US{static __registry=new zS;constructor($){super($);yj.__registry.set(this,$?.key)}getAvailabilityCalendars($){return($?.client??this.client).get({url:"/availability-calendars",...$})}setAvailabilityCalendar($){return($.client??this.client).put({url:"/availability-calendars/{calendar_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}listCalendars($){return($?.client??this.client).get({url:"/calendars",...$})}createCalendarEvent($){return($.client??this.client).post({url:"/events",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteCalendarEvent($){return($.client??this.client).delete({url:"/events/{event_id}",...$})}updateCalendarEvent($){return($.client??this.client).patch({url:"/events/{event_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}copyCalendarEvent($){return($.client??this.client).post({url:"/events/{event_id}/copy",...$,headers:{"Content-Type":"application/json",...$.headers}})}inviteCalendarEventGuests($){return($.client??this.client).post({url:"/events/{event_id}/guests",...$,headers:{"Content-Type":"application/json",...$.headers}})}calendarEventProviderUrl($){return($.client??this.client).get({url:"/events/{event_id}/provider-url",...$})}prepareCalendarReplacement($){return($.client??this.client).post({url:"/events/{event_id}/replacement",...$,headers:{"Content-Type":"application/json",...$.headers}})}rsvpCalendarEvent($){return($.client??this.client).put({url:"/events/{event_id}/rsvp",...$,headers:{"Content-Type":"application/json",...$.headers}})}healthHandler($){return($?.client??this.client).get({url:"/health",...$})}respondToJoinRequest($){return($.client??this.client).put({url:"/join-requests/{request_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}discardCalendarReplacement($){return($.client??this.client).delete({url:"/replacements/{operation_id}",...$})}calendarReplacementStatus($){return($.client??this.client).get({url:"/replacements/{operation_id}",...$})}confirmCalendarReplacement($){return($.client??this.client).post({url:"/replacements/{operation_id}/confirm",...$})}getTeamSharing($){return($?.client??this.client).get({url:"/team-sharing",...$})}setTeamSharing($){return($.client??this.client).put({url:"/team-sharing",...$,headers:{"Content-Type":"application/json",...$.headers}})}}function IS({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:G,url:L,...Y}){let J,T=G??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=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(J!==void 0)P.set("Last-Event-ID",J);try{let D={redirect:"follow",...Y,body:Y.serializedBody,headers:P,signal:I},C=new Request(L,D);if($)C=await $(L,D);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="",k=()=>{try{H.cancel()}catch{}};I.addEventListener("abort",k);try{while(!0){let{done:d,value:l}=await H.read();if(d)break;U+=l,U=U.replace(/\r\n?/g,`
-`);let g=U.split(`
+`);try{_=JSON.parse(R),v=!0}catch{_=R}}if(v){if(S)await S(_);if(x)_=await x(_)}if(j?.({data:_,event:y,id:J,retry:V}),F.length)yield _}}}finally{I.removeEventListener("abort",g),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let C=Math.min(V*2**(B-1),X??30000);await T(C)}}}()}}var T7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},H7=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},R7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},bj=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((G)=>encodeURIComponent(G))).join(H7(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=T7(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return RO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},RO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},gj=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let G=[];Object.entries(S).forEach(([Y,J])=>{G=[...G,Y,$?J:encodeURIComponent(J)]});let L=G.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=R7(x),X=Object.entries(S).map(([G,L])=>RO({allowReserved:$,name:x==="deepObject"?`${j}[${G}]`:G,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var D7=/\{[^{}]+\}/g,C7=({path:$,url:O})=>{let j=O,x=O.match(D7);if(x)for(let S of x){let K=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))K=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let G=$[Z];if(G===void 0||G===null)continue;if(Array.isArray(G)){j=j.replace(S,bj({explode:K,name:Z,style:X,value:G}));continue}if(typeof G==="object"){j=j.replace(S,gj({explode:K,name:Z,style:X,value:G,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${RO({name:Z,value:G})}`);continue}let L=encodeURIComponent(X==="label"?`.${G}`:G);j=j.replace(S,L)}return j},QS=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=C7({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function y0($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var JS=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var VS={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var WS=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let G=bj({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(G)S.push(G)}else if(typeof Z==="object"){let G=gj({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(G)S.push(G)}else{let G=RO({allowReserved:X.allowReserved,name:K,value:Z});if(G)S.push(G)}}return S.join("&")}},BS=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},_7=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function LS($){for(let O of $.security??[]){if(_7($,O.name))continue;let j=await JS(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var v0=($)=>QS({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:WS($.querySerializer),url:$.url}),h0=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=yj($.headers,O.headers),j},A7=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},yj=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?A7(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class kj{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var US=()=>({error:new kj,request:new kj,response:new kj}),M7=WS({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),P7={"Content-Type":"application/json"},sO=($={})=>({...VS,headers:P7,parseAs:"auto",querySerializer:M7,...$});var m0=($={})=>{let O=h0(sO(),$),j=()=>({...O}),x=(Y)=>{return O=h0(O,Y),j()},S=US(),K=async(Y)=>{let J={...O,...Y,fetch:Y.fetch??O.fetch??globalThis.fetch,headers:yj(O.headers,Y.headers),serializedBody:void 0};if(J.security)await LS(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let T=J,z=v0(T);return{opts:T,url:z}},Z=async(Y)=>{let J=Y.throwOnError??O.throwOnError,T=Y.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(Y),I={redirect:"follow",...V,body:y0(V)};z=new Request(B,I);for(let U of S.request.fns)if(U)z=await U(z,V);let P=V.fetch;W=await P(z);for(let U of S.response.fns)if(U)W=await U(W,z,V);let D={request:z,response:W};if(W.ok){let U=(V.parseAs==="auto"?BS(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let N;switch(U){case"arrayBuffer":case"blob":case"text":N=await W[U]();break;case"formData":N=new FormData;break;case"stream":N=W.body;break;case"json":default:N={};break}return V.responseStyle==="data"?N:{data:N,...D}}let H;switch(U){case"arrayBuffer":case"blob":case"formData":case"text":H=await W[U]();break;case"json":{let N=await W.text();H=N?JSON.parse(N):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(U==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let C=await W.text(),w;try{w=JSON.parse(C)}catch{}throw w??C}catch(V){let B=V;for(let I of S.error.fns)if(I)B=await I(B,W,z,Y);if(B=B||{},J)throw B;return T==="data"?void 0:{error:B,request:z,response:W}}},X=(Y)=>(J)=>Z({...J,method:Y}),G=(Y)=>async(J)=>{let{opts:T,url:z}=await K(J);return YS({...T,body:T.body,method:Y,onRequest:async(W,V)=>{let B=new Request(W,V);for(let I of S.request.fns)if(I)B=await I(B,T);return B},serializedBody:y0(T),url:z})};return{buildUrl:(Y)=>v0({...O,...Y}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:G("CONNECT"),delete:G("DELETE"),get:G("GET"),head:G("HEAD"),options:G("OPTIONS"),patch:G("PATCH"),post:G("POST"),put:G("PUT"),trace:G("TRACE")},trace:X("TRACE")}};var NS=m0(sO());class zS{client;constructor($){this.client=$?.client??NS}}class IS{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class vj extends zS{static __registry=new IS;constructor($){super($);vj.__registry.set(this,$?.key)}getAvailabilityCalendars($){return($?.client??this.client).get({url:"/availability-calendars",...$})}setAvailabilityCalendar($){return($.client??this.client).put({url:"/availability-calendars/{calendar_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}listCalendars($){return($?.client??this.client).get({url:"/calendars",...$})}createCalendarEvent($){return($.client??this.client).post({url:"/events",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteCalendarEvent($){return($.client??this.client).delete({url:"/events/{event_id}",...$})}updateCalendarEvent($){return($.client??this.client).patch({url:"/events/{event_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}copyCalendarEvent($){return($.client??this.client).post({url:"/events/{event_id}/copy",...$,headers:{"Content-Type":"application/json",...$.headers}})}inviteCalendarEventGuests($){return($.client??this.client).post({url:"/events/{event_id}/guests",...$,headers:{"Content-Type":"application/json",...$.headers}})}eventNotes($){return($.client??this.client).get({url:"/events/{event_id}/notes",...$})}unlinkEventNote($){return($.client??this.client).delete({url:"/events/{event_id}/notes/{document_id}",...$})}linkEventNote($){return($.client??this.client).put({url:"/events/{event_id}/notes/{document_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}calendarEventProviderUrl($){return($.client??this.client).get({url:"/events/{event_id}/provider-url",...$})}prepareCalendarReplacement($){return($.client??this.client).post({url:"/events/{event_id}/replacement",...$,headers:{"Content-Type":"application/json",...$.headers}})}rsvpCalendarEvent($){return($.client??this.client).put({url:"/events/{event_id}/rsvp",...$,headers:{"Content-Type":"application/json",...$.headers}})}healthHandler($){return($?.client??this.client).get({url:"/health",...$})}respondToJoinRequest($){return($.client??this.client).put({url:"/join-requests/{request_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}noteDocuments($){return($?.client??this.client).get({url:"/meeting-notes/documents",...$})}documentNoteLinks($){return($.client??this.client).get({url:"/meeting-notes/documents/{document_id}/links",...$})}discardCalendarReplacement($){return($.client??this.client).delete({url:"/replacements/{operation_id}",...$})}calendarReplacementStatus($){return($.client??this.client).get({url:"/replacements/{operation_id}",...$})}confirmCalendarReplacement($){return($.client??this.client).post({url:"/replacements/{operation_id}/confirm",...$})}getTeamSharing($){return($?.client??this.client).get({url:"/team-sharing",...$})}setTeamSharing($){return($.client??this.client).put({url:"/team-sharing",...$,headers:{"Content-Type":"application/json",...$.headers}})}}function TS({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:G,url:L,...Y}){let J,T=G??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=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(J!==void 0)P.set("Last-Event-ID",J);try{let D={redirect:"follow",...Y,body:Y.serializedBody,headers:P,signal:I},C=new Request(L,D);if($)C=await $(L,D);let U=await(Y.fetch??globalThis.fetch)(C);if(!U.ok)throw Error(`SSE failed: ${U.status} ${U.statusText}`);if(!U.body)throw Error("No body in SSE response");let H=U.body.pipeThrough(new TextDecoderStream).getReader(),N="",g=()=>{try{H.cancel()}catch{}};I.addEventListener("abort",g);try{while(!0){let{done:d,value:l}=await H.read();if(d)break;N+=l,N=N.replace(/\r\n?/g,`
+`);let k=N.split(`
-`);U=g.pop()??"";for(let r of g){let p=r.split(`
+`);N=k.pop()??"";for(let r of k){let p=r.split(`
`),F=[],y;for(let R of p)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))y=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let h=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(h))V=h}let _,v=!1;if(F.length){let R=F.join(`
-`);try{_=JSON.parse(R),v=!0}catch{_=R}}if(v){if(S)await S(_);if(x)_=await x(_)}if(j?.({data:_,event:y,id:J,retry:V}),F.length)yield _}}}finally{I.removeEventListener("abort",k),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let C=Math.min(V*2**(B-1),X??30000);await T(C)}}}()}}var P7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},F7=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},E7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},vj=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((G)=>encodeURIComponent(G))).join(F7(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=P7(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return RO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},RO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},hj=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let G=[];Object.entries(S).forEach(([Y,J])=>{G=[...G,Y,$?J:encodeURIComponent(J)]});let L=G.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=E7(x),X=Object.entries(S).map(([G,L])=>RO({allowReserved:$,name:x==="deepObject"?`${j}[${G}]`:G,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var w7=/\{[^{}]+\}/g,q7=({path:$,url:O})=>{let j=O,x=O.match(w7);if(x)for(let S of x){let K=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))K=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let G=$[Z];if(G===void 0||G===null)continue;if(Array.isArray(G)){j=j.replace(S,vj({explode:K,name:Z,style:X,value:G}));continue}if(typeof G==="object"){j=j.replace(S,hj({explode:K,name:Z,style:X,value:G,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${RO({name:Z,value:G})}`);continue}let L=encodeURIComponent(X==="label"?`.${G}`:G);j=j.replace(S,L)}return j},TS=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=q7({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function m0($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var HS=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var RS={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var DS=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let G=vj({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(G)S.push(G)}else if(typeof Z==="object"){let G=hj({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(G)S.push(G)}else{let G=RO({allowReserved:X.allowReserved,name:K,value:Z});if(G)S.push(G)}}return S.join("&")}},CS=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},f7=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function _S($){for(let O of $.security??[]){if(f7($,O.name))continue;let j=await HS(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var c0=($)=>TS({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:DS($.querySerializer),url:$.url}),u0=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=cj($.headers,O.headers),j},b7=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},cj=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?b7(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class mj{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var MS=()=>({error:new mj,request:new mj,response:new mj}),k7=DS({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),g7={"Content-Type":"application/json"},sO=($={})=>({...RS,headers:g7,parseAs:"auto",querySerializer:k7,...$});var d0=($={})=>{let O=u0(sO(),$),j=()=>({...O}),x=(Y)=>{return O=u0(O,Y),j()},S=MS(),K=async(Y)=>{let J={...O,...Y,fetch:Y.fetch??O.fetch??globalThis.fetch,headers:cj(O.headers,Y.headers),serializedBody:void 0};if(J.security)await _S(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let T=J,z=c0(T);return{opts:T,url:z}},Z=async(Y)=>{let J=Y.throwOnError??O.throwOnError,T=Y.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(Y),I={redirect:"follow",...V,body:m0(V)};z=new Request(B,I);for(let N of S.request.fns)if(N)z=await N(z,V);let P=V.fetch;W=await P(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?CS(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await W[N]();break;case"json":{let U=await W.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let C=await W.text(),E;try{E=JSON.parse(C)}catch{}throw E??C}catch(V){let B=V;for(let I of S.error.fns)if(I)B=await I(B,W,z,Y);if(B=B||{},J)throw B;return T==="data"?void 0:{error:B,request:z,response:W}}},X=(Y)=>(J)=>Z({...J,method:Y}),G=(Y)=>async(J)=>{let{opts:T,url:z}=await K(J);return IS({...T,body:T.body,method:Y,onRequest:async(W,V)=>{let B=new Request(W,V);for(let I of S.request.fns)if(I)B=await I(B,T);return B},serializedBody:m0(T),url:z})};return{buildUrl:(Y)=>c0({...O,...Y}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:G("CONNECT"),delete:G("DELETE"),get:G("GET"),head:G("HEAD"),options:G("OPTIONS"),patch:G("PATCH"),post:G("POST"),put:G("PUT"),trace:G("TRACE")},trace:X("TRACE")}};var AS=d0(sO());class PS{client;constructor($){this.client=$?.client??AS}}class FS{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class uj extends PS{static __registry=new FS;constructor($){super($);uj.__registry.set(this,$?.key)}setPricingHandler($){return($.client??this.client).post({url:"/ai-cost/pricing",...$,headers:{"Content-Type":"application/json",...$.headers}})}getUsageHandler($){return($.client??this.client).post({url:"/ai-cost/usage",...$,headers:{"Content-Type":"application/json",...$.headers}})}upsertAiProjection($){return($.client??this.client).post({url:"/ai-projections",...$,headers:{"Content-Type":"application/json",...$.headers}})}getChatsForAttachmentHandler($){return($.client??this.client).get({url:"/attachments/{attachment_id}/chats",...$})}deleteChat($){return($.client??this.client).delete({url:"/chat/{chat_id}",...$})}patchChat($){return($.client??this.client).patch({url:"/chat/{chat_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}permanentlyDeleteChat($){return($.client??this.client).delete({url:"/chat/{chat_id}/permanent",...$})}createChat($){return($.client??this.client).post({url:"/chats",...$,headers:{"Content-Type":"application/json",...$.headers}})}getChatHistoryHandler($){return($.client??this.client).get({url:"/chats/history/{chat_id}",...$})}getChatHistoryBatchMessagesHandler($){return($.client??this.client).post({url:"/chats/history_batch_messages",...$,headers:{"Content-Type":"application/json",...$.headers}})}getChat($){return($.client??this.client).get({url:"/chats/{chat_id}",...$})}copyChat($){return($.client??this.client).post({url:"/chats/{chat_id}/copy",...$})}getChatPermissions($){return($.client??this.client).get({url:"/chats/{chat_id}/permissions",...$})}revertDeleteChat($){return($.client??this.client).put({url:"/chats/{chat_id}/revert_delete",...$})}callTool($){return($.client??this.client).post({url:"/chats/{chat_id}/tool/call",...$,headers:{"Content-Type":"application/json",...$.headers}})}rejectToolCall($){return($.client??this.client).post({url:"/chats/{chat_id}/tool/reject",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateToolResponse($){return($.client??this.client).post({url:"/chats/{chat_id}/tool/response/update",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateToolCall($){return($.client??this.client).post({url:"/chats/{chat_id}/tool/update",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCitationHandler($){return($.client??this.client).get({url:"/citations/{id}",...$})}decisions($){return($.client??this.client).post({url:"/decisions",...$,headers:{"Content-Type":"application/json",...$.headers}})}healthHandler($){return($?.client??this.client).get({url:"/health",...$})}runImportHandler($){return($.client??this.client).post({url:"/import/run",...$,headers:{"Content-Type":"application/json",...$.headers}})}discoverHandler($){return($.client??this.client).post({url:"/import/runs/{source}/discover",...$})}dismissRunHandler($){return($.client??this.client).post({url:"/import/runs/{source}/dismiss",...$})}retryGatherHandler($){return($.client??this.client).post({url:"/import/runs/{source}/retry",...$})}getStateHandler($){return($?.client??this.client).get({url:"/import/state",...$})}deleteMcpServer($){return($.client??this.client).delete({url:"/mcp/servers",...$})}listMcpServers($){return($?.client??this.client).get({url:"/mcp/servers",...$})}addMcpServer($){return($.client??this.client).post({url:"/mcp/servers",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateMcpServer($){return($.client??this.client).put({url:"/mcp/servers",...$,headers:{"Content-Type":"application/json",...$.headers}})}mcpAuthCallback($){return($?.client??this.client).get({url:"/mcp/servers/auth/callback",...$})}mcpOauthClientMetadata($){return($?.client??this.client).get({url:"/mcp/servers/auth/client-metadata",...$})}startMcpAuth($){return($.client??this.client).post({url:"/mcp/servers/auth/start",...$,headers:{"Content-Type":"application/json",...$.headers}})}getMemoryHandler($){return($?.client??this.client).get({url:"/memory",...$})}getStateHandler2($){return($?.client??this.client).get({url:"/onboarding",...$})}completeHandler($){return($.client??this.client).post({url:"/onboarding/complete",...$,headers:{"Content-Type":"application/json",...$.headers}})}dismissedPromptsHandler($){return($?.client??this.client).get({url:"/onboarding/prompts",...$})}dismissPromptHandler($){return($.client??this.client).post({url:"/onboarding/prompts/{prompt_id}/dismiss",...$})}browsePipedreamMcpCatalog($){return($?.client??this.client).get({url:"/pipedream/mcp/catalog",...$})}completePipedreamMcpConnection($){return($.client??this.client).post({url:"/pipedream/mcp/complete",...$,headers:{"Content-Type":"application/json",...$.headers}})}deletePipedreamMcpConnection($){return($.client??this.client).delete({url:"/pipedream/mcp/connections",...$})}listPipedreamMcpConnections($){return($?.client??this.client).get({url:"/pipedream/mcp/connections",...$})}updatePipedreamMcpConnection($){return($.client??this.client).put({url:"/pipedream/mcp/connections",...$,headers:{"Content-Type":"application/json",...$.headers}})}createPipedreamMcpToken($){return($?.client??this.client).post({url:"/pipedream/mcp/token",...$})}getBatchPreview($){return($.client??this.client).post({url:"/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}sendChatMessage($){return($.client??this.client).post({url:"/stream/chat/message",...$,headers:{"Content-Type":"application/json",...$.headers}})}stopChatStream($){return($.client??this.client).post({url:"/stream/chat/message/stop",...$,headers:{"Content-Type":"application/json",...$.headers}})}structuredCompletion($){return($.client??this.client).post({url:"/structured-completion",...$,headers:{"Content-Type":"application/json",...$.headers}})}}function ES({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:G,url:L,...Y}){let J,T=G??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=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(J!==void 0)P.set("Last-Event-ID",J);try{let D={redirect:"follow",...Y,body:Y.serializedBody,headers:P,signal:I},C=new Request(L,D);if($)C=await $(L,D);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="",k=()=>{try{H.cancel()}catch{}};I.addEventListener("abort",k);try{while(!0){let{done:d,value:l}=await H.read();if(d)break;U+=l,U=U.replace(/\r\n?/g,`
-`);let g=U.split(`
+`);try{_=JSON.parse(R),v=!0}catch{_=R}}if(v){if(S)await S(_);if(x)_=await x(_)}if(j?.({data:_,event:y,id:J,retry:V}),F.length)yield _}}}finally{I.removeEventListener("abort",g),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let C=Math.min(V*2**(B-1),X??30000);await T(C)}}}()}}var F7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},E7=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},w7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},hj=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((G)=>encodeURIComponent(G))).join(E7(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=F7(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return DO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},DO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},mj=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let G=[];Object.entries(S).forEach(([Y,J])=>{G=[...G,Y,$?J:encodeURIComponent(J)]});let L=G.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=w7(x),X=Object.entries(S).map(([G,L])=>DO({allowReserved:$,name:x==="deepObject"?`${j}[${G}]`:G,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var q7=/\{[^{}]+\}/g,f7=({path:$,url:O})=>{let j=O,x=O.match(q7);if(x)for(let S of x){let K=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))K=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let G=$[Z];if(G===void 0||G===null)continue;if(Array.isArray(G)){j=j.replace(S,hj({explode:K,name:Z,style:X,value:G}));continue}if(typeof G==="object"){j=j.replace(S,mj({explode:K,name:Z,style:X,value:G,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${DO({name:Z,value:G})}`);continue}let L=encodeURIComponent(X==="label"?`.${G}`:G);j=j.replace(S,L)}return j},HS=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=f7({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function c0($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var RS=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var DS={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var CS=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let G=hj({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(G)S.push(G)}else if(typeof Z==="object"){let G=mj({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(G)S.push(G)}else{let G=DO({allowReserved:X.allowReserved,name:K,value:Z});if(G)S.push(G)}}return S.join("&")}},_S=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},b7=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function AS($){for(let O of $.security??[]){if(b7($,O.name))continue;let j=await RS(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var u0=($)=>HS({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:CS($.querySerializer),url:$.url}),d0=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=uj($.headers,O.headers),j},g7=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},uj=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?g7(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class cj{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var MS=()=>({error:new cj,request:new cj,response:new cj}),k7=CS({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),y7={"Content-Type":"application/json"},tO=($={})=>({...DS,headers:y7,parseAs:"auto",querySerializer:k7,...$});var l0=($={})=>{let O=d0(tO(),$),j=()=>({...O}),x=(Y)=>{return O=d0(O,Y),j()},S=MS(),K=async(Y)=>{let J={...O,...Y,fetch:Y.fetch??O.fetch??globalThis.fetch,headers:uj(O.headers,Y.headers),serializedBody:void 0};if(J.security)await AS(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let T=J,z=u0(T);return{opts:T,url:z}},Z=async(Y)=>{let J=Y.throwOnError??O.throwOnError,T=Y.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(Y),I={redirect:"follow",...V,body:c0(V)};z=new Request(B,I);for(let U of S.request.fns)if(U)z=await U(z,V);let P=V.fetch;W=await P(z);for(let U of S.response.fns)if(U)W=await U(W,z,V);let D={request:z,response:W};if(W.ok){let U=(V.parseAs==="auto"?_S(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let N;switch(U){case"arrayBuffer":case"blob":case"text":N=await W[U]();break;case"formData":N=new FormData;break;case"stream":N=W.body;break;case"json":default:N={};break}return V.responseStyle==="data"?N:{data:N,...D}}let H;switch(U){case"arrayBuffer":case"blob":case"formData":case"text":H=await W[U]();break;case"json":{let N=await W.text();H=N?JSON.parse(N):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(U==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let C=await W.text(),w;try{w=JSON.parse(C)}catch{}throw w??C}catch(V){let B=V;for(let I of S.error.fns)if(I)B=await I(B,W,z,Y);if(B=B||{},J)throw B;return T==="data"?void 0:{error:B,request:z,response:W}}},X=(Y)=>(J)=>Z({...J,method:Y}),G=(Y)=>async(J)=>{let{opts:T,url:z}=await K(J);return TS({...T,body:T.body,method:Y,onRequest:async(W,V)=>{let B=new Request(W,V);for(let I of S.request.fns)if(I)B=await I(B,T);return B},serializedBody:c0(T),url:z})};return{buildUrl:(Y)=>u0({...O,...Y}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:G("CONNECT"),delete:G("DELETE"),get:G("GET"),head:G("HEAD"),options:G("OPTIONS"),patch:G("PATCH"),post:G("POST"),put:G("PUT"),trace:G("TRACE")},trace:X("TRACE")}};var PS=l0(tO());class FS{client;constructor($){this.client=$?.client??PS}}class ES{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class dj extends FS{static __registry=new ES;constructor($){super($);dj.__registry.set(this,$?.key)}setPricingHandler($){return($.client??this.client).post({url:"/ai-cost/pricing",...$,headers:{"Content-Type":"application/json",...$.headers}})}getUsageHandler($){return($.client??this.client).post({url:"/ai-cost/usage",...$,headers:{"Content-Type":"application/json",...$.headers}})}upsertAiProjection($){return($.client??this.client).post({url:"/ai-projections",...$,headers:{"Content-Type":"application/json",...$.headers}})}getChatsForAttachmentHandler($){return($.client??this.client).get({url:"/attachments/{attachment_id}/chats",...$})}deleteChat($){return($.client??this.client).delete({url:"/chat/{chat_id}",...$})}patchChat($){return($.client??this.client).patch({url:"/chat/{chat_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}permanentlyDeleteChat($){return($.client??this.client).delete({url:"/chat/{chat_id}/permanent",...$})}createChat($){return($.client??this.client).post({url:"/chats",...$,headers:{"Content-Type":"application/json",...$.headers}})}getChatHistoryHandler($){return($.client??this.client).get({url:"/chats/history/{chat_id}",...$})}getChatHistoryBatchMessagesHandler($){return($.client??this.client).post({url:"/chats/history_batch_messages",...$,headers:{"Content-Type":"application/json",...$.headers}})}getChat($){return($.client??this.client).get({url:"/chats/{chat_id}",...$})}copyChat($){return($.client??this.client).post({url:"/chats/{chat_id}/copy",...$})}getChatPermissions($){return($.client??this.client).get({url:"/chats/{chat_id}/permissions",...$})}revertDeleteChat($){return($.client??this.client).put({url:"/chats/{chat_id}/revert_delete",...$})}callTool($){return($.client??this.client).post({url:"/chats/{chat_id}/tool/call",...$,headers:{"Content-Type":"application/json",...$.headers}})}rejectToolCall($){return($.client??this.client).post({url:"/chats/{chat_id}/tool/reject",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateToolResponse($){return($.client??this.client).post({url:"/chats/{chat_id}/tool/response/update",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateToolCall($){return($.client??this.client).post({url:"/chats/{chat_id}/tool/update",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCitationHandler($){return($.client??this.client).get({url:"/citations/{id}",...$})}decisions($){return($.client??this.client).post({url:"/decisions",...$,headers:{"Content-Type":"application/json",...$.headers}})}healthHandler($){return($?.client??this.client).get({url:"/health",...$})}runImportHandler($){return($.client??this.client).post({url:"/import/run",...$,headers:{"Content-Type":"application/json",...$.headers}})}discoverHandler($){return($.client??this.client).post({url:"/import/runs/{source}/discover",...$})}dismissRunHandler($){return($.client??this.client).post({url:"/import/runs/{source}/dismiss",...$})}retryGatherHandler($){return($.client??this.client).post({url:"/import/runs/{source}/retry",...$})}getStateHandler($){return($?.client??this.client).get({url:"/import/state",...$})}deleteMcpServer($){return($.client??this.client).delete({url:"/mcp/servers",...$})}listMcpServers($){return($?.client??this.client).get({url:"/mcp/servers",...$})}addMcpServer($){return($.client??this.client).post({url:"/mcp/servers",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateMcpServer($){return($.client??this.client).put({url:"/mcp/servers",...$,headers:{"Content-Type":"application/json",...$.headers}})}mcpAuthCallback($){return($?.client??this.client).get({url:"/mcp/servers/auth/callback",...$})}mcpOauthClientMetadata($){return($?.client??this.client).get({url:"/mcp/servers/auth/client-metadata",...$})}startMcpAuth($){return($.client??this.client).post({url:"/mcp/servers/auth/start",...$,headers:{"Content-Type":"application/json",...$.headers}})}getMemoryHandler($){return($?.client??this.client).get({url:"/memory",...$})}getStateHandler2($){return($?.client??this.client).get({url:"/onboarding",...$})}completeHandler($){return($.client??this.client).post({url:"/onboarding/complete",...$,headers:{"Content-Type":"application/json",...$.headers}})}dismissedPromptsHandler($){return($?.client??this.client).get({url:"/onboarding/prompts",...$})}dismissPromptHandler($){return($.client??this.client).post({url:"/onboarding/prompts/{prompt_id}/dismiss",...$})}browsePipedreamMcpCatalog($){return($?.client??this.client).get({url:"/pipedream/mcp/catalog",...$})}completePipedreamMcpConnection($){return($.client??this.client).post({url:"/pipedream/mcp/complete",...$,headers:{"Content-Type":"application/json",...$.headers}})}deletePipedreamMcpConnection($){return($.client??this.client).delete({url:"/pipedream/mcp/connections",...$})}listPipedreamMcpConnections($){return($?.client??this.client).get({url:"/pipedream/mcp/connections",...$})}updatePipedreamMcpConnection($){return($.client??this.client).put({url:"/pipedream/mcp/connections",...$,headers:{"Content-Type":"application/json",...$.headers}})}createPipedreamMcpToken($){return($?.client??this.client).post({url:"/pipedream/mcp/token",...$})}getBatchPreview($){return($.client??this.client).post({url:"/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}sendChatMessage($){return($.client??this.client).post({url:"/stream/chat/message",...$,headers:{"Content-Type":"application/json",...$.headers}})}stopChatStream($){return($.client??this.client).post({url:"/stream/chat/message/stop",...$,headers:{"Content-Type":"application/json",...$.headers}})}structuredCompletion($){return($.client??this.client).post({url:"/structured-completion",...$,headers:{"Content-Type":"application/json",...$.headers}})}}function wS({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:G,url:L,...Y}){let J,T=G??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=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(J!==void 0)P.set("Last-Event-ID",J);try{let D={redirect:"follow",...Y,body:Y.serializedBody,headers:P,signal:I},C=new Request(L,D);if($)C=await $(L,D);let U=await(Y.fetch??globalThis.fetch)(C);if(!U.ok)throw Error(`SSE failed: ${U.status} ${U.statusText}`);if(!U.body)throw Error("No body in SSE response");let H=U.body.pipeThrough(new TextDecoderStream).getReader(),N="",g=()=>{try{H.cancel()}catch{}};I.addEventListener("abort",g);try{while(!0){let{done:d,value:l}=await H.read();if(d)break;N+=l,N=N.replace(/\r\n?/g,`
+`);let k=N.split(`
-`);U=g.pop()??"";for(let r of g){let p=r.split(`
+`);N=k.pop()??"";for(let r of k){let p=r.split(`
`),F=[],y;for(let R of p)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))y=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let h=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(h))V=h}let _,v=!1;if(F.length){let R=F.join(`
-`);try{_=JSON.parse(R),v=!0}catch{_=R}}if(v){if(S)await S(_);if(x)_=await x(_)}if(j?.({data:_,event:y,id:J,retry:V}),F.length)yield _}}}finally{I.removeEventListener("abort",k),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let C=Math.min(V*2**(B-1),X??30000);await T(C)}}}()}}var y7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},v7=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},h7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},dj=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((G)=>encodeURIComponent(G))).join(v7(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=y7(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return DO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},DO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},lj=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let G=[];Object.entries(S).forEach(([Y,J])=>{G=[...G,Y,$?J:encodeURIComponent(J)]});let L=G.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=h7(x),X=Object.entries(S).map(([G,L])=>DO({allowReserved:$,name:x==="deepObject"?`${j}[${G}]`:G,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var m7=/\{[^{}]+\}/g,c7=({path:$,url:O})=>{let j=O,x=O.match(m7);if(x)for(let S of x){let K=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))K=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let G=$[Z];if(G===void 0||G===null)continue;if(Array.isArray(G)){j=j.replace(S,dj({explode:K,name:Z,style:X,value:G}));continue}if(typeof G==="object"){j=j.replace(S,lj({explode:K,name:Z,style:X,value:G,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${DO({name:Z,value:G})}`);continue}let L=encodeURIComponent(X==="label"?`.${G}`:G);j=j.replace(S,L)}return j},wS=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=c7({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function l0($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var qS=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var fS={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var bS=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let G=dj({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(G)S.push(G)}else if(typeof Z==="object"){let G=lj({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(G)S.push(G)}else{let G=DO({allowReserved:X.allowReserved,name:K,value:Z});if(G)S.push(G)}}return S.join("&")}},kS=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},u7=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function gS($){for(let O of $.security??[]){if(u7($,O.name))continue;let j=await qS(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var r0=($)=>wS({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:bS($.querySerializer),url:$.url}),p0=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=pj($.headers,O.headers),j},d7=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},pj=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?d7(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class rj{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var yS=()=>({error:new rj,request:new rj,response:new rj}),l7=bS({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),r7={"Content-Type":"application/json"},tO=($={})=>({...fS,headers:r7,parseAs:"auto",querySerializer:l7,...$});var a0=($={})=>{let O=p0(tO(),$),j=()=>({...O}),x=(Y)=>{return O=p0(O,Y),j()},S=yS(),K=async(Y)=>{let J={...O,...Y,fetch:Y.fetch??O.fetch??globalThis.fetch,headers:pj(O.headers,Y.headers),serializedBody:void 0};if(J.security)await gS(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let T=J,z=r0(T);return{opts:T,url:z}},Z=async(Y)=>{let J=Y.throwOnError??O.throwOnError,T=Y.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(Y),I={redirect:"follow",...V,body:l0(V)};z=new Request(B,I);for(let N of S.request.fns)if(N)z=await N(z,V);let P=V.fetch;W=await P(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?kS(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await W[N]();break;case"json":{let U=await W.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let C=await W.text(),E;try{E=JSON.parse(C)}catch{}throw E??C}catch(V){let B=V;for(let I of S.error.fns)if(I)B=await I(B,W,z,Y);if(B=B||{},J)throw B;return T==="data"?void 0:{error:B,request:z,response:W}}},X=(Y)=>(J)=>Z({...J,method:Y}),G=(Y)=>async(J)=>{let{opts:T,url:z}=await K(J);return ES({...T,body:T.body,method:Y,onRequest:async(W,V)=>{let B=new Request(W,V);for(let I of S.request.fns)if(I)B=await I(B,T);return B},serializedBody:l0(T),url:z})};return{buildUrl:(Y)=>r0({...O,...Y}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:G("CONNECT"),delete:G("DELETE"),get:G("GET"),head:G("HEAD"),options:G("OPTIONS"),patch:G("PATCH"),post:G("POST"),put:G("PUT"),trace:G("TRACE")},trace:X("TRACE")}};var vS=a0(tO());class hS{client;constructor($){this.client=$?.client??vS}}class mS{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class aj extends hS{static __registry=new mS;constructor($){super($);aj.__registry.set(this,$?.key)}getContacts($){return($?.client??this.client).get({url:"/contacts",...$})}addContact($){return($.client??this.client).post({url:"/contacts",...$,headers:{"Content-Type":"application/json",...$.headers}})}}function cS({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:G,url:L,...Y}){let J,T=G??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=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(J!==void 0)P.set("Last-Event-ID",J);try{let D={redirect:"follow",...Y,body:Y.serializedBody,headers:P,signal:I},C=new Request(L,D);if($)C=await $(L,D);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="",k=()=>{try{H.cancel()}catch{}};I.addEventListener("abort",k);try{while(!0){let{done:d,value:l}=await H.read();if(d)break;U+=l,U=U.replace(/\r\n?/g,`
-`);let g=U.split(`
+`);try{_=JSON.parse(R),v=!0}catch{_=R}}if(v){if(S)await S(_);if(x)_=await x(_)}if(j?.({data:_,event:y,id:J,retry:V}),F.length)yield _}}}finally{I.removeEventListener("abort",g),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let C=Math.min(V*2**(B-1),X??30000);await T(C)}}}()}}var v7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},h7=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},m7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},lj=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((G)=>encodeURIComponent(G))).join(h7(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=v7(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return CO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},CO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},rj=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let G=[];Object.entries(S).forEach(([Y,J])=>{G=[...G,Y,$?J:encodeURIComponent(J)]});let L=G.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=m7(x),X=Object.entries(S).map(([G,L])=>CO({allowReserved:$,name:x==="deepObject"?`${j}[${G}]`:G,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var c7=/\{[^{}]+\}/g,u7=({path:$,url:O})=>{let j=O,x=O.match(c7);if(x)for(let S of x){let K=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))K=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let G=$[Z];if(G===void 0||G===null)continue;if(Array.isArray(G)){j=j.replace(S,lj({explode:K,name:Z,style:X,value:G}));continue}if(typeof G==="object"){j=j.replace(S,rj({explode:K,name:Z,style:X,value:G,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${CO({name:Z,value:G})}`);continue}let L=encodeURIComponent(X==="label"?`.${G}`:G);j=j.replace(S,L)}return j},qS=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=u7({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function r0($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var fS=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var bS={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var gS=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let G=lj({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(G)S.push(G)}else if(typeof Z==="object"){let G=rj({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(G)S.push(G)}else{let G=CO({allowReserved:X.allowReserved,name:K,value:Z});if(G)S.push(G)}}return S.join("&")}},kS=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},d7=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function yS($){for(let O of $.security??[]){if(d7($,O.name))continue;let j=await fS(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var p0=($)=>qS({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:gS($.querySerializer),url:$.url}),a0=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=aj($.headers,O.headers),j},l7=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},aj=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?l7(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class pj{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var vS=()=>({error:new pj,request:new pj,response:new pj}),r7=gS({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),p7={"Content-Type":"application/json"},eO=($={})=>({...bS,headers:p7,parseAs:"auto",querySerializer:r7,...$});var i0=($={})=>{let O=a0(eO(),$),j=()=>({...O}),x=(Y)=>{return O=a0(O,Y),j()},S=vS(),K=async(Y)=>{let J={...O,...Y,fetch:Y.fetch??O.fetch??globalThis.fetch,headers:aj(O.headers,Y.headers),serializedBody:void 0};if(J.security)await yS(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let T=J,z=p0(T);return{opts:T,url:z}},Z=async(Y)=>{let J=Y.throwOnError??O.throwOnError,T=Y.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(Y),I={redirect:"follow",...V,body:r0(V)};z=new Request(B,I);for(let U of S.request.fns)if(U)z=await U(z,V);let P=V.fetch;W=await P(z);for(let U of S.response.fns)if(U)W=await U(W,z,V);let D={request:z,response:W};if(W.ok){let U=(V.parseAs==="auto"?kS(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let N;switch(U){case"arrayBuffer":case"blob":case"text":N=await W[U]();break;case"formData":N=new FormData;break;case"stream":N=W.body;break;case"json":default:N={};break}return V.responseStyle==="data"?N:{data:N,...D}}let H;switch(U){case"arrayBuffer":case"blob":case"formData":case"text":H=await W[U]();break;case"json":{let N=await W.text();H=N?JSON.parse(N):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(U==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let C=await W.text(),w;try{w=JSON.parse(C)}catch{}throw w??C}catch(V){let B=V;for(let I of S.error.fns)if(I)B=await I(B,W,z,Y);if(B=B||{},J)throw B;return T==="data"?void 0:{error:B,request:z,response:W}}},X=(Y)=>(J)=>Z({...J,method:Y}),G=(Y)=>async(J)=>{let{opts:T,url:z}=await K(J);return wS({...T,body:T.body,method:Y,onRequest:async(W,V)=>{let B=new Request(W,V);for(let I of S.request.fns)if(I)B=await I(B,T);return B},serializedBody:r0(T),url:z})};return{buildUrl:(Y)=>p0({...O,...Y}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:G("CONNECT"),delete:G("DELETE"),get:G("GET"),head:G("HEAD"),options:G("OPTIONS"),patch:G("PATCH"),post:G("POST"),put:G("PUT"),trace:G("TRACE")},trace:X("TRACE")}};var hS=i0(eO());class mS{client;constructor($){this.client=$?.client??hS}}class cS{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class ij extends mS{static __registry=new cS;constructor($){super($);ij.__registry.set(this,$?.key)}getContacts($){return($?.client??this.client).get({url:"/contacts",...$})}addContact($){return($.client??this.client).post({url:"/contacts",...$,headers:{"Content-Type":"application/json",...$.headers}})}}function uS({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:G,url:L,...Y}){let J,T=G??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=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(J!==void 0)P.set("Last-Event-ID",J);try{let D={redirect:"follow",...Y,body:Y.serializedBody,headers:P,signal:I},C=new Request(L,D);if($)C=await $(L,D);let U=await(Y.fetch??globalThis.fetch)(C);if(!U.ok)throw Error(`SSE failed: ${U.status} ${U.statusText}`);if(!U.body)throw Error("No body in SSE response");let H=U.body.pipeThrough(new TextDecoderStream).getReader(),N="",g=()=>{try{H.cancel()}catch{}};I.addEventListener("abort",g);try{while(!0){let{done:d,value:l}=await H.read();if(d)break;N+=l,N=N.replace(/\r\n?/g,`
+`);let k=N.split(`
-`);U=g.pop()??"";for(let r of g){let p=r.split(`
+`);N=k.pop()??"";for(let r of k){let p=r.split(`
`),F=[],y;for(let R of p)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))y=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let h=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(h))V=h}let _,v=!1;if(F.length){let R=F.join(`
-`);try{_=JSON.parse(R),v=!0}catch{_=R}}if(v){if(S)await S(_);if(x)_=await x(_)}if(j?.({data:_,event:y,id:J,retry:V}),F.length)yield _}}}finally{I.removeEventListener("abort",k),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let C=Math.min(V*2**(B-1),X??30000);await T(C)}}}()}}var p7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},a7=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},i7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},ij=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((G)=>encodeURIComponent(G))).join(a7(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=p7(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return CO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},CO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},nj=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let G=[];Object.entries(S).forEach(([Y,J])=>{G=[...G,Y,$?J:encodeURIComponent(J)]});let L=G.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=i7(x),X=Object.entries(S).map(([G,L])=>CO({allowReserved:$,name:x==="deepObject"?`${j}[${G}]`:G,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var n7=/\{[^{}]+\}/g,s7=({path:$,url:O})=>{let j=O,x=O.match(n7);if(x)for(let S of x){let K=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))K=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let G=$[Z];if(G===void 0||G===null)continue;if(Array.isArray(G)){j=j.replace(S,ij({explode:K,name:Z,style:X,value:G}));continue}if(typeof G==="object"){j=j.replace(S,nj({explode:K,name:Z,style:X,value:G,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${CO({name:Z,value:G})}`);continue}let L=encodeURIComponent(X==="label"?`.${G}`:G);j=j.replace(S,L)}return j},uS=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=s7({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function i0($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var dS=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var lS={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var rS=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let G=ij({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(G)S.push(G)}else if(typeof Z==="object"){let G=nj({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(G)S.push(G)}else{let G=CO({allowReserved:X.allowReserved,name:K,value:Z});if(G)S.push(G)}}return S.join("&")}},pS=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},t7=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function aS($){for(let O of $.security??[]){if(t7($,O.name))continue;let j=await dS(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var n0=($)=>uS({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:rS($.querySerializer),url:$.url}),s0=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=tj($.headers,O.headers),j},e7=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},tj=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?e7(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class sj{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var iS=()=>({error:new sj,request:new sj,response:new sj}),o7=rS({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),$5={"Content-Type":"application/json"},eO=($={})=>({...lS,headers:$5,parseAs:"auto",querySerializer:o7,...$});var t0=($={})=>{let O=s0(eO(),$),j=()=>({...O}),x=(Y)=>{return O=s0(O,Y),j()},S=iS(),K=async(Y)=>{let J={...O,...Y,fetch:Y.fetch??O.fetch??globalThis.fetch,headers:tj(O.headers,Y.headers),serializedBody:void 0};if(J.security)await aS(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let T=J,z=n0(T);return{opts:T,url:z}},Z=async(Y)=>{let J=Y.throwOnError??O.throwOnError,T=Y.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(Y),I={redirect:"follow",...V,body:i0(V)};z=new Request(B,I);for(let N of S.request.fns)if(N)z=await N(z,V);let P=V.fetch;W=await P(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?pS(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await W[N]();break;case"json":{let U=await W.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let C=await W.text(),E;try{E=JSON.parse(C)}catch{}throw E??C}catch(V){let B=V;for(let I of S.error.fns)if(I)B=await I(B,W,z,Y);if(B=B||{},J)throw B;return T==="data"?void 0:{error:B,request:z,response:W}}},X=(Y)=>(J)=>Z({...J,method:Y}),G=(Y)=>async(J)=>{let{opts:T,url:z}=await K(J);return cS({...T,body:T.body,method:Y,onRequest:async(W,V)=>{let B=new Request(W,V);for(let I of S.request.fns)if(I)B=await I(B,T);return B},serializedBody:i0(T),url:z})};return{buildUrl:(Y)=>n0({...O,...Y}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:G("CONNECT"),delete:G("DELETE"),get:G("GET"),head:G("HEAD"),options:G("OPTIONS"),patch:G("PATCH"),post:G("POST"),put:G("PUT"),trace:G("TRACE")},trace:X("TRACE")}};var nS=t0(eO());class sS{client;constructor($){this.client=$?.client??nS}}class tS{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class ej extends sS{static __registry=new tS;constructor($){super($);ej.__registry.set(this,$?.key)}getAttachment($){return($.client??this.client).get({url:"/email/attachments/{id}",...$})}getAttachmentDocumentId($){return($.client??this.client).get({url:"/email/attachments/{id}/document_id",...$})}cancelBackfillGmail($){return($.client??this.client).delete({url:"/email/backfill/gmail",...$,headers:{"Content-Type":"application/json",...$.headers}})}listBackfillGmail($){return($?.client??this.client).get({url:"/email/backfill/gmail",...$})}getBackfillGmailActive($){return($?.client??this.client).get({url:"/email/backfill/gmail/active",...$})}getBackfillGmail($){return($.client??this.client).get({url:"/email/backfill/gmail/{id}",...$})}listContacts($){return($?.client??this.client).get({url:"/email/contacts",...$})}blockSender($){return($.client??this.client).post({url:"/email/contacts/block",...$,headers:{"Content-Type":"application/json",...$.headers}})}listBlockedSenders($){return($?.client??this.client).get({url:"/email/contacts/blocked",...$})}unblockSender($){return($.client??this.client).post({url:"/email/contacts/unblock",...$,headers:{"Content-Type":"application/json",...$.headers}})}recoverDraftTransfer($){return($.client??this.client).post({url:"/email/draft-transfers/{id}/recover",...$})}createDraft($){return($.client??this.client).post({url:"/email/drafts",...$,headers:{"Content-Type":"application/json",...$.headers}})}getScheduledMessages($){return($?.client??this.client).get({url:"/email/drafts/scheduled",...$})}upsertScheduledMessage($){return($.client??this.client).put({url:"/email/drafts/scheduled/{id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteScheduledDraft($){return($.client??this.client).delete({url:"/email/drafts/scheduled/{message_id}",...$})}deleteDraft($){return($.client??this.client).delete({url:"/email/drafts/{id}",...$})}addDraftAttachment($){return($.client??this.client).post({url:"/email/drafts/{id}/attachments",...$,headers:{"Content-Type":"application/json",...$.headers}})}removeDraftAttachment($){return($.client??this.client).delete({url:"/email/drafts/{id}/attachments/{attachment_id}",...$})}completeDraftAttachment($){return($.client??this.client).post({url:"/email/drafts/{id}/attachments/{attachment_id}/complete",...$})}addForwardedAttachment($){return($.client??this.client).post({url:"/email/drafts/{id}/forwarded-attachments",...$,headers:{"Content-Type":"application/json",...$.headers}})}removeForwardedAttachment($){return($.client??this.client).delete({url:"/email/drafts/{id}/forwarded-attachments/{attachment_id}",...$})}messageOperationStatus($){return($.client??this.client).get({url:"/email/drafts/{id}/operation",...$})}resolveMessageOperation($){return($.client??this.client).post({url:"/email/drafts/{id}/resolve",...$,headers:{"Content-Type":"application/json",...$.headers}})}transferDraft($){return($.client??this.client).post({url:"/email/drafts/{id}/transfer",...$,headers:{"Content-Type":"application/json",...$.headers}})}listEmailFilters($){return($?.client??this.client).get({url:"/email/filters",...$})}upsertEmailFilter($){return($.client??this.client).put({url:"/email/filters",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteEmailFilter($){return($.client??this.client).delete({url:"/email/filters/{id}",...$})}initUser($){return($?.client??this.client).post({url:"/email/init",...$})}listLabels($){return($?.client??this.client).get({url:"/email/labels",...$})}createLabel($){return($.client??this.client).post({url:"/email/labels",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteLabel($){return($.client??this.client).delete({url:"/email/labels/{id}",...$})}listLinks($){return($?.client??this.client).get({url:"/email/links",...$})}healthCheckLinks($){return($?.client??this.client).post({url:"/email/links/health-check",...$})}deleteLink($){return($.client??this.client).delete({url:"/email/links/{link_id}",...$})}disableLinkCalendar($){return($.client??this.client).delete({url:"/email/links/{link_id}/calendar",...$})}resyncLink($){return($.client??this.client).post({url:"/email/links/{link_id}/resync",...$})}sendMessage($){return($.client??this.client).post({url:"/email/messages",...$,headers:{"Content-Type":"application/json",...$.headers}})}getMessagesBatch($){return($.client??this.client).post({url:"/email/messages/batch",...$,headers:{"Content-Type":"application/json",...$.headers}})}addRemoveLabel($){return($.client??this.client).patch({url:"/email/messages/labels",...$,headers:{"Content-Type":"application/json",...$.headers}})}getMessage($){return($.client??this.client).get({url:"/email/messages/{id}",...$})}patchSettings($){return($.client??this.client).patch({url:"/email/settings",...$,headers:{"Content-Type":"application/json",...$.headers}})}mailboxSettingsOperations($){return($?.client??this.client).get({url:"/email/settings/operations",...$})}disableSync($){return($?.client??this.client).delete({url:"/email/sync",...$})}previewsInboxCursor($){return($.client??this.client).get({url:"/email/threads/previews/cursor/{view}",...$})}archiveThread($){return($.client??this.client).patch({url:"/email/threads/{id}/archived",...$,headers:{"Content-Type":"application/json",...$.headers}})}addRemoveThreadLabel($){return($.client??this.client).patch({url:"/email/threads/{id}/labels",...$,headers:{"Content-Type":"application/json",...$.headers}})}getThreadMessagesHandler($){return($.client??this.client).get({url:"/email/threads/{id}/messages",...$})}threadOperations($){return($.client??this.client).get({url:"/email/threads/{id}/operations",...$})}threadSeen($){return($.client??this.client).post({url:"/email/threads/{id}/seen",...$})}updateThreadState($){return($.client??this.client).patch({url:"/email/threads/{id}/state",...$,headers:{"Content-Type":"application/json",...$.headers}})}getThread($){return($.client??this.client).get({url:"/email/threads/{thread_id}",...$})}getThreadCalendarInvitations($){return($.client??this.client).get({url:"/email/threads/{thread_id}/calendar-invitations",...$})}updateThreadProject($){return($.client??this.client).patch({url:"/email/threads/{thread_id}/project",...$,headers:{"Content-Type":"application/json",...$.headers}})}healthHandler($){return($?.client??this.client).get({url:"/health",...$})}}function eS({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:G,url:L,...Y}){let J,T=G??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=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(J!==void 0)P.set("Last-Event-ID",J);try{let D={redirect:"follow",...Y,body:Y.serializedBody,headers:P,signal:I},C=new Request(L,D);if($)C=await $(L,D);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="",k=()=>{try{H.cancel()}catch{}};I.addEventListener("abort",k);try{while(!0){let{done:d,value:l}=await H.read();if(d)break;U+=l,U=U.replace(/\r\n?/g,`
-`);let g=U.split(`
+`);try{_=JSON.parse(R),v=!0}catch{_=R}}if(v){if(S)await S(_);if(x)_=await x(_)}if(j?.({data:_,event:y,id:J,retry:V}),F.length)yield _}}}finally{I.removeEventListener("abort",g),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let C=Math.min(V*2**(B-1),X??30000);await T(C)}}}()}}var a7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},i7=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},n7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},nj=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((G)=>encodeURIComponent(G))).join(i7(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=a7(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return _O({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},_O=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},sj=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let G=[];Object.entries(S).forEach(([Y,J])=>{G=[...G,Y,$?J:encodeURIComponent(J)]});let L=G.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=n7(x),X=Object.entries(S).map(([G,L])=>_O({allowReserved:$,name:x==="deepObject"?`${j}[${G}]`:G,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var s7=/\{[^{}]+\}/g,t7=({path:$,url:O})=>{let j=O,x=O.match(s7);if(x)for(let S of x){let K=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))K=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let G=$[Z];if(G===void 0||G===null)continue;if(Array.isArray(G)){j=j.replace(S,nj({explode:K,name:Z,style:X,value:G}));continue}if(typeof G==="object"){j=j.replace(S,sj({explode:K,name:Z,style:X,value:G,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${_O({name:Z,value:G})}`);continue}let L=encodeURIComponent(X==="label"?`.${G}`:G);j=j.replace(S,L)}return j},dS=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=t7({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function n0($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var lS=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var rS={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var pS=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let G=nj({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(G)S.push(G)}else if(typeof Z==="object"){let G=sj({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(G)S.push(G)}else{let G=_O({allowReserved:X.allowReserved,name:K,value:Z});if(G)S.push(G)}}return S.join("&")}},aS=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},e7=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function iS($){for(let O of $.security??[]){if(e7($,O.name))continue;let j=await lS(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var s0=($)=>dS({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:pS($.querySerializer),url:$.url}),t0=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=ej($.headers,O.headers),j},o7=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},ej=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?o7(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class tj{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var nS=()=>({error:new tj,request:new tj,response:new tj}),$5=pS({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),O5={"Content-Type":"application/json"},oO=($={})=>({...rS,headers:O5,parseAs:"auto",querySerializer:$5,...$});var e0=($={})=>{let O=t0(oO(),$),j=()=>({...O}),x=(Y)=>{return O=t0(O,Y),j()},S=nS(),K=async(Y)=>{let J={...O,...Y,fetch:Y.fetch??O.fetch??globalThis.fetch,headers:ej(O.headers,Y.headers),serializedBody:void 0};if(J.security)await iS(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let T=J,z=s0(T);return{opts:T,url:z}},Z=async(Y)=>{let J=Y.throwOnError??O.throwOnError,T=Y.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(Y),I={redirect:"follow",...V,body:n0(V)};z=new Request(B,I);for(let U of S.request.fns)if(U)z=await U(z,V);let P=V.fetch;W=await P(z);for(let U of S.response.fns)if(U)W=await U(W,z,V);let D={request:z,response:W};if(W.ok){let U=(V.parseAs==="auto"?aS(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let N;switch(U){case"arrayBuffer":case"blob":case"text":N=await W[U]();break;case"formData":N=new FormData;break;case"stream":N=W.body;break;case"json":default:N={};break}return V.responseStyle==="data"?N:{data:N,...D}}let H;switch(U){case"arrayBuffer":case"blob":case"formData":case"text":H=await W[U]();break;case"json":{let N=await W.text();H=N?JSON.parse(N):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(U==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let C=await W.text(),w;try{w=JSON.parse(C)}catch{}throw w??C}catch(V){let B=V;for(let I of S.error.fns)if(I)B=await I(B,W,z,Y);if(B=B||{},J)throw B;return T==="data"?void 0:{error:B,request:z,response:W}}},X=(Y)=>(J)=>Z({...J,method:Y}),G=(Y)=>async(J)=>{let{opts:T,url:z}=await K(J);return uS({...T,body:T.body,method:Y,onRequest:async(W,V)=>{let B=new Request(W,V);for(let I of S.request.fns)if(I)B=await I(B,T);return B},serializedBody:n0(T),url:z})};return{buildUrl:(Y)=>s0({...O,...Y}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:G("CONNECT"),delete:G("DELETE"),get:G("GET"),head:G("HEAD"),options:G("OPTIONS"),patch:G("PATCH"),post:G("POST"),put:G("PUT"),trace:G("TRACE")},trace:X("TRACE")}};var sS=e0(oO());class tS{client;constructor($){this.client=$?.client??sS}}class eS{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class oj extends tS{static __registry=new eS;constructor($){super($);oj.__registry.set(this,$?.key)}getAttachment($){return($.client??this.client).get({url:"/email/attachments/{id}",...$})}getAttachmentDocumentId($){return($.client??this.client).get({url:"/email/attachments/{id}/document_id",...$})}cancelBackfillGmail($){return($.client??this.client).delete({url:"/email/backfill/gmail",...$,headers:{"Content-Type":"application/json",...$.headers}})}listBackfillGmail($){return($?.client??this.client).get({url:"/email/backfill/gmail",...$})}getBackfillGmailActive($){return($?.client??this.client).get({url:"/email/backfill/gmail/active",...$})}getBackfillGmail($){return($.client??this.client).get({url:"/email/backfill/gmail/{id}",...$})}listContacts($){return($?.client??this.client).get({url:"/email/contacts",...$})}blockSender($){return($.client??this.client).post({url:"/email/contacts/block",...$,headers:{"Content-Type":"application/json",...$.headers}})}listBlockedSenders($){return($?.client??this.client).get({url:"/email/contacts/blocked",...$})}unblockSender($){return($.client??this.client).post({url:"/email/contacts/unblock",...$,headers:{"Content-Type":"application/json",...$.headers}})}recoverDraftTransfer($){return($.client??this.client).post({url:"/email/draft-transfers/{id}/recover",...$})}createDraft($){return($.client??this.client).post({url:"/email/drafts",...$,headers:{"Content-Type":"application/json",...$.headers}})}getScheduledMessages($){return($?.client??this.client).get({url:"/email/drafts/scheduled",...$})}upsertScheduledMessage($){return($.client??this.client).put({url:"/email/drafts/scheduled/{id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteScheduledDraft($){return($.client??this.client).delete({url:"/email/drafts/scheduled/{message_id}",...$})}deleteDraft($){return($.client??this.client).delete({url:"/email/drafts/{id}",...$})}addDraftAttachment($){return($.client??this.client).post({url:"/email/drafts/{id}/attachments",...$,headers:{"Content-Type":"application/json",...$.headers}})}removeDraftAttachment($){return($.client??this.client).delete({url:"/email/drafts/{id}/attachments/{attachment_id}",...$})}completeDraftAttachment($){return($.client??this.client).post({url:"/email/drafts/{id}/attachments/{attachment_id}/complete",...$})}addForwardedAttachment($){return($.client??this.client).post({url:"/email/drafts/{id}/forwarded-attachments",...$,headers:{"Content-Type":"application/json",...$.headers}})}removeForwardedAttachment($){return($.client??this.client).delete({url:"/email/drafts/{id}/forwarded-attachments/{attachment_id}",...$})}messageOperationStatus($){return($.client??this.client).get({url:"/email/drafts/{id}/operation",...$})}resolveMessageOperation($){return($.client??this.client).post({url:"/email/drafts/{id}/resolve",...$,headers:{"Content-Type":"application/json",...$.headers}})}transferDraft($){return($.client??this.client).post({url:"/email/drafts/{id}/transfer",...$,headers:{"Content-Type":"application/json",...$.headers}})}listEmailFilters($){return($?.client??this.client).get({url:"/email/filters",...$})}upsertEmailFilter($){return($.client??this.client).put({url:"/email/filters",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteEmailFilter($){return($.client??this.client).delete({url:"/email/filters/{id}",...$})}initUser($){return($?.client??this.client).post({url:"/email/init",...$})}listLabels($){return($?.client??this.client).get({url:"/email/labels",...$})}createLabel($){return($.client??this.client).post({url:"/email/labels",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteLabel($){return($.client??this.client).delete({url:"/email/labels/{id}",...$})}listLinks($){return($?.client??this.client).get({url:"/email/links",...$})}healthCheckLinks($){return($?.client??this.client).post({url:"/email/links/health-check",...$})}deleteLink($){return($.client??this.client).delete({url:"/email/links/{link_id}",...$})}disableLinkCalendar($){return($.client??this.client).delete({url:"/email/links/{link_id}/calendar",...$})}resyncLink($){return($.client??this.client).post({url:"/email/links/{link_id}/resync",...$})}sendMessage($){return($.client??this.client).post({url:"/email/messages",...$,headers:{"Content-Type":"application/json",...$.headers}})}getMessagesBatch($){return($.client??this.client).post({url:"/email/messages/batch",...$,headers:{"Content-Type":"application/json",...$.headers}})}addRemoveLabel($){return($.client??this.client).patch({url:"/email/messages/labels",...$,headers:{"Content-Type":"application/json",...$.headers}})}getMessage($){return($.client??this.client).get({url:"/email/messages/{id}",...$})}patchSettings($){return($.client??this.client).patch({url:"/email/settings",...$,headers:{"Content-Type":"application/json",...$.headers}})}mailboxSettingsOperations($){return($?.client??this.client).get({url:"/email/settings/operations",...$})}disableSync($){return($?.client??this.client).delete({url:"/email/sync",...$})}previewsInboxCursor($){return($.client??this.client).get({url:"/email/threads/previews/cursor/{view}",...$})}archiveThread($){return($.client??this.client).patch({url:"/email/threads/{id}/archived",...$,headers:{"Content-Type":"application/json",...$.headers}})}addRemoveThreadLabel($){return($.client??this.client).patch({url:"/email/threads/{id}/labels",...$,headers:{"Content-Type":"application/json",...$.headers}})}getThreadMessagesHandler($){return($.client??this.client).get({url:"/email/threads/{id}/messages",...$})}threadOperations($){return($.client??this.client).get({url:"/email/threads/{id}/operations",...$})}threadSeen($){return($.client??this.client).post({url:"/email/threads/{id}/seen",...$})}updateThreadState($){return($.client??this.client).patch({url:"/email/threads/{id}/state",...$,headers:{"Content-Type":"application/json",...$.headers}})}getThread($){return($.client??this.client).get({url:"/email/threads/{thread_id}",...$})}getThreadCalendarInvitations($){return($.client??this.client).get({url:"/email/threads/{thread_id}/calendar-invitations",...$})}updateThreadProject($){return($.client??this.client).patch({url:"/email/threads/{thread_id}/project",...$,headers:{"Content-Type":"application/json",...$.headers}})}healthHandler($){return($?.client??this.client).get({url:"/health",...$})}}function oS({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:G,url:L,...Y}){let J,T=G??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=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(J!==void 0)P.set("Last-Event-ID",J);try{let D={redirect:"follow",...Y,body:Y.serializedBody,headers:P,signal:I},C=new Request(L,D);if($)C=await $(L,D);let U=await(Y.fetch??globalThis.fetch)(C);if(!U.ok)throw Error(`SSE failed: ${U.status} ${U.statusText}`);if(!U.body)throw Error("No body in SSE response");let H=U.body.pipeThrough(new TextDecoderStream).getReader(),N="",g=()=>{try{H.cancel()}catch{}};I.addEventListener("abort",g);try{while(!0){let{done:d,value:l}=await H.read();if(d)break;N+=l,N=N.replace(/\r\n?/g,`
+`);let k=N.split(`
-`);U=g.pop()??"";for(let r of g){let p=r.split(`
+`);N=k.pop()??"";for(let r of k){let p=r.split(`
`),F=[],y;for(let R of p)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))y=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let h=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(h))V=h}let _,v=!1;if(F.length){let R=F.join(`
-`);try{_=JSON.parse(R),v=!0}catch{_=R}}if(v){if(S)await S(_);if(x)_=await x(_)}if(j?.({data:_,event:y,id:J,retry:V}),F.length)yield _}}}finally{I.removeEventListener("abort",k),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let C=Math.min(V*2**(B-1),X??30000);await T(C)}}}()}}var O5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},j5=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},x5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},oj=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((G)=>encodeURIComponent(G))).join(j5(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=O5(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return _O({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},_O=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},$x=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let G=[];Object.entries(S).forEach(([Y,J])=>{G=[...G,Y,$?J:encodeURIComponent(J)]});let L=G.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=x5(x),X=Object.entries(S).map(([G,L])=>_O({allowReserved:$,name:x==="deepObject"?`${j}[${G}]`:G,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var S5=/\{[^{}]+\}/g,Z5=({path:$,url:O})=>{let j=O,x=O.match(S5);if(x)for(let S of x){let K=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))K=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let G=$[Z];if(G===void 0||G===null)continue;if(Array.isArray(G)){j=j.replace(S,oj({explode:K,name:Z,style:X,value:G}));continue}if(typeof G==="object"){j=j.replace(S,$x({explode:K,name:Z,style:X,value:G,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${_O({name:Z,value:G})}`);continue}let L=encodeURIComponent(X==="label"?`.${G}`:G);j=j.replace(S,L)}return j},oS=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=Z5({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function e0($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var $2=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var O2={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var j2=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let G=oj({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(G)S.push(G)}else if(typeof Z==="object"){let G=$x({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(G)S.push(G)}else{let G=_O({allowReserved:X.allowReserved,name:K,value:Z});if(G)S.push(G)}}return S.join("&")}},x2=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},X5=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function S2($){for(let O of $.security??[]){if(X5($,O.name))continue;let j=await $2(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var o0=($)=>oS({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:j2($.querySerializer),url:$.url}),$1=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=jx($.headers,O.headers),j},G5=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},jx=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?G5(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class Ox{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var Z2=()=>({error:new Ox,request:new Ox,response:new Ox}),K5=j2({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),Y5={"Content-Type":"application/json"},oO=($={})=>({...O2,headers:Y5,parseAs:"auto",querySerializer:K5,...$});var O1=($={})=>{let O=$1(oO(),$),j=()=>({...O}),x=(Y)=>{return O=$1(O,Y),j()},S=Z2(),K=async(Y)=>{let J={...O,...Y,fetch:Y.fetch??O.fetch??globalThis.fetch,headers:jx(O.headers,Y.headers),serializedBody:void 0};if(J.security)await S2(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let T=J,z=o0(T);return{opts:T,url:z}},Z=async(Y)=>{let J=Y.throwOnError??O.throwOnError,T=Y.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(Y),I={redirect:"follow",...V,body:e0(V)};z=new Request(B,I);for(let N of S.request.fns)if(N)z=await N(z,V);let P=V.fetch;W=await P(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?x2(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await W[N]();break;case"json":{let U=await W.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let C=await W.text(),E;try{E=JSON.parse(C)}catch{}throw E??C}catch(V){let B=V;for(let I of S.error.fns)if(I)B=await I(B,W,z,Y);if(B=B||{},J)throw B;return T==="data"?void 0:{error:B,request:z,response:W}}},X=(Y)=>(J)=>Z({...J,method:Y}),G=(Y)=>async(J)=>{let{opts:T,url:z}=await K(J);return eS({...T,body:T.body,method:Y,onRequest:async(W,V)=>{let B=new Request(W,V);for(let I of S.request.fns)if(I)B=await I(B,T);return B},serializedBody:e0(T),url:z})};return{buildUrl:(Y)=>o0({...O,...Y}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:G("CONNECT"),delete:G("DELETE"),get:G("GET"),head:G("HEAD"),options:G("OPTIONS"),patch:G("PATCH"),post:G("POST"),put:G("PUT"),trace:G("TRACE")},trace:X("TRACE")}};var X2=O1(oO());class G2{client;constructor($){this.client=$?.client??X2}}class K2{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class xx extends G2{static __registry=new K2;constructor($){super($);xx.__registry.set(this,$?.key)}healthHandler($){return($?.client??this.client).get({url:"/health",...$})}getUnsubscribes($){return($?.client??this.client).get({url:"/unsubscribe",...$})}unsubscribeEmail($){return($?.client??this.client).post({url:"/unsubscribe/email",...$})}removeUnsubscribeItem($){return($.client??this.client).delete({url:"/unsubscribe/item/{item_type}/{item_id}",...$})}unsubscribeItem($){return($.client??this.client).post({url:"/unsubscribe/item/{item_type}/{item_id}",...$})}removeUnsubscribeAll($){return($?.client??this.client).delete({url:"/unsubscribe/mute",...$})}unsubscribeAll($){return($?.client??this.client).post({url:"/unsubscribe/mute",...$})}listTypedNotifications($){return($?.client??this.client).get({url:"/v1/user_notifications",...$})}bulkGetTypedNotificationsByEventItemIds($){return($.client??this.client).post({url:"/v1/user_notifications/item/bulk",...$,headers:{"Content-Type":"application/json",...$.headers}})}getTypedNotificationsByEventItemId($){return($.client??this.client).get({url:"/v1/user_notifications/item/{event_item_id}",...$})}getNotificationTypePreferences($){return($?.client??this.client).get({url:"/v1/user_notifications/preferences",...$})}disableNotificationType($){return($.client??this.client).put({url:"/v1/user_notifications/preferences/{notification_event_type}/disable",...$})}enableNotificationType($){return($.client??this.client).put({url:"/v1/user_notifications/preferences/{notification_event_type}/enable",...$})}getTypedNotificationById($){return($.client??this.client).get({url:"/v1/user_notifications/{notification_id}",...$})}bulkDeleteUserNotificationsV2($){return($.client??this.client).delete({url:"/v2/user_notifications/bulk",...$,headers:{"Content-Type":"application/json",...$.headers}})}bulkMarkNotificationsDone($){return($.client??this.client).patch({url:"/v2/user_notifications/bulk/done",...$,headers:{"Content-Type":"application/json",...$.headers}})}bulkMarkNotificationsSeen($){return($.client??this.client).patch({url:"/v2/user_notifications/bulk/seen",...$,headers:{"Content-Type":"application/json",...$.headers}})}bulkMarkNotificationsUndone($){return($.client??this.client).patch({url:"/v2/user_notifications/bulk/undone",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteUserNotificationV2($){return($.client??this.client).delete({url:"/v2/user_notifications/{notification_id}",...$})}}function Y2({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:G,url:L,...Y}){let J,T=G??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=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(J!==void 0)P.set("Last-Event-ID",J);try{let D={redirect:"follow",...Y,body:Y.serializedBody,headers:P,signal:I},C=new Request(L,D);if($)C=await $(L,D);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="",k=()=>{try{H.cancel()}catch{}};I.addEventListener("abort",k);try{while(!0){let{done:d,value:l}=await H.read();if(d)break;U+=l,U=U.replace(/\r\n?/g,`
-`);let g=U.split(`
+`);try{_=JSON.parse(R),v=!0}catch{_=R}}if(v){if(S)await S(_);if(x)_=await x(_)}if(j?.({data:_,event:y,id:J,retry:V}),F.length)yield _}}}finally{I.removeEventListener("abort",g),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let C=Math.min(V*2**(B-1),X??30000);await T(C)}}}()}}var j5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},x5=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},S5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},$x=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((G)=>encodeURIComponent(G))).join(x5(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=j5(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return AO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},AO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},Ox=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let G=[];Object.entries(S).forEach(([Y,J])=>{G=[...G,Y,$?J:encodeURIComponent(J)]});let L=G.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=S5(x),X=Object.entries(S).map(([G,L])=>AO({allowReserved:$,name:x==="deepObject"?`${j}[${G}]`:G,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var Z5=/\{[^{}]+\}/g,X5=({path:$,url:O})=>{let j=O,x=O.match(Z5);if(x)for(let S of x){let K=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))K=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let G=$[Z];if(G===void 0||G===null)continue;if(Array.isArray(G)){j=j.replace(S,$x({explode:K,name:Z,style:X,value:G}));continue}if(typeof G==="object"){j=j.replace(S,Ox({explode:K,name:Z,style:X,value:G,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${AO({name:Z,value:G})}`);continue}let L=encodeURIComponent(X==="label"?`.${G}`:G);j=j.replace(S,L)}return j},$2=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=X5({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function o0($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var O2=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var j2={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var x2=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let G=$x({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(G)S.push(G)}else if(typeof Z==="object"){let G=Ox({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(G)S.push(G)}else{let G=AO({allowReserved:X.allowReserved,name:K,value:Z});if(G)S.push(G)}}return S.join("&")}},S2=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},G5=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function Z2($){for(let O of $.security??[]){if(G5($,O.name))continue;let j=await O2(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var $1=($)=>$2({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:x2($.querySerializer),url:$.url}),O1=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=xx($.headers,O.headers),j},K5=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},xx=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?K5(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class jx{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var X2=()=>({error:new jx,request:new jx,response:new jx}),Y5=x2({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),Q5={"Content-Type":"application/json"},$j=($={})=>({...j2,headers:Q5,parseAs:"auto",querySerializer:Y5,...$});var j1=($={})=>{let O=O1($j(),$),j=()=>({...O}),x=(Y)=>{return O=O1(O,Y),j()},S=X2(),K=async(Y)=>{let J={...O,...Y,fetch:Y.fetch??O.fetch??globalThis.fetch,headers:xx(O.headers,Y.headers),serializedBody:void 0};if(J.security)await Z2(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let T=J,z=$1(T);return{opts:T,url:z}},Z=async(Y)=>{let J=Y.throwOnError??O.throwOnError,T=Y.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(Y),I={redirect:"follow",...V,body:o0(V)};z=new Request(B,I);for(let U of S.request.fns)if(U)z=await U(z,V);let P=V.fetch;W=await P(z);for(let U of S.response.fns)if(U)W=await U(W,z,V);let D={request:z,response:W};if(W.ok){let U=(V.parseAs==="auto"?S2(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let N;switch(U){case"arrayBuffer":case"blob":case"text":N=await W[U]();break;case"formData":N=new FormData;break;case"stream":N=W.body;break;case"json":default:N={};break}return V.responseStyle==="data"?N:{data:N,...D}}let H;switch(U){case"arrayBuffer":case"blob":case"formData":case"text":H=await W[U]();break;case"json":{let N=await W.text();H=N?JSON.parse(N):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(U==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let C=await W.text(),w;try{w=JSON.parse(C)}catch{}throw w??C}catch(V){let B=V;for(let I of S.error.fns)if(I)B=await I(B,W,z,Y);if(B=B||{},J)throw B;return T==="data"?void 0:{error:B,request:z,response:W}}},X=(Y)=>(J)=>Z({...J,method:Y}),G=(Y)=>async(J)=>{let{opts:T,url:z}=await K(J);return oS({...T,body:T.body,method:Y,onRequest:async(W,V)=>{let B=new Request(W,V);for(let I of S.request.fns)if(I)B=await I(B,T);return B},serializedBody:o0(T),url:z})};return{buildUrl:(Y)=>$1({...O,...Y}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:G("CONNECT"),delete:G("DELETE"),get:G("GET"),head:G("HEAD"),options:G("OPTIONS"),patch:G("PATCH"),post:G("POST"),put:G("PUT"),trace:G("TRACE")},trace:X("TRACE")}};var G2=j1($j());class K2{client;constructor($){this.client=$?.client??G2}}class Y2{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class Sx extends K2{static __registry=new Y2;constructor($){super($);Sx.__registry.set(this,$?.key)}healthHandler($){return($?.client??this.client).get({url:"/health",...$})}getUnsubscribes($){return($?.client??this.client).get({url:"/unsubscribe",...$})}unsubscribeEmail($){return($?.client??this.client).post({url:"/unsubscribe/email",...$})}removeUnsubscribeItem($){return($.client??this.client).delete({url:"/unsubscribe/item/{item_type}/{item_id}",...$})}unsubscribeItem($){return($.client??this.client).post({url:"/unsubscribe/item/{item_type}/{item_id}",...$})}removeUnsubscribeAll($){return($?.client??this.client).delete({url:"/unsubscribe/mute",...$})}unsubscribeAll($){return($?.client??this.client).post({url:"/unsubscribe/mute",...$})}listTypedNotifications($){return($?.client??this.client).get({url:"/v1/user_notifications",...$})}bulkGetTypedNotificationsByEventItemIds($){return($.client??this.client).post({url:"/v1/user_notifications/item/bulk",...$,headers:{"Content-Type":"application/json",...$.headers}})}getTypedNotificationsByEventItemId($){return($.client??this.client).get({url:"/v1/user_notifications/item/{event_item_id}",...$})}getNotificationTypePreferences($){return($?.client??this.client).get({url:"/v1/user_notifications/preferences",...$})}disableNotificationType($){return($.client??this.client).put({url:"/v1/user_notifications/preferences/{notification_event_type}/disable",...$})}enableNotificationType($){return($.client??this.client).put({url:"/v1/user_notifications/preferences/{notification_event_type}/enable",...$})}getTypedNotificationById($){return($.client??this.client).get({url:"/v1/user_notifications/{notification_id}",...$})}bulkDeleteUserNotificationsV2($){return($.client??this.client).delete({url:"/v2/user_notifications/bulk",...$,headers:{"Content-Type":"application/json",...$.headers}})}bulkMarkNotificationsDone($){return($.client??this.client).patch({url:"/v2/user_notifications/bulk/done",...$,headers:{"Content-Type":"application/json",...$.headers}})}bulkMarkNotificationsSeen($){return($.client??this.client).patch({url:"/v2/user_notifications/bulk/seen",...$,headers:{"Content-Type":"application/json",...$.headers}})}bulkMarkNotificationsUndone($){return($.client??this.client).patch({url:"/v2/user_notifications/bulk/undone",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteUserNotificationV2($){return($.client??this.client).delete({url:"/v2/user_notifications/{notification_id}",...$})}}function Q2({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:G,url:L,...Y}){let J,T=G??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=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(J!==void 0)P.set("Last-Event-ID",J);try{let D={redirect:"follow",...Y,body:Y.serializedBody,headers:P,signal:I},C=new Request(L,D);if($)C=await $(L,D);let U=await(Y.fetch??globalThis.fetch)(C);if(!U.ok)throw Error(`SSE failed: ${U.status} ${U.statusText}`);if(!U.body)throw Error("No body in SSE response");let H=U.body.pipeThrough(new TextDecoderStream).getReader(),N="",g=()=>{try{H.cancel()}catch{}};I.addEventListener("abort",g);try{while(!0){let{done:d,value:l}=await H.read();if(d)break;N+=l,N=N.replace(/\r\n?/g,`
+`);let k=N.split(`
-`);U=g.pop()??"";for(let r of g){let p=r.split(`
+`);N=k.pop()??"";for(let r of k){let p=r.split(`
`),F=[],y;for(let R of p)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))y=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let h=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(h))V=h}let _,v=!1;if(F.length){let R=F.join(`
-`);try{_=JSON.parse(R),v=!0}catch{_=R}}if(v){if(S)await S(_);if(x)_=await x(_)}if(j?.({data:_,event:y,id:J,retry:V}),F.length)yield _}}}finally{I.removeEventListener("abort",k),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let C=Math.min(V*2**(B-1),X??30000);await T(C)}}}()}}var Q5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},J5=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},V5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},Sx=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((G)=>encodeURIComponent(G))).join(J5(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=Q5(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return MO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},MO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},Zx=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let G=[];Object.entries(S).forEach(([Y,J])=>{G=[...G,Y,$?J:encodeURIComponent(J)]});let L=G.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=V5(x),X=Object.entries(S).map(([G,L])=>MO({allowReserved:$,name:x==="deepObject"?`${j}[${G}]`:G,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var W5=/\{[^{}]+\}/g,B5=({path:$,url:O})=>{let j=O,x=O.match(W5);if(x)for(let S of x){let K=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))K=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let G=$[Z];if(G===void 0||G===null)continue;if(Array.isArray(G)){j=j.replace(S,Sx({explode:K,name:Z,style:X,value:G}));continue}if(typeof G==="object"){j=j.replace(S,Zx({explode:K,name:Z,style:X,value:G,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${MO({name:Z,value:G})}`);continue}let L=encodeURIComponent(X==="label"?`.${G}`:G);j=j.replace(S,L)}return j},Q2=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=B5({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function j1($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var J2=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var V2={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var W2=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let G=Sx({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(G)S.push(G)}else if(typeof Z==="object"){let G=Zx({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(G)S.push(G)}else{let G=MO({allowReserved:X.allowReserved,name:K,value:Z});if(G)S.push(G)}}return S.join("&")}},B2=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},L5=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function L2($){for(let O of $.security??[]){if(L5($,O.name))continue;let j=await J2(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var x1=($)=>Q2({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:W2($.querySerializer),url:$.url}),S1=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=Gx($.headers,O.headers),j},N5=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},Gx=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?N5(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class Xx{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var N2=()=>({error:new Xx,request:new Xx,response:new Xx}),U5=W2({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),z5={"Content-Type":"application/json"},$j=($={})=>({...V2,headers:z5,parseAs:"auto",querySerializer:U5,...$});var Z1=($={})=>{let O=S1($j(),$),j=()=>({...O}),x=(Y)=>{return O=S1(O,Y),j()},S=N2(),K=async(Y)=>{let J={...O,...Y,fetch:Y.fetch??O.fetch??globalThis.fetch,headers:Gx(O.headers,Y.headers),serializedBody:void 0};if(J.security)await L2(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let T=J,z=x1(T);return{opts:T,url:z}},Z=async(Y)=>{let J=Y.throwOnError??O.throwOnError,T=Y.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(Y),I={redirect:"follow",...V,body:j1(V)};z=new Request(B,I);for(let N of S.request.fns)if(N)z=await N(z,V);let P=V.fetch;W=await P(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?B2(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await W[N]();break;case"json":{let U=await W.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let C=await W.text(),E;try{E=JSON.parse(C)}catch{}throw E??C}catch(V){let B=V;for(let I of S.error.fns)if(I)B=await I(B,W,z,Y);if(B=B||{},J)throw B;return T==="data"?void 0:{error:B,request:z,response:W}}},X=(Y)=>(J)=>Z({...J,method:Y}),G=(Y)=>async(J)=>{let{opts:T,url:z}=await K(J);return Y2({...T,body:T.body,method:Y,onRequest:async(W,V)=>{let B=new Request(W,V);for(let I of S.request.fns)if(I)B=await I(B,T);return B},serializedBody:j1(T),url:z})};return{buildUrl:(Y)=>x1({...O,...Y}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:G("CONNECT"),delete:G("DELETE"),get:G("GET"),head:G("HEAD"),options:G("OPTIONS"),patch:G("PATCH"),post:G("POST"),put:G("PUT"),trace:G("TRACE")},trace:X("TRACE")}};var U2=Z1($j());class z2{client;constructor($){this.client=$?.client??U2}}class I2{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class Kx extends z2{static __registry=new I2;constructor($){super($);Kx.__registry.set(this,$?.key)}listProperties($){return($.client??this.client).get({url:"/properties/definitions",...$})}createPropertyDefinition($){return($.client??this.client).post({url:"/properties/definitions",...$,headers:{"Content-Type":"application/json",...$.headers}})}deletePropertyDefinition($){return($.client??this.client).delete({url:"/properties/definitions/{definition_id}",...$})}getPropertyDefinition($){return($.client??this.client).get({url:"/properties/definitions/{definition_id}",...$})}getPropertyOptions($){return($.client??this.client).get({url:"/properties/definitions/{definition_id}/options",...$})}addPropertyOption($){return($.client??this.client).post({url:"/properties/definitions/{definition_id}/options",...$,headers:{"Content-Type":"application/json",...$.headers}})}deletePropertyOption($){return($.client??this.client).delete({url:"/properties/definitions/{definition_id}/options/{option_id}",...$})}updatePropertyOption($){return($.client??this.client).patch({url:"/properties/definitions/{definition_id}/options/{option_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getBulkEntityProperties($){return($.client??this.client).post({url:"/properties/entities/bulk",...$,headers:{"Content-Type":"application/json",...$.headers}})}getEntityProperties($){return($.client??this.client).get({url:"/properties/entities/{entity_type}/{entity_id}",...$})}bulkUpdateEntityPropertyOptions($){return($.client??this.client).post({url:"/properties/entities/{entity_type}/{entity_id}/options/bulk",...$,headers:{"Content-Type":"application/json",...$.headers}})}setEntityProperty($){return($.client??this.client).put({url:"/properties/entities/{entity_type}/{entity_id}/{property_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}removeEntityPropertyOption($){return($.client??this.client).delete({url:"/properties/entities/{entity_type}/{entity_id}/{property_id}/options/{option_id}",...$})}addEntityPropertyOption($){return($.client??this.client).post({url:"/properties/entities/{entity_type}/{entity_id}/{property_id}/options/{option_id}",...$})}deleteEntityProperty($){return($.client??this.client).delete({url:"/properties/entity_properties/{entity_property_id}",...$})}bulkUpdateEntitiesPropertyOptions($){return($.client??this.client).post({url:"/properties/options/bulk",...$,headers:{"Content-Type":"application/json",...$.headers}})}listTags($){return($?.client??this.client).get({url:"/properties/tags",...$})}ensureTagSet($){return($.client??this.client).post({url:"/properties/tags",...$,headers:{"Content-Type":"application/json",...$.headers}})}mergeTag($){return($.client??this.client).post({url:"/properties/tags/merge",...$,headers:{"Content-Type":"application/json",...$.headers}})}promoteTag($){return($.client??this.client).post({url:"/properties/tags/promote",...$,headers:{"Content-Type":"application/json",...$.headers}})}}function T2({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:G,url:L,...Y}){let J,T=G??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=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(J!==void 0)P.set("Last-Event-ID",J);try{let D={redirect:"follow",...Y,body:Y.serializedBody,headers:P,signal:I},C=new Request(L,D);if($)C=await $(L,D);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="",k=()=>{try{H.cancel()}catch{}};I.addEventListener("abort",k);try{while(!0){let{done:d,value:l}=await H.read();if(d)break;U+=l,U=U.replace(/\r\n?/g,`
-`);let g=U.split(`
+`);try{_=JSON.parse(R),v=!0}catch{_=R}}if(v){if(S)await S(_);if(x)_=await x(_)}if(j?.({data:_,event:y,id:J,retry:V}),F.length)yield _}}}finally{I.removeEventListener("abort",g),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let C=Math.min(V*2**(B-1),X??30000);await T(C)}}}()}}var J5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},V5=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},W5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},Zx=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((G)=>encodeURIComponent(G))).join(V5(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=J5(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return MO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},MO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},Xx=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let G=[];Object.entries(S).forEach(([Y,J])=>{G=[...G,Y,$?J:encodeURIComponent(J)]});let L=G.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=W5(x),X=Object.entries(S).map(([G,L])=>MO({allowReserved:$,name:x==="deepObject"?`${j}[${G}]`:G,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var B5=/\{[^{}]+\}/g,L5=({path:$,url:O})=>{let j=O,x=O.match(B5);if(x)for(let S of x){let K=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))K=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let G=$[Z];if(G===void 0||G===null)continue;if(Array.isArray(G)){j=j.replace(S,Zx({explode:K,name:Z,style:X,value:G}));continue}if(typeof G==="object"){j=j.replace(S,Xx({explode:K,name:Z,style:X,value:G,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${MO({name:Z,value:G})}`);continue}let L=encodeURIComponent(X==="label"?`.${G}`:G);j=j.replace(S,L)}return j},J2=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=L5({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function x1($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var V2=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var W2={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var B2=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let G=Zx({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(G)S.push(G)}else if(typeof Z==="object"){let G=Xx({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(G)S.push(G)}else{let G=MO({allowReserved:X.allowReserved,name:K,value:Z});if(G)S.push(G)}}return S.join("&")}},L2=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},U5=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function U2($){for(let O of $.security??[]){if(U5($,O.name))continue;let j=await V2(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var S1=($)=>J2({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:B2($.querySerializer),url:$.url}),Z1=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=Kx($.headers,O.headers),j},N5=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},Kx=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?N5(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class Gx{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var N2=()=>({error:new Gx,request:new Gx,response:new Gx}),z5=B2({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),I5={"Content-Type":"application/json"},Oj=($={})=>({...W2,headers:I5,parseAs:"auto",querySerializer:z5,...$});var X1=($={})=>{let O=Z1(Oj(),$),j=()=>({...O}),x=(Y)=>{return O=Z1(O,Y),j()},S=N2(),K=async(Y)=>{let J={...O,...Y,fetch:Y.fetch??O.fetch??globalThis.fetch,headers:Kx(O.headers,Y.headers),serializedBody:void 0};if(J.security)await U2(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let T=J,z=S1(T);return{opts:T,url:z}},Z=async(Y)=>{let J=Y.throwOnError??O.throwOnError,T=Y.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(Y),I={redirect:"follow",...V,body:x1(V)};z=new Request(B,I);for(let U of S.request.fns)if(U)z=await U(z,V);let P=V.fetch;W=await P(z);for(let U of S.response.fns)if(U)W=await U(W,z,V);let D={request:z,response:W};if(W.ok){let U=(V.parseAs==="auto"?L2(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let N;switch(U){case"arrayBuffer":case"blob":case"text":N=await W[U]();break;case"formData":N=new FormData;break;case"stream":N=W.body;break;case"json":default:N={};break}return V.responseStyle==="data"?N:{data:N,...D}}let H;switch(U){case"arrayBuffer":case"blob":case"formData":case"text":H=await W[U]();break;case"json":{let N=await W.text();H=N?JSON.parse(N):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(U==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let C=await W.text(),w;try{w=JSON.parse(C)}catch{}throw w??C}catch(V){let B=V;for(let I of S.error.fns)if(I)B=await I(B,W,z,Y);if(B=B||{},J)throw B;return T==="data"?void 0:{error:B,request:z,response:W}}},X=(Y)=>(J)=>Z({...J,method:Y}),G=(Y)=>async(J)=>{let{opts:T,url:z}=await K(J);return Q2({...T,body:T.body,method:Y,onRequest:async(W,V)=>{let B=new Request(W,V);for(let I of S.request.fns)if(I)B=await I(B,T);return B},serializedBody:x1(T),url:z})};return{buildUrl:(Y)=>S1({...O,...Y}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:G("CONNECT"),delete:G("DELETE"),get:G("GET"),head:G("HEAD"),options:G("OPTIONS"),patch:G("PATCH"),post:G("POST"),put:G("PUT"),trace:G("TRACE")},trace:X("TRACE")}};var z2=X1(Oj());class I2{client;constructor($){this.client=$?.client??z2}}class T2{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class Yx extends I2{static __registry=new T2;constructor($){super($);Yx.__registry.set(this,$?.key)}listProperties($){return($.client??this.client).get({url:"/properties/definitions",...$})}createPropertyDefinition($){return($.client??this.client).post({url:"/properties/definitions",...$,headers:{"Content-Type":"application/json",...$.headers}})}deletePropertyDefinition($){return($.client??this.client).delete({url:"/properties/definitions/{definition_id}",...$})}getPropertyDefinition($){return($.client??this.client).get({url:"/properties/definitions/{definition_id}",...$})}getPropertyOptions($){return($.client??this.client).get({url:"/properties/definitions/{definition_id}/options",...$})}addPropertyOption($){return($.client??this.client).post({url:"/properties/definitions/{definition_id}/options",...$,headers:{"Content-Type":"application/json",...$.headers}})}deletePropertyOption($){return($.client??this.client).delete({url:"/properties/definitions/{definition_id}/options/{option_id}",...$})}updatePropertyOption($){return($.client??this.client).patch({url:"/properties/definitions/{definition_id}/options/{option_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getBulkEntityProperties($){return($.client??this.client).post({url:"/properties/entities/bulk",...$,headers:{"Content-Type":"application/json",...$.headers}})}getEntityProperties($){return($.client??this.client).get({url:"/properties/entities/{entity_type}/{entity_id}",...$})}bulkUpdateEntityPropertyOptions($){return($.client??this.client).post({url:"/properties/entities/{entity_type}/{entity_id}/options/bulk",...$,headers:{"Content-Type":"application/json",...$.headers}})}setEntityProperty($){return($.client??this.client).put({url:"/properties/entities/{entity_type}/{entity_id}/{property_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}removeEntityPropertyOption($){return($.client??this.client).delete({url:"/properties/entities/{entity_type}/{entity_id}/{property_id}/options/{option_id}",...$})}addEntityPropertyOption($){return($.client??this.client).post({url:"/properties/entities/{entity_type}/{entity_id}/{property_id}/options/{option_id}",...$})}deleteEntityProperty($){return($.client??this.client).delete({url:"/properties/entity_properties/{entity_property_id}",...$})}bulkUpdateEntitiesPropertyOptions($){return($.client??this.client).post({url:"/properties/options/bulk",...$,headers:{"Content-Type":"application/json",...$.headers}})}listTags($){return($?.client??this.client).get({url:"/properties/tags",...$})}ensureTagSet($){return($.client??this.client).post({url:"/properties/tags",...$,headers:{"Content-Type":"application/json",...$.headers}})}mergeTag($){return($.client??this.client).post({url:"/properties/tags/merge",...$,headers:{"Content-Type":"application/json",...$.headers}})}promoteTag($){return($.client??this.client).post({url:"/properties/tags/promote",...$,headers:{"Content-Type":"application/json",...$.headers}})}}function H2({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:G,url:L,...Y}){let J,T=G??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=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(J!==void 0)P.set("Last-Event-ID",J);try{let D={redirect:"follow",...Y,body:Y.serializedBody,headers:P,signal:I},C=new Request(L,D);if($)C=await $(L,D);let U=await(Y.fetch??globalThis.fetch)(C);if(!U.ok)throw Error(`SSE failed: ${U.status} ${U.statusText}`);if(!U.body)throw Error("No body in SSE response");let H=U.body.pipeThrough(new TextDecoderStream).getReader(),N="",g=()=>{try{H.cancel()}catch{}};I.addEventListener("abort",g);try{while(!0){let{done:d,value:l}=await H.read();if(d)break;N+=l,N=N.replace(/\r\n?/g,`
+`);let k=N.split(`
-`);U=g.pop()??"";for(let r of g){let p=r.split(`
+`);N=k.pop()??"";for(let r of k){let p=r.split(`
`),F=[],y;for(let R of p)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))y=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let h=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(h))V=h}let _,v=!1;if(F.length){let R=F.join(`
-`);try{_=JSON.parse(R),v=!0}catch{_=R}}if(v){if(S)await S(_);if(x)_=await x(_)}if(j?.({data:_,event:y,id:J,retry:V}),F.length)yield _}}}finally{I.removeEventListener("abort",k),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let C=Math.min(V*2**(B-1),X??30000);await T(C)}}}()}}var I5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},T5=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},H5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},Yx=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((G)=>encodeURIComponent(G))).join(T5(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=I5(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return AO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},AO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},Qx=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let G=[];Object.entries(S).forEach(([Y,J])=>{G=[...G,Y,$?J:encodeURIComponent(J)]});let L=G.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=H5(x),X=Object.entries(S).map(([G,L])=>AO({allowReserved:$,name:x==="deepObject"?`${j}[${G}]`:G,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var R5=/\{[^{}]+\}/g,D5=({path:$,url:O})=>{let j=O,x=O.match(R5);if(x)for(let S of x){let K=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))K=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let G=$[Z];if(G===void 0||G===null)continue;if(Array.isArray(G)){j=j.replace(S,Yx({explode:K,name:Z,style:X,value:G}));continue}if(typeof G==="object"){j=j.replace(S,Qx({explode:K,name:Z,style:X,value:G,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${AO({name:Z,value:G})}`);continue}let L=encodeURIComponent(X==="label"?`.${G}`:G);j=j.replace(S,L)}return j},H2=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=D5({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function X1($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var R2=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var D2={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var C2=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let G=Yx({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(G)S.push(G)}else if(typeof Z==="object"){let G=Qx({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(G)S.push(G)}else{let G=AO({allowReserved:X.allowReserved,name:K,value:Z});if(G)S.push(G)}}return S.join("&")}},_2=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},C5=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function M2($){for(let O of $.security??[]){if(C5($,O.name))continue;let j=await R2(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var G1=($)=>H2({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:C2($.querySerializer),url:$.url}),K1=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=Vx($.headers,O.headers),j},_5=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},Vx=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?_5(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class Jx{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var A2=()=>({error:new Jx,request:new Jx,response:new Jx}),M5=C2({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),A5={"Content-Type":"application/json"},Oj=($={})=>({...D2,headers:A5,parseAs:"auto",querySerializer:M5,...$});var Y1=($={})=>{let O=K1(Oj(),$),j=()=>({...O}),x=(Y)=>{return O=K1(O,Y),j()},S=A2(),K=async(Y)=>{let J={...O,...Y,fetch:Y.fetch??O.fetch??globalThis.fetch,headers:Vx(O.headers,Y.headers),serializedBody:void 0};if(J.security)await M2(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let T=J,z=G1(T);return{opts:T,url:z}},Z=async(Y)=>{let J=Y.throwOnError??O.throwOnError,T=Y.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(Y),I={redirect:"follow",...V,body:X1(V)};z=new Request(B,I);for(let N of S.request.fns)if(N)z=await N(z,V);let P=V.fetch;W=await P(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?_2(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await W[N]();break;case"json":{let U=await W.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let C=await W.text(),E;try{E=JSON.parse(C)}catch{}throw E??C}catch(V){let B=V;for(let I of S.error.fns)if(I)B=await I(B,W,z,Y);if(B=B||{},J)throw B;return T==="data"?void 0:{error:B,request:z,response:W}}},X=(Y)=>(J)=>Z({...J,method:Y}),G=(Y)=>async(J)=>{let{opts:T,url:z}=await K(J);return T2({...T,body:T.body,method:Y,onRequest:async(W,V)=>{let B=new Request(W,V);for(let I of S.request.fns)if(I)B=await I(B,T);return B},serializedBody:X1(T),url:z})};return{buildUrl:(Y)=>G1({...O,...Y}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:G("CONNECT"),delete:G("DELETE"),get:G("GET"),head:G("HEAD"),options:G("OPTIONS"),patch:G("PATCH"),post:G("POST"),put:G("PUT"),trace:G("TRACE")},trace:X("TRACE")}};var P2=Y1(Oj());class F2{client;constructor($){this.client=$?.client??P2}}class E2{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class Wx extends F2{static __registry=new E2;constructor($){super($);Wx.__registry.set(this,$?.key)}scheduledActionHealth($){return($?.client??this.client).get({url:"/health",...$})}listScheduledActions($){return($?.client??this.client).get({url:"/scheduled-actions",...$})}createScheduledAction($){return($.client??this.client).post({url:"/scheduled-actions",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteScheduledAction($){return($.client??this.client).delete({url:"/scheduled-actions/{id}",...$})}getScheduledAction($){return($.client??this.client).get({url:"/scheduled-actions/{id}",...$})}updateScheduledAction($){return($.client??this.client).put({url:"/scheduled-actions/{id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}setScheduledActionEnabled($){return($.client??this.client).put({url:"/scheduled-actions/{id}/enabled",...$,headers:{"Content-Type":"application/json",...$.headers}})}executeScheduledActionNow($){return($.client??this.client).post({url:"/scheduled-actions/{id}/execute",...$})}listScheduledActionHistory($){return($.client??this.client).get({url:"/scheduled-actions/{id}/history",...$})}}function w2({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:G,url:L,...Y}){let J,T=G??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=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(J!==void 0)P.set("Last-Event-ID",J);try{let D={redirect:"follow",...Y,body:Y.serializedBody,headers:P,signal:I},C=new Request(L,D);if($)C=await $(L,D);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="",k=()=>{try{H.cancel()}catch{}};I.addEventListener("abort",k);try{while(!0){let{done:d,value:l}=await H.read();if(d)break;U+=l,U=U.replace(/\r\n?/g,`
-`);let g=U.split(`
+`);try{_=JSON.parse(R),v=!0}catch{_=R}}if(v){if(S)await S(_);if(x)_=await x(_)}if(j?.({data:_,event:y,id:J,retry:V}),F.length)yield _}}}finally{I.removeEventListener("abort",g),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let C=Math.min(V*2**(B-1),X??30000);await T(C)}}}()}}var T5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},H5=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},R5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},Qx=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((G)=>encodeURIComponent(G))).join(H5(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=T5(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return PO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},PO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},Jx=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let G=[];Object.entries(S).forEach(([Y,J])=>{G=[...G,Y,$?J:encodeURIComponent(J)]});let L=G.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=R5(x),X=Object.entries(S).map(([G,L])=>PO({allowReserved:$,name:x==="deepObject"?`${j}[${G}]`:G,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var D5=/\{[^{}]+\}/g,C5=({path:$,url:O})=>{let j=O,x=O.match(D5);if(x)for(let S of x){let K=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))K=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let G=$[Z];if(G===void 0||G===null)continue;if(Array.isArray(G)){j=j.replace(S,Qx({explode:K,name:Z,style:X,value:G}));continue}if(typeof G==="object"){j=j.replace(S,Jx({explode:K,name:Z,style:X,value:G,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${PO({name:Z,value:G})}`);continue}let L=encodeURIComponent(X==="label"?`.${G}`:G);j=j.replace(S,L)}return j},R2=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=C5({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function G1($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var D2=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var C2={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var _2=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let G=Qx({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(G)S.push(G)}else if(typeof Z==="object"){let G=Jx({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(G)S.push(G)}else{let G=PO({allowReserved:X.allowReserved,name:K,value:Z});if(G)S.push(G)}}return S.join("&")}},A2=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},_5=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function M2($){for(let O of $.security??[]){if(_5($,O.name))continue;let j=await D2(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var K1=($)=>R2({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:_2($.querySerializer),url:$.url}),Y1=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=Wx($.headers,O.headers),j},A5=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},Wx=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?A5(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class Vx{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var P2=()=>({error:new Vx,request:new Vx,response:new Vx}),M5=_2({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),P5={"Content-Type":"application/json"},jj=($={})=>({...C2,headers:P5,parseAs:"auto",querySerializer:M5,...$});var Q1=($={})=>{let O=Y1(jj(),$),j=()=>({...O}),x=(Y)=>{return O=Y1(O,Y),j()},S=P2(),K=async(Y)=>{let J={...O,...Y,fetch:Y.fetch??O.fetch??globalThis.fetch,headers:Wx(O.headers,Y.headers),serializedBody:void 0};if(J.security)await M2(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let T=J,z=K1(T);return{opts:T,url:z}},Z=async(Y)=>{let J=Y.throwOnError??O.throwOnError,T=Y.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(Y),I={redirect:"follow",...V,body:G1(V)};z=new Request(B,I);for(let U of S.request.fns)if(U)z=await U(z,V);let P=V.fetch;W=await P(z);for(let U of S.response.fns)if(U)W=await U(W,z,V);let D={request:z,response:W};if(W.ok){let U=(V.parseAs==="auto"?A2(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let N;switch(U){case"arrayBuffer":case"blob":case"text":N=await W[U]();break;case"formData":N=new FormData;break;case"stream":N=W.body;break;case"json":default:N={};break}return V.responseStyle==="data"?N:{data:N,...D}}let H;switch(U){case"arrayBuffer":case"blob":case"formData":case"text":H=await W[U]();break;case"json":{let N=await W.text();H=N?JSON.parse(N):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(U==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let C=await W.text(),w;try{w=JSON.parse(C)}catch{}throw w??C}catch(V){let B=V;for(let I of S.error.fns)if(I)B=await I(B,W,z,Y);if(B=B||{},J)throw B;return T==="data"?void 0:{error:B,request:z,response:W}}},X=(Y)=>(J)=>Z({...J,method:Y}),G=(Y)=>async(J)=>{let{opts:T,url:z}=await K(J);return H2({...T,body:T.body,method:Y,onRequest:async(W,V)=>{let B=new Request(W,V);for(let I of S.request.fns)if(I)B=await I(B,T);return B},serializedBody:G1(T),url:z})};return{buildUrl:(Y)=>K1({...O,...Y}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:G("CONNECT"),delete:G("DELETE"),get:G("GET"),head:G("HEAD"),options:G("OPTIONS"),patch:G("PATCH"),post:G("POST"),put:G("PUT"),trace:G("TRACE")},trace:X("TRACE")}};var F2=Q1(jj());class E2{client;constructor($){this.client=$?.client??F2}}class w2{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class Bx extends E2{static __registry=new w2;constructor($){super($);Bx.__registry.set(this,$?.key)}scheduledActionHealth($){return($?.client??this.client).get({url:"/health",...$})}listScheduledActions($){return($?.client??this.client).get({url:"/scheduled-actions",...$})}createScheduledAction($){return($.client??this.client).post({url:"/scheduled-actions",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteScheduledAction($){return($.client??this.client).delete({url:"/scheduled-actions/{id}",...$})}getScheduledAction($){return($.client??this.client).get({url:"/scheduled-actions/{id}",...$})}updateScheduledAction($){return($.client??this.client).put({url:"/scheduled-actions/{id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}setScheduledActionEnabled($){return($.client??this.client).put({url:"/scheduled-actions/{id}/enabled",...$,headers:{"Content-Type":"application/json",...$.headers}})}executeScheduledActionNow($){return($.client??this.client).post({url:"/scheduled-actions/{id}/execute",...$})}listScheduledActionHistory($){return($.client??this.client).get({url:"/scheduled-actions/{id}/history",...$})}}function q2({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:G,url:L,...Y}){let J,T=G??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=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(J!==void 0)P.set("Last-Event-ID",J);try{let D={redirect:"follow",...Y,body:Y.serializedBody,headers:P,signal:I},C=new Request(L,D);if($)C=await $(L,D);let U=await(Y.fetch??globalThis.fetch)(C);if(!U.ok)throw Error(`SSE failed: ${U.status} ${U.statusText}`);if(!U.body)throw Error("No body in SSE response");let H=U.body.pipeThrough(new TextDecoderStream).getReader(),N="",g=()=>{try{H.cancel()}catch{}};I.addEventListener("abort",g);try{while(!0){let{done:d,value:l}=await H.read();if(d)break;N+=l,N=N.replace(/\r\n?/g,`
+`);let k=N.split(`
-`);U=g.pop()??"";for(let r of g){let p=r.split(`
+`);N=k.pop()??"";for(let r of k){let p=r.split(`
`),F=[],y;for(let R of p)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))y=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let h=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(h))V=h}let _,v=!1;if(F.length){let R=F.join(`
-`);try{_=JSON.parse(R),v=!0}catch{_=R}}if(v){if(S)await S(_);if(x)_=await x(_)}if(j?.({data:_,event:y,id:J,retry:V}),F.length)yield _}}}finally{I.removeEventListener("abort",k),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let C=Math.min(V*2**(B-1),X??30000);await T(C)}}}()}}var P5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},F5=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},E5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},Bx=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((G)=>encodeURIComponent(G))).join(F5(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=P5(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return PO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},PO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},Lx=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let G=[];Object.entries(S).forEach(([Y,J])=>{G=[...G,Y,$?J:encodeURIComponent(J)]});let L=G.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=E5(x),X=Object.entries(S).map(([G,L])=>PO({allowReserved:$,name:x==="deepObject"?`${j}[${G}]`:G,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var w5=/\{[^{}]+\}/g,q5=({path:$,url:O})=>{let j=O,x=O.match(w5);if(x)for(let S of x){let K=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))K=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let G=$[Z];if(G===void 0||G===null)continue;if(Array.isArray(G)){j=j.replace(S,Bx({explode:K,name:Z,style:X,value:G}));continue}if(typeof G==="object"){j=j.replace(S,Lx({explode:K,name:Z,style:X,value:G,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${PO({name:Z,value:G})}`);continue}let L=encodeURIComponent(X==="label"?`.${G}`:G);j=j.replace(S,L)}return j},q2=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=q5({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function Q1($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var f2=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var b2={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var k2=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let G=Bx({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(G)S.push(G)}else if(typeof Z==="object"){let G=Lx({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(G)S.push(G)}else{let G=PO({allowReserved:X.allowReserved,name:K,value:Z});if(G)S.push(G)}}return S.join("&")}},g2=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},f5=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function y2($){for(let O of $.security??[]){if(f5($,O.name))continue;let j=await f2(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var J1=($)=>q2({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:k2($.querySerializer),url:$.url}),V1=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=Ux($.headers,O.headers),j},b5=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},Ux=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?b5(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class Nx{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var v2=()=>({error:new Nx,request:new Nx,response:new Nx}),k5=k2({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),g5={"Content-Type":"application/json"},jj=($={})=>({...b2,headers:g5,parseAs:"auto",querySerializer:k5,...$});var W1=($={})=>{let O=V1(jj(),$),j=()=>({...O}),x=(Y)=>{return O=V1(O,Y),j()},S=v2(),K=async(Y)=>{let J={...O,...Y,fetch:Y.fetch??O.fetch??globalThis.fetch,headers:Ux(O.headers,Y.headers),serializedBody:void 0};if(J.security)await y2(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let T=J,z=J1(T);return{opts:T,url:z}},Z=async(Y)=>{let J=Y.throwOnError??O.throwOnError,T=Y.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(Y),I={redirect:"follow",...V,body:Q1(V)};z=new Request(B,I);for(let N of S.request.fns)if(N)z=await N(z,V);let P=V.fetch;W=await P(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?g2(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await W[N]();break;case"json":{let U=await W.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let C=await W.text(),E;try{E=JSON.parse(C)}catch{}throw E??C}catch(V){let B=V;for(let I of S.error.fns)if(I)B=await I(B,W,z,Y);if(B=B||{},J)throw B;return T==="data"?void 0:{error:B,request:z,response:W}}},X=(Y)=>(J)=>Z({...J,method:Y}),G=(Y)=>async(J)=>{let{opts:T,url:z}=await K(J);return w2({...T,body:T.body,method:Y,onRequest:async(W,V)=>{let B=new Request(W,V);for(let I of S.request.fns)if(I)B=await I(B,T);return B},serializedBody:Q1(T),url:z})};return{buildUrl:(Y)=>J1({...O,...Y}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:G("CONNECT"),delete:G("DELETE"),get:G("GET"),head:G("HEAD"),options:G("OPTIONS"),patch:G("PATCH"),post:G("POST"),put:G("PUT"),trace:G("TRACE")},trace:X("TRACE")}};var h2=W1(jj());class m2{client;constructor($){this.client=$?.client??h2}}class c2{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class zx extends m2{static __registry=new c2;constructor($){super($);zx.__registry.set(this,$?.key)}unifiedSearch($){return($.client??this.client).post({url:"/search",...$,headers:{"Content-Type":"application/json",...$.headers}})}simpleUnifiedSearch($){return($.client??this.client).post({url:"/search/simple",...$,headers:{"Content-Type":"application/json",...$.headers}})}}function u2({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:G,url:L,...Y}){let J,T=G??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=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(J!==void 0)P.set("Last-Event-ID",J);try{let D={redirect:"follow",...Y,body:Y.serializedBody,headers:P,signal:I},C=new Request(L,D);if($)C=await $(L,D);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="",k=()=>{try{H.cancel()}catch{}};I.addEventListener("abort",k);try{while(!0){let{done:d,value:l}=await H.read();if(d)break;U+=l,U=U.replace(/\r\n?/g,`
-`);let g=U.split(`
+`);try{_=JSON.parse(R),v=!0}catch{_=R}}if(v){if(S)await S(_);if(x)_=await x(_)}if(j?.({data:_,event:y,id:J,retry:V}),F.length)yield _}}}finally{I.removeEventListener("abort",g),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let C=Math.min(V*2**(B-1),X??30000);await T(C)}}}()}}var F5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},E5=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},w5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},Lx=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((G)=>encodeURIComponent(G))).join(E5(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=F5(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return FO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},FO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},Ux=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let G=[];Object.entries(S).forEach(([Y,J])=>{G=[...G,Y,$?J:encodeURIComponent(J)]});let L=G.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=w5(x),X=Object.entries(S).map(([G,L])=>FO({allowReserved:$,name:x==="deepObject"?`${j}[${G}]`:G,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var q5=/\{[^{}]+\}/g,f5=({path:$,url:O})=>{let j=O,x=O.match(q5);if(x)for(let S of x){let K=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))K=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let G=$[Z];if(G===void 0||G===null)continue;if(Array.isArray(G)){j=j.replace(S,Lx({explode:K,name:Z,style:X,value:G}));continue}if(typeof G==="object"){j=j.replace(S,Ux({explode:K,name:Z,style:X,value:G,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${FO({name:Z,value:G})}`);continue}let L=encodeURIComponent(X==="label"?`.${G}`:G);j=j.replace(S,L)}return j},f2=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=f5({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function J1($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var b2=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var g2={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var k2=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let G=Lx({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(G)S.push(G)}else if(typeof Z==="object"){let G=Ux({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(G)S.push(G)}else{let G=FO({allowReserved:X.allowReserved,name:K,value:Z});if(G)S.push(G)}}return S.join("&")}},y2=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},b5=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function v2($){for(let O of $.security??[]){if(b5($,O.name))continue;let j=await b2(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var V1=($)=>f2({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:k2($.querySerializer),url:$.url}),W1=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=zx($.headers,O.headers),j},g5=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},zx=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?g5(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class Nx{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var h2=()=>({error:new Nx,request:new Nx,response:new Nx}),k5=k2({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),y5={"Content-Type":"application/json"},xj=($={})=>({...g2,headers:y5,parseAs:"auto",querySerializer:k5,...$});var B1=($={})=>{let O=W1(xj(),$),j=()=>({...O}),x=(Y)=>{return O=W1(O,Y),j()},S=h2(),K=async(Y)=>{let J={...O,...Y,fetch:Y.fetch??O.fetch??globalThis.fetch,headers:zx(O.headers,Y.headers),serializedBody:void 0};if(J.security)await v2(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let T=J,z=V1(T);return{opts:T,url:z}},Z=async(Y)=>{let J=Y.throwOnError??O.throwOnError,T=Y.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(Y),I={redirect:"follow",...V,body:J1(V)};z=new Request(B,I);for(let U of S.request.fns)if(U)z=await U(z,V);let P=V.fetch;W=await P(z);for(let U of S.response.fns)if(U)W=await U(W,z,V);let D={request:z,response:W};if(W.ok){let U=(V.parseAs==="auto"?y2(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let N;switch(U){case"arrayBuffer":case"blob":case"text":N=await W[U]();break;case"formData":N=new FormData;break;case"stream":N=W.body;break;case"json":default:N={};break}return V.responseStyle==="data"?N:{data:N,...D}}let H;switch(U){case"arrayBuffer":case"blob":case"formData":case"text":H=await W[U]();break;case"json":{let N=await W.text();H=N?JSON.parse(N):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(U==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let C=await W.text(),w;try{w=JSON.parse(C)}catch{}throw w??C}catch(V){let B=V;for(let I of S.error.fns)if(I)B=await I(B,W,z,Y);if(B=B||{},J)throw B;return T==="data"?void 0:{error:B,request:z,response:W}}},X=(Y)=>(J)=>Z({...J,method:Y}),G=(Y)=>async(J)=>{let{opts:T,url:z}=await K(J);return q2({...T,body:T.body,method:Y,onRequest:async(W,V)=>{let B=new Request(W,V);for(let I of S.request.fns)if(I)B=await I(B,T);return B},serializedBody:J1(T),url:z})};return{buildUrl:(Y)=>V1({...O,...Y}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:G("CONNECT"),delete:G("DELETE"),get:G("GET"),head:G("HEAD"),options:G("OPTIONS"),patch:G("PATCH"),post:G("POST"),put:G("PUT"),trace:G("TRACE")},trace:X("TRACE")}};var m2=B1(xj());class c2{client;constructor($){this.client=$?.client??m2}}class u2{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class Ix extends c2{static __registry=new u2;constructor($){super($);Ix.__registry.set(this,$?.key)}unifiedSearch($){return($.client??this.client).post({url:"/search",...$,headers:{"Content-Type":"application/json",...$.headers}})}simpleUnifiedSearch($){return($.client??this.client).post({url:"/search/simple",...$,headers:{"Content-Type":"application/json",...$.headers}})}}function d2({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:G,url:L,...Y}){let J,T=G??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=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(J!==void 0)P.set("Last-Event-ID",J);try{let D={redirect:"follow",...Y,body:Y.serializedBody,headers:P,signal:I},C=new Request(L,D);if($)C=await $(L,D);let U=await(Y.fetch??globalThis.fetch)(C);if(!U.ok)throw Error(`SSE failed: ${U.status} ${U.statusText}`);if(!U.body)throw Error("No body in SSE response");let H=U.body.pipeThrough(new TextDecoderStream).getReader(),N="",g=()=>{try{H.cancel()}catch{}};I.addEventListener("abort",g);try{while(!0){let{done:d,value:l}=await H.read();if(d)break;N+=l,N=N.replace(/\r\n?/g,`
+`);let k=N.split(`
-`);U=g.pop()??"";for(let r of g){let p=r.split(`
+`);N=k.pop()??"";for(let r of k){let p=r.split(`
`),F=[],y;for(let R of p)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))y=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let h=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(h))V=h}let _,v=!1;if(F.length){let R=F.join(`
-`);try{_=JSON.parse(R),v=!0}catch{_=R}}if(v){if(S)await S(_);if(x)_=await x(_)}if(j?.({data:_,event:y,id:J,retry:V}),F.length)yield _}}}finally{I.removeEventListener("abort",k),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let C=Math.min(V*2**(B-1),X??30000);await T(C)}}}()}}var y5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},v5=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},h5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},Ix=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((G)=>encodeURIComponent(G))).join(v5(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=y5(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return FO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},FO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},Tx=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let G=[];Object.entries(S).forEach(([Y,J])=>{G=[...G,Y,$?J:encodeURIComponent(J)]});let L=G.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=h5(x),X=Object.entries(S).map(([G,L])=>FO({allowReserved:$,name:x==="deepObject"?`${j}[${G}]`:G,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var m5=/\{[^{}]+\}/g,c5=({path:$,url:O})=>{let j=O,x=O.match(m5);if(x)for(let S of x){let K=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))K=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let G=$[Z];if(G===void 0||G===null)continue;if(Array.isArray(G)){j=j.replace(S,Ix({explode:K,name:Z,style:X,value:G}));continue}if(typeof G==="object"){j=j.replace(S,Tx({explode:K,name:Z,style:X,value:G,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${FO({name:Z,value:G})}`);continue}let L=encodeURIComponent(X==="label"?`.${G}`:G);j=j.replace(S,L)}return j},d2=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=c5({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function B1($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var l2=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var r2={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var p2=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let G=Ix({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(G)S.push(G)}else if(typeof Z==="object"){let G=Tx({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(G)S.push(G)}else{let G=FO({allowReserved:X.allowReserved,name:K,value:Z});if(G)S.push(G)}}return S.join("&")}},a2=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},u5=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function i2($){for(let O of $.security??[]){if(u5($,O.name))continue;let j=await l2(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var L1=($)=>d2({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:p2($.querySerializer),url:$.url}),N1=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=Rx($.headers,O.headers),j},d5=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},Rx=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?d5(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class Hx{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var n2=()=>({error:new Hx,request:new Hx,response:new Hx}),l5=p2({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),r5={"Content-Type":"application/json"},xj=($={})=>({...r2,headers:r5,parseAs:"auto",querySerializer:l5,...$});var Sj=($={})=>{let O=N1(xj(),$),j=()=>({...O}),x=(Y)=>{return O=N1(O,Y),j()},S=n2(),K=async(Y)=>{let J={...O,...Y,fetch:Y.fetch??O.fetch??globalThis.fetch,headers:Rx(O.headers,Y.headers),serializedBody:void 0};if(J.security)await i2(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let T=J,z=L1(T);return{opts:T,url:z}},Z=async(Y)=>{let J=Y.throwOnError??O.throwOnError,T=Y.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(Y),I={redirect:"follow",...V,body:B1(V)};z=new Request(B,I);for(let N of S.request.fns)if(N)z=await N(z,V);let P=V.fetch;W=await P(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?a2(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await W[N]();break;case"json":{let U=await W.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let C=await W.text(),E;try{E=JSON.parse(C)}catch{}throw E??C}catch(V){let B=V;for(let I of S.error.fns)if(I)B=await I(B,W,z,Y);if(B=B||{},J)throw B;return T==="data"?void 0:{error:B,request:z,response:W}}},X=(Y)=>(J)=>Z({...J,method:Y}),G=(Y)=>async(J)=>{let{opts:T,url:z}=await K(J);return u2({...T,body:T.body,method:Y,onRequest:async(W,V)=>{let B=new Request(W,V);for(let I of S.request.fns)if(I)B=await I(B,T);return B},serializedBody:B1(T),url:z})};return{buildUrl:(Y)=>L1({...O,...Y}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:G("CONNECT"),delete:G("DELETE"),get:G("GET"),head:G("HEAD"),options:G("OPTIONS"),patch:G("PATCH"),post:G("POST"),put:G("PUT"),trace:G("TRACE")},trace:X("TRACE")}};var s2=Sj(xj());class t2{client;constructor($){this.client=$?.client??s2}}class e2{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class Dx extends t2{static __registry=new e2;constructor($){super($);Dx.__registry.set(this,$?.key)}listAgents($){return($?.client??this.client).get({url:"/agents",...$})}createAgent($){return($.client??this.client).post({url:"/agents",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateAgent($){return($.client??this.client).put({url:"/agents/{agent_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteAnchor($){return($.client??this.client).delete({url:"/annotations/anchors",...$,headers:{"Content-Type":"application/json",...$.headers}})}editAnchor($){return($.client??this.client).patch({url:"/annotations/anchors",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDocumentAnchors($){return($.client??this.client).get({url:"/annotations/anchors/document/{document_id}",...$})}createAnchor($){return($.client??this.client).post({url:"/annotations/anchors/document/{document_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getSelfBot($){return($?.client??this.client).get({url:"/bots/me",...$})}getBotOwnerProfiles($){return($?.client??this.client).get({url:"/bots/profiles",...$})}listBotChannels($){return($.client??this.client).get({url:"/bots/{bot_id}/channels",...$})}removeBotFromChannelByBot($){return($.client??this.client).delete({url:"/bots/{bot_id}/channels/{channel_id}",...$})}listOccurrences($){return($.client??this.client).get({url:"/calendar-events",...$})}mentionPreviews($){return($.client??this.client).post({url:"/calendar-events/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}listTeamCalendar($){return($.client??this.client).get({url:"/calendar-events/team",...$})}listTeamOutOfOffice($){return($.client??this.client).get({url:"/calendar-events/team-out-of-office",...$})}eventIcs($){return($.client??this.client).get({url:"/calendar-events/{event_id}/ics",...$})}listJoinRequests($){return($.client??this.client).get({url:"/calendar-events/{event_id}/join-requests",...$})}requestToJoin($){return($.client??this.client).post({url:"/calendar-events/{event_id}/join-requests",...$})}getActiveCalls($){return($?.client??this.client).get({url:"/call/active",...$})}guestCallChatRead($){return($.client??this.client).get({url:"/call/guest-chat/{call_id}",...$})}guestCallChatPost($){return($.client??this.client).post({url:"/call/guest-chat/{call_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}meetingLookup($){return($.client??this.client).get({url:"/call/join/{token}",...$})}meetingGuestJoin($){return($.client??this.client).post({url:"/call/join/{token}",...$,headers:{"Content-Type":"application/json",...$.headers}})}meetingLeave($){return($.client??this.client).post({url:"/call/join/{token}/leave",...$})}meetingGuestParticipants($){return($.client??this.client).get({url:"/call/join/{token}/participants",...$})}meetingList($){return($?.client??this.client).get({url:"/call/meetings",...$})}meetingCreate($){return($.client??this.client).post({url:"/call/meetings",...$,headers:{"Content-Type":"application/json",...$.headers}})}meetingListActive($){return($?.client??this.client).get({url:"/call/meetings/active",...$})}meetingInvitePermissions($){return($.client??this.client).get({url:"/call/meetings/invite/{token}",...$})}meetingInvite($){return($.client??this.client).post({url:"/call/meetings/invite/{token}",...$,headers:{"Content-Type":"application/json",...$.headers}})}meetingInviteUsers($){return($.client??this.client).post({url:"/call/meetings/invite/{token}/users",...$,headers:{"Content-Type":"application/json",...$.headers}})}meetingJoin($){return($.client??this.client).post({url:"/call/meetings/join/{token}",...$})}meetingParticipants($){return($.client??this.client).get({url:"/call/meetings/join/{token}/participants",...$})}meetingPrepare($){return($?.client??this.client).post({url:"/call/meetings/prepare",...$})}meetingCancelPreparation($){return($.client??this.client).delete({url:"/call/meetings/prepare/{preparation_id}",...$})}meetingCancel($){return($.client??this.client).delete({url:"/call/meetings/{meeting_id}",...$})}meetingUpdate($){return($.client??this.client).patch({url:"/call/meetings/{meeting_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getBatchCallRecordPreview($){return($.client??this.client).post({url:"/call/record/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteCallRecord($){return($.client??this.client).delete({url:"/call/record/{call_id}",...$})}getCallRecord($){return($.client??this.client).get({url:"/call/record/{call_id}",...$})}editCallRecord($){return($.client??this.client).patch({url:"/call/record/{call_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}declineCall($){return($.client??this.client).post({url:"/call/record/{call_id}/decline",...$})}meetingShare($){return($.client??this.client).post({url:"/call/record/{call_id}/link",...$})}toggleShareWithTeam($){return($.client??this.client).post({url:"/call/record/{call_id}/share-with-team/toggle",...$})}editCallTranscript($){return($.client??this.client).patch({url:"/call/record/{call_id}/transcript",...$,headers:{"Content-Type":"application/json",...$.headers}})}getRingStatus($){return($.client??this.client).get({url:"/call/ring-status/{call_id}",...$})}declineRing($){return($.client??this.client).post({url:"/call/ring-status/{call_id}/decline",...$})}callWebhook($){return($?.client??this.client).post({url:"/call/webhook",...$})}leaveOrEndCall($){return($.client??this.client).delete({url:"/call/{channel_id}",...$})}getOrCreateCall($){return($.client??this.client).get({url:"/call/{channel_id}",...$})}checkActiveCall($){return($.client??this.client).get({url:"/call/{channel_id}/active",...$})}ingestTranscript($){return($.client??this.client).post({url:"/call/{room_name}/transcript",...$,headers:{"Content-Type":"application/json",...$.headers}})}listChannelLabels($){return($?.client??this.client).get({url:"/channel-labels",...$})}createChannelLabel($){return($.client??this.client).post({url:"/channel-labels",...$,headers:{"Content-Type":"application/json",...$.headers}})}setChannelLabel($){return($.client??this.client).put({url:"/channel-labels/channels/{channel_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}previewSmartTag($){return($.client??this.client).post({url:"/channel-labels/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteChannelLabel($){return($.client??this.client).delete({url:"/channel-labels/{label_id}",...$})}renameChannelLabel($){return($.client??this.client).patch({url:"/channel-labels/{label_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}createChannel($){return($.client??this.client).post({url:"/channels",...$,headers:{"Content-Type":"application/json",...$.headers}})}getActivity($){return($?.client??this.client).get({url:"/channels/activity",...$})}postActivity($){return($.client??this.client).post({url:"/channels/activity",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAttachmentReferences($){return($.client??this.client).get({url:"/channels/attachments/{entity_type}/{entity_id}/references",...$})}getOrCreateDm($){return($.client??this.client).post({url:"/channels/get_or_create_dm",...$,headers:{"Content-Type":"application/json",...$.headers}})}getOrCreatePrivate($){return($.client??this.client).post({url:"/channels/get_or_create_private",...$,headers:{"Content-Type":"application/json",...$.headers}})}joinChannelByCode($){return($.client??this.client).post({url:"/channels/join/{join_code}",...$})}createEntityMention($){return($.client??this.client).post({url:"/channels/mentions",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteEntityMention($){return($.client??this.client).delete({url:"/channels/mentions/{mention_id}",...$})}getBatchChannelPreview($){return($.client??this.client).post({url:"/channels/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteChannel($){return($.client??this.client).delete({url:"/channels/{channel_id}",...$})}getChannel($){return($.client??this.client).get({url:"/channels/{channel_id}",...$})}patchChannel($){return($.client??this.client).patch({url:"/channels/{channel_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getChannelAttachments($){return($.client??this.client).get({url:"/channels/{channel_id}/attachments",...$})}createChannelScopedBot($){return($.client??this.client).post({url:"/channels/{channel_id}/bots/scoped",...$,headers:{"Content-Type":"application/json",...$.headers}})}joinChannel($){return($.client??this.client).post({url:"/channels/{channel_id}/join",...$})}getChannelJoinLink($){return($.client??this.client).get({url:"/channels/{channel_id}/join-link",...$})}leaveChannel($){return($.client??this.client).post({url:"/channels/{channel_id}/leave",...$})}removeParticipants($){return($.client??this.client).delete({url:"/channels/{channel_id}/participants",...$,headers:{"Content-Type":"application/json",...$.headers}})}getChannelParticipants($){return($.client??this.client).get({url:"/channels/{channel_id}/participants",...$})}addParticipants($){return($.client??this.client).post({url:"/channels/{channel_id}/participants",...$,headers:{"Content-Type":"application/json",...$.headers}})}setChannelPicture($){return($.client??this.client).put({url:"/channels/{channel_id}/profile_picture",...$,headers:{"Content-Type":"application/json",...$.headers}})}postChannelBotWebhook($){return($.client??this.client).post({url:"/channels/{channel_id}/webhook",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteCollabSurface($){return($.client??this.client).delete({url:"/collab_surfaces/{id}",...$})}getCollabSurface($){return($.client??this.client).get({url:"/collab_surfaces/{id}",...$})}ensureCollabSurface($){return($.client??this.client).put({url:"/collab_surfaces/{id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}createCollabSurfaceToken($){return($.client??this.client).post({url:"/collab_surfaces/{id}/token",...$})}getChannels($){return($?.client??this.client).get({url:"/comms/channels",...$})}createCrmCompany($){return($.client??this.client).post({url:"/crm/companies",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCompany($){return($.client??this.client).get({url:"/crm/companies/{company_id}",...$})}listCompanyContacts($){return($.client??this.client).get({url:"/crm/companies/{company_id}/contacts",...$})}createCrmContact($){return($.client??this.client).post({url:"/crm/companies/{company_id}/contacts",...$,headers:{"Content-Type":"application/json",...$.headers}})}setEmailSync($){return($.client??this.client).put({url:"/crm/companies/{company_id}/email-sync",...$,headers:{"Content-Type":"application/json",...$.headers}})}setCompanyHidden($){return($.client??this.client).put({url:"/crm/companies/{company_id}/hidden",...$,headers:{"Content-Type":"application/json",...$.headers}})}setCrmCompanyName($){return($.client??this.client).put({url:"/crm/companies/{company_id}/name",...$,headers:{"Content-Type":"application/json",...$.headers}})}searchContacts($){return($?.client??this.client).get({url:"/crm/contacts",...$})}getContactByEmail($){return($.client??this.client).get({url:"/crm/contacts/by-email",...$})}getContact($){return($.client??this.client).get({url:"/crm/contacts/{contact_id}",...$})}setContactHidden($){return($.client??this.client).put({url:"/crm/contacts/{contact_id}/hidden",...$,headers:{"Content-Type":"application/json",...$.headers}})}setCrmContactName($){return($.client??this.client).put({url:"/crm/contacts/{contact_id}/name",...$,headers:{"Content-Type":"application/json",...$.headers}})}listCrmPipelines($){return($?.client??this.client).get({url:"/crm/pipelines",...$})}createCrmPipeline($){return($.client??this.client).post({url:"/crm/pipelines",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCrmPipeline($){return($.client??this.client).get({url:"/crm/pipelines/{id}",...$})}renameCrmPipeline($){return($.client??this.client).put({url:"/crm/pipelines/{id}/name",...$,headers:{"Content-Type":"application/json",...$.headers}})}applyCrmPipelineOps($){return($.client??this.client).post({url:"/crm/pipelines/{id}/ops",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCrmPipelinePermissions($){return($.client??this.client).get({url:"/crm/pipelines/{id}/permissions",...$})}updateCrmPipelinePermissions($){return($.client??this.client).patch({url:"/crm/pipelines/{id}/permissions",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCrmPipelineRows($){return($.client??this.client).get({url:"/crm/pipelines/{id}/rows",...$})}queryCrmPipelineRows($){return($.client??this.client).post({url:"/crm/pipelines/{id}/rows",...$,headers:{"Content-Type":"application/json",...$.headers}})}shareCrmPipeline($){return($.client??this.client).put({url:"/crm/pipelines/{id}/sharing",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCrmPipelineTable($){return($.client??this.client).get({url:"/crm/pipelines/{id}/table",...$})}trashCrmPipeline($){return($.client??this.client).put({url:"/crm/pipelines/{id}/trash",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCrmTeamSettings($){return($?.client??this.client).get({url:"/crm/settings",...$})}putCrmTeamSettings($){return($.client??this.client).put({url:"/crm/settings",...$,headers:{"Content-Type":"application/json",...$.headers}})}resetCrmTeamStages($){return($?.client??this.client).delete({url:"/crm/stages",...$})}putCrmTeamStages($){return($.client??this.client).put({url:"/crm/stages",...$,headers:{"Content-Type":"application/json",...$.headers}})}listDatabases($){return($?.client??this.client).get({url:"/databases",...$})}createDatabase($){return($.client??this.client).post({url:"/databases",...$,headers:{"Content-Type":"application/json",...$.headers}})}saveDatabaseQuery($){return($.client??this.client).post({url:"/databases/queries",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDatabaseQuery($){return($.client??this.client).get({url:"/databases/queries/{query_id}",...$})}queryDatabases($){return($.client??this.client).post({url:"/databases/query",...$,headers:{"Content-Type":"application/json",...$.headers}})}ensureStarterHandler($){return($?.client??this.client).post({url:"/databases/starter",...$})}deliverDatabaseWebhook($){return($.client??this.client).post({url:"/databases/webhooks/{token}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDatabase($){return($.client??this.client).get({url:"/databases/{id}",...$})}shareDatabaseAwareness($){return($.client??this.client).put({url:"/databases/{id}/awareness",...$,headers:{"Content-Type":"application/json",...$.headers}})}undoDatabaseChange($){return($.client??this.client).post({url:"/databases/{id}/changes/{change}/undo",...$})}importDatabaseTable($){return($.client??this.client).post({url:"/databases/{id}/import",...$,headers:{"Content-Type":"application/json",...$.headers}})}applyDatabaseOps($){return($.client??this.client).post({url:"/databases/{id}/ops",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDatabasePermissions($){return($.client??this.client).get({url:"/databases/{id}/permissions",...$})}updateDatabasePermissions($){return($.client??this.client).patch({url:"/databases/{id}/permissions",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDatabaseTableChanges($){return($.client??this.client).get({url:"/databases/{id}/tables/{table_id}/changes",...$})}listDatabaseColumnCasts($){return($.client??this.client).get({url:"/databases/{id}/tables/{table_id}/columns/{column_id}/casts",...$})}convertDatabaseColumn($){return($.client??this.client).post({url:"/databases/{id}/tables/{table_id}/columns/{column_id}/conversion",...$,headers:{"Content-Type":"application/json",...$.headers}})}inferDatabaseColumnType($){return($.client??this.client).post({url:"/databases/{id}/tables/{table_id}/columns/{column_id}/infer-type",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDatabaseRowHistory($){return($.client??this.client).get({url:"/databases/{id}/tables/{table_id}/rows/{row_id}/history",...$})}getDatabaseViewPositions($){return($.client??this.client).get({url:"/databases/{id}/views/{view_id}/positions",...$})}listDatabaseWebhooks($){return($.client??this.client).get({url:"/databases/{id}/webhooks",...$})}createDatabaseWebhook($){return($.client??this.client).post({url:"/databases/{id}/webhooks",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteDatabaseWebhook($){return($.client??this.client).delete({url:"/databases/{id}/webhooks/{webhook_id}",...$})}transcribeDictation($){return($.client??this.client).post({bodySerializer:null,url:"/dictation/transcribe",...$,headers:{"Content-Type":"audio/webm",...$.headers}})}getUserDocumentsHandler($){return($.client??this.client).get({url:"/documents",...$})}createDocument($){return($.client??this.client).post({url:"/documents",...$,headers:{"Content-Type":"application/json",...$.headers}})}createMarkdownHandler($){return($.client??this.client).post({url:"/documents/create_markdown",...$,headers:{"Content-Type":"application/json",...$.headers}})}createSkillHandler($){return($.client??this.client).post({url:"/documents/create_skill",...$,headers:{"Content-Type":"application/json",...$.headers}})}createSnippetHandler($){return($.client??this.client).post({url:"/documents/create_snippet",...$,headers:{"Content-Type":"application/json",...$.headers}})}createTaskHandler($){return($.client??this.client).post({url:"/documents/create_task",...$,headers:{"Content-Type":"application/json",...$.headers}})}getGithubPullRequestTasks($){return($.client??this.client).post({url:"/documents/github_prs/tasks",...$,headers:{"Content-Type":"application/json",...$.headers}})}initializeUserDocuments($){return($?.client??this.client).post({url:"/documents/initialize_user_documents",...$})}getDocumentListHandler($){return($?.client??this.client).get({url:"/documents/list",...$})}validateDocumentPermissionsToken($){return($.client??this.client).post({url:"/documents/permissions_token/validate",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDocumentPermissionsToken($){return($.client??this.client).post({url:"/documents/permissions_token/{document_id}",...$})}presaveDocumentHandler($){return($.client??this.client).put({url:"/documents/presave/{document_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getBatchPreviewHandler($){return($.client??this.client).post({url:"/documents/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDocumentByTeamSlug($){return($.client??this.client).get({url:"/documents/slug/{slug}",...$})}handler($){return($?.client??this.client).get({url:"/documents/starter_docs",...$})}getSystemSkillsHandler($){return($?.client??this.client).get({url:"/documents/system_skills",...$})}deleteDocument($){return($.client??this.client).delete({url:"/documents/{document_id}",...$})}getDocument($){return($.client??this.client).get({url:"/documents/{document_id}",...$})}editDocument($){return($.client??this.client).patch({url:"/documents/{document_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}saveDocumentHandler($){return($.client??this.client).put({url:"/documents/{document_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDocumentBranchName($){return($.client??this.client).get({url:"/documents/{document_id}/branch_name",...$})}copyDocument($){return($.client??this.client).post({url:"/documents/{document_id}/copy",...$,headers:{"Content-Type":"application/json",...$.headers}})}exportDocument($){return($.client??this.client).get({url:"/documents/{document_id}/export",...$})}getDocumentGithubPullRequests($){return($.client??this.client).get({url:"/documents/{document_id}/github_prs",...$})}getLocationHandler($){return($.client??this.client).get({url:"/documents/{document_id}/location",...$})}getDocumentLocationV3($){return($.client??this.client).get({url:"/documents/{document_id}/location_v3",...$})}permanentlyDeleteDocument($){return($.client??this.client).delete({url:"/documents/{document_id}/permanent",...$})}getDocumentProcessingResult($){return($.client??this.client).get({url:"/documents/{document_id}/processing",...$})}jobProcessingResultHandler($){return($.client??this.client).get({url:"/documents/{document_id}/processing/{job_id}",...$})}revertDeleteDocument($){return($.client??this.client).put({url:"/documents/{document_id}/revert_delete",...$})}getDocumentShortId($){return($.client??this.client).get({url:"/documents/{document_id}/short_id",...$})}simpleSave($){return($.client??this.client).put({url:"/documents/{document_id}/simple_save",...$})}getDocumentTeamShare($){return($.client??this.client).get({url:"/documents/{document_id}/team_share",...$})}setDocumentTeamShare($){return($.client??this.client).put({url:"/documents/{document_id}/team_share",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDocumentTextContent($){return($.client??this.client).get({url:"/documents/{document_id}/text-content",...$})}getDocumentViewsHandler($){return($.client??this.client).get({url:"/documents/{document_id}/views",...$})}getDocumentVersion($){return($.client??this.client).get({url:"/documents/{document_id}/{document_version_id}",...$})}accessRequestsState($){return($.client??this.client).get({url:"/entities/{entity_type}/{entity_id}/access-requests",...$})}accessRequestsCancel($){return($.client??this.client).delete({url:"/entities/{entity_type}/{entity_id}/access-requests/mine",...$})}accessRequestsSubmit($){return($.client??this.client).put({url:"/entities/{entity_type}/{entity_id}/access-requests/mine",...$,headers:{"Content-Type":"application/json",...$.headers}})}accessRequestsResolve($){return($.client??this.client).post({url:"/entities/{entity_type}/{entity_id}/access-requests/{request_id}/resolve",...$,headers:{"Content-Type":"application/json",...$.headers}})}accessRequestsDirect($){return($.client??this.client).get({url:"/entities/{entity_type}/{entity_id}/direct-access",...$})}accessRequestsRemoveDirect($){return($.client??this.client).delete({url:"/entities/{entity_type}/{entity_id}/direct-access/{user_id}",...$})}accessRequestsSetDirect($){return($.client??this.client).put({url:"/entities/{entity_type}/{entity_id}/direct-access/{user_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getEntityPermission($){return($.client??this.client).get({url:"/entity/{entity_type}/{entity_id}/permissions",...$})}listFavorites($){return($?.client??this.client).get({url:"/favorites",...$})}addFavorite($){return($.client??this.client).post({url:"/favorites",...$,headers:{"Content-Type":"application/json",...$.headers}})}reorderFavorites($){return($.client??this.client).patch({url:"/favorites/reorder",...$,headers:{"Content-Type":"application/json",...$.headers}})}removeFavoriteByEntity($){return($.client??this.client).delete({url:"/favorites/{entity_type}/{entity_id}",...$})}getForeignEntityBySource($){return($.client??this.client).get({url:"/foreign_entity/by_source/{source}/{foreign_entity_id}",...$})}getForeignEntity($){return($.client??this.client).get({url:"/foreign_entity/{id}",...$})}listForms($){return($.client??this.client).get({url:"/forms",...$})}createForm($){return($.client??this.client).post({url:"/forms",...$,headers:{"Content-Type":"application/json",...$.headers}})}listAccessibleForms($){return($?.client??this.client).get({url:"/forms/accessible",...$})}getForm($){return($.client??this.client).get({url:"/forms/{id}",...$})}updateForm($){return($.client??this.client).patch({url:"/forms/{id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}collaborateForm($){return($.client??this.client).post({url:"/forms/{id}/collaboration",...$})}putFormLayout($){return($.client??this.client).put({url:"/forms/{id}/layout",...$,headers:{"Content-Type":"application/json",...$.headers}})}getFormPermissions($){return($.client??this.client).get({url:"/forms/{id}/permissions",...$})}updateFormPermissions($){return($.client??this.client).patch({url:"/forms/{id}/permissions",...$,headers:{"Content-Type":"application/json",...$.headers}})}submitFormResponse($){return($.client??this.client).post({url:"/forms/{id}/responses",...$,headers:{"Content-Type":"application/json",...$.headers}})}getMyFormResponse($){return($.client??this.client).get({url:"/forms/{id}/responses/mine",...$})}editMyFormResponse($){return($.client??this.client).put({url:"/forms/{id}/responses/mine",...$,headers:{"Content-Type":"application/json",...$.headers}})}getFormResponseSummary($){return($.client??this.client).get({url:"/forms/{id}/responses/summary",...$})}getFormTally($){return($.client??this.client).get({url:"/forms/{id}/tally",...$})}installSync($){return($?.client??this.client).get({url:"/github/install-sync",...$})}getGithubPullRequestFacets($){return($?.client??this.client).get({url:"/github_pull_requests/facets",...$})}getGithubPullRequest($){return($.client??this.client).get({url:"/github_pull_requests/{id}",...$})}getGithubPullRequestChanges($){return($.client??this.client).get({url:"/github_pull_requests/{id}/changes",...$})}getGithubPullRequestChangesPatch($){return($.client??this.client).get({url:"/github_pull_requests/{id}/changes/patch",...$})}createHarnessPairing($){return($.client??this.client).post({url:"/harness-pairings",...$,headers:{"Content-Type":"application/json",...$.headers}})}getHarnessPairing($){return($.client??this.client).get({url:"/harness-pairings/{code}",...$})}approveHarnessPairing($){return($.client??this.client).post({url:"/harness-pairings/{code}/approve",...$,headers:{"Content-Type":"application/json",...$.headers}})}claimHarnessPairing($){return($.client??this.client).post({url:"/harness-pairings/{pairing_id}/claim",...$,headers:{"Content-Type":"application/json",...$.headers}})}listHarnesses($){return($?.client??this.client).get({url:"/harnesses",...$})}deleteSelfHarness($){return($?.client??this.client).delete({url:"/harnesses/me",...$})}getSelfHarness($){return($?.client??this.client).get({url:"/harnesses/me",...$})}listHarnessAgents($){return($?.client??this.client).get({url:"/harnesses/me/agents",...$})}listHarnessSessions($){return($?.client??this.client).get({url:"/harnesses/me/sessions",...$})}deleteHarness($){return($.client??this.client).delete({url:"/harnesses/{harness_id}",...$})}healthHandler($){return($?.client??this.client).get({url:"/health",...$})}getHistoryHandler($){return($?.client??this.client).get({url:"/history",...$})}deleteHistoryHandler($){return($.client??this.client).delete({url:"/history/{item_type}/{item_id}",...$})}upsertHistoryHandler($){return($.client??this.client).post({url:"/history/{item_type}/{item_id}",...$})}listInitiatives($){return($?.client??this.client).get({url:"/initiatives",...$})}createInitiative($){return($.client??this.client).post({url:"/initiatives",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteInitiative($){return($.client??this.client).delete({url:"/initiatives/{initiative_id}",...$})}getInitiative($){return($.client??this.client).get({url:"/initiatives/{initiative_id}",...$})}updateInitiative($){return($.client??this.client).patch({url:"/initiatives/{initiative_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getInstructionsHandler($){return($?.client??this.client).get({url:"/instructions",...$})}createInstructionsHandler($){return($?.client??this.client).post({url:"/instructions",...$})}getItemsSoup($){return($?.client??this.client).get({url:"/items/soup",...$})}postItemsSoup($){return($.client??this.client).post({url:"/items/soup",...$,headers:{"Content-Type":"application/json",...$.headers}})}postItemsSoupAst($){return($.client??this.client).post({url:"/items/soup/ast",...$,headers:{"Content-Type":"application/json",...$.headers}})}postItemsSoupAstGrouped($){return($.client??this.client).post({url:"/items/soup/ast/grouped",...$,headers:{"Content-Type":"application/json",...$.headers}})}messageTimeline($){return($.client??this.client).get({url:"/messages/{parent_type}/{parent_id}",...$})}entityMessageCreate($){return($.client??this.client).post({url:"/messages/{parent_type}/{parent_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}entityMessageDeleteMessage($){return($.client??this.client).delete({url:"/messages/{parent_type}/{parent_id}/items/{id}",...$})}entityMessageGetMessage($){return($.client??this.client).get({url:"/messages/{parent_type}/{parent_id}/items/{id}",...$})}entityMessageEdit($){return($.client??this.client).patch({url:"/messages/{parent_type}/{parent_id}/items/{id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}entityMessageReact($){return($.client??this.client).post({url:"/messages/{parent_type}/{parent_id}/items/{id}/reactions",...$,headers:{"Content-Type":"application/json",...$.headers}})}entityMessageLegacy($){return($.client??this.client).get({url:"/messages/{parent_type}/{parent_id}/legacy/{legacy_id}",...$})}entityMessageDeleteThread($){return($.client??this.client).delete({url:"/messages/{parent_type}/{parent_id}/threads/{id}",...$})}entityMessageGetThread($){return($.client??this.client).get({url:"/messages/{parent_type}/{parent_id}/threads/{id}",...$})}entityMessagePatchThread($){return($.client??this.client).patch({url:"/messages/{parent_type}/{parent_id}/threads/{id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}messageTimelineEntries($){return($.client??this.client).get({url:"/messages/{parent_type}/{parent_id}/timeline",...$})}entityMessageTyping($){return($.client??this.client).post({url:"/messages/{parent_type}/{parent_id}/typing",...$,headers:{"Content-Type":"application/json",...$.headers}})}getPinsHandler($){return($?.client??this.client).get({url:"/pins",...$})}reorderPinsHandler($){return($.client??this.client).patch({url:"/pins",...$,headers:{"Content-Type":"application/json",...$.headers}})}removePinHandler($){return($.client??this.client).delete({url:"/pins/{pinned_item_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}addPinHandler($){return($.client??this.client).post({url:"/pins/{pinned_item_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getProjectsHandler($){return($?.client??this.client).get({url:"/projects",...$})}createProjectHandler($){return($.client??this.client).post({url:"/projects",...$,headers:{"Content-Type":"application/json",...$.headers}})}getPendingProjectsHandler($){return($?.client??this.client).get({url:"/projects/pending",...$})}getBatchProjectPreview($){return($.client??this.client).post({url:"/projects/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}uploadFolderHandler($){return($.client??this.client).post({url:"/projects/upload",...$,headers:{"Content-Type":"application/json",...$.headers}})}uploadExtractFolderHandler($){return($.client??this.client).post({url:"/projects/upload_extract",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteProjectHandler($){return($.client??this.client).delete({url:"/projects/{id}",...$})}getProjectHandler($){return($.client??this.client).get({url:"/projects/{id}",...$})}getProjectUserAccessLevel($){return($.client??this.client).get({url:"/projects/{id}/access_level",...$})}getProjectContentHandler($){return($.client??this.client).get({url:"/projects/{id}/content",...$})}permanentlyDeleteProject($){return($.client??this.client).delete({url:"/projects/{id}/permanent",...$})}getProjectPermissionsV2($){return($.client??this.client).get({url:"/projects/{id}/permissions",...$})}revertDeleteProject($){return($.client??this.client).put({url:"/projects/{id}/revert_delete",...$})}recentlyDeleted($){return($?.client??this.client).get({url:"/recents/deleted",...$})}listEmailReminders($){return($?.client??this.client).get({url:"/reminders/email/collection",...$})}getEmailFollowup($){return($.client??this.client).get({url:"/reminders/email/{thread_id}",...$})}setEmailFollowup($){return($.client??this.client).put({url:"/reminders/email/{thread_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getViewsHandler($){return($?.client??this.client).get({url:"/saved_views",...$})}createViewHandler($){return($.client??this.client).post({url:"/saved_views",...$,headers:{"Content-Type":"application/json",...$.headers}})}excludeDefaultViewHandler($){return($.client??this.client).post({url:"/saved_views/exclude_default",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteViewHandler($){return($.client??this.client).delete({url:"/saved_views/{saved_view_id}",...$})}patchViewHandler($){return($.client??this.client).patch({url:"/saved_views/{saved_view_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}listSlackImports($){return($?.client??this.client).get({url:"/slack/imports",...$})}createSlackImport($){return($.client??this.client).post({url:"/slack/imports",...$,headers:{"Content-Type":"application/json",...$.headers}})}getSlackImport($){return($.client??this.client).get({url:"/slack/imports/{job_id}",...$})}cancelSlackImport($){return($.client??this.client).post({url:"/slack/imports/{job_id}/cancel",...$})}finalizeSlackImport($){return($.client??this.client).post({url:"/slack/imports/{job_id}/finalize",...$})}registerSlackImportUploads($){return($.client??this.client).post({url:"/slack/imports/{job_id}/uploads",...$,headers:{"Content-Type":"application/json",...$.headers}})}completeSlackImportUploads($){return($.client??this.client).post({url:"/slack/imports/{job_id}/uploads/complete",...$,headers:{"Content-Type":"application/json",...$.headers}})}bulkWakeupSyncServiceDocuments($){return($.client??this.client).post({url:"/sync_service/wakeup",...$,headers:{"Content-Type":"application/json",...$.headers}})}editThreadV2($){return($.client??this.client).patch({url:"/threads/{thread_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}listUserApiKeys($){return($?.client??this.client).get({url:"/user-api-keys",...$})}createUserApiKey($){return($.client??this.client).post({url:"/user-api-keys",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteUserApiKey($){return($.client??this.client).delete({url:"/user-api-keys/{id}",...$})}deleteUserDocumentViewLocation($){return($.client??this.client).delete({url:"/user_document_view_location/{document_id}",...$})}getUserDocumentViewLocation($){return($.client??this.client).get({url:"/user_document_view_location/{document_id}",...$})}upsertUserDocumentViewLocation($){return($.client??this.client).post({url:"/user_document_view_location/{document_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDocumentPermissionsV2($){return($.client??this.client).get({url:"/v2/documents/{document_id}/permissions",...$})}editProjectV2($){return($.client??this.client).patch({url:"/v2/projects/{id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}streamEvents($){return($.client??this.client).sse.get({url:"/webhook/events/stream",...$})}listWebhooks($){return($?.client??this.client).get({url:"/webhook/webhooks",...$})}createWebhook($){return($.client??this.client).post({url:"/webhook/webhooks",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteWebhook($){return($.client??this.client).delete({url:"/webhook/webhooks/{webhook_id}",...$})}getWebhook($){return($.client??this.client).get({url:"/webhook/webhooks/{webhook_id}",...$})}patchWebhook($){return($.client??this.client).patch({url:"/webhook/webhooks/{webhook_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}validateWebhook($){return($.client??this.client).post({url:"/webhook/webhooks/{webhook_id}/validate",...$})}}function o2({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:G,url:L,...Y}){let J,T=G??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=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(J!==void 0)P.set("Last-Event-ID",J);try{let D={redirect:"follow",...Y,body:Y.serializedBody,headers:P,signal:I},C=new Request(L,D);if($)C=await $(L,D);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="",k=()=>{try{H.cancel()}catch{}};I.addEventListener("abort",k);try{while(!0){let{done:d,value:l}=await H.read();if(d)break;U+=l,U=U.replace(/\r\n?/g,`
-`);let g=U.split(`
+`);try{_=JSON.parse(R),v=!0}catch{_=R}}if(v){if(S)await S(_);if(x)_=await x(_)}if(j?.({data:_,event:y,id:J,retry:V}),F.length)yield _}}}finally{I.removeEventListener("abort",g),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let C=Math.min(V*2**(B-1),X??30000);await T(C)}}}()}}var v5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},h5=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},m5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},Tx=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((G)=>encodeURIComponent(G))).join(h5(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=v5(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return EO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},EO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},Hx=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let G=[];Object.entries(S).forEach(([Y,J])=>{G=[...G,Y,$?J:encodeURIComponent(J)]});let L=G.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=m5(x),X=Object.entries(S).map(([G,L])=>EO({allowReserved:$,name:x==="deepObject"?`${j}[${G}]`:G,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var c5=/\{[^{}]+\}/g,u5=({path:$,url:O})=>{let j=O,x=O.match(c5);if(x)for(let S of x){let K=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))K=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let G=$[Z];if(G===void 0||G===null)continue;if(Array.isArray(G)){j=j.replace(S,Tx({explode:K,name:Z,style:X,value:G}));continue}if(typeof G==="object"){j=j.replace(S,Hx({explode:K,name:Z,style:X,value:G,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${EO({name:Z,value:G})}`);continue}let L=encodeURIComponent(X==="label"?`.${G}`:G);j=j.replace(S,L)}return j},l2=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=u5({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function L1($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var r2=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var p2={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var a2=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let G=Tx({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(G)S.push(G)}else if(typeof Z==="object"){let G=Hx({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(G)S.push(G)}else{let G=EO({allowReserved:X.allowReserved,name:K,value:Z});if(G)S.push(G)}}return S.join("&")}},i2=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},d5=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function n2($){for(let O of $.security??[]){if(d5($,O.name))continue;let j=await r2(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var U1=($)=>l2({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:a2($.querySerializer),url:$.url}),N1=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=Dx($.headers,O.headers),j},l5=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},Dx=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?l5(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class Rx{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var s2=()=>({error:new Rx,request:new Rx,response:new Rx}),r5=a2({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),p5={"Content-Type":"application/json"},Sj=($={})=>({...p2,headers:p5,parseAs:"auto",querySerializer:r5,...$});var Zj=($={})=>{let O=N1(Sj(),$),j=()=>({...O}),x=(Y)=>{return O=N1(O,Y),j()},S=s2(),K=async(Y)=>{let J={...O,...Y,fetch:Y.fetch??O.fetch??globalThis.fetch,headers:Dx(O.headers,Y.headers),serializedBody:void 0};if(J.security)await n2(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let T=J,z=U1(T);return{opts:T,url:z}},Z=async(Y)=>{let J=Y.throwOnError??O.throwOnError,T=Y.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(Y),I={redirect:"follow",...V,body:L1(V)};z=new Request(B,I);for(let U of S.request.fns)if(U)z=await U(z,V);let P=V.fetch;W=await P(z);for(let U of S.response.fns)if(U)W=await U(W,z,V);let D={request:z,response:W};if(W.ok){let U=(V.parseAs==="auto"?i2(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let N;switch(U){case"arrayBuffer":case"blob":case"text":N=await W[U]();break;case"formData":N=new FormData;break;case"stream":N=W.body;break;case"json":default:N={};break}return V.responseStyle==="data"?N:{data:N,...D}}let H;switch(U){case"arrayBuffer":case"blob":case"formData":case"text":H=await W[U]();break;case"json":{let N=await W.text();H=N?JSON.parse(N):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(U==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let C=await W.text(),w;try{w=JSON.parse(C)}catch{}throw w??C}catch(V){let B=V;for(let I of S.error.fns)if(I)B=await I(B,W,z,Y);if(B=B||{},J)throw B;return T==="data"?void 0:{error:B,request:z,response:W}}},X=(Y)=>(J)=>Z({...J,method:Y}),G=(Y)=>async(J)=>{let{opts:T,url:z}=await K(J);return d2({...T,body:T.body,method:Y,onRequest:async(W,V)=>{let B=new Request(W,V);for(let I of S.request.fns)if(I)B=await I(B,T);return B},serializedBody:L1(T),url:z})};return{buildUrl:(Y)=>U1({...O,...Y}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:G("CONNECT"),delete:G("DELETE"),get:G("GET"),head:G("HEAD"),options:G("OPTIONS"),patch:G("PATCH"),post:G("POST"),put:G("PUT"),trace:G("TRACE")},trace:X("TRACE")}};var t2=Zj(Sj());class e2{client;constructor($){this.client=$?.client??t2}}class o2{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class Cx extends e2{static __registry=new o2;constructor($){super($);Cx.__registry.set(this,$?.key)}listAgents($){return($?.client??this.client).get({url:"/agents",...$})}createAgent($){return($.client??this.client).post({url:"/agents",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateAgent($){return($.client??this.client).put({url:"/agents/{agent_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteAnchor($){return($.client??this.client).delete({url:"/annotations/anchors",...$,headers:{"Content-Type":"application/json",...$.headers}})}editAnchor($){return($.client??this.client).patch({url:"/annotations/anchors",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDocumentAnchors($){return($.client??this.client).get({url:"/annotations/anchors/document/{document_id}",...$})}createAnchor($){return($.client??this.client).post({url:"/annotations/anchors/document/{document_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getSelfBot($){return($?.client??this.client).get({url:"/bots/me",...$})}getBotOwnerProfiles($){return($?.client??this.client).get({url:"/bots/profiles",...$})}listBotChannels($){return($.client??this.client).get({url:"/bots/{bot_id}/channels",...$})}removeBotFromChannelByBot($){return($.client??this.client).delete({url:"/bots/{bot_id}/channels/{channel_id}",...$})}listOccurrences($){return($.client??this.client).get({url:"/calendar-events",...$})}mentionPreviews($){return($.client??this.client).post({url:"/calendar-events/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}listTeamCalendar($){return($.client??this.client).get({url:"/calendar-events/team",...$})}listTeamOutOfOffice($){return($.client??this.client).get({url:"/calendar-events/team-out-of-office",...$})}eventIcs($){return($.client??this.client).get({url:"/calendar-events/{event_id}/ics",...$})}listJoinRequests($){return($.client??this.client).get({url:"/calendar-events/{event_id}/join-requests",...$})}requestToJoin($){return($.client??this.client).post({url:"/calendar-events/{event_id}/join-requests",...$})}getActiveCalls($){return($?.client??this.client).get({url:"/call/active",...$})}guestCallChatRead($){return($.client??this.client).get({url:"/call/guest-chat/{call_id}",...$})}guestCallChatPost($){return($.client??this.client).post({url:"/call/guest-chat/{call_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}meetingLookup($){return($.client??this.client).get({url:"/call/join/{token}",...$})}meetingGuestJoin($){return($.client??this.client).post({url:"/call/join/{token}",...$,headers:{"Content-Type":"application/json",...$.headers}})}meetingLeave($){return($.client??this.client).post({url:"/call/join/{token}/leave",...$})}meetingGuestParticipants($){return($.client??this.client).get({url:"/call/join/{token}/participants",...$})}meetingList($){return($?.client??this.client).get({url:"/call/meetings",...$})}meetingCreate($){return($.client??this.client).post({url:"/call/meetings",...$,headers:{"Content-Type":"application/json",...$.headers}})}meetingListActive($){return($?.client??this.client).get({url:"/call/meetings/active",...$})}meetingInvitePermissions($){return($.client??this.client).get({url:"/call/meetings/invite/{token}",...$})}meetingInvite($){return($.client??this.client).post({url:"/call/meetings/invite/{token}",...$,headers:{"Content-Type":"application/json",...$.headers}})}meetingInviteUsers($){return($.client??this.client).post({url:"/call/meetings/invite/{token}/users",...$,headers:{"Content-Type":"application/json",...$.headers}})}meetingJoin($){return($.client??this.client).post({url:"/call/meetings/join/{token}",...$})}meetingParticipants($){return($.client??this.client).get({url:"/call/meetings/join/{token}/participants",...$})}meetingPrepare($){return($?.client??this.client).post({url:"/call/meetings/prepare",...$})}meetingCancelPreparation($){return($.client??this.client).delete({url:"/call/meetings/prepare/{preparation_id}",...$})}meetingCancel($){return($.client??this.client).delete({url:"/call/meetings/{meeting_id}",...$})}meetingUpdate($){return($.client??this.client).patch({url:"/call/meetings/{meeting_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getBatchCallRecordPreview($){return($.client??this.client).post({url:"/call/record/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteCallRecord($){return($.client??this.client).delete({url:"/call/record/{call_id}",...$})}getCallRecord($){return($.client??this.client).get({url:"/call/record/{call_id}",...$})}editCallRecord($){return($.client??this.client).patch({url:"/call/record/{call_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}declineCall($){return($.client??this.client).post({url:"/call/record/{call_id}/decline",...$})}meetingShare($){return($.client??this.client).post({url:"/call/record/{call_id}/link",...$})}toggleShareWithTeam($){return($.client??this.client).post({url:"/call/record/{call_id}/share-with-team/toggle",...$})}editCallTranscript($){return($.client??this.client).patch({url:"/call/record/{call_id}/transcript",...$,headers:{"Content-Type":"application/json",...$.headers}})}getRingStatus($){return($.client??this.client).get({url:"/call/ring-status/{call_id}",...$})}declineRing($){return($.client??this.client).post({url:"/call/ring-status/{call_id}/decline",...$})}callWebhook($){return($?.client??this.client).post({url:"/call/webhook",...$})}leaveOrEndCall($){return($.client??this.client).delete({url:"/call/{channel_id}",...$})}getOrCreateCall($){return($.client??this.client).get({url:"/call/{channel_id}",...$})}checkActiveCall($){return($.client??this.client).get({url:"/call/{channel_id}/active",...$})}ingestTranscript($){return($.client??this.client).post({url:"/call/{room_name}/transcript",...$,headers:{"Content-Type":"application/json",...$.headers}})}listChannelLabels($){return($?.client??this.client).get({url:"/channel-labels",...$})}createChannelLabel($){return($.client??this.client).post({url:"/channel-labels",...$,headers:{"Content-Type":"application/json",...$.headers}})}setChannelLabel($){return($.client??this.client).put({url:"/channel-labels/channels/{channel_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}previewSmartTag($){return($.client??this.client).post({url:"/channel-labels/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteChannelLabel($){return($.client??this.client).delete({url:"/channel-labels/{label_id}",...$})}renameChannelLabel($){return($.client??this.client).patch({url:"/channel-labels/{label_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}createChannel($){return($.client??this.client).post({url:"/channels",...$,headers:{"Content-Type":"application/json",...$.headers}})}getActivity($){return($?.client??this.client).get({url:"/channels/activity",...$})}postActivity($){return($.client??this.client).post({url:"/channels/activity",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAttachmentReferences($){return($.client??this.client).get({url:"/channels/attachments/{entity_type}/{entity_id}/references",...$})}getOrCreateDm($){return($.client??this.client).post({url:"/channels/get_or_create_dm",...$,headers:{"Content-Type":"application/json",...$.headers}})}getOrCreatePrivate($){return($.client??this.client).post({url:"/channels/get_or_create_private",...$,headers:{"Content-Type":"application/json",...$.headers}})}joinChannelByCode($){return($.client??this.client).post({url:"/channels/join/{join_code}",...$})}createEntityMention($){return($.client??this.client).post({url:"/channels/mentions",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteEntityMention($){return($.client??this.client).delete({url:"/channels/mentions/{mention_id}",...$})}getBatchChannelPreview($){return($.client??this.client).post({url:"/channels/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteChannel($){return($.client??this.client).delete({url:"/channels/{channel_id}",...$})}getChannel($){return($.client??this.client).get({url:"/channels/{channel_id}",...$})}patchChannel($){return($.client??this.client).patch({url:"/channels/{channel_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getChannelAttachments($){return($.client??this.client).get({url:"/channels/{channel_id}/attachments",...$})}createChannelScopedBot($){return($.client??this.client).post({url:"/channels/{channel_id}/bots/scoped",...$,headers:{"Content-Type":"application/json",...$.headers}})}joinChannel($){return($.client??this.client).post({url:"/channels/{channel_id}/join",...$})}getChannelJoinLink($){return($.client??this.client).get({url:"/channels/{channel_id}/join-link",...$})}leaveChannel($){return($.client??this.client).post({url:"/channels/{channel_id}/leave",...$})}removeParticipants($){return($.client??this.client).delete({url:"/channels/{channel_id}/participants",...$,headers:{"Content-Type":"application/json",...$.headers}})}getChannelParticipants($){return($.client??this.client).get({url:"/channels/{channel_id}/participants",...$})}addParticipants($){return($.client??this.client).post({url:"/channels/{channel_id}/participants",...$,headers:{"Content-Type":"application/json",...$.headers}})}setChannelPicture($){return($.client??this.client).put({url:"/channels/{channel_id}/profile_picture",...$,headers:{"Content-Type":"application/json",...$.headers}})}postChannelBotWebhook($){return($.client??this.client).post({url:"/channels/{channel_id}/webhook",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteCollabSurface($){return($.client??this.client).delete({url:"/collab_surfaces/{id}",...$})}getCollabSurface($){return($.client??this.client).get({url:"/collab_surfaces/{id}",...$})}ensureCollabSurface($){return($.client??this.client).put({url:"/collab_surfaces/{id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}createCollabSurfaceToken($){return($.client??this.client).post({url:"/collab_surfaces/{id}/token",...$})}getChannels($){return($?.client??this.client).get({url:"/comms/channels",...$})}createCrmCompany($){return($.client??this.client).post({url:"/crm/companies",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCompany($){return($.client??this.client).get({url:"/crm/companies/{company_id}",...$})}listCompanyContacts($){return($.client??this.client).get({url:"/crm/companies/{company_id}/contacts",...$})}createCrmContact($){return($.client??this.client).post({url:"/crm/companies/{company_id}/contacts",...$,headers:{"Content-Type":"application/json",...$.headers}})}setEmailSync($){return($.client??this.client).put({url:"/crm/companies/{company_id}/email-sync",...$,headers:{"Content-Type":"application/json",...$.headers}})}setCompanyHidden($){return($.client??this.client).put({url:"/crm/companies/{company_id}/hidden",...$,headers:{"Content-Type":"application/json",...$.headers}})}setCrmCompanyName($){return($.client??this.client).put({url:"/crm/companies/{company_id}/name",...$,headers:{"Content-Type":"application/json",...$.headers}})}searchContacts($){return($?.client??this.client).get({url:"/crm/contacts",...$})}getContactByEmail($){return($.client??this.client).get({url:"/crm/contacts/by-email",...$})}getContact($){return($.client??this.client).get({url:"/crm/contacts/{contact_id}",...$})}setContactHidden($){return($.client??this.client).put({url:"/crm/contacts/{contact_id}/hidden",...$,headers:{"Content-Type":"application/json",...$.headers}})}setCrmContactName($){return($.client??this.client).put({url:"/crm/contacts/{contact_id}/name",...$,headers:{"Content-Type":"application/json",...$.headers}})}listCrmPipelines($){return($?.client??this.client).get({url:"/crm/pipelines",...$})}createCrmPipeline($){return($.client??this.client).post({url:"/crm/pipelines",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCrmPipeline($){return($.client??this.client).get({url:"/crm/pipelines/{id}",...$})}renameCrmPipeline($){return($.client??this.client).put({url:"/crm/pipelines/{id}/name",...$,headers:{"Content-Type":"application/json",...$.headers}})}applyCrmPipelineOps($){return($.client??this.client).post({url:"/crm/pipelines/{id}/ops",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCrmPipelinePermissions($){return($.client??this.client).get({url:"/crm/pipelines/{id}/permissions",...$})}updateCrmPipelinePermissions($){return($.client??this.client).patch({url:"/crm/pipelines/{id}/permissions",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCrmPipelineRows($){return($.client??this.client).get({url:"/crm/pipelines/{id}/rows",...$})}queryCrmPipelineRows($){return($.client??this.client).post({url:"/crm/pipelines/{id}/rows",...$,headers:{"Content-Type":"application/json",...$.headers}})}shareCrmPipeline($){return($.client??this.client).put({url:"/crm/pipelines/{id}/sharing",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCrmPipelineTable($){return($.client??this.client).get({url:"/crm/pipelines/{id}/table",...$})}trashCrmPipeline($){return($.client??this.client).put({url:"/crm/pipelines/{id}/trash",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCrmTeamSettings($){return($?.client??this.client).get({url:"/crm/settings",...$})}putCrmTeamSettings($){return($.client??this.client).put({url:"/crm/settings",...$,headers:{"Content-Type":"application/json",...$.headers}})}resetCrmTeamStages($){return($?.client??this.client).delete({url:"/crm/stages",...$})}putCrmTeamStages($){return($.client??this.client).put({url:"/crm/stages",...$,headers:{"Content-Type":"application/json",...$.headers}})}listDatabases($){return($?.client??this.client).get({url:"/databases",...$})}createDatabase($){return($.client??this.client).post({url:"/databases",...$,headers:{"Content-Type":"application/json",...$.headers}})}saveDatabaseQuery($){return($.client??this.client).post({url:"/databases/queries",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDatabaseQuery($){return($.client??this.client).get({url:"/databases/queries/{query_id}",...$})}queryDatabases($){return($.client??this.client).post({url:"/databases/query",...$,headers:{"Content-Type":"application/json",...$.headers}})}ensureStarterHandler($){return($?.client??this.client).post({url:"/databases/starter",...$})}deliverDatabaseWebhook($){return($.client??this.client).post({url:"/databases/webhooks/{token}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDatabase($){return($.client??this.client).get({url:"/databases/{id}",...$})}shareDatabaseAwareness($){return($.client??this.client).put({url:"/databases/{id}/awareness",...$,headers:{"Content-Type":"application/json",...$.headers}})}undoDatabaseChange($){return($.client??this.client).post({url:"/databases/{id}/changes/{change}/undo",...$})}importDatabaseTable($){return($.client??this.client).post({url:"/databases/{id}/import",...$,headers:{"Content-Type":"application/json",...$.headers}})}applyDatabaseOps($){return($.client??this.client).post({url:"/databases/{id}/ops",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDatabasePermissions($){return($.client??this.client).get({url:"/databases/{id}/permissions",...$})}updateDatabasePermissions($){return($.client??this.client).patch({url:"/databases/{id}/permissions",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDatabaseTableChanges($){return($.client??this.client).get({url:"/databases/{id}/tables/{table_id}/changes",...$})}listDatabaseColumnCasts($){return($.client??this.client).get({url:"/databases/{id}/tables/{table_id}/columns/{column_id}/casts",...$})}convertDatabaseColumn($){return($.client??this.client).post({url:"/databases/{id}/tables/{table_id}/columns/{column_id}/conversion",...$,headers:{"Content-Type":"application/json",...$.headers}})}inferDatabaseColumnType($){return($.client??this.client).post({url:"/databases/{id}/tables/{table_id}/columns/{column_id}/infer-type",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDatabaseRowHistory($){return($.client??this.client).get({url:"/databases/{id}/tables/{table_id}/rows/{row_id}/history",...$})}getDatabaseViewPositions($){return($.client??this.client).get({url:"/databases/{id}/views/{view_id}/positions",...$})}listDatabaseWebhooks($){return($.client??this.client).get({url:"/databases/{id}/webhooks",...$})}createDatabaseWebhook($){return($.client??this.client).post({url:"/databases/{id}/webhooks",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteDatabaseWebhook($){return($.client??this.client).delete({url:"/databases/{id}/webhooks/{webhook_id}",...$})}transcribeDictation($){return($.client??this.client).post({bodySerializer:null,url:"/dictation/transcribe",...$,headers:{"Content-Type":"audio/webm",...$.headers}})}getUserDocumentsHandler($){return($.client??this.client).get({url:"/documents",...$})}createDocument($){return($.client??this.client).post({url:"/documents",...$,headers:{"Content-Type":"application/json",...$.headers}})}createMarkdownHandler($){return($.client??this.client).post({url:"/documents/create_markdown",...$,headers:{"Content-Type":"application/json",...$.headers}})}createSkillHandler($){return($.client??this.client).post({url:"/documents/create_skill",...$,headers:{"Content-Type":"application/json",...$.headers}})}createSnippetHandler($){return($.client??this.client).post({url:"/documents/create_snippet",...$,headers:{"Content-Type":"application/json",...$.headers}})}createTaskHandler($){return($.client??this.client).post({url:"/documents/create_task",...$,headers:{"Content-Type":"application/json",...$.headers}})}getGithubPullRequestTasks($){return($.client??this.client).post({url:"/documents/github_prs/tasks",...$,headers:{"Content-Type":"application/json",...$.headers}})}initializeUserDocuments($){return($?.client??this.client).post({url:"/documents/initialize_user_documents",...$})}getDocumentListHandler($){return($?.client??this.client).get({url:"/documents/list",...$})}validateDocumentPermissionsToken($){return($.client??this.client).post({url:"/documents/permissions_token/validate",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDocumentPermissionsToken($){return($.client??this.client).post({url:"/documents/permissions_token/{document_id}",...$})}presaveDocumentHandler($){return($.client??this.client).put({url:"/documents/presave/{document_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getBatchPreviewHandler($){return($.client??this.client).post({url:"/documents/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDocumentByTeamSlug($){return($.client??this.client).get({url:"/documents/slug/{slug}",...$})}handler($){return($?.client??this.client).get({url:"/documents/starter_docs",...$})}getSystemSkillsHandler($){return($?.client??this.client).get({url:"/documents/system_skills",...$})}deleteDocument($){return($.client??this.client).delete({url:"/documents/{document_id}",...$})}getDocument($){return($.client??this.client).get({url:"/documents/{document_id}",...$})}editDocument($){return($.client??this.client).patch({url:"/documents/{document_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}saveDocumentHandler($){return($.client??this.client).put({url:"/documents/{document_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDocumentBranchName($){return($.client??this.client).get({url:"/documents/{document_id}/branch_name",...$})}copyDocument($){return($.client??this.client).post({url:"/documents/{document_id}/copy",...$,headers:{"Content-Type":"application/json",...$.headers}})}exportDocument($){return($.client??this.client).get({url:"/documents/{document_id}/export",...$})}getDocumentGithubPullRequests($){return($.client??this.client).get({url:"/documents/{document_id}/github_prs",...$})}getLocationHandler($){return($.client??this.client).get({url:"/documents/{document_id}/location",...$})}getDocumentLocationV3($){return($.client??this.client).get({url:"/documents/{document_id}/location_v3",...$})}permanentlyDeleteDocument($){return($.client??this.client).delete({url:"/documents/{document_id}/permanent",...$})}getDocumentProcessingResult($){return($.client??this.client).get({url:"/documents/{document_id}/processing",...$})}jobProcessingResultHandler($){return($.client??this.client).get({url:"/documents/{document_id}/processing/{job_id}",...$})}revertDeleteDocument($){return($.client??this.client).put({url:"/documents/{document_id}/revert_delete",...$})}getDocumentShortId($){return($.client??this.client).get({url:"/documents/{document_id}/short_id",...$})}simpleSave($){return($.client??this.client).put({url:"/documents/{document_id}/simple_save",...$})}getDocumentTeamShare($){return($.client??this.client).get({url:"/documents/{document_id}/team_share",...$})}setDocumentTeamShare($){return($.client??this.client).put({url:"/documents/{document_id}/team_share",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDocumentTextContent($){return($.client??this.client).get({url:"/documents/{document_id}/text-content",...$})}getDocumentViewsHandler($){return($.client??this.client).get({url:"/documents/{document_id}/views",...$})}getDocumentVersion($){return($.client??this.client).get({url:"/documents/{document_id}/{document_version_id}",...$})}accessRequestsState($){return($.client??this.client).get({url:"/entities/{entity_type}/{entity_id}/access-requests",...$})}accessRequestsCancel($){return($.client??this.client).delete({url:"/entities/{entity_type}/{entity_id}/access-requests/mine",...$})}accessRequestsSubmit($){return($.client??this.client).put({url:"/entities/{entity_type}/{entity_id}/access-requests/mine",...$,headers:{"Content-Type":"application/json",...$.headers}})}accessRequestsResolve($){return($.client??this.client).post({url:"/entities/{entity_type}/{entity_id}/access-requests/{request_id}/resolve",...$,headers:{"Content-Type":"application/json",...$.headers}})}accessRequestsDirect($){return($.client??this.client).get({url:"/entities/{entity_type}/{entity_id}/direct-access",...$})}accessRequestsRemoveDirect($){return($.client??this.client).delete({url:"/entities/{entity_type}/{entity_id}/direct-access/{user_id}",...$})}accessRequestsSetDirect($){return($.client??this.client).put({url:"/entities/{entity_type}/{entity_id}/direct-access/{user_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getEntityPermission($){return($.client??this.client).get({url:"/entity/{entity_type}/{entity_id}/permissions",...$})}listFavorites($){return($?.client??this.client).get({url:"/favorites",...$})}addFavorite($){return($.client??this.client).post({url:"/favorites",...$,headers:{"Content-Type":"application/json",...$.headers}})}reorderFavorites($){return($.client??this.client).patch({url:"/favorites/reorder",...$,headers:{"Content-Type":"application/json",...$.headers}})}removeFavoriteByEntity($){return($.client??this.client).delete({url:"/favorites/{entity_type}/{entity_id}",...$})}getForeignEntityBySource($){return($.client??this.client).get({url:"/foreign_entity/by_source/{source}/{foreign_entity_id}",...$})}getForeignEntity($){return($.client??this.client).get({url:"/foreign_entity/{id}",...$})}listForms($){return($.client??this.client).get({url:"/forms",...$})}createForm($){return($.client??this.client).post({url:"/forms",...$,headers:{"Content-Type":"application/json",...$.headers}})}listAccessibleForms($){return($?.client??this.client).get({url:"/forms/accessible",...$})}getForm($){return($.client??this.client).get({url:"/forms/{id}",...$})}updateForm($){return($.client??this.client).patch({url:"/forms/{id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}collaborateForm($){return($.client??this.client).post({url:"/forms/{id}/collaboration",...$})}putFormLayout($){return($.client??this.client).put({url:"/forms/{id}/layout",...$,headers:{"Content-Type":"application/json",...$.headers}})}getFormPermissions($){return($.client??this.client).get({url:"/forms/{id}/permissions",...$})}updateFormPermissions($){return($.client??this.client).patch({url:"/forms/{id}/permissions",...$,headers:{"Content-Type":"application/json",...$.headers}})}submitFormResponse($){return($.client??this.client).post({url:"/forms/{id}/responses",...$,headers:{"Content-Type":"application/json",...$.headers}})}getMyFormResponse($){return($.client??this.client).get({url:"/forms/{id}/responses/mine",...$})}editMyFormResponse($){return($.client??this.client).put({url:"/forms/{id}/responses/mine",...$,headers:{"Content-Type":"application/json",...$.headers}})}getFormResponseSummary($){return($.client??this.client).get({url:"/forms/{id}/responses/summary",...$})}getFormTally($){return($.client??this.client).get({url:"/forms/{id}/tally",...$})}installSync($){return($?.client??this.client).get({url:"/github/install-sync",...$})}getGithubPullRequestFacets($){return($?.client??this.client).get({url:"/github_pull_requests/facets",...$})}getGithubPullRequest($){return($.client??this.client).get({url:"/github_pull_requests/{id}",...$})}getGithubPullRequestChanges($){return($.client??this.client).get({url:"/github_pull_requests/{id}/changes",...$})}getGithubPullRequestChangesPatch($){return($.client??this.client).get({url:"/github_pull_requests/{id}/changes/patch",...$})}createHarnessPairing($){return($.client??this.client).post({url:"/harness-pairings",...$,headers:{"Content-Type":"application/json",...$.headers}})}getHarnessPairing($){return($.client??this.client).get({url:"/harness-pairings/{code}",...$})}approveHarnessPairing($){return($.client??this.client).post({url:"/harness-pairings/{code}/approve",...$,headers:{"Content-Type":"application/json",...$.headers}})}claimHarnessPairing($){return($.client??this.client).post({url:"/harness-pairings/{pairing_id}/claim",...$,headers:{"Content-Type":"application/json",...$.headers}})}listHarnesses($){return($?.client??this.client).get({url:"/harnesses",...$})}deleteSelfHarness($){return($?.client??this.client).delete({url:"/harnesses/me",...$})}getSelfHarness($){return($?.client??this.client).get({url:"/harnesses/me",...$})}listHarnessAgents($){return($?.client??this.client).get({url:"/harnesses/me/agents",...$})}listHarnessSessions($){return($?.client??this.client).get({url:"/harnesses/me/sessions",...$})}deleteHarness($){return($.client??this.client).delete({url:"/harnesses/{harness_id}",...$})}healthHandler($){return($?.client??this.client).get({url:"/health",...$})}getHistoryHandler($){return($?.client??this.client).get({url:"/history",...$})}deleteHistoryHandler($){return($.client??this.client).delete({url:"/history/{item_type}/{item_id}",...$})}upsertHistoryHandler($){return($.client??this.client).post({url:"/history/{item_type}/{item_id}",...$})}listInitiatives($){return($?.client??this.client).get({url:"/initiatives",...$})}createInitiative($){return($.client??this.client).post({url:"/initiatives",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteInitiative($){return($.client??this.client).delete({url:"/initiatives/{initiative_id}",...$})}getInitiative($){return($.client??this.client).get({url:"/initiatives/{initiative_id}",...$})}updateInitiative($){return($.client??this.client).patch({url:"/initiatives/{initiative_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getInstructionsHandler($){return($?.client??this.client).get({url:"/instructions",...$})}createInstructionsHandler($){return($?.client??this.client).post({url:"/instructions",...$})}getItemsSoup($){return($?.client??this.client).get({url:"/items/soup",...$})}postItemsSoup($){return($.client??this.client).post({url:"/items/soup",...$,headers:{"Content-Type":"application/json",...$.headers}})}postItemsSoupAst($){return($.client??this.client).post({url:"/items/soup/ast",...$,headers:{"Content-Type":"application/json",...$.headers}})}postItemsSoupAstGrouped($){return($.client??this.client).post({url:"/items/soup/ast/grouped",...$,headers:{"Content-Type":"application/json",...$.headers}})}messageTimeline($){return($.client??this.client).get({url:"/messages/{parent_type}/{parent_id}",...$})}entityMessageCreate($){return($.client??this.client).post({url:"/messages/{parent_type}/{parent_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}entityMessageDeleteMessage($){return($.client??this.client).delete({url:"/messages/{parent_type}/{parent_id}/items/{id}",...$})}entityMessageGetMessage($){return($.client??this.client).get({url:"/messages/{parent_type}/{parent_id}/items/{id}",...$})}entityMessageEdit($){return($.client??this.client).patch({url:"/messages/{parent_type}/{parent_id}/items/{id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}entityMessageReact($){return($.client??this.client).post({url:"/messages/{parent_type}/{parent_id}/items/{id}/reactions",...$,headers:{"Content-Type":"application/json",...$.headers}})}entityMessageLegacy($){return($.client??this.client).get({url:"/messages/{parent_type}/{parent_id}/legacy/{legacy_id}",...$})}entityMessageDeleteThread($){return($.client??this.client).delete({url:"/messages/{parent_type}/{parent_id}/threads/{id}",...$})}entityMessageGetThread($){return($.client??this.client).get({url:"/messages/{parent_type}/{parent_id}/threads/{id}",...$})}entityMessagePatchThread($){return($.client??this.client).patch({url:"/messages/{parent_type}/{parent_id}/threads/{id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}messageTimelineEntries($){return($.client??this.client).get({url:"/messages/{parent_type}/{parent_id}/timeline",...$})}entityMessageTyping($){return($.client??this.client).post({url:"/messages/{parent_type}/{parent_id}/typing",...$,headers:{"Content-Type":"application/json",...$.headers}})}getPinsHandler($){return($?.client??this.client).get({url:"/pins",...$})}reorderPinsHandler($){return($.client??this.client).patch({url:"/pins",...$,headers:{"Content-Type":"application/json",...$.headers}})}removePinHandler($){return($.client??this.client).delete({url:"/pins/{pinned_item_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}addPinHandler($){return($.client??this.client).post({url:"/pins/{pinned_item_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getProjectsHandler($){return($?.client??this.client).get({url:"/projects",...$})}createProjectHandler($){return($.client??this.client).post({url:"/projects",...$,headers:{"Content-Type":"application/json",...$.headers}})}getPendingProjectsHandler($){return($?.client??this.client).get({url:"/projects/pending",...$})}getBatchProjectPreview($){return($.client??this.client).post({url:"/projects/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}uploadFolderHandler($){return($.client??this.client).post({url:"/projects/upload",...$,headers:{"Content-Type":"application/json",...$.headers}})}uploadExtractFolderHandler($){return($.client??this.client).post({url:"/projects/upload_extract",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteProjectHandler($){return($.client??this.client).delete({url:"/projects/{id}",...$})}getProjectHandler($){return($.client??this.client).get({url:"/projects/{id}",...$})}getProjectUserAccessLevel($){return($.client??this.client).get({url:"/projects/{id}/access_level",...$})}getProjectContentHandler($){return($.client??this.client).get({url:"/projects/{id}/content",...$})}permanentlyDeleteProject($){return($.client??this.client).delete({url:"/projects/{id}/permanent",...$})}getProjectPermissionsV2($){return($.client??this.client).get({url:"/projects/{id}/permissions",...$})}revertDeleteProject($){return($.client??this.client).put({url:"/projects/{id}/revert_delete",...$})}recentlyDeleted($){return($?.client??this.client).get({url:"/recents/deleted",...$})}listEmailReminders($){return($?.client??this.client).get({url:"/reminders/email/collection",...$})}getEmailFollowup($){return($.client??this.client).get({url:"/reminders/email/{thread_id}",...$})}setEmailFollowup($){return($.client??this.client).put({url:"/reminders/email/{thread_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getViewsHandler($){return($?.client??this.client).get({url:"/saved_views",...$})}createViewHandler($){return($.client??this.client).post({url:"/saved_views",...$,headers:{"Content-Type":"application/json",...$.headers}})}excludeDefaultViewHandler($){return($.client??this.client).post({url:"/saved_views/exclude_default",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteViewHandler($){return($.client??this.client).delete({url:"/saved_views/{saved_view_id}",...$})}patchViewHandler($){return($.client??this.client).patch({url:"/saved_views/{saved_view_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}listSlackImports($){return($?.client??this.client).get({url:"/slack/imports",...$})}createSlackImport($){return($.client??this.client).post({url:"/slack/imports",...$,headers:{"Content-Type":"application/json",...$.headers}})}getSlackImport($){return($.client??this.client).get({url:"/slack/imports/{job_id}",...$})}cancelSlackImport($){return($.client??this.client).post({url:"/slack/imports/{job_id}/cancel",...$})}finalizeSlackImport($){return($.client??this.client).post({url:"/slack/imports/{job_id}/finalize",...$})}registerSlackImportUploads($){return($.client??this.client).post({url:"/slack/imports/{job_id}/uploads",...$,headers:{"Content-Type":"application/json",...$.headers}})}completeSlackImportUploads($){return($.client??this.client).post({url:"/slack/imports/{job_id}/uploads/complete",...$,headers:{"Content-Type":"application/json",...$.headers}})}bulkWakeupSyncServiceDocuments($){return($.client??this.client).post({url:"/sync_service/wakeup",...$,headers:{"Content-Type":"application/json",...$.headers}})}editThreadV2($){return($.client??this.client).patch({url:"/threads/{thread_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}listUserApiKeys($){return($?.client??this.client).get({url:"/user-api-keys",...$})}createUserApiKey($){return($.client??this.client).post({url:"/user-api-keys",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteUserApiKey($){return($.client??this.client).delete({url:"/user-api-keys/{id}",...$})}deleteUserDocumentViewLocation($){return($.client??this.client).delete({url:"/user_document_view_location/{document_id}",...$})}getUserDocumentViewLocation($){return($.client??this.client).get({url:"/user_document_view_location/{document_id}",...$})}upsertUserDocumentViewLocation($){return($.client??this.client).post({url:"/user_document_view_location/{document_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDocumentPermissionsV2($){return($.client??this.client).get({url:"/v2/documents/{document_id}/permissions",...$})}editProjectV2($){return($.client??this.client).patch({url:"/v2/projects/{id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}streamEvents($){return($.client??this.client).sse.get({url:"/webhook/events/stream",...$})}listWebhooks($){return($?.client??this.client).get({url:"/webhook/webhooks",...$})}createWebhook($){return($.client??this.client).post({url:"/webhook/webhooks",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteWebhook($){return($.client??this.client).delete({url:"/webhook/webhooks/{webhook_id}",...$})}getWebhook($){return($.client??this.client).get({url:"/webhook/webhooks/{webhook_id}",...$})}patchWebhook($){return($.client??this.client).patch({url:"/webhook/webhooks/{webhook_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}validateWebhook($){return($.client??this.client).post({url:"/webhook/webhooks/{webhook_id}/validate",...$})}}function $6({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:G,url:L,...Y}){let J,T=G??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=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(J!==void 0)P.set("Last-Event-ID",J);try{let D={redirect:"follow",...Y,body:Y.serializedBody,headers:P,signal:I},C=new Request(L,D);if($)C=await $(L,D);let U=await(Y.fetch??globalThis.fetch)(C);if(!U.ok)throw Error(`SSE failed: ${U.status} ${U.statusText}`);if(!U.body)throw Error("No body in SSE response");let H=U.body.pipeThrough(new TextDecoderStream).getReader(),N="",g=()=>{try{H.cancel()}catch{}};I.addEventListener("abort",g);try{while(!0){let{done:d,value:l}=await H.read();if(d)break;N+=l,N=N.replace(/\r\n?/g,`
+`);let k=N.split(`
-`);U=g.pop()??"";for(let r of g){let p=r.split(`
+`);N=k.pop()??"";for(let r of k){let p=r.split(`
`),F=[],y;for(let R of p)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))y=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let h=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(h))V=h}let _,v=!1;if(F.length){let R=F.join(`
-`);try{_=JSON.parse(R),v=!0}catch{_=R}}if(v){if(S)await S(_);if(x)_=await x(_)}if(j?.({data:_,event:y,id:J,retry:V}),F.length)yield _}}}finally{I.removeEventListener("abort",k),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let C=Math.min(V*2**(B-1),X??30000);await T(C)}}}()}}var p5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},a5=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},i5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},Cx=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((G)=>encodeURIComponent(G))).join(a5(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=p5(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return EO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},EO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},_x=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let G=[];Object.entries(S).forEach(([Y,J])=>{G=[...G,Y,$?J:encodeURIComponent(J)]});let L=G.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=i5(x),X=Object.entries(S).map(([G,L])=>EO({allowReserved:$,name:x==="deepObject"?`${j}[${G}]`:G,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var n5=/\{[^{}]+\}/g,s5=({path:$,url:O})=>{let j=O,x=O.match(n5);if(x)for(let S of x){let K=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))K=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let G=$[Z];if(G===void 0||G===null)continue;if(Array.isArray(G)){j=j.replace(S,Cx({explode:K,name:Z,style:X,value:G}));continue}if(typeof G==="object"){j=j.replace(S,_x({explode:K,name:Z,style:X,value:G,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${EO({name:Z,value:G})}`);continue}let L=encodeURIComponent(X==="label"?`.${G}`:G);j=j.replace(S,L)}return j},$6=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=s5({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function U1($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var O6=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var j6={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var x6=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let G=Cx({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(G)S.push(G)}else if(typeof Z==="object"){let G=_x({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(G)S.push(G)}else{let G=EO({allowReserved:X.allowReserved,name:K,value:Z});if(G)S.push(G)}}return S.join("&")}},S6=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},t5=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function Z6($){for(let O of $.security??[]){if(t5($,O.name))continue;let j=await O6(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var z1=($)=>$6({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:x6($.querySerializer),url:$.url}),I1=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=Ax($.headers,O.headers),j},e5=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},Ax=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?e5(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class Mx{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var X6=()=>({error:new Mx,request:new Mx,response:new Mx}),o5=x6({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),$4={"Content-Type":"application/json"},Zj=($={})=>({...j6,headers:$4,parseAs:"auto",querySerializer:o5,...$});var T1=($={})=>{let O=I1(Zj(),$),j=()=>({...O}),x=(Y)=>{return O=I1(O,Y),j()},S=X6(),K=async(Y)=>{let J={...O,...Y,fetch:Y.fetch??O.fetch??globalThis.fetch,headers:Ax(O.headers,Y.headers),serializedBody:void 0};if(J.security)await Z6(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let T=J,z=z1(T);return{opts:T,url:z}},Z=async(Y)=>{let J=Y.throwOnError??O.throwOnError,T=Y.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(Y),I={redirect:"follow",...V,body:U1(V)};z=new Request(B,I);for(let N of S.request.fns)if(N)z=await N(z,V);let P=V.fetch;W=await P(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?S6(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await W[N]();break;case"json":{let U=await W.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let C=await W.text(),E;try{E=JSON.parse(C)}catch{}throw E??C}catch(V){let B=V;for(let I of S.error.fns)if(I)B=await I(B,W,z,Y);if(B=B||{},J)throw B;return T==="data"?void 0:{error:B,request:z,response:W}}},X=(Y)=>(J)=>Z({...J,method:Y}),G=(Y)=>async(J)=>{let{opts:T,url:z}=await K(J);return o2({...T,body:T.body,method:Y,onRequest:async(W,V)=>{let B=new Request(W,V);for(let I of S.request.fns)if(I)B=await I(B,T);return B},serializedBody:U1(T),url:z})};return{buildUrl:(Y)=>z1({...O,...Y}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:G("CONNECT"),delete:G("DELETE"),get:G("GET"),head:G("HEAD"),options:G("OPTIONS"),patch:G("PATCH"),post:G("POST"),put:G("PUT"),trace:G("TRACE")},trace:X("TRACE")}};var G6=T1(Zj());class K6{client;constructor($){this.client=$?.client??G6}}class Y6{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class Px extends K6{static __registry=new Y6;constructor($){super($);Px.__registry.set(this,$?.key)}proxyRequestHandler($){return($.client??this.client).get({url:"/proxy",...$})}getUnfurl($){return($.client??this.client).get({url:"/unfurl",...$})}getUnfurlBulk($){return($.client??this.client).post({url:"/unfurl/bulk",...$,headers:{"Content-Type":"application/json",...$.headers}})}}var Q6={dev:"https://dev.macro.com",prod:"https://macro.com",local:"http://localhost:3000"},H1={dev:{"agent-harness":"https://dev-gateway.macro.com/agent-harness",storage:"https://dev-gateway.macro.com/dss",auth:"https://dev-gateway.macro.com/auth",email:"https://dev-gateway.macro.com/email",calendar:"https://dev-gateway.macro.com/calendar",cognition:"https://dev-gateway.macro.com/cognition",notification:"https://dev-gateway.macro.com/notification",properties:"https://dev-gateway.macro.com/dss",search:"https://dev-gateway.macro.com/dss","scheduled-action":"https://dev-gateway.macro.com/scheduled-action","static-files":"https://static-file-service-dev.macro.com",connection:"https://dev-gateway.macro.com/connection-gateway",contacts:"https://dev-gateway.macro.com/contacts",unfurl:"https://dev-gateway.macro.com/unfurl"},prod:{"agent-harness":"https://gateway.macro.com/agent-harness",storage:"https://gateway.macro.com/dss",auth:"https://gateway.macro.com/auth",email:"https://gateway.macro.com/email",calendar:"https://gateway.macro.com/calendar",cognition:"https://gateway.macro.com/cognition",notification:"https://gateway.macro.com/notification",properties:"https://gateway.macro.com/dss",search:"https://gateway.macro.com/dss","scheduled-action":"https://gateway.macro.com/scheduled-action","static-files":"https://static-file-service.macro.com",connection:"https://gateway.macro.com/connection-gateway",contacts:"https://gateway.macro.com/contacts",unfurl:"https://gateway.macro.com/unfurl"},local:{"agent-harness":"http://localhost:8101",storage:"http://localhost:8086",auth:"http://localhost:8080",email:"http://localhost:8087",calendar:"http://localhost:8088/calendar",cognition:"http://localhost:8101/cognition",notification:"http://localhost:8089",properties:"http://localhost:8086",search:"http://localhost:8086","scheduled-action":"http://localhost:8101/scheduled-action","static-files":"http://localhost:8100",connection:"http://localhost:8082",contacts:"http://localhost:8083",unfurl:"http://localhost:8095"}};function O4($,O){let j=O?.channel_id;return O&&j?{channel:f.byId($,j),thread:new g$($,j,O.thread_id)}:{channel:void 0,thread:void 0}}function P$($,O){return{session:i.byId($,O.session_id),owner:M.byId($,O.owner_id),...O4($,O.origin)}}function wO($,O,j){let x=O.origin?.channel_id;return x&&j?e.byId($,x,j):void 0}function qO($,O){return O?M.byId($,O):void 0}function J6($,O){return c(O).with({event_type:"agent_session.opened"},({metadata:j})=>({event_type:"agent_session.opened",metadata:j,...P$($,j.identity)})).with({event_type:"agent_session.turn_started"},({metadata:j})=>({event_type:"agent_session.turn_started",metadata:j,...P$($,j.identity),actor:qO($,j.actor),announcement:wO($,j.identity,j.announcement_message_id)})).with({event_type:"agent_session.turn_ended"},({metadata:j})=>({event_type:"agent_session.turn_ended",metadata:j,...P$($,j.identity),actor:qO($,j.actor),announcement:wO($,j.identity,j.announcement_message_id)})).with({event_type:"agent_session.command_rejected"},({metadata:j})=>({event_type:"agent_session.command_rejected",metadata:j,...P$($,j.identity),actor:qO($,j.actor),announcement:wO($,j.identity,j.announcement_message_id)})).with({event_type:"agent_session.settled"},({metadata:j})=>({event_type:"agent_session.settled",metadata:j,...P$($,j.identity),actor:qO($,j.last_turn?.actor),announcement:wO($,j.identity,j.last_turn?.announcement_message_id)})).with({event_type:"agent_session.waiting_for_input"},({metadata:j})=>({event_type:"agent_session.waiting_for_input",metadata:j,...P$($,j.identity),announcement:wO($,j.identity,j.announcement_message_id)})).with({event_type:"agent_session.input_received"},({metadata:j})=>({event_type:"agent_session.input_received",metadata:j,...P$($,j.identity)})).with({event_type:"agent_session.mentioned"},({metadata:j})=>({event_type:"agent_session.mentioned",metadata:j,...P$($,j.identity),mentionedBy:qO($,j.mentioned_by),mentioned:j.mentioned.map((x)=>M.byId($,x))})).with({event_type:"agent_session.stopped"},({metadata:j})=>({event_type:"agent_session.stopped",metadata:j,...P$($,j.identity),actor:qO($,j.turn_in_flight?.actor),announcement:wO($,j.identity,j.turn_in_flight?.announcement_message_id)})).with({event_type:"agent_session.renamed"},({metadata:j})=>({event_type:"agent_session.renamed",metadata:j,...P$($,j.identity)})).with({event_type:"agent_session.deleted"},({metadata:j})=>({event_type:"agent_session.deleted",metadata:j,...P$($,j.identity)})).exhaustive((j)=>{console.warn("macro sdk: unknown agent session event",j);return})}var V6="macro|";function C$($,O){return O.startsWith(V6)&&O.length>V6.length?M.byId($,O.toLowerCase()):void 0}function W6($,O){return c(O).with({event_type:"channel.created"},({metadata:j})=>({event_type:"channel.created",metadata:j,channel:f.byId($,j.channel_id),actor:C$($,j.actor),participants:j.participant_user_ids.map((x)=>M.byId($,x))})).with({event_type:"channel.updated"},({metadata:j})=>({event_type:"channel.updated",metadata:j,channel:f.byId($,j.channel_id),actor:C$($,j.actor)})).with({event_type:"channel.deleted"},({metadata:j})=>({event_type:"channel.deleted",metadata:j,channel:f.byId($,j.channel_id),actor:C$($,j.actor)})).with({event_type:"channel.picture_changed"},({metadata:j})=>({event_type:"channel.picture_changed",metadata:j,channel:f.byId($,j.channel_id),actor:C$($,j.actor)})).with({event_type:"channel.participant_added"},({metadata:j})=>({event_type:"channel.participant_added",metadata:j,channel:f.byId($,j.channel_id),addedBy:C$($,j.added_by),addedUsers:j.added_user_ids.map((x)=>M.byId($,x))})).with({event_type:"channel.participant_removed"},({metadata:j})=>({event_type:"channel.participant_removed",metadata:j,channel:f.byId($,j.channel_id),removedBy:M.byId($,j.removed_by),removedUsers:j.removed_user_ids.map((x)=>M.byId($,x))})).exhaustive((j)=>{console.warn("macro sdk: unknown channel event",j);return})}function B6($,O){return c(O).with({event_type:"document.created"},({metadata:j})=>({event_type:"document.created",metadata:j,document:q.byId($,j.document_id),owner:M.byId($,j.owner),project:j.project_id?n.byId($,j.project_id):void 0})).with({event_type:"document.updated"},({metadata:j})=>({event_type:"document.updated",metadata:j,document:q.byId($,j.document_id),owner:M.byId($,j.owner),actor:j.actor_user_id?M.byId($,j.actor_user_id):void 0,project:j.project_id?n.byId($,j.project_id):void 0,previousProject:j.previous_project_id?n.byId($,j.previous_project_id):void 0})).with({event_type:"document.deleted"},({metadata:j})=>({event_type:"document.deleted",metadata:j,document:q.byId($,j.document_id),actor:j.actor_user_id?M.byId($,j.actor_user_id):void 0,project:j.project_id?n.byId($,j.project_id):void 0})).with({event_type:"document.content_uploaded"},({metadata:j})=>({event_type:"document.content_uploaded",metadata:j,document:q.byId($,j.document_id),owner:M.byId($,j.owner)})).with({event_type:"document.sync_content_updated"},({metadata:j})=>({event_type:"document.sync_content_updated",metadata:j,document:q.byId($,j.document_id)})).with({event_type:"document.purged"},({metadata:j})=>({event_type:"document.purged",metadata:j,document:q.byId($,j.document_id)})).with({event_type:"document.copied"},({metadata:j})=>({event_type:"document.copied",metadata:j,document:q.byId($,j.document_id),sourceDocument:q.byId($,j.source_document_id),owner:M.byId($,j.owner),project:j.project_id?n.byId($,j.project_id):void 0})).with({event_type:"document.interaction"},({metadata:j})=>({event_type:"document.interaction",metadata:j,document:q.byId($,j.document_id)})).exhaustive((j)=>{console.warn("macro sdk: unknown document event",j);return})}function fO($,O,j=[]){let x=O.parent;if(x.type==="call")return{type:"call",call:Y$.byId($,x.id),message:v$.byId($,x.id,O.message_id),threadId:x.id};if(x.type==="channel")return{type:"channel",channel:f.byId($,x.id),message:e.byId($,x.id,O.message_id,j),thread:O.thread_id?new g$($,x.id,O.thread_id):void 0};return{type:"document",document:q.byId($,x.id),comment:c$.byId($,x.id,O.message_id),threadId:O.root_id}}function L6($,O){return c(O).with({event_type:"message.posted"},({metadata:j})=>({event_type:"message.posted",metadata:j,target:fO($,j,j.mentions),sender:C$($,j.sender)})).with({event_type:"message.mentioned"},({metadata:j})=>({event_type:"message.mentioned",metadata:j,target:fO($,j),sender:C$($,j.sender)})).with({event_type:"message.patched"},({metadata:j})=>({event_type:"message.patched",metadata:j,target:fO($,j),actor:C$($,j.actor)})).with({event_type:"message.deleted"},({metadata:j})=>({event_type:"message.deleted",metadata:j,target:fO($,j),actor:C$($,j.actor)})).with({event_type:"message.attachment_created"},({metadata:j})=>({event_type:"message.attachment_created",metadata:j,target:fO($,j),actor:C$($,j.actor)})).with({event_type:"message.attachment_removed"},({metadata:j})=>({event_type:"message.attachment_removed",metadata:j,target:fO($,j),actor:C$($,j.actor)})).exhaustive((j)=>{console.warn("macro sdk: unknown message event",j);return})}async function N6($){let O=new TextEncoder,j=await crypto.subtle.importKey("raw",O.encode($.secret),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),x=await crypto.subtle.sign("HMAC",j,O.encode(`${$.timestamp}.${$.rawBody}`));return`v1=${new Uint8Array(x).toHex()}`===$.signature}var j4="webhook.validation.test";function x4($,O){return c(O).with({event_type:x$.string.startsWith("document.")},(j)=>B6($,j)).with({event_type:x$.string.startsWith("channel.")},(j)=>W6($,j)).with({event_type:x$.string.startsWith("message.")},(j)=>L6($,j)).with({event_type:x$.string.startsWith("agent_session.")},(j)=>J6($,j)).otherwise(()=>{return})}class R1{client;secret;handlers=new Map;constructor($,O){this.client=$;this.secret=O}on($,O){let j=this.handlers.get($)??new Set;return j.add(O),this.handlers.set($,j),()=>j.delete(O)}onSelfMention($){return this.on("message.mentioned",async(O)=>{if(O.metadata.mentioned.entity_id.toLowerCase()!==(await this.client.myPrincipalId()).toLowerCase())return;await $(O)})}async listen($={}){let O=$.filters??this.filtersFromHandlers();if(O.length===0||O.every((K)=>K.events.length===0))throw new b("listen() needs filters — pass filters or register handlers with .on() first");let j=new AbortController;if($.signal)if($.signal.aborted)j.abort();else $.signal.addEventListener("abort",()=>j.abort(),{once:!0});let{stream:x}=await this.client.storage.streamEvents({query:{scope:$.scope??"user",filters:JSON.stringify(O)},signal:j.signal});return(async()=>{try{for await(let K of x)await this.dispatchEvent(K)}catch{if(j.signal.aborted)return;throw new b("event stream failed")}})().catch(()=>{}),()=>{j.abort()}}async handle($,O){if(!this.secret)throw new b("webhookSecret is required to verify incoming webhook deliveries");if(!await N6({secret:this.secret,timestamp:O.timestamp??"",rawBody:$,signature:O.signature??""}))throw new b("invalid webhook signature");if(O.event===j4)return;await this.dispatchEvent(JSON.parse($))}webhook(){if(!this.secret)throw new b("webhookSecret is required to verify incoming webhook deliveries");return async($)=>{return await this.handle(await $.text(),{event:$.headers.get("x-macro-event")??void 0,eventId:$.headers.get("x-macro-event-id")??void 0,timestamp:$.headers.get("x-macro-timestamp")??void 0,signature:$.headers.get("x-macro-signature")??void 0}),new Response("ok")}}filtersFromHandlers(){let $=[...this.handlers.entries()].filter(([,O])=>O.size>0).map(([O])=>O);return $.length>0?[{events:$}]:[]}async dispatchEvent($){let O=typeof $==="string"?JSON.parse($):$;if(O===null||typeof O!=="object"||!("event_type"in O))return;let j=O,x=this.handlers.get(j.event_type);if(!x||x.size===0)return;let S=x4(this.client,j);if(!S)return;await Promise.all([...x].map((K)=>K(S)))}}function U6(){return}var S4=0,D1;function Z4($){D1=$}function N$($,O,j){if(!j&&!D1)return $;let x=(S)=>{for(let K of[D1,j])try{Promise.resolve(K?.(S)).catch(()=>{})}catch{}};return new Proxy($,{get(S,K,Z){let X=Reflect.get(S,K,Z);if(typeof K!=="string"||typeof X!=="function")return X;return async(...G)=>{let L={id:++S4,service:O,operation:K};x({...L,status:"started"});try{let Y=await Reflect.apply(X,S,G),J=Y!==null&&typeof Y==="object"&&"error"in Y&&Y.error!=null;return x({...L,status:J?"failed":"completed"}),Y}catch(Y){throw x({...L,status:"failed"}),Y}}}})}var I6="x-macro-user-api-key",X4="mak_",C1="mbot_";function G4($){return c($).with(x$.string.startsWith(C1),()=>{throw Error("bot token passed as a user credential. Use auth: { type: 'bot', token } or MACRO_BOT_TOKEN.")}).with(x$.string.startsWith(X4),(O)=>[I6,O]).otherwise((O)=>["Authorization",`Bearer ${O}`])}async function z6($){return typeof $==="function"?await $():$}async function K4($,O,j){return c($).with({type:"bot"},async(x)=>{let S=await z6(x.token);if(!S.startsWith(C1))throw Error("user API key passed as a bot token. Use auth: { type: 'user', apiKey } or MACRO_API_KEY.");let K=[["x-macro-bot-token",S]];if(!j?.hasBotScope)K.push(["x-macro-bot-scope",x.scope??(O?"user":"team")]);if(O)K.push(["x-macro-bot-for-macro-user-id",O]);return K}).with({type:"user",apiKey:x$.string},({apiKey:x})=>{if(x.startsWith(C1))throw Error("bot token passed as a user credential. Use auth: { type: 'bot', token } or MACRO_BOT_TOKEN.");return[[I6,x]]}).with({type:"user"},async({token:x})=>{return[G4(await z6(x))]}).exhaustive()}class _1{scheduledAction;unfurl;agentHarness;auth;calendar;cognition;contacts;email;notification;properties;search;storage;webAppUrl;wsVerify;events;authConfig;hosts;localPortmap;requestedAs;selfBotRecord;selfPrincipal;constructor($){let O=Y4($),j=O==="local"?U6():void 0,x={...H1[O],...j?.hosts,...$.hosts};this.hosts=x,this.localPortmap=j;let S=typeof process<"u"?{}.MACRO_WEB_URL:void 0;if(this.webAppUrl=$.webAppUrl??S??j?.webAppUrl??Q6[O],this.authConfig=Q4($),this.requestedAs=$.requestedAs,this.requestedAs&&this.authConfig.type!=="bot")throw Error("requestedAs() requires bot auth — a user token always acts as its own user");this.wsVerify=$.wsVerify,this.scheduledAction=N$(new Wx({client:this.makeClient(x["scheduled-action"])}),"scheduled-action",$.onRequest),this.unfurl=N$(new Px({client:this.makeClient(x.unfurl)}),"unfurl",$.onRequest),this.agentHarness=N$(new Aj({client:this.makeClient(x["agent-harness"])}),"agent-harness",$.onRequest),this.auth=N$(new qj({client:this.makeClient(x.auth)}),"auth",$.onRequest),this.calendar=N$(new yj({client:this.makeClient(x.calendar)}),"calendar",$.onRequest),this.cognition=N$(new uj({client:this.makeClient(x.cognition)}),"cognition",$.onRequest),this.contacts=N$(new aj({client:this.makeClient(x.contacts)}),"contacts",$.onRequest),this.email=N$(new ej({client:this.makeClient(x.email)}),"email",$.onRequest),this.notification=N$(new xx({client:this.makeClient(x.notification)}),"notification",$.onRequest),this.properties=N$(new Kx({client:this.makeClient(x.properties)}),"properties",$.onRequest),this.search=N$(new zx({client:this.makeClient(x.search)}),"search",$.onRequest),this.storage=N$(new Dx({client:this.makeClient(x.storage)}),"storage",$.onRequest);let K=typeof process<"u"?{}.MACRO_WEBHOOK_SECRET:void 0,Z=$.webhookSecret??K;this.events=new R1(this,Z)}hasActingUser(){return this.authConfig.type==="user"||this.requestedAs!==void 0}selfBot(){return this.selfBotRecord??=new yO(this).me().catch(($)=>{throw this.selfBotRecord=void 0,$}),this.selfBotRecord}myPrincipalId(){return this.selfPrincipal??=(this.authConfig.type==="bot"?this.selfBot().then(($)=>`bot|${$.id}`):M.me(this).then(($)=>$.id)).catch(($)=>{throw this.selfPrincipal=void 0,$}),this.selfPrincipal}makeClient($){let O=Sj({baseUrl:$});return O.interceptors.request.use(async(j)=>{let x=await K4(this.authConfig,this.requestedAs,{hasBotScope:j.headers.has("x-macro-bot-scope")});for(let[S,K]of x)j.headers.set(S,K);return j}),O}}function Y4($){if($.env)return $.env;let O=typeof process<"u"?{}.MACRO_ENV:void 0;if(!O)return"prod";if(!(O in H1))throw Error(`invalid MACRO_ENV "${O}" — expected local, dev, or prod`);return O}function Q4($){if($.auth)return $.auth;if($.token)return{type:"user",token:$.token};let O=typeof process<"u"?{}.MACRO_API_KEY:void 0,j=typeof process<"u"?{}.MACRO_BOT_TOKEN:void 0;if(O&&j)throw Error("both MACRO_API_KEY and MACRO_BOT_TOKEN are set — pass auth to new Macro() to pick one");if(j)return{type:"bot",token:j};return{type:"user",token:O??(()=>{throw Error("no Macro credential. Set MACRO_API_KEY (API key or bearer token) or MACRO_BOT_TOKEN, or pass token/auth to new Macro().")})}}class M1{id;constructor($){this.id=$}static byId($){return new M1($)}toJSON(){return{id:this.id}}}class T6{routines;unfurls;agents;initiatives;apiKeys;harnesses;meetings;githubPullRequests;entityMentions;agentSessions;ai;bots;calendar;calls;channels;chats;crm;databases;documents;email;favorites;foreignEntities;forms;notifications;pins;projects;properties;tasks;teams;users;webhooks;workspace;events;webAppUrl;_client;opts;constructor($){this.opts=$;let O=new _1($);this._client=O,this.routines=new z0(O),this.unfurls=new H0(O),this.agents=new fx(O),this.initiatives=new Y0(O),this.apiKeys=new kx(O),this.harnesses=new K0(O),this.meetings=new Q0(O),this.githubPullRequests=new G0(O),this.entityMentions=new j0(O),this.agentSessions=new qx(O),this.ai=new bx(O),this.bots=new yO(O),this.calendar=new gx(O),this.calls=new yx(O),this.channels=new hx(O),this.chats=new mx(O),this.crm=new ux(O),this.databases=new ex(O),this.documents=new ox(O),this.email=new O0(O),this.favorites=new x0(O),this.foreignEntities=new S0(O),this.forms=new Z0(O),this.notifications=new J0(O),this.pins=new V0(O),this.projects=new W0(O),this.properties=new B0(O),this.tasks=new I0(O),this.teams=new T0(O),this.users=new R0(O),this.webhooks=new D0(O),this.workspace=new A0(O),this.events=O.events,this.webAppUrl=O.webAppUrl}myPrincipalId(){return this._client.myPrincipalId()}requestedAs($){return new T6({...this.opts,requestedAs:$.id})}}export{l$ as wrapXml,$$ as toBody,Z4 as observeRequests,D6 as msg,R6 as here,p$ as UserApiKey,gO as ToolApproval,L$ as SessionReview,N0 as RoutineExecution,jO as Routine,wx as ReviewItem,X0 as PullRequestChangeset,Qj as PipelineTable,XO as PipelineRow,Jj as PipelineColumn,B$ as MessageThread,I$ as Meeting,tx as MacroOpRefusedError,T6 as Macro,$O as Initiative,UO as HarnessPairing,W$ as Harness,NO as GithubPullRequest,d$ as FormSection,LO as FormResponse,Tj as FormReference,u$ as FormQuestion,JO as FormOption,k$ as Form,BO as EntityMention,o as EntityAccess,QO as EmailFilter,YO as EmailDraft,rO as DraftAttachment,lO as DocumentVersion,GO as DocumentAnchor,pO as DevicePairing,a$ as CrmPipeline,Ex as ConversationTurn,kO as CodeExecution,mO as ChatMessage,hO as ChatGeneration,M1 as ChannelPicture,ZO as ChannelActivity,Gj as AgentConversation,U$ as Agent,WO as AccessRequest};
+`);try{_=JSON.parse(R),v=!0}catch{_=R}}if(v){if(S)await S(_);if(x)_=await x(_)}if(j?.({data:_,event:y,id:J,retry:V}),F.length)yield _}}}finally{I.removeEventListener("abort",g),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let C=Math.min(V*2**(B-1),X??30000);await T(C)}}}()}}var a5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},i5=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},n5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},_x=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((G)=>encodeURIComponent(G))).join(i5(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=a5(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return wO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},wO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},Ax=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let G=[];Object.entries(S).forEach(([Y,J])=>{G=[...G,Y,$?J:encodeURIComponent(J)]});let L=G.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=n5(x),X=Object.entries(S).map(([G,L])=>wO({allowReserved:$,name:x==="deepObject"?`${j}[${G}]`:G,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var s5=/\{[^{}]+\}/g,t5=({path:$,url:O})=>{let j=O,x=O.match(s5);if(x)for(let S of x){let K=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))K=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let G=$[Z];if(G===void 0||G===null)continue;if(Array.isArray(G)){j=j.replace(S,_x({explode:K,name:Z,style:X,value:G}));continue}if(typeof G==="object"){j=j.replace(S,Ax({explode:K,name:Z,style:X,value:G,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${wO({name:Z,value:G})}`);continue}let L=encodeURIComponent(X==="label"?`.${G}`:G);j=j.replace(S,L)}return j},O6=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=t5({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function z1($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var j6=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var x6={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var S6=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let G=_x({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(G)S.push(G)}else if(typeof Z==="object"){let G=Ax({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(G)S.push(G)}else{let G=wO({allowReserved:X.allowReserved,name:K,value:Z});if(G)S.push(G)}}return S.join("&")}},Z6=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},e5=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function X6($){for(let O of $.security??[]){if(e5($,O.name))continue;let j=await j6(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var I1=($)=>O6({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:S6($.querySerializer),url:$.url}),T1=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=Px($.headers,O.headers),j},o5=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},Px=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?o5(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class Mx{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var G6=()=>({error:new Mx,request:new Mx,response:new Mx}),$4=S6({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),O4={"Content-Type":"application/json"},Xj=($={})=>({...x6,headers:O4,parseAs:"auto",querySerializer:$4,...$});var H1=($={})=>{let O=T1(Xj(),$),j=()=>({...O}),x=(Y)=>{return O=T1(O,Y),j()},S=G6(),K=async(Y)=>{let J={...O,...Y,fetch:Y.fetch??O.fetch??globalThis.fetch,headers:Px(O.headers,Y.headers),serializedBody:void 0};if(J.security)await X6(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let T=J,z=I1(T);return{opts:T,url:z}},Z=async(Y)=>{let J=Y.throwOnError??O.throwOnError,T=Y.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(Y),I={redirect:"follow",...V,body:z1(V)};z=new Request(B,I);for(let U of S.request.fns)if(U)z=await U(z,V);let P=V.fetch;W=await P(z);for(let U of S.response.fns)if(U)W=await U(W,z,V);let D={request:z,response:W};if(W.ok){let U=(V.parseAs==="auto"?Z6(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let N;switch(U){case"arrayBuffer":case"blob":case"text":N=await W[U]();break;case"formData":N=new FormData;break;case"stream":N=W.body;break;case"json":default:N={};break}return V.responseStyle==="data"?N:{data:N,...D}}let H;switch(U){case"arrayBuffer":case"blob":case"formData":case"text":H=await W[U]();break;case"json":{let N=await W.text();H=N?JSON.parse(N):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(U==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let C=await W.text(),w;try{w=JSON.parse(C)}catch{}throw w??C}catch(V){let B=V;for(let I of S.error.fns)if(I)B=await I(B,W,z,Y);if(B=B||{},J)throw B;return T==="data"?void 0:{error:B,request:z,response:W}}},X=(Y)=>(J)=>Z({...J,method:Y}),G=(Y)=>async(J)=>{let{opts:T,url:z}=await K(J);return $6({...T,body:T.body,method:Y,onRequest:async(W,V)=>{let B=new Request(W,V);for(let I of S.request.fns)if(I)B=await I(B,T);return B},serializedBody:z1(T),url:z})};return{buildUrl:(Y)=>I1({...O,...Y}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:G("CONNECT"),delete:G("DELETE"),get:G("GET"),head:G("HEAD"),options:G("OPTIONS"),patch:G("PATCH"),post:G("POST"),put:G("PUT"),trace:G("TRACE")},trace:X("TRACE")}};var K6=H1(Xj());class Y6{client;constructor($){this.client=$?.client??K6}}class Q6{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class Fx extends Y6{static __registry=new Q6;constructor($){super($);Fx.__registry.set(this,$?.key)}proxyRequestHandler($){return($.client??this.client).get({url:"/proxy",...$})}getUnfurl($){return($.client??this.client).get({url:"/unfurl",...$})}getUnfurlBulk($){return($.client??this.client).post({url:"/unfurl/bulk",...$,headers:{"Content-Type":"application/json",...$.headers}})}}var J6={dev:"https://dev.macro.com",prod:"https://macro.com",local:"http://localhost:3000"},R1={dev:{"agent-harness":"https://dev-gateway.macro.com/agent-harness",storage:"https://dev-gateway.macro.com/dss",auth:"https://dev-gateway.macro.com/auth",email:"https://dev-gateway.macro.com/email",calendar:"https://dev-gateway.macro.com/calendar",cognition:"https://dev-gateway.macro.com/cognition",notification:"https://dev-gateway.macro.com/notification",properties:"https://dev-gateway.macro.com/dss",search:"https://dev-gateway.macro.com/dss","scheduled-action":"https://dev-gateway.macro.com/scheduled-action","static-files":"https://static-file-service-dev.macro.com",connection:"https://dev-gateway.macro.com/connection-gateway",contacts:"https://dev-gateway.macro.com/contacts",unfurl:"https://dev-gateway.macro.com/unfurl"},prod:{"agent-harness":"https://gateway.macro.com/agent-harness",storage:"https://gateway.macro.com/dss",auth:"https://gateway.macro.com/auth",email:"https://gateway.macro.com/email",calendar:"https://gateway.macro.com/calendar",cognition:"https://gateway.macro.com/cognition",notification:"https://gateway.macro.com/notification",properties:"https://gateway.macro.com/dss",search:"https://gateway.macro.com/dss","scheduled-action":"https://gateway.macro.com/scheduled-action","static-files":"https://static-file-service.macro.com",connection:"https://gateway.macro.com/connection-gateway",contacts:"https://gateway.macro.com/contacts",unfurl:"https://gateway.macro.com/unfurl"},local:{"agent-harness":"http://localhost:8101",storage:"http://localhost:8086",auth:"http://localhost:8080",email:"http://localhost:8087",calendar:"http://localhost:8088/calendar",cognition:"http://localhost:8101/cognition",notification:"http://localhost:8089",properties:"http://localhost:8086",search:"http://localhost:8086","scheduled-action":"http://localhost:8101/scheduled-action","static-files":"http://localhost:8100",connection:"http://localhost:8082",contacts:"http://localhost:8083",unfurl:"http://localhost:8095"}};function j4($,O){let j=O?.channel_id;return O&&j?{channel:b.byId($,j),thread:new y$($,j,O.thread_id)}:{channel:void 0,thread:void 0}}function P$($,O){return{session:i.byId($,O.session_id),owner:A.byId($,O.owner_id),...j4($,O.origin)}}function qO($,O,j){let x=O.origin?.channel_id;return x&&j?e.byId($,x,j):void 0}function fO($,O){return O?A.byId($,O):void 0}function V6($,O){return c(O).with({event_type:"agent_session.opened"},({metadata:j})=>({event_type:"agent_session.opened",metadata:j,...P$($,j.identity)})).with({event_type:"agent_session.turn_started"},({metadata:j})=>({event_type:"agent_session.turn_started",metadata:j,...P$($,j.identity),actor:fO($,j.actor),announcement:qO($,j.identity,j.announcement_message_id)})).with({event_type:"agent_session.turn_ended"},({metadata:j})=>({event_type:"agent_session.turn_ended",metadata:j,...P$($,j.identity),actor:fO($,j.actor),announcement:qO($,j.identity,j.announcement_message_id)})).with({event_type:"agent_session.command_rejected"},({metadata:j})=>({event_type:"agent_session.command_rejected",metadata:j,...P$($,j.identity),actor:fO($,j.actor),announcement:qO($,j.identity,j.announcement_message_id)})).with({event_type:"agent_session.settled"},({metadata:j})=>({event_type:"agent_session.settled",metadata:j,...P$($,j.identity),actor:fO($,j.last_turn?.actor),announcement:qO($,j.identity,j.last_turn?.announcement_message_id)})).with({event_type:"agent_session.waiting_for_input"},({metadata:j})=>({event_type:"agent_session.waiting_for_input",metadata:j,...P$($,j.identity),announcement:qO($,j.identity,j.announcement_message_id)})).with({event_type:"agent_session.input_received"},({metadata:j})=>({event_type:"agent_session.input_received",metadata:j,...P$($,j.identity)})).with({event_type:"agent_session.mentioned"},({metadata:j})=>({event_type:"agent_session.mentioned",metadata:j,...P$($,j.identity),mentionedBy:fO($,j.mentioned_by),mentioned:j.mentioned.map((x)=>A.byId($,x))})).with({event_type:"agent_session.stopped"},({metadata:j})=>({event_type:"agent_session.stopped",metadata:j,...P$($,j.identity),actor:fO($,j.turn_in_flight?.actor),announcement:qO($,j.identity,j.turn_in_flight?.announcement_message_id)})).with({event_type:"agent_session.renamed"},({metadata:j})=>({event_type:"agent_session.renamed",metadata:j,...P$($,j.identity)})).with({event_type:"agent_session.deleted"},({metadata:j})=>({event_type:"agent_session.deleted",metadata:j,...P$($,j.identity)})).exhaustive((j)=>{console.warn("macro sdk: unknown agent session event",j);return})}var W6="macro|";function C$($,O){return O.startsWith(W6)&&O.length>W6.length?A.byId($,O.toLowerCase()):void 0}function B6($,O){return c(O).with({event_type:"channel.created"},({metadata:j})=>({event_type:"channel.created",metadata:j,channel:b.byId($,j.channel_id),actor:C$($,j.actor),participants:j.participant_user_ids.map((x)=>A.byId($,x))})).with({event_type:"channel.updated"},({metadata:j})=>({event_type:"channel.updated",metadata:j,channel:b.byId($,j.channel_id),actor:C$($,j.actor)})).with({event_type:"channel.deleted"},({metadata:j})=>({event_type:"channel.deleted",metadata:j,channel:b.byId($,j.channel_id),actor:C$($,j.actor)})).with({event_type:"channel.picture_changed"},({metadata:j})=>({event_type:"channel.picture_changed",metadata:j,channel:b.byId($,j.channel_id),actor:C$($,j.actor)})).with({event_type:"channel.participant_added"},({metadata:j})=>({event_type:"channel.participant_added",metadata:j,channel:b.byId($,j.channel_id),addedBy:C$($,j.added_by),addedUsers:j.added_user_ids.map((x)=>A.byId($,x))})).with({event_type:"channel.participant_removed"},({metadata:j})=>({event_type:"channel.participant_removed",metadata:j,channel:b.byId($,j.channel_id),removedBy:A.byId($,j.removed_by),removedUsers:j.removed_user_ids.map((x)=>A.byId($,x))})).exhaustive((j)=>{console.warn("macro sdk: unknown channel event",j);return})}function L6($,O){return c(O).with({event_type:"document.created"},({metadata:j})=>({event_type:"document.created",metadata:j,document:q.byId($,j.document_id),owner:A.byId($,j.owner),project:j.project_id?n.byId($,j.project_id):void 0})).with({event_type:"document.updated"},({metadata:j})=>({event_type:"document.updated",metadata:j,document:q.byId($,j.document_id),owner:A.byId($,j.owner),actor:j.actor_user_id?A.byId($,j.actor_user_id):void 0,project:j.project_id?n.byId($,j.project_id):void 0,previousProject:j.previous_project_id?n.byId($,j.previous_project_id):void 0})).with({event_type:"document.deleted"},({metadata:j})=>({event_type:"document.deleted",metadata:j,document:q.byId($,j.document_id),actor:j.actor_user_id?A.byId($,j.actor_user_id):void 0,project:j.project_id?n.byId($,j.project_id):void 0})).with({event_type:"document.content_uploaded"},({metadata:j})=>({event_type:"document.content_uploaded",metadata:j,document:q.byId($,j.document_id),owner:A.byId($,j.owner)})).with({event_type:"document.sync_content_updated"},({metadata:j})=>({event_type:"document.sync_content_updated",metadata:j,document:q.byId($,j.document_id)})).with({event_type:"document.purged"},({metadata:j})=>({event_type:"document.purged",metadata:j,document:q.byId($,j.document_id)})).with({event_type:"document.copied"},({metadata:j})=>({event_type:"document.copied",metadata:j,document:q.byId($,j.document_id),sourceDocument:q.byId($,j.source_document_id),owner:A.byId($,j.owner),project:j.project_id?n.byId($,j.project_id):void 0})).with({event_type:"document.interaction"},({metadata:j})=>({event_type:"document.interaction",metadata:j,document:q.byId($,j.document_id)})).exhaustive((j)=>{console.warn("macro sdk: unknown document event",j);return})}function bO($,O,j=[]){let x=O.parent;if(x.type==="call")return{type:"call",call:Q$.byId($,x.id),message:m$.byId($,x.id,O.message_id),threadId:x.id};if(x.type==="channel")return{type:"channel",channel:b.byId($,x.id),message:e.byId($,x.id,O.message_id,j),thread:O.thread_id?new y$($,x.id,O.thread_id):void 0};return{type:"document",document:q.byId($,x.id),comment:h$.byId($,x.id,O.message_id),threadId:O.root_id}}function U6($,O){return c(O).with({event_type:"message.posted"},({metadata:j})=>({event_type:"message.posted",metadata:j,target:bO($,j,j.mentions),sender:C$($,j.sender)})).with({event_type:"message.mentioned"},({metadata:j})=>({event_type:"message.mentioned",metadata:j,target:bO($,j),sender:C$($,j.sender)})).with({event_type:"message.patched"},({metadata:j})=>({event_type:"message.patched",metadata:j,target:bO($,j),actor:C$($,j.actor)})).with({event_type:"message.deleted"},({metadata:j})=>({event_type:"message.deleted",metadata:j,target:bO($,j),actor:C$($,j.actor)})).with({event_type:"message.attachment_created"},({metadata:j})=>({event_type:"message.attachment_created",metadata:j,target:bO($,j),actor:C$($,j.actor)})).with({event_type:"message.attachment_removed"},({metadata:j})=>({event_type:"message.attachment_removed",metadata:j,target:bO($,j),actor:C$($,j.actor)})).exhaustive((j)=>{console.warn("macro sdk: unknown message event",j);return})}async function N6($){let O=new TextEncoder,j=await crypto.subtle.importKey("raw",O.encode($.secret),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),x=await crypto.subtle.sign("HMAC",j,O.encode(`${$.timestamp}.${$.rawBody}`));return`v1=${new Uint8Array(x).toHex()}`===$.signature}var x4="webhook.validation.test";function S4($,O){return c(O).with({event_type:Z$.string.startsWith("document.")},(j)=>L6($,j)).with({event_type:Z$.string.startsWith("channel.")},(j)=>B6($,j)).with({event_type:Z$.string.startsWith("message.")},(j)=>U6($,j)).with({event_type:Z$.string.startsWith("agent_session.")},(j)=>V6($,j)).otherwise(()=>{return})}class D1{client;secret;handlers=new Map;constructor($,O){this.client=$;this.secret=O}on($,O){let j=this.handlers.get($)??new Set;return j.add(O),this.handlers.set($,j),()=>j.delete(O)}onSelfMention($){return this.on("message.mentioned",async(O)=>{if(O.metadata.mentioned.entity_id.toLowerCase()!==(await this.client.myPrincipalId()).toLowerCase())return;await $(O)})}async listen($={}){let O=$.filters??this.filtersFromHandlers();if(O.length===0||O.every((K)=>K.events.length===0))throw new f("listen() needs filters — pass filters or register handlers with .on() first");let j=new AbortController;if($.signal)if($.signal.aborted)j.abort();else $.signal.addEventListener("abort",()=>j.abort(),{once:!0});let{stream:x}=await this.client.storage.streamEvents({query:{scope:$.scope??"user",filters:JSON.stringify(O)},signal:j.signal});return(async()=>{try{for await(let K of x)await this.dispatchEvent(K)}catch{if(j.signal.aborted)return;throw new f("event stream failed")}})().catch(()=>{}),()=>{j.abort()}}async handle($,O){if(!this.secret)throw new f("webhookSecret is required to verify incoming webhook deliveries");if(!await N6({secret:this.secret,timestamp:O.timestamp??"",rawBody:$,signature:O.signature??""}))throw new f("invalid webhook signature");if(O.event===x4)return;await this.dispatchEvent(JSON.parse($))}webhook(){if(!this.secret)throw new f("webhookSecret is required to verify incoming webhook deliveries");return async($)=>{return await this.handle(await $.text(),{event:$.headers.get("x-macro-event")??void 0,eventId:$.headers.get("x-macro-event-id")??void 0,timestamp:$.headers.get("x-macro-timestamp")??void 0,signature:$.headers.get("x-macro-signature")??void 0}),new Response("ok")}}filtersFromHandlers(){let $=[...this.handlers.entries()].filter(([,O])=>O.size>0).map(([O])=>O);return $.length>0?[{events:$}]:[]}async dispatchEvent($){let O=typeof $==="string"?JSON.parse($):$;if(O===null||typeof O!=="object"||!("event_type"in O))return;let j=O,x=this.handlers.get(j.event_type);if(!x||x.size===0)return;let S=S4(this.client,j);if(!S)return;await Promise.all([...x].map((K)=>K(S)))}}function z6(){return}var Z4=0,C1;function X4($){C1=$}function N$($,O,j){if(!j&&!C1)return $;let x=(S)=>{for(let K of[C1,j])try{Promise.resolve(K?.(S)).catch(()=>{})}catch{}};return new Proxy($,{get(S,K,Z){let X=Reflect.get(S,K,Z);if(typeof K!=="string"||typeof X!=="function")return X;return async(...G)=>{let L={id:++Z4,service:O,operation:K};x({...L,status:"started"});try{let Y=await Reflect.apply(X,S,G),J=Y!==null&&typeof Y==="object"&&"error"in Y&&Y.error!=null;return x({...L,status:J?"failed":"completed"}),Y}catch(Y){throw x({...L,status:"failed"}),Y}}}})}var T6="x-macro-user-api-key",G4="mak_",_1="mbot_";function K4($){return c($).with(Z$.string.startsWith(_1),()=>{throw Error("bot token passed as a user credential. Use auth: { type: 'bot', token } or MACRO_BOT_TOKEN.")}).with(Z$.string.startsWith(G4),(O)=>[T6,O]).otherwise((O)=>["Authorization",`Bearer ${O}`])}async function I6($){return typeof $==="function"?await $():$}async function Y4($,O,j){return c($).with({type:"bot"},async(x)=>{let S=await I6(x.token);if(!S.startsWith(_1))throw Error("user API key passed as a bot token. Use auth: { type: 'user', apiKey } or MACRO_API_KEY.");let K=[["x-macro-bot-token",S]];if(!j?.hasBotScope)K.push(["x-macro-bot-scope",x.scope??(O?"user":"team")]);if(O)K.push(["x-macro-bot-for-macro-user-id",O]);return K}).with({type:"user",apiKey:Z$.string},({apiKey:x})=>{if(x.startsWith(_1))throw Error("bot token passed as a user credential. Use auth: { type: 'bot', token } or MACRO_BOT_TOKEN.");return[[T6,x]]}).with({type:"user"},async({token:x})=>{return[K4(await I6(x))]}).exhaustive()}class A1{scheduledAction;unfurl;agentHarness;auth;calendar;cognition;contacts;email;notification;properties;search;storage;webAppUrl;wsVerify;events;authConfig;hosts;localPortmap;requestedAs;selfBotRecord;selfPrincipal;constructor($){let O=Q4($),j=O==="local"?z6():void 0,x={...R1[O],...j?.hosts,...$.hosts};this.hosts=x,this.localPortmap=j;let S=typeof process<"u"?{}.MACRO_WEB_URL:void 0;if(this.webAppUrl=$.webAppUrl??S??j?.webAppUrl??J6[O],this.authConfig=J4($),this.requestedAs=$.requestedAs,this.requestedAs&&this.authConfig.type!=="bot")throw Error("requestedAs() requires bot auth — a user token always acts as its own user");this.wsVerify=$.wsVerify,this.scheduledAction=N$(new Bx({client:this.makeClient(x["scheduled-action"])}),"scheduled-action",$.onRequest),this.unfurl=N$(new Fx({client:this.makeClient(x.unfurl)}),"unfurl",$.onRequest),this.agentHarness=N$(new Pj({client:this.makeClient(x["agent-harness"])}),"agent-harness",$.onRequest),this.auth=N$(new fj({client:this.makeClient(x.auth)}),"auth",$.onRequest),this.calendar=N$(new vj({client:this.makeClient(x.calendar)}),"calendar",$.onRequest),this.cognition=N$(new dj({client:this.makeClient(x.cognition)}),"cognition",$.onRequest),this.contacts=N$(new ij({client:this.makeClient(x.contacts)}),"contacts",$.onRequest),this.email=N$(new oj({client:this.makeClient(x.email)}),"email",$.onRequest),this.notification=N$(new Sx({client:this.makeClient(x.notification)}),"notification",$.onRequest),this.properties=N$(new Yx({client:this.makeClient(x.properties)}),"properties",$.onRequest),this.search=N$(new Ix({client:this.makeClient(x.search)}),"search",$.onRequest),this.storage=N$(new Cx({client:this.makeClient(x.storage)}),"storage",$.onRequest);let K=typeof process<"u"?{}.MACRO_WEBHOOK_SECRET:void 0,Z=$.webhookSecret??K;this.events=new D1(this,Z)}hasActingUser(){return this.authConfig.type==="user"||this.requestedAs!==void 0}selfBot(){return this.selfBotRecord??=new vO(this).me().catch(($)=>{throw this.selfBotRecord=void 0,$}),this.selfBotRecord}myPrincipalId(){return this.selfPrincipal??=(this.authConfig.type==="bot"?this.selfBot().then(($)=>`bot|${$.id}`):A.me(this).then(($)=>$.id)).catch(($)=>{throw this.selfPrincipal=void 0,$}),this.selfPrincipal}makeClient($){let O=Zj({baseUrl:$});return O.interceptors.request.use(async(j)=>{let x=await Y4(this.authConfig,this.requestedAs,{hasBotScope:j.headers.has("x-macro-bot-scope")});for(let[S,K]of x)j.headers.set(S,K);return j}),O}}function Q4($){if($.env)return $.env;let O=typeof process<"u"?{}.MACRO_ENV:void 0;if(!O)return"prod";if(!(O in R1))throw Error(`invalid MACRO_ENV "${O}" — expected local, dev, or prod`);return O}function J4($){if($.auth)return $.auth;if($.token)return{type:"user",token:$.token};let O=typeof process<"u"?{}.MACRO_API_KEY:void 0,j=typeof process<"u"?{}.MACRO_BOT_TOKEN:void 0;if(O&&j)throw Error("both MACRO_API_KEY and MACRO_BOT_TOKEN are set — pass auth to new Macro() to pick one");if(j)return{type:"bot",token:j};return{type:"user",token:O??(()=>{throw Error("no Macro credential. Set MACRO_API_KEY (API key or bearer token) or MACRO_BOT_TOKEN, or pass token/auth to new Macro().")})}}class M1{id;constructor($){this.id=$}static byId($){return new M1($)}toJSON(){return{id:this.id}}}class H6{routines;unfurls;agents;initiatives;apiKeys;harnesses;meetings;githubPullRequests;entityMentions;agentSessions;ai;bots;calendar;calls;channels;chats;crm;databases;documents;email;favorites;foreignEntities;forms;notifications;pins;projects;properties;tasks;teams;users;webhooks;workspace;events;webAppUrl;_client;opts;constructor($){this.opts=$;let O=new A1($);this._client=O,this.routines=new I0(O),this.unfurls=new R0(O),this.agents=new bx(O),this.initiatives=new Q0(O),this.apiKeys=new kx(O),this.harnesses=new Y0(O),this.meetings=new J0(O),this.githubPullRequests=new K0(O),this.entityMentions=new x0(O),this.agentSessions=new fx(O),this.ai=new gx(O),this.bots=new vO(O),this.calendar=new yx(O),this.calls=new vx(O),this.channels=new mx(O),this.chats=new cx(O),this.crm=new dx(O),this.databases=new ox(O),this.documents=new $0(O),this.email=new j0(O),this.favorites=new S0(O),this.foreignEntities=new Z0(O),this.forms=new X0(O),this.notifications=new V0(O),this.pins=new W0(O),this.projects=new B0(O),this.properties=new L0(O),this.tasks=new T0(O),this.teams=new H0(O),this.users=new D0(O),this.webhooks=new C0(O),this.workspace=new P0(O),this.events=O.events,this.webAppUrl=O.webAppUrl}myPrincipalId(){return this._client.myPrincipalId()}requestedAs($){return new H6({...this.opts,requestedAs:$.id})}}export{r$ as wrapXml,$$ as toBody,X4 as observeRequests,C6 as msg,D6 as here,a$ as UserApiKey,yO as ToolApproval,U$ as SessionReview,N0 as RoutineExecution,xO as Routine,qx as ReviewItem,G0 as PullRequestChangeset,Jj as PipelineTable,KO as PipelineRow,Vj as PipelineColumn,L$ as MessageThread,T$ as Meeting,ex as MacroOpRefusedError,H6 as Macro,OO as Initiative,zO as HarnessPairing,B$ as Harness,NO as GithubPullRequest,l$ as FormSection,UO as FormResponse,Hj as FormReference,d$ as FormQuestion,VO as FormOption,k$ as Form,LO as EntityMention,o as EntityAccess,JO as EmailFilter,QO as EmailDraft,pO as DraftAttachment,mO as DocumentVersion,GO as DocumentAnchor,aO as DevicePairing,i$ as CrmPipeline,wx as ConversationTurn,kO as CodeExecution,uO as ChatMessage,cO as ChatGeneration,M1 as ChannelPicture,XO as ChannelActivity,w$ as CalendarNote,Kj as AgentConversation,z$ as Agent,BO as AccessRequest};
diff --git a/crates/entity_access/AGENTS.md b/crates/entity_access/AGENTS.md
index 3f4dbb4169..e0a0ebfc24 100644
--- a/crates/entity_access/AGENTS.md
+++ b/crates/entity_access/AGENTS.md
@@ -56,6 +56,9 @@ the entity-access domain service.
## Gotchas
+- Document checks fall back to live calendar-note or optional team grants only
+ when ordinary document access is absent; these grants are authenticated and
+ view-only. Keep the shared SQL visibility policy aligned with calendar note reads.
- `#![deny(missing_docs)]`.
- `EntityAccessReceipt<R: RequiredPermission>` is the only proof a caller
checked access at the right level; domain code downstream (e.g.
diff --git a/crates/entity_access/src/outbound/pg_access_repo.rs b/crates/entity_access/src/outbound/pg_access_repo.rs
index c0ce729105..825db99aa7 100644
--- a/crates/entity_access/src/outbound/pg_access_repo.rs
+++ b/crates/entity_access/src/outbound/pg_access_repo.rs
@@ -70,22 +70,47 @@ impl AccessRepository for PgAccessRepository {
let source_ids = queries::get_user_source_ids(&self.pool, user_id)
.await
.map_err(anyhow_access_error)?;
- let Ok(document_uuid) = document_id.parse::<Uuid>() else {
- return Ok(queries::document_access::get_legacy_document_access(
+ let access = if let Ok(document_uuid) = document_id.parse::<Uuid>() {
+ queries::document_access::get_document_access(
+ &self.pool,
+ &document_uuid,
+ &source_ids,
+ user_id,
+ )
+ .await?
+ } else {
+ queries::document_access::get_legacy_document_access(
&self.pool,
document_id,
&source_ids,
user_id,
)
- .await?);
+ .await?
};
- Ok(queries::document_access::get_document_access(
- &self.pool,
- &document_uuid,
- &source_ids,
- user_id,
+ if access.is_some() || user_id.is_none() {
+ return Ok(access);
+ }
+ let has_note_access = sqlx::query_scalar!(
+ r#"
+ SELECT EXISTS (
+ SELECT 1 FROM calendar_event_notes note
+ JOIN "Document" d ON d.id = note.document_id
+ AND d."deletedAt" IS NULL AND d."fileType" = 'md'
+ WHERE note.document_id = $1 AND (
+ calendar_note_event_visible($2, note.event_id, note.occurrence_key)
+ OR EXISTS (
+ SELECT 1 FROM team_user member
+ WHERE member.team_id = note.team_id AND member.user_id = $2
+ )
+ )
+ ) AS "visible!"
+ "#,
+ document_id,
+ user_id.map(AsRef::as_ref)
)
- .await?)
+ .fetch_one(&self.pool)
+ .await?;
+ Ok(has_note_access.then_some(AccessLevel::View))
}
#[tracing::instrument(err, skip(self))]
diff --git a/crates/macro_db_client/AGENTS.md b/crates/macro_db_client/AGENTS.md
index 63e33a5762..42f3ba60fd 100644
--- a/crates/macro_db_client/AGENTS.md
+++ b/crates/macro_db_client/AGENTS.md
@@ -70,6 +70,10 @@ unreferenced replicas. These additive tables do not change agent-session claims.
## Gotchas
+- `calendar_event_notes` and `calendar_note_event_visible` are shared by calendar
+ note reads and document authorization; keep both consumers on the same policy.
+ The additive migration must precede their service rollout. See
+ [meeting-note access](../../docs/architecture/calendar-meeting-notes.md).
- Migrations deploy before service code: never drop a column/table in the
same PR that removes its last usage (see `docs/development/database.md`).
- Never hand-edit `.sqlx/query-*.json` or invent a migration timestamp.
diff --git a/crates/macro_db_client/migrations/20261023154856_calendar_event_notes.sql b/crates/macro_db_client/migrations/20261023154856_calendar_event_notes.sql
new file mode 100644
index 0000000000..14b10c026c
--- /dev/null
+++ b/crates/macro_db_client/migrations/20261023154856_calendar_event_notes.sql
@@ -0,0 +1,150 @@
+-- Links grant view access only. The markdown document keeps its own ownership,
+-- editor grants, and lifetime. Calendar sync never writes this table.
+CREATE TABLE calendar_event_notes (
+ event_id uuid NOT NULL REFERENCES calendar_events(id) ON DELETE CASCADE,
+ occurrence_key text NOT NULL,
+ document_id text NOT NULL REFERENCES "Document"(id) ON DELETE CASCADE,
+ team_id uuid REFERENCES team(id) ON DELETE SET NULL,
+ user_id text NOT NULL REFERENCES "User"(id) ON DELETE CASCADE,
+ created_at timestamptz NOT NULL DEFAULT now(),
+ PRIMARY KEY (event_id, occurrence_key, document_id)
+);
+
+CREATE INDEX calendar_event_notes_document_idx ON calendar_event_notes (document_id);
+CREATE INDEX calendar_event_notes_team_idx ON calendar_event_notes (team_id) WHERE team_id IS NOT NULL;
+CREATE INDEX calendar_event_notes_user_idx ON calendar_event_notes (user_id);
+
+-- Shared by calendar-note reads and the document authorization boundary. A
+-- grant is checked at read time so leaving a team/channel or hiding an event
+-- revokes inherited access. The caller must be authenticated.
+-- One-time meetings follow the event through a reschedule. Recurring notes
+-- keep the provider's original-start key and never spread to another instance.
+CREATE OR REPLACE FUNCTION calendar_note_link_key(requested_id uuid, occurrence text)
+RETURNS text LANGUAGE sql STABLE AS $$
+ SELECT CASE WHEN cardinality(recurrence_lines) = 0 THEN 'single' ELSE occurrence END
+ FROM calendar_events WHERE id = requested_id;
+$$;
+
+-- Copy identity is corroborated independently of viewer access. A channel grant
+-- on an unrelated fabricated copy must not inject notes into a real meeting.
+CREATE OR REPLACE FUNCTION calendar_note_copies_match(requested_id uuid, candidate_id uuid, occurrence text)
+RETURNS boolean LANGUAGE sql STABLE AS $$
+ SELECT EXISTS (
+ SELECT 1 FROM calendar_events requested
+ JOIN calendar_event_occurrences requested_occurrence
+ ON requested_occurrence.event_id = requested.id AND (requested_occurrence.occurrence_key = occurrence OR (occurrence = 'single' AND cardinality(requested.recurrence_lines) = 0))
+ AND NOT requested_occurrence.is_cancelled
+ LEFT JOIN calendar_event_overrides requested_exception
+ ON requested_exception.event_id = requested.id AND requested_exception.recurrence_id = requested_occurrence.recurrence_id
+ JOIN calendar_events event ON event.id = candidate_id AND event.ical_uid = requested.ical_uid
+ AND lower(event.organizer_email) IS NOT DISTINCT FROM lower(requested.organizer_email)
+ JOIN calendar_event_occurrences event_occurrence
+ ON event_occurrence.event_id = event.id AND (event_occurrence.occurrence_key = occurrence OR (occurrence = 'single' AND cardinality(event.recurrence_lines) = 0))
+ AND NOT event_occurrence.is_cancelled
+ LEFT JOIN calendar_event_overrides event_exception
+ ON event_exception.event_id = event.id AND event_exception.recurrence_id = event_occurrence.recurrence_id
+ WHERE requested.id = requested_id AND requested.status <> 'cancelled' AND NOT requested.is_snapshot
+ AND event.status <> 'cancelled' AND NOT event.is_snapshot
+ AND (cardinality(event.recurrence_lines) = 0) = (cardinality(requested.recurrence_lines) = 0)
+ AND COALESCE(requested_exception.status, 'confirmed') <> 'cancelled'
+ AND COALESCE(event_exception.status, 'confirmed') <> 'cancelled'
+ -- A UID is provider input, not an authorization credential. A different
+ -- inbox's copy must belong to an organizer/guest on the linked copy.
+ AND (event.source_link_id = requested.source_link_id OR EXISTS (
+ SELECT 1 FROM email_links inbox WHERE inbox.id = event.source_link_id
+ AND (lower(inbox.email_address) = lower(requested.organizer_email) OR (
+ COALESCE(requested_exception.attendees_overridden, false) AND EXISTS (
+ SELECT 1 FROM calendar_event_override_attendees guest
+ WHERE guest.event_id = requested.id AND guest.recurrence_id = requested_exception.recurrence_id
+ AND lower(guest.email) = lower(inbox.email_address)
+ )
+ ) OR (NOT COALESCE(requested_exception.attendees_overridden, false) AND EXISTS (
+ SELECT 1 FROM calendar_event_attendees guest
+ WHERE guest.event_id = requested.id AND lower(guest.email) = lower(inbox.email_address)
+ )))
+ ))
+ -- Corroborate in both directions: a fabricated copy cannot inject
+ -- notes into a real meeting merely by claiming its organizer/UID.
+ AND (event.source_link_id = requested.source_link_id OR EXISTS (
+ SELECT 1 FROM email_links inbox WHERE inbox.id = requested.source_link_id
+ AND (lower(inbox.email_address) = lower(event.organizer_email) OR (
+ COALESCE(event_exception.attendees_overridden, false) AND EXISTS (
+ SELECT 1 FROM calendar_event_override_attendees guest
+ WHERE guest.event_id = event.id AND guest.recurrence_id = event_exception.recurrence_id
+ AND lower(guest.email) = lower(inbox.email_address)
+ )
+ ) OR (NOT COALESCE(event_exception.attendees_overridden, false) AND EXISTS (
+ SELECT 1 FROM calendar_event_attendees guest
+ WHERE guest.event_id = event.id AND lower(guest.email) = lower(inbox.email_address)
+ )))
+ ))
+ );
+$$;
+
+CREATE OR REPLACE FUNCTION calendar_note_event_visible(viewer_id text, requested_id uuid, occurrence text)
+RETURNS boolean LANGUAGE sql STABLE AS $$
+ SELECT viewer_id IS NOT NULL AND EXISTS (
+ SELECT 1 FROM calendar_events requested
+ JOIN calendar_events event ON event.ical_uid = requested.ical_uid
+ AND lower(event.organizer_email) IS NOT DISTINCT FROM lower(requested.organizer_email)
+ WHERE requested.id = requested_id
+ AND calendar_note_copies_match(requested.id, event.id, occurrence)
+ AND (
+ event.owner_id = viewer_id
+ OR EXISTS (
+ SELECT 1 FROM macro_user_links link
+ WHERE link.link_id = event.source_link_id AND link.primary_macro_id = viewer_id
+ )
+ OR (
+ event.visibility IN ('default', 'public')
+ AND NOT EXISTS (
+ SELECT 1 FROM calendar_event_sources source
+ CROSS JOIN LATERAL jsonb_array_elements(source.normalized_payload->'occurrences') item(value)
+ CROSS JOIN LATERAL jsonb_array_elements(source.normalized_payload->'overrides') exception(value)
+ WHERE source.event_id = event.id AND (item.value->>'occurrenceKey' = occurrence OR (occurrence = 'single' AND cardinality(event.recurrence_lines) = 0))
+ AND exception.value->>'recurrenceId' = item.value->>'recurrenceId'
+ AND (exception.value->>'visibility' IN ('private', 'confidential')
+ OR exception.value->>'status' = 'cancelled')
+ )
+ AND EXISTS (
+ SELECT 1 FROM entity_access grant_row
+ JOIN comms_channel_participants participant
+ ON participant.channel_id::text = grant_row.source_id
+ AND participant.user_id = viewer_id AND participant.left_at IS NULL
+ WHERE grant_row.entity_id = event.id
+ AND grant_row.entity_type = 'calendar_event' AND grant_row.source_type = 'channel'
+ )
+ )
+ OR EXISTS (
+ SELECT 1 FROM calendar_event_sources source
+ JOIN calendars calendar ON calendar.id = source.calendar_id AND NOT calendar.is_deleted
+ AND calendar.synced_at IS NOT NULL AND calendar.last_sync_error IS NULL
+ AND calendar.snapshot_normalization_version >= 1
+ AND source.provider_access_role IS NOT NULL
+ AND source.provider_access_role = calendar.access_role
+ JOIN calendar_accounts account ON account.id = source.account_id
+ AND account.sync_status IN ('ready', 'syncing') AND account.last_sync_error IS NULL
+ AND account.last_synced_at > now() - interval '15 minutes'
+ JOIN calendar_team_sharing policy ON policy.sharing = 'all'
+ AND (policy.user_id = account.owner_id OR EXISTS (
+ SELECT 1 FROM macro_user_links link
+ WHERE link.link_id = account.email_link_id AND link.primary_macro_id = policy.user_id
+ ))
+ JOIN team_user sharer ON sharer.user_id = policy.user_id
+ JOIN team_user viewer ON viewer.team_id = sharer.team_id AND viewer.user_id = viewer_id
+ CROSS JOIN LATERAL jsonb_array_elements(source.normalized_payload->'occurrences') item(value)
+ WHERE source.event_id = event.id
+ AND source.normalized_payload->'event'->>'status' <> 'cancelled'
+ AND source.normalized_payload->'event'->>'visibility' IN ('default', 'public')
+ AND (item.value->>'occurrenceKey' = occurrence OR (occurrence = 'single' AND cardinality(event.recurrence_lines) = 0))
+ AND NOT COALESCE((item.value->>'isCancelled')::boolean, false)
+ AND NOT EXISTS (
+ SELECT 1 FROM jsonb_array_elements(source.normalized_payload->'overrides') exception(value)
+ WHERE exception.value->>'recurrenceId' = item.value->>'recurrenceId'
+ AND (exception.value->>'visibility' IN ('private', 'confidential')
+ OR exception.value->>'status' = 'cancelled')
+ )
+ )
+ )
+ );
+$$;
diff --git a/docs/agent-guide/calendar.md b/docs/agent-guide/calendar.md
index 1eb98ebdab..15ce8b5c9d 100644
--- a/docs/agent-guide/calendar.md
+++ b/docs/agent-guide/calendar.md
@@ -1,5 +1,78 @@
# Calendar
+## Meeting notes
+
+Meeting notes require `enable-calendar-meeting-notes`. It is on automatically in
+dev; production uses PostHog, with an initial rollout intended for `@macro.com`
+users. `VITE_ENABLE_CALENDAR_MEETING_NOTES=true` or `false` overrides it locally.
+With the flag off, event notes and document Share meeting-link controls do not
+mount or request note data, on desktop or phone. The flag does not revoke saved
+meeting/team grants or change API permissions.
+
+Open a live meeting's details and choose **Create** beside **Meeting notes**.
+This creates a Markdown document named after the meeting, links it with meeting
+viewer access, and opens it immediately. Team access starts off. A meeting can
+have multiple notes; **Create** and **Link** remain on the section title row
+so you can keep creating notes or linking existing documents.
+
+Choose **Link** to search your markdown documents, select one, review
+the sharing explanation, and optionally include your existing team before
+**Link note**. Team access starts off for each note. Recurring meetings link only
+the displayed occurrence. Notes on a
+one-time meeting follow it when its date or time changes.
+Existing document editors and other sharing keep their access.
+Notes use the event details' existing row layout and controls. Team choices come
+from current Macro team memberships; they do not introduce departments or subteams.
+
+Open the linked title to read the original document. On desktop it opens in a
+new split; on mobile it replaces the calendar pane and closes event details.
+Opening a note leaves focus available to the document as it mounts; dismissing
+desktop details normally returns focus to the calendar event.
+Meeting access and occurrence scope are explained in the linking/access dialog;
+each note shows any additional team audience. Document owners use **Options →
+Manage access** to change that team, or **Options → Unlink from meeting** to remove
+this meeting's grants without deleting the document. Keep access explanations as
+plain text and actions labeled.
+In the linking dialog, only the document results scroll. The meeting context,
+sharing controls, and action buttons stay visible, including in a short viewport.
+If the owner has since left the selected team, **Remove team access** still works.
+Failed saves retain the selection and audience for retry; dismissing starts fresh.
+If creation succeeds but linking fails, **Retry linking** reuses the saved document;
+**Open saved note** lets you continue editing before the link is confirmed. Closing
+details never deletes that document; it remains in Drive. Changing the selected
+meeting or account prevents a late creation result from navigating away from the
+new selection.
+
+Owners can also open the markdown document's **Share** panel and find **Meeting
+links** (inside **Link** on mobile). Every saved link remains removable here even
+if the meeting was cancelled, fell outside the sync window, or stopped being
+shared with the owner. **Unlink** asks before removing its meeting/team grants.
+Unavailable meetings use a safe label rather than revealing private details.
+
+Full-detail team events expose the same note controls; provider actions such as
+editing the event or RSVPing stay unavailable. Busy-only team entries and
+imported snapshots have no meeting-note controls.
+Inherited access follows current meeting details and requires a synced live
+occurrence. If the provider hides its guest list, some guests need a direct
+document share. Independent team sharing lasts until the link is removed or the
+viewer leaves that team; it does not make the calendar event visible to that team.
+
+Verify on desktop and phone: create and open notes, add a second note, retry a failed
+link without duplicating the new document, link an existing note with team unchecked,
+add/remove a team, and unlink while keeping the document. On desktop, hover a note
+title and select a neighboring note while its tooltip is visible. The
+backend-free browser suite mounts the real event popover and mobile drawer with
+sample data and preview service adapters. It is
+`apps/web/src/features/calendar-notes/browser-test/playwright.config.ts`.
+API permission cases are covered in `crates/calendar_events/src/outbound/pg/test/notes.rs`.
+The fixture accepts `?notes=off` to check the event details without notes.
+Use `?team=details` or `?team=busy` to check team visibility boundaries.
+
+Browser fixture screenshots: [desktop](media/calendar-notes/desktop.png) ·
+[phone](media/calendar-notes/phone.png) ·
+[desktop picker](media/calendar-notes/link-desktop.png) ·
+[phone picker](media/calendar-notes/link-phone.png).
+
## Calendar — `/app/calendar/<month-or-week-or-day>`
Microsoft calendars use the same editor and calendar views after calendar consent.
diff --git a/docs/agent-guide/documents.md b/docs/agent-guide/documents.md
index da20076741..9611b0d8c4 100644
--- a/docs/agent-guide/documents.md
+++ b/docs/agent-guide/documents.md
@@ -4,6 +4,17 @@ The document header has separate Share, Copy Share Link, and Side Panel buttons.
They are borderless with a soft rounded background on hover. Share opens the
sharing dialog; copying a link is a separate action.
+With `enable-calendar-meeting-notes` enabled, owned markdown documents' Share
+panel also lists **Meeting links** (under the **Link** tab on mobile).
+Each shows its occurrence and optional team view grant.
+Use **Unlink** and confirm to remove that grant without deleting the document.
+This remains available when the meeting is cancelled or no longer shared with
+you; unavailable meeting details are hidden. See [Calendar meeting notes](calendar.md#meeting-notes).
+Turning the flag off does not revoke saved grants. If meeting access cannot be
+checked, the share status uses **Restricted** instead of claiming **Just me**;
+known public, team, or shared access still appears.
+This status follows the current document and account when navigating with Share open.
+
Verify **Public → View** links in a fresh signed-out browser context. The
`/app/drive/md/<id>` route (including folder/tab document links and legacy
`/app/md/<id>` redirects) must show the document without private Drive lists or
diff --git a/docs/agent-guide/media/calendar-notes/desktop.png b/docs/agent-guide/media/calendar-notes/desktop.png
new file mode 100644
index 0000000000..614a34f057
Binary files /dev/null and b/docs/agent-guide/media/calendar-notes/desktop.png differ
diff --git a/docs/agent-guide/media/calendar-notes/link-desktop.png b/docs/agent-guide/media/calendar-notes/link-desktop.png
new file mode 100644
index 0000000000..d3b5ee0c8b
Binary files /dev/null and b/docs/agent-guide/media/calendar-notes/link-desktop.png differ
diff --git a/docs/agent-guide/media/calendar-notes/link-phone.png b/docs/agent-guide/media/calendar-notes/link-phone.png
new file mode 100644
index 0000000000..53bdc9d57f
Binary files /dev/null and b/docs/agent-guide/media/calendar-notes/link-phone.png differ
diff --git a/docs/agent-guide/media/calendar-notes/phone.png b/docs/agent-guide/media/calendar-notes/phone.png
new file mode 100644
index 0000000000..481e5e9e0c
Binary files /dev/null and b/docs/agent-guide/media/calendar-notes/phone.png differ
diff --git a/docs/architecture/calendar-meeting-notes.md b/docs/architecture/calendar-meeting-notes.md
new file mode 100644
index 0000000000..f649c0a433
--- /dev/null
+++ b/docs/architecture/calendar-meeting-notes.md
@@ -0,0 +1,109 @@
+# Calendar meeting notes
+
+Meeting notes link Markdown documents to a one-time meeting or one occurrence of a
+recurring meeting. Each occurrence can have multiple notes, created from event
+details or linked from the owner's existing documents.
+They reuse the document's content, editor, collaboration, and ownership; calendar
+sync does not copy or own that content.
+
+## Access contract
+
+- The document owner explicitly links it and optionally chooses one current team.
+- Authenticated full-detail meeting viewers inherit **view** access. Busy-only
+ visibility, snapshots, and anonymous links do not qualify.
+- The selected team's current members independently receive **view** access.
+ Team access does not expose the calendar event itself.
+- `team_user_user_id_unique` restricts each account to one current team; the
+ optional checkbox uses that membership, with no subteam picker.
+- Existing ownership, editor, public, and other document grants remain unchanged.
+- Unlinking removes only this occurrence's meeting/team grant, never the document.
+ An owner can revoke it from the document's Share panel, SDK, or API even after
+ losing meeting access.
+
+`calendar_event_notes` stores `(event_id, occurrence_key, document_id)`, an optional
+`team_id`, and the linking user. Recurring links use the original-start key, which
+survives rescheduling that occurrence. One-time meetings use the canonical key
+`single`, so moving their start time preserves notes and old API handles. The API
+accepts the current calendar occurrence key for either kind; owner link listings
+return `single` for a one-time meeting. Links intentionally have no occurrence foreign key: provider
+sync replaces occurrence projections. Event, document, and linking-user deletion
+cascade links; team deletion clears only the additional audience.
+
+## Shared authorization
+
+`calendar_note_event_visible` is used by both note reads and the ordinary document
+access boundary. It checks the primary database on every authorization. A caller
+must have a live full-detail copy through inbox ownership/delegation, a current
+channel grant, or current full-detail team calendar sharing. Team projections
+also require fresh, successful source snapshots and non-private event/override
+visibility. Existing document permissions are checked first; the fallback never
+elevates above view.
+
+Different inbox copies have different event IDs. Matching iCalendar UID and
+organizer alone is insufficient: each inbox must be corroborated by the other
+copy's organizer or effective occurrence guest list. This prevents both reading
+real notes from a fabricated event and injecting notes into a real meeting.
+`calendar_note_copies_match` also checks the requested event against the note
+anchor directly, even if the viewer separately has access to both meetings.
+Both copies must have a live materialized occurrence. Provider cancellation
+often removes an instance rather than storing a cancelled row; missing instances
+therefore fail closed. If an old occurrence leaves the sync window, its inherited
+grant stops until it is synced again. Durable links and independent document/team
+grants remain. Hidden guest lists may also require an explicit document share.
+
+Writes use an owner-level document receipt. Only live markdown is accepted;
+additional team sharing requires current membership. A document-scoped advisory
+transaction lock serializes link/unlink across equivalent inbox copies. Relinking
+updates the existing grant and removes duplicates across those copies.
+
+## Surface and API
+
+The remote web flag `enable-calendar-meeting-notes` gates both event-details
+surfaces and document Share meeting-link management before their query sources
+mount. It defaults on in development; production falls through to PostHog, with
+the initial rollout intended for `@macro.com` users. The local override is
+`VITE_ENABLE_CALENDAR_MEETING_NOTES`. This is a UI rollout, not an authorization
+boundary: backend/SDK operations and persisted grants retain the access contract
+above when the web flag is off.
+The Share panel retains known shared status and otherwise uses a neutral
+restricted-link label while meeting access cannot be checked with the flag off.
+
+The web feature lives in `apps/web/src/features/calendar-notes`, with an injected
+data source, query adapter, controller, and presentational view. It mounts within
+desktop and mobile event details. Its shared dialog becomes a phone sheet with
+`Dialog.contentOwnsScroll`: only document results scroll, while context, sharing,
+and actions stay visible. Choices survive failures. Note options use labeled menu
+actions; the host dialog guard follows both the menu and access dialog, and clears
+when a note disappears during a live refresh.
+**Create** and **Link** stay beside the section title so additional notes can be
+added without leaving the meeting. **Create** uses the standard Markdown creation
+flow, links the resulting document with no team grant, then opens the editor. It
+captures the account and occurrence before creation starts, suppresses duplicate
+clicks, and retains the created document for retry if linking fails. A disposed
+view never navigates on a late result. There is no separate calendar-owned content
+store or create endpoint.
+The document Share panel also lists owner-only durable links and offers inline
+unlink confirmation. That list does not require current meeting access. It uses
+generic labels for inaccessible or indirectly shared meetings, so it cannot reveal
+a richer canonical event title through a restricted provider projection.
+
+The calendar service mounts these authenticated routes even when provider sync is
+disabled. Every response is private and non-cacheable:
+
+| Method | Path | Purpose |
+| --- | --- | --- |
+| GET | `/meeting-notes/documents?query=` | Up to 30 owned markdown suggestions and current teams |
+| GET | `/meeting-notes/documents/{document_id}/links` | Owner-only durable grants, including unavailable meetings |
+| GET | `/events/{event_id}/notes?occurrenceKey=` | Notes visible through this occurrence |
+| PUT | `/events/{event_id}/notes/{document_id}?occurrenceKey=` | Link/update with `{ "teamId": null }` or a team UUID |
+| DELETE | `/events/{event_id}/notes/{document_id}?occurrenceKey=` | Idempotently unlink the owned document |
+
+The gateway prefixes these paths with `/calendar`. The SDK exposes
+`calendar.noteDocuments`, `CalendarEvent.notes`, `CalendarEvent.linkNote`,
+`Document.meetingNotes`, `CalendarNote.setTeam`, and `CalendarNote.unlink`. Event methods accept the
+occurrence record returned by calendar reads and reject an event mismatch.
+
+Deploy the additive migration before the updated calendar/document services and
+web client. Operation spans use `calendar.notes.*`; the ordinary authenticated
+service client and HTTP middleware propagate trace context. Browser fixtures use
+an in-memory source, while SQLx tests exercise real authorization and migrations.
diff --git a/packages/code-mode-sdk/AGENTS.md b/packages/code-mode-sdk/AGENTS.md
index eca6e3f265..b46ba77456 100644
--- a/packages/code-mode-sdk/AGENTS.md
+++ b/packages/code-mode-sdk/AGENTS.md
@@ -28,3 +28,5 @@ Run from this directory after installing the root workspace and the standalone
must match the public SDK; edit source and regenerate them together.
Use the repository's pinned Bun version (via `nix develop`); different Bun
bundlers produce different checked-in output even from identical SDK source.
+Run SDK-docs and code-mode generated-output checks sequentially; both render into
+`packages/sdk-docs/dist/docs`.
diff --git a/packages/sdk-docs/reference/generated/calendar/types.gen/README.md b/packages/sdk-docs/reference/generated/calendar/types.gen/README.md
index 1e76d416f8..d68bedcaeb 100644
--- a/packages/sdk-docs/reference/generated/calendar/types.gen/README.md
+++ b/packages/sdk-docs/reference/generated/calendar/types.gen/README.md
@@ -63,6 +63,13 @@
- [DiscardCalendarReplacementErrors](type-aliases/DiscardCalendarReplacementErrors.md)
- [DiscardCalendarReplacementResponse](type-aliases/DiscardCalendarReplacementResponse.md)
- [DiscardCalendarReplacementResponses](type-aliases/DiscardCalendarReplacementResponses.md)
+- [DocumentNoteLink](type-aliases/DocumentNoteLink.md)
+- [DocumentNoteLinksData](type-aliases/DocumentNoteLinksData.md)
+- [DocumentNoteLinksResponse](type-aliases/DocumentNoteLinksResponse.md)
+- [DocumentNoteLinksResponses](type-aliases/DocumentNoteLinksResponses.md)
+- [EventNotesData](type-aliases/EventNotesData.md)
+- [EventNotesResponse](type-aliases/EventNotesResponse.md)
+- [EventNotesResponses](type-aliases/EventNotesResponses.md)
- [EventReminderOverride](type-aliases/EventReminderOverride.md)
- [EventReminders](type-aliases/EventReminders.md)
- [EventStatus](type-aliases/EventStatus.md)
@@ -86,12 +93,23 @@
- [InviteCalendarEventGuestsRequest](type-aliases/InviteCalendarEventGuestsRequest.md)
- [InviteCalendarEventGuestsResponse](type-aliases/InviteCalendarEventGuestsResponse.md)
- [InviteCalendarEventGuestsResponses](type-aliases/InviteCalendarEventGuestsResponses.md)
+- [LinkEventNoteData](type-aliases/LinkEventNoteData.md)
+- [LinkEventNoteResponse](type-aliases/LinkEventNoteResponse.md)
+- [LinkEventNoteResponses](type-aliases/LinkEventNoteResponses.md)
+- [LinkNoteRequest](type-aliases/LinkNoteRequest.md)
- [ListCalendarsData](type-aliases/ListCalendarsData.md)
- [ListCalendarsError](type-aliases/ListCalendarsError.md)
- [ListCalendarsErrors](type-aliases/ListCalendarsErrors.md)
- [ListCalendarsResponse](type-aliases/ListCalendarsResponse.md)
- [ListCalendarsResponse2](type-aliases/ListCalendarsResponse2.md)
- [ListCalendarsResponses](type-aliases/ListCalendarsResponses.md)
+- [MeetingNote](type-aliases/MeetingNote.md)
+- [NoteDocument](type-aliases/NoteDocument.md)
+- [NoteDocumentsData](type-aliases/NoteDocumentsData.md)
+- [NoteDocumentsResponse](type-aliases/NoteDocumentsResponse.md)
+- [NoteDocumentsResponses](type-aliases/NoteDocumentsResponses.md)
+- [NotePicker](type-aliases/NotePicker.md)
+- [NoteTeam](type-aliases/NoteTeam.md)
- [OutOfOfficeAutoDeclineMode](type-aliases/OutOfOfficeAutoDeclineMode.md)
- [OutOfOfficeProperties](type-aliases/OutOfOfficeProperties.md)
- [PrepareCalendarReplacementData](type-aliases/PrepareCalendarReplacementData.md)
@@ -122,6 +140,9 @@
- [SetTeamSharingResponses](type-aliases/SetTeamSharingResponses.md)
- [TeamCalendarSharing](type-aliases/TeamCalendarSharing.md)
- [TeamCalendarSharingBody](type-aliases/TeamCalendarSharingBody.md)
+- [UnlinkEventNoteData](type-aliases/UnlinkEventNoteData.md)
+- [UnlinkEventNoteResponse](type-aliases/UnlinkEventNoteResponse.md)
+- [UnlinkEventNoteResponses](type-aliases/UnlinkEventNoteResponses.md)
- [UpdateCalendarEventData](type-aliases/UpdateCalendarEventData.md)
- [UpdateCalendarEventError](type-aliases/UpdateCalendarEventError.md)
- [UpdateCalendarEventErrors](type-aliases/UpdateCalendarEventErrors.md)
diff --git a/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/DocumentNoteLink.md b/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/DocumentNoteLink.md
new file mode 100644
index 0000000000..a73a8c1be4
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/DocumentNoteLink.md
@@ -0,0 +1,15 @@
+# Type Alias: DocumentNoteLink
+
+> **DocumentNoteLink** = \{ `documentName`: `string`; `eventId`: `string`; `eventTitle`: `string`; `occurrenceKey`: `string`; `team?`: `null` \| [`NoteTeam`](NoteTeam.md); \}
+
+An owner's durable sharing link, including meetings they can no longer open.
+
+## Properties
+
+| Property | Type | Description |
+| ------ | ------ | ------ |
+| <a id="property-documentname"></a> `documentName` | `string` | Current name of the owned markdown document. |
+| <a id="property-eventid"></a> `eventId` | `string` | Linked calendar copy. |
+| <a id="property-eventtitle"></a> `eventTitle` | `string` | Current title, or a safe placeholder when meeting details are unavailable. |
+| <a id="property-occurrencekey"></a> `occurrenceKey` | `string` | Original occurrence start, or `single` for a one-time meeting. |
+| <a id="property-team"></a> `team?` | `null` \| [`NoteTeam`](NoteTeam.md) | - |
diff --git a/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/DocumentNoteLinksData.md b/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/DocumentNoteLinksData.md
new file mode 100644
index 0000000000..5fce9d2ded
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/DocumentNoteLinksData.md
@@ -0,0 +1,13 @@
+# Type Alias: DocumentNoteLinksData
+
+> **DocumentNoteLinksData** = \{ `body?`: `never`; `path`: \{ `document_id`: `string`; \}; `query?`: `never`; `url`: `"/meeting-notes/documents/{document_id}/links"`; \}
+
+## Properties
+
+| Property | Type |
+| ------ | ------ |
+| <a id="property-body"></a> `body?` | `never` |
+| <a id="property-path"></a> `path` | \{ `document_id`: `string`; \} |
+| `path.document_id` | `string` |
+| <a id="property-query"></a> `query?` | `never` |
+| <a id="property-url"></a> `url` | `"/meeting-notes/documents/{document_id}/links"` |
diff --git a/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/DocumentNoteLinksResponse.md b/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/DocumentNoteLinksResponse.md
new file mode 100644
index 0000000000..46bb67808f
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/DocumentNoteLinksResponse.md
@@ -0,0 +1,3 @@
+# Type Alias: DocumentNoteLinksResponse
+
+> **DocumentNoteLinksResponse** = [`DocumentNoteLinksResponses`](DocumentNoteLinksResponses.md)\[keyof [`DocumentNoteLinksResponses`](DocumentNoteLinksResponses.md)\]
diff --git a/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/DocumentNoteLinksResponses.md b/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/DocumentNoteLinksResponses.md
new file mode 100644
index 0000000000..c689fb87fb
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/DocumentNoteLinksResponses.md
@@ -0,0 +1,9 @@
+# Type Alias: DocumentNoteLinksResponses
+
+> **DocumentNoteLinksResponses** = \{ `200`: [`DocumentNoteLink`](DocumentNoteLink.md)[]; \}
+
+## Properties
+
+| Property | Type |
+| ------ | ------ |
+| <a id="property-200"></a> `200` | [`DocumentNoteLink`](DocumentNoteLink.md)[] |
diff --git a/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/EventNotesData.md b/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/EventNotesData.md
new file mode 100644
index 0000000000..766f17f78a
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/EventNotesData.md
@@ -0,0 +1,14 @@
+# Type Alias: EventNotesData
+
+> **EventNotesData** = \{ `body?`: `never`; `path`: \{ `event_id`: `string`; \}; `query`: \{ `occurrenceKey`: `string`; \}; `url`: `"/events/{event_id}/notes"`; \}
+
+## Properties
+
+| Property | Type | Description |
+| ------ | ------ | ------ |
+| <a id="property-body"></a> `body?` | `never` | - |
+| <a id="property-path"></a> `path` | \{ `event_id`: `string`; \} | - |
+| `path.event_id` | `string` | - |
+| <a id="property-query"></a> `query` | \{ `occurrenceKey`: `string`; \} | - |
+| `query.occurrenceKey` | `string` | Stable occurrence key returned by the calendar read API. |
+| <a id="property-url"></a> `url` | `"/events/{event_id}/notes"` | - |
diff --git a/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/EventNotesResponse.md b/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/EventNotesResponse.md
new file mode 100644
index 0000000000..07ff73a220
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/EventNotesResponse.md
@@ -0,0 +1,3 @@
+# Type Alias: EventNotesResponse
+
+> **EventNotesResponse** = [`EventNotesResponses`](EventNotesResponses.md)\[keyof [`EventNotesResponses`](EventNotesResponses.md)\]
diff --git a/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/EventNotesResponses.md b/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/EventNotesResponses.md
new file mode 100644
index 0000000000..ab717451d6
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/EventNotesResponses.md
@@ -0,0 +1,9 @@
+# Type Alias: EventNotesResponses
+
+> **EventNotesResponses** = \{ `200`: [`MeetingNote`](MeetingNote.md)[]; \}
+
+## Properties
+
+| Property | Type |
+| ------ | ------ |
+| <a id="property-200"></a> `200` | [`MeetingNote`](MeetingNote.md)[] |
diff --git a/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/LinkEventNoteData.md b/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/LinkEventNoteData.md
new file mode 100644
index 0000000000..48c3aeda8c
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/LinkEventNoteData.md
@@ -0,0 +1,15 @@
+# Type Alias: LinkEventNoteData
+
+> **LinkEventNoteData** = \{ `body`: [`LinkNoteRequest`](LinkNoteRequest.md); `path`: \{ `document_id`: `string`; `event_id`: `string`; \}; `query`: \{ `occurrenceKey`: `string`; \}; `url`: `"/events/{event_id}/notes/{document_id}"`; \}
+
+## Properties
+
+| Property | Type | Description |
+| ------ | ------ | ------ |
+| <a id="property-body"></a> `body` | [`LinkNoteRequest`](LinkNoteRequest.md) | - |
+| <a id="property-path"></a> `path` | \{ `document_id`: `string`; `event_id`: `string`; \} | - |
+| `path.document_id` | `string` | - |
+| `path.event_id` | `string` | - |
+| <a id="property-query"></a> `query` | \{ `occurrenceKey`: `string`; \} | - |
+| `query.occurrenceKey` | `string` | Stable occurrence key returned by the calendar read API. |
+| <a id="property-url"></a> `url` | `"/events/{event_id}/notes/{document_id}"` | - |
diff --git a/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/LinkEventNoteResponse.md b/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/LinkEventNoteResponse.md
new file mode 100644
index 0000000000..cc386b249a
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/LinkEventNoteResponse.md
@@ -0,0 +1,3 @@
+# Type Alias: LinkEventNoteResponse
+
+> **LinkEventNoteResponse** = [`LinkEventNoteResponses`](LinkEventNoteResponses.md)\[keyof [`LinkEventNoteResponses`](LinkEventNoteResponses.md)\]
diff --git a/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/LinkEventNoteResponses.md b/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/LinkEventNoteResponses.md
new file mode 100644
index 0000000000..95d8459e3c
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/LinkEventNoteResponses.md
@@ -0,0 +1,9 @@
+# Type Alias: LinkEventNoteResponses
+
+> **LinkEventNoteResponses** = \{ `204`: `void`; \}
+
+## Properties
+
+| Property | Type |
+| ------ | ------ |
+| <a id="property-204"></a> `204` | `void` |
diff --git a/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/LinkNoteRequest.md b/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/LinkNoteRequest.md
new file mode 100644
index 0000000000..6d3fef55ef
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/LinkNoteRequest.md
@@ -0,0 +1,11 @@
+# Type Alias: LinkNoteRequest
+
+> **LinkNoteRequest** = \{ `teamId?`: `string` \| `null`; \}
+
+Optional additional view access for one team.
+
+## Properties
+
+| Property | Type | Description |
+| ------ | ------ | ------ |
+| <a id="property-teamid"></a> `teamId?` | `string` \| `null` | Null means the meeting audience only. |
diff --git a/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/MeetingNote.md b/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/MeetingNote.md
new file mode 100644
index 0000000000..3284bbe960
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/MeetingNote.md
@@ -0,0 +1,14 @@
+# Type Alias: MeetingNote
+
+> **MeetingNote** = \{ `canManage`: `boolean`; `documentId`: `string`; `name`: `string`; `team?`: `null` \| [`NoteTeam`](NoteTeam.md); \}
+
+One linked document and the extra access this link grants.
+
+## Properties
+
+| Property | Type | Description |
+| ------ | ------ | ------ |
+| <a id="property-canmanage"></a> `canManage` | `boolean` | Whether this viewer can change this document's sharing. |
+| <a id="property-documentid"></a> `documentId` | `string` | Markdown document identity. |
+| <a id="property-name"></a> `name` | `string` | Current document name. |
+| <a id="property-team"></a> `team?` | `null` \| [`NoteTeam`](NoteTeam.md) | - |
diff --git a/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/NoteDocument.md b/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/NoteDocument.md
new file mode 100644
index 0000000000..ee48c54810
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/NoteDocument.md
@@ -0,0 +1,12 @@
+# Type Alias: NoteDocument
+
+> **NoteDocument** = \{ `documentId`: `string`; `name`: `string`; \}
+
+A document available in the note picker.
+
+## Properties
+
+| Property | Type | Description |
+| ------ | ------ | ------ |
+| <a id="property-documentid"></a> `documentId` | `string` | Markdown document identity. |
+| <a id="property-name"></a> `name` | `string` | Current document name, never a copied title. |
diff --git a/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/NoteDocumentsData.md b/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/NoteDocumentsData.md
new file mode 100644
index 0000000000..46586ded89
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/NoteDocumentsData.md
@@ -0,0 +1,13 @@
+# Type Alias: NoteDocumentsData
+
+> **NoteDocumentsData** = \{ `body?`: `never`; `path?`: `never`; `query?`: \{ `query?`: `string`; \}; `url`: `"/meeting-notes/documents"`; \}
+
+## Properties
+
+| Property | Type | Description |
+| ------ | ------ | ------ |
+| <a id="property-body"></a> `body?` | `never` | - |
+| <a id="property-path"></a> `path?` | `never` | - |
+| <a id="property-query"></a> `query?` | \{ `query?`: `string`; \} | - |
+| `query.query?` | `string` | Empty returns recent documents. |
+| <a id="property-url"></a> `url` | `"/meeting-notes/documents"` | - |
diff --git a/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/NoteDocumentsResponse.md b/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/NoteDocumentsResponse.md
new file mode 100644
index 0000000000..f03a5c91f7
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/NoteDocumentsResponse.md
@@ -0,0 +1,3 @@
+# Type Alias: NoteDocumentsResponse
+
+> **NoteDocumentsResponse** = [`NoteDocumentsResponses`](NoteDocumentsResponses.md)\[keyof [`NoteDocumentsResponses`](NoteDocumentsResponses.md)\]
diff --git a/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/NoteDocumentsResponses.md b/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/NoteDocumentsResponses.md
new file mode 100644
index 0000000000..3f45077451
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/NoteDocumentsResponses.md
@@ -0,0 +1,9 @@
+# Type Alias: NoteDocumentsResponses
+
+> **NoteDocumentsResponses** = \{ `200`: [`NotePicker`](NotePicker.md); \}
+
+## Properties
+
+| Property | Type |
+| ------ | ------ |
+| <a id="property-200"></a> `200` | [`NotePicker`](NotePicker.md) |
diff --git a/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/NotePicker.md b/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/NotePicker.md
new file mode 100644
index 0000000000..0c466a0f73
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/NotePicker.md
@@ -0,0 +1,12 @@
+# Type Alias: NotePicker
+
+> **NotePicker** = \{ `documents`: [`NoteDocument`](NoteDocument.md)[]; `teams`: [`NoteTeam`](NoteTeam.md)[]; \}
+
+Picker results; only documents whose owner is the caller are suggested.
+
+## Properties
+
+| Property | Type | Description |
+| ------ | ------ | ------ |
+| <a id="property-documents"></a> `documents` | [`NoteDocument`](NoteDocument.md)[] | At most 30 matching markdown documents, most recently updated first. |
+| <a id="property-teams"></a> `teams` | [`NoteTeam`](NoteTeam.md)[] | Teams the caller currently belongs to. |
diff --git a/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/NoteTeam.md b/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/NoteTeam.md
new file mode 100644
index 0000000000..366a863367
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/NoteTeam.md
@@ -0,0 +1,12 @@
+# Type Alias: NoteTeam
+
+> **NoteTeam** = \{ `id`: `string`; `name`: `string`; \}
+
+An additional team audience, separate from the meeting's audience.
+
+## Properties
+
+| Property | Type | Description |
+| ------ | ------ | ------ |
+| <a id="property-id"></a> `id` | `string` | Team identity. |
+| <a id="property-name"></a> `name` | `string` | Display name. |
diff --git a/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/UnlinkEventNoteData.md b/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/UnlinkEventNoteData.md
new file mode 100644
index 0000000000..bd76bd4092
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/UnlinkEventNoteData.md
@@ -0,0 +1,15 @@
+# Type Alias: UnlinkEventNoteData
+
+> **UnlinkEventNoteData** = \{ `body?`: `never`; `path`: \{ `document_id`: `string`; `event_id`: `string`; \}; `query`: \{ `occurrenceKey`: `string`; \}; `url`: `"/events/{event_id}/notes/{document_id}"`; \}
+
+## Properties
+
+| Property | Type | Description |
+| ------ | ------ | ------ |
+| <a id="property-body"></a> `body?` | `never` | - |
+| <a id="property-path"></a> `path` | \{ `document_id`: `string`; `event_id`: `string`; \} | - |
+| `path.document_id` | `string` | - |
+| `path.event_id` | `string` | - |
+| <a id="property-query"></a> `query` | \{ `occurrenceKey`: `string`; \} | - |
+| `query.occurrenceKey` | `string` | Stable occurrence key returned by the calendar read API. |
+| <a id="property-url"></a> `url` | `"/events/{event_id}/notes/{document_id}"` | - |
diff --git a/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/UnlinkEventNoteResponse.md b/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/UnlinkEventNoteResponse.md
new file mode 100644
index 0000000000..d8a22c61f2
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/UnlinkEventNoteResponse.md
@@ -0,0 +1,3 @@
+# Type Alias: UnlinkEventNoteResponse
+
+> **UnlinkEventNoteResponse** = [`UnlinkEventNoteResponses`](UnlinkEventNoteResponses.md)\[keyof [`UnlinkEventNoteResponses`](UnlinkEventNoteResponses.md)\]
diff --git a/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/UnlinkEventNoteResponses.md b/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/UnlinkEventNoteResponses.md
new file mode 100644
index 0000000000..1e267e7066
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/UnlinkEventNoteResponses.md
@@ -0,0 +1,9 @@
+# Type Alias: UnlinkEventNoteResponses
+
+> **UnlinkEventNoteResponses** = \{ `204`: `void`; \}
+
+## Properties
+
+| Property | Type |
+| ------ | ------ |
+| <a id="property-204"></a> `204` | `void` |
diff --git a/packages/sdk-docs/reference/modules.md b/packages/sdk-docs/reference/modules.md
index d3639cbcc6..1bb70e7fbd 100644
--- a/packages/sdk-docs/reference/modules.md
+++ b/packages/sdk-docs/reference/modules.md
@@ -33,6 +33,7 @@
- [src/entities/calendar/calendar](src/entities/calendar/calendar/README.md)
- [src/entities/calendar/event](src/entities/calendar/event/README.md)
- [src/entities/calendar/namespace](src/entities/calendar/namespace/README.md)
+- [src/entities/calendar/note](src/entities/calendar/note/README.md)
- [src/entities/calendar/replacement](src/entities/calendar/replacement/README.md)
- [src/entities/calls/call-record](src/entities/calls/call-record/README.md)
- [src/entities/calls/message](src/entities/calls/message/README.md)
diff --git a/packages/sdk-docs/reference/src/entities/calendar/event/classes/CalendarEvent.md b/packages/sdk-docs/reference/src/entities/calendar/event/classes/CalendarEvent.md
index 99db111c0b..d24b3afe88 100644
--- a/packages/sdk-docs/reference/src/entities/calendar/event/classes/CalendarEvent.md
+++ b/packages/sdk-docs/reference/src/entities/calendar/event/classes/CalendarEvent.md
@@ -113,6 +113,46 @@ the new guests.
***
+### linkNote()
+
+> **linkNote**(`document`, `occurrence`, `options?`): `Promise`\<[`CalendarNote`](../../note/classes/CalendarNote.md)\>
+
+Link a markdown document you own. Meeting-detail viewers gain read access;
+an optional team gains read access too. Editing and other sharing are preserved.
+
+#### Parameters
+
+| Parameter | Type |
+| ------ | ------ |
+| `document` | [`Document`](../../../documents/document/classes/Document.md) |
+| `occurrence` | [`CalendarOccurrence`](../../../../../generated/storage/types.gen/type-aliases/CalendarOccurrence.md) |
+| `options?` | \{ `team?`: [`Team`](../../../teams/team/classes/Team.md); \} |
+| `options.team?` | [`Team`](../../../teams/team/classes/Team.md) |
+
+#### Returns
+
+`Promise`\<[`CalendarNote`](../../note/classes/CalendarNote.md)\>
+
+***
+
+### notes()
+
+> **notes**(`occurrence`): `Promise`\<[`CalendarNote`](../../note/classes/CalendarNote.md)[]\>
+
+Notes linked to a specific occurrence returned by `calendar.occurrences()`.
+
+#### Parameters
+
+| Parameter | Type |
+| ------ | ------ |
+| `occurrence` | [`CalendarOccurrence`](../../../../../generated/storage/types.gen/type-aliases/CalendarOccurrence.md) |
+
+#### Returns
+
+`Promise`\<[`CalendarNote`](../../note/classes/CalendarNote.md)[]\>
+
+***
+
### prepareReplacement()
> **prepareReplacement**(`options`): `Promise`\<[`CalendarReplacement`](../../replacement/classes/CalendarReplacement.md)\>
diff --git a/packages/sdk-docs/reference/src/entities/calendar/namespace/classes/CalendarNamespace.md b/packages/sdk-docs/reference/src/entities/calendar/namespace/classes/CalendarNamespace.md
index f79811c53e..0ecd2b44cf 100644
--- a/packages/sdk-docs/reference/src/entities/calendar/namespace/classes/CalendarNamespace.md
+++ b/packages/sdk-docs/reference/src/entities/calendar/namespace/classes/CalendarNamespace.md
@@ -100,6 +100,24 @@ A handle to a calendar event by id, for driving mutations.
***
+### noteDocuments()
+
+> **noteDocuments**(`query?`): `Promise`\<\{ `documents`: \{ `document`: [`Document`](../../../documents/document/classes/Document.md); `name`: `string`; \}[]; `teams`: \{ `name`: `string`; `team`: [`Team`](../../../teams/team/classes/Team.md); \}[]; \}\>
+
+Find up to 30 owned markdown documents for meeting notes, plus available extra team audiences.
+
+#### Parameters
+
+| Parameter | Type | Default value |
+| ------ | ------ | ------ |
+| `query?` | `string` | `''` |
+
+#### Returns
+
+`Promise`\<\{ `documents`: \{ `document`: [`Document`](../../../documents/document/classes/Document.md); `name`: `string`; \}[]; `teams`: \{ `name`: `string`; `team`: [`Team`](../../../teams/team/classes/Team.md); \}[]; \}\>
+
+***
+
### occurrences()
> **occurrences**(`options`): `AsyncGenerator`\<\{ `event`: [`CalendarEvent`](../../event/classes/CalendarEvent.md); `occurrence`: [`CalendarOccurrence`](../../../../../generated/storage/types.gen/type-aliases/CalendarOccurrence.md); \}, `any`, `any`\>
diff --git a/packages/sdk-docs/reference/src/entities/calendar/note/README.md b/packages/sdk-docs/reference/src/entities/calendar/note/README.md
new file mode 100644
index 0000000000..808f54042f
--- /dev/null
+++ b/packages/sdk-docs/reference/src/entities/calendar/note/README.md
@@ -0,0 +1,5 @@
+# src/entities/calendar/note
+
+## Classes
+
+- [CalendarNote](classes/CalendarNote.md)
diff --git a/packages/sdk-docs/reference/src/entities/calendar/note/classes/CalendarNote.md b/packages/sdk-docs/reference/src/entities/calendar/note/classes/CalendarNote.md
new file mode 100644
index 0000000000..fb6e524b4c
--- /dev/null
+++ b/packages/sdk-docs/reference/src/entities/calendar/note/classes/CalendarNote.md
@@ -0,0 +1,130 @@
+# Class: CalendarNote
+
+A markdown document linked to one meeting occurrence, with view-only access.
+
+## Extends
+
+- [`MacroEntity`](../../../entity/classes/MacroEntity.md)\<[`MeetingNote`](../../../../../generated/calendar/types.gen/type-aliases/MeetingNote.md)\>
+
+## Properties
+
+| Property | Modifier | Type | Description | Inherited from |
+| ------ | ------ | ------ | ------ | ------ |
+| <a id="property-canmanage"></a> `canManage` | `readonly` | () => `Promise`\<`boolean`\> | Whether the caller may change this link's sharing. | - |
+| <a id="property-document"></a> `document` | `readonly` | () => `Promise`\<[`Document`](../../../documents/document/classes/Document.md)\> | The original markdown document; unlinking never deletes it. | - |
+| <a id="property-event"></a> `event` | `readonly` | [`CalendarEvent`](../../event/classes/CalendarEvent.md) | - | - |
+| <a id="property-id"></a> `id` | `public readonly` | `string` | - | [`MacroEntity`](../../../entity/classes/MacroEntity.md).[`id`](../../../entity/classes/MacroEntity.md#property-id) |
+| <a id="property-name"></a> `name` | `readonly` | () => `Promise`\<`string`\> | Current document name. | - |
+| <a id="property-occurrence"></a> `occurrence` | `readonly` | `Pick`\<[`CalendarOccurrence`](../../../../../generated/storage/types.gen/type-aliases/CalendarOccurrence.md), `"eventId"` \| `"occurrenceKey"`\> | - | - |
+| <a id="property-team"></a> `team` | `readonly` | () => `Promise`\<[`Team`](../../../teams/team/classes/Team.md) \| `undefined`\> | Optional extra team audience. Meeting-detail viewers already have view access. | - |
+
+## Methods
+
+### setTeam()
+
+> **setTeam**(`team?`): `Promise`\<`void`\>
+
+Change the extra team view grant; omit the team to remove it. Requires document ownership.
+
+#### Parameters
+
+| Parameter | Type |
+| ------ | ------ |
+| `team?` | [`Team`](../../../teams/team/classes/Team.md) |
+
+#### Returns
+
+`Promise`\<`void`\>
+
+***
+
+### toJSON()
+
+> **toJSON**(): \{ `detail?`: [`MeetingNote`](../../../../../generated/calendar/types.gen/type-aliases/MeetingNote.md); `id`: `string`; \}
+
+#### Returns
+
+\{ `detail?`: [`MeetingNote`](../../../../../generated/calendar/types.gen/type-aliases/MeetingNote.md); `id`: `string`; \}
+
+| Name | Type |
+| ------ | ------ |
+| `detail?` | [`MeetingNote`](../../../../../generated/calendar/types.gen/type-aliases/MeetingNote.md) |
+| `id` | `string` |
+
+#### Inherited from
+
+[`MacroEntity`](../../../entity/classes/MacroEntity.md).[`toJSON`](../../../entity/classes/MacroEntity.md#tojson)
+
+***
+
+### unlink()
+
+> **unlink**(): `Promise`\<`void`\>
+
+Remove this occurrence's link and view grants, preserving the document and other sharing.
+
+#### Returns
+
+`Promise`\<`void`\>
+
+***
+
+### forDocument()
+
+> `static` **forDocument**(`client`, `event`, `occurrence`, `document`): `CalendarNote`
+
+Construct a handle for a document already linked to this occurrence.
+
+#### Parameters
+
+| Parameter | Type |
+| ------ | ------ |
+| `client` | `MacroClient` |
+| `event` | [`CalendarEvent`](../../event/classes/CalendarEvent.md) |
+| `occurrence` | [`CalendarOccurrence`](../../../../../generated/storage/types.gen/type-aliases/CalendarOccurrence.md) |
+| `document` | [`Document`](../../../documents/document/classes/Document.md) |
+
+#### Returns
+
+`CalendarNote`
+
+***
+
+### fromDocumentLink()
+
+> `static` **fromDocumentLink**(`client`, `document`, `link`): `CalendarNote`
+
+Seed an owner-visible link that can be revoked even if the meeting is unavailable.
+
+#### Parameters
+
+| Parameter | Type |
+| ------ | ------ |
+| `client` | `MacroClient` |
+| `document` | [`Document`](../../../documents/document/classes/Document.md) |
+| `link` | [`DocumentNoteLink`](../../../../../generated/calendar/types.gen/type-aliases/DocumentNoteLink.md) |
+
+#### Returns
+
+`CalendarNote`
+
+***
+
+### fromRecord()
+
+> `static` **fromRecord**(`client`, `event`, `occurrence`, `record`): `CalendarNote`
+
+Seed a handle with a record returned by the meeting-note API.
+
+#### Parameters
+
+| Parameter | Type |
+| ------ | ------ |
+| `client` | `MacroClient` |
+| `event` | [`CalendarEvent`](../../event/classes/CalendarEvent.md) |
+| `occurrence` | [`CalendarOccurrence`](../../../../../generated/storage/types.gen/type-aliases/CalendarOccurrence.md) |
+| `record` | [`MeetingNote`](../../../../../generated/calendar/types.gen/type-aliases/MeetingNote.md) |
+
+#### Returns
+
+`CalendarNote`
diff --git a/packages/sdk-docs/reference/src/entities/documents/document/classes/Document.md b/packages/sdk-docs/reference/src/entities/documents/document/classes/Document.md
index e18c21a1b9..6a71d4ebd8 100644
--- a/packages/sdk-docs/reference/src/entities/documents/document/classes/Document.md
+++ b/packages/sdk-docs/reference/src/entities/documents/document/classes/Document.md
@@ -217,6 +217,18 @@ GitHub pull requests associated with the document.
***
+### meetingNotes()
+
+> **meetingNotes**(): `Promise`\<\{ `eventTitle`: `string`; `note`: [`CalendarNote`](../../../calendar/note/classes/CalendarNote.md); \}[]\>
+
+Owner-only meeting grants, including unavailable meetings. Unlink a returned note to revoke its meeting/team access.
+
+#### Returns
+
+`Promise`\<\{ `eventTitle`: `string`; `note`: [`CalendarNote`](../../../calendar/note/classes/CalendarNote.md); \}[]\>
+
+***
+
### messageThreadById()
> **messageThreadById**(`id`): [`MessageThread`](../../../messages/thread/classes/MessageThread.md)
diff --git a/packages/sdk-docs/reference/src/entities/entity/classes/MacroEntity.md b/packages/sdk-docs/reference/src/entities/entity/classes/MacroEntity.md
index ea5156d82a..8d8a3a890a 100644
--- a/packages/sdk-docs/reference/src/entities/entity/classes/MacroEntity.md
+++ b/packages/sdk-docs/reference/src/entities/entity/classes/MacroEntity.md
@@ -14,6 +14,7 @@ field and mutate.
- [`UserApiKey`](../../api-keys/api-key/classes/UserApiKey.md)
- [`Calendar`](../../calendar/calendar/classes/Calendar.md)
- [`CalendarEvent`](../../calendar/event/classes/CalendarEvent.md)
+- [`CalendarNote`](../../calendar/note/classes/CalendarNote.md)
- [`CallMessage`](../../calls/message/classes/CallMessage.md)
- [`ChatMessage`](../../chats/generation/classes/ChatMessage.md)
- [`CrmComment`](../../crm/comment/classes/CrmComment.md)
diff --git a/packages/sdk-docs/reference/src/entities/tasks/task/classes/Task.md b/packages/sdk-docs/reference/src/entities/tasks/task/classes/Task.md
index f75900583b..88c2eb2a14 100644
--- a/packages/sdk-docs/reference/src/entities/tasks/task/classes/Task.md
+++ b/packages/sdk-docs/reference/src/entities/tasks/task/classes/Task.md
@@ -259,6 +259,22 @@ GitHub pull requests associated with the document.
***
+### meetingNotes()
+
+> **meetingNotes**(): `Promise`\<\{ `eventTitle`: `string`; `note`: [`CalendarNote`](../../../calendar/note/classes/CalendarNote.md); \}[]\>
+
+Owner-only meeting grants, including unavailable meetings. Unlink a returned note to revoke its meeting/team access.
+
+#### Returns
+
+`Promise`\<\{ `eventTitle`: `string`; `note`: [`CalendarNote`](../../../calendar/note/classes/CalendarNote.md); \}[]\>
+
+#### Inherited from
+
+[`Document`](../../../documents/document/classes/Document.md).[`meetingNotes`](../../../documents/document/classes/Document.md#meetingnotes)
+
+***
+
### messageThreadById()
> **messageThreadById**(`id`): [`MessageThread`](../../../messages/thread/classes/MessageThread.md)
diff --git a/packages/sdk-docs/reference/src/macro/README.md b/packages/sdk-docs/reference/src/macro/README.md
index 0166f6a7dd..b8c94bd429 100644
--- a/packages/sdk-docs/reference/src/macro/README.md
+++ b/packages/sdk-docs/reference/src/macro/README.md
@@ -46,6 +46,12 @@ Re-exports [ApplyOpsOptions](../entities/databases/database/type-aliases/ApplyOp
***
+### CalendarNote
+
+Re-exports [CalendarNote](../entities/calendar/note/classes/CalendarNote.md)
+
+***
+
### CallMessage
Re-exports [CallMessage](../entities/calls/message/classes/CallMessage.md)
diff --git a/packages/sdk/AGENTS.md b/packages/sdk/AGENTS.md
index 13e6dacf7e..0772091c16 100644
--- a/packages/sdk/AGENTS.md
+++ b/packages/sdk/AGENTS.md
@@ -40,12 +40,18 @@ the existing gateway prefixes.
## Gotchas
+- Calendar notes accept a document handle and the occurrence returned by calendar
+ reads. `CalendarNote` owns optional team sharing and unlinking; clearing its team
+ sends explicit null and never changes the document's other permissions.
+ `Document.meetingNotes()` discovers durable grants for revocation after losing
+ meeting access.
- Regenerate Rust OpenAPI and web service clients before `bun run sync-specs &&
bun run generate`; do not copy deployed schemas over a local API change.
- Regenerate `../sdk-docs/reference` after SDK source or generated type changes;
run that package's checks because web CI verifies the reference is current.
- Also run `bun packages/code-mode-sdk/scripts/generate.ts` from the root and
- commit `crates/agent_code_mode/src/domain/documentation.json`; CI's Typecheck
+- Run `bun run generate` and the checks in `../code-mode-sdk` after SDK changes
+ to keep the embedded Deno bundle, agent documentation, and operation catalog current.
+ Commit `crates/agent_code_mode/src/domain/documentation.json`; CI's Typecheck
fails when it is stale.
- `generated/agent-fold/` is not from OpenAPI: `cargo run -p agent_fold --bin
export_types` writes it, and `foldedLog()` casts the opaque wire schema to it.
diff --git a/packages/sdk/README.md b/packages/sdk/README.md
index 41a8b94d7e..caacb15ea4 100644
--- a/packages/sdk/README.md
+++ b/packages/sdk/README.md
@@ -477,6 +477,14 @@ when mutations invalidate metadata. `update`, `cancel`, `invite(email)`,
`availabilityCalendars`, `calendar.setContributesToAvailability`, `teamSharing` and
`setTeamSharing` manage availability and sharing preferences.
+`calendar.noteDocuments(query)` suggests owned markdown and optional team handles.
+Use `event.linkNote(document, occurrence, { team })` to grant meeting viewers view
+access; omit `team` for meeting access only. One-time notes follow reschedules;
+recurring notes stay on the selected occurrence. `event.notes(occurrence)` returns
+`CalendarNote` handles with `setTeam(team?)` and `unlink()`. Existing editing and
+other document sharing stay unchanged. Owners can discover every durable grant
+through `document.meetingNotes()` and unlink it even when the meeting is unavailable.
+
### Document lifecycle and other resources
`documents.createUpload(options)` reserves a binary document and returns upload
diff --git a/packages/sdk/generated/calendar/index.ts b/packages/sdk/generated/calendar/index.ts
index 7fbb761cb6..6d2725b607 100644
--- a/packages/sdk/generated/calendar/index.ts
+++ b/packages/sdk/generated/calendar/index.ts
@@ -1,4 +1,4 @@
// This file is auto-generated by @hey-api/openapi-ts
export { type Options, Sdk } from './sdk.gen';
-export type { AttendeeResponseStatus, AvailabilityCalendar, AvailabilityCalendarBody, AvailabilityCalendarsResponse, CalendarAttendee, CalendarAttendeeInputBody, CalendarCapabilities, CalendarDeletionScopeParam, CalendarEvent, CalendarEventProviderUrl, CalendarEventProviderUrlData, CalendarEventProviderUrlError, CalendarEventProviderUrlErrors, CalendarEventProviderUrlResponse, CalendarEventProviderUrlResponses, CalendarEventSourceContent, CalendarGuestInputBody, CalendarJoinRequest, CalendarJoinRequestDecision, CalendarJoinRequestStatus, CalendarMutationApiError, CalendarMutationErrorCode, CalendarProvider, CalendarReplacementStatusData, CalendarReplacementStatusError, CalendarReplacementStatusErrors, CalendarReplacementStatusResponse, CalendarReplacementStatusResponses, CalendarReplacementView, CalendarRsvpScopeParam, CalendarUpdateScopeParam, ClientOptions, ConferenceChange, ConferenceProvider, ConfirmCalendarReplacementData, ConfirmCalendarReplacementError, ConfirmCalendarReplacementErrors, ConfirmCalendarReplacementResponse, ConfirmCalendarReplacementResponses, CopyCalendarEventData, CopyCalendarEventError, CopyCalendarEventErrors, CopyCalendarEventRequest, CopyCalendarEventResponse, CopyCalendarEventResponses, CreateCalendarEventData, CreateCalendarEventError, CreateCalendarEventErrors, CreateCalendarEventRequest, CreateCalendarEventResponse, CreateCalendarEventResponses, DeleteCalendarEventData, DeleteCalendarEventError, DeleteCalendarEventErrors, DeleteCalendarEventResponse, DeleteCalendarEventResponses, DiscardCalendarReplacementData, DiscardCalendarReplacementError, DiscardCalendarReplacementErrors, DiscardCalendarReplacementResponse, DiscardCalendarReplacementResponses, EventReminderOverride, EventReminders, EventStatus, EventTime, EventTransparency, EventType, EventVisibility, GetAvailabilityCalendarsData, GetAvailabilityCalendarsResponse, GetAvailabilityCalendarsResponses, GetTeamSharingData, GetTeamSharingResponse, GetTeamSharingResponses, GuestPolicy, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, InviteCalendarEventGuestsData, InviteCalendarEventGuestsError, InviteCalendarEventGuestsErrors, InviteCalendarEventGuestsRequest, InviteCalendarEventGuestsResponse, InviteCalendarEventGuestsResponses, ListCalendarsData, ListCalendarsError, ListCalendarsErrors, ListCalendarsResponse, ListCalendarsResponse2, ListCalendarsResponses, OutOfOfficeAutoDeclineMode, OutOfOfficeProperties, PrepareCalendarReplacementData, PrepareCalendarReplacementError, PrepareCalendarReplacementErrors, PrepareCalendarReplacementRequest, PrepareCalendarReplacementResponse, PrepareCalendarReplacementResponses, RefreshCalendarEvent, ReplacementStatus, RespondToJoinRequestData, RespondToJoinRequestError, RespondToJoinRequestErrors, RespondToJoinRequestRequest, RespondToJoinRequestResponse, RespondToJoinRequestResponses, RsvpCalendarEventData, RsvpCalendarEventError, RsvpCalendarEventErrors, RsvpCalendarEventRequest, RsvpCalendarEventResponse, RsvpCalendarEventResponses, SetAvailabilityCalendarData, SetAvailabilityCalendarResponse, SetAvailabilityCalendarResponses, SetTeamSharingData, SetTeamSharingResponse, SetTeamSharingResponses, TeamCalendarSharing, TeamCalendarSharingBody, UpdateCalendarEventData, UpdateCalendarEventError, UpdateCalendarEventErrors, UpdateCalendarEventRequest, UpdateCalendarEventResponse, UpdateCalendarEventResponses, ViewerCapabilities, VisibleCalendar } from './types.gen';
+export type { AttendeeResponseStatus, AvailabilityCalendar, AvailabilityCalendarBody, AvailabilityCalendarsResponse, CalendarAttendee, CalendarAttendeeInputBody, CalendarCapabilities, CalendarDeletionScopeParam, CalendarEvent, CalendarEventProviderUrl, CalendarEventProviderUrlData, CalendarEventProviderUrlError, CalendarEventProviderUrlErrors, CalendarEventProviderUrlResponse, CalendarEventProviderUrlResponses, CalendarEventSourceContent, CalendarGuestInputBody, CalendarJoinRequest, CalendarJoinRequestDecision, CalendarJoinRequestStatus, CalendarMutationApiError, CalendarMutationErrorCode, CalendarProvider, CalendarReplacementStatusData, CalendarReplacementStatusError, CalendarReplacementStatusErrors, CalendarReplacementStatusResponse, CalendarReplacementStatusResponses, CalendarReplacementView, CalendarRsvpScopeParam, CalendarUpdateScopeParam, ClientOptions, ConferenceChange, ConferenceProvider, ConfirmCalendarReplacementData, ConfirmCalendarReplacementError, ConfirmCalendarReplacementErrors, ConfirmCalendarReplacementResponse, ConfirmCalendarReplacementResponses, CopyCalendarEventData, CopyCalendarEventError, CopyCalendarEventErrors, CopyCalendarEventRequest, CopyCalendarEventResponse, CopyCalendarEventResponses, CreateCalendarEventData, CreateCalendarEventError, CreateCalendarEventErrors, CreateCalendarEventRequest, CreateCalendarEventResponse, CreateCalendarEventResponses, DeleteCalendarEventData, DeleteCalendarEventError, DeleteCalendarEventErrors, DeleteCalendarEventResponse, DeleteCalendarEventResponses, DiscardCalendarReplacementData, DiscardCalendarReplacementError, DiscardCalendarReplacementErrors, DiscardCalendarReplacementResponse, DiscardCalendarReplacementResponses, DocumentNoteLink, DocumentNoteLinksData, DocumentNoteLinksResponse, DocumentNoteLinksResponses, EventNotesData, EventNotesResponse, EventNotesResponses, EventReminderOverride, EventReminders, EventStatus, EventTime, EventTransparency, EventType, EventVisibility, GetAvailabilityCalendarsData, GetAvailabilityCalendarsResponse, GetAvailabilityCalendarsResponses, GetTeamSharingData, GetTeamSharingResponse, GetTeamSharingResponses, GuestPolicy, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, InviteCalendarEventGuestsData, InviteCalendarEventGuestsError, InviteCalendarEventGuestsErrors, InviteCalendarEventGuestsRequest, InviteCalendarEventGuestsResponse, InviteCalendarEventGuestsResponses, LinkEventNoteData, LinkEventNoteResponse, LinkEventNoteResponses, LinkNoteRequest, ListCalendarsData, ListCalendarsError, ListCalendarsErrors, ListCalendarsResponse, ListCalendarsResponse2, ListCalendarsResponses, MeetingNote, NoteDocument, NoteDocumentsData, NoteDocumentsResponse, NoteDocumentsResponses, NotePicker, NoteTeam, OutOfOfficeAutoDeclineMode, OutOfOfficeProperties, PrepareCalendarReplacementData, PrepareCalendarReplacementError, PrepareCalendarReplacementErrors, PrepareCalendarReplacementRequest, PrepareCalendarReplacementResponse, PrepareCalendarReplacementResponses, RefreshCalendarEvent, ReplacementStatus, RespondToJoinRequestData, RespondToJoinRequestError, RespondToJoinRequestErrors, RespondToJoinRequestRequest, RespondToJoinRequestResponse, RespondToJoinRequestResponses, RsvpCalendarEventData, RsvpCalendarEventError, RsvpCalendarEventErrors, RsvpCalendarEventRequest, RsvpCalendarEventResponse, RsvpCalendarEventResponses, SetAvailabilityCalendarData, SetAvailabilityCalendarResponse, SetAvailabilityCalendarResponses, SetTeamSharingData, SetTeamSharingResponse, SetTeamSharingResponses, TeamCalendarSharing, TeamCalendarSharingBody, UnlinkEventNoteData, UnlinkEventNoteResponse, UnlinkEventNoteResponses, UpdateCalendarEventData, UpdateCalendarEventError, UpdateCalendarEventErrors, UpdateCalendarEventRequest, UpdateCalendarEventResponse, UpdateCalendarEventResponses, ViewerCapabilities, VisibleCalendar } from './types.gen';
diff --git a/packages/sdk/generated/calendar/sdk.gen.ts b/packages/sdk/generated/calendar/sdk.gen.ts
index faf33bb7f2..3b3a3deb5b 100644
--- a/packages/sdk/generated/calendar/sdk.gen.ts
+++ b/packages/sdk/generated/calendar/sdk.gen.ts
@@ -2,7 +2,7 @@
import type { Client, ClientMeta, Options as Options2, RequestResult, TDataShape } from './client';
import { client } from './client.gen';
-import type { CalendarEventProviderUrlData, CalendarEventProviderUrlErrors, CalendarEventProviderUrlResponses, CalendarReplacementStatusData, CalendarReplacementStatusErrors, CalendarReplacementStatusResponses, ConfirmCalendarReplacementData, ConfirmCalendarReplacementErrors, ConfirmCalendarReplacementResponses, CopyCalendarEventData, CopyCalendarEventErrors, CopyCalendarEventResponses, CreateCalendarEventData, CreateCalendarEventErrors, CreateCalendarEventResponses, DeleteCalendarEventData, DeleteCalendarEventErrors, DeleteCalendarEventResponses, DiscardCalendarReplacementData, DiscardCalendarReplacementErrors, DiscardCalendarReplacementResponses, GetAvailabilityCalendarsData, GetAvailabilityCalendarsResponses, GetTeamSharingData, GetTeamSharingResponses, HealthHandlerData, HealthHandlerResponses, InviteCalendarEventGuestsData, InviteCalendarEventGuestsErrors, InviteCalendarEventGuestsResponses, ListCalendarsData, ListCalendarsErrors, ListCalendarsResponses, PrepareCalendarReplacementData, PrepareCalendarReplacementErrors, PrepareCalendarReplacementResponses, RespondToJoinRequestData, RespondToJoinRequestErrors, RespondToJoinRequestResponses, RsvpCalendarEventData, RsvpCalendarEventErrors, RsvpCalendarEventResponses, SetAvailabilityCalendarData, SetAvailabilityCalendarResponses, SetTeamSharingData, SetTeamSharingResponses, UpdateCalendarEventData, UpdateCalendarEventErrors, UpdateCalendarEventResponses } from './types.gen';
+import type { CalendarEventProviderUrlData, CalendarEventProviderUrlErrors, CalendarEventProviderUrlResponses, CalendarReplacementStatusData, CalendarReplacementStatusErrors, CalendarReplacementStatusResponses, ConfirmCalendarReplacementData, ConfirmCalendarReplacementErrors, ConfirmCalendarReplacementResponses, CopyCalendarEventData, CopyCalendarEventErrors, CopyCalendarEventResponses, CreateCalendarEventData, CreateCalendarEventErrors, CreateCalendarEventResponses, DeleteCalendarEventData, DeleteCalendarEventErrors, DeleteCalendarEventResponses, DiscardCalendarReplacementData, DiscardCalendarReplacementErrors, DiscardCalendarReplacementResponses, DocumentNoteLinksData, DocumentNoteLinksResponses, EventNotesData, EventNotesResponses, GetAvailabilityCalendarsData, GetAvailabilityCalendarsResponses, GetTeamSharingData, GetTeamSharingResponses, HealthHandlerData, HealthHandlerResponses, InviteCalendarEventGuestsData, InviteCalendarEventGuestsErrors, InviteCalendarEventGuestsResponses, LinkEventNoteData, LinkEventNoteResponses, ListCalendarsData, ListCalendarsErrors, ListCalendarsResponses, NoteDocumentsData, NoteDocumentsResponses, PrepareCalendarReplacementData, PrepareCalendarReplacementErrors, PrepareCalendarReplacementResponses, RespondToJoinRequestData, RespondToJoinRequestErrors, RespondToJoinRequestResponses, RsvpCalendarEventData, RsvpCalendarEventErrors, RsvpCalendarEventResponses, SetAvailabilityCalendarData, SetAvailabilityCalendarResponses, SetTeamSharingData, SetTeamSharingResponses, UnlinkEventNoteData, UnlinkEventNoteResponses, UpdateCalendarEventData, UpdateCalendarEventErrors, UpdateCalendarEventResponses } from './types.gen';
export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown> = Options2<TData, ThrowOnError, TResponse> & {
/**
@@ -153,6 +153,34 @@ export class Sdk extends HeyApiClient {
});
}
+ /**
+ * List notes visible through this meeting occurrence.
+ */
+ public eventNotes<ThrowOnError extends boolean = false>(options: Options<EventNotesData, ThrowOnError>): RequestResult<EventNotesResponses, unknown, ThrowOnError> {
+ return (options.client ?? this.client).get<EventNotesResponses, unknown, ThrowOnError>({ url: '/events/{event_id}/notes', ...options });
+ }
+
+ /**
+ * Remove this meeting's grant without deleting the document.
+ */
+ public unlinkEventNote<ThrowOnError extends boolean = false>(options: Options<UnlinkEventNoteData, ThrowOnError>): RequestResult<UnlinkEventNoteResponses, unknown, ThrowOnError> {
+ return (options.client ?? this.client).delete<UnlinkEventNoteResponses, unknown, ThrowOnError>({ url: '/events/{event_id}/notes/{document_id}', ...options });
+ }
+
+ /**
+ * Idempotently link a markdown document and its optional team audience.
+ */
+ public linkEventNote<ThrowOnError extends boolean = false>(options: Options<LinkEventNoteData, ThrowOnError>): RequestResult<LinkEventNoteResponses, unknown, ThrowOnError> {
+ return (options.client ?? this.client).put<LinkEventNoteResponses, unknown, ThrowOnError>({
+ url: '/events/{event_id}/notes/{document_id}',
+ ...options,
+ headers: {
+ 'Content-Type': 'application/json',
+ ...options.headers
+ }
+ });
+ }
+
/**
* Resolve an authorized event's provider link for Outlook-only actions.
*/
@@ -211,6 +239,20 @@ export class Sdk extends HeyApiClient {
});
}
+ /**
+ * Suggest the caller's markdown documents and extra team audiences.
+ */
+ public noteDocuments<ThrowOnError extends boolean = false>(options?: Options<NoteDocumentsData, ThrowOnError>): RequestResult<NoteDocumentsResponses, unknown, ThrowOnError> {
+ return (options?.client ?? this.client).get<NoteDocumentsResponses, unknown, ThrowOnError>({ url: '/meeting-notes/documents', ...options });
+ }
+
+ /**
+ * List an owned document's meeting grants, including unavailable meetings.
+ */
+ public documentNoteLinks<ThrowOnError extends boolean = false>(options: Options<DocumentNoteLinksData, ThrowOnError>): RequestResult<DocumentNoteLinksResponses, unknown, ThrowOnError> {
+ return (options.client ?? this.client).get<DocumentNoteLinksResponses, unknown, ThrowOnError>({ url: '/meeting-notes/documents/{document_id}/links', ...options });
+ }
+
/**
* Discard a preview only if no confirmation has been recorded.
*/
diff --git a/packages/sdk/generated/calendar/types.gen.ts b/packages/sdk/generated/calendar/types.gen.ts
index c80eac10e3..2b9f9a4675 100644
--- a/packages/sdk/generated/calendar/types.gen.ts
+++ b/packages/sdk/generated/calendar/types.gen.ts
@@ -572,6 +572,29 @@ export type CreateCalendarEventRequest = {
visibility?: null | EventVisibility;
};
+/**
+ * An owner's durable sharing link, including meetings they can no longer open.
+ */
+export type DocumentNoteLink = {
+ /**
+ * Current name of the owned markdown document.
+ */
+ documentName: string;
+ /**
+ * Linked calendar copy.
+ */
+ eventId: string;
+ /**
+ * Current title, or a safe placeholder when meeting details are unavailable.
+ */
+ eventTitle: string;
+ /**
+ * Original occurrence start, or `single` for a one-time meeting.
+ */
+ occurrenceKey: string;
+ team?: null | NoteTeam;
+};
+
/**
* One reminder: how it alerts and how many minutes before the event start
* (before midnight in the calendar's zone for all-day events) it fires.
@@ -699,6 +722,16 @@ export type InviteCalendarEventGuestsRequest = {
scope?: null | CalendarUpdateScopeParam;
};
+/**
+ * Optional additional view access for one team.
+ */
+export type LinkNoteRequest = {
+ /**
+ * Null means the meeting audience only.
+ */
+ teamId?: string | null;
+};
+
/**
* Calendars visible to the requester across connected and delegated inboxes.
*/
@@ -709,6 +742,67 @@ export type ListCalendarsResponse = {
calendars: Array<VisibleCalendar>;
};
+/**
+ * One linked document and the extra access this link grants.
+ */
+export type MeetingNote = {
+ /**
+ * Whether this viewer can change this document's sharing.
+ */
+ canManage: boolean;
+ /**
+ * Markdown document identity.
+ */
+ documentId: string;
+ /**
+ * Current document name.
+ */
+ name: string;
+ team?: null | NoteTeam;
+};
+
+/**
+ * A document available in the note picker.
+ */
+export type NoteDocument = {
+ /**
+ * Markdown document identity.
+ */
+ documentId: string;
+ /**
+ * Current document name, never a copied title.
+ */
+ name: string;
+};
+
+/**
+ * Picker results; only documents whose owner is the caller are suggested.
+ */
+export type NotePicker = {
+ /**
+ * At most 30 matching markdown documents, most recently updated first.
+ */
+ documents: Array<NoteDocument>;
+ /**
+ * Teams the caller currently belongs to.
+ */
+ teams: Array<NoteTeam>;
+};
+
+/**
+ * An additional team audience, separate from the meeting's audience.
+ */
+export type NoteTeam = {
+ /**
+ * Team identity.
+ */
+ id: string;
+ /**
+ * Display name.
+ */
+ name: string;
+};
+
/**
* How an out-of-office event responds to conflicting invitations, mirroring
* Google's `autoDeclineMode`.
@@ -1264,6 +1358,68 @@ export type InviteCalendarEventGuestsResponses = {
export type InviteCalendarEventGuestsResponse = InviteCalendarEventGuestsResponses[keyof InviteCalendarEventGuestsResponses];
+export type EventNotesData = {
+ body?: never;
+ path: {
+ event_id: string;
+ };
+ query: {
+ /**
+ * Stable occurrence key returned by the calendar read API.
+ */
+ occurrenceKey: string;
+ };
+ url: '/events/{event_id}/notes';
+};
+
+export type EventNotesResponses = {
+ 200: Array<MeetingNote>;
+};
+
+export type EventNotesResponse = EventNotesResponses[keyof EventNotesResponses];
+
+export type UnlinkEventNoteData = {
+ body?: never;
+ path: {
+ event_id: string;
+ document_id: string;
+ };
+ query: {
+ /**
+ * Stable occurrence key returned by the calendar read API.
+ */
+ occurrenceKey: string;
+ };
+ url: '/events/{event_id}/notes/{document_id}';
+};
+
+export type UnlinkEventNoteResponses = {
+ 204: void;
+};
+
+export type UnlinkEventNoteResponse = UnlinkEventNoteResponses[keyof UnlinkEventNoteResponses];
+
+export type LinkEventNoteData = {
+ body: LinkNoteRequest;
+ path: {
+ event_id: string;
+ document_id: string;
+ };
+ query: {
+ /**
+ * Stable occurrence key returned by the calendar read API.
+ */
+ occurrenceKey: string;
+ };
+ url: '/events/{event_id}/notes/{document_id}';
+};
+
+export type LinkEventNoteResponses = {
+ 204: void;
+};
+
+export type LinkEventNoteResponse = LinkEventNoteResponses[keyof LinkEventNoteResponses];
+
export type CalendarEventProviderUrlData = {
body?: never;
path: {
@@ -1423,6 +1579,39 @@ export type RespondToJoinRequestResponses = {
export type RespondToJoinRequestResponse = RespondToJoinRequestResponses[keyof RespondToJoinRequestResponses];
+export type NoteDocumentsData = {
+ body?: never;
+ path?: never;
+ query?: {
+ /**
+ * Empty returns recent documents.
+ */
+ query?: string;
+ };
+ url: '/meeting-notes/documents';
+};
+
+export type NoteDocumentsResponses = {
+ 200: NotePicker;
+};
+
+export type NoteDocumentsResponse = NoteDocumentsResponses[keyof NoteDocumentsResponses];
+
+export type DocumentNoteLinksData = {
+ body?: never;
+ path: {
+ document_id: string;
+ };
+ query?: never;
+ url: '/meeting-notes/documents/{document_id}/links';
+};
+
+export type DocumentNoteLinksResponses = {
+ 200: Array<DocumentNoteLink>;
+};
+
+export type DocumentNoteLinksResponse = DocumentNoteLinksResponses[keyof DocumentNoteLinksResponses];
+
export type DiscardCalendarReplacementData = {
body?: never;
path: {
diff --git a/packages/sdk/specs/calendar.json b/packages/sdk/specs/calendar.json
index 2a7ce3e2e2..f6fe893dee 100644
--- a/packages/sdk/specs/calendar.json
+++ b/packages/sdk/specs/calendar.json
@@ -540,6 +540,136 @@
}
}
},
+ "/events/{event_id}/notes": {
+ "get": {
+ "tags": ["calendar_events"],
+ "summary": "List notes visible through this meeting occurrence.",
+ "operationId": "event_notes",
+ "parameters": [
+ {
+ "name": "event_id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ },
+ {
+ "name": "occurrenceKey",
+ "in": "query",
+ "description": "Stable occurrence key returned by the calendar read API.",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/MeetingNote"
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/events/{event_id}/notes/{document_id}": {
+ "put": {
+ "tags": ["calendar_events"],
+ "summary": "Idempotently link a markdown document and its optional team audience.",
+ "operationId": "link_event_note",
+ "parameters": [
+ {
+ "name": "event_id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ },
+ {
+ "name": "document_id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ },
+ {
+ "name": "occurrenceKey",
+ "in": "query",
+ "description": "Stable occurrence key returned by the calendar read API.",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/LinkNoteRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "204": {
+ "description": ""
+ }
+ }
+ },
+ "delete": {
+ "tags": ["calendar_events"],
+ "summary": "Remove this meeting's grant without deleting the document.",
+ "operationId": "unlink_event_note",
+ "parameters": [
+ {
+ "name": "event_id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ },
+ {
+ "name": "document_id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ },
+ {
+ "name": "occurrenceKey",
+ "in": "query",
+ "description": "Stable occurrence key returned by the calendar read API.",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "204": {
+ "description": ""
+ }
+ }
+ }
+ },
"/events/{event_id}/provider-url": {
"get": {
"tags": ["calendar_events"],
@@ -836,6 +966,68 @@
}
}
},
+ "/meeting-notes/documents": {
+ "get": {
+ "tags": ["calendar_events"],
+ "summary": "Suggest the caller's markdown documents and extra team audiences.",
+ "operationId": "note_documents",
+ "parameters": [
+ {
+ "name": "query",
+ "in": "query",
+ "description": "Empty returns recent documents.",
+ "required": false,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/NotePicker"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/meeting-notes/documents/{document_id}/links": {
+ "get": {
+ "tags": ["calendar_events"],
+ "summary": "List an owned document's meeting grants, including unavailable meetings.",
+ "operationId": "document_note_links",
+ "parameters": [
+ {
+ "name": "document_id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/DocumentNoteLink"
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/replacements/{operation_id}": {
"get": {
"tags": ["calendar_events"],
@@ -1737,6 +1929,41 @@
}
}
},
+ "DocumentNoteLink": {
+ "type": "object",
+ "description": "An owner's durable sharing link, including meetings they can no longer open.",
+ "required": ["documentName", "eventId", "occurrenceKey", "eventTitle"],
+ "properties": {
+ "documentName": {
+ "type": "string",
+ "description": "Current name of the owned markdown document."
+ },
+ "eventId": {
+ "type": "string",
+ "format": "uuid",
+ "description": "Linked calendar copy."
+ },
+ "eventTitle": {
+ "type": "string",
+ "description": "Current title, or a safe placeholder when meeting details are unavailable."
+ },
+ "occurrenceKey": {
+ "type": "string",
+ "description": "Original occurrence start, or `single` for a one-time meeting."
+ },
+ "team": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/NoteTeam",
+ "description": "Independent optional team audience."
+ }
+ ]
+ }
+ }
+ },
"EventReminderOverride": {
"type": "object",
"description": "One 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.",
@@ -1903,6 +2130,17 @@
}
}
},
+ "LinkNoteRequest": {
+ "type": "object",
+ "description": "Optional additional view access for one team.",
+ "properties": {
+ "teamId": {
+ "type": ["string", "null"],
+ "format": "uuid",
+ "description": "Null means the meeting audience only."
+ }
+ }
+ },
"ListCalendarsResponse": {
"type": "object",
"description": "Calendars visible to the requester across connected and delegated inboxes.",
@@ -1917,6 +2155,88 @@
}
}
},
+ "MeetingNote": {
+ "type": "object",
+ "description": "One linked document and the extra access this link grants.",
+ "required": ["documentId", "name", "canManage"],
+ "properties": {
+ "canManage": {
+ "type": "boolean",
+ "description": "Whether this viewer can change this document's sharing."
+ },
+ "documentId": {
+ "type": "string",
+ "description": "Markdown document identity."
+ },
+ "name": {
+ "type": "string",
+ "description": "Current document name."
+ },
+ "team": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/NoteTeam",
+ "description": "Optional extra team view grant."
+ }
+ ]
+ }
+ }
+ },
+ "NoteDocument": {
+ "type": "object",
+ "description": "A document available in the note picker.",
+ "required": ["documentId", "name"],
+ "properties": {
+ "documentId": {
+ "type": "string",
+ "description": "Markdown document identity."
+ },
+ "name": {
+ "type": "string",
+ "description": "Current document name, never a copied title."
+ }
+ }
+ },
+ "NotePicker": {
+ "type": "object",
+ "description": "Picker results; only documents whose owner is the caller are suggested.",
+ "required": ["documents", "teams"],
+ "properties": {
+ "documents": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/NoteDocument"
+ },
+ "description": "At most 30 matching markdown documents, most recently updated first."
+ },
+ "teams": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/NoteTeam"
+ },
+ "description": "Teams the caller currently belongs to."
+ }
+ }
+ },
+ "NoteTeam": {
+ "type": "object",
+ "description": "An additional team audience, separate from the meeting's audience.",
+ "required": ["id", "name"],
+ "properties": {
+ "id": {
+ "type": "string",
+ "format": "uuid",
+ "description": "Team identity."
+ },
+ "name": {
+ "type": "string",
+ "description": "Display name."
+ }
+ }
+ },
"OutOfOfficeAutoDeclineMode": {
"type": "string",
"description": "How an out-of-office event responds to conflicting invitations, mirroring\nGoogle's `autoDeclineMode`.",
diff --git a/packages/sdk/src/entities/calendar/event.ts b/packages/sdk/src/entities/calendar/event.ts
index db992df1d2..b226fc9c4c 100644
--- a/packages/sdk/src/entities/calendar/event.ts
+++ b/packages/sdk/src/entities/calendar/event.ts
@@ -15,10 +15,14 @@ import type {
OutOfOfficeProperties,
UpdateCalendarEventRequest,
} from '../../../generated/calendar/types.gen';
+import type { CalendarOccurrence } from '../../../generated/storage/types.gen';
import { MacroError, unwrap } from '../../utils';
import type { MacroClient } from '../../utils/client';
+import type { Document } from '../documents/document';
import { MacroEntity } from '../entity';
+import type { Team } from '../teams/team';
import { Calendar } from './calendar';
+import { CalendarNote } from './note';
import { CalendarReplacement } from './replacement';
/** Fields to change on an event; omitted fields are left untouched. */
@@ -113,6 +117,43 @@ export interface RsvpEventOptions {
* mutations, but reading a field on it throws.
*/
export class CalendarEvent extends MacroEntity<CalendarEventRecord> {
+ /** Notes linked to a specific occurrence returned by `calendar.occurrences()`. */
+ async notes(occurrence: CalendarOccurrence): Promise<CalendarNote[]> {
+ this.requireOwnOccurrence(occurrence);
+ const notes = unwrap(
+ await this.client.calendar.eventNotes({
+ path: { event_id: this.id },
+ query: { occurrenceKey: occurrence.occurrenceKey },
+ }),
+ );
+ return notes.map((note) =>
+ CalendarNote.fromRecord(this.client, this, occurrence, note),
+ );
+ }
+
+ /** Link a markdown document you own. Meeting-detail viewers gain read access;
+ * an optional team gains read access too. Editing and other sharing are preserved. */
+ async linkNote(
+ document: Document,
+ occurrence: CalendarOccurrence,
+ options: { team?: Team } = {},
+ ): Promise<CalendarNote> {
+ this.requireOwnOccurrence(occurrence);
+ unwrap(
+ await this.client.calendar.linkEventNote({
+ path: { event_id: this.id, document_id: document.id },
+ query: { occurrenceKey: occurrence.occurrenceKey },
+ body: { teamId: options.team?.id ?? null },
+ }),
+ );
+ return CalendarNote.forDocument(this.client, this, occurrence, document);
+ }
+
+ private requireOwnOccurrence(occurrence: CalendarOccurrence) {
+ if (occurrence.eventId !== this.id)
+ throw new MacroError('The occurrence belongs to a different event');
+ }
+
protected async fetch(): Promise<CalendarEventRecord> {
throw new MacroError(
`calendar event ${this.id} has no fetch-by-id endpoint; read the record ` +
diff --git a/packages/sdk/src/entities/calendar/namespace.ts b/packages/sdk/src/entities/calendar/namespace.ts
index 1e79566bff..cac8f89cad 100644
--- a/packages/sdk/src/entities/calendar/namespace.ts
+++ b/packages/sdk/src/entities/calendar/namespace.ts
@@ -17,7 +17,9 @@ import type {
} from '../../../generated/storage/types.gen';
import { paginate, unwrap } from '../../utils';
import type { MacroClient } from '../../utils/client';
+import { Document } from '../documents/document';
import type { Link } from '../email/link';
+import { Team } from '../teams/team';
import { User } from '../users/user';
import { Calendar } from './calendar';
import { CalendarEvent } from './event';
@@ -66,6 +68,23 @@ export interface CreateEventOptions {
* SDK reaches it on the gateway's `/calendar` route).
*/
export class CalendarNamespace {
+ /** Find up to 30 owned markdown documents for meeting notes, plus available extra team audiences. */
+ async noteDocuments(query = '') {
+ const picker = unwrap(
+ await this.client.calendar.noteDocuments({ query: { query } }),
+ );
+ return {
+ documents: picker.documents.map((note) => ({
+ document: Document.byId(this.client, note.documentId),
+ name: note.name,
+ })),
+ teams: picker.teams.map((team) => ({
+ team: Team.byId(this.client, team.id),
+ name: team.name,
+ })),
+ };
+ }
+
/** Calendar availability settings, each referring to a typed calendar. */
async availabilityCalendars() {
return unwrap(
diff --git a/packages/sdk/src/entities/calendar/note.ts b/packages/sdk/src/entities/calendar/note.ts
new file mode 100644
index 0000000000..fb4c405520
--- /dev/null
+++ b/packages/sdk/src/entities/calendar/note.ts
@@ -0,0 +1,147 @@
+import type {
+ DocumentNoteLink,
+ MeetingNote,
+} from '../../../generated/calendar/types.gen';
+import type { CalendarOccurrence } from '../../../generated/storage/types.gen';
+import { MacroError, MacroNotFoundError, unwrap } from '../../utils';
+import type { MacroClient } from '../../utils/client';
+import { Document } from '../documents/document';
+import { MacroEntity } from '../entity';
+import { Team } from '../teams/team';
+import { CalendarEvent } from './event';
+
+/** A markdown document linked to one meeting occurrence, with view-only access. */
+export class CalendarNote extends MacroEntity<MeetingNote> {
+ private constructor(
+ client: MacroClient,
+ readonly event: CalendarEvent,
+ readonly occurrence: Pick<CalendarOccurrence, 'eventId' | 'occurrenceKey'>,
+ document: Document,
+ record?: MeetingNote,
+ private readonly fromDocument = false,
+ ) {
+ super(client, document.id, record);
+ if (occurrence.eventId !== event.id) {
+ throw new MacroError('Choose an occurrence belonging to this event');
+ }
+ }
+
+ /** Seed an owner-visible link that can be revoked even if the meeting is unavailable. */
+ static fromDocumentLink(
+ client: MacroClient,
+ document: Document,
+ link: DocumentNoteLink,
+ ): CalendarNote {
+ return new CalendarNote(
+ client,
+ CalendarEvent.byId(client, link.eventId),
+ link,
+ document,
+ {
+ documentId: document.id,
+ name: link.documentName,
+ team: link.team,
+ canManage: true,
+ },
+ true,
+ );
+ }
+
+ /** Construct a handle for a document already linked to this occurrence. */
+ static forDocument(
+ client: MacroClient,
+ event: CalendarEvent,
+ occurrence: CalendarOccurrence,
+ document: Document,
+ ): CalendarNote {
+ return new CalendarNote(client, event, occurrence, document);
+ }
+
+ /** Seed a handle with a record returned by the meeting-note API. */
+ static fromRecord(
+ client: MacroClient,
+ event: CalendarEvent,
+ occurrence: CalendarOccurrence,
+ record: MeetingNote,
+ ): CalendarNote {
+ return new CalendarNote(
+ client,
+ event,
+ occurrence,
+ Document.byId(client, record.documentId),
+ record,
+ );
+ }
+
+ protected async fetch(): Promise<MeetingNote> {
+ if (this.fromDocument) {
+ const links = unwrap(
+ await this.client.calendar.documentNoteLinks({
+ path: { document_id: this.id },
+ }),
+ );
+ const link = links.find(
+ (item) =>
+ item.eventId === this.event.id &&
+ item.occurrenceKey === this.occurrence.occurrenceKey,
+ );
+ if (!link)
+ throw new MacroNotFoundError('This meeting link has been removed');
+ return {
+ documentId: this.id,
+ name: link.documentName,
+ team: link.team,
+ canManage: true,
+ };
+ }
+ const notes = unwrap(
+ await this.client.calendar.eventNotes({
+ path: { event_id: this.event.id },
+ query: { occurrenceKey: this.occurrence.occurrenceKey },
+ }),
+ );
+ const note = notes.find((item) => item.documentId === this.id);
+ if (!note)
+ throw new MacroNotFoundError(
+ 'This document is no longer linked to the meeting',
+ );
+ return note;
+ }
+
+ /** The original markdown document; unlinking never deletes it. */
+ readonly document = this.mappedField('documentId', (id) =>
+ Document.byId(this.client, id),
+ );
+
+ /** Current document name. */
+ readonly name = this.field('name');
+
+ /** Optional extra team audience. Meeting-detail viewers already have view access. */
+ readonly team = this.mappedField('team', (team) =>
+ team ? Team.byId(this.client, team.id) : undefined,
+ );
+
+ /** Whether the caller may change this link's sharing. */
+ readonly canManage = this.field('canManage');
+
+ /** Change the extra team view grant; omit the team to remove it. Requires document ownership. */
+ async setTeam(team?: Team): Promise<void> {
+ await this.mutate((client) =>
+ client.calendar.linkEventNote({
+ path: { event_id: this.event.id, document_id: this.id },
+ query: { occurrenceKey: this.occurrence.occurrenceKey },
+ body: { teamId: team?.id ?? null },
+ }),
+ );
+ }
+
+ /** Remove this occurrence's link and view grants, preserving the document and other sharing. */
+ async unlink(): Promise<void> {
+ await this.mutate((client) =>
+ client.calendar.unlinkEventNote({
+ path: { event_id: this.event.id, document_id: this.id },
+ query: { occurrenceKey: this.occurrence.occurrenceKey },
+ }),
+ );
+ }
+}
diff --git a/packages/sdk/src/entities/documents/document.ts b/packages/sdk/src/entities/documents/document.ts
index 2677e36116..8a90fd26b1 100644
--- a/packages/sdk/src/entities/documents/document.ts
+++ b/packages/sdk/src/entities/documents/document.ts
@@ -20,6 +20,7 @@ import {
} from '../../mentions';
import { MacroApiError, mapConcurrently, paginate, unwrap } from '../../utils';
import type { MacroClient } from '../../utils/client';
+import { CalendarNote } from '../calendar/note';
import { PropertiedEntity } from '../entity';
import {
MessageThread,
@@ -55,6 +56,20 @@ export class Document
extends PropertiedEntity<DocumentDetail>
implements Mentionable
{
+ /** Owner-only meeting grants, including unavailable meetings. Unlink a returned note to revoke its meeting/team access. */
+ async meetingNotes(): Promise<
+ Array<{ note: CalendarNote; eventTitle: string }>
+ > {
+ const links = unwrap(
+ await this.client.calendar.documentNoteLinks({
+ path: { document_id: this.id },
+ }),
+ );
+ return links.map((link) => ({
+ note: CalendarNote.fromDocumentLink(this.client, this, link),
+ eventTitle: link.eventTitle,
+ }));
+ }
/** PDF annotations in this document. */
async anchors(): Promise<DocumentAnchor[]> {
return unwrap(
diff --git a/packages/sdk/src/macro.ts b/packages/sdk/src/macro.ts
index 0ac3be6802..37ff467cd3 100644
--- a/packages/sdk/src/macro.ts
+++ b/packages/sdk/src/macro.ts
@@ -244,6 +244,7 @@ export { ReviewItem, SessionReview } from './entities/agent-sessions/review';
export { ToolApproval } from './entities/agent-sessions/tool-approval';
export { Agent, type AgentOptions } from './entities/agents/agent';
export { UserApiKey } from './entities/api-keys/api-key';
+export { CalendarNote } from './entities/calendar/note';
export { ChannelActivity } from './entities/channels/activity';
export { ChannelPicture } from './entities/channels/picture';
export { ChatGeneration, ChatMessage } from './entities/chats/generation';
diff --git a/packages/sdk/tests/calendar-notes.test.ts b/packages/sdk/tests/calendar-notes.test.ts
new file mode 100644
index 0000000000..4aef6ca402
--- /dev/null
+++ b/packages/sdk/tests/calendar-notes.test.ts
@@ -0,0 +1,151 @@
+import { afterEach, expect, test } from 'bun:test';
+import type { CalendarOccurrence } from '../generated/storage/types.gen';
+import { Macro } from '../src/macro';
+
+const originalFetch = globalThis.fetch;
+afterEach(() => {
+ globalThis.fetch = originalFetch;
+});
+
+const occurrence: CalendarOccurrence = {
+ eventId: 'event-1',
+ occurrenceKey: '2026-10-23T14:00:00+00:00',
+ isCancelled: false,
+ time: {
+ kind: 'timed',
+ startsAt: '2026-10-23T14:00:00Z',
+ endsAt: '2026-10-23T15:00:00Z',
+ },
+};
+
+function recordingMacro() {
+ const requests: Request[] = [];
+ let teamId: string | null = null;
+ let linked = false;
+ globalThis.fetch = (async (input, init) => {
+ const request = input instanceof Request ? input : new Request(input, init);
+ requests.push(request);
+ if (new URL(request.url).pathname === '/meeting-notes/documents') {
+ return Response.json({
+ documents: [{ documentId: 'note-1', name: 'Design notes' }],
+ teams: [{ id: 'team-1', name: 'Design' }],
+ });
+ }
+ if (request.method === 'PUT') {
+ const body = await request.clone().json();
+ teamId = body.teamId;
+ linked = true;
+ return new Response(null, { status: 204 });
+ }
+ if (request.method === 'DELETE') {
+ linked = false;
+ return new Response(null, { status: 204 });
+ }
+ return Response.json(
+ linked
+ ? [
+ {
+ documentId: 'note-1',
+ name: 'Design notes',
+ canManage: true,
+ team: teamId ? { id: teamId, name: 'Design' } : null,
+ },
+ ]
+ : [],
+ );
+ }) as typeof fetch;
+ return {
+ requests,
+ macro: new Macro({
+ env: 'dev',
+ token: 'test-token',
+ hosts: { calendar: 'https://calendar.example.test' },
+ }),
+ };
+}
+
+test('meeting notes use occurrence-scoped handles and explicit optional team grants', async () => {
+ const { macro, requests } = recordingMacro();
+ const picker = await macro.calendar.noteDocuments('Design');
+ const document = picker.documents[0].document;
+ const team = picker.teams[0].team;
+ expect(document.id).toBe('note-1');
+ const event = macro.calendar.event(occurrence.eventId);
+ const note = await event.linkNote(document, occurrence);
+ expect(await requests[1].clone().json()).toEqual({ teamId: null });
+ expect(new URL(requests[1].url).searchParams.get('occurrenceKey')).toBe(
+ occurrence.occurrenceKey,
+ );
+ expect(await note.team()).toBeUndefined();
+ await note.setTeam(team);
+ expect((await note.team())?.id).toBe('team-1');
+ await note.setTeam();
+ expect(await note.team()).toBeUndefined();
+ const listed = await event.notes(occurrence);
+ expect((await listed[0].document()).id).toBe(document.id);
+ const beforeSeededRead = requests.length;
+ expect(await listed[0].name()).toBe('Design notes');
+ expect(requests).toHaveLength(beforeSeededRead);
+ await note.unlink();
+ expect(await event.notes(occurrence)).toEqual([]);
+ expect(
+ requests
+ .filter((request) => request.method === 'DELETE')
+ .map((request) => new URL(request.url).pathname),
+ ).toEqual(['/events/event-1/notes/note-1']);
+});
+
+test('a mismatched occurrence cannot share a document or issue a request', async () => {
+ const { macro, requests } = recordingMacro();
+ await expect(
+ macro.calendar
+ .event('different-event')
+ .linkNote(macro.documents.byId('note-1'), occurrence),
+ ).rejects.toThrow('different event');
+ expect(requests).toHaveLength(0);
+});
+
+test('a document owner can discover and revoke an unavailable meeting grant', async () => {
+ const { macro } = recordingMacro();
+ const requests: Request[] = [];
+ globalThis.fetch = (async (input, init) => {
+ const request = input instanceof Request ? input : new Request(input, init);
+ requests.push(request);
+ if (request.method === 'DELETE') return new Response(null, { status: 204 });
+ return Response.json([
+ {
+ eventId: occurrence.eventId,
+ occurrenceKey: occurrence.occurrenceKey,
+ eventTitle: 'Unavailable meeting',
+ documentName: 'Design notes',
+ team: { id: 'team-1', name: 'Design' },
+ },
+ ]);
+ }) as typeof fetch;
+ const links = await macro.documents.byId('note-1').meetingNotes();
+ expect(links[0].eventTitle).toBe('Unavailable meeting');
+ expect((await links[0].note.team())?.id).toBe('team-1');
+ await links[0].note.unlink();
+ expect(new URL(requests[1].url).pathname).toBe(
+ '/events/event-1/notes/note-1',
+ );
+ expect(new URL(requests[1].url).searchParams.get('occurrenceKey')).toBe(
+ occurrence.occurrenceKey,
+ );
+});
+
+test('a rejected share surfaces the error without retrying or granting team access', async () => {
+ const { macro, requests } = recordingMacro();
+ const event = macro.calendar.event(occurrence.eventId);
+ const note = await event.linkNote(macro.documents.byId('note-1'), occurrence);
+ expect(await note.team()).toBeUndefined();
+ let attempts = 0;
+ globalThis.fetch = (async (_input) => {
+ attempts++;
+ return Response.json({ message: 'Forbidden' }, { status: 403 });
+ }) as typeof fetch;
+ await expect(note.setTeam(macro.teams.byId('team-1'))).rejects.toThrow();
+ expect(attempts).toBe(1);
+ expect(await note.team()).toBeUndefined();
+ expect(requests).toHaveLength(2);
+});
diff --git a/rules/ast-grep/ts-feature-components-presentational.yml b/rules/ast-grep/ts-feature-components-presentational.yml
index 24eab62211..a74bfc31eb 100644
--- a/rules/ast-grep/ts-feature-components-presentational.yml
+++ b/rules/ast-grep/ts-feature-components-presentational.yml
@@ -13,6 +13,7 @@ note: |-
untyped wire JSON for property-changed rows. In block-agent, `ui/` is
the presentation layer and `component/` is the composition layer.
files:
+ - apps/web/src/features/calendar-notes/components/**
- apps/web/src/features/access-requests/components/**
- apps/web/src/features/agent-activity/components/**
- apps/web/src/features/agent-dms/components/**
diff --git a/rules/ast-grep/ts-feature-core-pure.yml b/rules/ast-grep/ts-feature-core-pure.yml
index 9c3b652ef9..2b24d7eb4d 100644
--- a/rules/ast-grep/ts-feature-core-pure.yml
+++ b/rules/ast-grep/ts-feature-core-pure.yml
@@ -15,6 +15,7 @@ note: |-
The shared @core/util/base64 codec, cron helpers, and dateSearch/parseTime parser are pure utilities and may be reused.
Block-agent names its rendering layers `ui/` and `component/`.
files:
+ - apps/web/src/features/calendar-notes/core/**
- apps/web/src/features/access-requests/core/**
- apps/web/src/features/agent-activity/core/**
- apps/web/src/features/agent-dms/core/**
diff --git a/rules/ast-grep/ts-feature-data-no-ui.yml b/rules/ast-grep/ts-feature-data-no-ui.yml
index d87689084e..ce1ac9754e 100644
--- a/rules/ast-grep/ts-feature-data-no-ui.yml
+++ b/rules/ast-grep/ts-feature-data-no-ui.yml
@@ -11,6 +11,8 @@ note: |-
with fake clients and controllers with fake capabilities; neither imports
rendering code, including block-agent’s `ui/` and `component/` layers.
files:
+ - apps/web/src/features/calendar-notes/queries/**
+ - apps/web/src/features/calendar-notes/primitives/**
- apps/web/src/features/access-requests/queries/**
- apps/web/src/features/access-requests/primitives/**
- apps/web/src/features/agent-activity/queries/**
diff --git a/rules/ast-grep/ts-feature-layers-use-context.yml b/rules/ast-grep/ts-feature-layers-use-context.yml
index 368a72e4d8..1b090e4153 100644
--- a/rules/ast-grep/ts-feature-layers-use-context.yml
+++ b/rules/ast-grep/ts-feature-layers-use-context.yml
@@ -15,6 +15,10 @@ note: |-
`files` in each ts-/tsx-feature-* rule. Block-agent uses `ui/` for
presentation and `component/` for composition.
files:
+ - apps/web/src/features/calendar-notes/queries/**
+ - apps/web/src/features/calendar-notes/primitives/**
+ - apps/web/src/features/calendar-notes/components/**
+ - apps/web/src/features/calendar-notes/views/**
- apps/web/src/features/access-requests/primitives/**
- apps/web/src/features/access-requests/views/**
- apps/web/src/features/agent-activity/queries/**
diff --git a/rules/ast-grep/tsx-feature-components-presentational.yml b/rules/ast-grep/tsx-feature-components-presentational.yml
index 1b1df55668..614317e202 100644
--- a/rules/ast-grep/tsx-feature-components-presentational.yml
+++ b/rules/ast-grep/tsx-feature-components-presentational.yml
@@ -13,6 +13,7 @@ note: |-
untyped wire JSON for property-changed rows. In block-agent, `ui/` is
the presentation layer and `component/` is the composition layer.
files:
+ - apps/web/src/features/calendar-notes/components/**
- apps/web/src/features/access-requests/components/**
- apps/web/src/features/agent-activity/components/**
- apps/web/src/features/agent-dms/components/**
diff --git a/rules/ast-grep/tsx-feature-core-pure.yml b/rules/ast-grep/tsx-feature-core-pure.yml
index fdafc8237b..d7dab46180 100644
--- a/rules/ast-grep/tsx-feature-core-pure.yml
+++ b/rules/ast-grep/tsx-feature-core-pure.yml
@@ -15,6 +15,7 @@ note: |-
The shared @core/util/base64 codec, cron helpers, and dateSearch/parseTime parser are pure utilities and may be reused.
Block-agent names its rendering layers `ui/` and `component/`.
files:
+ - apps/web/src/features/calendar-notes/core/**
- apps/web/src/features/access-requests/core/**
- apps/web/src/features/agent-activity/core/**
- apps/web/src/features/agent-dms/core/**
diff --git a/rules/ast-grep/tsx-feature-data-no-ui.yml b/rules/ast-grep/tsx-feature-data-no-ui.yml
index 76224a64a8..30cb739c21 100644
--- a/rules/ast-grep/tsx-feature-data-no-ui.yml
+++ b/rules/ast-grep/tsx-feature-data-no-ui.yml
@@ -11,6 +11,8 @@ note: |-
with fake clients and controllers with fake capabilities; neither imports
rendering code, including block-agent’s `ui/` and `component/` layers.
files:
+ - apps/web/src/features/calendar-notes/queries/**
+ - apps/web/src/features/calendar-notes/primitives/**
- apps/web/src/features/access-requests/queries/**
- apps/web/src/features/access-requests/primitives/**
- apps/web/src/features/agent-activity/queries/**
diff --git a/rules/ast-grep/tsx-feature-layers-use-context.yml b/rules/ast-grep/tsx-feature-layers-use-context.yml
index f7a7a62332..8c8dc74b21 100644
--- a/rules/ast-grep/tsx-feature-layers-use-context.yml
+++ b/rules/ast-grep/tsx-feature-layers-use-context.yml
@@ -15,6 +15,10 @@ note: |-
`files` in each ts-/tsx-feature-* rule. Block-agent uses `ui/` for
presentation and `component/` for composition.
files:
+ - apps/web/src/features/calendar-notes/queries/**
+ - apps/web/src/features/calendar-notes/primitives/**
+ - apps/web/src/features/calendar-notes/components/**
+ - apps/web/src/features/calendar-notes/views/**
- apps/web/src/features/access-requests/primitives/**
- apps/web/src/features/access-requests/views/**
- apps/web/src/features/agent-activity/queries/**
diff --git a/services/calendar_service/AGENTS.md b/services/calendar_service/AGENTS.md
index 16a366fdd4..dc0cad1c8d 100644
--- a/services/calendar_service/AGENTS.md
+++ b/services/calendar_service/AGENTS.md
@@ -16,7 +16,7 @@ gateway `/calendar` prefix.
## Scope
- Owns: the Google Calendar push webhook, calendar mutation routes, calendar
- sync scheduling/outbox, and the backfill queue worker.
+ sync scheduling/outbox, meeting-note link routes, and the backfill queue worker.
- Not here: calendar domain logic and the Postgres/Google adapters →
`crates/calendar_events`, `crates/calendar_scheduling`.
@@ -45,6 +45,8 @@ gateway `/calendar` prefix.
- The router is mounted at both `/` and `/calendar` (`GATEWAY_PATH_PREFIX` in
`src/api.rs`) because the gateway forwards the path unchanged.
+- Meeting-note routes remain mounted with calendar sync disabled; compose their
+ repository and document access service from the primary database.
- Reauth-required notifications ride the shared `LinkManagerQueue`, consumed by
`email_service`; don't add a second calendar-specific reconnect notification.
- Forward `team_ooo_changed` to both inbox and teammate refresh notifications;
diff --git a/services/calendar_service/Cargo.toml b/services/calendar_service/Cargo.toml
index 8623cc73b0..4a445a035c 100644
--- a/services/calendar_service/Cargo.toml
+++ b/services/calendar_service/Cargo.toml
@@ -28,12 +28,14 @@ calendar_events = { path = "../../crates/calendar_events", features = [
"google",
"inbound",
"postgres",
+ "notes",
] }
calendar_scheduling = { path = "../../crates/calendar_scheduling", features = ["calendar", "inbound", "postgres"] }
chrono = { workspace = true }
connection_gateway_client = { path = "../../crates/connection_gateway_client" }
email_db_client = { path = "../../crates/email_db_client" }
email_utils = { path = "../../crates/email_utils" }
+entity_access = { path = "../../crates/entity_access", default-features = false, features = ["outbound", "ports"] }
futures = { workspace = true }
google_token = { path = "../../crates/google_token" }
macro_auth = { path = "../../crates/macro_auth" }
diff --git a/services/calendar_service/src/api.rs b/services/calendar_service/src/api.rs
index 218952cff4..539eef8244 100644
--- a/services/calendar_service/src/api.rs
+++ b/services/calendar_service/src/api.rs
@@ -64,6 +64,13 @@ fn swagger_ui() -> Router {
}
fn api_router(state: ApiContext) -> Router<ApiContext> {
+ let notes = calendar_events::inbound::notes_router::notes_router(
+ calendar_events::inbound::notes_router::NotesRouterState::new(
+ state.calendar_notes.clone(),
+ state.note_access.clone(),
+ state.authorization_state.clone(),
+ ),
+ );
let team_settings = calendar_events::inbound::team_router::team_calendar_settings_router(
calendar_events::inbound::team_router::CalendarTeamRouterState::new(
state.calendar_team_service.clone(),
@@ -74,6 +81,7 @@ fn api_router(state: ApiContext) -> Router<ApiContext> {
// provider write would never be reflected locally.
if state.config.calendar_sync_enabled {
calendar_watch::router()
+ .merge(notes)
.merge(team_settings)
.nest(
"/scheduling",
@@ -96,6 +104,6 @@ fn api_router(state: ApiContext) -> Router<ApiContext> {
state.authorization_state.clone(),
)))
} else {
- calendar_watch::router().merge(team_settings)
+ calendar_watch::router().merge(team_settings).merge(notes)
}
}
diff --git a/services/calendar_service/src/api/context.rs b/services/calendar_service/src/api/context.rs
index bb7a9d4d52..0362772cd2 100644
--- a/services/calendar_service/src/api/context.rs
+++ b/services/calendar_service/src/api/context.rs
@@ -18,6 +18,14 @@ use crate::config::Config;
pub type AuthorizationService = MacroAuthorizationServiceImpl<MacroAuthJwtValidator>;
/// Calendar grant/watch service backing the push webhook.
pub type CalendarGrantService = CalendarService<PgCalendarRepository>;
+/// Meeting-note links with current meeting and team audiences.
+pub type CalendarNotesService = calendar_events::domain::notes::MeetingNotes<
+ calendar_events::outbound::pg_notes::PgNoteRepository,
+>;
+/// Shared document permission boundary.
+pub type NoteAccessService = entity_access::domain::service::EntityAccessServiceImpl<
+ entity_access::outbound::PgAccessRepository,
+>;
/// Team-sharing policy service with viewer refresh notifications.
pub type CalendarTeamSvc = calendar_events::domain::team::CalendarTeamServiceImpl<
calendar_events::outbound::pg_team::PgCalendarTeamRepository,
@@ -56,6 +64,10 @@ pub struct ApiContext {
pub authorization_state: MacroAuthorizationState<AuthorizationService>,
/// Calendar grant/watch service backing the push webhook.
pub calendar_service: Arc<CalendarGrantService>,
+ /// Persistent meeting-note links.
+ pub calendar_notes: Arc<CalendarNotesService>,
+ /// Document ownership receipts required before sharing notes.
+ pub note_access: Arc<NoteAccessService>,
/// User-initiated calendar mutation service.
pub calendar_mutation_service: Arc<CalendarMutationSvc>,
/// Read-only team-sharing preferences and personal availability inclusion.
diff --git a/services/calendar_service/src/api/swagger.rs b/services/calendar_service/src/api/swagger.rs
index 6ecf215e20..953a8dfd23 100644
--- a/services/calendar_service/src/api/swagger.rs
+++ b/services/calendar_service/src/api/swagger.rs
@@ -9,6 +9,11 @@ use utoipa::OpenApi;
#[openapi(
paths(
crate::health::health_handler,
+ calendar_events::inbound::notes_router::event_notes,
+ calendar_events::inbound::notes_router::note_documents,
+ calendar_events::inbound::notes_router::document_note_links,
+ calendar_events::inbound::notes_router::link_event_note,
+ calendar_events::inbound::notes_router::unlink_event_note,
calendar_events::inbound::replacement_router::prepare_calendar_replacement,
calendar_events::inbound::replacement_router::confirm_calendar_replacement,
calendar_events::inbound::replacement_router::calendar_replacement_status,
diff --git a/services/calendar_service/src/main.rs b/services/calendar_service/src/main.rs
index 1dd1606a3b..37abc57cb3 100644
--- a/services/calendar_service/src/main.rs
+++ b/services/calendar_service/src/main.rs
@@ -321,6 +321,14 @@ async fn main() -> anyhow::Result<()> {
config: Arc::new(config),
authorization_state,
calendar_service,
+ calendar_notes: Arc::new(calendar_events::domain::notes::MeetingNotes::new(
+ calendar_events::outbound::pg_notes::PgNoteRepository::new(db.clone()),
+ )),
+ note_access: Arc::new(
+ entity_access::domain::service::EntityAccessServiceImpl::new(
+ entity_access::outbound::PgAccessRepository::new(db.clone()),
+ ),
+ ),
calendar_mutation_service,
calendar_team_service,
scheduling_service,