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(email): add opt-in read receipts for sent messages (#8646)

gbirmane2cbf4a9cf46
diff --git a/.sqlx/query-163fa0170324c974aacef9994a92701fde037a3113321ce78d29804e1276c167.json b/.sqlx/query-163fa0170324c974aacef9994a92701fde037a3113321ce78d29804e1276c167.json
new file mode 100644
index 0000000000..d2cef23115
--- /dev/null
+++ b/.sqlx/query-163fa0170324c974aacef9994a92701fde037a3113321ce78d29804e1276c167.json
@@ -0,0 +1,43 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO email_settings (link_id, signature_on_replies_forwards, signature, read_receipts_enabled)\n VALUES ($1, COALESCE($2, FALSE), $3, COALESCE($4, FALSE))\n ON CONFLICT (link_id)\n DO UPDATE SET\n signature_on_replies_forwards = COALESCE($2, email_settings.signature_on_replies_forwards),\n signature = COALESCE($3, email_settings.signature),\n read_receipts_enabled = COALESCE($4, email_settings.read_receipts_enabled),\n updated_at = NOW()\n RETURNING link_id, signature_on_replies_forwards, signature, read_receipts_enabled\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "link_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "signature_on_replies_forwards",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 2,
+ "name": "signature",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "read_receipts_enabled",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Bool",
+ "Text",
+ "Bool"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ true,
+ false
+ ]
+ },
+ "hash": "163fa0170324c974aacef9994a92701fde037a3113321ce78d29804e1276c167"
+}
diff --git a/.sqlx/query-1cd3d12ac72da02f60fc8466960f516f90c7200be2d31d02f2abcfe44d452716.json b/.sqlx/query-1cd3d12ac72da02f60fc8466960f516f90c7200be2d31d02f2abcfe44d452716.json
new file mode 100644
index 0000000000..9cc663509b
--- /dev/null
+++ b/.sqlx/query-1cd3d12ac72da02f60fc8466960f516f90c7200be2d31d02f2abcfe44d452716.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "INSERT INTO email_message_read_receipts (message_id, token)\n VALUES ($1, $2)\n ON CONFLICT (message_id) DO UPDATE SET token = email_message_read_receipts.token\n RETURNING token",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "token",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "1cd3d12ac72da02f60fc8466960f516f90c7200be2d31d02f2abcfe44d452716"
+}
diff --git a/.sqlx/query-2f751429d2d4337eba900ff8431c0431f999ca145a9eb74055f8a1f0523473cc.json b/.sqlx/query-2f751429d2d4337eba900ff8431c0431f999ca145a9eb74055f8a1f0523473cc.json
new file mode 100644
index 0000000000..d75ab0316c
--- /dev/null
+++ b/.sqlx/query-2f751429d2d4337eba900ff8431c0431f999ca145a9eb74055f8a1f0523473cc.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT read_receipts_enabled FROM email_settings WHERE link_id = $1",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "read_receipts_enabled",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "2f751429d2d4337eba900ff8431c0431f999ca145a9eb74055f8a1f0523473cc"
+}
diff --git a/.sqlx/query-e8a7f3c048d9491523f7f8edc5632db0f5fa2d33b35bf6180307c46ca2d40fb7.json b/.sqlx/query-913d72a0c7f476c831938f9d2e5871c213de40d76b095dd73290f6f9c655aae1.json
similarity index 52%
rename from .sqlx/query-e8a7f3c048d9491523f7f8edc5632db0f5fa2d33b35bf6180307c46ca2d40fb7.json
rename to .sqlx/query-913d72a0c7f476c831938f9d2e5871c213de40d76b095dd73290f6f9c655aae1.json
index 9ec6c079bd..e445033b21 100644
--- a/.sqlx/query-e8a7f3c048d9491523f7f8edc5632db0f5fa2d33b35bf6180307c46ca2d40fb7.json
+++ b/.sqlx/query-913d72a0c7f476c831938f9d2e5871c213de40d76b095dd73290f6f9c655aae1.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT l.id as \"id!\", l.macro_id as \"macro_id!\",\n l.fusionauth_user_id as \"fusionauth_user_id!\",\n l.email_address as \"email_address!\",\n l.provider as \"provider!: _\",\n l.is_sync_active as \"is_sync_active!\",\n l.is_primary as \"is_primary!\",\n l.needs_reauth as \"needs_reauth!\",\n l.last_sync_error_at,\n l.created_at as \"created_at!\",\n l.updated_at as \"updated_at!\",\n s.signature_on_replies_forwards as \"signature_on_replies_forwards?\",\n s.signature,\n CASE WHEN l.provider = 'OUTLOOK' THEN\n CASE WHEN NOT EXISTS (SELECT 1 FROM email_sync_streams ss WHERE ss.link_id = l.id AND ss.generation = l.sync_generation AND ss.kind IN ('folder_catalog','mail_folder'))\n THEN 'Init'::email_backfill_job_status\n WHEN EXISTS (SELECT 1 FROM email_sync_streams ss WHERE ss.link_id = l.id AND ss.generation = l.sync_generation AND ss.kind IN ('folder_catalog','mail_folder') AND NOT ss.initial_complete)\n OR EXISTS (SELECT 1 FROM email_message_reconciliation mr WHERE mr.link_id = l.id AND mr.generation = l.sync_generation AND mr.is_import)\n THEN 'InProgress'::email_backfill_job_status\n ELSE 'Complete'::email_backfill_job_status END\n ELSE bj.status END as \"latest_backfill_status?: _\",\n c.sfs_photo_url as \"photo_url?\",\n CASE WHEN l.provider = 'OUTLOOK' THEN COALESCE(ms.granted_scopes, '{}') ELSE COALESCE(g.granted_scopes, '{}') END AS \"provider_granted_scopes!\",\n (CASE WHEN l.provider = 'OUTLOOK' THEN ms.calendar_disabled_at ELSE g.calendar_disabled_at END IS NOT NULL) AS \"calendar_disabled!\",\n EXISTS (\n SELECT 1 FROM calendar_accounts ca WHERE ca.email_link_id = l.id\n ) AS \"has_calendar_data!\"\n FROM (\n SELECT el.id, el.macro_id, el.fusionauth_user_id, el.email_address,\n el.provider, el.is_sync_active, el.is_primary, el.needs_reauth,\n el.last_sync_error_at, el.created_at, el.updated_at,el.sync_generation,el.grant_generation\n FROM email_links el\n WHERE el.macro_id = $1\n UNION\n SELECT el.id, el.macro_id, el.fusionauth_user_id, el.email_address,\n el.provider, el.is_sync_active, el.is_primary, el.needs_reauth,\n el.last_sync_error_at, el.created_at, el.updated_at,el.sync_generation,el.grant_generation\n FROM email_links el\n JOIN macro_user_links mul ON el.id = mul.link_id\n WHERE mul.primary_macro_id = $1\n ) l\n LEFT JOIN email_link_google_scopes g ON g.link_id = l.id\n LEFT JOIN email_link_microsoft_scopes ms ON ms.link_id = l.id AND ms.grant_generation = l.grant_generation\n LEFT JOIN email_settings s ON s.link_id = l.id\n LEFT JOIN LATERAL (\n SELECT status FROM email_backfill_jobs\n WHERE link_id = l.id\n ORDER BY created_at DESC\n LIMIT 1\n ) bj ON true\n LEFT JOIN email_contacts c\n ON c.link_id = l.id AND LOWER(c.email_address) = LOWER(l.email_address)\n ORDER BY l.created_at DESC\n ",
+ "query": "\n SELECT l.id as \"id!\", l.macro_id as \"macro_id!\",\n l.fusionauth_user_id as \"fusionauth_user_id!\",\n l.email_address as \"email_address!\",\n l.provider as \"provider!: _\",\n l.is_sync_active as \"is_sync_active!\",\n l.is_primary as \"is_primary!\",\n l.needs_reauth as \"needs_reauth!\",\n l.last_sync_error_at,\n l.created_at as \"created_at!\",\n l.updated_at as \"updated_at!\",\n s.signature_on_replies_forwards as \"signature_on_replies_forwards?\",\n s.signature,\n s.read_receipts_enabled as \"read_receipts_enabled?\",\n CASE WHEN l.provider = 'OUTLOOK' THEN\n CASE WHEN NOT EXISTS (SELECT 1 FROM email_sync_streams ss WHERE ss.link_id = l.id AND ss.generation = l.sync_generation AND ss.kind IN ('folder_catalog','mail_folder'))\n THEN 'Init'::email_backfill_job_status\n WHEN EXISTS (SELECT 1 FROM email_sync_streams ss WHERE ss.link_id = l.id AND ss.generation = l.sync_generation AND ss.kind IN ('folder_catalog','mail_folder') AND NOT ss.initial_complete)\n OR EXISTS (SELECT 1 FROM email_message_reconciliation mr WHERE mr.link_id = l.id AND mr.generation = l.sync_generation AND mr.is_import)\n THEN 'InProgress'::email_backfill_job_status\n ELSE 'Complete'::email_backfill_job_status END\n ELSE bj.status END as \"latest_backfill_status?: _\",\n c.sfs_photo_url as \"photo_url?\",\n CASE WHEN l.provider = 'OUTLOOK' THEN COALESCE(ms.granted_scopes, '{}') ELSE COALESCE(g.granted_scopes, '{}') END AS \"provider_granted_scopes!\",\n (CASE WHEN l.provider = 'OUTLOOK' THEN ms.calendar_disabled_at ELSE g.calendar_disabled_at END IS NOT NULL) AS \"calendar_disabled!\",\n EXISTS (\n SELECT 1 FROM calendar_accounts ca WHERE ca.email_link_id = l.id\n ) AS \"has_calendar_data!\"\n FROM (\n SELECT el.id, el.macro_id, el.fusionauth_user_id, el.email_address,\n el.provider, el.is_sync_active, el.is_primary, el.needs_reauth,\n el.last_sync_error_at, el.created_at, el.updated_at,el.sync_generation,el.grant_generation\n FROM email_links el\n WHERE el.macro_id = $1\n UNION\n SELECT el.id, el.macro_id, el.fusionauth_user_id, el.email_address,\n el.provider, el.is_sync_active, el.is_primary, el.needs_reauth,\n el.last_sync_error_at, el.created_at, el.updated_at,el.sync_generation,el.grant_generation\n FROM email_links el\n JOIN macro_user_links mul ON el.id = mul.link_id\n WHERE mul.primary_macro_id = $1\n ) l\n LEFT JOIN email_link_google_scopes g ON g.link_id = l.id\n LEFT JOIN email_link_microsoft_scopes ms ON ms.link_id = l.id AND ms.grant_generation = l.grant_generation\n LEFT JOIN email_settings s ON s.link_id = l.id\n LEFT JOIN LATERAL (\n SELECT status FROM email_backfill_jobs\n WHERE link_id = l.id\n ORDER BY created_at DESC\n LIMIT 1\n ) bj ON true\n LEFT JOIN email_contacts c\n ON c.link_id = l.id AND LOWER(c.email_address) = LOWER(l.email_address)\n ORDER BY l.created_at DESC\n ",
"describe": {
"columns": [
{
@@ -80,6 +80,11 @@
},
{
"ordinal": 13,
+ "name": "read_receipts_enabled?",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 14,
"name": "latest_backfill_status?: _",
"type_info": {
"Custom": {
@@ -97,22 +102,22 @@
}
},
{
- "ordinal": 14,
+ "ordinal": 15,
"name": "photo_url?",
"type_info": "Text"
},
{
- "ordinal": 15,
+ "ordinal": 16,
"name": "provider_granted_scopes!",
"type_info": "TextArray"
},
{
- "ordinal": 16,
+ "ordinal": 17,
"name": "calendar_disabled!",
"type_info": "Bool"
},
{
- "ordinal": 17,
+ "ordinal": 18,
"name": "has_calendar_data!",
"type_info": "Bool"
}
@@ -136,6 +141,7 @@
null,
false,
true,
+ false,
null,
true,
null,
@@ -143,5 +149,5 @@
null
]
},
- "hash": "e8a7f3c048d9491523f7f8edc5632db0f5fa2d33b35bf6180307c46ca2d40fb7"
+ "hash": "913d72a0c7f476c831938f9d2e5871c213de40d76b095dd73290f6f9c655aae1"
}
diff --git a/.sqlx/query-b9151a8d786e553b1d03de00a93f9370a3850a6a165b3ca0634d1f8222c2b1a5.json b/.sqlx/query-b9151a8d786e553b1d03de00a93f9370a3850a6a165b3ca0634d1f8222c2b1a5.json
new file mode 100644
index 0000000000..ddc4fcf8af
--- /dev/null
+++ b/.sqlx/query-b9151a8d786e553b1d03de00a93f9370a3850a6a165b3ca0634d1f8222c2b1a5.json
@@ -0,0 +1,42 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT r.message_id, r.open_count, r.first_opened_at, r.last_opened_at\n FROM email_message_read_receipts r\n JOIN email_messages m ON m.id = r.message_id\n WHERE m.thread_id = $1 AND m.link_id = ANY($2) AND m.is_sent\n ORDER BY m.internal_date_ts DESC NULLS LAST, r.message_id\n LIMIT $3",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "message_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "open_count",
+ "type_info": "Int4"
+ },
+ {
+ "ordinal": 2,
+ "name": "first_opened_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 3,
+ "name": "last_opened_at",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "UuidArray",
+ "Int8"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ true,
+ true
+ ]
+ },
+ "hash": "b9151a8d786e553b1d03de00a93f9370a3850a6a165b3ca0634d1f8222c2b1a5"
+}
diff --git a/.sqlx/query-d728d837465a8c930ea6fd8d69117d216c66bf5fa08d07a44b9f4b5503280111.json b/.sqlx/query-d728d837465a8c930ea6fd8d69117d216c66bf5fa08d07a44b9f4b5503280111.json
deleted file mode 100644
index 19f2172a05..0000000000
--- a/.sqlx/query-d728d837465a8c930ea6fd8d69117d216c66bf5fa08d07a44b9f4b5503280111.json
+++ /dev/null
@@ -1,36 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n INSERT INTO email_settings (link_id, signature_on_replies_forwards, signature)\n VALUES ($1, COALESCE($2, FALSE), $3)\n ON CONFLICT (link_id)\n DO UPDATE SET\n signature_on_replies_forwards = COALESCE($2, email_settings.signature_on_replies_forwards),\n signature = COALESCE($3, email_settings.signature),\n updated_at = NOW()\n RETURNING link_id, signature_on_replies_forwards, signature\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "link_id",
- "type_info": "Uuid"
- },
- {
- "ordinal": 1,
- "name": "signature_on_replies_forwards",
- "type_info": "Bool"
- },
- {
- "ordinal": 2,
- "name": "signature",
- "type_info": "Text"
- }
- ],
- "parameters": {
- "Left": [
- "Uuid",
- "Bool",
- "Text"
- ]
- },
- "nullable": [
- false,
- false,
- true
- ]
- },
- "hash": "d728d837465a8c930ea6fd8d69117d216c66bf5fa08d07a44b9f4b5503280111"
-}
diff --git a/.sqlx/query-f69d2ac9d0be422ed1b42f04ce1d903d3f19a8bb85f19c40563ef812746cea51.json b/.sqlx/query-f19b1211d617153488352d7d202c12d4d2bcec0aa57b065e19932af3eecd60b2.json
similarity index 63%
rename from .sqlx/query-f69d2ac9d0be422ed1b42f04ce1d903d3f19a8bb85f19c40563ef812746cea51.json
rename to .sqlx/query-f19b1211d617153488352d7d202c12d4d2bcec0aa57b065e19932af3eecd60b2.json
index 627475f42b..b0b27f4c87 100644
--- a/.sqlx/query-f69d2ac9d0be422ed1b42f04ce1d903d3f19a8bb85f19c40563ef812746cea51.json
+++ b/.sqlx/query-f19b1211d617153488352d7d202c12d4d2bcec0aa57b065e19932af3eecd60b2.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT link_id, signature_on_replies_forwards, signature\n FROM email_settings\n WHERE link_id = $1\n ",
+ "query": "\n SELECT link_id, signature_on_replies_forwards, signature, read_receipts_enabled\n FROM email_settings\n WHERE link_id = $1\n ",
"describe": {
"columns": [
{
@@ -17,6 +17,11 @@
"ordinal": 2,
"name": "signature",
"type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "read_receipts_enabled",
+ "type_info": "Bool"
}
],
"parameters": {
@@ -27,8 +32,9 @@
"nullable": [
false,
false,
- true
+ true,
+ false
]
},
- "hash": "f69d2ac9d0be422ed1b42f04ce1d903d3f19a8bb85f19c40563ef812746cea51"
+ "hash": "f19b1211d617153488352d7d202c12d4d2bcec0aa57b065e19932af3eecd60b2"
}
diff --git a/.sqlx/query-f9951cfb41afb227eafc6f93105d53fdbe6d73df948870c25fd67cb97e7dc4d7.json b/.sqlx/query-f9951cfb41afb227eafc6f93105d53fdbe6d73df948870c25fd67cb97e7dc4d7.json
new file mode 100644
index 0000000000..fd4ce7cbb7
--- /dev/null
+++ b/.sqlx/query-f9951cfb41afb227eafc6f93105d53fdbe6d73df948870c25fd67cb97e7dc4d7.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE email_message_read_receipts r\n SET open_count = r.open_count + 1,\n first_opened_at = COALESCE(r.first_opened_at, $2),\n last_opened_at = $2\n FROM email_messages m\n WHERE r.token = $1\n AND m.id = r.message_id\n AND m.is_sent\n AND (r.last_opened_at IS NULL OR r.last_opened_at <= $3)",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Timestamptz",
+ "Timestamptz"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "f9951cfb41afb227eafc6f93105d53fdbe6d73df948870c25fd67cb97e7dc4d7"
+}
diff --git a/Cargo.lock b/Cargo.lock
index fe15fd2d10..6fac79a84f 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -7233,6 +7233,7 @@ dependencies = [
"models_email",
"models_pagination",
"non_empty",
+ "rand 0.9.4",
"recursion",
"redis",
"reqwest 0.13.4",
diff --git a/apps/web/src/features/email-compose/primitives/prepare-email-body.test.ts b/apps/web/src/features/email-compose/primitives/prepare-email-body.test.ts
index c597529cae..d6546b7d86 100644
--- a/apps/web/src/features/email-compose/primitives/prepare-email-body.test.ts
+++ b/apps/web/src/features/email-compose/primitives/prepare-email-body.test.ts
@@ -1,6 +1,9 @@
// @vitest-environment jsdom
-import { staticFileReferenceEndpoint } from '@core/constant/servers';
+import {
+ EMAIL_SERVICE_EMBEDDED_HOSTS,
+ staticFileReferenceEndpoint,
+} from '@core/constant/servers';
import { $generateNodesFromDOM } from '@lexical/html';
import { DocumentMentionNode } from '@macro-inc/lexical-core';
import { $getRoot, $nodesOfType, createEditor } from 'lexical';
@@ -136,6 +139,36 @@ describe('prepareEmailBodyFromHtml', () => {
'cid:missing',
]);
});
+ it.each(['reply', 'forward'] as const)(
+ 'drops Macro read-receipt pixels from a quoted %s',
+ (replyType) => {
+ const pixel = `${EMAIL_SERVICE_EMBEDDED_HOSTS[0]}/opens/token`;
+ const original = {
+ ...replyingTo,
+ body_html_sanitized: `<p>Original</p><img src="${pixel}" width="1" height="1"><img src="https://example.com/logo.png">`,
+ };
+ const prepared = prepareEmailBodyFromHtml('<p>My reply</p>', {
+ replyType,
+ replyingTo: original,
+ });
+ expect(quotedImageSources(decodeBase64Utf8(prepared.bodyHtml))).toEqual([
+ null,
+ 'https://example.com/logo.png',
+ ]);
+ const editor = createEmailEditor('My reply');
+ registerToggleAppendedThread(editor);
+ editor.dispatchCommand(TOGGLE_APPEND_EMAIL_THREAD_COMMAND, {
+ replyingTo: original,
+ replyType,
+ visible: true,
+ });
+ const fromEditor = prepareEmailBody(editor, {
+ replyType,
+ replyingTo: original,
+ });
+ expect(decodeBase64Utf8(fromEditor!.bodyHtml)).not.toContain('/opens/');
+ }
+ );
it('does not add a quote block without appendReply (undo-send restore)', () => {
const prepared = prepareEmailBodyFromHtml('<p>hi there</p>');
const decoded = decodeBase64Utf8(prepared.bodyHtml);
diff --git a/apps/web/src/features/email-compose/primitives/prepare-email-body.ts b/apps/web/src/features/email-compose/primitives/prepare-email-body.ts
index 0a7320e139..73d42f185d 100644
--- a/apps/web/src/features/email-compose/primitives/prepare-email-body.ts
+++ b/apps/web/src/features/email-compose/primitives/prepare-email-body.ts
@@ -3,15 +3,19 @@ import {
normalizeContentId,
staticFileIdsByContentId,
} from '@app/features/email-message/core/inline-images';
+import { readReceiptPixelPrefixes } from '@app/features/email-message/core/read-receipt';
import { convertBookingLinkMentionsToLinks } from '@core/component/LexicalMarkdown/utils/convertBookingLinkMentionsToLinks';
import { convertDocumentMentionsToLinks } from '@core/component/LexicalMarkdown/utils/convertDocumentMentionsToLinks';
-import { staticFileReferenceEndpoint } from '@core/constant/servers';
+import {
+ EMAIL_SERVICE_EMBEDDED_HOSTS,
+ staticFileReferenceEndpoint,
+} from '@core/constant/servers';
import { encodeBase64UrlUtf8 } from '@core/util/base64';
import { formatEmailDate } from '@core/util/date';
import { $generateHtmlFromNodes, $generateNodesFromDOM } from '@lexical/html';
import { $createQuoteNode, $isQuoteNode } from '@lexical/rich-text';
import { $dfsIterator } from '@lexical/utils';
-import { sanitizeEmailHtml } from '@macro-inc/email-renderer';
+import { type ImagePolicy, sanitizeEmailHtml } from '@macro-inc/email-renderer';
import type { DocumentMentionInfo } from '@macro-inc/lexical-core';
import {
$createClassedBlockNode,
@@ -38,6 +42,13 @@ import { flattenConsecutiveParagraphs } from './flatten-consecutive-paragraphs';
export { TOGGLE_APPEND_EMAIL_THREAD_COMMAND } from './email-editor-commands';
+// Quotes always drop Macro pixels: the composer would count an open, and a
+// reply or forward must not carry the original's pixel to new recipients.
+const QUOTED_IMAGES: ImagePolicy = {
+ remote: 'allow',
+ hiddenUrlPrefixes: readReceiptPixelPrefixes(EMAIL_SERVICE_EMBEDDED_HOSTS),
+};
+
export function clearEmailBody(editor: LexicalEditor | undefined) {
if (!editor) return;
editor.update(
@@ -193,7 +204,7 @@ const $appendPreviousEmail = (
} else {
const parser = new DOMParser();
const dom = parser.parseFromString(
- sanitizeEmailHtml(replyingToBodyHTML),
+ sanitizeEmailHtml(replyingToBodyHTML, QUOTED_IMAGES),
'text/html'
);
linkInlineImages(dom, replyingTo);
@@ -400,7 +411,7 @@ function getAppendedReplyElement(
quote.textContent = replyingTo.body_text ?? '';
} else {
const innerDom = new DOMParser().parseFromString(
- sanitizeEmailHtml(replyingToBodyHTML),
+ sanitizeEmailHtml(replyingToBodyHTML, QUOTED_IMAGES),
'text/html'
);
linkInlineImages(innerDom, replyingTo);
diff --git a/apps/web/src/features/email-message/components/email-message-top-bar.test.tsx b/apps/web/src/features/email-message/components/email-message-top-bar.test.tsx
new file mode 100644
index 0000000000..b5436a7aaf
--- /dev/null
+++ b/apps/web/src/features/email-message/components/email-message-top-bar.test.tsx
@@ -0,0 +1,63 @@
+import { cleanup, render, screen } from '@solidjs/testing-library';
+import { createSignal, type JSX } from 'solid-js';
+import { afterEach, expect, it, vi } from 'vitest';
+import type { EmailMessage } from '../core/email-message';
+import { formatShortDateTime } from '../core/format-email-date';
+import type { ReadReceipt } from '../core/read-receipt';
+import { EmailMessageTopBar } from './email-message-top-bar';
+
+vi.mock('./email-user-tooltip', () => ({
+ EmailUserTooltip: (props: { children: JSX.Element }) => props.children,
+}));
+
+afterEach(cleanup);
+
+const message = {
+ db_id: 'sent',
+ from: { email: '[email protected]', name: 'Me' },
+ to: [{ email: '[email protected]', name: 'Ada' }],
+ cc: [],
+ bcc: [],
+ internal_date_ts: '2026-10-20T09:00:00Z',
+} as unknown as EmailMessage;
+
+function renderTopBar(readReceipt?: ReadReceipt) {
+ const [expandedHeader, setExpandedHeader] = createSignal(true);
+ return render(() => (
+ <EmailMessageTopBar
+ message={message}
+ focused={false}
+ viewerEmail="[email protected]"
+ isTouch={false}
+ readReceipt={readReceipt}
+ setExpandedBodyId={() => {}}
+ isBodyExpanded={() => true}
+ expandedHeader={expandedHeader}
+ setExpandedHeader={setExpandedHeader}
+ setFocusedMessageId={() => {}}
+ />
+ ));
+}
+
+it('shows no read status for untracked messages', () => {
+ renderTopBar();
+ expect(screen.queryByText('Opened')).toBeNull();
+ expect(screen.queryByText('Not opened')).toBeNull();
+});
+
+it('labels an unopened tracked message', () => {
+ renderTopBar({ openCount: 0 });
+ expect(screen.getByText('Not opened')).toBeTruthy();
+ expect(screen.getByText('Not opened yet')).toBeTruthy();
+});
+
+it('shows opens beside the date and in the expanded details', () => {
+ const last = '2026-10-21T16:40:00Z';
+ renderTopBar({
+ openCount: 1,
+ firstOpenedAt: last,
+ lastOpenedAt: last,
+ });
+ expect(screen.getByText('Opened')).toBeTruthy();
+ expect(screen.getByText(`Opened ${formatShortDateTime(last)}`)).toBeTruthy();
+});
diff --git a/apps/web/src/features/email-message/components/email-message-top-bar.tsx b/apps/web/src/features/email-message/components/email-message-top-bar.tsx
index 5edd2faa7e..d48895040b 100644
--- a/apps/web/src/features/email-message/components/email-message-top-bar.tsx
+++ b/apps/web/src/features/email-message/components/email-message-top-bar.tsx
@@ -1,5 +1,6 @@
import type { EmailMessage } from '@app/features/email-message/core/email-message';
import CaretRight from '@icon/system/regular/caret-right.svg';
+import Checks from '@icon/system/regular/checks.svg';
import { Button, cn, Tooltip } from '@ui';
import {
type Accessor,
@@ -15,6 +16,11 @@ import {
getSenderDisplayName,
} from '../core/email-user';
import { formatFullDate, formatShortDate } from '../core/format-email-date';
+import {
+ type ReadReceipt,
+ readReceiptDetail,
+ readReceiptLabel,
+} from '../core/read-receipt';
import { EmailUserTooltip } from './email-user-tooltip';
import { type EmailMessageAction, MessageActions } from './message-actions';
@@ -24,6 +30,7 @@ interface EmailMessageTopBarProps {
focused: boolean;
viewerEmail?: string;
isTouch: boolean;
+ readReceipt?: ReadReceipt;
setExpandedBodyId: (id: string, expanded: boolean) => void;
isBodyExpanded: Accessor<boolean>;
expandedHeader: Accessor<boolean>;
@@ -83,7 +90,10 @@ function DetailRow(props: {
);
}
-function ExpandedDetails(props: { message: EmailMessage }): JSX.Element {
+function ExpandedDetails(props: {
+ message: EmailMessage;
+ readReceipt?: ReadReceipt;
+}): JSX.Element {
const fromRecipients = createMemo(() =>
props.message.from ? [props.message.from] : []
);
@@ -99,10 +109,35 @@ function ExpandedDetails(props: { message: EmailMessage }): JSX.Element {
{formatFullDate(props.message.internal_date_ts!)}
</div>
</Show>
+ {/* Tooltips don't open on touch, so the full receipt also lives here. */}
+ <Show when={props.readReceipt}>
+ {(receipt) => (
+ <div class="text-xs text-ink-extra-muted tabular-nums select-text cursor-text">
+ {readReceiptDetail(receipt())}
+ </div>
+ )}
+ </Show>
</div>
);
}
+function ReadReceiptStatus(props: { receipt: ReadReceipt }): JSX.Element {
+ const opened = () => props.receipt.openCount > 0;
+ return (
+ <Tooltip as="span" label={readReceiptDetail(props.receipt)}>
+ <span
+ class={cn(
+ 'flex items-center gap-1 shrink-0 text-xs whitespace-nowrap',
+ opened() ? 'text-accent' : 'text-ink-extra-muted/60'
+ )}
+ >
+ <Checks class="size-3.5" aria-hidden="true" />
+ {readReceiptLabel(props.receipt)}
+ </span>
+ </Tooltip>
+ );
+}
+
function CollapsedRecipientList(props: {
recipients: Recipient[];
currentUserEmail?: string;
@@ -139,6 +174,7 @@ function HeaderTopRow(props: {
onReply?: (action: EmailMessageAction) => void;
hiddenActions?: EmailMessageAction[];
currentUserEmail?: string;
+ readReceipt?: ReadReceipt;
}): JSX.Element {
const allRecipients = createMemo(() => [
...props.message.to,
@@ -197,6 +233,9 @@ function HeaderTopRow(props: {
hiddenActions={props.hiddenActions}
/>
</div>
+ <Show when={props.readReceipt}>
+ {(receipt) => <ReadReceiptStatus receipt={receipt()} />}
+ </Show>
<Show when={props.message.internal_date_ts}>
<Tooltip
as="span"
@@ -257,10 +296,14 @@ export function EmailMessageTopBar(props: EmailMessageTopBarProps) {
onReply={props.onReply}
hiddenActions={props.hiddenActions}
currentUserEmail={userEmail()}
+ readReceipt={props.readReceipt}
/>
</div>
<Show when={props.expandedHeader()}>
- <ExpandedDetails message={props.message} />
+ <ExpandedDetails
+ message={props.message}
+ readReceipt={props.readReceipt}
+ />
</Show>
</Show>
</div>
diff --git a/apps/web/src/features/email-message/context/email-rendering-context.tsx b/apps/web/src/features/email-message/context/email-rendering-context.tsx
index 7f190e9c41..950d6f89fa 100644
--- a/apps/web/src/features/email-message/context/email-rendering-context.tsx
+++ b/apps/web/src/features/email-message/context/email-rendering-context.tsx
@@ -10,6 +10,8 @@ import type { EmailAttachment } from '../core/email-message';
export interface EmailRenderingContextValue {
theme: Accessor<ThemeColorParams>;
images?: ImagePolicy;
+ /** Macro read-receipt pixel URL prefixes, hidden unless a body may count an open. */
+ readReceiptPixels?: readonly string[];
prepareLinks?: (container: HTMLElement) => void;
resolveImages(
root: ShadowRoot,
diff --git a/apps/web/src/features/email-message/core/format-email-date.ts b/apps/web/src/features/email-message/core/format-email-date.ts
index eabb5f3e74..bc79a466bb 100644
--- a/apps/web/src/features/email-message/core/format-email-date.ts
+++ b/apps/web/src/features/email-message/core/format-email-date.ts
@@ -14,6 +14,15 @@ export function formatFullDate(date: DateValue): string {
.replace(',', '');
}
+export function formatShortDateTime(date: DateValue): string {
+ return new Date(date).toLocaleString('en-US', {
+ month: 'short',
+ day: 'numeric',
+ hour: 'numeric',
+ minute: '2-digit',
+ });
+}
+
export function formatShortDate(date: DateValue): string {
const d = new Date(date);
if (d.getFullYear() !== new Date().getFullYear()) {
diff --git a/apps/web/src/features/email-message/core/read-receipt.test.ts b/apps/web/src/features/email-message/core/read-receipt.test.ts
new file mode 100644
index 0000000000..6167332acb
--- /dev/null
+++ b/apps/web/src/features/email-message/core/read-receipt.test.ts
@@ -0,0 +1,125 @@
+import { describe, expect, it } from 'vitest';
+import { message } from '../tests/messages';
+import { formatShortDateTime } from './format-email-date';
+import {
+ readReceiptDetail,
+ readReceiptLabel,
+ readReceiptPixelPrefixes,
+ showsReadReceiptPixel,
+ type ViewerInbox,
+} from './read-receipt';
+
+const first = '2026-10-20T09:15:00Z';
+const last = '2026-10-21T16:40:00Z';
+
+const work: ViewerInbox = {
+ id: 'work',
+ email_address: '[email protected]',
+ sendAs: [{ email_address: '[email protected]' }],
+};
+const personal: ViewerInbox = {
+ id: 'personal',
+ email_address: '[email protected]',
+};
+const delegated: ViewerInbox = {
+ id: 'boss',
+ email_address: '[email protected]',
+ sendAs: null,
+};
+const inboxes = [work, personal, delegated];
+
+describe('read receipt pixel visibility', () => {
+ it('shows the pixel on a copy the viewer received from someone else', () => {
+ const received = message('received', {
+ link_id: 'personal',
+ from: { email: '[email protected]' },
+ });
+ expect(showsReadReceiptPixel(received, inboxes)).toBe(true);
+ });
+
+ it.each([
+ ['their primary address', '[email protected]'],
+ ['a send-as alias', '[email protected]'],
+ ['an inbox they are a delegate of', '[email protected]'],
+ ])('hides the pixel on a copy the viewer sent from %s', (_, from) => {
+ const sent = message('sent', { link_id: 'work', from: { email: from } });
+ expect(showsReadReceiptPixel(sent, inboxes)).toBe(false);
+ });
+
+ it('hides the pixel on a copy the sender also received', () => {
+ const ccSelf = message('cc-self', {
+ link_id: 'personal',
+ from: { email: '[email protected]' },
+ cc: [{ email: '[email protected]' }],
+ });
+ expect(showsReadReceiptPixel(ccSelf, inboxes)).toBe(false);
+ });
+
+ it('hides the pixel on a Gmail sent copy from an unrecognised address', () => {
+ const sent = message('sent', {
+ link_id: 'boss',
+ from: { email: '[email protected]' },
+ labels: [{ provider_label_id: 'SENT' }],
+ });
+ expect(showsReadReceiptPixel(sent, inboxes)).toBe(false);
+ });
+
+ it('hides the pixel on copies seen through sharing or before inboxes load', () => {
+ const shared = message('shared', {
+ link_id: 'someone-else',
+ from: { email: '[email protected]' },
+ });
+ expect(showsReadReceiptPixel(shared, inboxes)).toBe(false);
+ expect(showsReadReceiptPixel({ ...shared, link_id: 'personal' }, [])).toBe(
+ false
+ );
+ });
+});
+
+describe('read receipts', () => {
+ it('builds one pixel prefix per host without doubled slashes', () => {
+ expect(
+ readReceiptPixelPrefixes([
+ 'https://gateway.macro.com/email',
+ 'http://localhost:8087/',
+ ])
+ ).toEqual([
+ 'https://gateway.macro.com/email/opens/',
+ 'http://localhost:8087/opens/',
+ ]);
+ });
+
+ it('labels unopened and opened messages', () => {
+ expect(readReceiptLabel({ openCount: 0 })).toBe('Not opened');
+ expect(readReceiptDetail({ openCount: 0 })).toBe('Not opened yet');
+ expect(
+ readReceiptLabel({
+ openCount: 2,
+ firstOpenedAt: first,
+ lastOpenedAt: last,
+ })
+ ).toBe('Opened');
+ });
+
+ it('describes a single open by its time', () => {
+ expect(
+ readReceiptDetail({
+ openCount: 1,
+ firstOpenedAt: last,
+ lastOpenedAt: last,
+ })
+ ).toBe(`Opened ${formatShortDateTime(last)}`);
+ });
+
+ it('describes repeat opens with count, first and last times', () => {
+ expect(
+ readReceiptDetail({
+ openCount: 3,
+ firstOpenedAt: first,
+ lastOpenedAt: last,
+ })
+ ).toBe(
+ `Opened 3 times · first ${formatShortDateTime(first)} · last ${formatShortDateTime(last)}`
+ );
+ });
+});
diff --git a/apps/web/src/features/email-message/core/read-receipt.ts b/apps/web/src/features/email-message/core/read-receipt.ts
new file mode 100644
index 0000000000..0fe0b94757
--- /dev/null
+++ b/apps/web/src/features/email-message/core/read-receipt.ts
@@ -0,0 +1,55 @@
+import type { EmailMessage } from './email-message';
+import { formatShortDateTime } from './format-email-date';
+
+/** Open tracking for one of the viewer's sent messages. */
+export interface ReadReceipt {
+ openCount: number;
+ firstOpenedAt?: string;
+ lastOpenedAt?: string;
+}
+
+/** An inbox the viewer owns or is a delegate of, with its send-as aliases. */
+export interface ViewerInbox {
+ id: string;
+ email_address: string;
+ sendAs?: readonly { email_address: string }[] | null;
+}
+
+const PIXEL_PATH = '/opens/';
+
+/** URL prefixes of read-receipt pixels served by these email-service hosts. */
+export function readReceiptPixelPrefixes(hosts: readonly string[]): string[] {
+ return hosts.map((host) => `${host.replace(/\/+$/, '')}${PIXEL_PATH}`);
+}
+
+/** Only a recipient reading their own copy counts as an open. The sender's
+ * copies stay hidden, including one they received by CC'ing themselves, as do
+ * copies seen only through sharing and every copy while inboxes load. */
+export function showsReadReceiptPixel(
+ message: Pick<EmailMessage, 'link_id' | 'from' | 'labels'>,
+ inboxes: readonly ViewerInbox[]
+): boolean {
+ if (!inboxes.some((inbox) => inbox.id === message.link_id)) return false;
+ // Gmail labels the sender's copy even when its alias lookup failed.
+ if (message.labels.some((label) => label.provider_label_id === 'SENT'))
+ return false;
+ const from = message.from?.email.toLowerCase();
+ if (!from) return true;
+ return !inboxes.some(
+ (inbox) =>
+ inbox.email_address.toLowerCase() === from ||
+ inbox.sendAs?.some((alias) => alias.email_address.toLowerCase() === from)
+ );
+}
+
+export function readReceiptLabel(receipt: ReadReceipt): string {
+ return receipt.openCount > 0 ? 'Opened' : 'Not opened';
+}
+
+export function readReceiptDetail(receipt: ReadReceipt): string {
+ const { openCount, firstOpenedAt, lastOpenedAt } = receipt;
+ if (openCount === 0 || !lastOpenedAt) return 'Not opened yet';
+ const last = formatShortDateTime(lastOpenedAt);
+ if (openCount === 1 || !firstOpenedAt) return `Opened ${last}`;
+ return `Opened ${openCount} times · first ${formatShortDateTime(firstOpenedAt)} · last ${last}`;
+}
diff --git a/apps/web/src/features/email-message/primitives/email-message-body.test.ts b/apps/web/src/features/email-message/primitives/email-message-body.test.ts
index a5b909614c..5179dc2911 100644
--- a/apps/web/src/features/email-message/primitives/email-message-body.test.ts
+++ b/apps/web/src/features/email-message/primitives/email-message-body.test.ts
@@ -166,6 +166,64 @@ describe('independent email body', () => {
expect(revoke).toHaveBeenCalledWith('blob:email');
expect(disconnect).toHaveBeenCalled();
});
+ it('loads Macro pixels only when the copy may count an open', async () => {
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ observe() {}
+ disconnect() {}
+ }
+ );
+ const pixel = 'https://mail.test/opens/token';
+ const sources = (host: HTMLElement | undefined) =>
+ [...(host?.shadowRoot?.querySelectorAll('img[src]') ?? [])].map((image) =>
+ image.getAttribute('src')
+ );
+ const root = createRoot((dispose) => {
+ const [value, setValue] = createSignal(
+ message('tracked', {
+ body_html_sanitized: `<p>Hi</p><img src="${pixel}"><img src="https://images.test/logo.png">`,
+ })
+ );
+ const [show, setShow] = createSignal(false);
+ const body = createEmailMessageBody(
+ {
+ get message() {
+ return value();
+ },
+ ...bodyOptions,
+ get showReadReceiptPixel() {
+ return show();
+ },
+ },
+ {
+ theme: () => theme,
+ images: { remote: 'allow' },
+ readReceiptPixels: ['https://mail.test/opens/'],
+ resolveImages: async () => {},
+ }
+ );
+ return { dispose, body, setValue, setShow };
+ });
+ try {
+ await Promise.resolve();
+ expect(sources(root.body.host())).toEqual([
+ 'https://images.test/logo.png',
+ ]);
+ root.setShow(true);
+ expect(sources(root.body.host())).toEqual([
+ pixel,
+ 'https://images.test/logo.png',
+ ]);
+
+ root.setValue(message('plain'));
+ const plain = root.body.host();
+ root.setShow(false);
+ expect(root.body.host()).toBe(plain);
+ } finally {
+ root.dispose();
+ }
+ });
it.each([
{ body_macro: 'A document mention' },
{
diff --git a/apps/web/src/features/email-message/primitives/email-message-body.ts b/apps/web/src/features/email-message/primitives/email-message-body.ts
index c2d6be9eab..347a874793 100644
--- a/apps/web/src/features/email-message/primitives/email-message-body.ts
+++ b/apps/web/src/features/email-message/primitives/email-message-body.ts
@@ -20,6 +20,8 @@ export interface EmailMessageBodyProps {
setFocusedMessageId: (messageId: string | undefined) => void;
showFullContent?: boolean;
isFocused: boolean;
+ /** Load Macro read-receipt pixels, so viewing this copy counts as an open. */
+ showReadReceiptPixel?: boolean;
}
/** Solid only translates reactive inputs and owns the renderer's lifetime. */
@@ -28,6 +30,17 @@ export function createEmailMessageBody(
renderingContext: EmailRenderingContextValue
) {
const [showFullHTML, setShowFullHTML] = createSignal(false);
+ const pixels = renderingContext.readReceiptPixels ?? [];
+ // Pixels stay hidden while ownership is unknown. Only a body that carries one
+ // re-renders when it may show, so other bodies keep their image resources.
+ const hiddenPixels = () => {
+ const { body_html_sanitized: html, body_replyless: replyless } =
+ props.message;
+ const carriesPixel = pixels.some(
+ (prefix) => html?.includes(prefix) || replyless?.includes(prefix)
+ );
+ return props.showReadReceiptPixel && carriesPixel ? [] : pixels;
+ };
// Thread refreshes replace message objects after every draft save. Only
// changes to rendering inputs should dispose the body and its image resources.
const content = createMemo(
@@ -43,17 +56,22 @@ export function createEmailMessageBody(
normalizeFonts:
props.isPersonal &&
!props.message.from?.email?.toLowerCase().endsWith('@macro.com'),
+ hiddenPixels: hiddenPixels(),
}),
undefined,
{ equals: deepEqual }
);
- const prepared = createMemo(() =>
- prepareEmailBody(content(), {
+ const prepared = createMemo(() => {
+ const images = renderingContext.images;
+ return prepareEmailBody(content(), {
showQuotedContent: showFullHTML(),
showFullContent: content().showFullContent,
- images: renderingContext.images,
- })
- );
+ images: images && {
+ ...images,
+ hiddenUrlPrefixes: content().hiddenPixels,
+ },
+ });
+ });
const rendered = createMemo(() => {
// Preserve the app's existing Markdown paths without starting hidden HTML
// resources behind them. Their Lexical semantics stay at the app boundary.
diff --git a/apps/web/src/features/email-message/rendering-adapter.ts b/apps/web/src/features/email-message/rendering-adapter.ts
index d1849fbeab..ca0efa9b98 100644
--- a/apps/web/src/features/email-message/rendering-adapter.ts
+++ b/apps/web/src/features/email-message/rendering-adapter.ts
@@ -1,7 +1,11 @@
import { ENABLE_PROXY_EMAIL_IMAGES } from '@core/constant/featureFlags';
-import { SERVER_HOSTS } from '@core/constant/servers';
+import {
+ EMAIL_SERVICE_EMBEDDED_HOSTS,
+ SERVER_HOSTS,
+} from '@core/constant/servers';
import { interceptMailtoLinks } from '@core/util/interceptMailtoLinks';
import type { EmailRenderingContextValue } from './context/email-rendering-context';
+import { readReceiptPixelPrefixes } from './core/read-receipt';
import { fetchImagesViaPlatform, resolveCidImages } from './image-adapter';
import { createEmailTheme } from './theme';
@@ -15,6 +19,7 @@ export function createEmailRenderingContext(): EmailRenderingContextValue {
? `${SERVER_HOSTS['image-proxy-service']}/proxy`
: undefined,
},
+ readReceiptPixels: readReceiptPixelPrefixes(EMAIL_SERVICE_EMBEDDED_HOSTS),
prepareLinks: interceptMailtoLinks,
async resolveImages(root, attachments, lifetime) {
const blobUrls: string[] = [];
diff --git a/apps/web/src/features/email-message/views/email-message.tsx b/apps/web/src/features/email-message/views/email-message.tsx
index 63a2d83c54..db35fcedfe 100644
--- a/apps/web/src/features/email-message/views/email-message.tsx
+++ b/apps/web/src/features/email-message/views/email-message.tsx
@@ -19,6 +19,8 @@ import {
} from '../core/calendar-invitation';
import { type EmailAttachment, isCalendarFile } from '../core/email-message';
import { inlineContentIds, normalizeContentId } from '../core/inline-images';
+import type { ReadReceipt } from '../core/read-receipt';
+
export interface InvitationRenderOptions {
/** Called before a card action opens something else in the app. */
onNavigate?: () => void;
@@ -35,6 +37,8 @@ export interface EmailMessageViewProps {
) => JSX.Element;
renderOperation?: (message: EmailMessage) => JSX.Element;
renderAvatar?: (message: EmailMessage) => JSX.Element;
+ readReceipt?: ReadReceipt;
+ showReadReceiptPixel?: boolean;
viewerEmail?: string;
isTouch: boolean;
isPersonal: boolean;
@@ -111,6 +115,7 @@ export function EmailMessageView(props: EmailMessageViewProps) {
setFocusedMessageId={() => props.onSelect?.()}
showFullContent={props.showFullContent}
isFocused={props.isSelected}
+ showReadReceiptPixel={props.showReadReceiptPixel}
/>
</div>
);
@@ -186,6 +191,7 @@ export function EmailMessageView(props: EmailMessageViewProps) {
onReply={props.onReply}
isTouch={props.isTouch}
viewerEmail={props.viewerEmail}
+ readReceipt={props.readReceipt}
hiddenActions={
props.onReply ? undefined : ['reply', 'reply-all', 'forward']
}
diff --git a/apps/web/src/features/email-thread/context/email-thread-view-context.tsx b/apps/web/src/features/email-thread/context/email-thread-view-context.tsx
index 603463bfbe..de2e436e59 100644
--- a/apps/web/src/features/email-thread/context/email-thread-view-context.tsx
+++ b/apps/web/src/features/email-thread/context/email-thread-view-context.tsx
@@ -8,6 +8,7 @@ import type {
EmailAttachment,
EmailMessage,
} from '../../email-message/core/email-message';
+import type { ReadReceipt } from '../../email-message/core/read-receipt';
import type { InvitationRenderOptions } from '../../email-message/views/email-message';
import type { EmailThreadContext } from './email-thread-context';
@@ -33,6 +34,8 @@ export interface EmailThreadViewContext {
) => JSX.Element;
renderOperation?: (message: EmailMessage) => JSX.Element;
renderAvatar?: (message: EmailMessage) => JSX.Element;
+ readReceipt?: (message: EmailMessage) => ReadReceipt | undefined;
+ showReadReceiptPixel?: (message: EmailMessage) => boolean;
openAttachment?: (attachment: EmailAttachment) => void;
downloadAttachment?: (attachment: EmailAttachment) => void;
};
diff --git a/apps/web/src/features/email-thread/email-thread.test.tsx b/apps/web/src/features/email-thread/email-thread.test.tsx
index e167d634a4..f0307f5d76 100644
--- a/apps/web/src/features/email-thread/email-thread.test.tsx
+++ b/apps/web/src/features/email-thread/email-thread.test.tsx
@@ -3,7 +3,10 @@ import { createSignal, type ParentProps } from 'solid-js';
import { afterEach, describe, expect, it, vi } from 'vitest';
import type { EmailComposeContextOptions } from '../email-compose/compose-adapter';
import { createComposeContext } from '../email-compose/tests/capabilities';
-import { useEmailThreadViewContext } from './context/email-thread-view-context';
+import {
+ type EmailThreadViewContext,
+ useEmailThreadViewContext,
+} from './context/email-thread-view-context';
import { EmailThread } from './email-thread';
import { createThreadContext, message, thread } from './tests/fixtures';
import { EmailParticipants } from './views/email-participants';
@@ -12,6 +15,7 @@ const mocks = vi.hoisted(() => ({
query: vi.fn(),
clearDraft: vi.fn(),
source: vi.fn(),
+ rendering: vi.fn<(rendering: EmailThreadViewContext['rendering']) => void>(),
composeOptions: vi.fn<(options: EmailComposeContextOptions) => void>(),
started: [] as Promise<void>[],
}));
@@ -77,13 +81,18 @@ vi.mock('../email-message/sender-icon-adapter', () => ({
vi.mock('./calendar-invitation', () => ({
EmailCalendarInvitation: () => null,
}));
+vi.mock('./read-receipts', () => ({
+ createThreadReadReceipts: () => () => undefined,
+}));
vi.mock('./thread-action-adapter', () => ({
createThreadActionAdapter: vi.fn(),
}));
vi.mock('./views/email-thread', () => ({
EmailThreadView: () => {
- const source = useEmailThreadViewContext().thread.source;
+ const context = useEmailThreadViewContext();
+ const source = context.thread.source;
mocks.source(source);
+ mocks.rendering(context.rendering);
return (
<div>
<EmailParticipants />
@@ -185,4 +194,23 @@ describe('email thread query ownership', () => {
.filter(Boolean);
expect(participants).toEqual(['viewer', 'Me']);
});
+
+ it('lets only copies the viewer received load read-receipt pixels', () => {
+ const source = createThreadContext({
+ thread: () => thread([message('first')]),
+ }).source;
+ render(() => (
+ <EmailThread
+ title="Subject"
+ threadId={source.id}
+ source={source}
+ threadTransport={() => 'graphql'}
+ />
+ ));
+ const show = mocks.rendering.mock.calls[0][0].showReadReceiptPixel;
+ expect(show?.(message('received'))).toBe(true);
+ expect(show?.(message('sent', { from: { email: '[email protected]' } }))).toBe(
+ false
+ );
+ });
});
diff --git a/apps/web/src/features/email-thread/email-thread.tsx b/apps/web/src/features/email-thread/email-thread.tsx
index 9a60b04e0b..088535955b 100644
--- a/apps/web/src/features/email-thread/email-thread.tsx
+++ b/apps/web/src/features/email-thread/email-thread.tsx
@@ -29,6 +29,7 @@ import type {
EmailMessage,
} from '../email-message/core/email-message';
import { operationSettled } from '../email-message/core/message-operation';
+import { showsReadReceiptPixel } from '../email-message/core/read-receipt';
import { EmailMessageOperation } from '../email-message/email-message-operation';
import { createEmailRenderingContext } from '../email-message/rendering-adapter';
import { EmailSenderIcon } from '../email-message/sender-icon-adapter';
@@ -44,6 +45,7 @@ import type {
import type { EmailThreadOrganizationStatus } from './context/email-thread-view-context';
import { EmailThreadOperations } from './email-thread-operations';
import { createOptimisticThreadSend } from './primitives/optimistic-send';
+import { createThreadReadReceipts } from './read-receipts';
import { createThreadActionAdapter } from './thread-action-adapter';
import {
EmailThreadSurface,
@@ -143,6 +145,9 @@ export function EmailThread(props: EmailThreadProps) {
renderAvatar: (message: EmailMessage) => (
<EmailSenderIcon message={message} />
),
+ readReceipt: createThreadReadReceipts(() => props.threadId()),
+ showReadReceiptPixel: (message: EmailMessage) =>
+ showsReadReceiptPixel(message, compose.accounts.inboxes()),
},
};
const rendering = createEmailRenderingContext();
diff --git a/apps/web/src/features/email-thread/read-receipts.ts b/apps/web/src/features/email-thread/read-receipts.ts
new file mode 100644
index 0000000000..dd0e43ad59
--- /dev/null
+++ b/apps/web/src/features/email-thread/read-receipts.ts
@@ -0,0 +1,30 @@
+import { useFeatureFlag } from '@app/lib/analytics/posthog';
+import { enableEmailReadReceipts } from '@core/constant/featureFlags';
+import { useEmailLinksQuery } from '@queries/email/link';
+import { useThreadReadReceiptsQuery } from '@queries/email/read-receipts';
+import { queryReadyGate } from '@queries/gate';
+import type { Accessor } from 'solid-js';
+import type { EmailMessage } from '../email-message/core/email-message';
+import type { ReadReceipt } from '../email-message/core/read-receipt';
+
+/** Looks up opens for the viewer's tracked messages. Never suspends: the
+ * thread renders without receipts until they load. */
+export function createThreadReadReceipts(threadId: Accessor<string>) {
+ const flag = useFeatureFlag(enableEmailReadReceipts);
+ const links = useEmailLinksQuery();
+ const tracking = () =>
+ flag().enabled &&
+ queryReadyGate(links) &&
+ links.data.links.some((link) => link.settings.read_receipts_enabled);
+ const query = useThreadReadReceiptsQuery(threadId, tracking);
+ return (message: EmailMessage): ReadReceipt | undefined => {
+ if (!tracking() || !queryReadyGate(query)) return undefined;
+ const receipt = query.data[message.db_id];
+ if (!receipt) return undefined;
+ return {
+ openCount: receipt.open_count,
+ firstOpenedAt: receipt.first_opened_at ?? undefined,
+ lastOpenedAt: receipt.last_opened_at ?? undefined,
+ };
+ };
+}
diff --git a/apps/web/src/features/email-thread/views/message-container.tsx b/apps/web/src/features/email-thread/views/message-container.tsx
index f0b0099021..8a8de5530d 100644
--- a/apps/web/src/features/email-thread/views/message-container.tsx
+++ b/apps/web/src/features/email-thread/views/message-container.tsx
@@ -102,6 +102,8 @@ export function MessageContainer(props: MessageContainerProps) {
renderInvitation={rendering.renderInvitation}
renderAvatar={rendering.renderAvatar}
renderOperation={rendering.renderOperation}
+ readReceipt={rendering.readReceipt?.(props.message)}
+ showReadReceiptPixel={rendering.showReadReceiptPixel?.(props.message)}
viewerEmail={threadContext.viewerEmail()}
isTouch={threadContext.isTouch()}
isPersonal={isPersonalMessage(
diff --git a/apps/web/src/features/settings/email-settings.test.tsx b/apps/web/src/features/settings/email-settings.test.tsx
new file mode 100644
index 0000000000..8f455826cd
--- /dev/null
+++ b/apps/web/src/features/settings/email-settings.test.tsx
@@ -0,0 +1,80 @@
+/**
+ * @vitest-environment jsdom
+ */
+
+import { cleanup, render, screen } from '@solidjs/testing-library';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { EmailSettings } from './email-settings';
+
+const mocks = vi.hoisted(() => ({
+ query: {} as Record<string, unknown>,
+}));
+
+vi.mock('@app/lib/analytics/posthog', () => ({
+ useFeatureFlag: () => () => ({ enabled: true }),
+}));
+vi.mock('@core/component/Toast/Toast', () => ({
+ toast: { success: vi.fn(), failure: vi.fn() },
+}));
+vi.mock('@core/constant/SettingsState', () => ({
+ useSettingsState: () => ({ openSettings: vi.fn() }),
+}));
+vi.mock('@core/constant/settingsTabsConfig', () => ({
+ useSettingsTabAvailable: () => () => false,
+}));
+vi.mock('@core/context/user', () => ({
+ useUserId: () => () => 'macro|[email protected]',
+}));
+vi.mock('@core/email-link', () => ({
+ useEmailLinks: () => ({ query: mocks.query }),
+}));
+vi.mock('@queries/email/settings', () => ({
+ useUpdateEmailSettingsMutation: () => ({ isPending: false, mutate: vi.fn() }),
+}));
+vi.mock('./Email', () => ({ EmailCard: () => null }));
+vi.mock('./SignatureSection', () => ({ SignatureSection: () => null }));
+
+const link = {
+ id: 'link-1',
+ macro_id: 'macro|[email protected]',
+ email_address: '[email protected]',
+ settings: { read_receipts_enabled: true },
+};
+
+afterEach(() => {
+ cleanup();
+});
+
+describe('EmailSettings read receipts', () => {
+ it('keeps cached account switches when a refetch fails', () => {
+ mocks.query = {
+ isPending: false,
+ isError: true,
+ isSuccess: false,
+ data: { links: [link] },
+ refetch: vi.fn(),
+ };
+ render(() => <EmailSettings />);
+
+ expect(
+ screen.getByRole('switch', {
+ name: 'Read receipts for [email protected]',
+ })
+ ).toBeTruthy();
+ expect(screen.queryByText("Couldn't load accounts")).toBeNull();
+ });
+
+ it('offers a retry only when no accounts have loaded', () => {
+ mocks.query = {
+ isPending: false,
+ isError: true,
+ isSuccess: false,
+ data: undefined,
+ refetch: vi.fn(),
+ };
+ render(() => <EmailSettings />);
+
+ expect(screen.getByText("Couldn't load accounts")).toBeTruthy();
+ expect(screen.queryByRole('switch')).toBeNull();
+ });
+});
diff --git a/apps/web/src/features/settings/email-settings.tsx b/apps/web/src/features/settings/email-settings.tsx
index c3e8da0164..4275197c17 100644
--- a/apps/web/src/features/settings/email-settings.tsx
+++ b/apps/web/src/features/settings/email-settings.tsx
@@ -1,11 +1,17 @@
import { useFeatureFlag } from '@app/lib/analytics/posthog';
-import { enableEmailSignatures } from '@core/constant/featureFlags';
+import { toast } from '@core/component/Toast/Toast';
+import {
+ enableEmailReadReceipts,
+ enableEmailSignatures,
+} from '@core/constant/featureFlags';
import { useSettingsState } from '@core/constant/SettingsState';
import { useSettingsTabAvailable } from '@core/constant/settingsTabsConfig';
import { useUserId } from '@core/context/user';
import { useEmailLinks } from '@core/email-link';
import { fireAndForget } from '@core/util/fireAndForget';
-import { Button } from '@ui';
+import { useUpdateEmailSettingsMutation } from '@queries/email/settings';
+import type { Link as EmailLink } from '@service-email/generated/schemas';
+import { Button, ToggleSwitch } from '@ui';
import { For, Show, Suspense } from 'solid-js';
import { EmailCard } from './Email';
import {
@@ -18,6 +24,7 @@ import { SignatureSection } from './SignatureSection';
export function EmailSettings() {
const signatures = useFeatureFlag(enableEmailSignatures);
+ const readReceipts = useFeatureFlag(enableEmailReadReceipts);
const { openSettings } = useSettingsState();
const isAvailable = useSettingsTabAvailable();
return (
@@ -55,6 +62,22 @@ export function EmailSettings() {
</Suspense>
</SettingsSection>
</Show>
+ <Show when={readReceipts().enabled}>
+ <SettingsSection
+ title="Read receipts"
+ description="See when recipients open messages you send. Macro adds an invisible image to each message, so opens are approximate: some mail apps load images automatically and others block them. Only people with access to the inbox see its opens."
+ >
+ <Suspense
+ fallback={
+ <p role="status" class="text-sm text-ink-muted">
+ Loading accounts…
+ </p>
+ }
+ >
+ <EmailReadReceipts />
+ </Suspense>
+ </SettingsSection>
+ </Show>
<Show when={isAvailable('Notifications') || isAvailable('Calendar')}>
<SettingsSection title="Related settings">
<SettingsCard>
@@ -150,3 +173,71 @@ function EmailSignatures() {
</Show>
);
}
+
+function EmailReadReceipts() {
+ const userId = useUserId();
+ const { query } = useEmailLinks();
+ const links = () =>
+ (query.data?.links ?? []).filter((link) => link.macro_id === userId());
+ return (
+ <Show
+ when={!query.isPending}
+ fallback={
+ <p role="status" class="text-sm text-ink-muted">
+ Loading accounts…
+ </p>
+ }
+ >
+ <Show
+ when={query.data}
+ fallback={
+ <SettingsCard>
+ <SettingsRow label="Couldn't load accounts">
+ <Button
+ variant="outline"
+ onClick={() => fireAndForget(query.refetch(), 'email-settings')}
+ >
+ Try again
+ </Button>
+ </SettingsRow>
+ </SettingsCard>
+ }
+ >
+ <SettingsCard>
+ <For
+ each={links()}
+ fallback={
+ <SettingsRow label="Connect an email account above to use read receipts." />
+ }
+ >
+ {(link) => <ReadReceiptsRow link={link} />}
+ </For>
+ </SettingsCard>
+ </Show>
+ </Show>
+ );
+}
+
+function ReadReceiptsRow(props: { link: EmailLink }) {
+ const updateSettings = useUpdateEmailSettingsMutation();
+ return (
+ <SettingsRow label={props.link.email_address}>
+ <ToggleSwitch
+ size="md"
+ label={`Read receipts for ${props.link.email_address}`}
+ labelClass="sr-only"
+ checked={props.link.settings.read_receipts_enabled ?? false}
+ disabled={updateSettings.isPending}
+ onChange={(checked) =>
+ updateSettings.mutate(
+ {
+ linkId: props.link.id,
+ settings: { read_receipts_enabled: checked },
+ },
+ { onError: () => toast.failure('Failed to update read receipts.') }
+ )
+ }
+ />
+ </SettingsRow>
+ );
+}
diff --git a/apps/web/src/lib/core/constant/featureFlags.ts b/apps/web/src/lib/core/constant/featureFlags.ts
index cf9847c794..8695132acb 100644
--- a/apps/web/src/lib/core/constant/featureFlags.ts
+++ b/apps/web/src/lib/core/constant/featureFlags.ts
@@ -483,6 +483,15 @@ export const enableEmailSignatures = defineFlag({
default: onInDev,
});
+// Email read receipts: the per-inbox switch in Settings › Email and the
+// opened status on sent messages. Which copies load Macro's pixels, and so
+// count as opens, does not depend on this flag.
+export const enableEmailReadReceipts = defineFlag({
+ key: 'enable-email-read-receipts',
+ env: 'ENABLE_EMAIL_READ_RECEIPTS',
+ default: onInDev,
+});
+
// CRM companies & contacts frontend: the Companies view + sidebar entry, the
// company/contact detail blocks, CRM mentions / quick-access, and CRM rows in
// global search. PostHog-gated (currently targeted at the Macro team in prod)
diff --git a/apps/web/src/lib/core/constant/servers.ts b/apps/web/src/lib/core/constant/servers.ts
index 92cfa89f4d..4d942fcce0 100644
--- a/apps/web/src/lib/core/constant/servers.ts
+++ b/apps/web/src/lib/core/constant/servers.ts
@@ -227,6 +227,16 @@ export const SYNC_PERMISSION_TOKEN_DSS_HOST =
? serverHostRemote['document-storage-service']
: SERVER_HOSTS['document-storage-service'];
+/** Hosts the email service may have embedded in sent mail. Development
+ * proxies rewrite `SERVER_HOSTS`, while the backend embeds its direct URL. */
+export const EMAIL_SERVICE_EMBEDDED_HOSTS: readonly string[] = [
+ ...new Set([
+ SERVER_HOSTS['email-service'],
+ directServerHostRemote['email-service'],
+ serverHostLocal['email-service'],
+ ]),
+];
+
/** Creates endpoint URL for accessing a static file by its ID */
export function staticFileIdEndpoint(id: string): string {
return `${SERVER_HOSTS['static-file']}/file/${id}`;
diff --git a/apps/web/src/lib/queries/email/keys.ts b/apps/web/src/lib/queries/email/keys.ts
index 4e4f19db1f..c405d77e0c 100644
--- a/apps/web/src/lib/queries/email/keys.ts
+++ b/apps/web/src/lib/queries/email/keys.ts
@@ -16,6 +16,9 @@ export const emailKeys = createQueryKeys('email', {
threadMessages: (threadId: string) => ({
queryKey: ['messages', threadId],
}),
+ threadReadReceipts: (threadId: string) => ({
+ queryKey: ['read-receipts', threadId],
+ }),
messageInbox: (messageId: string | undefined) => ({
queryKey: ['message-inbox', messageId],
}),
diff --git a/apps/web/src/lib/queries/email/read-receipts.ts b/apps/web/src/lib/queries/email/read-receipts.ts
new file mode 100644
index 0000000000..b0b9155dbe
--- /dev/null
+++ b/apps/web/src/lib/queries/email/read-receipts.ts
@@ -0,0 +1,39 @@
+import { throwOnErr } from '@core/util/result';
+import { emailClient } from '@service-email/client';
+import type {
+ MessageReadReceipt,
+ ThreadReadReceipts,
+} from '@service-email/generated/schemas';
+import { useQuery } from '@tanstack/solid-query';
+import type { Accessor } from 'solid-js';
+import { emailKeys } from './keys';
+
+/** The viewer's tracked sent messages in one thread, keyed by message id. */
+export type ReadReceiptsByMessage = Record<string, MessageReadReceipt>;
+
+const REFRESH_INTERVAL = 60_000;
+
+function byMessage({ receipts }: ThreadReadReceipts): ReadReceiptsByMessage {
+ return Object.fromEntries(receipts.map((r) => [r.message_id, r]));
+}
+
+function threadReadReceiptsQueryOptions(threadId: string, enabled: boolean) {
+ return {
+ queryKey: emailKeys.threadReadReceipts(threadId).queryKey,
+ queryFn: () =>
+ throwOnErr(() => emailClient.getThreadReadReceipts(threadId)),
+ select: byMessage,
+ enabled,
+ staleTime: REFRESH_INTERVAL,
+ refetchInterval: REFRESH_INTERVAL,
+ refetchOnWindowFocus: true,
+ };
+}
+
+/** Polls while the thread is open; recipients' opens arrive asynchronously. */
+export function useThreadReadReceiptsQuery(
+ threadId: Accessor<string>,
+ enabled: Accessor<boolean>
+) {
+ return useQuery(() => threadReadReceiptsQueryOptions(threadId(), enabled()));
+}
diff --git a/apps/web/src/lib/service-clients/service-email/client.ts b/apps/web/src/lib/service-clients/service-email/client.ts
index 8bb7f822c3..621d4cf8e2 100644
--- a/apps/web/src/lib/service-clients/service-email/client.ts
+++ b/apps/web/src/lib/service-clients/service-email/client.ts
@@ -53,6 +53,7 @@ import type {
SendMessageRequest,
SendMessageResponse,
SharedInboxConflictResponse,
+ ThreadReadReceipts,
TransferDraftRequest,
TransferDraftResponse,
TransferRecoveryResponse,
@@ -227,6 +228,11 @@ export const emailClient = {
errorResponseHandler: forwardCalendarEventErrorHandler,
});
},
+ async getThreadReadReceipts(threadId: string) {
+ return emailFetch<ThreadReadReceipts>(
+ `/email/threads/${threadId}/read-receipts`
+ );
+ },
async init(args?: { linkId?: string; forceShare?: boolean }) {
const params = new URLSearchParams();
if (args?.linkId) params.set('link_id', args.linkId);
diff --git a/apps/web/src/lib/service-clients/service-email/generated/client.ts b/apps/web/src/lib/service-clients/service-email/generated/client.ts
index 8a81ea8a05..7efb96a55c 100644
--- a/apps/web/src/lib/service-clients/service-email/generated/client.ts
+++ b/apps/web/src/lib/service-clients/service-email/generated/client.ts
@@ -66,6 +66,7 @@ import type {
SendMessageRequest,
SendMessageResponse,
SharedInboxConflictResponse,
+ ThreadReadReceipts,
TransferDraftRequest,
TransferDraftResponse,
TransferRecoveryResponse,
@@ -4110,6 +4111,61 @@ export const updateThreadProject = async (
} as updateThreadProjectResponse;
};
+export type getThreadReadReceiptsResponse200 = {
+ data: ThreadReadReceipts;
+ status: 200;
+};
+
+export type getThreadReadReceiptsResponse401 = {
+ data: void;
+ status: 401;
+};
+
+export type getThreadReadReceiptsResponse403 = {
+ data: void;
+ status: 403;
+};
+
+export type getThreadReadReceiptsResponseSuccess =
+ getThreadReadReceiptsResponse200 & {
+ headers: Headers;
+ };
+export type getThreadReadReceiptsResponseError = (
+ | getThreadReadReceiptsResponse401
+ | getThreadReadReceiptsResponse403
+) & {
+ headers: Headers;
+};
+
+export type getThreadReadReceiptsResponse =
+ | getThreadReadReceiptsResponseSuccess
+ | getThreadReadReceiptsResponseError;
+
+export const getGetThreadReadReceiptsUrl = (threadId: string) => {
+ return `/email/threads/${threadId}/read-receipts`;
+};
+
+export const getThreadReadReceipts = async (
+ threadId: string,
+ options?: RequestInit
+): Promise<getThreadReadReceiptsResponse> => {
+ const res = await fetch(getGetThreadReadReceiptsUrl(threadId), {
+ ...options,
+ method: 'GET',
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: getThreadReadReceiptsResponse['data'] = body
+ ? JSON.parse(body)
+ : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as getThreadReadReceiptsResponse;
+};
+
/**
* @summary Health check
*/
@@ -4145,3 +4201,43 @@ export const healthHandler = async (
headers: res.headers,
} as healthHandlerResponse;
};
+
+/**
+ * @summary Every request gets the same uncacheable pixel so the response reveals nothing
+about the token, and each open reaches the server.
+ */
+export type getReadReceiptPixelResponseDefault = {
+ data: unknown;
+ status: number;
+};
+export type getReadReceiptPixelResponseError =
+ getReadReceiptPixelResponseDefault & {
+ headers: Headers;
+ };
+
+export type getReadReceiptPixelResponse = getReadReceiptPixelResponseError;
+
+export const getGetReadReceiptPixelUrl = (token: string) => {
+ return `/opens/${token}`;
+};
+
+export const getReadReceiptPixel = async (
+ token: string,
+ options?: RequestInit
+): Promise<getReadReceiptPixelResponse> => {
+ const res = await fetch(getGetReadReceiptPixelUrl(token), {
+ ...options,
+ method: 'GET',
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: getReadReceiptPixelResponse['data'] = body
+ ? JSON.parse(body)
+ : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as getReadReceiptPixelResponse;
+};
diff --git a/apps/web/src/lib/service-clients/service-email/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-email/generated/schemas/index.ts
index 36002e52b4..4123f3d80d 100644
--- a/apps/web/src/lib/service-clients/service-email/generated/schemas/index.ts
+++ b/apps/web/src/lib/service-clients/service-email/generated/schemas/index.ts
@@ -339,6 +339,9 @@ export * from './messageOperationResponseOperation';
export * from './messageProviderHistoryId';
export * from './messageProviderId';
export * from './messageProviderThreadId';
+export * from './messageReadReceipt';
+export * from './messageReadReceiptFirstOpenedAt';
+export * from './messageReadReceiptLastOpenedAt';
export * from './messageReplyingToId';
export * from './messageScheduledSendTime';
export * from './messageSentAt';
@@ -379,6 +382,7 @@ export * from './scheduledSendStatus';
export * from './sendMessageRequest';
export * from './sendMessageResponse';
export * from './settings';
+export * from './settingsReadReceiptsEnabled';
export * from './settingsSignature';
export * from './settingsSignatureOnRepliesForwards';
export * from './sharedInboxConflictResponse';
@@ -398,6 +402,7 @@ export * from './threadPreviewCursorSenderPhotoUrl';
export * from './threadPreviewCursorSnippet';
export * from './threadPreviewCursorViewedAt';
export * from './threadProviderId';
+export * from './threadReadReceipts';
export * from './threadStateField';
export * from './threadSummary';
export * from './transferDraftRequest';
diff --git a/apps/web/src/lib/service-clients/service-email/generated/schemas/messageReadReceipt.ts b/apps/web/src/lib/service-clients/service-email/generated/schemas/messageReadReceipt.ts
new file mode 100644
index 0000000000..aa796923e6
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-email/generated/schemas/messageReadReceipt.ts
@@ -0,0 +1,25 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * email_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { MessageReadReceiptFirstOpenedAt } from './messageReadReceiptFirstOpenedAt';
+import type { MessageReadReceiptLastOpenedAt } from './messageReadReceiptLastOpenedAt';
+
+/**
+ * Open state of one tracked, sent message.
+ */
+export interface MessageReadReceipt {
+ /** First counted fetch. */
+ first_opened_at?: MessageReadReceiptFirstOpenedAt;
+ /** Latest counted fetch. */
+ last_opened_at?: MessageReadReceiptLastOpenedAt;
+ /** The tracked message. */
+ message_id: string;
+ /**
+ * Counted pixel fetches.
+ * @minimum 0
+ */
+ open_count: number;
+}
diff --git a/apps/web/src/lib/service-clients/service-email/generated/schemas/messageReadReceiptFirstOpenedAt.ts b/apps/web/src/lib/service-clients/service-email/generated/schemas/messageReadReceiptFirstOpenedAt.ts
new file mode 100644
index 0000000000..7520ed3666
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-email/generated/schemas/messageReadReceiptFirstOpenedAt.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * email_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * First counted fetch.
+ */
+export type MessageReadReceiptFirstOpenedAt = string | null;
diff --git a/apps/web/src/lib/service-clients/service-email/generated/schemas/messageReadReceiptLastOpenedAt.ts b/apps/web/src/lib/service-clients/service-email/generated/schemas/messageReadReceiptLastOpenedAt.ts
new file mode 100644
index 0000000000..7d44783dcf
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-email/generated/schemas/messageReadReceiptLastOpenedAt.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * email_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Latest counted fetch.
+ */
+export type MessageReadReceiptLastOpenedAt = string | null;
diff --git a/apps/web/src/lib/service-clients/service-email/generated/schemas/settings.ts b/apps/web/src/lib/service-clients/service-email/generated/schemas/settings.ts
index 51570cc794..4028c75f15 100644
--- a/apps/web/src/lib/service-clients/service-email/generated/schemas/settings.ts
+++ b/apps/web/src/lib/service-clients/service-email/generated/schemas/settings.ts
@@ -4,10 +4,13 @@
* email_service
* OpenAPI spec version: 0.1.0
*/
+import type { SettingsReadReceiptsEnabled } from './settingsReadReceiptsEnabled';
import type { SettingsSignature } from './settingsSignature';
import type { SettingsSignatureOnRepliesForwards } from './settingsSignatureOnRepliesForwards';
export interface Settings {
+ /** Whether messages sent from this inbox carry an open-tracking pixel. */
+ read_receipts_enabled?: SettingsReadReceiptsEnabled;
/** The user's email signature content (HTML). On a patch, omit or send
`null` to leave unchanged (both deserialize to `None`); pass an empty
string to clear it. The column cannot be set to SQL NULL via patch. */
diff --git a/apps/web/src/lib/service-clients/service-email/generated/schemas/settingsReadReceiptsEnabled.ts b/apps/web/src/lib/service-clients/service-email/generated/schemas/settingsReadReceiptsEnabled.ts
new file mode 100644
index 0000000000..bb9c949881
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-email/generated/schemas/settingsReadReceiptsEnabled.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * email_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Whether messages sent from this inbox carry an open-tracking pixel.
+ */
+export type SettingsReadReceiptsEnabled = boolean | null;
diff --git a/apps/web/src/lib/service-clients/service-email/generated/schemas/threadReadReceipts.ts b/apps/web/src/lib/service-clients/service-email/generated/schemas/threadReadReceipts.ts
new file mode 100644
index 0000000000..e4b6bf2067
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-email/generated/schemas/threadReadReceipts.ts
@@ -0,0 +1,14 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * email_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { MessageReadReceipt } from './messageReadReceipt';
+
+/**
+ * Open state of the caller's tracked, sent messages in one thread.
+ */
+export interface ThreadReadReceipts {
+ receipts: MessageReadReceipt[];
+}
diff --git a/apps/web/src/lib/service-clients/service-email/openapi.json b/apps/web/src/lib/service-clients/service-email/openapi.json
index 1fcd7389c8..fe30d6a7e6 100644
--- a/apps/web/src/lib/service-clients/service-email/openapi.json
+++ b/apps/web/src/lib/service-clients/service-email/openapi.json
@@ -3871,6 +3871,42 @@
}
}
},
+ "/email/threads/{thread_id}/read-receipts": {
+ "get": {
+ "tags": ["email"],
+ "operationId": "get_thread_read_receipts",
+ "parameters": [
+ {
+ "name": "thread_id",
+ "in": "path",
+ "description": "Authorized email thread",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ThreadReadReceipts"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": ""
+ },
+ "403": {
+ "description": ""
+ }
+ }
+ }
+ },
"/health": {
"get": {
"tags": ["Health"],
@@ -3889,6 +3925,32 @@
}
}
}
+ },
+ "/opens/{token}": {
+ "get": {
+ "tags": ["email"],
+ "summary": "Every request gets the same uncacheable pixel so the response reveals nothing\nabout the token, and each open reaches the server.",
+ "operationId": "get_read_receipt_pixel",
+ "parameters": [
+ {
+ "name": "token",
+ "in": "path",
+ "description": "Opaque pixel token",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "Transparent pixel, for any token",
+ "content": {
+ "image/gif": {}
+ }
+ }
+ }
+ }
}
},
"components": {
@@ -6949,6 +7011,34 @@
}
}
},
+ "MessageReadReceipt": {
+ "type": "object",
+ "description": "Open state of one tracked, sent message.",
+ "required": ["message_id", "open_count"],
+ "properties": {
+ "first_opened_at": {
+ "type": ["string", "null"],
+ "format": "date-time",
+ "description": "First counted fetch."
+ },
+ "last_opened_at": {
+ "type": ["string", "null"],
+ "format": "date-time",
+ "description": "Latest counted fetch."
+ },
+ "message_id": {
+ "type": "string",
+ "format": "uuid",
+ "description": "The tracked message."
+ },
+ "open_count": {
+ "type": "integer",
+ "format": "int32",
+ "description": "Counted pixel fetches.",
+ "minimum": 0
+ }
+ }
+ },
"ParsedMessage": {
"type": "object",
"required": [
@@ -7270,6 +7360,10 @@
"Settings": {
"type": "object",
"properties": {
+ "read_receipts_enabled": {
+ "type": ["boolean", "null"],
+ "description": "Whether messages sent from this inbox carry an open-tracking pixel."
+ },
"signature": {
"type": ["string", "null"],
"description": "The user's email signature content (HTML). On a patch, omit or send\n`null` to leave unchanged (both deserialize to `None`); pass an empty\nstring to clear it. The column cannot be set to SQL NULL via patch."
@@ -7464,6 +7558,19 @@
}
}
},
+ "ThreadReadReceipts": {
+ "type": "object",
+ "description": "Open state of the caller's tracked, sent messages in one thread.",
+ "required": ["receipts"],
+ "properties": {
+ "receipts": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/MessageReadReceipt"
+ }
+ }
+ }
+ },
"ThreadStateField": {
"type": "string",
"description": "Semantic mailbox facts, independent of folder/category names.",
diff --git a/crates/agent_code_mode/src/domain/documentation.json b/crates/agent_code_mode/src/domain/documentation.json
index f707ad9d38..3f499b5663 100644
--- a/crates/agent_code_mode/src/domain/documentation.json
+++ b/crates/agent_code_mode/src/domain/documentation.json
@@ -88,7 +88,7 @@
{
"name": "email",
"description": "Search, read, draft, and send email.",
- "index": "## email\nSearch, read, draft, and send email.\nRead any symbol below, or one a reference names, with ReadCodeDocs.\n\n### EmailAttachment\nA file attached to an email message.\nExtends `MacroEntity`.\nFields: contentId, dataUrl, filename, id, mimeType, sfsId, size\n- `EmailAttachment.toDocument`: toDocument(): Promise<Document> — The Macro document holding this attachment's content.\n- `EmailAttachment.byId`: static byId(client, id): EmailAttachment — A handle to an attachment by id.\n- `EmailAttachment.from`: static from(client, data): EmailAttachment — Build an attachment from an already-fetched record (pre-seeded, no fetch).\n\n### DraftAttachment\nAn uploaded or forwarded attachment belonging to a draft.\nFields: draft, draftGeneration, forwarded, id\n- `DraftAttachment.complete`: complete(): Promise<void> — Complete verification after uploading the file.\n- `DraftAttachment.remove`: remove(): Promise<void> — Remove this attachment from its draft.\n- `DraftAttachment.toJSON`: toJSON(): { draftGeneration: number; draftId: string; forwarded: boolean; id: string; } — Serialize identity without credentials.\n- `DraftAttachment.byId`: static byId(_client, draft, id, forwarded?, draftGeneration?): DraftAttachment — Construct a draft scoped attachment handle.\n\n### EmailDraft\nA draft email.\nExtends `EmailMessage`.\nFields: bcc, body, cc, draftGeneration, from, id, labels, link, sentAt, subject, to\n- `EmailDraft.addAttachment`: addAttachment(options): Promise<{ attachment: DraftAttachment; contentType: string; uploadUrl: string; }> — Reserve an attachment upload.\n- `EmailDraft.delete`: delete(): Promise<void> — Delete the draft.\n- `EmailDraft.forwardAttachment`: forwardAttachment(attachment): Promise<DraftAttachment> — Forward an existing attachment into this draft.\n- `EmailDraft.removeAttachment`: removeAttachment(attachment): Promise<void> — Remove a draft attachment.\n- `EmailDraft.schedule`: schedule(sendTime, options?): Promise<void> — Schedule this draft for sending.\n- `EmailDraft.unschedule`: unschedule(): Promise<void> — Remove a scheduled send.\n- `EmailDraft.update`: update(options): Promise<void> — Replace draft content without changing its identity or sending it.\n- `EmailDraft.verifyAttachment`: verifyAttachment(attachment): Promise<void> — Complete verification of an uploaded attachment.\n- `EmailDraft.byId`: static byId(client, id): EmailDraft — Construct a lazy draft handle.\n\n### EmailFilter\nAn importance filter matched by sender address or domain.\nExtends `MacroEntity`.\nFields: emailAddress, emailDomain, id, isImportant\n- `EmailFilter.delete`: delete(): Promise<void> — Delete this filter.\n- `EmailFilter.setImportant`: setImportant(isImportant): Promise<void> — Change the importance for the same sender selector.\n- `EmailFilter.byId`: static byId(client, id, inbox?): EmailFilter — Construct a lazy filter handle.\n- `EmailFilter.from`: static from(client, record, inbox?): EmailFilter — Seed from a server record.\n\n### Label\nAn email label.\nExtends `MacroEntity`.\nFields: createdAt, id, labelListVisibility, linkId, messageListVisibility, name, type\n- `Label.delete`: delete(): Promise<void> — Delete this label.\n- `Label.byId`: static byId(client, id): Label — A handle to a label by id.\n- `Label.create`: static create(client, name): Promise<Label> — Create a user label.\n- `Label.list`: static list(client): Promise<Label[]> — All labels across the user's inboxes.\n\n### Link\nAn email link: a connected inbox (e.g.\nExtends `MacroEntity`.\nFields: emailAddress, id, isPrimary, isSyncActive, needsReauth, photoUrl, provider, syncStatus\n- `Link.settingsOperations`: settingsOperations(): Promise<MailboxSettingsOperation[]> — Read category and sender-policy changes for this inbox.\n- `Link.byId`: static byId(client, id): Link — A handle to an email link by id.\n- `Link.list`: static list(client): Promise<Link[]> — The caller's connected email links.\n\n### EmailMessage\nA message in an email thread.\nExtends `MacroEntity`.\nFields: bcc, body, cc, from, id, labels, link, sentAt, subject, to\n- `EmailMessage.addLabel`: addLabel(label): Promise<void> — Add a label to this message.\n- `EmailMessage.completeDraftAttachment`: completeDraftAttachment(attachmentId, draftGeneration?): Promise<void> — Verify an uploaded attachment using the draft generation captured when its upload began.\n- `EmailMessage.downloadEml`: downloadEml(): Promise<Blob> — The message's original source, exactly as Gmail or Outlook holds it, as message/rfc822 bytes for an .eml file.\n- `EmailMessage.operationStatus`: operationStatus(): Promise<MessageOperationResponse> — Read the draft's durable send, upload, or conflict status without retrying it.\n- `EmailMessage.removeLabel`: removeLabel(label): Promise<void> — Remove a label from this message.\n- `EmailMessage.resolveOperation`: resolveOperation(request): Promise<void> — Resolve the displayed operation revision after the user chooses an action.\n- `EmailMessage.thread`: thread(): Promise<EmailThread> — The thread this message belongs to.\n- `EmailMessage.transferDraft`: transferDraft(request): Promise<TransferDraftResponse> — Move a draft to another inbox using a caller-persisted operation UUID.\n- `EmailMessage.byId`: static byId(client, id): EmailMessage — A handle to a message by id.\n- `EmailMessage.from`: static from(client, data): EmailMessage — Build a message from an already-fetched record (pre-seeded, no fetch).\n- `EmailMessage.send`: static send(client, opts): Promise<EmailMessage | undefined> — Send a new email message.\n\n### EmailNamespace (`macro.email`)\n- `EmailNamespace.archive`: archive(threads, archived?): Promise<EmailThread[]> — Archive many threads (or unarchive with false).\n- `EmailNamespace.attachment`: attachment(id): EmailAttachment — A handle to an email attachment by id.\n- `EmailNamespace.blockedSenders`: blockedSenders(): Promise<string[]> — The email addresses currently blocked.\n- `EmailNamespace.blockSender`: blockSender(email): Promise<void> — Block an email sender.\n- `EmailNamespace.byId`: byId(id): EmailThread — A handle to an email thread by id.\n- `EmailNamespace.connectionProviders`: connectionProviders(): Promise<EmailConnectionProviders> — Providers the server currently permits this caller to connect.\n- `EmailNamespace.contacts`: contacts(): Promise<{[key: string]: ContactInfoWithInteraction[]; }> — Address book contacts grouped by the service's interaction buckets.\n- `EmailNamespace.createDraft`: createDraft(options, inbox?): Promise<EmailDraft> — Create a draft without sending it; the inbox defaults to the caller's primary.\n- `EmailNamespace.createLabel`: createLabel(name): Promise<Label> — Create a user label.\n- `EmailNamespace.deleteLabel`: deleteLabel(label): Promise<void> — Delete a label.\n- `EmailNamespace.draftById`: draftById(id): EmailDraft — Construct a lazy draft handle.\n- `EmailNamespace.filters`: filters(inbox?): Promise<EmailFilter[]> — Importance filters.\n- `EmailNamespace.inbox`: inbox(opts?): AsyncGenerator<EmailThread> — The threads in the inbox, most recent first, auto-paginated.\n- `EmailNamespace.label`: label(id): Label — A handle to a label by id.\n- `EmailNamespace.labels`: labels(): Promise<Label[]> — All labels across the user's inboxes.\n- `EmailNamespace.link`: link(id): Link — A handle to a connected inbox (email link) by id.\n- `EmailNamespace.links`: links(): Promise<Link[]> — The caller's connected inboxes (email links).\n- `EmailNamespace.message`: message(id): EmailMessage — A handle to an email message by id.\n- `EmailNamespace.recoverDraftTransfer`: recoverDraftTransfer(operationId): Promise<TransferRecoveryResponse> — Recover a draft move using its original operation UUID; never starts a new move.\n- `EmailNamespace.reminders`: reminders(options?): AsyncGenerator<{ followup: EmailFollowup; thread: EmailThread; }, any, any> — Follow-up reminders with thread handles, automatically paginated.\n- `EmailNamespace.scheduled`: scheduled(options?): AsyncGenerator<EmailDraft> — Scheduled drafts, fetched lazily in bounded pages.\n- `EmailNamespace.search`: search(query, opts?): AsyncGenerator<EmailThread> — Search email threads by subject and content.\n- `EmailNamespace.send`: send(opts): Promise<EmailMessage | undefined> — Send a new email message.\n- `EmailNamespace.unblockSender`: unblockSender(email): Promise<void> — Unblock a previously blocked sender.\n- `EmailNamespace.upsertFilter`: upsertFilter(options, inbox?): Promise<EmailFilter> — Create or replace a filter matching an address or domain.\n\n### EmailThread\nAn email thread.\nExtends `PropertiedEntity`.\nFields: access, accessLevel, createdAt, entityType, id, inboxVisible, isRead, latestInboundAt, latestNonSpamAt, latestOutboundAt, link, project, providerId, updatedAt, search\n- `EmailThread.addEventToCalendar`: addEventToCalendar(message, invitation, options?): Promise<CalendarEvent> — Add a shared event one of this thread's messages carries (a published .ics, such as one sent with Forward by email) to one of the requester's Google calendar...\n- `EmailThread.addLabel`: addLabel(label): Promise<void> — Add a label to every message in the thread.\n- `EmailThread.archive`: archive(archived?): Promise<void> — Archive the thread (or unarchive with false).\n- `EmailThread.attachments`: attachments(): Promise<EmailAttachment[]> — The attachments across this thread's first 100 messages, pre-seeded from the thread detail.\n- `EmailThread.calendarInvitations`: calendarInvitations(): Promise<{[key: string]: InvitationResolution; }> — Calendar invitations resolved from this thread's messages.\n- `EmailThread.followup`: followup(): Promise<EmailFollowupResponse> — Read follow-up state for this thread.\n- `EmailThread.markSeen`: markSeen(): Promise<void> — Mark the thread as seen.\n- `EmailThread.messages`: messages(opts?): Promise<EmailMessage[]> — The messages in this thread, pre-seeded from the list endpoint.\n- `EmailThread.moveToProject`: moveToProject(project): Promise<void> — Attach the thread to a project, or clear the project with null.\n- `EmailThread.operations`: operations(): Promise<MailboxOperation[]> — Read pending or failed mailbox changes without initiating a retry.\n- `EmailThread.participants`: participants(): Promise<ApiContactInfo[]> — Everyone on the thread (senders and recipients), deduped by email.\n- `EmailThread.removeLabel`: removeLabel(label): Promise<void> — Remove a label from every message in the thread.\n- `EmailThread.reply`: reply(opts): Promise<EmailMessage | undefined> — Send a reply within this thread.\n- `EmailThread.setFollowup`: setFollowup(command): Promise<EmailFollowup> — Set or remove a follow-up using a persisted operation id and revision.\n- `EmailThread.subject`: subject(): Promise<string | undefined> — The thread's subject, from its first message with one.\n- `EmailThread.update`: update(options): Promise<void> — Change project membership or share permissions for this thread.\n- `EmailThread.updateState`: updateState(request): Promise<void> — Update provider-neutral read, trash, spam, or star state.\n- `EmailThread.archiveMany`: static archiveMany(client, threads, archived?): Promise<EmailThread[]> — Archive many threads (or unarchive with false), sending one request per 100 threads.\n- `EmailThread.byId`: static byId(client, id): EmailThread — A handle to a thread by id.\n\nFunctions: `draftBody`\n\nTypes: `EmailAttachmentData`, `DraftOptions`, `EmailFilterOptions`, `SendEmailOptions`, `EmailMessageData`, `InboxOptions`, `ReplyEmailOptions`\n"
+ "index": "## email\nSearch, read, draft, and send email.\nRead any symbol below, or one a reference names, with ReadCodeDocs.\n\n### EmailAttachment\nA file attached to an email message.\nExtends `MacroEntity`.\nFields: contentId, dataUrl, filename, id, mimeType, sfsId, size\n- `EmailAttachment.toDocument`: toDocument(): Promise<Document> — The Macro document holding this attachment's content.\n- `EmailAttachment.byId`: static byId(client, id): EmailAttachment — A handle to an attachment by id.\n- `EmailAttachment.from`: static from(client, data): EmailAttachment — Build an attachment from an already-fetched record (pre-seeded, no fetch).\n\n### DraftAttachment\nAn uploaded or forwarded attachment belonging to a draft.\nFields: draft, draftGeneration, forwarded, id\n- `DraftAttachment.complete`: complete(): Promise<void> — Complete verification after uploading the file.\n- `DraftAttachment.remove`: remove(): Promise<void> — Remove this attachment from its draft.\n- `DraftAttachment.toJSON`: toJSON(): { draftGeneration: number; draftId: string; forwarded: boolean; id: string; } — Serialize identity without credentials.\n- `DraftAttachment.byId`: static byId(_client, draft, id, forwarded?, draftGeneration?): DraftAttachment — Construct a draft scoped attachment handle.\n\n### EmailDraft\nA draft email.\nExtends `EmailMessage`.\nFields: bcc, body, cc, draftGeneration, from, id, labels, link, sentAt, subject, to\n- `EmailDraft.addAttachment`: addAttachment(options): Promise<{ attachment: DraftAttachment; contentType: string; uploadUrl: string; }> — Reserve an attachment upload.\n- `EmailDraft.delete`: delete(): Promise<void> — Delete the draft.\n- `EmailDraft.forwardAttachment`: forwardAttachment(attachment): Promise<DraftAttachment> — Forward an existing attachment into this draft.\n- `EmailDraft.removeAttachment`: removeAttachment(attachment): Promise<void> — Remove a draft attachment.\n- `EmailDraft.schedule`: schedule(sendTime, options?): Promise<void> — Schedule this draft for sending.\n- `EmailDraft.unschedule`: unschedule(): Promise<void> — Remove a scheduled send.\n- `EmailDraft.update`: update(options): Promise<void> — Replace draft content without changing its identity or sending it.\n- `EmailDraft.verifyAttachment`: verifyAttachment(attachment): Promise<void> — Complete verification of an uploaded attachment.\n- `EmailDraft.byId`: static byId(client, id): EmailDraft — Construct a lazy draft handle.\n\n### EmailFilter\nAn importance filter matched by sender address or domain.\nExtends `MacroEntity`.\nFields: emailAddress, emailDomain, id, isImportant\n- `EmailFilter.delete`: delete(): Promise<void> — Delete this filter.\n- `EmailFilter.setImportant`: setImportant(isImportant): Promise<void> — Change the importance for the same sender selector.\n- `EmailFilter.byId`: static byId(client, id, inbox?): EmailFilter — Construct a lazy filter handle.\n- `EmailFilter.from`: static from(client, record, inbox?): EmailFilter — Seed from a server record.\n\n### Label\nAn email label.\nExtends `MacroEntity`.\nFields: createdAt, id, labelListVisibility, linkId, messageListVisibility, name, type\n- `Label.delete`: delete(): Promise<void> — Delete this label.\n- `Label.byId`: static byId(client, id): Label — A handle to a label by id.\n- `Label.create`: static create(client, name): Promise<Label> — Create a user label.\n- `Label.list`: static list(client): Promise<Label[]> — All labels across the user's inboxes.\n\n### Link\nAn email link: a connected inbox (e.g.\nExtends `MacroEntity`.\nFields: emailAddress, id, isPrimary, isSyncActive, needsReauth, photoUrl, provider, syncStatus\n- `Link.settingsOperations`: settingsOperations(): Promise<MailboxSettingsOperation[]> — Read category and sender-policy changes for this inbox.\n- `Link.byId`: static byId(client, id): Link — A handle to an email link by id.\n- `Link.list`: static list(client): Promise<Link[]> — The caller's connected email links.\n\n### EmailMessage\nA message in an email thread.\nExtends `MacroEntity`.\nFields: bcc, body, cc, from, id, labels, link, sentAt, subject, to\n- `EmailMessage.addLabel`: addLabel(label): Promise<void> — Add a label to this message.\n- `EmailMessage.completeDraftAttachment`: completeDraftAttachment(attachmentId, draftGeneration?): Promise<void> — Verify an uploaded attachment using the draft generation captured when its upload began.\n- `EmailMessage.downloadEml`: downloadEml(): Promise<Blob> — The message's original source, exactly as Gmail or Outlook holds it, as message/rfc822 bytes for an .eml file.\n- `EmailMessage.operationStatus`: operationStatus(): Promise<MessageOperationResponse> — Read the draft's durable send, upload, or conflict status without retrying it.\n- `EmailMessage.removeLabel`: removeLabel(label): Promise<void> — Remove a label from this message.\n- `EmailMessage.resolveOperation`: resolveOperation(request): Promise<void> — Resolve the displayed operation revision after the user chooses an action.\n- `EmailMessage.thread`: thread(): Promise<EmailThread> — The thread this message belongs to.\n- `EmailMessage.transferDraft`: transferDraft(request): Promise<TransferDraftResponse> — Move a draft to another inbox using a caller-persisted operation UUID.\n- `EmailMessage.byId`: static byId(client, id): EmailMessage — A handle to a message by id.\n- `EmailMessage.from`: static from(client, data): EmailMessage — Build a message from an already-fetched record (pre-seeded, no fetch).\n- `EmailMessage.send`: static send(client, opts): Promise<EmailMessage | undefined> — Send a new email message.\n\n### EmailNamespace (`macro.email`)\n- `EmailNamespace.archive`: archive(threads, archived?): Promise<EmailThread[]> — Archive many threads (or unarchive with false).\n- `EmailNamespace.attachment`: attachment(id): EmailAttachment — A handle to an email attachment by id.\n- `EmailNamespace.blockedSenders`: blockedSenders(): Promise<string[]> — The email addresses currently blocked.\n- `EmailNamespace.blockSender`: blockSender(email): Promise<void> — Block an email sender.\n- `EmailNamespace.byId`: byId(id): EmailThread — A handle to an email thread by id.\n- `EmailNamespace.connectionProviders`: connectionProviders(): Promise<EmailConnectionProviders> — Providers the server currently permits this caller to connect.\n- `EmailNamespace.contacts`: contacts(): Promise<{[key: string]: ContactInfoWithInteraction[]; }> — Address book contacts grouped by the service's interaction buckets.\n- `EmailNamespace.createDraft`: createDraft(options, inbox?): Promise<EmailDraft> — Create a draft without sending it; the inbox defaults to the caller's primary.\n- `EmailNamespace.createLabel`: createLabel(name): Promise<Label> — Create a user label.\n- `EmailNamespace.deleteLabel`: deleteLabel(label): Promise<void> — Delete a label.\n- `EmailNamespace.draftById`: draftById(id): EmailDraft — Construct a lazy draft handle.\n- `EmailNamespace.filters`: filters(inbox?): Promise<EmailFilter[]> — Importance filters.\n- `EmailNamespace.inbox`: inbox(opts?): AsyncGenerator<EmailThread> — The threads in the inbox, most recent first, auto-paginated.\n- `EmailNamespace.label`: label(id): Label — A handle to a label by id.\n- `EmailNamespace.labels`: labels(): Promise<Label[]> — All labels across the user's inboxes.\n- `EmailNamespace.link`: link(id): Link — A handle to a connected inbox (email link) by id.\n- `EmailNamespace.links`: links(): Promise<Link[]> — The caller's connected inboxes (email links).\n- `EmailNamespace.message`: message(id): EmailMessage — A handle to an email message by id.\n- `EmailNamespace.recoverDraftTransfer`: recoverDraftTransfer(operationId): Promise<TransferRecoveryResponse> — Recover a draft move using its original operation UUID; never starts a new move.\n- `EmailNamespace.reminders`: reminders(options?): AsyncGenerator<{ followup: EmailFollowup; thread: EmailThread; }, any, any> — Follow-up reminders with thread handles, automatically paginated.\n- `EmailNamespace.scheduled`: scheduled(options?): AsyncGenerator<EmailDraft> — Scheduled drafts, fetched lazily in bounded pages.\n- `EmailNamespace.search`: search(query, opts?): AsyncGenerator<EmailThread> — Search email threads by subject and content.\n- `EmailNamespace.send`: send(opts): Promise<EmailMessage | undefined> — Send a new email message.\n- `EmailNamespace.unblockSender`: unblockSender(email): Promise<void> — Unblock a previously blocked sender.\n- `EmailNamespace.upsertFilter`: upsertFilter(options, inbox?): Promise<EmailFilter> — Create or replace a filter matching an address or domain.\n\n### EmailThread\nAn email thread.\nExtends `PropertiedEntity`.\nFields: access, accessLevel, createdAt, entityType, id, inboxVisible, isRead, latestInboundAt, latestNonSpamAt, latestOutboundAt, link, project, providerId, updatedAt, search\n- `EmailThread.addEventToCalendar`: addEventToCalendar(message, invitation, options?): Promise<CalendarEvent> — Add a shared event one of this thread's messages carries (a published .ics, such as one sent with Forward by email) to one of the requester's Google calendar...\n- `EmailThread.addLabel`: addLabel(label): Promise<void> — Add a label to every message in the thread.\n- `EmailThread.archive`: archive(archived?): Promise<void> — Archive the thread (or unarchive with false).\n- `EmailThread.attachments`: attachments(): Promise<EmailAttachment[]> — The attachments across this thread's first 100 messages, pre-seeded from the thread detail.\n- `EmailThread.calendarInvitations`: calendarInvitations(): Promise<{[key: string]: InvitationResolution; }> — Calendar invitations resolved from this thread's messages.\n- `EmailThread.followup`: followup(): Promise<EmailFollowupResponse> — Read follow-up state for this thread.\n- `EmailThread.markSeen`: markSeen(): Promise<void> — Mark the thread as seen.\n- `EmailThread.messages`: messages(opts?): Promise<EmailMessage[]> — The messages in this thread, pre-seeded from the list endpoint.\n- `EmailThread.moveToProject`: moveToProject(project): Promise<void> — Attach the thread to a project, or clear the project with null.\n- `EmailThread.operations`: operations(): Promise<MailboxOperation[]> — Read pending or failed mailbox changes without initiating a retry.\n- `EmailThread.participants`: participants(): Promise<ApiContactInfo[]> — Everyone on the thread (senders and recipients), deduped by email.\n- `EmailThread.readReceipts`: readReceipts(): Promise<EmailReadReceipt[]> — Opens recorded for messages sent from the caller's own or delegated inboxes with read receipts on, newest message first.\n- `EmailThread.removeLabel`: removeLabel(label): Promise<void> — Remove a label from every message in the thread.\n- `EmailThread.reply`: reply(opts): Promise<EmailMessage | undefined> — Send a reply within this thread.\n- `EmailThread.setFollowup`: setFollowup(command): Promise<EmailFollowup> — Set or remove a follow-up using a persisted operation id and revision.\n- `EmailThread.subject`: subject(): Promise<string | undefined> — The thread's subject, from its first message with one.\n- `EmailThread.update`: update(options): Promise<void> — Change project membership or share permissions for this thread.\n- `EmailThread.updateState`: updateState(request): Promise<void> — Update provider-neutral read, trash, spam, or star state.\n- `EmailThread.archiveMany`: static archiveMany(client, threads, archived?): Promise<EmailThread[]> — Archive many threads (or unarchive with false), sending one request per 100 threads.\n- `EmailThread.byId`: static byId(client, id): EmailThread — A handle to a thread by id.\n\nFunctions: `draftBody`\n\nTypes: `EmailAttachmentData`, `DraftOptions`, `EmailFilterOptions`, `SendEmailOptions`, `EmailMessageData`, `InboxOptions`, `EmailReadReceipt`, `ReplyEmailOptions`\n"
},
{
"name": "favorites",
@@ -335,7 +335,7 @@
"ParsedMessage": "# Type Alias: ParsedMessage\n\n> **ParsedMessage** = \\{ `bcc`: `ContactInfo`[]; `body_parsed?`: `string` \\| `null`; `cc`: `ContactInfo`[]; `db_id`: `string`; `draft_generation?`: `number`; `from?`: `null` \\| `ContactInfo`; `internal_date_ts?`: `string` \\| `null`; `labels`: `LabelInfo`[]; `link_id`: `string`; `subject?`: `string` \\| `null`; `thread_db_id`: `string`; `to`: `ContactInfo`[]; \\}\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-bcc\"></a> `bcc` | `ContactInfo`[] | - |\n| <a id=\"property-body_parsed\"></a> `body_parsed?` | `string` \\| `null` | - |\n| <a id=\"property-cc\"></a> `cc` | `ContactInfo`[] | - |\n| <a id=\"property-db_id\"></a> `db_id` | `string` | - |\n| <a id=\"property-draft_generation\"></a> `draft_generation?` | `number` | Draft edit generation captured with this message snapshot. |\n| <a id=\"property-from\"></a> `from?` | `null` \\| `ContactInfo` | - |\n| <a id=\"property-internal_date_ts\"></a> `internal_date_ts?` | `string` \\| `null` | - |\n| <a id=\"property-labels\"></a> `labels` | `LabelInfo`[] | - |\n| <a id=\"property-link_id\"></a> `link_id` | `string` | - |\n| <a id=\"property-subject\"></a> `subject?` | `string` \\| `null` | - |\n| <a id=\"property-thread_db_id\"></a> `thread_db_id` | `string` | - |\n| <a id=\"property-to\"></a> `to` | `ContactInfo`[] | - |",
"ResolveMessageOperationRequest": "# Type Alias: ResolveMessageOperationRequest\n\n> **ResolveMessageOperationRequest** = \\{ `accept_duplicate_risk?`: `boolean`; `action`: `ApiMessageResolutionAction`; `remote_version?`: `string` \\| `null`; `revision`: `string`; \\}\n\nStale versions fail without altering the current operation.\n\n## Properties\n\n| Property | Type |\n| ------ | ------ |\n| <a id=\"property-accept_duplicate_risk\"></a> `accept_duplicate_risk?` | `boolean` |\n| <a id=\"property-action\"></a> `action` | `ApiMessageResolutionAction` |\n| <a id=\"property-remote_version\"></a> `remote_version?` | `string` \\| `null` |\n| <a id=\"property-revision\"></a> `revision` | `string` |",
"ScheduledSendStatus": "# Type Alias: ScheduledSendStatus\n\n> **ScheduledSendStatus** = `\"pending\"` \\| `\"sending\"` \\| `\"failed\"` \\| `\"unconfirmed\"`\n\nThe user-visible delivery state of an unsent scheduled message.",
- "Settings": "# Type Alias: Settings\n\n> **Settings** = \\{ `signature?`: `string` \\| `null`; `signature_on_replies_forwards?`: `boolean` \\| `null`; \\}\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-signature\"></a> `signature?` | `string` \\| `null` | The user's email signature content (HTML). On a patch, omit or send `null` to leave unchanged (both deserialize to `None`); pass an empty string to clear it. The column cannot be set to SQL NULL via patch. |\n| <a id=\"property-signature_on_replies_forwards\"></a> `signature_on_replies_forwards?` | `boolean` \\| `null` | - |",
+ "Settings": "# Type Alias: Settings\n\n> **Settings** = \\{ `read_receipts_enabled?`: `boolean` \\| `null`; `signature?`: `string` \\| `null`; `signature_on_replies_forwards?`: `boolean` \\| `null`; \\}\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-read_receipts_enabled\"></a> `read_receipts_enabled?` | `boolean` \\| `null` | Whether messages sent from this inbox carry an open-tracking pixel. |\n| <a id=\"property-signature\"></a> `signature?` | `string` \\| `null` | The user's email signature content (HTML). On a patch, omit or send `null` to leave unchanged (both deserialize to `None`); pass an empty string to clear it. The column cannot be set to SQL NULL via patch. |\n| <a id=\"property-signature_on_replies_forwards\"></a> `signature_on_replies_forwards?` | `boolean` \\| `null` | - |",
"SyncStatus": "# Type Alias: SyncStatus\n\n> **SyncStatus** = `\"SYNCING\"` \\| `\"UP_TO_DATE\"` \\| `\"ERROR\"` \\| `\"NEEDS_REAUTH\"` \\| `\"INACTIVE\"`\n\nCoarse sync state for an inbox, used to render a one-line hint in the\nmulti-inbox settings list. Derived from the link's `is_sync_active` flag, its\nreauth health, and its most recent backfill job.",
"ThreadStateField": "# Type Alias: ThreadStateField\n\n> **ThreadStateField** = `\"read\"` \\| `\"starred\"` \\| `\"trashed\"` \\| `\"junk\"`\n\nSemantic mailbox facts, independent of folder/category names.",
"TransferDraftRequest": "# Type Alias: TransferDraftRequest\n\n> **TransferDraftRequest** = \\{ `destination_link_id`: `string`; `draft_generation?`: `number`; `operation_id`: `string`; \\}\n\nReuse the same operation ID when retrying after a lost response.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-destination_link_id\"></a> `destination_link_id` | `string` | - |\n| <a id=\"property-draft_generation\"></a> `draft_generation?` | `number` | Generation captured with the source draft. |\n| <a id=\"property-operation_id\"></a> `operation_id` | `string` | - |",
@@ -1474,6 +1474,7 @@
"EmailThread.permission": "### permission()\n\n> **permission**(): `Promise`\\<\\{ `permission`: `EntityPermission`; `status`: `\"access\"`; \\} \\| \\{ `status`: `\"no_access\"`; \\}\\>\n\nRead the caller's effective permission on this entity.\n\n#### Returns\n\n`Promise`\\<\\{ `permission`: `EntityPermission`; `status`: `\"access\"`; \\} \\| \\{ `status`: `\"no_access\"`; \\}\\>\n\n#### Inherited from\n\n`PropertiedEntity.permission`",
"EmailThread.properties": "### properties()\n\n> **properties**(`opts?`): `Promise`\\<`EntityPropertyWithDefinition`[]\\>\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`[]\\>\n\n#### Inherited from\n\n`PropertiedEntity.properties`",
"EmailThread.propertyReference": "### propertyReference()\n\n> **propertyReference**(): `PropertyTargetReference`\n\nThis entity's reference for bulk property operations.\n\n#### Returns\n\n`PropertyTargetReference`\n\n#### Inherited from\n\n`PropertiedEntity.propertyReference`",
+ "EmailThread.readReceipts": "### readReceipts()\n\n> **readReceipts**(): `Promise`\\<`EmailReadReceipt`[]\\>\n\nOpens recorded for messages sent from the caller's own or delegated\ninboxes with read receipts on, newest message first. Counts are\napproximate: some mail apps prefetch images and others block them.\n\n#### Returns\n\n`Promise`\\<`EmailReadReceipt`[]\\>",
"EmailThread.removeLabel": "### removeLabel()\n\n> **removeLabel**(`label`): `Promise`\\<`void`\\>\n\nRemove a label from every message in the thread.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `label` | `Label` |\n\n#### Returns\n\n`Promise`\\<`void`\\>",
"EmailThread.reply": "### reply()\n\n> **reply**(`opts`): `Promise`\\<`EmailMessage` \\| `undefined`\\>\n\nSend a reply within this thread. Returns a handle when the API reports the created message's id.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `opts` | `ReplyEmailOptions` |\n\n#### Returns\n\n`Promise`\\<`EmailMessage` \\| `undefined`\\>",
"EmailThread.setFollowup": "### setFollowup()\n\n> **setFollowup**(`command`): `Promise`\\<`EmailFollowup`\\>\n\nSet or remove a follow-up using a persisted operation id and revision.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `command` | `EmailFollowupCommand` |\n\n#### Returns\n\n`Promise`\\<`EmailFollowup`\\>",
@@ -1486,6 +1487,7 @@
"EmailThread.updateState": "### updateState()\n\n> **updateState**(`request`): `Promise`\\<`void`\\>\n\nUpdate provider-neutral read, trash, spam, or star state.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `request` | `UpdateThreadStateRequest` |\n\n#### Returns\n\n`Promise`\\<`void`\\>",
"EmailThread.archiveMany": "### archiveMany()\n\n> `static` **archiveMany**(`client`, `threads`, `archived?`): `Promise`\\<`EmailThread`[]\\>\n\nArchive many threads (or unarchive with `false`), sending one request per\n100 threads. Resolves to the threads whose state could not change.\n\n#### Parameters\n\n| Parameter | Type | Default value |\n| ------ | ------ | ------ |\n| `client` | `MacroClient` | `undefined` |\n| `threads` | `EmailThread`[] | `undefined` |\n| `archived?` | `boolean` | `true` |\n\n#### Returns\n\n`Promise`\\<`EmailThread`[]\\>",
"EmailThread.byId": "### byId()\n\n> `static` **byId**(`client`, `id`): `EmailThread`\n\nA handle to a thread 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`EmailThread`",
+ "EmailReadReceipt": "# Interface: EmailReadReceipt\n\nOpen tracking for one of the caller's sent messages.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-firstopenedat\"></a> `firstOpenedAt?` | `string` | When the first counted fetch happened, if any. |\n| <a id=\"property-lastopenedat\"></a> `lastOpenedAt?` | `string` | When the latest counted fetch happened, if any. |\n| <a id=\"property-message\"></a> `message` | `EmailMessage` | The tracked message. |\n| <a id=\"property-opencount\"></a> `openCount` | `number` | Counted pixel fetches; repeats within a few seconds count once. |",
"ReplyEmailOptions": "# Interface: ReplyEmailOptions\n\nOptions for replying within an email thread.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-bcc\"></a> `bcc?` | `ApiDraftContactInfo`[] | Bcc recipients. |\n| <a id=\"property-bodytext\"></a> `bodyText` | `string` | Plain-text body. |\n| <a id=\"property-cc\"></a> `cc?` | `ApiDraftContactInfo`[] | Cc recipients. |\n| <a id=\"property-replyingto\"></a> `replyingTo?` | `EmailMessage` | The message being replied to. |\n| <a id=\"property-subject\"></a> `subject?` | `string` | Subject line. Defaults to the subject of the thread's first message. |\n| <a id=\"property-to\"></a> `to` | `ApiDraftContactInfo`[] | Recipients. |",
"EntityMention": "# Class: EntityMention\n\nA stored mention connecting two resources.\n\n## Properties\n\n| Property | Modifier | Type | Description |\n| ------ | ------ | ------ | ------ |\n| <a id=\"property-id\"></a> `id` | `readonly` | `string` | Mention identity. |",
"EntityMention.delete": "### delete()\n\n> **delete**(): `Promise`\\<`void`\\>\n\nRemove this mention.\n\n#### Returns\n\n`Promise`\\<`void`\\>",
diff --git a/crates/agent_code_mode/src/domain/operations.json b/crates/agent_code_mode/src/domain/operations.json
index 3739a94aa0..2e98761181 100644
--- a/crates/agent_code_mode/src/domain/operations.json
+++ b/crates/agent_code_mode/src/domain/operations.json
@@ -287,7 +287,9 @@
"email.getThreadCalendarInvitations": "Get Thread Calendar Invitations",
"email.copyThreadCalendarInvitation": "Copy Thread Calendar Invitation",
"email.updateThreadProject": "Update Thread Project",
+ "email.getThreadReadReceipts": "Get Thread Read Receipts",
"email.healthHandler": "Health",
+ "email.getReadReceiptPixel": "Get Read Receipt Pixel",
"notification.healthHandler": "Health",
"notification.getUnsubscribes": "Get Unsubscribes",
"notification.unsubscribeEmail": "Unsubscribe Email",
diff --git a/crates/code_execution/src/outbound/deno/sdk.mjs b/crates/code_execution/src/outbound/deno/sdk.mjs
index f394115467..c4f4c77bca 100644
--- a/crates/code_execution/src/outbound/deno/sdk.mjs
+++ b/crates/code_execution/src/outbound/deno/sdk.mjs
@@ -1,5 +1,5 @@
// Generated by packages/code-mode-sdk/scripts/generate.ts.
-async function cO($,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 B${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*c($){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 QO 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 Y($){if($.error!==void 0)throw new QO($.response?.status??0,$.error);return $.data}class P{client;id;detail;constructor($,O,j){this.client=$;this.id=O;this.detail=new B$(()=>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=Y(await $(this.client));return this.detail.clear(),O}}class H$ extends P{async permission(){return Y(await this.client.storage.getEntityPermission({path:{entity_type:this.entityType,entity_id:this.id}}))}async favorite(){return Y(await this.client.storage.addFavorite({body:{entityId:this.id,entityType:this.entityType}})),this}async unfavorite(){return Y(await this.client.storage.removeFavoriteByEntity({path:{entity_type:this.entityType,entity_id:this.id}})),this}}class X$ extends H${propertyReference(){return{entity_type:this.propertyEntityType,entity_id:this.id}}async properties($){let{properties:O}=Y(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){Y(await this.client.properties.setEntityProperty({path:{...this.propertyReference(),property_id:$.id},body:{value:O??null}}))}async updatePropertyOptions($){return Y(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($){Y(await this.client.properties.deleteEntityProperty({path:{entity_property_id:$.property.id}}))}}var m7={"<":"\\u003c",">":"\\u003e","&":"\\u0026"};function n$($,O){let j=JSON.stringify(O).replace(/[<>&]/g,(x)=>m7[x]??x);return`<${$}>${j}</${$}>`}function u7($){return typeof $==="object"&&$!==null&&typeof $.toMention==="function"}var c7={toMention:()=>({tag:n$("m-group-mention",{groupAlias:"here"}),mention:{entity_type:"group",entity_id:"here"}})};function d7($,...O){let j="",x=[];for(let[S,K]of $.entries()){j+=K;let Z=O[S];if(Z===void 0)continue;if(u7(Z)){let X=Z.toMention();j+=X.tag,x.push(X.mention)}else j+=String(Z)}return{content:j,mentions:l7(x)}}function l7($){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 O$($){return typeof $==="string"?{content:$,mentions:[]}:$}class L$ extends P{static byId($,O){return new L$($,O)}static from($,O){return new L$($,O.id,O)}async fetch(){let $=Y(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 T$ extends P{static byId($,O){return new T$($,O)}static from($,O){return new T$($,O.bot.id,O)}async fetch(){let $=Y(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",($)=>$?L$.byId(this.client,$):void 0);async update($){await this.mutate((O)=>O.storage.updateAgent({path:{agent_id:this.id},body:m0($)}))}}function m0($){let{channels:O,team:j,host:x,autoAcceptPermissions:S,avatarUrl:K,channelScope:Z,defaultModel:X,isCoding:G,...L}=$;return{...L,channel_ids:O?.map((Q)=>Q.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 Bj($,O,j,x=[]){let{channelId:S,thread:K}=p7(O);if(await a7($)){let{id:X}=Y(await $.storage.entityMessageCreate({path:{parent_type:"channel",parent_id:S},body:{content:j.content,mentions:j.mentions,attachments:x.map((G)=>({entity_type:r7,entity_id:G.id,width:G.width??null,height:G.height??null})),thread_id:K?.rootId??null,nonce:crypto.randomUUID()}}));return X}if(x.length>0)throw new f("a user-owned bot can only post via the channel webhook endpoint, which "+"does not support images — use a team-owned bot, or requestedAs(user), "+"to attach images");if(K)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:Z}=Y(await $.storage.postChannelBotWebhook({path:{channel_id:S},body:{content:j.content},headers:{"x-macro-bot-scope":"user"}}));return Z}var r7="static/image";function p7($){return"rootId"in $?{channelId:$.channelId,thread:$}:{channelId:$.id}}async function a7($){if($.authConfig.type!=="bot"||$.hasActingUser())return!0;let{owner:O}=await $.selfBot();return O?.type==="team"}class m${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:$}=Y(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($,O){let j=await Bj(this.client,this,O$($),O?.images);return e.byId(this.client,this.channelId,j)}}class e extends H${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 Y(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 m$(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}=O$($);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 Lj{client;channel;record;constructor($,O,j){this.client=$;this.channel=O;this.record=j}agent(){return T$.byId(this.client,this.record.botId)}sessions(){return this.record.sessions.map(($)=>({session:l.byId(this.client,$.sessionId),isCurrent:$.isCurrent,createdAt:$.createdAt}))}turns(){return this.record.turns.map(($)=>new u0(this.client,this,$))}async startFresh($){Y(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 u0{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 l.byId(this.client,this.record.sessionId)}async retry($){Y(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 N$ extends P{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 N$($,O,j)}get path(){return{parent_type:this.parent.type,parent_id:this.parent.entity.id,id:this.id}}async fetch(){return Y(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 q$($,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=Y(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 i7=50;function x$($){let{filters:O,type:j,make:x,includeCrm:S}=$;return(K,Z,X)=>{let G=X?.searchOn??"name_content",L=X?.pageSize??i7;return c(async(Q)=>{let{results:J,next_cursor:I}=Y(await K.search.unifiedSearch({body:{query:Z,match_type:"partial",search_on:G,...O?{filters:O}:{},...S?{include_crm:!0}:{}},query:{page_size:L,...Q?{cursor:Q}:{}}}));return{items:J.filter((W)=>W.type===j).map((W)=>x(K,W)),nextCursor:I}})}}class JO{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 JO(this.client,this.channel,Y(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 JO(this.client,this,Y(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 N$.byId(this.client,{type:"channel",entity:this},$)}timelinePage($){return q$(this.client,{type:"channel",entity:this},(O)=>e.from(this.client,this.id,O),$)}async agentConversations(){return Y(await this.client.agentHarness.listAgentConversations({path:{channel_id:this.id}})).conversations.map(($)=>new Lj(this.client,this,$))}entityType="channel";propertyEntityType="CHANNEL";async fetch(){return Y(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}=Y(await $.storage.getOrCreateDm({body:{recipient_id:O.id}}));return new b($,j)}static async private($,O){let{channel_id:j}=Y(await $.storage.getOrCreatePrivate({body:{recipients:O.map((x)=>x.id)}}));return new b($,j)}static async create($,O){let{id:j}=Y(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 Bj(this.client,O?.thread??this,O$($),O?.images);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 c(async(O)=>{let j=Y(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:$}=Y(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 Y(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){Y(await this.client.storage.entityMessageTyping({path:{parent_type:"channel",parent_id:this.id},body:{active:$==="start",thread_id:O?.thread?.rootId??null}}))}attachments($){return c(async(O)=>{let j=Y(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=x$({type:"channel",make:($,O)=>new b($,O.channel_id)})}class A extends X${entityType="user";propertyEntityType="USER";async fetch(){let{names:$}=Y(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 fromName($,O){return new A($,O.id,O)}static async me($){let{user_id:O}=Y(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:n$("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=Y(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?HO.from(this.client,this,O.mine):void 0,requests:O.requests.map((j)=>HO.from(this.client,this,j))}}async submit($,O){return HO.from(this.client,this,Y(await this.client.storage.accessRequestsSubmit({path:this.path,body:{requestedLevel:$,revision:O}})))}async cancel($){Y(await this.client.storage.accessRequestsCancel({path:this.path,query:{revision:$}}))}async direct(){return Y(await this.client.storage.accessRequestsDirect({path:this.path})).map(($)=>({user:A.byId(this.client,$.userId),accessLevel:$.accessLevel}))}async grant($,O){Y(await this.client.storage.accessRequestsSetDirect({path:{...this.path,user_id:$.id},body:{accessLevel:O}}))}async remove($){Y(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 Y(await this.client.storage.accessRequestsResolve({path:{...this.path,request_id:$.id},body:O}))}toJSON(){return this.path}}class HO extends P{access;resolvedRecord;constructor($,O,j){super($,j.id,j);this.access=O}static from($,O,j){return new HO($,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 s$($){return{...$,channelSharePermissions:$.channelSharePermissions===void 0||$.channelSharePermissions===null?$.channelSharePermissions:$.channelSharePermissions.map((O)=>({channelId:O.channel.id,accessLevel:O.accessLevel,operation:O.operation}))}}class U$ extends P{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=Y(await $.agentHarness.createSessionReview({path:{session_id:O.id},body:{...j,executionId:x?.id??null}}));return U$.fromRecord($,O,S)}static async list($,O){return Y(await $.agentHarness.listExecutionReviews({path:{session_id:O.session().id,execution_id:O.id}})).map((x)=>U$.fromRecord($,O.session(),x))}async fetch(){return Y(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 c0($,{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 c0{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 dO extends P{parent;constructor($,O,j){super($,O);this.parent=j}static byId($,O,j){return new dO($,j,O)}async fetch(){return Y(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 Nj{client;sessionId;dto;constructor($,O,j){this.client=$;this.sessionId=O;this.dto=j}static from($,O,j){return new Nj($,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 Y(await this.client.agentHarness.editQueuedAction({path:{session_id:this.sessionId,action_id:this.actionId},body:{prompt:$}})),this.dto={...this.dto,prompt:$},this}async steer(){Y(await this.client.agentHarness.steerQueuedAction({path:{session_id:this.sessionId,action_id:this.actionId}}))}async remove(){Y(await this.client.agentHarness.removeQueuedAction({path:{session_id:this.sessionId,action_id:this.actionId}}))}}class lO{client;session;id;constructor($,O,j){this.client=$;this.session=O;this.id=j}static byId($,O,j){return new lO($,O,j)}async answer($){return Y(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 l extends P{access=new o(this.client,"agent_session",this);toolApprovalById($){return lO.byId(this.client,this,$)}async sharePermissions(){return Y(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:s$($)}))}static byId($,O){return new l($,O)}static async createManaged($,O){let{session:j}=Y(await $.agentHarness.createAgentSession({body:{prompt:O?.prompt,instructions:O?.instructions,model:O?.model,repoUrl:O?.repoUrl,repoBranch:O?.repoBranch}}));return new l($,j.id,j)}static async repositories($){let{repositories:O}=Y(await $.agentHarness.listAgentRepositories());return O.map((j)=>({url:j.url,defaultBranch:j.defaultBranch??void 0}))}static async repositoryBranches($,O){let{branches:j}=Y(await $.agentHarness.listAgentRepositoryBranches({query:{repoUrl:O}}));return j}static async chooseMode($,O){let{mode:j}=Y(await $.agentHarness.chooseAgentMode({body:{prompt:O}}));return j}async fetch(){return Y(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}=Y(await $.agentHarness.agentSessionsForPullRequest({body:{url:O}}));return j.map((x)=>l.byId($,x))}async pullRequests(){let{pullRequests:$}=Y(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($){Y(await this.client.agentHarness.linkAgentSessionPullRequest({path:{session_id:this.id},body:{url:$}}))}async unlinkPullRequest($){Y(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 Y(await $.agentHarness.getAgentSandboxSize()).size}static async setDefaultSandboxSize($,O){return Y(await $.agentHarness.putAgentSandboxSize({body:{size:O}})).size}static async codingPreferences($){return Y(await $.agentHarness.getAgentCodingPreferences())}static async setCodingPreferences($,O){return Y(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:$}=Y(await this.client.agentHarness.getAgentSessionQueue({path:{session_id:this.id}}));return $.map((O)=>Nj.from(this.client,this.id,O))}async changes(){return Y(await this.client.agentHarness.getAgentSessionChanges({path:{session_id:this.id}}))}async changesPatch(){return Y(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}=Y(await this.client.agentHarness.getAgentSessionFoldedLog({path:{session_id:this.id}}));return{bot:$,messages:O}}async log(){return Y(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:($)=>dO.byId(this.client,this,$)};async delete(){await this.mutate(($)=>$.agentHarness.deleteAgentSession({path:{session_id:this.id}}))}}class d0{client;constructor($){this.client=$}byId($){return l.byId(this.client,$)}createManaged($){return l.createManaged(this.client,$)}chooseMode($){return l.chooseMode(this.client,$)}repositories(){return l.repositories(this.client)}repositoryBranches($){return l.repositoryBranches(this.client,$)}forPullRequest($){return l.forPullRequest(this.client,$)}defaultSandboxSize(){return l.defaultSandboxSize(this.client)}setDefaultSandboxSize($){return l.setDefaultSandboxSize(this.client,$)}codingPreferences(){return l.codingPreferences(this.client)}setCodingPreferences($){return l.setCodingPreferences(this.client,$)}}class l0{client;constructor($){this.client=$}byId($){return T$.byId(this.client,$)}async list(){return Y(await this.client.storage.listAgents()).map(($)=>T$.from(this.client,$))}async create($){return T$.from(this.client,Y(await this.client.storage.createAgent({body:m0($)})))}}class r0{client;async usage($={}){let{users:O,...j}=$;return Y(await this.client.cognition.getUsageHandler({body:{...j,include_users:O?.map((x)=>x.id)}}))}constructor($){this.client=$}async structuredCompletion($){return Y(await this.client.cognition.structuredCompletion({body:$}))}async decide($){return Y(await this.client.cognition.decisions({body:$}))}}class t$ extends P{static byId($,O){return new t$($,O)}static from($,O){return new t$($,O.id,{id:O.id,name:O.name,createdAt:O.createdAt})}async fetch(){let $=Y(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 p0{client;constructor($){this.client=$}byId($){return t$.byId(this.client,$)}async list(){return Y(await this.client.storage.listUserApiKeys()).keys.map(($)=>t$.from(this.client,$))}async create($){let O=Y(await this.client.storage.createUserApiKey({body:{name:$}}));return{key:t$.from(this.client,O),secret:O.key}}async tokenForEmail($){return Y(await this.client.auth.macroApiToken({query:{email:$}}))}}class rO{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 Y(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 Y(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 S$ extends P{async fetch(){let O=Y(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 S$($,O)}static async current($){let O=Y(await $.auth.getTeam());if(!O)throw new E("caller has no current team");return new S$($,O.team.id,O.team)}static async list($){return Y(await $.auth.getUserTeams()).map((j)=>new S$($,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 $=Y(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 R$ extends P{async fetch(){let{links:$}=Y(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 R$($,O)}static async list($){let{links:O}=Y(await $.email.listLinks());return O.map((j)=>new R$($,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 Y(await this.client.email.mailboxSettingsOperations({headers:{"X-Email-Link-Id":this.id}}))}}class u$ extends P{async setContributesToAvailability($){await this.mutate((O)=>O.calendar.setAvailabilityCalendar({path:{calendar_id:this.id},body:{contributesToAvailability:$}}))}async fetch(){let{calendars:$}=Y(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 u$($,O)}static async list($){let{calendars:O}=Y(await $.calendar.listCalendars());return O.map((j)=>new u$($,j.id,j))}name=this.field("name");emailAddress=this.field("emailAddress");isPrimary=this.field("isPrimary");isWritable=this.field("isWritable");contributesToAvailability=this.field("contributesToAvailability");isSubscription=this.field("isSubscription");color=this.field("color");syncError=this.field("syncError");emailLink=this.mappedField("emailLinkId",($)=>R$.byId(this.client,$))}class pO{client;id;constructor($,O){this.client=$;this.id=O}async status(){return Y(await this.client.calendar.calendarReplacementStatus({path:{operation_id:this.id}}))}async confirm(){return Y(await this.client.calendar.confirmCalendarReplacement({path:{operation_id:this.id}}))}async discard(){Y(await this.client.calendar.discardCalendarReplacement({path:{operation_id:this.id}}))}}class $$ extends P{async notes($){return this.requireOwnOccurrence($),Y(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),Y(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 $$($,O)}static fromRecord($,O){return new $$($,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",($)=>$?u$.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:n7($)}));return $$.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,inbox:$.inbox}}))}async prepareReplacement($){let O=Y(await this.client.calendar.prepareCalendarReplacement({path:{event_id:this.id},body:{removeConference:$.removeConference,recurrenceId:$.recurrenceId,calendarId:$.calendar?.id}}));return new pO(this.client,O.operationId)}async providerUrl($={}){return Y(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,inbox:$.inbox}}));return $$.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 $$.fromRecord(this.client,O)}async ics(){return Y(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 $$.fromRecord(this.client,O)}}function n7($){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,inbox:$.inbox}}class w$ extends P{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$($,$$.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=Y(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=Y(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",($)=>$?S$.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 Y(await this.client.storage.getProjectPermissionsV2({path:{id:this.id}}))}async accessLevel(){return Y(await this.client.storage.getProjectUserAccessLevel({path:{id:this.id}}))}access=new o(this.client,"project",this);entityType="project";propertyEntityType="PROJECT";async fetch(){let{data:$}=Y(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}=Y(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:$}=Y(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=x$({filters:{project_filters:{}},type:"project",make:($,O)=>new n($,O.id)})}class VO extends P{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 VO($,O,j)}static from($,O,j){return new VO($,O,j.uuid,j)}async fetch(){let $=Y(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 c$ extends P{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 Y(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 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}=O$($);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 aO{client;document;id;detail;constructor($,O,j){this.client=$;this.document=O;this.id=j;this.detail=new B$(async()=>Y(await this.client.storage.getDocumentVersion({path:{document_id:O.id,document_version_id:j}})).data)}static byId($,O,j){return new aO($,O,j)}read(){return this.detail.get()}toJSON(){return{id:this.id,documentId:this.document.id}}}var s7=8;class q extends X${async meetingNotes(){return Y(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 Y(await this.client.storage.getDocumentAnchors({path:{document_id:this.id}})).data.map(($)=>VO.from(this.client,this,$))}async createHighlight($){return VO.from(this.client,this,Y(await this.client.storage.createAnchor({path:{document_id:this.id},body:{...$,fileType:"pdf",anchorType:"highlight"}})))}version($){return aO.byId(this.client,this,$)}async sharePermissions(){return Y(await this.client.storage.getDocumentPermissionsV2({path:{document_id:this.id}})).documentPermissions}async permissionsToken(){return Y(await this.client.storage.getDocumentPermissionsToken({path:{document_id:this.id}})).token}async prepareSave($){return Y(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 N$.byId(this.client,{type:"document",entity:this},$)}timelinePage($){return q$(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:$}=Y(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}=Y(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}=Y(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}=Y(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 c(async(x)=>{let S=Y(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}=Y(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:$}=Y(await this.client.storage.getDocumentTextContent({path:{document_id:this.id}}));if($!==null)return $;let{presigned_url:O}=Y(await this.client.storage.exportDocument({path:{document_id:this.id}})),j=await fetch(O);if(!j.ok)throw new QO(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}=Y(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=c(async(x)=>{let S=Y(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 cO(j,s7,async(x)=>{let{state:S,root:K,replies:Z}=Y(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:{...O$($),thread_id:O?.threadId??null}}));return c$.from(this.client,this.id,j)}async shortId(){return Y(await this.client.storage.getDocumentShortId({path:{document_id:this.id}}))}async teamShare(){return Y(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:$}=Y(await this.client.storage.getDocumentGithubPullRequests({path:{document_id:this.id}}));return $}async branchName(){let{branchName:$}=Y(await this.client.storage.getDocumentBranchName({path:{document_id:this.id}}));return $}webUrl(){return`${this.client.webAppUrl}/app/md/${this.id}`}static search=x$({filters:{document_filters:{}},type:"document",make:($,O)=>new q($,O.document_id)});toMention(){let $=this.detail.peek();return{tag:n$("m-document-mention",{documentId:this.id,documentName:$?.documentName??"",blockName:$?.fileType??"md"}),mention:{entity_type:"document",entity_id:this.id}}}}class a0{client;async noteDocuments($=""){let O=Y(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:S$.byId(this.client,j.id),name:j.name}))}}async availabilityCalendars(){return Y(await this.client.calendar.getAvailabilityCalendars()).calendars.map(($)=>({calendar:u$.byId(this.client,$.calendarId),name:$.name,isPrimary:$.isPrimary,contributesToAvailability:$.contributesToAvailability}))}async teamSharing(){return Y(await this.client.calendar.getTeamSharing()).sharing}async setTeamSharing($){return Y(await this.client.calendar.setTeamSharing({body:{sharing:$}})).sharing}occurrences($){let O;return c(async(j)=>{let x=Y(await this.client.storage.listOccurrences({query:{...$,cursor:j}}));O??=e7(this.client);let S=await O;return{items:x.items.map((K)=>{let Z=K.event.calendarId?S.get(K.event.calendarId):void 0;return{event:$$.fromRecord(this.client,K.event),occurrence:K.occurrence,calendarName:Z?.name,contributesToAvailability:d1(K.event,S),inbox:Z?.emailAddress,role:o7(K.event,S)}}),nextCursor:x.nextCursor}})}async teamPage($){let O=Y(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=Y(await this.client.storage.listTeamOutOfOffice({query:$}));return{items:O.items.map((j)=>({event:$$.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 u$.list(this.client)}calendar($){return u$.byId(this.client,$)}event($){return $$.byId(this.client,$)}replacement($){return new pO(this.client,$)}async createEvent($){let O=Y(await this.client.calendar.createCalendarEvent({body:t7($)}));return $$.fromRecord(this.client,O)}}function t7($){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}}async function e7($){let{calendars:O}=Y(await $.calendar.listCalendars());return new Map(O.map((j)=>[j.id,j]))}function d1($,O){let j=[$.calendarId,...($.sources??[]).map((x)=>x.calendarId)].flatMap((x)=>{let S=x?O.get(x):void 0;return S?[S.contributesToAvailability]:[]});if(j.some(Boolean))return!0;return j.length>0&&j.every((x)=>x===!1)?!1:void 0}function o7($,O){let j=$.attendees.find((S)=>S.isSelf);if(j?.isOrganizer)return $.isReadOnly?void 0:"organizer";let x=$.attendees.some((S)=>S.isOrganizer);if($.viewerCan.organize&&d1($,O)&&!x)return"organizer";return j?"guest":void 0}class D$ extends P{lookupToken;constructor($,O,j){super($,O,j);this.lookupToken=j?.shareToken}static byId($,O){return new D$($,O)}static from($,O){return new D$($,O.id,O)}async fetch(){if(this.lookupToken)return Y(await this.client.storage.meetingLookup({path:{token:this.lookupToken}}));let $=Y(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",($)=>$?J$.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 Y(await this.client.storage.meetingInvitePermissions({path:{token:(await this.detail.get()).shareToken}}))}async invite($){Y(await this.client.storage.meetingInvite({path:{token:(await this.detail.get()).shareToken},body:{email:$}}))}async inviteUsers($){Y(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 d$ extends P{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 Y(await this.client.storage.entityMessageGetMessage({path:this.path}))}static byId($,O,j){return new d$($,O,j)}static from($,O,j){return new d$($,O,j.id,j)}content=this.field("content");createdAt=this.field("created_at");updatedAt=this.field("updated_at");call(){return J$.byId(this.client,this.callId)}async author(){return A.byId(this.client,(await this.detail.get()).sender_id)}async reply($){let O=Y(await this.client.storage.entityMessageCreate({path:{parent_type:"call",parent_id:this.callId},body:{...O$($),thread_id:this.callId}}));return d$.from(this.client,this.callId,O)}async edit($){let{content:O,mentions:j}=O$($);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 J$ extends H${messageThreadById($){return N$.byId(this.client,{type:"call",entity:this},$)}timelinePage($){return q$(this.client,{type:"call",entity:this},(O)=>d$.from(this.client,this.id,O),$)}access=new o(this.client,"call",this);async meeting(){return D$.from(this.client,Y(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 Y(await this.client.storage.getCallRecord({path:{call_id:this.id}}))}static byId($,O){return new J$($,O)}message($){return d$.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=x$({filters:{call_filters:{}},type:"call",make:($,O)=>new J$($,O.call_id)})}class i0{client;constructor($){this.client=$}byId($){return J$.byId(this.client,$)}search($,O){return J$.search(this.client,$,O)}}class n0{client;constructor($){this.client=$}async list(){let{labels:$}=Y(await this.client.storage.listChannelLabels());return $}async create($,O=[]){return Y(await this.client.storage.createChannelLabel({body:{name:$,channelIds:O.map((j)=>j.id)}}))}async createSmartTag($,O){return Y(await this.client.storage.createChannelLabel({body:{name:$,rule:O}}))}async previewSmartTag($){return Y(await this.client.storage.previewSmartTag({body:$}))}async updateSmartTag($,O,j){return Y(await this.client.storage.renameChannelLabel({path:{label_id:$.id},body:{name:O,rule:j}}))}async rename($,O){return Y(await this.client.storage.renameChannelLabel({path:{label_id:$.id},body:{name:O}}))}async delete($){Y(await this.client.storage.deleteChannelLabel({path:{label_id:$.id}}))}async setLabel($,O){Y(await this.client.storage.setChannelLabel({path:{channel_id:$.id},body:{labelId:O?.id??null}}))}}class s0{client;async activity(){return Y(await this.client.storage.getActivity()).map(($)=>new JO(this.client,b.byId(this.client,$.channel_id),$))}labels;constructor($){this.client=$;this.labels=new n0($)}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:$}=Y(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}=Y(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 iO{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 iO($,O,j,x)}async stop(){Y(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 nO extends P{chat;constructor($,O,j){super($,j);this.chat=O}static byId($,O,j){return new nO($,O,j)}async fetch(){let $=Y(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 K$ 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=K$.byId(this.client,S.chat_id);return iO.byId(this.client,K,S.stream_id,nO.byId(this.client,K,S.message_id))}access=new o(this.client,"chat",this);entityType="chat";propertyEntityType="CHAT";async fetch(){let{chat:$}=Y(await this.client.cognition.getChat({path:{chat_id:this.id}}));return $}static byId($,O){return new K$($,O)}static async create($,O){let{id:j}=Y(await $.cognition.createChat({body:{name:O?.name??null,projectId:O?.project?.id??null}}));return new K$($,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 K$(this.client,$)}async restore(){await this.mutate(($)=>$.cognition.revertDeleteChat({path:{chat_id:this.id}}))}async history(){let{conversation:$}=Y(await this.client.cognition.getChatHistoryHandler({path:{chat_id:this.id}}));return $}webUrl(){return`${this.client.webAppUrl}/app/chat/${this.id}`}static search=x$({filters:{chat_filters:{}},type:"chat",make:($,O)=>new K$($,O.chat_id)});toMention(){return{tag:n$("m-document-mention",{documentId:this.id,documentName:this.detail.peek()?.name??"",blockName:"chat",blockParams:{}}),mention:{entity_type:"chat",entity_id:this.id}}}}class t0{client;constructor($){this.client=$}byId($){return K$.byId(this.client,$)}create($){return K$.create(this.client,$)}search($,O){return K$.search(this.client,$,O)}}var $S=8;class P$ extends P{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 Y(await this.client.storage.entityMessageGetMessage({path:this.path}))}static byId($,O,j){return new P$($,O,j)}static from($,O,j){return new P$($,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 sO(this.client,this.parent,$,{threadId:await this.threadId()})}async edit($){let{content:O,mentions:j}=O$($);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 Uj($,O){let j={parent_type:O.type,parent_id:O.id},x=c(async(K)=>{let Z=Y(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 cO(S,$S,async(K)=>{let{state:Z,root:X,replies:G}=Y(await $.storage.entityMessageGetThread({path:{...j,id:K.id}}));return{thread:Z,comments:[X,...G].map((L)=>P$.from($,O,L))}})}async function sO($,O,j,x){let S=Y(await $.storage.entityMessageCreate({path:{parent_type:O.type,parent_id:O.id},body:{...O$(j),thread_id:x?.threadId??null}}));return P$.from($,O,S)}class f$ extends H${messageThreadById($){return N$.byId(this.client,{type:"crm_contact",entity:this},$)}timelinePage($){return q$(this.client,{type:"crm_contact",entity:this},(O)=>P$.from(this.client,{type:"crm_contact",id:this.id},O),$)}entityType="crm_contact";async fetch(){return Y(await this.client.storage.getContact({path:{contact_id:this.id}}))}static byId($,O){return new f$($,O)}static from($,O){return new f$($,O.id,O)}name=this.field("name");email=this.field("email");company=this.mappedField("companyId",($)=>b$.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 Uj(this.client,this.commentParent)}async comment($,O){return sO(this.client,this.commentParent,$,O)}commentById($){return P$.byId(this.client,this.commentParent,$)}}class b$ extends X${messageThreadById($){return N$.byId(this.client,{type:"crm_company",entity:this},$)}timelinePage($){return q$(this.client,{type:"crm_company",entity:this},(O)=>P$.from(this.client,{type:"crm_company",id:this.id},O),$)}entityType="crm_company";propertyEntityType="COMPANY";async fetch(){return Y(await this.client.storage.getCompany({path:{company_id:this.id}}))}static byId($,O){return new b$($,O)}static from($,O){return new b$($,O.id,O)}name=this.field("name");description=this.field("description");hidden=this.field("hidden");emailSync=this.field("emailSync");team=this.mappedField("teamId",($)=>S$.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 Y(await this.client.storage.listCompanyContacts({path:{company_id:this.id}})).map((O)=>f$.from(this.client,O))}static search=x$({filters:{crm_company_filters:{}},type:"company",includeCrm:!0,make:($,O)=>new b$($,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 f$.from(this.client,O)}get commentParent(){return{type:"crm_company",id:this.id}}async comments(){return Uj(this.client,this.commentParent)}async comment($,O){return sO(this.client,this.commentParent,$,O)}commentById($){return P$.byId(this.client,this.commentParent,$)}}class e$ extends P{tableDetail=new B$(async()=>Y(await this.client.storage.getCrmPipelineTable({path:{id:this.id}})));static byId($,O){return new e$($,O)}static from($,O){return new e$($,O.id,O)}async fetch(){return Y(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",($)=>S$.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 Y(await this.client.storage.getCrmPipelinePermissions({path:{id:this.id}}))}async updateSharePermissions($){return this.mutate((O)=>O.storage.updateCrmPipelinePermissions({path:{id:this.id},body:s$($)}))}async table(){return zj.from(this.client,this,await this.tableRecord())}tableRecord(){return this.tableDetail.get()}rows(){return c(async($)=>{let O=Y(await this.client.storage.getCrmPipelineRows({path:{id:this.id},query:{after:$}}));return{items:O.rows.map((j)=>WO.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 c(async(O)=>{let j=Y(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)=>WO.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 zj extends P{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 zj($,O,j)}fetch(){return this.pipeline.tableRecord()}async columns(){return(await this.pipeline.tableRecord()).columns.map(($)=>Ij.from(this.client,this,$))}async version(){return(await this.pipeline.tableRecord()).table.version}rowById($){return WO.byId(this.client,this.pipeline,$)}rows(){return this.pipeline.rows()}}class WO extends P{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 WO($,O,j)}static from($,O,j){return new WO($,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 Ij extends P{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 Ij($,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 e0{client;constructor($){this.client=$}byId($){return e$.byId(this.client,$)}async list(){return Y(await this.client.storage.listCrmPipelines()).map(($)=>e$.from(this.client,$))}async create($){return e$.from(this.client,Y(await this.client.storage.createCrmPipeline({body:$})))}}class o0{client;pipelines;constructor($){this.client=$;this.pipelines=new e0($)}companyById($){return b$.byId(this.client,$)}contactById($){return f$.byId(this.client,$)}async contactByEmail($){let{contact:O}=Y(await this.client.storage.getContactByEmail({query:{email:$}}));return O?f$.from(this.client,O):void 0}async searchContacts($,O={}){let{contacts:j}=Y(await this.client.storage.searchContacts({query:{query:$,limit:O.limit}}));return j.map((x)=>f$.from(this.client,x))}async createCompany($){return b$.from(this.client,Y(await this.client.storage.createCrmCompany({body:$})))}async settings(){return Y(await this.client.storage.getCrmTeamSettings())}async updateSettings($){return Y(await this.client.storage.putCrmTeamSettings({body:$}))}async setStages($){return Y(await this.client.storage.putCrmTeamStages({body:$}))}async resetStages(){Y(await this.client.storage.resetCrmTeamStages())}searchCompanies($){return b$.search(this.client,$)}}var Y$=Symbol.for("@ts-pattern/matcher"),r1=Symbol.for("@ts-pattern/isVariadic");var $x=($)=>Boolean($&&typeof $=="object"),Hj=($)=>$&&!!$[Y$],s=($,O,j)=>{if(Hj($)){let x=$[Y$](),{matched:S,selections:K}=x.match(O);return S&&K&&Object.keys(K).forEach((Z)=>j(Z,K[Z])),S}if($x($)){if(!$x(O))return!1;if(Array.isArray($)){if(!Array.isArray(O))return!1;let x=[],S=[],K=[];for(let Z of $.keys()){let X=$[Z];Hj(X)&&X[r1]?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,Q)=>s(L,Z[Q],j))&&S.every((L,Q)=>s(L,X[Q],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)||Hj(K=S)&&K[Y$]().matcherType==="optional")&&s(S,O[x],j);var K})}return Object.is(O,$)},G$=($)=>{var O,j,x;return $x($)?Hj($)?(O=(j=(x=$[Y$]()).getSelectionKeys)==null?void 0:j.call(x))!=null?O:[]:Array.isArray($)?tO($,G$):tO(Object.values($),G$):[]},tO=($,O)=>$.reduce((j,x)=>j.concat(O(x)),[]);function OS(...$){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:()=>xx($),and:(O)=>d($,O),or:(O)=>p1($,O),select:(O)=>O===void 0?eO($):eO(O,$)})}function Ox($){return Object.assign(((O)=>Object.assign(O,{[Symbol.iterator](){let j=0,x=[{value:Object.assign(O,{[r1]:!0}),done:!1},{done:!0,value:void 0}];return{next:()=>{var S;return(S=x[j++])!=null?S:x.at(-1)}}}}))($),{optional:()=>Ox(xx($)),select:(O)=>Ox(O===void 0?eO($):eO(O,$))})}function xx($){return t({[Y$]:()=>({match:(O)=>{let j={},x=(S,K)=>{j[S]=K};return O===void 0?(G$($).forEach((S)=>x(S,void 0)),{matched:!0,selections:j}):{matched:s($,O,x),selections:j}},getSelectionKeys:()=>G$($),matcherType:"optional"})})}var jS=($,O)=>{for(let j of $)if(!O(j))return!1;return!0},xS=($,O)=>{for(let[j,x]of $.entries())if(!O(x,j))return!1;return!0},SS=($,O)=>{let j=Reflect.ownKeys($);for(let x of j)if(!O(x,$[x]))return!1;return!0};function d(...$){return t({[Y$]:()=>({match:(O)=>{let j={},x=(S,K)=>{j[S]=K};return{matched:$.every((S)=>s(S,O,x)),selections:j}},getSelectionKeys:()=>tO($,G$),matcherType:"and"})})}function p1(...$){return t({[Y$]:()=>({match:(O)=>{let j={},x=(S,K)=>{j[S]=K};return tO($,G$).forEach((S)=>x(S,void 0)),{matched:$.some((S)=>s(S,O,x)),selections:j}},getSelectionKeys:()=>tO($,G$),matcherType:"or"})})}function u($){return{[Y$]:()=>({match:(O)=>({matched:Boolean($(O))})})}}function eO(...$){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?[]:G$(j))})})}function a1($){return!0}function k$($){return typeof $=="number"}function o$($){return typeof $=="string"}function $O($){return typeof $=="bigint"}var i1=t(u(a1)),ZS=t(u(a1)),XS=i1,OO=($)=>Object.assign(t($),{startsWith:(O)=>{return OO(d($,(j=O,u((x)=>o$(x)&&x.startsWith(j)))));var j},endsWith:(O)=>{return OO(d($,(j=O,u((x)=>o$(x)&&x.endsWith(j)))));var j},minLength:(O)=>OO(d($,((j)=>u((x)=>o$(x)&&x.length>=j))(O))),length:(O)=>OO(d($,((j)=>u((x)=>o$(x)&&x.length===j))(O))),maxLength:(O)=>OO(d($,((j)=>u((x)=>o$(x)&&x.length<=j))(O))),includes:(O)=>{return OO(d($,(j=O,u((x)=>o$(x)&&x.includes(j)))));var j},regex:(O)=>{return OO(d($,(j=O,u((x)=>o$(x)&&Boolean(x.match(j))))));var j}}),l1=OO(u(o$)),g$=($)=>Object.assign(t($),{between:(O,j)=>g$(d($,((x,S)=>u((K)=>k$(K)&&x<=K&&S>=K))(O,j))),lt:(O)=>g$(d($,((j)=>u((x)=>k$(x)&&x<j))(O))),gt:(O)=>g$(d($,((j)=>u((x)=>k$(x)&&x>j))(O))),lte:(O)=>g$(d($,((j)=>u((x)=>k$(x)&&x<=j))(O))),gte:(O)=>g$(d($,((j)=>u((x)=>k$(x)&&x>=j))(O))),int:()=>g$(d($,u((O)=>k$(O)&&Number.isInteger(O)))),finite:()=>g$(d($,u((O)=>k$(O)&&Number.isFinite(O)))),positive:()=>g$(d($,u((O)=>k$(O)&&O>0))),negative:()=>g$(d($,u((O)=>k$(O)&&O<0)))}),KS=g$(u(k$)),jO=($)=>Object.assign(t($),{between:(O,j)=>jO(d($,((x,S)=>u((K)=>$O(K)&&x<=K&&S>=K))(O,j))),lt:(O)=>jO(d($,((j)=>u((x)=>$O(x)&&x<j))(O))),gt:(O)=>jO(d($,((j)=>u((x)=>$O(x)&&x>j))(O))),lte:(O)=>jO(d($,((j)=>u((x)=>$O(x)&&x<=j))(O))),gte:(O)=>jO(d($,((j)=>u((x)=>$O(x)&&x>=j))(O))),positive:()=>jO(d($,u((O)=>$O(O)&&O>0))),negative:()=>jO(d($,u((O)=>$O(O)&&O<0)))}),GS=jO(u($O)),YS=t(u(function($){return typeof $=="boolean"})),QS=t(u(function($){return typeof $=="symbol"})),JS=t(u(function($){return $==null})),VS=t(u(function($){return $!=null})),Z$={__proto__:null,matcher:Y$,optional:xx,array:function(...$){return Ox({[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 G$(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?[]:G$($[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:jS(O,(K)=>s(S,K,x)),selections:j}},getSelectionKeys:()=>$.length===0?[]:G$($[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:xS(O,(X,G)=>{let L=s(K,G,x),Q=s(Z,X,x);return L&&Q}),selections:j}},getSelectionKeys:()=>$.length===0?[]:[...G$($[0]),...G$($[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?[l1,$[0]]:$;return{matched:SS(O,(X,G)=>{let L=typeof X!="string"||Number.isNaN(Number(X))?null:Number(X),Q=L!==null&&s(K,L,S),J=s(K,X,S),I=s(Z,G,S);return(J||Q)&&I}),selections:x}},getSelectionKeys:()=>$.length===0?[]:[...G$($[0]),...G$($[1])]})})},intersection:d,union:p1,not:function($){return t({[Y$]:()=>({match:(O)=>({matched:!s($,O,()=>{})}),getSelectionKeys:()=>[],matcherType:"not"})})},when:u,select:eO,any:i1,unknown:ZS,_:XS,string:l1,number:KS,bigint:GS,boolean:YS,symbol:QS,nullish:JS,nonNullable:VS,instanceOf:function($){return t(u(function(O){return(j)=>j instanceof O}($)))},shape:function($){return t(u(OS($)))}};class n1 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 jx={matched:!1,value:void 0};function k($){return new Tj($,jx)}class Tj{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))?jx:{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 Tj(this.input,X)}when($,O){if(this.state.matched)return this;let j=Boolean($(this.input));return new Tj(this.input,j?{matched:!0,value:O(this.input,this.input)}:jx)}otherwise($){return this.state.matched?this.state.value:$(this.input)}exhaustive($=WS){return this.state.matched?this.state.value:$(this.input)}run(){return this.exhaustive()}returnType(){return this}narrow(){return this}}function WS($){throw new n1($)}var Sx,BS=new Uint8Array(16);function Rj(){if(!Sx){if(typeof crypto>"u"||!crypto.getRandomValues)throw Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Sx=crypto.getRandomValues.bind(crypto)}return Sx(BS)}var j$=[];for(let $=0;$<256;++$)j$.push(($+256).toString(16).slice(1));function s1($,O=0){return(j$[$[O+0]]+j$[$[O+1]]+j$[$[O+2]]+j$[$[O+3]]+"-"+j$[$[O+4]]+j$[$[O+5]]+"-"+j$[$[O+6]]+j$[$[O+7]]+"-"+j$[$[O+8]]+j$[$[O+9]]+"-"+j$[$[O+10]]+j$[$[O+11]]+j$[$[O+12]]+j$[$[O+13]]+j$[$[O+14]]+j$[$[O+15]]).toLowerCase()}var Zx={};function LS($,O,j){let x;if($)x=t1($.random??$.rng?.()??Rj(),$.msecs,$.seq,O,j);else{let S=Date.now(),K=Rj();NS(Zx,S,K),x=t1(K,Zx.msecs,Zx.seq,O,j)}return O??s1(x)}function NS($,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 t1($,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 l$=LS;class C${table;id;constructor($,O){this.table=$;this.id=O}static byId($,O){return new C$($,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 F${table;id;constructor($,O){this.table=$;this.id=O}static byId($,O){return new F$($,O)}history(){return this.table.database.rowHistory(this)}toJSON(){return{id:this.id,tableId:this.table.id}}}class Dj{table;id;constructor($,O){this.table=$;this.id=O}static byId($,O){return new Dj($,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 V${database;id;constructor($,O){this.database=$;this.id=O}static byId($,O){return new V$($,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)=>C$.byId(this,O.column.id))}addColumn($){return this.database.addColumn(this,$)}async reorderColumns($){return await this.database.reorderColumns(this,$),this}row($){return F$.byId(this,$)}async views(){let{views:$}=await this.detail();return $.map((O)=>Dj.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 _j($,O,j,x={}){let S=Y(await $.storage.queryDatabases({body:{sql:j,databaseId:x.database?.id,baseVersions:Object.fromEntries((x.baseVersions??[]).map(({table:Q,version:J})=>[Q.id,J]))}})),K=new Map;for(let Q of[x.database,...(x.baseVersions??[]).map(({table:J})=>J.database)]){if(!Q)continue;let J=K.get(Q.id);if(J)J.add(Q);else K.set(Q.id,new Set([Q]))}let Z=(Q)=>{let J=K.get(Q)?.values().next().value;if(J)return J;let I=O($,Q);return K.set(Q,new Set([I])),I},X=(Q)=>{let J=S.tableDatabases[Q];if(!J)throw Error(`SQL response is missing the owner of table ${Q}`);return V$.byId(Z(J),Q)},G=new Set(Object.keys(S.newVersions).map((Q)=>X(Q).database.id));if(S.statement.kind==="schema")G.add(S.statement.databaseId);for(let Q of G)for(let J of K.get(Q)??[])J.invalidateSchema();let L=k(S.statement).with({kind:"select"},(Q)=>Q).with({kind:"schema"},({databaseId:Q,summary:J})=>({kind:"schema",database:Z(Q),summary:J})).with({kind:"insert"},{kind:"update"},{kind:"delete"},({kind:Q,tableId:J,tableName:I})=>({kind:Q,table:X(J),tableName:I})).with({kind:"alterColumnType"},({tableId:Q,tableName:J,columnId:I,columnName:z,to:W})=>{let V=X(Q);return{kind:"alterColumnType",table:V,tableName:J,column:C$.byId(V,I),columnName:z,to:W}}).exhaustive();return{result:S.result?US(S.result,X,S.tableDatabases):void 0,changesApplied:S.changesApplied,insertedRows:L.kind==="insert"?S.insertedRowIds.map((Q)=>F$.byId(L.table,Q)):[],newVersions:Object.entries(S.newVersions).map(([Q,J])=>({table:X(Q),version:J})),readVersions:Object.entries(S.readVersions).map(([Q,J])=>({table:X(Q),version:J})),truncatedTables:S.truncatedTables,statement:L}}function US($,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)=>F$.byId(x,S)):[]}}class Mj{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 Mj($,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 Gx extends QO{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 Aj($){return k($).with({type:"relation"},({table:O})=>({type:"relation",database:O.database.id,table:O.id})).with({type:Z$.not("relation")},(O)=>O).exhaustive()}var zS={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 IS($){return k($).with({type:"text"},()=>"Text").with({type:"number"},()=>"Number").with({type:"boolean"},()=>"Checkbox").with({type:"date"},()=>"Date").with({type:"date_range"},()=>"Time range").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})=>zS[O]).with({type:"relation"},()=>"Relation").exhaustive(()=>"Column")}function Xx($){return $.map((O)=>({id:l$(),label:O}))}function e1($,O,j){return $?.kind===O&&"change"in $&&$.change.kind===j}function Kx($){return k($).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 r$($,O,j){let[x]=$;if($.length!==1||!e1(x,O,j))throw new f(`expected one ${O}.${j} result, got ${$.map(Kx).join(", ")||"none"}`);return x}class W$ extends P{access=new o(this.client,"database",this);async fetch(){return Y(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 W$($,O)}static async create($,O){let j=Y(await $.storage.createDatabase({body:{name:O.name}}));return new W$($,j.id)}static async list($){return Y(await $.storage.listDatabases()).map((j)=>new W$($,j.database.id))}query($,O){return _j(this.client,W$.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)=>V$.byId(this,O.table.id)));async table($){let{tables:O}=await this.schema(),j=O.find((x)=>x.table.name===$);return j?V$.byId(this,j.table.id):void 0}async createTable($){let{table:O}=r$(await this.applyOps([{kind:"table",table:l$(),change:{kind:"create",name:$.name}}]),"table","created");return V$.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 Gx(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(Kx).join(", ")||"none"}`);return j.tables.map(({table:x})=>V$.byId(this,x))}async deleteTable($){this.assertOwns(`table ${$.id}`,$.database),r$(await this.applyOps([{kind:"table",table:$.id,change:{kind:"delete"}}]),"table","deleted")}async columnCasts($){return this.assertOwns(`column ${$.id}`,$.table.database),Y(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}=Y(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}=Y(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 V$.byId(this,O.id)}webhookOf($){return Mj.fromRecord(V$.byId(this,$.tableId),A.byId(this.client,$.createdBy),$)}async webhooks(){let{webhooks:$}=Y(await this.client.storage.listDatabaseWebhooks({path:{id:this.id}}));return $.map((O)=>this.webhookOf(O))}async createWebhook($){this.assertOwns("table",$.database);let O=Y(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),Y(await this.client.storage.deleteDatabaseWebhook({path:{id:this.id,webhook_id:$.id}}))}async sharePermissions(){return Y(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 r$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"change_type",to:Aj(O.to)}}],{baseVersions:[{table:$.table,version:j}]}),"column","type_changed")}async columnConversion($,O){return this.assertOwns(`column ${$.id}`,$.table.database),Y(await this.client.storage.convertDatabaseColumn({path:{id:this.id,table_id:$.table.id,column_id:$.id},body:{to:Aj(O)}}))}async convertColumnIntoNewColumn($,O){let j=await this.columnConversion($,O.to),x=O.name??`${await $.name()} (${IS(O.to)})`,S=l$(),K=[{kind:"column",table:$.table.id,column:S,change:{kind:"create",definition:{source:"new",name:x,type:Aj(O.to),options:Xx(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(!e1(Z,"column","created"))throw new f(`expected a column.created result, got ${Z?Kx(Z):"none"}`);return C$.byId($.table,Z.column)}async deleteColumn($){this.assertOwns(`column ${$.id}`,$.table.database);let O=await $.table.version(),{tableVersion:j}=r$(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}=r$(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}=r$(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}=r$(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:Aj(O.type),...O.options!==void 0?{options:Xx(O.options)}:{},...O.inferType!==void 0?{inferType:O.inferType}:{}},{column:x}=r$(await this.applyOps([{kind:"column",table:$.id,column:l$(),change:{kind:"create",definition:j,...O.after!==void 0?{after:O.after.id}:{}}}]),"column","created");return C$.byId($,x)}async addColumnOptions($,O){return this.assertOwns(`column ${$.id}`,$.table.database),r$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"add_options",options:Xx(O)}}]),"column","options_added")}}class Yx{client;constructor($){this.client=$}query($,O){return _j(this.client,W$.byId,$,O)}byId($){return W$.byId(this.client,$)}create($){return W$.create(this.client,$)}list(){return W$.list(this.client)}}class Pj{id;name;constructor($,O){this.id=$;this.name=O}static async list($){let{skills:O}=Y(await $.storage.getSystemSkillsHandler());return O.map((j)=>new Pj(j.id,j.name))}}class Qx{client;async byTeamSlug($){let O=Y(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=Y(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=Y(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,$)}async createCanvas($){let O=Y(await this.client.storage.createCanvasHandler({body:{documentName:$.name,projectId:$.project?.id}}));return q.byId(this.client,O.documentId)}createSnippet($){return q.createSnippet(this.client,$)}createSkill($){return q.createSkill(this.client,$)}systemSkills(){return Pj.list(this.client)}search($,O){return q.search(this.client,$,O)}recent($){return q.recent(this.client,$)}recentlyDeleted(){return q.recentlyDeleted(this.client)}}class BO extends P{async fetch(){let{attachment:$}=Y(await this.client.email.getAttachment({path:{id:this.id}}));return $}static byId($,O){return new BO($,O)}static from($,O){return new BO($,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:$}=Y(await this.client.email.getAttachmentDocumentId({path:{id:this.id}}));return q.byId(this.client,$)}}class z$ extends X${access=new o(this.client,"email_thread",this);async followup(){return Y(await this.client.storage.getEmailFollowup({path:{thread_id:this.id}}))}async setFollowup($){return Y(await this.client.storage.setEmailFollowup({path:{thread_id:this.id},body:$}))}async calendarInvitations(){return Y(await this.client.email.getThreadCalendarInvitations({path:{thread_id:this.id}}))}async addEventToCalendar($,O,j={}){let x=Y(await this.client.email.copyThreadCalendarInvitation({path:{thread_id:this.id,message_id:$.id,invitation_id:O.id},body:{calendarId:j.calendar?.id}}));return $$.fromRecord(this.client,x)}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?s$($.sharePermission):void 0}}))}entityType="email_thread";propertyEntityType="THREAD";async fetch(){let{thread:$}=Y(await this.client.email.getThread({path:{thread_id:this.id},query:{limit:100}}));return $}static byId($,O){return new z$($,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",($)=>R$.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 Y(await this.client.email.getThreadMessagesHandler({path:{id:this.id},query:{...$?.since?{since:$.since}:{},...$?.limit?{limit:$.limit}:{}}})).map((j)=>_$.from(this.client,j))}async attachments(){let{messages:$}=await this.detail.get();return $.flatMap((O)=>O.attachments.map((j)=>BO.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?_$.byId(this.client,j.db_id):void 0}async archive($=!0){await this.mutate((O)=>O.email.archiveThread({path:{id:this.id},body:{value:$}}))}static async archiveMany($,O,j=!0){let x=[];for(let S=0;S<O.length;S+=100){let K=O.slice(S,S+100),Z=Y(await $.email.archiveThreads({body:{thread_ids:K.map((G)=>G.id),value:j}})),X=new Set(Z.failed_thread_ids);for(let G of K)if(G.detail.clear(),X.has(G.id))x.push(G)}return x}async updateState($){await this.mutate((O)=>O.email.updateThreadState({path:{id:this.id},body:$}))}async operations(){return Y(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=x$({filters:{email_filters:{}},type:"email",make:($,O)=>new z$($,O.thread_id)})}class _$ extends P{async fetch(){return Y(await this.client.email.getMessage({path:{id:this.id}}))}static byId($,O){return new _$($,O)}static from($,O){return new _$($,O.db_id,O)}static async send($,O){let{message:j}=Y(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?_$.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",($)=>R$.byId(this.client,$));async operationStatus(){return Y(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 z$.byId(this.client,(await this.detail.get()).thread_db_id)}async downloadEml(){return Y(await this.client.email.getMessageEml({path:{id:this.id},parseAs:"blob"}))}}class LO extends _${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 LO($,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:{...Jx($),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:oO.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 oO.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 oO{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 oO(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 Jx($){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),(Q)=>String.fromCharCode(Q)).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 NO extends P{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 NO($,O,void 0,j)}static from($,O,j){return new NO($,O.id,O,j)}async fetch(){let $=Y(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 xO extends P{async fetch(){let{labels:$}=Y(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 xO($,O)}static async list($){let{labels:O}=Y(await $.email.listLabels());return O.map((j)=>new xO($,j.id,j))}static async create($,O){let{label:j}=Y(await $.email.createLabel({body:{label_name:O}}));if(!j.id)throw new f("created label has no id");return new xO($,j.id)}async delete(){Y(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 Vx{client;async createDraft($,O){let j=Y(await this.client.email.createDraft({body:{draft:Jx($)},headers:O?{"X-Email-Link-Id":O.id}:void 0}));if(!j.draft.db_id)throw Error("Draft response has no message id");return LO.byId(this.client,j.draft.db_id)}draftById($){return LO.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=Y(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 LO.byId(this.client,K.db_id);if(S.messages.length<j)return}}async filters($){return Y(await this.client.email.listEmailFilters({headers:$?{"X-Email-Link-Id":$.id}:void 0})).filters.map((O)=>NO.from(this.client,O,$))}async upsertFilter($,O){return NO.from(this.client,Y(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 Y(await this.client.email.listContacts()).contacts}reminders($){let{inboxes:O,...j}=$??{};return c(async(x)=>{let S=Y(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:z$.byId(this.client,K)})),nextCursor:S.nextCursor}})}constructor($){this.client=$}byId($){return z$.byId(this.client,$)}message($){return _$.byId(this.client,$)}attachment($){return BO.byId(this.client,$)}link($){return R$.byId(this.client,$)}links(){return R$.list(this.client)}async connectionProviders(){return Y(await this.client.auth.emailConnectionProviders())}async recoverDraftTransfer($){return Y(await this.client.email.recoverDraftTransfer({path:{id:$}}))}send($){return _$.send(this.client,$)}search($,O){return z$.search(this.client,$,O)}inbox($){return c(async(O)=>{let j=Y(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)=>z$.byId(this.client,x.id)),nextCursor:j.next_cursor}})}label($){return xO.byId(this.client,$)}labels(){return xO.list(this.client)}createLabel($){return xO.create(this.client,$)}archive($,O=!0){return z$.archiveMany(this.client,$,O)}async deleteLabel($){Y(await this.client.email.deleteLabel({path:{id:$.id}}))}async blockSender($){Y(await this.client.email.blockSender({body:{email_address:$}}))}async unblockSender($){Y(await this.client.email.unblockSender({body:{email_address:$}}))}async blockedSenders(){return Y(await this.client.email.listBlockedSenders()).blocked_emails}}class TO{client;id;constructor($,O){this.client=$;this.id=O}static byId($,O){return new TO($,O)}async delete(){Y(await this.client.storage.deleteEntityMention({path:{mention_id:this.id}}))}toJSON(){return{id:this.id}}}class Wx{client;constructor($){this.client=$}byId($){return TO.byId(this.client,$)}async create($,O){let j=Y(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 TO.byId(this.client,j.id)}}function Bx($,O){return{chat:UO.byId($,O.id),name:O.name,announcements:O.announcements}}class UO extends P{static byId($,O){return new UO($,O)}static from($,O){return new UO($,O.jid,O)}async fetch(){let{chats:$}=Y(await this.client.storage.whatsappChats()),O=$.find((j)=>j.jid===this.id);if(!O)throw new E("WhatsApp chat is not available");return O}kind=this.field("kind");name=this.field("name");phoneNumber=this.field("phoneNumber");lastActivityAt=this.field("lastActivityAt");archived=this.field("archived");pinned=this.field("pinned");canAdd=this.field("canAdd");cannotAddReason=this.field("cannotAddReason");community=this.mappedField("community",($)=>$?Bx(this.client,$):void 0);added=this.mappedField("added",($)=>$?y$.byId(this.client,$.id):void 0);shared=this.mappedField("shared",($)=>$?y$.byId(this.client,$.id):void 0);async add(){let $=await this.kind(),O=await this.mutate((j)=>j.storage.externalChatAdd({body:{provider:"whatsapp",remoteId:this.id,kind:$}}));return y$.byId(this.client,O.chatId)}async refresh(){return this.detail.clear(),await this.detail.get(),this}}class M$ extends P{chat;constructor($,O,j,x){super($,j,x);this.chat=O}static byId($,O,j){return new M$($,O,j)}static from($,O,j){return new M$($,O,j.id,j)}async fetch(){return Y(await this.client.storage.externalChatMessage({path:{chat_id:this.chat.id,message_id:this.id}}))}body=this.field("body");sender=this.field("sender");sentAt=this.field("sentAt");editedAt=this.field("editedAt");deleted=this.field("deleted");reactions=this.field("reactions");deliveryState=this.field("deliveryState");kind=this.field("kind");forwarded=this.field("forwarded");viewOnce=this.field("viewOnce");mentions=this.field("mentions");rich=this.field("rich");replyTo=this.mappedField("replyTo",($)=>$?M$.byId(this.client,this.chat,$):void 0);attachments=this.mappedField("attachments",($)=>$.map((O)=>({ordinal:O.ordinal,state:O.state,fileName:O.fileName,mime:O.mime,size:O.size,width:O.width??void 0,height:O.height??void 0,durationSeconds:O.durationSeconds??void 0,presentation:O.presentation??void 0,url:O.fileId?`${this.client.hosts["static-files"]}/file/${O.fileId}`:void 0})))}class SO{chat;id;record;constructor($,O,j){this.chat=$;this.id=O;this.record=j}static byId($,O){return new SO($,O)}static from($,O){return new SO($,O.jid,O)}get displayName(){return this.record?.displayName??void 0}get mentionToken(){return this.id.split("@")[0]??this.id}get admin(){return this.record?.admin}toJSON(){return{id:this.id,chat:this.chat.id,displayName:this.displayName,admin:this.admin}}}class ZO{id;chat;filename;kind;constructor($,O,j,x){this.id=$;this.chat=O;this.filename=j;this.kind=x}static byId($,O){return new ZO(O,$)}static from($,O){return new ZO(O.uploadId,$,O.filename,O.kind)}toJSON(){return{id:this.id,chat:this.chat.id,filename:this.filename,kind:this.kind}}}class XO extends P{chat;constructor($,O,j,x){super($,j,x);this.chat=O}static byId($,O,j){return new XO($,O,j)}static from($,O,j){return new XO($,O,j.id,j)}async fetch(){let O=Y(await this.client.storage.externalChatDelivery({path:{chat_id:this.chat.id},body:[this.id]})).find((j)=>j.id===this.id);if(!O)throw new E("External chat send is not available");return O}state=this.field("state");errorCode=this.field("errorCode");createdAt=this.field("createdAt");message=this.mappedField("messageId",($)=>$?M$.byId(this.client,this.chat,$):void 0);async request(){let{payload:$}=await this.detail.get(),O=$.message,j=k(O).returnType().with({type:"media"},(x)=>({type:"media",upload:ZO.byId(this.chat,x.uploadId),caption:x.caption??void 0})).with({type:"mutation"},(x)=>({type:"mutation",message:M$.byId(this.client,this.chat,x.messageId),operation:x.operation,text:x.text??void 0})).with({type:"text"},(x)=>({type:"text",text:x.text,mentions:(x.mentions??[]).map((S)=>SO.byId(this.chat,S))})).exhaustive();return{idempotencyKey:$.idempotencyKey,message:j,replyTo:$.replyTo?M$.byId(this.client,this.chat,$.replyTo):void 0}}async refresh(){return this.detail.clear(),await this.detail.get(),this}}class y$ extends H${entityType="external_chat";static byId($,O){return new y$($,O)}async fetch(){return Y(await this.client.storage.externalChat({path:{chat_id:this.id}}))}provider=this.field("provider");name=this.field("name");kind=this.field("kind");canSend=this.field("canSend");sendReason=this.field("sendReason");sendingIdentity=this.field("sendingIdentity");unreadCount=this.field("unreadCount");backfill=this.field("backfill");limits=this.field("limits");members=this.field("members");participants=this.mappedField("members",($)=>($?.participants??[]).map((O)=>SO.from(this,O)));disappearingSeconds=this.field("disappearingSeconds");owner=this.mappedField("userId",($)=>A.byId(this.client,$));async community(){let{provider:$,community:O}=await this.detail.get();if(!O)return;return k($).with("whatsapp",()=>Bx(this.client,O)).exhaustive()}async*messages($={}){yield*c(async(O)=>{let j=Y(await this.client.storage.externalChatMessages({path:{chat_id:this.id},query:{before:O,limit:$.limit}}));return{items:j.messages.map((x)=>M$.from(this.client,this,x)),nextCursor:j.nextCursor}})}async markRead($){this.assertChat($.chat),await this.mutate((O)=>O.storage.externalChatRead({path:{chat_id:this.id},body:{messageId:$.id}}))}async permissions(){return Y(await this.client.storage.externalChatPermissions({path:{chat_id:this.id}}))}async updatePermissions($){await this.mutate((O)=>O.storage.externalChatUpdatePermissions({path:{chat_id:this.id},body:$}))}async remove(){await this.mutate(($)=>$.storage.externalChatRemove({path:{chat_id:this.id}}))}async upload($){let O=Y(await this.client.storage.externalChatUpload({path:{chat_id:this.id},body:{file:$}}));return ZO.from(this,O)}async send($,O){if(O.replyTo)this.assertChat(O.replyTo.chat);let j=k($).returnType().with({type:"text"},(S)=>{let K=S.mentions??[];for(let Z of K)this.assertChat(Z.chat);return{type:"text",text:S.text,mentions:K.map((Z)=>Z.id)}}).with({type:"media"},(S)=>{return this.assertChat(S.upload.chat),{type:"media",uploadId:S.upload.id,caption:S.caption}}).with({type:"mutation"},(S)=>{return this.assertChat(S.message.chat),{type:"mutation",messageId:S.message.id,operation:S.operation,text:S.text}}).exhaustive(),x=await this.mutate((S)=>S.storage.externalChatSend({path:{chat_id:this.id},body:{idempotencyKey:O.idempotencyKey,message:j,replyTo:O.replyTo?.id}}));return XO.from(this.client,this,x)}async sends(){return Y(await this.client.storage.externalChatSends({path:{chat_id:this.id}})).map(($)=>XO.from(this.client,this,$))}async delivery($){for(let O of $)this.assertChat(O.chat);return Y(await this.client.storage.externalChatDelivery({path:{chat_id:this.id},body:$.map((O)=>O.id)})).map((O)=>XO.from(this.client,this,O))}async messageAttachments($){for(let O of $)this.assertChat(O.chat);return Y(await this.client.storage.externalChatMessageAttachments({path:{chat_id:this.id},body:$.map((O)=>O.id)})).map((O)=>({message:M$.byId(this.client,this,O.messageId),attachments:O.attachments.map((j)=>({ordinal:j.ordinal,state:j.state,fileName:j.fileName,mime:j.mime,size:j.size,url:j.fileId?`${this.client.hosts["static-files"]}/file/${j.fileId}`:void 0}))}))}async refresh(){return this.detail.clear(),await this.detail.get(),this}assertChat($){if($.id!==this.id)throw Error("External chat reference belongs to another chat")}}class Lx{client;constructor($){this.client=$}async list(){return Y(await this.client.storage.externalChats()).map(($)=>y$.byId(this.client,$.id))}byId($){return y$.byId(this.client,$)}}class Nx{client;constructor($){this.client=$}async list($={}){let{favorites:O}=Y(await this.client.storage.listFavorites({query:{entityType:$.entityTypes,entityId:$.entityIds}}));return O}async add($){return Y(await this.client.storage.addFavorite({body:{entityId:$.id,entityType:$.entityType}}))}async remove($){Y(await this.client.storage.removeFavoriteByEntity({path:{entity_type:$.entityType,entity_id:$.id}}))}async reorder($){Y(await this.client.storage.reorderFavorites({body:{favorites:$}}))}}class KO extends H${entityType="foreign_entity";async fetch(){return Y(await this.client.storage.getForeignEntity({path:{id:this.id}}))}static byId($,O){return new KO($,O)}static fromRecord($,O){return new KO($,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 o1({login:$,...O}){return{...O,login:$??void 0}}class Ux{client;constructor($){this.client=$}byId($){return KO.byId(this.client,$)}async bySource($,O){return KO.fromRecord(this.client,Y(await this.client.storage.getForeignEntityBySource({path:{source:$,foreign_entity_id:O}})))}async githubPullRequestFacets(){let{repositories:$,authors:O,assignees:j,labels:x}=Y(await this.client.storage.getGithubPullRequestFacets());return{repositories:$,authors:O.map(o1),assignees:j.map(o1),labels:x.map(({color:S,...K})=>({...K,color:S??void 0}))}}}class p${form;id;constructor($,O){this.form=$;this.id=O}static byId($,O){return new p$($,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 C$.byId(await this.form.table(),(await this.detail()).column)}async options(){return(await this.detail()).options.map(($)=>zO.byId(this,$.id))}}class zO{question;id;constructor($,O){this.question=$;this.id=O}static byId($,O){return new zO($,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 RO{form;id;detail;constructor($,O,j){this.form=$;this.id=O;this.detail=new B$(()=>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 RO($,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 B$(()=>this.load(),$),this}}class a${form;id;constructor($,O){this.form=$;this.id=O}static byId($,O){return new a$($,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)=>p$.byId(this.form,O.id)):[]}}class Cj{entityType;id;constructor($,O){this.entityType=$;this.id=O}static byId($,O){return new Cj($,O)}}class v$ extends P{async fetch(){return Y(await this.client.storage.getForm({path:{id:this.id}}))}static byId($,O){return new v$($,O)}static async create($,O){let j=Y(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 v$($,j.form.id,j)}static async list($,O){if(!O)return Y(await $.storage.listAccessibleForms()).map(({form:S})=>new v$($,S.id));return Y(await $.storage.listForms({query:{databaseId:O.id}})).map((x)=>new v$($,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",($)=>W$.byId(this.client,$.databaseId));table=this.mappedField("form",($)=>V$.byId(W$.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(($)=>a$.byId(this,$.id))}async questions(){return(await this.detail.get()).sections.flatMap(($)=>$.kind==="questions"?$.questions.map((O)=>p$.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)=>k(X).with({kind:"group"},(G)=>({kind:"group",...x(G)})).with({kind:"condition"},(G)=>({kind:"condition",column:j(G.column),test:k(G.test).with({kind:"options"},(L)=>({...L,options:L.options.map((Q)=>Q.id)})).with({kind:"entities"},(L)=>({...L,entities:L.entities.map((Q)=>Q.id)})).with({kind:Z$.union("presence","text","number","date","dateRange","checkbox")},(L)=>L).exhaustive()})).exhaustive())}),S={sections:$.map((Z)=>{if(Z.section)this.assertOwns(Z.section);let X={id:Z.section?.id??l$(),title:Z.title,description:Z.description??""};return k(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??l$(),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=k(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","date_range","link","clear")},(S)=>S).exhaustive();return{question:O.id,value:x}})}unlockedBooking($){return $?{...$,section:a$.byId(this,$.section)}:void 0}async outcome($,O){return k($).with({outcome:"stopped"},(j)=>({...j,section:a$.byId(this,j.section)})).with({outcome:"submitted"},async(j)=>{let x=F$.byId(await this.table(),j.row),S=this.unlockedBooking(j.booking);return{outcome:"submitted",response:RO.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(Y(await this.client.storage.submitFormResponse({path:{id:this.id},body:O})),$)}async editResponse($){let O={answers:this.wireAnswers($)};return this.outcome(Y(await this.client.storage.editMyFormResponse({path:{id:this.id},body:O})),$)}async myResponse(){let $=Y(await this.client.storage.getMyFormResponse({path:{id:this.id}})),O=await this.table(),j=await Promise.all($.answers.map(async(K)=>{let Z=p$.byId(this,K.question),X=await k(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 zO.byId(Z,L.id)})})).with({type:"entities"},(G)=>({type:"entities",value:G.value.map((L)=>({entityType:L.entityType,entity:Cj.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 Q=V$.byId(W$.byId(this.client,L.kind.database),L.kind.table);return{type:"rows",value:G.value.map((J)=>F$.byId(Q,J))}}).with({type:Z$.union("text","number","boolean","date","date_range","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?F$.byId(O,$.response.row):void 0,S=this.unlockedBooking($.booking);return{...S?{booking:S}:{},response:RO.byId(this,$.response.id,{status:$.response.status,row:x,answers:j,booking:S}),status:$.response.status,stoppedAtSection:$.response.stoppedAtSection?a$.byId(this,$.response.stoppedAtSection):void 0,row:x,submittedAt:$.response.submittedAt,updatedAt:$.response.updatedAt,answers:j}}async responseSummary(){let $=Y(await this.client.storage.getFormResponseSummary({path:{id:this.id}}));return{...$,stoppedBySection:$.stoppedBySection.map((O)=>({section:a$.byId(this,O.section),count:O.count}))}}async tally(){return Y(await this.client.storage.getFormTally({path:{id:this.id}})).questions.map((O)=>{let j=p$.byId(this,O.question);return{question:j,responses:O.responses,buckets:O.buckets.flatMap((x)=>k(x.value).with({kind:"option"},(S)=>[{count:x.count,value:{kind:"option",option:zO.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 Y(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 zx{client;constructor($){this.client=$}byId($){return v$.byId(this.client,$)}create($){return v$.create(this.client,$)}list($){return v$.list(this.client,$)}}class DO extends P{static byId($,O){return new DO($,O)}async fetch(){return Y(await this.client.storage.getGithubPullRequest({path:{id:this.id}}))}title=this.field("title");url=this.field("url");status=this.field("status");async changes(){let $=Y(await this.client.storage.getGithubPullRequestChanges({path:{id:this.id}}));return{changeset:$.changeset?new Ix(this.client,this,$.changeset):void 0,error:$.error??void 0}}}class Ix{client;pullRequest;record;constructor($,O,j){this.client=$;this.pullRequest=O;this.record=j}get id(){return this.record.id}async patch(){return Y(await this.client.storage.getGithubPullRequestChangesPatch({path:{id:this.pullRequest.id},query:{changeset:this.id}})).patch}toJSON(){return{pullRequestId:this.pullRequest.id,...this.record}}}class Hx{client;constructor($){this.client=$}byId($){return DO.byId(this.client,$)}forEntity($){return DO.byId(this.client,$.id)}}class _O extends P{static byId($,O){return new _O($,O)}async fetch(){return Y(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 L$.from(this.client,await this.mutate((j)=>j.storage.approveHarnessPairing({path:{code:this.id},body:O})))}}class $j{client;id;constructor($,O){this.client=$;this.id=O}static byId($,O){return new $j($,O)}async claim($){let O=Y(await this.client.storage.claimHarnessPairing({path:{pairing_id:this.id},body:{device_secret:$}}));return"harness"in O?{harness:L$.from(this.client,O.harness),token:O.token}:void 0}toJSON(){return{id:this.id}}}class Tx{client;constructor($){this.client=$}byId($){return L$.byId(this.client,$)}async list(){return Y(await this.client.storage.listHarnesses()).map(($)=>L$.from(this.client,$))}async me(){return L$.from(this.client,Y(await this.client.storage.getSelfHarness()))}async deleteSelf(){Y(await this.client.storage.deleteSelfHarness())}async agents(){return Y(await this.client.storage.listHarnessAgents()).map(($)=>T$.byId(this.client,$.bot_id))}async sessions(){return Y(await this.client.storage.listHarnessSessions()).map(($)=>l.byId(this.client,$.session_id))}pairing($){return _O.byId(this.client,$)}async createPairing($){let O=Y(await this.client.storage.createHarnessPairing({body:$}));return{pairing:_O.byId(this.client,O.code),device:$j.byId(this.client,O.pairing_id),deviceSecret:O.device_secret,expiresAt:O.expires_at,pollIntervalSeconds:O.poll_interval_seconds}}}class Fj{id;url;width;height;constructor($,O,j,x){this.id=$;this.url=O;this.width=j;this.height=x}static byId($,O,j){return new Fj(O,`${$.hosts["static-files"]}/file/${O}`,j?.width,j?.height)}toJSON(){return{id:this.id,url:this.url,width:this.width,height:this.height}}}class Ej extends Fj{width;height;mimeType;sizeBytes;note;constructor($,O,j,x,S,K,Z){super($,O,j,x);this.width=j;this.height=x;this.mimeType=S;this.sizeBytes=K;this.note=Z}toJSON(){return{...super.toJSON(),mimeType:this.mimeType,sizeBytes:this.sizeBytes,note:this.note}}}class Rx{client;constructor($){this.client=$}async generate($){let O=Y(await this.client.cognition.generateImage({body:{prompt:$.prompt,aspectRatio:$.aspectRatio??null,referenceImages:($.referenceImages??[]).map(HS)}}));return new Ej(O.staticFileId,O.url,O.width,O.height,O.mimeType,O.sizeBytes,O.note??void 0)}}function HS($){return $ instanceof q?{type:"document",id:$.id}:{type:"staticFile",id:$.id}}var TS="00000001-0000-0000-0000-000000000001",$2="00000001-0000-0000-0000-000000000002",RS="00000001-0000-0000-0000-000000000004",DS="00000001-0000-0000-0000-000000000014",_S="00000001-0000-0000-0002-000000000001",MS="00000001-0000-0000-0002-000000000004";function AS($){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 Q$ extends q{static byId($,O){return new Q$($,O)}static async create($,O){let{documentId:j}=Y(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,propertyValues:await PS($,O)}}));return new Q$($,j)}static async summaries($,O){if(O.length===0)return[];let{previews:j}=Y(await $.storage.getBatchPreviewHandler({body:{document_ids:O.map((S)=>S.id)}})),x=new Map(j.flatMap((S)=>S.type==="access"?[[S.document_id,S]]:[]));return O.flatMap((S)=>{let K=x.get(S.id);if(!K)return[];return[{task:S,name:K.document_name,owner:A.byId($,K.owner),updatedAt:K.updated_at??void 0,completed:K.sub_type?.type==="task"&&K.sub_type.is_completed}]})}static async findSimilar($,O){let{results:j}=Y(await $.storage.taskSimilaritySearchHandler({body:{taskName:O.title,markdown:O.body??null}}));return j.map((x)=>({task:new Q$($,x.taskId),name:x.taskName,similarity:x.vectorScore}))}static async forPullRequest($,O){let j=AS(O),{pullRequests:x}=Y(await $.storage.getGithubPullRequestTasks({body:{githubKeys:[j]}}));return(x[0]?.taskIds??[]).map((S)=>new Q$($,S))}async completed(){let{subType:$}=await this.detail.get();if($!=="task")return;let j=(await this.properties()).find((x)=>x.definition.id===$2)?.value;return j?.type==="SelectOption"&&j.value.includes(MS)}webUrl(){return`${this.client.webAppUrl}/app/task/${this.id}`}static search=x$({filters:{document_filters:{sub_types:["task"],task_filters:{}}},type:"document",make:($,O)=>new Q$($,O.document_id)})}async function PS($,O){if(!O.initiative&&!O.assignees&&!O.dueDate)return null;let j=O.assignees??[await A.me($)],x=[{propertyId:$2,value:{type:"select_option",option_id:_S}}];if(j.length>0)x.push({propertyId:TS,value:{type:"multi_entity_reference",references:j.map((S)=>({entity_id:S.id,entity_type:"USER"}))}});if(O.initiative)x.push({propertyId:DS,value:{type:"entity_reference",reference:{entity_id:O.initiative.id,entity_type:"INITIATIVE"}}});if(O.dueDate)x.push({propertyId:RS,value:{type:"date",value:O.dueDate.toISOString()}});return x}class i$ extends P{access=new o(this.client,"initiative",this);static byId($,O){return new i$($,O)}static from($,O){return new i$($,O.id,O)}async fetch(){return Y(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)=>Q$.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?s$($.sharePermission):void 0}}))}async delete(){await this.mutate(($)=>$.storage.deleteInitiative({path:{initiative_id:this.id}}))}}class Dx{client;constructor($){this.client=$}byId($){return i$.byId(this.client,$)}async list(){return Y(await this.client.storage.listInitiatives()).initiatives.map(($)=>i$.byId(this.client,$.id))}async summaries(){return Y(await this.client.storage.listInitiatives()).initiatives.map(($)=>({initiative:i$.byId(this.client,$.id),name:$.name,updatedAt:$.updatedAt}))}async create($){return i$.from(this.client,Y(await this.client.storage.createInitiative({body:{name:$.name,description:$.description,memberIds:$.members?.map((O)=>O.id),shareWithTeam:$.shareWithTeam,propertyValues:$.propertyValues}})))}}class _x{client;constructor($){this.client=$}byId($){return D$.byId(this.client,$)}async create($){return D$.from(this.client,Y(await this.client.storage.meetingCreate({body:$})))}async list(){return Y(await this.client.storage.meetingList()).meetings.map(($)=>D$.from(this.client,$))}async active(){return Y(await this.client.storage.meetingListActive()).meetings.map(($)=>D$.from(this.client,$))}async lookup($){return D$.from(this.client,Y(await this.client.storage.meetingLookup({path:{token:$}})))}}class IO extends P{async fetch(){return Y(await this.client.notification.getTypedNotificationById({path:{notification_id:this.id}}))}static byId($,O){return new IO($,O)}static from($,O){return new IO($,O.id,O)}static list($,O){return c(async(j)=>{let x=Y(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)=>IO.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 Mx{client;constructor($){this.client=$}byId($){return IO.byId(this.client,$)}list($){return IO.list(this.client,$)}async markSeen($){Y(await this.client.notification.bulkMarkNotificationsSeen({body:{notificationIds:$}}))}async markDone($){Y(await this.client.notification.bulkMarkNotificationsDone({body:{notificationIds:$}}))}async delete($){Y(await this.client.notification.bulkDeleteUserNotificationsV2({body:{notificationIds:$}}))}async preferences(){return Y(await this.client.notification.getNotificationTypePreferences())}async enableType($){Y(await this.client.notification.enableNotificationType({path:{notification_event_type:$}}))}async disableType($){Y(await this.client.notification.disableNotificationType({path:{notification_event_type:$}}))}}class Ax{client;constructor($){this.client=$}async list(){let{data:$}=Y(await this.client.storage.getPinsHandler({}));return $?.recent??[]}async add($,O){Y(await this.client.storage.addPinHandler({path:{pinned_item_id:$.id},body:{pinType:$.entityType,pinIndex:O.index}}))}async remove($){Y(await this.client.storage.removePinHandler({path:{pinned_item_id:$.id},body:{pinType:$.entityType}}))}async reorder($){Y(await this.client.storage.reorderPinsHandler({body:$}))}}class Px{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 MO{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 MO($,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=Y(await this.client.properties.updatePropertyOption({path:{definition_id:this.definitionId,option_id:this.id},body:$})),this}async delete(){Y(await this.client.properties.deletePropertyOption({path:{definition_id:this.definitionId,option_id:this.id}}))}}class GO{client;id;detail;constructor($,O,j){this.client=$;this.id=O;this.detail=new B$(()=>this.fetch(),j)}async fetch(){return Y(await this.client.properties.getPropertyDefinition({path:{definition_id:this.id}}))}static async create($,O){let j=Y(await $.properties.createPropertyDefinition({body:{display_name:O.displayName,scope:O.scope,data_type:O.dataType}}));return new GO($,j.id,j)}static byId($,O){return new GO($,O)}static fromRecord($,O){return new GO($,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 Y(await this.client.properties.deletePropertyDefinition({path:{definition_id:this.id}}))}async options(){return Y(await this.client.properties.getPropertyOptions({path:{definition_id:this.id}})).map((O)=>MO.from(this.client,this.id,O))}async addOption($){let O=Y(await this.client.properties.addPropertyOption({path:{definition_id:this.id},body:$}));return MO.from(this.client,this.id,O)}async updateOption($,O){let j=Y(await this.client.properties.updatePropertyOption({path:{definition_id:this.id,option_id:$.id},body:O}));return MO.from(this.client,this.id,j)}async deleteOption($){return Y(await this.client.properties.deletePropertyOption({path:{definition_id:this.id,option_id:$.id}}))}}class Cx{client;constructor($){this.client=$}async list($){return Y(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 GO.fromRecord(this.client,x)})}create($){return GO.create(this.client,$)}definition($){return GO.byId(this.client,$)}async bulkEntityProperties($){return Y(await this.client.properties.getBulkEntityProperties({body:$}))}async updateEntityPropertyOptions($,O){return Y(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 Y(await this.client.properties.addEntityPropertyOption({path:{...$.entity.propertyReference(),property_id:$.property.id,option_id:$.option.id}}))}async removeEntityPropertyOption($){return Y(await this.client.properties.removeEntityPropertyOption({path:{...$.entity.propertyReference(),property_id:$.property.id,option_id:$.option.id}}))}async tags(){return Y(await this.client.properties.listTags({}))}}function Fx($){return k($).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 CS($){return k($).with({type:"multiple"},(O)=>({type:"multiple",triggers:O.triggers.map(Fx)})).with({type:"cron"},Fx).with({type:"events"},Fx).exhaustive()}class h$ extends P{static byId($,O){return new h$($,O)}static from($,O){if(!O.id)throw Error("Routine response has no id");return new h$($,O.id,O)}async fetch(){return Y(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,$));sourceTemplate=this.mappedField("template_id",($)=>$?h$.byId(this.client,$):void 0);async template(){let $=await this.client.scheduledAction.getScheduledActionTemplate({path:{id:this.id}});if($.response?.status===404)return;return this.toTemplate(Y($))}async shareAsTemplate($){return this.toTemplate(Y(await this.client.scheduledAction.shareScheduledActionTemplate({path:{id:this.id},body:$})))}async activateTemplate($){return h$.from(this.client,Y(await this.client.scheduledAction.activateScheduledActionTemplate({path:{id:this.id},body:{...qj($),enabled:$.enabled??!0}})))}toTemplate($){return new O2(this,A.byId(this.client,$.author),$)}async stopSharingTemplate(){Y(await this.client.scheduledAction.unshareScheduledActionTemplate({path:{id:this.id}}))}async update($){await this.mutate((O)=>O.scheduledAction.updateScheduledAction({path:{id:this.id},body:qj($)}))}async setEnabled($){await this.mutate((O)=>O.scheduledAction.setScheduledActionEnabled({path:{id:this.id},body:{enabled:$}}))}async execute(){let $=Y(await this.client.scheduledAction.executeScheduledActionNow({path:{id:this.id}}));if($.resource)return k($.resource).with({type:"agent"},(O)=>l.byId(this.client,O.id)).with({type:"chat"},(O)=>K$.byId(this.client,O.id)).exhaustive();return $.chat_id?K$.byId(this.client,$.chat_id):void 0}async history(){return Y(await this.client.scheduledAction.listScheduledActionHistory({path:{id:this.id}})).map(($)=>new Ex(this,$))}async delete(){await this.mutate(($)=>$.scheduledAction.deleteScheduledAction({path:{id:this.id}}))}}class O2{routine;author;record;constructor($,O,j){this.routine=$;this.author=O;this.record=j}activate($){return this.routine.activateTemplate($)}toJSON(){return this.record}}class Ex{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 qj($){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:CS($.trigger),task:{...O}}}class qx{client;constructor($){this.client=$}byId($){return h$.byId(this.client,$)}async create($){return h$.from(this.client,Y(await this.client.scheduledAction.createScheduledAction({body:{...qj($),enabled:$.enabled??!0}})))}async list($){return Y(await this.client.scheduledAction.listScheduledActions({query:{include_events:$?.includeEvents}})).map((O)=>h$.from(this.client,O))}}class wx{client;constructor($){this.client=$}byId($){return Q$.byId(this.client,$)}create($){return Q$.create(this.client,$)}summaries($){return Q$.summaries(this.client,$)}findSimilar($){return Q$.findSimilar(this.client,$)}forPullRequest($){return Q$.forPullRequest(this.client,$)}search($,O){return Q$.search(this.client,$,O)}}class fx{client;constructor($){this.client=$}byId($){return S$.byId(this.client,$)}current(){return S$.current(this.client)}list(){return S$.list(this.client)}}class bx{client;constructor($){this.client=$}async get($){return Y(await this.client.unfurl.getUnfurl({query:{url:$}}))}async bulk($){return Y(await this.client.unfurl.getUnfurlBulk({body:{url_list:$}}))}}class kx{client;constructor($){this.client=$}byId($){return A.byId(this.client,$)}me(){return A.me(this.client)}async search($){let O=$.trim().toLocaleLowerCase();if(!O)throw Error("A person search needs a name or email.");let j=await this.client.contacts.getContacts();if(j.response?.status===404)return[];let{contacts:x}=Y(j),S=[...new Set(x)],K=[];for(let Z=0;Z<S.length;Z+=100){let X=S.slice(Z,Z+100),{names:G}=Y(await this.client.auth.getUserNamesWithEmail({body:{user_ids:X}})),L=new Map(G.map((Q)=>[Q.id,Q]));for(let Q of X){let J=L.get(Q)??{id:Q};if(`${[J.first_name,J.last_name].filter(Boolean).join(" ")} ${Q}`.toLocaleLowerCase().includes(O))K.push(A.fromName(this.client,J))}}return K}}class YO extends P{signingSecret;constructor($,O,j,x){super($,O,j);this.signingSecret=x}async fetch(){return Y(await this.client.storage.getWebhook({path:{webhook_id:this.id}}))}static async create($,O){let j=Y(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 YO($,j.id,j,j.signing_secret)}static byId($,O){return new YO($,O)}static fromRecord($,O){return new YO($,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 gx{client;constructor($){this.client=$}create($){return YO.create(this.client,$)}byId($){return YO.byId(this.client,$)}async list(){let{webhooks:$}=Y(await this.client.storage.listWebhooks());return $.map((O)=>YO.fromRecord(this.client,O))}}class AO extends P{static byId($,O){return new AO($,O)}static from($,O){return new AO($,O.id,O)}async fetch(){let{account:$}=Y(await this.client.storage.whatsappAccount());if($?.id!==this.id)throw new E("WhatsApp account is not available");return $}state=this.field("state");identity=this.field("identityJid");owner=this.mappedField("userId",($)=>A.byId(this.client,$));async refresh(){return this.detail.clear(),await this.detail.get(),this}}class yx{client;constructor($){this.client=$}async account(){let{account:$}=Y(await this.client.storage.whatsappAccount());return $?AO.from(this.client,$):void 0}async chats(){return Y(await this.client.storage.whatsappChats()).chats.map(($)=>UO.from(this.client,$))}}function vx($){if("properties"in $.data)return $.data.properties;if($.tag==="calendarEvent")return $.data.extra.properties;return[]}function j2($,O,j){let x=[];for(let S of vx(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:K$.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:z$.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 m$($,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:J$.byId($,O.data.callId),snapshot:O,tags:x,createdBy:O.data.createdBy};case"calendarEvent":return{type:"calendar_event",id:O.data.id,entity:$$.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:KO.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 x2="00000000-0000-0000-0000-000000000000",hx={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"]},wj=($)=>$.replace(/[A-Z]/g,(O)=>O.toLowerCase()),S2=($,O)=>$==null?O:{"&":[$,O]};function mx($,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==="!"){mx(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)=>{mx(Z,`${O}.${S}[${X}]`)})}class fj{client;tagSets;constructor($){this.client=$}sets(){return this.tagSets??=this.client.properties.listTags({}).then(Y),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(hx,S))))throw Error(`Invalid workspace includeTypes. Supported values: ${Object.keys(hx).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)mx($[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:x2}},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}=Y(await this.client.email.listLinks()),K=S.filter((X)=>wj(X.email_address)===wj(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=S2(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(hx))if(!x.includes(S))O[K]={l:{[Z]:x2}}}if($.tags?.length){let S=(await this.sets()).flatMap((G)=>{let L=G.definition;if(!L)return[];return G.options.flatMap((Q)=>Q.value.type==="string"?[{id:Q.id,definitionId:L.id,label:Q.value.value,scope:G.scope==="user"?"personal":"team"}]:[])}),K=new Map;for(let G of $.tags){let L=S.filter((Q)=>wj(Q.label)===wj(G.label.trim())&&(!G.scope||Q.scope===G.scope));if(!L.length)throw Error(`Unknown tag "${G.label}". Available tags: ${S.map((Q)=>`${Q.label} (${Q.scope})`).join(", ")}.`);if($.tagsMatch==="all"&&L.length>1)throw Error(`Tag "${G.label}" is ambiguous; specify personal or team scope.`);for(let Q of L)K.set(Q.id,Q)}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=S2(O.propf,X)}return O}}class ux{client;constructor($){this.client=$}async page($={}){let O=new fj(this.client);return this.fetch(O,await O.body($),$.cursor)}async*list($={}){let O=new fj(this.client),j=await O.body($);yield*c((x)=>this.fetch(O,j,x))}async fetch($,O,j){let x=Y(await this.client.storage.postItemsSoupAst({body:O,query:j?{cursor:j}:void 0})),K=x.items.some((Z)=>vx(Z).some((X)=>X.definition.data_type==="TAG"))?await $.tagMap():new Map;return{items:x.items.map((Z)=>j2(this.client,Z,K)),nextCursor:x.next_cursor,hasMore:x.next_cursor!=null}}}function Z2({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:G,url:L,...Q}){let J,I=G??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,H=Q.signal??new AbortController().signal;while(!0){if(H.aborted)break;B++;let C=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)C.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:C,signal:H},_=new Request(L,D);if($)_=await $(L,D);let N=await(Q.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let T=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{T.cancel()}catch{}};H.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await T.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
+async function cO($,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 B${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*c($){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 QO 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 Y($){if($.error!==void 0)throw new QO($.response?.status??0,$.error);return $.data}class P{client;id;detail;constructor($,O,j){this.client=$;this.id=O;this.detail=new B$(()=>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=Y(await $(this.client));return this.detail.clear(),O}}class T$ extends P{async permission(){return Y(await this.client.storage.getEntityPermission({path:{entity_type:this.entityType,entity_id:this.id}}))}async favorite(){return Y(await this.client.storage.addFavorite({body:{entityId:this.id,entityType:this.entityType}})),this}async unfavorite(){return Y(await this.client.storage.removeFavoriteByEntity({path:{entity_type:this.entityType,entity_id:this.id}})),this}}class X$ extends T${propertyReference(){return{entity_type:this.propertyEntityType,entity_id:this.id}}async properties($){let{properties:O}=Y(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){Y(await this.client.properties.setEntityProperty({path:{...this.propertyReference(),property_id:$.id},body:{value:O??null}}))}async updatePropertyOptions($){return Y(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($){Y(await this.client.properties.deleteEntityProperty({path:{entity_property_id:$.property.id}}))}}var m7={"<":"\\u003c",">":"\\u003e","&":"\\u0026"};function n$($,O){let j=JSON.stringify(O).replace(/[<>&]/g,(x)=>m7[x]??x);return`<${$}>${j}</${$}>`}function u7($){return typeof $==="object"&&$!==null&&typeof $.toMention==="function"}var c7={toMention:()=>({tag:n$("m-group-mention",{groupAlias:"here"}),mention:{entity_type:"group",entity_id:"here"}})};function d7($,...O){let j="",x=[];for(let[S,K]of $.entries()){j+=K;let Z=O[S];if(Z===void 0)continue;if(u7(Z)){let X=Z.toMention();j+=X.tag,x.push(X.mention)}else j+=String(Z)}return{content:j,mentions:l7(x)}}function l7($){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 O$($){return typeof $==="string"?{content:$,mentions:[]}:$}class L$ extends P{static byId($,O){return new L$($,O)}static from($,O){return new L$($,O.id,O)}async fetch(){let $=Y(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 R$ extends P{static byId($,O){return new R$($,O)}static from($,O){return new R$($,O.bot.id,O)}async fetch(){let $=Y(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",($)=>$?L$.byId(this.client,$):void 0);async update($){await this.mutate((O)=>O.storage.updateAgent({path:{agent_id:this.id},body:m0($)}))}}function m0($){let{channels:O,team:j,host:x,autoAcceptPermissions:S,avatarUrl:K,channelScope:Z,defaultModel:X,isCoding:G,...L}=$;return{...L,channel_ids:O?.map((Q)=>Q.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 Bj($,O,j,x=[]){let{channelId:S,thread:K}=p7(O);if(await a7($)){let{id:X}=Y(await $.storage.entityMessageCreate({path:{parent_type:"channel",parent_id:S},body:{content:j.content,mentions:j.mentions,attachments:x.map((G)=>({entity_type:r7,entity_id:G.id,width:G.width??null,height:G.height??null})),thread_id:K?.rootId??null,nonce:crypto.randomUUID()}}));return X}if(x.length>0)throw new f("a user-owned bot can only post via the channel webhook endpoint, which "+"does not support images — use a team-owned bot, or requestedAs(user), "+"to attach images");if(K)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:Z}=Y(await $.storage.postChannelBotWebhook({path:{channel_id:S},body:{content:j.content},headers:{"x-macro-bot-scope":"user"}}));return Z}var r7="static/image";function p7($){return"rootId"in $?{channelId:$.channelId,thread:$}:{channelId:$.id}}async function a7($){if($.authConfig.type!=="bot"||$.hasActingUser())return!0;let{owner:O}=await $.selfBot();return O?.type==="team"}class m${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:$}=Y(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($,O){let j=await Bj(this.client,this,O$($),O?.images);return e.byId(this.client,this.channelId,j)}}class e extends T${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 Y(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 m$(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}=O$($);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 Lj{client;channel;record;constructor($,O,j){this.client=$;this.channel=O;this.record=j}agent(){return R$.byId(this.client,this.record.botId)}sessions(){return this.record.sessions.map(($)=>({session:l.byId(this.client,$.sessionId),isCurrent:$.isCurrent,createdAt:$.createdAt}))}turns(){return this.record.turns.map(($)=>new u0(this.client,this,$))}async startFresh($){Y(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 u0{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 l.byId(this.client,this.record.sessionId)}async retry($){Y(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 N$ extends P{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 N$($,O,j)}get path(){return{parent_type:this.parent.type,parent_id:this.parent.entity.id,id:this.id}}async fetch(){return Y(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 q$($,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=Y(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 i7=50;function x$($){let{filters:O,type:j,make:x,includeCrm:S}=$;return(K,Z,X)=>{let G=X?.searchOn??"name_content",L=X?.pageSize??i7;return c(async(Q)=>{let{results:J,next_cursor:I}=Y(await K.search.unifiedSearch({body:{query:Z,match_type:"partial",search_on:G,...O?{filters:O}:{},...S?{include_crm:!0}:{}},query:{page_size:L,...Q?{cursor:Q}:{}}}));return{items:J.filter((W)=>W.type===j).map((W)=>x(K,W)),nextCursor:I}})}}class JO{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 JO(this.client,this.channel,Y(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 JO(this.client,this,Y(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 N$.byId(this.client,{type:"channel",entity:this},$)}timelinePage($){return q$(this.client,{type:"channel",entity:this},(O)=>e.from(this.client,this.id,O),$)}async agentConversations(){return Y(await this.client.agentHarness.listAgentConversations({path:{channel_id:this.id}})).conversations.map(($)=>new Lj(this.client,this,$))}entityType="channel";propertyEntityType="CHANNEL";async fetch(){return Y(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}=Y(await $.storage.getOrCreateDm({body:{recipient_id:O.id}}));return new b($,j)}static async private($,O){let{channel_id:j}=Y(await $.storage.getOrCreatePrivate({body:{recipients:O.map((x)=>x.id)}}));return new b($,j)}static async create($,O){let{id:j}=Y(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 Bj(this.client,O?.thread??this,O$($),O?.images);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 c(async(O)=>{let j=Y(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:$}=Y(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 Y(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){Y(await this.client.storage.entityMessageTyping({path:{parent_type:"channel",parent_id:this.id},body:{active:$==="start",thread_id:O?.thread?.rootId??null}}))}attachments($){return c(async(O)=>{let j=Y(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=x$({type:"channel",make:($,O)=>new b($,O.channel_id)})}class A extends X${entityType="user";propertyEntityType="USER";async fetch(){let{names:$}=Y(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 fromName($,O){return new A($,O.id,O)}static async me($){let{user_id:O}=Y(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:n$("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=Y(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?HO.from(this.client,this,O.mine):void 0,requests:O.requests.map((j)=>HO.from(this.client,this,j))}}async submit($,O){return HO.from(this.client,this,Y(await this.client.storage.accessRequestsSubmit({path:this.path,body:{requestedLevel:$,revision:O}})))}async cancel($){Y(await this.client.storage.accessRequestsCancel({path:this.path,query:{revision:$}}))}async direct(){return Y(await this.client.storage.accessRequestsDirect({path:this.path})).map(($)=>({user:A.byId(this.client,$.userId),accessLevel:$.accessLevel}))}async grant($,O){Y(await this.client.storage.accessRequestsSetDirect({path:{...this.path,user_id:$.id},body:{accessLevel:O}}))}async remove($){Y(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 Y(await this.client.storage.accessRequestsResolve({path:{...this.path,request_id:$.id},body:O}))}toJSON(){return this.path}}class HO extends P{access;resolvedRecord;constructor($,O,j){super($,j.id,j);this.access=O}static from($,O,j){return new HO($,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 s$($){return{...$,channelSharePermissions:$.channelSharePermissions===void 0||$.channelSharePermissions===null?$.channelSharePermissions:$.channelSharePermissions.map((O)=>({channelId:O.channel.id,accessLevel:O.accessLevel,operation:O.operation}))}}class U$ extends P{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=Y(await $.agentHarness.createSessionReview({path:{session_id:O.id},body:{...j,executionId:x?.id??null}}));return U$.fromRecord($,O,S)}static async list($,O){return Y(await $.agentHarness.listExecutionReviews({path:{session_id:O.session().id,execution_id:O.id}})).map((x)=>U$.fromRecord($,O.session(),x))}async fetch(){return Y(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 c0($,{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 c0{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 dO extends P{parent;constructor($,O,j){super($,O);this.parent=j}static byId($,O,j){return new dO($,j,O)}async fetch(){return Y(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 Nj{client;sessionId;dto;constructor($,O,j){this.client=$;this.sessionId=O;this.dto=j}static from($,O,j){return new Nj($,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 Y(await this.client.agentHarness.editQueuedAction({path:{session_id:this.sessionId,action_id:this.actionId},body:{prompt:$}})),this.dto={...this.dto,prompt:$},this}async steer(){Y(await this.client.agentHarness.steerQueuedAction({path:{session_id:this.sessionId,action_id:this.actionId}}))}async remove(){Y(await this.client.agentHarness.removeQueuedAction({path:{session_id:this.sessionId,action_id:this.actionId}}))}}class lO{client;session;id;constructor($,O,j){this.client=$;this.session=O;this.id=j}static byId($,O,j){return new lO($,O,j)}async answer($){return Y(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 l extends P{access=new o(this.client,"agent_session",this);toolApprovalById($){return lO.byId(this.client,this,$)}async sharePermissions(){return Y(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:s$($)}))}static byId($,O){return new l($,O)}static async createManaged($,O){let{session:j}=Y(await $.agentHarness.createAgentSession({body:{prompt:O?.prompt,instructions:O?.instructions,model:O?.model,repoUrl:O?.repoUrl,repoBranch:O?.repoBranch}}));return new l($,j.id,j)}static async repositories($){let{repositories:O}=Y(await $.agentHarness.listAgentRepositories());return O.map((j)=>({url:j.url,defaultBranch:j.defaultBranch??void 0}))}static async repositoryBranches($,O){let{branches:j}=Y(await $.agentHarness.listAgentRepositoryBranches({query:{repoUrl:O}}));return j}static async chooseMode($,O){let{mode:j}=Y(await $.agentHarness.chooseAgentMode({body:{prompt:O}}));return j}async fetch(){return Y(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}=Y(await $.agentHarness.agentSessionsForPullRequest({body:{url:O}}));return j.map((x)=>l.byId($,x))}async pullRequests(){let{pullRequests:$}=Y(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($){Y(await this.client.agentHarness.linkAgentSessionPullRequest({path:{session_id:this.id},body:{url:$}}))}async unlinkPullRequest($){Y(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 Y(await $.agentHarness.getAgentSandboxSize()).size}static async setDefaultSandboxSize($,O){return Y(await $.agentHarness.putAgentSandboxSize({body:{size:O}})).size}static async codingPreferences($){return Y(await $.agentHarness.getAgentCodingPreferences())}static async setCodingPreferences($,O){return Y(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:$}=Y(await this.client.agentHarness.getAgentSessionQueue({path:{session_id:this.id}}));return $.map((O)=>Nj.from(this.client,this.id,O))}async changes(){return Y(await this.client.agentHarness.getAgentSessionChanges({path:{session_id:this.id}}))}async changesPatch(){return Y(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}=Y(await this.client.agentHarness.getAgentSessionFoldedLog({path:{session_id:this.id}}));return{bot:$,messages:O}}async log(){return Y(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:($)=>dO.byId(this.client,this,$)};async delete(){await this.mutate(($)=>$.agentHarness.deleteAgentSession({path:{session_id:this.id}}))}}class d0{client;constructor($){this.client=$}byId($){return l.byId(this.client,$)}createManaged($){return l.createManaged(this.client,$)}chooseMode($){return l.chooseMode(this.client,$)}repositories(){return l.repositories(this.client)}repositoryBranches($){return l.repositoryBranches(this.client,$)}forPullRequest($){return l.forPullRequest(this.client,$)}defaultSandboxSize(){return l.defaultSandboxSize(this.client)}setDefaultSandboxSize($){return l.setDefaultSandboxSize(this.client,$)}codingPreferences(){return l.codingPreferences(this.client)}setCodingPreferences($){return l.setCodingPreferences(this.client,$)}}class l0{client;constructor($){this.client=$}byId($){return R$.byId(this.client,$)}async list(){return Y(await this.client.storage.listAgents()).map(($)=>R$.from(this.client,$))}async create($){return R$.from(this.client,Y(await this.client.storage.createAgent({body:m0($)})))}}class r0{client;async usage($={}){let{users:O,...j}=$;return Y(await this.client.cognition.getUsageHandler({body:{...j,include_users:O?.map((x)=>x.id)}}))}constructor($){this.client=$}async structuredCompletion($){return Y(await this.client.cognition.structuredCompletion({body:$}))}async decide($){return Y(await this.client.cognition.decisions({body:$}))}}class t$ extends P{static byId($,O){return new t$($,O)}static from($,O){return new t$($,O.id,{id:O.id,name:O.name,createdAt:O.createdAt})}async fetch(){let $=Y(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 p0{client;constructor($){this.client=$}byId($){return t$.byId(this.client,$)}async list(){return Y(await this.client.storage.listUserApiKeys()).keys.map(($)=>t$.from(this.client,$))}async create($){let O=Y(await this.client.storage.createUserApiKey({body:{name:$}}));return{key:t$.from(this.client,O),secret:O.key}}async tokenForEmail($){return Y(await this.client.auth.macroApiToken({query:{email:$}}))}}class rO{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 Y(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 Y(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 S$ extends P{async fetch(){let O=Y(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 S$($,O)}static async current($){let O=Y(await $.auth.getTeam());if(!O)throw new E("caller has no current team");return new S$($,O.team.id,O.team)}static async list($){return Y(await $.auth.getUserTeams()).map((j)=>new S$($,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 $=Y(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 D$ extends P{async fetch(){let{links:$}=Y(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 D$($,O)}static async list($){let{links:O}=Y(await $.email.listLinks());return O.map((j)=>new D$($,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 Y(await this.client.email.mailboxSettingsOperations({headers:{"X-Email-Link-Id":this.id}}))}}class u$ extends P{async setContributesToAvailability($){await this.mutate((O)=>O.calendar.setAvailabilityCalendar({path:{calendar_id:this.id},body:{contributesToAvailability:$}}))}async fetch(){let{calendars:$}=Y(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 u$($,O)}static async list($){let{calendars:O}=Y(await $.calendar.listCalendars());return O.map((j)=>new u$($,j.id,j))}name=this.field("name");emailAddress=this.field("emailAddress");isPrimary=this.field("isPrimary");isWritable=this.field("isWritable");contributesToAvailability=this.field("contributesToAvailability");isSubscription=this.field("isSubscription");color=this.field("color");syncError=this.field("syncError");emailLink=this.mappedField("emailLinkId",($)=>D$.byId(this.client,$))}class pO{client;id;constructor($,O){this.client=$;this.id=O}async status(){return Y(await this.client.calendar.calendarReplacementStatus({path:{operation_id:this.id}}))}async confirm(){return Y(await this.client.calendar.confirmCalendarReplacement({path:{operation_id:this.id}}))}async discard(){Y(await this.client.calendar.discardCalendarReplacement({path:{operation_id:this.id}}))}}class $$ extends P{async notes($){return this.requireOwnOccurrence($),Y(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),Y(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 $$($,O)}static fromRecord($,O){return new $$($,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",($)=>$?u$.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:n7($)}));return $$.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,inbox:$.inbox}}))}async prepareReplacement($){let O=Y(await this.client.calendar.prepareCalendarReplacement({path:{event_id:this.id},body:{removeConference:$.removeConference,recurrenceId:$.recurrenceId,calendarId:$.calendar?.id}}));return new pO(this.client,O.operationId)}async providerUrl($={}){return Y(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,inbox:$.inbox}}));return $$.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 $$.fromRecord(this.client,O)}async ics(){return Y(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 $$.fromRecord(this.client,O)}}function n7($){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,inbox:$.inbox}}class w$ extends P{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$($,$$.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=Y(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=Y(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",($)=>$?S$.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 Y(await this.client.storage.getProjectPermissionsV2({path:{id:this.id}}))}async accessLevel(){return Y(await this.client.storage.getProjectUserAccessLevel({path:{id:this.id}}))}access=new o(this.client,"project",this);entityType="project";propertyEntityType="PROJECT";async fetch(){let{data:$}=Y(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}=Y(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:$}=Y(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=x$({filters:{project_filters:{}},type:"project",make:($,O)=>new n($,O.id)})}class VO extends P{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 VO($,O,j)}static from($,O,j){return new VO($,O,j.uuid,j)}async fetch(){let $=Y(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 c$ extends P{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 Y(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 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}=O$($);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 aO{client;document;id;detail;constructor($,O,j){this.client=$;this.document=O;this.id=j;this.detail=new B$(async()=>Y(await this.client.storage.getDocumentVersion({path:{document_id:O.id,document_version_id:j}})).data)}static byId($,O,j){return new aO($,O,j)}read(){return this.detail.get()}toJSON(){return{id:this.id,documentId:this.document.id}}}var s7=8;class q extends X${async meetingNotes(){return Y(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 Y(await this.client.storage.getDocumentAnchors({path:{document_id:this.id}})).data.map(($)=>VO.from(this.client,this,$))}async createHighlight($){return VO.from(this.client,this,Y(await this.client.storage.createAnchor({path:{document_id:this.id},body:{...$,fileType:"pdf",anchorType:"highlight"}})))}version($){return aO.byId(this.client,this,$)}async sharePermissions(){return Y(await this.client.storage.getDocumentPermissionsV2({path:{document_id:this.id}})).documentPermissions}async permissionsToken(){return Y(await this.client.storage.getDocumentPermissionsToken({path:{document_id:this.id}})).token}async prepareSave($){return Y(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 N$.byId(this.client,{type:"document",entity:this},$)}timelinePage($){return q$(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:$}=Y(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}=Y(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}=Y(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}=Y(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 c(async(x)=>{let S=Y(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}=Y(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:$}=Y(await this.client.storage.getDocumentTextContent({path:{document_id:this.id}}));if($!==null)return $;let{presigned_url:O}=Y(await this.client.storage.exportDocument({path:{document_id:this.id}})),j=await fetch(O);if(!j.ok)throw new QO(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}=Y(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=c(async(x)=>{let S=Y(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 cO(j,s7,async(x)=>{let{state:S,root:K,replies:Z}=Y(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:{...O$($),thread_id:O?.threadId??null}}));return c$.from(this.client,this.id,j)}async shortId(){return Y(await this.client.storage.getDocumentShortId({path:{document_id:this.id}}))}async teamShare(){return Y(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:$}=Y(await this.client.storage.getDocumentGithubPullRequests({path:{document_id:this.id}}));return $}async branchName(){let{branchName:$}=Y(await this.client.storage.getDocumentBranchName({path:{document_id:this.id}}));return $}webUrl(){return`${this.client.webAppUrl}/app/md/${this.id}`}static search=x$({filters:{document_filters:{}},type:"document",make:($,O)=>new q($,O.document_id)});toMention(){let $=this.detail.peek();return{tag:n$("m-document-mention",{documentId:this.id,documentName:$?.documentName??"",blockName:$?.fileType??"md"}),mention:{entity_type:"document",entity_id:this.id}}}}class a0{client;async noteDocuments($=""){let O=Y(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:S$.byId(this.client,j.id),name:j.name}))}}async availabilityCalendars(){return Y(await this.client.calendar.getAvailabilityCalendars()).calendars.map(($)=>({calendar:u$.byId(this.client,$.calendarId),name:$.name,isPrimary:$.isPrimary,contributesToAvailability:$.contributesToAvailability}))}async teamSharing(){return Y(await this.client.calendar.getTeamSharing()).sharing}async setTeamSharing($){return Y(await this.client.calendar.setTeamSharing({body:{sharing:$}})).sharing}occurrences($){let O;return c(async(j)=>{let x=Y(await this.client.storage.listOccurrences({query:{...$,cursor:j}}));O??=e7(this.client);let S=await O;return{items:x.items.map((K)=>{let Z=K.event.calendarId?S.get(K.event.calendarId):void 0;return{event:$$.fromRecord(this.client,K.event),occurrence:K.occurrence,calendarName:Z?.name,contributesToAvailability:d1(K.event,S),inbox:Z?.emailAddress,role:o7(K.event,S)}}),nextCursor:x.nextCursor}})}async teamPage($){let O=Y(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=Y(await this.client.storage.listTeamOutOfOffice({query:$}));return{items:O.items.map((j)=>({event:$$.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 u$.list(this.client)}calendar($){return u$.byId(this.client,$)}event($){return $$.byId(this.client,$)}replacement($){return new pO(this.client,$)}async createEvent($){let O=Y(await this.client.calendar.createCalendarEvent({body:t7($)}));return $$.fromRecord(this.client,O)}}function t7($){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}}async function e7($){let{calendars:O}=Y(await $.calendar.listCalendars());return new Map(O.map((j)=>[j.id,j]))}function d1($,O){let j=[$.calendarId,...($.sources??[]).map((x)=>x.calendarId)].flatMap((x)=>{let S=x?O.get(x):void 0;return S?[S.contributesToAvailability]:[]});if(j.some(Boolean))return!0;return j.length>0&&j.every((x)=>x===!1)?!1:void 0}function o7($,O){let j=$.attendees.find((S)=>S.isSelf);if(j?.isOrganizer)return $.isReadOnly?void 0:"organizer";let x=$.attendees.some((S)=>S.isOrganizer);if($.viewerCan.organize&&d1($,O)&&!x)return"organizer";return j?"guest":void 0}class _$ extends P{lookupToken;constructor($,O,j){super($,O,j);this.lookupToken=j?.shareToken}static byId($,O){return new _$($,O)}static from($,O){return new _$($,O.id,O)}async fetch(){if(this.lookupToken)return Y(await this.client.storage.meetingLookup({path:{token:this.lookupToken}}));let $=Y(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",($)=>$?J$.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 Y(await this.client.storage.meetingInvitePermissions({path:{token:(await this.detail.get()).shareToken}}))}async invite($){Y(await this.client.storage.meetingInvite({path:{token:(await this.detail.get()).shareToken},body:{email:$}}))}async inviteUsers($){Y(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 d$ extends P{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 Y(await this.client.storage.entityMessageGetMessage({path:this.path}))}static byId($,O,j){return new d$($,O,j)}static from($,O,j){return new d$($,O,j.id,j)}content=this.field("content");createdAt=this.field("created_at");updatedAt=this.field("updated_at");call(){return J$.byId(this.client,this.callId)}async author(){return A.byId(this.client,(await this.detail.get()).sender_id)}async reply($){let O=Y(await this.client.storage.entityMessageCreate({path:{parent_type:"call",parent_id:this.callId},body:{...O$($),thread_id:this.callId}}));return d$.from(this.client,this.callId,O)}async edit($){let{content:O,mentions:j}=O$($);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 J$ extends T${messageThreadById($){return N$.byId(this.client,{type:"call",entity:this},$)}timelinePage($){return q$(this.client,{type:"call",entity:this},(O)=>d$.from(this.client,this.id,O),$)}access=new o(this.client,"call",this);async meeting(){return _$.from(this.client,Y(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 Y(await this.client.storage.getCallRecord({path:{call_id:this.id}}))}static byId($,O){return new J$($,O)}message($){return d$.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=x$({filters:{call_filters:{}},type:"call",make:($,O)=>new J$($,O.call_id)})}class i0{client;constructor($){this.client=$}byId($){return J$.byId(this.client,$)}search($,O){return J$.search(this.client,$,O)}}class n0{client;constructor($){this.client=$}async list(){let{labels:$}=Y(await this.client.storage.listChannelLabels());return $}async create($,O=[]){return Y(await this.client.storage.createChannelLabel({body:{name:$,channelIds:O.map((j)=>j.id)}}))}async createSmartTag($,O){return Y(await this.client.storage.createChannelLabel({body:{name:$,rule:O}}))}async previewSmartTag($){return Y(await this.client.storage.previewSmartTag({body:$}))}async updateSmartTag($,O,j){return Y(await this.client.storage.renameChannelLabel({path:{label_id:$.id},body:{name:O,rule:j}}))}async rename($,O){return Y(await this.client.storage.renameChannelLabel({path:{label_id:$.id},body:{name:O}}))}async delete($){Y(await this.client.storage.deleteChannelLabel({path:{label_id:$.id}}))}async setLabel($,O){Y(await this.client.storage.setChannelLabel({path:{channel_id:$.id},body:{labelId:O?.id??null}}))}}class s0{client;async activity(){return Y(await this.client.storage.getActivity()).map(($)=>new JO(this.client,b.byId(this.client,$.channel_id),$))}labels;constructor($){this.client=$;this.labels=new n0($)}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:$}=Y(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}=Y(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 iO{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 iO($,O,j,x)}async stop(){Y(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 nO extends P{chat;constructor($,O,j){super($,j);this.chat=O}static byId($,O,j){return new nO($,O,j)}async fetch(){let $=Y(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 K$ 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=K$.byId(this.client,S.chat_id);return iO.byId(this.client,K,S.stream_id,nO.byId(this.client,K,S.message_id))}access=new o(this.client,"chat",this);entityType="chat";propertyEntityType="CHAT";async fetch(){let{chat:$}=Y(await this.client.cognition.getChat({path:{chat_id:this.id}}));return $}static byId($,O){return new K$($,O)}static async create($,O){let{id:j}=Y(await $.cognition.createChat({body:{name:O?.name??null,projectId:O?.project?.id??null}}));return new K$($,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 K$(this.client,$)}async restore(){await this.mutate(($)=>$.cognition.revertDeleteChat({path:{chat_id:this.id}}))}async history(){let{conversation:$}=Y(await this.client.cognition.getChatHistoryHandler({path:{chat_id:this.id}}));return $}webUrl(){return`${this.client.webAppUrl}/app/chat/${this.id}`}static search=x$({filters:{chat_filters:{}},type:"chat",make:($,O)=>new K$($,O.chat_id)});toMention(){return{tag:n$("m-document-mention",{documentId:this.id,documentName:this.detail.peek()?.name??"",blockName:"chat",blockParams:{}}),mention:{entity_type:"chat",entity_id:this.id}}}}class t0{client;constructor($){this.client=$}byId($){return K$.byId(this.client,$)}create($){return K$.create(this.client,$)}search($,O){return K$.search(this.client,$,O)}}var $S=8;class P$ extends P{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 Y(await this.client.storage.entityMessageGetMessage({path:this.path}))}static byId($,O,j){return new P$($,O,j)}static from($,O,j){return new P$($,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 sO(this.client,this.parent,$,{threadId:await this.threadId()})}async edit($){let{content:O,mentions:j}=O$($);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 Uj($,O){let j={parent_type:O.type,parent_id:O.id},x=c(async(K)=>{let Z=Y(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 cO(S,$S,async(K)=>{let{state:Z,root:X,replies:G}=Y(await $.storage.entityMessageGetThread({path:{...j,id:K.id}}));return{thread:Z,comments:[X,...G].map((L)=>P$.from($,O,L))}})}async function sO($,O,j,x){let S=Y(await $.storage.entityMessageCreate({path:{parent_type:O.type,parent_id:O.id},body:{...O$(j),thread_id:x?.threadId??null}}));return P$.from($,O,S)}class f$ extends T${messageThreadById($){return N$.byId(this.client,{type:"crm_contact",entity:this},$)}timelinePage($){return q$(this.client,{type:"crm_contact",entity:this},(O)=>P$.from(this.client,{type:"crm_contact",id:this.id},O),$)}entityType="crm_contact";async fetch(){return Y(await this.client.storage.getContact({path:{contact_id:this.id}}))}static byId($,O){return new f$($,O)}static from($,O){return new f$($,O.id,O)}name=this.field("name");email=this.field("email");company=this.mappedField("companyId",($)=>b$.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 Uj(this.client,this.commentParent)}async comment($,O){return sO(this.client,this.commentParent,$,O)}commentById($){return P$.byId(this.client,this.commentParent,$)}}class b$ extends X${messageThreadById($){return N$.byId(this.client,{type:"crm_company",entity:this},$)}timelinePage($){return q$(this.client,{type:"crm_company",entity:this},(O)=>P$.from(this.client,{type:"crm_company",id:this.id},O),$)}entityType="crm_company";propertyEntityType="COMPANY";async fetch(){return Y(await this.client.storage.getCompany({path:{company_id:this.id}}))}static byId($,O){return new b$($,O)}static from($,O){return new b$($,O.id,O)}name=this.field("name");description=this.field("description");hidden=this.field("hidden");emailSync=this.field("emailSync");team=this.mappedField("teamId",($)=>S$.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 Y(await this.client.storage.listCompanyContacts({path:{company_id:this.id}})).map((O)=>f$.from(this.client,O))}static search=x$({filters:{crm_company_filters:{}},type:"company",includeCrm:!0,make:($,O)=>new b$($,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 f$.from(this.client,O)}get commentParent(){return{type:"crm_company",id:this.id}}async comments(){return Uj(this.client,this.commentParent)}async comment($,O){return sO(this.client,this.commentParent,$,O)}commentById($){return P$.byId(this.client,this.commentParent,$)}}class e$ extends P{tableDetail=new B$(async()=>Y(await this.client.storage.getCrmPipelineTable({path:{id:this.id}})));static byId($,O){return new e$($,O)}static from($,O){return new e$($,O.id,O)}async fetch(){return Y(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",($)=>S$.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 Y(await this.client.storage.getCrmPipelinePermissions({path:{id:this.id}}))}async updateSharePermissions($){return this.mutate((O)=>O.storage.updateCrmPipelinePermissions({path:{id:this.id},body:s$($)}))}async table(){return zj.from(this.client,this,await this.tableRecord())}tableRecord(){return this.tableDetail.get()}rows(){return c(async($)=>{let O=Y(await this.client.storage.getCrmPipelineRows({path:{id:this.id},query:{after:$}}));return{items:O.rows.map((j)=>WO.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 c(async(O)=>{let j=Y(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)=>WO.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 zj extends P{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 zj($,O,j)}fetch(){return this.pipeline.tableRecord()}async columns(){return(await this.pipeline.tableRecord()).columns.map(($)=>Ij.from(this.client,this,$))}async version(){return(await this.pipeline.tableRecord()).table.version}rowById($){return WO.byId(this.client,this.pipeline,$)}rows(){return this.pipeline.rows()}}class WO extends P{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 WO($,O,j)}static from($,O,j){return new WO($,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 Ij extends P{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 Ij($,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 e0{client;constructor($){this.client=$}byId($){return e$.byId(this.client,$)}async list(){return Y(await this.client.storage.listCrmPipelines()).map(($)=>e$.from(this.client,$))}async create($){return e$.from(this.client,Y(await this.client.storage.createCrmPipeline({body:$})))}}class o0{client;pipelines;constructor($){this.client=$;this.pipelines=new e0($)}companyById($){return b$.byId(this.client,$)}contactById($){return f$.byId(this.client,$)}async contactByEmail($){let{contact:O}=Y(await this.client.storage.getContactByEmail({query:{email:$}}));return O?f$.from(this.client,O):void 0}async searchContacts($,O={}){let{contacts:j}=Y(await this.client.storage.searchContacts({query:{query:$,limit:O.limit}}));return j.map((x)=>f$.from(this.client,x))}async createCompany($){return b$.from(this.client,Y(await this.client.storage.createCrmCompany({body:$})))}async settings(){return Y(await this.client.storage.getCrmTeamSettings())}async updateSettings($){return Y(await this.client.storage.putCrmTeamSettings({body:$}))}async setStages($){return Y(await this.client.storage.putCrmTeamStages({body:$}))}async resetStages(){Y(await this.client.storage.resetCrmTeamStages())}searchCompanies($){return b$.search(this.client,$)}}var Y$=Symbol.for("@ts-pattern/matcher"),r1=Symbol.for("@ts-pattern/isVariadic");var $x=($)=>Boolean($&&typeof $=="object"),Hj=($)=>$&&!!$[Y$],s=($,O,j)=>{if(Hj($)){let x=$[Y$](),{matched:S,selections:K}=x.match(O);return S&&K&&Object.keys(K).forEach((Z)=>j(Z,K[Z])),S}if($x($)){if(!$x(O))return!1;if(Array.isArray($)){if(!Array.isArray(O))return!1;let x=[],S=[],K=[];for(let Z of $.keys()){let X=$[Z];Hj(X)&&X[r1]?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,Q)=>s(L,Z[Q],j))&&S.every((L,Q)=>s(L,X[Q],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)||Hj(K=S)&&K[Y$]().matcherType==="optional")&&s(S,O[x],j);var K})}return Object.is(O,$)},G$=($)=>{var O,j,x;return $x($)?Hj($)?(O=(j=(x=$[Y$]()).getSelectionKeys)==null?void 0:j.call(x))!=null?O:[]:Array.isArray($)?tO($,G$):tO(Object.values($),G$):[]},tO=($,O)=>$.reduce((j,x)=>j.concat(O(x)),[]);function OS(...$){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:()=>xx($),and:(O)=>d($,O),or:(O)=>p1($,O),select:(O)=>O===void 0?eO($):eO(O,$)})}function Ox($){return Object.assign(((O)=>Object.assign(O,{[Symbol.iterator](){let j=0,x=[{value:Object.assign(O,{[r1]:!0}),done:!1},{done:!0,value:void 0}];return{next:()=>{var S;return(S=x[j++])!=null?S:x.at(-1)}}}}))($),{optional:()=>Ox(xx($)),select:(O)=>Ox(O===void 0?eO($):eO(O,$))})}function xx($){return t({[Y$]:()=>({match:(O)=>{let j={},x=(S,K)=>{j[S]=K};return O===void 0?(G$($).forEach((S)=>x(S,void 0)),{matched:!0,selections:j}):{matched:s($,O,x),selections:j}},getSelectionKeys:()=>G$($),matcherType:"optional"})})}var jS=($,O)=>{for(let j of $)if(!O(j))return!1;return!0},xS=($,O)=>{for(let[j,x]of $.entries())if(!O(x,j))return!1;return!0},SS=($,O)=>{let j=Reflect.ownKeys($);for(let x of j)if(!O(x,$[x]))return!1;return!0};function d(...$){return t({[Y$]:()=>({match:(O)=>{let j={},x=(S,K)=>{j[S]=K};return{matched:$.every((S)=>s(S,O,x)),selections:j}},getSelectionKeys:()=>tO($,G$),matcherType:"and"})})}function p1(...$){return t({[Y$]:()=>({match:(O)=>{let j={},x=(S,K)=>{j[S]=K};return tO($,G$).forEach((S)=>x(S,void 0)),{matched:$.some((S)=>s(S,O,x)),selections:j}},getSelectionKeys:()=>tO($,G$),matcherType:"or"})})}function u($){return{[Y$]:()=>({match:(O)=>({matched:Boolean($(O))})})}}function eO(...$){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?[]:G$(j))})})}function a1($){return!0}function k$($){return typeof $=="number"}function o$($){return typeof $=="string"}function $O($){return typeof $=="bigint"}var i1=t(u(a1)),ZS=t(u(a1)),XS=i1,OO=($)=>Object.assign(t($),{startsWith:(O)=>{return OO(d($,(j=O,u((x)=>o$(x)&&x.startsWith(j)))));var j},endsWith:(O)=>{return OO(d($,(j=O,u((x)=>o$(x)&&x.endsWith(j)))));var j},minLength:(O)=>OO(d($,((j)=>u((x)=>o$(x)&&x.length>=j))(O))),length:(O)=>OO(d($,((j)=>u((x)=>o$(x)&&x.length===j))(O))),maxLength:(O)=>OO(d($,((j)=>u((x)=>o$(x)&&x.length<=j))(O))),includes:(O)=>{return OO(d($,(j=O,u((x)=>o$(x)&&x.includes(j)))));var j},regex:(O)=>{return OO(d($,(j=O,u((x)=>o$(x)&&Boolean(x.match(j))))));var j}}),l1=OO(u(o$)),g$=($)=>Object.assign(t($),{between:(O,j)=>g$(d($,((x,S)=>u((K)=>k$(K)&&x<=K&&S>=K))(O,j))),lt:(O)=>g$(d($,((j)=>u((x)=>k$(x)&&x<j))(O))),gt:(O)=>g$(d($,((j)=>u((x)=>k$(x)&&x>j))(O))),lte:(O)=>g$(d($,((j)=>u((x)=>k$(x)&&x<=j))(O))),gte:(O)=>g$(d($,((j)=>u((x)=>k$(x)&&x>=j))(O))),int:()=>g$(d($,u((O)=>k$(O)&&Number.isInteger(O)))),finite:()=>g$(d($,u((O)=>k$(O)&&Number.isFinite(O)))),positive:()=>g$(d($,u((O)=>k$(O)&&O>0))),negative:()=>g$(d($,u((O)=>k$(O)&&O<0)))}),KS=g$(u(k$)),jO=($)=>Object.assign(t($),{between:(O,j)=>jO(d($,((x,S)=>u((K)=>$O(K)&&x<=K&&S>=K))(O,j))),lt:(O)=>jO(d($,((j)=>u((x)=>$O(x)&&x<j))(O))),gt:(O)=>jO(d($,((j)=>u((x)=>$O(x)&&x>j))(O))),lte:(O)=>jO(d($,((j)=>u((x)=>$O(x)&&x<=j))(O))),gte:(O)=>jO(d($,((j)=>u((x)=>$O(x)&&x>=j))(O))),positive:()=>jO(d($,u((O)=>$O(O)&&O>0))),negative:()=>jO(d($,u((O)=>$O(O)&&O<0)))}),GS=jO(u($O)),YS=t(u(function($){return typeof $=="boolean"})),QS=t(u(function($){return typeof $=="symbol"})),JS=t(u(function($){return $==null})),VS=t(u(function($){return $!=null})),Z$={__proto__:null,matcher:Y$,optional:xx,array:function(...$){return Ox({[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 G$(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?[]:G$($[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:jS(O,(K)=>s(S,K,x)),selections:j}},getSelectionKeys:()=>$.length===0?[]:G$($[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:xS(O,(X,G)=>{let L=s(K,G,x),Q=s(Z,X,x);return L&&Q}),selections:j}},getSelectionKeys:()=>$.length===0?[]:[...G$($[0]),...G$($[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?[l1,$[0]]:$;return{matched:SS(O,(X,G)=>{let L=typeof X!="string"||Number.isNaN(Number(X))?null:Number(X),Q=L!==null&&s(K,L,S),J=s(K,X,S),I=s(Z,G,S);return(J||Q)&&I}),selections:x}},getSelectionKeys:()=>$.length===0?[]:[...G$($[0]),...G$($[1])]})})},intersection:d,union:p1,not:function($){return t({[Y$]:()=>({match:(O)=>({matched:!s($,O,()=>{})}),getSelectionKeys:()=>[],matcherType:"not"})})},when:u,select:eO,any:i1,unknown:ZS,_:XS,string:l1,number:KS,bigint:GS,boolean:YS,symbol:QS,nullish:JS,nonNullable:VS,instanceOf:function($){return t(u(function(O){return(j)=>j instanceof O}($)))},shape:function($){return t(u(OS($)))}};class n1 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 jx={matched:!1,value:void 0};function k($){return new Tj($,jx)}class Tj{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))?jx:{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 Tj(this.input,X)}when($,O){if(this.state.matched)return this;let j=Boolean($(this.input));return new Tj(this.input,j?{matched:!0,value:O(this.input,this.input)}:jx)}otherwise($){return this.state.matched?this.state.value:$(this.input)}exhaustive($=WS){return this.state.matched?this.state.value:$(this.input)}run(){return this.exhaustive()}returnType(){return this}narrow(){return this}}function WS($){throw new n1($)}var Sx,BS=new Uint8Array(16);function Rj(){if(!Sx){if(typeof crypto>"u"||!crypto.getRandomValues)throw Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Sx=crypto.getRandomValues.bind(crypto)}return Sx(BS)}var j$=[];for(let $=0;$<256;++$)j$.push(($+256).toString(16).slice(1));function s1($,O=0){return(j$[$[O+0]]+j$[$[O+1]]+j$[$[O+2]]+j$[$[O+3]]+"-"+j$[$[O+4]]+j$[$[O+5]]+"-"+j$[$[O+6]]+j$[$[O+7]]+"-"+j$[$[O+8]]+j$[$[O+9]]+"-"+j$[$[O+10]]+j$[$[O+11]]+j$[$[O+12]]+j$[$[O+13]]+j$[$[O+14]]+j$[$[O+15]]).toLowerCase()}var Zx={};function LS($,O,j){let x;if($)x=t1($.random??$.rng?.()??Rj(),$.msecs,$.seq,O,j);else{let S=Date.now(),K=Rj();NS(Zx,S,K),x=t1(K,Zx.msecs,Zx.seq,O,j)}return O??s1(x)}function NS($,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 t1($,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 l$=LS;class C${table;id;constructor($,O){this.table=$;this.id=O}static byId($,O){return new C$($,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 F${table;id;constructor($,O){this.table=$;this.id=O}static byId($,O){return new F$($,O)}history(){return this.table.database.rowHistory(this)}toJSON(){return{id:this.id,tableId:this.table.id}}}class Dj{table;id;constructor($,O){this.table=$;this.id=O}static byId($,O){return new Dj($,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 V${database;id;constructor($,O){this.database=$;this.id=O}static byId($,O){return new V$($,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)=>C$.byId(this,O.column.id))}addColumn($){return this.database.addColumn(this,$)}async reorderColumns($){return await this.database.reorderColumns(this,$),this}row($){return F$.byId(this,$)}async views(){let{views:$}=await this.detail();return $.map((O)=>Dj.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 _j($,O,j,x={}){let S=Y(await $.storage.queryDatabases({body:{sql:j,databaseId:x.database?.id,baseVersions:Object.fromEntries((x.baseVersions??[]).map(({table:Q,version:J})=>[Q.id,J]))}})),K=new Map;for(let Q of[x.database,...(x.baseVersions??[]).map(({table:J})=>J.database)]){if(!Q)continue;let J=K.get(Q.id);if(J)J.add(Q);else K.set(Q.id,new Set([Q]))}let Z=(Q)=>{let J=K.get(Q)?.values().next().value;if(J)return J;let I=O($,Q);return K.set(Q,new Set([I])),I},X=(Q)=>{let J=S.tableDatabases[Q];if(!J)throw Error(`SQL response is missing the owner of table ${Q}`);return V$.byId(Z(J),Q)},G=new Set(Object.keys(S.newVersions).map((Q)=>X(Q).database.id));if(S.statement.kind==="schema")G.add(S.statement.databaseId);for(let Q of G)for(let J of K.get(Q)??[])J.invalidateSchema();let L=k(S.statement).with({kind:"select"},(Q)=>Q).with({kind:"schema"},({databaseId:Q,summary:J})=>({kind:"schema",database:Z(Q),summary:J})).with({kind:"insert"},{kind:"update"},{kind:"delete"},({kind:Q,tableId:J,tableName:I})=>({kind:Q,table:X(J),tableName:I})).with({kind:"alterColumnType"},({tableId:Q,tableName:J,columnId:I,columnName:z,to:W})=>{let V=X(Q);return{kind:"alterColumnType",table:V,tableName:J,column:C$.byId(V,I),columnName:z,to:W}}).exhaustive();return{result:S.result?US(S.result,X,S.tableDatabases):void 0,changesApplied:S.changesApplied,insertedRows:L.kind==="insert"?S.insertedRowIds.map((Q)=>F$.byId(L.table,Q)):[],newVersions:Object.entries(S.newVersions).map(([Q,J])=>({table:X(Q),version:J})),readVersions:Object.entries(S.readVersions).map(([Q,J])=>({table:X(Q),version:J})),truncatedTables:S.truncatedTables,statement:L}}function US($,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)=>F$.byId(x,S)):[]}}class Mj{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 Mj($,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 Gx extends QO{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 Aj($){return k($).with({type:"relation"},({table:O})=>({type:"relation",database:O.database.id,table:O.id})).with({type:Z$.not("relation")},(O)=>O).exhaustive()}var zS={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 IS($){return k($).with({type:"text"},()=>"Text").with({type:"number"},()=>"Number").with({type:"boolean"},()=>"Checkbox").with({type:"date"},()=>"Date").with({type:"date_range"},()=>"Time range").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})=>zS[O]).with({type:"relation"},()=>"Relation").exhaustive(()=>"Column")}function Xx($){return $.map((O)=>({id:l$(),label:O}))}function e1($,O,j){return $?.kind===O&&"change"in $&&$.change.kind===j}function Kx($){return k($).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 r$($,O,j){let[x]=$;if($.length!==1||!e1(x,O,j))throw new f(`expected one ${O}.${j} result, got ${$.map(Kx).join(", ")||"none"}`);return x}class W$ extends P{access=new o(this.client,"database",this);async fetch(){return Y(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 W$($,O)}static async create($,O){let j=Y(await $.storage.createDatabase({body:{name:O.name}}));return new W$($,j.id)}static async list($){return Y(await $.storage.listDatabases()).map((j)=>new W$($,j.database.id))}query($,O){return _j(this.client,W$.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)=>V$.byId(this,O.table.id)));async table($){let{tables:O}=await this.schema(),j=O.find((x)=>x.table.name===$);return j?V$.byId(this,j.table.id):void 0}async createTable($){let{table:O}=r$(await this.applyOps([{kind:"table",table:l$(),change:{kind:"create",name:$.name}}]),"table","created");return V$.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 Gx(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(Kx).join(", ")||"none"}`);return j.tables.map(({table:x})=>V$.byId(this,x))}async deleteTable($){this.assertOwns(`table ${$.id}`,$.database),r$(await this.applyOps([{kind:"table",table:$.id,change:{kind:"delete"}}]),"table","deleted")}async columnCasts($){return this.assertOwns(`column ${$.id}`,$.table.database),Y(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}=Y(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}=Y(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 V$.byId(this,O.id)}webhookOf($){return Mj.fromRecord(V$.byId(this,$.tableId),A.byId(this.client,$.createdBy),$)}async webhooks(){let{webhooks:$}=Y(await this.client.storage.listDatabaseWebhooks({path:{id:this.id}}));return $.map((O)=>this.webhookOf(O))}async createWebhook($){this.assertOwns("table",$.database);let O=Y(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),Y(await this.client.storage.deleteDatabaseWebhook({path:{id:this.id,webhook_id:$.id}}))}async sharePermissions(){return Y(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 r$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"change_type",to:Aj(O.to)}}],{baseVersions:[{table:$.table,version:j}]}),"column","type_changed")}async columnConversion($,O){return this.assertOwns(`column ${$.id}`,$.table.database),Y(await this.client.storage.convertDatabaseColumn({path:{id:this.id,table_id:$.table.id,column_id:$.id},body:{to:Aj(O)}}))}async convertColumnIntoNewColumn($,O){let j=await this.columnConversion($,O.to),x=O.name??`${await $.name()} (${IS(O.to)})`,S=l$(),K=[{kind:"column",table:$.table.id,column:S,change:{kind:"create",definition:{source:"new",name:x,type:Aj(O.to),options:Xx(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(!e1(Z,"column","created"))throw new f(`expected a column.created result, got ${Z?Kx(Z):"none"}`);return C$.byId($.table,Z.column)}async deleteColumn($){this.assertOwns(`column ${$.id}`,$.table.database);let O=await $.table.version(),{tableVersion:j}=r$(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}=r$(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}=r$(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}=r$(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:Aj(O.type),...O.options!==void 0?{options:Xx(O.options)}:{},...O.inferType!==void 0?{inferType:O.inferType}:{}},{column:x}=r$(await this.applyOps([{kind:"column",table:$.id,column:l$(),change:{kind:"create",definition:j,...O.after!==void 0?{after:O.after.id}:{}}}]),"column","created");return C$.byId($,x)}async addColumnOptions($,O){return this.assertOwns(`column ${$.id}`,$.table.database),r$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"add_options",options:Xx(O)}}]),"column","options_added")}}class Yx{client;constructor($){this.client=$}query($,O){return _j(this.client,W$.byId,$,O)}byId($){return W$.byId(this.client,$)}create($){return W$.create(this.client,$)}list(){return W$.list(this.client)}}class Pj{id;name;constructor($,O){this.id=$;this.name=O}static async list($){let{skills:O}=Y(await $.storage.getSystemSkillsHandler());return O.map((j)=>new Pj(j.id,j.name))}}class Qx{client;async byTeamSlug($){let O=Y(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=Y(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=Y(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,$)}async createCanvas($){let O=Y(await this.client.storage.createCanvasHandler({body:{documentName:$.name,projectId:$.project?.id}}));return q.byId(this.client,O.documentId)}createSnippet($){return q.createSnippet(this.client,$)}createSkill($){return q.createSkill(this.client,$)}systemSkills(){return Pj.list(this.client)}search($,O){return q.search(this.client,$,O)}recent($){return q.recent(this.client,$)}recentlyDeleted(){return q.recentlyDeleted(this.client)}}class BO extends P{async fetch(){let{attachment:$}=Y(await this.client.email.getAttachment({path:{id:this.id}}));return $}static byId($,O){return new BO($,O)}static from($,O){return new BO($,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:$}=Y(await this.client.email.getAttachmentDocumentId({path:{id:this.id}}));return q.byId(this.client,$)}}class I$ extends X${access=new o(this.client,"email_thread",this);async followup(){return Y(await this.client.storage.getEmailFollowup({path:{thread_id:this.id}}))}async setFollowup($){return Y(await this.client.storage.setEmailFollowup({path:{thread_id:this.id},body:$}))}async calendarInvitations(){return Y(await this.client.email.getThreadCalendarInvitations({path:{thread_id:this.id}}))}async addEventToCalendar($,O,j={}){let x=Y(await this.client.email.copyThreadCalendarInvitation({path:{thread_id:this.id,message_id:$.id,invitation_id:O.id},body:{calendarId:j.calendar?.id}}));return $$.fromRecord(this.client,x)}async readReceipts(){let{receipts:$}=Y(await this.client.email.getThreadReadReceipts({path:{thread_id:this.id}}));return $.map((O)=>({message:z$.byId(this.client,O.message_id),openCount:O.open_count,firstOpenedAt:O.first_opened_at??void 0,lastOpenedAt:O.last_opened_at??void 0}))}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?s$($.sharePermission):void 0}}))}entityType="email_thread";propertyEntityType="THREAD";async fetch(){let{thread:$}=Y(await this.client.email.getThread({path:{thread_id:this.id},query:{limit:100}}));return $}static byId($,O){return new I$($,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",($)=>D$.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 Y(await this.client.email.getThreadMessagesHandler({path:{id:this.id},query:{...$?.since?{since:$.since}:{},...$?.limit?{limit:$.limit}:{}}})).map((j)=>z$.from(this.client,j))}async attachments(){let{messages:$}=await this.detail.get();return $.flatMap((O)=>O.attachments.map((j)=>BO.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?z$.byId(this.client,j.db_id):void 0}async archive($=!0){await this.mutate((O)=>O.email.archiveThread({path:{id:this.id},body:{value:$}}))}static async archiveMany($,O,j=!0){let x=[];for(let S=0;S<O.length;S+=100){let K=O.slice(S,S+100),Z=Y(await $.email.archiveThreads({body:{thread_ids:K.map((G)=>G.id),value:j}})),X=new Set(Z.failed_thread_ids);for(let G of K)if(G.detail.clear(),X.has(G.id))x.push(G)}return x}async updateState($){await this.mutate((O)=>O.email.updateThreadState({path:{id:this.id},body:$}))}async operations(){return Y(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=x$({filters:{email_filters:{}},type:"email",make:($,O)=>new I$($,O.thread_id)})}class z$ extends P{async fetch(){return Y(await this.client.email.getMessage({path:{id:this.id}}))}static byId($,O){return new z$($,O)}static from($,O){return new z$($,O.db_id,O)}static async send($,O){let{message:j}=Y(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?z$.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",($)=>D$.byId(this.client,$));async operationStatus(){return Y(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 I$.byId(this.client,(await this.detail.get()).thread_db_id)}async downloadEml(){return Y(await this.client.email.getMessageEml({path:{id:this.id},parseAs:"blob"}))}}class LO extends z${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 LO($,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:{...Jx($),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:oO.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 oO.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 oO{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 oO(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 Jx($){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),(Q)=>String.fromCharCode(Q)).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 NO extends P{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 NO($,O,void 0,j)}static from($,O,j){return new NO($,O.id,O,j)}async fetch(){let $=Y(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 xO extends P{async fetch(){let{labels:$}=Y(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 xO($,O)}static async list($){let{labels:O}=Y(await $.email.listLabels());return O.map((j)=>new xO($,j.id,j))}static async create($,O){let{label:j}=Y(await $.email.createLabel({body:{label_name:O}}));if(!j.id)throw new f("created label has no id");return new xO($,j.id)}async delete(){Y(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 Vx{client;async createDraft($,O){let j=Y(await this.client.email.createDraft({body:{draft:Jx($)},headers:O?{"X-Email-Link-Id":O.id}:void 0}));if(!j.draft.db_id)throw Error("Draft response has no message id");return LO.byId(this.client,j.draft.db_id)}draftById($){return LO.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=Y(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 LO.byId(this.client,K.db_id);if(S.messages.length<j)return}}async filters($){return Y(await this.client.email.listEmailFilters({headers:$?{"X-Email-Link-Id":$.id}:void 0})).filters.map((O)=>NO.from(this.client,O,$))}async upsertFilter($,O){return NO.from(this.client,Y(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 Y(await this.client.email.listContacts()).contacts}reminders($){let{inboxes:O,...j}=$??{};return c(async(x)=>{let S=Y(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:I$.byId(this.client,K)})),nextCursor:S.nextCursor}})}constructor($){this.client=$}byId($){return I$.byId(this.client,$)}message($){return z$.byId(this.client,$)}attachment($){return BO.byId(this.client,$)}link($){return D$.byId(this.client,$)}links(){return D$.list(this.client)}async connectionProviders(){return Y(await this.client.auth.emailConnectionProviders())}async recoverDraftTransfer($){return Y(await this.client.email.recoverDraftTransfer({path:{id:$}}))}send($){return z$.send(this.client,$)}search($,O){return I$.search(this.client,$,O)}inbox($){return c(async(O)=>{let j=Y(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)=>I$.byId(this.client,x.id)),nextCursor:j.next_cursor}})}label($){return xO.byId(this.client,$)}labels(){return xO.list(this.client)}createLabel($){return xO.create(this.client,$)}archive($,O=!0){return I$.archiveMany(this.client,$,O)}async deleteLabel($){Y(await this.client.email.deleteLabel({path:{id:$.id}}))}async blockSender($){Y(await this.client.email.blockSender({body:{email_address:$}}))}async unblockSender($){Y(await this.client.email.unblockSender({body:{email_address:$}}))}async blockedSenders(){return Y(await this.client.email.listBlockedSenders()).blocked_emails}}class TO{client;id;constructor($,O){this.client=$;this.id=O}static byId($,O){return new TO($,O)}async delete(){Y(await this.client.storage.deleteEntityMention({path:{mention_id:this.id}}))}toJSON(){return{id:this.id}}}class Wx{client;constructor($){this.client=$}byId($){return TO.byId(this.client,$)}async create($,O){let j=Y(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 TO.byId(this.client,j.id)}}function Bx($,O){return{chat:UO.byId($,O.id),name:O.name,announcements:O.announcements}}class UO extends P{static byId($,O){return new UO($,O)}static from($,O){return new UO($,O.jid,O)}async fetch(){let{chats:$}=Y(await this.client.storage.whatsappChats()),O=$.find((j)=>j.jid===this.id);if(!O)throw new E("WhatsApp chat is not available");return O}kind=this.field("kind");name=this.field("name");phoneNumber=this.field("phoneNumber");lastActivityAt=this.field("lastActivityAt");archived=this.field("archived");pinned=this.field("pinned");canAdd=this.field("canAdd");cannotAddReason=this.field("cannotAddReason");community=this.mappedField("community",($)=>$?Bx(this.client,$):void 0);added=this.mappedField("added",($)=>$?y$.byId(this.client,$.id):void 0);shared=this.mappedField("shared",($)=>$?y$.byId(this.client,$.id):void 0);async add(){let $=await this.kind(),O=await this.mutate((j)=>j.storage.externalChatAdd({body:{provider:"whatsapp",remoteId:this.id,kind:$}}));return y$.byId(this.client,O.chatId)}async refresh(){return this.detail.clear(),await this.detail.get(),this}}class M$ extends P{chat;constructor($,O,j,x){super($,j,x);this.chat=O}static byId($,O,j){return new M$($,O,j)}static from($,O,j){return new M$($,O,j.id,j)}async fetch(){return Y(await this.client.storage.externalChatMessage({path:{chat_id:this.chat.id,message_id:this.id}}))}body=this.field("body");sender=this.field("sender");sentAt=this.field("sentAt");editedAt=this.field("editedAt");deleted=this.field("deleted");reactions=this.field("reactions");deliveryState=this.field("deliveryState");kind=this.field("kind");forwarded=this.field("forwarded");viewOnce=this.field("viewOnce");mentions=this.field("mentions");rich=this.field("rich");replyTo=this.mappedField("replyTo",($)=>$?M$.byId(this.client,this.chat,$):void 0);attachments=this.mappedField("attachments",($)=>$.map((O)=>({ordinal:O.ordinal,state:O.state,fileName:O.fileName,mime:O.mime,size:O.size,width:O.width??void 0,height:O.height??void 0,durationSeconds:O.durationSeconds??void 0,presentation:O.presentation??void 0,url:O.fileId?`${this.client.hosts["static-files"]}/file/${O.fileId}`:void 0})))}class SO{chat;id;record;constructor($,O,j){this.chat=$;this.id=O;this.record=j}static byId($,O){return new SO($,O)}static from($,O){return new SO($,O.jid,O)}get displayName(){return this.record?.displayName??void 0}get mentionToken(){return this.id.split("@")[0]??this.id}get admin(){return this.record?.admin}toJSON(){return{id:this.id,chat:this.chat.id,displayName:this.displayName,admin:this.admin}}}class ZO{id;chat;filename;kind;constructor($,O,j,x){this.id=$;this.chat=O;this.filename=j;this.kind=x}static byId($,O){return new ZO(O,$)}static from($,O){return new ZO(O.uploadId,$,O.filename,O.kind)}toJSON(){return{id:this.id,chat:this.chat.id,filename:this.filename,kind:this.kind}}}class XO extends P{chat;constructor($,O,j,x){super($,j,x);this.chat=O}static byId($,O,j){return new XO($,O,j)}static from($,O,j){return new XO($,O,j.id,j)}async fetch(){let O=Y(await this.client.storage.externalChatDelivery({path:{chat_id:this.chat.id},body:[this.id]})).find((j)=>j.id===this.id);if(!O)throw new E("External chat send is not available");return O}state=this.field("state");errorCode=this.field("errorCode");createdAt=this.field("createdAt");message=this.mappedField("messageId",($)=>$?M$.byId(this.client,this.chat,$):void 0);async request(){let{payload:$}=await this.detail.get(),O=$.message,j=k(O).returnType().with({type:"media"},(x)=>({type:"media",upload:ZO.byId(this.chat,x.uploadId),caption:x.caption??void 0})).with({type:"mutation"},(x)=>({type:"mutation",message:M$.byId(this.client,this.chat,x.messageId),operation:x.operation,text:x.text??void 0})).with({type:"text"},(x)=>({type:"text",text:x.text,mentions:(x.mentions??[]).map((S)=>SO.byId(this.chat,S))})).exhaustive();return{idempotencyKey:$.idempotencyKey,message:j,replyTo:$.replyTo?M$.byId(this.client,this.chat,$.replyTo):void 0}}async refresh(){return this.detail.clear(),await this.detail.get(),this}}class y$ extends T${entityType="external_chat";static byId($,O){return new y$($,O)}async fetch(){return Y(await this.client.storage.externalChat({path:{chat_id:this.id}}))}provider=this.field("provider");name=this.field("name");kind=this.field("kind");canSend=this.field("canSend");sendReason=this.field("sendReason");sendingIdentity=this.field("sendingIdentity");unreadCount=this.field("unreadCount");backfill=this.field("backfill");limits=this.field("limits");members=this.field("members");participants=this.mappedField("members",($)=>($?.participants??[]).map((O)=>SO.from(this,O)));disappearingSeconds=this.field("disappearingSeconds");owner=this.mappedField("userId",($)=>A.byId(this.client,$));async community(){let{provider:$,community:O}=await this.detail.get();if(!O)return;return k($).with("whatsapp",()=>Bx(this.client,O)).exhaustive()}async*messages($={}){yield*c(async(O)=>{let j=Y(await this.client.storage.externalChatMessages({path:{chat_id:this.id},query:{before:O,limit:$.limit}}));return{items:j.messages.map((x)=>M$.from(this.client,this,x)),nextCursor:j.nextCursor}})}async markRead($){this.assertChat($.chat),await this.mutate((O)=>O.storage.externalChatRead({path:{chat_id:this.id},body:{messageId:$.id}}))}async permissions(){return Y(await this.client.storage.externalChatPermissions({path:{chat_id:this.id}}))}async updatePermissions($){await this.mutate((O)=>O.storage.externalChatUpdatePermissions({path:{chat_id:this.id},body:$}))}async remove(){await this.mutate(($)=>$.storage.externalChatRemove({path:{chat_id:this.id}}))}async upload($){let O=Y(await this.client.storage.externalChatUpload({path:{chat_id:this.id},body:{file:$}}));return ZO.from(this,O)}async send($,O){if(O.replyTo)this.assertChat(O.replyTo.chat);let j=k($).returnType().with({type:"text"},(S)=>{let K=S.mentions??[];for(let Z of K)this.assertChat(Z.chat);return{type:"text",text:S.text,mentions:K.map((Z)=>Z.id)}}).with({type:"media"},(S)=>{return this.assertChat(S.upload.chat),{type:"media",uploadId:S.upload.id,caption:S.caption}}).with({type:"mutation"},(S)=>{return this.assertChat(S.message.chat),{type:"mutation",messageId:S.message.id,operation:S.operation,text:S.text}}).exhaustive(),x=await this.mutate((S)=>S.storage.externalChatSend({path:{chat_id:this.id},body:{idempotencyKey:O.idempotencyKey,message:j,replyTo:O.replyTo?.id}}));return XO.from(this.client,this,x)}async sends(){return Y(await this.client.storage.externalChatSends({path:{chat_id:this.id}})).map(($)=>XO.from(this.client,this,$))}async delivery($){for(let O of $)this.assertChat(O.chat);return Y(await this.client.storage.externalChatDelivery({path:{chat_id:this.id},body:$.map((O)=>O.id)})).map((O)=>XO.from(this.client,this,O))}async messageAttachments($){for(let O of $)this.assertChat(O.chat);return Y(await this.client.storage.externalChatMessageAttachments({path:{chat_id:this.id},body:$.map((O)=>O.id)})).map((O)=>({message:M$.byId(this.client,this,O.messageId),attachments:O.attachments.map((j)=>({ordinal:j.ordinal,state:j.state,fileName:j.fileName,mime:j.mime,size:j.size,url:j.fileId?`${this.client.hosts["static-files"]}/file/${j.fileId}`:void 0}))}))}async refresh(){return this.detail.clear(),await this.detail.get(),this}assertChat($){if($.id!==this.id)throw Error("External chat reference belongs to another chat")}}class Lx{client;constructor($){this.client=$}async list(){return Y(await this.client.storage.externalChats()).map(($)=>y$.byId(this.client,$.id))}byId($){return y$.byId(this.client,$)}}class Nx{client;constructor($){this.client=$}async list($={}){let{favorites:O}=Y(await this.client.storage.listFavorites({query:{entityType:$.entityTypes,entityId:$.entityIds}}));return O}async add($){return Y(await this.client.storage.addFavorite({body:{entityId:$.id,entityType:$.entityType}}))}async remove($){Y(await this.client.storage.removeFavoriteByEntity({path:{entity_type:$.entityType,entity_id:$.id}}))}async reorder($){Y(await this.client.storage.reorderFavorites({body:{favorites:$}}))}}class KO extends T${entityType="foreign_entity";async fetch(){return Y(await this.client.storage.getForeignEntity({path:{id:this.id}}))}static byId($,O){return new KO($,O)}static fromRecord($,O){return new KO($,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 o1({login:$,...O}){return{...O,login:$??void 0}}class Ux{client;constructor($){this.client=$}byId($){return KO.byId(this.client,$)}async bySource($,O){return KO.fromRecord(this.client,Y(await this.client.storage.getForeignEntityBySource({path:{source:$,foreign_entity_id:O}})))}async githubPullRequestFacets(){let{repositories:$,authors:O,assignees:j,labels:x}=Y(await this.client.storage.getGithubPullRequestFacets());return{repositories:$,authors:O.map(o1),assignees:j.map(o1),labels:x.map(({color:S,...K})=>({...K,color:S??void 0}))}}}class p${form;id;constructor($,O){this.form=$;this.id=O}static byId($,O){return new p$($,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 C$.byId(await this.form.table(),(await this.detail()).column)}async options(){return(await this.detail()).options.map(($)=>zO.byId(this,$.id))}}class zO{question;id;constructor($,O){this.question=$;this.id=O}static byId($,O){return new zO($,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 RO{form;id;detail;constructor($,O,j){this.form=$;this.id=O;this.detail=new B$(()=>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 RO($,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 B$(()=>this.load(),$),this}}class a${form;id;constructor($,O){this.form=$;this.id=O}static byId($,O){return new a$($,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)=>p$.byId(this.form,O.id)):[]}}class Cj{entityType;id;constructor($,O){this.entityType=$;this.id=O}static byId($,O){return new Cj($,O)}}class v$ extends P{async fetch(){return Y(await this.client.storage.getForm({path:{id:this.id}}))}static byId($,O){return new v$($,O)}static async create($,O){let j=Y(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 v$($,j.form.id,j)}static async list($,O){if(!O)return Y(await $.storage.listAccessibleForms()).map(({form:S})=>new v$($,S.id));return Y(await $.storage.listForms({query:{databaseId:O.id}})).map((x)=>new v$($,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",($)=>W$.byId(this.client,$.databaseId));table=this.mappedField("form",($)=>V$.byId(W$.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(($)=>a$.byId(this,$.id))}async questions(){return(await this.detail.get()).sections.flatMap(($)=>$.kind==="questions"?$.questions.map((O)=>p$.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)=>k(X).with({kind:"group"},(G)=>({kind:"group",...x(G)})).with({kind:"condition"},(G)=>({kind:"condition",column:j(G.column),test:k(G.test).with({kind:"options"},(L)=>({...L,options:L.options.map((Q)=>Q.id)})).with({kind:"entities"},(L)=>({...L,entities:L.entities.map((Q)=>Q.id)})).with({kind:Z$.union("presence","text","number","date","dateRange","checkbox")},(L)=>L).exhaustive()})).exhaustive())}),S={sections:$.map((Z)=>{if(Z.section)this.assertOwns(Z.section);let X={id:Z.section?.id??l$(),title:Z.title,description:Z.description??""};return k(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??l$(),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=k(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","date_range","link","clear")},(S)=>S).exhaustive();return{question:O.id,value:x}})}unlockedBooking($){return $?{...$,section:a$.byId(this,$.section)}:void 0}async outcome($,O){return k($).with({outcome:"stopped"},(j)=>({...j,section:a$.byId(this,j.section)})).with({outcome:"submitted"},async(j)=>{let x=F$.byId(await this.table(),j.row),S=this.unlockedBooking(j.booking);return{outcome:"submitted",response:RO.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(Y(await this.client.storage.submitFormResponse({path:{id:this.id},body:O})),$)}async editResponse($){let O={answers:this.wireAnswers($)};return this.outcome(Y(await this.client.storage.editMyFormResponse({path:{id:this.id},body:O})),$)}async myResponse(){let $=Y(await this.client.storage.getMyFormResponse({path:{id:this.id}})),O=await this.table(),j=await Promise.all($.answers.map(async(K)=>{let Z=p$.byId(this,K.question),X=await k(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 zO.byId(Z,L.id)})})).with({type:"entities"},(G)=>({type:"entities",value:G.value.map((L)=>({entityType:L.entityType,entity:Cj.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 Q=V$.byId(W$.byId(this.client,L.kind.database),L.kind.table);return{type:"rows",value:G.value.map((J)=>F$.byId(Q,J))}}).with({type:Z$.union("text","number","boolean","date","date_range","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?F$.byId(O,$.response.row):void 0,S=this.unlockedBooking($.booking);return{...S?{booking:S}:{},response:RO.byId(this,$.response.id,{status:$.response.status,row:x,answers:j,booking:S}),status:$.response.status,stoppedAtSection:$.response.stoppedAtSection?a$.byId(this,$.response.stoppedAtSection):void 0,row:x,submittedAt:$.response.submittedAt,updatedAt:$.response.updatedAt,answers:j}}async responseSummary(){let $=Y(await this.client.storage.getFormResponseSummary({path:{id:this.id}}));return{...$,stoppedBySection:$.stoppedBySection.map((O)=>({section:a$.byId(this,O.section),count:O.count}))}}async tally(){return Y(await this.client.storage.getFormTally({path:{id:this.id}})).questions.map((O)=>{let j=p$.byId(this,O.question);return{question:j,responses:O.responses,buckets:O.buckets.flatMap((x)=>k(x.value).with({kind:"option"},(S)=>[{count:x.count,value:{kind:"option",option:zO.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 Y(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 zx{client;constructor($){this.client=$}byId($){return v$.byId(this.client,$)}create($){return v$.create(this.client,$)}list($){return v$.list(this.client,$)}}class DO extends P{static byId($,O){return new DO($,O)}async fetch(){return Y(await this.client.storage.getGithubPullRequest({path:{id:this.id}}))}title=this.field("title");url=this.field("url");status=this.field("status");async changes(){let $=Y(await this.client.storage.getGithubPullRequestChanges({path:{id:this.id}}));return{changeset:$.changeset?new Ix(this.client,this,$.changeset):void 0,error:$.error??void 0}}}class Ix{client;pullRequest;record;constructor($,O,j){this.client=$;this.pullRequest=O;this.record=j}get id(){return this.record.id}async patch(){return Y(await this.client.storage.getGithubPullRequestChangesPatch({path:{id:this.pullRequest.id},query:{changeset:this.id}})).patch}toJSON(){return{pullRequestId:this.pullRequest.id,...this.record}}}class Hx{client;constructor($){this.client=$}byId($){return DO.byId(this.client,$)}forEntity($){return DO.byId(this.client,$.id)}}class _O extends P{static byId($,O){return new _O($,O)}async fetch(){return Y(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 L$.from(this.client,await this.mutate((j)=>j.storage.approveHarnessPairing({path:{code:this.id},body:O})))}}class $j{client;id;constructor($,O){this.client=$;this.id=O}static byId($,O){return new $j($,O)}async claim($){let O=Y(await this.client.storage.claimHarnessPairing({path:{pairing_id:this.id},body:{device_secret:$}}));return"harness"in O?{harness:L$.from(this.client,O.harness),token:O.token}:void 0}toJSON(){return{id:this.id}}}class Tx{client;constructor($){this.client=$}byId($){return L$.byId(this.client,$)}async list(){return Y(await this.client.storage.listHarnesses()).map(($)=>L$.from(this.client,$))}async me(){return L$.from(this.client,Y(await this.client.storage.getSelfHarness()))}async deleteSelf(){Y(await this.client.storage.deleteSelfHarness())}async agents(){return Y(await this.client.storage.listHarnessAgents()).map(($)=>R$.byId(this.client,$.bot_id))}async sessions(){return Y(await this.client.storage.listHarnessSessions()).map(($)=>l.byId(this.client,$.session_id))}pairing($){return _O.byId(this.client,$)}async createPairing($){let O=Y(await this.client.storage.createHarnessPairing({body:$}));return{pairing:_O.byId(this.client,O.code),device:$j.byId(this.client,O.pairing_id),deviceSecret:O.device_secret,expiresAt:O.expires_at,pollIntervalSeconds:O.poll_interval_seconds}}}class Fj{id;url;width;height;constructor($,O,j,x){this.id=$;this.url=O;this.width=j;this.height=x}static byId($,O,j){return new Fj(O,`${$.hosts["static-files"]}/file/${O}`,j?.width,j?.height)}toJSON(){return{id:this.id,url:this.url,width:this.width,height:this.height}}}class Ej extends Fj{width;height;mimeType;sizeBytes;note;constructor($,O,j,x,S,K,Z){super($,O,j,x);this.width=j;this.height=x;this.mimeType=S;this.sizeBytes=K;this.note=Z}toJSON(){return{...super.toJSON(),mimeType:this.mimeType,sizeBytes:this.sizeBytes,note:this.note}}}class Rx{client;constructor($){this.client=$}async generate($){let O=Y(await this.client.cognition.generateImage({body:{prompt:$.prompt,aspectRatio:$.aspectRatio??null,referenceImages:($.referenceImages??[]).map(HS)}}));return new Ej(O.staticFileId,O.url,O.width,O.height,O.mimeType,O.sizeBytes,O.note??void 0)}}function HS($){return $ instanceof q?{type:"document",id:$.id}:{type:"staticFile",id:$.id}}var TS="00000001-0000-0000-0000-000000000001",$2="00000001-0000-0000-0000-000000000002",RS="00000001-0000-0000-0000-000000000004",DS="00000001-0000-0000-0000-000000000014",_S="00000001-0000-0000-0002-000000000001",MS="00000001-0000-0000-0002-000000000004";function AS($){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 Q$ extends q{static byId($,O){return new Q$($,O)}static async create($,O){let{documentId:j}=Y(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,propertyValues:await PS($,O)}}));return new Q$($,j)}static async summaries($,O){if(O.length===0)return[];let{previews:j}=Y(await $.storage.getBatchPreviewHandler({body:{document_ids:O.map((S)=>S.id)}})),x=new Map(j.flatMap((S)=>S.type==="access"?[[S.document_id,S]]:[]));return O.flatMap((S)=>{let K=x.get(S.id);if(!K)return[];return[{task:S,name:K.document_name,owner:A.byId($,K.owner),updatedAt:K.updated_at??void 0,completed:K.sub_type?.type==="task"&&K.sub_type.is_completed}]})}static async findSimilar($,O){let{results:j}=Y(await $.storage.taskSimilaritySearchHandler({body:{taskName:O.title,markdown:O.body??null}}));return j.map((x)=>({task:new Q$($,x.taskId),name:x.taskName,similarity:x.vectorScore}))}static async forPullRequest($,O){let j=AS(O),{pullRequests:x}=Y(await $.storage.getGithubPullRequestTasks({body:{githubKeys:[j]}}));return(x[0]?.taskIds??[]).map((S)=>new Q$($,S))}async completed(){let{subType:$}=await this.detail.get();if($!=="task")return;let j=(await this.properties()).find((x)=>x.definition.id===$2)?.value;return j?.type==="SelectOption"&&j.value.includes(MS)}webUrl(){return`${this.client.webAppUrl}/app/task/${this.id}`}static search=x$({filters:{document_filters:{sub_types:["task"],task_filters:{}}},type:"document",make:($,O)=>new Q$($,O.document_id)})}async function PS($,O){if(!O.initiative&&!O.assignees&&!O.dueDate)return null;let j=O.assignees??[await A.me($)],x=[{propertyId:$2,value:{type:"select_option",option_id:_S}}];if(j.length>0)x.push({propertyId:TS,value:{type:"multi_entity_reference",references:j.map((S)=>({entity_id:S.id,entity_type:"USER"}))}});if(O.initiative)x.push({propertyId:DS,value:{type:"entity_reference",reference:{entity_id:O.initiative.id,entity_type:"INITIATIVE"}}});if(O.dueDate)x.push({propertyId:RS,value:{type:"date",value:O.dueDate.toISOString()}});return x}class i$ extends P{access=new o(this.client,"initiative",this);static byId($,O){return new i$($,O)}static from($,O){return new i$($,O.id,O)}async fetch(){return Y(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)=>Q$.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?s$($.sharePermission):void 0}}))}async delete(){await this.mutate(($)=>$.storage.deleteInitiative({path:{initiative_id:this.id}}))}}class Dx{client;constructor($){this.client=$}byId($){return i$.byId(this.client,$)}async list(){return Y(await this.client.storage.listInitiatives()).initiatives.map(($)=>i$.byId(this.client,$.id))}async summaries(){return Y(await this.client.storage.listInitiatives()).initiatives.map(($)=>({initiative:i$.byId(this.client,$.id),name:$.name,updatedAt:$.updatedAt}))}async create($){return i$.from(this.client,Y(await this.client.storage.createInitiative({body:{name:$.name,description:$.description,memberIds:$.members?.map((O)=>O.id),shareWithTeam:$.shareWithTeam,propertyValues:$.propertyValues}})))}}class _x{client;constructor($){this.client=$}byId($){return _$.byId(this.client,$)}async create($){return _$.from(this.client,Y(await this.client.storage.meetingCreate({body:$})))}async list(){return Y(await this.client.storage.meetingList()).meetings.map(($)=>_$.from(this.client,$))}async active(){return Y(await this.client.storage.meetingListActive()).meetings.map(($)=>_$.from(this.client,$))}async lookup($){return _$.from(this.client,Y(await this.client.storage.meetingLookup({path:{token:$}})))}}class IO extends P{async fetch(){return Y(await this.client.notification.getTypedNotificationById({path:{notification_id:this.id}}))}static byId($,O){return new IO($,O)}static from($,O){return new IO($,O.id,O)}static list($,O){return c(async(j)=>{let x=Y(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)=>IO.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 Mx{client;constructor($){this.client=$}byId($){return IO.byId(this.client,$)}list($){return IO.list(this.client,$)}async markSeen($){Y(await this.client.notification.bulkMarkNotificationsSeen({body:{notificationIds:$}}))}async markDone($){Y(await this.client.notification.bulkMarkNotificationsDone({body:{notificationIds:$}}))}async delete($){Y(await this.client.notification.bulkDeleteUserNotificationsV2({body:{notificationIds:$}}))}async preferences(){return Y(await this.client.notification.getNotificationTypePreferences())}async enableType($){Y(await this.client.notification.enableNotificationType({path:{notification_event_type:$}}))}async disableType($){Y(await this.client.notification.disableNotificationType({path:{notification_event_type:$}}))}}class Ax{client;constructor($){this.client=$}async list(){let{data:$}=Y(await this.client.storage.getPinsHandler({}));return $?.recent??[]}async add($,O){Y(await this.client.storage.addPinHandler({path:{pinned_item_id:$.id},body:{pinType:$.entityType,pinIndex:O.index}}))}async remove($){Y(await this.client.storage.removePinHandler({path:{pinned_item_id:$.id},body:{pinType:$.entityType}}))}async reorder($){Y(await this.client.storage.reorderPinsHandler({body:$}))}}class Px{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 MO{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 MO($,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=Y(await this.client.properties.updatePropertyOption({path:{definition_id:this.definitionId,option_id:this.id},body:$})),this}async delete(){Y(await this.client.properties.deletePropertyOption({path:{definition_id:this.definitionId,option_id:this.id}}))}}class GO{client;id;detail;constructor($,O,j){this.client=$;this.id=O;this.detail=new B$(()=>this.fetch(),j)}async fetch(){return Y(await this.client.properties.getPropertyDefinition({path:{definition_id:this.id}}))}static async create($,O){let j=Y(await $.properties.createPropertyDefinition({body:{display_name:O.displayName,scope:O.scope,data_type:O.dataType}}));return new GO($,j.id,j)}static byId($,O){return new GO($,O)}static fromRecord($,O){return new GO($,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 Y(await this.client.properties.deletePropertyDefinition({path:{definition_id:this.id}}))}async options(){return Y(await this.client.properties.getPropertyOptions({path:{definition_id:this.id}})).map((O)=>MO.from(this.client,this.id,O))}async addOption($){let O=Y(await this.client.properties.addPropertyOption({path:{definition_id:this.id},body:$}));return MO.from(this.client,this.id,O)}async updateOption($,O){let j=Y(await this.client.properties.updatePropertyOption({path:{definition_id:this.id,option_id:$.id},body:O}));return MO.from(this.client,this.id,j)}async deleteOption($){return Y(await this.client.properties.deletePropertyOption({path:{definition_id:this.id,option_id:$.id}}))}}class Cx{client;constructor($){this.client=$}async list($){return Y(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 GO.fromRecord(this.client,x)})}create($){return GO.create(this.client,$)}definition($){return GO.byId(this.client,$)}async bulkEntityProperties($){return Y(await this.client.properties.getBulkEntityProperties({body:$}))}async updateEntityPropertyOptions($,O){return Y(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 Y(await this.client.properties.addEntityPropertyOption({path:{...$.entity.propertyReference(),property_id:$.property.id,option_id:$.option.id}}))}async removeEntityPropertyOption($){return Y(await this.client.properties.removeEntityPropertyOption({path:{...$.entity.propertyReference(),property_id:$.property.id,option_id:$.option.id}}))}async tags(){return Y(await this.client.properties.listTags({}))}}function Fx($){return k($).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 CS($){return k($).with({type:"multiple"},(O)=>({type:"multiple",triggers:O.triggers.map(Fx)})).with({type:"cron"},Fx).with({type:"events"},Fx).exhaustive()}class h$ extends P{static byId($,O){return new h$($,O)}static from($,O){if(!O.id)throw Error("Routine response has no id");return new h$($,O.id,O)}async fetch(){return Y(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,$));sourceTemplate=this.mappedField("template_id",($)=>$?h$.byId(this.client,$):void 0);async template(){let $=await this.client.scheduledAction.getScheduledActionTemplate({path:{id:this.id}});if($.response?.status===404)return;return this.toTemplate(Y($))}async shareAsTemplate($){return this.toTemplate(Y(await this.client.scheduledAction.shareScheduledActionTemplate({path:{id:this.id},body:$})))}async activateTemplate($){return h$.from(this.client,Y(await this.client.scheduledAction.activateScheduledActionTemplate({path:{id:this.id},body:{...qj($),enabled:$.enabled??!0}})))}toTemplate($){return new O2(this,A.byId(this.client,$.author),$)}async stopSharingTemplate(){Y(await this.client.scheduledAction.unshareScheduledActionTemplate({path:{id:this.id}}))}async update($){await this.mutate((O)=>O.scheduledAction.updateScheduledAction({path:{id:this.id},body:qj($)}))}async setEnabled($){await this.mutate((O)=>O.scheduledAction.setScheduledActionEnabled({path:{id:this.id},body:{enabled:$}}))}async execute(){let $=Y(await this.client.scheduledAction.executeScheduledActionNow({path:{id:this.id}}));if($.resource)return k($.resource).with({type:"agent"},(O)=>l.byId(this.client,O.id)).with({type:"chat"},(O)=>K$.byId(this.client,O.id)).exhaustive();return $.chat_id?K$.byId(this.client,$.chat_id):void 0}async history(){return Y(await this.client.scheduledAction.listScheduledActionHistory({path:{id:this.id}})).map(($)=>new Ex(this,$))}async delete(){await this.mutate(($)=>$.scheduledAction.deleteScheduledAction({path:{id:this.id}}))}}class O2{routine;author;record;constructor($,O,j){this.routine=$;this.author=O;this.record=j}activate($){return this.routine.activateTemplate($)}toJSON(){return this.record}}class Ex{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 qj($){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:CS($.trigger),task:{...O}}}class qx{client;constructor($){this.client=$}byId($){return h$.byId(this.client,$)}async create($){return h$.from(this.client,Y(await this.client.scheduledAction.createScheduledAction({body:{...qj($),enabled:$.enabled??!0}})))}async list($){return Y(await this.client.scheduledAction.listScheduledActions({query:{include_events:$?.includeEvents}})).map((O)=>h$.from(this.client,O))}}class wx{client;constructor($){this.client=$}byId($){return Q$.byId(this.client,$)}create($){return Q$.create(this.client,$)}summaries($){return Q$.summaries(this.client,$)}findSimilar($){return Q$.findSimilar(this.client,$)}forPullRequest($){return Q$.forPullRequest(this.client,$)}search($,O){return Q$.search(this.client,$,O)}}class fx{client;constructor($){this.client=$}byId($){return S$.byId(this.client,$)}current(){return S$.current(this.client)}list(){return S$.list(this.client)}}class bx{client;constructor($){this.client=$}async get($){return Y(await this.client.unfurl.getUnfurl({query:{url:$}}))}async bulk($){return Y(await this.client.unfurl.getUnfurlBulk({body:{url_list:$}}))}}class kx{client;constructor($){this.client=$}byId($){return A.byId(this.client,$)}me(){return A.me(this.client)}async search($){let O=$.trim().toLocaleLowerCase();if(!O)throw Error("A person search needs a name or email.");let j=await this.client.contacts.getContacts();if(j.response?.status===404)return[];let{contacts:x}=Y(j),S=[...new Set(x)],K=[];for(let Z=0;Z<S.length;Z+=100){let X=S.slice(Z,Z+100),{names:G}=Y(await this.client.auth.getUserNamesWithEmail({body:{user_ids:X}})),L=new Map(G.map((Q)=>[Q.id,Q]));for(let Q of X){let J=L.get(Q)??{id:Q};if(`${[J.first_name,J.last_name].filter(Boolean).join(" ")} ${Q}`.toLocaleLowerCase().includes(O))K.push(A.fromName(this.client,J))}}return K}}class YO extends P{signingSecret;constructor($,O,j,x){super($,O,j);this.signingSecret=x}async fetch(){return Y(await this.client.storage.getWebhook({path:{webhook_id:this.id}}))}static async create($,O){let j=Y(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 YO($,j.id,j,j.signing_secret)}static byId($,O){return new YO($,O)}static fromRecord($,O){return new YO($,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 gx{client;constructor($){this.client=$}create($){return YO.create(this.client,$)}byId($){return YO.byId(this.client,$)}async list(){let{webhooks:$}=Y(await this.client.storage.listWebhooks());return $.map((O)=>YO.fromRecord(this.client,O))}}class AO extends P{static byId($,O){return new AO($,O)}static from($,O){return new AO($,O.id,O)}async fetch(){let{account:$}=Y(await this.client.storage.whatsappAccount());if($?.id!==this.id)throw new E("WhatsApp account is not available");return $}state=this.field("state");identity=this.field("identityJid");owner=this.mappedField("userId",($)=>A.byId(this.client,$));async refresh(){return this.detail.clear(),await this.detail.get(),this}}class yx{client;constructor($){this.client=$}async account(){let{account:$}=Y(await this.client.storage.whatsappAccount());return $?AO.from(this.client,$):void 0}async chats(){return Y(await this.client.storage.whatsappChats()).chats.map(($)=>UO.from(this.client,$))}}function vx($){if("properties"in $.data)return $.data.properties;if($.tag==="calendarEvent")return $.data.extra.properties;return[]}function j2($,O,j){let x=[];for(let S of vx(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:K$.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:I$.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 m$($,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:J$.byId($,O.data.callId),snapshot:O,tags:x,createdBy:O.data.createdBy};case"calendarEvent":return{type:"calendar_event",id:O.data.id,entity:$$.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:KO.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 x2="00000000-0000-0000-0000-000000000000",hx={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"]},wj=($)=>$.replace(/[A-Z]/g,(O)=>O.toLowerCase()),S2=($,O)=>$==null?O:{"&":[$,O]};function mx($,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==="!"){mx(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)=>{mx(Z,`${O}.${S}[${X}]`)})}class fj{client;tagSets;constructor($){this.client=$}sets(){return this.tagSets??=this.client.properties.listTags({}).then(Y),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(hx,S))))throw Error(`Invalid workspace includeTypes. Supported values: ${Object.keys(hx).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)mx($[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:x2}},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}=Y(await this.client.email.listLinks()),K=S.filter((X)=>wj(X.email_address)===wj(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=S2(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(hx))if(!x.includes(S))O[K]={l:{[Z]:x2}}}if($.tags?.length){let S=(await this.sets()).flatMap((G)=>{let L=G.definition;if(!L)return[];return G.options.flatMap((Q)=>Q.value.type==="string"?[{id:Q.id,definitionId:L.id,label:Q.value.value,scope:G.scope==="user"?"personal":"team"}]:[])}),K=new Map;for(let G of $.tags){let L=S.filter((Q)=>wj(Q.label)===wj(G.label.trim())&&(!G.scope||Q.scope===G.scope));if(!L.length)throw Error(`Unknown tag "${G.label}". Available tags: ${S.map((Q)=>`${Q.label} (${Q.scope})`).join(", ")}.`);if($.tagsMatch==="all"&&L.length>1)throw Error(`Tag "${G.label}" is ambiguous; specify personal or team scope.`);for(let Q of L)K.set(Q.id,Q)}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=S2(O.propf,X)}return O}}class ux{client;constructor($){this.client=$}async page($={}){let O=new fj(this.client);return this.fetch(O,await O.body($),$.cursor)}async*list($={}){let O=new fj(this.client),j=await O.body($);yield*c((x)=>this.fetch(O,j,x))}async fetch($,O,j){let x=Y(await this.client.storage.postItemsSoupAst({body:O,query:j?{cursor:j}:void 0})),K=x.items.some((Z)=>vx(Z).some((X)=>X.definition.data_type==="TAG"))?await $.tagMap():new Map;return{items:x.items.map((Z)=>j2(this.client,Z,K)),nextCursor:x.next_cursor,hasMore:x.next_cursor!=null}}}function Z2({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:G,url:L,...Q}){let J,I=G??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,H=Q.signal??new AbortController().signal;while(!0){if(H.aborted)break;B++;let C=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)C.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:C,signal:H},_=new Request(L,D);if($)_=await $(L,D);let N=await(Q.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let T=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{T.cancel()}catch{}};H.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await T.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
`);let y=U.split(`
`);U=y.pop()??"";for(let a of y){let i=a.split(`
@@ -29,7 +29,7 @@ async function cO($,O,j){if(!Number.isInteger(O)||O<1)throw RangeError(`concurre
`);U=y.pop()??"";for(let a of y){let i=a.split(`
`),F=[],v;for(let R of i)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))v=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let m=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(m))V=m}let M,h=!1;if(F.length){let R=F.join(`
-`);try{M=JSON.parse(R),h=!0}catch{M=R}}if(h){if(S)await S(M);if(x)M=await x(M)}if(j?.({data:M,event:v,id:J,retry:V}),F.length)yield M}}}finally{H.removeEventListener("abort",g),T.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var H5=($)=>{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","}},R5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},Z0=({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=H5(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)}`},X0=({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(([Q,J])=>{G=[...G,Q,$?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])=>wO({allowReserved:$,name:x==="deepObject"?`${j}[${G}]`:G,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var D5=/\{[^{}]+\}/g,_5=({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,Z0({explode:K,name:Z,style:X,value:G}));continue}if(typeof G==="object"){j=j.replace(S,X0({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},K6=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=_5({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 G6=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 Y6={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var Q6=({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=Z0({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=X0({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("&")}},J6=($)=>{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},M5=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function V6($){for(let O of $.security??[]){if(M5($,O.name))continue;let j=await G6(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 Y1=($)=>K6({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:Q6($.querySerializer),url:$.url}),Q1=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=G0($.headers,O.headers),j},A5=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},G0=(...$)=>{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 K0{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 W6=()=>({error:new K0,request:new K0,response:new K0}),P5=Q6({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),C5={"Content-Type":"application/json"},Xj=($={})=>({...Y6,headers:C5,parseAs:"auto",querySerializer:P5,...$});var J1=($={})=>{let O=Q1(Xj(),$),j=()=>({...O}),x=(Q)=>{return O=Q1(O,Q),j()},S=W6(),K=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:G0(O.headers,Q.headers),serializedBody:void 0};if(J.security)await V6(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 I=J,z=Y1(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(Q),H={redirect:"follow",...V,body:G1(V)};z=new Request(B,H);for(let N of S.request.fns)if(N)z=await N(z,V);let C=V.fetch;W=await C(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"?J6(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 T;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":T=await W[N]();break;case"json":{let U=await W.text();T=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(T);if(V.responseTransformer)T=await V.responseTransformer(T)}return V.responseStyle==="data"?T:{data:T,...D}}let _=await W.text(),w;try{w=JSON.parse(_)}catch{}throw w??_}catch(V){let B=V;for(let H of S.error.fns)if(H)B=await H(B,W,z,Q);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(Q)=>(J)=>Z({...J,method:Q}),G=(Q)=>async(J)=>{let{opts:I,url:z}=await K(J);return X6({...I,body:I.body,method:Q,onRequest:async(W,V)=>{let B=new Request(W,V);for(let H of S.request.fns)if(H)B=await H(B,I);return B},serializedBody:G1(I),url:z})};return{buildUrl:(Q)=>Y1({...O,...Q}),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 B6=J1(Xj());class L6{client;constructor($){this.client=$?.client??B6}}class N6{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 Y0 extends L6{static __registry=new N6;constructor($){super($);Y0.__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}",...$})}forwardCalendarEvent($){return($.client??this.client).post({url:"/email/calendar-events/{event_id}/forward",...$,headers:{"Content-Type":"application/json",...$.headers}})}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}",...$})}getMessageEml($){return($.client??this.client).get({url:"/email/messages/{id}/eml",...$})}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",...$})}archiveThreads($){return($.client??this.client).patch({url:"/email/threads/archived",...$,headers:{"Content-Type":"application/json",...$.headers}})}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",...$})}copyThreadCalendarInvitation($){return($.client??this.client).post({url:"/email/threads/{thread_id}/messages/{message_id}/calendar-invitations/{invitation_id}/copy",...$,headers:{"Content-Type":"application/json",...$.headers}})}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 U6({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:G,url:L,...Q}){let J,I=G??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,H=Q.signal??new AbortController().signal;while(!0){if(H.aborted)break;B++;let C=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)C.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:C,signal:H},_=new Request(L,D);if($)_=await $(L,D);let N=await(Q.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let T=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{T.cancel()}catch{}};H.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await T.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
+`);try{M=JSON.parse(R),h=!0}catch{M=R}}if(h){if(S)await S(M);if(x)M=await x(M)}if(j?.({data:M,event:v,id:J,retry:V}),F.length)yield M}}}finally{H.removeEventListener("abort",g),T.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var H5=($)=>{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","}},R5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},Z0=({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=H5(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)}`},X0=({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(([Q,J])=>{G=[...G,Q,$?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])=>wO({allowReserved:$,name:x==="deepObject"?`${j}[${G}]`:G,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var D5=/\{[^{}]+\}/g,_5=({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,Z0({explode:K,name:Z,style:X,value:G}));continue}if(typeof G==="object"){j=j.replace(S,X0({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},K6=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=_5({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 G6=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 Y6={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var Q6=({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=Z0({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=X0({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("&")}},J6=($)=>{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},M5=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function V6($){for(let O of $.security??[]){if(M5($,O.name))continue;let j=await G6(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 Y1=($)=>K6({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:Q6($.querySerializer),url:$.url}),Q1=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=G0($.headers,O.headers),j},A5=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},G0=(...$)=>{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 K0{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 W6=()=>({error:new K0,request:new K0,response:new K0}),P5=Q6({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),C5={"Content-Type":"application/json"},Xj=($={})=>({...Y6,headers:C5,parseAs:"auto",querySerializer:P5,...$});var J1=($={})=>{let O=Q1(Xj(),$),j=()=>({...O}),x=(Q)=>{return O=Q1(O,Q),j()},S=W6(),K=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:G0(O.headers,Q.headers),serializedBody:void 0};if(J.security)await V6(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 I=J,z=Y1(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(Q),H={redirect:"follow",...V,body:G1(V)};z=new Request(B,H);for(let N of S.request.fns)if(N)z=await N(z,V);let C=V.fetch;W=await C(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"?J6(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 T;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":T=await W[N]();break;case"json":{let U=await W.text();T=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(T);if(V.responseTransformer)T=await V.responseTransformer(T)}return V.responseStyle==="data"?T:{data:T,...D}}let _=await W.text(),w;try{w=JSON.parse(_)}catch{}throw w??_}catch(V){let B=V;for(let H of S.error.fns)if(H)B=await H(B,W,z,Q);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(Q)=>(J)=>Z({...J,method:Q}),G=(Q)=>async(J)=>{let{opts:I,url:z}=await K(J);return X6({...I,body:I.body,method:Q,onRequest:async(W,V)=>{let B=new Request(W,V);for(let H of S.request.fns)if(H)B=await H(B,I);return B},serializedBody:G1(I),url:z})};return{buildUrl:(Q)=>Y1({...O,...Q}),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 B6=J1(Xj());class L6{client;constructor($){this.client=$?.client??B6}}class N6{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 Y0 extends L6{static __registry=new N6;constructor($){super($);Y0.__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}",...$})}forwardCalendarEvent($){return($.client??this.client).post({url:"/email/calendar-events/{event_id}/forward",...$,headers:{"Content-Type":"application/json",...$.headers}})}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}",...$})}getMessageEml($){return($.client??this.client).get({url:"/email/messages/{id}/eml",...$})}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",...$})}archiveThreads($){return($.client??this.client).patch({url:"/email/threads/archived",...$,headers:{"Content-Type":"application/json",...$.headers}})}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",...$})}copyThreadCalendarInvitation($){return($.client??this.client).post({url:"/email/threads/{thread_id}/messages/{message_id}/calendar-invitations/{invitation_id}/copy",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateThreadProject($){return($.client??this.client).patch({url:"/email/threads/{thread_id}/project",...$,headers:{"Content-Type":"application/json",...$.headers}})}getThreadReadReceipts($){return($.client??this.client).get({url:"/email/threads/{thread_id}/read-receipts",...$})}healthHandler($){return($?.client??this.client).get({url:"/health",...$})}getReadReceiptPixel($){return($.client??this.client).get({url:"/opens/{token}",...$})}}function U6({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:G,url:L,...Q}){let J,I=G??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,H=Q.signal??new AbortController().signal;while(!0){if(H.aborted)break;B++;let C=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)C.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:C,signal:H},_=new Request(L,D);if($)_=await $(L,D);let N=await(Q.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let T=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{T.cancel()}catch{}};H.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await T.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
`);let y=U.split(`
`);U=y.pop()??"";for(let a of y){let i=a.split(`
@@ -59,4 +59,4 @@ async function cO($,O,j){if(!Number.isInteger(O)||O<1)throw RangeError(`concurre
`);U=y.pop()??"";for(let a of y){let i=a.split(`
`),F=[],v;for(let R of i)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))v=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let m=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(m))V=m}let M,h=!1;if(F.length){let R=F.join(`
-`);try{M=JSON.parse(R),h=!0}catch{M=R}}if(h){if(S)await S(M);if(x)M=await x(M)}if(j?.({data:M,event:v,id:J,retry:V}),F.length)yield M}}}finally{H.removeEventListener("abort",g),T.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var H4=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},T4=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},R4=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},k0=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((G)=>encodeURIComponent(G))).join(T4(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=H4(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return vO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},vO=({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)}`},g0=({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(([Q,J])=>{G=[...G,Q,$?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=R4(x),X=Object.entries(S).map(([G,L])=>vO({allowReserved:$,name:x==="deepObject"?`${j}[${G}]`:G,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var D4=/\{[^{}]+\}/g,_4=({path:$,url:O})=>{let j=O,x=O.match(D4);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,k0({explode:K,name:Z,style:X,value:G}));continue}if(typeof G==="object"){j=j.replace(S,g0({explode:K,name:Z,style:X,value:G,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${vO({name:Z,value:G})}`);continue}let L=encodeURIComponent(X==="label"?`.${G}`:G);j=j.replace(S,L)}return j},I7=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=_4({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function f1($){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 H7=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 T7={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var R7=({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=k0({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=g0({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(G)S.push(G)}else{let G=vO({allowReserved:X.allowReserved,name:K,value:Z});if(G)S.push(G)}}return S.join("&")}},D7=($)=>{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},M4=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function _7($){for(let O of $.security??[]){if(M4($,O.name))continue;let j=await H7(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 b1=($)=>I7({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:R7($.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=v0($.headers,O.headers),j},A4=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},v0=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?A4(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 y0{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 M7=()=>({error:new y0,request:new y0,response:new y0}),P4=R7({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),C4={"Content-Type":"application/json"},Wj=($={})=>({...T7,headers:C4,parseAs:"auto",querySerializer:P4,...$});var g1=($={})=>{let O=k1(Wj(),$),j=()=>({...O}),x=(Q)=>{return O=k1(O,Q),j()},S=M7(),K=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:v0(O.headers,Q.headers),serializedBody:void 0};if(J.security)await _7(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 I=J,z=b1(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(Q),H={redirect:"follow",...V,body:f1(V)};z=new Request(B,H);for(let N of S.request.fns)if(N)z=await N(z,V);let C=V.fetch;W=await C(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"?D7(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 T;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":T=await W[N]();break;case"json":{let U=await W.text();T=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(T);if(V.responseTransformer)T=await V.responseTransformer(T)}return V.responseStyle==="data"?T:{data:T,...D}}let _=await W.text(),w;try{w=JSON.parse(_)}catch{}throw w??_}catch(V){let B=V;for(let H of S.error.fns)if(H)B=await H(B,W,z,Q);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(Q)=>(J)=>Z({...J,method:Q}),G=(Q)=>async(J)=>{let{opts:I,url:z}=await K(J);return z7({...I,body:I.body,method:Q,onRequest:async(W,V)=>{let B=new Request(W,V);for(let H of S.request.fns)if(H)B=await H(B,I);return B},serializedBody:f1(I),url:z})};return{buildUrl:(Q)=>b1({...O,...Q}),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 A7=g1(Wj());class P7{client;constructor($){this.client=$?.client??A7}}class C7{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 h0 extends P7{static __registry=new C7;constructor($){super($);h0.__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 F7={dev:"https://dev.macro.com",prod:"https://macro.com",local:"http://localhost:3000"},y1={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 F4($,O){let j=O?.channel_id;return O&&j?{channel:b.byId($,j),thread:new m$($,j,O.thread_id)}:{channel:void 0,thread:void 0}}function E$($,O){return{session:l.byId($,O.session_id),owner:A.byId($,O.owner_id),...F4($,O.origin)}}function hO($,O,j){let x=O.origin?.channel_id;return x&&j?e.byId($,x,j):void 0}function mO($,O){return O?A.byId($,O):void 0}function E7($,O){return k(O).with({event_type:"agent_session.opened"},({metadata:j})=>({event_type:"agent_session.opened",metadata:j,...E$($,j.identity)})).with({event_type:"agent_session.turn_started"},({metadata:j})=>({event_type:"agent_session.turn_started",metadata:j,...E$($,j.identity),actor:mO($,j.actor),announcement:hO($,j.identity,j.announcement_message_id)})).with({event_type:"agent_session.turn_ended"},({metadata:j})=>({event_type:"agent_session.turn_ended",metadata:j,...E$($,j.identity),actor:mO($,j.actor),announcement:hO($,j.identity,j.announcement_message_id)})).with({event_type:"agent_session.command_rejected"},({metadata:j})=>({event_type:"agent_session.command_rejected",metadata:j,...E$($,j.identity),actor:mO($,j.actor),announcement:hO($,j.identity,j.announcement_message_id)})).with({event_type:"agent_session.settled"},({metadata:j})=>({event_type:"agent_session.settled",metadata:j,...E$($,j.identity),actor:mO($,j.last_turn?.actor),announcement:hO($,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,...E$($,j.identity),announcement:hO($,j.identity,j.announcement_message_id)})).with({event_type:"agent_session.input_received"},({metadata:j})=>({event_type:"agent_session.input_received",metadata:j,...E$($,j.identity)})).with({event_type:"agent_session.mentioned"},({metadata:j})=>({event_type:"agent_session.mentioned",metadata:j,...E$($,j.identity),mentionedBy:mO($,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,...E$($,j.identity),actor:mO($,j.turn_in_flight?.actor),announcement:hO($,j.identity,j.turn_in_flight?.announcement_message_id)})).with({event_type:"agent_session.renamed"},({metadata:j})=>({event_type:"agent_session.renamed",metadata:j,...E$($,j.identity)})).with({event_type:"agent_session.deleted"},({metadata:j})=>({event_type:"agent_session.deleted",metadata:j,...E$($,j.identity)})).exhaustive((j)=>{console.warn("macro sdk: unknown agent session event",j);return})}var q7="macro|";function A$($,O){return O.startsWith(q7)&&O.length>q7.length?A.byId($,O.toLowerCase()):void 0}function w7($,O){return k(O).with({event_type:"channel.created"},({metadata:j})=>({event_type:"channel.created",metadata:j,channel:b.byId($,j.channel_id),actor:A$($,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:A$($,j.actor)})).with({event_type:"channel.deleted"},({metadata:j})=>({event_type:"channel.deleted",metadata:j,channel:b.byId($,j.channel_id),actor:A$($,j.actor)})).with({event_type:"channel.picture_changed"},({metadata:j})=>({event_type:"channel.picture_changed",metadata:j,channel:b.byId($,j.channel_id),actor:A$($,j.actor)})).with({event_type:"channel.participant_added"},({metadata:j})=>({event_type:"channel.participant_added",metadata:j,channel:b.byId($,j.channel_id),addedBy:A$($,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 f7($,O){return k(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 uO($,O,j=[]){let x=O.parent;if(x.type==="call")return{type:"call",call:J$.byId($,x.id),message:d$.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 m$($,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 b7($,O){return k(O).with({event_type:"message.posted"},({metadata:j})=>({event_type:"message.posted",metadata:j,target:uO($,j,j.mentions),sender:A$($,j.sender)})).with({event_type:"message.mentioned"},({metadata:j})=>({event_type:"message.mentioned",metadata:j,target:uO($,j),sender:A$($,j.sender)})).with({event_type:"message.patched"},({metadata:j})=>({event_type:"message.patched",metadata:j,target:uO($,j),actor:A$($,j.actor)})).with({event_type:"message.deleted"},({metadata:j})=>({event_type:"message.deleted",metadata:j,target:uO($,j),actor:A$($,j.actor)})).with({event_type:"message.attachment_created"},({metadata:j})=>({event_type:"message.attachment_created",metadata:j,target:uO($,j),actor:A$($,j.actor)})).with({event_type:"message.attachment_removed"},({metadata:j})=>({event_type:"message.attachment_removed",metadata:j,target:uO($,j),actor:A$($,j.actor)})).exhaustive((j)=>{console.warn("macro sdk: unknown message event",j);return})}async function k7($){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 E4="webhook.validation.test";function q4($,O){return k(O).with({event_type:Z$.string.startsWith("document.")},(j)=>f7($,j)).with({event_type:Z$.string.startsWith("channel.")},(j)=>w7($,j)).with({event_type:Z$.string.startsWith("message.")},(j)=>b7($,j)).with({event_type:Z$.string.startsWith("agent_session.")},(j)=>E7($,j)).otherwise(()=>{return})}class v1{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 k7({secret:this.secret,timestamp:O.timestamp??"",rawBody:$,signature:O.signature??""}))throw new f("invalid webhook signature");if(O.event===E4)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=q4(this.client,j);if(!S)return;await Promise.all([...x].map((K)=>K(S)))}}function g7(){return}var w4=0,h1;function f4($){h1=$}function I$($,O,j){if(!j&&!h1)return $;let x=(S)=>{for(let K of[h1,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:++w4,service:O,operation:K};x({...L,status:"started"});try{let Q=await Reflect.apply(X,S,G),J=Q!==null&&typeof Q==="object"&&"error"in Q&&Q.error!=null;return x({...L,status:J?"failed":"completed"}),Q}catch(Q){throw x({...L,status:"failed"}),Q}}}})}var v7="x-macro-user-api-key",b4="mak_",m1="mbot_";function k4($){return k($).with(Z$.string.startsWith(m1),()=>{throw Error("bot token passed as a user credential. Use auth: { type: 'bot', token } or MACRO_BOT_TOKEN.")}).with(Z$.string.startsWith(b4),(O)=>[v7,O]).otherwise((O)=>["Authorization",`Bearer ${O}`])}async function y7($){return typeof $==="function"?await $():$}async function g4($,O,j){return k($).with({type:"bot"},async(x)=>{let S=await y7(x.token);if(!S.startsWith(m1))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(m1))throw Error("bot token passed as a user credential. Use auth: { type: 'bot', token } or MACRO_BOT_TOKEN.");return[[v7,x]]}).with({type:"user"},async({token:x})=>{return[k4(await y7(x))]}).exhaustive()}class u1{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"?g7():void 0,x={...y1[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??F7[O],this.authConfig=v4($),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=I$(new _0({client:this.makeClient(x["scheduled-action"])}),"scheduled-action",$.onRequest),this.unfurl=I$(new h0({client:this.makeClient(x.unfurl)}),"unfurl",$.onRequest),this.agentHarness=I$(new vj({client:this.makeClient(x["agent-harness"])}),"agent-harness",$.onRequest),this.auth=I$(new dj({client:this.makeClient(x.auth)}),"auth",$.onRequest),this.calendar=I$(new ij({client:this.makeClient(x.calendar)}),"calendar",$.onRequest),this.cognition=I$(new oj({client:this.makeClient(x.cognition)}),"cognition",$.onRequest),this.contacts=I$(new S0({client:this.makeClient(x.contacts)}),"contacts",$.onRequest),this.email=I$(new Y0({client:this.makeClient(x.email)}),"email",$.onRequest),this.notification=I$(new B0({client:this.makeClient(x.notification)}),"notification",$.onRequest),this.properties=I$(new I0({client:this.makeClient(x.properties)}),"properties",$.onRequest),this.search=I$(new F0({client:this.makeClient(x.search)}),"search",$.onRequest),this.storage=I$(new b0({client:this.makeClient(x.storage)}),"storage",$.onRequest);let K=typeof process<"u"?{}.MACRO_WEBHOOK_SECRET:void 0,Z=$.webhookSecret??K;this.events=new v1(this,Z)}hasActingUser(){return this.authConfig.type==="user"||this.requestedAs!==void 0}selfBot(){return this.selfBotRecord??=new rO(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=Vj({baseUrl:$});return O.interceptors.request.use(async(j)=>{let x=await g4(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 y1))throw Error(`invalid MACRO_ENV "${O}" — expected local, dev, or prod`);return O}function v4($){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 c1{id;constructor($){this.id=$}static byId($){return new c1($)}toJSON(){return{id:this.id}}}class h7{routines;unfurls;agents;initiatives;apiKeys;harnesses;meetings;githubPullRequests;entityMentions;agentSessions;ai;bots;calendar;calls;channels;externalChats;whatsapp;chats;crm;databases;documents;email;favorites;foreignEntities;forms;images;notifications;pins;projects;properties;tasks;teams;users;webhooks;workspace;events;webAppUrl;_client;opts;constructor($){this.opts=$;let O=new u1($);this._client=O,this.routines=new qx(O),this.unfurls=new bx(O),this.agents=new l0(O),this.initiatives=new Dx(O),this.apiKeys=new p0(O),this.harnesses=new Tx(O),this.meetings=new _x(O),this.githubPullRequests=new Hx(O),this.entityMentions=new Wx(O),this.agentSessions=new d0(O),this.ai=new r0(O),this.bots=new rO(O),this.calendar=new a0(O),this.calls=new i0(O),this.channels=new s0(O),this.externalChats=new Lx(O),this.whatsapp=new yx(O),this.chats=new t0(O),this.crm=new o0(O),this.databases=new Yx(O),this.documents=new Qx(O),this.email=new Vx(O),this.favorites=new Nx(O),this.foreignEntities=new Ux(O),this.forms=new zx(O),this.images=new Rx(O),this.notifications=new Mx(O),this.pins=new Ax(O),this.projects=new Px(O),this.properties=new Cx(O),this.tasks=new wx(O),this.teams=new fx(O),this.users=new kx(O),this.webhooks=new gx(O),this.workspace=new ux(O),this.events=O.events,this.webAppUrl=O.webAppUrl}myPrincipalId(){return this._client.myPrincipalId()}requestedAs($){return new h7({...this.opts,requestedAs:$.id})}}export{n$ as wrapXml,O$ as toBody,f4 as observeRequests,d7 as msg,c7 as here,UO as WhatsAppChat,AO as WhatsAppAccount,t$ as UserApiKey,lO as ToolApproval,Fj as StaticImage,U$ as SessionReview,Ex as RoutineExecution,h$ as Routine,c0 as ReviewItem,Ix as PullRequestChangeset,zj as PipelineTable,WO as PipelineRow,Ij as PipelineColumn,N$ as MessageThread,D$ as Meeting,Gx as MacroOpRefusedError,h7 as Macro,i$ as Initiative,_O as HarnessPairing,L$ as Harness,DO as GithubPullRequest,Ej as GeneratedImage,a$ as FormSection,RO as FormResponse,Cj as FormReference,p$ as FormQuestion,zO as FormOption,v$ as Form,ZO as ExternalChatUpload,XO as ExternalChatSend,SO as ExternalChatParticipant,M$ as ExternalChatMessage,y$ as ExternalChat,TO as EntityMention,o as EntityAccess,NO as EmailFilter,LO as EmailDraft,oO as DraftAttachment,aO as DocumentVersion,VO as DocumentAnchor,$j as DevicePairing,e$ as CrmPipeline,u0 as ConversationTurn,dO as CodeExecution,nO as ChatMessage,iO as ChatGeneration,c1 as ChannelPicture,JO as ChannelActivity,w$ as CalendarNote,Lj as AgentConversation,T$ as Agent,HO as AccessRequest};
+`);try{M=JSON.parse(R),h=!0}catch{M=R}}if(h){if(S)await S(M);if(x)M=await x(M)}if(j?.({data:M,event:v,id:J,retry:V}),F.length)yield M}}}finally{H.removeEventListener("abort",g),T.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var H4=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},T4=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},R4=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},k0=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((G)=>encodeURIComponent(G))).join(T4(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=H4(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return vO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},vO=({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)}`},g0=({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(([Q,J])=>{G=[...G,Q,$?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=R4(x),X=Object.entries(S).map(([G,L])=>vO({allowReserved:$,name:x==="deepObject"?`${j}[${G}]`:G,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var D4=/\{[^{}]+\}/g,_4=({path:$,url:O})=>{let j=O,x=O.match(D4);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,k0({explode:K,name:Z,style:X,value:G}));continue}if(typeof G==="object"){j=j.replace(S,g0({explode:K,name:Z,style:X,value:G,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${vO({name:Z,value:G})}`);continue}let L=encodeURIComponent(X==="label"?`.${G}`:G);j=j.replace(S,L)}return j},I7=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=_4({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function f1($){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 H7=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 T7={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var R7=({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=k0({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=g0({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(G)S.push(G)}else{let G=vO({allowReserved:X.allowReserved,name:K,value:Z});if(G)S.push(G)}}return S.join("&")}},D7=($)=>{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},M4=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function _7($){for(let O of $.security??[]){if(M4($,O.name))continue;let j=await H7(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 b1=($)=>I7({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:R7($.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=v0($.headers,O.headers),j},A4=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},v0=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?A4(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 y0{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 M7=()=>({error:new y0,request:new y0,response:new y0}),P4=R7({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),C4={"Content-Type":"application/json"},Wj=($={})=>({...T7,headers:C4,parseAs:"auto",querySerializer:P4,...$});var g1=($={})=>{let O=k1(Wj(),$),j=()=>({...O}),x=(Q)=>{return O=k1(O,Q),j()},S=M7(),K=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:v0(O.headers,Q.headers),serializedBody:void 0};if(J.security)await _7(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 I=J,z=b1(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(Q),H={redirect:"follow",...V,body:f1(V)};z=new Request(B,H);for(let N of S.request.fns)if(N)z=await N(z,V);let C=V.fetch;W=await C(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"?D7(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 T;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":T=await W[N]();break;case"json":{let U=await W.text();T=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(T);if(V.responseTransformer)T=await V.responseTransformer(T)}return V.responseStyle==="data"?T:{data:T,...D}}let _=await W.text(),w;try{w=JSON.parse(_)}catch{}throw w??_}catch(V){let B=V;for(let H of S.error.fns)if(H)B=await H(B,W,z,Q);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(Q)=>(J)=>Z({...J,method:Q}),G=(Q)=>async(J)=>{let{opts:I,url:z}=await K(J);return z7({...I,body:I.body,method:Q,onRequest:async(W,V)=>{let B=new Request(W,V);for(let H of S.request.fns)if(H)B=await H(B,I);return B},serializedBody:f1(I),url:z})};return{buildUrl:(Q)=>b1({...O,...Q}),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 A7=g1(Wj());class P7{client;constructor($){this.client=$?.client??A7}}class C7{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 h0 extends P7{static __registry=new C7;constructor($){super($);h0.__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 F7={dev:"https://dev.macro.com",prod:"https://macro.com",local:"http://localhost:3000"},y1={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 F4($,O){let j=O?.channel_id;return O&&j?{channel:b.byId($,j),thread:new m$($,j,O.thread_id)}:{channel:void 0,thread:void 0}}function E$($,O){return{session:l.byId($,O.session_id),owner:A.byId($,O.owner_id),...F4($,O.origin)}}function hO($,O,j){let x=O.origin?.channel_id;return x&&j?e.byId($,x,j):void 0}function mO($,O){return O?A.byId($,O):void 0}function E7($,O){return k(O).with({event_type:"agent_session.opened"},({metadata:j})=>({event_type:"agent_session.opened",metadata:j,...E$($,j.identity)})).with({event_type:"agent_session.turn_started"},({metadata:j})=>({event_type:"agent_session.turn_started",metadata:j,...E$($,j.identity),actor:mO($,j.actor),announcement:hO($,j.identity,j.announcement_message_id)})).with({event_type:"agent_session.turn_ended"},({metadata:j})=>({event_type:"agent_session.turn_ended",metadata:j,...E$($,j.identity),actor:mO($,j.actor),announcement:hO($,j.identity,j.announcement_message_id)})).with({event_type:"agent_session.command_rejected"},({metadata:j})=>({event_type:"agent_session.command_rejected",metadata:j,...E$($,j.identity),actor:mO($,j.actor),announcement:hO($,j.identity,j.announcement_message_id)})).with({event_type:"agent_session.settled"},({metadata:j})=>({event_type:"agent_session.settled",metadata:j,...E$($,j.identity),actor:mO($,j.last_turn?.actor),announcement:hO($,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,...E$($,j.identity),announcement:hO($,j.identity,j.announcement_message_id)})).with({event_type:"agent_session.input_received"},({metadata:j})=>({event_type:"agent_session.input_received",metadata:j,...E$($,j.identity)})).with({event_type:"agent_session.mentioned"},({metadata:j})=>({event_type:"agent_session.mentioned",metadata:j,...E$($,j.identity),mentionedBy:mO($,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,...E$($,j.identity),actor:mO($,j.turn_in_flight?.actor),announcement:hO($,j.identity,j.turn_in_flight?.announcement_message_id)})).with({event_type:"agent_session.renamed"},({metadata:j})=>({event_type:"agent_session.renamed",metadata:j,...E$($,j.identity)})).with({event_type:"agent_session.deleted"},({metadata:j})=>({event_type:"agent_session.deleted",metadata:j,...E$($,j.identity)})).exhaustive((j)=>{console.warn("macro sdk: unknown agent session event",j);return})}var q7="macro|";function A$($,O){return O.startsWith(q7)&&O.length>q7.length?A.byId($,O.toLowerCase()):void 0}function w7($,O){return k(O).with({event_type:"channel.created"},({metadata:j})=>({event_type:"channel.created",metadata:j,channel:b.byId($,j.channel_id),actor:A$($,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:A$($,j.actor)})).with({event_type:"channel.deleted"},({metadata:j})=>({event_type:"channel.deleted",metadata:j,channel:b.byId($,j.channel_id),actor:A$($,j.actor)})).with({event_type:"channel.picture_changed"},({metadata:j})=>({event_type:"channel.picture_changed",metadata:j,channel:b.byId($,j.channel_id),actor:A$($,j.actor)})).with({event_type:"channel.participant_added"},({metadata:j})=>({event_type:"channel.participant_added",metadata:j,channel:b.byId($,j.channel_id),addedBy:A$($,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 f7($,O){return k(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 uO($,O,j=[]){let x=O.parent;if(x.type==="call")return{type:"call",call:J$.byId($,x.id),message:d$.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 m$($,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 b7($,O){return k(O).with({event_type:"message.posted"},({metadata:j})=>({event_type:"message.posted",metadata:j,target:uO($,j,j.mentions),sender:A$($,j.sender)})).with({event_type:"message.mentioned"},({metadata:j})=>({event_type:"message.mentioned",metadata:j,target:uO($,j),sender:A$($,j.sender)})).with({event_type:"message.patched"},({metadata:j})=>({event_type:"message.patched",metadata:j,target:uO($,j),actor:A$($,j.actor)})).with({event_type:"message.deleted"},({metadata:j})=>({event_type:"message.deleted",metadata:j,target:uO($,j),actor:A$($,j.actor)})).with({event_type:"message.attachment_created"},({metadata:j})=>({event_type:"message.attachment_created",metadata:j,target:uO($,j),actor:A$($,j.actor)})).with({event_type:"message.attachment_removed"},({metadata:j})=>({event_type:"message.attachment_removed",metadata:j,target:uO($,j),actor:A$($,j.actor)})).exhaustive((j)=>{console.warn("macro sdk: unknown message event",j);return})}async function k7($){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 E4="webhook.validation.test";function q4($,O){return k(O).with({event_type:Z$.string.startsWith("document.")},(j)=>f7($,j)).with({event_type:Z$.string.startsWith("channel.")},(j)=>w7($,j)).with({event_type:Z$.string.startsWith("message.")},(j)=>b7($,j)).with({event_type:Z$.string.startsWith("agent_session.")},(j)=>E7($,j)).otherwise(()=>{return})}class v1{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 k7({secret:this.secret,timestamp:O.timestamp??"",rawBody:$,signature:O.signature??""}))throw new f("invalid webhook signature");if(O.event===E4)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=q4(this.client,j);if(!S)return;await Promise.all([...x].map((K)=>K(S)))}}function g7(){return}var w4=0,h1;function f4($){h1=$}function H$($,O,j){if(!j&&!h1)return $;let x=(S)=>{for(let K of[h1,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:++w4,service:O,operation:K};x({...L,status:"started"});try{let Q=await Reflect.apply(X,S,G),J=Q!==null&&typeof Q==="object"&&"error"in Q&&Q.error!=null;return x({...L,status:J?"failed":"completed"}),Q}catch(Q){throw x({...L,status:"failed"}),Q}}}})}var v7="x-macro-user-api-key",b4="mak_",m1="mbot_";function k4($){return k($).with(Z$.string.startsWith(m1),()=>{throw Error("bot token passed as a user credential. Use auth: { type: 'bot', token } or MACRO_BOT_TOKEN.")}).with(Z$.string.startsWith(b4),(O)=>[v7,O]).otherwise((O)=>["Authorization",`Bearer ${O}`])}async function y7($){return typeof $==="function"?await $():$}async function g4($,O,j){return k($).with({type:"bot"},async(x)=>{let S=await y7(x.token);if(!S.startsWith(m1))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(m1))throw Error("bot token passed as a user credential. Use auth: { type: 'bot', token } or MACRO_BOT_TOKEN.");return[[v7,x]]}).with({type:"user"},async({token:x})=>{return[k4(await y7(x))]}).exhaustive()}class u1{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"?g7():void 0,x={...y1[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??F7[O],this.authConfig=v4($),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=H$(new _0({client:this.makeClient(x["scheduled-action"])}),"scheduled-action",$.onRequest),this.unfurl=H$(new h0({client:this.makeClient(x.unfurl)}),"unfurl",$.onRequest),this.agentHarness=H$(new vj({client:this.makeClient(x["agent-harness"])}),"agent-harness",$.onRequest),this.auth=H$(new dj({client:this.makeClient(x.auth)}),"auth",$.onRequest),this.calendar=H$(new ij({client:this.makeClient(x.calendar)}),"calendar",$.onRequest),this.cognition=H$(new oj({client:this.makeClient(x.cognition)}),"cognition",$.onRequest),this.contacts=H$(new S0({client:this.makeClient(x.contacts)}),"contacts",$.onRequest),this.email=H$(new Y0({client:this.makeClient(x.email)}),"email",$.onRequest),this.notification=H$(new B0({client:this.makeClient(x.notification)}),"notification",$.onRequest),this.properties=H$(new I0({client:this.makeClient(x.properties)}),"properties",$.onRequest),this.search=H$(new F0({client:this.makeClient(x.search)}),"search",$.onRequest),this.storage=H$(new b0({client:this.makeClient(x.storage)}),"storage",$.onRequest);let K=typeof process<"u"?{}.MACRO_WEBHOOK_SECRET:void 0,Z=$.webhookSecret??K;this.events=new v1(this,Z)}hasActingUser(){return this.authConfig.type==="user"||this.requestedAs!==void 0}selfBot(){return this.selfBotRecord??=new rO(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=Vj({baseUrl:$});return O.interceptors.request.use(async(j)=>{let x=await g4(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 y1))throw Error(`invalid MACRO_ENV "${O}" — expected local, dev, or prod`);return O}function v4($){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 c1{id;constructor($){this.id=$}static byId($){return new c1($)}toJSON(){return{id:this.id}}}class h7{routines;unfurls;agents;initiatives;apiKeys;harnesses;meetings;githubPullRequests;entityMentions;agentSessions;ai;bots;calendar;calls;channels;externalChats;whatsapp;chats;crm;databases;documents;email;favorites;foreignEntities;forms;images;notifications;pins;projects;properties;tasks;teams;users;webhooks;workspace;events;webAppUrl;_client;opts;constructor($){this.opts=$;let O=new u1($);this._client=O,this.routines=new qx(O),this.unfurls=new bx(O),this.agents=new l0(O),this.initiatives=new Dx(O),this.apiKeys=new p0(O),this.harnesses=new Tx(O),this.meetings=new _x(O),this.githubPullRequests=new Hx(O),this.entityMentions=new Wx(O),this.agentSessions=new d0(O),this.ai=new r0(O),this.bots=new rO(O),this.calendar=new a0(O),this.calls=new i0(O),this.channels=new s0(O),this.externalChats=new Lx(O),this.whatsapp=new yx(O),this.chats=new t0(O),this.crm=new o0(O),this.databases=new Yx(O),this.documents=new Qx(O),this.email=new Vx(O),this.favorites=new Nx(O),this.foreignEntities=new Ux(O),this.forms=new zx(O),this.images=new Rx(O),this.notifications=new Mx(O),this.pins=new Ax(O),this.projects=new Px(O),this.properties=new Cx(O),this.tasks=new wx(O),this.teams=new fx(O),this.users=new kx(O),this.webhooks=new gx(O),this.workspace=new ux(O),this.events=O.events,this.webAppUrl=O.webAppUrl}myPrincipalId(){return this._client.myPrincipalId()}requestedAs($){return new h7({...this.opts,requestedAs:$.id})}}export{n$ as wrapXml,O$ as toBody,f4 as observeRequests,d7 as msg,c7 as here,UO as WhatsAppChat,AO as WhatsAppAccount,t$ as UserApiKey,lO as ToolApproval,Fj as StaticImage,U$ as SessionReview,Ex as RoutineExecution,h$ as Routine,c0 as ReviewItem,Ix as PullRequestChangeset,zj as PipelineTable,WO as PipelineRow,Ij as PipelineColumn,N$ as MessageThread,_$ as Meeting,Gx as MacroOpRefusedError,h7 as Macro,i$ as Initiative,_O as HarnessPairing,L$ as Harness,DO as GithubPullRequest,Ej as GeneratedImage,a$ as FormSection,RO as FormResponse,Cj as FormReference,p$ as FormQuestion,zO as FormOption,v$ as Form,ZO as ExternalChatUpload,XO as ExternalChatSend,SO as ExternalChatParticipant,M$ as ExternalChatMessage,y$ as ExternalChat,TO as EntityMention,o as EntityAccess,NO as EmailFilter,LO as EmailDraft,oO as DraftAttachment,aO as DocumentVersion,VO as DocumentAnchor,$j as DevicePairing,e$ as CrmPipeline,u0 as ConversationTurn,dO as CodeExecution,nO as ChatMessage,iO as ChatGeneration,c1 as ChannelPicture,JO as ChannelActivity,w$ as CalendarNote,Lj as AgentConversation,R$ as Agent,HO as AccessRequest};
diff --git a/crates/email/AGENTS.md b/crates/email/AGENTS.md
index faf23f8768..b0ccdd5e15 100644
--- a/crates/email/AGENTS.md
+++ b/crates/email/AGENTS.md
@@ -106,6 +106,11 @@ tools — hexagonal, heavily feature-gated.
- Outlook links have no system label rows. Move a thread in or out of the inbox
through `set_thread_inbox`, and read Outlook inbox, trash, and junk state from
`email_message_mailbox_facts`, never from labels.
+- Read receipts (`domain/read_receipts.rs`) own pixel policy for every send
+ path: strip existing Macro pixels, track only HTML bodies, never block
+ delivery on a tracking failure, and count opens only for sent messages.
+ Tokens are stored per message, so a retried send or Outlook draft revision
+ rebuilds the same URL; keep it that way or the draft fingerprints drift.
- Outlook organization commands only run in their link's current
`sync_generation`. Anything that bumps it must rebind unfinished commands as
`pending`, since claims skip `confirming` ones while those still block later
diff --git a/crates/email/Cargo.toml b/crates/email/Cargo.toml
index 7113494f8e..8ef6bf5197 100644
--- a/crates/email/Cargo.toml
+++ b/crates/email/Cargo.toml
@@ -93,6 +93,7 @@ non_empty = { path = "../non_empty", optional = true }
model-error-response = { path = "../model-error-response", optional = true }
models_pagination = { path = "../models_pagination" }
models_email = { path = "../models_email", optional = true }
+rand = { workspace = true }
recursion = { workspace = true }
reqwest = { workspace = true, optional = true }
rootcause = { workspace = true }
diff --git a/crates/email/src/domain.rs b/crates/email/src/domain.rs
index 3aae5dc704..3ad5810d36 100644
--- a/crates/email/src/domain.rs
+++ b/crates/email/src/domain.rs
@@ -20,6 +20,8 @@ pub mod invitation_resolution;
#[cfg(feature = "mailbox")]
pub mod mailbox;
pub mod models;
+#[cfg(feature = "ports")]
+pub mod read_receipts;
pub mod senders;
#[cfg(feature = "ports")]
diff --git a/crates/email/src/domain/read_receipts.rs b/crates/email/src/domain/read_receipts.rs
new file mode 100644
index 0000000000..f336950ea6
--- /dev/null
+++ b/crates/email/src/domain/read_receipts.rs
@@ -0,0 +1,336 @@
+//! Sender-opted-in open tracking: a per-message pixel added at provider delivery.
+//!
+//! Opens are approximate. Image proxies and privacy features fetch pixels on
+//! delivery, and clients that block images never fetch them.
+
+use chrono::{DateTime, Utc};
+use entity_access::domain::models::{EntityAccessReceipt, EntityType, ViewAccessLevel};
+use lol_html::{HtmlRewriter, Settings, element};
+use macro_user_id::user_id::MacroUserIdStr;
+use rand::RngCore;
+use rootcause::Report;
+use std::future::Future;
+use uuid::Uuid;
+
+#[cfg(test)]
+mod test;
+
+/// Path of the public pixel route, relative to the email service base URL.
+pub const PIXEL_PATH: &str = "/opens/";
+/// Repeat fetches inside this window count as one open; clients often load an image twice.
+const OPEN_DEBOUNCE_SECS: i64 = 5;
+/// Upper bound on receipts returned for one thread.
+pub const MAX_THREAD_RECEIPTS: i64 = 200;
+const TOKEN_BYTES: usize = 32;
+/// Base64url without padding of [`TOKEN_BYTES`].
+const TOKEN_LEN: usize = 43;
+
+/// Unguessable pixel token: URL-path-safe base64url without padding.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct ReadReceiptToken(String);
+
+impl ReadReceiptToken {
+ /// A fresh random token.
+ pub fn generate() -> Self {
+ use base64::Engine;
+ let mut bytes = [0_u8; TOKEN_BYTES];
+ rand::rng().fill_bytes(&mut bytes);
+ Self(base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(bytes))
+ }
+
+ /// Accept only the shape [`Self::generate`] produces.
+ pub fn parse(raw: &str) -> Option<Self> {
+ (raw.len() == TOKEN_LEN
+ && raw
+ .bytes()
+ .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_'))
+ .then(|| Self(raw.to_owned()))
+ }
+
+ /// The token as stored and embedded in the pixel URL.
+ pub fn as_str(&self) -> &str {
+ &self.0
+ }
+}
+
+/// Absolute URL every Macro pixel starts with, e.g. `https://gateway.macro.com/email/opens/`.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct PixelUrlPrefix(String);
+
+impl PixelUrlPrefix {
+ /// Build from the email service's public base URL.
+ pub fn new(email_service_base: &str) -> Self {
+ Self(format!(
+ "{}{PIXEL_PATH}",
+ email_service_base.trim_end_matches('/')
+ ))
+ }
+
+ /// The prefix as a string, for clients that hide Macro's own pixels.
+ pub fn as_str(&self) -> &str {
+ &self.0
+ }
+
+ fn url(&self, token: &ReadReceiptToken) -> String {
+ format!("{}{}", self.0, token.as_str())
+ }
+}
+
+/// Open state of one tracked, sent message.
+#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
+#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]
+pub struct MessageReadReceipt {
+ /// The tracked message.
+ pub message_id: Uuid,
+ /// Counted pixel fetches.
+ pub open_count: u32,
+ /// First counted fetch.
+ pub first_opened_at: Option<DateTime<Utc>>,
+ /// Latest counted fetch.
+ pub last_opened_at: Option<DateTime<Utc>>,
+}
+
+/// Failures of the thread read path.
+#[derive(Debug, thiserror::Error)]
+pub enum ReadReceiptError {
+ /// The receipt carries no user identity.
+ #[error("authentication required")]
+ Unauthorized,
+ /// Persistence failed.
+ #[error("internal error")]
+ Internal(Report),
+}
+
+impl From<Report> for ReadReceiptError {
+ fn from(report: Report) -> Self {
+ Self::Internal(report)
+ }
+}
+
+/// Persisted facts for open tracking.
+pub trait ReadReceiptRepository: Send + Sync + 'static {
+ /// Whether the inbox opted in; a missing settings row means no.
+ fn tracking_enabled(&self, link_id: Uuid) -> impl Future<Output = Result<bool, Report>> + Send;
+ /// Store `candidate` unless the message already has a token; return the stored token.
+ fn message_token(
+ &self,
+ message_id: Uuid,
+ candidate: &ReadReceiptToken,
+ ) -> impl Future<Output = Result<ReadReceiptToken, Report>> + Send;
+ /// Count an open at `at` for a sent message, unless its last counted open is
+ /// after `debounce_after`. Returns whether an open was counted.
+ fn record_open(
+ &self,
+ token: &ReadReceiptToken,
+ at: DateTime<Utc>,
+ debounce_after: DateTime<Utc>,
+ ) -> impl Future<Output = Result<bool, Report>> + Send;
+ /// The user's own and delegated inboxes.
+ fn accessible_inboxes(
+ &self,
+ user: &MacroUserIdStr<'_>,
+ ) -> impl Future<Output = Result<Vec<Uuid>, Report>> + Send;
+ /// Receipts of sent messages in the thread that belong to `link_ids`, newest first.
+ fn thread_receipts(
+ &self,
+ thread_id: Uuid,
+ link_ids: &[Uuid],
+ limit: i64,
+ ) -> impl Future<Output = Result<Vec<MessageReadReceipt>, Report>> + Send;
+}
+
+/// Open tracking policy shared by every delivery path and the read API.
+#[derive(Debug, Clone)]
+pub struct ReadReceiptService<R> {
+ repo: R,
+ prefix: PixelUrlPrefix,
+}
+
+impl<R: ReadReceiptRepository> ReadReceiptService<R> {
+ /// Construct with the repository adapter and the public pixel URL prefix.
+ pub fn new(repo: R, prefix: PixelUrlPrefix) -> Self {
+ Self { repo, prefix }
+ }
+
+ /// The HTML body to hand the provider. Macro pixels quoted from earlier
+ /// messages are always removed so a reply never reports opens of its
+ /// ancestors. When the inbox opted in, this message's pixel is appended.
+ /// Plain-text-only messages are not tracked, and tracking failures never
+ /// block delivery.
+ #[tracing::instrument(skip(self, html), fields(tracked = tracing::field::Empty))]
+ pub async fn tracked_html(
+ &self,
+ link_id: Uuid,
+ message_id: Uuid,
+ html: Option<&str>,
+ ) -> Option<String> {
+ let stripped = self.untracked_html(html)?;
+ let token = async {
+ if !self.repo.tracking_enabled(link_id).await? {
+ return Ok(None);
+ }
+ self.repo
+ .message_token(message_id, &ReadReceiptToken::generate())
+ .await
+ .map(Some)
+ }
+ .await
+ .inspect_err(|error: &Report| {
+ tracing::warn!(error = ?error, "read receipt unavailable; sending untracked");
+ })
+ .ok()
+ .flatten();
+ tracing::Span::current().record("tracked", token.is_some());
+ Some(match token {
+ Some(token) => append_pixel(&stripped, &self.prefix.url(&token)),
+ None => stripped,
+ })
+ }
+
+ /// The HTML body with any Macro pixel removed, for drafts that are not being sent.
+ pub fn untracked_html(&self, html: Option<&str>) -> Option<String> {
+ html.map(|html| strip_pixels(html, &self.prefix))
+ }
+
+ /// Count a pixel fetch. Malformed, unknown, and unsent tokens are ignored
+ /// so the public route reveals nothing about the token.
+ #[tracing::instrument(skip_all, fields(counted = tracing::field::Empty), err)]
+ pub async fn record_open(&self, raw_token: &str) -> Result<(), Report> {
+ let Some(token) = ReadReceiptToken::parse(raw_token) else {
+ return Ok(());
+ };
+ let now = Utc::now();
+ let counted = self
+ .repo
+ .record_open(
+ &token,
+ now,
+ now - chrono::Duration::seconds(OPEN_DEBOUNCE_SECS),
+ )
+ .await?;
+ tracing::Span::current().record("counted", counted);
+ Ok(())
+ }
+
+ /// Receipts for an authorized thread, limited to inboxes the viewer owns or
+ /// was delegated. People the thread was shared with never see when its
+ /// recipients opened it.
+ #[tracing::instrument(skip_all, err)]
+ pub async fn thread_receipts(
+ &self,
+ receipt: EntityAccessReceipt<ViewAccessLevel>,
+ ) -> Result<Vec<MessageReadReceipt>, ReadReceiptError> {
+ if receipt.entity().entity_type != EntityType::EmailThread {
+ return Err(ReadReceiptError::Unauthorized);
+ }
+ let viewer = receipt
+ .acting_user_id()
+ .ok_or(ReadReceiptError::Unauthorized)?;
+ let thread_id = Uuid::parse_str(&receipt.entity().entity_id)
+ .map_err(|error| rootcause::report!("invalid thread id: {error}"))?;
+ let inboxes = self.repo.accessible_inboxes(viewer).await?;
+ if inboxes.is_empty() {
+ return Ok(Vec::new());
+ }
+ Ok(self
+ .repo
+ .thread_receipts(thread_id, &inboxes, MAX_THREAD_RECEIPTS)
+ .await?)
+ }
+}
+
+fn pixel_tag(url: &str) -> String {
+ format!(
+ r#"<img src="{url}" width="1" height="1" alt="" style="display:block;width:1px;height:1px;border:0;margin:0;padding:0" />"#
+ )
+}
+
+/// Insert the pixel before the closing `</body>`, or append it to a fragment.
+pub(crate) fn append_pixel(html: &str, url: &str) -> String {
+ let pixel = pixel_tag(url);
+ match html.to_ascii_lowercase().rfind("</body>") {
+ Some(at) => format!("{}{pixel}{}", &html[..at], &html[at..]),
+ None => format!("{html}{pixel}"),
+ }
+}
+
+/// Remove every `<img>` whose source is a Macro pixel; any other content is untouched.
+pub(crate) fn strip_pixels(html: &str, prefix: &PixelUrlPrefix) -> String {
+ if !html.contains(prefix.as_str()) {
+ return html.to_owned();
+ }
+ let selector = format!(r#"img[src^="{}"]"#, prefix.as_str());
+ let mut output = Vec::with_capacity(html.len());
+ let mut rewriter = HtmlRewriter::new(
+ Settings {
+ element_content_handlers: vec![element!(selector.as_str(), |el| {
+ el.remove();
+ Ok(())
+ })],
+ ..Settings::default()
+ },
+ |chunk: &[u8]| output.extend_from_slice(chunk),
+ );
+ if rewriter.write(html.as_bytes()).is_err() || rewriter.end().is_err() {
+ return html.to_owned();
+ }
+ String::from_utf8(output).unwrap_or_else(|_| html.to_owned())
+}
+
+#[cfg(feature = "mailbox")]
+mod outlook {
+ use super::{ReadReceiptRepository, ReadReceiptService};
+ use crate::domain::mailbox::MailboxError;
+ use crate::domain::mailbox::drafts::models::{DraftFile, DraftLease, PreparedDraft};
+ use crate::domain::mailbox::drafts::ports::DraftMaterializer;
+
+ /// Adds the read receipt pixel to Outlook drafts that are scheduled to send.
+ /// A checkpoint freezes the prepared body per revision and the token is
+ /// stable per message, so draft revisions rebuild the same body.
+ pub struct ReadReceiptMaterializer<M, R> {
+ inner: M,
+ receipts: ReadReceiptService<R>,
+ }
+
+ impl<M, R> ReadReceiptMaterializer<M, R> {
+ /// Wrap the content materializer.
+ pub fn new(inner: M, receipts: ReadReceiptService<R>) -> Self {
+ Self { inner, receipts }
+ }
+ }
+
+ impl<M: DraftMaterializer, R: ReadReceiptRepository> DraftMaterializer
+ for ReadReceiptMaterializer<M, R>
+ {
+ async fn prepare_draft(&self, lease: &DraftLease) -> Result<PreparedDraft, MailboxError> {
+ let mut prepared = self.inner.prepare_draft(lease).await?;
+ if lease.delete_requested {
+ return Ok(prepared);
+ }
+ let message = &mut prepared.request.message;
+ message.body_html = if lease.input.send_time.is_some() {
+ self.receipts
+ .tracked_html(
+ lease.mailbox.link_id,
+ lease.message_id,
+ message.body_html.as_deref(),
+ )
+ .await
+ } else {
+ self.receipts.untracked_html(message.body_html.as_deref())
+ };
+ Ok(prepared)
+ }
+
+ async fn draft_file_bytes(
+ &self,
+ lease: &DraftLease,
+ file: &DraftFile,
+ ) -> Result<Vec<u8>, MailboxError> {
+ self.inner.draft_file_bytes(lease, file).await
+ }
+ }
+}
+
+#[cfg(feature = "mailbox")]
+pub use outlook::ReadReceiptMaterializer;
diff --git a/crates/email/src/domain/read_receipts/test.rs b/crates/email/src/domain/read_receipts/test.rs
new file mode 100644
index 0000000000..56c180c222
--- /dev/null
+++ b/crates/email/src/domain/read_receipts/test.rs
@@ -0,0 +1,388 @@
+use super::*;
+use std::sync::{Arc, Mutex};
+
+const BASE: &str = "https://gateway.macro.com/email/";
+const PREFIX: &str = "https://gateway.macro.com/email/opens/";
+
+#[derive(Default)]
+struct State {
+ enabled: bool,
+ fail: bool,
+ stored: Option<ReadReceiptToken>,
+ opens: Vec<(String, DateTime<Utc>, DateTime<Utc>)>,
+ inboxes: Vec<Uuid>,
+ thread_queries: Vec<(Uuid, Vec<Uuid>, i64)>,
+}
+
+#[derive(Clone, Default)]
+struct Fake(Arc<Mutex<State>>);
+
+impl Fake {
+ fn enabled() -> Self {
+ let fake = Self::default();
+ fake.0.lock().unwrap().enabled = true;
+ fake
+ }
+ fn service(&self) -> ReadReceiptService<Self> {
+ ReadReceiptService::new(self.clone(), PixelUrlPrefix::new(BASE))
+ }
+}
+
+impl ReadReceiptRepository for Fake {
+ async fn tracking_enabled(&self, _: Uuid) -> Result<bool, Report> {
+ let state = self.0.lock().unwrap();
+ if state.fail {
+ return Err(rootcause::report!("settings unavailable"));
+ }
+ Ok(state.enabled)
+ }
+ async fn message_token(
+ &self,
+ _: Uuid,
+ candidate: &ReadReceiptToken,
+ ) -> Result<ReadReceiptToken, Report> {
+ let mut state = self.0.lock().unwrap();
+ Ok(state
+ .stored
+ .get_or_insert_with(|| candidate.clone())
+ .clone())
+ }
+ async fn record_open(
+ &self,
+ token: &ReadReceiptToken,
+ at: DateTime<Utc>,
+ debounce_after: DateTime<Utc>,
+ ) -> Result<bool, Report> {
+ self.0
+ .lock()
+ .unwrap()
+ .opens
+ .push((token.as_str().to_owned(), at, debounce_after));
+ Ok(true)
+ }
+ async fn accessible_inboxes(&self, _: &MacroUserIdStr<'_>) -> Result<Vec<Uuid>, Report> {
+ Ok(self.0.lock().unwrap().inboxes.clone())
+ }
+ async fn thread_receipts(
+ &self,
+ thread_id: Uuid,
+ link_ids: &[Uuid],
+ limit: i64,
+ ) -> Result<Vec<MessageReadReceipt>, Report> {
+ self.0
+ .lock()
+ .unwrap()
+ .thread_queries
+ .push((thread_id, link_ids.to_vec(), limit));
+ Ok(Vec::new())
+ }
+}
+
+fn pixel_count(html: &str) -> usize {
+ html.matches(PREFIX).count()
+}
+
+#[test]
+fn generated_tokens_parse_and_differ() {
+ let token = ReadReceiptToken::generate();
+ assert_eq!(token.as_str().len(), TOKEN_LEN);
+ assert_eq!(ReadReceiptToken::parse(token.as_str()), Some(token.clone()));
+ assert_ne!(ReadReceiptToken::generate(), token);
+}
+
+#[test]
+fn malformed_tokens_are_rejected() {
+ let valid = ReadReceiptToken::generate();
+ assert!(ReadReceiptToken::parse("").is_none());
+ assert!(ReadReceiptToken::parse(&valid.as_str()[1..]).is_none());
+ assert!(ReadReceiptToken::parse(&format!("{}x", valid.as_str())).is_none());
+ assert!(ReadReceiptToken::parse(&format!("{}/", &valid.as_str()[1..])).is_none());
+}
+
+#[test]
+fn prefix_joins_base_without_double_slash() {
+ assert_eq!(PixelUrlPrefix::new(BASE).as_str(), PREFIX);
+ assert_eq!(
+ PixelUrlPrefix::new("http://localhost:8087").as_str(),
+ "http://localhost:8087/opens/"
+ );
+}
+
+#[test]
+fn pixel_goes_before_closing_body_or_at_end() {
+ let in_body = append_pixel("<html><BODY><p>Hi</p></BODY></html>", "https://p/x");
+ assert!(in_body.starts_with("<html><BODY><p>Hi</p><img src=\"https://p/x\""));
+ assert!(in_body.ends_with("</BODY></html>"));
+
+ let fragment = append_pixel("<p>Hi</p>", "https://p/x");
+ assert!(fragment.starts_with("<p>Hi</p><img src=\"https://p/x\""));
+}
+
+#[test]
+fn strip_removes_only_macro_pixels() {
+ let prefix = PixelUrlPrefix::new(BASE);
+ let html = format!(
+ r#"<p>Hi</p><img src="https://cdn.example.com/logo.png"><blockquote><img src="{PREFIX}old" width="1"></blockquote>"#
+ );
+ let stripped = strip_pixels(&html, &prefix);
+ assert_eq!(pixel_count(&stripped), 0);
+ assert!(stripped.contains("https://cdn.example.com/logo.png"));
+ assert!(stripped.contains("<blockquote></blockquote>"));
+
+ let untouched = "<p>No pixels</p>";
+ assert_eq!(strip_pixels(untouched, &prefix), untouched);
+}
+
+#[tokio::test]
+async fn disabled_inbox_sends_without_pixel() {
+ let fake = Fake::default();
+ let html = fake
+ .service()
+ .tracked_html(Uuid::now_v7(), Uuid::now_v7(), Some("<p>Hi</p>"))
+ .await
+ .unwrap();
+ assert_eq!(html, "<p>Hi</p>");
+ assert!(fake.0.lock().unwrap().stored.is_none());
+}
+
+#[tokio::test]
+async fn enabled_inbox_appends_its_stable_pixel() {
+ let fake = Fake::enabled();
+ let service = fake.service();
+ let (link, message) = (Uuid::now_v7(), Uuid::now_v7());
+ let first = service
+ .tracked_html(link, message, Some("<p>Hi</p>"))
+ .await
+ .unwrap();
+ let token = fake.0.lock().unwrap().stored.clone().unwrap();
+ assert_eq!(pixel_count(&first), 1);
+ assert!(first.contains(&format!("{PREFIX}{}", token.as_str())));
+
+ let retried = service
+ .tracked_html(link, message, Some(&first))
+ .await
+ .unwrap();
+ assert_eq!(retried, first);
+}
+
+#[tokio::test]
+async fn quoted_pixels_are_replaced_by_this_messages_pixel() {
+ let fake = Fake::enabled();
+ let quoted = format!(r#"<p>Reply</p><blockquote><img src="{PREFIX}ancestor"></blockquote>"#);
+ let html = fake
+ .service()
+ .tracked_html(Uuid::now_v7(), Uuid::now_v7(), Some(&quoted))
+ .await
+ .unwrap();
+ assert_eq!(pixel_count(&html), 1);
+ assert!(!html.contains("ancestor"));
+}
+
+#[tokio::test]
+async fn plain_text_messages_are_not_tracked() {
+ let fake = Fake::enabled();
+ let html = fake
+ .service()
+ .tracked_html(Uuid::now_v7(), Uuid::now_v7(), None)
+ .await;
+ assert!(html.is_none());
+ assert!(fake.0.lock().unwrap().stored.is_none());
+}
+
+#[tokio::test]
+async fn tracking_failure_still_delivers_untracked() {
+ let fake = Fake::enabled();
+ fake.0.lock().unwrap().fail = true;
+ let quoted = format!(r#"<p>Hi</p><img src="{PREFIX}ancestor">"#);
+ let html = fake
+ .service()
+ .tracked_html(Uuid::now_v7(), Uuid::now_v7(), Some(&quoted))
+ .await
+ .unwrap();
+ assert_eq!(html, "<p>Hi</p>");
+}
+
+#[tokio::test]
+async fn malformed_tokens_never_reach_storage() {
+ let fake = Fake::default();
+ fake.service().record_open("not-a-token").await.unwrap();
+ assert!(fake.0.lock().unwrap().opens.is_empty());
+}
+
+#[tokio::test]
+async fn opens_are_debounced_from_now() {
+ let fake = Fake::default();
+ let token = ReadReceiptToken::generate();
+ fake.service().record_open(token.as_str()).await.unwrap();
+ let opens = &fake.0.lock().unwrap().opens;
+ let (stored, at, debounce_after) = &opens[0];
+ assert_eq!(stored, token.as_str());
+ assert_eq!(*at - *debounce_after, chrono::Duration::seconds(5));
+}
+
+fn thread_receipt(entity_type: EntityType) -> EntityAccessReceipt<ViewAccessLevel> {
+ EntityAccessReceipt::dangerously_assert_authenticated_user(
+ MacroUserIdStr::try_from_email("[email protected]").unwrap(),
+ "0198f0aa-0000-7000-8000-000000000001",
+ entity_type,
+ )
+}
+
+#[tokio::test]
+async fn thread_receipts_are_scoped_to_the_viewers_inboxes() {
+ let fake = Fake::default();
+ let inbox = Uuid::now_v7();
+ fake.0.lock().unwrap().inboxes = vec![inbox];
+ fake.service()
+ .thread_receipts(thread_receipt(EntityType::EmailThread))
+ .await
+ .unwrap();
+ let queries = &fake.0.lock().unwrap().thread_queries;
+ assert_eq!(
+ queries.as_slice(),
+ [(
+ Uuid::parse_str("0198f0aa-0000-7000-8000-000000000001").unwrap(),
+ vec![inbox],
+ MAX_THREAD_RECEIPTS
+ )]
+ );
+}
+
+#[tokio::test]
+async fn viewers_without_inbox_access_see_no_receipts() {
+ let fake = Fake::default();
+ let receipts = fake
+ .service()
+ .thread_receipts(thread_receipt(EntityType::EmailThread))
+ .await
+ .unwrap();
+ assert!(receipts.is_empty());
+ assert!(fake.0.lock().unwrap().thread_queries.is_empty());
+}
+
+#[tokio::test]
+async fn non_user_and_non_thread_receipts_are_rejected() {
+ let fake = Fake::default();
+ let internal = EntityAccessReceipt::<ViewAccessLevel>::dangerously_assert_internal_user(
+ "0198f0aa-0000-7000-8000-000000000001",
+ EntityType::EmailThread,
+ );
+ assert!(matches!(
+ fake.service().thread_receipts(internal).await,
+ Err(ReadReceiptError::Unauthorized)
+ ));
+ assert!(matches!(
+ fake.service()
+ .thread_receipts(thread_receipt(EntityType::Document))
+ .await,
+ Err(ReadReceiptError::Unauthorized)
+ ));
+}
+
+#[cfg(feature = "mailbox")]
+mod outlook {
+ use super::*;
+ use crate::domain::mailbox::{
+ MailboxError, MailboxKey,
+ drafts::{
+ models::{DraftFile, DraftLease, PreparedDraft},
+ ports::DraftMaterializer,
+ },
+ };
+ use email_api_client::domain::models::SendRequest;
+
+ struct Content;
+
+ impl DraftMaterializer for Content {
+ async fn prepare_draft(&self, lease: &DraftLease) -> Result<PreparedDraft, MailboxError> {
+ Ok(PreparedDraft {
+ reply_to: None,
+ request: SendRequest {
+ message_id: None,
+ message: serde_json::from_value(serde_json::json!({
+ "db_id": lease.message_id,
+ "link_id": lease.mailbox.link_id,
+ "subject": "Hello",
+ "body_html": format!(r#"<p>Hi</p><img src="{PREFIX}ancestor">"#),
+ }))
+ .unwrap(),
+ from: models_email::service::address::ContactInfo {
+ email: "[email protected]".into(),
+ name: None,
+ photo_url: None,
+ },
+ parent_message_id: None,
+ references: None,
+ },
+ files: Vec::new(),
+ removals: Vec::new(),
+ })
+ }
+ async fn draft_file_bytes(
+ &self,
+ _: &DraftLease,
+ _: &DraftFile,
+ ) -> Result<Vec<u8>, MailboxError> {
+ Ok(Vec::new())
+ }
+ }
+
+ fn lease(send_time: Option<DateTime<Utc>>, delete_requested: bool) -> DraftLease {
+ let message = Uuid::now_v7();
+ DraftLease {
+ message_id: message,
+ lease_id: Uuid::now_v7(),
+ mailbox: MailboxKey {
+ link_id: Uuid::now_v7(),
+ sync_generation: 1,
+ grant_generation: 1,
+ },
+ revision: 1,
+ actor_id: "macro|[email protected]".into(),
+ input: serde_json::from_value(serde_json::json!({
+ "db_id": message,
+ "thread_db_id": Uuid::now_v7(),
+ "subject": "Hello",
+ "to": [], "cc": [], "bcc": [],
+ "actor_id": "macro|[email protected]",
+ "send_time": send_time,
+ }))
+ .unwrap(),
+ attachments: Default::default(),
+ provider_id: None,
+ base_version: None,
+ delete_requested,
+ checkpoint: None,
+ }
+ }
+
+ async fn body(lease: &DraftLease) -> String {
+ ReadReceiptMaterializer::new(Content, Fake::enabled().service())
+ .prepare_draft(lease)
+ .await
+ .unwrap()
+ .request
+ .message
+ .body_html
+ .unwrap()
+ }
+
+ #[tokio::test]
+ async fn scheduled_drafts_carry_only_their_own_pixel() {
+ let html = body(&lease(Some(Utc::now()), false)).await;
+ assert_eq!(pixel_count(&html), 1);
+ assert!(!html.contains("ancestor"));
+ }
+
+ #[tokio::test]
+ async fn unsent_drafts_carry_no_pixel() {
+ let html = body(&lease(None, false)).await;
+ assert_eq!(html, "<p>Hi</p>");
+ }
+
+ #[tokio::test]
+ async fn deletions_leave_content_untouched() {
+ let html = body(&lease(Some(Utc::now()), true)).await;
+ assert!(html.contains("ancestor"));
+ }
+}
diff --git a/crates/email/src/outbound.rs b/crates/email/src/outbound.rs
index 77692e342a..2bb491f00c 100644
--- a/crates/email/src/outbound.rs
+++ b/crates/email/src/outbound.rs
@@ -10,6 +10,8 @@ mod gmail_sender_provider;
mod gmail_token_provider;
#[cfg(feature = "outbound")]
pub mod invitation_pg;
+#[cfg(feature = "outbound")]
+pub mod read_receipts_pg;
#[cfg(feature = "s3")]
mod s3_draft_attachment_storage;
diff --git a/crates/email/src/outbound/read_receipts_pg.rs b/crates/email/src/outbound/read_receipts_pg.rs
new file mode 100644
index 0000000000..5303bd5232
--- /dev/null
+++ b/crates/email/src/outbound/read_receipts_pg.rs
@@ -0,0 +1,119 @@
+//! Postgres persistence for message open tracking.
+use crate::domain::read_receipts::{MessageReadReceipt, ReadReceiptRepository, ReadReceiptToken};
+use chrono::{DateTime, Utc};
+use macro_user_id::user_id::MacroUserIdStr;
+use rootcause::{Report, prelude::IntoRootcause};
+use sqlx::PgPool;
+use uuid::Uuid;
+
+#[cfg(test)]
+mod test;
+
+/// Read receipt adapter over `email_message_read_receipts` and `email_settings`.
+#[derive(Debug, Clone)]
+pub struct ReadReceiptPgRepository(pub PgPool);
+
+impl ReadReceiptRepository for ReadReceiptPgRepository {
+ #[tracing::instrument(skip(self), err)]
+ async fn tracking_enabled(&self, link_id: Uuid) -> Result<bool, Report> {
+ Ok(sqlx::query_scalar!(
+ "SELECT read_receipts_enabled FROM email_settings WHERE link_id = $1",
+ link_id
+ )
+ .fetch_optional(&self.0)
+ .await?
+ .unwrap_or(false))
+ }
+
+ #[tracing::instrument(skip(self, candidate), err)]
+ async fn message_token(
+ &self,
+ message_id: Uuid,
+ candidate: &ReadReceiptToken,
+ ) -> Result<ReadReceiptToken, Report> {
+ // The no-op update returns the existing token, including under a concurrent insert.
+ let stored = sqlx::query_scalar!(
+ r#"INSERT INTO email_message_read_receipts (message_id, token)
+ VALUES ($1, $2)
+ ON CONFLICT (message_id) DO UPDATE SET token = email_message_read_receipts.token
+ RETURNING token"#,
+ message_id,
+ candidate.as_str(),
+ )
+ .fetch_one(&self.0)
+ .await?;
+ ReadReceiptToken::parse(&stored)
+ .ok_or_else(|| rootcause::report!("stored read receipt token is malformed"))
+ }
+
+ #[tracing::instrument(skip(self, token), err)]
+ async fn record_open(
+ &self,
+ token: &ReadReceiptToken,
+ at: DateTime<Utc>,
+ debounce_after: DateTime<Utc>,
+ ) -> Result<bool, Report> {
+ let counted = sqlx::query!(
+ r#"UPDATE email_message_read_receipts r
+ SET open_count = r.open_count + 1,
+ first_opened_at = COALESCE(r.first_opened_at, $2),
+ last_opened_at = $2
+ FROM email_messages m
+ WHERE r.token = $1
+ AND m.id = r.message_id
+ AND m.is_sent
+ AND (r.last_opened_at IS NULL OR r.last_opened_at <= $3)"#,
+ token.as_str(),
+ at,
+ debounce_after,
+ )
+ .execute(&self.0)
+ .await?
+ .rows_affected();
+ Ok(counted > 0)
+ }
+
+ #[tracing::instrument(skip(self, user), err)]
+ async fn accessible_inboxes(&self, user: &MacroUserIdStr<'_>) -> Result<Vec<Uuid>, Report> {
+ Ok(
+ email_db_client::links::get::fetch_inboxes_for_macro_id(&self.0, user.as_ref())
+ .await
+ .into_rootcause()?
+ .into_iter()
+ .map(|link| link.id)
+ .collect(),
+ )
+ }
+
+ #[tracing::instrument(skip(self, link_ids), err)]
+ async fn thread_receipts(
+ &self,
+ thread_id: Uuid,
+ link_ids: &[Uuid],
+ limit: i64,
+ ) -> Result<Vec<MessageReadReceipt>, Report> {
+ let rows = sqlx::query!(
+ r#"SELECT r.message_id, r.open_count, r.first_opened_at, r.last_opened_at
+ FROM email_message_read_receipts r
+ JOIN email_messages m ON m.id = r.message_id
+ WHERE m.thread_id = $1 AND m.link_id = ANY($2) AND m.is_sent
+ ORDER BY m.internal_date_ts DESC NULLS LAST, r.message_id
+ LIMIT $3"#,
+ thread_id,
+ link_ids,
+ limit,
+ )
+ .fetch_all(&self.0)
+ .await?;
+ rows.into_iter()
+ .map(|row| {
+ Ok(MessageReadReceipt {
+ message_id: row.message_id,
+ open_count: u32::try_from(row.open_count)?,
+ first_opened_at: row.first_opened_at,
+ last_opened_at: row.last_opened_at,
+ })
+ })
+ .collect()
+ }
+}
diff --git a/crates/email/src/outbound/read_receipts_pg/test.rs b/crates/email/src/outbound/read_receipts_pg/test.rs
new file mode 100644
index 0000000000..0bcbe3e841
--- /dev/null
+++ b/crates/email/src/outbound/read_receipts_pg/test.rs
@@ -0,0 +1,144 @@
+use super::*;
+use chrono::Duration;
+use macro_db_migrator::MACRO_DB_MIGRATIONS;
+use sqlx::{Pool, Postgres};
+
+const LINK: &str = "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa";
+const THREAD: &str = "11111111-1111-1111-1111-111111111111";
+const RECEIVED: &str = "ee000001-0000-0000-0000-000000000001";
+const SENT: &str = "ee000002-0000-0000-0000-000000000002";
+const DRAFT: &str = "ee000003-0000-0000-0000-000000000003";
+
+fn id(value: &str) -> Uuid {
+ Uuid::parse_str(value).unwrap()
+}
+
+async fn stored_receipt(pool: &PgPool, message: &str) -> (i32, Option<DateTime<Utc>>) {
+ let row = sqlx::query!(
+ "SELECT open_count, first_opened_at FROM email_message_read_receipts WHERE message_id = $1",
+ id(message)
+ )
+ .fetch_one(pool)
+ .await
+ .unwrap();
+ (row.open_count, row.first_opened_at)
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("email_message"))
+)]
+async fn tracking_follows_the_inbox_setting(pool: Pool<Postgres>) -> Result<(), Report> {
+ let repo = ReadReceiptPgRepository(pool.clone());
+ assert!(!repo.tracking_enabled(id(LINK)).await?);
+
+ sqlx::query!(
+ "INSERT INTO email_settings (link_id, read_receipts_enabled) VALUES ($1, TRUE)",
+ id(LINK)
+ )
+ .execute(&pool)
+ .await?;
+ assert!(repo.tracking_enabled(id(LINK)).await?);
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("email_message"))
+)]
+async fn a_message_keeps_its_first_token(pool: Pool<Postgres>) -> Result<(), Report> {
+ let repo = ReadReceiptPgRepository(pool);
+ let first = ReadReceiptToken::generate();
+ assert_eq!(repo.message_token(id(SENT), &first).await?, first);
+ assert_eq!(
+ repo.message_token(id(SENT), &ReadReceiptToken::generate())
+ .await?,
+ first
+ );
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("email_message"))
+)]
+async fn opens_count_only_for_sent_messages_outside_the_debounce(
+ pool: Pool<Postgres>,
+) -> Result<(), Report> {
+ let repo = ReadReceiptPgRepository(pool.clone());
+ let draft = repo
+ .message_token(id(DRAFT), &ReadReceiptToken::generate())
+ .await?;
+ let sent = repo
+ .message_token(id(SENT), &ReadReceiptToken::generate())
+ .await?;
+ let first = Utc::now();
+ let debounce = Duration::seconds(5);
+
+ assert!(!repo.record_open(&draft, first, first - debounce).await?);
+ assert_eq!(stored_receipt(&pool, DRAFT).await, (0, None));
+
+ assert!(repo.record_open(&sent, first, first - debounce).await?);
+ let soon = first + Duration::seconds(1);
+ assert!(!repo.record_open(&sent, soon, soon - debounce).await?);
+ let later = first + Duration::minutes(1);
+ assert!(repo.record_open(&sent, later, later - debounce).await?);
+
+ let (count, first_opened_at) = stored_receipt(&pool, SENT).await;
+ assert_eq!(count, 2);
+ assert_eq!(
+ first_opened_at.map(|at| at.timestamp_micros()),
+ Some(first.timestamp_micros())
+ );
+ assert!(
+ !repo
+ .record_open(&ReadReceiptToken::generate(), later, later - debounce)
+ .await?
+ );
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("email_message"))
+)]
+async fn thread_receipts_list_sent_messages_of_the_given_inboxes(
+ pool: Pool<Postgres>,
+) -> Result<(), Report> {
+ let repo = ReadReceiptPgRepository(pool);
+ for message in [RECEIVED, SENT] {
+ repo.message_token(id(message), &ReadReceiptToken::generate())
+ .await?;
+ }
+
+ let receipts = repo.thread_receipts(id(THREAD), &[id(LINK)], 10).await?;
+ assert_eq!(
+ receipts,
+ [MessageReadReceipt {
+ message_id: id(SENT),
+ open_count: 0,
+ first_opened_at: None,
+ last_opened_at: None,
+ }]
+ );
+ assert!(
+ repo.thread_receipts(id(THREAD), &[Uuid::now_v7()], 10)
+ .await?
+ .is_empty()
+ );
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("email_message"))
+)]
+async fn accessible_inboxes_include_the_owners_link(pool: Pool<Postgres>) -> Result<(), Report> {
+ let repo = ReadReceiptPgRepository(pool.clone());
+ let link = email_db_client::links::get::fetch_link_by_id(&pool, id(LINK))
+ .await
+ .into_rootcause()?
+ .expect("fixture link exists");
+ assert_eq!(repo.accessible_inboxes(&link.macro_id).await?, [id(LINK)]);
+ Ok(())
+}
diff --git a/crates/email_db_client/src/links/get.rs b/crates/email_db_client/src/links/get.rs
index 69d3f648ae..2640789e97 100644
--- a/crates/email_db_client/src/links/get.rs
+++ b/crates/email_db_client/src/links/get.rs
@@ -201,6 +201,7 @@ struct DbInboxDetailsRow {
updated_at: DateTime<Utc>,
signature_on_replies_forwards: Option<bool>,
signature: Option<String>,
+ read_receipts_enabled: Option<bool>,
latest_backfill_status: Option<db::backfill::BackfillJobStatus>,
provider_granted_scopes: Vec<String>,
calendar_disabled: bool,
@@ -234,6 +235,7 @@ pub async fn fetch_inbox_details_for_macro_id(
l.updated_at as "updated_at!",
s.signature_on_replies_forwards as "signature_on_replies_forwards?",
s.signature,
+ s.read_receipts_enabled as "read_receipts_enabled?",
CASE WHEN l.provider = 'OUTLOOK' THEN
CASE WHEN NOT EXISTS (SELECT 1 FROM email_sync_streams ss WHERE ss.link_id = l.id AND ss.generation = l.sync_generation AND ss.kind IN ('folder_catalog','mail_folder'))
THEN 'Init'::email_backfill_job_status
@@ -287,6 +289,7 @@ pub async fn fetch_inbox_details_for_macro_id(
// Missing settings row → schema default (FALSE).
signature_on_replies_forwards: row.signature_on_replies_forwards.unwrap_or(false),
signature: row.signature,
+ read_receipts_enabled: row.read_receipts_enabled.unwrap_or(false),
};
let link = link::Link::try_from(DbLink {
id: row.id,
diff --git a/crates/email_db_client/src/links/get/test.rs b/crates/email_db_client/src/links/get/test.rs
index ea82ffc239..aa7276de1a 100644
--- a/crates/email_db_client/src/links/get/test.rs
+++ b/crates/email_db_client/src/links/get/test.rs
@@ -296,6 +296,12 @@ async fn fetch_inbox_details_joins_settings_backfill_and_photo(
let (link_id, _, _) =
insert_inbox_with_thread_and_message(&pool, CHILD, "[email protected]").await;
insert_settings(&pool, link_id, true, Some("<p>sig</p>")).await;
+ sqlx::query!(
+ "UPDATE email_settings SET read_receipts_enabled = TRUE WHERE link_id = $1",
+ link_id
+ )
+ .execute(&pool)
+ .await?;
// Older Complete job then a newer Failed one — the latest wins.
insert_backfill_job(
@@ -331,6 +337,7 @@ async fn fetch_inbox_details_joins_settings_backfill_and_photo(
assert_eq!(inbox.link.id, link_id);
assert!(inbox.settings.signature_on_replies_forwards);
assert_eq!(inbox.settings.signature.as_deref(), Some("<p>sig</p>"));
+ assert!(inbox.settings.read_receipts_enabled);
assert_eq!(
inbox.latest_backfill_status,
Some(BackfillJobStatus::Failed)
@@ -623,6 +630,7 @@ async fn fetch_inbox_details_defaults_settings_when_row_missing(
assert_eq!(inbox.link.id, link_id);
assert!(!inbox.settings.signature_on_replies_forwards);
assert!(inbox.settings.signature.is_none());
+ assert!(!inbox.settings.read_receipts_enabled);
Ok(())
}
diff --git a/crates/email_db_client/src/settings.rs b/crates/email_db_client/src/settings.rs
index 5b456939a6..382d36e63b 100644
--- a/crates/email_db_client/src/settings.rs
+++ b/crates/email_db_client/src/settings.rs
@@ -3,8 +3,8 @@ use sqlx::PgPool;
use sqlx::types::Uuid;
/// Applies a partial update to a user's settings. Fields left `None` in the
-/// patch keep their existing value (COALESCE); on a fresh insert, an omitted
-/// `signature_on_replies_forwards` is written as FALSE and `signature` as NULL.
+/// patch keep their existing value (COALESCE); on a fresh insert, omitted
+/// booleans are written as FALSE and `signature` as NULL.
// skip `patch` — it carries the user's signature HTML, which shouldn't hit traces.
#[tracing::instrument(skip(pool, patch), err)]
pub async fn patch_settings(
@@ -14,18 +14,20 @@ pub async fn patch_settings(
let result = sqlx::query_as!(
db::settings::Settings,
r#"
- INSERT INTO email_settings (link_id, signature_on_replies_forwards, signature)
- VALUES ($1, COALESCE($2, FALSE), $3)
+ INSERT INTO email_settings (link_id, signature_on_replies_forwards, signature, read_receipts_enabled)
+ VALUES ($1, COALESCE($2, FALSE), $3, COALESCE($4, FALSE))
ON CONFLICT (link_id)
DO UPDATE SET
signature_on_replies_forwards = COALESCE($2, email_settings.signature_on_replies_forwards),
signature = COALESCE($3, email_settings.signature),
+ read_receipts_enabled = COALESCE($4, email_settings.read_receipts_enabled),
updated_at = NOW()
- RETURNING link_id, signature_on_replies_forwards, signature
+ RETURNING link_id, signature_on_replies_forwards, signature, read_receipts_enabled
"#,
patch.link_id,
patch.signature_on_replies_forwards,
patch.signature,
+ patch.read_receipts_enabled,
)
.fetch_one(pool)
.await?;
@@ -42,7 +44,7 @@ pub async fn fetch_settings(
let result = sqlx::query_as!(
db::settings::Settings,
r#"
- SELECT link_id, signature_on_replies_forwards, signature
+ SELECT link_id, signature_on_replies_forwards, signature, read_receipts_enabled
FROM email_settings
WHERE link_id = $1
"#,
@@ -53,3 +55,6 @@ pub async fn fetch_settings(
Ok(service::settings::Settings::from(result))
}
+
+#[cfg(test)]
+mod test;
diff --git a/crates/email_db_client/src/settings/test.rs b/crates/email_db_client/src/settings/test.rs
new file mode 100644
index 0000000000..add87786a3
--- /dev/null
+++ b/crates/email_db_client/src/settings/test.rs
@@ -0,0 +1,68 @@
+use crate::settings::{fetch_settings, patch_settings};
+use macro_db_migrator::MACRO_DB_MIGRATIONS;
+use models_email::service::settings::SettingsPatch;
+use sqlx::types::Uuid;
+use sqlx::{Pool, Postgres};
+
+async fn insert_link(pool: &Pool<Postgres>) -> Uuid {
+ let link_id = Uuid::new_v4();
+ sqlx::query!(
+ r#"INSERT INTO email_links (id, macro_id, fusionauth_user_id, email_address, provider)
+ VALUES ($1, 'macro|[email protected]', 'macro|[email protected]', '[email protected]', 'GMAIL')"#,
+ link_id,
+ )
+ .execute(pool)
+ .await
+ .unwrap();
+ link_id
+}
+
+fn patch(link_id: Uuid) -> SettingsPatch {
+ SettingsPatch {
+ link_id,
+ signature_on_replies_forwards: None,
+ signature: None,
+ read_receipts_enabled: None,
+ }
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn read_receipts_default_off_and_patch_independently(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let link_id = insert_link(&pool).await;
+
+ let created = patch_settings(
+ &pool,
+ SettingsPatch {
+ signature: Some("<p>sig</p>".into()),
+ ..patch(link_id)
+ },
+ )
+ .await?;
+ assert!(!created.read_receipts_enabled);
+
+ let enabled = patch_settings(
+ &pool,
+ SettingsPatch {
+ read_receipts_enabled: Some(true),
+ ..patch(link_id)
+ },
+ )
+ .await?;
+ assert!(enabled.read_receipts_enabled);
+ assert_eq!(enabled.signature.as_deref(), Some("<p>sig</p>"));
+
+ let untouched = patch_settings(
+ &pool,
+ SettingsPatch {
+ signature_on_replies_forwards: Some(true),
+ ..patch(link_id)
+ },
+ )
+ .await?;
+ assert!(untouched.read_receipts_enabled);
+ assert!(fetch_settings(&pool, link_id).await?.read_receipts_enabled);
+
+ Ok(())
+}
diff --git a/crates/macro_db_client/migrations/20261022224928_email_read_receipts.sql b/crates/macro_db_client/migrations/20261022224928_email_read_receipts.sql
new file mode 100644
index 0000000000..df4fd178a9
--- /dev/null
+++ b/crates/macro_db_client/migrations/20261022224928_email_read_receipts.sql
@@ -0,0 +1,15 @@
+-- Open tracking is opt-in per inbox.
+ALTER TABLE email_settings
+ ADD COLUMN read_receipts_enabled BOOLEAN NOT NULL DEFAULT FALSE;
+
+-- One pixel per delivered message. The token is kept so delivery retries and
+-- Outlook draft revisions rebuild the same pixel URL; it only lets its holder
+-- count an open of that one message.
+CREATE TABLE email_message_read_receipts (
+ message_id uuid PRIMARY KEY REFERENCES email_messages(id) ON DELETE CASCADE,
+ token text NOT NULL UNIQUE,
+ open_count integer NOT NULL DEFAULT 0 CHECK (open_count >= 0),
+ first_opened_at timestamptz,
+ last_opened_at timestamptz,
+ created_at timestamptz NOT NULL DEFAULT now()
+);
diff --git a/crates/models_email/src/email/api/settings.rs b/crates/models_email/src/email/api/settings.rs
index 230c638d37..a94da746a3 100644
--- a/crates/models_email/src/email/api/settings.rs
+++ b/crates/models_email/src/email/api/settings.rs
@@ -8,6 +8,8 @@ pub struct Settings {
/// `null` to leave unchanged (both deserialize to `None`); pass an empty
/// string to clear it. The column cannot be set to SQL NULL via patch.
pub signature: Option<String>,
+ /// Whether messages sent from this inbox carry an open-tracking pixel.
+ pub read_receipts_enabled: Option<bool>,
}
impl From<crate::email::service::settings::Settings> for Settings {
@@ -15,6 +17,7 @@ impl From<crate::email::service::settings::Settings> for Settings {
Settings {
signature_on_replies_forwards: Some(service_settings.signature_on_replies_forwards),
signature: service_settings.signature,
+ read_receipts_enabled: Some(service_settings.read_receipts_enabled),
}
}
}
diff --git a/crates/models_email/src/email/db/settings.rs b/crates/models_email/src/email/db/settings.rs
index 1d995336df..6386a07ef4 100644
--- a/crates/models_email/src/email/db/settings.rs
+++ b/crates/models_email/src/email/db/settings.rs
@@ -7,4 +7,5 @@ pub struct Settings {
pub link_id: Uuid,
pub signature_on_replies_forwards: bool,
pub signature: Option<String>,
+ pub read_receipts_enabled: bool,
}
diff --git a/crates/models_email/src/email/service/settings.rs b/crates/models_email/src/email/service/settings.rs
index 555163dde0..6f92c4604b 100644
--- a/crates/models_email/src/email/service/settings.rs
+++ b/crates/models_email/src/email/service/settings.rs
@@ -7,6 +7,7 @@ pub struct Settings {
pub link_id: Uuid,
pub signature_on_replies_forwards: bool,
pub signature: Option<String>,
+ pub read_receipts_enabled: bool,
}
impl From<crate::email::db::settings::Settings> for Settings {
@@ -15,6 +16,7 @@ impl From<crate::email::db::settings::Settings> for Settings {
link_id: db_settings.link_id,
signature_on_replies_forwards: db_settings.signature_on_replies_forwards,
signature: db_settings.signature,
+ read_receipts_enabled: db_settings.read_receipts_enabled,
}
}
}
@@ -25,6 +27,7 @@ pub struct SettingsPatch {
pub link_id: Uuid,
pub signature_on_replies_forwards: Option<bool>,
pub signature: Option<String>,
+ pub read_receipts_enabled: Option<bool>,
}
impl SettingsPatch {
@@ -33,6 +36,7 @@ impl SettingsPatch {
link_id,
signature_on_replies_forwards: api_settings.signature_on_replies_forwards,
signature: api_settings.signature,
+ read_receipts_enabled: api_settings.read_receipts_enabled,
}
}
}
diff --git a/docs/agent-guide/email.md b/docs/agent-guide/email.md
index e6622a58be..ba0e1c2718 100644
--- a/docs/agent-guide/email.md
+++ b/docs/agent-guide/email.md
@@ -824,6 +824,30 @@ Macro Markdown messages retain document mentions. Ordinary HTML bodies use an
open shadow root: Playwright text locators can reach them, but a card's ordinary
`innerText` or `querySelector` does not traverse that root.
+### Read receipts
+
+With `enable-email-read-receipts` on and read receipts turned on for an inbox
+(see [Settings](settings.md#email-read-receipts)), messages sent from that
+inbox show **Opened** or **Not opened** beside the date in the expanded
+message header. The desktop tooltip and the expanded header details (tap the
+header caret on touch) give the count and first and last open times. Only
+people with access to the sending inbox see it, and the thread refreshes it
+about once a minute. Turning the setting off stops tracking new messages;
+statuses already recorded for that inbox stay visible while another of the
+viewer's inboxes has read receipts on, and every status hides once none does.
+A recipient who reads their own copy in Macro counts as
+an open; the reader loads the pixel only on copies in an inbox the viewer owns
+or is a delegate of that were not sent from one of the viewer's addresses or
+send-as aliases. The sender's copy never loads it, including a copy the sender
+received by CC'ing themselves, and neither does a thread seen only through
+sharing or any copy while the viewer's inboxes load. Quoted replies and
+forwards always drop it, so new recipients never inherit the original's pixel.
+With the image proxy on, a browser caches the pixel, so a recipient's repeat
+opens in Macro on one device count once. Verify with two Macro accounts: open
+the recipient's copy, then check the sender's status; the sender's own views
+must not change it. Opens need the email service's public URL, which the local
+Docker stack cannot serve.
+
Sending a reply from an inbox thread marks that thread done but stays on it.
Send and mark done (Shift+Cmd+Enter) and Mark done open the next email, counted
from where the thread sat when it was opened (a reply draft lifts its thread to
diff --git a/docs/agent-guide/settings.md b/docs/agent-guide/settings.md
index 62e4baa661..4d8d325f9e 100644
--- a/docs/agent-guide/settings.md
+++ b/docs/agent-guide/settings.md
@@ -111,6 +111,13 @@ Trace signature actions under `email.signature.save`, `email.signature.clear`,
or `email.signature.import`; the REST write and `email.settings.refresh` run
under that action, including the account catalog's durable refresh.
+### Email read receipts
+
+Behind `enable-email-read-receipts` (on in dev), **Settings → Email → Read
+receipts** lists each owned inbox with a switch that saves immediately. It is
+off by default. Messages sent from an inbox with it on carry an invisible
+pixel; see [read receipts in a thread](email.md#read-receipts) for the status.
+
### Notification permission prompt
After onboarding, an eligible desktop app user sees **Enable Desktop
diff --git a/docs/architecture/email.md b/docs/architecture/email.md
index 119661f9c6..ef50a7e005 100644
--- a/docs/architecture/email.md
+++ b/docs/architecture/email.md
@@ -97,7 +97,7 @@ test exercises this ordering.
| `EmailThreadContext` | Thread source, viewer and device state, recipients, and the command factory used by thread state and navigation |
| `EmailThreadViewContext` | Thread and compose contexts, plus view callbacks and optional compose host behavior |
| `EmailThreadHost` | Optional location target, focus, activation status, and keyboard registration |
-| `EmailRenderingContextValue` | Theme values, explicit image policy, link preparation, and image resolution with an abortable resource lifetime |
+| `EmailRenderingContextValue` | Theme values, explicit image policy, Macro read-receipt pixel prefixes (hidden unless the thread lets a copy count an open), link preparation, and image resolution with an abortable resource lifetime |
| `EmailFormContextInputs` | Viewer address and available inbox identities for recipient selection |
| `EmailReplySession` | Thread identity, recipient options, personal-reply classification, a targeted reply request, and host intents for leaving the composer or removing its draft |
| `EmailDraftStorage` | Save/delete and restore an undone draft, and drop a moved draft's working copy; inputs use domain inbox IDs and completion intent |
diff --git a/packages/email-renderer/README.md b/packages/email-renderer/README.md
index 98e61b307f..b55b3ad08d 100644
--- a/packages/email-renderer/README.md
+++ b/packages/email-renderer/README.md
@@ -117,7 +117,11 @@ There is no implicit fetch client or native-platform detection in this package.
authenticated-image adapter. CSS URLs and HTML background attributes follow
the same allow/block policy but keep direct URLs; authenticated backgrounds
are not supported by that native adapter. Escaped CSS URL functions that the
- parser cannot normalize as URL nodes are excluded.
+ parser cannot normalize as URL nodes are excluded. `hiddenUrlPrefixes` drops
+ matching HTTP(S) `img[src]` values before proxying. The app passes Macro's
+ read-receipt pixel URLs for every quoted reply or forward, and in the reader
+ for every copy except one a recipient received, so only a recipient's view
+ counts as an open.
- Links open with `target="_blank"` and `rel="noopener noreferrer"`; the host
may intercept mailto links. Shadow containment bounds layout and paint. It is
not an iframe security boundary; sanitization remains essential.
diff --git a/packages/email-renderer/src/core/html.test.ts b/packages/email-renderer/src/core/html.test.ts
index 6a71d0e8a5..9ff863d3ab 100644
--- a/packages/email-renderer/src/core/html.test.ts
+++ b/packages/email-renderer/src/core/html.test.ts
@@ -253,6 +253,35 @@ describe('content and resource policy', () => {
expect(result.html).toContain('background="https://example.com/table"');
expect(result.html.match(/proxy\.test/g)).toHaveLength(1);
});
+ it('drops hidden image prefixes before proxying and in quoted HTML', () => {
+ const html =
+ '<p>Hi</p><img src="HTTPS://mail.test/opens/abc" width="1"><img src="https://mail.test/logo.png">';
+ const hiddenUrlPrefixes = ['https://mail.test/opens/'];
+ const direct = prepareEmailBody(
+ { html },
+ { images: { remote: 'allow', hiddenUrlPrefixes } }
+ ).html;
+ expect(direct).not.toContain('/opens/');
+ expect(direct).toContain('src="https://mail.test/logo.png"');
+ const proxied = prepareEmailBody(
+ { html },
+ {
+ images: {
+ remote: 'allow',
+ proxyUrl: 'https://proxy.test',
+ hiddenUrlPrefixes,
+ },
+ }
+ ).html;
+ expect(proxied).not.toContain('opens');
+ expect(proxied).toContain('logo.png');
+ const quoted = sanitizeEmailHtml(html, {
+ remote: 'allow',
+ hiddenUrlPrefixes,
+ });
+ expect(quoted).not.toContain('/opens/');
+ expect(quoted).toContain('<p>Hi</p>');
+ });
it('keeps CID and raster data images, excluding SVG data images', () => {
const result = sanitizeEmailHtml(
'<img src="cid:part"><img src="data:image/png;base64,AAAA"><img src="data:image/svg+xml;base64,AAAA">'
diff --git a/packages/email-renderer/src/core/resource-policy.ts b/packages/email-renderer/src/core/resource-policy.ts
index 64159978ea..dc398d66ab 100644
--- a/packages/email-renderer/src/core/resource-policy.ts
+++ b/packages/email-renderer/src/core/resource-policy.ts
@@ -4,6 +4,9 @@ export interface ImagePolicy {
/** Proxy for img[src], matching native authenticated-image support.
* CSS/background images retain direct URLs under the remote policy. */
proxyUrl?: string;
+ /** HTTP(S) img[src] values starting with one of these are dropped before
+ * proxying, so a host can withhold its own tracking pixels. */
+ hiddenUrlPrefixes?: readonly string[];
}
function cleanUrl(value: string): string {
@@ -32,8 +35,10 @@ export function imageUrl(
if (policy.remote === 'block') return;
if (!hasScheme(url)) return url;
if (!/^https?:\/\//i.test(url)) return;
- if (!policy.proxyUrl)
- return url.replace(/^https?:/i, (scheme) => scheme.toLowerCase());
+ const direct = url.replace(/^https?:/i, (scheme) => scheme.toLowerCase());
+ if (policy.hiddenUrlPrefixes?.some((prefix) => direct.startsWith(prefix)))
+ return;
+ if (!policy.proxyUrl) return direct;
if (!/^https?:\/\//i.test(policy.proxyUrl)) return;
return `${policy.proxyUrl}${policy.proxyUrl.includes('?') ? '&' : '?'}url=${encodeURIComponent(url)}`;
}
diff --git a/packages/sdk-docs/reference/generated/email/types.gen/README.md b/packages/sdk-docs/reference/generated/email/types.gen/README.md
index 6c1ca97696..6e1e250920 100644
--- a/packages/sdk-docs/reference/generated/email/types.gen/README.md
+++ b/packages/sdk-docs/reference/generated/email/types.gen/README.md
@@ -215,6 +215,8 @@
- [GetMessagesBatchResponse](type-aliases/GetMessagesBatchResponse.md)
- [GetMessagesBatchResponses](type-aliases/GetMessagesBatchResponses.md)
- [GetPreviewsCursorParams](type-aliases/GetPreviewsCursorParams.md)
+- [GetReadReceiptPixelData](type-aliases/GetReadReceiptPixelData.md)
+- [GetReadReceiptPixelResponses](type-aliases/GetReadReceiptPixelResponses.md)
- [GetScheduledMessagesData](type-aliases/GetScheduledMessagesData.md)
- [GetScheduledMessagesError](type-aliases/GetScheduledMessagesError.md)
- [GetScheduledMessagesErrors](type-aliases/GetScheduledMessagesErrors.md)
@@ -233,6 +235,10 @@
- [GetThreadMessagesHandlerErrors](type-aliases/GetThreadMessagesHandlerErrors.md)
- [GetThreadMessagesHandlerResponse](type-aliases/GetThreadMessagesHandlerResponse.md)
- [GetThreadMessagesHandlerResponses](type-aliases/GetThreadMessagesHandlerResponses.md)
+- [GetThreadReadReceiptsData](type-aliases/GetThreadReadReceiptsData.md)
+- [GetThreadReadReceiptsErrors](type-aliases/GetThreadReadReceiptsErrors.md)
+- [GetThreadReadReceiptsResponse](type-aliases/GetThreadReadReceiptsResponse.md)
+- [GetThreadReadReceiptsResponses](type-aliases/GetThreadReadReceiptsResponses.md)
- [GetThreadResponse](type-aliases/GetThreadResponse.md)
- [GetThreadResponse2](type-aliases/GetThreadResponse2.md)
- [GetThreadResponses](type-aliases/GetThreadResponses.md)
@@ -313,6 +319,7 @@
- [MessageOperationStatusErrors](type-aliases/MessageOperationStatusErrors.md)
- [MessageOperationStatusResponse](type-aliases/MessageOperationStatusResponse.md)
- [MessageOperationStatusResponses](type-aliases/MessageOperationStatusResponses.md)
+- [MessageReadReceipt](type-aliases/MessageReadReceipt.md)
- [ParsedMessage](type-aliases/ParsedMessage.md)
- [PatchSettingsData](type-aliases/PatchSettingsData.md)
- [PatchSettingsError](type-aliases/PatchSettingsError.md)
@@ -374,6 +381,7 @@
- [ThreadOperationsResponse](type-aliases/ThreadOperationsResponse.md)
- [ThreadOperationsResponses](type-aliases/ThreadOperationsResponses.md)
- [ThreadPreviewCursor](type-aliases/ThreadPreviewCursor.md)
+- [ThreadReadReceipts](type-aliases/ThreadReadReceipts.md)
- [ThreadSeenData](type-aliases/ThreadSeenData.md)
- [ThreadSeenError](type-aliases/ThreadSeenError.md)
- [ThreadSeenErrors](type-aliases/ThreadSeenErrors.md)
diff --git a/packages/sdk-docs/reference/generated/email/types.gen/type-aliases/GetReadReceiptPixelData.md b/packages/sdk-docs/reference/generated/email/types.gen/type-aliases/GetReadReceiptPixelData.md
new file mode 100644
index 0000000000..a8f9e37288
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/email/types.gen/type-aliases/GetReadReceiptPixelData.md
@@ -0,0 +1,13 @@
+# Type Alias: GetReadReceiptPixelData
+
+> **GetReadReceiptPixelData** = \{ `body?`: `never`; `path`: \{ `token`: `string`; \}; `query?`: `never`; `url`: `"/opens/{token}"`; \}
+
+## Properties
+
+| Property | Type | Description |
+| ------ | ------ | ------ |
+| <a id="property-body"></a> `body?` | `never` | - |
+| <a id="property-path"></a> `path` | \{ `token`: `string`; \} | - |
+| `path.token` | `string` | Opaque pixel token |
+| <a id="property-query"></a> `query?` | `never` | - |
+| <a id="property-url"></a> `url` | `"/opens/{token}"` | - |
diff --git a/packages/sdk-docs/reference/generated/email/types.gen/type-aliases/GetReadReceiptPixelResponses.md b/packages/sdk-docs/reference/generated/email/types.gen/type-aliases/GetReadReceiptPixelResponses.md
new file mode 100644
index 0000000000..76020d9df3
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/email/types.gen/type-aliases/GetReadReceiptPixelResponses.md
@@ -0,0 +1,9 @@
+# Type Alias: GetReadReceiptPixelResponses
+
+> **GetReadReceiptPixelResponses** = \{ `200`: `unknown`; \}
+
+## Properties
+
+| Property | Type | Description |
+| ------ | ------ | ------ |
+| <a id="property-200"></a> `200` | `unknown` | Transparent pixel, for any token |
diff --git a/packages/sdk-docs/reference/generated/email/types.gen/type-aliases/GetThreadReadReceiptsData.md b/packages/sdk-docs/reference/generated/email/types.gen/type-aliases/GetThreadReadReceiptsData.md
new file mode 100644
index 0000000000..7dcf9f0929
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/email/types.gen/type-aliases/GetThreadReadReceiptsData.md
@@ -0,0 +1,13 @@
+# Type Alias: GetThreadReadReceiptsData
+
+> **GetThreadReadReceiptsData** = \{ `body?`: `never`; `path`: \{ `thread_id`: `string`; \}; `query?`: `never`; `url`: `"/email/threads/{thread_id}/read-receipts"`; \}
+
+## Properties
+
+| Property | Type | Description |
+| ------ | ------ | ------ |
+| <a id="property-body"></a> `body?` | `never` | - |
+| <a id="property-path"></a> `path` | \{ `thread_id`: `string`; \} | - |
+| `path.thread_id` | `string` | Authorized email thread |
+| <a id="property-query"></a> `query?` | `never` | - |
+| <a id="property-url"></a> `url` | `"/email/threads/{thread_id}/read-receipts"` | - |
diff --git a/packages/sdk-docs/reference/generated/email/types.gen/type-aliases/GetThreadReadReceiptsErrors.md b/packages/sdk-docs/reference/generated/email/types.gen/type-aliases/GetThreadReadReceiptsErrors.md
new file mode 100644
index 0000000000..d36fe8ad2a
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/email/types.gen/type-aliases/GetThreadReadReceiptsErrors.md
@@ -0,0 +1,10 @@
+# Type Alias: GetThreadReadReceiptsErrors
+
+> **GetThreadReadReceiptsErrors** = \{ `401`: `unknown`; `403`: `unknown`; \}
+
+## Properties
+
+| Property | Type |
+| ------ | ------ |
+| <a id="property-401"></a> `401` | `unknown` |
+| <a id="property-403"></a> `403` | `unknown` |
diff --git a/packages/sdk-docs/reference/generated/email/types.gen/type-aliases/GetThreadReadReceiptsResponse.md b/packages/sdk-docs/reference/generated/email/types.gen/type-aliases/GetThreadReadReceiptsResponse.md
new file mode 100644
index 0000000000..1cef7a2cde
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/email/types.gen/type-aliases/GetThreadReadReceiptsResponse.md
@@ -0,0 +1,3 @@
+# Type Alias: GetThreadReadReceiptsResponse
+
+> **GetThreadReadReceiptsResponse** = [`GetThreadReadReceiptsResponses`](GetThreadReadReceiptsResponses.md)\[keyof [`GetThreadReadReceiptsResponses`](GetThreadReadReceiptsResponses.md)\]
diff --git a/packages/sdk-docs/reference/generated/email/types.gen/type-aliases/GetThreadReadReceiptsResponses.md b/packages/sdk-docs/reference/generated/email/types.gen/type-aliases/GetThreadReadReceiptsResponses.md
new file mode 100644
index 0000000000..442a774eda
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/email/types.gen/type-aliases/GetThreadReadReceiptsResponses.md
@@ -0,0 +1,9 @@
+# Type Alias: GetThreadReadReceiptsResponses
+
+> **GetThreadReadReceiptsResponses** = \{ `200`: [`ThreadReadReceipts`](ThreadReadReceipts.md); \}
+
+## Properties
+
+| Property | Type |
+| ------ | ------ |
+| <a id="property-200"></a> `200` | [`ThreadReadReceipts`](ThreadReadReceipts.md) |
diff --git a/packages/sdk-docs/reference/generated/email/types.gen/type-aliases/MessageReadReceipt.md b/packages/sdk-docs/reference/generated/email/types.gen/type-aliases/MessageReadReceipt.md
new file mode 100644
index 0000000000..92b554d7a2
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/email/types.gen/type-aliases/MessageReadReceipt.md
@@ -0,0 +1,14 @@
+# Type Alias: MessageReadReceipt
+
+> **MessageReadReceipt** = \{ `first_opened_at?`: `string` \| `null`; `last_opened_at?`: `string` \| `null`; `message_id`: `string`; `open_count`: `number`; \}
+
+Open state of one tracked, sent message.
+
+## Properties
+
+| Property | Type | Description |
+| ------ | ------ | ------ |
+| <a id="property-first_opened_at"></a> `first_opened_at?` | `string` \| `null` | First counted fetch. |
+| <a id="property-last_opened_at"></a> `last_opened_at?` | `string` \| `null` | Latest counted fetch. |
+| <a id="property-message_id"></a> `message_id` | `string` | The tracked message. |
+| <a id="property-open_count"></a> `open_count` | `number` | Counted pixel fetches. |
diff --git a/packages/sdk-docs/reference/generated/email/types.gen/type-aliases/Settings.md b/packages/sdk-docs/reference/generated/email/types.gen/type-aliases/Settings.md
index 7cdb2dd272..0dd453d31f 100644
--- a/packages/sdk-docs/reference/generated/email/types.gen/type-aliases/Settings.md
+++ b/packages/sdk-docs/reference/generated/email/types.gen/type-aliases/Settings.md
@@ -1,10 +1,11 @@
# Type Alias: Settings
-> **Settings** = \{ `signature?`: `string` \| `null`; `signature_on_replies_forwards?`: `boolean` \| `null`; \}
+> **Settings** = \{ `read_receipts_enabled?`: `boolean` \| `null`; `signature?`: `string` \| `null`; `signature_on_replies_forwards?`: `boolean` \| `null`; \}
## Properties
| Property | Type | Description |
| ------ | ------ | ------ |
+| <a id="property-read_receipts_enabled"></a> `read_receipts_enabled?` | `boolean` \| `null` | Whether messages sent from this inbox carry an open-tracking pixel. |
| <a id="property-signature"></a> `signature?` | `string` \| `null` | The user's email signature content (HTML). On a patch, omit or send `null` to leave unchanged (both deserialize to `None`); pass an empty string to clear it. The column cannot be set to SQL NULL via patch. |
| <a id="property-signature_on_replies_forwards"></a> `signature_on_replies_forwards?` | `boolean` \| `null` | - |
diff --git a/packages/sdk-docs/reference/generated/email/types.gen/type-aliases/ThreadReadReceipts.md b/packages/sdk-docs/reference/generated/email/types.gen/type-aliases/ThreadReadReceipts.md
new file mode 100644
index 0000000000..1a332e03aa
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/email/types.gen/type-aliases/ThreadReadReceipts.md
@@ -0,0 +1,11 @@
+# Type Alias: ThreadReadReceipts
+
+> **ThreadReadReceipts** = \{ `receipts`: [`MessageReadReceipt`](MessageReadReceipt.md)[]; \}
+
+Open state of the caller's tracked, sent messages in one thread.
+
+## Properties
+
+| Property | Type |
+| ------ | ------ |
+| <a id="property-receipts"></a> `receipts` | [`MessageReadReceipt`](MessageReadReceipt.md)[] |
diff --git a/packages/sdk-docs/reference/src/entities/email/thread/README.md b/packages/sdk-docs/reference/src/entities/email/thread/README.md
index 283c52c27e..0565e12850 100644
--- a/packages/sdk-docs/reference/src/entities/email/thread/README.md
+++ b/packages/sdk-docs/reference/src/entities/email/thread/README.md
@@ -6,4 +6,5 @@
## Interfaces
+- [EmailReadReceipt](interfaces/EmailReadReceipt.md)
- [ReplyEmailOptions](interfaces/ReplyEmailOptions.md)
diff --git a/packages/sdk-docs/reference/src/entities/email/thread/classes/EmailThread.md b/packages/sdk-docs/reference/src/entities/email/thread/classes/EmailThread.md
index 9129bbf8db..cce12804b8 100644
--- a/packages/sdk-docs/reference/src/entities/email/thread/classes/EmailThread.md
+++ b/packages/sdk-docs/reference/src/entities/email/thread/classes/EmailThread.md
@@ -303,6 +303,20 @@ This entity's reference for bulk property operations.
***
+### readReceipts()
+
+> **readReceipts**(): `Promise`\<[`EmailReadReceipt`](../interfaces/EmailReadReceipt.md)[]\>
+
+Opens recorded for messages sent from the caller's own or delegated
+inboxes with read receipts on, newest message first. Counts are
+approximate: some mail apps prefetch images and others block them.
+
+#### Returns
+
+`Promise`\<[`EmailReadReceipt`](../interfaces/EmailReadReceipt.md)[]\>
+
+***
+
### removeLabel()
> **removeLabel**(`label`): `Promise`\<`void`\>
diff --git a/packages/sdk-docs/reference/src/entities/email/thread/interfaces/EmailReadReceipt.md b/packages/sdk-docs/reference/src/entities/email/thread/interfaces/EmailReadReceipt.md
new file mode 100644
index 0000000000..4a049e4a8b
--- /dev/null
+++ b/packages/sdk-docs/reference/src/entities/email/thread/interfaces/EmailReadReceipt.md
@@ -0,0 +1,12 @@
+# Interface: EmailReadReceipt
+
+Open tracking for one of the caller's sent messages.
+
+## Properties
+
+| Property | Type | Description |
+| ------ | ------ | ------ |
+| <a id="property-firstopenedat"></a> `firstOpenedAt?` | `string` | When the first counted fetch happened, if any. |
+| <a id="property-lastopenedat"></a> `lastOpenedAt?` | `string` | When the latest counted fetch happened, if any. |
+| <a id="property-message"></a> `message` | [`EmailMessage`](../../message/classes/EmailMessage.md) | The tracked message. |
+| <a id="property-opencount"></a> `openCount` | `number` | Counted pixel fetches; repeats within a few seconds count once. |
diff --git a/packages/sdk/generated/email/index.ts b/packages/sdk/generated/email/index.ts
index baa8aff159..b9722babcf 100644
--- a/packages/sdk/generated/email/index.ts
+++ b/packages/sdk/generated/email/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 { AccessLevel, AddDraftAttachmentData, AddDraftAttachmentError, AddDraftAttachmentErrors, AddDraftAttachmentRequest, AddDraftAttachmentResponse, AddDraftAttachmentResponse2, AddDraftAttachmentResponses, AddForwardedAttachmentData, AddForwardedAttachmentError, AddForwardedAttachmentErrors, AddForwardedAttachmentRequest, AddForwardedAttachmentResponse, AddForwardedAttachmentResponse2, AddForwardedAttachmentResponses, AddRemoveLabelData, AddRemoveLabelError, AddRemoveLabelErrors, AddRemoveLabelResponse, AddRemoveLabelResponses, AddRemoveThreadLabelData, AddRemoveThreadLabelError, AddRemoveThreadLabelErrors, AddRemoveThreadLabelResponse, AddRemoveThreadLabelResponses, ApiAttachment, ApiAttachmentDraft, ApiAttachmentForwarded, ApiContact, ApiContactInfo, ApiDraftContactInfo, ApiDraftInput, ApiDraftOutput, ApiEmailFilter, ApiLabel, ApiLabelListVisibility, ApiLabelType, ApiMessage, ApiMessageAttachment, ApiMessageLabel, ApiMessageListVisibility, ApiMessageOperation, ApiMessageOperationIssue, ApiMessageOperationState, ApiMessageResolutionAction, ApiPaginatedThreadCursor, ApiSortMethod, ApiThread, ApiThreadPreviewCursor, ApiThreadPreviewCursorInner, ArchiveThreadData, ArchiveThreadError, ArchiveThreadErrors, ArchiveThreadRequest, ArchiveThreadResponse, ArchiveThreadResponses, ArchiveThreadsData, ArchiveThreadsError, ArchiveThreadsErrors, ArchiveThreadsRequest, ArchiveThreadsResponse, ArchiveThreadsResponse2, ArchiveThreadsResponses, Attachment, AttachmentDraft, AttachmentForwarded, AttendeeResponseStatus, BackfillJob, BackfillJobStatus, BackfillStatus, BlockSenderData, BlockSenderError, BlockSenderErrors, BlockSenderRequest, BlockSenderResponses, CalendarAttendee, CalendarEvent, CalendarEventSourceContent, CalendarInvitation, CalendarMutationApiError, CalendarMutationErrorCode, CalendarOccurrence, CancelBackfillGmailData, CancelBackfillGmailError, CancelBackfillGmailErrors, CancelBackfillGmailResponse, CancelBackfillGmailResponses, CancelBackfillParams, ClientOptions, CompleteDraftAttachmentData, CompleteDraftAttachmentErrors, CompleteDraftAttachmentResponse, CompleteDraftAttachmentResponses, ConferenceProvider, Contact, ContactInfo, ContactInfoLegacy, ContactInfoWithInteraction, CopyCalendarEventRequest, CopyThreadCalendarInvitationData, CopyThreadCalendarInvitationError, CopyThreadCalendarInvitationErrors, CopyThreadCalendarInvitationResponse, CopyThreadCalendarInvitationResponses, CreateDraftData, CreateDraftError, CreateDraftErrors, CreateDraftRequest, CreateDraftResponse, CreateDraftResponse2, CreateDraftResponses, CreateLabelData, CreateLabelError, CreateLabelErrors, CreateLabelRequest, CreateLabelResponse, CreateLabelResponse2, CreateLabelResponses, DeleteDraftData, DeleteDraftError, DeleteDraftErrors, DeleteDraftResponse, DeleteDraftResponses, DeleteEmailFilterData, DeleteEmailFilterError, DeleteEmailFilterErrors, DeleteEmailFilterResponse, DeleteEmailFilterResponses, DeleteLabelData, DeleteLabelError, DeleteLabelErrors, DeleteLabelResponse, DeleteLabelResponses, DeleteLinkData, DeleteLinkError, DeleteLinkErrors, DeleteLinkResponse, DeleteLinkResponses, DeleteScheduledDraftData, DeleteScheduledDraftError, DeleteScheduledDraftErrors, DeleteScheduledDraftResponse, DeleteScheduledDraftResponses, DisableLinkCalendarData, DisableLinkCalendarError, DisableLinkCalendarErrors, DisableLinkCalendarResponse, DisableLinkCalendarResponses, DisableSyncData, DisableSyncError, DisableSyncErrors, DisableSyncResponse, DisableSyncResponses, EmlFile, EmptyResponse, ErrorResponse, EventReminderOverride, EventReminders, EventStatus, EventTime, EventTransparency, EventType, EventVisibility, ForwardCalendarEventData, ForwardCalendarEventError, ForwardCalendarEventError2, ForwardCalendarEventErrorCode, ForwardCalendarEventErrors, ForwardCalendarEventRecipient, ForwardCalendarEventRequest, ForwardCalendarEventResponse, ForwardCalendarEventResponse2, ForwardCalendarEventResponses, GetActiveBackfillJobResponse, GetAttachmentData, GetAttachmentDocumentIdData, GetAttachmentDocumentIdError, GetAttachmentDocumentIdErrors, GetAttachmentDocumentIdResponse, GetAttachmentDocumentIdResponse2, GetAttachmentDocumentIdResponses, GetAttachmentError, GetAttachmentErrors, GetAttachmentResponse, GetAttachmentResponse2, GetAttachmentResponses, GetBackfillGmailActiveData, GetBackfillGmailActiveError, GetBackfillGmailActiveErrors, GetBackfillGmailActiveResponse, GetBackfillGmailActiveResponses, GetBackfillGmailData, GetBackfillGmailError, GetBackfillGmailErrors, GetBackfillGmailResponse, GetBackfillGmailResponses, GetBackfillJobResponse, GetMessageData, GetMessageEmlData, GetMessageEmlError, GetMessageEmlErrors, GetMessageEmlResponse, GetMessageEmlResponses, GetMessageError, GetMessageErrors, GetMessageResponse, GetMessageResponses, GetMessagesBatchData, GetMessagesBatchError, GetMessagesBatchErrors, GetMessagesBatchResponse, GetMessagesBatchResponses, GetPreviewsCursorParams, GetScheduledMessagesData, GetScheduledMessagesError, GetScheduledMessagesErrors, GetScheduledMessagesResponse, GetScheduledMessagesResponses, GetScheduledResponse, GetThreadCalendarInvitationsData, GetThreadCalendarInvitationsErrors, GetThreadCalendarInvitationsResponse, GetThreadCalendarInvitationsResponses, GetThreadData, GetThreadError, GetThreadErrors, GetThreadMessagesHandlerData, GetThreadMessagesHandlerError, GetThreadMessagesHandlerErrors, GetThreadMessagesHandlerResponse, GetThreadMessagesHandlerResponses, GetThreadResponse, GetThreadResponse2, GetThreadResponses, GuestPolicy, HealthCheckLinksData, HealthCheckLinksError, HealthCheckLinksErrors, HealthCheckLinksResponse, HealthCheckLinksResponses, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, InitErrorCodeResponse, InitResponse, InitUserData, InitUserError, InitUserErrors, InitUserResponse, InitUserResponses, InvitationDateTime, InvitationMethod, InvitationParticipant, InvitationResolution, Label, LabelInfo, LabelListVisibility, LabelType, Link, ListBackfillGmailData, ListBackfillGmailError, ListBackfillGmailErrors, ListBackfillGmailResponse, ListBackfillGmailResponses, ListBackfillJobsResponse, ListBlockedResponse, ListBlockedSendersData, ListBlockedSendersError, ListBlockedSendersErrors, ListBlockedSendersResponse, ListBlockedSendersResponses, ListContactsData, ListContactsError, ListContactsErrors, ListContactsResponse, ListContactsResponse2, ListContactsResponses, ListEmailFiltersData, ListEmailFiltersError, ListEmailFiltersErrors, ListEmailFiltersResponse, ListEmailFiltersResponse2, ListEmailFiltersResponses, ListLabelsData, ListLabelsError, ListLabelsErrors, ListLabelsResponse, ListLabelsResponse2, ListLabelsResponses, ListLinksData, ListLinksError, ListLinksErrors, ListLinksResponse, ListLinksResponse2, ListLinksResponses, MailboxAction, MailboxOperation, MailboxOperationState, MailboxSettingsChange, MailboxSettingsOperation, MailboxSettingsOperationsData, MailboxSettingsOperationsResponse, MailboxSettingsOperationsResponses, Message, MessageListVisibility, MessageOperationResponse, MessageOperationStatusData, MessageOperationStatusError, MessageOperationStatusErrors, MessageOperationStatusResponse, MessageOperationStatusResponses, ParsedMessage, PatchSettingsData, PatchSettingsError, PatchSettingsErrors, PatchSettingsRequest, PatchSettingsResponse, PatchSettingsResponse2, PatchSettingsResponses, PreviewsInboxCursorData, PreviewsInboxCursorError, PreviewsInboxCursorErrors, PreviewsInboxCursorResponse, PreviewsInboxCursorResponses, PreviewView, PreviewViewStandardLabel, RecoverDraftTransferData, RecoverDraftTransferErrors, RecoverDraftTransferResponse, RecoverDraftTransferResponses, RefreshEmailEvent, RemoveDraftAttachmentData, RemoveDraftAttachmentError, RemoveDraftAttachmentErrors, RemoveDraftAttachmentResponse, RemoveDraftAttachmentResponses, RemoveForwardedAttachmentData, RemoveForwardedAttachmentError, RemoveForwardedAttachmentErrors, RemoveForwardedAttachmentResponse, RemoveForwardedAttachmentResponses, ResolveMessageOperationData, ResolveMessageOperationError, ResolveMessageOperationErrors, ResolveMessageOperationRequest, ResolveMessageOperationResponse, ResolveMessageOperationResponses, ResyncLinkData, ResyncLinkError, ResyncLinkErrors, ResyncLinkResponse, ResyncLinkResponses, ResyncResponse, ScheduledSendStatus, SendMessageData, SendMessageError, SendMessageErrors, SendMessageRequest, SendMessageResponse, SendMessageResponse2, SendMessageResponses, Settings, SharedInboxConflictResponse, SyncStatus, Thread, ThreadList, ThreadOperationsData, ThreadOperationsError, ThreadOperationsErrors, ThreadOperationsResponse, ThreadOperationsResponses, ThreadPreviewCursor, ThreadSeenData, ThreadSeenError, ThreadSeenErrors, ThreadSeenResponse, ThreadSeenResponses, ThreadStateField, ThreadSummary, TransferDraftData, TransferDraftErrors, TransferDraftRequest, TransferDraftResponse, TransferDraftResponse2, TransferDraftResponses, TransferRecoveryResponse, UnblockSenderData, UnblockSenderError, UnblockSenderErrors, UnblockSenderRequest, UnblockSenderResponse, UnblockSenderResponses, UnresolvedSignatureImagesError, UpdateLabelBatchRequest, UpdateLabelBatchResponse, UpdateThreadLabelRequest, UpdateThreadLabelsResponse, UpdateThreadProjectData, UpdateThreadProjectError, UpdateThreadProjectErrors, UpdateThreadProjectRequest, UpdateThreadProjectResponse, UpdateThreadProjectResponse2, UpdateThreadProjectResponses, UpdateThreadStateData, UpdateThreadStateError, UpdateThreadStateErrors, UpdateThreadStateRequest, UpdateThreadStateResponse, UpdateThreadStateResponses, UpsertEmailFilterData, UpsertEmailFilterError, UpsertEmailFilterErrors, UpsertEmailFilterRequest, UpsertEmailFilterResponse, UpsertEmailFilterResponse2, UpsertEmailFilterResponses, UpsertScheduledMessageData, UpsertScheduledMessageError, UpsertScheduledMessageErrors, UpsertScheduledMessageResponse, UpsertScheduledMessageResponses, UpsertScheduledRequest, UpsertScheduledResponse, UserProvider, Value, ViewerCapabilities } from './types.gen';
+export type { AccessLevel, AddDraftAttachmentData, AddDraftAttachmentError, AddDraftAttachmentErrors, AddDraftAttachmentRequest, AddDraftAttachmentResponse, AddDraftAttachmentResponse2, AddDraftAttachmentResponses, AddForwardedAttachmentData, AddForwardedAttachmentError, AddForwardedAttachmentErrors, AddForwardedAttachmentRequest, AddForwardedAttachmentResponse, AddForwardedAttachmentResponse2, AddForwardedAttachmentResponses, AddRemoveLabelData, AddRemoveLabelError, AddRemoveLabelErrors, AddRemoveLabelResponse, AddRemoveLabelResponses, AddRemoveThreadLabelData, AddRemoveThreadLabelError, AddRemoveThreadLabelErrors, AddRemoveThreadLabelResponse, AddRemoveThreadLabelResponses, ApiAttachment, ApiAttachmentDraft, ApiAttachmentForwarded, ApiContact, ApiContactInfo, ApiDraftContactInfo, ApiDraftInput, ApiDraftOutput, ApiEmailFilter, ApiLabel, ApiLabelListVisibility, ApiLabelType, ApiMessage, ApiMessageAttachment, ApiMessageLabel, ApiMessageListVisibility, ApiMessageOperation, ApiMessageOperationIssue, ApiMessageOperationState, ApiMessageResolutionAction, ApiPaginatedThreadCursor, ApiSortMethod, ApiThread, ApiThreadPreviewCursor, ApiThreadPreviewCursorInner, ArchiveThreadData, ArchiveThreadError, ArchiveThreadErrors, ArchiveThreadRequest, ArchiveThreadResponse, ArchiveThreadResponses, ArchiveThreadsData, ArchiveThreadsError, ArchiveThreadsErrors, ArchiveThreadsRequest, ArchiveThreadsResponse, ArchiveThreadsResponse2, ArchiveThreadsResponses, Attachment, AttachmentDraft, AttachmentForwarded, AttendeeResponseStatus, BackfillJob, BackfillJobStatus, BackfillStatus, BlockSenderData, BlockSenderError, BlockSenderErrors, BlockSenderRequest, BlockSenderResponses, CalendarAttendee, CalendarEvent, CalendarEventSourceContent, CalendarInvitation, CalendarMutationApiError, CalendarMutationErrorCode, CalendarOccurrence, CancelBackfillGmailData, CancelBackfillGmailError, CancelBackfillGmailErrors, CancelBackfillGmailResponse, CancelBackfillGmailResponses, CancelBackfillParams, ClientOptions, CompleteDraftAttachmentData, CompleteDraftAttachmentErrors, CompleteDraftAttachmentResponse, CompleteDraftAttachmentResponses, ConferenceProvider, Contact, ContactInfo, ContactInfoLegacy, ContactInfoWithInteraction, CopyCalendarEventRequest, CopyThreadCalendarInvitationData, CopyThreadCalendarInvitationError, CopyThreadCalendarInvitationErrors, CopyThreadCalendarInvitationResponse, CopyThreadCalendarInvitationResponses, CreateDraftData, CreateDraftError, CreateDraftErrors, CreateDraftRequest, CreateDraftResponse, CreateDraftResponse2, CreateDraftResponses, CreateLabelData, CreateLabelError, CreateLabelErrors, CreateLabelRequest, CreateLabelResponse, CreateLabelResponse2, CreateLabelResponses, DeleteDraftData, DeleteDraftError, DeleteDraftErrors, DeleteDraftResponse, DeleteDraftResponses, DeleteEmailFilterData, DeleteEmailFilterError, DeleteEmailFilterErrors, DeleteEmailFilterResponse, DeleteEmailFilterResponses, DeleteLabelData, DeleteLabelError, DeleteLabelErrors, DeleteLabelResponse, DeleteLabelResponses, DeleteLinkData, DeleteLinkError, DeleteLinkErrors, DeleteLinkResponse, DeleteLinkResponses, DeleteScheduledDraftData, DeleteScheduledDraftError, DeleteScheduledDraftErrors, DeleteScheduledDraftResponse, DeleteScheduledDraftResponses, DisableLinkCalendarData, DisableLinkCalendarError, DisableLinkCalendarErrors, DisableLinkCalendarResponse, DisableLinkCalendarResponses, DisableSyncData, DisableSyncError, DisableSyncErrors, DisableSyncResponse, DisableSyncResponses, EmlFile, EmptyResponse, ErrorResponse, EventReminderOverride, EventReminders, EventStatus, EventTime, EventTransparency, EventType, EventVisibility, ForwardCalendarEventData, ForwardCalendarEventError, ForwardCalendarEventError2, ForwardCalendarEventErrorCode, ForwardCalendarEventErrors, ForwardCalendarEventRecipient, ForwardCalendarEventRequest, ForwardCalendarEventResponse, ForwardCalendarEventResponse2, ForwardCalendarEventResponses, GetActiveBackfillJobResponse, GetAttachmentData, GetAttachmentDocumentIdData, GetAttachmentDocumentIdError, GetAttachmentDocumentIdErrors, GetAttachmentDocumentIdResponse, GetAttachmentDocumentIdResponse2, GetAttachmentDocumentIdResponses, GetAttachmentError, GetAttachmentErrors, GetAttachmentResponse, GetAttachmentResponse2, GetAttachmentResponses, GetBackfillGmailActiveData, GetBackfillGmailActiveError, GetBackfillGmailActiveErrors, GetBackfillGmailActiveResponse, GetBackfillGmailActiveResponses, GetBackfillGmailData, GetBackfillGmailError, GetBackfillGmailErrors, GetBackfillGmailResponse, GetBackfillGmailResponses, GetBackfillJobResponse, GetMessageData, GetMessageEmlData, GetMessageEmlError, GetMessageEmlErrors, GetMessageEmlResponse, GetMessageEmlResponses, GetMessageError, GetMessageErrors, GetMessageResponse, GetMessageResponses, GetMessagesBatchData, GetMessagesBatchError, GetMessagesBatchErrors, GetMessagesBatchResponse, GetMessagesBatchResponses, GetPreviewsCursorParams, GetReadReceiptPixelData, GetReadReceiptPixelResponses, GetScheduledMessagesData, GetScheduledMessagesError, GetScheduledMessagesErrors, GetScheduledMessagesResponse, GetScheduledMessagesResponses, GetScheduledResponse, GetThreadCalendarInvitationsData, GetThreadCalendarInvitationsErrors, GetThreadCalendarInvitationsResponse, GetThreadCalendarInvitationsResponses, GetThreadData, GetThreadError, GetThreadErrors, GetThreadMessagesHandlerData, GetThreadMessagesHandlerError, GetThreadMessagesHandlerErrors, GetThreadMessagesHandlerResponse, GetThreadMessagesHandlerResponses, GetThreadReadReceiptsData, GetThreadReadReceiptsErrors, GetThreadReadReceiptsResponse, GetThreadReadReceiptsResponses, GetThreadResponse, GetThreadResponse2, GetThreadResponses, GuestPolicy, HealthCheckLinksData, HealthCheckLinksError, HealthCheckLinksErrors, HealthCheckLinksResponse, HealthCheckLinksResponses, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, InitErrorCodeResponse, InitResponse, InitUserData, InitUserError, InitUserErrors, InitUserResponse, InitUserResponses, InvitationDateTime, InvitationMethod, InvitationParticipant, InvitationResolution, Label, LabelInfo, LabelListVisibility, LabelType, Link, ListBackfillGmailData, ListBackfillGmailError, ListBackfillGmailErrors, ListBackfillGmailResponse, ListBackfillGmailResponses, ListBackfillJobsResponse, ListBlockedResponse, ListBlockedSendersData, ListBlockedSendersError, ListBlockedSendersErrors, ListBlockedSendersResponse, ListBlockedSendersResponses, ListContactsData, ListContactsError, ListContactsErrors, ListContactsResponse, ListContactsResponse2, ListContactsResponses, ListEmailFiltersData, ListEmailFiltersError, ListEmailFiltersErrors, ListEmailFiltersResponse, ListEmailFiltersResponse2, ListEmailFiltersResponses, ListLabelsData, ListLabelsError, ListLabelsErrors, ListLabelsResponse, ListLabelsResponse2, ListLabelsResponses, ListLinksData, ListLinksError, ListLinksErrors, ListLinksResponse, ListLinksResponse2, ListLinksResponses, MailboxAction, MailboxOperation, MailboxOperationState, MailboxSettingsChange, MailboxSettingsOperation, MailboxSettingsOperationsData, MailboxSettingsOperationsResponse, MailboxSettingsOperationsResponses, Message, MessageListVisibility, MessageOperationResponse, MessageOperationStatusData, MessageOperationStatusError, MessageOperationStatusErrors, MessageOperationStatusResponse, MessageOperationStatusResponses, MessageReadReceipt, ParsedMessage, PatchSettingsData, PatchSettingsError, PatchSettingsErrors, PatchSettingsRequest, PatchSettingsResponse, PatchSettingsResponse2, PatchSettingsResponses, PreviewsInboxCursorData, PreviewsInboxCursorError, PreviewsInboxCursorErrors, PreviewsInboxCursorResponse, PreviewsInboxCursorResponses, PreviewView, PreviewViewStandardLabel, RecoverDraftTransferData, RecoverDraftTransferErrors, RecoverDraftTransferResponse, RecoverDraftTransferResponses, RefreshEmailEvent, RemoveDraftAttachmentData, RemoveDraftAttachmentError, RemoveDraftAttachmentErrors, RemoveDraftAttachmentResponse, RemoveDraftAttachmentResponses, RemoveForwardedAttachmentData, RemoveForwardedAttachmentError, RemoveForwardedAttachmentErrors, RemoveForwardedAttachmentResponse, RemoveForwardedAttachmentResponses, ResolveMessageOperationData, ResolveMessageOperationError, ResolveMessageOperationErrors, ResolveMessageOperationRequest, ResolveMessageOperationResponse, ResolveMessageOperationResponses, ResyncLinkData, ResyncLinkError, ResyncLinkErrors, ResyncLinkResponse, ResyncLinkResponses, ResyncResponse, ScheduledSendStatus, SendMessageData, SendMessageError, SendMessageErrors, SendMessageRequest, SendMessageResponse, SendMessageResponse2, SendMessageResponses, Settings, SharedInboxConflictResponse, SyncStatus, Thread, ThreadList, ThreadOperationsData, ThreadOperationsError, ThreadOperationsErrors, ThreadOperationsResponse, ThreadOperationsResponses, ThreadPreviewCursor, ThreadReadReceipts, ThreadSeenData, ThreadSeenError, ThreadSeenErrors, ThreadSeenResponse, ThreadSeenResponses, ThreadStateField, ThreadSummary, TransferDraftData, TransferDraftErrors, TransferDraftRequest, TransferDraftResponse, TransferDraftResponse2, TransferDraftResponses, TransferRecoveryResponse, UnblockSenderData, UnblockSenderError, UnblockSenderErrors, UnblockSenderRequest, UnblockSenderResponse, UnblockSenderResponses, UnresolvedSignatureImagesError, UpdateLabelBatchRequest, UpdateLabelBatchResponse, UpdateThreadLabelRequest, UpdateThreadLabelsResponse, UpdateThreadProjectData, UpdateThreadProjectError, UpdateThreadProjectErrors, UpdateThreadProjectRequest, UpdateThreadProjectResponse, UpdateThreadProjectResponse2, UpdateThreadProjectResponses, UpdateThreadStateData, UpdateThreadStateError, UpdateThreadStateErrors, UpdateThreadStateRequest, UpdateThreadStateResponse, UpdateThreadStateResponses, UpsertEmailFilterData, UpsertEmailFilterError, UpsertEmailFilterErrors, UpsertEmailFilterRequest, UpsertEmailFilterResponse, UpsertEmailFilterResponse2, UpsertEmailFilterResponses, UpsertScheduledMessageData, UpsertScheduledMessageError, UpsertScheduledMessageErrors, UpsertScheduledMessageResponse, UpsertScheduledMessageResponses, UpsertScheduledRequest, UpsertScheduledResponse, UserProvider, Value, ViewerCapabilities } from './types.gen';
diff --git a/packages/sdk/generated/email/sdk.gen.ts b/packages/sdk/generated/email/sdk.gen.ts
index 6ed66436fd..fc106e3ebf 100644
--- a/packages/sdk/generated/email/sdk.gen.ts
+++ b/packages/sdk/generated/email/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 { AddDraftAttachmentData, AddDraftAttachmentErrors, AddDraftAttachmentResponses, AddForwardedAttachmentData, AddForwardedAttachmentErrors, AddForwardedAttachmentResponses, AddRemoveLabelData, AddRemoveLabelErrors, AddRemoveLabelResponses, AddRemoveThreadLabelData, AddRemoveThreadLabelErrors, AddRemoveThreadLabelResponses, ArchiveThreadData, ArchiveThreadErrors, ArchiveThreadResponses, ArchiveThreadsData, ArchiveThreadsErrors, ArchiveThreadsResponses, BlockSenderData, BlockSenderErrors, BlockSenderResponses, CancelBackfillGmailData, CancelBackfillGmailErrors, CancelBackfillGmailResponses, CompleteDraftAttachmentData, CompleteDraftAttachmentErrors, CompleteDraftAttachmentResponses, CopyThreadCalendarInvitationData, CopyThreadCalendarInvitationErrors, CopyThreadCalendarInvitationResponses, CreateDraftData, CreateDraftErrors, CreateDraftResponses, CreateLabelData, CreateLabelErrors, CreateLabelResponses, DeleteDraftData, DeleteDraftErrors, DeleteDraftResponses, DeleteEmailFilterData, DeleteEmailFilterErrors, DeleteEmailFilterResponses, DeleteLabelData, DeleteLabelErrors, DeleteLabelResponses, DeleteLinkData, DeleteLinkErrors, DeleteLinkResponses, DeleteScheduledDraftData, DeleteScheduledDraftErrors, DeleteScheduledDraftResponses, DisableLinkCalendarData, DisableLinkCalendarErrors, DisableLinkCalendarResponses, DisableSyncData, DisableSyncErrors, DisableSyncResponses, ForwardCalendarEventData, ForwardCalendarEventErrors, ForwardCalendarEventResponses, GetAttachmentData, GetAttachmentDocumentIdData, GetAttachmentDocumentIdErrors, GetAttachmentDocumentIdResponses, GetAttachmentErrors, GetAttachmentResponses, GetBackfillGmailActiveData, GetBackfillGmailActiveErrors, GetBackfillGmailActiveResponses, GetBackfillGmailData, GetBackfillGmailErrors, GetBackfillGmailResponses, GetMessageData, GetMessageEmlData, GetMessageEmlErrors, GetMessageEmlResponses, GetMessageErrors, GetMessageResponses, GetMessagesBatchData, GetMessagesBatchErrors, GetMessagesBatchResponses, GetScheduledMessagesData, GetScheduledMessagesErrors, GetScheduledMessagesResponses, GetThreadCalendarInvitationsData, GetThreadCalendarInvitationsErrors, GetThreadCalendarInvitationsResponses, GetThreadData, GetThreadErrors, GetThreadMessagesHandlerData, GetThreadMessagesHandlerErrors, GetThreadMessagesHandlerResponses, GetThreadResponses, HealthCheckLinksData, HealthCheckLinksErrors, HealthCheckLinksResponses, HealthHandlerData, HealthHandlerResponses, InitUserData, InitUserErrors, InitUserResponses, ListBackfillGmailData, ListBackfillGmailErrors, ListBackfillGmailResponses, ListBlockedSendersData, ListBlockedSendersErrors, ListBlockedSendersResponses, ListContactsData, ListContactsErrors, ListContactsResponses, ListEmailFiltersData, ListEmailFiltersErrors, ListEmailFiltersResponses, ListLabelsData, ListLabelsErrors, ListLabelsResponses, ListLinksData, ListLinksErrors, ListLinksResponses, MailboxSettingsOperationsData, MailboxSettingsOperationsResponses, MessageOperationStatusData, MessageOperationStatusErrors, MessageOperationStatusResponses, PatchSettingsData, PatchSettingsErrors, PatchSettingsResponses, PreviewsInboxCursorData, PreviewsInboxCursorErrors, PreviewsInboxCursorResponses, RecoverDraftTransferData, RecoverDraftTransferErrors, RecoverDraftTransferResponses, RemoveDraftAttachmentData, RemoveDraftAttachmentErrors, RemoveDraftAttachmentResponses, RemoveForwardedAttachmentData, RemoveForwardedAttachmentErrors, RemoveForwardedAttachmentResponses, ResolveMessageOperationData, ResolveMessageOperationErrors, ResolveMessageOperationResponses, ResyncLinkData, ResyncLinkErrors, ResyncLinkResponses, SendMessageData, SendMessageErrors, SendMessageResponses, ThreadOperationsData, ThreadOperationsErrors, ThreadOperationsResponses, ThreadSeenData, ThreadSeenErrors, ThreadSeenResponses, TransferDraftData, TransferDraftErrors, TransferDraftResponses, UnblockSenderData, UnblockSenderErrors, UnblockSenderResponses, UpdateThreadProjectData, UpdateThreadProjectErrors, UpdateThreadProjectResponses, UpdateThreadStateData, UpdateThreadStateErrors, UpdateThreadStateResponses, UpsertEmailFilterData, UpsertEmailFilterErrors, UpsertEmailFilterResponses, UpsertScheduledMessageData, UpsertScheduledMessageErrors, UpsertScheduledMessageResponses } from './types.gen';
+import type { AddDraftAttachmentData, AddDraftAttachmentErrors, AddDraftAttachmentResponses, AddForwardedAttachmentData, AddForwardedAttachmentErrors, AddForwardedAttachmentResponses, AddRemoveLabelData, AddRemoveLabelErrors, AddRemoveLabelResponses, AddRemoveThreadLabelData, AddRemoveThreadLabelErrors, AddRemoveThreadLabelResponses, ArchiveThreadData, ArchiveThreadErrors, ArchiveThreadResponses, ArchiveThreadsData, ArchiveThreadsErrors, ArchiveThreadsResponses, BlockSenderData, BlockSenderErrors, BlockSenderResponses, CancelBackfillGmailData, CancelBackfillGmailErrors, CancelBackfillGmailResponses, CompleteDraftAttachmentData, CompleteDraftAttachmentErrors, CompleteDraftAttachmentResponses, CopyThreadCalendarInvitationData, CopyThreadCalendarInvitationErrors, CopyThreadCalendarInvitationResponses, CreateDraftData, CreateDraftErrors, CreateDraftResponses, CreateLabelData, CreateLabelErrors, CreateLabelResponses, DeleteDraftData, DeleteDraftErrors, DeleteDraftResponses, DeleteEmailFilterData, DeleteEmailFilterErrors, DeleteEmailFilterResponses, DeleteLabelData, DeleteLabelErrors, DeleteLabelResponses, DeleteLinkData, DeleteLinkErrors, DeleteLinkResponses, DeleteScheduledDraftData, DeleteScheduledDraftErrors, DeleteScheduledDraftResponses, DisableLinkCalendarData, DisableLinkCalendarErrors, DisableLinkCalendarResponses, DisableSyncData, DisableSyncErrors, DisableSyncResponses, ForwardCalendarEventData, ForwardCalendarEventErrors, ForwardCalendarEventResponses, GetAttachmentData, GetAttachmentDocumentIdData, GetAttachmentDocumentIdErrors, GetAttachmentDocumentIdResponses, GetAttachmentErrors, GetAttachmentResponses, GetBackfillGmailActiveData, GetBackfillGmailActiveErrors, GetBackfillGmailActiveResponses, GetBackfillGmailData, GetBackfillGmailErrors, GetBackfillGmailResponses, GetMessageData, GetMessageEmlData, GetMessageEmlErrors, GetMessageEmlResponses, GetMessageErrors, GetMessageResponses, GetMessagesBatchData, GetMessagesBatchErrors, GetMessagesBatchResponses, GetReadReceiptPixelData, GetReadReceiptPixelResponses, GetScheduledMessagesData, GetScheduledMessagesErrors, GetScheduledMessagesResponses, GetThreadCalendarInvitationsData, GetThreadCalendarInvitationsErrors, GetThreadCalendarInvitationsResponses, GetThreadData, GetThreadErrors, GetThreadMessagesHandlerData, GetThreadMessagesHandlerErrors, GetThreadMessagesHandlerResponses, GetThreadReadReceiptsData, GetThreadReadReceiptsErrors, GetThreadReadReceiptsResponses, GetThreadResponses, HealthCheckLinksData, HealthCheckLinksErrors, HealthCheckLinksResponses, HealthHandlerData, HealthHandlerResponses, InitUserData, InitUserErrors, InitUserResponses, ListBackfillGmailData, ListBackfillGmailErrors, ListBackfillGmailResponses, ListBlockedSendersData, ListBlockedSendersErrors, ListBlockedSendersResponses, ListContactsData, ListContactsErrors, ListContactsResponses, ListEmailFiltersData, ListEmailFiltersErrors, ListEmailFiltersResponses, ListLabelsData, ListLabelsErrors, ListLabelsResponses, ListLinksData, ListLinksErrors, ListLinksResponses, MailboxSettingsOperationsData, MailboxSettingsOperationsResponses, MessageOperationStatusData, MessageOperationStatusErrors, MessageOperationStatusResponses, PatchSettingsData, PatchSettingsErrors, PatchSettingsResponses, PreviewsInboxCursorData, PreviewsInboxCursorErrors, PreviewsInboxCursorResponses, RecoverDraftTransferData, RecoverDraftTransferErrors, RecoverDraftTransferResponses, RemoveDraftAttachmentData, RemoveDraftAttachmentErrors, RemoveDraftAttachmentResponses, RemoveForwardedAttachmentData, RemoveForwardedAttachmentErrors, RemoveForwardedAttachmentResponses, ResolveMessageOperationData, ResolveMessageOperationErrors, ResolveMessageOperationResponses, ResyncLinkData, ResyncLinkErrors, ResyncLinkResponses, SendMessageData, SendMessageErrors, SendMessageResponses, ThreadOperationsData, ThreadOperationsErrors, ThreadOperationsResponses, ThreadSeenData, ThreadSeenErrors, ThreadSeenResponses, TransferDraftData, TransferDraftErrors, TransferDraftResponses, UnblockSenderData, UnblockSenderErrors, UnblockSenderResponses, UpdateThreadProjectData, UpdateThreadProjectErrors, UpdateThreadProjectResponses, UpdateThreadStateData, UpdateThreadStateErrors, UpdateThreadStateResponses, UpsertEmailFilterData, UpsertEmailFilterErrors, UpsertEmailFilterResponses, UpsertScheduledMessageData, UpsertScheduledMessageErrors, UpsertScheduledMessageResponses } from './types.gen';
export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown> = Options2<TData, ThrowOnError, TResponse> & {
/**
@@ -638,10 +638,22 @@ export class Sdk extends HeyApiClient {
});
}
+ public getThreadReadReceipts<ThrowOnError extends boolean = false>(options: Options<GetThreadReadReceiptsData, ThrowOnError>): RequestResult<GetThreadReadReceiptsResponses, GetThreadReadReceiptsErrors, ThrowOnError> {
+ return (options.client ?? this.client).get<GetThreadReadReceiptsResponses, GetThreadReadReceiptsErrors, ThrowOnError>({ url: '/email/threads/{thread_id}/read-receipts', ...options });
+ }
+
/**
* Health check
*/
public healthHandler<ThrowOnError extends boolean = false>(options?: Options<HealthHandlerData, ThrowOnError>): RequestResult<HealthHandlerResponses, unknown, ThrowOnError> {
return (options?.client ?? this.client).get<HealthHandlerResponses, unknown, ThrowOnError>({ url: '/health', ...options });
}
+
+ /**
+ * Every request gets the same uncacheable pixel so the response reveals nothing
+ * about the token, and each open reaches the server.
+ */
+ public getReadReceiptPixel<ThrowOnError extends boolean = false>(options: Options<GetReadReceiptPixelData, ThrowOnError>): RequestResult<GetReadReceiptPixelResponses, unknown, ThrowOnError> {
+ return (options.client ?? this.client).get<GetReadReceiptPixelResponses, unknown, ThrowOnError>({ url: '/opens/{token}', ...options });
+ }
}
diff --git a/packages/sdk/generated/email/types.gen.ts b/packages/sdk/generated/email/types.gen.ts
index 32c1d1b869..ab1573863b 100644
--- a/packages/sdk/generated/email/types.gen.ts
+++ b/packages/sdk/generated/email/types.gen.ts
@@ -1659,6 +1659,28 @@ export type MessageOperationResponse = {
operation?: null | ApiMessageOperation;
};
+/**
+ * Open state of one tracked, sent message.
+ */
+export type MessageReadReceipt = {
+ /**
+ * First counted fetch.
+ */
+ first_opened_at?: string | null;
+ /**
+ * Latest counted fetch.
+ */
+ last_opened_at?: string | null;
+ /**
+ * The tracked message.
+ */
+ message_id: string;
+ /**
+ * Counted pixel fetches.
+ */
+ open_count: number;
+};
+
export type ParsedMessage = {
bcc: Array<ContactInfo>;
body_parsed?: string | null;
@@ -1774,6 +1796,10 @@ export type SendMessageResponse = {
};
export type Settings = {
+ /**
+ * Whether messages sent from this inbox carry an open-tracking pixel.
+ */
+ read_receipts_enabled?: boolean | null;
/**
* The user's email signature content (HTML). On a patch, omit or send
* `null` to leave unchanged (both deserialize to `None`); pass an empty
@@ -1853,6 +1879,13 @@ export type ThreadPreviewCursor = {
viewedAt?: string | null;
};
+/**
+ * Open state of the caller's tracked, sent messages in one thread.
+ */
+export type ThreadReadReceipts = {
+ receipts: Array<MessageReadReceipt>;
+};
+
/**
* Semantic mailbox facts, independent of folder/category names.
*/
@@ -3586,6 +3619,29 @@ export type UpdateThreadProjectResponses = {
export type UpdateThreadProjectResponse2 = UpdateThreadProjectResponses[keyof UpdateThreadProjectResponses];
+export type GetThreadReadReceiptsData = {
+ body?: never;
+ path: {
+ /**
+ * Authorized email thread
+ */
+ thread_id: string;
+ };
+ query?: never;
+ url: '/email/threads/{thread_id}/read-receipts';
+};
+
+export type GetThreadReadReceiptsErrors = {
+ 401: unknown;
+ 403: unknown;
+};
+
+export type GetThreadReadReceiptsResponses = {
+ 200: ThreadReadReceipts;
+};
+
+export type GetThreadReadReceiptsResponse = GetThreadReadReceiptsResponses[keyof GetThreadReadReceiptsResponses];
+
export type HealthHandlerData = {
body?: never;
path?: never;
@@ -3601,3 +3657,22 @@ export type HealthHandlerResponses = {
};
export type HealthHandlerResponse = HealthHandlerResponses[keyof HealthHandlerResponses];
+
+export type GetReadReceiptPixelData = {
+ body?: never;
+ path: {
+ /**
+ * Opaque pixel token
+ */
+ token: string;
+ };
+ query?: never;
+ url: '/opens/{token}';
+};
+
+export type GetReadReceiptPixelResponses = {
+ /**
+ * Transparent pixel, for any token
+ */
+ 200: unknown;
+};
diff --git a/packages/sdk/specs/email.json b/packages/sdk/specs/email.json
index 1fcd7389c8..fe30d6a7e6 100644
--- a/packages/sdk/specs/email.json
+++ b/packages/sdk/specs/email.json
@@ -3871,6 +3871,42 @@
}
}
},
+ "/email/threads/{thread_id}/read-receipts": {
+ "get": {
+ "tags": ["email"],
+ "operationId": "get_thread_read_receipts",
+ "parameters": [
+ {
+ "name": "thread_id",
+ "in": "path",
+ "description": "Authorized email thread",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ThreadReadReceipts"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": ""
+ },
+ "403": {
+ "description": ""
+ }
+ }
+ }
+ },
"/health": {
"get": {
"tags": ["Health"],
@@ -3889,6 +3925,32 @@
}
}
}
+ },
+ "/opens/{token}": {
+ "get": {
+ "tags": ["email"],
+ "summary": "Every request gets the same uncacheable pixel so the response reveals nothing\nabout the token, and each open reaches the server.",
+ "operationId": "get_read_receipt_pixel",
+ "parameters": [
+ {
+ "name": "token",
+ "in": "path",
+ "description": "Opaque pixel token",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "Transparent pixel, for any token",
+ "content": {
+ "image/gif": {}
+ }
+ }
+ }
+ }
}
},
"components": {
@@ -6949,6 +7011,34 @@
}
}
},
+ "MessageReadReceipt": {
+ "type": "object",
+ "description": "Open state of one tracked, sent message.",
+ "required": ["message_id", "open_count"],
+ "properties": {
+ "first_opened_at": {
+ "type": ["string", "null"],
+ "format": "date-time",
+ "description": "First counted fetch."
+ },
+ "last_opened_at": {
+ "type": ["string", "null"],
+ "format": "date-time",
+ "description": "Latest counted fetch."
+ },
+ "message_id": {
+ "type": "string",
+ "format": "uuid",
+ "description": "The tracked message."
+ },
+ "open_count": {
+ "type": "integer",
+ "format": "int32",
+ "description": "Counted pixel fetches.",
+ "minimum": 0
+ }
+ }
+ },
"ParsedMessage": {
"type": "object",
"required": [
@@ -7270,6 +7360,10 @@
"Settings": {
"type": "object",
"properties": {
+ "read_receipts_enabled": {
+ "type": ["boolean", "null"],
+ "description": "Whether messages sent from this inbox carry an open-tracking pixel."
+ },
"signature": {
"type": ["string", "null"],
"description": "The user's email signature content (HTML). On a patch, omit or send\n`null` to leave unchanged (both deserialize to `None`); pass an empty\nstring to clear it. The column cannot be set to SQL NULL via patch."
@@ -7464,6 +7558,19 @@
}
}
},
+ "ThreadReadReceipts": {
+ "type": "object",
+ "description": "Open state of the caller's tracked, sent messages in one thread.",
+ "required": ["receipts"],
+ "properties": {
+ "receipts": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/MessageReadReceipt"
+ }
+ }
+ }
+ },
"ThreadStateField": {
"type": "string",
"description": "Semantic mailbox facts, independent of folder/category names.",
diff --git a/packages/sdk/src/coverage/skipped.ts b/packages/sdk/src/coverage/skipped.ts
index ab41cae43e..0888096efa 100644
--- a/packages/sdk/src/coverage/skipped.ts
+++ b/packages/sdk/src/coverage/skipped.ts
@@ -234,6 +234,7 @@ export const emailExcluded = [
'getBackfillGmail',
'getBackfillGmailActive',
'getMessagesBatch',
+ 'getReadReceiptPixel',
'healthCheckLinks',
'healthHandler',
'initUser',
diff --git a/packages/sdk/src/entities/email/thread.ts b/packages/sdk/src/entities/email/thread.ts
index b0afbc7e3a..14c60bdd75 100644
--- a/packages/sdk/src/entities/email/thread.ts
+++ b/packages/sdk/src/entities/email/thread.ts
@@ -42,6 +42,21 @@ export interface ReplyEmailOptions {
replyingTo?: EmailMessage;
}
+/** Open tracking for one of the caller's sent messages. */
+export interface EmailReadReceipt {
+ /** The tracked message. */
+ message: EmailMessage;
+
+ /** Counted pixel fetches; repeats within a few seconds count once. */
+ openCount: number;
+
+ /** When the first counted fetch happened, if any. */
+ firstOpenedAt?: string;
+
+ /** When the latest counted fetch happened, if any. */
+ lastOpenedAt?: string;
+}
+
/**
* An email thread. A free-to-construct handle: the detail record (including
* up to the first 100 messages) loads lazily on first field access.
@@ -108,6 +123,25 @@ export class EmailThread extends PropertiedEntity<ThreadDetail> {
return CalendarEvent.fromRecord(this.client, record);
}
+ /**
+ * Opens recorded for messages sent from the caller's own or delegated
+ * inboxes with read receipts on, newest message first. Counts are
+ * approximate: some mail apps prefetch images and others block them.
+ */
+ async readReceipts(): Promise<EmailReadReceipt[]> {
+ const { receipts } = unwrap(
+ await this.client.email.getThreadReadReceipts({
+ path: { thread_id: this.id },
+ }),
+ );
+ return receipts.map((receipt) => ({
+ message: EmailMessage.byId(this.client, receipt.message_id),
+ openCount: receipt.open_count,
+ firstOpenedAt: receipt.first_opened_at ?? undefined,
+ lastOpenedAt: receipt.last_opened_at ?? undefined,
+ }));
+ }
+
/** Change project membership or share permissions for this thread. */
async update(options: {
project?: Project | null;
diff --git a/packages/sdk/tests/email-read-receipts.test.ts b/packages/sdk/tests/email-read-receipts.test.ts
new file mode 100644
index 0000000000..d1be89ec1b
--- /dev/null
+++ b/packages/sdk/tests/email-read-receipts.test.ts
@@ -0,0 +1,61 @@
+import { afterEach, expect, mock, spyOn, test } from 'bun:test';
+import type { ThreadReadReceipts } from '../generated/email/types.gen';
+import { EmailMessage } from '../src/entities/email/message';
+import { Macro } from '../src/macro';
+
+afterEach(() => mock.restore());
+
+const threadId = '0198a4cc-e138-7670-a308-a6b766602710';
+const receipts: ThreadReadReceipts = {
+ receipts: [
+ {
+ message_id: '0198a4cc-e138-7670-a308-a6b766602711',
+ open_count: 2,
+ first_opened_at: '2026-10-20T09:15:00Z',
+ last_opened_at: '2026-10-21T16:40:00Z',
+ },
+ {
+ message_id: '0198a4cc-e138-7670-a308-a6b766602712',
+ open_count: 0,
+ first_opened_at: null,
+ last_opened_at: null,
+ },
+ ],
+};
+
+test('thread read receipts return message handles with camelCase fields', async () => {
+ const requests: Request[] = [];
+ spyOn(globalThis, 'fetch').mockImplementation(
+ Object.assign(
+ async (input: Parameters<typeof fetch>[0]) => {
+ const request = input instanceof Request ? input : new Request(input);
+ requests.push(request);
+ return Response.json(receipts);
+ },
+ { preconnect: globalThis.fetch.preconnect },
+ ),
+ );
+ const macro = new Macro({
+ auth: { type: 'user', apiKey: 'mak_test' },
+ hosts: { email: 'https://email.example.test' },
+ });
+
+ const result = await macro.email.byId(threadId).readReceipts();
+
+ expect(new URL(requests[0].url).pathname).toBe(
+ `/email/threads/${threadId}/read-receipts`,
+ );
+ expect(result.every((r) => r.message instanceof EmailMessage)).toBe(true);
+ expect(result.map((r) => r.message.id)).toEqual([
+ '0198a4cc-e138-7670-a308-a6b766602711',
+ '0198a4cc-e138-7670-a308-a6b766602712',
+ ]);
+ expect(result[0]).toMatchObject({
+ openCount: 2,
+ firstOpenedAt: '2026-10-20T09:15:00Z',
+ lastOpenedAt: '2026-10-21T16:40:00Z',
+ });
+ expect(result[1].openCount).toBe(0);
+ expect(result[1].firstOpenedAt).toBeUndefined();
+ expect(result[1].lastOpenedAt).toBeUndefined();
+});
diff --git a/services/email_service/AGENTS.md b/services/email_service/AGENTS.md
index 068eb2b90b..b6abda9bfb 100644
--- a/services/email_service/AGENTS.md
+++ b/services/email_service/AGENTS.md
@@ -158,6 +158,11 @@ the gateway `/email` prefix.
visibility while processing. Don't raise its receive batch: messages queued
behind a long mailbox purge would be redelivered and purged twice.
`PurgePacing` (`email_db_client::links::delete`) sets the purge's write rate.
+- `GET /opens/{token}` is public and must return the same uncacheable GIF for
+ every token. Gmail sends add the pixel only to the provider copy in
+ `outbound/scheduled_delivery.rs`; Outlook adds it through the materializer
+ wrapper in the `pubsub_workers` binary. Pixels use `EmailServiceUrl`, so the
+ local Docker stack embeds an in-network host recipients cannot load.
## Related
diff --git a/services/email_service/src/api.rs b/services/email_service/src/api.rs
index 8990473282..2efe746ae4 100644
--- a/services/email_service/src/api.rs
+++ b/services/email_service/src/api.rs
@@ -1,5 +1,6 @@
mod calendar_event_forward;
mod calendar_invitations;
+pub(crate) mod read_receipts;
use anyhow::Context;
use axum::Router;
use context::ApiContext;
@@ -81,6 +82,12 @@ fn api_router(state: ApiContext) -> Router<ApiContext> {
"/email/calendar-events/{event_id}/forward",
axum::routing::post(calendar_event_forward::handler),
)
+ .route(
+ "/email/threads/{thread_id}/read-receipts",
+ axum::routing::get(read_receipts::thread),
+ )
+ // Fetched by recipients' mail clients, so it takes no credentials.
+ .route("/opens/{token}", axum::routing::get(read_receipts::pixel))
.nest("/email", email::router(state))
.nest("/gmail", gmail::router())
.nest("/outlook", outlook::router())
diff --git a/services/email_service/src/api/context.rs b/services/email_service/src/api/context.rs
index 0e0d30c984..701f604a98 100644
--- a/services/email_service/src/api/context.rs
+++ b/services/email_service/src/api/context.rs
@@ -149,6 +149,7 @@ pub(crate) struct ApiContext {
>,
>,
pub mailbox_initializer: Arc<MailboxInitializer>,
+ pub read_receipts: crate::composition::ReadReceipts,
pub invitation_snapshots: email::outbound::invitation_pg::InvitationPgRepository,
pub invitation_resolver: Arc<
calendar_events::domain::invitations::CalendarInvitationResolver<
diff --git a/services/email_service/src/api/email/settings/import_signature.rs b/services/email_service/src/api/email/settings/import_signature.rs
index c471e455a0..3711f76f38 100644
--- a/services/email_service/src/api/email/settings/import_signature.rs
+++ b/services/email_service/src/api/email/settings/import_signature.rs
@@ -125,6 +125,7 @@ pub async fn import_signature_handler(
api::settings::Settings {
signature: Some(sanitized_signature),
signature_on_replies_forwards: None,
+ read_receipts_enabled: None,
},
link.id,
);
diff --git a/services/email_service/src/api/read_receipts.rs b/services/email_service/src/api/read_receipts.rs
new file mode 100644
index 0000000000..cb44d269a4
--- /dev/null
+++ b/services/email_service/src/api/read_receipts.rs
@@ -0,0 +1,73 @@
+//! Public open-tracking pixel and the authorized per-thread read path.
+use super::context::{ApiContext, AuthorizationService, EmailEntityAccessService};
+use axum::{
+ Json,
+ extract::{Path, State},
+ http::{StatusCode, header},
+ response::IntoResponse,
+};
+use email::domain::read_receipts::{MessageReadReceipt, ReadReceiptError};
+use entity_access::{
+ domain::models::ViewAccessLevel, inbound::axum_extractors::ThreadAccessLevelExtractor,
+};
+
+/// A 1×1 transparent GIF.
+const PIXEL_GIF: &[u8] = &[
+ 0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 0x01, 0x00, 0x01, 0x00, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0xff, 0xff, 0xff, 0x21, 0xf9, 0x04, 0x01, 0x00, 0x00, 0x00, 0x00, 0x2c, 0x00, 0x00, 0x00, 0x00,
+ 0x01, 0x00, 0x01, 0x00, 0x00, 0x02, 0x02, 0x44, 0x01, 0x00, 0x3b,
+];
+
+/// Every request gets the same uncacheable pixel so the response reveals nothing
+/// about the token, and each open reaches the server.
+#[utoipa::path(get, path = "/opens/{token}", tag = "email",
+ operation_id = "get_read_receipt_pixel",
+ params(("token" = String, Path, description = "Opaque pixel token")),
+ responses((status = 200, content_type = "image/gif", description = "Transparent pixel, for any token")))]
+pub(crate) async fn pixel(
+ State(state): State<ApiContext>,
+ Path(token): Path<String>,
+) -> impl IntoResponse {
+ let _ = state.read_receipts.record_open(&token).await;
+ (
+ [
+ (header::CONTENT_TYPE, "image/gif"),
+ (
+ header::CACHE_CONTROL,
+ "no-store, no-cache, must-revalidate, private, max-age=0",
+ ),
+ (header::PRAGMA, "no-cache"),
+ (header::EXPIRES, "0"),
+ ],
+ PIXEL_GIF,
+ )
+}
+
+/// Open state of the caller's tracked, sent messages in one thread.
+#[derive(serde::Serialize, utoipa::ToSchema)]
+pub(crate) struct ThreadReadReceipts {
+ receipts: Vec<MessageReadReceipt>,
+}
+
+#[utoipa::path(get, path = "/email/threads/{thread_id}/read-receipts", tag = "email",
+ operation_id = "get_thread_read_receipts",
+ params(("thread_id" = uuid::Uuid, Path, description = "Authorized email thread")),
+ responses((status = 200, body = ThreadReadReceipts), (status = 401), (status = 403)))]
+pub(crate) async fn thread(
+ State(state): State<ApiContext>,
+ access: ThreadAccessLevelExtractor<
+ ViewAccessLevel,
+ EmailEntityAccessService,
+ AuthorizationService,
+ >,
+) -> Result<Json<ThreadReadReceipts>, StatusCode> {
+ state
+ .read_receipts
+ .thread_receipts(access.entity_access_receipt)
+ .await
+ .map(|receipts| Json(ThreadReadReceipts { receipts }))
+ .map_err(|error| match error {
+ ReadReceiptError::Unauthorized => StatusCode::UNAUTHORIZED,
+ ReadReceiptError::Internal(_) => StatusCode::INTERNAL_SERVER_ERROR,
+ })
+}
diff --git a/services/email_service/src/api/swagger.rs b/services/email_service/src/api/swagger.rs
index 0e85061015..162eee3ba2 100644
--- a/services/email_service/src/api/swagger.rs
+++ b/services/email_service/src/api/swagger.rs
@@ -66,6 +66,8 @@ use utoipa::OpenApi;
crate::api::calendar_invitations::handler,
crate::api::calendar_invitations::copy_handler,
crate::api::calendar_event_forward::handler,
+ crate::api::read_receipts::pixel,
+ crate::api::read_receipts::thread,
health::health_handler,
email::attachments::get::handler,
email::attachments::get_document_id::handler,
diff --git a/services/email_service/src/bin/pubsub_workers/pubsub_workers.rs b/services/email_service/src/bin/pubsub_workers/pubsub_workers.rs
index 2d8ae35d49..fc4629b6dc 100644
--- a/services/email_service/src/bin/pubsub_workers/pubsub_workers.rs
+++ b/services/email_service/src/bin/pubsub_workers/pubsub_workers.rs
@@ -496,11 +496,15 @@ async fn main() -> anyhow::Result<()> {
},
worker_cancellation_token.clone(),
));
+ let read_receipts = email_service::composition::read_receipts(db.clone(), env)?;
worker_tracker.spawn(email_service::mailbox_sync_worker::run_drafts(
email::domain::mailbox::drafts::MailboxDraftService::new(
mailbox_repository.clone(),
email_service::outbound::email_api::ProviderMailboxGateway(outlook_api.clone()),
- draft_content.clone(),
+ email::domain::read_receipts::ReadReceiptMaterializer::new(
+ draft_content.clone(),
+ read_receipts.clone(),
+ ),
)
.with_writes_enabled(config.outlook_writes_enabled),
worker_cancellation_token.clone(),
@@ -769,6 +773,7 @@ async fn main() -> anyhow::Result<()> {
s3_client: s3_client_scheduled,
attachment_bucket: attachment_bucket_scheduled,
macro_event_broker: macro_event_broker_scheduled,
+ read_receipts,
},
cancellation_token,
)
diff --git a/services/email_service/src/composition.rs b/services/email_service/src/composition.rs
index 5be460b72f..876618120c 100644
--- a/services/email_service/src/composition.rs
+++ b/services/email_service/src/composition.rs
@@ -72,3 +72,19 @@ pub fn inbox_health(
},
)
}
+
+pub type ReadReceipts = email::domain::read_receipts::ReadReceiptService<
+ email::outbound::read_receipts_pg::ReadReceiptPgRepository,
+>;
+
+/// Pixels point at this service's public URL, which serves `/opens/{token}`.
+pub fn read_receipts(
+ db: sqlx::PgPool,
+ environment: macro_env::Environment,
+) -> anyhow::Result<ReadReceipts> {
+ let base = macro_service_urls::EmailServiceUrl::new_for_environment(environment)?;
+ Ok(email::domain::read_receipts::ReadReceiptService::new(
+ email::outbound::read_receipts_pg::ReadReceiptPgRepository(db),
+ email::domain::read_receipts::PixelUrlPrefix::new(base.as_str()),
+ ))
+}
diff --git a/services/email_service/src/outbound/scheduled_delivery.rs b/services/email_service/src/outbound/scheduled_delivery.rs
index fc28f9c0b4..34465d7888 100644
--- a/services/email_service/src/outbound/scheduled_delivery.rs
+++ b/services/email_service/src/outbound/scheduled_delivery.rs
@@ -40,6 +40,9 @@ pub struct ScheduledDeliveryAdapter {
pub s3_client: s3_client::S3,
pub attachment_bucket: String,
pub macro_event_broker: MacroEventBrokerService<KafkaEventPublisher, TaskTracker>,
+ pub read_receipts: email::domain::read_receipts::ReadReceiptService<
+ email::outbound::read_receipts_pg::ReadReceiptPgRepository,
+ >,
}
/// Context obtained only by winning an atomic database claim.
@@ -371,10 +374,20 @@ impl ScheduledDeliveryAdapter {
duration_ms = started.elapsed().as_millis() as u64,
"approved email attachments prepared"
);
+ // Only the provider copy carries the pixel; sync brings it back later.
+ let mut outgoing = message.clone();
+ outgoing.body_html = self
+ .read_receipts
+ .tracked_html(
+ claim.link.id,
+ data.message_id,
+ outgoing.body_html.as_deref(),
+ )
+ .await;
tracing::Span::current().record("phase", "mime_and_credentials");
let started = Instant::now();
let request = SendRequest {
- message: message.clone(),
+ message: outgoing,
from: sender_contact,
parent_message_id,
references,
diff --git a/services/email_service/src/pubsub/scheduled/context.rs b/services/email_service/src/pubsub/scheduled/context.rs
index 1bce1a853e..5c128ed60e 100644
--- a/services/email_service/src/pubsub/scheduled/context.rs
+++ b/services/email_service/src/pubsub/scheduled/context.rs
@@ -12,6 +12,7 @@ pub struct ScheduledContext {
pub s3_client: s3_client::S3,
pub attachment_bucket: String,
pub macro_event_broker: PubSubEventBroker,
+ pub read_receipts: crate::composition::ReadReceipts,
}
impl ScheduledContext {
@@ -32,6 +33,7 @@ impl ScheduledContext {
s3_client: self.s3_client.clone(),
attachment_bucket: self.attachment_bucket.clone(),
macro_event_broker: self.macro_event_broker.clone(),
+ read_receipts: self.read_receipts.clone(),
}
}
}
diff --git a/services/email_service/src/pubsub/scheduled/worker.rs b/services/email_service/src/pubsub/scheduled/worker.rs
index 4913be2472..8c7e067f6c 100644
--- a/services/email_service/src/pubsub/scheduled/worker.rs
+++ b/services/email_service/src/pubsub/scheduled/worker.rs
@@ -8,6 +8,10 @@ use sqlx::PgPool;
use tokio_util::sync::CancellationToken;
/// method that ingests sqs messages and calls the process function for each
+#[expect(
+ clippy::too_many_arguments,
+ reason = "mirrors the ScheduledContext fields"
+)]
pub async fn run_worker(
worker: sqs_worker::SQSWorker,
db: PgPool,
@@ -18,6 +22,7 @@ pub async fn run_worker(
s3_client: s3_client::S3,
attachment_bucket: String,
macro_event_broker: PubSubEventBroker,
+ read_receipts: crate::composition::ReadReceipts,
) {
run_worker_with_cancellation(
ScheduledContext {
@@ -28,6 +33,7 @@ pub async fn run_worker(
s3_client,
attachment_bucket,
macro_event_broker,
+ read_receipts,
},
CancellationToken::new(),
)
diff --git a/services/email_service/src/server.rs b/services/email_service/src/server.rs
index e21334e423..d7f14b29a7 100644
--- a/services/email_service/src/server.rs
+++ b/services/email_service/src/server.rs
@@ -390,6 +390,7 @@ pub async fn run() -> anyhow::Result<()> {
)
.with_connections_enabled(config.outlook_connections_enabled),
),
+ read_receipts: crate::composition::read_receipts(db.clone(), env)?,
invitation_snapshots: email::outbound::invitation_pg::InvitationPgRepository(db.clone()),
// calendar_service's sync kill switch rejects RSVP writes itself.
invitation_resolver: Arc::new(CalendarInvitationResolver::new(PgCalendarRepository::new(