Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(whatsapp): add disappearing, community and direct chats to Macro (#8729)
Wolf Mermelstein4b72fb700125
diff --git a/.sqlx/query-ba40979be74986251c332eb8a01123f5897d48baba2801111b08a4d356d948c6.json b/.sqlx/query-07e87b3e4c647003f48d8e7069d13cefd058b0e76e5a6916d3a78c60782a7554.jsonsimilarity index 51%rename from .sqlx/query-ba40979be74986251c332eb8a01123f5897d48baba2801111b08a4d356d948c6.jsonrename to .sqlx/query-07e87b3e4c647003f48d8e7069d13cefd058b0e76e5a6916d3a78c60782a7554.jsonindex 72e03bb720..51de495444 100644--- a/.sqlx/query-ba40979be74986251c332eb8a01123f5897d48baba2801111b08a4d356d948c6.json+++ b/.sqlx/query-07e87b3e4c647003f48d8e7069d13cefd058b0e76e5a6916d3a78c60782a7554.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "INSERT INTO whatsapp_media_blob (document_id, group_id, user_id, mime, filename, sha256, bytes)\n VALUES ($1, $2, $3, $4, $5, $6, $7)",+ "query": "INSERT INTO whatsapp_media_blob (document_id, group_id, user_id, mime, filename, sha256, bytes, width, height, duration_seconds)\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)","describe": {"columns": [],"parameters": {@@ -11,10 +11,13 @@"Text","Text","Bytea",- "Bytea"+ "Bytea",+ "Int4",+ "Int4",+ "Int4"]},"nullable": []},- "hash": "ba40979be74986251c332eb8a01123f5897d48baba2801111b08a4d356d948c6"+ "hash": "07e87b3e4c647003f48d8e7069d13cefd058b0e76e5a6916d3a78c60782a7554"}diff --git a/.sqlx/query-085ce27dd33eb6e55bca93a8859190f42b32c236c605b5c22fcc2fb762def411.json b/.sqlx/query-085ce27dd33eb6e55bca93a8859190f42b32c236c605b5c22fcc2fb762def411.jsondeleted file mode 100644index 55266fddee..0000000000--- a/.sqlx/query-085ce27dd33eb6e55bca93a8859190f42b32c236c605b5c22fcc2fb762def411.json+++ /dev/null@@ -1,59 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "SELECT g.id,g.name,g.user_id,g.backfill_state,g.backfill_imported,\n (SELECT count(*) FROM whatsapp_group_message m WHERE m.binding_id = g.id AND m.message_id IS NOT NULL\n AND m.deleted_at IS NULL AND m.origin <> 'history' AND m.kind <> 'system'\n AND NOT EXISTS (SELECT 1 FROM whatsapp_external_person p WHERE p.id = m.person_id AND p.user_id = $2)\n AND (r.message_id IS NULL OR (m.source_at,m.id) > (r.read_at,r.message_id))) AS \"unread_count!\",\n (SELECT max(source_at) FROM whatsapp_group_message WHERE binding_id = g.id AND message_id IS NOT NULL) AS last_message_at\n FROM whatsapp_group g LEFT JOIN whatsapp_group_read_state r ON r.group_id = g.id AND r.user_id = $2\n WHERE g.id = $1",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "id",- "type_info": "Uuid"- },- {- "ordinal": 1,- "name": "name",- "type_info": "Text"- },- {- "ordinal": 2,- "name": "user_id",- "type_info": "Text"- },- {- "ordinal": 3,- "name": "backfill_state",- "type_info": "Text"- },- {- "ordinal": 4,- "name": "backfill_imported",- "type_info": "Int4"- },- {- "ordinal": 5,- "name": "unread_count!",- "type_info": "Int8"- },- {- "ordinal": 6,- "name": "last_message_at",- "type_info": "Timestamptz"- }- ],- "parameters": {- "Left": [- "Uuid",- "Text"- ]- },- "nullable": [- false,- false,- false,- true,- false,- null,- null- ]- },- "hash": "085ce27dd33eb6e55bca93a8859190f42b32c236c605b5c22fcc2fb762def411"-}diff --git a/.sqlx/query-1e7e87d03030988ea937936c2ad13d417ecf46fdd43f6e4478e4634974e22faa.json b/.sqlx/query-1e7e87d03030988ea937936c2ad13d417ecf46fdd43f6e4478e4634974e22faa.jsondeleted file mode 100644index 397513b450..0000000000--- a/.sqlx/query-1e7e87d03030988ea937936c2ad13d417ecf46fdd43f6e4478e4634974e22faa.json+++ /dev/null@@ -1,82 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "SELECT g.id,g.name,g.user_id,g.group_jid,g.state,g.adopted_at,g.backfill_state,g.backfill_imported,\n (SELECT count(*) FROM whatsapp_group_message m WHERE m.binding_id=g.id AND m.message_id IS NOT NULL\n AND m.deleted_at IS NULL AND m.origin<>'history' AND m.kind<>'system'\n AND NOT EXISTS(SELECT 1 FROM whatsapp_external_person p WHERE p.id=m.person_id AND p.user_id=$1)\n AND (r.message_id IS NULL OR (m.source_at,m.id)>(r.read_at,r.message_id))) AS \"unread_count!\",\n (SELECT max(source_at) FROM whatsapp_group_message WHERE binding_id=g.id AND message_id IS NOT NULL) AS last_message_at,\n roster.metadata AS \"metadata?\"\n FROM whatsapp_group g\n LEFT JOIN whatsapp_group_read_state r ON r.group_id=g.id AND r.user_id=$1\n LEFT JOIN whatsapp_linked_account a ON a.user_id=$1\n LEFT JOIN whatsapp_group_roster roster ON roster.account_id=a.id AND roster.group_jid=g.group_jid\n WHERE whatsapp_group_can_view(g.id,$1)\n AND (r.user_id IS NOT NULL OR EXISTS (SELECT 1 FROM entity_access ea\n WHERE ea.entity_id=g.id AND ea.entity_type='whatsapp_group'\n AND (ea.source_id=$1 OR ea.source_id IN (SELECT team_id::text FROM team_user WHERE user_id=$1)\n OR ea.source_id IN (SELECT channel_id::text FROM comms_channel_participants WHERE user_id=$1 AND left_at IS NULL))))\n ORDER BY g.adopted_at DESC LIMIT 2000",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "id",- "type_info": "Uuid"- },- {- "ordinal": 1,- "name": "name",- "type_info": "Text"- },- {- "ordinal": 2,- "name": "user_id",- "type_info": "Text"- },- {- "ordinal": 3,- "name": "group_jid",- "type_info": "Text"- },- {- "ordinal": 4,- "name": "state",- "type_info": "Text"- },- {- "ordinal": 5,- "name": "adopted_at",- "type_info": "Timestamptz"- },- {- "ordinal": 6,- "name": "backfill_state",- "type_info": "Text"- },- {- "ordinal": 7,- "name": "backfill_imported",- "type_info": "Int4"- },- {- "ordinal": 8,- "name": "unread_count!",- "type_info": "Int8"- },- {- "ordinal": 9,- "name": "last_message_at",- "type_info": "Timestamptz"- },- {- "ordinal": 10,- "name": "metadata?",- "type_info": "Jsonb"- }- ],- "parameters": {- "Left": [- "Text"- ]- },- "nullable": [- false,- false,- false,- false,- false,- false,- true,- false,- null,- null,- false- ]- },- "hash": "1e7e87d03030988ea937936c2ad13d417ecf46fdd43f6e4478e4634974e22faa"-}diff --git a/.sqlx/query-325bc4556208b7bfc7afcdb7e7702fb1754ff7050af96e1c92a1a4ab12880f67.json b/.sqlx/query-325bc4556208b7bfc7afcdb7e7702fb1754ff7050af96e1c92a1a4ab12880f67.jsonnew file mode 100644index 0000000000..30f704b80f--- /dev/null+++ b/.sqlx/query-325bc4556208b7bfc7afcdb7e7702fb1754ff7050af96e1c92a1a4ab12880f67.json@@ -0,0 +1,46 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT mime, filename, width, height, duration_seconds FROM whatsapp_media_blob WHERE document_id = $1",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "mime",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "filename",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "width",+ "type_info": "Int4"+ },+ {+ "ordinal": 3,+ "name": "height",+ "type_info": "Int4"+ },+ {+ "ordinal": 4,+ "name": "duration_seconds",+ "type_info": "Int4"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false,+ false,+ true,+ true,+ true+ ]+ },+ "hash": "325bc4556208b7bfc7afcdb7e7702fb1754ff7050af96e1c92a1a4ab12880f67"+}diff --git a/.sqlx/query-3d481413e6f2e955c5de04e9a8b7483fc36724eaaa647fe2ff39a836e85bbb6c.json b/.sqlx/query-3d481413e6f2e955c5de04e9a8b7483fc36724eaaa647fe2ff39a836e85bbb6c.jsonnew file mode 100644index 0000000000..ccf72f0f8f--- /dev/null+++ b/.sqlx/query-3d481413e6f2e955c5de04e9a8b7483fc36724eaaa647fe2ff39a836e85bbb6c.json@@ -0,0 +1,17 @@+{+ "db_name": "PostgreSQL",+ "query": "INSERT INTO whatsapp_group_membership (binding_id,account_id,generation,consent_at,remote_member,can_post,reconciled,observed_at)\n SELECT g.id,$1,$2,clock_timestamp(),true,true,true,$4 FROM whatsapp_group g\n WHERE g.kind = 'direct' AND g.user_id = $3 AND g.state = 'active'\n ON CONFLICT (binding_id,account_id) DO UPDATE SET generation = excluded.generation, consent_ended_at = NULL,\n remote_member = true, can_post = true, reconciled = true, observed_at = excluded.observed_at\n WHERE whatsapp_group_membership.generation <> excluded.generation\n OR whatsapp_group_membership.consent_ended_at IS NOT NULL",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Int8",+ "Text",+ "Timestamptz"+ ]+ },+ "nullable": []+ },+ "hash": "3d481413e6f2e955c5de04e9a8b7483fc36724eaaa647fe2ff39a836e85bbb6c"+}diff --git a/.sqlx/query-42e4e3d706b23957b8996fb0202749784b8066b2ce206607e43344cf725743ef.json b/.sqlx/query-42e4e3d706b23957b8996fb0202749784b8066b2ce206607e43344cf725743ef.jsonnew file mode 100644index 0000000000..515007b198--- /dev/null+++ b/.sqlx/query-42e4e3d706b23957b8996fb0202749784b8066b2ce206607e43344cf725743ef.json@@ -0,0 +1,88 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT g.id,g.name,g.kind,g.user_id,g.group_jid,g.state,g.adopted_at,g.backfill_state,g.backfill_imported,\n (SELECT count(*) FROM whatsapp_group_message m WHERE m.binding_id=g.id AND m.message_id IS NOT NULL\n AND m.deleted_at IS NULL AND m.origin<>'history' AND m.kind<>'system'\n AND NOT EXISTS(SELECT 1 FROM whatsapp_external_person p WHERE p.id=m.person_id AND p.user_id=$1)\n AND (r.message_id IS NULL OR (m.source_at,m.id)>(r.read_at,r.message_id))) AS \"unread_count!\",\n (SELECT max(source_at) FROM whatsapp_group_message WHERE binding_id=g.id AND message_id IS NOT NULL) AS last_message_at,\n roster.metadata AS \"metadata?\"\n FROM whatsapp_group g\n LEFT JOIN whatsapp_group_read_state r ON r.group_id=g.id AND r.user_id=$1\n LEFT JOIN whatsapp_linked_account a ON a.user_id=$1\n LEFT JOIN whatsapp_group_roster roster ON roster.account_id=a.id AND roster.group_jid=g.group_jid\n WHERE whatsapp_group_can_view(g.id,$1)\n AND (r.user_id IS NOT NULL OR EXISTS (SELECT 1 FROM entity_access ea\n WHERE ea.entity_id=g.id AND ea.entity_type='whatsapp_group'\n AND (ea.source_id=$1 OR ea.source_id IN (SELECT team_id::text FROM team_user WHERE user_id=$1)\n OR ea.source_id IN (SELECT channel_id::text FROM comms_channel_participants WHERE user_id=$1 AND left_at IS NULL))))\n ORDER BY g.adopted_at DESC LIMIT 2000",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "name",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "kind",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "user_id",+ "type_info": "Text"+ },+ {+ "ordinal": 4,+ "name": "group_jid",+ "type_info": "Text"+ },+ {+ "ordinal": 5,+ "name": "state",+ "type_info": "Text"+ },+ {+ "ordinal": 6,+ "name": "adopted_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 7,+ "name": "backfill_state",+ "type_info": "Text"+ },+ {+ "ordinal": 8,+ "name": "backfill_imported",+ "type_info": "Int4"+ },+ {+ "ordinal": 9,+ "name": "unread_count!",+ "type_info": "Int8"+ },+ {+ "ordinal": 10,+ "name": "last_message_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 11,+ "name": "metadata?",+ "type_info": "Jsonb"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ false,+ false,+ false,+ false,+ false,+ false,+ false,+ true,+ false,+ null,+ null,+ false+ ]+ },+ "hash": "42e4e3d706b23957b8996fb0202749784b8066b2ce206607e43344cf725743ef"+}diff --git a/.sqlx/query-787a1ab8c93b9fa8d433f37faac23d7265f18a8d26ce45ef476d32b8b21c4a83.json b/.sqlx/query-4432b2af358f8226cb247012f4a4b4064d3d386c1f9d0b5509bad9272e1821e3.jsonsimilarity index 76%rename from .sqlx/query-787a1ab8c93b9fa8d433f37faac23d7265f18a8d26ce45ef476d32b8b21c4a83.jsonrename to .sqlx/query-4432b2af358f8226cb247012f4a4b4064d3d386c1f9d0b5509bad9272e1821e3.jsonindex 1a555bd26a..659039d712 100644--- a/.sqlx/query-787a1ab8c93b9fa8d433f37faac23d7265f18a8d26ce45ef476d32b8b21c4a83.json+++ b/.sqlx/query-4432b2af358f8226cb247012f4a4b4064d3d386c1f9d0b5509bad9272e1821e3.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "UPDATE whatsapp_send s SET state = 'sending', claimed_epoch = $2, updated_at = now()\n FROM whatsapp_group b\n WHERE s.id IN (\n SELECT id FROM whatsapp_send WHERE account_id = $1 AND generation = $3 AND state = 'pending'\n ORDER BY group_id, group_sequence LIMIT $4 FOR UPDATE SKIP LOCKED)\n AND b.id = s.group_id\n RETURNING s.id, s.group_id AS binding_id, s.group_sequence, s.payload, s.traceparent, b.group_jid",+ "query": "UPDATE whatsapp_send s SET state = 'sending', claimed_epoch = $2, updated_at = now()\n FROM whatsapp_group b\n WHERE s.id IN (\n SELECT id FROM whatsapp_send WHERE account_id = $1 AND generation = $3 AND state = 'pending'\n ORDER BY group_id, group_sequence LIMIT $4 FOR UPDATE SKIP LOCKED)\n AND b.id = s.group_id\n RETURNING s.id, s.group_id AS binding_id, s.group_sequence, s.payload, s.traceparent, b.group_jid,\n (SELECT r.metadata FROM whatsapp_group_roster r WHERE r.account_id = s.account_id AND r.group_jid = b.group_jid) AS roster","describe": {"columns": [{@@ -32,6 +32,11 @@"ordinal": 5,"name": "group_jid","type_info": "Text"+ },+ {+ "ordinal": 6,+ "name": "roster",+ "type_info": "Jsonb"}],"parameters": {@@ -48,8 +53,9 @@false,false,true,- false+ false,+ null]},- "hash": "787a1ab8c93b9fa8d433f37faac23d7265f18a8d26ce45ef476d32b8b21c4a83"+ "hash": "4432b2af358f8226cb247012f4a4b4064d3d386c1f9d0b5509bad9272e1821e3"}diff --git a/.sqlx/query-5cdf4f5fd4b016c7e9fbbf0e29806e655eb2d1ac02526375f6ac4d8432585148.json b/.sqlx/query-5cdf4f5fd4b016c7e9fbbf0e29806e655eb2d1ac02526375f6ac4d8432585148.jsonnew file mode 100644index 0000000000..cedfb293ac--- /dev/null+++ b/.sqlx/query-5cdf4f5fd4b016c7e9fbbf0e29806e655eb2d1ac02526375f6ac4d8432585148.json@@ -0,0 +1,58 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT b.id, b.group_jid, b.kind, b.user_id, b.state, b.adopted_at\n FROM whatsapp_group b JOIN whatsapp_group_membership m ON m.binding_id = b.id\n WHERE b.group_jid = $1 AND b.state = 'active'\n AND m.account_id = $2 AND m.generation = $3 AND m.consent_ended_at IS NULL\n AND m.remote_member AND m.reconciled\n AND CASE WHEN $7 THEN b.user_id = $5 ELSE\n $4 >= date_trunc('second', b.adopted_at) - make_interval(secs => $6)\n AND $4 >= date_trunc('second', m.consent_at) - make_interval(secs => $6) END\n AND whatsapp_group_can_view(b.id, $5)\n ORDER BY b.id LIMIT 100",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "group_jid",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "kind",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "user_id",+ "type_info": "Text"+ },+ {+ "ordinal": 4,+ "name": "state",+ "type_info": "Text"+ },+ {+ "ordinal": 5,+ "name": "adopted_at",+ "type_info": "Timestamptz"+ }+ ],+ "parameters": {+ "Left": [+ "Text",+ "Uuid",+ "Int8",+ "Timestamptz",+ "Text",+ "Float8",+ "Bool"+ ]+ },+ "nullable": [+ false,+ false,+ false,+ false,+ false,+ false+ ]+ },+ "hash": "5cdf4f5fd4b016c7e9fbbf0e29806e655eb2d1ac02526375f6ac4d8432585148"+}diff --git a/.sqlx/query-6346d7b868ab315c5c1c2a2bb0c5b344671608e00001e465f56cf37be096cc8d.json b/.sqlx/query-6346d7b868ab315c5c1c2a2bb0c5b344671608e00001e465f56cf37be096cc8d.jsonnew file mode 100644index 0000000000..41d3aa4f40--- /dev/null+++ b/.sqlx/query-6346d7b868ab315c5c1c2a2bb0c5b344671608e00001e465f56cf37be096cc8d.json@@ -0,0 +1,65 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT g.id,g.name,g.kind,g.user_id,g.backfill_state,g.backfill_imported,\n (SELECT count(*) FROM whatsapp_group_message m WHERE m.binding_id = g.id AND m.message_id IS NOT NULL\n AND m.deleted_at IS NULL AND m.origin <> 'history' AND m.kind <> 'system'\n AND NOT EXISTS (SELECT 1 FROM whatsapp_external_person p WHERE p.id = m.person_id AND p.user_id = $2)\n AND (r.message_id IS NULL OR (m.source_at,m.id) > (r.read_at,r.message_id))) AS \"unread_count!\",\n (SELECT max(source_at) FROM whatsapp_group_message WHERE binding_id = g.id AND message_id IS NOT NULL) AS last_message_at\n FROM whatsapp_group g LEFT JOIN whatsapp_group_read_state r ON r.group_id = g.id AND r.user_id = $2\n WHERE g.id = $1",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "name",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "kind",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "user_id",+ "type_info": "Text"+ },+ {+ "ordinal": 4,+ "name": "backfill_state",+ "type_info": "Text"+ },+ {+ "ordinal": 5,+ "name": "backfill_imported",+ "type_info": "Int4"+ },+ {+ "ordinal": 6,+ "name": "unread_count!",+ "type_info": "Int8"+ },+ {+ "ordinal": 7,+ "name": "last_message_at",+ "type_info": "Timestamptz"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Text"+ ]+ },+ "nullable": [+ false,+ false,+ false,+ false,+ true,+ false,+ null,+ null+ ]+ },+ "hash": "6346d7b868ab315c5c1c2a2bb0c5b344671608e00001e465f56cf37be096cc8d"+}diff --git a/.sqlx/query-0ec2ffba860a21733fa888c272fbc5c2511d760ce8547c3f7dd26afdc31d002f.json b/.sqlx/query-792b0e56cb37594f6a5473fdc1fe12206b1492433fd4e99fb90964292329cf53.jsonsimilarity index 55%rename from .sqlx/query-0ec2ffba860a21733fa888c272fbc5c2511d760ce8547c3f7dd26afdc31d002f.jsonrename to .sqlx/query-792b0e56cb37594f6a5473fdc1fe12206b1492433fd4e99fb90964292329cf53.jsonindex abf99725ab..83b953f94c 100644--- a/.sqlx/query-0ec2ffba860a21733fa888c272fbc5c2511d760ce8547c3f7dd26afdc31d002f.json+++ b/.sqlx/query-792b0e56cb37594f6a5473fdc1fe12206b1492433fd4e99fb90964292329cf53.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "SELECT mime, filename, sha256, octet_length(bytes) AS \"size!\" FROM whatsapp_media_blob WHERE document_id = $1",+ "query": "SELECT mime, filename, sha256, octet_length(bytes) AS \"size!\", width, height, duration_seconds FROM whatsapp_media_blob WHERE document_id = $1","describe": {"columns": [{@@ -22,6 +22,21 @@"ordinal": 3,"name": "size!","type_info": "Int4"+ },+ {+ "ordinal": 4,+ "name": "width",+ "type_info": "Int4"+ },+ {+ "ordinal": 5,+ "name": "height",+ "type_info": "Int4"+ },+ {+ "ordinal": 6,+ "name": "duration_seconds",+ "type_info": "Int4"}],"parameters": {@@ -33,8 +48,11 @@false,false,false,- null+ null,+ true,+ true,+ true]},- "hash": "0ec2ffba860a21733fa888c272fbc5c2511d760ce8547c3f7dd26afdc31d002f"+ "hash": "792b0e56cb37594f6a5473fdc1fe12206b1492433fd4e99fb90964292329cf53"}diff --git a/.sqlx/query-d13944564f25e7b1ade377a971f3a527c2cf40ef49ba848d9963725568431ace.json b/.sqlx/query-826decd9d2670f80a8521605dd231456cfa914d36a64de15ce9b11d1961a7c4f.jsonsimilarity index 60%rename from .sqlx/query-d13944564f25e7b1ade377a971f3a527c2cf40ef49ba848d9963725568431ace.jsonrename to .sqlx/query-826decd9d2670f80a8521605dd231456cfa914d36a64de15ce9b11d1961a7c4f.jsonindex 5542ee9e1b..e649f850ce 100644--- a/.sqlx/query-d13944564f25e7b1ade377a971f3a527c2cf40ef49ba848d9963725568431ace.json+++ b/.sqlx/query-826decd9d2670f80a8521605dd231456cfa914d36a64de15ce9b11d1961a7c4f.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "SELECT id, group_jid, user_id, state, adopted_at FROM whatsapp_group WHERE user_id = $1 AND group_jid = $2 AND state <> 'detached' FOR UPDATE",+ "query": "INSERT INTO whatsapp_group (id, group_jid, kind, name, user_id, state, share_permission_id, backfill_state) VALUES ($1,$2,$3,$4,$5,'active',$6,'pending') RETURNING id, group_jid, kind, user_id, state, adopted_at","describe": {"columns": [{@@ -15,22 +15,31 @@},{"ordinal": 2,- "name": "user_id",+ "name": "kind","type_info": "Text"},{"ordinal": 3,- "name": "state",+ "name": "user_id","type_info": "Text"},{"ordinal": 4,+ "name": "state",+ "type_info": "Text"+ },+ {+ "ordinal": 5,"name": "adopted_at","type_info": "Timestamptz"}],"parameters": {"Left": [+ "Uuid",+ "Text",+ "Text",+ "Text","Text","Text"]@@ -40,8 +49,9 @@false,false,false,+ false,false]},- "hash": "d13944564f25e7b1ade377a971f3a527c2cf40ef49ba848d9963725568431ace"+ "hash": "826decd9d2670f80a8521605dd231456cfa914d36a64de15ce9b11d1961a7c4f"}diff --git a/.sqlx/query-85d964350370a1ed8a2dfa828949ebb3692ac77b03f3b146aa74c3f0af5c5eb3.json b/.sqlx/query-85d964350370a1ed8a2dfa828949ebb3692ac77b03f3b146aa74c3f0af5c5eb3.jsondeleted file mode 100644index 86038c3297..0000000000--- a/.sqlx/query-85d964350370a1ed8a2dfa828949ebb3692ac77b03f3b146aa74c3f0af5c5eb3.json+++ /dev/null@@ -1,28 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "SELECT mime, filename FROM whatsapp_media_blob WHERE document_id = $1",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "mime",- "type_info": "Text"- },- {- "ordinal": 1,- "name": "filename",- "type_info": "Text"- }- ],- "parameters": {- "Left": [- "Uuid"- ]- },- "nullable": [- false,- false- ]- },- "hash": "85d964350370a1ed8a2dfa828949ebb3692ac77b03f3b146aa74c3f0af5c5eb3"-}diff --git a/.sqlx/query-b4ca13f663d78e9839a95b921f85252fa9069d30fe664ed8abce4271b6027293.json b/.sqlx/query-a5766045317a6b1c0150cf3ec99c1d30fa3327a2d5df4ae3f63c0b4366887cd1.jsonsimilarity index 67%rename from .sqlx/query-b4ca13f663d78e9839a95b921f85252fa9069d30fe664ed8abce4271b6027293.jsonrename to .sqlx/query-a5766045317a6b1c0150cf3ec99c1d30fa3327a2d5df4ae3f63c0b4366887cd1.jsonindex 9257298297..c4d075edd6 100644--- a/.sqlx/query-b4ca13f663d78e9839a95b921f85252fa9069d30fe664ed8abce4271b6027293.json+++ b/.sqlx/query-a5766045317a6b1c0150cf3ec99c1d30fa3327a2d5df4ae3f63c0b4366887cd1.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "INSERT INTO whatsapp_group (id, group_jid, name, user_id, state, share_permission_id, backfill_state) VALUES ($1,$2,$3,$4,'active',$5,'pending') RETURNING id, group_jid, user_id, state, adopted_at",+ "query": "SELECT id, group_jid, kind, user_id, state, adopted_at FROM whatsapp_group WHERE user_id = $1 AND group_jid = $2 AND state <> 'detached' FOR UPDATE","describe": {"columns": [{@@ -15,25 +15,27 @@},{"ordinal": 2,- "name": "user_id",+ "name": "kind","type_info": "Text"},{"ordinal": 3,- "name": "state",+ "name": "user_id","type_info": "Text"},{"ordinal": 4,+ "name": "state",+ "type_info": "Text"+ },+ {+ "ordinal": 5,"name": "adopted_at","type_info": "Timestamptz"}],"parameters": {"Left": [- "Uuid",- "Text",- "Text","Text","Text"]@@ -43,8 +45,9 @@false,false,false,+ false,false]},- "hash": "b4ca13f663d78e9839a95b921f85252fa9069d30fe664ed8abce4271b6027293"+ "hash": "a5766045317a6b1c0150cf3ec99c1d30fa3327a2d5df4ae3f63c0b4366887cd1"}diff --git a/.sqlx/query-b786cd62597579e1a8d765131145b54e10ba43192282c30371864597614ba9aa.json b/.sqlx/query-b786cd62597579e1a8d765131145b54e10ba43192282c30371864597614ba9aa.jsonnew file mode 100644index 0000000000..3ca9eb494e--- /dev/null+++ b/.sqlx/query-b786cd62597579e1a8d765131145b54e10ba43192282c30371864597614ba9aa.json@@ -0,0 +1,24 @@+{+ "db_name": "PostgreSQL",+ "query": "UPDATE whatsapp_group SET name = $3\n WHERE user_id = $1 AND group_jid = $2 AND kind = 'direct' AND state = 'active' AND name <> $3\n RETURNING id",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ }+ ],+ "parameters": {+ "Left": [+ "Text",+ "Text",+ "Text"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "b786cd62597579e1a8d765131145b54e10ba43192282c30371864597614ba9aa"+}diff --git a/.sqlx/query-bffc78fb65119282a60b4daaf2ea92affd9d9e9b5db7a8e5c71883ca7479ff8b.json b/.sqlx/query-bffc78fb65119282a60b4daaf2ea92affd9d9e9b5db7a8e5c71883ca7479ff8b.jsonnew file mode 100644index 0000000000..6310877976--- /dev/null+++ b/.sqlx/query-bffc78fb65119282a60b4daaf2ea92affd9d9e9b5db7a8e5c71883ca7479ff8b.json@@ -0,0 +1,29 @@+{+ "db_name": "PostgreSQL",+ "query": "INSERT INTO whatsapp_group_message (id, binding_id, person_id, source_id, origin, source_at, content_revision, deleted_at, revision_content, revised_at,\n kind, rich, mentions, forwarded, view_once)\n VALUES ($11, $1, $2, $3, $4, $5, $6, $7, $8, $9, $12, $13, $14, $15, $16)\n ON CONFLICT (binding_id, person_id, source_id) DO UPDATE SET\n deleted_at = COALESCE(whatsapp_group_message.deleted_at, excluded.deleted_at),\n revision_content = CASE WHEN excluded.content_revision > whatsapp_group_message.content_revision\n THEN excluded.revision_content ELSE whatsapp_group_message.revision_content END,\n revised_at = CASE WHEN excluded.content_revision > whatsapp_group_message.content_revision\n THEN excluded.revised_at ELSE whatsapp_group_message.revised_at END,\n content_revision = GREATEST(whatsapp_group_message.content_revision, excluded.content_revision),\n source_at = CASE WHEN $10 THEN whatsapp_group_message.source_at ELSE excluded.source_at END,\n kind = CASE WHEN $10 THEN whatsapp_group_message.kind ELSE excluded.kind END,\n rich = CASE WHEN $10 THEN whatsapp_group_message.rich ELSE COALESCE(excluded.rich, whatsapp_group_message.rich) END,\n mentions = CASE WHEN $10 OR cardinality(excluded.mentions) = 0 THEN whatsapp_group_message.mentions ELSE excluded.mentions END,\n forwarded = whatsapp_group_message.forwarded OR excluded.forwarded,\n view_once = whatsapp_group_message.view_once OR excluded.view_once",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Uuid",+ "Text",+ "Text",+ "Timestamptz",+ "Int8",+ "Timestamptz",+ "Text",+ "Timestamptz",+ "Bool",+ "Uuid",+ "Text",+ "Jsonb",+ "TextArray",+ "Bool",+ "Bool"+ ]+ },+ "nullable": []+ },+ "hash": "bffc78fb65119282a60b4daaf2ea92affd9d9e9b5db7a8e5c71883ca7479ff8b"+}diff --git a/.sqlx/query-789cab67b176c1c4210c99802510c1adf3efe836a89b78d439c17d0c114fb017.json b/.sqlx/query-e10b37259bd5492da30b4473b5d8174a5ac455a4533ce299d3c57316a7a145a2.jsonsimilarity index 71%rename from .sqlx/query-789cab67b176c1c4210c99802510c1adf3efe836a89b78d439c17d0c114fb017.jsonrename to .sqlx/query-e10b37259bd5492da30b4473b5d8174a5ac455a4533ce299d3c57316a7a145a2.jsonindex db261a41e0..68d0bdd120 100644--- a/.sqlx/query-789cab67b176c1c4210c99802510c1adf3efe836a89b78d439c17d0c114fb017.json+++ b/.sqlx/query-e10b37259bd5492da30b4473b5d8174a5ac455a4533ce299d3c57316a7a145a2.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "SELECT id, group_jid, user_id, state, adopted_at FROM whatsapp_group WHERE id = $1",+ "query": "SELECT id, group_jid, kind, user_id, state, adopted_at FROM whatsapp_group WHERE id = $1","describe": {"columns": [{@@ -15,16 +15,21 @@},{"ordinal": 2,- "name": "user_id",+ "name": "kind","type_info": "Text"},{"ordinal": 3,- "name": "state",+ "name": "user_id","type_info": "Text"},{"ordinal": 4,+ "name": "state",+ "type_info": "Text"+ },+ {+ "ordinal": 5,"name": "adopted_at","type_info": "Timestamptz"}@@ -39,8 +44,9 @@false,false,false,+ false,false]},- "hash": "789cab67b176c1c4210c99802510c1adf3efe836a89b78d439c17d0c114fb017"+ "hash": "e10b37259bd5492da30b4473b5d8174a5ac455a4533ce299d3c57316a7a145a2"}diff --git a/.sqlx/query-6f2c4bb9d028f5fe23c3358858dfa8524707cbf5e38ebb03e2f8bcbd683fb493.json b/.sqlx/query-e55c16693e50ef596a84285d816a513f20f480b1c15be658fc894fdab1dfaf3a.jsonsimilarity index 72%rename from .sqlx/query-6f2c4bb9d028f5fe23c3358858dfa8524707cbf5e38ebb03e2f8bcbd683fb493.jsonrename to .sqlx/query-e55c16693e50ef596a84285d816a513f20f480b1c15be658fc894fdab1dfaf3a.jsonindex f8dd9156c2..7324b607c3 100644--- a/.sqlx/query-6f2c4bb9d028f5fe23c3358858dfa8524707cbf5e38ebb03e2f8bcbd683fb493.json+++ b/.sqlx/query-e55c16693e50ef596a84285d816a513f20f480b1c15be658fc894fdab1dfaf3a.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "SELECT m.id,m.person_id,p.user_id,COALESCE(p.display_name,'WhatsApp participant') AS \"name!\",\n m.body,m.reply_to,m.source_at,m.ingested_at,m.revised_at,m.deleted_at,m.kind,m.rich,m.mentions,m.forwarded,\n (SELECT state FROM whatsapp_send s WHERE s.message_id = m.id AND s.user_id = $2 ORDER BY s.created_at DESC LIMIT 1) AS delivery\n FROM whatsapp_group_message m JOIN whatsapp_external_person p ON p.id = m.person_id\n WHERE m.binding_id = $1 AND m.message_id IS NOT NULL\n AND ($3::uuid IS NULL OR (m.source_at,m.id) < (SELECT source_at,id FROM whatsapp_group_message WHERE id = $3 AND binding_id = $1 AND message_id IS NOT NULL))\n ORDER BY m.source_at DESC,m.id DESC LIMIT $4",+ "query": "SELECT m.id,m.person_id,p.user_id,COALESCE(p.display_name,'WhatsApp participant') AS \"name!\",\n m.body,m.reply_to,m.source_at,m.ingested_at,m.revised_at,m.deleted_at,m.kind,m.rich,m.mentions,m.forwarded,m.view_once,\n (SELECT state FROM whatsapp_send s WHERE s.message_id = m.id AND s.user_id = $2 ORDER BY s.created_at DESC LIMIT 1) AS delivery\n FROM whatsapp_group_message m JOIN whatsapp_external_person p ON p.id = m.person_id\n WHERE m.binding_id = $1 AND m.message_id IS NOT NULL\n AND ($3::uuid IS NULL OR (m.source_at,m.id) < (SELECT source_at,id FROM whatsapp_group_message WHERE id = $3 AND binding_id = $1 AND message_id IS NOT NULL))\n ORDER BY m.source_at DESC,m.id DESC LIMIT $4","describe": {"columns": [{@@ -75,6 +75,11 @@},{"ordinal": 14,+ "name": "view_once",+ "type_info": "Bool"+ },+ {+ "ordinal": 15,"name": "delivery","type_info": "Text"}@@ -102,8 +107,9 @@true,false,false,+ false,null]},- "hash": "6f2c4bb9d028f5fe23c3358858dfa8524707cbf5e38ebb03e2f8bcbd683fb493"+ "hash": "e55c16693e50ef596a84285d816a513f20f480b1c15be658fc894fdab1dfaf3a"}diff --git a/.sqlx/query-f376b23fdfc65eac1e9043a5eb25fa3e94257cdf185bbfea48e7c4b76c97fbf0.json b/.sqlx/query-f376b23fdfc65eac1e9043a5eb25fa3e94257cdf185bbfea48e7c4b76c97fbf0.jsondeleted file mode 100644index 76ef2f3628..0000000000--- a/.sqlx/query-f376b23fdfc65eac1e9043a5eb25fa3e94257cdf185bbfea48e7c4b76c97fbf0.json+++ /dev/null@@ -1,52 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "SELECT b.id, b.group_jid, b.user_id, b.state, b.adopted_at\n FROM whatsapp_group b JOIN whatsapp_group_membership m ON m.binding_id = b.id\n WHERE b.group_jid = $1 AND b.state = 'active'\n AND m.account_id = $2 AND m.generation = $3 AND m.consent_ended_at IS NULL\n AND m.remote_member AND m.reconciled\n AND CASE WHEN $7 THEN b.user_id = $5 ELSE\n $4 >= date_trunc('second', b.adopted_at) - make_interval(secs => $6)\n AND $4 >= date_trunc('second', m.consent_at) - make_interval(secs => $6) END\n AND whatsapp_group_can_view(b.id, $5)\n ORDER BY b.id LIMIT 100",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "id",- "type_info": "Uuid"- },- {- "ordinal": 1,- "name": "group_jid",- "type_info": "Text"- },- {- "ordinal": 2,- "name": "user_id",- "type_info": "Text"- },- {- "ordinal": 3,- "name": "state",- "type_info": "Text"- },- {- "ordinal": 4,- "name": "adopted_at",- "type_info": "Timestamptz"- }- ],- "parameters": {- "Left": [- "Text",- "Uuid",- "Int8",- "Timestamptz",- "Text",- "Float8",- "Bool"- ]- },- "nullable": [- false,- false,- false,- false,- false- ]- },- "hash": "f376b23fdfc65eac1e9043a5eb25fa3e94257cdf185bbfea48e7c4b76c97fbf0"-}diff --git a/.sqlx/query-ffe827ebcfa81b6aa7e166f299aa3df33f6582f18848f092e28801b131536f27.json b/.sqlx/query-ffe827ebcfa81b6aa7e166f299aa3df33f6582f18848f092e28801b131536f27.jsondeleted file mode 100644index 9df29e0183..0000000000--- a/.sqlx/query-ffe827ebcfa81b6aa7e166f299aa3df33f6582f18848f092e28801b131536f27.json+++ /dev/null@@ -1,28 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "INSERT INTO whatsapp_group_message (id, binding_id, person_id, source_id, origin, source_at, content_revision, deleted_at, revision_content, revised_at,\n kind, rich, mentions, forwarded)\n VALUES ($11, $1, $2, $3, $4, $5, $6, $7, $8, $9, $12, $13, $14, $15)\n ON CONFLICT (binding_id, person_id, source_id) DO UPDATE SET\n deleted_at = COALESCE(whatsapp_group_message.deleted_at, excluded.deleted_at),\n revision_content = CASE WHEN excluded.content_revision > whatsapp_group_message.content_revision\n THEN excluded.revision_content ELSE whatsapp_group_message.revision_content END,\n revised_at = CASE WHEN excluded.content_revision > whatsapp_group_message.content_revision\n THEN excluded.revised_at ELSE whatsapp_group_message.revised_at END,\n content_revision = GREATEST(whatsapp_group_message.content_revision, excluded.content_revision),\n source_at = CASE WHEN $10 THEN whatsapp_group_message.source_at ELSE excluded.source_at END,\n kind = CASE WHEN $10 THEN whatsapp_group_message.kind ELSE excluded.kind END,\n rich = CASE WHEN $10 THEN whatsapp_group_message.rich ELSE COALESCE(excluded.rich, whatsapp_group_message.rich) END,\n mentions = CASE WHEN $10 OR cardinality(excluded.mentions) = 0 THEN whatsapp_group_message.mentions ELSE excluded.mentions END,\n forwarded = whatsapp_group_message.forwarded OR excluded.forwarded",- "describe": {- "columns": [],- "parameters": {- "Left": [- "Uuid",- "Uuid",- "Text",- "Text",- "Timestamptz",- "Int8",- "Timestamptz",- "Text",- "Timestamptz",- "Bool",- "Uuid",- "Text",- "Jsonb",- "TextArray",- "Bool"- ]- },- "nullable": []- },- "hash": "ffe827ebcfa81b6aa7e166f299aa3df33f6582f18848f092e28801b131536f27"-}diff --git a/Cargo.lock b/Cargo.lockindex 1f98eff5a8..4a479264b9 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -21647,6 +21647,7 @@ dependencies = ["entity_access_db_utils","entity_registry_db_utils","harness_id",+ "image","macro_authorization","macro_db_migrator","macro_user_id",@@ -21654,6 +21655,7 @@ dependencies = ["model_owner","model_user","models_permissions",+ "nom 8.0.0","opentelemetry","rootcause","serde",diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.mdindex 6b2d83d8d4..37210202e6 100644--- a/apps/web/AGENTS.md+++ b/apps/web/AGENTS.md@@ -232,7 +232,7 @@ ownership. Cancel, logout, and the ten-minute timeout retire pending callbacks.- Compose multiselect filters with `Dropdown.MultiSelectItem` and the sharedsearchable filters; follow [multiselect dropdowns](../../docs/agent-guide/ui-conventions.md#multiselect-dropdowns)for checkbox, row, Only, keyboard, and touch behavior.-- Keep adopted WhatsApp groups in External at `/external/whatsapp/:id` (`/whatsapp-group/:id` redirects) with their own queries; sharing controls viewing and the viewer's own WhatsApp membership controls sending. Never route them through channel context or services.+- Keep adopted WhatsApp groups in External at `/external/whatsapp/:id` with their own queries; sharing controls viewing and the viewer's own WhatsApp membership controls sending. Never route them through channel context or services.- All API/network calls live in service-clients.- Open projects through `openProject` (`features/projects/open-project.ts`): itretargets an already-open project split to the section or comment in place.diff --git a/apps/web/src/components/app/split-layout/componentRegistry.tsx b/apps/web/src/components/app/split-layout/componentRegistry.tsxindex 24013a46c6..fd2c9b1149 100644--- a/apps/web/src/components/app/split-layout/componentRegistry.tsx+++ b/apps/web/src/components/app/split-layout/componentRegistry.tsx@@ -2,10 +2,8 @@ import { parseAgentsRoute } from '@app/features/agents-view/core/route';import { useSpreadsheetAccess } from '@app/features/block-spreadsheet/primitives/use-spreadsheet-access';import type { EventEditorInitialValues } from '@app/features/calendar/components/composer/event-form-model';import type { CalendarEvent } from '@app/features/calendar/types';-import { whatsappGroupContent } from '@app/features/external-view/hosted-content';import { HomeRouteView } from '@app/features/home/route-views';import { parseProjectRoute } from '@app/features/projects/core/route';-import { parseWhatsAppGroupComponentId } from '@app/features/whatsapp-group/core/route';import { useFeatureFlag } from '@app/lib/analytics/posthog';import { NOT_FOUND_ROUTE_ID } from '@app/routes/app-route';import { LoadingBlock } from '@core/component/LoadingBlock';@@ -206,11 +204,6 @@ export function resolveComponent(): ResolvedComponent {const registration = REGISTRY.get(name);if (!registration) {- const groupId = parseWhatsAppGroupComponentId(name);- if (groupId)- return {- element: () => <RedirectSplit to={whatsappGroupContent(groupId)} />,- };if (parseProjectRoute(name)) {const base = REGISTRY.get('initiative-view');if (base)diff --git a/apps/web/src/components/app/split-layout/split-router/legacy-route.test.ts b/apps/web/src/components/app/split-layout/split-router/legacy-route.test.tsindex dd2329219b..24e143cfda 100644--- a/apps/web/src/components/app/split-layout/split-router/legacy-route.test.ts+++ b/apps/web/src/components/app/split-layout/split-router/legacy-route.test.ts@@ -1,19 +1,12 @@import { createRoutesManifest, type SplitRoutes } from '@app/lib/split-router';import {appRoute,- externalRoute,- externalWhatsappGroupRoute,homeSplitRoute,legacyContentRoute,notFoundRoute,- whatsappGroupRoute,} from '@app/routes/routes';import { describe, expect, it, vi } from 'vitest';-import {- resolveContentLocation,- splitContentFromLocation,- upgradeLegacyPath,-} from './legacy-route';+import { resolveContentLocation, upgradeLegacyPath } from './legacy-route';vi.mock('@components/app/split-layout/componentRegistry', () => ({resolveComponent: vi.fn(() => ({ type: 'mock-component' })),@@ -33,13 +26,7 @@ const routes = createRoutesManifest({definitions: [{...appRoute,- children: [- homeSplitRoute,- { ...externalRoute, children: [externalWhatsappGroupRoute] },- whatsappGroupRoute,- legacyContentRoute,- notFoundRoute,- ],+ children: [homeSplitRoute, legacyContentRoute, notFoundRoute],},],defaultRoute: () => ({ matches: [{ id: 'view-home', params: {} }] }),@@ -72,21 +59,3 @@ describe('resolveContentLocation', () => {).toBeUndefined();});});--it('restores a saved WhatsApp group component inside External', () => {- const location = resolveContentLocation(routes, {- type: 'component',- id: 'whatsapp-group:019a061e-0000-7000-8000-000000000001',- });- expect(location.route.matches.slice(1)).toEqual([- { id: 'view-external', params: {} },- {- id: 'external-whatsapp-group',- params: { groupId: '019a061e-0000-7000-8000-000000000001' },- },- ]);- expect(splitContentFromLocation(location)).toEqual({- type: 'component',- id: 'external',- });-});diff --git a/apps/web/src/components/app/split-layout/split-router/legacy-route.ts b/apps/web/src/components/app/split-layout/split-router/legacy-route.tsindex f4ded5436a..40d80ab2a4 100644--- a/apps/web/src/components/app/split-layout/split-router/legacy-route.ts+++ b/apps/web/src/components/app/split-layout/split-router/legacy-route.ts@@ -21,7 +21,6 @@ import {routineIdFromContent,routineLocation,} from '@app/features/routines/routine-navigation';-import { parseWhatsAppGroupComponentId } from '@app/features/whatsapp-group/core/route';import {canonicalRoute,decodePane,@@ -292,14 +291,6 @@ export function splitLocationFromContent(}if (content.type === 'component') {- const groupId = parseWhatsAppGroupComponentId(content.id);- if (groupId)- return {- route: paneRoute(- { id: 'view-external', params: {} },- { id: 'external-whatsapp-group', params: { groupId } }- ),- };const viewId = `view-${content.id}`;if (routes.byId.has(viewId)) {return { route: paneRoute({ id: viewId, params: {} }) };@@ -417,9 +408,6 @@ export function splitContentFromLocation(throw new Error('Invalid routine detail split route');}- // The retired route only redirects; its pane belongs to External.- if (root.id === 'whatsapp-group')- return { type: 'component', id: 'external' };if (root.id.startsWith('view-'))return { type: 'component', id: root.id.slice('view-'.length) };if (root.id === 'drive') return { type: 'component', id: 'documents' };diff --git a/apps/web/src/components/app/split-layout/tests/fixtures.ts b/apps/web/src/components/app/split-layout/tests/fixtures.tsindex d219b024bc..936c5b09bb 100644--- a/apps/web/src/components/app/split-layout/tests/fixtures.ts+++ b/apps/web/src/components/app/split-layout/tests/fixtures.ts@@ -16,7 +16,6 @@ import {homeSplitRoute,legacyContentRoute,notFoundRoute,- whatsappGroupRoute,} from '@app/routes/routes';import type { BlockOrchestrator } from '@core/orchestrator';import { createSplitLayout, type SplitManager } from '../layoutManager';@@ -36,7 +35,6 @@ const routes: SplitRoutes = {...appRoute,children: [homeSplitRoute,- whatsappGroupRoute,{ ...externalRoute, children: [externalWhatsappGroupRoute] },{ ...channelsSplitRoute, children: [channelDetailRoute] },legacyContentRoute,diff --git a/apps/web/src/features/channel/Input/ChannelInput.tsx b/apps/web/src/features/channel/Input/ChannelInput.tsxindex 19be6e1b6b..374ddcdd4a 100644--- a/apps/web/src/features/channel/Input/ChannelInput.tsx+++ b/apps/web/src/features/channel/Input/ChannelInput.tsx@@ -101,7 +101,7 @@ import { hasSendableInputContent } from './utils/sendable-content';* What the composer offers beyond text, formatting and file attachments.* Hosts that carry only those, such as a WhatsApp group, switch the rest off.*/-export type ChannelInputFeatures = {+type ChannelInputFeatures = {/*** `@` mentions of people, agents and Macro items, including Ask Macro.* `'participants'` offers only the `participants` prop: no agents, items,diff --git a/apps/web/src/features/channel/Input/utils/file-helpers.ts b/apps/web/src/features/channel/Input/utils/file-helpers.tsindex a7e5436904..3a4918fb80 100644--- a/apps/web/src/features/channel/Input/utils/file-helpers.ts+++ b/apps/web/src/features/channel/Input/utils/file-helpers.ts@@ -13,7 +13,7 @@ export type UploadFailedResult = {};/** A file the host stored for its own send, such as a WhatsApp group upload. */-export type UploadStagedSuccessResult = {+type UploadStagedSuccessResult = {failed: false;destination: 'staged';id: string;diff --git a/apps/web/src/features/external-view/components/in-macro-section.test.tsx b/apps/web/src/features/external-view/components/in-macro-section.test.tsxindex 123843d3a2..dec8a95f71 100644--- a/apps/web/src/features/external-view/components/in-macro-section.test.tsx+++ b/apps/web/src/features/external-view/components/in-macro-section.test.tsx@@ -30,16 +30,25 @@ it('lists readable groups with unread counts and marks read-only ones', () => {groups={[{id: 'group-design',+ kind: 'group',name: 'Design Crit',unreadCount: 3,canSend: true,},{id: 'group-family',+ kind: 'group',name: 'Ana, Ben, +2',unreadCount: 0,canSend: false,},+ {+ id: 'chat-ana',+ kind: 'direct',+ name: 'Ana Ruiz',+ unreadCount: 1,+ canSend: false,+ },]}isPending={false}isError={false}@@ -49,7 +58,7 @@ it('lists readable groups with unread counts and marks read-only ones', () => {/>));const nav = within(- screen.getByRole('navigation', { name: 'WhatsApp groups in Macro' })+ screen.getByRole('navigation', { name: 'WhatsApp chats in Macro' }));const design = nav.getByRole('button', { name: /Design Crit/ });expect(within(design).getByLabelText('3 unread messages')).toBeTruthy();@@ -57,6 +66,11 @@ it('lists readable groups with unread counts and marks read-only ones', () => {const family = nav.getByRole('button', { name: /Ana, Ben, \+2/ });expect(family.getAttribute('aria-current')).toBe('page');expect(within(family).getByText('Read-only')).toBeTruthy();+ // A shared direct chat: only its owner replies.+ const direct = nav.getByRole('button', { name: /Ana Ruiz/ });+ expect(within(direct).getByText('Read-only').getAttribute('title')).toBe(+ 'You can read this chat. Only its owner can reply.'+ );fireEvent.click(design);expect(onOpenGroup).toHaveBeenCalledWith('group-design');diff --git a/apps/web/src/features/external-view/components/in-macro-section.tsx b/apps/web/src/features/external-view/components/in-macro-section.tsxindex 6ad61415c0..05e345f4b1 100644--- a/apps/web/src/features/external-view/components/in-macro-section.tsx+++ b/apps/web/src/features/external-view/components/in-macro-section.tsx@@ -1,5 +1,7 @@import { ViewSidebar } from '@app/components/view-shell';+import { ViewSkeleton } from '@app/components/view-shell/ViewSkeleton';import type { GroupSummary } from '@app/features/whatsapp-group/core/group';+import UserIcon from '@phosphor/user.svg';import UsersThreeIcon from '@phosphor/users-three.svg';import { Button } from '@ui';import { For, Match, Show, Switch } from 'solid-js';@@ -29,7 +31,12 @@ function GroupRow(props: {onClick={props.onOpen}><ViewSidebar.Icon>- <UsersThreeIcon />+ <Show+ when={props.group.kind === 'direct'}+ fallback={<UsersThreeIcon />}+ >+ <UserIcon />+ </Show></ViewSidebar.Icon><spanclass="min-w-0 flex-1 truncate"@@ -40,7 +47,11 @@ function GroupRow(props: {<Show when={!props.group.canSend}><spanclass="shrink-0 text-xs text-ink-extra-muted"- title="You can read this group. Your WhatsApp isn't in it, so you can't send."+ title={+ props.group.kind === 'direct'+ ? 'You can read this chat. Only its owner can reply.'+ : "You can read this group. Your WhatsApp isn't in it, so you can't send."+ }>Read-only</span>@@ -66,12 +77,12 @@ export function InMacroGroups(props: {<Switch><Match when={props.groups}>{(groups) => (- <ViewSidebar.Nav aria-label="WhatsApp groups in Macro">+ <ViewSidebar.Nav aria-label="WhatsApp chats in Macro"><Foreach={groups()}fallback={<p class="px-(--sidebar-item-inset) py-1.5 text-sm text-ink-extra-muted">- No groups added yet+ No chats added yet</p>}>@@ -87,16 +98,11 @@ export function InMacroGroups(props: {)}</Match><Match when={props.isPending}>- <p- role="status"- class="px-(--sidebar-item-inset) py-1.5 text-sm text-ink-extra-muted"- >- Loading groups…- </p>+ <ViewSkeleton.Rows label="Loading chats" count={3} /></Match><Match when={props.isError}><div class="flex items-center gap-2 px-(--sidebar-item-inset) py-1.5 text-sm text-ink-muted">- <span role="alert">Couldn't load your groups.</span>+ <span role="alert">Couldn't load your chats.</span><Button size="sm" variant="ghost" onClick={props.onRetry}>Try again</Button>diff --git a/apps/web/src/features/whatsapp-group/AGENTS.md b/apps/web/src/features/whatsapp-group/AGENTS.mdindex a9cb0719a5..089d10bb73 100644--- a/apps/web/src/features/whatsapp-group/AGENTS.md+++ b/apps/web/src/features/whatsapp-group/AGENTS.md@@ -27,6 +27,10 @@ lists belong to `features/whatsapp-linked` and `features/external-view`.## Gotchas+- Despite the name, this is any added WhatsApp chat: `kind` is `group` or+ `direct`. A direct chat has no roster (header shows the person) and only+ its owner sends; shared viewers see "Only <owner> can reply in this chat".+ User-facing copy says "chat"; code, routes and the entity type keep "group".- Viewing follows ordinary entity sharing. WhatsApp membership controls sending.- Every write uses the viewer's own connected WhatsApp account.- A draft keeps one idempotency key until DSS records it; unknown outcomes@@ -46,6 +50,15 @@ lists belong to `features/whatsapp-linked` and `features/external-view`.the document chips. DSS's declared width/height reserve the space (keepsthe open-at-bottom scroll right); stickers, GIFs and voice notes follow theattachment's `presentation`.+- The timeline and composer use Chat's layout (`macro-message-width` column,+ `CustomScrollbar`, `ChannelInputContainer` → centered column). The view+ follows the bottom (a `ResizeObserver` on the content) until the reader+ scrolls by intent (wheel, touch, keys, scrollbar); layout-driven scroll+ events never change that. Media URLs keep their first presigned URL and+ memoized items so refetches don't remount or reload them.+- Files this page sent keep their local preview and size on the stored+ message (`conversation.sentFiles`), so the swap from pending neither+ flashes nor jumps.- `kind: 'system'` rows render through Chat's `SystemActivityLine`(`components/system-line.tsx`, words in `core/rich.ts`) and enter the listmeta as `activity` entries; they never count toward the unread divider.diff --git a/apps/web/src/features/whatsapp-group/components/inbound-media.tsx b/apps/web/src/features/whatsapp-group/components/inbound-media.tsxindex b354ed9b68..c1d9c49d72 100644--- a/apps/web/src/features/whatsapp-group/components/inbound-media.tsx+++ b/apps/web/src/features/whatsapp-group/components/inbound-media.tsx@@ -2,7 +2,7 @@ import type { MediaItem } from '@channel/Media/media-items';import { MediaPreview } from '@channel/Message/MediaPreview';import { constrainImageDimensions } from '@macro-inc/lexical-core/utils/media';import MicrophoneIcon from '@phosphor/microphone.svg';-import { For, Match, Show, Switch } from 'solid-js';+import { createMemo, For, Match, Show, Switch } from 'solid-js';import { formatDuration } from '../core/rich';/** An imported image, video or voice note with its resolved file URL. */@@ -12,6 +12,8 @@ export type InboundMediaFile = {fileName: string;/** Undefined while the URL resolves. */url: string | undefined;+ /** A local preview shown until `url` loads (files this page sent). */+ previewUrl?: string;/** Declared by WhatsApp; reserves the space before the file loads. */width?: number;height?: number;@@ -157,21 +159,33 @@ export function InboundMedia(props: { files: InboundMediaFile[] }) {file.presentation !== 'sticker' &&file.presentation !== 'gif');- const visual = (): MediaItem[] =>- grid().flatMap((file) =>- file.url && file.kind !== 'audio'- ? [- {- id: file.id,- src: file.url,- fullSrc: file.url,- kind: file.kind,- width: file.width,- height: file.height,- },- ]- : []- );+ // Like Chat's `mapMediaItems`: an unchanged file keeps its item, so the+ // grid doesn't remount (and reload) it.+ const visual = createMemo(+ (previous: MediaItem[]) =>+ grid().flatMap((file): MediaItem[] => {+ if (!file.url || file.kind === 'audio') return [];+ const item: MediaItem = {+ id: file.id,+ src: file.url,+ fullSrc: file.url,+ previewSrc: file.previewUrl,+ kind: file.kind,+ width: file.width,+ height: file.height,+ };+ const kept = previous.find((old) => old.id === item.id);+ return [+ kept &&+ (Object.keys(item) as (keyof MediaItem)[]).every(+ (key) => kept[key] === item[key]+ )+ ? kept+ : item,+ ];+ }),+ []+ );return (<div class="mt-1 flex flex-col gap-2" data-whatsapp-inline-media><Show when={visual().length > 0}>diff --git a/apps/web/src/features/whatsapp-group/context/whatsapp-group-context.tsx b/apps/web/src/features/whatsapp-group/context/whatsapp-group-context.tsxindex 5ebacd0cf4..f070f40f7a 100644--- a/apps/web/src/features/whatsapp-group/context/whatsapp-group-context.tsx+++ b/apps/web/src/features/whatsapp-group/context/whatsapp-group-context.tsx@@ -21,7 +21,8 @@ export type WhatsAppGroupCapabilities = {timeline: SourceRead<GroupMessage[]>;hasOlder: Accessor<boolean>;loadingOlder: Accessor<boolean>;- loadOlder: () => Promise<unknown>;+ /** Loads the next older page; false when that request failed. */+ loadOlder: () => Promise<boolean>;/** Records one write; DSS dedupes a retry that reuses its key. */send: (request: GroupSend,diff --git a/apps/web/src/features/whatsapp-group/core/attachments.ts b/apps/web/src/features/whatsapp-group/core/attachments.tsindex 5e0b5429c3..ebf9577a85 100644--- a/apps/web/src/features/whatsapp-group/core/attachments.ts+++ b/apps/web/src/features/whatsapp-group/core/attachments.ts@@ -11,13 +11,19 @@ export type InboundAttachment = {height?: number;durationSeconds?: number;presentation?: 'sticker' | 'gif' | 'voice_note';+ /** The local preview of a file this page sent, before DSS stored it. */+ previewUrl?: string;};/** How a ready file plays inline, like Chat's media; undefined for a file chip. */export function inlineMediaKind(attachment: InboundAttachment): 'image' | 'video' | 'audio' | undefined {- if (attachment.state !== 'ready' || !attachment.documentId) return undefined;+ if (+ attachment.state !== 'ready' ||+ !(attachment.documentId || attachment.previewUrl)+ )+ return undefined;const type = attachment.mime.split('/')[0];if (type === 'image' || type === 'video' || type === 'audio') return type;return undefined;diff --git a/apps/web/src/features/whatsapp-group/core/group.ts b/apps/web/src/features/whatsapp-group/core/group.tsindex 0f1b4e2dce..2f0063b372 100644--- a/apps/web/src/features/whatsapp-group/core/group.ts+++ b/apps/web/src/features/whatsapp-group/core/group.ts@@ -1,10 +1,12 @@import { match, P } from 'ts-pattern';import type { InboundAttachment } from './attachments';-import type { Mention, RichContent } from './rich';+import { disappearingLabel, type Mention, type RichContent } from './rich';/** Feature vocabulary; transport decoding lives in queries/. */export type GroupSummary = {id: string;+ /** A group, or a one-to-one chat (named after the other person). */+ kind: 'group' | 'direct';name: string;unreadCount: number;/** False for viewers who can only read. */@@ -21,6 +23,8 @@ export type GroupBackfill = {};export type GroupDetail = {id: string;+ /** A group, or a one-to-one chat: `name` is the person, no roster. */+ kind: 'group' | 'direct';name: string;ownerId: string;accessLevel: 'view' | 'comment' | 'edit' | 'owner';@@ -31,11 +35,14 @@ export type GroupDetail = {unreadCount: number;members: { id: string; name: string; admin: boolean }[];backfill?: GroupBackfill;+ /** WhatsApp's timer while disappearing messages are on; Macro keeps all. */+ disappearingSeconds?: number;+ /** The WhatsApp community the group belongs to. */+ community?: { name: string; announcements: boolean };limits: {textBytes: number;attachmentBytes: number;attachmentTypes: string[];- maxAttachments: number;editSeconds: number;mutations: ('reaction' | 'edit' | 'delete')[];};@@ -116,7 +123,17 @@ export function canChangeMessage();}-export function composerNote(group: GroupDetail): string {+export function composerNote(+ group: GroupDetail,+ /** Who owns the chat, for "Only Ana can reply in this chat". */+ ownerName = 'its owner'+): string {+ if (+ !group.canSend &&+ group.kind === 'direct' &&+ group.sendReason === 'not_observing'+ )+ return `Only ${ownerName} can reply in this chat`;if (group.canSend)return group.phone? `Sending as ${group.phone}`@@ -134,7 +151,7 @@ export function composerNote(group: GroupDetail): string {'not_allowed_in_group',() => "Your WhatsApp can't post in this group")- .with('group_unavailable', () => 'This group is no longer syncing')+ .with('group_unavailable', () => 'This chat is no longer syncing').with('sending_disabled', () => 'Sending to WhatsApp is turned off').otherwise(() => 'Sending to WhatsApp is unavailable right now');}@@ -206,6 +223,21 @@ export function backfillStatus(.exhaustive();}+/** "Launch · Design", or "Launch · Announcements" for its announcement group. */+export function groupTitle(group: GroupDetail): string {+ if (!group.community) return group.name;+ return `${group.community.name} · ${group.community.announcements ? 'Announcements' : group.name}`;+}++/** WhatsApp deletes this group's messages after a while; Macro doesn't. */+export function disappearingNote(group: GroupDetail): string | undefined {+ if (!group.disappearingSeconds) return undefined;+ const timer = disappearingLabel(String(group.disappearingSeconds));+ return timer+ ? `Disappearing messages are on in WhatsApp (${timer}). Macro keeps them.`+ : 'Disappearing messages are on in WhatsApp. Macro keeps them.';+}+/** Shown above the oldest message once the import stopped at its limit. */export function historyStartNote(backfill: GroupBackfill | undefineddiff --git a/apps/web/src/features/whatsapp-group/core/rich.ts b/apps/web/src/features/whatsapp-group/core/rich.tsindex e8db1e2815..d6e185a9f4 100644--- a/apps/web/src/features/whatsapp-group/core/rich.ts+++ b/apps/web/src/features/whatsapp-group/core/rich.ts@@ -145,8 +145,10 @@ export function formatDuration(totalSeconds: number): string {: `${minutes}:${rest}`;}-/** WhatsApp's own disappearing-message timer names. */-function disappearingLabel(value: string | undefined): string | undefined {+/** WhatsApp's own disappearing-message timer names: "24 hours", "7 days". */+export function disappearingLabel(+ value: string | undefined+): string | undefined {const seconds = Number(value ?? '0');if (!Number.isFinite(seconds) || seconds <= 0) return undefined;const days = seconds / 86400;diff --git a/apps/web/src/features/whatsapp-group/core/route.ts b/apps/web/src/features/whatsapp-group/core/route.tsdeleted file mode 100644index 82ee77cb2d..0000000000--- a/apps/web/src/features/whatsapp-group/core/route.ts+++ /dev/null@@ -1,13 +0,0 @@-import { z } from 'zod';--const prefix = 'whatsapp-group:';-/**- * Groups once opened as their own `whatsapp-group:<id>` split component;- * restored layouts still carry that identity and now open in External.- */-export function parseWhatsAppGroupComponentId(- componentId: string-): string | undefined {- if (!componentId.startsWith(prefix)) return;- return z.uuid().safeParse(componentId.slice(prefix.length)).data;-}diff --git a/apps/web/src/features/whatsapp-group/primitives/conversation.ts b/apps/web/src/features/whatsapp-group/primitives/conversation.tsindex 23725c22fa..0e041dc030 100644--- a/apps/web/src/features/whatsapp-group/primitives/conversation.ts+++ b/apps/web/src/features/whatsapp-group/primitives/conversation.ts@@ -11,7 +11,7 @@ import {} from 'solid-js';import { v5 as uuidv5 } from 'uuid';import type { WhatsAppGroupCapabilities } from '../context/whatsapp-group-context';-import { attachmentProblem } from '../core/attachments';+import { attachmentProblem, type InboundAttachment } from '../core/attachments';import { markdownToWhatsApp } from '../core/formatting';import {canChangeMessage,@@ -23,12 +23,39 @@ import {} from '../core/group';import { composerMentions, mentionToken } from '../core/mentions';+/** A file the composer staged, with its local preview when it has one. */+type DraftFile = {+ id: string;+ name: string;+ mime?: string;+ /** The composer's local image or video preview. */+ previewUrl?: string;+ width?: number;+ height?: number;+};+/** What the composer hands over: its Markdown and the files it staged. */export type Draft = {markdown: string;- attachments: { id: string; name: string }[];+ attachments: DraftFile[];};+/** A sent file as the page already shows it: local preview and size. */+function sentAttachment(file: DraftFile, ordinal: number): InboundAttachment {+ const visual = !!file.previewUrl;+ return {+ ordinal,+ // Images and video show their local preview at once, like Chat's.+ state: visual ? 'ready' : 'loading',+ fileName: file.name,+ mime: file.mime ?? '',+ documentId: undefined,+ previewUrl: file.previewUrl,+ width: file.width,+ height: file.height,+ };+}+/** The message a reply quotes or an edit replaces. */export type ConversationTarget =| { kind: 'reply'; message: GroupMessage }@@ -50,7 +77,7 @@ const RETRY_DELAYS_MS = [1000, 2000, 4000];const UNKNOWN_SEND ="Couldn't reach WhatsApp. Check your connection and try again.";-export type ConversationHost = {+type ConversationHost = {/** Tells the person why a write did not go through. */notify: (message: string) => void;/** Puts a draft that was not sent back in the composer. */@@ -120,6 +147,20 @@ export function createConversation(.map((part) => part.row),];+ // Files this page sent keep their local preview and size on the stored+ // message, which DSS doesn't size, so the swap neither flashes nor jumps.+ const [kept, setKept] = createSignal(new Map<string, InboundAttachment[]>());+ const sentFiles = (messageId: string): InboundAttachment[] | undefined => {+ const stored = kept().get(messageId);+ if (stored) return stored;+ const part = pending().find(+ (item) =>+ item.sendId &&+ progressBySend().get(item.sendId)?.messageId === messageId+ );+ return part?.row.attachments.length ? part.row.attachments : undefined;+ };+const drop = (keys: string[]) =>setPending((parts) => parts.filter((part) => !keys.includes(part.key)));@@ -134,8 +175,14 @@ export function createConversation(const outcome = recordedOutcome(send);if (outcome === 'waiting') continue;if (outcome === 'accepted') {- if (arrived(part)) drop([part.key]);- else source.timeline.refetch();+ if (arrived(part)) {+ const messageId = send.messageId;+ if (messageId && part.row.attachments.length > 0)+ setKept((map) =>+ new Map(map).set(messageId, part.row.attachments)+ );+ drop([part.key]);+ } else source.timeline.refetch();continue;}drop([part.key]);@@ -241,7 +288,7 @@ export function createConversation(const submit = (draft: Draft): Result<Promise<void>, string> => {const group = source.group.data;const senderId = userId();- if (!group || !senderId) return err('This group is still loading.');+ if (!group || !senderId) return err('This chat is still loading.');if (!group.canSend) return err(composerNote(group));const mentioned = composerMentions(draft.markdown,@@ -313,13 +360,7 @@ export function createConversation(request.kind === 'media'? draft.attachments.filter((file) => file.id === request.uploadId)- .map((file, ordinal) => ({- ordinal,- state: 'loading' as const,- fileName: file.name,- mime: '',- documentId: undefined,- }))+ .map(sentAttachment): [],pending: true,},@@ -363,6 +404,7 @@ export function createConversation(return {rows,+ sentFiles,target,initialRead,initialUnreadCount,@@ -387,9 +429,7 @@ export function createConversation(): Promise<Result<{ uploadId: string }, string>> => {const group = source.group.data;if (!group?.canSend)- return err(- group ? composerNote(group) : 'This group is still loading.'- );+ return err(group ? composerNote(group) : 'This chat is still loading.');const problem = attachmentProblem(file, group.limits);if (problem) return err(problem);const result = await source.upload(file);diff --git a/apps/web/src/features/whatsapp-group/queries/capabilities.ts b/apps/web/src/features/whatsapp-group/queries/capabilities.tsindex 2e9869b104..fc743e9545 100644--- a/apps/web/src/features/whatsapp-group/queries/capabilities.ts+++ b/apps/web/src/features/whatsapp-group/queries/capabilities.ts@@ -112,7 +112,8 @@ export function createWhatsAppGroupCapabilities(},hasOlder: () => queries.messages.hasNextPage,loadingOlder: () => queries.messages.isFetchingNextPage,- loadOlder: () => queries.messages.fetchNextPage(),+ loadOlder: async () =>+ !(await queries.messages.fetchNextPage()).isFetchNextPageError,send: (request, idempotencyKey) =>Telemetry.span('whatsapp.group.send.attempt', async (span) => {span.setAttr('whatsapp.group.id', groupId());diff --git a/apps/web/src/features/whatsapp-group/queries/production-api.test.ts b/apps/web/src/features/whatsapp-group/queries/production-api.test.tsindex a772278857..481eeb06a9 100644--- a/apps/web/src/features/whatsapp-group/queries/production-api.test.ts+++ b/apps/web/src/features/whatsapp-group/queries/production-api.test.ts@@ -25,6 +25,7 @@ beforeEach(() => vi.clearAllMocks());it('decodes shared viewing separately from the callers own sending account and handles an absent roster', async () => {const detail = {id: '019a061e-0000-7000-8000-000000000001',+ kind: 'group',name: 'Shared group',user_id: 'macro|[email protected]',unread_count: 3,@@ -72,6 +73,7 @@ it('decodes pagination, deleted flags, reaction ownership and attachment statesbody: '',mentions: [],forwarded: false,+ view_once: false,rich: null,reply_to: null,sent_at: '2026-10-21T12:00:00Z',@@ -122,6 +124,7 @@ it('decodes mentions, forwarding, media presentation and every rich type, keepinkind: 'message',mentions: [],forwarded: false,+ view_once: false,rich: null,};const page = {diff --git a/apps/web/src/features/whatsapp-group/queries/production-api.ts b/apps/web/src/features/whatsapp-group/queries/production-api.tsindex d7dd5689a4..b144d884cc 100644--- a/apps/web/src/features/whatsapp-group/queries/production-api.ts+++ b/apps/web/src/features/whatsapp-group/queries/production-api.ts@@ -157,7 +157,7 @@ function writeFailure(})).with(P.union('forbidden', 'FORBIDDEN'), () => ({kind: 'refused',- reason: "Your WhatsApp can't send to this group.",+ reason: "Your WhatsApp can't send to this chat.",})).with(P.union('not_found', 'NOT_FOUND', 'GONE'), () => ({kind: 'refused',@@ -194,6 +194,7 @@ export const whatsappGroupApi: WhatsAppGroupApi = {list: async () =>(await throwOnErr(client.list)).map((group) => ({id: group.id,+ kind: group.kind,name: group.name,unreadCount: group.unread_count,canSend: group.can_send,@@ -202,6 +203,7 @@ export const whatsappGroupApi: WhatsAppGroupApi = {const view = await throwOnErr(() => client.detail(id));return {id,+ kind: view.kind,name: view.name,ownerId: view.user_id,accessLevel: view.access_level,@@ -222,11 +224,17 @@ export const whatsappGroupApi: WhatsAppGroupApi = {backfill: view.backfill? { state: view.backfill.state, imported: view.backfill.imported }: undefined,+ disappearingSeconds: view.disappearing_seconds ?? undefined,+ community: view.community+ ? {+ name: view.community.name,+ announcements: view.community.announcements,+ }+ : undefined,limits: {textBytes: view.limits.text_limit_bytes,attachmentBytes: view.limits.attachment_limit_bytes,attachmentTypes: view.limits.attachment_types,- maxAttachments: view.limits.max_attachments,editSeconds: view.limits.mutation_window_seconds,mutations: view.limits.mutations,},diff --git a/apps/web/src/features/whatsapp-group/route-views.tsx b/apps/web/src/features/whatsapp-group/route-views.tsxdeleted file mode 100644index cd1d02f9d7..0000000000--- a/apps/web/src/features/whatsapp-group/route-views.tsx+++ /dev/null@@ -1,27 +0,0 @@-import { useNavigate, useRouteParams } from '@app/lib/split-router';-import {- externalWhatsappGroupRoute,- whatsappGroupRoute,-} from '@app/routes/routes';-import { fireAndForget } from '@core/util/fireAndForget';-import { onMount } from 'solid-js';-import { WhatsAppGroupSkeleton } from './whatsapp-group-entry';--/** Retired `/whatsapp-group/:groupId` links open the group inside External. */-export function WhatsAppGroupRedirectRouteView() {- const params = useRouteParams(whatsappGroupRoute);- const navigate = useNavigate();- onMount(() =>- fireAndForget(- navigate(- {- route: externalWhatsappGroupRoute,- params: { groupId: params.groupId },- },- { replace: true }- ),- 'whatsapp-group.redirect'- )- );- return <WhatsAppGroupSkeleton />;-}diff --git a/apps/web/src/features/whatsapp-group/tests/fake-capabilities.ts b/apps/web/src/features/whatsapp-group/tests/fake-capabilities.tsindex 46500d1897..a5948dbd0d 100644--- a/apps/web/src/features/whatsapp-group/tests/fake-capabilities.ts+++ b/apps/web/src/features/whatsapp-group/tests/fake-capabilities.ts@@ -13,6 +13,7 @@ import type {export const group: GroupDetail = {id: '019a061e-0000-7000-8000-000000000001',+ kind: 'group',name: 'Design Crit',ownerId: 'macro|[email protected]',accessLevel: 'owner',@@ -25,7 +26,6 @@ export const group: GroupDetail = {textBytes: 65536,attachmentBytes: 33554432,attachmentTypes: ['image/png', 'application/pdf', 'audio/ogg'],- maxAttachments: 1,editSeconds: 900,mutations: ['reaction', 'edit', 'delete'],},@@ -78,7 +78,7 @@ export function createFakeGroup(timeline: read(timeline),hasOlder: () => false,loadingOlder: () => false,- loadOlder: vi.fn(async () => undefined),+ loadOlder: vi.fn(async () => true),send: vi.fn(async (_request: GroupSend,diff --git a/apps/web/src/features/whatsapp-group/views/whatsapp-group-view.test.tsx b/apps/web/src/features/whatsapp-group/views/whatsapp-group-view.test.tsxindex 9e2debb07a..a7f06f1117 100644--- a/apps/web/src/features/whatsapp-group/views/whatsapp-group-view.test.tsx+++ b/apps/web/src/features/whatsapp-group/views/whatsapp-group-view.test.tsx@@ -534,3 +534,121 @@ it('quotes stickers, voice notes and cards by what they are', () => {screen.getByRole('button', { name: 'Ana Ruiz: Poll: Lunch?' })).toBeTruthy();});++it('shows a sent image at once and keeps it in place when WhatsApp stores it', async () => {+ const fake = createFakeGroup();+ mount(fake);+ await mocks.composer?.onSend?.({+ value: '',+ mentions: [],+ attachments: [+ {+ id: 'upload-1',+ name: 'photo.png',+ kind: 'image',+ mimeType: 'image/png',+ previewSrc: 'blob:local-photo',+ width: 800,+ height: 600,+ },+ ],+ });+ await waitFor(() =>+ expect(fake.capabilities.send).toHaveBeenCalledWith(+ {+ kind: 'media',+ uploadId: 'upload-1',+ caption: undefined,+ replyTo: undefined,+ },+ expect.any(String)+ )+ );+ // The local preview, at its size, before WhatsApp has it: no file chip.+ const pending = screen.getByRole('button', { name: 'Open image viewer' });+ expect(pending.style.width).toBe('400px');+ expect(screen.queryByText(/Loading photo\.png/)).toBeNull();+ expect(+ [...document.querySelectorAll('img')].some(+ (image) => image.getAttribute('src') === 'blob:local-photo'+ )+ ).toBe(true);++ const key = fake.capabilities.send.mock.calls[0]?.[1];+ fake.setDelivery([+ { id: `send-${key}`, state: 'accepted', messageId: 'message-3' },+ ]);+ fake.setMessages([+ ...messages,+ {+ ...messages[1],+ id: 'message-3',+ body: '',+ replyTo: undefined,+ sentAt: new Date().toISOString(),+ // DSS stores no size for files sent from Macro.+ attachments: [+ {+ ordinal: 0,+ state: 'ready',+ fileName: 'photo.png',+ mime: 'image/png',+ documentId: 'document-sent',+ },+ ],+ },+ ]);+ await waitFor(() =>+ expect(document.querySelector('[data-message-id="message-3"]')).toBeTruthy()+ );+ // One image, the stored one, still at the sent size.+ const shown = screen.getAllByRole('button', { name: 'Open image viewer' });+ expect(shown).toHaveLength(1);+ expect(shown[0]?.style.width).toBe('400px');+ expect(+ [...document.querySelectorAll('img')].some(+ (image) =>+ image.getAttribute('src') === 'https://files.example.test/document-sent'+ )+ ).toBe(true);+});++it('names the community and notes disappearing messages quietly', () => {+ const fake = createFakeGroup({+ group: {+ ...group,+ name: 'Design',+ community: { name: 'Launch', announcements: false },+ disappearingSeconds: 604800,+ },+ });+ mount(fake);+ expect(screen.getByRole('heading', { name: 'Launch · Design' })).toBeTruthy();+ const note =+ 'Disappearing messages are on in WhatsApp (7 days). Macro keeps them.';+ expect(screen.getByLabelText(note)).toBeTruthy();+ expect(screen.getByText(note)).toBeTruthy();+ // Sending works as in any group.+ expect(screen.getByTestId('whatsapp-composer')).toBeTruthy();+});++it('shows a direct chat as the person, and who can reply when shared', () => {+ const fake = createFakeGroup({+ group: {+ ...group,+ kind: 'direct',+ name: 'Ana Ruiz',+ members: [],+ accessLevel: 'view',+ canSend: false,+ sendReason: 'not_observing',+ },+ });+ mount(fake);+ expect(screen.getByRole('heading', { name: 'Ana Ruiz' })).toBeTruthy();+ expect(screen.queryByRole('button', { name: /member/ })).toBeNull();+ expect(screen.getByRole('status').textContent).toMatch(+ /^Only .+ can reply in this chat$/+ );+ expect(screen.queryByTestId('whatsapp-composer')).toBeNull();+});diff --git a/apps/web/src/features/whatsapp-group/views/whatsapp-group-view.tsx b/apps/web/src/features/whatsapp-group/views/whatsapp-group-view.tsxindex 2c1c0514b8..c5f7f79dc5 100644--- a/apps/web/src/features/whatsapp-group/views/whatsapp-group-view.tsx+++ b/apps/web/src/features/whatsapp-group/views/whatsapp-group-view.tsx@@ -11,18 +11,21 @@ import { SenderName } from '@channel/Message/SenderName';import { MaybeMessageActionDrawerManager } from '@channel/Mobile/MessageActionDrawerManager';import { HeaderActionButton } from '@components/app/HeaderActionButton';import { FloatRegionOrInline } from '@components/app/mobile/float-regions/FloatRegion';+import { CustomScrollbar } from '@core/component/CustomScrollbar';import { StaticMarkdownContext } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';import { toast } from '@core/component/Toast/Toast';import type {MessageActionContext,MessageActions,} from '@core/messages/types';+import { getDisplayName, tryMacroId } from '@core/user';import type { IUser } from '@core/user/types';import { fireAndForget } from '@core/util/fireAndForget';import ShareFatIcon from '@phosphor/share-fat.svg';+import TimerIcon from '@phosphor/timer.svg';import UsersThreeIcon from '@phosphor/users-three.svg';import WhatsappIcon from '@phosphor/whatsapp-logo.svg';-import { Button, ConfirmDialog } from '@ui';+import { Button, ConfirmDialog, Tooltip } from '@ui';import {createEffect,createMemo,@@ -50,8 +53,10 @@ import {canChangeMessage,composerNote,composerPlaceholder,+ disappearingNote,type GroupDetail,type GroupMessage,+ groupTitle,historyStartNote,} from '../core/group';import { mentionToken } from '../core/mentions';@@ -118,33 +123,78 @@ function ForwardedTag() {);}-/** A message's images, video and voice notes, played inline. */-function MessageMedia(props: { attachments: InboundAttachment[] }) {+function sameMediaFile(+ a: InboundMediaFile | undefined,+ b: InboundMediaFile | undefined+): boolean {+ if (!a || !b) return a === b;+ return (Object.keys(a) as (keyof InboundMediaFile)[]).every(+ (key) => a[key] === b[key]+ );+}++/**+ * A message's images, video and voice notes, played inline. `sent` is what+ * this page showed for a file it sent: its local preview and size stand in+ * until the stored file loads.+ */+function MessageMedia(props: {+ attachments: InboundAttachment[];+ sent?: InboundAttachment[];+}) {const source = useWhatsAppGroup();const media = createMemo(() =>- props.attachments.flatMap((attachment) => {- const kind = inlineMediaKind(attachment);- return kind && attachment.documentId- ? [{ attachment, kind, documentId: attachment.documentId }]- : [];+ props.attachments.flatMap((attachment, index) => {+ const local = props.sent?.[index];+ const file: InboundAttachment = local+ ? {+ ...attachment,+ previewUrl: attachment.previewUrl ?? local.previewUrl,+ width: attachment.width ?? local.width,+ height: attachment.height ?? local.height,+ }+ : attachment;+ const kind = inlineMediaKind(file);+ return kind ? [{ attachment: file, kind }] : [];}));- const files = mapArray(media, (file) => {- const url = source.fileUrl(() => file.documentId);- return (): InboundMediaFile => ({- id: file.documentId,- kind: file.kind,- fileName: file.attachment.fileName,- url: url.data,- width: file.attachment.width,- height: file.attachment.height,- durationSeconds: file.attachment.durationSeconds,- presentation: file.attachment.presentation,- });- });+ const files = mapArray(+ () => media().map((file) => file.attachment.documentId ?? ''),+ (documentId, index) => {+ const stored = documentId ? source.fileUrl(() => documentId) : undefined;+ // A refetch signs a new URL for the same file; keep the first so the+ // image doesn't reload (and the row shrink and grow) on every refresh.+ let firstUrl: string | undefined;+ const url = () => {+ firstUrl ??= stored?.data;+ return firstUrl;+ };+ // One object per change, so Chat's media rows don't remount.+ return createMemo(+ (): InboundMediaFile | undefined => {+ const file = media()[index()];+ if (!file) return undefined;+ return {+ id: documentId || `${file.attachment.ordinal}`,+ kind: file.kind,+ fileName: file.attachment.fileName,+ url: url() ?? file.attachment.previewUrl,+ previewUrl: file.attachment.previewUrl,+ width: file.attachment.width,+ height: file.attachment.height,+ durationSeconds: file.attachment.durationSeconds,+ presentation: file.attachment.presentation,+ };+ },+ undefined,+ { equals: sameMediaFile }+ );+ }+ );+ const shown = () => files().flatMap((file) => file() ?? []);return (- <Show when={files().length > 0}>- <InboundMedia files={files().map((file) => file())} />+ <Show when={shown().length > 0}>+ <InboundMedia files={shown()} /></Show>);}@@ -185,29 +235,28 @@ export function WhatsAppGroupView(props: {// Distance from the bottom at the last scroll, to hold the view in place// when imported history lands above it.let fromBottom = 0;+ // The reader is at the bottom and stays there as rows and media grow.+ // Only the reader's own scrolling changes it: layout (media loading,+ // shrinking, clamping) fires scroll events that say nothing about intent.+ let following = true;+ let intentAt = 0;+ const intent = () => {+ intentAt = Date.now();+ };onCleanup(() => {alive = false;});// Media WhatsApp sent no size for grows after it loads; a reader who was- // at the bottom stays there. Rows with loaded media are watched for that- // growth (it lands after the load event).- const pinBottom = () => {- if (alive && scroller && fromBottom < 80)+ // at the bottom stays there whenever the timeline's content changes size.+ const grown = new ResizeObserver(() => {+ if (alive && scroller && following)scroller.scrollTop = scroller.scrollHeight;- };- const grown = new ResizeObserver(pinBottom);+ });onCleanup(() => grown.disconnect());- const holdBottom = (event: Event) => {- const row =- event.target instanceof Element- ? event.target.closest('[data-message-id]')- : null;- if (row) grown.observe(row);- };+ const [scrollerElement, setScrollerElement] = createSignal<HTMLDivElement>();const setScroller = (element: HTMLDivElement) => {scroller = element;- element.addEventListener('load', holdBottom, true);- element.addEventListener('loadedmetadata', holdBottom, true);+ setScrollerElement(element);};/** Choosing a reply or an edit puts the composer in that mode. */@@ -303,10 +352,14 @@ export function WhatsAppGroupView(props: {const latest = rows().at(-1)?.id;if (!latest || latest === newest) return;const follow =- !newest || nearBottom() || !!messagesById().get(latest)?.pending;+ !newest ||+ following ||+ nearBottom() ||+ !!messagesById().get(latest)?.pending;newest = latest;queueMicrotask(() => {if (!alive || !follow) return;+ following = true;if (scroller) scroller.scrollTop = scroller.scrollHeight;markRead();});@@ -315,7 +368,7 @@ export function WhatsAppGroupView(props: {const first = rows()[0]?.id;const grewAbove = !!oldest && !!first && first !== oldest;oldest = first;- if (!grewAbove || !scroller) return;+ if (!grewAbove || !scroller || following) return;scroller.scrollTop =scroller.scrollHeight - scroller.clientHeight - fromBottom;});@@ -334,28 +387,31 @@ export function WhatsAppGroupView(props: {? undefined: historyStartNote(source.group.data?.backfill);const older = async () => {+ following = false;const height = scroller?.scrollHeight ?? 0;const offset = scroller?.scrollTop ?? 0;- await source.loadOlder();+ const loaded = await source.loadOlder();if (alive && scroller)scroller.scrollTop = offset + scroller.scrollHeight - height;+ return loaded;};const openQuoted = async (id: string) => {const find = () =>scroller?.querySelector(`[data-message-id="${CSS.escape(id)}"]`);- try {- while (alive && !find() && source.hasOlder()) {- const count = storedCount();- await older();- if (storedCount() === count) break;+ while (alive && !find() && source.hasOlder()) {+ const count = storedCount();+ if (!(await older())) {+ if (alive)+ toast.failure("Couldn't load the quoted message. Try again.");+ return;}- if (!alive) return;- const row = find();- if (row) row.scrollIntoView({ block: 'center', behavior: 'smooth' });- else toast.alert('This quoted message is no longer available.');- } catch {- if (alive) toast.failure("Couldn't load the quoted message. Try again.");+ if (storedCount() === count) break;}+ if (!alive) return;+ const row = find();+ if (row) following = false;+ if (row) row.scrollIntoView({ block: 'center', behavior: 'smooth' });+ else toast.alert('This quoted message is no longer available.');};/**@@ -418,6 +474,10 @@ export function WhatsAppGroupView(props: {attachments: snapshot.attachments.map((file) => ({id: file.id,name: file.name,+ mime: file.mimeType,+ previewUrl: file.kind === 'document' ? undefined : file.previewSrc,+ width: file.width,+ height: file.height,})),};snapshots.set(draft, snapshot);@@ -427,10 +487,7 @@ export function WhatsAppGroupView(props: {};return (- <div- class="flex h-full min-h-0 min-w-0 flex-col bg-panel text-ink touch:pt-(--mobile-content-inset-top)"- style={{ '--user-icon-width': '32px', '--message-padding-x': '16px' }}- >+ <div class="flex h-full min-h-0 min-w-0 flex-col bg-panel text-ink touch:pt-(--mobile-content-inset-top)"><header class="flex h-12 shrink-0 items-center gap-2 px-3 touch:px-(--mobile-chrome-gutter)">{props.leading}<span@@ -441,24 +498,44 @@ export function WhatsAppGroupView(props: {</span><div class="flex min-w-0 flex-1 items-baseline gap-2"><h1 class="ph-no-capture min-w-0 truncate text-sm font-semibold">- {source.group.data?.name ?? 'WhatsApp group'}+ {source.group.data+ ? groupTitle(source.group.data)+ : 'WhatsApp chat'}</h1>+ <Show when={source.group.data && disappearingNote(source.group.data)}>+ {(note) => (+ <Tooltip+ label={note()}+ as="span"+ class="flex shrink-0 self-center"+ >+ <TimerIcon+ class="size-3.5 text-ink-extra-muted"+ aria-label={note()}+ data-whatsapp-disappearing+ />+ </Tooltip>+ )}+ </Show><span class="shrink-0 truncate text-xs text-ink-extra-muted mobile:hidden"><Show when={importing()}>{(status) => <> · {status()}</>}</Show></span></div><div class="flex shrink-0 items-center gap-1">- <HeaderActionButton- label={memberLabel()}- icon={<UsersThreeIcon />}- tooltip="WhatsApp members"- onClick={() => setRoster((value) => !value)}- />+ {/* A direct chat is the person in the title; it has no roster. */}+ <Show when={source.group.data?.kind !== 'direct'}>+ <HeaderActionButton+ label={memberLabel()}+ icon={<UsersThreeIcon />}+ tooltip="WhatsApp members"+ onClick={() => setRoster((value) => !value)}+ />+ </Show>{props.share}</div></header>- <Show when={roster()}>+ <Show when={roster() && source.group.data?.kind !== 'direct'}><aside class="max-h-56 shrink-0 overflow-y-auto border-b border-edge-muted p-4"><h2 class="mb-2 text-sm font-medium">WhatsApp members</h2><p class="mb-2 text-xs text-ink-muted">@@ -490,191 +567,245 @@ export function WhatsAppGroupView(props: {</Show><StaticMarkdownContext><MaybeMessageActionDrawerManager>- <div- ref={setScroller}- class="min-h-0 flex-1 overflow-y-auto overscroll-contain pb-4 [overflow-anchor:none] mobile:pb-(--mobile-content-inset-bottom)"- role="log"- aria-label="WhatsApp messages"- onScroll={() => {- if (!scroller) return;- fromBottom =- scroller.scrollHeight -- scroller.scrollTop -- scroller.clientHeight;- if (fromBottom < 60) markRead();- }}- >- <Show when={source.group.isPending || source.timeline.isPending}>- <p role="status" class="p-6 text-sm text-ink-muted">- Loading WhatsApp group…- </p>- </Show>- <Show when={source.group.isError || source.timeline.isError}>- <div class="p-4 text-sm">- <p role="alert">- Couldn't load this group. You may need access from its owner.- </p>- <Button- variant="outline"- size="sm"- onClick={() => {- source.group.refetch();- source.timeline.refetch();- }}- >- Try again- </Button>- </div>- </Show>- <Show when={source.hasOlder()}>- <div class="flex justify-center p-3">- <Button- variant="ghost"- size="sm"- disabled={source.loadingOlder()}- onClick={() => fireAndForget(older(), 'whatsapp-group.older')}+ {/* Chat's thread list layout: a full-width scroller with Chat's+ custom scrollbar, rows in the centered message column. */}+ <div class="relative min-h-0 flex-1">+ <div+ ref={setScroller}+ class="scrollbar-hidden h-full overflow-y-auto overscroll-contain px-2 pb-4 [overflow-anchor:none] mobile:pb-(--mobile-content-inset-bottom)"+ role="log"+ aria-label="WhatsApp messages"+ onWheel={intent}+ onTouchMove={intent}+ onKeyDown={intent}+ onPointerDown={intent}+ onScroll={() => {+ if (!scroller) return;+ fromBottom =+ scroller.scrollHeight -+ scroller.scrollTop -+ scroller.clientHeight;+ if (Date.now() - intentAt < 1000) following = fromBottom < 80;+ if (fromBottom < 60) markRead();+ }}+ >+ <div class="flex w-full justify-center">+ <div+ ref={(content) => grown.observe(content)}+ class="macro-message-width relative">- {source.loadingOlder() ? 'Loading…' : 'Load earlier messages'}- </Button>- </div>- </Show>- <Show when={source.timeline.data && !source.hasOlder()}>- <Show when={importing() ?? historyStart()}>- {(note) => (- <p- role="status"- class="p-3 text-center text-xs text-ink-muted"+ <Show+ when={source.group.isPending || source.timeline.isPending}>- {note()}- </p>- )}- </Show>- </Show>- <Show- when={source.timeline.data && rows().length === 0 && !importing()}- >- <p class="p-6 text-center text-sm text-ink-muted">- No messages yet. New WhatsApp messages will appear here.- </p>- </Show>- <For each={rows()}>- {(message) => {- const systemLine = () =>- message.kind === 'system' && message.rich?.type === 'system'- ? message.rich- : undefined;- const meta = () =>- listMeta()[- message.kind === 'system'- ? `activity:${message.id}`- : message.id- ];- const quoted = () =>- message.replyTo- ? messagesById().get(message.replyTo)- : undefined;- const actions = actionsFor(message);- const placeholders = () =>- message.attachments.filter(- (attachment) => attachment.state !== 'ready'- );- return (+ <p role="status" class="p-6 text-sm text-ink-muted">+ Loading WhatsApp chat…+ </p>+ </Show>+ <Show when={source.group.isError || source.timeline.isError}>+ <div class="p-4 text-sm">+ <p role="alert">+ Couldn't load this chat. You may need access from its+ owner.+ </p>+ <Button+ variant="outline"+ size="sm"+ onClick={() => {+ source.group.refetch();+ source.timeline.refetch();+ }}+ >+ Try again+ </Button>+ </div>+ </Show>+ <Show when={source.hasOlder()}>+ <div class="flex justify-center p-3">+ <Button+ variant="ghost"+ size="sm"+ disabled={source.loadingOlder()}+ onClick={() =>+ fireAndForget(older(), 'whatsapp-group.older')+ }+ >+ {source.loadingOlder()+ ? 'Loading…'+ : 'Load earlier messages'}+ </Button>+ </div>+ </Show>+ <Show when={source.timeline.data && !source.hasOlder()}>+ <Show+ when={+ source.group.data && disappearingNote(source.group.data)+ }+ >+ {(note) => (+ <p class="p-3 text-center text-xs text-ink-muted">+ {note()}+ </p>+ )}+ </Show>+ <Show when={importing() ?? historyStart()}>+ {(note) => (+ <p+ role="status"+ class="p-3 text-center text-xs text-ink-muted"+ >+ {note()}+ </p>+ )}+ </Show>+ </Show><Show- when={message.kind !== 'system'}- fallback={- <>- <DateDivider- createdAt={message.sentAt}- listMeta={meta()}- />- <Show when={systemLine()}>- {(line) => (- <WhatsAppSystemLine- id={message.id}- line={line()}- occurredAt={message.sentAt}- />- )}- </Show>- </>+ when={+ source.timeline.data &&+ rows().length === 0 &&+ !importing()}>- <DateDivider createdAt={message.sentAt} listMeta={meta()} />- <NewDivider- createdAt={message.sentAt}- listMeta={meta()}- onDismiss={markRead}- />- <ChannelMessage- parent={{- type: 'whatsapp_group',- id: source.group.data?.id ?? '',- }}- message={groupMessageData(message, props.userId)}- actions={actions}- listMeta={meta()}- targeted={- conversation.target()?.message.id === message.id- }- renderContent={(content) => (- <>- <Show when={!message.deleted && message.forwarded}>- <ForwardedTag />- </Show>- <Show when={!message.deleted && message.replyTo}>- {(id) => (- <button- type="button"- class="mb-1 block max-w-full truncate border-l-2 border-accent py-0.5 pl-3 text-left text-xs text-ink-muted"- onClick={() =>- fireAndForget(- openQuoted(id()),- 'whatsapp-group.quote'- )- }- >+ <p class="p-6 text-center text-sm text-ink-muted">+ No messages yet. New WhatsApp messages will appear here.+ </p>+ </Show>+ <For each={rows()}>+ {(message) => {+ const systemLine = () =>+ message.kind === 'system' &&+ message.rich?.type === 'system'+ ? message.rich+ : undefined;+ const meta = () =>+ listMeta()[+ message.kind === 'system'+ ? `activity:${message.id}`+ : message.id+ ];+ const quoted = () =>+ message.replyTo+ ? messagesById().get(message.replyTo)+ : undefined;+ const actions = actionsFor(message);+ const placeholders = () =>+ message.attachments.filter(+ (attachment) => attachment.state !== 'ready'+ );+ return (+ <Show+ when={message.kind !== 'system'}+ fallback={+ <>+ <DateDivider+ createdAt={message.sentAt}+ listMeta={meta()}+ />+ <Show when={systemLine()}>+ {(line) => (+ <WhatsAppSystemLine+ id={message.id}+ line={line()}+ occurredAt={message.sentAt}+ />+ )}+ </Show>+ </>+ }+ >+ <NewDivider+ createdAt={message.sentAt}+ listMeta={meta()}+ onDismiss={markRead}+ />+ <DateDivider+ createdAt={message.sentAt}+ listMeta={meta()}+ />+ <ChannelMessage+ parent={{+ type: 'whatsapp_group',+ id: source.group.data?.id ?? '',+ }}+ message={groupMessageData(message, props.userId)}+ actions={actions}+ listMeta={meta()}+ targeted={+ conversation.target()?.message.id === message.id+ }+ renderContent={(content) => (+ <>+ <Show+ when={!message.deleted && message.forwarded}+ >+ <ForwardedTag />+ </Show><Show- when={quoted()}- fallback="View quoted message"+ when={!message.deleted && message.replyTo}>- {(reply) => (- <>- <SenderName- message={groupMessageData(- reply(),- props.userId+ {(id) => (+ <button+ type="button"+ class="mb-1 block max-w-full truncate border-l-2 border-accent py-0.5 pl-3 text-left text-xs text-ink-muted"+ onClick={() =>+ fireAndForget(+ openQuoted(id()),+ 'whatsapp-group.quote'+ )+ }+ >+ <Show+ when={quoted()}+ fallback="View quoted message"+ >+ {(reply) => (+ <>+ <SenderName+ message={groupMessageData(+ reply(),+ props.userId+ )}+ />+ : {quotePreview(reply())}+ </>)}- />- : {quotePreview(reply())}- </>+ </Show>+ </button>)}</Show>- </button>+ {content}+ <Show when={!message.deleted && message.rich}>+ {(rich) => <RichCard rich={rich()} />}+ </Show>+ <MessageMedia+ attachments={message.attachments}+ sent={conversation.sentFiles(message.id)}+ />+ <Show when={placeholders().length > 0}>+ <div class="mt-1 flex flex-wrap gap-2">+ <For each={placeholders()}>+ {(attachment) => (+ <InboundAttachmentPlaceholder+ attachment={attachment}+ />+ )}+ </For>+ </div>+ </Show>+ </>)}- </Show>- {content}- <Show when={!message.deleted && message.rich}>- {(rich) => <RichCard rich={rich()} />}- </Show>- <MessageMedia attachments={message.attachments} />- <Show when={placeholders().length > 0}>- <div class="mt-1 flex flex-wrap gap-2">- <For each={placeholders()}>- {(attachment) => (- <InboundAttachmentPlaceholder- attachment={attachment}- />- )}- </For>- </div>- </Show>- </>- )}- />- </Show>- );- }}- </For>+ />+ </Show>+ );+ }}+ </For>+ </div>+ </div>+ </div>+ <CustomScrollbar+ scrollContainer={scrollerElement}+ watchContent+ onScrollIntent={intent}+ /></div></MaybeMessageActionDrawerManager></StaticMarkdownContext>@@ -684,31 +815,40 @@ export function WhatsAppGroupView(props: {<Showwhen={group().canSend && !stopped()}fallback={- <div class="mx-3 mb-3 flex shrink-0 flex-wrap items-center gap-2 border-t border-edge-muted px-1 pt-3 text-sm text-ink-muted touch:pointer-events-auto touch:mx-(--mobile-chrome-gutter) touch:mb-2 touch:rounded-2xl touch:border-0 touch:island touch:px-3 touch:py-2">- <span role="status">- {stopped()- ? 'This group is no longer syncing'- : composerNote(group())}- </span>- <Show- when={- group().sendReason === 'no_account' ||- group().sendReason === 'disconnected'- }- >- <Button- variant="outline"- size="sm"- onClick={props.onConnect}+ <ChannelInputContainer>+ <div class="macro-message-width flex shrink-0 flex-wrap items-center gap-2 border-t border-edge-muted px-4 pt-3 text-sm text-ink-muted touch:rounded-2xl touch:border-0 touch:island touch:px-3 touch:py-2">+ <span role="status">+ {stopped()+ ? 'This chat is no longer syncing'+ : composerNote(+ group(),+ getDisplayName(tryMacroId(group().ownerId)) ||+ undefined+ )}+ </span>+ <Show+ when={+ group().sendReason === 'no_account' ||+ group().sendReason === 'disconnected'+ }>- Connect WhatsApp- </Button>- </Show>- </div>+ <Button+ variant="outline"+ size="sm"+ onClick={props.onConnect}+ >+ Connect WhatsApp+ </Button>+ </Show>+ </div>+ </ChannelInputContainer>}><ChannelInputContainer>- <div class="flex w-full min-w-0 flex-col px-3 touch:px-0">+ <div+ data-keep-keyboard+ class="relative flex w-full flex-col items-center gap-1"+ ><Show when={conversation.target()}>{(target) => (<InputFlag@@ -803,7 +943,7 @@ export function WhatsAppGroupView(props: {<ConfirmDialogopen={stopping()}onOpenChange={setStopping}- title="Stop syncing this group?"+ title="Stop syncing this chat?"body="Its history stays in Macro. New messages will stop syncing."confirmLabel="Stop syncing"tone="danger"diff --git a/apps/web/src/features/whatsapp-group/whatsapp-group-entry.tsx b/apps/web/src/features/whatsapp-group/whatsapp-group-entry.tsxindex 54ac93c75d..cd4174a917 100644--- a/apps/web/src/features/whatsapp-group/whatsapp-group-entry.tsx+++ b/apps/web/src/features/whatsapp-group/whatsapp-group-entry.tsx@@ -10,7 +10,7 @@ const Group = lazy(async () => ({export function WhatsAppGroupSkeleton() {return (<p role="status" class="p-6 text-sm text-ink-muted">- Loading WhatsApp group…+ Loading WhatsApp chat…</p>);}diff --git a/apps/web/src/features/whatsapp-group/whatsapp-group.tsx b/apps/web/src/features/whatsapp-group/whatsapp-group.tsxindex 4202746df0..8b77230c63 100644--- a/apps/web/src/features/whatsapp-group/whatsapp-group.tsx+++ b/apps/web/src/features/whatsapp-group/whatsapp-group.tsx@@ -28,7 +28,7 @@ export function WhatsAppGroup(props: {() => userId() ?? '',() => props.groupId);- useSplitDisplayName(() => source.group.data?.name ?? 'WhatsApp group');+ useSplitDisplayName(() => source.group.data?.name ?? 'WhatsApp chat');const share = useShareModal(() => {const group = source.group.data;if (!group) return;diff --git a/apps/web/src/features/whatsapp-linked/AGENTS.md b/apps/web/src/features/whatsapp-linked/AGENTS.mdindex f45dad7ede..658ba473aa 100644--- a/apps/web/src/features/whatsapp-linked/AGENTS.md+++ b/apps/web/src/features/whatsapp-linked/AGENTS.md@@ -3,8 +3,8 @@## What it isPersonal WhatsApp accounts linked as devices (External tab → WhatsApp): link an-account by QR, list its WhatsApp chats, and add a group as its own shareable-Macro entity. Each person sends from their own account. Behind the `enable-whatsapp-linked` flag.+account by QR, list its WhatsApp chats, and add a group or direct chat as its+own shareable Macro entity. Each person sends from their own account. Behind the `enable-whatsapp-linked` flag.## Start here@@ -21,7 +21,8 @@ Macro entity. Each person sends from their own account. Behind the `enable-whats- Owns: the WhatsApp account page, pairing dialog and one-click adoption(no dialog; DSS names the group after WhatsApp).-- Group timeline and sending: `features/whatsapp-group`; no channel integration.+- Chat timeline and sending: `features/whatsapp-group`; channels only reach a+ chat through a mention, which shares it (`MentionsMenu`).- One account at a time: there is no replace flow; switching meansDisconnect, then Connect.- Not here: the External tab shell, the groups nested under WhatsApp in its@@ -46,11 +47,13 @@ Macro entity. Each person sends from their own account. Behind the `enable-whats`core/adopt.ts` words each one. Never show a catch-all message.- The chat list (`GET /meta/linked/chats`) arrives sorted by recent activity;keep DSS's order. Sections follow its `group`/`shared`/`canAdd`/- `cannotAddReason` fields; direct chats are listed but not addable until DSS- says `canAdd`.+ `cannotAddReason` fields; direct chats are addable, except the chat with+ yourself.+ User-facing copy says "chat", not "group". Community groups show as "Community · Group"+ (`communityTitle`); disappearing and community groups are addable, a+ community itself is not.- Adoption grants access only to its owner; the generic Share dialog manages- later access. No special audience lists or WhatsApp membership requirement- for viewing.+ later access. Viewing never requires WhatsApp membership.## Checksdiff --git a/apps/web/src/features/whatsapp-linked/components/account-card.tsx b/apps/web/src/features/whatsapp-linked/components/account-card.tsxindex cc52e4f754..a2bb8d8d40 100644--- a/apps/web/src/features/whatsapp-linked/components/account-card.tsx+++ b/apps/web/src/features/whatsapp-linked/components/account-card.tsx@@ -20,8 +20,8 @@ export function ConnectCard(props: {<Item.Title>WhatsApp</Item.Title><Item.Description>{props.reconnect- ? 'WhatsApp signed this device out. Link it again to keep your groups syncing.'- : 'Link your personal WhatsApp as a linked device. Only groups you choose come into Macro.'}+ ? 'WhatsApp signed this device out. Link it again to keep your chats syncing.'+ : 'Link your personal WhatsApp as a linked device. Only chats you choose come into Macro.'}</Item.Description><Item.Metadata>Macro connects as an unofficial WhatsApp client, which WhatsApp maydiff --git a/apps/web/src/features/whatsapp-linked/components/chat-list.tsx b/apps/web/src/features/whatsapp-linked/components/chat-list.tsxindex 471e16095b..d2532eb735 100644--- a/apps/web/src/features/whatsapp-linked/components/chat-list.tsx+++ b/apps/web/src/features/whatsapp-linked/components/chat-list.tsx@@ -1,12 +1,18 @@import { formatRelativeDate } from '@core/util/time';import CaretDownIcon from '@phosphor/caret-down.svg';+import MegaphoneIcon from '@phosphor/megaphone-simple.svg';import PlusIcon from '@phosphor/plus.svg';import UserIcon from '@phosphor/user.svg';import UsersThreeIcon from '@phosphor/users-three.svg';import { Button, cn } from '@ui';import { CollapseTransition } from '@ui/components/CollapseTransition';import { createSignal, For, type JSX, Match, Show, Switch } from 'solid-js';-import { cannotAddLabel, chatMetadata, type WhatsAppChat } from '../core/chat';+import {+ cannotAddLabel,+ chatMetadata,+ communityTitle,+ type WhatsAppChat,+} from '../core/chat';/** A list heading, on the same 16px rail as the rows' icons. */export function ChatSectionHeading(props: { id: string; children: string }) {@@ -40,15 +46,17 @@ function ChatRow(props: {data-whatsapp-chat-kind={props.chat.kind}><span aria-hidden="true" class="flex size-4 shrink-0 text-ink-muted">- <Show- when={props.chat.kind === 'direct'}- fallback={<UsersThreeIcon class="size-4" />}- >- <UserIcon class="size-4" />- </Show>+ <Switch fallback={<UsersThreeIcon class="size-4" />}>+ <Match when={props.chat.kind === 'direct'}>+ <UserIcon class="size-4" />+ </Match>+ <Match when={props.chat.community?.announcements}>+ <MegaphoneIcon class="size-4" />+ </Match>+ </Switch></span><span class="ph-no-capture min-w-0 shrink truncate font-medium text-ink">- {props.chat.name}+ {communityTitle(props.chat.name, props.chat.community)}</span><span class="min-w-0 shrink-[2] truncate text-xs text-ink-extra-muted">{chatMetadata(props.chat)}@@ -141,7 +149,7 @@ export function AddableChatList(props: {onOpenGroup: (groupId: string) => void;}) {return (- <ul class="flex flex-col" aria-label="Groups to add to Macro">+ <ul class="flex flex-col" aria-label="Chats to add to Macro"><Foreach={props.chats}fallback={@@ -178,7 +186,7 @@ export function AddableChatList(props: {tooltip={props.canAdd? undefined- : 'Adding WhatsApp groups is turned off'+ : 'Adding WhatsApp chats is turned off'}onClick={() => props.onAdd(chat)}>diff --git a/apps/web/src/features/whatsapp-linked/core/adopt.test.ts b/apps/web/src/features/whatsapp-linked/core/adopt.test.tsindex bfae16c730..970ee42caa 100644--- a/apps/web/src/features/whatsapp-linked/core/adopt.test.ts+++ b/apps/web/src/features/whatsapp-linked/core/adopt.test.ts@@ -12,7 +12,7 @@ describe('adoption refusals', () => {))).toBe(- "Your WhatsApp isn't allowed to add this group. Check that you're still a member."+ "Your WhatsApp isn't allowed to add this chat. Check that you're still in it.");expect(adoptFailureMessage(@@ -26,7 +26,7 @@ describe('adoption refusals', () => {))).toBe(- "WhatsApp didn't accept this group: groups with disappearing messages cannot be added."+ "WhatsApp didn't accept this chat: groups with disappearing messages cannot be added.");expect(adoptFailureMessage(diff --git a/apps/web/src/features/whatsapp-linked/core/adopt.ts b/apps/web/src/features/whatsapp-linked/core/adopt.tsindex 57383cbb43..a6ab75762b 100644--- a/apps/web/src/features/whatsapp-linked/core/adopt.ts+++ b/apps/web/src/features/whatsapp-linked/core/adopt.ts@@ -22,17 +22,17 @@ export function adoptFailureMessage(failure: AdoptRefusal): string {.with({ reason: 'not-allowed' },() =>- "Your WhatsApp isn't allowed to add this group. Check that you're still a member."+ "Your WhatsApp isn't allowed to add this chat. Check that you're still in it.")- .with({ reason: 'gone' }, () => 'This group is no longer on your WhatsApp.')- .with({ reason: 'already-added' }, () => 'This group is already in Macro.')+ .with({ reason: 'gone' }, () => 'This chat is no longer on your WhatsApp.')+ .with({ reason: 'already-added' }, () => 'This chat is already in Macro.').with({ reason: 'disconnected' },- () => 'Your WhatsApp is disconnected. Reconnect it, then add the group.'+ () => 'Your WhatsApp is disconnected. Reconnect it, then add the chat.').with({ reason: 'turned-off' },- () => 'Adding WhatsApp groups is turned off.'+ () => 'Adding WhatsApp chats is turned off.').with({ reason: 'rate-limited' },@@ -44,11 +44,11 @@ export function adoptFailureMessage(failure: AdoptRefusal): string {).with({ reason: 'rejected' },- ({ detail }) => `WhatsApp didn't accept this group: ${detail}.`+ ({ detail }) => `WhatsApp didn't accept this chat: ${detail}.`).with({ reason: 'signed-out' },- () => 'Your Macro session expired. Sign in again to add this group.'+ () => 'Your Macro session expired. Sign in again to add this chat.').with({ reason: 'unreachable' },diff --git a/apps/web/src/features/whatsapp-linked/core/chat.ts b/apps/web/src/features/whatsapp-linked/core/chat.tsindex 4dc049b665..4e57b807c8 100644--- a/apps/web/src/features/whatsapp-linked/core/chat.ts+++ b/apps/web/src/features/whatsapp-linked/core/chat.ts@@ -3,6 +3,25 @@ export type InMacro =| { kind: 'own'; groupId: string }| { kind: 'shared'; groupId: string; ownerId: string; ownerName: string };+/** The WhatsApp community a group belongs to. */+export type ChatCommunity = {+ name: string;+ /** The community's announcement group (named after the community). */+ announcements: boolean;+};++/**+ * "Launch · Design", or "Launch · Announcements": WhatsApp names a+ * community's groups under it.+ */+export function communityTitle(+ name: string,+ community: ChatCommunity | undefined+): string {+ if (!community) return name;+ return `${community.name} · ${community.announcements ? 'Announcements' : name}`;+}+/** A conversation in the connected account's WhatsApp chat list. */export type WhatsAppChat = {jid: string;@@ -17,6 +36,8 @@ export type WhatsAppChat = {canAdd: boolean;/** DSS's reason this chat can't be added, when it can't. */cannotAddReason: string | undefined;+ /** Set for a group inside a WhatsApp community. */+ community?: ChatCommunity;};/**@@ -46,14 +67,14 @@ const fold = (text: string) =>export function matchesChatQuery(chat: WhatsAppChat, query: string): boolean {const wanted = fold(query.trim());if (!wanted) return true;- if (fold(chat.name).includes(wanted)) return true;+ if (fold(communityTitle(chat.name, chat.community)).includes(wanted))+ return true;const digits = wanted.replace(/[\s()+-]/g, '');return /^\d+$/.test(digits) && chat.name.replace(/\D/g, '').includes(digits);}/** DSS's refusal sentence, shortened for direct chats. */export function cannotAddLabel(chat: WhatsAppChat): string | undefined {- if (chat.kind === 'direct') return "Can't add direct chats yet";const reason = chat.cannotAddReason;return reason? `${reason.charAt(0).toUpperCase()}${reason.slice(1)}`@@ -63,7 +84,13 @@ export function cannotAddLabel(chat: WhatsAppChat): string | undefined {/** "Group", "Direct chat · Archived"; the row shows last activity apart. */export function chatMetadata(chat: WhatsAppChat): string {return [- chat.kind === 'direct' ? 'Direct chat' : 'Group',+ chat.kind === 'direct'+ ? 'Direct chat'+ : chat.community?.announcements+ ? 'Announcement group'+ : chat.community+ ? 'Community group'+ : 'Group',chat.archived ? 'Archived' : undefined,].filter(Boolean)diff --git a/apps/web/src/features/whatsapp-linked/queries/decode.ts b/apps/web/src/features/whatsapp-linked/queries/decode.tsindex 484d6e27f1..569e89ba7a 100644--- a/apps/web/src/features/whatsapp-linked/queries/decode.ts+++ b/apps/web/src/features/whatsapp-linked/queries/decode.ts@@ -39,12 +39,18 @@ export function decodeChat(? {kind: 'shared',groupId: chat.shared.id,- ownerId: chat.shared.owner_id,- ownerName: ownerName(chat.shared.owner_id),+ ownerId: chat.shared.ownerId,+ ownerName: ownerName(chat.shared.ownerId),}: undefined,canAdd: chat.canAdd,cannotAddReason: chat.cannotAddReason ?? undefined,+ community: chat.community+ ? {+ name: chat.community.name,+ announcements: chat.community.announcements,+ }+ : undefined,};}diff --git a/apps/web/src/features/whatsapp-linked/views/whatsapp-page.test.tsx b/apps/web/src/features/whatsapp-linked/views/whatsapp-page.test.tsxindex 1d6802d610..370831c171 100644--- a/apps/web/src/features/whatsapp-linked/views/whatsapp-page.test.tsx+++ b/apps/web/src/features/whatsapp-linked/views/whatsapp-page.test.tsx@@ -67,7 +67,7 @@ const chats = [name: 'Ana Ruiz',lastActivityAt: '2025-03-07T10:00:00Z',canAdd: false,- cannotAddReason: "direct chats can't be added to Macro yet",+ cannotAddReason: "your chat with yourself can't be added to Macro",},{...chat,@@ -101,7 +101,8 @@ const chats = [name: 'Neighbourhood',archived: true,canAdd: false,- cannotAddReason: "community groups can't be added to Macro",+ cannotAddReason:+ 'a community has no messages of its own; add one of its groups',},];@@ -222,7 +223,7 @@ describe('connected', () => {).toBeNull();const list = within(- screen.getByRole('list', { name: 'Groups to add to Macro' })+ screen.getByRole('list', { name: 'Chats to add to Macro' }));expect(list.queryByText('Design Crit')).toBeNull();expect(list.getAllByRole('listitem').map((row) => row.textContent)).toEqual(@@ -248,10 +249,14 @@ describe('connected', () => {);expect(direct.getByText('Direct chat')).toBeTruthy();expect(direct.getByText('Mar 7, 2025')).toBeTruthy();- expect(direct.getByText("Can't add direct chats yet")).toBeTruthy();+ expect(+ direct.getByText("Your chat with yourself can't be added to Macro")+ ).toBeTruthy();expect(direct.queryByRole('button')).toBeNull();expect(- unsupported.getByText("Community groups can't be added to Macro")+ unsupported.getByText(+ 'A community has no messages of its own; add one of its groups'+ )).toBeTruthy();expect(unsupported.getByText('Group · Archived')).toBeTruthy();@@ -305,7 +310,7 @@ describe('connected', () => {fireEvent.input(search, { target: { value: 'ana' } });const list = within(- screen.getByRole('list', { name: 'Groups to add to Macro' })+ screen.getByRole('list', { name: 'Chats to add to Macro' }));expect(list.getByText('Ana, Ben, +2')).toBeTruthy();expect(list.queryByText('Launch War Room')).toBeNull();@@ -342,6 +347,93 @@ describe('connected', () => {expect(screen.queryByRole('dialog')).toBeNull();});+ it('adds a direct chat like a group', async () => {+ const fake = createFakeWhatsApp({+ account: { generation: 3, phone: '+14155550142', health: 'connected' },+ chats: [+ {+ ...chat,+ jid: '[email protected]',+ kind: 'direct' as const,+ name: 'Ben Ode',+ },+ ],+ });+ mount(fake);+ const row = within(+ within(screen.getByRole('list', { name: 'Chats to add to Macro' }))+ .getByText('Ben Ode')+ .closest('li') as HTMLElement+ );+ expect(row.getByText('Direct chat')).toBeTruthy();+ fireEvent.click(row.getByRole('button', { name: 'Add to Macro' }));+ await waitFor(() =>+ expect(fake.capabilities.adopt).toHaveBeenCalledWith(+ )+ );+ });++ it('offers community and disappearing-message groups like any group', async () => {+ const fake = createFakeWhatsApp({+ account: { generation: 3, phone: '+14155550142', health: 'connected' },+ chats: [+ {+ ...chat,+ jid: '[email protected]',+ name: 'Design',+ community: { name: 'Launch', announcements: false },+ },+ {+ ...chat,+ jid: '[email protected]',+ name: 'Launch',+ community: { name: 'Launch', announcements: true },+ },+ // Disappearing messages no longer keep a group out.+ { ...chat, jid: '[email protected]', name: 'Night shift' },+ {+ ...chat,+ jid: '[email protected]',+ name: 'Launch',+ canAdd: false,+ cannotAddReason:+ 'a community has no messages of its own; add one of its groups',+ },+ ],+ });+ mount(fake);+ const addable = within(+ screen.getByRole('list', { name: 'Chats to add to Macro' })+ );+ const design = within(+ addable.getByText('Launch · Design').closest('li') as HTMLElement+ );+ expect(design.getByText('Community group')).toBeTruthy();+ expect(addable.getByText('Launch · Announcements')).toBeTruthy();+ expect(addable.getByText('Announcement group')).toBeTruthy();+ expect(addable.getByText('Night shift')).toBeTruthy();+ expect(+ addable.getAllByRole('button', { name: 'Add to Macro' })+ ).toHaveLength(3);+ fireEvent.click(+ screen.getByRole('button', { name: /Can't be added \(1\)/ })+ );+ expect(+ within(screen.getByRole('list', { name: "Can't be added" })).getByText(+ 'A community has no messages of its own; add one of its groups'+ )+ ).toBeTruthy();+ // Searching the community finds its groups.+ fireEvent.input(+ screen.getByRole('searchbox', { name: 'Search WhatsApp chats' }),+ {+ target: { value: 'launch' },+ }+ );+ expect(addable.getByText('Launch · Design')).toBeTruthy();+ });+it('says exactly why adding failed, on the group it failed for', async () => {const fake = createFakeWhatsApp({account: { generation: 3, phone: '+14155550142', health: 'connected' },@@ -357,7 +449,7 @@ describe('connected', () => {screen.getByText('Launch War Room').closest('li') as HTMLElement);expect((await row.findByRole('alert')).textContent).toBe(- 'Your WhatsApp is disconnected. Reconnect it, then add the group.'+ 'Your WhatsApp is disconnected. Reconnect it, then add the chat.');expect(row.getByRole('button', { name: 'Add to Macro' })).toBeTruthy();});diff --git a/apps/web/src/features/whatsapp-linked/views/whatsapp-page.tsx b/apps/web/src/features/whatsapp-linked/views/whatsapp-page.tsxindex 0f5aab2fdb..e38eecc118 100644--- a/apps/web/src/features/whatsapp-linked/views/whatsapp-page.tsx+++ b/apps/web/src/features/whatsapp-linked/views/whatsapp-page.tsx@@ -1,4 +1,5 @@import { SearchBar } from '@app/components/view-shell';+import { ViewSkeleton } from '@app/components/view-shell/ViewSkeleton';import { fireAndForget } from '@core/util/fireAndForget';import { Button, ConfirmDialog } from '@ui';import { createSignal, type JSX, Match, onMount, Show, Switch } from 'solid-js';@@ -205,7 +206,7 @@ export function WhatsAppPage(props: {empty={searching()? 'No chats to add match your search.'- : 'Every WhatsApp group you can add is already in Macro.'+ : 'Every WhatsApp chat you can add is already in Macro.'}onAdd={(chat) =>fireAndForget(@@ -227,9 +228,7 @@ export function WhatsAppPage(props: {}}</Match><Match when={chats.isPending}>- <p role="status" class="px-4 py-2 text-sm text-ink-muted">- Loading chats…- </p>+ <ViewSkeleton.Rows label="Loading chats" class="px-2 pt-3" /></Match><Match when={chats.isError}><LoadFailure what="your chats" onRetry={chats.refetch} />@@ -239,7 +238,7 @@ export function WhatsAppPage(props: {open={confirmingDisconnect()}onOpenChange={setConfirmingDisconnect}title="Disconnect WhatsApp?"- body="Macro stops syncing and sending from this account. Groups and their history stay in Macro."+ body="Macro stops syncing and sending from this account. Chats and their history stay in Macro."confirmLabel="Disconnect"tone="danger"pending={whatsapp.isDisconnecting()}diff --git a/apps/web/src/lib/core/component/EntityIcon.tsx b/apps/web/src/lib/core/component/EntityIcon.tsxindex 1fe8a2bb52..84bd55fc08 100644--- a/apps/web/src/lib/core/component/EntityIcon.tsx+++ b/apps/web/src/lib/core/component/EntityIcon.tsx@@ -154,7 +154,7 @@ export const ENTITY_ICON_CONFIGS: Record<EntityWithValidIcon, IconConfig> = {boldIcon: WhatsappLogoBold,foreground: 'text-communication',background: 'bg-communication/20',- prettyName: 'WhatsApp group',+ prettyName: 'WhatsApp chat',},document: {icon: File,diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/DocumentMention.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/DocumentMention.tsxindex 6423f7483a..b9800c1a32 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/DocumentMention.tsx+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/DocumentMention.tsx@@ -2,6 +2,7 @@ import { parseLocalDate } from '@app/features/calendar/utils/calendar-date';import { calendarMentionOpen } from '@app/features/calendar-view/mention-open-target';import { openCalendarEventSplit } from '@app/features/calendar-view/open-calendar-event';import { whatsappGroupContent } from '@app/features/external-view/hosted-content';+import { whatsappGroupApi } from '@app/features/whatsapp-group/queries/production-api';import { useFeatureFlag } from '@app/lib/analytics/posthog';import { URL_PARAMS as CHANNEL_PARAMS } from '@block-channel/constants';import { useSplitLayout } from '@components/app/split-layout/layout';@@ -32,6 +33,7 @@ import {ENABLE_BLOCK_IN_BLOCK,enableDatabases,} from '@core/constant/featureFlags';+import { useUserId } from '@core/context/user';import { isTouchDevice } from '@core/mobile/isTouchDevice';import { canNestBlock } from '@core/orchestrator';import { formatDate } from '@core/util/date';@@ -60,6 +62,7 @@ import {import { useDatabaseDetailQuery } from '@queries/storage/databases';import { useFormDetailQuery } from '@queries/storage/forms';import { useSystemSkillsQuery } from '@queries/storage/system-skills';+import { useWhatsappGroupDetailQuery } from '@queries/whatsapp-groups';import { blockNameToItemType } from '@service-storage/client';import { createCallback } from '@solid-primitives/rootless';import { Button, Tooltip } from '@ui';@@ -457,6 +460,77 @@ function createRecentMention(createdAt: number | undefined) {return isRecent;}+/**+ * A reference that opens its item on click or Enter: its icon and name in+ * the mention chip, without a document preview.+ */+function EntityMentionLink(props: {+ documentId: string;+ blockName: string;+ name: string;+ icon: JSX.Element;+ collapsed?: boolean;+ onOpen: (event: MouseEvent | KeyboardEvent) => void;+}) {+ const open = (event: MouseEvent | KeyboardEvent) => {+ event.preventDefault();+ event.stopPropagation();+ props.onOpen(event);+ };+ return (+ <span+ class="rounded-xs hover:bg-hover focus-visible:outline-2 focus-visible:outline-ink/30"+ role="link"+ tabIndex={0}+ on:mousedown={(event) => event.preventDefault()}+ on:click={open}+ onKeyDown={(event) => {+ if (event.key === 'Enter') open(event);+ }}+ >+ <MentionContainer+ icon={props.icon}+ collapsed={props.collapsed}+ text={+ <span+ data-document-mention="true"+ data-document-id={props.documentId}+ data-block-name={props.blockName}+ data-document-name={props.name}+ >+ {props.name}+ </span>+ }+ />+ </span>+ );+}++/** How an unavailable reference reads: `Deleted` or `No Access`. */+function UnavailableMentionChip(props: {+ access: PreviewItemNoAccess['access'];+ collapsed?: boolean;+}) {+ return (+ <Show+ when={props.access === 'no_access'}+ fallback={+ <MentionContainer+ icon={<TrashSimple />}+ text="Deleted"+ collapsed={props.collapsed}+ />+ }+ >+ <MentionContainer+ icon={<EyeSlashDuo />}+ text="No Access"+ collapsed={props.collapsed}+ />+ </Show>+ );+}+/*** A database, form or routine reference whose item is gone or hidden from the* viewer. It reads `Deleted` or `No Access` like any other unavailable@@ -500,22 +574,10 @@ function UnavailableMention(props: {if (event.key === 'Enter') open(event);}}>- <Show- when={props.access === 'no_access'}- fallback={- <MentionContainer- icon={<TrashSimple />}- text="Deleted"- collapsed={props.collapsed}- />- }- >- <MentionContainer- icon={<EyeSlashDuo />}- text="No Access"- collapsed={props.collapsed}- />- </Show>+ <UnavailableMentionChip+ access={props.access}+ collapsed={props.collapsed}+ /></span>}content={@@ -638,16 +700,6 @@ function DatabaseMention(props: DocumentMentionDecoratorProps) {);const name = () =>detail.isSuccess ? detail.data.database.name : props.documentName;- const open = (event: MouseEvent | KeyboardEvent) => {- event.preventDefault();- event.stopPropagation();- openDocument(- 'database',- props.documentId,- props.blockParams,- openInNewSplitForMention(event.shiftKey, true)- );- };const expand = (event: MouseEvent) => {event.preventDefault();event.stopPropagation();@@ -662,31 +714,21 @@ function DatabaseMention(props: DocumentMentionDecoratorProps) {when={detailUnavailable(detail)}fallback={<span class="inline-flex items-baseline gap-1">- <span- class="rounded-xs hover:bg-hover focus-visible:outline-2 focus-visible:outline-ink/30"- role="link"- tabIndex={0}- on:mousedown={(event) => event.preventDefault()}- on:click={open}- onKeyDown={(event) => {- if (event.key === 'Enter') open(event);- }}- >- <MentionContainer- icon={<EntityIcon targetType="database" size="fill" />}- collapsed={props.collapsed}- text={- <span- data-document-mention="true"- data-document-id={props.documentId}- data-block-name="database"- data-document-name={name()}- >- {name() || 'Database'}- </span>- }- />- </span>+ <EntityMentionLink+ documentId={props.documentId}+ blockName="database"+ name={name() || 'Database'}+ icon={<EntityIcon targetType="database" size="fill" />}+ collapsed={props.collapsed}+ onOpen={(event) =>+ openDocument(+ 'database',+ props.documentId,+ props.blockParams,+ openInNewSplitForMention(event.shiftKey, true)+ )+ }+ /><Showwhen={enabled().enabled && editable() && wrapper?.isInteractable()}>@@ -727,45 +769,25 @@ function FormMention(props: DocumentMentionDecoratorProps) {const detail = useFormDetailQuery(() => props.documentId);const name = () =>detail.isSuccess ? detail.data.form.name : props.documentName;- const open = (event: MouseEvent | KeyboardEvent) => {- event.preventDefault();- event.stopPropagation();- openDocument(- 'form',- props.documentId,- props.blockParams,- openInNewSplitForMention(event.shiftKey, true)- );- };return (<Showwhen={detailUnavailable(detail)}fallback={- <span- class="rounded-xs hover:bg-hover focus-visible:outline-2 focus-visible:outline-ink/30"- role="link"- tabIndex={0}- on:mousedown={(event) => event.preventDefault()}- on:click={open}- onKeyDown={(event) => {- if (event.key === 'Enter') open(event);- }}- >- <MentionContainer- icon={<EntityIcon targetType="form" size="fill" />}- collapsed={props.collapsed}- text={- <span- data-document-mention="true"- data-document-id={props.documentId}- data-block-name="form"- data-document-name={name()}- >- {name() || 'Form'}- </span>- }- />- </span>+ <EntityMentionLink+ documentId={props.documentId}+ blockName="form"+ name={name() || 'Form'}+ icon={<EntityIcon targetType="form" size="fill" />}+ collapsed={props.collapsed}+ onOpen={(event) =>+ openDocument(+ 'form',+ props.documentId,+ props.blockParams,+ openInNewSplitForMention(event.shiftKey, true)+ )+ }+ />}>{(access) => (@@ -785,44 +807,41 @@ function FormMention(props: DocumentMentionDecoratorProps) {}/**- * A WhatsApp group: not a previewable document, so it shows its stored name- * and opens inside External.+ * A WhatsApp chat: not a previewable document, so it shows its name and opens+ * inside External; a viewer the chat isn't shared with sees it as+ * unavailable.*/function WhatsAppGroupMention(props: DocumentMentionDecoratorProps) {const { openWithSplit } = useSplitLayout();- const open = (event: MouseEvent | KeyboardEvent) => {- event.preventDefault();- event.stopPropagation();- openWithSplit(whatsappGroupContent(props.documentId), {- preferNewSplit: openInNewSplitForMention(event.shiftKey, true),- });- };+ const userId = useUserId();+ const detail = useWhatsappGroupDetailQuery(+ whatsappGroupApi,+ () => userId() ?? '',+ () => props.documentId+ );+ const name = () => (detail.isSuccess ? detail.data.name : props.documentName);return (- <span- class="rounded-xs hover:bg-hover focus-visible:outline-2 focus-visible:outline-ink/30"- role="link"- tabIndex={0}- on:mousedown={(event) => event.preventDefault()}- on:click={open}- onKeyDown={(event) => {- if (event.key === 'Enter') open(event);- }}+ <Show+ when={detailUnavailable(detail)}+ fallback={+ <EntityMentionLink+ documentId={props.documentId}+ blockName="whatsapp_group"+ name={name() || 'WhatsApp chat'}+ icon={<EntityIcon targetType="whatsapp_group" size="fill" />}+ collapsed={props.collapsed}+ onOpen={(event) =>+ openWithSplit(whatsappGroupContent(props.documentId), {+ preferNewSplit: openInNewSplitForMention(event.shiftKey, true),+ })+ }+ />+ }>- <MentionContainer- icon={<EntityIcon targetType="whatsapp_group" size="fill" />}- collapsed={props.collapsed}- text={- <span- data-document-mention="true"- data-document-id={props.documentId}- data-block-name="whatsapp_group"- data-document-name={props.documentName}- >- {props.documentName || 'WhatsApp group'}- </span>- }- />- </span>+ {(access) => (+ <UnavailableMentionChip access={access()} collapsed={props.collapsed} />+ )}+ </Show>);}diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/WhatsAppGroupMention.test.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/WhatsAppGroupMention.test.tsxindex 110042287e..642fd64e97 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/WhatsAppGroupMention.test.tsx+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/WhatsAppGroupMention.test.tsx@@ -1,8 +1,33 @@+import { ThrownResultError } from '@core/util/result';import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';import { afterEach, expect, it, vi } from 'vitest';import { DocumentMention } from './DocumentMention';-const mocks = vi.hoisted(() => ({ openWithSplit: vi.fn() }));+type DetailRead = {+ isSuccess: boolean;+ isError: boolean;+ error: unknown;+ dataUpdatedAt: number;+ data?: { name: string };+};+const mocks = vi.hoisted(() => ({+ openWithSplit: vi.fn(),+ detail: {+ isSuccess: false,+ isError: false,+ error: null,+ dataUpdatedAt: 0,+ } as DetailRead,+}));+vi.mock('@core/context/user', () => ({+ useUserId: () => () => 'macro|[email protected]',+}));+vi.mock('@app/features/whatsapp-group/queries/production-api', () => ({+ whatsappGroupApi: {},+}));+vi.mock('@queries/whatsapp-groups', () => ({+ useWhatsappGroupDetailQuery: () => mocks.detail,+}));vi.mock('@components/app/split-layout/layout', () => ({useSplitLayout: () => ({ openWithSplit: mocks.openWithSplit }),}));@@ -12,6 +37,12 @@ vi.mock('@core/mobile/isTouchDevice', () => ({ isTouchDevice: () => false }));afterEach(() => {cleanup();mocks.openWithSplit.mockClear();+ mocks.detail = {+ isSuccess: false,+ isError: false,+ error: null,+ dataUpdatedAt: 0,+ };});it('shows a WhatsApp group mention by name and opens it inside External', () => {@@ -45,3 +76,26 @@ it('shows a WhatsApp group mention by name and opens it inside External', () =>{ preferNewSplit: true });});++it('shows a chat the viewer cannot read as unavailable, not as a link', () => {+ mocks.detail = {+ isSuccess: false,+ isError: true,+ error: new ThrownResultError([+ { code: 'UNAUTHORIZED', message: 'Unauthorized' },+ ]),+ dataUpdatedAt: 0,+ };+ render(() => (+ <DocumentMention+ key="node-1"+ documentId="01a16445-9fdc-7bb1-80b4-8935a1243c98"+ documentName="Design Crit"+ blockName="whatsapp_group"+ theme={{}}+ />+ ));+ expect(screen.getByText('No Access')).toBeTruthy();+ expect(screen.queryByRole('link')).toBeNull();+ expect(screen.queryByText('Design Crit')).toBeNull();+});diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.test.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.test.tsxindex a28f54f166..3d38745a0a 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.test.tsx+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.test.tsx@@ -478,7 +478,7 @@ it('offers WhatsApp groups to share by mention, only in channel composers', () =onPick={vi.fn()}/>));- expect(screen.getByText('WhatsApp groups')).toBeTruthy();+ expect(screen.getByText('WhatsApp chats')).toBeTruthy();expect(screen.getByText('Design Crit')).toBeTruthy();expect(screen.queryByText('Launch Room')).toBeNull();cleanup();@@ -492,6 +492,6 @@ it('offers WhatsApp groups to share by mention, only in channel composers', () =onPick={vi.fn()}/>));- expect(screen.queryByText('WhatsApp groups')).toBeNull();+ expect(screen.queryByText('WhatsApp chats')).toBeNull();expect(mocks.whatsappUserIds.every((id) => id === '')).toBe(true);});diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.tsxindex d8a5fd88ef..09153d52e0 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.tsx+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.tsx@@ -484,7 +484,7 @@ function MentionsMenuInner(props: MentionsMenuProps) {},{id: 'whatsappGroups',- label: 'WhatsApp groups',+ label: 'WhatsApp chats',getData: whatsappGroups,getFullCount: () => whatsappGroups().length,},diff --git a/apps/web/src/lib/core/component/TopBar/ShareButton.tsx b/apps/web/src/lib/core/component/TopBar/ShareButton.tsxindex 12c08d9d88..774fc15857 100644--- a/apps/web/src/lib/core/component/TopBar/ShareButton.tsx+++ b/apps/web/src/lib/core/component/TopBar/ShareButton.tsx@@ -220,7 +220,7 @@ const SHARE_LINK_SUBTEXT =// copying skips SHARE_LINK_SUBTEXT.const RESTRICTED_SHARE_DESCRIPTIONS: Partial<Record<ShareItemType, string>> = {whatsapp_group:- 'Only the owner can share access to this WhatsApp group. Sending always requires your own connected WhatsApp account.',+ 'Only the owner can share access to this WhatsApp chat. Sending always requires your own connected WhatsApp account.',crm_pipeline:'Only editors can share this pipeline. You can copy a link for people who already have access.',agent_session:diff --git a/apps/web/src/lib/core/component/TopBar/linkShare.ts b/apps/web/src/lib/core/component/TopBar/linkShare.tsindex 0d9435346c..d4e0d475ed 100644--- a/apps/web/src/lib/core/component/TopBar/linkShare.ts+++ b/apps/web/src/lib/core/component/TopBar/linkShare.ts@@ -46,7 +46,7 @@ export function getShareItemNoun(itemType: ShareItemType): string {.with('channel_message', () => 'message').with('channel_thread', () => 'thread').with('foreign', () => 'item')- .with('whatsapp_group', () => 'WhatsApp group')+ .with('whatsapp_group', () => 'WhatsApp chat').with('document','chat',diff --git a/apps/web/src/lib/core/constant/featureFlags.ts b/apps/web/src/lib/core/constant/featureFlags.tsindex 61596ca7d6..3e46c235e0 100644--- a/apps/web/src/lib/core/constant/featureFlags.ts+++ b/apps/web/src/lib/core/constant/featureFlags.ts@@ -898,8 +898,8 @@ export const enableInAppTours = defineFlag({});/**- * Personal WhatsApp linked devices: the External tab, pairing, group adoption- * and linked-channel composing. Off in dev too: dev has no WhatsApp session+ * Personal WhatsApp linked devices: the External tab, pairing, adding chats+ * to Macro and sharing them by mention in channels. Off in dev too: dev has no WhatsApp session* service, so the tab would only show errors. Override locally with* VITE_ENABLE_WHATSAPP_LINKED=true. Backend switches gate each operation* independently.diff --git a/apps/web/src/lib/queries/whatsapp-groups/index.ts b/apps/web/src/lib/queries/whatsapp-groups/index.tsindex 4c3fdfacbe..b5c15bcf8d 100644--- a/apps/web/src/lib/queries/whatsapp-groups/index.ts+++ b/apps/web/src/lib/queries/whatsapp-groups/index.ts@@ -110,6 +110,14 @@ export function useWhatsappGroupQueries();return { group, messages };}+/** One chat's detail alone, e.g. to name a mention of it. */+export function useWhatsappGroupDetailQuery(+ api: WhatsAppGroupApi,+ userId: Accessor<string>,+ groupId: Accessor<string>+) {+ return useQuery(() => detailOptions(api, userId(), groupId()));+}export function useWhatsappGroupDeliveryQuery(api: WhatsAppGroupApi,userId: Accessor<string>,diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.tsindex 44180d30d1..62514ee5e2 100644--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts@@ -1216,22 +1216,25 @@ export * from './linkedAttachmentState';export * from './linkedAttachmentWidth';export * from './linkedBackfill';export * from './linkedBackfillState';+export * from './linkedCannotAdd';export * from './linkedCapabilities';export * from './linkedChat';export * from './linkedChatCannotAddReason';+export * from './linkedChatCommunity';export * from './linkedChatGroup';export * from './linkedChatKind';export * from './linkedChatLastActivityAt';export * from './linkedChatShared';export * from './linkedChats';+export * from './linkedCommunityReference';export * from './linkedConnect';export * from './linkedDeliveryState';export * from './linkedDisconnect';export * from './linkedDisconnectRequest';export * from './linkedFeatures';export * from './linkedGroupInfo';-export * from './linkedGroupInfoGroup';-export * from './linkedGroupInfoShared';+export * from './linkedGroupInfoCommunityJid';+export * from './linkedGroupInfoDisappearingSeconds';export * from './linkedGroupReference';export * from './linkedIdentity';export * from './linkedIdentityAlternateJid';@@ -2264,6 +2267,8 @@ export * from './whatsAppEventLocation';export * from './whatsAppEventStartAt';export * from './whatsAppGroupDetail';export * from './whatsAppGroupDetailAllOf';+export * from './whatsAppGroupDetailAllOfCommunity';+export * from './whatsAppGroupDetailAllOfDisappearingSeconds';export * from './whatsAppGroupDetailAllOfRoster';export * from './whatsAppGroupDetailAllOfSendingIdentity';export * from './whatsAppGroupMessage';diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedAdoptGroup.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedAdoptGroup.tsindex 3b3bf8543e..b63d0c0f37 100644--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedAdoptGroup.ts+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedAdoptGroup.ts@@ -10,6 +10,7 @@group's name always follows WhatsApp.*/export interface LinkedAdoptGroup {- /** Group the requester's account has joined. */+ /** A group the requester's account has joined, or a direct chat from+their chat list (the other person's JID, as the list names it). */group_jid: string;}diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedCannotAdd.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedCannotAdd.tsnew file mode 100644index 0000000000..6d2b153afe--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedCannotAdd.ts@@ -0,0 +1,20 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Why a chat can't be added to Macro; the app words it from the code.+ */+export type LinkedCannotAdd =+ (typeof LinkedCannotAdd)[keyof typeof LinkedCannotAdd];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const LinkedCannotAdd = {+ not_in_group: 'not_in_group',+ community: 'community',+ own_chat: 'own_chat',+ not_in_chat_list: 'not_in_chat_list',+} as const;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedChat.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedChat.tsindex e89ef3f11b..d3f8453234 100644--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedChat.ts+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedChat.ts@@ -5,6 +5,7 @@* OpenAPI spec version: 0.1.0*/import type { LinkedChatCannotAddReason } from './linkedChatCannotAddReason';+import type { LinkedChatCommunity } from './linkedChatCommunity';import type { LinkedChatGroup } from './linkedChatGroup';import type { LinkedChatKind } from './linkedChatKind';import type { LinkedChatLastActivityAt } from './linkedChatLastActivityAt';@@ -18,8 +19,8 @@ export interface LinkedChat {archived: boolean;/** "Add to Macro" works now. */canAdd: boolean;- /** Why it can't be added, when it is neither added, shared nor addable. */cannotAddReason?: LinkedChatCannotAddReason;+ community?: LinkedChatCommunity;group?: LinkedChatGroup;/** WhatsApp chat JID: a group, or the other person's phone-number JID(LID when WhatsApp never told us the number). */diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedChatCannotAddReason.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedChatCannotAddReason.tsindex d84295b74f..75ca844a71 100644--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedChatCannotAddReason.ts+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedChatCannotAddReason.ts@@ -4,8 +4,6 @@* document_storage_service* OpenAPI spec version: 0.1.0*/+import type { LinkedCannotAdd } from './linkedCannotAdd';-/**- * Why it can't be added, when it is neither added, shared nor addable.- */-export type LinkedChatCannotAddReason = string | null;+export type LinkedChatCannotAddReason = null | LinkedCannotAdd;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedChatCommunity.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedChatCommunity.tsnew file mode 100644index 0000000000..c62f52f6e6--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedChatCommunity.ts@@ -0,0 +1,9 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { LinkedCommunityReference } from './linkedCommunityReference';++export type LinkedChatCommunity = null | LinkedCommunityReference;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedCommunityReference.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedCommunityReference.tsnew file mode 100644index 0000000000..9bdce0a2cc--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedCommunityReference.ts@@ -0,0 +1,18 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * The WhatsApp community a group belongs to.+ */+export interface LinkedCommunityReference {+ /** This group is the community's announcement group. */+ announcements: boolean;+ /** The community's WhatsApp JID. */+ id: string;+ /** The community's name. */+ name: string;+}diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedGroupInfo.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedGroupInfo.tsindex 75e07a3eef..da06e832d9 100644--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedGroupInfo.ts+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedGroupInfo.ts@@ -4,8 +4,8 @@* document_storage_service* OpenAPI spec version: 0.1.0*/-import type { LinkedGroupInfoGroup } from './linkedGroupInfoGroup';-import type { LinkedGroupInfoShared } from './linkedGroupInfoShared';+import type { LinkedGroupInfoCommunityJid } from './linkedGroupInfoCommunityJid';+import type { LinkedGroupInfoDisappearingSeconds } from './linkedGroupInfoDisappearingSeconds';import type { LinkedParticipant } from './linkedParticipant';/**@@ -14,11 +14,18 @@ import type { LinkedParticipant } from './linkedParticipant';export interface LinkedGroupInfo {/** Only admins may post. */announce: boolean;- /** Community announcement or parent group, outside the supported surface. */- community: boolean;- /** Disappearing messages are on; content is not retained. */- disappearing: boolean;- group?: LinkedGroupInfoGroup;+ /** The community's announcement group (everyone reads, admins post). */+ communityAnnouncements?: boolean;+ /** The community a linked subgroup or announcement group belongs to. */+ communityJid?: LinkedGroupInfoCommunityJid;+ /** The community itself: it has no messages of its own and can't be added. */+ communityParent?: boolean;+ /**+ * Disappearing-messages timer in seconds while it is on. Macro keeps the+messages; its sends carry the timer so phones treat them like their own.+ * @minimum 0+ */+ disappearingSeconds?: LinkedGroupInfoDisappearingSeconds;/** Remote group JID. */jid: string;/** Current subject. */@@ -27,5 +34,4 @@ export interface LinkedGroupInfo {observedAt: string;/** Full roster. */participants: LinkedParticipant[];- shared?: LinkedGroupInfoShared;}diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedGroupInfoCommunityJid.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedGroupInfoCommunityJid.tsnew file mode 100644index 0000000000..38d4efe096--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedGroupInfoCommunityJid.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * The community a linked subgroup or announcement group belongs to.+ */+export type LinkedGroupInfoCommunityJid = string | null;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedGroupInfoDisappearingSeconds.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedGroupInfoDisappearingSeconds.tsnew file mode 100644index 0000000000..8dde4a28ec--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedGroupInfoDisappearingSeconds.ts@@ -0,0 +1,13 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Disappearing-messages timer in seconds while it is on. Macro keeps the+messages; its sends carry the timer so phones treat them like their own.+ * @minimum 0+ */+export type LinkedGroupInfoDisappearingSeconds = number | null;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedGroupInfoGroup.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedGroupInfoGroup.tsdeleted file mode 100644index b2d3999c95..0000000000--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedGroupInfoGroup.ts+++ /dev/null@@ -1,9 +0,0 @@-/**- * Generated by orval v7.21.0 🍺- * Do not edit manually.- * document_storage_service- * OpenAPI spec version: 0.1.0- */-import type { LinkedGroupReference } from './linkedGroupReference';--export type LinkedGroupInfoGroup = null | LinkedGroupReference;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedGroupInfoShared.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedGroupInfoShared.tsdeleted file mode 100644index 206e786c7c..0000000000--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedGroupInfoShared.ts+++ /dev/null@@ -1,9 +0,0 @@-/**- * Generated by orval v7.21.0 🍺- * Do not edit manually.- * document_storage_service- * OpenAPI spec version: 0.1.0- */-import type { LinkedSharedGroupReference } from './linkedSharedGroupReference';--export type LinkedGroupInfoShared = null | LinkedSharedGroupReference;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedSharedGroupReference.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedSharedGroupReference.tsindex 349efc8859..f665dadf95 100644--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedSharedGroupReference.ts+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedSharedGroupReference.ts@@ -14,5 +14,5 @@ export interface LinkedSharedGroupReference {/** Display name, following WhatsApp. */name: string;/** Macro user who added the group and shared it. */- owner_id: string;+ ownerId: string;}diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/whatsAppGroupDetailAllOf.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/whatsAppGroupDetailAllOf.tsindex 9bc8a5e760..52417dbd1f 100644--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/whatsAppGroupDetailAllOf.ts+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/whatsAppGroupDetailAllOf.ts@@ -7,12 +7,21 @@import type { AccessLevel } from './accessLevel';import type { LinkedCapabilities } from './linkedCapabilities';import type { SharePermissionV2 } from './sharePermissionV2';+import type { WhatsAppGroupDetailAllOfCommunity } from './whatsAppGroupDetailAllOfCommunity';+import type { WhatsAppGroupDetailAllOfDisappearingSeconds } from './whatsAppGroupDetailAllOfDisappearingSeconds';import type { WhatsAppGroupDetailAllOfRoster } from './whatsAppGroupDetailAllOfRoster';import type { WhatsAppGroupDetailAllOfSendingIdentity } from './whatsAppGroupDetailAllOfSendingIdentity';export type WhatsAppGroupDetailAllOf = {/** Caller's effective permission. */access_level: AccessLevel;+ community?: WhatsAppGroupDetailAllOfCommunity;+ /**+ * WhatsApp's disappearing-messages timer in seconds while it is on;+Macro keeps the messages anyway. `null` when off or unknown.+ * @minimum 0+ */+ disappearing_seconds?: WhatsAppGroupDetailAllOfDisappearingSeconds;/** Size and mutation limits. */limits: LinkedCapabilities;roster?: WhatsAppGroupDetailAllOfRoster;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/whatsAppGroupDetailAllOfCommunity.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/whatsAppGroupDetailAllOfCommunity.tsnew file mode 100644index 0000000000..465e5ea72c--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/whatsAppGroupDetailAllOfCommunity.ts@@ -0,0 +1,9 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { LinkedCommunityReference } from './linkedCommunityReference';++export type WhatsAppGroupDetailAllOfCommunity = null | LinkedCommunityReference;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/whatsAppGroupDetailAllOfDisappearingSeconds.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/whatsAppGroupDetailAllOfDisappearingSeconds.tsnew file mode 100644index 0000000000..24f68c578d--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/whatsAppGroupDetailAllOfDisappearingSeconds.ts@@ -0,0 +1,13 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * WhatsApp's disappearing-messages timer in seconds while it is on;+Macro keeps the messages anyway. `null` when off or unknown.+ * @minimum 0+ */+export type WhatsAppGroupDetailAllOfDisappearingSeconds = number | null;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/whatsAppGroupMessage.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/whatsAppGroupMessage.tsindex fe30bedbca..efba0f7ad7 100644--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/whatsAppGroupMessage.ts+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/whatsAppGroupMessage.ts@@ -46,4 +46,6 @@ export interface WhatsAppGroupMessage {sender: WhatsAppGroupSender;/** Timestamp assigned by WhatsApp. */sent_at: string;+ /** Sent as view-once in WhatsApp; Macro shows it like any media. */+ view_once: boolean;}diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/whatsAppGroupSummary.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/whatsAppGroupSummary.tsindex 396e762eb6..f00b7fbb10 100644--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/whatsAppGroupSummary.ts+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/whatsAppGroupSummary.ts@@ -4,6 +4,8 @@* document_storage_service* OpenAPI spec version: 0.1.0*/++import type { LinkedChatKind } from './linkedChatKind';import type { WhatsAppGroupSummaryBackfill } from './whatsAppGroupSummaryBackfill';import type { WhatsAppGroupSummaryLastMessageAt } from './whatsAppGroupSummaryLastMessageAt';import type { WhatsAppGroupSummarySendReason } from './whatsAppGroupSummarySendReason';@@ -17,9 +19,11 @@ export interface WhatsAppGroupSummary {can_send: boolean;/** Entity identifier. */id: string;+ /** A group, or a direct chat with one person (only its owner sends). */+ kind: LinkedChatKind;/** Latest message timestamp. */last_message_at?: WhatsAppGroupSummaryLastMessageAt;- /** Display name. */+ /** Display name: the group's, or a direct chat's other person. */name: string;send_reason?: WhatsAppGroupSummarySendReason;/** Unread live messages for this viewer. */diff --git a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts b/apps/web/src/lib/service-clients/service-storage/generated/zod.tsindex 6da28b37ca..f1f33ff6dc 100644--- a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts+++ b/apps/web/src/lib/service-clients/service-storage/generated/zod.ts@@ -49242,11 +49242,36 @@ export const linkedChatsResponse = zodarchived: zod.boolean().describe('Archived in WhatsApp.'),canAdd: zod.boolean().describe('\"Add to Macro\" works now.'),cannotAddReason: zod- .string()- .nullish()- .describe(- "Why it can't be added, when it is neither added, shared nor addable."- ),+ .union([+ zod.null(),+ zod+ .enum([+ 'not_in_group',+ 'community',+ 'own_chat',+ 'not_in_chat_list',+ ])+ .describe(+ "Why a chat can't be added to Macro; the app words it from the code."+ ),+ ])+ .optional(),+ community: zod+ .union([+ zod.null(),+ zod+ .object({+ announcements: zod+ .boolean()+ .describe(+ "This group is the community's announcement group."+ ),+ id: zod.string().describe("The community's WhatsApp JID."),+ name: zod.string().describe("The community's name."),+ })+ .describe('The WhatsApp community a group belongs to.'),+ ])+ .optional(),group: zod.union([zod.null(),@@ -49291,7 +49316,7 @@ export const linkedChatsResponse = zodname: zod.string().describe('Display name, following WhatsApp.'),- owner_id: zod+ ownerId: zod.string().describe('Macro user who added the group and shared it.'@@ -49386,89 +49411,6 @@ export const linkedDisconnectResponse = zod}).describe('Result of disconnecting an account.');-/**- * @summary Groups the caller's account has joined.- */-export const linkedGroupsResponseItem = zod- .object({- announce: zod.boolean().describe('Only admins may post.'),- community: zod- .boolean()- .describe(- 'Community announcement or parent group, outside the supported surface.'- ),- disappearing: zod- .boolean()- .describe('Disappearing messages are on; content is not retained.'),- group: zod- .union([- zod.null(),- zod- .object({- id: zod.uuid().describe('Group entity id.'),- name: zod.string().describe('Display name, following WhatsApp.'),- })- .describe('A group entity bound to a remote group.'),- ])- .optional(),- jid: zod.string().describe('Remote group JID.'),- name: zod.string().describe('Current subject.'),- observedAt: zod.iso- .datetime({})- .describe('When the session service read this metadata.'),- participants: zod- .array(- zod- .object({- alternateJid: zod- .string()- .nullish()- .describe(- 'Verified alternate identity, never inferred from a name or phone typed by a user.'- ),- displayName: zod- .string()- .nullish()- .describe('Untrusted display name.'),- jid: zod.string().describe('Phone-number or LID account JID.'),- })- .describe(- 'Verified sender aliases, supplied only by protocol metadata.'- )- .and(- zod.object({- admin: zod- .boolean()- .describe(- 'Group admin; only admins post in announcement groups.'- ),- })- )- .describe(- 'Current remote participant; Macro access is a separate grant.'- )- )- .describe('Full roster.'),- shared: zod- .union([- zod.null(),- zod- .object({- id: zod.uuid().describe('Group entity id.'),- name: zod.string().describe('Display name, following WhatsApp.'),- owner_id: zod- .string()- .describe('Macro user who added the group and shared it.'),- })- .describe("Another person's group entity the caller can view."),- ])- .optional(),- })- .describe(- 'One full metadata read of a group, never an incomplete membership delta.'- );-export const linkedGroupsResponse = zod.array(linkedGroupsResponseItem);-/*** @summary Adopt one of the caller's groups into a standalone group entity.*/@@ -49476,7 +49418,9 @@ export const linkedAdoptBody = zod.object({group_jid: zod.string()- .describe("Group the requester's account has joined."),+ .describe(+ "A group the requester's account has joined, or a direct chat from\ntheir chat list (the other person's JID, as the list names it)."+ ),}).describe("Explicit adoption request; the account is selected server-side. The\ngroup's name always follows WhatsApp."@@ -49585,11 +49529,16 @@ export const whatsappGroupsResponseItem = zod.boolean().describe('Caller may currently send from their own account.'),id: zod.uuid().describe('Entity identifier.'),+ kind: zod+ .enum(['group', 'direct'])+ .describe('Whether a WhatsApp chat is a group or a one-to-one chat.'),last_message_at: zod.iso.datetime({}).nullish().describe('Latest message timestamp.'),- name: zod.string().describe('Display name.'),+ name: zod+ .string()+ .describe("Display name: the group's, or a direct chat's other person."),send_reason: zod.union([zod.null(),@@ -49622,6 +49571,8 @@ export const whatsappGroupParams = zod.object({export const whatsappGroupResponseBackfillImportedMin = 0;+export const whatsappGroupResponseDisappearingSecondsMin = 0;+export const whatsappGroupResponseLimitsAttachmentLimitBytesMin = 0;export const whatsappGroupResponseLimitsMaxAttachmentsMin = 0;@@ -49630,6 +49581,8 @@ export const whatsappGroupResponseLimitsMutationWindowSecondsMin = 0;export const whatsappGroupResponseLimitsTextLimitBytesMin = 0;+export const whatsappGroupResponseRosterDisappearingSecondsMin = 0;+export const whatsappGroupResponse = zod.object({backfill: zod@@ -49660,11 +49613,16 @@ export const whatsappGroupResponse = zod.boolean().describe('Caller may currently send from their own account.'),id: zod.uuid().describe('Entity identifier.'),+ kind: zod+ .enum(['group', 'direct'])+ .describe('Whether a WhatsApp chat is a group or a one-to-one chat.'),last_message_at: zod.iso.datetime({}).nullish().describe('Latest message timestamp.'),- name: zod.string().describe('Display name.'),+ name: zod+ .string()+ .describe("Display name: the group's, or a direct chat's other person."),send_reason: zod.union([zod.null(),@@ -49691,6 +49649,27 @@ export const whatsappGroupResponse = zodaccess_level: zod.enum(['view', 'comment', 'edit', 'owner']).describe('Ordered from least to most access top -> bottom'),+ community: zod+ .union([+ zod.null(),+ zod+ .object({+ announcements: zod+ .boolean()+ .describe("This group is the community's announcement group."),+ id: zod.string().describe("The community's WhatsApp JID."),+ name: zod.string().describe("The community's name."),+ })+ .describe('The WhatsApp community a group belongs to.'),+ ])+ .optional(),+ disappearing_seconds: zod+ .number()+ .min(whatsappGroupResponseDisappearingSecondsMin)+ .nullish()+ .describe(+ "WhatsApp's disappearing-messages timer in seconds while it is on;\nMacro keeps the messages anyway. `null` when off or unknown."+ ),limits: zod.object({attachment_limit_bytes: zod@@ -49731,29 +49710,31 @@ export const whatsappGroupResponse = zodzod.object({announce: zod.boolean().describe('Only admins may post.'),- community: zod+ communityAnnouncements: zod.boolean()+ .optional().describe(- 'Community announcement or parent group, outside the supported surface.'+ "The community's announcement group (everyone reads, admins post)."),- disappearing: zod+ communityJid: zod+ .string()+ .nullish()+ .describe(+ 'The community a linked subgroup or announcement group belongs to.'+ ),+ communityParent: zod.boolean()+ .optional().describe(- 'Disappearing messages are on; content is not retained.'+ "The community itself: it has no messages of its own and can't be added."+ ),+ disappearingSeconds: zod+ .number()+ .min(whatsappGroupResponseRosterDisappearingSecondsMin)+ .nullish()+ .describe(+ 'Disappearing-messages timer in seconds while it is on. Macro keeps the\nmessages; its sends carry the timer so phones treat them like their own.'),- group: zod- .union([- zod.null(),- zod- .object({- id: zod.uuid().describe('Group entity id.'),- name: zod- .string()- .describe('Display name, following WhatsApp.'),- })- .describe('A group entity bound to a remote group.'),- ])- .optional(),jid: zod.string().describe('Remote group JID.'),name: zod.string().describe('Current subject.'),observedAt: zod.iso@@ -49794,26 +49775,6 @@ export const whatsappGroupResponse = zod)).describe('Full roster.'),- shared: zod- .union([- zod.null(),- zod- .object({- id: zod.uuid().describe('Group entity id.'),- name: zod- .string()- .describe('Display name, following WhatsApp.'),- owner_id: zod- .string()- .describe(- 'Macro user who added the group and shared it.'- ),- })- .describe(- "Another person's group entity the caller can view."- ),- ])- .optional(),}).describe('One full metadata read of a group, never an incomplete membership delta.'@@ -50464,6 +50425,11 @@ export const whatsappGroupMessagesResponse = zodsent_at: zod.iso.datetime({}).describe('Timestamp assigned by WhatsApp.'),+ view_once: zod+ .boolean()+ .describe(+ 'Sent as view-once in WhatsApp; Macro shows it like any media.'+ ),}).describe('One message in an adopted group.'))diff --git a/apps/web/src/lib/service-clients/service-storage/openapi.json b/apps/web/src/lib/service-clients/service-storage/openapi.jsonindex 40ef0d2c47..5228f51a53 100644--- a/apps/web/src/lib/service-clients/service-storage/openapi.json+++ b/apps/web/src/lib/service-clients/service-storage/openapi.json@@ -16143,28 +16143,6 @@}}},- "/meta/linked/groups": {- "get": {- "tags": ["whatsapp_linked::inbound::router"],- "summary": "Groups the caller's account has joined.",- "operationId": "linked_groups",- "responses": {- "200": {- "description": "",- "content": {- "application/json": {- "schema": {- "type": "array",- "items": {- "$ref": "#/components/schemas/LinkedGroupInfo"- }- }- }- }- }- }- }- },"/meta/linked/groups/adopt": {"post": {"tags": ["whatsapp_linked::inbound::router"],@@ -33365,7 +33343,7 @@"properties": {"group_jid": {"type": "string",- "description": "Group the requester's account has joined."+ "description": "A group the requester's account has joined, or a direct chat from\ntheir chat list (the other person's JID, as the list names it)."}}},@@ -33460,6 +33438,11 @@"description": "Where importing a group's earlier messages stands.","enum": ["pending", "running", "waiting_for_phone", "done", "partial"]},+ "LinkedCannotAdd": {+ "type": "string",+ "description": "Why a chat can't be added to Macro; the app words it from the code.",+ "enum": ["not_in_group", "community", "own_chat", "not_in_chat_list"]+ },"LinkedCapabilities": {"type": "object","description": "Operations implemented for linked groups, independent of current permission.",@@ -33526,8 +33509,26 @@"description": "\"Add to Macro\" works now."},"cannotAddReason": {- "type": ["string", "null"],- "description": "Why it can't be added, when it is neither added, shared nor addable."+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/LinkedCannotAdd",+ "description": "Why it can't be added, when it is neither added, shared nor addable."+ }+ ]+ },+ "community": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/LinkedCommunityReference",+ "description": "The community a group belongs to (a community's group or its\nannouncement group); `null` otherwise."+ }+ ]},"group": {"oneOf": [@@ -33593,6 +33594,25 @@}}},+ "LinkedCommunityReference": {+ "type": "object",+ "description": "The WhatsApp community a group belongs to.",+ "required": ["id", "name", "announcements"],+ "properties": {+ "announcements": {+ "type": "boolean",+ "description": "This group is the community's announcement group."+ },+ "id": {+ "type": "string",+ "description": "The community's WhatsApp JID."+ },+ "name": {+ "type": "string",+ "description": "The community's name."+ }+ }+ },"LinkedConnect": {"type": "object","description": "Explicit pairing intent; replacement is a separate deliberate action.",@@ -33662,38 +33682,29 @@"LinkedGroupInfo": {"type": "object","description": "One full metadata read of a group, never an incomplete membership delta.",- "required": [- "jid",- "name",- "participants",- "announce",- "disappearing",- "community",- "observedAt"- ],+ "required": ["jid", "name", "participants", "announce", "observedAt"],"properties": {"announce": {"type": "boolean","description": "Only admins may post."},- "community": {+ "communityAnnouncements": {"type": "boolean",- "description": "Community announcement or parent group, outside the supported surface."+ "description": "The community's announcement group (everyone reads, admins post)."+ },+ "communityJid": {+ "type": ["string", "null"],+ "description": "The community a linked subgroup or announcement group belongs to."},- "disappearing": {+ "communityParent": {"type": "boolean",- "description": "Disappearing messages are on; content is not retained."+ "description": "The community itself: it has no messages of its own and can't be added."},- "group": {- "oneOf": [- {- "type": "null"- },- {- "$ref": "#/components/schemas/LinkedGroupReference",- "description": "The caller's own Macro group for this remote group, once they added\nit. Only set by the groups listing."- }- ]+ "disappearingSeconds": {+ "type": ["integer", "null"],+ "format": "int32",+ "description": "Disappearing-messages timer in seconds while it is on. Macro keeps the\nmessages; its sends carry the timer so phones treat them like their own.",+ "minimum": 0},"jid": {"type": "string",@@ -33714,17 +33725,6 @@"$ref": "#/components/schemas/LinkedParticipant"},"description": "Full roster."- },- "shared": {- "oneOf": [- {- "type": "null"- },- {- "$ref": "#/components/schemas/LinkedSharedGroupReference",- "description": "Someone else's Macro group for this remote group that was shared with\nthe caller, when the caller has not added their own. Only set by the\ngroups listing."- }- ]}}},@@ -34044,7 +34044,7 @@"LinkedSharedGroupReference": {"type": "object","description": "Another person's group entity the caller can view.",- "required": ["id", "name", "owner_id"],+ "required": ["id", "name", "ownerId"],"properties": {"id": {"type": "string",@@ -34055,7 +34055,7 @@"type": "string","description": "Display name, following WhatsApp."},- "owner_id": {+ "ownerId": {"type": "string","description": "Macro user who added the group and shared it."}@@ -44690,6 +44690,23 @@"$ref": "#/components/schemas/AccessLevel","description": "Caller's effective permission."},+ "community": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/LinkedCommunityReference",+ "description": "The WhatsApp community this group belongs to, if any."+ }+ ]+ },+ "disappearing_seconds": {+ "type": ["integer", "null"],+ "format": "int32",+ "description": "WhatsApp's disappearing-messages timer in seconds while it is on;\nMacro keeps the messages anyway. `null` when off or unknown.",+ "minimum": 0+ },"limits": {"$ref": "#/components/schemas/LinkedCapabilities","description": "Size and mutation limits."@@ -44732,6 +44749,7 @@"attachments","kind","forwarded",+ "view_once","mentions"],"properties": {@@ -44822,6 +44840,10 @@"type": "string","format": "date-time","description": "Timestamp assigned by WhatsApp."+ },+ "view_once": {+ "type": "boolean",+ "description": "Sent as view-once in WhatsApp; Macro shows it like any media."}}},@@ -44887,7 +44909,14 @@"WhatsAppGroupSummary": {"type": "object","description": "Adopted group visible through ordinary entity sharing.",- "required": ["id", "name", "user_id", "unread_count", "can_send"],+ "required": [+ "id",+ "name",+ "kind",+ "user_id",+ "unread_count",+ "can_send"+ ],"properties": {"backfill": {"oneOf": [@@ -44909,6 +44938,10 @@"format": "uuid","description": "Entity identifier."},+ "kind": {+ "$ref": "#/components/schemas/LinkedChatKind",+ "description": "A group, or a direct chat with one person (only its owner sends)."+ },"last_message_at": {"type": ["string", "null"],"format": "date-time",@@ -44916,7 +44949,7 @@},"name": {"type": "string",- "description": "Display name."+ "description": "Display name: the group's, or a direct chat's other person."},"send_reason": {"oneOf": [diff --git a/apps/web/src/routes/app-router-view.tsx b/apps/web/src/routes/app-router-view.tsxindex 916556e955..a9088c344c 100644--- a/apps/web/src/routes/app-router-view.tsx+++ b/apps/web/src/routes/app-router-view.tsx@@ -154,7 +154,6 @@ import {tasksSplitRoute,teamInviteRoute,welcomeRoute,- whatsappGroupRoute,} from './routes';import {AppShell,@@ -164,10 +163,6 @@ import {withMeetingShell,} from './shells';-const WhatsAppGroupRedirectRouteView = lazyNamed(- () => import('@app/features/whatsapp-group/route-views'),- 'WhatsAppGroupRedirectRouteView'-);const ExternalWhatsAppGroupRouteView = lazyNamed(() => import('@app/features/external-view/route-views'),'ExternalWhatsAppGroupRouteView'@@ -430,10 +425,6 @@ export function AppRouterView() {<Route definition={callsRoute} component={CallsRouteView}><Route definition={callsCallRoute} component={CallsCallDetail} /></Route>- <Route- definition={whatsappGroupRoute}- component={WhatsAppGroupRedirectRouteView}- /><Route definition={callDetailRoute} component={CallDetailRouteView} /><Route definition={companiesRoute} component={CompaniesRouteView}><Route definition={crmPipelineRoute}>diff --git a/apps/web/src/routes/routes.ts b/apps/web/src/routes/routes.tsindex 8d9590cb60..6bc59c42cb 100644--- a/apps/web/src/routes/routes.ts+++ b/apps/web/src/routes/routes.ts@@ -578,14 +578,6 @@ export const reviewsSplitRoute = defineRoute({search: [reviewsTabSearch.namespace],});-/** Retired `/whatsapp-group/:groupId` links; redirects into External. */-export const whatsappGroupRoute = defineRoute({- id: 'whatsapp-group',- path: 'whatsapp-group/:groupId',- params: z.object({ groupId: z.string().uuid() }),- remountKey: ({ groupId }) => groupId,-});-/** A shareable WhatsApp conversation in External's main pane, with no channel or legacy block. */export const externalWhatsappGroupRoute = defineRoute({id: 'external-whatsapp-group',diff --git a/apps/web/tests/functional/whatsapp-linked.spec.ts b/apps/web/tests/functional/whatsapp-linked.spec.tsindex 6101117231..6eb37542f0 100644--- a/apps/web/tests/functional/whatsapp-linked.spec.ts+++ b/apps/web/tests/functional/whatsapp-linked.spec.ts@@ -10,7 +10,9 @@ type Chat = {name: string;lastActivityAt: string | null;group: { id: string; name: string } | null;- shared?: { id: string; name: string; owner_id: string };+ shared?: { id: string; name: string; ownerId: string };+ /** The account's chat with itself. */+ self?: boolean;};/** Server state the mocked DSS `/meta/linked` routes answer from. */@@ -41,6 +43,8 @@ type LinkedServer = {sendReplies: { status: number; json: unknown }[];/** Progress `POST /delivery` reports, by send id. */delivery: Record<string, { state: string; message_id: string | null }>;+ /** What `POST /attachments` says it staged. */+ upload: { filename: string; kind: string };};function server(): LinkedServer {@@ -80,9 +84,17 @@ function server(): LinkedServer {shared: {id: 'group-shared-family',name: 'Ana, Ben, +2',- owner_id: 'macro|[email protected]',+ ownerId: 'macro|[email protected]',},},+ {+ jid: '[email protected]',+ kind: 'direct',+ name: 'You',+ lastActivityAt: null,+ group: null,+ self: true,+ },],requests: [],adoptions: [],@@ -95,6 +107,7 @@ function server(): LinkedServer {readMessages: [],sendReplies: [],delivery: {},+ upload: { filename: 'design.pdf', kind: 'document' },};}@@ -315,11 +328,7 @@ async function mount(page: Page, state: LinkedServer, query = '') {}if (suffix === '/attachments')return route.fulfill({- json: {- upload_id: 'upload-1',- filename: 'design.pdf',- kind: 'document',- },+ json: { upload_id: 'upload-1', ...state.upload },});if (suffix === '/permissions' && method === 'PATCH') {state.permissionUpdates.push(route.request().postDataJSON());@@ -348,6 +357,7 @@ async function mount(page: Page, state: LinkedServer, query = '') {.filter((item) => item.group).map((item) => ({id: item.group?.id,+ kind: item.kind,name: item.group?.name,user_id: USER_ID,unread_count: item.group?.id === GROUP_ID ? 2 : 0,@@ -402,11 +412,10 @@ async function mount(page: Page, state: LinkedServer, query = '') {archived: false,pinned: false,shared: chat.group ? null : (chat.shared ?? null),- canAdd: chat.kind === 'group' && !chat.group && !chat.shared,- cannotAddReason:- chat.kind === 'direct'- ? "direct chats can't be added to Macro yet"- : null,+ canAdd: !chat.self && !chat.group && !chat.shared,+ cannotAddReason: chat.self+ ? "your chat with yourself can't be added to Macro"+ : null,})),},});@@ -471,17 +480,25 @@ test('links WhatsApp by QR, then adds a shareable WhatsApp group', async ({await expect(dialog).toBeHidden();expect(state.requests).not.toContain('DELETE pairing/pairing-1');- const groups = page.getByRole('list', { name: 'Groups to add to Macro' });+ const groups = page.getByRole('list', { name: 'Chats to add to Macro' });await expect(groups.getByText('Launch War Room')).toBeVisible();await expect(groups.getByText('Design Crit')).toHaveCount(0);- // Direct chats are listed by recent activity but can't be added yet.+ // Direct chats are added like groups; only the chat with yourself isn't.+ await expect(+ groups+ .getByRole('listitem')+ .filter({ hasText: 'Ana Ruiz' })+ .getByText('Direct chat')+ ).toBeVisible();await page.getByRole('button', { name: /Can't be added \(1\)/ }).click();- const direct = page+ const self = page.getByRole('list', { name: "Can't be added" }).getByRole('listitem')- .filter({ hasText: 'Ana Ruiz' });- await expect(direct.getByText("Can't add direct chats yet")).toBeVisible();- await expect(direct.getByRole('button')).toHaveCount(0);+ .filter({ hasText: 'You' });+ await expect(+ self.getByText("Your chat with yourself can't be added to Macro")+ ).toBeVisible();+ await expect(self.getByRole('button')).toHaveCount(0);const search = page.getByRole('searchbox', { name: 'Search WhatsApp chats' });await search.fill('design');await expect(@@ -492,7 +509,7 @@ test('links WhatsApp by QR, then adds a shareable WhatsApp group', async ({await search.fill('launch');await expect(groups.getByRole('listitem')).toHaveCount(1);await search.fill('');- await expect(groups.getByRole('listitem')).toHaveCount(2);+ await expect(groups.getByRole('listitem')).toHaveCount(3);await groups.getByRole('button', { name: /shared with you by Group Owner/i }).click();@@ -500,7 +517,11 @@ test('links WhatsApp by QR, then adds a shareable WhatsApp group', async ({'group-shared-family',]);- await groups.getByRole('button', { name: 'Add to Macro' }).click();+ await groups+ .getByRole('listitem')+ .filter({ hasText: 'Launch War Room' })+ .getByRole('button', { name: 'Add to Macro' })+ .click();await expect(page.getByRole('dialog')).toHaveCount(0);await expect(groups.getByText('Launch War Room')).toHaveCount(0);expect(state.adoptions).toEqual([{ group_jid: '[email protected]' }]);@@ -528,12 +549,12 @@ test('a refused add says why, on that group', async ({ page }) => {}));const row = page- .getByRole('list', { name: 'Groups to add to Macro' })+ .getByRole('list', { name: 'Chats to add to Macro' }).getByRole('listitem').filter({ hasText: 'Launch War Room' });await row.getByRole('button', { name: 'Add to Macro' }).click();await expect(row.getByRole('alert')).toHaveText(- 'Your WhatsApp is disconnected. Reconnect it, then add the group.'+ 'Your WhatsApp is disconnected. Reconnect it, then add the chat.');expect(unexpected).toEqual([]);});@@ -545,7 +566,7 @@ test('External lists groups in Macro with unread counts and read-only tags', asystate.chats[2].group = { id: 'group-shared', name: 'Launch War Room' };const unexpected = await mount(page, state, '?view=in-macro');const nav = page.getByRole('navigation', {- name: 'WhatsApp groups in Macro',+ name: 'WhatsApp chats in Macro',});const design = nav.getByRole('button', { name: /design-crit/ });await expect(design.getByLabel('2 unread messages')).toBeVisible();@@ -716,8 +737,8 @@ function everyMessageType() {rich: {type: 'system',action: 'participants_added',- actor: { name: 'Ana Ruiz', userId: null },- participants: [{ name: '+1 555 0100', userId: null }],+ actor: { name: 'Ana Ruiz', user_id: null },+ participants: [{ name: '+1 555 0100', user_id: null }],value: null,call: null,},@@ -728,7 +749,7 @@ function everyMessageType() {sent_at: at(2),forwarded: true,body: 'Ping @15550001111 about https://example.com',- mentions: [{ token: '15550001111', name: 'Ben Ode', userId: null }],+ mentions: [{ token: '15550001111', name: 'Ben Ode', user_id: null }],},{...base,@@ -741,7 +762,7 @@ function everyMessageType() {{ name: 'Tacos', votes: 2, mine: true, voters: [] },{ name: 'Pho', votes: 0, mine: false, voters: [] },],- selectableCount: 1,+ selectable_count: 1,voters: 2,},},@@ -777,10 +798,10 @@ function everyMessageType() {type: 'event',name: 'Launch party',description: null,- startAt: '2026-10-24T22:00:00Z',- endAt: null,+ start_at: '2026-10-24T22:00:00Z',+ end_at: null,location: 'Rooftop',- joinLink: null,+ join_link: null,canceled: false,},},@@ -838,14 +859,14 @@ function everyMessageType() {actor: null,participants: [],value: null,- call: { video: true, outcome: 'missed', durationSeconds: null },+ call: { video: true, outcome: 'missed', duration_seconds: null },},},{...base,- id: 'type-view-once',+ id: 'type-unknown',sent_at: at(12),- body: 'View-once message — open it on your phone',+ body: "Sent something Macro can't show yet",},];}@@ -909,7 +930,7 @@ test('every WhatsApp message type renders with Chat parts and small cards', asyn]));await expect(- timeline.getByText('View-once message — open it on your phone')+ timeline.getByText("Sent something Macro can't show yet")).toBeVisible();// The newest row is in view: the timeline opened at the bottom.await expect(@@ -941,6 +962,73 @@ test('the composer mentions group participants as WhatsApp mentions', async ({expect(unexpected).toEqual([]);});+const PNG = Buffer.from(+ 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==',+ 'base64'+);++test('an image sent from Macro shows at once and stays one image once stored', async ({+ page,+}) => {+ const state = server();+ state.upload = { filename: 'photo.png', kind: 'image' };+ const unexpected = await mount(page, state, `?group=${GROUP_ID}`);+ const timeline = page.getByRole('log', { name: 'WhatsApp messages' });+ await page+ .locator('[data-input] input[type="file"]')+ .first()+ .setInputFiles({ name: 'photo.png', mimeType: 'image/png', buffer: PNG });+ const send = page.getByRole('button', { name: 'Send message' });+ await expect(send).toBeEnabled();+ await send.click();+ await expect.poll(() => state.outgoing.length).toBe(1);+ expect(state.outgoing[0]).toMatchObject({+ message: { type: 'media', upload_id: 'upload-1' },+ });+ // The local preview, before WhatsApp has it; no file chip.+ await expect(timeline.locator('img[src^="blob:"]').first()).toBeAttached();+ await expect(timeline.getByText(/Loading photo\.png/)).toHaveCount(0);+ const sendId = Object.keys(state.delivery)[0] ?? '';+ state.imported = [+ {+ ...incomingMessage,+ id: 'message-sent',+ body: '',+ sender: { name: 'Me', user_id: USER_ID },+ sent_at: new Date(Date.now() + 1000).toISOString(),+ reactions: [],+ attachments: [+ {+ ordinal: 0,+ state: 'ready',+ file_name: 'photo.png',+ mime: 'image/png',+ size: PNG.length,+ document_id: 'document-sent',+ width: null,+ height: null,+ duration_seconds: null,+ presentation: null,+ },+ ],+ },+ ];+ state.delivery[sendId] = { state: 'accepted', message_id: 'message-sent' };+ await expect(+ timeline.locator('[data-message-id="message-sent"]')+ ).toBeVisible();+ // One image: the pending row gave way to the stored message.+ await expect(+ timeline.getByRole('button', { name: 'Open image viewer' })+ ).toHaveCount(1);+ await expect(+ timeline+ .locator('[data-message-id="message-sent"]')+ .getByRole('button', { name: 'Open image viewer' })+ ).toBeVisible();+ expect(unexpected).toEqual([]);+});+test('history imported after adding shows up older, with the import state', async ({page,}) => {@@ -990,7 +1078,7 @@ test('a refused send leaves the conversation, says why and restores the draft',await typeInComposer(page, 'Not allowed here');await page.getByRole('button', { name: 'Send message' }).click();await expect(- page.getByText("Your WhatsApp can't send to this group.")+ page.getByText("Your WhatsApp can't send to this chat.")).toBeVisible();await expect(page.locator('[role="log"]').getByText('Not allowed here')@@ -1103,7 +1191,7 @@ test('opens the standard share dialog for the independent group entity', async (await expect(page.getByRole('dialog')- .getByText(/Only the owner can share access to this WhatsApp group/)+ .getByText(/Only the owner can share access to this WhatsApp chat/)).toBeVisible();await expect(page.getByRole('dialog').getByRole('button', { name: 'Copy Link' })diff --git a/crates/agent_code_mode/src/domain/documentation.json b/crates/agent_code_mode/src/domain/documentation.jsonindex 6731c47ba4..148ebc273d 100644--- a/crates/agent_code_mode/src/domain/documentation.json+++ b/crates/agent_code_mode/src/domain/documentation.json@@ -79,9 +79,9 @@},{"name": "channels",- "description": "Read and send channel messages; read and share standalone WhatsApp groups, discover remote groups, and send from the credential owner’s own member account with media and delivery. Pairing stays in the app.",+ "description": "Read and send channel messages; list the WhatsApp chat list (groups and direct chats), add chats to Macro, read and share added chats, and send from the credential owner's own account with mentions, media and delivery. Pairing stays in the app.","overview": "<!-- src/entities/channels/namespace/classes/ChannelNamespace.md -->\n# Class: ChannelNamespace\n\n## Constructors\n\n### Constructor\n\n> **new ChannelNamespace**(`client`): `ChannelNamespace`\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n\n#### Returns\n\n`ChannelNamespace`\n\n## Properties\n\n| Property | Modifier | Type | Description |\n| ------ | ------ | ------ | ------ |\n| <a id=\"property-labels\"></a> `labels` | `readonly` | [`ChannelLabelsNamespace`](../../labels/classes/ChannelLabelsNamespace.md) | Team-shared labels that group channels in the Chat sidebar. |\n\n## Methods\n\n### activity()\n\n> **activity**(): `Promise`\\<[`ChannelActivity`](../../activity/classes/ChannelActivity.md)[]\\>\n\nRecent channel activity, with channel and user handles.\n\n#### Returns\n\n`Promise`\\<[`ChannelActivity`](../../activity/classes/ChannelActivity.md)[]\\>\n\n***\n\n### byId()\n\n> **byId**(`id`): [`Channel`](../../channel/classes/Channel.md)\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `id` | `string` |\n\n#### Returns\n\n[`Channel`](../../channel/classes/Channel.md)\n\n***\n\n### create()\n\n> **create**(`opts`): `Promise`\\<[`Channel`](../../channel/classes/Channel.md)\\>\n\nCreate a channel. The caller becomes the owner.\n\n#### Parameters\n\n| Parameter | Type | Description |\n| ------ | ------ | ------ |\n| `opts` | \\{ `name?`: `string`; `participants?`: [`User`](../../../users/user/classes/User.md)[]; `team?`: [`Team`](../../../teams/team/classes/Team.md); `type`: [`ChannelType`](../../../../../generated/storage/types.gen/type-aliases/ChannelType.md); \\} | - |\n| `opts.name?` | `string` | - |\n| `opts.participants?` | [`User`](../../../users/user/classes/User.md)[] | Participants to add, excluding the owner. |\n| `opts.team?` | [`Team`](../../../teams/team/classes/Team.md) | Team, for team channels. |\n| `opts.type` | [`ChannelType`](../../../../../generated/storage/types.gen/type-aliases/ChannelType.md) | - |\n\n#### Returns\n\n`Promise`\\<[`Channel`](../../channel/classes/Channel.md)\\>\n\n***\n\n### dm()\n\n> **dm**(`recipient`): `Promise`\\<[`Channel`](../../channel/classes/Channel.md)\\>\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `recipient` | [`User`](../../../users/user/classes/User.md) |\n\n#### Returns\n\n`Promise`\\<[`Channel`](../../channel/classes/Channel.md)\\>\n\n***\n\n### list()\n\n> **list**(): `Promise`\\<[`Channel`](../../channel/classes/Channel.md)[]\\>\n\nAll channels the authenticated user is a member of.\n\n#### Returns\n\n`Promise`\\<[`Channel`](../../channel/classes/Channel.md)[]\\>\n\n***\n\n### private()\n\n> **private**(`recipients`): `Promise`\\<[`Channel`](../../channel/classes/Channel.md)\\>\n\nOpen (creating if needed) the private group channel with a set of users.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `recipients` | [`User`](../../../users/user/classes/User.md)[] |\n\n#### Returns\n\n`Promise`\\<[`Channel`](../../channel/classes/Channel.md)\\>\n\n***\n\n### search()\n\n> **search**(`query`, `opts?`): `AsyncGenerator`\\<[`Channel`](../../channel/classes/Channel.md)\\>\n\nSearch channels by name (client-side fuzzy filter on the full channel list)\nor by content (server-side unified search).\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `query` | `string` |\n| `opts?` | [`SearchOpts`](../../../search/interfaces/SearchOpts.md) |\n\n#### Returns\n\n`AsyncGenerator`\\<[`Channel`](../../channel/classes/Channel.md)\\>\n\n\n<!-- src/entities/whatsapp/namespace/classes/WhatsAppNamespace.md -->\n# Class: WhatsAppNamespace\n\nOperate on an account already paired through the Macro app.\n\n## Constructors\n\n### Constructor\n\n> **new WhatsAppNamespace**(`client`): `WhatsAppNamespace`\n\nBind existing-account operations to this authenticated client.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n\n#### Returns\n\n`WhatsAppNamespace`\n\n## Methods\n\n### account()\n\n> **account**(): `Promise`\\<[`WhatsAppAccount`](../../account/classes/WhatsAppAccount.md) \\| `undefined`\\>\n\nCurrent owner's account, or undefined when no account has been connected.\n\n#### Returns\n\n`Promise`\\<[`WhatsAppAccount`](../../account/classes/WhatsAppAccount.md) \\| `undefined`\\>\n\n***\n\n### byId()\n\n> **byId**(`id`): [`WhatsAppGroup`](../../group/classes/WhatsAppGroup.md)\n\nReference an adopted entity without fetching it.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `id` | `string` |\n\n#### Returns\n\n[`WhatsAppGroup`](../../group/classes/WhatsAppGroup.md)\n\n***\n\n### groups()\n\n> **groups**(): `Promise`\\<[`WhatsAppGroup`](../../group/classes/WhatsAppGroup.md)[]\\>\n\nAdopted groups shared with the caller, including without WhatsApp.\n\n#### Returns\n\n`Promise`\\<[`WhatsAppGroup`](../../group/classes/WhatsAppGroup.md)[]\\>\n",- "documentation": "# Macro SDK: channels\n\nGenerated by TypeDoc. Paths below refer to the canonical Markdown hierarchy. Other entity handles are documented in their named section; request core for shared SDK helpers.\n\n<!-- generated/properties/types.gen/type-aliases/BulkUpdateEntityPropertyOptionsResponse.md -->\n# Type Alias: BulkUpdateEntityPropertyOptionsResponse\n\n> **BulkUpdateEntityPropertyOptionsResponse** = \\{ `properties`: [`EntityPropertyOptionSelectionResponse`](EntityPropertyOptionSelectionResponse.md)[]; \\}\n\nResponse for a bulk option update: each property's reconciled final ids.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-properties\"></a> `properties` | [`EntityPropertyOptionSelectionResponse`](EntityPropertyOptionSelectionResponse.md)[] | The final option ids per updated property. |\n\n\n<!-- generated/properties/types.gen/type-aliases/DataType.md -->\n# Type Alias: DataType\n\n> **DataType** = `\"BOOLEAN\"` \\| `\"DATE\"` \\| `\"NUMBER\"` \\| `\"STRING\"` \\| `\"SELECT_NUMBER\"` \\| `\"SELECT_STRING\"` \\| `\"TAG\"` \\| `\"ENTITY\"` \\| `\"LINK\"`\n\nData type for property values, determining storage and validation.\n\n\n<!-- generated/properties/types.gen/type-aliases/EntityProperty.md -->\n# Type Alias: EntityProperty\n\n> **EntityProperty** = \\{ `created_at`: `string`; `entity_id`: `string`; `entity_type`: [`EntityType`](EntityType.md); `id`: `string`; `property_definition_id`: `string`; `updated_at`: `string`; \\}\n\nAssignment of a property definition to a specific entity (service representation).\n\n## Properties\n\n| Property | Type |\n| ------ | ------ |\n| <a id=\"property-created_at\"></a> `created_at` | `string` |\n| <a id=\"property-entity_id\"></a> `entity_id` | `string` |\n| <a id=\"property-entity_type\"></a> `entity_type` | [`EntityType`](EntityType.md) |\n| <a id=\"property-id\"></a> `id` | `string` |\n| <a id=\"property-property_definition_id\"></a> `property_definition_id` | `string` |\n| <a id=\"property-updated_at\"></a> `updated_at` | `string` |\n\n\n<!-- generated/properties/types.gen/type-aliases/EntityPropertyOptionSelectionResponse.md -->\n# Type Alias: EntityPropertyOptionSelectionResponse\n\n> **EntityPropertyOptionSelectionResponse** = \\{ `option_ids`: `string`[]; `property_id`: `string`; \\}\n\nThe reconciled final option ids stored for one property after a bulk update.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-option_ids\"></a> `option_ids` | `string`[] | The final option ids the server persisted, in stored order. |\n| <a id=\"property-property_id\"></a> `property_id` | `string` | The property definition the options belong to. |\n\n\n<!-- generated/properties/types.gen/type-aliases/EntityPropertyWithDefinition.md -->\n# Type Alias: EntityPropertyWithDefinition\n\n> **EntityPropertyWithDefinition** = \\{ `definition`: [`PropertyDefinition`](PropertyDefinition.md); `options?`: [`PropertyOption`](PropertyOption.md)[] \\| `null`; `property`: [`EntityProperty`](EntityProperty.md); `value?`: `null` \\| [`PropertyValue`](PropertyValue.md); \\}\n\nEntity property with its definition, value, and options (service representation).\n\n## Properties\n\n| Property | Type |\n| ------ | ------ |\n| <a id=\"property-definition\"></a> `definition` | [`PropertyDefinition`](PropertyDefinition.md) |\n| <a id=\"property-options\"></a> `options?` | [`PropertyOption`](PropertyOption.md)[] \\| `null` |\n| <a id=\"property-property\"></a> `property` | [`EntityProperty`](EntityProperty.md) |\n| <a id=\"property-value\"></a> `value?` | `null` \\| [`PropertyValue`](PropertyValue.md) |\n\n\n<!-- generated/properties/types.gen/type-aliases/EntityReference.md -->\n# Type Alias: EntityReference\n\n> **EntityReference** = \\{ `entity_id`: `string`; `entity_type`: [`EntityType`](EntityType.md); `specific_message_id?`: `string` \\| `null`; \\}\n\nEntity reference for entity-type property values.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-entity_id\"></a> `entity_id` | `string` | - |\n| <a id=\"property-entity_type\"></a> `entity_type` | [`EntityType`](EntityType.md) | - |\n| <a id=\"property-specific_message_id\"></a> `specific_message_id?` | `string` \\| `null` | For CHANNEL, CHAT, THREAD entity types - optional specific message ID. This allows referencing a specific message within a thread/channel/chat. |\n\n\n<!-- generated/properties/types.gen/type-aliases/EntityType.md -->\n# Type Alias: EntityType\n\n> **EntityType** = `\"CALENDAR_EVENT\"` \\| `\"CALL_RECORD\"` \\| `\"CHANNEL\"` \\| `\"CHAT\"` \\| `\"COMPANY\"` \\| `\"DATABASE_ROW\"` \\| `\"CONTACT\"` \\| `\"DOCUMENT\"` \\| `\"INITIATIVE\"` \\| `\"PROJECT\"` \\| `\"TASK\"` \\| `\"THREAD\"` \\| `\"USER\"`\n\nType of entity that can be referenced by entity properties.\n\n\n<!-- generated/properties/types.gen/type-aliases/PropertyDefinition.md -->\n# Type Alias: PropertyDefinition\n\n> **PropertyDefinition** = \\{ `created_at`: `string`; `data_type`: [`DataType`](DataType.md); `display_name`: `string`; `id`: `string`; `is_metadata`: `boolean`; `is_multi_select`: `boolean`; `is_system`: `boolean`; `owner`: [`PropertyOwner`](PropertyOwner.md); `specific_entity_type`: `null` \\| [`EntityType`](EntityType.md); `updated_at`: `string`; \\}\n\nProperty definition model (service representation).\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-created_at\"></a> `created_at` | `string` | - |\n| <a id=\"property-data_type\"></a> `data_type` | [`DataType`](DataType.md) | - |\n| <a id=\"property-display_name\"></a> `display_name` | `string` | - |\n| <a id=\"property-id\"></a> `id` | `string` | - |\n| <a id=\"property-is_metadata\"></a> `is_metadata` | `boolean` | Flag to indicate if this is a system-generated metadata property. Not stored in database - computed at service layer. |\n| <a id=\"property-is_multi_select\"></a> `is_multi_select` | `boolean` | - |\n| <a id=\"property-is_system\"></a> `is_system` | `boolean` | Flag to indicate if this is a system property (stored in DB). |\n| <a id=\"property-owner\"></a> `owner` | [`PropertyOwner`](PropertyOwner.md) | - |\n| <a id=\"property-specific_entity_type\"></a> `specific_entity_type` | `null` \\| [`EntityType`](EntityType.md) | - |\n| <a id=\"property-updated_at\"></a> `updated_at` | `string` | - |\n\n\n<!-- generated/properties/types.gen/type-aliases/PropertyOption.md -->\n# Type Alias: PropertyOption\n\n> **PropertyOption** = \\{ `color`: `string` \\| `null`; `created_at`: `string`; `display_order`: `number`; `id`: `string`; `property_definition_id`: `string`; `updated_at`: `string`; `value`: [`PropertyOptionValue`](PropertyOptionValue.md); \\}\n\nA selectable option for select-type properties (service representation).\n\n## Properties\n\n| Property | Type |\n| ------ | ------ |\n| <a id=\"property-color\"></a> `color` | `string` \\| `null` |\n| <a id=\"property-created_at\"></a> `created_at` | `string` |\n| <a id=\"property-display_order\"></a> `display_order` | `number` |\n| <a id=\"property-id\"></a> `id` | `string` |\n| <a id=\"property-property_definition_id\"></a> `property_definition_id` | `string` |\n| <a id=\"property-updated_at\"></a> `updated_at` | `string` |\n| <a id=\"property-value\"></a> `value` | [`PropertyOptionValue`](PropertyOptionValue.md) |\n\n\n<!-- generated/properties/types.gen/type-aliases/PropertyOptionValue.md -->\n# Type Alias: PropertyOptionValue\n\n> **PropertyOptionValue** = \\{ `type`: `\"string\"`; `value`: `string`; \\} \\| \\{ `type`: `\"number\"`; `value`: `number`; \\}\n\nThe value of a property option - either a string or a number.\n\n## Union Members\n\n### Type Literal\n\n\\{ `type`: `\"string\"`; `value`: `string`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `type` | `\"string\"` | - |\n| `value` | `string` | String value for SelectString properties |\n\n***\n\n### Type Literal\n\n\\{ `type`: `\"number\"`; `value`: `number`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `type` | `\"number\"` | - |\n| `value` | `number` | Number value for SelectNumber properties |\n\n\n<!-- generated/properties/types.gen/type-aliases/PropertyOwner.md -->\n# Type Alias: PropertyOwner\n\n> **PropertyOwner** = \\{ `scope`: `\"user\"`; `user_id`: `string`; \\} \\| \\{ `scope`: `\"team\"`; `team_id`: `string`; \\} \\| \\{ `database_id`: `string`; `scope`: `\"database\"`; \\} \\| \\{ `scope`: `\"system\"`; \\}\n\nDefines who owns a property - user-scoped, team-scoped, database-scoped, or system.\n\n\n<!-- generated/properties/types.gen/type-aliases/PropertyTargetEntityType.md -->\n# Type Alias: PropertyTargetEntityType\n\n> **PropertyTargetEntityType** = `\"CALL_RECORD\"` \\| `\"CHANNEL\"` \\| `\"CHAT\"` \\| `\"COMPANY\"` \\| `\"DATABASE_ROW\"` \\| `\"DOCUMENT\"` \\| `\"INITIATIVE\"` \\| `\"PROJECT\"` \\| `\"THREAD\"` \\| `\"USER\"`\n\nCanonical type of an entity receiving properties.\n\nTasks are documents at API boundaries. `Task` intentionally does not exist\nhere; task classification is resolved by the properties domain from the\ndocument subtype.\n\n\n<!-- generated/properties/types.gen/type-aliases/PropertyTargetReference.md -->\n# Type Alias: PropertyTargetReference\n\n> **PropertyTargetReference** = \\{ `entity_id`: `string`; `entity_type`: [`PropertyTargetEntityType`](PropertyTargetEntityType.md); \\}\n\nCanonical reference to an entity receiving properties.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-entity_id\"></a> `entity_id` | `string` | Entity identifier. |\n| <a id=\"property-entity_type\"></a> `entity_type` | [`PropertyTargetEntityType`](PropertyTargetEntityType.md) | Canonical entity type. |\n\n\n<!-- generated/properties/types.gen/type-aliases/PropertyValue.md -->\n# Type Alias: PropertyValue\n\n> **PropertyValue** = \\{ `type`: `\"Boolean\"`; `value`: `boolean`; \\} \\| \\{ `type`: `\"Number\"`; `value`: `number`; \\} \\| \\{ `type`: `\"String\"`; `value`: `string`; \\} \\| \\{ `type`: `\"Date\"`; `value`: `string`; \\} \\| \\{ `type`: `\"SelectOption\"`; `value`: `string`[]; \\} \\| \\{ `type`: `\"EntityReference\"`; `value`: [`EntityReference`](EntityReference.md)[]; \\} \\| \\{ `type`: `\"Link\"`; `value`: `string`[]; \\}\n\nProperty value (service representation).\n\nRepresents the actual value stored for an entity property.\nThis is serialized to/from JSONB in the database.\n\n## Union Members\n\n### Type Literal\n\n\\{ `type`: `\"Boolean\"`; `value`: `boolean`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `type` | `\"Boolean\"` | - |\n| `value` | `boolean` | Boolean value Serializes as: {\"type\": \"Boolean\", \"value\": true} |\n\n***\n\n### Type Literal\n\n\\{ `type`: `\"Number\"`; `value`: `number`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `type` | `\"Number\"` | - |\n| `value` | `number` | Numeric value Serializes as: {\"type\": \"Number\", \"value\": 42.5} |\n\n***\n\n### Type Literal\n\n\\{ `type`: `\"String\"`; `value`: `string`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `type` | `\"String\"` | - |\n| `value` | `string` | String value Serializes as: {\"type\": \"String\", \"value\": \"text\"} |\n\n***\n\n### Type Literal\n\n\\{ `type`: `\"Date\"`; `value`: `string`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `type` | `\"Date\"` | - |\n| `value` | `string` | Date/timestamp value Serializes as: {\"type\": \"Date\", \"value\": \"2025-01-01T00:00:00Z\"} |\n\n***\n\n### Type Literal\n\n\\{ `type`: `\"SelectOption\"`; `value`: `string`[]; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `type` | `\"SelectOption\"` | - |\n| `value` | `string`[] | Select option(s) - always an array (check is_multi_select to determine if single or multi) Single-select: {\"type\": \"SelectOption\", \"value\": [\"uuid\"]} (length 0 or 1) Multi-select: {\"type\": \"SelectOption\", \"value\": [\"uuid1\", \"uuid2\", ...]} (length 0+) |\n\n***\n\n### Type Literal\n\n\\{ `type`: `\"EntityReference\"`; `value`: [`EntityReference`](EntityReference.md)[]; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `type` | `\"EntityReference\"` | - |\n| `value` | [`EntityReference`](EntityReference.md)[] | Entity reference(s) - always an array (check is_multi_select to determine if single or multi) Single-select: {\"type\": \"EntityReference\", \"value\": [{...}]} (length 0 or 1) Multi-select: {\"type\": \"EntityReference\", \"value\": [{...}, {...}, ...]} (length 0+) |\n\n***\n\n### Type Literal\n\n\\{ `type`: `\"Link\"`; `value`: `string`[]; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `type` | `\"Link\"` | - |\n| `value` | `string`[] | Link value(s) - always an array (check is_multi_select to determine if single or multi) Single-select: {\"type\": \"Link\", \"value\": [\"https://example.com\"]} (length 0 or 1) Multi-select: {\"type\": \"Link\", \"value\": [\"https://example.com\", \"https://other.com\"]} (length 0+) |\n\n\n<!-- generated/properties/types.gen/type-aliases/SetPropertyValue.md -->\n# Type Alias: SetPropertyValue\n\n> **SetPropertyValue** = \\{ `type`: `\"boolean\"`; `value`: `boolean`; \\} \\| \\{ `type`: `\"date\"`; `value`: `string`; \\} \\| \\{ `type`: `\"number\"`; `value`: `number`; \\} \\| \\{ `type`: `\"string\"`; `value`: `string`; \\} \\| \\{ `option_id`: `string`; `type`: `\"select_option\"`; \\} \\| \\{ `option_ids`: `string`[]; `type`: `\"multi_select_option\"`; \\} \\| \\{ `reference`: [`EntityReference`](EntityReference.md); `type`: `\"entity_reference\"`; \\} \\| \\{ `references`: [`EntityReference`](EntityReference.md)[]; `type`: `\"multi_entity_reference\"`; \\} \\| \\{ `type`: `\"link\"`; `url`: `string`; \\} \\| \\{ `type`: `\"multi_link\"`; `urls`: `string`[]; \\}\n\nType-safe enum for setting entity property values - provides compile-time validation.\n\n\n<!-- generated/storage/types.gen/type-aliases/AccessLevel.md -->\n# Type Alias: AccessLevel\n\n> **AccessLevel** = `\"view\"` \\| `\"comment\"` \\| `\"edit\"` \\| `\"owner\"`\n\nOrdered from least to most access top -> bottom\n\n\n<!-- generated/storage/types.gen/type-aliases/ActivityType.md -->\n# Type Alias: ActivityType\n\n> **ActivityType** = `\"view\"` \\| `\"interact\"`\n\nThe kind of activity a user performs in a channel.\n\n\n<!-- generated/storage/types.gen/type-aliases/ApiActivity.md -->\n# Type Alias: ApiActivity\n\n> **ApiActivity** = \\{ `channel_id`: `string`; `created_at`: `string`; `id`: `string`; `interacted_at?`: `string` \\| `null`; `updated_at`: `string`; `user_id`: `string`; `viewed_at?`: `string` \\| `null`; \\}\n\nA user's activity (view/interaction) within a channel.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-channel_id\"></a> `channel_id` | `string` | Channel id. |\n| <a id=\"property-created_at\"></a> `created_at` | `string` | When the activity row was created. |\n| <a id=\"property-id\"></a> `id` | `string` | Activity id. |\n| <a id=\"property-interacted_at\"></a> `interacted_at?` | `string` \\| `null` | The last time the user interacted with the channel. |\n| <a id=\"property-updated_at\"></a> `updated_at` | `string` | When the activity row was last updated. |\n| <a id=\"property-user_id\"></a> `user_id` | `string` | User id. |\n| <a id=\"property-viewed_at\"></a> `viewed_at?` | `string` \\| `null` | The last time the user viewed the channel. |\n\n\n<!-- generated/storage/types.gen/type-aliases/ApiChannelAttachment.md -->\n# Type Alias: ApiChannelAttachment\n\n> **ApiChannelAttachment** = \\{ `channel_id`: `string`; `created_at`: `string`; `entity_id`: `string`; `entity_type`: `string`; `height?`: `number` \\| `null`; `id`: `string`; `message_id`: `string`; `sender_id`: `string`; `width?`: `number` \\| `null`; \\}\n\nA channel-level attachment.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-channel_id\"></a> `channel_id` | `string` | Channel id. |\n| <a id=\"property-created_at\"></a> `created_at` | `string` | When the attachment was created. |\n| <a id=\"property-entity_id\"></a> `entity_id` | `string` | Entity id. |\n| <a id=\"property-entity_type\"></a> `entity_type` | `string` | Type of entity. |\n| <a id=\"property-height\"></a> `height?` | `number` \\| `null` | Height (for images). |\n| <a id=\"property-id\"></a> `id` | `string` | Attachment id. |\n| <a id=\"property-message_id\"></a> `message_id` | `string` | Message id this attachment belongs to. |\n| <a id=\"property-sender_id\"></a> `sender_id` | `string` | The user who sent the message containing this attachment. |\n| <a id=\"property-width\"></a> `width?` | `number` \\| `null` | Width (for images). |\n\n\n<!-- generated/storage/types.gen/type-aliases/ApiChannelAttachmentsPage.md -->\n# Type Alias: ApiChannelAttachmentsPage\n\n> **ApiChannelAttachmentsPage** = \\{ `items`: [`ApiChannelAttachment`](ApiChannelAttachment.md)[]; `next_cursor?`: `string` \\| `null`; \\}\n\nPaginated response of channel attachments.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-items\"></a> `items` | [`ApiChannelAttachment`](ApiChannelAttachment.md)[] | Attachments on this page. |\n| <a id=\"property-next_cursor\"></a> `next_cursor?` | `string` \\| `null` | Cursor for the next page, null if no more pages. |\n\n\n<!-- generated/storage/types.gen/type-aliases/ApiChannelDetail.md -->\n# Type Alias: ApiChannelDetail\n\n> **ApiChannelDetail** = \\{ `channel_id`: `string`; `channel_name`: `string`; `channel_type`: [`ChannelType`](ChannelType.md); `participants`: [`ApiChannelParticipant`](ApiChannelParticipant.md)[]; \\}\n\nChannel detail: metadata and active participants.\n\nMessages are read through `/messages/channel/{channel_id}`.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-channel_id\"></a> `channel_id` | `string` | Channel id. |\n| <a id=\"property-channel_name\"></a> `channel_name` | `string` | Resolved display name from the viewer's perspective. |\n| <a id=\"property-channel_type\"></a> `channel_type` | [`ChannelType`](ChannelType.md) | Channel type. |\n| <a id=\"property-participants\"></a> `participants` | [`ApiChannelParticipant`](ApiChannelParticipant.md)[] | Active participants. |\n\n\n<!-- generated/storage/types.gen/type-aliases/ApiChannelParticipant.md -->\n# Type Alias: ApiChannelParticipant\n\n> **ApiChannelParticipant** = \\{ `channel_id`: `string`; `joined_at`: `string`; `role`: [`ApiParticipantRole`](ApiParticipantRole.md); `user_id`: `string`; \\}\n\nA channel participant.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-channel_id\"></a> `channel_id` | `string` | Channel id. |\n| <a id=\"property-joined_at\"></a> `joined_at` | `string` | When the user joined. |\n| <a id=\"property-role\"></a> `role` | [`ApiParticipantRole`](ApiParticipantRole.md) | Role in the channel. |\n| <a id=\"property-user_id\"></a> `user_id` | `string` | User id. |\n\n\n<!-- generated/storage/types.gen/type-aliases/ApiParticipantRole.md -->\n# Type Alias: ApiParticipantRole\n\n> **ApiParticipantRole** = `\"owner\"` \\| `\"admin\"` \\| `\"member\"`\n\nParticipant role in a channel.\n\n\n<!-- generated/storage/types.gen/type-aliases/BotSenderProfile.md -->\n# Type Alias: BotSenderProfile\n\n> **BotSenderProfile** = \\{ `avatar_url?`: `string` \\| `null`; `name`: `string`; \\}\n\nPublic bot profile attached to bot-authored messages.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-avatar_url\"></a> `avatar_url?` | `string` \\| `null` | Bot avatar URL. |\n| <a id=\"property-name\"></a> `name` | `string` | Bot display name. |\n\n\n<!-- generated/storage/types.gen/type-aliases/ChannelLabel.md -->\n# Type Alias: ChannelLabel\n\n> **ChannelLabel** = \\{ `channelCount`: `number`; `channelIds`: `string`[]; `createdAt`: `string`; `id`: `string`; `name`: `string`; `rule?`: `null` \\| [`ChannelLabelRule`](ChannelLabelRule.md); `sortOrder`: `number`; `teamId?`: `string` \\| `null`; `updatedAt`: `string`; \\}\n\nA shared or account-private label grouping chat channels in the sidebar.\n\n`channel_ids` is viewer-relative: it lists only the labelled channels the\nrequesting user participates in. `channel_count` counts every channel in\nthe label so clients can warn accurately before a delete.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-channelcount\"></a> `channelCount` | `number` | All assignments for a manual label; visible matches for a smart tag. |\n| <a id=\"property-channelids\"></a> `channelIds` | `string`[] | Channels in this label that the requesting user participates in. |\n| <a id=\"property-createdat\"></a> `createdAt` | `string` | When the label was created. |\n| <a id=\"property-id\"></a> `id` | `string` | Stable label id. |\n| <a id=\"property-name\"></a> `name` | `string` | Display name, unique within the scope (case-insensitive). |\n| <a id=\"property-rule\"></a> `rule?` | `null` \\| [`ChannelLabelRule`](ChannelLabelRule.md) | - |\n| <a id=\"property-sortorder\"></a> `sortOrder` | `number` | Manual ordering value within the scope; lower sorts first. |\n| <a id=\"property-teamid\"></a> `teamId?` | `string` \\| `null` | Owning team, or `None` for account-private labels. |\n| <a id=\"property-updatedat\"></a> `updatedAt` | `string` | When the label was last renamed or reordered. |\n\n\n<!-- generated/storage/types.gen/type-aliases/ChannelLabelRule.md -->\n# Type Alias: ChannelLabelRule\n\n> **ChannelLabelRule** = \\{ `attribute`: `\"name\"`; `contains`: `string`; \\}\n\nCase-insensitive, literal substring matching on the channel name.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-attribute\"></a> `attribute` | `\"name\"` | - |\n| <a id=\"property-contains\"></a> `contains` | `string` | The substring to find anywhere in the name. |\n\n\n<!-- generated/storage/types.gen/type-aliases/ChannelSharePermission.md -->\n# Type Alias: ChannelSharePermission\n\n> **ChannelSharePermission** = \\{ `access_level`: [`AccessLevel`](AccessLevel.md); `channel_id`: `string`; \\}\n\nThe channel share permission\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-access_level\"></a> `access_level` | [`AccessLevel`](AccessLevel.md) | The access level for the channel |\n| <a id=\"property-channel_id\"></a> `channel_id` | `string` | The channel id |\n\n\n<!-- generated/storage/types.gen/type-aliases/ChannelType.md -->\n# Type Alias: ChannelType\n\n> **ChannelType** = `\"public\"` \\| `\"private\"` \\| `\"direct_message\"` \\| `\"team\"`\n\nType of channel.\n\n\n<!-- generated/storage/types.gen/type-aliases/CountedReaction.md -->\n# Type Alias: CountedReaction\n\n> **CountedReaction** = \\{ `emoji`: `string`; `users`: `string`[]; \\}\n\nReaction emoji and the users who added it.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-emoji\"></a> `emoji` | `string` | Emoji being reacted with. |\n| <a id=\"property-users\"></a> `users` | `string`[] | User identifiers. |\n\n\n<!-- generated/storage/types.gen/type-aliases/DocumentId.md -->\n# Type Alias: DocumentId\n\n> **DocumentId** = `string`\n\nA validated document identifier. Historical document ids need not be UUIDs.\n\n\n<!-- generated/storage/types.gen/type-aliases/EntityPermission.md -->\n# Type Alias: EntityPermission\n\n> **EntityPermission** = \\{ `access_level`: [`AccessLevel`](AccessLevel.md); `type`: `\"access_level\"`; \\} \\| \\{ `type`: `\"channel_view_only\"`; \\} \\| \\{ `role`: [`ParticipantRole`](ParticipantRole.md); `type`: `\"channel_role\"`; \\} \\| \\{ `role`: [`TeamRole`](TeamRole.md); `type`: `\"team_role\"`; \\}\n\nA user's permission for an entity, discriminated by entity kind.\n\nItems (documents, chats, projects, threads) use access levels.\nChannels use view-only permission or participant roles.\n\n## Union Members\n\n### Type Literal\n\n\\{ `access_level`: [`AccessLevel`](AccessLevel.md); `type`: `\"access_level\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `access_level` | [`AccessLevel`](AccessLevel.md) | The access level the user has. |\n| `type` | `\"access_level\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `type`: `\"channel_view_only\"`; \\}\n\n***\n\n### Type Literal\n\n\\{ `role`: [`ParticipantRole`](ParticipantRole.md); `type`: `\"channel_role\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `role` | [`ParticipantRole`](ParticipantRole.md) | The role the user has in the channel. |\n| `type` | `\"channel_role\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `role`: [`TeamRole`](TeamRole.md); `type`: `\"team_role\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `role` | [`TeamRole`](TeamRole.md) | The role the user has in the team. |\n| `type` | `\"team_role\"` | - |\n\n\n<!-- generated/storage/types.gen/type-aliases/GetChannelAttachmentsResponses.md -->\n# Type Alias: GetChannelAttachmentsResponses\n\n> **GetChannelAttachmentsResponses** = \\{ `200`: [`ApiChannelAttachmentsPage`](ApiChannelAttachmentsPage.md); \\}\n\n## Properties\n\n| Property | Type |\n| ------ | ------ |\n| <a id=\"property-200\"></a> `200` | [`ApiChannelAttachmentsPage`](ApiChannelAttachmentsPage.md) |\n\n\n<!-- generated/storage/types.gen/type-aliases/GetChannelParticipantsResponses.md -->\n# Type Alias: GetChannelParticipantsResponses\n\n> **GetChannelParticipantsResponses** = \\{ `200`: [`ApiChannelParticipant`](ApiChannelParticipant.md)[]; \\}\n\n## Properties\n\n| Property | Type |\n| ------ | ------ |\n| <a id=\"property-200\"></a> `200` | [`ApiChannelParticipant`](ApiChannelParticipant.md)[] |\n\n\n<!-- generated/storage/types.gen/type-aliases/ImportedAuthor.md -->\n# Type Alias: ImportedAuthor\n\n> **ImportedAuthor** = \\{ `name`: `string`; \\}\n\nDisplay attribution for a comment imported from an external document.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-name\"></a> `name` | `string` | Original author text; never interpreted as an authenticated principal. |\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkShare.md -->\n# Type Alias: LinkShare\n\n> **LinkShare** = `\"PUBLIC\"` \\| `\"TEAM\"`\n\nDefines who can access an item through its share link.\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedAccount.md -->\n# Type Alias: LinkedAccount\n\n> **LinkedAccount** = \\{ `authorization_generation`: `number`; `id`: `string`; `identity_jid?`: `string` \\| `null`; `state`: [`LinkedAccountState`](LinkedAccountState.md); `user_id`: `string`; \\}\n\nOne person's account, never owned by a workspace.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-authorization_generation\"></a> `authorization_generation` | `number` | Explicit consent generation; reconnecting a socket never changes it. |\n| <a id=\"property-id\"></a> `id` | `string` | Stable account identity. |\n| <a id=\"property-identity_jid\"></a> `identity_jid?` | `string` \\| `null` | WhatsApp-verified identity, absent until the first pairing succeeds. |\n| <a id=\"property-state\"></a> `state` | [`LinkedAccountState`](LinkedAccountState.md) | Lifecycle. |\n| <a id=\"property-user_id\"></a> `user_id` | `string` | Authenticated owner. |\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedAccountState.md -->\n# Type Alias: LinkedAccountState\n\n> **LinkedAccountState** = `\"pairing\"` \\| `\"connected\"` \\| `\"logged_out\"` \\| `\"disconnected\"`\n\nAccount lifecycle. Transport outages are not stored: a connected account\nstays connected while its session service reconnects.\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedAttachment.md -->\n# Type Alias: LinkedAttachment\n\n> **LinkedAttachment** = \\{ `document_id?`: `string` \\| `null`; `duration_seconds?`: `number` \\| `null`; `file_name`: `string`; `height?`: `number` \\| `null`; `mime`: `string`; `ordinal`: `number`; `presentation?`: `null` \\| [`LinkedMediaPresentation`](LinkedMediaPresentation.md); `size`: `number`; `state`: [`LinkedAttachmentState`](LinkedAttachmentState.md); `width?`: `number` \\| `null`; \\}\n\nOne attachment of a linked message.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-document_id\"></a> `document_id?` | `string` \\| `null` | The private document, once ready. |\n| <a id=\"property-duration_seconds\"></a> `duration_seconds?` | `number` \\| `null` | Length of audio or video in whole seconds, when declared. |\n| <a id=\"property-file_name\"></a> `file_name` | `string` | Display filename. |\n| <a id=\"property-height\"></a> `height?` | `number` \\| `null` | Pixel height, when declared. |\n| <a id=\"property-mime\"></a> `mime` | `string` | Declared MIME type. |\n| <a id=\"property-ordinal\"></a> `ordinal` | `number` | Position within the message. |\n| <a id=\"property-presentation\"></a> `presentation?` | `null` \\| [`LinkedMediaPresentation`](LinkedMediaPresentation.md) | - |\n| <a id=\"property-size\"></a> `size` | `number` | Declared size in bytes. |\n| <a id=\"property-state\"></a> `state` | [`LinkedAttachmentState`](LinkedAttachmentState.md) | Current state. |\n| <a id=\"property-width\"></a> `width?` | `number` \\| `null` | Pixel width of an image, sticker or video, when WhatsApp declared it. |\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedAttachmentState.md -->\n# Type Alias: LinkedAttachmentState\n\n> **LinkedAttachmentState** = `\"loading\"` \\| `\"ready\"` \\| `\"unavailable\"` \\| `\"unsupported\"`\n\nWhere an attachment of a linked message stands.\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedBackfill.md -->\n# Type Alias: LinkedBackfill\n\n> **LinkedBackfill** = \\{ `imported`: `number`; `state`: [`LinkedBackfillState`](LinkedBackfillState.md); \\}\n\nEarlier messages imported after adding a group.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-imported\"></a> `imported` | `number` | Messages received from the phone so far (including ones already shown). |\n| <a id=\"property-state\"></a> `state` | [`LinkedBackfillState`](LinkedBackfillState.md) | Progress. |\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedBackfillState.md -->\n# Type Alias: LinkedBackfillState\n\n> **LinkedBackfillState** = `\"pending\"` \\| `\"running\"` \\| `\"waiting_for_phone\"` \\| `\"done\"` \\| `\"partial\"`\n\nWhere importing a group's earlier messages stands.\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedCapabilities.md -->\n# Type Alias: LinkedCapabilities\n\n> **LinkedCapabilities** = \\{ `attachment_limit_bytes`: `number`; `attachment_types`: `string`[]; `max_attachments`: `number`; `mutation_window_seconds`: `number`; `mutations`: [`LinkedMutation`](LinkedMutation.md)[]; `text_limit_bytes`: `number`; \\}\n\nOperations implemented for linked groups, independent of current permission.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-attachment_limit_bytes\"></a> `attachment_limit_bytes` | `number` | Largest attachment in bytes. |\n| <a id=\"property-attachment_types\"></a> `attachment_types` | `string`[] | Supported attachment MIME types. |\n| <a id=\"property-max_attachments\"></a> `max_attachments` | `number` | Attachments per send. |\n| <a id=\"property-mutation_window_seconds\"></a> `mutation_window_seconds` | `number` | Edits and deletes are offered this long after sending. |\n| <a id=\"property-mutations\"></a> `mutations` | [`LinkedMutation`](LinkedMutation.md)[] | Supported message operations. |\n| <a id=\"property-text_limit_bytes\"></a> `text_limit_bytes` | `number` | Maximum UTF-8 bytes per text send. |\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedChat.md -->\n# Type Alias: LinkedChat\n\n> **LinkedChat** = \\{ `archived`: `boolean`; `canAdd`: `boolean`; `cannotAddReason?`: `string` \\| `null`; `group?`: `null` \\| [`LinkedGroupReference`](LinkedGroupReference.md); `jid`: `string`; `kind`: [`LinkedChatKind`](LinkedChatKind.md); `lastActivityAt?`: `string` \\| `null`; `name`: `string`; `pinned`: `boolean`; `shared?`: `null` \\| [`LinkedSharedGroupReference`](LinkedSharedGroupReference.md); \\}\n\nOne chat of the caller's WhatsApp chat list, as WhatsApp Web lists it.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-archived\"></a> `archived` | `boolean` | Archived in WhatsApp. |\n| <a id=\"property-canadd\"></a> `canAdd` | `boolean` | \"Add to Macro\" works now. |\n| <a id=\"property-cannotaddreason\"></a> `cannotAddReason?` | `string` \\| `null` | Why it can't be added, when it is neither added, shared nor addable. |\n| <a id=\"property-group\"></a> `group?` | `null` \\| [`LinkedGroupReference`](LinkedGroupReference.md) | - |\n| <a id=\"property-jid\"></a> `jid` | `string` | WhatsApp chat JID: a group, or the other person's phone-number JID (LID when WhatsApp never told us the number). |\n| <a id=\"property-kind\"></a> `kind` | [`LinkedChatKind`](LinkedChatKind.md) | Group or direct chat. |\n| <a id=\"property-lastactivityat\"></a> `lastActivityAt?` | `string` \\| `null` | Newest activity WhatsApp reported (message or history sync); `null` when unknown. The list is sorted by it, newest first, unknown last. |\n| <a id=\"property-name\"></a> `name` | `string` | Group: the subject, or member names for an unnamed group. Direct: the contact or WhatsApp name, else `+<phone>`. Always non-empty. |\n| <a id=\"property-pinned\"></a> `pinned` | `boolean` | Pinned in WhatsApp. |\n| <a id=\"property-shared\"></a> `shared?` | `null` \\| [`LinkedSharedGroupReference`](LinkedSharedGroupReference.md) | - |\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedChatKind.md -->\n# Type Alias: LinkedChatKind\n\n> **LinkedChatKind** = `\"group\"` \\| `\"direct\"`\n\nWhether a WhatsApp chat is a group or a one-to-one chat.\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedDeliveryState.md -->\n# Type Alias: LinkedDeliveryState\n\n> **LinkedDeliveryState** = `\"pending\"` \\| `\"sending\"` \\| `\"unknown\"` \\| `\"accepted\"` \\| `\"sent\"` \\| `\"delivered\"` \\| `\"read\"` \\| `\"failed\"`\n\nObserved send state. `unknown` means the request may have reached WhatsApp;\nit is never sent again automatically.\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedGroupInfo.md -->\n# Type Alias: LinkedGroupInfo\n\n> **LinkedGroupInfo** = \\{ `announce`: `boolean`; `community`: `boolean`; `disappearing`: `boolean`; `group?`: `null` \\| [`LinkedGroupReference`](LinkedGroupReference.md); `jid`: `string`; `name`: `string`; `observedAt`: `string`; `participants`: [`LinkedParticipant`](LinkedParticipant.md)[]; `shared?`: `null` \\| [`LinkedSharedGroupReference`](LinkedSharedGroupReference.md); \\}\n\nOne full metadata read of a group, never an incomplete membership delta.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-announce\"></a> `announce` | `boolean` | Only admins may post. |\n| <a id=\"property-community\"></a> `community` | `boolean` | Community announcement or parent group, outside the supported surface. |\n| <a id=\"property-disappearing\"></a> `disappearing` | `boolean` | Disappearing messages are on; content is not retained. |\n| <a id=\"property-group\"></a> `group?` | `null` \\| [`LinkedGroupReference`](LinkedGroupReference.md) | - |\n| <a id=\"property-jid\"></a> `jid` | `string` | Remote group JID. |\n| <a id=\"property-name\"></a> `name` | `string` | Current subject. |\n| <a id=\"property-observedat\"></a> `observedAt` | `string` | When the session service read this metadata. |\n| <a id=\"property-participants\"></a> `participants` | [`LinkedParticipant`](LinkedParticipant.md)[] | Full roster. |\n| <a id=\"property-shared\"></a> `shared?` | `null` \\| [`LinkedSharedGroupReference`](LinkedSharedGroupReference.md) | - |\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedGroupReference.md -->\n# Type Alias: LinkedGroupReference\n\n> **LinkedGroupReference** = \\{ `id`: `string`; `name`: `string`; \\}\n\nA group entity bound to a remote group.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-id\"></a> `id` | `string` | Group entity id. |\n| <a id=\"property-name\"></a> `name` | `string` | Display name, following WhatsApp. |\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedIdentity.md -->\n# Type Alias: LinkedIdentity\n\n> **LinkedIdentity** = \\{ `alternateJid?`: `string` \\| `null`; `displayName?`: `string` \\| `null`; `jid`: `string`; \\}\n\nVerified sender aliases, supplied only by protocol metadata.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-alternatejid\"></a> `alternateJid?` | `string` \\| `null` | Verified alternate identity, never inferred from a name or phone typed by a user. |\n| <a id=\"property-displayname\"></a> `displayName?` | `string` \\| `null` | Untrusted display name. |\n| <a id=\"property-jid\"></a> `jid` | `string` | Phone-number or LID account JID. |\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedMediaKind.md -->\n# Type Alias: LinkedMediaKind\n\n> **LinkedMediaKind** = `\"image\"` \\| `\"audio\"` \\| `\"video\"` \\| `\"document\"`\n\nAttachment categories WhatsApp distinguishes.\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedMediaPresentation.md -->\n# Type Alias: LinkedMediaPresentation\n\n> **LinkedMediaPresentation** = `\"sticker\"` \\| `\"gif\"` \\| `\"voice_note\"`\n\nHow WhatsApp shows an attachment, when not as a plain file of its kind.\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedMutation.md -->\n# Type Alias: LinkedMutation\n\n> **LinkedMutation** = `\"reaction\"` \\| `\"edit\"` \\| `\"delete\"`\n\nDeliberate operations on an existing linked-group message.\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedParticipant.md -->\n# Type Alias: LinkedParticipant\n\n> **LinkedParticipant** = [`LinkedIdentity`](LinkedIdentity.md) & \\{ `admin`: `boolean`; \\}\n\nCurrent remote participant; Macro access is a separate grant.\n\n## Type Declaration\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `admin` | `boolean` | Group admin; only admins post in announcement groups. |\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedReplyBlock.md -->\n# Type Alias: LinkedReplyBlock\n\n> **LinkedReplyBlock** = `\"sending_disabled\"` \\| `\"no_account\"` \\| `\"disconnected\"` \\| `\"not_observing\"` \\| `\"not_allowed_in_group\"` \\| `\"group_unavailable\"`\n\nWhy the viewer cannot send now.\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedReplyContent.md -->\n# Type Alias: LinkedReplyContent\n\n> **LinkedReplyContent** = \\{ `mentions?`: `string`[]; `text`: `string`; `type`: `\"text\"`; \\} \\| \\{ `caption?`: `string` \\| `null`; `type`: `\"media\"`; `upload_id`: `string`; \\} \\| \\{ `message_id`: `string`; `operation`: [`LinkedMutation`](LinkedMutation.md); `text?`: `string` \\| `null`; `type`: `\"mutation\"`; \\}\n\nContent of a deliberate send.\n\n## Union Members\n\n### Type Literal\n\n\\{ `mentions?`: `string`[]; `text`: `string`; `type`: `\"text\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `mentions?` | `string`[] | Group participants the text @-mentions, by their WhatsApp id (`jid` of a roster participant); the text must contain `@<digits before the @ of the id>` for each. |\n| `text` | `string` | UTF-8 text, at most [`TEXT_LIMIT_BYTES`] bytes. |\n| `type` | `\"text\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `caption?`: `string` \\| `null`; `type`: `\"media\"`; `upload_id`: `string`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `caption?` | `string` \\| `null` | Optional caption; audio has none. |\n| `type` | `\"media\"` | - |\n| `upload_id` | `string` | The staged upload, which becomes the message's private document. |\n\n***\n\n### Type Literal\n\n\\{ `message_id`: `string`; `operation`: [`LinkedMutation`](LinkedMutation.md); `text?`: `string` \\| `null`; `type`: `\"mutation\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `message_id` | `string` | Existing group message, resolved to its WhatsApp source by the server. |\n| `operation` | [`LinkedMutation`](LinkedMutation.md) | Explicit operation. |\n| `text?` | `string` \\| `null` | Replacement text or emoji; absent for delete, empty to remove a reaction. |\n| `type` | `\"mutation\"` | - |\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedSendProgress.md -->\n# Type Alias: LinkedSendProgress\n\n> **LinkedSendProgress** = \\{ `created_at`: `string`; `error_code?`: `string` \\| `null`; `group_id`: `string`; `id`: `string`; `message_id?`: `string` \\| `null`; `payload`: [`LinkedSendReply`](LinkedSendReply.md); `state`: [`LinkedDeliveryState`](LinkedDeliveryState.md); `user_id`: `string`; \\}\n\nDurable result of a deliberate send.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-created_at\"></a> `created_at` | `string` | Intent creation time. |\n| <a id=\"property-error_code\"></a> `error_code?` | `string` \\| `null` | Sanitized failure code. |\n| <a id=\"property-group_id\"></a> `group_id` | `string` | Group entity. |\n| <a id=\"property-id\"></a> `id` | `string` | Stable intent id. |\n| <a id=\"property-message_id\"></a> `message_id?` | `string` \\| `null` | Group message, once WhatsApp accepted it. |\n| <a id=\"property-payload\"></a> `payload` | [`LinkedSendReply`](LinkedSendReply.md) | The original request, so a failed draft can be recovered. |\n| <a id=\"property-state\"></a> `state` | [`LinkedDeliveryState`](LinkedDeliveryState.md) | Current state. |\n| <a id=\"property-user_id\"></a> `user_id` | `string` | Person who submitted it. |\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedSendReply.md -->\n# Type Alias: LinkedSendReply\n\n> **LinkedSendReply** = \\{ `idempotency_key`: `string`; `message`: [`LinkedReplyContent`](LinkedReplyContent.md); `reply_to?`: `string` \\| `null`; \\}\n\nExplicit send action from a person. Only deliberate sends reach WhatsApp.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-idempotency_key\"></a> `idempotency_key` | `string` | Stable client intent key. A changed payload with this key is a conflict. |\n| <a id=\"property-message\"></a> `message` | [`LinkedReplyContent`](LinkedReplyContent.md) | Content. |\n| <a id=\"property-reply_to\"></a> `reply_to?` | `string` \\| `null` | Group message being quoted, within this group. |\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedSharedGroupReference.md -->\n# Type Alias: LinkedSharedGroupReference\n\n> **LinkedSharedGroupReference** = \\{ `id`: `string`; `name`: `string`; `owner_id`: `string`; \\}\n\nAnother person's group entity the caller can view.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-id\"></a> `id` | `string` | Group entity id. |\n| <a id=\"property-name\"></a> `name` | `string` | Display name, following WhatsApp. |\n| <a id=\"property-owner_id\"></a> `owner_id` | `string` | Macro user who added the group and shared it. |\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedUploadedAttachment.md -->\n# Type Alias: LinkedUploadedAttachment\n\n> **LinkedUploadedAttachment** = \\{ `filename`: `string`; `kind`: [`LinkedMediaKind`](LinkedMediaKind.md); `upload_id`: `string`; \\}\n\nA staged attachment, sent only by a later deliberate send.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-filename\"></a> `filename` | `string` | Display filename. |\n| <a id=\"property-kind\"></a> `kind` | [`LinkedMediaKind`](LinkedMediaKind.md) | Category. |\n| <a id=\"property-upload_id\"></a> `upload_id` | `string` | Use as `upload_id` in a media send; also the future document id. |\n\n\n<!-- generated/storage/types.gen/type-aliases/Message.md -->\n# Type Alias: Message\n\n> **Message** = \\{ `attachments`: [`MessageAttachment`](MessageAttachment.md)[]; `bot_profile?`: `null` \\| [`BotSenderProfile`](BotSenderProfile.md); `content`: `string`; `created_at`: `string`; `deleted_at?`: `string` \\| `null`; `edited_at?`: `string` \\| `null`; `guest_name?`: `string` \\| `null`; `id`: `string`; `imported_author?`: `null` \\| [`ImportedAuthor`](ImportedAuthor.md); `mentions`: [`SimpleMention`](SimpleMention.md)[]; `parent`: [`MessageParent`](MessageParent.md); `reactions`: [`CountedReaction`](CountedReaction.md)[]; `sender_id`: `string`; `thread_id?`: `string` \\| `null`; `triggered_by?`: `string` \\| `null`; `updated_at`: `string`; \\}\n\nShared message representation for channel timelines and entity discussions.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-attachments\"></a> `attachments` | [`MessageAttachment`](MessageAttachment.md)[] | Attached entities. |\n| <a id=\"property-bot_profile\"></a> `bot_profile?` | `null` \\| [`BotSenderProfile`](BotSenderProfile.md) | - |\n| <a id=\"property-content\"></a> `content` | `string` | Macro Markdown body. |\n| <a id=\"property-created_at\"></a> `created_at` | `string` | Creation time. |\n| <a id=\"property-deleted_at\"></a> `deleted_at?` | `string` \\| `null` | Message tombstone, independent of thread deletion. |\n| <a id=\"property-edited_at\"></a> `edited_at?` | `string` \\| `null` | Last content edit, if any. |\n| <a id=\"property-guest_name\"></a> `guest_name?` | `string` \\| `null` | Display name of a verified call guest, retained after the call ends. |\n| <a id=\"property-id\"></a> `id` | `string` | Message UUID. |\n| <a id=\"property-imported_author\"></a> `imported_author?` | `null` \\| [`ImportedAuthor`](ImportedAuthor.md) | - |\n| <a id=\"property-mentions\"></a> `mentions` | [`SimpleMention`](SimpleMention.md)[] | Tracked mentions, retained when a caller changes attachments only. |\n| <a id=\"property-parent\"></a> `parent` | [`MessageParent`](MessageParent.md) | Entity that owns this conversation. |\n| <a id=\"property-reactions\"></a> `reactions` | [`CountedReaction`](CountedReaction.md)[] | Aggregated reactions. |\n| <a id=\"property-sender_id\"></a> `sender_id` | `string` | Authenticated actor or owner of imported content. |\n| <a id=\"property-thread_id\"></a> `thread_id?` | `string` \\| `null` | Root message UUID for replies; absent on roots. |\n| <a id=\"property-triggered_by\"></a> `triggered_by?` | `string` \\| `null` | User who triggered a bot-authored message. |\n| <a id=\"property-updated_at\"></a> `updated_at` | `string` | Last persisted update. |\n\n\n<!-- generated/storage/types.gen/type-aliases/MessageAttachment.md -->\n# Type Alias: MessageAttachment\n\n> **MessageAttachment** = \\{ `created_at`: `string`; `entity_id`: `string`; `entity_type`: `string`; `height?`: `number` \\| `null`; `id`: `string`; `width?`: `number` \\| `null`; \\}\n\nAn entity attached to a message.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-created_at\"></a> `created_at` | `string` | When the attachment was added. |\n| <a id=\"property-entity_id\"></a> `entity_id` | `string` | Attached entity identifier. |\n| <a id=\"property-entity_type\"></a> `entity_type` | `string` | Attached entity type. |\n| <a id=\"property-height\"></a> `height?` | `number` \\| `null` | Optional media height. |\n| <a id=\"property-id\"></a> `id` | `string` | Attachment UUID. |\n| <a id=\"property-width\"></a> `width?` | `number` \\| `null` | Optional media width. |\n\n\n<!-- generated/storage/types.gen/type-aliases/MessageCursor.md -->\n# Type Alias: MessageCursor\n\n> **MessageCursor** = \\{ `created_at`: `string`; `id`: `string`; \\}\n\nCursor for a chronological parent timeline.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-created_at\"></a> `created_at` | `string` | Last message creation time or activity occurrence time. |\n| <a id=\"property-id\"></a> `id` | `string` | Last entry UUID, used to break timestamp ties across both sources. |\n\n\n<!-- generated/storage/types.gen/type-aliases/MessageParent.md -->\n# Type Alias: MessageParent\n\n> **MessageParent** = \\{ `id`: `string`; `type`: `\"channel\"`; \\} \\| \\{ `id`: [`DocumentId`](DocumentId.md); `type`: `\"document\"`; \\} \\| \\{ `id`: `string`; `type`: `\"initiative\"`; \\} \\| \\{ `id`: `string`; `type`: `\"crm_company\"`; \\} \\| \\{ `id`: `string`; `type`: `\"crm_contact\"`; \\} \\| \\{ `id`: `string`; `type`: `\"call\"`; \\}\n\nThe entity whose permissions and lifecycle govern a message.\n\n## Union Members\n\n### Type Literal\n\n\\{ `id`: `string`; `type`: `\"channel\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `id` | `string` | A channel, including direct messages. |\n| `type` | `\"channel\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `id`: [`DocumentId`](DocumentId.md); `type`: `\"document\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `id` | [`DocumentId`](DocumentId.md) | A document, including tasks and PDFs. |\n| `type` | `\"document\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `id`: `string`; `type`: `\"initiative\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `id` | `string` | An initiative, presented as a project in the application. |\n| `type` | `\"initiative\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `id`: `string`; `type`: `\"crm_company\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `id` | `string` | A CRM company. |\n| `type` | `\"crm_company\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `id`: `string`; `type`: `\"crm_contact\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `id` | `string` | A CRM contact. |\n| `type` | `\"crm_contact\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `id`: `string`; `type`: `\"call\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `id` | `string` | A video call and its persistent chat thread. |\n| `type` | `\"call\"` | - |\n\n\n<!-- generated/storage/types.gen/type-aliases/ParticipantRole.md -->\n# Type Alias: ParticipantRole\n\n> **ParticipantRole** = `\"owner\"` \\| `\"admin\"` \\| `\"member\"`\n\nThe role a user has within a channel.\n\n\n<!-- generated/storage/types.gen/type-aliases/SharePermissionV2.md -->\n# Type Alias: SharePermissionV2\n\n> **SharePermissionV2** = \\{ `channelSharePermissions?`: [`ChannelSharePermission`](ChannelSharePermission.md)[] \\| `null`; `id`: `string`; `linkShare?`: `null` \\| [`LinkShare`](LinkShare.md); `linkShareAccessLevel?`: `null` \\| [`AccessLevel`](AccessLevel.md); `owner`: `string`; `teamShareAccessLevel?`: `null` \\| [`AccessLevel`](AccessLevel.md); \\}\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-channelsharepermissions\"></a> `channelSharePermissions?` | [`ChannelSharePermission`](ChannelSharePermission.md)[] \\| `null` | The channel share permissions for the item |\n| <a id=\"property-id\"></a> `id` | `string` | The share permission id |\n| <a id=\"property-linkshare\"></a> `linkShare?` | `null` \\| [`LinkShare`](LinkShare.md) | - |\n| <a id=\"property-linkshareaccesslevel\"></a> `linkShareAccessLevel?` | `null` \\| [`AccessLevel`](AccessLevel.md) | - |\n| <a id=\"property-owner\"></a> `owner` | `string` | The owner of the item |\n| <a id=\"property-teamshareaccesslevel\"></a> `teamShareAccessLevel?` | `null` \\| [`AccessLevel`](AccessLevel.md) | - |\n\n\n<!-- generated/storage/types.gen/type-aliases/SimpleMention.md -->\n# Type Alias: SimpleMention\n\n> **SimpleMention** = \\{ `entity_id`: `string`; `entity_type`: `string`; \\}\n\nA mention tracked in a message body.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-entity_id\"></a> `entity_id` | `string` | Mentioned entity identifier. |\n| <a id=\"property-entity_type\"></a> `entity_type` | `string` | Mentioned entity type. |\n\n\n<!-- generated/storage/types.gen/type-aliases/SmartTagChannelMatch.md -->\n# Type Alias: SmartTagChannelMatch\n\n> **SmartTagChannelMatch** = \\{ `id`: `string`; `name`: `string`; \\}\n\nA channel visible to the caller that matches a smart tag rule.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-id\"></a> `id` | `string` | Channel id. |\n| <a id=\"property-name\"></a> `name` | `string` | Channel display name. |\n\n\n<!-- generated/storage/types.gen/type-aliases/SmartTagPreview.md -->\n# Type Alias: SmartTagPreview\n\n> **SmartTagPreview** = \\{ `channels`: [`SmartTagChannelMatch`](SmartTagChannelMatch.md)[]; `totalCount`: `number`; \\}\n\nA bounded preview and the total number of visible channels matching a rule.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-channels\"></a> `channels` | [`SmartTagChannelMatch`](SmartTagChannelMatch.md)[] | First matches, in alphabetical order. |\n| <a id=\"property-totalcount\"></a> `totalCount` | `number` | Number of matching channels the caller participates in, including overflow. |\n\n\n<!-- generated/storage/types.gen/type-aliases/TeamRole.md -->\n# Type Alias: TeamRole\n\n> **TeamRole** = `\"member\"` \\| `\"admin\"` \\| `\"owner\"`\n\nThe role a user has within a team.\n\nOrdered least to most privileged so comparisons reflect access strength.\n\n\n<!-- generated/storage/types.gen/type-aliases/UpdateChannelSharePermission.md -->\n# Type Alias: UpdateChannelSharePermission\n\n> **UpdateChannelSharePermission** = \\{ `accessLevel?`: `null` \\| [`AccessLevel`](AccessLevel.md); `channelId`: `string`; `operation`: [`UpdateOperation`](UpdateOperation.md); \\}\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-accesslevel\"></a> `accessLevel?` | `null` \\| [`AccessLevel`](AccessLevel.md) | - |\n| <a id=\"property-channelid\"></a> `channelId` | `string` | The channel id |\n| <a id=\"property-operation\"></a> `operation` | [`UpdateOperation`](UpdateOperation.md) | The type of operation to be performed on the chanel share permission You can add, remove or replace and existing permission |\n\n\n<!-- generated/storage/types.gen/type-aliases/UpdateOperation.md -->\n# Type Alias: UpdateOperation\n\n> **UpdateOperation** = `\"add\"` \\| `\"remove\"` \\| `\"replace\"`\n\n\n<!-- generated/storage/types.gen/type-aliases/UpdateSharePermissionRequestV2.md -->\n# Type Alias: UpdateSharePermissionRequestV2\n\n> **UpdateSharePermissionRequestV2** = \\{ `channelSharePermissions?`: [`UpdateChannelSharePermission`](UpdateChannelSharePermission.md)[] \\| `null`; `linkShare?`: `null` \\| [`LinkShare`](LinkShare.md); `linkShareAccessLevel?`: `null` \\| [`AccessLevel`](AccessLevel.md); `teamShareAccessLevel?`: `null` \\| [`AccessLevel`](AccessLevel.md); \\}\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-channelsharepermissions\"></a> `channelSharePermissions?` | [`UpdateChannelSharePermission`](UpdateChannelSharePermission.md)[] \\| `null` | Any channel share permissions to be created/updated/removed |\n| <a id=\"property-linkshare\"></a> `linkShare?` | `null` \\| [`LinkShare`](LinkShare.md) | - |\n| <a id=\"property-linkshareaccesslevel\"></a> `linkShareAccessLevel?` | `null` \\| [`AccessLevel`](AccessLevel.md) | - |\n| <a id=\"property-teamshareaccesslevel\"></a> `teamShareAccessLevel?` | `null` \\| [`AccessLevel`](AccessLevel.md) | - |\n\n\n<!-- generated/storage/types.gen/type-aliases/WhatsAppCall.md -->\n# Type Alias: WhatsAppCall\n\n> **WhatsAppCall** = \\{ `durationSeconds?`: `number` \\| `null`; `outcome`: [`WhatsAppCallOutcome`](WhatsAppCallOutcome.md); `video`: `boolean`; \\}\n\nA call in the group.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-durationseconds\"></a> `durationSeconds?` | `number` \\| `null` | Length, when it connected. |\n| <a id=\"property-outcome\"></a> `outcome` | [`WhatsAppCallOutcome`](WhatsAppCallOutcome.md) | How it went for the account that saw it. |\n| <a id=\"property-video\"></a> `video` | `boolean` | Video rather than voice. |\n\n\n<!-- generated/storage/types.gen/type-aliases/WhatsAppCallOutcome.md -->\n# Type Alias: WhatsAppCallOutcome\n\n> **WhatsAppCallOutcome** = `\"answered\"` \\| `\"missed\"` \\| `\"rejected\"` \\| `\"other\"`\n\nHow a call went.\n\n\n<!-- generated/storage/types.gen/type-aliases/WhatsAppContactCard.md -->\n# Type Alias: WhatsAppContactCard\n\n> **WhatsAppContactCard** = \\{ `name`: `string`; `phones`: `string`[]; \\}\n\nOne contact card, from its vCard.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-name\"></a> `name` | `string` | Display name. |\n| <a id=\"property-phones\"></a> `phones` | `string`[] | Phone numbers as written on the card. |\n\n\n<!-- generated/storage/types.gen/type-aliases/WhatsAppContacts.md -->\n# Type Alias: WhatsAppContacts\n\n> **WhatsAppContacts** = \\{ `contacts`: [`WhatsAppContactCard`](WhatsAppContactCard.md)[]; \\}\n\nContact cards.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-contacts\"></a> `contacts` | [`WhatsAppContactCard`](WhatsAppContactCard.md)[] | The cards, in order. |\n\n\n<!-- generated/storage/types.gen/type-aliases/WhatsAppEvent.md -->\n# Type Alias: WhatsAppEvent\n\n> **WhatsAppEvent** = \\{ `canceled?`: `boolean`; `description?`: `string` \\| `null`; `endAt?`: `string` \\| `null`; `joinLink?`: `string` \\| `null`; `location?`: `string` \\| `null`; `name`: `string`; `startAt?`: `string` \\| `null`; \\}\n\nA WhatsApp event.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-canceled\"></a> `canceled?` | `boolean` | Canceled by its organizer. |\n| <a id=\"property-description\"></a> `description?` | `string` \\| `null` | Description. |\n| <a id=\"property-endat\"></a> `endAt?` | `string` \\| `null` | End. |\n| <a id=\"property-joinlink\"></a> `joinLink?` | `string` \\| `null` | Call link for an online event. |\n| <a id=\"property-location\"></a> `location?` | `string` \\| `null` | Place name or address. |\n| <a id=\"property-name\"></a> `name` | `string` | Title. |\n| <a id=\"property-startat\"></a> `startAt?` | `string` \\| `null` | Start. |\n\n\n<!-- generated/storage/types.gen/type-aliases/WhatsAppGroupDetail.md -->\n# Type Alias: WhatsAppGroupDetail\n\n> **WhatsAppGroupDetail** = [`WhatsAppGroupSummary`](WhatsAppGroupSummary.md) & \\{ `access_level`: [`AccessLevel`](AccessLevel.md); `limits`: [`LinkedCapabilities`](LinkedCapabilities.md); `roster?`: `null` \\| [`LinkedGroupInfo`](LinkedGroupInfo.md); `sending_identity?`: `string` \\| `null`; `share_permission`: [`SharePermissionV2`](SharePermissionV2.md); \\}\n\nFull group detail and current viewer capabilities.\n\n## Type Declaration\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `access_level` | [`AccessLevel`](AccessLevel.md) | Caller's effective permission. |\n| `limits` | [`LinkedCapabilities`](LinkedCapabilities.md) | Size and mutation limits. |\n| `roster?` | `null` \\| [`LinkedGroupInfo`](LinkedGroupInfo.md) | - |\n| `sending_identity?` | `string` \\| `null` | Caller's own phone identity, never another account's identity. |\n| `share_permission` | [`SharePermissionV2`](SharePermissionV2.md) | Owner-controlled standard sharing configuration. |\n\n\n<!-- generated/storage/types.gen/type-aliases/WhatsAppGroupMessage.md -->\n# Type Alias: WhatsAppGroupMessage\n\n> **WhatsAppGroupMessage** = \\{ `attachments`: [`LinkedAttachment`](LinkedAttachment.md)[]; `body`: `string`; `deleted`: `boolean`; `delivery_state?`: `null` \\| [`LinkedDeliveryState`](LinkedDeliveryState.md); `edited_at?`: `string` \\| `null`; `forwarded`: `boolean`; `id`: `string`; `kind`: [`WhatsAppMessageKind`](WhatsAppMessageKind.md); `mentions`: [`WhatsAppMention`](WhatsAppMention.md)[]; `reactions`: [`WhatsAppGroupReaction`](WhatsAppGroupReaction.md)[]; `received_at`: `string`; `reply_to?`: `string` \\| `null`; `rich?`: `null` \\| [`WhatsAppRichContent`](WhatsAppRichContent.md); `sender`: [`WhatsAppGroupSender`](WhatsAppGroupSender.md); `sent_at`: `string`; \\}\n\nOne message in an adopted group.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-attachments\"></a> `attachments` | [`LinkedAttachment`](LinkedAttachment.md)[] | Imported or pending attachments. |\n| <a id=\"property-body\"></a> `body` | `string` | Plain WhatsApp text. |\n| <a id=\"property-deleted\"></a> `deleted` | `boolean` | Deleted for everyone. |\n| <a id=\"property-delivery_state\"></a> `delivery_state?` | `null` \\| [`LinkedDeliveryState`](LinkedDeliveryState.md) | - |\n| <a id=\"property-edited_at\"></a> `edited_at?` | `string` \\| `null` | Last edit timestamp. |\n| <a id=\"property-forwarded\"></a> `forwarded` | `boolean` | Forwarded from another chat. |\n| <a id=\"property-id\"></a> `id` | `string` | Stable message id. |\n| <a id=\"property-kind\"></a> `kind` | [`WhatsAppMessageKind`](WhatsAppMessageKind.md) | A message, or a system line. |\n| <a id=\"property-mentions\"></a> `mentions` | [`WhatsAppMention`](WhatsAppMention.md)[] | People the body @-mentions. |\n| <a id=\"property-reactions\"></a> `reactions` | [`WhatsAppGroupReaction`](WhatsAppGroupReaction.md)[] | Reactions grouped by emoji. |\n| <a id=\"property-received_at\"></a> `received_at` | `string` | Timestamp first received by Macro. |\n| <a id=\"property-reply_to\"></a> `reply_to?` | `string` \\| `null` | Message quoted by this one. |\n| <a id=\"property-rich\"></a> `rich?` | `null` \\| [`WhatsAppRichContent`](WhatsAppRichContent.md) | - |\n| <a id=\"property-sender\"></a> `sender` | [`WhatsAppGroupSender`](WhatsAppGroupSender.md) | Sender. |\n| <a id=\"property-sent_at\"></a> `sent_at` | `string` | Timestamp assigned by WhatsApp. |\n\n\n<!-- generated/storage/types.gen/type-aliases/WhatsAppGroupReaction.md -->\n# Type Alias: WhatsAppGroupReaction\n\n> **WhatsAppGroupReaction** = \\{ `count`: `number`; `emoji`: `string`; `mine`: `boolean`; \\}\n\nGrouped reactions.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-count\"></a> `count` | `number` | Number of reacting people. |\n| <a id=\"property-emoji\"></a> `emoji` | `string` | Emoji. |\n| <a id=\"property-mine\"></a> `mine` | `boolean` | Caller has this reaction. |\n\n\n<!-- generated/storage/types.gen/type-aliases/WhatsAppGroupSender.md -->\n# Type Alias: WhatsAppGroupSender\n\n> **WhatsAppGroupSender** = \\{ `name`: `string`; `person_id`: `string`; `user_id?`: `string` \\| `null`; \\}\n\nMessage sender from protocol-verified identity evidence.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-name\"></a> `name` | `string` | Display name, never authentication evidence. |\n| <a id=\"property-person_id\"></a> `person_id` | `string` | External person identity. |\n| <a id=\"property-user_id\"></a> `user_id?` | `string` \\| `null` | Verified Macro user association, if present. |\n\n\n<!-- generated/storage/types.gen/type-aliases/WhatsAppGroupSummary.md -->\n# Type Alias: WhatsAppGroupSummary\n\n> **WhatsAppGroupSummary** = \\{ `backfill?`: `null` \\| [`LinkedBackfill`](LinkedBackfill.md); `can_send`: `boolean`; `id`: `string`; `last_message_at?`: `string` \\| `null`; `name`: `string`; `send_reason?`: `null` \\| [`LinkedReplyBlock`](LinkedReplyBlock.md); `unread_count`: `number`; `user_id`: `string`; \\}\n\nAdopted group visible through ordinary entity sharing.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-backfill\"></a> `backfill?` | `null` \\| [`LinkedBackfill`](LinkedBackfill.md) | - |\n| <a id=\"property-can_send\"></a> `can_send` | `boolean` | Caller may currently send from their own account. |\n| <a id=\"property-id\"></a> `id` | `string` | Entity identifier. |\n| <a id=\"property-last_message_at\"></a> `last_message_at?` | `string` \\| `null` | Latest message timestamp. |\n| <a id=\"property-name\"></a> `name` | `string` | Display name. |\n| <a id=\"property-send_reason\"></a> `send_reason?` | `null` \\| [`LinkedReplyBlock`](LinkedReplyBlock.md) | - |\n| <a id=\"property-unread_count\"></a> `unread_count` | `number` | Unread live messages for this viewer. |\n| <a id=\"property-user_id\"></a> `user_id` | `string` | Actual entity owner. |\n\n\n<!-- generated/storage/types.gen/type-aliases/WhatsAppLocation.md -->\n# Type Alias: WhatsAppLocation\n\n> **WhatsAppLocation** = \\{ `address?`: `string` \\| `null`; `comment?`: `string` \\| `null`; `latitude`: `number`; `live?`: `boolean`; `longitude`: `number`; `name?`: `string` \\| `null`; `url?`: `string` \\| `null`; \\}\n\nA shared place.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-address\"></a> `address?` | `string` \\| `null` | Street address. |\n| <a id=\"property-comment\"></a> `comment?` | `string` \\| `null` | Caption or comment. |\n| <a id=\"property-latitude\"></a> `latitude` | `number` | Degrees. |\n| <a id=\"property-live\"></a> `live?` | `boolean` | Shared as a live location (this is where it started). |\n| <a id=\"property-longitude\"></a> `longitude` | `number` | Degrees. |\n| <a id=\"property-name\"></a> `name?` | `string` \\| `null` | Place name. |\n| <a id=\"property-url\"></a> `url?` | `string` \\| `null` | Link the sender attached. |\n\n\n<!-- generated/storage/types.gen/type-aliases/WhatsAppMention.md -->\n# Type Alias: WhatsAppMention\n\n> **WhatsAppMention** = [`WhatsAppPersonRef`](WhatsAppPersonRef.md) & \\{ `token`: `string`; \\}\n\nAn @-mention in a message body.\n\n## Type Declaration\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `token` | `string` | What follows the `@` in the body (the digits of the person's WhatsApp id); replace `@<token>` with the name. |\n\n\n<!-- generated/storage/types.gen/type-aliases/WhatsAppMessageKind.md -->\n# Type Alias: WhatsAppMessageKind\n\n> **WhatsAppMessageKind** = `\"message\"` \\| `\"system\"`\n\nWhat a timeline entry is.\n\n\n<!-- generated/storage/types.gen/type-aliases/WhatsAppPersonRef.md -->\n# Type Alias: WhatsAppPersonRef\n\n> **WhatsAppPersonRef** = \\{ `name`: `string`; `userId?`: `string` \\| `null`; \\}\n\nA person named in a message: a Macro user when verified, else their\nWhatsApp name, else their phone number.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-name\"></a> `name` | `string` | Display name, never authentication evidence. |\n| <a id=\"property-userid\"></a> `userId?` | `string` \\| `null` | Verified Macro user, if any. |\n\n\n<!-- generated/storage/types.gen/type-aliases/WhatsAppPoll.md -->\n# Type Alias: WhatsAppPoll\n\n> **WhatsAppPoll** = \\{ `options`: [`WhatsAppPollOption`](WhatsAppPollOption.md)[]; `question`: `string`; `selectableCount`: `number`; `voters`: `number`; \\}\n\nA poll, read-only in Macro.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-options\"></a> `options` | [`WhatsAppPollOption`](WhatsAppPollOption.md)[] | Options in order, with tallies. |\n| <a id=\"property-question\"></a> `question` | `string` | The question. |\n| <a id=\"property-selectablecount\"></a> `selectableCount` | `number` | How many options one person may choose; 0 means any number. |\n| <a id=\"property-voters\"></a> `voters` | `number` | People who voted for anything. |\n\n\n<!-- generated/storage/types.gen/type-aliases/WhatsAppPollOption.md -->\n# Type Alias: WhatsAppPollOption\n\n> **WhatsAppPollOption** = \\{ `mine`: `boolean`; `name`: `string`; `voters`: [`WhatsAppPersonRef`](WhatsAppPersonRef.md)[]; `votes`: `number`; \\}\n\nOne option of a poll with its votes.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-mine\"></a> `mine` | `boolean` | The caller chose it. |\n| <a id=\"property-name\"></a> `name` | `string` | Option text. |\n| <a id=\"property-voters\"></a> `voters` | [`WhatsAppPersonRef`](WhatsAppPersonRef.md)[] | Who chose it. |\n| <a id=\"property-votes\"></a> `votes` | `number` | People who chose it. |\n\n\n<!-- generated/storage/types.gen/type-aliases/WhatsAppRichContent.md -->\n# Type Alias: WhatsAppRichContent\n\n> **WhatsAppRichContent** = [`WhatsAppPoll`](WhatsAppPoll.md) & \\{ `type`: `\"poll\"`; \\} \\| [`WhatsAppLocation`](WhatsAppLocation.md) & \\{ `type`: `\"location\"`; \\} \\| [`WhatsAppContacts`](WhatsAppContacts.md) & \\{ `type`: `\"contacts\"`; \\} \\| [`WhatsAppEvent`](WhatsAppEvent.md) & \\{ `type`: `\"event\"`; \\} \\| [`WhatsAppSystemLine`](WhatsAppSystemLine.md) & \\{ `type`: `\"system\"`; \\}\n\nStructured content of a message besides its body.\n\n\n<!-- generated/storage/types.gen/type-aliases/WhatsAppSystemAction.md -->\n# Type Alias: WhatsAppSystemAction\n\n> **WhatsAppSystemAction** = `\"group_created\"` \\| `\"participants_added\"` \\| `\"participants_removed\"` \\| `\"participants_left\"` \\| `\"participants_joined\"` \\| `\"participants_promoted\"` \\| `\"participants_demoted\"` \\| `\"subject_changed\"` \\| `\"icon_changed\"` \\| `\"description_changed\"` \\| `\"disappearing_changed\"` \\| `\"message_pinned\"` \\| `\"message_unpinned\"` \\| `\"call\"`\n\nKinds of system lines.\n\n\n<!-- generated/storage/types.gen/type-aliases/WhatsAppSystemLine.md -->\n# Type Alias: WhatsAppSystemLine\n\n> **WhatsAppSystemLine** = \\{ `action`: [`WhatsAppSystemAction`](WhatsAppSystemAction.md); `actor?`: `null` \\| [`WhatsAppPersonRef`](WhatsAppPersonRef.md); `call?`: `null` \\| [`WhatsAppCall`](WhatsAppCall.md); `participants`: [`WhatsAppPersonRef`](WhatsAppPersonRef.md)[]; `value?`: `string` \\| `null`; \\}\n\nSomething that happened in the group.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-action\"></a> `action` | [`WhatsAppSystemAction`](WhatsAppSystemAction.md) | What happened. |\n| <a id=\"property-actor\"></a> `actor?` | `null` \\| [`WhatsAppPersonRef`](WhatsAppPersonRef.md) | - |\n| <a id=\"property-call\"></a> `call?` | `null` \\| [`WhatsAppCall`](WhatsAppCall.md) | - |\n| <a id=\"property-participants\"></a> `participants` | [`WhatsAppPersonRef`](WhatsAppPersonRef.md)[] | Who it happened to (added, removed, promoted, …). |\n| <a id=\"property-value\"></a> `value?` | `string` \\| `null` | New subject or description; disappearing-messages timer in seconds (`\"0\"` is off). |\n\n\n<!-- src/entities/channels/activity/classes/ChannelActivity.md -->\n# Class: ChannelActivity\n\nA user's channel activity marker.\n\n## Constructors\n\n### Constructor\n\n> **new ChannelActivity**(`client`, `channel`, `record`): `ChannelActivity`\n\n#### Parameters\n\n| Parameter | Type | Description |\n| ------ | ------ | ------ |\n| `client` | `MacroClient` | - |\n| `channel` | [`Channel`](../../channel/classes/Channel.md) | Related channel. |\n| `record` | [`ApiActivity`](../../../../../generated/storage/types.gen/type-aliases/ApiActivity.md) | - |\n\n#### Returns\n\n`ChannelActivity`\n\n## Properties\n\n| Property | Modifier | Type | Description |\n| ------ | ------ | ------ | ------ |\n| <a id=\"property-channel\"></a> `channel` | `readonly` | [`Channel`](../../channel/classes/Channel.md) | Related channel. |\n\n## Accessors\n\n### id\n\n#### Get Signature\n\n> **get** **id**(): `string`\n\nActivity identity.\n\n##### Returns\n\n`string`\n\n## Methods\n\n### createdAt()\n\n> **createdAt**(): `string`\n\nCreation time.\n\n#### Returns\n\n`string`\n\n***\n\n### recordInteraction()\n\n> **recordInteraction**(`type`): `Promise`\\<`ChannelActivity`\\>\n\nRecord a view or interaction in this channel.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `type` | [`ActivityType`](../../../../../generated/storage/types.gen/type-aliases/ActivityType.md) |\n\n#### Returns\n\n`Promise`\\<`ChannelActivity`\\>\n\n***\n\n### toJSON()\n\n> **toJSON**(): [`ApiActivity`](../../../../../generated/storage/types.gen/type-aliases/ApiActivity.md)\n\nSerialize activity without credentials.\n\n#### Returns\n\n[`ApiActivity`](../../../../../generated/storage/types.gen/type-aliases/ApiActivity.md)\n\n***\n\n### user()\n\n> **user**(): [`User`](../../../users/user/classes/User.md)\n\nUser who interacted.\n\n#### Returns\n\n[`User`](../../../users/user/classes/User.md)\n\n\n<!-- src/entities/channels/channel/classes/Channel.md -->\n# Class: Channel\n\nA channel.\n\n## Extends\n\n- [`PropertiedEntity`](../../../entity/classes/PropertiedEntity.md)\\<`ChannelDetail`\\>\n\n## Properties\n\n| Property | Modifier | Type | Default value | Description | Overrides | Inherited from |\n| ------ | ------ | ------ | ------ | ------ | ------ | ------ |\n| <a id=\"property-entitytype\"></a> `entityType` | `readonly` | `\"channel\"` | `'channel'` | Favorites identify channels as `channel`. | [`PropertiedEntity`](../../../entity/classes/PropertiedEntity.md).[`entityType`](../../../entity/classes/PropertiedEntity.md#property-entitytype) | - |\n| <a id=\"property-id\"></a> `id` | `public readonly` | `string` | `undefined` | - | - | [`PropertiedEntity`](../../../entity/classes/PropertiedEntity.md).[`id`](../../../entity/classes/PropertiedEntity.md#property-id) |\n| <a id=\"property-name\"></a> `name` | `readonly` | () => `Promise`\\<`string`\\> | `...` | The channel's display name, resolved from the viewer's perspective. | - | - |\n| <a id=\"property-type\"></a> `type` | `readonly` | () => `Promise`\\<[`ChannelType`](../../../../../generated/storage/types.gen/type-aliases/ChannelType.md)\\> | `...` | The channel's type (e.g. `public`, `dm`, `private`). | - | - |\n| <a id=\"property-search\"></a> `search` | `static` | (`client`, `query`, `searchOpts?`) => `AsyncGenerator`\\<`Channel`\\> | `...` | Search channels by content, most relevant first, auto-paginated. | - | - |\n\n## Methods\n\n### addParticipants()\n\n> **addParticipants**(`users`): `Promise`\\<`void`\\>\n\nAdd users to the channel.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `users` | [`User`](../../../users/user/classes/User.md)[] |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### agentConversations()\n\n> **agentConversations**(): `Promise`\\<[`AgentConversation`](../../../agent-sessions/conversation/classes/AgentConversation.md)[]\\>\n\nConversations maintained by agents in this channel.\n\n#### Returns\n\n`Promise`\\<[`AgentConversation`](../../../agent-sessions/conversation/classes/AgentConversation.md)[]\\>\n\n***\n\n### attachments()\n\n> **attachments**(`opts?`): `AsyncGenerator`\\<[`ApiChannelAttachment`](../../../../../generated/storage/types.gen/type-aliases/ApiChannelAttachment.md)\\>\n\nThe attachments posted in this channel, auto-paginated.\n\n#### Parameters\n\n| Parameter | Type | Description |\n| ------ | ------ | ------ |\n| `opts?` | \\{ `pageSize?`: `number`; `type?`: `string`; \\} | - |\n| `opts.pageSize?` | `number` | - |\n| `opts.type?` | `string` | Filter by type: `static` for images/videos, `dss` for documents. |\n\n#### Returns\n\n`AsyncGenerator`\\<[`ApiChannelAttachment`](../../../../../generated/storage/types.gen/type-aliases/ApiChannelAttachment.md)\\>\n\n***\n\n### delete()\n\n> **delete**(): `Promise`\\<`void`\\>\n\nDelete the channel. This is not reversible.\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### deleteProperty()\n\n> **deleteProperty**(`assignment`): `Promise`\\<`void`\\>\n\nRemove a property from this entity, given its [properties](#properties) entry.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `assignment` | [`EntityPropertyWithDefinition`](../../../../../generated/properties/types.gen/type-aliases/EntityPropertyWithDefinition.md) |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n#### Inherited from\n\n[`PropertiedEntity`](../../../entity/classes/PropertiedEntity.md).[`deleteProperty`](../../../entity/classes/PropertiedEntity.md#deleteproperty)\n\n***\n\n### favorite()\n\n> **favorite**(): `Promise`\\<`Channel`\\>\n\nAdd this entity to the user's favorites. Returns this handle for chaining.\nPlain unwrap: favoriting alters the user's favorites collection, not this\nentity's own detail, so there's nothing cached to invalidate.\n\n#### Returns\n\n`Promise`\\<`Channel`\\>\n\n#### Inherited from\n\n[`PropertiedEntity`](../../../entity/classes/PropertiedEntity.md).[`favorite`](../../../entity/classes/PropertiedEntity.md#favorite)\n\n***\n\n### join()\n\n> **join**(): `Promise`\\<`void`\\>\n\nJoin the channel as the current user.\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### joinCode()\n\n> **joinCode**(): `Promise`\\<`string`\\>\n\nA reusable code that lets a user join this channel.\n\n#### Returns\n\n`Promise`\\<`string`\\>\n\n***\n\n### leave()\n\n> **leave**(): `Promise`\\<`void`\\>\n\nLeave the channel as the current user.\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### message()\n\n> **message**(`id`): [`Message`](../../message/classes/Message.md)\n\nA handle to a message in this channel by id.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `id` | `string` |\n\n#### Returns\n\n[`Message`](../../message/classes/Message.md)\n\n***\n\n### messages()\n\n> **messages**(`opts?`): `AsyncGenerator`\\<[`Message`](../../message/classes/Message.md)\\>\n\nRoot messages in this channel, most recent first, auto-paginated.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `opts?` | \\{ `pageSize?`: `number`; \\} |\n| `opts.pageSize?` | `number` |\n\n#### Returns\n\n`AsyncGenerator`\\<[`Message`](../../message/classes/Message.md)\\>\n\n***\n\n### messagesAfter()\n\n> **messagesAfter**(`after`, `opts?`): `AsyncGenerator`\\<[`Message`](../../message/classes/Message.md)\\>\n\nRoot messages created or replied to at or after `after`, most recent\nfirst, auto-paginated. Use it to catch up after a disconnect.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `after` | `string` \\| `Date` |\n| `opts?` | \\{ `pageSize?`: `number`; \\} |\n| `opts.pageSize?` | `number` |\n\n#### Returns\n\n`AsyncGenerator`\\<[`Message`](../../message/classes/Message.md)\\>\n\n***\n\n### messageThreadById()\n\n> **messageThreadById**(`id`): [`MessageThread`](../../../messages/thread/classes/MessageThread.md)\n\nA shared message thread scoped to this resource.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `id` | `string` |\n\n#### Returns\n\n[`MessageThread`](../../../messages/thread/classes/MessageThread.md)\n\n***\n\n### participants()\n\n> **participants**(): `Promise`\\<[`ApiChannelParticipant`](../../../../../generated/storage/types.gen/type-aliases/ApiChannelParticipant.md)[]\\>\n\nThe channel's members, with their roles and join times.\n\n#### Returns\n\n`Promise`\\<[`ApiChannelParticipant`](../../../../../generated/storage/types.gen/type-aliases/ApiChannelParticipant.md)[]\\>\n\n***\n\n### permission()\n\n> **permission**(): `Promise`\\<\\{ `permission`: [`EntityPermission`](../../../../../generated/storage/types.gen/type-aliases/EntityPermission.md); `status`: `\"access\"`; \\} \\| \\{ `status`: `\"no_access\"`; \\}\\>\n\nRead the caller's effective permission on this entity.\n\n#### Returns\n\n`Promise`\\<\\{ `permission`: [`EntityPermission`](../../../../../generated/storage/types.gen/type-aliases/EntityPermission.md); `status`: `\"access\"`; \\} \\| \\{ `status`: `\"no_access\"`; \\}\\>\n\n#### Inherited from\n\n[`PropertiedEntity`](../../../entity/classes/PropertiedEntity.md).[`permission`](../../../entity/classes/PropertiedEntity.md#permission)\n\n***\n\n### properties()\n\n> **properties**(`opts?`): `Promise`\\<[`EntityPropertyWithDefinition`](../../../../../generated/properties/types.gen/type-aliases/EntityPropertyWithDefinition.md)[]\\>\n\nThe properties set on this entity, each with its definition, value, and options.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `opts?` | \\{ `includeMetadata?`: `boolean`; \\} |\n| `opts.includeMetadata?` | `boolean` |\n\n#### Returns\n\n`Promise`\\<[`EntityPropertyWithDefinition`](../../../../../generated/properties/types.gen/type-aliases/EntityPropertyWithDefinition.md)[]\\>\n\n#### Inherited from\n\n[`PropertiedEntity`](../../../entity/classes/PropertiedEntity.md).[`properties`](../../../entity/classes/PropertiedEntity.md#properties)\n\n***\n\n### propertyReference()\n\n> **propertyReference**(): [`PropertyTargetReference`](../../../../../generated/properties/types.gen/type-aliases/PropertyTargetReference.md)\n\nThis entity's reference for bulk property operations.\n\n#### Returns\n\n[`PropertyTargetReference`](../../../../../generated/properties/types.gen/type-aliases/PropertyTargetReference.md)\n\n#### Inherited from\n\n[`PropertiedEntity`](../../../entity/classes/PropertiedEntity.md).[`propertyReference`](../../../entity/classes/PropertiedEntity.md#propertyreference)\n\n***\n\n### recordActivity()\n\n> **recordActivity**(`type`): `Promise`\\<[`ChannelActivity`](../../activity/classes/ChannelActivity.md)\\>\n\nRecord a view or interaction in this channel.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `type` | [`ActivityType`](../../../../../generated/storage/types.gen/type-aliases/ActivityType.md) |\n\n#### Returns\n\n`Promise`\\<[`ChannelActivity`](../../activity/classes/ChannelActivity.md)\\>\n\n***\n\n### removeParticipants()\n\n> **removeParticipants**(`users`): `Promise`\\<`void`\\>\n\nRemove users from the channel.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `users` | [`User`](../../../users/user/classes/User.md)[] |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### rename()\n\n> **rename**(`name`): `Promise`\\<`void`\\>\n\nRename the channel.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `name` | `string` |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### send()\n\n> **send**(`body`, `opts?`): `Promise`\\<[`Message`](../../message/classes/Message.md)\\>\n\nPost a message. Plain text, or a rich body composed with `msg`.\n\nWorks with a channel webhook token as well as a normal one — see\n[postToChannel](../../post/functions/postToChannel.md) for which endpoint that picks and what it costs.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `body` | `string` \\| [`RichMessage`](../../../../mentions/interfaces/RichMessage.md) |\n| `opts?` | \\{ `thread?`: [`Thread`](../../thread/classes/Thread.md); \\} |\n| `opts.thread?` | [`Thread`](../../thread/classes/Thread.md) |\n\n#### Returns\n\n`Promise`\\<[`Message`](../../message/classes/Message.md)\\>\n\n***\n\n### setPicture()\n\n> **setPicture**(`picture?`): `Promise`\\<`void`\\>\n\nSet an uploaded profile picture, or clear it.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `picture?` | [`ChannelPicture`](../../picture/classes/ChannelPicture.md) |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### setProperty()\n\n> **setProperty**(`property`, `value?`): `Promise`\\<`void`\\>\n\nSet a property value on this entity, or attach the property without a\nvalue when `value` is omitted.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `property` | [`PropertyDefinition`](../../../properties/property-definition/classes/PropertyDefinition.md) |\n| `value?` | [`SetPropertyValue`](../../../../../generated/properties/types.gen/type-aliases/SetPropertyValue.md) |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n#### Inherited from\n\n[`PropertiedEntity`](../../../entity/classes/PropertiedEntity.md).[`setProperty`](../../../entity/classes/PropertiedEntity.md#setproperty)\n\n***\n\n### timelinePage()\n\n> **timelinePage**(`selection?`): `Promise`\\<\\{ `entries`: (\\{ `activity`: \\{ `action`: `string`; `actor`: [`User`](../../../users/user/classes/User.md); `actor_id`: `string`; `id`: `string`; `occurred_at`: `string`; `payload?`: `unknown`; \\}; `message?`: `undefined`; `type`: `\"activity\"`; \\} \\| \\{ `activity?`: `undefined`; `message`: [`Message`](../../message/classes/Message.md); `type`: `\"message\"`; \\})[]; `nextCursor`: [`MessageCursor`](../../../../../generated/storage/types.gen/type-aliases/MessageCursor.md) \\| `undefined`; `previousCursor`: [`MessageCursor`](../../../../../generated/storage/types.gen/type-aliases/MessageCursor.md) \\| `undefined`; \\}\\>\n\nA mixed message and activity timeline page.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `selection?` | [`TimelineOptions`](../../../messages/thread/interfaces/TimelineOptions.md)\\<[`Message`](../../message/classes/Message.md)\\> |\n\n#### Returns\n\n`Promise`\\<\\{ `entries`: (\\{ `activity`: \\{ `action`: `string`; `actor`: [`User`](../../../users/user/classes/User.md); `actor_id`: `string`; `id`: `string`; `occurred_at`: `string`; `payload?`: `unknown`; \\}; `message?`: `undefined`; `type`: `\"activity\"`; \\} \\| \\{ `activity?`: `undefined`; `message`: [`Message`](../../message/classes/Message.md); `type`: `\"message\"`; \\})[]; `nextCursor`: [`MessageCursor`](../../../../../generated/storage/types.gen/type-aliases/MessageCursor.md) \\| `undefined`; `previousCursor`: [`MessageCursor`](../../../../../generated/storage/types.gen/type-aliases/MessageCursor.md) \\| `undefined`; \\}\\>\n\n***\n\n### toJSON()\n\n> **toJSON**(): \\{ `detail?`: [`ApiChannelDetail`](../../../../../generated/storage/types.gen/type-aliases/ApiChannelDetail.md); `id`: `string`; \\}\n\n#### Returns\n\n\\{ `detail?`: [`ApiChannelDetail`](../../../../../generated/storage/types.gen/type-aliases/ApiChannelDetail.md); `id`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `detail?` | [`ApiChannelDetail`](../../../../../generated/storage/types.gen/type-aliases/ApiChannelDetail.md) |\n| `id` | `string` |\n\n#### Inherited from\n\n[`PropertiedEntity`](../../../entity/classes/PropertiedEntity.md).[`toJSON`](../../../entity/classes/PropertiedEntity.md#tojson)\n\n***\n\n### typing()\n\n> **typing**(`action`, `opts?`): `Promise`\\<`void`\\>\n\nBroadcast a typing indicator, optionally scoped to a thread.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `action` | `\"stop\"` \\| `\"start\"` |\n| `opts?` | \\{ `thread?`: [`Thread`](../../thread/classes/Thread.md); \\} |\n| `opts.thread?` | [`Thread`](../../thread/classes/Thread.md) |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### unfavorite()\n\n> **unfavorite**(): `Promise`\\<`Channel`\\>\n\nRemove this entity from the user's favorites. Returns this handle for chaining.\n\n#### Returns\n\n`Promise`\\<`Channel`\\>\n\n#### Inherited from\n\n[`PropertiedEntity`](../../../entity/classes/PropertiedEntity.md).[`unfavorite`](../../../entity/classes/PropertiedEntity.md#unfavorite)\n\n***\n\n### updatePropertyOptions()\n\n> **updatePropertyOptions**(`changes`): `Promise`\\<[`BulkUpdateEntityPropertyOptionsResponse`](../../../../../generated/properties/types.gen/type-aliases/BulkUpdateEntityPropertyOptionsResponse.md)\\>\n\nApply multi-select option deltas atomically across this entity's properties.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `changes` | [`PropertyOptionDelta`](../../../entity/interfaces/PropertyOptionDelta.md)[] |\n\n#### Returns\n\n`Promise`\\<[`BulkUpdateEntityPropertyOptionsResponse`](../../../../../generated/properties/types.gen/type-aliases/BulkUpdateEntityPropertyOptionsResponse.md)\\>\n\n#### Inherited from\n\n[`PropertiedEntity`](../../../entity/classes/PropertiedEntity.md).[`updatePropertyOptions`](../../../entity/classes/PropertiedEntity.md#updatepropertyoptions)\n\n***\n\n### webUrl()\n\n> **webUrl**(): `string`\n\nThe channel's URL in the Macro web app.\n\n#### Returns\n\n`string`\n\n***\n\n### byId()\n\n> `static` **byId**(`client`, `id`): `Channel`\n\nA handle to a channel 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`Channel`\n\n***\n\n### create()\n\n> `static` **create**(`client`, `opts`): `Promise`\\<`Channel`\\>\n\nCreate a channel. The caller becomes the owner.\n\n#### Parameters\n\n| Parameter | Type | Description |\n| ------ | ------ | ------ |\n| `client` | `MacroClient` | - |\n| `opts` | \\{ `name?`: `string`; `participants?`: [`User`](../../../users/user/classes/User.md)[]; `team?`: [`Team`](../../../teams/team/classes/Team.md); `type`: [`ChannelType`](../../../../../generated/storage/types.gen/type-aliases/ChannelType.md); \\} | - |\n| `opts.name?` | `string` | - |\n| `opts.participants?` | [`User`](../../../users/user/classes/User.md)[] | Participants to add, excluding the owner. |\n| `opts.team?` | [`Team`](../../../teams/team/classes/Team.md) | Team, for team channels. |\n| `opts.type` | [`ChannelType`](../../../../../generated/storage/types.gen/type-aliases/ChannelType.md) | - |\n\n#### Returns\n\n`Promise`\\<`Channel`\\>\n\n***\n\n### dm()\n\n> `static` **dm**(`client`, `recipient`): `Promise`\\<`Channel`\\>\n\nOpen (creating if needed) the DM channel with a user.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `recipient` | [`User`](../../../users/user/classes/User.md) |\n\n#### Returns\n\n`Promise`\\<`Channel`\\>\n\n***\n\n### private()\n\n> `static` **private**(`client`, `recipients`): `Promise`\\<`Channel`\\>\n\nOpen (creating if needed) the private group channel with a set of users.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `recipients` | [`User`](../../../users/user/classes/User.md)[] |\n\n#### Returns\n\n`Promise`\\<`Channel`\\>\n\n\n<!-- src/entities/channels/channel/type-aliases/ChannelAttachment.md -->\n# Type Alias: ChannelAttachment\n\n> **ChannelAttachment** = [`GetChannelAttachmentsResponses`](../../../../../generated/storage/types.gen/type-aliases/GetChannelAttachmentsResponses.md)\\[`200`\\]\\[`\"items\"`\\]\\[`number`\\]\n\nA file or entity attached to a message in a channel.\n\n\n<!-- src/entities/channels/channel/type-aliases/ChannelParticipant.md -->\n# Type Alias: ChannelParticipant\n\n> **ChannelParticipant** = [`GetChannelParticipantsResponses`](../../../../../generated/storage/types.gen/type-aliases/GetChannelParticipantsResponses.md)\\[`200`\\]\\[`number`\\]\n\nA member of a channel, with their role and join time.\n\n\n<!-- src/entities/channels/labels/classes/ChannelLabelsNamespace.md -->\n# Class: ChannelLabelsNamespace\n\nShared or private channel labels: named groups of channels shown in the Chat\nsidebar. Every member of the team sees the same labels in the same order,\nand any member may create, rename, delete, or move channels between them;\neach change applies to the whole team. Users without a team have private\nlabels belonging to their account.\n\nA label's `channelIds` lists only the channels the authenticated user is a\nmember of. Manual labels count all assignments; smart tags count visible\nmatches. A channel can be in one manual label and any number of matching\nsmart tags per team or account. Direct messages cannot be grouped.\n\n## Constructors\n\n### Constructor\n\n> **new ChannelLabelsNamespace**(`client`): `ChannelLabelsNamespace`\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n\n#### Returns\n\n`ChannelLabelsNamespace`\n\n## Methods\n\n### create()\n\n> **create**(`name`, `channels?`): `Promise`\\<[`ChannelLabel`](../../../../../generated/storage/types.gen/type-aliases/ChannelLabel.md)\\>\n\nCreate a label and atomically move `channels` into it. Names are unique\nwithin the team or account, case-insensitively.\n\n#### Parameters\n\n| Parameter | Type | Default value |\n| ------ | ------ | ------ |\n| `name` | `string` | `undefined` |\n| `channels?` | [`Channel`](../../channel/classes/Channel.md)[] | `[]` |\n\n#### Returns\n\n`Promise`\\<[`ChannelLabel`](../../../../../generated/storage/types.gen/type-aliases/ChannelLabel.md)\\>\n\n***\n\n### createSmartTag()\n\n> **createSmartTag**(`name`, `rule`): `Promise`\\<[`ChannelLabel`](../../../../../generated/storage/types.gen/type-aliases/ChannelLabel.md)\\>\n\nCreate a smart tag whose membership follows an attribute rule automatically.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `name` | `string` |\n| `rule` | [`ChannelLabelRule`](../../../../../generated/storage/types.gen/type-aliases/ChannelLabelRule.md) |\n\n#### Returns\n\n`Promise`\\<[`ChannelLabel`](../../../../../generated/storage/types.gen/type-aliases/ChannelLabel.md)\\>\n\n***\n\n### delete()\n\n> **delete**(`label`): `Promise`\\<`void`\\>\n\nDelete a label for the whole team; its channels return to the plain list.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `label` | [`ChannelLabel`](../../../../../generated/storage/types.gen/type-aliases/ChannelLabel.md) |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### list()\n\n> **list**(): `Promise`\\<[`ChannelLabel`](../../../../../generated/storage/types.gen/type-aliases/ChannelLabel.md)[]\\>\n\nEvery label in the authenticated user's shared or private scope.\n\n#### Returns\n\n`Promise`\\<[`ChannelLabel`](../../../../../generated/storage/types.gen/type-aliases/ChannelLabel.md)[]\\>\n\n***\n\n### previewSmartTag()\n\n> **previewSmartTag**(`rule`): `Promise`\\<[`SmartTagPreview`](../../../../../generated/storage/types.gen/type-aliases/SmartTagPreview.md)\\>\n\nPreview the first matches and total visible count without creating a tag.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `rule` | [`ChannelLabelRule`](../../../../../generated/storage/types.gen/type-aliases/ChannelLabelRule.md) |\n\n#### Returns\n\n`Promise`\\<[`SmartTagPreview`](../../../../../generated/storage/types.gen/type-aliases/SmartTagPreview.md)\\>\n\n***\n\n### rename()\n\n> **rename**(`label`, `name`): `Promise`\\<[`ChannelLabel`](../../../../../generated/storage/types.gen/type-aliases/ChannelLabel.md)\\>\n\nRename a label for the whole team.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `label` | [`ChannelLabel`](../../../../../generated/storage/types.gen/type-aliases/ChannelLabel.md) |\n| `name` | `string` |\n\n#### Returns\n\n`Promise`\\<[`ChannelLabel`](../../../../../generated/storage/types.gen/type-aliases/ChannelLabel.md)\\>\n\n***\n\n### setLabel()\n\n> **setLabel**(`channel`, `label`): `Promise`\\<`void`\\>\n\nMove a channel into `label`, or out of any label when `label` is `undefined`.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `channel` | [`Channel`](../../channel/classes/Channel.md) |\n| `label` | [`ChannelLabel`](../../../../../generated/storage/types.gen/type-aliases/ChannelLabel.md) \\| `undefined` |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### updateSmartTag()\n\n> **updateSmartTag**(`label`, `name`, `rule`): `Promise`\\<[`ChannelLabel`](../../../../../generated/storage/types.gen/type-aliases/ChannelLabel.md)\\>\n\nUpdate the name and matching rule of an existing smart tag.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `label` | [`ChannelLabel`](../../../../../generated/storage/types.gen/type-aliases/ChannelLabel.md) |\n| `name` | `string` |\n| `rule` | [`ChannelLabelRule`](../../../../../generated/storage/types.gen/type-aliases/ChannelLabelRule.md) |\n\n#### Returns\n\n`Promise`\\<[`ChannelLabel`](../../../../../generated/storage/types.gen/type-aliases/ChannelLabel.md)\\>\n\n\n<!-- src/entities/channels/message/classes/Message.md -->\n# Class: Message\n\nA message in a channel. A thin handle: `id` and `channelId` are known up\nfront, and record-backed fields (`content`, `author`) load lazily on first\naccess and cache. Actions carry the ids for you.\n\n## Extends\n\n- [`FavoritableEntity`](../../../entity/classes/FavoritableEntity.md)\\<[`Message`](../../../../../generated/storage/types.gen/type-aliases/Message.md)\\>\n\n## Properties\n\n| Property | Modifier | Type | Default value | Description | Overrides | Inherited from |\n| ------ | ------ | ------ | ------ | ------ | ------ | ------ |\n| <a id=\"property-channelid\"></a> `channelId` | `readonly` | `string` | `undefined` | - | - | - |\n| <a id=\"property-content\"></a> `content` | `readonly` | () => `Promise`\\<`string`\\> | `...` | The message body. | - | - |\n| <a id=\"property-createdat\"></a> `createdAt` | `readonly` | () => `Promise`\\<`string`\\> | `...` | When the message was created. | - | - |\n| <a id=\"property-editedat\"></a> `editedAt` | `readonly` | () => `Promise`\\<`string` \\| `undefined`\\> | `...` | When the message was last edited, if it has been. | - | - |\n| <a id=\"property-entitytype\"></a> `entityType` | `readonly` | `\"channel_message\"` | `'channel_message'` | Favorites identify channel messages as `channel_message`. | [`FavoritableEntity`](../../../entity/classes/FavoritableEntity.md).[`entityType`](../../../entity/classes/FavoritableEntity.md#property-entitytype) | - |\n| <a id=\"property-id\"></a> `id` | `public readonly` | `string` | `undefined` | - | - | [`FavoritableEntity`](../../../entity/classes/FavoritableEntity.md).[`id`](../../../entity/classes/FavoritableEntity.md#property-id) |\n| <a id=\"property-mentions\"></a> `mentions` | `readonly` | [`SimpleMention`](../../../../../generated/storage/types.gen/type-aliases/SimpleMention.md)[] | `[]` | Entities mentioned in this message, when a list, thread, or event supplied them. | - | - |\n| <a id=\"property-updatedat\"></a> `updatedAt` | `readonly` | () => `Promise`\\<`string`\\> | `...` | When the message was last updated. | - | - |\n\n## Methods\n\n### author()\n\n> **author**(): `Promise`\\<[`User`](../../../users/user/classes/User.md)\\>\n\nThe user who sent this message.\n\n#### Returns\n\n`Promise`\\<[`User`](../../../users/user/classes/User.md)\\>\n\n***\n\n### channel()\n\n> **channel**(): [`Channel`](../../channel/classes/Channel.md)\n\nThe channel this message is in.\n\n#### Returns\n\n[`Channel`](../../channel/classes/Channel.md)\n\n***\n\n### delete()\n\n> **delete**(): `Promise`\\<`void`\\>\n\nDelete this message.\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### edit()\n\n> **edit**(`body`): `Promise`\\<`Message`\\>\n\nReplace this message's body.\n\n#### Parameters\n\n| Parameter | Type | Description |\n| ------ | ------ | ------ |\n| `body` | `string` \\| [`RichMessage`](../../../../mentions/interfaces/RichMessage.md) | Plain text, or a rich body composed with msg. |\n\n#### Returns\n\n`Promise`\\<`Message`\\>\n\n***\n\n### favorite()\n\n> **favorite**(): `Promise`\\<`Message`\\>\n\nAdd this entity to the user's favorites. Returns this handle for chaining.\nPlain unwrap: favoriting alters the user's favorites collection, not this\nentity's own detail, so there's nothing cached to invalidate.\n\n#### Returns\n\n`Promise`\\<`Message`\\>\n\n#### Inherited from\n\n[`FavoritableEntity`](../../../entity/classes/FavoritableEntity.md).[`favorite`](../../../entity/classes/FavoritableEntity.md#favorite)\n\n***\n\n### permission()\n\n> **permission**(): `Promise`\\<\\{ `permission`: [`EntityPermission`](../../../../../generated/storage/types.gen/type-aliases/EntityPermission.md); `status`: `\"access\"`; \\} \\| \\{ `status`: `\"no_access\"`; \\}\\>\n\nRead the caller's effective permission on this entity.\n\n#### Returns\n\n`Promise`\\<\\{ `permission`: [`EntityPermission`](../../../../../generated/storage/types.gen/type-aliases/EntityPermission.md); `status`: `\"access\"`; \\} \\| \\{ `status`: `\"no_access\"`; \\}\\>\n\n#### Inherited from\n\n[`FavoritableEntity`](../../../entity/classes/FavoritableEntity.md).[`permission`](../../../entity/classes/FavoritableEntity.md#permission)\n\n***\n\n### react()\n\n> **react**(`emoji`): `Promise`\\<`Message`\\>\n\nAdd an emoji reaction to this message.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `emoji` | `string` |\n\n#### Returns\n\n`Promise`\\<`Message`\\>\n\n***\n\n### reply()\n\n> **reply**(`body`): `Promise`\\<`Message`\\>\n\nPost a reply in this message's thread.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `body` | `string` \\| [`RichMessage`](../../../../mentions/interfaces/RichMessage.md) |\n\n#### Returns\n\n`Promise`\\<`Message`\\>\n\n***\n\n### thread()\n\n> **thread**(): [`Thread`](../../thread/classes/Thread.md)\n\nThe thread rooted at this message.\n\n#### Returns\n\n[`Thread`](../../thread/classes/Thread.md)\n\n***\n\n### toJSON()\n\n> **toJSON**(): \\{ `detail?`: [`Message`](../../../../../generated/storage/types.gen/type-aliases/Message.md); `id`: `string`; \\}\n\n#### Returns\n\n\\{ `detail?`: [`Message`](../../../../../generated/storage/types.gen/type-aliases/Message.md); `id`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `detail?` | [`Message`](../../../../../generated/storage/types.gen/type-aliases/Message.md) |\n| `id` | `string` |\n\n#### Inherited from\n\n[`FavoritableEntity`](../../../entity/classes/FavoritableEntity.md).[`toJSON`](../../../entity/classes/FavoritableEntity.md#tojson)\n\n***\n\n### unfavorite()\n\n> **unfavorite**(): `Promise`\\<`Message`\\>\n\nRemove this entity from the user's favorites. Returns this handle for chaining.\n\n#### Returns\n\n`Promise`\\<`Message`\\>\n\n#### Inherited from\n\n[`FavoritableEntity`](../../../entity/classes/FavoritableEntity.md).[`unfavorite`](../../../entity/classes/FavoritableEntity.md#unfavorite)\n\n***\n\n### unreact()\n\n> **unreact**(`emoji`): `Promise`\\<`Message`\\>\n\nRemove one of your emoji reactions from this message.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `emoji` | `string` |\n\n#### Returns\n\n`Promise`\\<`Message`\\>\n\n***\n\n### byId()\n\n> `static` **byId**(`client`, `channelId`, `id`, `mentions?`): `Message`\n\nA handle to a message by id. Fields load on first access.\n\n#### Parameters\n\n| Parameter | Type | Default value |\n| ------ | ------ | ------ |\n| `client` | `MacroClient` | `undefined` |\n| `channelId` | `string` | `undefined` |\n| `id` | `string` | `undefined` |\n| `mentions?` | [`SimpleMention`](../../../../../generated/storage/types.gen/type-aliases/SimpleMention.md)[] | `[]` |\n\n#### Returns\n\n`Message`\n\n***\n\n### from()\n\n> `static` **from**(`client`, `channelId`, `data`): `Message`\n\nBuild a root or reply from a message record (pre-seeded, no fetch).\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `channelId` | `string` |\n| `data` | [`Message`](../../../../../generated/storage/types.gen/type-aliases/Message.md) |\n\n#### Returns\n\n`Message`\n\n\n<!-- src/entities/channels/message/type-aliases/MessageData.md -->\n# Type Alias: MessageData\n\n> **MessageData** = [`Message`](../../../../../generated/storage/types.gen/type-aliases/Message.md)\n\nThe API's representation of a message; the same record the document comment API returns.\n\n\n<!-- src/entities/channels/namespace/classes/ChannelNamespace.md -->\n# Class: ChannelNamespace\n\n## Constructors\n\n### Constructor\n\n> **new ChannelNamespace**(`client`): `ChannelNamespace`\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n\n#### Returns\n\n`ChannelNamespace`\n\n## Properties\n\n| Property | Modifier | Type | Description |\n| ------ | ------ | ------ | ------ |\n| <a id=\"property-labels\"></a> `labels` | `readonly` | [`ChannelLabelsNamespace`](../../labels/classes/ChannelLabelsNamespace.md) | Team-shared labels that group channels in the Chat sidebar. |\n\n## Methods\n\n### activity()\n\n> **activity**(): `Promise`\\<[`ChannelActivity`](../../activity/classes/ChannelActivity.md)[]\\>\n\nRecent channel activity, with channel and user handles.\n\n#### Returns\n\n`Promise`\\<[`ChannelActivity`](../../activity/classes/ChannelActivity.md)[]\\>\n\n***\n\n### byId()\n\n> **byId**(`id`): [`Channel`](../../channel/classes/Channel.md)\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `id` | `string` |\n\n#### Returns\n\n[`Channel`](../../channel/classes/Channel.md)\n\n***\n\n### create()\n\n> **create**(`opts`): `Promise`\\<[`Channel`](../../channel/classes/Channel.md)\\>\n\nCreate a channel. The caller becomes the owner.\n\n#### Parameters\n\n| Parameter | Type | Description |\n| ------ | ------ | ------ |\n| `opts` | \\{ `name?`: `string`; `participants?`: [`User`](../../../users/user/classes/User.md)[]; `team?`: [`Team`](../../../teams/team/classes/Team.md); `type`: [`ChannelType`](../../../../../generated/storage/types.gen/type-aliases/ChannelType.md); \\} | - |\n| `opts.name?` | `string` | - |\n| `opts.participants?` | [`User`](../../../users/user/classes/User.md)[] | Participants to add, excluding the owner. |\n| `opts.team?` | [`Team`](../../../teams/team/classes/Team.md) | Team, for team channels. |\n| `opts.type` | [`ChannelType`](../../../../../generated/storage/types.gen/type-aliases/ChannelType.md) | - |\n\n#### Returns\n\n`Promise`\\<[`Channel`](../../channel/classes/Channel.md)\\>\n\n***\n\n### dm()\n\n> **dm**(`recipient`): `Promise`\\<[`Channel`](../../channel/classes/Channel.md)\\>\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `recipient` | [`User`](../../../users/user/classes/User.md) |\n\n#### Returns\n\n`Promise`\\<[`Channel`](../../channel/classes/Channel.md)\\>\n\n***\n\n### list()\n\n> **list**(): `Promise`\\<[`Channel`](../../channel/classes/Channel.md)[]\\>\n\nAll channels the authenticated user is a member of.\n\n#### Returns\n\n`Promise`\\<[`Channel`](../../channel/classes/Channel.md)[]\\>\n\n***\n\n### private()\n\n> **private**(`recipients`): `Promise`\\<[`Channel`](../../channel/classes/Channel.md)\\>\n\nOpen (creating if needed) the private group channel with a set of users.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `recipients` | [`User`](../../../users/user/classes/User.md)[] |\n\n#### Returns\n\n`Promise`\\<[`Channel`](../../channel/classes/Channel.md)\\>\n\n***\n\n### search()\n\n> **search**(`query`, `opts?`): `AsyncGenerator`\\<[`Channel`](../../channel/classes/Channel.md)\\>\n\nSearch channels by name (client-side fuzzy filter on the full channel list)\nor by content (server-side unified search).\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `query` | `string` |\n| `opts?` | [`SearchOpts`](../../../search/interfaces/SearchOpts.md) |\n\n#### Returns\n\n`AsyncGenerator`\\<[`Channel`](../../channel/classes/Channel.md)\\>\n\n\n<!-- src/entities/channels/picture/classes/ChannelPicture.md -->\n# Class: ChannelPicture\n\nAn uploaded channel profile picture in static file storage.\n\n## Properties\n\n| Property | Modifier | Type |\n| ------ | ------ | ------ |\n| <a id=\"property-id\"></a> `id` | `readonly` | `string` |\n\n## Methods\n\n### toJSON()\n\n> **toJSON**(): \\{ `id`: `string`; \\}\n\nSerialize the uploaded picture reference.\n\n#### Returns\n\n\\{ `id`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `id` | `string` |\n\n***\n\n### byId()\n\n> `static` **byId**(`id`): `ChannelPicture`\n\nConstruct a reference from the upload receipt.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `id` | `string` |\n\n#### Returns\n\n`ChannelPicture`\n\n\n<!-- src/entities/channels/post/functions/postToChannel.md -->\n# Function: postToChannel()\n\n> **postToChannel**(`client`, `target`, `body`): `Promise`\\<`string`\\>\n\nPost a message using the endpoint supported by the caller's credentials.\n\nMost credentials use `POST /messages/channel/{id}`. User-owned bots without\nan acting user instead use `POST /channels/{id}/webhook`, which authorizes\nthrough channel membership. The bot owner is read from `GET /bots/me` and\ncached by the client.\n\nThe webhook endpoint supports content only. Mentions in `<m-*>` tags still\nwork, but threads and attachments are not supported.\n\nPosting to a `Thread` puts the message in that thread; to a `Channel`, at the\nchannel root. One target rather than a channel plus a thread id, so the two\ncan't disagree.\n\n## Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `target` | [`Channel`](../../channel/classes/Channel.md) \\| [`Thread`](../../thread/classes/Thread.md) |\n| `body` | [`RichMessage`](../../../../mentions/interfaces/RichMessage.md) |\n\n## Returns\n\n`Promise`\\<`string`\\>\n\n\n<!-- src/entities/channels/thread/classes/Thread.md -->\n# Class: Thread\n\nA thread within a channel, rooted at a top-level message. Replies and\nthread-scoped posting live here.\n\n## Constructors\n\n### Constructor\n\n> **new Thread**(`client`, `channelId`, `rootId`): `Thread`\n\n#### Parameters\n\n| Parameter | Type | Description |\n| ------ | ------ | ------ |\n| `client` | `MacroClient` | - |\n| `channelId` | `string` | - |\n| `rootId` | `string` | The id of the message this thread hangs off. |\n\n#### Returns\n\n`Thread`\n\n## Properties\n\n| Property | Modifier | Type | Description |\n| ------ | ------ | ------ | ------ |\n| <a id=\"property-channelid\"></a> `channelId` | `readonly` | `string` | - |\n| <a id=\"property-rootid\"></a> `rootId` | `readonly` | `string` | The id of the message this thread hangs off. |\n\n## Methods\n\n### channel()\n\n> **channel**(): [`Channel`](../../channel/classes/Channel.md)\n\nThe channel this thread is in.\n\n#### Returns\n\n[`Channel`](../../channel/classes/Channel.md)\n\n***\n\n### replies()\n\n> **replies**(): `Promise`\\<[`Message`](../../message/classes/Message.md)[]\\>\n\nList the replies in this thread, oldest first.\n\n#### Returns\n\n`Promise`\\<[`Message`](../../message/classes/Message.md)[]\\>\n\n***\n\n### reply()\n\n> **reply**(`body`): `Promise`\\<[`Message`](../../message/classes/Message.md)\\>\n\nPost a reply in this thread.\n\n#### Parameters\n\n| Parameter | Type | Description |\n| ------ | ------ | ------ |\n| `body` | `string` \\| [`RichMessage`](../../../../mentions/interfaces/RichMessage.md) | Plain text, or a rich body composed with msg. |\n\n#### Returns\n\n`Promise`\\<[`Message`](../../message/classes/Message.md)\\>\n\nThe created reply.\n\n***\n\n### root()\n\n> **root**(): [`Message`](../../message/classes/Message.md)\n\nThe message this thread hangs off.\n\n#### Returns\n\n[`Message`](../../message/classes/Message.md)\n\n***\n\n### toJSON()\n\n> **toJSON**(): \\{ `channelId`: `string`; `rootId`: `string`; \\}\n\nSerialize the thread identity without its authenticated client.\n\n#### Returns\n\n\\{ `channelId`: `string`; `rootId`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `channelId` | `string` |\n| `rootId` | `string` |\n\n\n<!-- src/entities/whatsapp/account/classes/WhatsAppAccount.md -->\n# Class: WhatsAppAccount\n\nThe current user's WhatsApp account, connected through the Macro app.\n\n## Extends\n\n- [`MacroEntity`](../../../entity/classes/MacroEntity.md)\\<[`LinkedAccount`](../../../../../generated/storage/types.gen/type-aliases/LinkedAccount.md)\\>\n\n## Properties\n\n| Property | Modifier | Type | Description | Inherited from |\n| ------ | ------ | ------ | ------ | ------ |\n| <a id=\"property-id\"></a> `id` | `public readonly` | `string` | - | [`MacroEntity`](../../../entity/classes/MacroEntity.md).[`id`](../../../entity/classes/MacroEntity.md#property-id) |\n| <a id=\"property-identity\"></a> `identity` | `readonly` | () => `Promise`\\<`string` \\| `undefined`\\> | Verified remote identity, absent until pairing succeeds. | - |\n| <a id=\"property-owner\"></a> `owner` | `readonly` | () => `Promise`\\<[`User`](../../../users/user/classes/User.md)\\> | The Macro user who owns this account. | - |\n| <a id=\"property-state\"></a> `state` | `readonly` | () => `Promise`\\<[`LinkedAccountState`](../../../../../generated/storage/types.gen/type-aliases/LinkedAccountState.md)\\> | Account connection state; call refresh before polling it again. | - |\n\n## Methods\n\n### refresh()\n\n> **refresh**(): `Promise`\\<`WhatsAppAccount`\\>\n\nDiscard cached connection state and load its current value.\n\n#### Returns\n\n`Promise`\\<`WhatsAppAccount`\\>\n\n***\n\n### toJSON()\n\n> **toJSON**(): \\{ `detail?`: [`LinkedAccount`](../../../../../generated/storage/types.gen/type-aliases/LinkedAccount.md); `id`: `string`; \\}\n\n#### Returns\n\n\\{ `detail?`: [`LinkedAccount`](../../../../../generated/storage/types.gen/type-aliases/LinkedAccount.md); `id`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `detail?` | [`LinkedAccount`](../../../../../generated/storage/types.gen/type-aliases/LinkedAccount.md) |\n| `id` | `string` |\n\n#### Inherited from\n\n[`MacroEntity`](../../../entity/classes/MacroEntity.md).[`toJSON`](../../../entity/classes/MacroEntity.md#tojson)\n\n***\n\n### byId()\n\n> `static` **byId**(`client`, `id`): `WhatsAppAccount`\n\nReference an account; reads still enforce the authenticated owner's scope.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `id` | `string` |\n\n#### Returns\n\n`WhatsAppAccount`\n\n***\n\n### from()\n\n> `static` **from**(`client`, `record`): `WhatsAppAccount`\n\nSeed an account handle from an API record.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `record` | [`LinkedAccount`](../../../../../generated/storage/types.gen/type-aliases/LinkedAccount.md) |\n\n#### Returns\n\n`WhatsAppAccount`\n\n\n<!-- src/entities/whatsapp/chat/classes/WhatsAppChat.md -->\n# Class: WhatsAppChat\n\nOne chat of the current user's WhatsApp chat list: a group or a direct chat.\n\n## Extends\n\n- [`MacroEntity`](../../../entity/classes/MacroEntity.md)\\<[`LinkedChat`](../../../../../generated/storage/types.gen/type-aliases/LinkedChat.md)\\>\n\n## Properties\n\n| Property | Modifier | Type | Description | Inherited from |\n| ------ | ------ | ------ | ------ | ------ |\n| <a id=\"property-archived\"></a> `archived` | `readonly` | () => `Promise`\\<`boolean`\\> | Archived in WhatsApp. | - |\n| <a id=\"property-canadd\"></a> `canAdd` | `readonly` | () => `Promise`\\<`boolean`\\> | Whether adding it to Macro works now. | - |\n| <a id=\"property-cannotaddreason\"></a> `cannotAddReason` | `readonly` | () => `Promise`\\<`string` \\| `undefined`\\> | Why it can't be added, when it is neither added, shared nor addable. | - |\n| <a id=\"property-group\"></a> `group` | `readonly` | () => `Promise`\\<[`WhatsAppGroup`](../../group/classes/WhatsAppGroup.md) \\| `undefined`\\> | The current user's own Macro group for this chat, once added. | - |\n| <a id=\"property-id\"></a> `id` | `public readonly` | `string` | - | [`MacroEntity`](../../../entity/classes/MacroEntity.md).[`id`](../../../entity/classes/MacroEntity.md#property-id) |\n| <a id=\"property-kind\"></a> `kind` | `readonly` | () => `Promise`\\<[`LinkedChatKind`](../../../../../generated/storage/types.gen/type-aliases/LinkedChatKind.md)\\> | `group` or `direct`. | - |\n| <a id=\"property-lastactivityat\"></a> `lastActivityAt` | `readonly` | () => `Promise`\\<`string` \\| `undefined`\\> | Newest activity WhatsApp reported, when known. | - |\n| <a id=\"property-name\"></a> `name` | `readonly` | () => `Promise`\\<`string`\\> | Group subject (or member names), or the other person's name or number. | - |\n| <a id=\"property-pinned\"></a> `pinned` | `readonly` | () => `Promise`\\<`boolean`\\> | Pinned in WhatsApp. | - |\n| <a id=\"property-shared\"></a> `shared` | `readonly` | () => `Promise`\\<[`WhatsAppGroup`](../../group/classes/WhatsAppGroup.md) \\| `undefined`\\> | Someone else's Macro group for this chat, shared with the current user. | - |\n\n## Methods\n\n### adopt()\n\n> **adopt**(): `Promise`\\<[`WhatsAppGroup`](../../group/classes/WhatsAppGroup.md)\\>\n\nAdd a group chat to Macro as the current user's own group; its earlier\nmessages are imported from the phone. Adding it again returns the same\ngroup. Direct chats can't be added yet.\n\n#### Returns\n\n`Promise`\\<[`WhatsAppGroup`](../../group/classes/WhatsAppGroup.md)\\>\n\n***\n\n### refresh()\n\n> **refresh**(): `Promise`\\<`WhatsAppChat`\\>\n\nReload the chat's list entry.\n\n#### Returns\n\n`Promise`\\<`WhatsAppChat`\\>\n\n***\n\n### toJSON()\n\n> **toJSON**(): \\{ `detail?`: [`LinkedChat`](../../../../../generated/storage/types.gen/type-aliases/LinkedChat.md); `id`: `string`; \\}\n\n#### Returns\n\n\\{ `detail?`: [`LinkedChat`](../../../../../generated/storage/types.gen/type-aliases/LinkedChat.md); `id`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `detail?` | [`LinkedChat`](../../../../../generated/storage/types.gen/type-aliases/LinkedChat.md) |\n| `id` | `string` |\n\n#### Inherited from\n\n[`MacroEntity`](../../../entity/classes/MacroEntity.md).[`toJSON`](../../../entity/classes/MacroEntity.md#tojson)\n\n***\n\n### byId()\n\n> `static` **byId**(`client`, `id`): `WhatsAppChat`\n\nReference a chat by its WhatsApp JID.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `id` | `string` |\n\n#### Returns\n\n`WhatsAppChat`\n\n***\n\n### from()\n\n> `static` **from**(`client`, `record`): `WhatsAppChat`\n\nSeed a chat handle from the chat list.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `record` | [`LinkedChat`](../../../../../generated/storage/types.gen/type-aliases/LinkedChat.md) |\n\n#### Returns\n\n`WhatsAppChat`\n\n\n<!-- src/entities/whatsapp/group/classes/WhatsAppGroup.md -->\n# Class: WhatsAppGroup\n\nIndependently shareable adopted WhatsApp group entity.\n\n## Extends\n\n- [`FavoritableEntity`](../../../entity/classes/FavoritableEntity.md)\\<[`WhatsAppGroupDetail`](../../../../../generated/storage/types.gen/type-aliases/WhatsAppGroupDetail.md)\\>\n\n## Properties\n\n| Property | Modifier | Type | Description | Overrides | Inherited from |\n| ------ | ------ | ------ | ------ | ------ | ------ |\n| <a id=\"property-backfill\"></a> `backfill` | `readonly` | () => `Promise`\\<[`LinkedBackfill`](../../../../../generated/storage/types.gen/type-aliases/LinkedBackfill.md) \\| `undefined`\\> | Importing earlier messages from the owner's phone after adding, if any. | - | - |\n| <a id=\"property-cansend\"></a> `canSend` | `readonly` | () => `Promise`\\<`boolean`\\> | Whether the caller can send from their own connected account. | - | - |\n| <a id=\"property-entitytype\"></a> `entityType` | `readonly` | `\"whatsapp_group\"` | Canonical sharing and favorites kind. | [`FavoritableEntity`](../../../entity/classes/FavoritableEntity.md).[`entityType`](../../../entity/classes/FavoritableEntity.md#property-entitytype) | - |\n| <a id=\"property-id\"></a> `id` | `public readonly` | `string` | - | - | [`FavoritableEntity`](../../../entity/classes/FavoritableEntity.md).[`id`](../../../entity/classes/FavoritableEntity.md#property-id) |\n| <a id=\"property-limits\"></a> `limits` | `readonly` | () => `Promise`\\<[`LinkedCapabilities`](../../../../../generated/storage/types.gen/type-aliases/LinkedCapabilities.md)\\> | Supported sizes and mutation window. | - | - |\n| <a id=\"property-name\"></a> `name` | `readonly` | () => `Promise`\\<`string`\\> | Display name. | - | - |\n| <a id=\"property-owner\"></a> `owner` | `readonly` | () => `Promise`\\<[`User`](../../../users/user/classes/User.md)\\> | Actual owner, independent of WhatsApp membership. | - | - |\n| <a id=\"property-roster\"></a> `roster` | `readonly` | () => `Promise`\\<[`LinkedGroupInfo`](../../../../../generated/storage/types.gen/type-aliases/LinkedGroupInfo.md) \\| `undefined`\\> | Current remote roster, when available. | - | - |\n| <a id=\"property-sendingidentity\"></a> `sendingIdentity` | `readonly` | () => `Promise`\\<`string` \\| `undefined`\\> | Caller's own verified sending identity. | - | - |\n| <a id=\"property-sendreason\"></a> `sendReason` | `readonly` | () => `Promise`\\<`NonNullable`\\<LinkedReplyBlock \\| null \\| undefined\\> \\| `undefined`\\> | Reason sending is blocked. | - | - |\n| <a id=\"property-unreadcount\"></a> `unreadCount` | `readonly` | () => `Promise`\\<`number`\\> | Per-user unread count. | - | - |\n\n## Methods\n\n### delivery()\n\n> **delivery**(`sends`): `Promise`\\<[`WhatsAppSend`](../../send/classes/WhatsAppSend.md)[]\\>\n\nRead delivery for selected caller-owned intents or messages.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `sends` | ([`WhatsAppMessage`](../../message/classes/WhatsAppMessage.md) \\| [`WhatsAppSend`](../../send/classes/WhatsAppSend.md))[] |\n\n#### Returns\n\n`Promise`\\<[`WhatsAppSend`](../../send/classes/WhatsAppSend.md)[]\\>\n\n***\n\n### detach()\n\n> **detach**(): `Promise`\\<`void`\\>\n\nStop observation while preserving history and established sharing.\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### favorite()\n\n> **favorite**(): `Promise`\\<`WhatsAppGroup`\\>\n\nAdd this entity to the user's favorites. Returns this handle for chaining.\nPlain unwrap: favoriting alters the user's favorites collection, not this\nentity's own detail, so there's nothing cached to invalidate.\n\n#### Returns\n\n`Promise`\\<`WhatsAppGroup`\\>\n\n#### Inherited from\n\n[`FavoritableEntity`](../../../entity/classes/FavoritableEntity.md).[`favorite`](../../../entity/classes/FavoritableEntity.md#favorite)\n\n***\n\n### markRead()\n\n> **markRead**(`message`): `Promise`\\<`void`\\>\n\nAdvance the caller's own read cursor.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `message` | [`WhatsAppMessage`](../../message/classes/WhatsAppMessage.md) |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### messageAttachments()\n\n> **messageAttachments**(`messages`): `Promise`\\<\\{ `attachments`: \\{ `document`: [`Document`](../../../documents/document/classes/Document.md) \\| `undefined`; `fileName`: `string`; `mime`: `string`; `ordinal`: `number`; `size`: `number`; `state`: [`LinkedAttachmentState`](../../../../../generated/storage/types.gen/type-aliases/LinkedAttachmentState.md); \\}[]; `message`: [`WhatsAppMessage`](../../message/classes/WhatsAppMessage.md); \\}[]\\>\n\nRead attachment states for selected messages.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `messages` | [`WhatsAppMessage`](../../message/classes/WhatsAppMessage.md)[] |\n\n#### Returns\n\n`Promise`\\<\\{ `attachments`: \\{ `document`: [`Document`](../../../documents/document/classes/Document.md) \\| `undefined`; `fileName`: `string`; `mime`: `string`; `ordinal`: `number`; `size`: `number`; `state`: [`LinkedAttachmentState`](../../../../../generated/storage/types.gen/type-aliases/LinkedAttachmentState.md); \\}[]; `message`: [`WhatsAppMessage`](../../message/classes/WhatsAppMessage.md); \\}[]\\>\n\n***\n\n### messages()\n\n> **messages**(`options?`): `AsyncGenerator`\\<[`WhatsAppMessage`](../../message/classes/WhatsAppMessage.md)\\>\n\nIterate newest-first timeline pages lazily.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `options?` | \\{ `limit?`: `number`; \\} |\n| `options.limit?` | `number` |\n\n#### Returns\n\n`AsyncGenerator`\\<[`WhatsAppMessage`](../../message/classes/WhatsAppMessage.md)\\>\n\n***\n\n### permission()\n\n> **permission**(): `Promise`\\<\\{ `permission`: [`EntityPermission`](../../../../../generated/storage/types.gen/type-aliases/EntityPermission.md); `status`: `\"access\"`; \\} \\| \\{ `status`: `\"no_access\"`; \\}\\>\n\nRead the caller's effective permission on this entity.\n\n#### Returns\n\n`Promise`\\<\\{ `permission`: [`EntityPermission`](../../../../../generated/storage/types.gen/type-aliases/EntityPermission.md); `status`: `\"access\"`; \\} \\| \\{ `status`: `\"no_access\"`; \\}\\>\n\n#### Inherited from\n\n[`FavoritableEntity`](../../../entity/classes/FavoritableEntity.md).[`permission`](../../../entity/classes/FavoritableEntity.md#permission)\n\n***\n\n### permissions()\n\n> **permissions**(): `Promise`\\<[`SharePermissionV2`](../../../../../generated/storage/types.gen/type-aliases/SharePermissionV2.md)\\>\n\nRead standard link/team sharing settings.\n\n#### Returns\n\n`Promise`\\<[`SharePermissionV2`](../../../../../generated/storage/types.gen/type-aliases/SharePermissionV2.md)\\>\n\n***\n\n### refresh()\n\n> **refresh**(): `Promise`\\<`WhatsAppGroup`\\>\n\nReload detail, permissions and caller capabilities.\n\n#### Returns\n\n`Promise`\\<`WhatsAppGroup`\\>\n\n***\n\n### reply()\n\n> **reply**(`content`, `options`): `Promise`\\<[`WhatsAppSend`](../../send/classes/WhatsAppSend.md)\\>\n\nPersonal sessions and owner API credentials can send. Bots never send.\nPreserve the idempotency key; uncertain outcomes are never automatically resent.\nThe server enforces one request per second per user.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `content` | [`WhatsAppReply`](../type-aliases/WhatsAppReply.md) |\n| `options` | \\{ `idempotencyKey`: `string`; `replyTo?`: [`WhatsAppMessage`](../../message/classes/WhatsAppMessage.md); \\} |\n| `options.idempotencyKey` | `string` |\n| `options.replyTo?` | [`WhatsAppMessage`](../../message/classes/WhatsAppMessage.md) |\n\n#### Returns\n\n`Promise`\\<[`WhatsAppSend`](../../send/classes/WhatsAppSend.md)\\>\n\n***\n\n### sends()\n\n> **sends**(): `Promise`\\<[`WhatsAppSend`](../../send/classes/WhatsAppSend.md)[]\\>\n\nRead only the caller's pending, uncertain or failed sends.\n\n#### Returns\n\n`Promise`\\<[`WhatsAppSend`](../../send/classes/WhatsAppSend.md)[]\\>\n\n***\n\n### toJSON()\n\n> **toJSON**(): \\{ `detail?`: [`WhatsAppGroupDetail`](../../../../../generated/storage/types.gen/type-aliases/WhatsAppGroupDetail.md); `id`: `string`; \\}\n\n#### Returns\n\n\\{ `detail?`: [`WhatsAppGroupDetail`](../../../../../generated/storage/types.gen/type-aliases/WhatsAppGroupDetail.md); `id`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `detail?` | [`WhatsAppGroupDetail`](../../../../../generated/storage/types.gen/type-aliases/WhatsAppGroupDetail.md) |\n| `id` | `string` |\n\n#### Inherited from\n\n[`FavoritableEntity`](../../../entity/classes/FavoritableEntity.md).[`toJSON`](../../../entity/classes/FavoritableEntity.md#tojson)\n\n***\n\n### unfavorite()\n\n> **unfavorite**(): `Promise`\\<`WhatsAppGroup`\\>\n\nRemove this entity from the user's favorites. Returns this handle for chaining.\n\n#### Returns\n\n`Promise`\\<`WhatsAppGroup`\\>\n\n#### Inherited from\n\n[`FavoritableEntity`](../../../entity/classes/FavoritableEntity.md).[`unfavorite`](../../../entity/classes/FavoritableEntity.md#unfavorite)\n\n***\n\n### updatePermissions()\n\n> **updatePermissions**(`update`): `Promise`\\<`void`\\>\n\nActual owner updates standard link/team sharing settings.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `update` | [`UpdateSharePermissionRequestV2`](../../../../../generated/storage/types.gen/type-aliases/UpdateSharePermissionRequestV2.md) |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### upload()\n\n> **upload**(`file`): `Promise`\\<[`WhatsAppUpload`](../../upload/classes/WhatsAppUpload.md)\\>\n\nStage a supported attachment for a deliberate send.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `file` | `Blob` \\| `File` |\n\n#### Returns\n\n`Promise`\\<[`WhatsAppUpload`](../../upload/classes/WhatsAppUpload.md)\\>\n\n***\n\n### byId()\n\n> `static` **byId**(`client`, `id`): `WhatsAppGroup`\n\nReference an adopted group; access is checked on each request.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `id` | `string` |\n\n#### Returns\n\n`WhatsAppGroup`\n\n\n<!-- src/entities/whatsapp/group/type-aliases/WhatsAppReply.md -->\n# Type Alias: WhatsAppReply\n\n> **WhatsAppReply** = \\{ `mentions?`: `string`[]; `text`: `string`; `type`: `\"text\"`; \\} \\| \\{ `caption?`: `string`; `type`: `\"media\"`; `upload`: [`WhatsAppUpload`](../../upload/classes/WhatsAppUpload.md); \\} \\| \\{ `message`: [`WhatsAppMessage`](../../message/classes/WhatsAppMessage.md); `operation`: `\"reaction\"` \\| `\"edit\"` \\| `\"delete\"`; `text?`: `string`; `type`: `\"mutation\"`; \\}\n\nDeliberate content from the credential owner's own WhatsApp account.\n\n## Union Members\n\n### Type Literal\n\n\\{ `mentions?`: `string`[]; `text`: `string`; `type`: `\"text\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `mentions?` | `string`[] | WhatsApp ids of mentioned participants (`roster.participants[].jid`); the text names each as `@<digits>`. |\n| `text` | `string` | - |\n| `type` | `\"text\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `caption?`: `string`; `type`: `\"media\"`; `upload`: [`WhatsAppUpload`](../../upload/classes/WhatsAppUpload.md); \\}\n\n***\n\n### Type Literal\n\n\\{ `message`: [`WhatsAppMessage`](../../message/classes/WhatsAppMessage.md); `operation`: `\"reaction\"` \\| `\"edit\"` \\| `\"delete\"`; `text?`: `string`; `type`: `\"mutation\"`; \\}\n\n\n<!-- src/entities/whatsapp/message/classes/WhatsAppMessage.md -->\n# Class: WhatsAppMessage\n\nMessage in an independently shared WhatsApp group.\n\n## Extends\n\n- [`MacroEntity`](../../../entity/classes/MacroEntity.md)\\<[`WhatsAppGroupMessage`](../../../../../generated/storage/types.gen/type-aliases/WhatsAppGroupMessage.md)\\>\n\n## Properties\n\n| Property | Modifier | Type | Description | Inherited from |\n| ------ | ------ | ------ | ------ | ------ |\n| <a id=\"property-attachments\"></a> `attachments` | `readonly` | () => `Promise`\\<\\{ `document`: [`Document`](../../../documents/document/classes/Document.md) \\| `undefined`; `durationSeconds`: `number` \\| `undefined`; `fileName`: `string`; `height`: `number` \\| `undefined`; `mime`: `string`; `ordinal`: `number`; `presentation`: [`LinkedMediaPresentation`](../../../../../generated/storage/types.gen/type-aliases/LinkedMediaPresentation.md) \\| `undefined`; `size`: `number`; `state`: [`LinkedAttachmentState`](../../../../../generated/storage/types.gen/type-aliases/LinkedAttachmentState.md); `width`: `number` \\| `undefined`; \\}[]\\> | Attachment state and imported document handles. | - |\n| <a id=\"property-body\"></a> `body` | `readonly` | () => `Promise`\\<`string`\\> | Plain WhatsApp text. | - |\n| <a id=\"property-deleted\"></a> `deleted` | `readonly` | () => `Promise`\\<`boolean`\\> | Deleted for everyone. | - |\n| <a id=\"property-deliverystate\"></a> `deliveryState` | `readonly` | () => `Promise`\\<`NonNullable`\\<LinkedDeliveryState \\| null \\| undefined\\> \\| `undefined`\\> | Caller-owned send's delivery state, when present. | - |\n| <a id=\"property-editedat\"></a> `editedAt` | `readonly` | () => `Promise`\\<`string` \\| `undefined`\\> | Last edit time. | - |\n| <a id=\"property-forwarded\"></a> `forwarded` | `readonly` | () => `Promise`\\<`boolean`\\> | Forwarded from another chat. | - |\n| <a id=\"property-id\"></a> `id` | `public readonly` | `string` | - | [`MacroEntity`](../../../entity/classes/MacroEntity.md).[`id`](../../../entity/classes/MacroEntity.md#property-id) |\n| <a id=\"property-kind\"></a> `kind` | `readonly` | () => `Promise`\\<[`WhatsAppMessageKind`](../../../../../generated/storage/types.gen/type-aliases/WhatsAppMessageKind.md)\\> | `message`, or `system` for something that happened in the group (see `rich`). | - |\n| <a id=\"property-mentions\"></a> `mentions` | `readonly` | () => `Promise`\\<[`WhatsAppMention`](../../../../../generated/storage/types.gen/type-aliases/WhatsAppMention.md)[]\\> | People the body @-mentions: `@<token>` in the body is this person. | - |\n| <a id=\"property-reactions\"></a> `reactions` | `readonly` | () => `Promise`\\<[`WhatsAppGroupReaction`](../../../../../generated/storage/types.gen/type-aliases/WhatsAppGroupReaction.md)[]\\> | Grouped emoji counts and caller's own reaction. | - |\n| <a id=\"property-replyto\"></a> `replyTo` | `readonly` | () => `Promise`\\<`WhatsAppMessage` \\| `undefined`\\> | Quoted message in this group. | - |\n| <a id=\"property-rich\"></a> `rich` | `readonly` | () => `Promise`\\<`NonNullable`\\<WhatsAppRichContent \\| null \\| undefined\\> \\| `undefined`\\> | Poll (with tallies), location, contact cards, event or system line. | - |\n| <a id=\"property-sender\"></a> `sender` | `readonly` | () => `Promise`\\<[`WhatsAppGroupSender`](../../../../../generated/storage/types.gen/type-aliases/WhatsAppGroupSender.md)\\> | Protocol-verified sender association and display name. | - |\n| <a id=\"property-sentat\"></a> `sentAt` | `readonly` | () => `Promise`\\<`string`\\> | WhatsApp timestamp. | - |\n\n## Accessors\n\n### groupId\n\n#### Get Signature\n\n> **get** **groupId**(): `string`\n\nGroup identity for checking reply/mutation scope.\n\n##### Returns\n\n`string`\n\n## Methods\n\n### toJSON()\n\n> **toJSON**(): \\{ `detail?`: [`WhatsAppGroupMessage`](../../../../../generated/storage/types.gen/type-aliases/WhatsAppGroupMessage.md); `id`: `string`; \\}\n\n#### Returns\n\n\\{ `detail?`: [`WhatsAppGroupMessage`](../../../../../generated/storage/types.gen/type-aliases/WhatsAppGroupMessage.md); `id`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `detail?` | [`WhatsAppGroupMessage`](../../../../../generated/storage/types.gen/type-aliases/WhatsAppGroupMessage.md) |\n| `id` | `string` |\n\n#### Inherited from\n\n[`MacroEntity`](../../../entity/classes/MacroEntity.md).[`toJSON`](../../../entity/classes/MacroEntity.md#tojson)\n\n***\n\n### byId()\n\n> `static` **byId**(`client`, `group`, `id`): `WhatsAppMessage`\n\nReference a message within its original group.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `group` | [`WhatsAppGroup`](../../group/classes/WhatsAppGroup.md) |\n| `id` | `string` |\n\n#### Returns\n\n`WhatsAppMessage`\n\n***\n\n### from()\n\n> `static` **from**(`client`, `group`, `record`): `WhatsAppMessage`\n\nSeed a message handle from a timeline response.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `group` | [`WhatsAppGroup`](../../group/classes/WhatsAppGroup.md) |\n| `record` | [`WhatsAppGroupMessage`](../../../../../generated/storage/types.gen/type-aliases/WhatsAppGroupMessage.md) |\n\n#### Returns\n\n`WhatsAppMessage`\n\n\n<!-- src/entities/whatsapp/namespace/classes/WhatsAppNamespace.md -->\n# Class: WhatsAppNamespace\n\nOperate on an account already paired through the Macro app.\n\n## Constructors\n\n### Constructor\n\n> **new WhatsAppNamespace**(`client`): `WhatsAppNamespace`\n\nBind existing-account operations to this authenticated client.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n\n#### Returns\n\n`WhatsAppNamespace`\n\n## Methods\n\n### account()\n\n> **account**(): `Promise`\\<[`WhatsAppAccount`](../../account/classes/WhatsAppAccount.md) \\| `undefined`\\>\n\nCurrent owner's account, or undefined when no account has been connected.\n\n#### Returns\n\n`Promise`\\<[`WhatsAppAccount`](../../account/classes/WhatsAppAccount.md) \\| `undefined`\\>\n\n***\n\n### byId()\n\n> **byId**(`id`): [`WhatsAppGroup`](../../group/classes/WhatsAppGroup.md)\n\nReference an adopted entity without fetching it.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `id` | `string` |\n\n#### Returns\n\n[`WhatsAppGroup`](../../group/classes/WhatsAppGroup.md)\n\n***\n\n### groups()\n\n> **groups**(): `Promise`\\<[`WhatsAppGroup`](../../group/classes/WhatsAppGroup.md)[]\\>\n\nAdopted groups shared with the caller, including without WhatsApp.\n\n#### Returns\n\n`Promise`\\<[`WhatsAppGroup`](../../group/classes/WhatsAppGroup.md)[]\\>\n\n\n<!-- src/entities/whatsapp/send/classes/WhatsAppSend.md -->\n# Class: WhatsAppSend\n\nOne deliberate send intent. Unknown outcomes must never be automatically resent.\n\n## Extends\n\n- [`MacroEntity`](../../../entity/classes/MacroEntity.md)\\<[`LinkedSendProgress`](../../../../../generated/storage/types.gen/type-aliases/LinkedSendProgress.md)\\>\n\n## Properties\n\n| Property | Modifier | Type | Description | Inherited from |\n| ------ | ------ | ------ | ------ | ------ |\n| <a id=\"property-createdat\"></a> `createdAt` | `readonly` | () => `Promise`\\<`string`\\> | When the send intent was created. | - |\n| <a id=\"property-errorcode\"></a> `errorCode` | `readonly` | () => `Promise`\\<`string` \\| `undefined`\\> | Sanitized failure code, when present. | - |\n| <a id=\"property-group\"></a> `group` | `readonly` | [`WhatsAppGroup`](../../group/classes/WhatsAppGroup.md) | Group entity containing this send. | - |\n| <a id=\"property-id\"></a> `id` | `public readonly` | `string` | - | [`MacroEntity`](../../../entity/classes/MacroEntity.md).[`id`](../../../entity/classes/MacroEntity.md#property-id) |\n| <a id=\"property-message\"></a> `message` | `readonly` | () => `Promise`\\<[`WhatsAppMessage`](../../message/classes/WhatsAppMessage.md) \\| `undefined`\\> | Group message once WhatsApp accepted the send. | - |\n| <a id=\"property-state\"></a> `state` | `readonly` | () => `Promise`\\<[`LinkedDeliveryState`](../../../../../generated/storage/types.gen/type-aliases/LinkedDeliveryState.md)\\> | Last observed delivery state; refresh explicitly to poll again. | - |\n\n## Methods\n\n### refresh()\n\n> **refresh**(): `Promise`\\<`WhatsAppSend`\\>\n\nFetch current delivery state without retrying or submitting the message.\n\n#### Returns\n\n`Promise`\\<`WhatsAppSend`\\>\n\n***\n\n### request()\n\n> **request**(): `Promise`\\<\\{ `idempotencyKey`: `string`; `message`: [`WhatsAppReply`](../../group/type-aliases/WhatsAppReply.md); `replyTo?`: [`WhatsAppMessage`](../../message/classes/WhatsAppMessage.md); \\}\\>\n\nInspect the original intent for reconciliation; never resubmit an unknown outcome automatically.\n\n#### Returns\n\n`Promise`\\<\\{ `idempotencyKey`: `string`; `message`: [`WhatsAppReply`](../../group/type-aliases/WhatsAppReply.md); `replyTo?`: [`WhatsAppMessage`](../../message/classes/WhatsAppMessage.md); \\}\\>\n\n***\n\n### toJSON()\n\n> **toJSON**(): \\{ `detail?`: [`LinkedSendProgress`](../../../../../generated/storage/types.gen/type-aliases/LinkedSendProgress.md); `id`: `string`; \\}\n\n#### Returns\n\n\\{ `detail?`: [`LinkedSendProgress`](../../../../../generated/storage/types.gen/type-aliases/LinkedSendProgress.md); `id`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `detail?` | [`LinkedSendProgress`](../../../../../generated/storage/types.gen/type-aliases/LinkedSendProgress.md) |\n| `id` | `string` |\n\n#### Inherited from\n\n[`MacroEntity`](../../../entity/classes/MacroEntity.md).[`toJSON`](../../../entity/classes/MacroEntity.md#tojson)\n\n***\n\n### byId()\n\n> `static` **byId**(`client`, `group`, `id`): `WhatsAppSend`\n\nReference a send intent within its original group.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `group` | [`WhatsAppGroup`](../../group/classes/WhatsAppGroup.md) |\n| `id` | `string` |\n\n#### Returns\n\n`WhatsAppSend`\n\n***\n\n### from()\n\n> `static` **from**(`client`, `group`, `record`): `WhatsAppSend`\n\nSeed a send handle from a server response.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `group` | [`WhatsAppGroup`](../../group/classes/WhatsAppGroup.md) |\n| `record` | [`LinkedSendProgress`](../../../../../generated/storage/types.gen/type-aliases/LinkedSendProgress.md) |\n\n#### Returns\n\n`WhatsAppSend`\n\n\n<!-- src/entities/whatsapp/upload/classes/WhatsAppUpload.md -->\n# Class: WhatsAppUpload\n\nA staged attachment scoped to one adopted group; use it in a deliberate media send.\n\n## Properties\n\n| Property | Modifier | Type | Description |\n| ------ | ------ | ------ | ------ |\n| <a id=\"property-filename\"></a> `filename?` | `readonly` | `string` | Display filename supplied by the server. |\n| <a id=\"property-groupid\"></a> `groupId` | `readonly` | `string` | The group this upload can be sent to. |\n| <a id=\"property-id\"></a> `id` | `readonly` | `string` | Correlation identity of the staged upload. |\n| <a id=\"property-kind\"></a> `kind?` | `readonly` | [`LinkedMediaKind`](../../../../../generated/storage/types.gen/type-aliases/LinkedMediaKind.md) | Media category supplied by the server. |\n\n## Methods\n\n### toJSON()\n\n> **toJSON**(): \\{ `filename`: `string` \\| `undefined`; `groupId`: `string`; `id`: `string`; `kind`: [`LinkedMediaKind`](../../../../../generated/storage/types.gen/type-aliases/LinkedMediaKind.md) \\| `undefined`; \\}\n\nSerialize the upload reference without credentials.\n\n#### Returns\n\n\\{ `filename`: `string` \\| `undefined`; `groupId`: `string`; `id`: `string`; `kind`: [`LinkedMediaKind`](../../../../../generated/storage/types.gen/type-aliases/LinkedMediaKind.md) \\| `undefined`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `filename` | `string` \\| `undefined` |\n| `groupId` | `string` |\n| `id` | `string` |\n| `kind` | [`LinkedMediaKind`](../../../../../generated/storage/types.gen/type-aliases/LinkedMediaKind.md) \\| `undefined` |\n\n***\n\n### byId()\n\n> `static` **byId**(`group`, `id`): `WhatsAppUpload`\n\nReference a previously staged upload in its original group.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `group` | [`WhatsAppGroup`](../../group/classes/WhatsAppGroup.md) |\n| `id` | `string` |\n\n#### Returns\n\n`WhatsAppUpload`\n\n***\n\n### from()\n\n> `static` **from**(`group`, `record`): `WhatsAppUpload`\n\nSeed a handle from the server's upload receipt.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `group` | [`WhatsAppGroup`](../../group/classes/WhatsAppGroup.md) |\n| `record` | [`LinkedUploadedAttachment`](../../../../../generated/storage/types.gen/type-aliases/LinkedUploadedAttachment.md) |\n\n#### Returns\n\n`WhatsAppUpload`\n"+ "documentation": "# Macro SDK: channels\n\nGenerated by TypeDoc. Paths below refer to the canonical Markdown hierarchy. Other entity handles are documented in their named section; request core for shared SDK helpers.\n\n<!-- generated/properties/types.gen/type-aliases/BulkUpdateEntityPropertyOptionsResponse.md -->\n# Type Alias: BulkUpdateEntityPropertyOptionsResponse\n\n> **BulkUpdateEntityPropertyOptionsResponse** = \\{ `properties`: [`EntityPropertyOptionSelectionResponse`](EntityPropertyOptionSelectionResponse.md)[]; \\}\n\nResponse for a bulk option update: each property's reconciled final ids.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-properties\"></a> `properties` | [`EntityPropertyOptionSelectionResponse`](EntityPropertyOptionSelectionResponse.md)[] | The final option ids per updated property. |\n\n\n<!-- generated/properties/types.gen/type-aliases/DataType.md -->\n# Type Alias: DataType\n\n> **DataType** = `\"BOOLEAN\"` \\| `\"DATE\"` \\| `\"NUMBER\"` \\| `\"STRING\"` \\| `\"SELECT_NUMBER\"` \\| `\"SELECT_STRING\"` \\| `\"TAG\"` \\| `\"ENTITY\"` \\| `\"LINK\"`\n\nData type for property values, determining storage and validation.\n\n\n<!-- generated/properties/types.gen/type-aliases/EntityProperty.md -->\n# Type Alias: EntityProperty\n\n> **EntityProperty** = \\{ `created_at`: `string`; `entity_id`: `string`; `entity_type`: [`EntityType`](EntityType.md); `id`: `string`; `property_definition_id`: `string`; `updated_at`: `string`; \\}\n\nAssignment of a property definition to a specific entity (service representation).\n\n## Properties\n\n| Property | Type |\n| ------ | ------ |\n| <a id=\"property-created_at\"></a> `created_at` | `string` |\n| <a id=\"property-entity_id\"></a> `entity_id` | `string` |\n| <a id=\"property-entity_type\"></a> `entity_type` | [`EntityType`](EntityType.md) |\n| <a id=\"property-id\"></a> `id` | `string` |\n| <a id=\"property-property_definition_id\"></a> `property_definition_id` | `string` |\n| <a id=\"property-updated_at\"></a> `updated_at` | `string` |\n\n\n<!-- generated/properties/types.gen/type-aliases/EntityPropertyOptionSelectionResponse.md -->\n# Type Alias: EntityPropertyOptionSelectionResponse\n\n> **EntityPropertyOptionSelectionResponse** = \\{ `option_ids`: `string`[]; `property_id`: `string`; \\}\n\nThe reconciled final option ids stored for one property after a bulk update.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-option_ids\"></a> `option_ids` | `string`[] | The final option ids the server persisted, in stored order. |\n| <a id=\"property-property_id\"></a> `property_id` | `string` | The property definition the options belong to. |\n\n\n<!-- generated/properties/types.gen/type-aliases/EntityPropertyWithDefinition.md -->\n# Type Alias: EntityPropertyWithDefinition\n\n> **EntityPropertyWithDefinition** = \\{ `definition`: [`PropertyDefinition`](PropertyDefinition.md); `options?`: [`PropertyOption`](PropertyOption.md)[] \\| `null`; `property`: [`EntityProperty`](EntityProperty.md); `value?`: `null` \\| [`PropertyValue`](PropertyValue.md); \\}\n\nEntity property with its definition, value, and options (service representation).\n\n## Properties\n\n| Property | Type |\n| ------ | ------ |\n| <a id=\"property-definition\"></a> `definition` | [`PropertyDefinition`](PropertyDefinition.md) |\n| <a id=\"property-options\"></a> `options?` | [`PropertyOption`](PropertyOption.md)[] \\| `null` |\n| <a id=\"property-property\"></a> `property` | [`EntityProperty`](EntityProperty.md) |\n| <a id=\"property-value\"></a> `value?` | `null` \\| [`PropertyValue`](PropertyValue.md) |\n\n\n<!-- generated/properties/types.gen/type-aliases/EntityReference.md -->\n# Type Alias: EntityReference\n\n> **EntityReference** = \\{ `entity_id`: `string`; `entity_type`: [`EntityType`](EntityType.md); `specific_message_id?`: `string` \\| `null`; \\}\n\nEntity reference for entity-type property values.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-entity_id\"></a> `entity_id` | `string` | - |\n| <a id=\"property-entity_type\"></a> `entity_type` | [`EntityType`](EntityType.md) | - |\n| <a id=\"property-specific_message_id\"></a> `specific_message_id?` | `string` \\| `null` | For CHANNEL, CHAT, THREAD entity types - optional specific message ID. This allows referencing a specific message within a thread/channel/chat. |\n\n\n<!-- generated/properties/types.gen/type-aliases/EntityType.md -->\n# Type Alias: EntityType\n\n> **EntityType** = `\"CALENDAR_EVENT\"` \\| `\"CALL_RECORD\"` \\| `\"CHANNEL\"` \\| `\"CHAT\"` \\| `\"COMPANY\"` \\| `\"DATABASE_ROW\"` \\| `\"CONTACT\"` \\| `\"DOCUMENT\"` \\| `\"INITIATIVE\"` \\| `\"PROJECT\"` \\| `\"TASK\"` \\| `\"THREAD\"` \\| `\"USER\"`\n\nType of entity that can be referenced by entity properties.\n\n\n<!-- generated/properties/types.gen/type-aliases/PropertyDefinition.md -->\n# Type Alias: PropertyDefinition\n\n> **PropertyDefinition** = \\{ `created_at`: `string`; `data_type`: [`DataType`](DataType.md); `display_name`: `string`; `id`: `string`; `is_metadata`: `boolean`; `is_multi_select`: `boolean`; `is_system`: `boolean`; `owner`: [`PropertyOwner`](PropertyOwner.md); `specific_entity_type`: `null` \\| [`EntityType`](EntityType.md); `updated_at`: `string`; \\}\n\nProperty definition model (service representation).\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-created_at\"></a> `created_at` | `string` | - |\n| <a id=\"property-data_type\"></a> `data_type` | [`DataType`](DataType.md) | - |\n| <a id=\"property-display_name\"></a> `display_name` | `string` | - |\n| <a id=\"property-id\"></a> `id` | `string` | - |\n| <a id=\"property-is_metadata\"></a> `is_metadata` | `boolean` | Flag to indicate if this is a system-generated metadata property. Not stored in database - computed at service layer. |\n| <a id=\"property-is_multi_select\"></a> `is_multi_select` | `boolean` | - |\n| <a id=\"property-is_system\"></a> `is_system` | `boolean` | Flag to indicate if this is a system property (stored in DB). |\n| <a id=\"property-owner\"></a> `owner` | [`PropertyOwner`](PropertyOwner.md) | - |\n| <a id=\"property-specific_entity_type\"></a> `specific_entity_type` | `null` \\| [`EntityType`](EntityType.md) | - |\n| <a id=\"property-updated_at\"></a> `updated_at` | `string` | - |\n\n\n<!-- generated/properties/types.gen/type-aliases/PropertyOption.md -->\n# Type Alias: PropertyOption\n\n> **PropertyOption** = \\{ `color`: `string` \\| `null`; `created_at`: `string`; `display_order`: `number`; `id`: `string`; `property_definition_id`: `string`; `updated_at`: `string`; `value`: [`PropertyOptionValue`](PropertyOptionValue.md); \\}\n\nA selectable option for select-type properties (service representation).\n\n## Properties\n\n| Property | Type |\n| ------ | ------ |\n| <a id=\"property-color\"></a> `color` | `string` \\| `null` |\n| <a id=\"property-created_at\"></a> `created_at` | `string` |\n| <a id=\"property-display_order\"></a> `display_order` | `number` |\n| <a id=\"property-id\"></a> `id` | `string` |\n| <a id=\"property-property_definition_id\"></a> `property_definition_id` | `string` |\n| <a id=\"property-updated_at\"></a> `updated_at` | `string` |\n| <a id=\"property-value\"></a> `value` | [`PropertyOptionValue`](PropertyOptionValue.md) |\n\n\n<!-- generated/properties/types.gen/type-aliases/PropertyOptionValue.md -->\n# Type Alias: PropertyOptionValue\n\n> **PropertyOptionValue** = \\{ `type`: `\"string\"`; `value`: `string`; \\} \\| \\{ `type`: `\"number\"`; `value`: `number`; \\}\n\nThe value of a property option - either a string or a number.\n\n## Union Members\n\n### Type Literal\n\n\\{ `type`: `\"string\"`; `value`: `string`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `type` | `\"string\"` | - |\n| `value` | `string` | String value for SelectString properties |\n\n***\n\n### Type Literal\n\n\\{ `type`: `\"number\"`; `value`: `number`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `type` | `\"number\"` | - |\n| `value` | `number` | Number value for SelectNumber properties |\n\n\n<!-- generated/properties/types.gen/type-aliases/PropertyOwner.md -->\n# Type Alias: PropertyOwner\n\n> **PropertyOwner** = \\{ `scope`: `\"user\"`; `user_id`: `string`; \\} \\| \\{ `scope`: `\"team\"`; `team_id`: `string`; \\} \\| \\{ `database_id`: `string`; `scope`: `\"database\"`; \\} \\| \\{ `scope`: `\"system\"`; \\}\n\nDefines who owns a property - user-scoped, team-scoped, database-scoped, or system.\n\n\n<!-- generated/properties/types.gen/type-aliases/PropertyTargetEntityType.md -->\n# Type Alias: PropertyTargetEntityType\n\n> **PropertyTargetEntityType** = `\"CALL_RECORD\"` \\| `\"CHANNEL\"` \\| `\"CHAT\"` \\| `\"COMPANY\"` \\| `\"DATABASE_ROW\"` \\| `\"DOCUMENT\"` \\| `\"INITIATIVE\"` \\| `\"PROJECT\"` \\| `\"THREAD\"` \\| `\"USER\"`\n\nCanonical type of an entity receiving properties.\n\nTasks are documents at API boundaries. `Task` intentionally does not exist\nhere; task classification is resolved by the properties domain from the\ndocument subtype.\n\n\n<!-- generated/properties/types.gen/type-aliases/PropertyTargetReference.md -->\n# Type Alias: PropertyTargetReference\n\n> **PropertyTargetReference** = \\{ `entity_id`: `string`; `entity_type`: [`PropertyTargetEntityType`](PropertyTargetEntityType.md); \\}\n\nCanonical reference to an entity receiving properties.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-entity_id\"></a> `entity_id` | `string` | Entity identifier. |\n| <a id=\"property-entity_type\"></a> `entity_type` | [`PropertyTargetEntityType`](PropertyTargetEntityType.md) | Canonical entity type. |\n\n\n<!-- generated/properties/types.gen/type-aliases/PropertyValue.md -->\n# Type Alias: PropertyValue\n\n> **PropertyValue** = \\{ `type`: `\"Boolean\"`; `value`: `boolean`; \\} \\| \\{ `type`: `\"Number\"`; `value`: `number`; \\} \\| \\{ `type`: `\"String\"`; `value`: `string`; \\} \\| \\{ `type`: `\"Date\"`; `value`: `string`; \\} \\| \\{ `type`: `\"SelectOption\"`; `value`: `string`[]; \\} \\| \\{ `type`: `\"EntityReference\"`; `value`: [`EntityReference`](EntityReference.md)[]; \\} \\| \\{ `type`: `\"Link\"`; `value`: `string`[]; \\}\n\nProperty value (service representation).\n\nRepresents the actual value stored for an entity property.\nThis is serialized to/from JSONB in the database.\n\n## Union Members\n\n### Type Literal\n\n\\{ `type`: `\"Boolean\"`; `value`: `boolean`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `type` | `\"Boolean\"` | - |\n| `value` | `boolean` | Boolean value Serializes as: {\"type\": \"Boolean\", \"value\": true} |\n\n***\n\n### Type Literal\n\n\\{ `type`: `\"Number\"`; `value`: `number`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `type` | `\"Number\"` | - |\n| `value` | `number` | Numeric value Serializes as: {\"type\": \"Number\", \"value\": 42.5} |\n\n***\n\n### Type Literal\n\n\\{ `type`: `\"String\"`; `value`: `string`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `type` | `\"String\"` | - |\n| `value` | `string` | String value Serializes as: {\"type\": \"String\", \"value\": \"text\"} |\n\n***\n\n### Type Literal\n\n\\{ `type`: `\"Date\"`; `value`: `string`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `type` | `\"Date\"` | - |\n| `value` | `string` | Date/timestamp value Serializes as: {\"type\": \"Date\", \"value\": \"2025-01-01T00:00:00Z\"} |\n\n***\n\n### Type Literal\n\n\\{ `type`: `\"SelectOption\"`; `value`: `string`[]; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `type` | `\"SelectOption\"` | - |\n| `value` | `string`[] | Select option(s) - always an array (check is_multi_select to determine if single or multi) Single-select: {\"type\": \"SelectOption\", \"value\": [\"uuid\"]} (length 0 or 1) Multi-select: {\"type\": \"SelectOption\", \"value\": [\"uuid1\", \"uuid2\", ...]} (length 0+) |\n\n***\n\n### Type Literal\n\n\\{ `type`: `\"EntityReference\"`; `value`: [`EntityReference`](EntityReference.md)[]; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `type` | `\"EntityReference\"` | - |\n| `value` | [`EntityReference`](EntityReference.md)[] | Entity reference(s) - always an array (check is_multi_select to determine if single or multi) Single-select: {\"type\": \"EntityReference\", \"value\": [{...}]} (length 0 or 1) Multi-select: {\"type\": \"EntityReference\", \"value\": [{...}, {...}, ...]} (length 0+) |\n\n***\n\n### Type Literal\n\n\\{ `type`: `\"Link\"`; `value`: `string`[]; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `type` | `\"Link\"` | - |\n| `value` | `string`[] | Link value(s) - always an array (check is_multi_select to determine if single or multi) Single-select: {\"type\": \"Link\", \"value\": [\"https://example.com\"]} (length 0 or 1) Multi-select: {\"type\": \"Link\", \"value\": [\"https://example.com\", \"https://other.com\"]} (length 0+) |\n\n\n<!-- generated/properties/types.gen/type-aliases/SetPropertyValue.md -->\n# Type Alias: SetPropertyValue\n\n> **SetPropertyValue** = \\{ `type`: `\"boolean\"`; `value`: `boolean`; \\} \\| \\{ `type`: `\"date\"`; `value`: `string`; \\} \\| \\{ `type`: `\"number\"`; `value`: `number`; \\} \\| \\{ `type`: `\"string\"`; `value`: `string`; \\} \\| \\{ `option_id`: `string`; `type`: `\"select_option\"`; \\} \\| \\{ `option_ids`: `string`[]; `type`: `\"multi_select_option\"`; \\} \\| \\{ `reference`: [`EntityReference`](EntityReference.md); `type`: `\"entity_reference\"`; \\} \\| \\{ `references`: [`EntityReference`](EntityReference.md)[]; `type`: `\"multi_entity_reference\"`; \\} \\| \\{ `type`: `\"link\"`; `url`: `string`; \\} \\| \\{ `type`: `\"multi_link\"`; `urls`: `string`[]; \\}\n\nType-safe enum for setting entity property values - provides compile-time validation.\n\n\n<!-- generated/storage/types.gen/type-aliases/AccessLevel.md -->\n# Type Alias: AccessLevel\n\n> **AccessLevel** = `\"view\"` \\| `\"comment\"` \\| `\"edit\"` \\| `\"owner\"`\n\nOrdered from least to most access top -> bottom\n\n\n<!-- generated/storage/types.gen/type-aliases/ActivityType.md -->\n# Type Alias: ActivityType\n\n> **ActivityType** = `\"view\"` \\| `\"interact\"`\n\nThe kind of activity a user performs in a channel.\n\n\n<!-- generated/storage/types.gen/type-aliases/ApiActivity.md -->\n# Type Alias: ApiActivity\n\n> **ApiActivity** = \\{ `channel_id`: `string`; `created_at`: `string`; `id`: `string`; `interacted_at?`: `string` \\| `null`; `updated_at`: `string`; `user_id`: `string`; `viewed_at?`: `string` \\| `null`; \\}\n\nA user's activity (view/interaction) within a channel.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-channel_id\"></a> `channel_id` | `string` | Channel id. |\n| <a id=\"property-created_at\"></a> `created_at` | `string` | When the activity row was created. |\n| <a id=\"property-id\"></a> `id` | `string` | Activity id. |\n| <a id=\"property-interacted_at\"></a> `interacted_at?` | `string` \\| `null` | The last time the user interacted with the channel. |\n| <a id=\"property-updated_at\"></a> `updated_at` | `string` | When the activity row was last updated. |\n| <a id=\"property-user_id\"></a> `user_id` | `string` | User id. |\n| <a id=\"property-viewed_at\"></a> `viewed_at?` | `string` \\| `null` | The last time the user viewed the channel. |\n\n\n<!-- generated/storage/types.gen/type-aliases/ApiChannelAttachment.md -->\n# Type Alias: ApiChannelAttachment\n\n> **ApiChannelAttachment** = \\{ `channel_id`: `string`; `created_at`: `string`; `entity_id`: `string`; `entity_type`: `string`; `height?`: `number` \\| `null`; `id`: `string`; `message_id`: `string`; `sender_id`: `string`; `width?`: `number` \\| `null`; \\}\n\nA channel-level attachment.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-channel_id\"></a> `channel_id` | `string` | Channel id. |\n| <a id=\"property-created_at\"></a> `created_at` | `string` | When the attachment was created. |\n| <a id=\"property-entity_id\"></a> `entity_id` | `string` | Entity id. |\n| <a id=\"property-entity_type\"></a> `entity_type` | `string` | Type of entity. |\n| <a id=\"property-height\"></a> `height?` | `number` \\| `null` | Height (for images). |\n| <a id=\"property-id\"></a> `id` | `string` | Attachment id. |\n| <a id=\"property-message_id\"></a> `message_id` | `string` | Message id this attachment belongs to. |\n| <a id=\"property-sender_id\"></a> `sender_id` | `string` | The user who sent the message containing this attachment. |\n| <a id=\"property-width\"></a> `width?` | `number` \\| `null` | Width (for images). |\n\n\n<!-- generated/storage/types.gen/type-aliases/ApiChannelAttachmentsPage.md -->\n# Type Alias: ApiChannelAttachmentsPage\n\n> **ApiChannelAttachmentsPage** = \\{ `items`: [`ApiChannelAttachment`](ApiChannelAttachment.md)[]; `next_cursor?`: `string` \\| `null`; \\}\n\nPaginated response of channel attachments.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-items\"></a> `items` | [`ApiChannelAttachment`](ApiChannelAttachment.md)[] | Attachments on this page. |\n| <a id=\"property-next_cursor\"></a> `next_cursor?` | `string` \\| `null` | Cursor for the next page, null if no more pages. |\n\n\n<!-- generated/storage/types.gen/type-aliases/ApiChannelDetail.md -->\n# Type Alias: ApiChannelDetail\n\n> **ApiChannelDetail** = \\{ `channel_id`: `string`; `channel_name`: `string`; `channel_type`: [`ChannelType`](ChannelType.md); `participants`: [`ApiChannelParticipant`](ApiChannelParticipant.md)[]; \\}\n\nChannel detail: metadata and active participants.\n\nMessages are read through `/messages/channel/{channel_id}`.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-channel_id\"></a> `channel_id` | `string` | Channel id. |\n| <a id=\"property-channel_name\"></a> `channel_name` | `string` | Resolved display name from the viewer's perspective. |\n| <a id=\"property-channel_type\"></a> `channel_type` | [`ChannelType`](ChannelType.md) | Channel type. |\n| <a id=\"property-participants\"></a> `participants` | [`ApiChannelParticipant`](ApiChannelParticipant.md)[] | Active participants. |\n\n\n<!-- generated/storage/types.gen/type-aliases/ApiChannelParticipant.md -->\n# Type Alias: ApiChannelParticipant\n\n> **ApiChannelParticipant** = \\{ `channel_id`: `string`; `joined_at`: `string`; `role`: [`ApiParticipantRole`](ApiParticipantRole.md); `user_id`: `string`; \\}\n\nA channel participant.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-channel_id\"></a> `channel_id` | `string` | Channel id. |\n| <a id=\"property-joined_at\"></a> `joined_at` | `string` | When the user joined. |\n| <a id=\"property-role\"></a> `role` | [`ApiParticipantRole`](ApiParticipantRole.md) | Role in the channel. |\n| <a id=\"property-user_id\"></a> `user_id` | `string` | User id. |\n\n\n<!-- generated/storage/types.gen/type-aliases/ApiParticipantRole.md -->\n# Type Alias: ApiParticipantRole\n\n> **ApiParticipantRole** = `\"owner\"` \\| `\"admin\"` \\| `\"member\"`\n\nParticipant role in a channel.\n\n\n<!-- generated/storage/types.gen/type-aliases/BotSenderProfile.md -->\n# Type Alias: BotSenderProfile\n\n> **BotSenderProfile** = \\{ `avatar_url?`: `string` \\| `null`; `name`: `string`; \\}\n\nPublic bot profile attached to bot-authored messages.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-avatar_url\"></a> `avatar_url?` | `string` \\| `null` | Bot avatar URL. |\n| <a id=\"property-name\"></a> `name` | `string` | Bot display name. |\n\n\n<!-- generated/storage/types.gen/type-aliases/ChannelLabel.md -->\n# Type Alias: ChannelLabel\n\n> **ChannelLabel** = \\{ `channelCount`: `number`; `channelIds`: `string`[]; `createdAt`: `string`; `id`: `string`; `name`: `string`; `rule?`: `null` \\| [`ChannelLabelRule`](ChannelLabelRule.md); `sortOrder`: `number`; `teamId?`: `string` \\| `null`; `updatedAt`: `string`; \\}\n\nA shared or account-private label grouping chat channels in the sidebar.\n\n`channel_ids` is viewer-relative: it lists only the labelled channels the\nrequesting user participates in. `channel_count` counts every channel in\nthe label so clients can warn accurately before a delete.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-channelcount\"></a> `channelCount` | `number` | All assignments for a manual label; visible matches for a smart tag. |\n| <a id=\"property-channelids\"></a> `channelIds` | `string`[] | Channels in this label that the requesting user participates in. |\n| <a id=\"property-createdat\"></a> `createdAt` | `string` | When the label was created. |\n| <a id=\"property-id\"></a> `id` | `string` | Stable label id. |\n| <a id=\"property-name\"></a> `name` | `string` | Display name, unique within the scope (case-insensitive). |\n| <a id=\"property-rule\"></a> `rule?` | `null` \\| [`ChannelLabelRule`](ChannelLabelRule.md) | - |\n| <a id=\"property-sortorder\"></a> `sortOrder` | `number` | Manual ordering value within the scope; lower sorts first. |\n| <a id=\"property-teamid\"></a> `teamId?` | `string` \\| `null` | Owning team, or `None` for account-private labels. |\n| <a id=\"property-updatedat\"></a> `updatedAt` | `string` | When the label was last renamed or reordered. |\n\n\n<!-- generated/storage/types.gen/type-aliases/ChannelLabelRule.md -->\n# Type Alias: ChannelLabelRule\n\n> **ChannelLabelRule** = \\{ `attribute`: `\"name\"`; `contains`: `string`; \\}\n\nCase-insensitive, literal substring matching on the channel name.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-attribute\"></a> `attribute` | `\"name\"` | - |\n| <a id=\"property-contains\"></a> `contains` | `string` | The substring to find anywhere in the name. |\n\n\n<!-- generated/storage/types.gen/type-aliases/ChannelSharePermission.md -->\n# Type Alias: ChannelSharePermission\n\n> **ChannelSharePermission** = \\{ `access_level`: [`AccessLevel`](AccessLevel.md); `channel_id`: `string`; \\}\n\nThe channel share permission\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-access_level\"></a> `access_level` | [`AccessLevel`](AccessLevel.md) | The access level for the channel |\n| <a id=\"property-channel_id\"></a> `channel_id` | `string` | The channel id |\n\n\n<!-- generated/storage/types.gen/type-aliases/ChannelType.md -->\n# Type Alias: ChannelType\n\n> **ChannelType** = `\"public\"` \\| `\"private\"` \\| `\"direct_message\"` \\| `\"team\"`\n\nType of channel.\n\n\n<!-- generated/storage/types.gen/type-aliases/CountedReaction.md -->\n# Type Alias: CountedReaction\n\n> **CountedReaction** = \\{ `emoji`: `string`; `users`: `string`[]; \\}\n\nReaction emoji and the users who added it.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-emoji\"></a> `emoji` | `string` | Emoji being reacted with. |\n| <a id=\"property-users\"></a> `users` | `string`[] | User identifiers. |\n\n\n<!-- generated/storage/types.gen/type-aliases/DocumentId.md -->\n# Type Alias: DocumentId\n\n> **DocumentId** = `string`\n\nA validated document identifier. Historical document ids need not be UUIDs.\n\n\n<!-- generated/storage/types.gen/type-aliases/EntityPermission.md -->\n# Type Alias: EntityPermission\n\n> **EntityPermission** = \\{ `access_level`: [`AccessLevel`](AccessLevel.md); `type`: `\"access_level\"`; \\} \\| \\{ `type`: `\"channel_view_only\"`; \\} \\| \\{ `role`: [`ParticipantRole`](ParticipantRole.md); `type`: `\"channel_role\"`; \\} \\| \\{ `role`: [`TeamRole`](TeamRole.md); `type`: `\"team_role\"`; \\}\n\nA user's permission for an entity, discriminated by entity kind.\n\nItems (documents, chats, projects, threads) use access levels.\nChannels use view-only permission or participant roles.\n\n## Union Members\n\n### Type Literal\n\n\\{ `access_level`: [`AccessLevel`](AccessLevel.md); `type`: `\"access_level\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `access_level` | [`AccessLevel`](AccessLevel.md) | The access level the user has. |\n| `type` | `\"access_level\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `type`: `\"channel_view_only\"`; \\}\n\n***\n\n### Type Literal\n\n\\{ `role`: [`ParticipantRole`](ParticipantRole.md); `type`: `\"channel_role\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `role` | [`ParticipantRole`](ParticipantRole.md) | The role the user has in the channel. |\n| `type` | `\"channel_role\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `role`: [`TeamRole`](TeamRole.md); `type`: `\"team_role\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `role` | [`TeamRole`](TeamRole.md) | The role the user has in the team. |\n| `type` | `\"team_role\"` | - |\n\n\n<!-- generated/storage/types.gen/type-aliases/GetChannelAttachmentsResponses.md -->\n# Type Alias: GetChannelAttachmentsResponses\n\n> **GetChannelAttachmentsResponses** = \\{ `200`: [`ApiChannelAttachmentsPage`](ApiChannelAttachmentsPage.md); \\}\n\n## Properties\n\n| Property | Type |\n| ------ | ------ |\n| <a id=\"property-200\"></a> `200` | [`ApiChannelAttachmentsPage`](ApiChannelAttachmentsPage.md) |\n\n\n<!-- generated/storage/types.gen/type-aliases/GetChannelParticipantsResponses.md -->\n# Type Alias: GetChannelParticipantsResponses\n\n> **GetChannelParticipantsResponses** = \\{ `200`: [`ApiChannelParticipant`](ApiChannelParticipant.md)[]; \\}\n\n## Properties\n\n| Property | Type |\n| ------ | ------ |\n| <a id=\"property-200\"></a> `200` | [`ApiChannelParticipant`](ApiChannelParticipant.md)[] |\n\n\n<!-- generated/storage/types.gen/type-aliases/ImportedAuthor.md -->\n# Type Alias: ImportedAuthor\n\n> **ImportedAuthor** = \\{ `name`: `string`; \\}\n\nDisplay attribution for a comment imported from an external document.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-name\"></a> `name` | `string` | Original author text; never interpreted as an authenticated principal. |\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkShare.md -->\n# Type Alias: LinkShare\n\n> **LinkShare** = `\"PUBLIC\"` \\| `\"TEAM\"`\n\nDefines who can access an item through its share link.\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedAccount.md -->\n# Type Alias: LinkedAccount\n\n> **LinkedAccount** = \\{ `authorization_generation`: `number`; `id`: `string`; `identity_jid?`: `string` \\| `null`; `state`: [`LinkedAccountState`](LinkedAccountState.md); `user_id`: `string`; \\}\n\nOne person's account, never owned by a workspace.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-authorization_generation\"></a> `authorization_generation` | `number` | Explicit consent generation; reconnecting a socket never changes it. |\n| <a id=\"property-id\"></a> `id` | `string` | Stable account identity. |\n| <a id=\"property-identity_jid\"></a> `identity_jid?` | `string` \\| `null` | WhatsApp-verified identity, absent until the first pairing succeeds. |\n| <a id=\"property-state\"></a> `state` | [`LinkedAccountState`](LinkedAccountState.md) | Lifecycle. |\n| <a id=\"property-user_id\"></a> `user_id` | `string` | Authenticated owner. |\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedAccountState.md -->\n# Type Alias: LinkedAccountState\n\n> **LinkedAccountState** = `\"pairing\"` \\| `\"connected\"` \\| `\"logged_out\"` \\| `\"disconnected\"`\n\nAccount lifecycle. Transport outages are not stored: a connected account\nstays connected while its session service reconnects.\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedAttachment.md -->\n# Type Alias: LinkedAttachment\n\n> **LinkedAttachment** = \\{ `document_id?`: `string` \\| `null`; `duration_seconds?`: `number` \\| `null`; `file_name`: `string`; `height?`: `number` \\| `null`; `mime`: `string`; `ordinal`: `number`; `presentation?`: `null` \\| [`LinkedMediaPresentation`](LinkedMediaPresentation.md); `size`: `number`; `state`: [`LinkedAttachmentState`](LinkedAttachmentState.md); `width?`: `number` \\| `null`; \\}\n\nOne attachment of a linked message.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-document_id\"></a> `document_id?` | `string` \\| `null` | The private document, once ready. |\n| <a id=\"property-duration_seconds\"></a> `duration_seconds?` | `number` \\| `null` | Length of audio or video in whole seconds, when declared. |\n| <a id=\"property-file_name\"></a> `file_name` | `string` | Display filename. |\n| <a id=\"property-height\"></a> `height?` | `number` \\| `null` | Pixel height, when declared. |\n| <a id=\"property-mime\"></a> `mime` | `string` | Declared MIME type. |\n| <a id=\"property-ordinal\"></a> `ordinal` | `number` | Position within the message. |\n| <a id=\"property-presentation\"></a> `presentation?` | `null` \\| [`LinkedMediaPresentation`](LinkedMediaPresentation.md) | - |\n| <a id=\"property-size\"></a> `size` | `number` | Declared size in bytes. |\n| <a id=\"property-state\"></a> `state` | [`LinkedAttachmentState`](LinkedAttachmentState.md) | Current state. |\n| <a id=\"property-width\"></a> `width?` | `number` \\| `null` | Pixel width of an image, sticker or video, when WhatsApp declared it. |\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedAttachmentState.md -->\n# Type Alias: LinkedAttachmentState\n\n> **LinkedAttachmentState** = `\"loading\"` \\| `\"ready\"` \\| `\"unavailable\"` \\| `\"unsupported\"`\n\nWhere an attachment of a linked message stands.\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedBackfill.md -->\n# Type Alias: LinkedBackfill\n\n> **LinkedBackfill** = \\{ `imported`: `number`; `state`: [`LinkedBackfillState`](LinkedBackfillState.md); \\}\n\nEarlier messages imported after adding a group.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-imported\"></a> `imported` | `number` | Messages received from the phone so far (including ones already shown). |\n| <a id=\"property-state\"></a> `state` | [`LinkedBackfillState`](LinkedBackfillState.md) | Progress. |\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedBackfillState.md -->\n# Type Alias: LinkedBackfillState\n\n> **LinkedBackfillState** = `\"pending\"` \\| `\"running\"` \\| `\"waiting_for_phone\"` \\| `\"done\"` \\| `\"partial\"`\n\nWhere importing a group's earlier messages stands.\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedCannotAdd.md -->\n# Type Alias: LinkedCannotAdd\n\n> **LinkedCannotAdd** = `\"not_in_group\"` \\| `\"community\"` \\| `\"own_chat\"` \\| `\"not_in_chat_list\"`\n\nWhy a chat can't be added to Macro; the app words it from the code.\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedCapabilities.md -->\n# Type Alias: LinkedCapabilities\n\n> **LinkedCapabilities** = \\{ `attachment_limit_bytes`: `number`; `attachment_types`: `string`[]; `max_attachments`: `number`; `mutation_window_seconds`: `number`; `mutations`: [`LinkedMutation`](LinkedMutation.md)[]; `text_limit_bytes`: `number`; \\}\n\nOperations implemented for linked groups, independent of current permission.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-attachment_limit_bytes\"></a> `attachment_limit_bytes` | `number` | Largest attachment in bytes. |\n| <a id=\"property-attachment_types\"></a> `attachment_types` | `string`[] | Supported attachment MIME types. |\n| <a id=\"property-max_attachments\"></a> `max_attachments` | `number` | Attachments per send. |\n| <a id=\"property-mutation_window_seconds\"></a> `mutation_window_seconds` | `number` | Edits and deletes are offered this long after sending. |\n| <a id=\"property-mutations\"></a> `mutations` | [`LinkedMutation`](LinkedMutation.md)[] | Supported message operations. |\n| <a id=\"property-text_limit_bytes\"></a> `text_limit_bytes` | `number` | Maximum UTF-8 bytes per text send. |\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedChat.md -->\n# Type Alias: LinkedChat\n\n> **LinkedChat** = \\{ `archived`: `boolean`; `canAdd`: `boolean`; `cannotAddReason?`: `null` \\| [`LinkedCannotAdd`](LinkedCannotAdd.md); `community?`: `null` \\| [`LinkedCommunityReference`](LinkedCommunityReference.md); `group?`: `null` \\| [`LinkedGroupReference`](LinkedGroupReference.md); `jid`: `string`; `kind`: [`LinkedChatKind`](LinkedChatKind.md); `lastActivityAt?`: `string` \\| `null`; `name`: `string`; `pinned`: `boolean`; `shared?`: `null` \\| [`LinkedSharedGroupReference`](LinkedSharedGroupReference.md); \\}\n\nOne chat of the caller's WhatsApp chat list, as WhatsApp Web lists it.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-archived\"></a> `archived` | `boolean` | Archived in WhatsApp. |\n| <a id=\"property-canadd\"></a> `canAdd` | `boolean` | \"Add to Macro\" works now. |\n| <a id=\"property-cannotaddreason\"></a> `cannotAddReason?` | `null` \\| [`LinkedCannotAdd`](LinkedCannotAdd.md) | - |\n| <a id=\"property-community\"></a> `community?` | `null` \\| [`LinkedCommunityReference`](LinkedCommunityReference.md) | - |\n| <a id=\"property-group\"></a> `group?` | `null` \\| [`LinkedGroupReference`](LinkedGroupReference.md) | - |\n| <a id=\"property-jid\"></a> `jid` | `string` | WhatsApp chat JID: a group, or the other person's phone-number JID (LID when WhatsApp never told us the number). |\n| <a id=\"property-kind\"></a> `kind` | [`LinkedChatKind`](LinkedChatKind.md) | Group or direct chat. |\n| <a id=\"property-lastactivityat\"></a> `lastActivityAt?` | `string` \\| `null` | Newest activity WhatsApp reported (message or history sync); `null` when unknown. The list is sorted by it, newest first, unknown last. |\n| <a id=\"property-name\"></a> `name` | `string` | Group: the subject, or member names for an unnamed group. Direct: the contact or WhatsApp name, else `+<phone>`. Always non-empty. |\n| <a id=\"property-pinned\"></a> `pinned` | `boolean` | Pinned in WhatsApp. |\n| <a id=\"property-shared\"></a> `shared?` | `null` \\| [`LinkedSharedGroupReference`](LinkedSharedGroupReference.md) | - |\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedChatKind.md -->\n# Type Alias: LinkedChatKind\n\n> **LinkedChatKind** = `\"group\"` \\| `\"direct\"`\n\nWhether a WhatsApp chat is a group or a one-to-one chat.\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedCommunityReference.md -->\n# Type Alias: LinkedCommunityReference\n\n> **LinkedCommunityReference** = \\{ `announcements`: `boolean`; `id`: `string`; `name`: `string`; \\}\n\nThe WhatsApp community a group belongs to.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-announcements\"></a> `announcements` | `boolean` | This group is the community's announcement group. |\n| <a id=\"property-id\"></a> `id` | `string` | The community's WhatsApp JID. |\n| <a id=\"property-name\"></a> `name` | `string` | The community's name. |\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedDeliveryState.md -->\n# Type Alias: LinkedDeliveryState\n\n> **LinkedDeliveryState** = `\"pending\"` \\| `\"sending\"` \\| `\"unknown\"` \\| `\"accepted\"` \\| `\"sent\"` \\| `\"delivered\"` \\| `\"read\"` \\| `\"failed\"`\n\nObserved send state. `unknown` means the request may have reached WhatsApp;\nit is never sent again automatically.\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedGroupInfo.md -->\n# Type Alias: LinkedGroupInfo\n\n> **LinkedGroupInfo** = \\{ `announce`: `boolean`; `communityAnnouncements?`: `boolean`; `communityJid?`: `string` \\| `null`; `communityParent?`: `boolean`; `disappearingSeconds?`: `number` \\| `null`; `jid`: `string`; `name`: `string`; `observedAt`: `string`; `participants`: [`LinkedParticipant`](LinkedParticipant.md)[]; \\}\n\nOne full metadata read of a group, never an incomplete membership delta.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-announce\"></a> `announce` | `boolean` | Only admins may post. |\n| <a id=\"property-communityannouncements\"></a> `communityAnnouncements?` | `boolean` | The community's announcement group (everyone reads, admins post). |\n| <a id=\"property-communityjid\"></a> `communityJid?` | `string` \\| `null` | The community a linked subgroup or announcement group belongs to. |\n| <a id=\"property-communityparent\"></a> `communityParent?` | `boolean` | The community itself: it has no messages of its own and can't be added. |\n| <a id=\"property-disappearingseconds\"></a> `disappearingSeconds?` | `number` \\| `null` | Disappearing-messages timer in seconds while it is on. Macro keeps the messages; its sends carry the timer so phones treat them like their own. |\n| <a id=\"property-jid\"></a> `jid` | `string` | Remote group JID. |\n| <a id=\"property-name\"></a> `name` | `string` | Current subject. |\n| <a id=\"property-observedat\"></a> `observedAt` | `string` | When the session service read this metadata. |\n| <a id=\"property-participants\"></a> `participants` | [`LinkedParticipant`](LinkedParticipant.md)[] | Full roster. |\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedGroupReference.md -->\n# Type Alias: LinkedGroupReference\n\n> **LinkedGroupReference** = \\{ `id`: `string`; `name`: `string`; \\}\n\nA group entity bound to a remote group.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-id\"></a> `id` | `string` | Group entity id. |\n| <a id=\"property-name\"></a> `name` | `string` | Display name, following WhatsApp. |\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedIdentity.md -->\n# Type Alias: LinkedIdentity\n\n> **LinkedIdentity** = \\{ `alternateJid?`: `string` \\| `null`; `displayName?`: `string` \\| `null`; `jid`: `string`; \\}\n\nVerified sender aliases, supplied only by protocol metadata.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-alternatejid\"></a> `alternateJid?` | `string` \\| `null` | Verified alternate identity, never inferred from a name or phone typed by a user. |\n| <a id=\"property-displayname\"></a> `displayName?` | `string` \\| `null` | Untrusted display name. |\n| <a id=\"property-jid\"></a> `jid` | `string` | Phone-number or LID account JID. |\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedMediaKind.md -->\n# Type Alias: LinkedMediaKind\n\n> **LinkedMediaKind** = `\"image\"` \\| `\"audio\"` \\| `\"video\"` \\| `\"document\"`\n\nAttachment categories WhatsApp distinguishes.\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedMediaPresentation.md -->\n# Type Alias: LinkedMediaPresentation\n\n> **LinkedMediaPresentation** = `\"sticker\"` \\| `\"gif\"` \\| `\"voice_note\"`\n\nHow WhatsApp shows an attachment, when not as a plain file of its kind.\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedMutation.md -->\n# Type Alias: LinkedMutation\n\n> **LinkedMutation** = `\"reaction\"` \\| `\"edit\"` \\| `\"delete\"`\n\nDeliberate operations on an existing linked-group message.\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedParticipant.md -->\n# Type Alias: LinkedParticipant\n\n> **LinkedParticipant** = [`LinkedIdentity`](LinkedIdentity.md) & \\{ `admin`: `boolean`; \\}\n\nCurrent remote participant; Macro access is a separate grant.\n\n## Type Declaration\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `admin` | `boolean` | Group admin; only admins post in announcement groups. |\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedReplyBlock.md -->\n# Type Alias: LinkedReplyBlock\n\n> **LinkedReplyBlock** = `\"sending_disabled\"` \\| `\"no_account\"` \\| `\"disconnected\"` \\| `\"not_observing\"` \\| `\"not_allowed_in_group\"` \\| `\"group_unavailable\"`\n\nWhy the viewer cannot send now.\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedReplyContent.md -->\n# Type Alias: LinkedReplyContent\n\n> **LinkedReplyContent** = \\{ `mentions?`: `string`[]; `text`: `string`; `type`: `\"text\"`; \\} \\| \\{ `caption?`: `string` \\| `null`; `type`: `\"media\"`; `upload_id`: `string`; \\} \\| \\{ `message_id`: `string`; `operation`: [`LinkedMutation`](LinkedMutation.md); `text?`: `string` \\| `null`; `type`: `\"mutation\"`; \\}\n\nContent of a deliberate send.\n\n## Union Members\n\n### Type Literal\n\n\\{ `mentions?`: `string`[]; `text`: `string`; `type`: `\"text\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `mentions?` | `string`[] | Group participants the text @-mentions, by their WhatsApp id (`jid` of a roster participant); the text must contain `@<digits before the @ of the id>` for each. |\n| `text` | `string` | UTF-8 text, at most [`TEXT_LIMIT_BYTES`] bytes. |\n| `type` | `\"text\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `caption?`: `string` \\| `null`; `type`: `\"media\"`; `upload_id`: `string`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `caption?` | `string` \\| `null` | Optional caption; audio has none. |\n| `type` | `\"media\"` | - |\n| `upload_id` | `string` | The staged upload, which becomes the message's private document. |\n\n***\n\n### Type Literal\n\n\\{ `message_id`: `string`; `operation`: [`LinkedMutation`](LinkedMutation.md); `text?`: `string` \\| `null`; `type`: `\"mutation\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `message_id` | `string` | Existing group message, resolved to its WhatsApp source by the server. |\n| `operation` | [`LinkedMutation`](LinkedMutation.md) | Explicit operation. |\n| `text?` | `string` \\| `null` | Replacement text or emoji; absent for delete, empty to remove a reaction. |\n| `type` | `\"mutation\"` | - |\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedSendProgress.md -->\n# Type Alias: LinkedSendProgress\n\n> **LinkedSendProgress** = \\{ `created_at`: `string`; `error_code?`: `string` \\| `null`; `group_id`: `string`; `id`: `string`; `message_id?`: `string` \\| `null`; `payload`: [`LinkedSendReply`](LinkedSendReply.md); `state`: [`LinkedDeliveryState`](LinkedDeliveryState.md); `user_id`: `string`; \\}\n\nDurable result of a deliberate send.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-created_at\"></a> `created_at` | `string` | Intent creation time. |\n| <a id=\"property-error_code\"></a> `error_code?` | `string` \\| `null` | Sanitized failure code. |\n| <a id=\"property-group_id\"></a> `group_id` | `string` | Group entity. |\n| <a id=\"property-id\"></a> `id` | `string` | Stable intent id. |\n| <a id=\"property-message_id\"></a> `message_id?` | `string` \\| `null` | Group message, once WhatsApp accepted it. |\n| <a id=\"property-payload\"></a> `payload` | [`LinkedSendReply`](LinkedSendReply.md) | The original request, so a failed draft can be recovered. |\n| <a id=\"property-state\"></a> `state` | [`LinkedDeliveryState`](LinkedDeliveryState.md) | Current state. |\n| <a id=\"property-user_id\"></a> `user_id` | `string` | Person who submitted it. |\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedSendReply.md -->\n# Type Alias: LinkedSendReply\n\n> **LinkedSendReply** = \\{ `idempotency_key`: `string`; `message`: [`LinkedReplyContent`](LinkedReplyContent.md); `reply_to?`: `string` \\| `null`; \\}\n\nExplicit send action from a person. Only deliberate sends reach WhatsApp.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-idempotency_key\"></a> `idempotency_key` | `string` | Stable client intent key. A changed payload with this key is a conflict. |\n| <a id=\"property-message\"></a> `message` | [`LinkedReplyContent`](LinkedReplyContent.md) | Content. |\n| <a id=\"property-reply_to\"></a> `reply_to?` | `string` \\| `null` | Group message being quoted, within this group. |\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedSharedGroupReference.md -->\n# Type Alias: LinkedSharedGroupReference\n\n> **LinkedSharedGroupReference** = \\{ `id`: `string`; `name`: `string`; `ownerId`: `string`; \\}\n\nAnother person's group entity the caller can view.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-id\"></a> `id` | `string` | Group entity id. |\n| <a id=\"property-name\"></a> `name` | `string` | Display name, following WhatsApp. |\n| <a id=\"property-ownerid\"></a> `ownerId` | `string` | Macro user who added the group and shared it. |\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedUploadedAttachment.md -->\n# Type Alias: LinkedUploadedAttachment\n\n> **LinkedUploadedAttachment** = \\{ `filename`: `string`; `kind`: [`LinkedMediaKind`](LinkedMediaKind.md); `upload_id`: `string`; \\}\n\nA staged attachment, sent only by a later deliberate send.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-filename\"></a> `filename` | `string` | Display filename. |\n| <a id=\"property-kind\"></a> `kind` | [`LinkedMediaKind`](LinkedMediaKind.md) | Category. |\n| <a id=\"property-upload_id\"></a> `upload_id` | `string` | Use as `upload_id` in a media send; also the future document id. |\n\n\n<!-- generated/storage/types.gen/type-aliases/Message.md -->\n# Type Alias: Message\n\n> **Message** = \\{ `attachments`: [`MessageAttachment`](MessageAttachment.md)[]; `bot_profile?`: `null` \\| [`BotSenderProfile`](BotSenderProfile.md); `content`: `string`; `created_at`: `string`; `deleted_at?`: `string` \\| `null`; `edited_at?`: `string` \\| `null`; `guest_name?`: `string` \\| `null`; `id`: `string`; `imported_author?`: `null` \\| [`ImportedAuthor`](ImportedAuthor.md); `mentions`: [`SimpleMention`](SimpleMention.md)[]; `parent`: [`MessageParent`](MessageParent.md); `reactions`: [`CountedReaction`](CountedReaction.md)[]; `sender_id`: `string`; `thread_id?`: `string` \\| `null`; `triggered_by?`: `string` \\| `null`; `updated_at`: `string`; \\}\n\nShared message representation for channel timelines and entity discussions.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-attachments\"></a> `attachments` | [`MessageAttachment`](MessageAttachment.md)[] | Attached entities. |\n| <a id=\"property-bot_profile\"></a> `bot_profile?` | `null` \\| [`BotSenderProfile`](BotSenderProfile.md) | - |\n| <a id=\"property-content\"></a> `content` | `string` | Macro Markdown body. |\n| <a id=\"property-created_at\"></a> `created_at` | `string` | Creation time. |\n| <a id=\"property-deleted_at\"></a> `deleted_at?` | `string` \\| `null` | Message tombstone, independent of thread deletion. |\n| <a id=\"property-edited_at\"></a> `edited_at?` | `string` \\| `null` | Last content edit, if any. |\n| <a id=\"property-guest_name\"></a> `guest_name?` | `string` \\| `null` | Display name of a verified call guest, retained after the call ends. |\n| <a id=\"property-id\"></a> `id` | `string` | Message UUID. |\n| <a id=\"property-imported_author\"></a> `imported_author?` | `null` \\| [`ImportedAuthor`](ImportedAuthor.md) | - |\n| <a id=\"property-mentions\"></a> `mentions` | [`SimpleMention`](SimpleMention.md)[] | Tracked mentions, retained when a caller changes attachments only. |\n| <a id=\"property-parent\"></a> `parent` | [`MessageParent`](MessageParent.md) | Entity that owns this conversation. |\n| <a id=\"property-reactions\"></a> `reactions` | [`CountedReaction`](CountedReaction.md)[] | Aggregated reactions. |\n| <a id=\"property-sender_id\"></a> `sender_id` | `string` | Authenticated actor or owner of imported content. |\n| <a id=\"property-thread_id\"></a> `thread_id?` | `string` \\| `null` | Root message UUID for replies; absent on roots. |\n| <a id=\"property-triggered_by\"></a> `triggered_by?` | `string` \\| `null` | User who triggered a bot-authored message. |\n| <a id=\"property-updated_at\"></a> `updated_at` | `string` | Last persisted update. |\n\n\n<!-- generated/storage/types.gen/type-aliases/MessageAttachment.md -->\n# Type Alias: MessageAttachment\n\n> **MessageAttachment** = \\{ `created_at`: `string`; `entity_id`: `string`; `entity_type`: `string`; `height?`: `number` \\| `null`; `id`: `string`; `width?`: `number` \\| `null`; \\}\n\nAn entity attached to a message.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-created_at\"></a> `created_at` | `string` | When the attachment was added. |\n| <a id=\"property-entity_id\"></a> `entity_id` | `string` | Attached entity identifier. |\n| <a id=\"property-entity_type\"></a> `entity_type` | `string` | Attached entity type. |\n| <a id=\"property-height\"></a> `height?` | `number` \\| `null` | Optional media height. |\n| <a id=\"property-id\"></a> `id` | `string` | Attachment UUID. |\n| <a id=\"property-width\"></a> `width?` | `number` \\| `null` | Optional media width. |\n\n\n<!-- generated/storage/types.gen/type-aliases/MessageCursor.md -->\n# Type Alias: MessageCursor\n\n> **MessageCursor** = \\{ `created_at`: `string`; `id`: `string`; \\}\n\nCursor for a chronological parent timeline.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-created_at\"></a> `created_at` | `string` | Last message creation time or activity occurrence time. |\n| <a id=\"property-id\"></a> `id` | `string` | Last entry UUID, used to break timestamp ties across both sources. |\n\n\n<!-- generated/storage/types.gen/type-aliases/MessageParent.md -->\n# Type Alias: MessageParent\n\n> **MessageParent** = \\{ `id`: `string`; `type`: `\"channel\"`; \\} \\| \\{ `id`: [`DocumentId`](DocumentId.md); `type`: `\"document\"`; \\} \\| \\{ `id`: `string`; `type`: `\"initiative\"`; \\} \\| \\{ `id`: `string`; `type`: `\"crm_company\"`; \\} \\| \\{ `id`: `string`; `type`: `\"crm_contact\"`; \\} \\| \\{ `id`: `string`; `type`: `\"call\"`; \\}\n\nThe entity whose permissions and lifecycle govern a message.\n\n## Union Members\n\n### Type Literal\n\n\\{ `id`: `string`; `type`: `\"channel\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `id` | `string` | A channel, including direct messages. |\n| `type` | `\"channel\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `id`: [`DocumentId`](DocumentId.md); `type`: `\"document\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `id` | [`DocumentId`](DocumentId.md) | A document, including tasks and PDFs. |\n| `type` | `\"document\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `id`: `string`; `type`: `\"initiative\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `id` | `string` | An initiative, presented as a project in the application. |\n| `type` | `\"initiative\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `id`: `string`; `type`: `\"crm_company\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `id` | `string` | A CRM company. |\n| `type` | `\"crm_company\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `id`: `string`; `type`: `\"crm_contact\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `id` | `string` | A CRM contact. |\n| `type` | `\"crm_contact\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `id`: `string`; `type`: `\"call\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `id` | `string` | A video call and its persistent chat thread. |\n| `type` | `\"call\"` | - |\n\n\n<!-- generated/storage/types.gen/type-aliases/ParticipantRole.md -->\n# Type Alias: ParticipantRole\n\n> **ParticipantRole** = `\"owner\"` \\| `\"admin\"` \\| `\"member\"`\n\nThe role a user has within a channel.\n\n\n<!-- generated/storage/types.gen/type-aliases/SharePermissionV2.md -->\n# Type Alias: SharePermissionV2\n\n> **SharePermissionV2** = \\{ `channelSharePermissions?`: [`ChannelSharePermission`](ChannelSharePermission.md)[] \\| `null`; `id`: `string`; `linkShare?`: `null` \\| [`LinkShare`](LinkShare.md); `linkShareAccessLevel?`: `null` \\| [`AccessLevel`](AccessLevel.md); `owner`: `string`; `teamShareAccessLevel?`: `null` \\| [`AccessLevel`](AccessLevel.md); \\}\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-channelsharepermissions\"></a> `channelSharePermissions?` | [`ChannelSharePermission`](ChannelSharePermission.md)[] \\| `null` | The channel share permissions for the item |\n| <a id=\"property-id\"></a> `id` | `string` | The share permission id |\n| <a id=\"property-linkshare\"></a> `linkShare?` | `null` \\| [`LinkShare`](LinkShare.md) | - |\n| <a id=\"property-linkshareaccesslevel\"></a> `linkShareAccessLevel?` | `null` \\| [`AccessLevel`](AccessLevel.md) | - |\n| <a id=\"property-owner\"></a> `owner` | `string` | The owner of the item |\n| <a id=\"property-teamshareaccesslevel\"></a> `teamShareAccessLevel?` | `null` \\| [`AccessLevel`](AccessLevel.md) | - |\n\n\n<!-- generated/storage/types.gen/type-aliases/SimpleMention.md -->\n# Type Alias: SimpleMention\n\n> **SimpleMention** = \\{ `entity_id`: `string`; `entity_type`: `string`; \\}\n\nA mention tracked in a message body.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-entity_id\"></a> `entity_id` | `string` | Mentioned entity identifier. |\n| <a id=\"property-entity_type\"></a> `entity_type` | `string` | Mentioned entity type. |\n\n\n<!-- generated/storage/types.gen/type-aliases/SmartTagChannelMatch.md -->\n# Type Alias: SmartTagChannelMatch\n\n> **SmartTagChannelMatch** = \\{ `id`: `string`; `name`: `string`; \\}\n\nA channel visible to the caller that matches a smart tag rule.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-id\"></a> `id` | `string` | Channel id. |\n| <a id=\"property-name\"></a> `name` | `string` | Channel display name. |\n\n\n<!-- generated/storage/types.gen/type-aliases/SmartTagPreview.md -->\n# Type Alias: SmartTagPreview\n\n> **SmartTagPreview** = \\{ `channels`: [`SmartTagChannelMatch`](SmartTagChannelMatch.md)[]; `totalCount`: `number`; \\}\n\nA bounded preview and the total number of visible channels matching a rule.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-channels\"></a> `channels` | [`SmartTagChannelMatch`](SmartTagChannelMatch.md)[] | First matches, in alphabetical order. |\n| <a id=\"property-totalcount\"></a> `totalCount` | `number` | Number of matching channels the caller participates in, including overflow. |\n\n\n<!-- generated/storage/types.gen/type-aliases/TeamRole.md -->\n# Type Alias: TeamRole\n\n> **TeamRole** = `\"member\"` \\| `\"admin\"` \\| `\"owner\"`\n\nThe role a user has within a team.\n\nOrdered least to most privileged so comparisons reflect access strength.\n\n\n<!-- generated/storage/types.gen/type-aliases/UpdateChannelSharePermission.md -->\n# Type Alias: UpdateChannelSharePermission\n\n> **UpdateChannelSharePermission** = \\{ `accessLevel?`: `null` \\| [`AccessLevel`](AccessLevel.md); `channelId`: `string`; `operation`: [`UpdateOperation`](UpdateOperation.md); \\}\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-accesslevel\"></a> `accessLevel?` | `null` \\| [`AccessLevel`](AccessLevel.md) | - |\n| <a id=\"property-channelid\"></a> `channelId` | `string` | The channel id |\n| <a id=\"property-operation\"></a> `operation` | [`UpdateOperation`](UpdateOperation.md) | The type of operation to be performed on the chanel share permission You can add, remove or replace and existing permission |\n\n\n<!-- generated/storage/types.gen/type-aliases/UpdateOperation.md -->\n# Type Alias: UpdateOperation\n\n> **UpdateOperation** = `\"add\"` \\| `\"remove\"` \\| `\"replace\"`\n\n\n<!-- generated/storage/types.gen/type-aliases/UpdateSharePermissionRequestV2.md -->\n# Type Alias: UpdateSharePermissionRequestV2\n\n> **UpdateSharePermissionRequestV2** = \\{ `channelSharePermissions?`: [`UpdateChannelSharePermission`](UpdateChannelSharePermission.md)[] \\| `null`; `linkShare?`: `null` \\| [`LinkShare`](LinkShare.md); `linkShareAccessLevel?`: `null` \\| [`AccessLevel`](AccessLevel.md); `teamShareAccessLevel?`: `null` \\| [`AccessLevel`](AccessLevel.md); \\}\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-channelsharepermissions\"></a> `channelSharePermissions?` | [`UpdateChannelSharePermission`](UpdateChannelSharePermission.md)[] \\| `null` | Any channel share permissions to be created/updated/removed |\n| <a id=\"property-linkshare\"></a> `linkShare?` | `null` \\| [`LinkShare`](LinkShare.md) | - |\n| <a id=\"property-linkshareaccesslevel\"></a> `linkShareAccessLevel?` | `null` \\| [`AccessLevel`](AccessLevel.md) | - |\n| <a id=\"property-teamshareaccesslevel\"></a> `teamShareAccessLevel?` | `null` \\| [`AccessLevel`](AccessLevel.md) | - |\n\n\n<!-- generated/storage/types.gen/type-aliases/WhatsAppCall.md -->\n# Type Alias: WhatsAppCall\n\n> **WhatsAppCall** = \\{ `durationSeconds?`: `number` \\| `null`; `outcome`: [`WhatsAppCallOutcome`](WhatsAppCallOutcome.md); `video`: `boolean`; \\}\n\nA call in the group.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-durationseconds\"></a> `durationSeconds?` | `number` \\| `null` | Length, when it connected. |\n| <a id=\"property-outcome\"></a> `outcome` | [`WhatsAppCallOutcome`](WhatsAppCallOutcome.md) | How it went for the account that saw it. |\n| <a id=\"property-video\"></a> `video` | `boolean` | Video rather than voice. |\n\n\n<!-- generated/storage/types.gen/type-aliases/WhatsAppCallOutcome.md -->\n# Type Alias: WhatsAppCallOutcome\n\n> **WhatsAppCallOutcome** = `\"answered\"` \\| `\"missed\"` \\| `\"rejected\"` \\| `\"other\"`\n\nHow a call went.\n\n\n<!-- generated/storage/types.gen/type-aliases/WhatsAppContactCard.md -->\n# Type Alias: WhatsAppContactCard\n\n> **WhatsAppContactCard** = \\{ `name`: `string`; `phones`: `string`[]; \\}\n\nOne contact card, from its vCard.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-name\"></a> `name` | `string` | Display name. |\n| <a id=\"property-phones\"></a> `phones` | `string`[] | Phone numbers as written on the card. |\n\n\n<!-- generated/storage/types.gen/type-aliases/WhatsAppContacts.md -->\n# Type Alias: WhatsAppContacts\n\n> **WhatsAppContacts** = \\{ `contacts`: [`WhatsAppContactCard`](WhatsAppContactCard.md)[]; \\}\n\nContact cards.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-contacts\"></a> `contacts` | [`WhatsAppContactCard`](WhatsAppContactCard.md)[] | The cards, in order. |\n\n\n<!-- generated/storage/types.gen/type-aliases/WhatsAppEvent.md -->\n# Type Alias: WhatsAppEvent\n\n> **WhatsAppEvent** = \\{ `canceled?`: `boolean`; `description?`: `string` \\| `null`; `endAt?`: `string` \\| `null`; `joinLink?`: `string` \\| `null`; `location?`: `string` \\| `null`; `name`: `string`; `startAt?`: `string` \\| `null`; \\}\n\nA WhatsApp event.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-canceled\"></a> `canceled?` | `boolean` | Canceled by its organizer. |\n| <a id=\"property-description\"></a> `description?` | `string` \\| `null` | Description. |\n| <a id=\"property-endat\"></a> `endAt?` | `string` \\| `null` | End. |\n| <a id=\"property-joinlink\"></a> `joinLink?` | `string` \\| `null` | Call link for an online event. |\n| <a id=\"property-location\"></a> `location?` | `string` \\| `null` | Place name or address. |\n| <a id=\"property-name\"></a> `name` | `string` | Title. |\n| <a id=\"property-startat\"></a> `startAt?` | `string` \\| `null` | Start. |\n\n\n<!-- generated/storage/types.gen/type-aliases/WhatsAppGroupDetail.md -->\n# Type Alias: WhatsAppGroupDetail\n\n> **WhatsAppGroupDetail** = [`WhatsAppGroupSummary`](WhatsAppGroupSummary.md) & \\{ `access_level`: [`AccessLevel`](AccessLevel.md); `community?`: `null` \\| [`LinkedCommunityReference`](LinkedCommunityReference.md); `disappearing_seconds?`: `number` \\| `null`; `limits`: [`LinkedCapabilities`](LinkedCapabilities.md); `roster?`: `null` \\| [`LinkedGroupInfo`](LinkedGroupInfo.md); `sending_identity?`: `string` \\| `null`; `share_permission`: [`SharePermissionV2`](SharePermissionV2.md); \\}\n\nFull group detail and current viewer capabilities.\n\n## Type Declaration\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `access_level` | [`AccessLevel`](AccessLevel.md) | Caller's effective permission. |\n| `community?` | `null` \\| [`LinkedCommunityReference`](LinkedCommunityReference.md) | - |\n| `disappearing_seconds?` | `number` \\| `null` | WhatsApp's disappearing-messages timer in seconds while it is on; Macro keeps the messages anyway. `null` when off or unknown. |\n| `limits` | [`LinkedCapabilities`](LinkedCapabilities.md) | Size and mutation limits. |\n| `roster?` | `null` \\| [`LinkedGroupInfo`](LinkedGroupInfo.md) | - |\n| `sending_identity?` | `string` \\| `null` | Caller's own phone identity, never another account's identity. |\n| `share_permission` | [`SharePermissionV2`](SharePermissionV2.md) | Owner-controlled standard sharing configuration. |\n\n\n<!-- generated/storage/types.gen/type-aliases/WhatsAppGroupMessage.md -->\n# Type Alias: WhatsAppGroupMessage\n\n> **WhatsAppGroupMessage** = \\{ `attachments`: [`LinkedAttachment`](LinkedAttachment.md)[]; `body`: `string`; `deleted`: `boolean`; `delivery_state?`: `null` \\| [`LinkedDeliveryState`](LinkedDeliveryState.md); `edited_at?`: `string` \\| `null`; `forwarded`: `boolean`; `id`: `string`; `kind`: [`WhatsAppMessageKind`](WhatsAppMessageKind.md); `mentions`: [`WhatsAppMention`](WhatsAppMention.md)[]; `reactions`: [`WhatsAppGroupReaction`](WhatsAppGroupReaction.md)[]; `received_at`: `string`; `reply_to?`: `string` \\| `null`; `rich?`: `null` \\| [`WhatsAppRichContent`](WhatsAppRichContent.md); `sender`: [`WhatsAppGroupSender`](WhatsAppGroupSender.md); `sent_at`: `string`; `view_once`: `boolean`; \\}\n\nOne message in an adopted group.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-attachments\"></a> `attachments` | [`LinkedAttachment`](LinkedAttachment.md)[] | Imported or pending attachments. |\n| <a id=\"property-body\"></a> `body` | `string` | Plain WhatsApp text. |\n| <a id=\"property-deleted\"></a> `deleted` | `boolean` | Deleted for everyone. |\n| <a id=\"property-delivery_state\"></a> `delivery_state?` | `null` \\| [`LinkedDeliveryState`](LinkedDeliveryState.md) | - |\n| <a id=\"property-edited_at\"></a> `edited_at?` | `string` \\| `null` | Last edit timestamp. |\n| <a id=\"property-forwarded\"></a> `forwarded` | `boolean` | Forwarded from another chat. |\n| <a id=\"property-id\"></a> `id` | `string` | Stable message id. |\n| <a id=\"property-kind\"></a> `kind` | [`WhatsAppMessageKind`](WhatsAppMessageKind.md) | A message, or a system line. |\n| <a id=\"property-mentions\"></a> `mentions` | [`WhatsAppMention`](WhatsAppMention.md)[] | People the body @-mentions. |\n| <a id=\"property-reactions\"></a> `reactions` | [`WhatsAppGroupReaction`](WhatsAppGroupReaction.md)[] | Reactions grouped by emoji. |\n| <a id=\"property-received_at\"></a> `received_at` | `string` | Timestamp first received by Macro. |\n| <a id=\"property-reply_to\"></a> `reply_to?` | `string` \\| `null` | Message quoted by this one. |\n| <a id=\"property-rich\"></a> `rich?` | `null` \\| [`WhatsAppRichContent`](WhatsAppRichContent.md) | - |\n| <a id=\"property-sender\"></a> `sender` | [`WhatsAppGroupSender`](WhatsAppGroupSender.md) | Sender. |\n| <a id=\"property-sent_at\"></a> `sent_at` | `string` | Timestamp assigned by WhatsApp. |\n| <a id=\"property-view_once\"></a> `view_once` | `boolean` | Sent as view-once in WhatsApp; Macro shows it like any media. |\n\n\n<!-- generated/storage/types.gen/type-aliases/WhatsAppGroupReaction.md -->\n# Type Alias: WhatsAppGroupReaction\n\n> **WhatsAppGroupReaction** = \\{ `count`: `number`; `emoji`: `string`; `mine`: `boolean`; \\}\n\nGrouped reactions.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-count\"></a> `count` | `number` | Number of reacting people. |\n| <a id=\"property-emoji\"></a> `emoji` | `string` | Emoji. |\n| <a id=\"property-mine\"></a> `mine` | `boolean` | Caller has this reaction. |\n\n\n<!-- generated/storage/types.gen/type-aliases/WhatsAppGroupSender.md -->\n# Type Alias: WhatsAppGroupSender\n\n> **WhatsAppGroupSender** = \\{ `name`: `string`; `person_id`: `string`; `user_id?`: `string` \\| `null`; \\}\n\nMessage sender from protocol-verified identity evidence.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-name\"></a> `name` | `string` | Display name, never authentication evidence. |\n| <a id=\"property-person_id\"></a> `person_id` | `string` | External person identity. |\n| <a id=\"property-user_id\"></a> `user_id?` | `string` \\| `null` | Verified Macro user association, if present. |\n\n\n<!-- generated/storage/types.gen/type-aliases/WhatsAppGroupSummary.md -->\n# Type Alias: WhatsAppGroupSummary\n\n> **WhatsAppGroupSummary** = \\{ `backfill?`: `null` \\| [`LinkedBackfill`](LinkedBackfill.md); `can_send`: `boolean`; `id`: `string`; `kind`: [`LinkedChatKind`](LinkedChatKind.md); `last_message_at?`: `string` \\| `null`; `name`: `string`; `send_reason?`: `null` \\| [`LinkedReplyBlock`](LinkedReplyBlock.md); `unread_count`: `number`; `user_id`: `string`; \\}\n\nAdopted group visible through ordinary entity sharing.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-backfill\"></a> `backfill?` | `null` \\| [`LinkedBackfill`](LinkedBackfill.md) | - |\n| <a id=\"property-can_send\"></a> `can_send` | `boolean` | Caller may currently send from their own account. |\n| <a id=\"property-id\"></a> `id` | `string` | Entity identifier. |\n| <a id=\"property-kind\"></a> `kind` | [`LinkedChatKind`](LinkedChatKind.md) | A group, or a direct chat with one person (only its owner sends). |\n| <a id=\"property-last_message_at\"></a> `last_message_at?` | `string` \\| `null` | Latest message timestamp. |\n| <a id=\"property-name\"></a> `name` | `string` | Display name: the group's, or a direct chat's other person. |\n| <a id=\"property-send_reason\"></a> `send_reason?` | `null` \\| [`LinkedReplyBlock`](LinkedReplyBlock.md) | - |\n| <a id=\"property-unread_count\"></a> `unread_count` | `number` | Unread live messages for this viewer. |\n| <a id=\"property-user_id\"></a> `user_id` | `string` | Actual entity owner. |\n\n\n<!-- generated/storage/types.gen/type-aliases/WhatsAppLocation.md -->\n# Type Alias: WhatsAppLocation\n\n> **WhatsAppLocation** = \\{ `address?`: `string` \\| `null`; `comment?`: `string` \\| `null`; `latitude`: `number`; `live?`: `boolean`; `longitude`: `number`; `name?`: `string` \\| `null`; `url?`: `string` \\| `null`; \\}\n\nA shared place.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-address\"></a> `address?` | `string` \\| `null` | Street address. |\n| <a id=\"property-comment\"></a> `comment?` | `string` \\| `null` | Caption or comment. |\n| <a id=\"property-latitude\"></a> `latitude` | `number` | Degrees. |\n| <a id=\"property-live\"></a> `live?` | `boolean` | Shared as a live location (this is where it started). |\n| <a id=\"property-longitude\"></a> `longitude` | `number` | Degrees. |\n| <a id=\"property-name\"></a> `name?` | `string` \\| `null` | Place name. |\n| <a id=\"property-url\"></a> `url?` | `string` \\| `null` | Link the sender attached. |\n\n\n<!-- generated/storage/types.gen/type-aliases/WhatsAppMention.md -->\n# Type Alias: WhatsAppMention\n\n> **WhatsAppMention** = [`WhatsAppPersonRef`](WhatsAppPersonRef.md) & \\{ `token`: `string`; \\}\n\nAn @-mention in a message body.\n\n## Type Declaration\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `token` | `string` | What follows the `@` in the body (the digits of the person's WhatsApp id); replace `@<token>` with the name. |\n\n\n<!-- generated/storage/types.gen/type-aliases/WhatsAppMessageKind.md -->\n# Type Alias: WhatsAppMessageKind\n\n> **WhatsAppMessageKind** = `\"message\"` \\| `\"system\"`\n\nWhat a timeline entry is.\n\n\n<!-- generated/storage/types.gen/type-aliases/WhatsAppPersonRef.md -->\n# Type Alias: WhatsAppPersonRef\n\n> **WhatsAppPersonRef** = \\{ `name`: `string`; `userId?`: `string` \\| `null`; \\}\n\nA person named in a message: a Macro user when verified, else their\nWhatsApp name, else their phone number.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-name\"></a> `name` | `string` | Display name, never authentication evidence. |\n| <a id=\"property-userid\"></a> `userId?` | `string` \\| `null` | Verified Macro user, if any. |\n\n\n<!-- generated/storage/types.gen/type-aliases/WhatsAppPoll.md -->\n# Type Alias: WhatsAppPoll\n\n> **WhatsAppPoll** = \\{ `options`: [`WhatsAppPollOption`](WhatsAppPollOption.md)[]; `question`: `string`; `selectableCount`: `number`; `voters`: `number`; \\}\n\nA poll, read-only in Macro.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-options\"></a> `options` | [`WhatsAppPollOption`](WhatsAppPollOption.md)[] | Options in order, with tallies. |\n| <a id=\"property-question\"></a> `question` | `string` | The question. |\n| <a id=\"property-selectablecount\"></a> `selectableCount` | `number` | How many options one person may choose; 0 means any number. |\n| <a id=\"property-voters\"></a> `voters` | `number` | People who voted for anything. |\n\n\n<!-- generated/storage/types.gen/type-aliases/WhatsAppPollOption.md -->\n# Type Alias: WhatsAppPollOption\n\n> **WhatsAppPollOption** = \\{ `mine`: `boolean`; `name`: `string`; `voters`: [`WhatsAppPersonRef`](WhatsAppPersonRef.md)[]; `votes`: `number`; \\}\n\nOne option of a poll with its votes.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-mine\"></a> `mine` | `boolean` | The caller chose it. |\n| <a id=\"property-name\"></a> `name` | `string` | Option text. |\n| <a id=\"property-voters\"></a> `voters` | [`WhatsAppPersonRef`](WhatsAppPersonRef.md)[] | Who chose it. |\n| <a id=\"property-votes\"></a> `votes` | `number` | People who chose it. |\n\n\n<!-- generated/storage/types.gen/type-aliases/WhatsAppRichContent.md -->\n# Type Alias: WhatsAppRichContent\n\n> **WhatsAppRichContent** = [`WhatsAppPoll`](WhatsAppPoll.md) & \\{ `type`: `\"poll\"`; \\} \\| [`WhatsAppLocation`](WhatsAppLocation.md) & \\{ `type`: `\"location\"`; \\} \\| [`WhatsAppContacts`](WhatsAppContacts.md) & \\{ `type`: `\"contacts\"`; \\} \\| [`WhatsAppEvent`](WhatsAppEvent.md) & \\{ `type`: `\"event\"`; \\} \\| [`WhatsAppSystemLine`](WhatsAppSystemLine.md) & \\{ `type`: `\"system\"`; \\}\n\nStructured content of a message besides its body.\n\n\n<!-- generated/storage/types.gen/type-aliases/WhatsAppSystemAction.md -->\n# Type Alias: WhatsAppSystemAction\n\n> **WhatsAppSystemAction** = `\"group_created\"` \\| `\"participants_added\"` \\| `\"participants_removed\"` \\| `\"participants_left\"` \\| `\"participants_joined\"` \\| `\"participants_promoted\"` \\| `\"participants_demoted\"` \\| `\"subject_changed\"` \\| `\"icon_changed\"` \\| `\"description_changed\"` \\| `\"disappearing_changed\"` \\| `\"message_pinned\"` \\| `\"message_unpinned\"` \\| `\"call\"`\n\nKinds of system lines.\n\n\n<!-- generated/storage/types.gen/type-aliases/WhatsAppSystemLine.md -->\n# Type Alias: WhatsAppSystemLine\n\n> **WhatsAppSystemLine** = \\{ `action`: [`WhatsAppSystemAction`](WhatsAppSystemAction.md); `actor?`: `null` \\| [`WhatsAppPersonRef`](WhatsAppPersonRef.md); `call?`: `null` \\| [`WhatsAppCall`](WhatsAppCall.md); `participants`: [`WhatsAppPersonRef`](WhatsAppPersonRef.md)[]; `value?`: `string` \\| `null`; \\}\n\nSomething that happened in the group.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-action\"></a> `action` | [`WhatsAppSystemAction`](WhatsAppSystemAction.md) | What happened. |\n| <a id=\"property-actor\"></a> `actor?` | `null` \\| [`WhatsAppPersonRef`](WhatsAppPersonRef.md) | - |\n| <a id=\"property-call\"></a> `call?` | `null` \\| [`WhatsAppCall`](WhatsAppCall.md) | - |\n| <a id=\"property-participants\"></a> `participants` | [`WhatsAppPersonRef`](WhatsAppPersonRef.md)[] | Who it happened to (added, removed, promoted, …). |\n| <a id=\"property-value\"></a> `value?` | `string` \\| `null` | New subject or description; disappearing-messages timer in seconds (`\"0\"` is off). |\n\n\n<!-- src/entities/channels/activity/classes/ChannelActivity.md -->\n# Class: ChannelActivity\n\nA user's channel activity marker.\n\n## Constructors\n\n### Constructor\n\n> **new ChannelActivity**(`client`, `channel`, `record`): `ChannelActivity`\n\n#### Parameters\n\n| Parameter | Type | Description |\n| ------ | ------ | ------ |\n| `client` | `MacroClient` | - |\n| `channel` | [`Channel`](../../channel/classes/Channel.md) | Related channel. |\n| `record` | [`ApiActivity`](../../../../../generated/storage/types.gen/type-aliases/ApiActivity.md) | - |\n\n#### Returns\n\n`ChannelActivity`\n\n## Properties\n\n| Property | Modifier | Type | Description |\n| ------ | ------ | ------ | ------ |\n| <a id=\"property-channel\"></a> `channel` | `readonly` | [`Channel`](../../channel/classes/Channel.md) | Related channel. |\n\n## Accessors\n\n### id\n\n#### Get Signature\n\n> **get** **id**(): `string`\n\nActivity identity.\n\n##### Returns\n\n`string`\n\n## Methods\n\n### createdAt()\n\n> **createdAt**(): `string`\n\nCreation time.\n\n#### Returns\n\n`string`\n\n***\n\n### recordInteraction()\n\n> **recordInteraction**(`type`): `Promise`\\<`ChannelActivity`\\>\n\nRecord a view or interaction in this channel.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `type` | [`ActivityType`](../../../../../generated/storage/types.gen/type-aliases/ActivityType.md) |\n\n#### Returns\n\n`Promise`\\<`ChannelActivity`\\>\n\n***\n\n### toJSON()\n\n> **toJSON**(): [`ApiActivity`](../../../../../generated/storage/types.gen/type-aliases/ApiActivity.md)\n\nSerialize activity without credentials.\n\n#### Returns\n\n[`ApiActivity`](../../../../../generated/storage/types.gen/type-aliases/ApiActivity.md)\n\n***\n\n### user()\n\n> **user**(): [`User`](../../../users/user/classes/User.md)\n\nUser who interacted.\n\n#### Returns\n\n[`User`](../../../users/user/classes/User.md)\n\n\n<!-- src/entities/channels/channel/classes/Channel.md -->\n# Class: Channel\n\nA channel.\n\n## Extends\n\n- [`PropertiedEntity`](../../../entity/classes/PropertiedEntity.md)\\<`ChannelDetail`\\>\n\n## Properties\n\n| Property | Modifier | Type | Default value | Description | Overrides | Inherited from |\n| ------ | ------ | ------ | ------ | ------ | ------ | ------ |\n| <a id=\"property-entitytype\"></a> `entityType` | `readonly` | `\"channel\"` | `'channel'` | Favorites identify channels as `channel`. | [`PropertiedEntity`](../../../entity/classes/PropertiedEntity.md).[`entityType`](../../../entity/classes/PropertiedEntity.md#property-entitytype) | - |\n| <a id=\"property-id\"></a> `id` | `public readonly` | `string` | `undefined` | - | - | [`PropertiedEntity`](../../../entity/classes/PropertiedEntity.md).[`id`](../../../entity/classes/PropertiedEntity.md#property-id) |\n| <a id=\"property-name\"></a> `name` | `readonly` | () => `Promise`\\<`string`\\> | `...` | The channel's display name, resolved from the viewer's perspective. | - | - |\n| <a id=\"property-type\"></a> `type` | `readonly` | () => `Promise`\\<[`ChannelType`](../../../../../generated/storage/types.gen/type-aliases/ChannelType.md)\\> | `...` | The channel's type (e.g. `public`, `dm`, `private`). | - | - |\n| <a id=\"property-search\"></a> `search` | `static` | (`client`, `query`, `searchOpts?`) => `AsyncGenerator`\\<`Channel`\\> | `...` | Search channels by content, most relevant first, auto-paginated. | - | - |\n\n## Methods\n\n### addParticipants()\n\n> **addParticipants**(`users`): `Promise`\\<`void`\\>\n\nAdd users to the channel.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `users` | [`User`](../../../users/user/classes/User.md)[] |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### agentConversations()\n\n> **agentConversations**(): `Promise`\\<[`AgentConversation`](../../../agent-sessions/conversation/classes/AgentConversation.md)[]\\>\n\nConversations maintained by agents in this channel.\n\n#### Returns\n\n`Promise`\\<[`AgentConversation`](../../../agent-sessions/conversation/classes/AgentConversation.md)[]\\>\n\n***\n\n### attachments()\n\n> **attachments**(`opts?`): `AsyncGenerator`\\<[`ApiChannelAttachment`](../../../../../generated/storage/types.gen/type-aliases/ApiChannelAttachment.md)\\>\n\nThe attachments posted in this channel, auto-paginated.\n\n#### Parameters\n\n| Parameter | Type | Description |\n| ------ | ------ | ------ |\n| `opts?` | \\{ `pageSize?`: `number`; `type?`: `string`; \\} | - |\n| `opts.pageSize?` | `number` | - |\n| `opts.type?` | `string` | Filter by type: `static` for images/videos, `dss` for documents. |\n\n#### Returns\n\n`AsyncGenerator`\\<[`ApiChannelAttachment`](../../../../../generated/storage/types.gen/type-aliases/ApiChannelAttachment.md)\\>\n\n***\n\n### delete()\n\n> **delete**(): `Promise`\\<`void`\\>\n\nDelete the channel. This is not reversible.\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### deleteProperty()\n\n> **deleteProperty**(`assignment`): `Promise`\\<`void`\\>\n\nRemove a property from this entity, given its [properties](#properties) entry.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `assignment` | [`EntityPropertyWithDefinition`](../../../../../generated/properties/types.gen/type-aliases/EntityPropertyWithDefinition.md) |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n#### Inherited from\n\n[`PropertiedEntity`](../../../entity/classes/PropertiedEntity.md).[`deleteProperty`](../../../entity/classes/PropertiedEntity.md#deleteproperty)\n\n***\n\n### favorite()\n\n> **favorite**(): `Promise`\\<`Channel`\\>\n\nAdd this entity to the user's favorites. Returns this handle for chaining.\nPlain unwrap: favoriting alters the user's favorites collection, not this\nentity's own detail, so there's nothing cached to invalidate.\n\n#### Returns\n\n`Promise`\\<`Channel`\\>\n\n#### Inherited from\n\n[`PropertiedEntity`](../../../entity/classes/PropertiedEntity.md).[`favorite`](../../../entity/classes/PropertiedEntity.md#favorite)\n\n***\n\n### join()\n\n> **join**(): `Promise`\\<`void`\\>\n\nJoin the channel as the current user.\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### joinCode()\n\n> **joinCode**(): `Promise`\\<`string`\\>\n\nA reusable code that lets a user join this channel.\n\n#### Returns\n\n`Promise`\\<`string`\\>\n\n***\n\n### leave()\n\n> **leave**(): `Promise`\\<`void`\\>\n\nLeave the channel as the current user.\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### message()\n\n> **message**(`id`): [`Message`](../../message/classes/Message.md)\n\nA handle to a message in this channel by id.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `id` | `string` |\n\n#### Returns\n\n[`Message`](../../message/classes/Message.md)\n\n***\n\n### messages()\n\n> **messages**(`opts?`): `AsyncGenerator`\\<[`Message`](../../message/classes/Message.md)\\>\n\nRoot messages in this channel, most recent first, auto-paginated.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `opts?` | \\{ `pageSize?`: `number`; \\} |\n| `opts.pageSize?` | `number` |\n\n#### Returns\n\n`AsyncGenerator`\\<[`Message`](../../message/classes/Message.md)\\>\n\n***\n\n### messagesAfter()\n\n> **messagesAfter**(`after`, `opts?`): `AsyncGenerator`\\<[`Message`](../../message/classes/Message.md)\\>\n\nRoot messages created or replied to at or after `after`, most recent\nfirst, auto-paginated. Use it to catch up after a disconnect.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `after` | `string` \\| `Date` |\n| `opts?` | \\{ `pageSize?`: `number`; \\} |\n| `opts.pageSize?` | `number` |\n\n#### Returns\n\n`AsyncGenerator`\\<[`Message`](../../message/classes/Message.md)\\>\n\n***\n\n### messageThreadById()\n\n> **messageThreadById**(`id`): [`MessageThread`](../../../messages/thread/classes/MessageThread.md)\n\nA shared message thread scoped to this resource.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `id` | `string` |\n\n#### Returns\n\n[`MessageThread`](../../../messages/thread/classes/MessageThread.md)\n\n***\n\n### participants()\n\n> **participants**(): `Promise`\\<[`ApiChannelParticipant`](../../../../../generated/storage/types.gen/type-aliases/ApiChannelParticipant.md)[]\\>\n\nThe channel's members, with their roles and join times.\n\n#### Returns\n\n`Promise`\\<[`ApiChannelParticipant`](../../../../../generated/storage/types.gen/type-aliases/ApiChannelParticipant.md)[]\\>\n\n***\n\n### permission()\n\n> **permission**(): `Promise`\\<\\{ `permission`: [`EntityPermission`](../../../../../generated/storage/types.gen/type-aliases/EntityPermission.md); `status`: `\"access\"`; \\} \\| \\{ `status`: `\"no_access\"`; \\}\\>\n\nRead the caller's effective permission on this entity.\n\n#### Returns\n\n`Promise`\\<\\{ `permission`: [`EntityPermission`](../../../../../generated/storage/types.gen/type-aliases/EntityPermission.md); `status`: `\"access\"`; \\} \\| \\{ `status`: `\"no_access\"`; \\}\\>\n\n#### Inherited from\n\n[`PropertiedEntity`](../../../entity/classes/PropertiedEntity.md).[`permission`](../../../entity/classes/PropertiedEntity.md#permission)\n\n***\n\n### properties()\n\n> **properties**(`opts?`): `Promise`\\<[`EntityPropertyWithDefinition`](../../../../../generated/properties/types.gen/type-aliases/EntityPropertyWithDefinition.md)[]\\>\n\nThe properties set on this entity, each with its definition, value, and options.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `opts?` | \\{ `includeMetadata?`: `boolean`; \\} |\n| `opts.includeMetadata?` | `boolean` |\n\n#### Returns\n\n`Promise`\\<[`EntityPropertyWithDefinition`](../../../../../generated/properties/types.gen/type-aliases/EntityPropertyWithDefinition.md)[]\\>\n\n#### Inherited from\n\n[`PropertiedEntity`](../../../entity/classes/PropertiedEntity.md).[`properties`](../../../entity/classes/PropertiedEntity.md#properties)\n\n***\n\n### propertyReference()\n\n> **propertyReference**(): [`PropertyTargetReference`](../../../../../generated/properties/types.gen/type-aliases/PropertyTargetReference.md)\n\nThis entity's reference for bulk property operations.\n\n#### Returns\n\n[`PropertyTargetReference`](../../../../../generated/properties/types.gen/type-aliases/PropertyTargetReference.md)\n\n#### Inherited from\n\n[`PropertiedEntity`](../../../entity/classes/PropertiedEntity.md).[`propertyReference`](../../../entity/classes/PropertiedEntity.md#propertyreference)\n\n***\n\n### recordActivity()\n\n> **recordActivity**(`type`): `Promise`\\<[`ChannelActivity`](../../activity/classes/ChannelActivity.md)\\>\n\nRecord a view or interaction in this channel.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `type` | [`ActivityType`](../../../../../generated/storage/types.gen/type-aliases/ActivityType.md) |\n\n#### Returns\n\n`Promise`\\<[`ChannelActivity`](../../activity/classes/ChannelActivity.md)\\>\n\n***\n\n### removeParticipants()\n\n> **removeParticipants**(`users`): `Promise`\\<`void`\\>\n\nRemove users from the channel.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `users` | [`User`](../../../users/user/classes/User.md)[] |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### rename()\n\n> **rename**(`name`): `Promise`\\<`void`\\>\n\nRename the channel.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `name` | `string` |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### send()\n\n> **send**(`body`, `opts?`): `Promise`\\<[`Message`](../../message/classes/Message.md)\\>\n\nPost a message. Plain text, or a rich body composed with `msg`.\n\nWorks with a channel webhook token as well as a normal one — see\n[postToChannel](../../post/functions/postToChannel.md) for which endpoint that picks and what it costs.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `body` | `string` \\| [`RichMessage`](../../../../mentions/interfaces/RichMessage.md) |\n| `opts?` | \\{ `thread?`: [`Thread`](../../thread/classes/Thread.md); \\} |\n| `opts.thread?` | [`Thread`](../../thread/classes/Thread.md) |\n\n#### Returns\n\n`Promise`\\<[`Message`](../../message/classes/Message.md)\\>\n\n***\n\n### setPicture()\n\n> **setPicture**(`picture?`): `Promise`\\<`void`\\>\n\nSet an uploaded profile picture, or clear it.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `picture?` | [`ChannelPicture`](../../picture/classes/ChannelPicture.md) |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### setProperty()\n\n> **setProperty**(`property`, `value?`): `Promise`\\<`void`\\>\n\nSet a property value on this entity, or attach the property without a\nvalue when `value` is omitted.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `property` | [`PropertyDefinition`](../../../properties/property-definition/classes/PropertyDefinition.md) |\n| `value?` | [`SetPropertyValue`](../../../../../generated/properties/types.gen/type-aliases/SetPropertyValue.md) |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n#### Inherited from\n\n[`PropertiedEntity`](../../../entity/classes/PropertiedEntity.md).[`setProperty`](../../../entity/classes/PropertiedEntity.md#setproperty)\n\n***\n\n### timelinePage()\n\n> **timelinePage**(`selection?`): `Promise`\\<\\{ `entries`: (\\{ `activity`: \\{ `action`: `string`; `actor`: [`User`](../../../users/user/classes/User.md); `actor_id`: `string`; `id`: `string`; `occurred_at`: `string`; `payload?`: `unknown`; \\}; `message?`: `undefined`; `type`: `\"activity\"`; \\} \\| \\{ `activity?`: `undefined`; `message`: [`Message`](../../message/classes/Message.md); `type`: `\"message\"`; \\})[]; `nextCursor`: [`MessageCursor`](../../../../../generated/storage/types.gen/type-aliases/MessageCursor.md) \\| `undefined`; `previousCursor`: [`MessageCursor`](../../../../../generated/storage/types.gen/type-aliases/MessageCursor.md) \\| `undefined`; \\}\\>\n\nA mixed message and activity timeline page.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `selection?` | [`TimelineOptions`](../../../messages/thread/interfaces/TimelineOptions.md)\\<[`Message`](../../message/classes/Message.md)\\> |\n\n#### Returns\n\n`Promise`\\<\\{ `entries`: (\\{ `activity`: \\{ `action`: `string`; `actor`: [`User`](../../../users/user/classes/User.md); `actor_id`: `string`; `id`: `string`; `occurred_at`: `string`; `payload?`: `unknown`; \\}; `message?`: `undefined`; `type`: `\"activity\"`; \\} \\| \\{ `activity?`: `undefined`; `message`: [`Message`](../../message/classes/Message.md); `type`: `\"message\"`; \\})[]; `nextCursor`: [`MessageCursor`](../../../../../generated/storage/types.gen/type-aliases/MessageCursor.md) \\| `undefined`; `previousCursor`: [`MessageCursor`](../../../../../generated/storage/types.gen/type-aliases/MessageCursor.md) \\| `undefined`; \\}\\>\n\n***\n\n### toJSON()\n\n> **toJSON**(): \\{ `detail?`: [`ApiChannelDetail`](../../../../../generated/storage/types.gen/type-aliases/ApiChannelDetail.md); `id`: `string`; \\}\n\n#### Returns\n\n\\{ `detail?`: [`ApiChannelDetail`](../../../../../generated/storage/types.gen/type-aliases/ApiChannelDetail.md); `id`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `detail?` | [`ApiChannelDetail`](../../../../../generated/storage/types.gen/type-aliases/ApiChannelDetail.md) |\n| `id` | `string` |\n\n#### Inherited from\n\n[`PropertiedEntity`](../../../entity/classes/PropertiedEntity.md).[`toJSON`](../../../entity/classes/PropertiedEntity.md#tojson)\n\n***\n\n### typing()\n\n> **typing**(`action`, `opts?`): `Promise`\\<`void`\\>\n\nBroadcast a typing indicator, optionally scoped to a thread.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `action` | `\"stop\"` \\| `\"start\"` |\n| `opts?` | \\{ `thread?`: [`Thread`](../../thread/classes/Thread.md); \\} |\n| `opts.thread?` | [`Thread`](../../thread/classes/Thread.md) |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### unfavorite()\n\n> **unfavorite**(): `Promise`\\<`Channel`\\>\n\nRemove this entity from the user's favorites. Returns this handle for chaining.\n\n#### Returns\n\n`Promise`\\<`Channel`\\>\n\n#### Inherited from\n\n[`PropertiedEntity`](../../../entity/classes/PropertiedEntity.md).[`unfavorite`](../../../entity/classes/PropertiedEntity.md#unfavorite)\n\n***\n\n### updatePropertyOptions()\n\n> **updatePropertyOptions**(`changes`): `Promise`\\<[`BulkUpdateEntityPropertyOptionsResponse`](../../../../../generated/properties/types.gen/type-aliases/BulkUpdateEntityPropertyOptionsResponse.md)\\>\n\nApply multi-select option deltas atomically across this entity's properties.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `changes` | [`PropertyOptionDelta`](../../../entity/interfaces/PropertyOptionDelta.md)[] |\n\n#### Returns\n\n`Promise`\\<[`BulkUpdateEntityPropertyOptionsResponse`](../../../../../generated/properties/types.gen/type-aliases/BulkUpdateEntityPropertyOptionsResponse.md)\\>\n\n#### Inherited from\n\n[`PropertiedEntity`](../../../entity/classes/PropertiedEntity.md).[`updatePropertyOptions`](../../../entity/classes/PropertiedEntity.md#updatepropertyoptions)\n\n***\n\n### webUrl()\n\n> **webUrl**(): `string`\n\nThe channel's URL in the Macro web app.\n\n#### Returns\n\n`string`\n\n***\n\n### byId()\n\n> `static` **byId**(`client`, `id`): `Channel`\n\nA handle to a channel 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`Channel`\n\n***\n\n### create()\n\n> `static` **create**(`client`, `opts`): `Promise`\\<`Channel`\\>\n\nCreate a channel. The caller becomes the owner.\n\n#### Parameters\n\n| Parameter | Type | Description |\n| ------ | ------ | ------ |\n| `client` | `MacroClient` | - |\n| `opts` | \\{ `name?`: `string`; `participants?`: [`User`](../../../users/user/classes/User.md)[]; `team?`: [`Team`](../../../teams/team/classes/Team.md); `type`: [`ChannelType`](../../../../../generated/storage/types.gen/type-aliases/ChannelType.md); \\} | - |\n| `opts.name?` | `string` | - |\n| `opts.participants?` | [`User`](../../../users/user/classes/User.md)[] | Participants to add, excluding the owner. |\n| `opts.team?` | [`Team`](../../../teams/team/classes/Team.md) | Team, for team channels. |\n| `opts.type` | [`ChannelType`](../../../../../generated/storage/types.gen/type-aliases/ChannelType.md) | - |\n\n#### Returns\n\n`Promise`\\<`Channel`\\>\n\n***\n\n### dm()\n\n> `static` **dm**(`client`, `recipient`): `Promise`\\<`Channel`\\>\n\nOpen (creating if needed) the DM channel with a user.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `recipient` | [`User`](../../../users/user/classes/User.md) |\n\n#### Returns\n\n`Promise`\\<`Channel`\\>\n\n***\n\n### private()\n\n> `static` **private**(`client`, `recipients`): `Promise`\\<`Channel`\\>\n\nOpen (creating if needed) the private group channel with a set of users.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `recipients` | [`User`](../../../users/user/classes/User.md)[] |\n\n#### Returns\n\n`Promise`\\<`Channel`\\>\n\n\n<!-- src/entities/channels/channel/type-aliases/ChannelAttachment.md -->\n# Type Alias: ChannelAttachment\n\n> **ChannelAttachment** = [`GetChannelAttachmentsResponses`](../../../../../generated/storage/types.gen/type-aliases/GetChannelAttachmentsResponses.md)\\[`200`\\]\\[`\"items\"`\\]\\[`number`\\]\n\nA file or entity attached to a message in a channel.\n\n\n<!-- src/entities/channels/channel/type-aliases/ChannelParticipant.md -->\n# Type Alias: ChannelParticipant\n\n> **ChannelParticipant** = [`GetChannelParticipantsResponses`](../../../../../generated/storage/types.gen/type-aliases/GetChannelParticipantsResponses.md)\\[`200`\\]\\[`number`\\]\n\nA member of a channel, with their role and join time.\n\n\n<!-- src/entities/channels/labels/classes/ChannelLabelsNamespace.md -->\n# Class: ChannelLabelsNamespace\n\nShared or private channel labels: named groups of channels shown in the Chat\nsidebar. Every member of the team sees the same labels in the same order,\nand any member may create, rename, delete, or move channels between them;\neach change applies to the whole team. Users without a team have private\nlabels belonging to their account.\n\nA label's `channelIds` lists only the channels the authenticated user is a\nmember of. Manual labels count all assignments; smart tags count visible\nmatches. A channel can be in one manual label and any number of matching\nsmart tags per team or account. Direct messages cannot be grouped.\n\n## Constructors\n\n### Constructor\n\n> **new ChannelLabelsNamespace**(`client`): `ChannelLabelsNamespace`\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n\n#### Returns\n\n`ChannelLabelsNamespace`\n\n## Methods\n\n### create()\n\n> **create**(`name`, `channels?`): `Promise`\\<[`ChannelLabel`](../../../../../generated/storage/types.gen/type-aliases/ChannelLabel.md)\\>\n\nCreate a label and atomically move `channels` into it. Names are unique\nwithin the team or account, case-insensitively.\n\n#### Parameters\n\n| Parameter | Type | Default value |\n| ------ | ------ | ------ |\n| `name` | `string` | `undefined` |\n| `channels?` | [`Channel`](../../channel/classes/Channel.md)[] | `[]` |\n\n#### Returns\n\n`Promise`\\<[`ChannelLabel`](../../../../../generated/storage/types.gen/type-aliases/ChannelLabel.md)\\>\n\n***\n\n### createSmartTag()\n\n> **createSmartTag**(`name`, `rule`): `Promise`\\<[`ChannelLabel`](../../../../../generated/storage/types.gen/type-aliases/ChannelLabel.md)\\>\n\nCreate a smart tag whose membership follows an attribute rule automatically.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `name` | `string` |\n| `rule` | [`ChannelLabelRule`](../../../../../generated/storage/types.gen/type-aliases/ChannelLabelRule.md) |\n\n#### Returns\n\n`Promise`\\<[`ChannelLabel`](../../../../../generated/storage/types.gen/type-aliases/ChannelLabel.md)\\>\n\n***\n\n### delete()\n\n> **delete**(`label`): `Promise`\\<`void`\\>\n\nDelete a label for the whole team; its channels return to the plain list.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `label` | [`ChannelLabel`](../../../../../generated/storage/types.gen/type-aliases/ChannelLabel.md) |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### list()\n\n> **list**(): `Promise`\\<[`ChannelLabel`](../../../../../generated/storage/types.gen/type-aliases/ChannelLabel.md)[]\\>\n\nEvery label in the authenticated user's shared or private scope.\n\n#### Returns\n\n`Promise`\\<[`ChannelLabel`](../../../../../generated/storage/types.gen/type-aliases/ChannelLabel.md)[]\\>\n\n***\n\n### previewSmartTag()\n\n> **previewSmartTag**(`rule`): `Promise`\\<[`SmartTagPreview`](../../../../../generated/storage/types.gen/type-aliases/SmartTagPreview.md)\\>\n\nPreview the first matches and total visible count without creating a tag.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `rule` | [`ChannelLabelRule`](../../../../../generated/storage/types.gen/type-aliases/ChannelLabelRule.md) |\n\n#### Returns\n\n`Promise`\\<[`SmartTagPreview`](../../../../../generated/storage/types.gen/type-aliases/SmartTagPreview.md)\\>\n\n***\n\n### rename()\n\n> **rename**(`label`, `name`): `Promise`\\<[`ChannelLabel`](../../../../../generated/storage/types.gen/type-aliases/ChannelLabel.md)\\>\n\nRename a label for the whole team.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `label` | [`ChannelLabel`](../../../../../generated/storage/types.gen/type-aliases/ChannelLabel.md) |\n| `name` | `string` |\n\n#### Returns\n\n`Promise`\\<[`ChannelLabel`](../../../../../generated/storage/types.gen/type-aliases/ChannelLabel.md)\\>\n\n***\n\n### setLabel()\n\n> **setLabel**(`channel`, `label`): `Promise`\\<`void`\\>\n\nMove a channel into `label`, or out of any label when `label` is `undefined`.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `channel` | [`Channel`](../../channel/classes/Channel.md) |\n| `label` | [`ChannelLabel`](../../../../../generated/storage/types.gen/type-aliases/ChannelLabel.md) \\| `undefined` |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### updateSmartTag()\n\n> **updateSmartTag**(`label`, `name`, `rule`): `Promise`\\<[`ChannelLabel`](../../../../../generated/storage/types.gen/type-aliases/ChannelLabel.md)\\>\n\nUpdate the name and matching rule of an existing smart tag.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `label` | [`ChannelLabel`](../../../../../generated/storage/types.gen/type-aliases/ChannelLabel.md) |\n| `name` | `string` |\n| `rule` | [`ChannelLabelRule`](../../../../../generated/storage/types.gen/type-aliases/ChannelLabelRule.md) |\n\n#### Returns\n\n`Promise`\\<[`ChannelLabel`](../../../../../generated/storage/types.gen/type-aliases/ChannelLabel.md)\\>\n\n\n<!-- src/entities/channels/message/classes/Message.md -->\n# Class: Message\n\nA message in a channel. A thin handle: `id` and `channelId` are known up\nfront, and record-backed fields (`content`, `author`) load lazily on first\naccess and cache. Actions carry the ids for you.\n\n## Extends\n\n- [`FavoritableEntity`](../../../entity/classes/FavoritableEntity.md)\\<[`Message`](../../../../../generated/storage/types.gen/type-aliases/Message.md)\\>\n\n## Properties\n\n| Property | Modifier | Type | Default value | Description | Overrides | Inherited from |\n| ------ | ------ | ------ | ------ | ------ | ------ | ------ |\n| <a id=\"property-channelid\"></a> `channelId` | `readonly` | `string` | `undefined` | - | - | - |\n| <a id=\"property-content\"></a> `content` | `readonly` | () => `Promise`\\<`string`\\> | `...` | The message body. | - | - |\n| <a id=\"property-createdat\"></a> `createdAt` | `readonly` | () => `Promise`\\<`string`\\> | `...` | When the message was created. | - | - |\n| <a id=\"property-editedat\"></a> `editedAt` | `readonly` | () => `Promise`\\<`string` \\| `undefined`\\> | `...` | When the message was last edited, if it has been. | - | - |\n| <a id=\"property-entitytype\"></a> `entityType` | `readonly` | `\"channel_message\"` | `'channel_message'` | Favorites identify channel messages as `channel_message`. | [`FavoritableEntity`](../../../entity/classes/FavoritableEntity.md).[`entityType`](../../../entity/classes/FavoritableEntity.md#property-entitytype) | - |\n| <a id=\"property-id\"></a> `id` | `public readonly` | `string` | `undefined` | - | - | [`FavoritableEntity`](../../../entity/classes/FavoritableEntity.md).[`id`](../../../entity/classes/FavoritableEntity.md#property-id) |\n| <a id=\"property-mentions\"></a> `mentions` | `readonly` | [`SimpleMention`](../../../../../generated/storage/types.gen/type-aliases/SimpleMention.md)[] | `[]` | Entities mentioned in this message, when a list, thread, or event supplied them. | - | - |\n| <a id=\"property-updatedat\"></a> `updatedAt` | `readonly` | () => `Promise`\\<`string`\\> | `...` | When the message was last updated. | - | - |\n\n## Methods\n\n### author()\n\n> **author**(): `Promise`\\<[`User`](../../../users/user/classes/User.md)\\>\n\nThe user who sent this message.\n\n#### Returns\n\n`Promise`\\<[`User`](../../../users/user/classes/User.md)\\>\n\n***\n\n### channel()\n\n> **channel**(): [`Channel`](../../channel/classes/Channel.md)\n\nThe channel this message is in.\n\n#### Returns\n\n[`Channel`](../../channel/classes/Channel.md)\n\n***\n\n### delete()\n\n> **delete**(): `Promise`\\<`void`\\>\n\nDelete this message.\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### edit()\n\n> **edit**(`body`): `Promise`\\<`Message`\\>\n\nReplace this message's body.\n\n#### Parameters\n\n| Parameter | Type | Description |\n| ------ | ------ | ------ |\n| `body` | `string` \\| [`RichMessage`](../../../../mentions/interfaces/RichMessage.md) | Plain text, or a rich body composed with msg. |\n\n#### Returns\n\n`Promise`\\<`Message`\\>\n\n***\n\n### favorite()\n\n> **favorite**(): `Promise`\\<`Message`\\>\n\nAdd this entity to the user's favorites. Returns this handle for chaining.\nPlain unwrap: favoriting alters the user's favorites collection, not this\nentity's own detail, so there's nothing cached to invalidate.\n\n#### Returns\n\n`Promise`\\<`Message`\\>\n\n#### Inherited from\n\n[`FavoritableEntity`](../../../entity/classes/FavoritableEntity.md).[`favorite`](../../../entity/classes/FavoritableEntity.md#favorite)\n\n***\n\n### permission()\n\n> **permission**(): `Promise`\\<\\{ `permission`: [`EntityPermission`](../../../../../generated/storage/types.gen/type-aliases/EntityPermission.md); `status`: `\"access\"`; \\} \\| \\{ `status`: `\"no_access\"`; \\}\\>\n\nRead the caller's effective permission on this entity.\n\n#### Returns\n\n`Promise`\\<\\{ `permission`: [`EntityPermission`](../../../../../generated/storage/types.gen/type-aliases/EntityPermission.md); `status`: `\"access\"`; \\} \\| \\{ `status`: `\"no_access\"`; \\}\\>\n\n#### Inherited from\n\n[`FavoritableEntity`](../../../entity/classes/FavoritableEntity.md).[`permission`](../../../entity/classes/FavoritableEntity.md#permission)\n\n***\n\n### react()\n\n> **react**(`emoji`): `Promise`\\<`Message`\\>\n\nAdd an emoji reaction to this message.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `emoji` | `string` |\n\n#### Returns\n\n`Promise`\\<`Message`\\>\n\n***\n\n### reply()\n\n> **reply**(`body`): `Promise`\\<`Message`\\>\n\nPost a reply in this message's thread.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `body` | `string` \\| [`RichMessage`](../../../../mentions/interfaces/RichMessage.md) |\n\n#### Returns\n\n`Promise`\\<`Message`\\>\n\n***\n\n### thread()\n\n> **thread**(): [`Thread`](../../thread/classes/Thread.md)\n\nThe thread rooted at this message.\n\n#### Returns\n\n[`Thread`](../../thread/classes/Thread.md)\n\n***\n\n### toJSON()\n\n> **toJSON**(): \\{ `detail?`: [`Message`](../../../../../generated/storage/types.gen/type-aliases/Message.md); `id`: `string`; \\}\n\n#### Returns\n\n\\{ `detail?`: [`Message`](../../../../../generated/storage/types.gen/type-aliases/Message.md); `id`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `detail?` | [`Message`](../../../../../generated/storage/types.gen/type-aliases/Message.md) |\n| `id` | `string` |\n\n#### Inherited from\n\n[`FavoritableEntity`](../../../entity/classes/FavoritableEntity.md).[`toJSON`](../../../entity/classes/FavoritableEntity.md#tojson)\n\n***\n\n### unfavorite()\n\n> **unfavorite**(): `Promise`\\<`Message`\\>\n\nRemove this entity from the user's favorites. Returns this handle for chaining.\n\n#### Returns\n\n`Promise`\\<`Message`\\>\n\n#### Inherited from\n\n[`FavoritableEntity`](../../../entity/classes/FavoritableEntity.md).[`unfavorite`](../../../entity/classes/FavoritableEntity.md#unfavorite)\n\n***\n\n### unreact()\n\n> **unreact**(`emoji`): `Promise`\\<`Message`\\>\n\nRemove one of your emoji reactions from this message.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `emoji` | `string` |\n\n#### Returns\n\n`Promise`\\<`Message`\\>\n\n***\n\n### byId()\n\n> `static` **byId**(`client`, `channelId`, `id`, `mentions?`): `Message`\n\nA handle to a message by id. Fields load on first access.\n\n#### Parameters\n\n| Parameter | Type | Default value |\n| ------ | ------ | ------ |\n| `client` | `MacroClient` | `undefined` |\n| `channelId` | `string` | `undefined` |\n| `id` | `string` | `undefined` |\n| `mentions?` | [`SimpleMention`](../../../../../generated/storage/types.gen/type-aliases/SimpleMention.md)[] | `[]` |\n\n#### Returns\n\n`Message`\n\n***\n\n### from()\n\n> `static` **from**(`client`, `channelId`, `data`): `Message`\n\nBuild a root or reply from a message record (pre-seeded, no fetch).\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `channelId` | `string` |\n| `data` | [`Message`](../../../../../generated/storage/types.gen/type-aliases/Message.md) |\n\n#### Returns\n\n`Message`\n\n\n<!-- src/entities/channels/message/type-aliases/MessageData.md -->\n# Type Alias: MessageData\n\n> **MessageData** = [`Message`](../../../../../generated/storage/types.gen/type-aliases/Message.md)\n\nThe API's representation of a message; the same record the document comment API returns.\n\n\n<!-- src/entities/channels/namespace/classes/ChannelNamespace.md -->\n# Class: ChannelNamespace\n\n## Constructors\n\n### Constructor\n\n> **new ChannelNamespace**(`client`): `ChannelNamespace`\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n\n#### Returns\n\n`ChannelNamespace`\n\n## Properties\n\n| Property | Modifier | Type | Description |\n| ------ | ------ | ------ | ------ |\n| <a id=\"property-labels\"></a> `labels` | `readonly` | [`ChannelLabelsNamespace`](../../labels/classes/ChannelLabelsNamespace.md) | Team-shared labels that group channels in the Chat sidebar. |\n\n## Methods\n\n### activity()\n\n> **activity**(): `Promise`\\<[`ChannelActivity`](../../activity/classes/ChannelActivity.md)[]\\>\n\nRecent channel activity, with channel and user handles.\n\n#### Returns\n\n`Promise`\\<[`ChannelActivity`](../../activity/classes/ChannelActivity.md)[]\\>\n\n***\n\n### byId()\n\n> **byId**(`id`): [`Channel`](../../channel/classes/Channel.md)\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `id` | `string` |\n\n#### Returns\n\n[`Channel`](../../channel/classes/Channel.md)\n\n***\n\n### create()\n\n> **create**(`opts`): `Promise`\\<[`Channel`](../../channel/classes/Channel.md)\\>\n\nCreate a channel. The caller becomes the owner.\n\n#### Parameters\n\n| Parameter | Type | Description |\n| ------ | ------ | ------ |\n| `opts` | \\{ `name?`: `string`; `participants?`: [`User`](../../../users/user/classes/User.md)[]; `team?`: [`Team`](../../../teams/team/classes/Team.md); `type`: [`ChannelType`](../../../../../generated/storage/types.gen/type-aliases/ChannelType.md); \\} | - |\n| `opts.name?` | `string` | - |\n| `opts.participants?` | [`User`](../../../users/user/classes/User.md)[] | Participants to add, excluding the owner. |\n| `opts.team?` | [`Team`](../../../teams/team/classes/Team.md) | Team, for team channels. |\n| `opts.type` | [`ChannelType`](../../../../../generated/storage/types.gen/type-aliases/ChannelType.md) | - |\n\n#### Returns\n\n`Promise`\\<[`Channel`](../../channel/classes/Channel.md)\\>\n\n***\n\n### dm()\n\n> **dm**(`recipient`): `Promise`\\<[`Channel`](../../channel/classes/Channel.md)\\>\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `recipient` | [`User`](../../../users/user/classes/User.md) |\n\n#### Returns\n\n`Promise`\\<[`Channel`](../../channel/classes/Channel.md)\\>\n\n***\n\n### list()\n\n> **list**(): `Promise`\\<[`Channel`](../../channel/classes/Channel.md)[]\\>\n\nAll channels the authenticated user is a member of.\n\n#### Returns\n\n`Promise`\\<[`Channel`](../../channel/classes/Channel.md)[]\\>\n\n***\n\n### private()\n\n> **private**(`recipients`): `Promise`\\<[`Channel`](../../channel/classes/Channel.md)\\>\n\nOpen (creating if needed) the private group channel with a set of users.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `recipients` | [`User`](../../../users/user/classes/User.md)[] |\n\n#### Returns\n\n`Promise`\\<[`Channel`](../../channel/classes/Channel.md)\\>\n\n***\n\n### search()\n\n> **search**(`query`, `opts?`): `AsyncGenerator`\\<[`Channel`](../../channel/classes/Channel.md)\\>\n\nSearch channels by name (client-side fuzzy filter on the full channel list)\nor by content (server-side unified search).\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `query` | `string` |\n| `opts?` | [`SearchOpts`](../../../search/interfaces/SearchOpts.md) |\n\n#### Returns\n\n`AsyncGenerator`\\<[`Channel`](../../channel/classes/Channel.md)\\>\n\n\n<!-- src/entities/channels/picture/classes/ChannelPicture.md -->\n# Class: ChannelPicture\n\nAn uploaded channel profile picture in static file storage.\n\n## Properties\n\n| Property | Modifier | Type |\n| ------ | ------ | ------ |\n| <a id=\"property-id\"></a> `id` | `readonly` | `string` |\n\n## Methods\n\n### toJSON()\n\n> **toJSON**(): \\{ `id`: `string`; \\}\n\nSerialize the uploaded picture reference.\n\n#### Returns\n\n\\{ `id`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `id` | `string` |\n\n***\n\n### byId()\n\n> `static` **byId**(`id`): `ChannelPicture`\n\nConstruct a reference from the upload receipt.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `id` | `string` |\n\n#### Returns\n\n`ChannelPicture`\n\n\n<!-- src/entities/channels/post/functions/postToChannel.md -->\n# Function: postToChannel()\n\n> **postToChannel**(`client`, `target`, `body`): `Promise`\\<`string`\\>\n\nPost a message using the endpoint supported by the caller's credentials.\n\nMost credentials use `POST /messages/channel/{id}`. User-owned bots without\nan acting user instead use `POST /channels/{id}/webhook`, which authorizes\nthrough channel membership. The bot owner is read from `GET /bots/me` and\ncached by the client.\n\nThe webhook endpoint supports content only. Mentions in `<m-*>` tags still\nwork, but threads and attachments are not supported.\n\nPosting to a `Thread` puts the message in that thread; to a `Channel`, at the\nchannel root. One target rather than a channel plus a thread id, so the two\ncan't disagree.\n\n## Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `target` | [`Channel`](../../channel/classes/Channel.md) \\| [`Thread`](../../thread/classes/Thread.md) |\n| `body` | [`RichMessage`](../../../../mentions/interfaces/RichMessage.md) |\n\n## Returns\n\n`Promise`\\<`string`\\>\n\n\n<!-- src/entities/channels/thread/classes/Thread.md -->\n# Class: Thread\n\nA thread within a channel, rooted at a top-level message. Replies and\nthread-scoped posting live here.\n\n## Constructors\n\n### Constructor\n\n> **new Thread**(`client`, `channelId`, `rootId`): `Thread`\n\n#### Parameters\n\n| Parameter | Type | Description |\n| ------ | ------ | ------ |\n| `client` | `MacroClient` | - |\n| `channelId` | `string` | - |\n| `rootId` | `string` | The id of the message this thread hangs off. |\n\n#### Returns\n\n`Thread`\n\n## Properties\n\n| Property | Modifier | Type | Description |\n| ------ | ------ | ------ | ------ |\n| <a id=\"property-channelid\"></a> `channelId` | `readonly` | `string` | - |\n| <a id=\"property-rootid\"></a> `rootId` | `readonly` | `string` | The id of the message this thread hangs off. |\n\n## Methods\n\n### channel()\n\n> **channel**(): [`Channel`](../../channel/classes/Channel.md)\n\nThe channel this thread is in.\n\n#### Returns\n\n[`Channel`](../../channel/classes/Channel.md)\n\n***\n\n### replies()\n\n> **replies**(): `Promise`\\<[`Message`](../../message/classes/Message.md)[]\\>\n\nList the replies in this thread, oldest first.\n\n#### Returns\n\n`Promise`\\<[`Message`](../../message/classes/Message.md)[]\\>\n\n***\n\n### reply()\n\n> **reply**(`body`): `Promise`\\<[`Message`](../../message/classes/Message.md)\\>\n\nPost a reply in this thread.\n\n#### Parameters\n\n| Parameter | Type | Description |\n| ------ | ------ | ------ |\n| `body` | `string` \\| [`RichMessage`](../../../../mentions/interfaces/RichMessage.md) | Plain text, or a rich body composed with msg. |\n\n#### Returns\n\n`Promise`\\<[`Message`](../../message/classes/Message.md)\\>\n\nThe created reply.\n\n***\n\n### root()\n\n> **root**(): [`Message`](../../message/classes/Message.md)\n\nThe message this thread hangs off.\n\n#### Returns\n\n[`Message`](../../message/classes/Message.md)\n\n***\n\n### toJSON()\n\n> **toJSON**(): \\{ `channelId`: `string`; `rootId`: `string`; \\}\n\nSerialize the thread identity without its authenticated client.\n\n#### Returns\n\n\\{ `channelId`: `string`; `rootId`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `channelId` | `string` |\n| `rootId` | `string` |\n\n\n<!-- src/entities/whatsapp/account/classes/WhatsAppAccount.md -->\n# Class: WhatsAppAccount\n\nThe current user's WhatsApp account, connected through the Macro app.\n\n## Extends\n\n- [`MacroEntity`](../../../entity/classes/MacroEntity.md)\\<[`LinkedAccount`](../../../../../generated/storage/types.gen/type-aliases/LinkedAccount.md)\\>\n\n## Properties\n\n| Property | Modifier | Type | Description | Inherited from |\n| ------ | ------ | ------ | ------ | ------ |\n| <a id=\"property-id\"></a> `id` | `public readonly` | `string` | - | [`MacroEntity`](../../../entity/classes/MacroEntity.md).[`id`](../../../entity/classes/MacroEntity.md#property-id) |\n| <a id=\"property-identity\"></a> `identity` | `readonly` | () => `Promise`\\<`string` \\| `undefined`\\> | Verified remote identity, absent until pairing succeeds. | - |\n| <a id=\"property-owner\"></a> `owner` | `readonly` | () => `Promise`\\<[`User`](../../../users/user/classes/User.md)\\> | The Macro user who owns this account. | - |\n| <a id=\"property-state\"></a> `state` | `readonly` | () => `Promise`\\<[`LinkedAccountState`](../../../../../generated/storage/types.gen/type-aliases/LinkedAccountState.md)\\> | Account connection state; call refresh before polling it again. | - |\n\n## Methods\n\n### refresh()\n\n> **refresh**(): `Promise`\\<`WhatsAppAccount`\\>\n\nDiscard cached connection state and load its current value.\n\n#### Returns\n\n`Promise`\\<`WhatsAppAccount`\\>\n\n***\n\n### toJSON()\n\n> **toJSON**(): \\{ `detail?`: [`LinkedAccount`](../../../../../generated/storage/types.gen/type-aliases/LinkedAccount.md); `id`: `string`; \\}\n\n#### Returns\n\n\\{ `detail?`: [`LinkedAccount`](../../../../../generated/storage/types.gen/type-aliases/LinkedAccount.md); `id`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `detail?` | [`LinkedAccount`](../../../../../generated/storage/types.gen/type-aliases/LinkedAccount.md) |\n| `id` | `string` |\n\n#### Inherited from\n\n[`MacroEntity`](../../../entity/classes/MacroEntity.md).[`toJSON`](../../../entity/classes/MacroEntity.md#tojson)\n\n***\n\n### byId()\n\n> `static` **byId**(`client`, `id`): `WhatsAppAccount`\n\nReference an account; reads still enforce the authenticated owner's scope.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `id` | `string` |\n\n#### Returns\n\n`WhatsAppAccount`\n\n***\n\n### from()\n\n> `static` **from**(`client`, `record`): `WhatsAppAccount`\n\nSeed an account handle from an API record.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `record` | [`LinkedAccount`](../../../../../generated/storage/types.gen/type-aliases/LinkedAccount.md) |\n\n#### Returns\n\n`WhatsAppAccount`\n\n\n<!-- src/entities/whatsapp/chat/classes/WhatsAppChat.md -->\n# Class: WhatsAppChat\n\nOne chat of the current user's WhatsApp chat list: a group or a direct chat.\n\n## Extends\n\n- [`MacroEntity`](../../../entity/classes/MacroEntity.md)\\<[`LinkedChat`](../../../../../generated/storage/types.gen/type-aliases/LinkedChat.md)\\>\n\n## Properties\n\n| Property | Modifier | Type | Description | Inherited from |\n| ------ | ------ | ------ | ------ | ------ |\n| <a id=\"property-archived\"></a> `archived` | `readonly` | () => `Promise`\\<`boolean`\\> | Archived in WhatsApp. | - |\n| <a id=\"property-canadd\"></a> `canAdd` | `readonly` | () => `Promise`\\<`boolean`\\> | Whether adding it to Macro works now. | - |\n| <a id=\"property-cannotaddreason\"></a> `cannotAddReason` | `readonly` | () => `Promise`\\<`NonNullable`\\<LinkedCannotAdd \\| null \\| undefined\\> \\| `undefined`\\> | Why it can't be added (`not_in_group`, `community`, `own_chat`, `not_in_chat_list`), when it is neither added, shared nor addable. | - |\n| <a id=\"property-community\"></a> `community` | `readonly` | () => `Promise`\\<[`WhatsAppCommunity`](../type-aliases/WhatsAppCommunity.md) \\| `undefined`\\> | The WhatsApp community a group belongs to, if any: the community's own chat, its name, and whether this is its announcement group. | - |\n| <a id=\"property-group\"></a> `group` | `readonly` | () => `Promise`\\<[`WhatsAppGroup`](../../group/classes/WhatsAppGroup.md) \\| `undefined`\\> | The current user's own Macro group for this chat, once added. | - |\n| <a id=\"property-id\"></a> `id` | `public readonly` | `string` | - | [`MacroEntity`](../../../entity/classes/MacroEntity.md).[`id`](../../../entity/classes/MacroEntity.md#property-id) |\n| <a id=\"property-kind\"></a> `kind` | `readonly` | () => `Promise`\\<[`LinkedChatKind`](../../../../../generated/storage/types.gen/type-aliases/LinkedChatKind.md)\\> | `group` or `direct`. | - |\n| <a id=\"property-lastactivityat\"></a> `lastActivityAt` | `readonly` | () => `Promise`\\<`string` \\| `undefined`\\> | Newest activity WhatsApp reported, when known. | - |\n| <a id=\"property-name\"></a> `name` | `readonly` | () => `Promise`\\<`string`\\> | Group subject (or member names), or the other person's name or number. | - |\n| <a id=\"property-pinned\"></a> `pinned` | `readonly` | () => `Promise`\\<`boolean`\\> | Pinned in WhatsApp. | - |\n| <a id=\"property-shared\"></a> `shared` | `readonly` | () => `Promise`\\<[`WhatsAppGroup`](../../group/classes/WhatsAppGroup.md) \\| `undefined`\\> | Someone else's Macro group for this chat, shared with the current user. | - |\n\n## Methods\n\n### adopt()\n\n> **adopt**(): `Promise`\\<[`WhatsAppGroup`](../../group/classes/WhatsAppGroup.md)\\>\n\nAdd the chat (a group or a direct chat) to Macro as the current user's\nown; its earlier messages are imported from the phone. Adding it again\nreturns the same chat. Only the owner sends in a direct chat.\n\n#### Returns\n\n`Promise`\\<[`WhatsAppGroup`](../../group/classes/WhatsAppGroup.md)\\>\n\n***\n\n### refresh()\n\n> **refresh**(): `Promise`\\<`WhatsAppChat`\\>\n\nReload the chat's list entry.\n\n#### Returns\n\n`Promise`\\<`WhatsAppChat`\\>\n\n***\n\n### toJSON()\n\n> **toJSON**(): \\{ `detail?`: [`LinkedChat`](../../../../../generated/storage/types.gen/type-aliases/LinkedChat.md); `id`: `string`; \\}\n\n#### Returns\n\n\\{ `detail?`: [`LinkedChat`](../../../../../generated/storage/types.gen/type-aliases/LinkedChat.md); `id`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `detail?` | [`LinkedChat`](../../../../../generated/storage/types.gen/type-aliases/LinkedChat.md) |\n| `id` | `string` |\n\n#### Inherited from\n\n[`MacroEntity`](../../../entity/classes/MacroEntity.md).[`toJSON`](../../../entity/classes/MacroEntity.md#tojson)\n\n***\n\n### byId()\n\n> `static` **byId**(`client`, `id`): `WhatsAppChat`\n\nReference a chat by its WhatsApp JID.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `id` | `string` |\n\n#### Returns\n\n`WhatsAppChat`\n\n***\n\n### from()\n\n> `static` **from**(`client`, `record`): `WhatsAppChat`\n\nSeed a chat handle from the chat list.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `record` | [`LinkedChat`](../../../../../generated/storage/types.gen/type-aliases/LinkedChat.md) |\n\n#### Returns\n\n`WhatsAppChat`\n\n\n<!-- src/entities/whatsapp/chat/functions/communityOf.md -->\n# Function: communityOf()\n\n> **communityOf**(`client`, `record`): [`WhatsAppCommunity`](../type-aliases/WhatsAppCommunity.md)\n\nA community reference as a handle on the community's own chat.\n\n## Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `record` | [`LinkedCommunityReference`](../../../../../generated/storage/types.gen/type-aliases/LinkedCommunityReference.md) |\n\n## Returns\n\n[`WhatsAppCommunity`](../type-aliases/WhatsAppCommunity.md)\n\n\n<!-- src/entities/whatsapp/chat/type-aliases/WhatsAppCommunity.md -->\n# Type Alias: WhatsAppCommunity\n\n> **WhatsAppCommunity** = \\{ `announcements`: `boolean`; `chat`: [`WhatsAppChat`](../classes/WhatsAppChat.md); `name`: `string`; \\}\n\nThe WhatsApp community a group belongs to.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-announcements\"></a> `announcements` | `boolean` | This group is the community's announcement group. |\n| <a id=\"property-chat\"></a> `chat` | [`WhatsAppChat`](../classes/WhatsAppChat.md) | The community itself, as a chat of the list (it can't be added). |\n| <a id=\"property-name\"></a> `name` | `string` | The community's name. |\n\n\n<!-- src/entities/whatsapp/group/classes/WhatsAppGroup.md -->\n# Class: WhatsAppGroup\n\nIndependently shareable added WhatsApp chat: a group or a direct chat.\n\n## Extends\n\n- [`FavoritableEntity`](../../../entity/classes/FavoritableEntity.md)\\<[`WhatsAppGroupDetail`](../../../../../generated/storage/types.gen/type-aliases/WhatsAppGroupDetail.md)\\>\n\n## Properties\n\n| Property | Modifier | Type | Description | Overrides | Inherited from |\n| ------ | ------ | ------ | ------ | ------ | ------ |\n| <a id=\"property-backfill\"></a> `backfill` | `readonly` | () => `Promise`\\<[`LinkedBackfill`](../../../../../generated/storage/types.gen/type-aliases/LinkedBackfill.md) \\| `undefined`\\> | Importing earlier messages from the owner's phone after adding, if any. | - | - |\n| <a id=\"property-cansend\"></a> `canSend` | `readonly` | () => `Promise`\\<`boolean`\\> | Whether the caller can send from their own connected account. | - | - |\n| <a id=\"property-community\"></a> `community` | `readonly` | () => `Promise`\\<[`WhatsAppCommunity`](../../chat/type-aliases/WhatsAppCommunity.md) \\| `undefined`\\> | The WhatsApp community this group belongs to, if any: the community's own chat, its name, and whether this is its announcement group. | - | - |\n| <a id=\"property-disappearingseconds\"></a> `disappearingSeconds` | `readonly` | () => `Promise`\\<`number` \\| `undefined`\\> | WhatsApp's disappearing-messages timer in seconds while on; Macro keeps the messages. | - | - |\n| <a id=\"property-entitytype\"></a> `entityType` | `readonly` | `\"whatsapp_group\"` | Canonical sharing and favorites kind. | [`FavoritableEntity`](../../../entity/classes/FavoritableEntity.md).[`entityType`](../../../entity/classes/FavoritableEntity.md#property-entitytype) | - |\n| <a id=\"property-id\"></a> `id` | `public readonly` | `string` | - | - | [`FavoritableEntity`](../../../entity/classes/FavoritableEntity.md).[`id`](../../../entity/classes/FavoritableEntity.md#property-id) |\n| <a id=\"property-kind\"></a> `kind` | `readonly` | () => `Promise`\\<[`LinkedChatKind`](../../../../../generated/storage/types.gen/type-aliases/LinkedChatKind.md)\\> | `group`, or `direct` for a one-to-one chat (only its owner sends). | - | - |\n| <a id=\"property-limits\"></a> `limits` | `readonly` | () => `Promise`\\<[`LinkedCapabilities`](../../../../../generated/storage/types.gen/type-aliases/LinkedCapabilities.md)\\> | Supported sizes and mutation window. | - | - |\n| <a id=\"property-name\"></a> `name` | `readonly` | () => `Promise`\\<`string`\\> | Display name: the group's, or a direct chat's other person. | - | - |\n| <a id=\"property-owner\"></a> `owner` | `readonly` | () => `Promise`\\<[`User`](../../../users/user/classes/User.md)\\> | Actual owner, independent of WhatsApp membership. | - | - |\n| <a id=\"property-participants\"></a> `participants` | `readonly` | () => `Promise`\\<[`WhatsAppParticipant`](../../participant/classes/WhatsAppParticipant.md)[]\\> | Everyone in the chat, from its roster; empty when no roster is known. | - | - |\n| <a id=\"property-roster\"></a> `roster` | `readonly` | () => `Promise`\\<[`LinkedGroupInfo`](../../../../../generated/storage/types.gen/type-aliases/LinkedGroupInfo.md) \\| `undefined`\\> | Current remote roster (name, participants, announce), when available. | - | - |\n| <a id=\"property-sendingidentity\"></a> `sendingIdentity` | `readonly` | () => `Promise`\\<`string` \\| `undefined`\\> | Caller's own verified sending identity. | - | - |\n| <a id=\"property-sendreason\"></a> `sendReason` | `readonly` | () => `Promise`\\<`NonNullable`\\<LinkedReplyBlock \\| null \\| undefined\\> \\| `undefined`\\> | Reason sending is blocked. | - | - |\n| <a id=\"property-unreadcount\"></a> `unreadCount` | `readonly` | () => `Promise`\\<`number`\\> | Per-user unread count. | - | - |\n\n## Methods\n\n### delivery()\n\n> **delivery**(`sends`): `Promise`\\<[`WhatsAppSend`](../../send/classes/WhatsAppSend.md)[]\\>\n\nRead delivery for selected caller-owned intents or messages.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `sends` | ([`WhatsAppMessage`](../../message/classes/WhatsAppMessage.md) \\| [`WhatsAppSend`](../../send/classes/WhatsAppSend.md))[] |\n\n#### Returns\n\n`Promise`\\<[`WhatsAppSend`](../../send/classes/WhatsAppSend.md)[]\\>\n\n***\n\n### detach()\n\n> **detach**(): `Promise`\\<`void`\\>\n\nStop observation while preserving history and established sharing.\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### favorite()\n\n> **favorite**(): `Promise`\\<`WhatsAppGroup`\\>\n\nAdd this entity to the user's favorites. Returns this handle for chaining.\nPlain unwrap: favoriting alters the user's favorites collection, not this\nentity's own detail, so there's nothing cached to invalidate.\n\n#### Returns\n\n`Promise`\\<`WhatsAppGroup`\\>\n\n#### Inherited from\n\n[`FavoritableEntity`](../../../entity/classes/FavoritableEntity.md).[`favorite`](../../../entity/classes/FavoritableEntity.md#favorite)\n\n***\n\n### markRead()\n\n> **markRead**(`message`): `Promise`\\<`void`\\>\n\nAdvance the caller's own read cursor.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `message` | [`WhatsAppMessage`](../../message/classes/WhatsAppMessage.md) |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### messageAttachments()\n\n> **messageAttachments**(`messages`): `Promise`\\<\\{ `attachments`: \\{ `document`: [`Document`](../../../documents/document/classes/Document.md) \\| `undefined`; `fileName`: `string`; `mime`: `string`; `ordinal`: `number`; `size`: `number`; `state`: [`LinkedAttachmentState`](../../../../../generated/storage/types.gen/type-aliases/LinkedAttachmentState.md); \\}[]; `message`: [`WhatsAppMessage`](../../message/classes/WhatsAppMessage.md); \\}[]\\>\n\nRead attachment states for selected messages.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `messages` | [`WhatsAppMessage`](../../message/classes/WhatsAppMessage.md)[] |\n\n#### Returns\n\n`Promise`\\<\\{ `attachments`: \\{ `document`: [`Document`](../../../documents/document/classes/Document.md) \\| `undefined`; `fileName`: `string`; `mime`: `string`; `ordinal`: `number`; `size`: `number`; `state`: [`LinkedAttachmentState`](../../../../../generated/storage/types.gen/type-aliases/LinkedAttachmentState.md); \\}[]; `message`: [`WhatsAppMessage`](../../message/classes/WhatsAppMessage.md); \\}[]\\>\n\n***\n\n### messages()\n\n> **messages**(`options?`): `AsyncGenerator`\\<[`WhatsAppMessage`](../../message/classes/WhatsAppMessage.md)\\>\n\nIterate newest-first timeline pages lazily.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `options?` | \\{ `limit?`: `number`; \\} |\n| `options.limit?` | `number` |\n\n#### Returns\n\n`AsyncGenerator`\\<[`WhatsAppMessage`](../../message/classes/WhatsAppMessage.md)\\>\n\n***\n\n### permission()\n\n> **permission**(): `Promise`\\<\\{ `permission`: [`EntityPermission`](../../../../../generated/storage/types.gen/type-aliases/EntityPermission.md); `status`: `\"access\"`; \\} \\| \\{ `status`: `\"no_access\"`; \\}\\>\n\nRead the caller's effective permission on this entity.\n\n#### Returns\n\n`Promise`\\<\\{ `permission`: [`EntityPermission`](../../../../../generated/storage/types.gen/type-aliases/EntityPermission.md); `status`: `\"access\"`; \\} \\| \\{ `status`: `\"no_access\"`; \\}\\>\n\n#### Inherited from\n\n[`FavoritableEntity`](../../../entity/classes/FavoritableEntity.md).[`permission`](../../../entity/classes/FavoritableEntity.md#permission)\n\n***\n\n### permissions()\n\n> **permissions**(): `Promise`\\<[`SharePermissionV2`](../../../../../generated/storage/types.gen/type-aliases/SharePermissionV2.md)\\>\n\nRead standard link/team sharing settings.\n\n#### Returns\n\n`Promise`\\<[`SharePermissionV2`](../../../../../generated/storage/types.gen/type-aliases/SharePermissionV2.md)\\>\n\n***\n\n### refresh()\n\n> **refresh**(): `Promise`\\<`WhatsAppGroup`\\>\n\nReload detail, permissions and caller capabilities.\n\n#### Returns\n\n`Promise`\\<`WhatsAppGroup`\\>\n\n***\n\n### reply()\n\n> **reply**(`content`, `options`): `Promise`\\<[`WhatsAppSend`](../../send/classes/WhatsAppSend.md)\\>\n\nPersonal sessions and owner API credentials can send. Bots never send.\nPreserve the idempotency key; uncertain outcomes are never automatically resent.\nThe server enforces one request per second per user.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `content` | [`WhatsAppReply`](../type-aliases/WhatsAppReply.md) |\n| `options` | \\{ `idempotencyKey`: `string`; `replyTo?`: [`WhatsAppMessage`](../../message/classes/WhatsAppMessage.md); \\} |\n| `options.idempotencyKey` | `string` |\n| `options.replyTo?` | [`WhatsAppMessage`](../../message/classes/WhatsAppMessage.md) |\n\n#### Returns\n\n`Promise`\\<[`WhatsAppSend`](../../send/classes/WhatsAppSend.md)\\>\n\n***\n\n### sends()\n\n> **sends**(): `Promise`\\<[`WhatsAppSend`](../../send/classes/WhatsAppSend.md)[]\\>\n\nRead only the caller's pending, uncertain or failed sends.\n\n#### Returns\n\n`Promise`\\<[`WhatsAppSend`](../../send/classes/WhatsAppSend.md)[]\\>\n\n***\n\n### toJSON()\n\n> **toJSON**(): \\{ `detail?`: [`WhatsAppGroupDetail`](../../../../../generated/storage/types.gen/type-aliases/WhatsAppGroupDetail.md); `id`: `string`; \\}\n\n#### Returns\n\n\\{ `detail?`: [`WhatsAppGroupDetail`](../../../../../generated/storage/types.gen/type-aliases/WhatsAppGroupDetail.md); `id`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `detail?` | [`WhatsAppGroupDetail`](../../../../../generated/storage/types.gen/type-aliases/WhatsAppGroupDetail.md) |\n| `id` | `string` |\n\n#### Inherited from\n\n[`FavoritableEntity`](../../../entity/classes/FavoritableEntity.md).[`toJSON`](../../../entity/classes/FavoritableEntity.md#tojson)\n\n***\n\n### unfavorite()\n\n> **unfavorite**(): `Promise`\\<`WhatsAppGroup`\\>\n\nRemove this entity from the user's favorites. Returns this handle for chaining.\n\n#### Returns\n\n`Promise`\\<`WhatsAppGroup`\\>\n\n#### Inherited from\n\n[`FavoritableEntity`](../../../entity/classes/FavoritableEntity.md).[`unfavorite`](../../../entity/classes/FavoritableEntity.md#unfavorite)\n\n***\n\n### updatePermissions()\n\n> **updatePermissions**(`update`): `Promise`\\<`void`\\>\n\nActual owner updates standard link/team sharing settings.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `update` | [`UpdateSharePermissionRequestV2`](../../../../../generated/storage/types.gen/type-aliases/UpdateSharePermissionRequestV2.md) |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### upload()\n\n> **upload**(`file`): `Promise`\\<[`WhatsAppUpload`](../../upload/classes/WhatsAppUpload.md)\\>\n\nStage a supported attachment for a deliberate send.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `file` | `Blob` \\| `File` |\n\n#### Returns\n\n`Promise`\\<[`WhatsAppUpload`](../../upload/classes/WhatsAppUpload.md)\\>\n\n***\n\n### byId()\n\n> `static` **byId**(`client`, `id`): `WhatsAppGroup`\n\nReference an adopted group; access is checked on each request.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `id` | `string` |\n\n#### Returns\n\n`WhatsAppGroup`\n\n\n<!-- src/entities/whatsapp/group/type-aliases/WhatsAppReply.md -->\n# Type Alias: WhatsAppReply\n\n> **WhatsAppReply** = \\{ `mentions?`: [`WhatsAppParticipant`](../../participant/classes/WhatsAppParticipant.md)[]; `text`: `string`; `type`: `\"text\"`; \\} \\| \\{ `caption?`: `string`; `type`: `\"media\"`; `upload`: [`WhatsAppUpload`](../../upload/classes/WhatsAppUpload.md); \\} \\| \\{ `message`: [`WhatsAppMessage`](../../message/classes/WhatsAppMessage.md); `operation`: `\"reaction\"` \\| `\"edit\"` \\| `\"delete\"`; `text?`: `string`; `type`: `\"mutation\"`; \\}\n\nDeliberate content from the credential owner's own WhatsApp account.\n\n## Union Members\n\n### Type Literal\n\n\\{ `mentions?`: [`WhatsAppParticipant`](../../participant/classes/WhatsAppParticipant.md)[]; `text`: `string`; `type`: `\"text\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `mentions?` | [`WhatsAppParticipant`](../../participant/classes/WhatsAppParticipant.md)[] | Participants mentioned (from `participants()`); the text names each as `@<mentionToken>`. |\n| `text` | `string` | - |\n| `type` | `\"text\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `caption?`: `string`; `type`: `\"media\"`; `upload`: [`WhatsAppUpload`](../../upload/classes/WhatsAppUpload.md); \\}\n\n***\n\n### Type Literal\n\n\\{ `message`: [`WhatsAppMessage`](../../message/classes/WhatsAppMessage.md); `operation`: `\"reaction\"` \\| `\"edit\"` \\| `\"delete\"`; `text?`: `string`; `type`: `\"mutation\"`; \\}\n\n\n<!-- src/entities/whatsapp/message/classes/WhatsAppMessage.md -->\n# Class: WhatsAppMessage\n\nMessage in an independently shared WhatsApp group.\n\n## Extends\n\n- [`MacroEntity`](../../../entity/classes/MacroEntity.md)\\<[`WhatsAppGroupMessage`](../../../../../generated/storage/types.gen/type-aliases/WhatsAppGroupMessage.md)\\>\n\n## Properties\n\n| Property | Modifier | Type | Description | Inherited from |\n| ------ | ------ | ------ | ------ | ------ |\n| <a id=\"property-attachments\"></a> `attachments` | `readonly` | () => `Promise`\\<\\{ `document`: [`Document`](../../../documents/document/classes/Document.md) \\| `undefined`; `durationSeconds`: `number` \\| `undefined`; `fileName`: `string`; `height`: `number` \\| `undefined`; `mime`: `string`; `ordinal`: `number`; `presentation`: [`LinkedMediaPresentation`](../../../../../generated/storage/types.gen/type-aliases/LinkedMediaPresentation.md) \\| `undefined`; `size`: `number`; `state`: [`LinkedAttachmentState`](../../../../../generated/storage/types.gen/type-aliases/LinkedAttachmentState.md); `width`: `number` \\| `undefined`; \\}[]\\> | Attachment state and imported document handles. | - |\n| <a id=\"property-body\"></a> `body` | `readonly` | () => `Promise`\\<`string`\\> | Plain WhatsApp text. | - |\n| <a id=\"property-deleted\"></a> `deleted` | `readonly` | () => `Promise`\\<`boolean`\\> | Deleted for everyone. | - |\n| <a id=\"property-deliverystate\"></a> `deliveryState` | `readonly` | () => `Promise`\\<`NonNullable`\\<LinkedDeliveryState \\| null \\| undefined\\> \\| `undefined`\\> | Caller-owned send's delivery state, when present. | - |\n| <a id=\"property-editedat\"></a> `editedAt` | `readonly` | () => `Promise`\\<`string` \\| `undefined`\\> | Last edit time. | - |\n| <a id=\"property-forwarded\"></a> `forwarded` | `readonly` | () => `Promise`\\<`boolean`\\> | Forwarded from another chat. | - |\n| <a id=\"property-group\"></a> `group` | `readonly` | [`WhatsAppGroup`](../../group/classes/WhatsAppGroup.md) | The chat this message is in. | - |\n| <a id=\"property-id\"></a> `id` | `public readonly` | `string` | - | [`MacroEntity`](../../../entity/classes/MacroEntity.md).[`id`](../../../entity/classes/MacroEntity.md#property-id) |\n| <a id=\"property-kind\"></a> `kind` | `readonly` | () => `Promise`\\<[`WhatsAppMessageKind`](../../../../../generated/storage/types.gen/type-aliases/WhatsAppMessageKind.md)\\> | `message`, or `system` for something that happened in the group (see `rich`). | - |\n| <a id=\"property-mentions\"></a> `mentions` | `readonly` | () => `Promise`\\<[`WhatsAppMention`](../../../../../generated/storage/types.gen/type-aliases/WhatsAppMention.md)[]\\> | People the body @-mentions: `@<token>` in the body is this person. | - |\n| <a id=\"property-reactions\"></a> `reactions` | `readonly` | () => `Promise`\\<[`WhatsAppGroupReaction`](../../../../../generated/storage/types.gen/type-aliases/WhatsAppGroupReaction.md)[]\\> | Grouped emoji counts and caller's own reaction. | - |\n| <a id=\"property-replyto\"></a> `replyTo` | `readonly` | () => `Promise`\\<`WhatsAppMessage` \\| `undefined`\\> | Quoted message in this group. | - |\n| <a id=\"property-rich\"></a> `rich` | `readonly` | () => `Promise`\\<`NonNullable`\\<WhatsAppRichContent \\| null \\| undefined\\> \\| `undefined`\\> | Poll (with tallies), location, contact cards, event or system line. | - |\n| <a id=\"property-sender\"></a> `sender` | `readonly` | () => `Promise`\\<[`WhatsAppGroupSender`](../../../../../generated/storage/types.gen/type-aliases/WhatsAppGroupSender.md)\\> | Protocol-verified sender association and display name. | - |\n| <a id=\"property-sentat\"></a> `sentAt` | `readonly` | () => `Promise`\\<`string`\\> | WhatsApp timestamp. | - |\n| <a id=\"property-viewonce\"></a> `viewOnce` | `readonly` | () => `Promise`\\<`boolean`\\> | Sent as view-once in WhatsApp; Macro keeps and shows it like any media. | - |\n\n## Methods\n\n### toJSON()\n\n> **toJSON**(): \\{ `detail?`: [`WhatsAppGroupMessage`](../../../../../generated/storage/types.gen/type-aliases/WhatsAppGroupMessage.md); `id`: `string`; \\}\n\n#### Returns\n\n\\{ `detail?`: [`WhatsAppGroupMessage`](../../../../../generated/storage/types.gen/type-aliases/WhatsAppGroupMessage.md); `id`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `detail?` | [`WhatsAppGroupMessage`](../../../../../generated/storage/types.gen/type-aliases/WhatsAppGroupMessage.md) |\n| `id` | `string` |\n\n#### Inherited from\n\n[`MacroEntity`](../../../entity/classes/MacroEntity.md).[`toJSON`](../../../entity/classes/MacroEntity.md#tojson)\n\n***\n\n### byId()\n\n> `static` **byId**(`client`, `group`, `id`): `WhatsAppMessage`\n\nReference a message within its original group.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `group` | [`WhatsAppGroup`](../../group/classes/WhatsAppGroup.md) |\n| `id` | `string` |\n\n#### Returns\n\n`WhatsAppMessage`\n\n***\n\n### from()\n\n> `static` **from**(`client`, `group`, `record`): `WhatsAppMessage`\n\nSeed a message handle from a timeline response.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `group` | [`WhatsAppGroup`](../../group/classes/WhatsAppGroup.md) |\n| `record` | [`WhatsAppGroupMessage`](../../../../../generated/storage/types.gen/type-aliases/WhatsAppGroupMessage.md) |\n\n#### Returns\n\n`WhatsAppMessage`\n\n\n<!-- src/entities/whatsapp/namespace/classes/WhatsAppNamespace.md -->\n# Class: WhatsAppNamespace\n\nOperate on an account already paired through the Macro app.\n\n## Constructors\n\n### Constructor\n\n> **new WhatsAppNamespace**(`client`): `WhatsAppNamespace`\n\nBind existing-account operations to this authenticated client.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n\n#### Returns\n\n`WhatsAppNamespace`\n\n## Methods\n\n### account()\n\n> **account**(): `Promise`\\<[`WhatsAppAccount`](../../account/classes/WhatsAppAccount.md) \\| `undefined`\\>\n\nCurrent owner's account, or undefined when no account has been connected.\n\n#### Returns\n\n`Promise`\\<[`WhatsAppAccount`](../../account/classes/WhatsAppAccount.md) \\| `undefined`\\>\n\n***\n\n### byId()\n\n> **byId**(`id`): [`WhatsAppGroup`](../../group/classes/WhatsAppGroup.md)\n\nReference an adopted entity without fetching it.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `id` | `string` |\n\n#### Returns\n\n[`WhatsAppGroup`](../../group/classes/WhatsAppGroup.md)\n\n***\n\n### groups()\n\n> **groups**(): `Promise`\\<[`WhatsAppGroup`](../../group/classes/WhatsAppGroup.md)[]\\>\n\nAdopted groups shared with the caller, including without WhatsApp.\n\n#### Returns\n\n`Promise`\\<[`WhatsAppGroup`](../../group/classes/WhatsAppGroup.md)[]\\>\n\n\n<!-- src/entities/whatsapp/participant/classes/WhatsAppParticipant.md -->\n# Class: WhatsAppParticipant\n\nSomeone in an added WhatsApp chat, from its roster; mention them in a text reply.\n\n## Properties\n\n| Property | Modifier | Type | Description |\n| ------ | ------ | ------ | ------ |\n| <a id=\"property-group\"></a> `group` | `readonly` | [`WhatsAppGroup`](../../group/classes/WhatsAppGroup.md) | The chat whose roster lists them. |\n| <a id=\"property-id\"></a> `id` | `readonly` | `string` | Their WhatsApp id: correlation data, not a Macro user. |\n\n## Accessors\n\n### admin\n\n#### Get Signature\n\n> **get** **admin**(): `boolean` \\| `undefined`\n\nWhether they administer the group, when read from the roster.\n\n##### Returns\n\n`boolean` \\| `undefined`\n\n***\n\n### displayName\n\n#### Get Signature\n\n> **get** **displayName**(): `string` \\| `undefined`\n\nTheir WhatsApp name, untrusted, when the roster had one.\n\n##### Returns\n\n`string` \\| `undefined`\n\n***\n\n### mentionToken\n\n#### Get Signature\n\n> **get** **mentionToken**(): `string`\n\nThe digits a text reply writes as `@<digits>` to mention them.\n\n##### Returns\n\n`string`\n\n## Methods\n\n### toJSON()\n\n> **toJSON**(): \\{ `admin`: `boolean` \\| `undefined`; `displayName`: `string` \\| `undefined`; `group`: `string`; `id`: `string`; \\}\n\nSerialize the participant reference without credentials.\n\n#### Returns\n\n\\{ `admin`: `boolean` \\| `undefined`; `displayName`: `string` \\| `undefined`; `group`: `string`; `id`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `admin` | `boolean` \\| `undefined` |\n| `displayName` | `string` \\| `undefined` |\n| `group` | `string` |\n| `id` | `string` |\n\n***\n\n### byId()\n\n> `static` **byId**(`group`, `id`): `WhatsAppParticipant`\n\nReference a participant of a chat by WhatsApp id.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `group` | [`WhatsAppGroup`](../../group/classes/WhatsAppGroup.md) |\n| `id` | `string` |\n\n#### Returns\n\n`WhatsAppParticipant`\n\n***\n\n### from()\n\n> `static` **from**(`group`, `record`): `WhatsAppParticipant`\n\nSeed a participant from the chat's roster.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `group` | [`WhatsAppGroup`](../../group/classes/WhatsAppGroup.md) |\n| `record` | [`LinkedParticipant`](../../../../../generated/storage/types.gen/type-aliases/LinkedParticipant.md) |\n\n#### Returns\n\n`WhatsAppParticipant`\n\n\n<!-- src/entities/whatsapp/send/classes/WhatsAppSend.md -->\n# Class: WhatsAppSend\n\nOne deliberate send intent. Unknown outcomes must never be automatically resent.\n\n## Extends\n\n- [`MacroEntity`](../../../entity/classes/MacroEntity.md)\\<[`LinkedSendProgress`](../../../../../generated/storage/types.gen/type-aliases/LinkedSendProgress.md)\\>\n\n## Properties\n\n| Property | Modifier | Type | Description | Inherited from |\n| ------ | ------ | ------ | ------ | ------ |\n| <a id=\"property-createdat\"></a> `createdAt` | `readonly` | () => `Promise`\\<`string`\\> | When the send intent was created. | - |\n| <a id=\"property-errorcode\"></a> `errorCode` | `readonly` | () => `Promise`\\<`string` \\| `undefined`\\> | Sanitized failure code, when present. | - |\n| <a id=\"property-group\"></a> `group` | `readonly` | [`WhatsAppGroup`](../../group/classes/WhatsAppGroup.md) | Group entity containing this send. | - |\n| <a id=\"property-id\"></a> `id` | `public readonly` | `string` | - | [`MacroEntity`](../../../entity/classes/MacroEntity.md).[`id`](../../../entity/classes/MacroEntity.md#property-id) |\n| <a id=\"property-message\"></a> `message` | `readonly` | () => `Promise`\\<[`WhatsAppMessage`](../../message/classes/WhatsAppMessage.md) \\| `undefined`\\> | Group message once WhatsApp accepted the send. | - |\n| <a id=\"property-state\"></a> `state` | `readonly` | () => `Promise`\\<[`LinkedDeliveryState`](../../../../../generated/storage/types.gen/type-aliases/LinkedDeliveryState.md)\\> | Last observed delivery state; refresh explicitly to poll again. | - |\n\n## Methods\n\n### refresh()\n\n> **refresh**(): `Promise`\\<`WhatsAppSend`\\>\n\nFetch current delivery state without retrying or submitting the message.\n\n#### Returns\n\n`Promise`\\<`WhatsAppSend`\\>\n\n***\n\n### request()\n\n> **request**(): `Promise`\\<\\{ `idempotencyKey`: `string`; `message`: [`WhatsAppReply`](../../group/type-aliases/WhatsAppReply.md); `replyTo?`: [`WhatsAppMessage`](../../message/classes/WhatsAppMessage.md); \\}\\>\n\nInspect the original intent for reconciliation; never resubmit an unknown outcome automatically.\n\n#### Returns\n\n`Promise`\\<\\{ `idempotencyKey`: `string`; `message`: [`WhatsAppReply`](../../group/type-aliases/WhatsAppReply.md); `replyTo?`: [`WhatsAppMessage`](../../message/classes/WhatsAppMessage.md); \\}\\>\n\n***\n\n### toJSON()\n\n> **toJSON**(): \\{ `detail?`: [`LinkedSendProgress`](../../../../../generated/storage/types.gen/type-aliases/LinkedSendProgress.md); `id`: `string`; \\}\n\n#### Returns\n\n\\{ `detail?`: [`LinkedSendProgress`](../../../../../generated/storage/types.gen/type-aliases/LinkedSendProgress.md); `id`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `detail?` | [`LinkedSendProgress`](../../../../../generated/storage/types.gen/type-aliases/LinkedSendProgress.md) |\n| `id` | `string` |\n\n#### Inherited from\n\n[`MacroEntity`](../../../entity/classes/MacroEntity.md).[`toJSON`](../../../entity/classes/MacroEntity.md#tojson)\n\n***\n\n### byId()\n\n> `static` **byId**(`client`, `group`, `id`): `WhatsAppSend`\n\nReference a send intent within its original group.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `group` | [`WhatsAppGroup`](../../group/classes/WhatsAppGroup.md) |\n| `id` | `string` |\n\n#### Returns\n\n`WhatsAppSend`\n\n***\n\n### from()\n\n> `static` **from**(`client`, `group`, `record`): `WhatsAppSend`\n\nSeed a send handle from a server response.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `group` | [`WhatsAppGroup`](../../group/classes/WhatsAppGroup.md) |\n| `record` | [`LinkedSendProgress`](../../../../../generated/storage/types.gen/type-aliases/LinkedSendProgress.md) |\n\n#### Returns\n\n`WhatsAppSend`\n\n\n<!-- src/entities/whatsapp/upload/classes/WhatsAppUpload.md -->\n# Class: WhatsAppUpload\n\nA staged attachment scoped to one adopted group; use it in a deliberate media send.\n\n## Properties\n\n| Property | Modifier | Type | Description |\n| ------ | ------ | ------ | ------ |\n| <a id=\"property-filename\"></a> `filename?` | `readonly` | `string` | Display filename supplied by the server. |\n| <a id=\"property-group\"></a> `group` | `readonly` | [`WhatsAppGroup`](../../group/classes/WhatsAppGroup.md) | The chat this upload can be sent to. |\n| <a id=\"property-id\"></a> `id` | `readonly` | `string` | Correlation identity of the staged upload. |\n| <a id=\"property-kind\"></a> `kind?` | `readonly` | [`LinkedMediaKind`](../../../../../generated/storage/types.gen/type-aliases/LinkedMediaKind.md) | Media category supplied by the server. |\n\n## Methods\n\n### toJSON()\n\n> **toJSON**(): \\{ `filename`: `string` \\| `undefined`; `group`: `string`; `id`: `string`; `kind`: [`LinkedMediaKind`](../../../../../generated/storage/types.gen/type-aliases/LinkedMediaKind.md) \\| `undefined`; \\}\n\nSerialize the upload reference without credentials.\n\n#### Returns\n\n\\{ `filename`: `string` \\| `undefined`; `group`: `string`; `id`: `string`; `kind`: [`LinkedMediaKind`](../../../../../generated/storage/types.gen/type-aliases/LinkedMediaKind.md) \\| `undefined`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `filename` | `string` \\| `undefined` |\n| `group` | `string` |\n| `id` | `string` |\n| `kind` | [`LinkedMediaKind`](../../../../../generated/storage/types.gen/type-aliases/LinkedMediaKind.md) \\| `undefined` |\n\n***\n\n### byId()\n\n> `static` **byId**(`group`, `id`): `WhatsAppUpload`\n\nReference a previously staged upload in its original group.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `group` | [`WhatsAppGroup`](../../group/classes/WhatsAppGroup.md) |\n| `id` | `string` |\n\n#### Returns\n\n`WhatsAppUpload`\n\n***\n\n### from()\n\n> `static` **from**(`group`, `record`): `WhatsAppUpload`\n\nSeed a handle from the server's upload receipt.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `group` | [`WhatsAppGroup`](../../group/classes/WhatsAppGroup.md) |\n| `record` | [`LinkedUploadedAttachment`](../../../../../generated/storage/types.gen/type-aliases/LinkedUploadedAttachment.md) |\n\n#### Returns\n\n`WhatsAppUpload`\n"},{"name": "crm",diff --git a/crates/agent_code_mode/src/domain/operations.json b/crates/agent_code_mode/src/domain/operations.jsonindex eddbdc3bcd..8aeff35d18 100644--- a/crates/agent_code_mode/src/domain/operations.json+++ b/crates/agent_code_mode/src/domain/operations.json@@ -579,7 +579,6 @@"storage.linkedConfiguration": "Linked Configuration","storage.linkedConnect": "Linked Connect","storage.linkedDisconnect": "Linked Disconnect",- "storage.linkedGroups": "Linked Groups","storage.linkedAdopt": "Linked Adopt","storage.linkedCancelPairing": "Linked Cancel Pairing","storage.linkedPairing": "Linked Pairing",diff --git a/crates/code_execution/src/outbound/deno/sdk.mjs b/crates/code_execution/src/outbound/deno/sdk.mjsindex e697f377d9..7b622dc790 100644--- a/crates/code_execution/src/outbound/deno/sdk.mjs+++ b/crates/code_execution/src/outbound/deno/sdk.mjs@@ -1,62 +1,62 @@// Generated by packages/code-mode-sdk/scripts/generate.ts.-async function 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 W${loader;value;inflight;constructor($,O){this.loader=$;this.value=O}get(){if(this.value!==void 0)return Promise.resolve(this.value);return this.inflight??=this.loader().then(($)=>{return this.value=$,$}),this.inflight}peek(){return this.value}clear(){this.value=void 0,this.inflight=void 0}}async function*u($){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 GO 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 G($){if($.error!==void 0)throw new GO($.response?.status??0,$.error);return $.data}class M{client;id;detail;constructor($,O,j){this.client=$;this.id=O;this.detail=new W$(()=>this.fetch(),j)}field($){return async()=>(await this.detail.get())[$]??void 0}mappedField($,O){return async()=>O((await this.detail.get())[$]??void 0)}toJSON(){let $=this.detail.peek();return $===void 0?{id:this.id}:{id:this.id,detail:$}}async mutate($){let O=G(await $(this.client));return this.detail.clear(),O}}class z$ extends M{async permission(){return G(await this.client.storage.getEntityPermission({path:{entity_type:this.entityType,entity_id:this.id}}))}async favorite(){return G(await this.client.storage.addFavorite({body:{entityId:this.id,entityType:this.entityType}})),this}async unfavorite(){return G(await this.client.storage.removeFavoriteByEntity({path:{entity_type:this.entityType,entity_id:this.id}})),this}}class X$ extends z${propertyReference(){return{entity_type:this.propertyEntityType,entity_id:this.id}}async properties($){let{properties:O}=G(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){G(await this.client.properties.setEntityProperty({path:{...this.propertyReference(),property_id:$.id},body:{value:O??null}}))}async updatePropertyOptions($){return G(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($){G(await this.client.properties.deleteEntityProperty({path:{entity_property_id:$.property.id}}))}}var w6={"<":"\\u003c",">":"\\u003e","&":"\\u0026"};function i$($,O){let j=JSON.stringify(O).replace(/[<>&]/g,(x)=>w6[x]??x);return`<${$}>${j}</${$}>`}function q6($){return typeof $==="object"&&$!==null&&typeof $.toMention==="function"}var f6={toMention:()=>({tag:i$("m-group-mention",{groupAlias:"here"}),mention:{entity_type:"group",entity_id:"here"}})};function b6($,...O){let j="",x=[];for(let[S,K]of $.entries()){j+=K;let Z=O[S];if(Z===void 0)continue;if(q6(Z)){let X=Z.toMention();j+=X.tag,x.push(X.mention)}else j+=String(Z)}return{content:j,mentions:k6(x)}}function k6($){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 B$ extends M{static byId($,O){return new B$($,O)}static from($,O){return new B$($,O.id,O)}async fetch(){let $=G(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 I$ extends M{static byId($,O){return new I$($,O)}static from($,O){return new I$($,O.bot.id,O)}async fetch(){let $=G(await this.client.storage.listAgents()).find((O)=>O.bot.id===this.id);if(!$)throw new E(`Agent ${this.id} is unavailable`);return $}name=this.mappedField("bot",($)=>$.name);instructions=this.field("instructions");defaultModel=this.field("default_model");channels=this.mappedField("channel_ids",($)=>$.map((O)=>b.byId(this.client,O)));host=this.mappedField("harness_id",($)=>$?B$.byId(this.client,$):void 0);async update($){await this.mutate((O)=>O.storage.updateAgent({path:{agent_id:this.id},body:gx($)}))}}function gx($){let{channels:O,team:j,host:x,autoAcceptPermissions:S,avatarUrl:K,channelScope:Z,defaultModel:X,isCoding:Y,...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:Y}}async function Wj($,O,j){let{channelId:x,thread:S}=g6(O);if(await y6($)){let{id:Z}=G(await $.storage.entityMessageCreate({path:{parent_type:"channel",parent_id:x},body:{content:j.content,mentions:j.mentions,attachments:[],thread_id:S?.rootId??null,nonce:crypto.randomUUID()}}));return Z}if(S)throw new f("a user-owned bot can only post via the channel webhook endpoint, which "+"does not support threads — use a team-owned bot, or requestedAs(user), "+"to reply in a thread");let{message_id:K}=G(await $.storage.postChannelBotWebhook({path:{channel_id:x},body:{content:j.content},headers:{"x-macro-bot-scope":"user"}}));return K}function g6($){return"rootId"in $?{channelId:$.channelId,thread:$}:{channelId:$.id}}async function y6($){if($.authConfig.type!=="bot"||$.hasActingUser())return!0;let{owner:O}=await $.selfBot();return O?.type==="team"}class h${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:$}=G(await this.client.storage.entityMessageGetThread({path:{parent_type:"channel",parent_id:this.channelId,id:this.rootId}}));return $.map((O)=>e.from(this.client,this.channelId,O))}async reply($){let O=await Wj(this.client,this,O$($));return e.byId(this.client,this.channelId,O)}}class e extends z${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 G(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 P.byId(this.client,(await this.detail.get()).sender_id)}channel(){return b.byId(this.client,this.channelId)}thread(){return new h$(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 Bj{client;channel;record;constructor($,O,j){this.client=$;this.channel=O;this.record=j}agent(){return I$.byId(this.client,this.record.botId)}sessions(){return this.record.sessions.map(($)=>({session:i.byId(this.client,$.sessionId),isCurrent:$.isCurrent,createdAt:$.createdAt}))}turns(){return this.record.turns.map(($)=>new yx(this.client,this,$))}async startFresh($){G(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 yx{client;conversation;record;constructor($,O,j){this.client=$;this.conversation=O;this.record=j}source(){return e.byId(this.client,this.conversation.channel.id,this.record.sourceMessageId)}session(){return i.byId(this.client,this.record.sessionId)}async retry($){G(await this.client.agentHarness.retryAgentConversationTurn({path:{channel_id:this.conversation.channel.id,bot_id:this.conversation.agent().id,source:this.record.sourceMessageId},body:{actionId:$}}))}toJSON(){return{channelId:this.conversation.channel.id,sourceMessageId:this.record.sourceMessageId}}}class L$ extends M{parent;toJSON(){return{...super.toJSON(),parentType:this.parent.type,parentId:this.parent.entity.id}}constructor($,O,j){super($,j);this.parent=O}static byId($,O,j){return new L$($,O,j)}get path(){return{parent_type:this.parent.type,parent_id:this.parent.entity.id,id:this.id}}async fetch(){return G(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 w$($,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=G(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:P.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 v6=50;function x$($){let{filters:O,type:j,make:x,includeCrm:S}=$;return(K,Z,X)=>{let Y=X?.searchOn??"name_content",L=X?.pageSize??v6;return u(async(Q)=>{let{results:J,next_cursor:I}=G(await K.search.unifiedSearch({body:{query:Z,match_type:"partial",search_on:Y,...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 QO{client;channel;record;constructor($,O,j){this.client=$;this.channel=O;this.record=j}get id(){return this.record.id}user(){return P.byId(this.client,this.record.user_id)}createdAt(){return this.record.created_at}async recordInteraction($){return new QO(this.client,this.channel,G(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 QO(this.client,this,G(await this.client.storage.postActivity({body:{activity_type:$,channel_id:this.id}})))}async setPicture($){await this.mutate((O)=>O.storage.setChannelPicture({path:{channel_id:this.id},body:{profile_picture_id:$?.id??null}}))}messageThreadById($){return L$.byId(this.client,{type:"channel",entity:this},$)}timelinePage($){return w$(this.client,{type:"channel",entity:this},(O)=>e.from(this.client,this.id,O),$)}async agentConversations(){return G(await this.client.agentHarness.listAgentConversations({path:{channel_id:this.id}})).conversations.map(($)=>new Bj(this.client,this,$))}entityType="channel";propertyEntityType="CHANNEL";async fetch(){return G(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}=G(await $.storage.getOrCreateDm({body:{recipient_id:O.id}}));return new b($,j)}static async private($,O){let{channel_id:j}=G(await $.storage.getOrCreatePrivate({body:{recipients:O.map((x)=>x.id)}}));return new b($,j)}static async create($,O){let{id:j}=G(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 Wj(this.client,O?.thread??this,O$($));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 u(async(O)=>{let j=G(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:$}=G(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 G(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){G(await this.client.storage.entityMessageTyping({path:{parent_type:"channel",parent_id:this.id},body:{active:$==="start",thread_id:O?.thread?.rootId??null}}))}attachments($){return u(async(O)=>{let j=G(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 P extends X${entityType="user";propertyEntityType="USER";async fetch(){let{names:$}=G(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 P($,O)}static fromName($,O){return new P($,O.id,O)}static async me($){let{user_id:O}=G(await $.auth.getUserInfo());return new P($,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:i$("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=G(await this.client.storage.accessRequestsState({path:this.path,query:{offset:$}}));return{accessLevel:O.accessLevel??void 0,canReview:O.canReview,owner:O.owner?P.byId(this.client,O.owner):void 0,pendingCount:O.pendingCount,supportedLevels:O.supportedLevels,nextOffset:O.nextOffset??void 0,mine:O.mine?zO.from(this.client,this,O.mine):void 0,requests:O.requests.map((j)=>zO.from(this.client,this,j))}}async submit($,O){return zO.from(this.client,this,G(await this.client.storage.accessRequestsSubmit({path:this.path,body:{requestedLevel:$,revision:O}})))}async cancel($){G(await this.client.storage.accessRequestsCancel({path:this.path,query:{revision:$}}))}async direct(){return G(await this.client.storage.accessRequestsDirect({path:this.path})).map(($)=>({user:P.byId(this.client,$.userId),accessLevel:$.accessLevel}))}async grant($,O){G(await this.client.storage.accessRequestsSetDirect({path:{...this.path,user_id:$.id},body:{accessLevel:O}}))}async remove($){G(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 G(await this.client.storage.accessRequestsResolve({path:{...this.path,request_id:$.id},body:O}))}toJSON(){return this.path}}class zO extends M{access;resolvedRecord;constructor($,O,j){super($,j.id,j);this.access=O}static from($,O,j){return new zO($,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",($)=>P.byId(this.client,$));async resolve($){this.resolvedRecord=await this.access.resolve(this,{revision:await this.revision(),grantedLevel:$}),this.detail.clear()}}function n$($){return{...$,channelSharePermissions:$.channelSharePermissions===void 0||$.channelSharePermissions===null?$.channelSharePermissions:$.channelSharePermissions.map((O)=>({channelId:O.channel.id,accessLevel:O.accessLevel,operation:O.operation}))}}class N$ extends M{parent;constructor($,O,j,x){super($,j,x);this.parent=O}static byId($,O,j){return new N$($,O,j)}static fromRecord($,O,j){return new N$($,O,j.id,j)}static async create($,O,j){return N$.createForSession($,O.session(),j,O)}static async createForSession($,O,j,x){let S=G(await $.agentHarness.createSessionReview({path:{session_id:O.id},body:{...j,executionId:x?.id??null}}));return N$.fromRecord($,O,S)}static async list($,O){return G(await $.agentHarness.listExecutionReviews({path:{session_id:O.session().id,execution_id:O.id}})).map((x)=>N$.fromRecord($,O.session(),x))}async fetch(){return G(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 vx($,{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 vx{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 uO extends M{parent;constructor($,O,j){super($,O);this.parent=j}static byId($,O,j){return new uO($,j,O)}async fetch(){return G(await this.client.agentHarness.getCodeExecution({path:{session_id:this.parent.id,execution_id:this.id}}))}reviews={create:($)=>N$.create(this.client,this,$),list:()=>N$.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 Lj{client;sessionId;dto;constructor($,O,j){this.client=$;this.sessionId=O;this.dto=j}static from($,O,j){return new Lj($,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 G(await this.client.agentHarness.editQueuedAction({path:{session_id:this.sessionId,action_id:this.actionId},body:{prompt:$}})),this.dto={...this.dto,prompt:$},this}async steer(){G(await this.client.agentHarness.steerQueuedAction({path:{session_id:this.sessionId,action_id:this.actionId}}))}async remove(){G(await this.client.agentHarness.removeQueuedAction({path:{session_id:this.sessionId,action_id:this.actionId}}))}}class dO{client;session;id;constructor($,O,j){this.client=$;this.session=O;this.id=j}static byId($,O,j){return new dO($,O,j)}async answer($){return G(await this.client.agentHarness.answerAgentSessionToolApproval({path:{session_id:this.session.id,approval_id:this.id},body:{answer:$}}))}toJSON(){return{id:this.id,sessionId:this.session.id}}}class i extends M{access=new o(this.client,"agent_session",this);toolApprovalById($){return dO.byId(this.client,this,$)}async sharePermissions(){return G(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:n$($)}))}static byId($,O){return new i($,O)}static async createManaged($,O){let{session:j}=G(await $.agentHarness.createAgentSession({body:{prompt:O?.prompt,instructions:O?.instructions,model:O?.model,repoUrl:O?.repoUrl,repoBranch:O?.repoBranch}}));return new i($,j.id,j)}static async repositories($){let{repositories:O}=G(await $.agentHarness.listAgentRepositories());return O.map((j)=>({url:j.url,defaultBranch:j.defaultBranch??void 0}))}static async repositoryBranches($,O){let{branches:j}=G(await $.agentHarness.listAgentRepositoryBranches({query:{repoUrl:O}}));return j}async fetch(){return G(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}=G(await $.agentHarness.agentSessionsForPullRequest({body:{url:O}}));return j.map((x)=>i.byId($,x))}async pullRequests(){let{pullRequests:$}=G(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?P.byId(this.client,O.linkedBy):void 0,createdAt:O.createdAt}))}async linkPullRequest($){G(await this.client.agentHarness.linkAgentSessionPullRequest({path:{session_id:this.id},body:{url:$}}))}async unlinkPullRequest($){G(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 G(await $.agentHarness.getAgentSandboxSize()).size}static async setDefaultSandboxSize($,O){return G(await $.agentHarness.putAgentSandboxSize({body:{size:O}})).size}static async codingPreferences($){return G(await $.agentHarness.getAgentCodingPreferences())}static async setCodingPreferences($,O){return G(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:$}=G(await this.client.agentHarness.getAgentSessionQueue({path:{session_id:this.id}}));return $.map((O)=>Lj.from(this.client,this.id,O))}async changes(){return G(await this.client.agentHarness.getAgentSessionChanges({path:{session_id:this.id}}))}async changesPatch(){return G(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}=G(await this.client.agentHarness.getAgentSessionFoldedLog({path:{session_id:this.id}}));return{bot:$,messages:O}}async log(){return G(await this.client.agentHarness.getAgentSessionLog({path:{session_id:this.id}}))}reviews={create:($)=>N$.createForSession(this.client,this,$),byId:($)=>N$.byId(this.client,this,$)};codeExecutions={byId:($)=>uO.byId(this.client,this,$)};async delete(){await this.mutate(($)=>$.agentHarness.deleteAgentSession({path:{session_id:this.id}}))}}class hx{client;constructor($){this.client=$}byId($){return i.byId(this.client,$)}createManaged($){return i.createManaged(this.client,$)}repositories(){return i.repositories(this.client)}repositoryBranches($){return i.repositoryBranches(this.client,$)}forPullRequest($){return i.forPullRequest(this.client,$)}defaultSandboxSize(){return i.defaultSandboxSize(this.client)}setDefaultSandboxSize($){return i.setDefaultSandboxSize(this.client,$)}codingPreferences(){return i.codingPreferences(this.client)}setCodingPreferences($){return i.setCodingPreferences(this.client,$)}}class mx{client;constructor($){this.client=$}byId($){return I$.byId(this.client,$)}async list(){return G(await this.client.storage.listAgents()).map(($)=>I$.from(this.client,$))}async create($){return I$.from(this.client,G(await this.client.storage.createAgent({body:gx($)})))}}class cx{client;async usage($={}){let{users:O,...j}=$;return G(await this.client.cognition.getUsageHandler({body:{...j,include_users:O?.map((x)=>x.id)}}))}constructor($){this.client=$}async structuredCompletion($){return G(await this.client.cognition.structuredCompletion({body:$}))}async decide($){return G(await this.client.cognition.decisions({body:$}))}}class s$ extends M{static byId($,O){return new s$($,O)}static from($,O){return new s$($,O.id,{id:O.id,name:O.name,createdAt:O.createdAt})}async fetch(){let $=G(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 ux{client;constructor($){this.client=$}byId($){return s$.byId(this.client,$)}async list(){return G(await this.client.storage.listUserApiKeys()).keys.map(($)=>s$.from(this.client,$))}async create($){let O=G(await this.client.storage.createUserApiKey({body:{name:$}}));return{key:s$.from(this.client,O),secret:O.key}}async tokenForEmail($){return G(await this.client.auth.macroApiToken({query:{email:$}}))}}class lO{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 G(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 G(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 M{async fetch(){let O=G(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=G(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 G(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",($)=>P.byId(this.client,$));async members(){let $=G(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:P.byId(this.client,O.user_id),role:O.role}))}}class T$ extends M{async fetch(){let{links:$}=G(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 T$($,O)}static async list($){let{links:O}=G(await $.email.listLinks());return O.map((j)=>new T$($,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 G(await this.client.email.mailboxSettingsOperations({headers:{"X-Email-Link-Id":this.id}}))}}class m$ extends M{async setContributesToAvailability($){await this.mutate((O)=>O.calendar.setAvailabilityCalendar({path:{calendar_id:this.id},body:{contributesToAvailability:$}}))}async fetch(){let{calendars:$}=G(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 m$($,O)}static async list($){let{calendars:O}=G(await $.calendar.listCalendars());return O.map((j)=>new m$($,j.id,j))}name=this.field("name");emailAddress=this.field("emailAddress");isPrimary=this.field("isPrimary");isWritable=this.field("isWritable");isSubscription=this.field("isSubscription");color=this.field("color");syncError=this.field("syncError");emailLink=this.mappedField("emailLinkId",($)=>T$.byId(this.client,$))}class rO{client;id;constructor($,O){this.client=$;this.id=O}async status(){return G(await this.client.calendar.calendarReplacementStatus({path:{operation_id:this.id}}))}async confirm(){return G(await this.client.calendar.confirmCalendarReplacement({path:{operation_id:this.id}}))}async discard(){G(await this.client.calendar.discardCalendarReplacement({path:{operation_id:this.id}}))}}class $$ extends M{async notes($){return this.requireOwnOccurrence($),G(await this.client.calendar.eventNotes({path:{event_id:this.id},query:{occurrenceKey:$.occurrenceKey}})).map((j)=>q$.fromRecord(this.client,this,$,j))}async linkNote($,O,j={}){return this.requireOwnOccurrence(O),G(await this.client.calendar.linkEventNote({path:{event_id:this.id,document_id:$.id},query:{occurrenceKey:O.occurrenceKey},body:{teamId:j.team?.id??null}})),q$.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",($)=>$?m$.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:h6($)}));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=G(await this.client.calendar.prepareCalendarReplacement({path:{event_id:this.id},body:{removeConference:$.removeConference,recurrenceId:$.recurrenceId,calendarId:$.calendar?.id}}));return new rO(this.client,O.operationId)}async providerUrl($={}){return G(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 G(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 h6($){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 q$ extends M{event;occurrence;fromDocument;constructor($,O,j,x,S,K=!1){super($,x.id,S);this.event=O;this.occurrence=j;this.fromDocument=K;if(j.eventId!==O.id)throw new f("Choose an occurrence belonging to this event")}static fromDocumentLink($,O,j){return new q$($,$$.byId($,j.eventId),j,O,{documentId:O.id,name:j.documentName,team:j.team,canManage:!0},!0)}static forDocument($,O,j,x){return new q$($,O,j,x)}static fromRecord($,O,j,x){return new q$($,O,j,w.byId($,x.documentId),x)}async fetch(){if(this.fromDocument){let x=G(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=G(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",($)=>w.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 G(await this.client.storage.getProjectPermissionsV2({path:{id:this.id}}))}async accessLevel(){return G(await this.client.storage.getProjectUserAccessLevel({path:{id:this.id}}))}access=new o(this.client,"project",this);entityType="project";propertyEntityType="PROJECT";async fetch(){let{data:$}=G(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}=G(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:$}=G(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 JO extends M{document;toJSON(){return{...super.toJSON(),documentId:this.document.id}}constructor($,O,j,x){super($,j,x);this.document=O}static byId($,O,j){return new JO($,O,j)}static from($,O,j){return new JO($,O,j.uuid,j)}async fetch(){let $=G(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 M{documentId;constructor($,O,j,x){super($,j,x);this.documentId=O}get path(){return{parent_type:"document",parent_id:this.documentId,id:this.id}}async fetch(){return G(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 w.byId(this.client,this.documentId)}async author(){return P.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 pO{client;document;id;detail;constructor($,O,j){this.client=$;this.document=O;this.id=j;this.detail=new W$(async()=>G(await this.client.storage.getDocumentVersion({path:{document_id:O.id,document_version_id:j}})).data)}static byId($,O,j){return new pO($,O,j)}read(){return this.detail.get()}toJSON(){return{id:this.id,documentId:this.document.id}}}var m6=8;class w extends X${async meetingNotes(){return G(await this.client.calendar.documentNoteLinks({path:{document_id:this.id}})).map((O)=>({note:q$.fromDocumentLink(this.client,this,O),eventTitle:O.eventTitle}))}async anchors(){return G(await this.client.storage.getDocumentAnchors({path:{document_id:this.id}})).data.map(($)=>JO.from(this.client,this,$))}async createHighlight($){return JO.from(this.client,this,G(await this.client.storage.createAnchor({path:{document_id:this.id},body:{...$,fileType:"pdf",anchorType:"highlight"}})))}version($){return pO.byId(this.client,this,$)}async sharePermissions(){return G(await this.client.storage.getDocumentPermissionsV2({path:{document_id:this.id}})).documentPermissions}async permissionsToken(){return G(await this.client.storage.getDocumentPermissionsToken({path:{document_id:this.id}})).token}async prepareSave($){return G(await this.client.storage.presaveDocumentHandler({path:{document_id:this.id},body:{newBom:$}})).data}async save($){return(await this.mutate((O)=>O.storage.saveDocumentHandler({path:{document_id:this.id},body:$}))).data}async simpleSave(){return(await this.mutate(($)=>$.storage.simpleSave({path:{document_id:this.id}}))).data}messageThreadById($){return L$.byId(this.client,{type:"document",entity:this},$)}timelinePage($){return w$(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:$}=G(await this.client.storage.getDocument({path:{document_id:this.id}}));return $.documentMetadata}static byId($,O){return new w($,O)}static async create($,O){let{documentId:j}=G(await $.storage.createMarkdownHandler({body:{documentName:O.name,markdown:O.markdown??null,projectId:O.project?.id??null}}));return new w($,j)}static async createSnippet($,O){let{documentId:j}=G(await $.storage.createSnippetHandler({body:{snippetName:O.name,markdown:O.markdown??null,projectId:O.project?.id??null}}));return new w($,j)}static async createSkill($,O){let{documentId:j}=G(await $.storage.createSkillHandler({body:{skillName:O.name,markdown:O.markdown??null,projectId:O.project?.id??null}}));return new w($,j)}static recent($,O){let j=O?.pageSize??50;return u(async(x)=>{let S=G(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 w($,Z.documentId)),nextCursor:K!=null?String(K):null}})}static async recentlyDeleted($){let{data:O}=G(await $.storage.recentlyDeleted({}));return O.items.filter((j)=>j.type==="document").map((j)=>new w($,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",($)=>P.byId(this.client,$));branchedFrom=this.mappedField("branchedFromId",($)=>$?w.byId(this.client,$):void 0);createdAt=this.field("createdAt");updatedAt=this.field("updatedAt");deletedAt=this.field("deletedAt");async content(){let{text:$}=G(await this.client.storage.getDocumentTextContent({path:{document_id:this.id}}));if($!==null)return $;let{presigned_url:O}=G(await this.client.storage.exportDocument({path:{document_id:this.id}})),j=await fetch(O);if(!j.ok)throw new GO(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}=G(await this.client.storage.copyDocument({path:{document_id:this.id},query:$.versionId!==void 0?{version_id:$.versionId}:void 0,body:{documentName:$.name}}));return new w(this.client,O.documentMetadata.documentId)}async comments(){let $={parent_type:"document",parent_id:this.id},O=u(async(x)=>{let S=G(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,m6,async(x)=>{let{state:S,root:K,replies:Z}=G(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 G(await this.client.storage.getDocumentShortId({path:{document_id:this.id}}))}async teamShare(){return G(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:$}=G(await this.client.storage.getDocumentGithubPullRequests({path:{document_id:this.id}}));return $}async branchName(){let{branchName:$}=G(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 w($,O.document_id)});toMention(){let $=this.detail.peek();return{tag:i$("m-document-mention",{documentId:this.id,documentName:$?.documentName??"",blockName:$?.fileType??"md"}),mention:{entity_type:"document",entity_id:this.id}}}}class dx{client;async noteDocuments($=""){let O=G(await this.client.calendar.noteDocuments({query:{query:$}}));return{documents:O.documents.map((j)=>({document:w.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 G(await this.client.calendar.getAvailabilityCalendars()).calendars.map(($)=>({calendar:m$.byId(this.client,$.calendarId),name:$.name,isPrimary:$.isPrimary,contributesToAvailability:$.contributesToAvailability}))}async teamSharing(){return G(await this.client.calendar.getTeamSharing()).sharing}async setTeamSharing($){return G(await this.client.calendar.setTeamSharing({body:{sharing:$}})).sharing}occurrences($){let O;return u(async(j)=>{let x=G(await this.client.storage.listOccurrences({query:{...$,cursor:j}}));O??=u6(this.client);let S=await O;return{items:x.items.map((K)=>({event:$$.fromRecord(this.client,K.event),occurrence:K.occurrence,inbox:K.event.calendarId?S.get(K.event.calendarId):void 0,role:d6(K.event)})),nextCursor:x.nextCursor}})}async teamPage($){let O=G(await this.client.storage.listTeamCalendar({query:$}));return{items:O.items.map(({ownerId:j,...x})=>({...x,owner:P.byId(this.client,j)})),members:O.members.map((j)=>({user:P.byId(this.client,j.userId),sharing:j.sharing,coverage:j.coverage})),nextCursor:O.nextCursor??void 0}}async teamOutOfOffice($){let O=G(await this.client.storage.listTeamOutOfOffice({query:$}));return{items:O.items.map((j)=>({event:$$.byId(this.client,j.eventId),owner:P.byId(this.client,j.ownerId),occurrenceKey:j.occurrenceKey,time:j.time,title:j.title??void 0})),hasMore:O.hasMore}}constructor($){this.client=$}calendars(){return m$.list(this.client)}calendar($){return m$.byId(this.client,$)}event($){return $$.byId(this.client,$)}replacement($){return new rO(this.client,$)}async createEvent($){let O=G(await this.client.calendar.createCalendarEvent({body:c6($)}));return $$.fromRecord(this.client,O)}}function c6($){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 u6($){let{calendars:O}=G(await $.calendar.listCalendars());return new Map(O.map((j)=>[j.id,j.emailAddress]))}function d6($){let O=$.attendees.find((j)=>j.isSelf);if($.viewerCan.organize||O?.isOrganizer)return"organizer";return O?"guest":void 0}class H$ extends M{lookupToken;constructor($,O,j){super($,O,j);this.lookupToken=j?.shareToken}static byId($,O){return new H$($,O)}static from($,O){return new H$($,O.id,O)}async fetch(){if(this.lookupToken)return G(await this.client.storage.meetingLookup({path:{token:this.lookupToken}}));let $=G(await this.client.storage.meetingList()).meetings.find((O)=>O.id===this.id);if(!$)throw new E(`Meeting ${this.id} is unavailable`);return this.lookupToken=$.shareToken,$}title=this.field("title");scheduledStart=this.field("scheduledStart");scheduledEnd=this.field("scheduledEnd");channel=this.mappedField("channelId",($)=>$?b.byId(this.client,$):void 0);call=this.mappedField("callId",($)=>$?Q$.byId(this.client,$):void 0);async update($){await this.mutate((O)=>O.storage.meetingUpdate({path:{meeting_id:this.id},body:$}))}async cancel(){await this.mutate(($)=>$.storage.meetingCancel({path:{meeting_id:this.id}}))}async invitePermissions(){return G(await this.client.storage.meetingInvitePermissions({path:{token:(await this.detail.get()).shareToken}}))}async invite($){G(await this.client.storage.meetingInvite({path:{token:(await this.detail.get()).shareToken},body:{email:$}}))}async inviteUsers($){G(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 u$ extends M{callId;constructor($,O,j,x){super($,j,x);this.callId=O}get path(){return{parent_type:"call",parent_id:this.callId,id:this.id}}async fetch(){return G(await this.client.storage.entityMessageGetMessage({path:this.path}))}static byId($,O,j){return new u$($,O,j)}static from($,O,j){return new u$($,O,j.id,j)}content=this.field("content");createdAt=this.field("created_at");updatedAt=this.field("updated_at");call(){return Q$.byId(this.client,this.callId)}async author(){return P.byId(this.client,(await this.detail.get()).sender_id)}async reply($){let O=G(await this.client.storage.entityMessageCreate({path:{parent_type:"call",parent_id:this.callId},body:{...O$($),thread_id:this.callId}}));return u$.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 Q$ extends z${messageThreadById($){return L$.byId(this.client,{type:"call",entity:this},$)}timelinePage($){return w$(this.client,{type:"call",entity:this},(O)=>u$.from(this.client,this.id,O),$)}access=new o(this.client,"call",this);async meeting(){return H$.from(this.client,G(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 G(await this.client.storage.getCallRecord({path:{call_id:this.id}}))}static byId($,O){return new Q$($,O)}message($){return u$.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",($)=>P.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 Q$($,O.call_id)})}class lx{client;constructor($){this.client=$}byId($){return Q$.byId(this.client,$)}search($,O){return Q$.search(this.client,$,O)}}class rx{client;constructor($){this.client=$}async list(){let{labels:$}=G(await this.client.storage.listChannelLabels());return $}async create($,O=[]){return G(await this.client.storage.createChannelLabel({body:{name:$,channelIds:O.map((j)=>j.id)}}))}async createSmartTag($,O){return G(await this.client.storage.createChannelLabel({body:{name:$,rule:O}}))}async previewSmartTag($){return G(await this.client.storage.previewSmartTag({body:$}))}async updateSmartTag($,O,j){return G(await this.client.storage.renameChannelLabel({path:{label_id:$.id},body:{name:O,rule:j}}))}async rename($,O){return G(await this.client.storage.renameChannelLabel({path:{label_id:$.id},body:{name:O}}))}async delete($){G(await this.client.storage.deleteChannelLabel({path:{label_id:$.id}}))}async setLabel($,O){G(await this.client.storage.setChannelLabel({path:{channel_id:$.id},body:{labelId:O?.id??null}}))}}class px{client;async activity(){return G(await this.client.storage.getActivity()).map(($)=>new QO(this.client,b.byId(this.client,$.channel_id),$))}labels;constructor($){this.client=$;this.labels=new rx($)}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:$}=G(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}=G(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 aO{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 aO($,O,j,x)}async stop(){G(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 iO extends M{chat;constructor($,O,j){super($,j);this.chat=O}static byId($,O,j){return new iO($,O,j)}async fetch(){let $=G(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 aO.byId(this.client,K,S.stream_id,iO.byId(this.client,K,S.message_id))}access=new o(this.client,"chat",this);entityType="chat";propertyEntityType="CHAT";async fetch(){let{chat:$}=G(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}=G(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:$}=G(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:i$("m-document-mention",{documentId:this.id,documentName:this.detail.peek()?.name??"",blockName:"chat",blockParams:{}}),mention:{entity_type:"chat",entity_id:this.id}}}}class ax{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 l6=8;class M$ extends M{parent;constructor($,O,j,x){super($,j,x);this.parent=O}get path(){return{parent_type:this.parent.type,parent_id:this.parent.id,id:this.id}}async fetch(){return G(await this.client.storage.entityMessageGetMessage({path:this.path}))}static byId($,O,j){return new M$($,O,j)}static from($,O,j){return new M$($,O,j.id,j)}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 P.byId(this.client,(await this.detail.get()).sender_id)}async reply($){return nO(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 Nj($,O){let j={parent_type:O.type,parent_id:O.id},x=u(async(K)=>{let Z=G(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,l6,async(K)=>{let{state:Z,root:X,replies:Y}=G(await $.storage.entityMessageGetThread({path:{...j,id:K.id}}));return{thread:Z,comments:[X,...Y].map((L)=>M$.from($,O,L))}})}async function nO($,O,j,x){let S=G(await $.storage.entityMessageCreate({path:{parent_type:O.type,parent_id:O.id},body:{...O$(j),thread_id:x?.threadId??null}}));return M$.from($,O,S)}class f$ extends z${messageThreadById($){return L$.byId(this.client,{type:"crm_contact",entity:this},$)}timelinePage($){return w$(this.client,{type:"crm_contact",entity:this},(O)=>M$.from(this.client,{type:"crm_contact",id:this.id},O),$)}entityType="crm_contact";async fetch(){return G(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 Nj(this.client,this.commentParent)}async comment($,O){return nO(this.client,this.commentParent,$,O)}commentById($){return M$.byId(this.client,this.commentParent,$)}}class b$ extends X${messageThreadById($){return L$.byId(this.client,{type:"crm_company",entity:this},$)}timelinePage($){return w$(this.client,{type:"crm_company",entity:this},(O)=>M$.from(this.client,{type:"crm_company",id:this.id},O),$)}entityType="crm_company";propertyEntityType="COMPANY";async fetch(){return G(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 G(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 Nj(this.client,this.commentParent)}async comment($,O){return nO(this.client,this.commentParent,$,O)}commentById($){return M$.byId(this.client,this.commentParent,$)}}class t$ extends M{tableDetail=new W$(async()=>G(await this.client.storage.getCrmPipelineTable({path:{id:this.id}})));static byId($,O){return new t$($,O)}static from($,O){return new t$($,O.id,O)}async fetch(){return G(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",($)=>P.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 G(await this.client.storage.getCrmPipelinePermissions({path:{id:this.id}}))}async updateSharePermissions($){return this.mutate((O)=>O.storage.updateCrmPipelinePermissions({path:{id:this.id},body:n$($)}))}async table(){return Uj.from(this.client,this,await this.tableRecord())}tableRecord(){return this.tableDetail.get()}rows(){return u(async($)=>{let O=G(await this.client.storage.getCrmPipelineRows({path:{id:this.id},query:{after:$}}));return{items:O.rows.map((j)=>VO.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 u(async(O)=>{let j=G(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)=>VO.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 Uj extends M{pipeline;toJSON(){return{...super.toJSON(),pipelineId:this.pipeline.id}}constructor($,O,j){super($,j.table.id,j);this.pipeline=O}static from($,O,j){return new Uj($,O,j)}fetch(){return this.pipeline.tableRecord()}async columns(){return(await this.pipeline.tableRecord()).columns.map(($)=>zj.from(this.client,this,$))}async version(){return(await this.pipeline.tableRecord()).table.version}rowById($){return VO.byId(this.client,this.pipeline,$)}rows(){return this.pipeline.rows()}}class VO extends M{pipeline;toJSON(){return{...super.toJSON(),pipelineId:this.pipeline.id}}constructor($,O,j,x){super($,j,x);this.pipeline=O}static byId($,O,j){return new VO($,O,j)}static from($,O,j){return new VO($,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 zj extends M{table;toJSON(){return{...super.toJSON(),pipelineId:this.table.pipeline.id,tableId:this.table.id}}constructor($,O,j){super($,j.column.id,j);this.table=O}static from($,O,j){return new zj($,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 ix{client;constructor($){this.client=$}byId($){return t$.byId(this.client,$)}async list(){return G(await this.client.storage.listCrmPipelines()).map(($)=>t$.from(this.client,$))}async create($){return t$.from(this.client,G(await this.client.storage.createCrmPipeline({body:$})))}}class nx{client;pipelines;constructor($){this.client=$;this.pipelines=new ix($)}companyById($){return b$.byId(this.client,$)}contactById($){return f$.byId(this.client,$)}async contactByEmail($){let{contact:O}=G(await this.client.storage.getContactByEmail({query:{email:$}}));return O?f$.from(this.client,O):void 0}async searchContacts($,O={}){let{contacts:j}=G(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,G(await this.client.storage.createCrmCompany({body:$})))}async settings(){return G(await this.client.storage.getCrmTeamSettings())}async updateSettings($){return G(await this.client.storage.putCrmTeamSettings({body:$}))}async setStages($){return G(await this.client.storage.putCrmTeamStages({body:$}))}async resetStages(){G(await this.client.storage.resetCrmTeamStages())}searchCompanies($){return b$.search(this.client,$)}}var G$=Symbol.for("@ts-pattern/matcher"),v1=Symbol.for("@ts-pattern/isVariadic");var sx=($)=>Boolean($&&typeof $=="object"),Ij=($)=>$&&!!$[G$],s=($,O,j)=>{if(Ij($)){let x=$[G$](),{matched:S,selections:K}=x.match(O);return S&&K&&Object.keys(K).forEach((Z)=>j(Z,K[Z])),S}if(sx($)){if(!sx(O))return!1;if(Array.isArray($)){if(!Array.isArray(O))return!1;let x=[],S=[],K=[];for(let Z of $.keys()){let X=$[Z];Ij(X)&&X[v1]?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),Y=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],Y,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)||Ij(K=S)&&K[G$]().matcherType==="optional")&&s(S,O[x],j);var K})}return Object.is(O,$)},Y$=($)=>{var O,j,x;return sx($)?Ij($)?(O=(j=(x=$[G$]()).getSelectionKeys)==null?void 0:j.call(x))!=null?O:[]:Array.isArray($)?sO($,Y$):sO(Object.values($),Y$):[]},sO=($,O)=>$.reduce((j,x)=>j.concat(O(x)),[]);function r6(...$){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:()=>ox($),and:(O)=>d($,O),or:(O)=>h1($,O),select:(O)=>O===void 0?tO($):tO(O,$)})}function tx($){return Object.assign(((O)=>Object.assign(O,{[Symbol.iterator](){let j=0,x=[{value:Object.assign(O,{[v1]:!0}),done:!1},{done:!0,value:void 0}];return{next:()=>{var S;return(S=x[j++])!=null?S:x.at(-1)}}}}))($),{optional:()=>tx(ox($)),select:(O)=>tx(O===void 0?tO($):tO(O,$))})}function ox($){return t({[G$]:()=>({match:(O)=>{let j={},x=(S,K)=>{j[S]=K};return O===void 0?(Y$($).forEach((S)=>x(S,void 0)),{matched:!0,selections:j}):{matched:s($,O,x),selections:j}},getSelectionKeys:()=>Y$($),matcherType:"optional"})})}var p6=($,O)=>{for(let j of $)if(!O(j))return!1;return!0},a6=($,O)=>{for(let[j,x]of $.entries())if(!O(x,j))return!1;return!0},i6=($,O)=>{let j=Reflect.ownKeys($);for(let x of j)if(!O(x,$[x]))return!1;return!0};function d(...$){return t({[G$]:()=>({match:(O)=>{let j={},x=(S,K)=>{j[S]=K};return{matched:$.every((S)=>s(S,O,x)),selections:j}},getSelectionKeys:()=>sO($,Y$),matcherType:"and"})})}function h1(...$){return t({[G$]:()=>({match:(O)=>{let j={},x=(S,K)=>{j[S]=K};return sO($,Y$).forEach((S)=>x(S,void 0)),{matched:$.some((S)=>s(S,O,x)),selections:j}},getSelectionKeys:()=>sO($,Y$),matcherType:"or"})})}function m($){return{[G$]:()=>({match:(O)=>({matched:Boolean($(O))})})}}function tO(...$){let O=typeof $[0]=="string"?$[0]:void 0,j=$.length===2?$[1]:typeof $[0]=="string"?void 0:$[0];return t({[G$]:()=>({match:(x)=>{let S={[O!=null?O:"@ts-pattern/anonymous-select-key"]:x};return{matched:j===void 0||s(j,x,(K,Z)=>{S[K]=Z}),selections:S}},getSelectionKeys:()=>[O!=null?O:"@ts-pattern/anonymous-select-key"].concat(j===void 0?[]:Y$(j))})})}function m1($){return!0}function k$($){return typeof $=="number"}function e$($){return typeof $=="string"}function o$($){return typeof $=="bigint"}var c1=t(m(m1)),n6=t(m(m1)),s6=c1,$O=($)=>Object.assign(t($),{startsWith:(O)=>{return $O(d($,(j=O,m((x)=>e$(x)&&x.startsWith(j)))));var j},endsWith:(O)=>{return $O(d($,(j=O,m((x)=>e$(x)&&x.endsWith(j)))));var j},minLength:(O)=>$O(d($,((j)=>m((x)=>e$(x)&&x.length>=j))(O))),length:(O)=>$O(d($,((j)=>m((x)=>e$(x)&&x.length===j))(O))),maxLength:(O)=>$O(d($,((j)=>m((x)=>e$(x)&&x.length<=j))(O))),includes:(O)=>{return $O(d($,(j=O,m((x)=>e$(x)&&x.includes(j)))));var j},regex:(O)=>{return $O(d($,(j=O,m((x)=>e$(x)&&Boolean(x.match(j))))));var j}}),y1=$O(m(e$)),g$=($)=>Object.assign(t($),{between:(O,j)=>g$(d($,((x,S)=>m((K)=>k$(K)&&x<=K&&S>=K))(O,j))),lt:(O)=>g$(d($,((j)=>m((x)=>k$(x)&&x<j))(O))),gt:(O)=>g$(d($,((j)=>m((x)=>k$(x)&&x>j))(O))),lte:(O)=>g$(d($,((j)=>m((x)=>k$(x)&&x<=j))(O))),gte:(O)=>g$(d($,((j)=>m((x)=>k$(x)&&x>=j))(O))),int:()=>g$(d($,m((O)=>k$(O)&&Number.isInteger(O)))),finite:()=>g$(d($,m((O)=>k$(O)&&Number.isFinite(O)))),positive:()=>g$(d($,m((O)=>k$(O)&&O>0))),negative:()=>g$(d($,m((O)=>k$(O)&&O<0)))}),t6=g$(m(k$)),OO=($)=>Object.assign(t($),{between:(O,j)=>OO(d($,((x,S)=>m((K)=>o$(K)&&x<=K&&S>=K))(O,j))),lt:(O)=>OO(d($,((j)=>m((x)=>o$(x)&&x<j))(O))),gt:(O)=>OO(d($,((j)=>m((x)=>o$(x)&&x>j))(O))),lte:(O)=>OO(d($,((j)=>m((x)=>o$(x)&&x<=j))(O))),gte:(O)=>OO(d($,((j)=>m((x)=>o$(x)&&x>=j))(O))),positive:()=>OO(d($,m((O)=>o$(O)&&O>0))),negative:()=>OO(d($,m((O)=>o$(O)&&O<0)))}),e6=OO(m(o$)),o6=t(m(function($){return typeof $=="boolean"})),$7=t(m(function($){return typeof $=="symbol"})),O7=t(m(function($){return $==null})),j7=t(m(function($){return $!=null})),Z$={__proto__:null,matcher:G$,optional:ox,array:function(...$){return tx({[G$]:()=>({match:(O)=>{if(!Array.isArray(O))return{matched:!1};if($.length===0)return{matched:!0};let j=$[0],x={};if(O.length===0)return Y$(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?[]:Y$($[0])})})},set:function(...$){return t({[G$]:()=>({match:(O)=>{if(!(O instanceof Set))return{matched:!1};let j={};if(O.size===0)return{matched:!0,selections:j};if($.length===0)return{matched:!0};let x=(K,Z)=>{j[K]=(j[K]||[]).concat([Z])},S=$[0];return{matched:p6(O,(K)=>s(S,K,x)),selections:j}},getSelectionKeys:()=>$.length===0?[]:Y$($[0])})})},map:function(...$){return t({[G$]:()=>({match:(O)=>{if(!(O instanceof Map))return{matched:!1};let j={};if(O.size===0)return{matched:!0,selections:j};let x=(X,Y)=>{j[X]=(j[X]||[]).concat([Y])};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:a6(O,(X,Y)=>{let L=s(K,Y,x),Q=s(Z,X,x);return L&&Q}),selections:j}},getSelectionKeys:()=>$.length===0?[]:[...Y$($[0]),...Y$($[1])]})})},record:function(...$){return t({[G$]:()=>({match:(O)=>{if(O===null||typeof O!="object"||Array.isArray(O))return{matched:!1};var j;if($.length===0)throw Error(`\`P.record\` wasn't given enough arguments. Expected (value) or (key, value), received ${(j=$[0])==null?void 0:j.toString()}`);let x={},S=(X,Y)=>{x[X]=(x[X]||[]).concat([Y])},[K,Z]=$.length===1?[y1,$[0]]:$;return{matched:i6(O,(X,Y)=>{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,Y,S);return(J||Q)&&I}),selections:x}},getSelectionKeys:()=>$.length===0?[]:[...Y$($[0]),...Y$($[1])]})})},intersection:d,union:h1,not:function($){return t({[G$]:()=>({match:(O)=>({matched:!s($,O,()=>{})}),getSelectionKeys:()=>[],matcherType:"not"})})},when:m,select:tO,any:c1,unknown:n6,_:s6,string:y1,number:t6,bigint:e6,boolean:o6,symbol:$7,nullish:O7,nonNullable:j7,instanceOf:function($){return t(m(function(O){return(j)=>j instanceof O}($)))},shape:function($){return t(m(r6($)))}};class u1 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 ex={matched:!1,value:void 0};function c($){return new Tj($,ex)}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=(Y,L)=>{S=!0,K[Y]=L},X=!j.some((Y)=>s(Y,this.input,Z))||x&&!Boolean(x(this.input))?ex:{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)}:ex)}otherwise($){return this.state.matched?this.state.value:$(this.input)}exhaustive($=x7){return this.state.matched?this.state.value:$(this.input)}run(){return this.exhaustive()}returnType(){return this}narrow(){return this}}function x7($){throw new u1($)}var $0,S7=new Uint8Array(16);function Hj(){if(!$0){if(typeof crypto>"u"||!crypto.getRandomValues)throw Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");$0=crypto.getRandomValues.bind(crypto)}return $0(S7)}var j$=[];for(let $=0;$<256;++$)j$.push(($+256).toString(16).slice(1));function d1($,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 O0={};function Z7($,O,j){let x;if($)x=l1($.random??$.rng?.()??Hj(),$.msecs,$.seq,O,j);else{let S=Date.now(),K=Hj();X7(O0,S,K),x=l1(K,O0.msecs,O0.seq,O,j)}return O??d1(x)}function X7($,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 l1($,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 d$=Z7;class A${table;id;constructor($,O){this.table=$;this.id=O}static byId($,O){return new A$($,O)}async detail(){let{columns:$}=await this.table.detail(),O=$.find((j)=>j.column.id===this.id);if(!O)throw new E(`column ${this.id} is not on table ${this.table.id}`);return O}async name(){let $=await this.detail();return $.column.display_name??$.definition.definition.display_name}async rename($){return await this.table.database.renameColumn(this,$),this}async inferType($){return await this.table.database.inferColumnType(this,$),this}changeType($){return this.table.database.changeColumnType(this,$)}convertIntoNewColumn($){return this.table.database.convertColumnIntoNewColumn(this,$)}casts(){return this.table.database.columnCasts(this)}async delete(){await this.table.database.deleteColumn(this)}async dataType(){return(await this.detail()).definition.definition.data_type}async isMultiSelect(){return(await this.detail()).definition.definition.is_multi_select}async position(){return(await this.detail()).column.position}async definition(){return(await this.detail()).definition}async config(){return(await this.detail()).column.config??void 0}async addOptions($){return await this.table.database.addColumnOptions(this,$),this}toJSON(){return{id:this.id,tableId:this.table.id}}}class 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 Rj{table;id;constructor($,O){this.table=$;this.id=O}static byId($,O){return new Rj($,O)}async detail(){let{views:$}=await this.table.detail(),O=$.find((j)=>j.id===this.id);if(!O)throw new E(`view ${this.id} is not on table ${this.table.id}`);return O}async name(){return(await this.detail()).name}async position(){return(await this.detail()).position}async layout(){return(await this.detail()).layout}async query(){return(await this.detail()).query}positions(){return this.table.database.viewPositions(this)}toJSON(){return{id:this.id,tableId:this.table.id}}}class J${database;id;constructor($,O){this.database=$;this.id=O}static byId($,O){return new J$($,O)}async detail(){let{tables:$}=await this.database.schema(),O=$.find((j)=>j.table.id===this.id);if(!O)throw new E(`table ${this.id} is not in database ${this.database.id}`);return O}async name(){return(await this.detail()).table.name}async rename($){return await this.database.renameTable(this,$),this}async version(){return(await this.detail()).table.version}async position(){return(await this.detail()).table.position}async columns(){let{columns:$}=await this.detail();return $.map((O)=>A$.byId(this,O.column.id))}addColumn($){return this.database.addColumn(this,$)}async reorderColumns($){return await this.database.reorderColumns(this,$),this}row($){return F$.byId(this,$)}async views(){let{views:$}=await this.detail();return $.map((O)=>Rj.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 Dj($,O,j,x={}){let S=G(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 J$.byId(Z(J),Q)},Y=new Set(Object.keys(S.newVersions).map((Q)=>X(Q).database.id));if(S.statement.kind==="schema")Y.add(S.statement.databaseId);for(let Q of Y)for(let J of K.get(Q)??[])J.invalidateSchema();let L=c(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:A$.byId(V,I),columnName:z,to:W}}).exhaustive();return{result:S.result?K7(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 K7($,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 _j{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 _j($,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 S0 extends GO{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 Cj($){return c($).with({type:"relation"},({table:O})=>({type:"relation",database:O.database.id,table:O.id})).with({type:Z$.not("relation")},(O)=>O).exhaustive()}var Y7={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 G7($){return c($).with({type:"text"},()=>"Text").with({type:"number"},()=>"Number").with({type:"boolean"},()=>"Checkbox").with({type:"date"},()=>"Date").with({type:"link"},()=>"URL").with({type:"select",multi:!0},()=>"Multi-select").with({type:"select",multi:!1},()=>"Select").with({type:"select_number",multi:!0},()=>"Multi-number select").with({type:"select_number",multi:!1},()=>"Number select").with({type:"tag"},()=>"Tag").with({type:"entity"},({target:O})=>Y7[O]).with({type:"relation"},()=>"Relation").exhaustive(()=>"Column")}function j0($){return $.map((O)=>({id:d$(),label:O}))}function r1($,O,j){return $?.kind===O&&"change"in $&&$.change.kind===j}function x0($){return c($).with({kind:"reorder_tables"},({kind:O})=>O).with({kind:Z$.union("table","column","rows","view")},({kind:O,change:j})=>`${O}.${j.kind}`).exhaustive(()=>"unknown")}function l$($,O,j){let[x]=$;if($.length!==1||!r1(x,O,j))throw new f(`expected one ${O}.${j} result, got ${$.map(x0).join(", ")||"none"}`);return x}class V$ extends M{access=new o(this.client,"database",this);async fetch(){return G(await this.client.storage.getDatabase({path:{id:this.id}}))}assertOwns($,O){if(O.id!==this.id)throw new f(`${$} does not belong to database ${this.id}`)}static byId($,O){return new V$($,O)}static async create($,O){let j=G(await $.storage.createDatabase({body:{name:O.name}}));return new V$($,j.id)}static async list($){return G(await $.storage.listDatabases()).map((j)=>new V$($,j.database.id))}query($,O){return Dj(this.client,V$.byId,$,{...O,database:this})}invalidateSchema(){this.detail.clear()}schema(){return this.detail.get()}name=this.mappedField("database",($)=>$.name);owner=this.mappedField("database",($)=>P.byId(this.client,$.owner_id));createdAt=this.mappedField("database",($)=>$.created_at);trashedAt=this.mappedField("database",($)=>$.trashed_at??void 0);grant=this.field("grant");tables=this.mappedField("tables",($)=>$.map((O)=>J$.byId(this,O.table.id)));async table($){let{tables:O}=await this.schema(),j=O.find((x)=>x.table.name===$);return j?J$.byId(this,j.table.id):void 0}async createTable($){let{table:O}=l$(await this.applyOps([{kind:"table",table:d$(),change:{kind:"create",name:$.name}}]),"table","created");return J$.byId(this,O)}async applyOps($,O={}){let j={ops:$};if(O.baseVersions!==void 0){for(let{table:S}of O.baseVersions)this.assertOwns(`table ${S.id}`,S.database);j.baseVersions=Object.fromEntries(O.baseVersions.map(({table:S,version:K})=>[S.id,K]))}let{results:x}=await this.mutate(async(S)=>{let K=await S.storage.applyDatabaseOps({path:{id:this.id},body:j});if(K.error!==void 0&&"op"in K.error)throw new S0(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(x0).join(", ")||"none"}`);return j.tables.map(({table:x})=>J$.byId(this,x))}async deleteTable($){this.assertOwns(`table ${$.id}`,$.database),l$(await this.applyOps([{kind:"table",table:$.id,change:{kind:"delete"}}]),"table","deleted")}async columnCasts($){return this.assertOwns(`column ${$.id}`,$.table.database),G(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}=G(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}=G(await this.client.storage.getDatabaseRowHistory({path:{id:this.id,table_id:$.table.id,row_id:$.id}}));return O}async importTable($){let O=await this.mutate((j)=>j.storage.importDatabaseTable({path:{id:this.id},body:$}));return J$.byId(this,O.id)}webhookOf($){return _j.fromRecord(J$.byId(this,$.tableId),P.byId(this.client,$.createdBy),$)}async webhooks(){let{webhooks:$}=G(await this.client.storage.listDatabaseWebhooks({path:{id:this.id}}));return $.map((O)=>this.webhookOf(O))}async createWebhook($){this.assertOwns("table",$.database);let O=G(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),G(await this.client.storage.deleteDatabaseWebhook({path:{id:this.id,webhook_id:$.id}}))}async sharePermissions(){return G(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 l$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"change_type",to:Cj(O.to)}}],{baseVersions:[{table:$.table,version:j}]}),"column","type_changed")}async columnConversion($,O){return this.assertOwns(`column ${$.id}`,$.table.database),G(await this.client.storage.convertDatabaseColumn({path:{id:this.id,table_id:$.table.id,column_id:$.id},body:{to:Cj(O)}}))}async convertColumnIntoNewColumn($,O){let j=await this.columnConversion($,O.to),x=O.name??`${await $.name()} (${G7(O.to)})`,S=d$(),K=[{kind:"column",table:$.table.id,column:S,change:{kind:"create",definition:{source:"new",name:x,type:Cj(O.to),options:j0(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:Y})=>({row:X,cells:[{column:S,value:Y}]}))}}});let[Z]=await this.applyOps(K,{baseVersions:[{table:$.table,version:j.tableVersion}]});if(!r1(Z,"column","created"))throw new f(`expected a column.created result, got ${Z?x0(Z):"none"}`);return A$.byId($.table,Z.column)}async deleteColumn($){this.assertOwns(`column ${$.id}`,$.table.database);let O=await $.table.version(),{tableVersion:j}=l$(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}=l$(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}=l$(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}=l$(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:Cj(O.type),...O.options!==void 0?{options:j0(O.options)}:{},...O.inferType!==void 0?{inferType:O.inferType}:{}},{column:x}=l$(await this.applyOps([{kind:"column",table:$.id,column:d$(),change:{kind:"create",definition:j,...O.after!==void 0?{after:O.after.id}:{}}}]),"column","created");return A$.byId($,x)}async addColumnOptions($,O){return this.assertOwns(`column ${$.id}`,$.table.database),l$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"add_options",options:j0(O)}}]),"column","options_added")}}class Z0{client;constructor($){this.client=$}query($,O){return Dj(this.client,V$.byId,$,O)}byId($){return V$.byId(this.client,$)}create($){return V$.create(this.client,$)}list(){return V$.list(this.client)}}class Pj{id;name;constructor($,O){this.id=$;this.name=O}static async list($){let{skills:O}=G(await $.storage.getSystemSkillsHandler());return O.map((j)=>new Pj(j.id,j.name))}}class X0{client;async byTeamSlug($){let O=G(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 w.byId(this.client,O.data.documentMetadata.documentId)}async validatePermissionsToken($){let O=G(await this.client.storage.validateDocumentPermissionsToken({body:{token:$}}));return{document:w.byId(this.client,O.document_id),user:O.user_id?P.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=G(await this.client.storage.createDocument({body:O})).data;return{document:w.byId(this.client,j.documentMetadata.documentId),uploadUrl:j.presignedUrl??void 0,contentType:j.contentType,content:j.documentMetadata.content}}constructor($){this.client=$}byId($){return w.byId(this.client,$)}create($){return w.create(this.client,$)}async createCanvas($){let O=G(await this.client.storage.createCanvasHandler({body:{documentName:$.name,projectId:$.project?.id}}));return w.byId(this.client,O.documentId)}createSnippet($){return w.createSnippet(this.client,$)}createSkill($){return w.createSkill(this.client,$)}systemSkills(){return Pj.list(this.client)}search($,O){return w.search(this.client,$,O)}recent($){return w.recent(this.client,$)}recentlyDeleted(){return w.recentlyDeleted(this.client)}}class WO extends M{async fetch(){let{attachment:$}=G(await this.client.email.getAttachment({path:{id:this.id}}));return $}static byId($,O){return new WO($,O)}static from($,O){return new WO($,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:$}=G(await this.client.email.getAttachmentDocumentId({path:{id:this.id}}));return w.byId(this.client,$)}}class R$ extends X${access=new o(this.client,"email_thread",this);async followup(){return G(await this.client.storage.getEmailFollowup({path:{thread_id:this.id}}))}async setFollowup($){return G(await this.client.storage.setEmailFollowup({path:{thread_id:this.id},body:$}))}async calendarInvitations(){return G(await this.client.email.getThreadCalendarInvitations({path:{thread_id:this.id}}))}async addEventToCalendar($,O,j={}){let x=G(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?n$($.sharePermission):void 0}}))}entityType="email_thread";propertyEntityType="THREAD";async fetch(){let{thread:$}=G(await this.client.email.getThread({path:{thread_id:this.id},query:{limit:100}}));return $}static byId($,O){return new R$($,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",($)=>T$.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 G(await this.client.email.getThreadMessagesHandler({path:{id:this.id},query:{...$?.since?{since:$.since}:{},...$?.limit?{limit:$.limit}:{}}})).map((j)=>D$.from(this.client,j))}async attachments(){let{messages:$}=await this.detail.get();return $.flatMap((O)=>O.attachments.map((j)=>WO.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?D$.byId(this.client,j.db_id):void 0}async archive($=!0){await this.mutate((O)=>O.email.archiveThread({path:{id:this.id},body:{value:$}}))}async updateState($){await this.mutate((O)=>O.email.updateThreadState({path:{id:this.id},body:$}))}async operations(){return G(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 R$($,O.thread_id)})}class D$ extends M{async fetch(){return G(await this.client.email.getMessage({path:{id:this.id}}))}static byId($,O){return new D$($,O)}static from($,O){return new D$($,O.db_id,O)}static async send($,O){let{message:j}=G(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?D$.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",($)=>T$.byId(this.client,$));async operationStatus(){return G(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 R$.byId(this.client,(await this.detail.get()).thread_db_id)}}class BO extends D${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 BO($,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:{...K0($),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:eO.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 eO.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 eO{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 eO(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 K0($){let{bodyText:O,bodyHtml:j,bodyMacro:x,headers:S,includeSignature:K,draftGeneration:Z,thread:X,replyingTo:Y,...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:Y?.id}}class LO extends M{inbox;constructor($,O,j,x){super($,O,j);this.inbox=x}get headers(){return this.inbox?{"X-Email-Link-Id":this.inbox.id}:void 0}static byId($,O,j){return new LO($,O,void 0,j)}static from($,O,j){return new LO($,O.id,O,j)}async fetch(){let $=G(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 jO extends M{async fetch(){let{labels:$}=G(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 jO($,O)}static async list($){let{labels:O}=G(await $.email.listLabels());return O.map((j)=>new jO($,j.id,j))}static async create($,O){let{label:j}=G(await $.email.createLabel({body:{label_name:O}}));if(!j.id)throw new f("created label has no id");return new jO($,j.id)}async delete(){G(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 Y0{client;async createDraft($,O){let j=G(await this.client.email.createDraft({body:{draft:K0($)},headers:O?{"X-Email-Link-Id":O.id}:void 0}));if(!j.draft.db_id)throw Error("Draft response has no message id");return BO.byId(this.client,j.draft.db_id)}draftById($){return BO.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=G(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 BO.byId(this.client,K.db_id);if(S.messages.length<j)return}}async filters($){return G(await this.client.email.listEmailFilters({headers:$?{"X-Email-Link-Id":$.id}:void 0})).filters.map((O)=>LO.from(this.client,O,$))}async upsertFilter($,O){return LO.from(this.client,G(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 G(await this.client.email.listContacts()).contacts}reminders($){let{inboxes:O,...j}=$??{};return u(async(x)=>{let S=G(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:R$.byId(this.client,K)})),nextCursor:S.nextCursor}})}constructor($){this.client=$}byId($){return R$.byId(this.client,$)}message($){return D$.byId(this.client,$)}attachment($){return WO.byId(this.client,$)}link($){return T$.byId(this.client,$)}links(){return T$.list(this.client)}async connectionProviders(){return G(await this.client.auth.emailConnectionProviders())}async recoverDraftTransfer($){return G(await this.client.email.recoverDraftTransfer({path:{id:$}}))}send($){return D$.send(this.client,$)}search($,O){return R$.search(this.client,$,O)}inbox($){return u(async(O)=>{let j=G(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)=>R$.byId(this.client,x.id)),nextCursor:j.next_cursor}})}label($){return jO.byId(this.client,$)}labels(){return jO.list(this.client)}createLabel($){return jO.create(this.client,$)}async deleteLabel($){G(await this.client.email.deleteLabel({path:{id:$.id}}))}async blockSender($){G(await this.client.email.blockSender({body:{email_address:$}}))}async unblockSender($){G(await this.client.email.unblockSender({body:{email_address:$}}))}async blockedSenders(){return G(await this.client.email.listBlockedSenders()).blocked_emails}}class IO{client;id;constructor($,O){this.client=$;this.id=O}static byId($,O){return new IO($,O)}async delete(){G(await this.client.storage.deleteEntityMention({path:{mention_id:this.id}}))}toJSON(){return{id:this.id}}}class G0{client;constructor($){this.client=$}byId($){return IO.byId(this.client,$)}async create($,O){let j=G(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 IO.byId(this.client,j.id)}}class Q0{client;constructor($){this.client=$}async list($={}){let{favorites:O}=G(await this.client.storage.listFavorites({query:{entityType:$.entityTypes,entityId:$.entityIds}}));return O}async add($){return G(await this.client.storage.addFavorite({body:{entityId:$.id,entityType:$.entityType}}))}async remove($){G(await this.client.storage.removeFavoriteByEntity({path:{entity_type:$.entityType,entity_id:$.id}}))}async reorder($){G(await this.client.storage.reorderFavorites({body:{favorites:$}}))}}class xO extends z${entityType="foreign_entity";async fetch(){return G(await this.client.storage.getForeignEntity({path:{id:this.id}}))}static byId($,O){return new xO($,O)}static fromRecord($,O){return new xO($,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 p1({login:$,...O}){return{...O,login:$??void 0}}class J0{client;constructor($){this.client=$}byId($){return xO.byId(this.client,$)}async bySource($,O){return xO.fromRecord(this.client,G(await this.client.storage.getForeignEntityBySource({path:{source:$,foreign_entity_id:O}})))}async githubPullRequestFacets(){let{repositories:$,authors:O,assignees:j,labels:x}=G(await this.client.storage.getGithubPullRequestFacets());return{repositories:$,authors:O.map(p1),assignees:j.map(p1),labels:x.map(({color:S,...K})=>({...K,color:S??void 0}))}}}class r${form;id;constructor($,O){this.form=$;this.id=O}static byId($,O){return new r$($,O)}async detail(){let O=(await this.form.schema()).sections.flatMap((j)=>j.kind==="questions"?j.questions:[]).find((j)=>j.id===this.id);if(!O)throw new E(`question ${this.id} is not on form ${this.form.id}`);return O}async title(){return(await this.detail()).title}async column(){return A$.byId(await this.form.table(),(await this.detail()).column)}async options(){return(await this.detail()).options.map(($)=>NO.byId(this,$.id))}}class NO{question;id;constructor($,O){this.question=$;this.id=O}static byId($,O){return new NO($,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 TO{form;id;detail;constructor($,O,j){this.form=$;this.id=O;this.detail=new W$(()=>this.load(),j)}async load(){let $=await this.form.myResponse();if($.response.id!==this.id)throw new E(`response ${this.id} is not your current response`);return $}static byId($,O,j){return new TO($,O,j)}async status(){return(await this.detail.get()).status}async row(){return(await this.detail.get()).row}async answers(){return(await this.detail.get()).answers}async booking(){return(await this.detail.get()).booking}async refresh(){let $=await this.load();return this.detail=new W$(()=>this.load(),$),this}}class p${form;id;constructor($,O){this.form=$;this.id=O}static byId($,O){return new p$($,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)=>r$.byId(this.form,O.id)):[]}}class Mj{entityType;id;constructor($,O){this.entityType=$;this.id=O}static byId($,O){return new Mj($,O)}}class y$ extends M{async fetch(){return G(await this.client.storage.getForm({path:{id:this.id}}))}static byId($,O){return new y$($,O)}static async create($,O){let j=G(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 y$($,j.form.id,j)}static async list($,O){if(!O)return G(await $.storage.listAccessibleForms()).map(({form:S})=>new y$($,S.id));return G(await $.storage.listForms({query:{databaseId:O.id}})).map((x)=>new y$($,x.id))}schema(){return this.detail.get()}name=this.mappedField("form",($)=>$.name);description=this.mappedField("form",($)=>$.description);owner=this.mappedField("form",($)=>P.byId(this.client,$.ownerId));database=this.mappedField("form",($)=>V$.byId(this.client,$.databaseId));table=this.mappedField("form",($)=>J$.byId(V$.byId(this.client,$.databaseId),$.tableId));audience=this.mappedField("form",($)=>$.audience);status=this.mappedField("form",($)=>$.status);closesAt=this.mappedField("form",($)=>$.closesAt??void 0);access=this.field("access");async sections(){return(await this.detail.get()).sections.map(($)=>p$.byId(this,$.id))}async questions(){return(await this.detail.get()).sections.flatMap(($)=>$.kind==="questions"?$.questions.map((O)=>r$.byId(this,O.id)):[])}async update($){return await this.mutate((O)=>O.storage.updateForm({path:{id:this.id},body:$})),this}assertOwns($){if($.form.id!==this.id)throw new f(`question or section does not belong to form ${this.id}`)}async replaceLayout($){let O=await this.table(),j=(Z)=>{if(Z.table.id!==O.id||Z.table.database.id!==O.database.id)throw new f(`column does not belong to form ${this.id}'s table`);return Z.id},x=(Z)=>({conjunction:Z.conjunction,conditions:Z.conditions.map((X)=>c(X).with({kind:"group"},(Y)=>({kind:"group",...x(Y)})).with({kind:"condition"},(Y)=>({kind:"condition",column:j(Y.column),test:c(Y.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","checkbox")},(L)=>L).exhaustive()})).exhaustive())}),S={sections:$.map((Z)=>{if(Z.section)this.assertOwns(Z.section);let X={id:Z.section?.id??d$(),title:Z.title,description:Z.description??""};return c(Z).with({kind:"booking"},(Y)=>({...X,kind:"booking",target:Y.target})).with({kind:"gate"},(Y)=>({...X,kind:"gate",rules:x(Y.rules),message:Y.message})).with({kind:"questions"},(Y)=>({...X,kind:"questions",questions:Y.questions.map((L)=>{if(L.question)this.assertOwns(L.question);return{id:L.question?.id??d$(),column:j(L.column),helpText:L.helpText??"",required:L.required??!1,widget:L.widget??null}})})).exhaustive()})},K=await this.mutate((Z)=>Z.storage.putFormLayout({path:{id:this.id},body:S}));return{form:this,publicationError:K.publicationError}}wireAnswers($){return $.map(({question:O,value:j})=>{this.assertOwns(O);let x=c(j).with({type:"rows"},(S)=>({type:"rows",value:S.value.map((K)=>K.id)})).with({type:"options"},(S)=>({type:"options",value:S.value.map((K)=>{if(K.question.id!==O.id||K.question.form.id!==this.id)throw new f("option does not belong to the answered question");return{id:K.id}})})).with({type:"entities"},(S)=>({type:"entities",value:S.value.map(({entityType:K,entity:Z})=>({entityType:K,entityId:Z.id}))})).with({type:Z$.union("text","number","boolean","date","link","clear")},(S)=>S).exhaustive();return{question:O.id,value:x}})}unlockedBooking($){return $?{...$,section:p$.byId(this,$.section)}:void 0}async outcome($,O){return c($).with({outcome:"stopped"},(j)=>({...j,section:p$.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:TO.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(G(await this.client.storage.submitFormResponse({path:{id:this.id},body:O})),$)}async editResponse($){let O={answers:this.wireAnswers($)};return this.outcome(G(await this.client.storage.editMyFormResponse({path:{id:this.id},body:O})),$)}async myResponse(){let $=G(await this.client.storage.getMyFormResponse({path:{id:this.id}})),O=await this.table(),j=await Promise.all($.answers.map(async(K)=>{let Z=r$.byId(this,K.question),X=await c(K.value).with({type:"options"},(Y)=>({type:"options",value:Y.value.map((L)=>{if(!("id"in L))throw new f("stored form answers must reference options by id");return NO.byId(Z,L.id)})})).with({type:"entities"},(Y)=>({type:"entities",value:Y.value.map((L)=>({entityType:L.entityType,entity:Mj.byId(L.entityType,L.entityId)}))})).with({type:"rows"},async(Y)=>{let L=await Z.detail();if(L.kind.type!=="relation")throw new f("row answer requires a relation question");let Q=J$.byId(V$.byId(this.client,L.kind.database),L.kind.table);return{type:"rows",value:Y.value.map((J)=>F$.byId(Q,J))}}).with({type:Z$.union("text","number","boolean","date","link","clear")},(Y)=>Y).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:TO.byId(this,$.response.id,{status:$.response.status,row:x,answers:j,booking:S}),status:$.response.status,stoppedAtSection:$.response.stoppedAtSection?p$.byId(this,$.response.stoppedAtSection):void 0,row:x,submittedAt:$.response.submittedAt,updatedAt:$.response.updatedAt,answers:j}}async responseSummary(){let $=G(await this.client.storage.getFormResponseSummary({path:{id:this.id}}));return{...$,stoppedBySection:$.stoppedBySection.map((O)=>({section:p$.byId(this,O.section),count:O.count}))}}async tally(){return G(await this.client.storage.getFormTally({path:{id:this.id}})).questions.map((O)=>{let j=r$.byId(this,O.question);return{question:j,responses:O.responses,buckets:O.buckets.flatMap((x)=>c(x.value).with({kind:"option"},(S)=>[{count:x.count,value:{kind:"option",option:NO.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 G(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 V0{client;constructor($){this.client=$}byId($){return y$.byId(this.client,$)}create($){return y$.create(this.client,$)}list($){return y$.list(this.client,$)}}class HO extends M{static byId($,O){return new HO($,O)}async fetch(){return G(await this.client.storage.getGithubPullRequest({path:{id:this.id}}))}title=this.field("title");url=this.field("url");status=this.field("status");async changes(){let $=G(await this.client.storage.getGithubPullRequestChanges({path:{id:this.id}}));return{changeset:$.changeset?new W0(this.client,this,$.changeset):void 0,error:$.error??void 0}}}class W0{client;pullRequest;record;constructor($,O,j){this.client=$;this.pullRequest=O;this.record=j}get id(){return this.record.id}async patch(){return G(await this.client.storage.getGithubPullRequestChangesPatch({path:{id:this.pullRequest.id},query:{changeset:this.id}})).patch}toJSON(){return{pullRequestId:this.pullRequest.id,...this.record}}}class B0{client;constructor($){this.client=$}byId($){return HO.byId(this.client,$)}forEntity($){return HO.byId(this.client,$.id)}}class RO extends M{static byId($,O){return new RO($,O)}async fetch(){return G(await this.client.storage.getHarnessPairing({path:{code:this.id}}))}name=this.field("requested_name");expiresAt=this.field("expires_at");async approve($){let O={name:$?.name,team_id:$?.team?.id,allow_permission_bypass:$?.allowPermissionBypass};return B$.from(this.client,await this.mutate((j)=>j.storage.approveHarnessPairing({path:{code:this.id},body:O})))}}class oO{client;id;constructor($,O){this.client=$;this.id=O}static byId($,O){return new oO($,O)}async claim($){let O=G(await this.client.storage.claimHarnessPairing({path:{pairing_id:this.id},body:{device_secret:$}}));return"harness"in O?{harness:B$.from(this.client,O.harness),token:O.token}:void 0}toJSON(){return{id:this.id}}}class L0{client;constructor($){this.client=$}byId($){return B$.byId(this.client,$)}async list(){return G(await this.client.storage.listHarnesses()).map(($)=>B$.from(this.client,$))}async me(){return B$.from(this.client,G(await this.client.storage.getSelfHarness()))}async deleteSelf(){G(await this.client.storage.deleteSelfHarness())}async agents(){return G(await this.client.storage.listHarnessAgents()).map(($)=>I$.byId(this.client,$.bot_id))}async sessions(){return G(await this.client.storage.listHarnessSessions()).map(($)=>i.byId(this.client,$.session_id))}pairing($){return RO.byId(this.client,$)}async createPairing($){let O=G(await this.client.storage.createHarnessPairing({body:$}));return{pairing:RO.byId(this.client,O.code),device:oO.byId(this.client,O.pairing_id),deviceSecret:O.device_secret,expiresAt:O.expires_at,pollIntervalSeconds:O.poll_interval_seconds}}}var Q7="00000001-0000-0000-0000-000000000002",J7="00000001-0000-0000-0002-000000000004";function V7($){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 _$ extends w{static byId($,O){return new _$($,O)}static async create($,O){let{documentId:j}=G(await $.storage.createTaskHandler({body:{taskName:O.name,markdown:O.markdown??null,projectId:O.project?.id??null,teamId:O.team?.id??null,shareWithTeam:O.shareWithTeam??!0}}));return new _$($,j)}static async forPullRequest($,O){let j=V7(O),{pullRequests:x}=G(await $.storage.getGithubPullRequestTasks({body:{githubKeys:[j]}}));return(x[0]?.taskIds??[]).map((S)=>new _$($,S))}async completed(){let{subType:$}=await this.detail.get();if($!=="task")return;let j=(await this.properties()).find((x)=>x.definition.id===Q7)?.value;return j?.type==="SelectOption"&&j.value.includes(J7)}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 _$($,O.document_id)})}class SO extends M{access=new o(this.client,"initiative",this);static byId($,O){return new SO($,O)}static from($,O){return new SO($,O.id,O)}async fetch(){return G(await this.client.storage.getInitiative({path:{initiative_id:this.id}}))}name=this.field("name");owner=this.mappedField("ownerId",($)=>P.byId(this.client,$));members=this.mappedField("memberIds",($)=>$.map((O)=>P.byId(this.client,O)));tasks=this.mappedField("taskIds",($)=>$.map((O)=>_$.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?n$($.sharePermission):void 0}}))}async delete(){await this.mutate(($)=>$.storage.deleteInitiative({path:{initiative_id:this.id}}))}}class N0{client;constructor($){this.client=$}byId($){return SO.byId(this.client,$)}async list(){return G(await this.client.storage.listInitiatives()).initiatives.map(($)=>SO.byId(this.client,$.id))}async create($){return SO.from(this.client,G(await this.client.storage.createInitiative({body:{name:$.name,description:$.description,memberIds:$.members?.map((O)=>O.id),shareWithTeam:$.shareWithTeam,propertyValues:$.propertyValues}})))}}class U0{client;constructor($){this.client=$}byId($){return H$.byId(this.client,$)}async create($){return H$.from(this.client,G(await this.client.storage.meetingCreate({body:$})))}async list(){return G(await this.client.storage.meetingList()).meetings.map(($)=>H$.from(this.client,$))}async active(){return G(await this.client.storage.meetingListActive()).meetings.map(($)=>H$.from(this.client,$))}async lookup($){return H$.from(this.client,G(await this.client.storage.meetingLookup({path:{token:$}})))}}class UO extends M{async fetch(){return G(await this.client.notification.getTypedNotificationById({path:{notification_id:this.id}}))}static byId($,O){return new UO($,O)}static from($,O){return new UO($,O.id,O)}static list($,O){return u(async(j)=>{let x=G(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)=>UO.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",($)=>P.byId(this.client,$));sender=this.mappedField("sender_id",($)=>$?P.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 z0{client;constructor($){this.client=$}byId($){return UO.byId(this.client,$)}list($){return UO.list(this.client,$)}async markSeen($){G(await this.client.notification.bulkMarkNotificationsSeen({body:{notificationIds:$}}))}async markDone($){G(await this.client.notification.bulkMarkNotificationsDone({body:{notificationIds:$}}))}async delete($){G(await this.client.notification.bulkDeleteUserNotificationsV2({body:{notificationIds:$}}))}async preferences(){return G(await this.client.notification.getNotificationTypePreferences())}async enableType($){G(await this.client.notification.enableNotificationType({path:{notification_event_type:$}}))}async disableType($){G(await this.client.notification.disableNotificationType({path:{notification_event_type:$}}))}}class I0{client;constructor($){this.client=$}async list(){let{data:$}=G(await this.client.storage.getPinsHandler({}));return $?.recent??[]}async add($,O){G(await this.client.storage.addPinHandler({path:{pinned_item_id:$.id},body:{pinType:$.entityType,pinIndex:O.index}}))}async remove($){G(await this.client.storage.removePinHandler({path:{pinned_item_id:$.id},body:{pinType:$.entityType}}))}async reorder($){G(await this.client.storage.reorderPinsHandler({body:$}))}}class T0{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 DO{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 DO($,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=G(await this.client.properties.updatePropertyOption({path:{definition_id:this.definitionId,option_id:this.id},body:$})),this}async delete(){G(await this.client.properties.deletePropertyOption({path:{definition_id:this.definitionId,option_id:this.id}}))}}class ZO{client;id;detail;constructor($,O,j){this.client=$;this.id=O;this.detail=new W$(()=>this.fetch(),j)}async fetch(){return G(await this.client.properties.getPropertyDefinition({path:{definition_id:this.id}}))}static async create($,O){let j=G(await $.properties.createPropertyDefinition({body:{display_name:O.displayName,scope:O.scope,data_type:O.dataType}}));return new ZO($,j.id,j)}static byId($,O){return new ZO($,O)}static fromRecord($,O){return new ZO($,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 G(await this.client.properties.deletePropertyDefinition({path:{definition_id:this.id}}))}async options(){return G(await this.client.properties.getPropertyOptions({path:{definition_id:this.id}})).map((O)=>DO.from(this.client,this.id,O))}async addOption($){let O=G(await this.client.properties.addPropertyOption({path:{definition_id:this.id},body:$}));return DO.from(this.client,this.id,O)}async updateOption($,O){let j=G(await this.client.properties.updatePropertyOption({path:{definition_id:this.id,option_id:$.id},body:O}));return DO.from(this.client,this.id,j)}async deleteOption($){return G(await this.client.properties.deletePropertyOption({path:{definition_id:this.id,option_id:$.id}}))}}class H0{client;constructor($){this.client=$}async list($){return G(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 ZO.fromRecord(this.client,x)})}create($){return ZO.create(this.client,$)}definition($){return ZO.byId(this.client,$)}async bulkEntityProperties($){return G(await this.client.properties.getBulkEntityProperties({body:$}))}async updateEntityPropertyOptions($,O){return G(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 G(await this.client.properties.addEntityPropertyOption({path:{...$.entity.propertyReference(),property_id:$.property.id,option_id:$.option.id}}))}async removeEntityPropertyOption($){return G(await this.client.properties.removeEntityPropertyOption({path:{...$.entity.propertyReference(),property_id:$.property.id,option_id:$.option.id}}))}async tags(){return G(await this.client.properties.listTags({}))}}function R0($){return c($).with({type:"cron"},(O)=>O).with({type:"events"},(O)=>({type:"events",filters:O.filters.map(({entities:j,...x})=>({...x,ids:j?.map((S)=>S.entity.id)}))})).exhaustive()}function W7($){return c($).with({type:"multiple"},(O)=>({type:"multiple",triggers:O.triggers.map(R0)})).with({type:"cron"},R0).with({type:"events"},R0).exhaustive()}class XO extends M{static byId($,O){return new XO($,O)}static from($,O){if(!O.id)throw Error("Routine response has no id");return new XO($,O.id,O)}async fetch(){return G(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",($)=>P.byId(this.client,$));async update($){await this.mutate((O)=>O.scheduledAction.updateScheduledAction({path:{id:this.id},body:_0($)}))}async setEnabled($){await this.mutate((O)=>O.scheduledAction.setScheduledActionEnabled({path:{id:this.id},body:{enabled:$}}))}async execute(){let $=G(await this.client.scheduledAction.executeScheduledActionNow({path:{id:this.id}}));if($.resource)return c($.resource).with({type:"agent"},(O)=>i.byId(this.client,O.id)).with({type:"chat"},(O)=>K$.byId(this.client,O.id)).exhaustive();return $.chat_id?K$.byId(this.client,$.chat_id):void 0}async history(){return G(await this.client.scheduledAction.listScheduledActionHistory({path:{id:this.id}})).map(($)=>new D0(this,$))}async delete(){await this.mutate(($)=>$.scheduledAction.deleteScheduledAction({path:{id:this.id}}))}}class D0{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 _0($){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:W7($.trigger),task:{...O}}}class C0{client;constructor($){this.client=$}byId($){return XO.byId(this.client,$)}async create($){return XO.from(this.client,G(await this.client.scheduledAction.createScheduledAction({body:{..._0($),enabled:$.enabled??!0}})))}async list($){return G(await this.client.scheduledAction.listScheduledActions({query:{include_events:$?.includeEvents}})).map((O)=>XO.from(this.client,O))}}class P0{client;constructor($){this.client=$}byId($){return _$.byId(this.client,$)}create($){return _$.create(this.client,$)}forPullRequest($){return _$.forPullRequest(this.client,$)}search($,O){return _$.search(this.client,$,O)}}class M0{client;constructor($){this.client=$}byId($){return S$.byId(this.client,$)}current(){return S$.current(this.client)}list(){return S$.list(this.client)}}class A0{client;constructor($){this.client=$}async get($){return G(await this.client.unfurl.getUnfurl({query:{url:$}}))}async bulk($){return G(await this.client.unfurl.getUnfurlBulk({body:{url_list:$}}))}}class F0{client;constructor($){this.client=$}byId($){return P.byId(this.client,$)}me(){return P.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}=G(j),S=[...new Set(x)],K=[];for(let Z=0;Z<S.length;Z+=100){let X=S.slice(Z,Z+100),{names:Y}=G(await this.client.auth.getUserNamesWithEmail({body:{user_ids:X}})),L=new Map(Y.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(P.fromName(this.client,J))}}return K}}class KO extends M{signingSecret;constructor($,O,j,x){super($,O,j);this.signingSecret=x}async fetch(){return G(await this.client.storage.getWebhook({path:{webhook_id:this.id}}))}static async create($,O){let j=G(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 KO($,j.id,j,j.signing_secret)}static byId($,O){return new KO($,O)}static fromRecord($,O){return new KO($,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",($)=>P.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 E0{client;constructor($){this.client=$}create($){return KO.create(this.client,$)}byId($){return KO.byId(this.client,$)}async list(){let{webhooks:$}=G(await this.client.storage.listWebhooks());return $.map((O)=>KO.fromRecord(this.client,O))}}class _O extends M{static byId($,O){return new _O($,O)}static from($,O){return new _O($,O.id,O)}async fetch(){let{account:$}=G(await this.client.storage.linkedAccount());if($?.id!==this.id)throw new E("WhatsApp account is not available");return $}state=this.field("state");identity=this.field("identity_jid");owner=this.mappedField("user_id",($)=>P.byId(this.client,$));async refresh(){return this.detail.clear(),await this.detail.get(),this}}class C$ extends M{group;constructor($,O,j,x){super($,j,x);this.group=O}static byId($,O,j){return new C$($,O,j)}static from($,O,j){return new C$($,O,j.id,j)}get groupId(){return this.group.id}async fetch(){for await(let $ of this.group.messages({limit:100}))if($.id===this.id)return $.detail.get();throw new E("WhatsApp message is not available")}body=this.field("body");sender=this.field("sender");sentAt=this.field("sent_at");editedAt=this.field("edited_at");deleted=this.field("deleted");reactions=this.field("reactions");deliveryState=this.field("delivery_state");kind=this.field("kind");forwarded=this.field("forwarded");mentions=this.field("mentions");rich=this.field("rich");replyTo=this.mappedField("reply_to",($)=>$?C$.byId(this.client,this.group,$):void 0);attachments=this.mappedField("attachments",($)=>$.map((O)=>({ordinal:O.ordinal,state:O.state,fileName:O.file_name,mime:O.mime,size:O.size,width:O.width??void 0,height:O.height??void 0,durationSeconds:O.duration_seconds??void 0,presentation:O.presentation??void 0,document:O.document_id?w.byId(this.client,O.document_id):void 0})))}class YO{id;groupId;filename;kind;constructor($,O,j,x){this.id=$;this.groupId=O;this.filename=j;this.kind=x}static byId($,O){return new YO(O,$.id)}static from($,O){return new YO(O.upload_id,$.id,O.filename,O.kind)}toJSON(){return{id:this.id,groupId:this.groupId,filename:this.filename,kind:this.kind}}}class a$ extends M{group;constructor($,O,j,x){super($,j,x);this.group=O}static byId($,O,j){return new a$($,O,j)}static from($,O,j){return new a$($,O,j.id,j)}async fetch(){let O=G(await this.client.storage.linkedDelivery({path:{group_id:this.group.id},body:[this.id]})).find((j)=>j.id===this.id);if(!O)throw new E("WhatsApp send is not available");return O}state=this.field("state");errorCode=this.field("error_code");createdAt=this.field("created_at");message=this.mappedField("message_id",($)=>$?C$.byId(this.client,this.group,$):void 0);async request(){let{payload:$}=await this.detail.get(),O=$.message,j=c(O).returnType().with({type:"media"},(x)=>({type:"media",upload:YO.byId(this.group,x.upload_id),caption:x.caption??void 0})).with({type:"mutation"},(x)=>({type:"mutation",message:C$.byId(this.client,this.group,x.message_id),operation:x.operation,text:x.text??void 0})).with({type:"text"},(x)=>({type:"text",text:x.text,mentions:x.mentions??[]})).exhaustive();return{idempotencyKey:$.idempotency_key,message:j,replyTo:$.reply_to?C$.byId(this.client,this.group,$.reply_to):void 0}}async refresh(){return this.detail.clear(),await this.detail.get(),this}}class v$ extends z${entityType="whatsapp_group";static byId($,O){return new v$($,O)}async fetch(){return G(await this.client.storage.whatsappGroup({path:{group_id:this.id}}))}name=this.field("name");canSend=this.field("can_send");sendReason=this.field("send_reason");sendingIdentity=this.field("sending_identity");unreadCount=this.field("unread_count");backfill=this.field("backfill");limits=this.field("limits");roster=this.field("roster");owner=this.mappedField("user_id",($)=>P.byId(this.client,$));async*messages($={}){yield*u(async(O)=>{let j=G(await this.client.storage.whatsappGroupMessages({path:{group_id:this.id},query:{before:O,limit:$.limit}}));return{items:j.messages.map((x)=>C$.from(this.client,this,x)),nextCursor:j.next_cursor}})}async markRead($){this.assertGroup($.groupId),await this.mutate((O)=>O.storage.whatsappGroupRead({path:{group_id:this.id},body:{message_id:$.id}}))}async permissions(){return G(await this.client.storage.whatsappGroupPermissions({path:{group_id:this.id}}))}async updatePermissions($){await this.mutate((O)=>O.storage.whatsappGroupUpdatePermissions({path:{group_id:this.id},body:$}))}async detach(){await this.mutate(($)=>$.storage.linkedDetach({path:{group_id:this.id}}))}async upload($){let O=G(await this.client.storage.linkedUpload({path:{group_id:this.id},body:{file:$}}));return YO.from(this,O)}async reply($,O){if(O.replyTo)this.assertGroup(O.replyTo.groupId);let j=c($).returnType().with({type:"text"},(S)=>({type:"text",text:S.text,mentions:S.mentions??[]})).with({type:"media"},(S)=>{return this.assertGroup(S.upload.groupId),{type:"media",upload_id:S.upload.id,caption:S.caption}}).with({type:"mutation"},(S)=>{return this.assertGroup(S.message.groupId),{type:"mutation",message_id:S.message.id,operation:S.operation,text:S.text}}).exhaustive(),x=await this.mutate((S)=>S.storage.linkedReply({path:{group_id:this.id},body:{idempotency_key:O.idempotencyKey,message:j,reply_to:O.replyTo?.id}}));return a$.from(this.client,this,x)}async sends(){return G(await this.client.storage.whatsappGroupSends({path:{group_id:this.id}})).map(($)=>a$.from(this.client,this,$))}async delivery($){for(let O of $)this.assertGroup(O instanceof a$?O.group.id:O.groupId);return G(await this.client.storage.linkedDelivery({path:{group_id:this.id},body:$.map((O)=>O.id)})).map((O)=>a$.from(this.client,this,O))}async messageAttachments($){for(let O of $)this.assertGroup(O.groupId);return G(await this.client.storage.linkedMessageAttachments({path:{group_id:this.id},body:$.map((O)=>O.id)})).map((O)=>({message:C$.byId(this.client,this,O.message_id),attachments:O.linked_attachments.map((j)=>({ordinal:j.ordinal,state:j.state,fileName:j.file_name,mime:j.mime,size:j.size,document:j.document_id?w.byId(this.client,j.document_id):void 0}))}))}async refresh(){return this.detail.clear(),await this.detail.get(),this}assertGroup($){if($!==this.id)throw Error("WhatsApp reference belongs to another group")}}class CO extends M{static byId($,O){return new CO($,O)}static from($,O){return new CO($,O.jid,O)}async fetch(){let{chats:$}=G(await this.client.storage.linkedChats()),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");lastActivityAt=this.field("lastActivityAt");archived=this.field("archived");pinned=this.field("pinned");canAdd=this.field("canAdd");cannotAddReason=this.field("cannotAddReason");group=this.mappedField("group",($)=>$?v$.byId(this.client,$.id):void 0);shared=this.mappedField("shared",($)=>$?v$.byId(this.client,$.id):void 0);async adopt(){let $=await this.mutate((O)=>O.storage.linkedAdopt({body:{group_jid:this.id}}));return v$.byId(this.client,$.group_id)}async refresh(){return this.detail.clear(),await this.detail.get(),this}}class w0{client;constructor($){this.client=$}async account(){let{account:$}=G(await this.client.storage.linkedAccount());return $?_O.from(this.client,$):void 0}async groups(){return G(await this.client.storage.whatsappGroups()).map(($)=>v$.byId(this.client,$.id))}async chats(){return G(await this.client.storage.linkedChats()).chats.map(($)=>CO.from(this.client,$))}byId($){return v$.byId(this.client,$)}}function q0($){if("properties"in $.data)return $.data.properties;if($.tag==="calendarEvent")return $.data.extra.properties;return[]}function a1($,O,j){let x=[];for(let S of q0(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:w.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:R$.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 h$($,O.data.channel_id,O.data.id),snapshot:O,tags:x,channelId:O.data.channel_id};case"call":return{type:"call",id:O.data.callId,entity:Q$.byId($,O.data.callId),snapshot:O,tags:x,createdBy:O.data.createdBy};case"calendarEvent":return{type:"calendar_event",id:O.data.id,entity:$$.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:xO.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 i1="00000000-0000-0000-0000-000000000000",f0={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"]},Aj=($)=>$.replace(/[A-Z]/g,(O)=>O.toLowerCase()),n1=($,O)=>$==null?O:{"&":[$,O]};function b0($,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==="!"){b0(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)=>{b0(Z,`${O}.${S}[${X}]`)})}class Fj{client;tagSets;constructor($){this.client=$}sets(){return this.tagSets??=this.client.properties.listTags({}).then(G),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(f0,S))))throw Error(`Invalid workspace includeTypes. Supported values: ${Object.keys(f0).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)b0($[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:i1}},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}=G(await this.client.email.listLinks()),K=S.filter((X)=>Aj(X.email_address)===Aj(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=n1(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(f0))if(!x.includes(S))O[K]={l:{[Z]:i1}}}if($.tags?.length){let S=(await this.sets()).flatMap((Y)=>{let L=Y.definition;if(!L)return[];return Y.options.flatMap((Q)=>Q.value.type==="string"?[{id:Q.id,definitionId:L.id,label:Q.value.value,scope:Y.scope==="user"?"personal":"team"}]:[])}),K=new Map;for(let Y of $.tags){let L=S.filter((Q)=>Aj(Q.label)===Aj(Y.label.trim())&&(!Y.scope||Q.scope===Y.scope));if(!L.length)throw Error(`Unknown tag "${Y.label}". Available tags: ${S.map((Q)=>`${Q.label} (${Q.scope})`).join(", ")}.`);if($.tagsMatch==="all"&&L.length>1)throw Error(`Tag "${Y.label}" is ambiguous; specify personal or team scope.`);for(let Q of L)K.set(Q.id,Q)}let X=[...K.values()].map((Y)=>({l:{pd:Y.definitionId,v:{so:Y.id}}})).reduce((Y,L)=>Y===void 0?L:{[$.tagsMatch==="all"?"&":"|"]:[Y,L]},void 0);O.propf=n1(O.propf,X)}return O}}class k0{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*u((x)=>this.fetch(O,j,x))}async fetch($,O,j){let x=G(await this.client.storage.postItemsSoupAst({body:O,query:j?{cursor:j}:void 0})),K=x.items.some((Z)=>q0(Z).some((X)=>X.definition.data_type==="TAG"))?await $.tagMap():new Map;return{items:x.items.map((Z)=>a1(this.client,Z,K)),nextCursor:x.next_cursor,hasMore:x.next_cursor!=null}}}function s1({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...Q}){let J,I=Y??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,T=Q.signal??new AbortController().signal;while(!0){if(T.aborted)break;B++;let A=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)A.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:A,signal:T},_=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 H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",k=()=>{try{H.cancel()}catch{}};T.addEventListener("abort",k);try{while(!0){let{done:l,value:r}=await H.read();if(l)break;U+=r,U=U.replace(/\r\n?/g,`+async function uO($,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*u($){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 G($){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=G(await $(this.client));return this.detail.clear(),O}}class z$ extends P{async permission(){return G(await this.client.storage.getEntityPermission({path:{entity_type:this.entityType,entity_id:this.id}}))}async favorite(){return G(await this.client.storage.addFavorite({body:{entityId:this.id,entityType:this.entityType}})),this}async unfavorite(){return G(await this.client.storage.removeFavoriteByEntity({path:{entity_type:this.entityType,entity_id:this.id}})),this}}class X$ extends z${propertyReference(){return{entity_type:this.propertyEntityType,entity_id:this.id}}async properties($){let{properties:O}=G(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){G(await this.client.properties.setEntityProperty({path:{...this.propertyReference(),property_id:$.id},body:{value:O??null}}))}async updatePropertyOptions($){return G(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($){G(await this.client.properties.deleteEntityProperty({path:{entity_property_id:$.property.id}}))}}var f6={"<":"\\u003c",">":"\\u003e","&":"\\u0026"};function a$($,O){let j=JSON.stringify(O).replace(/[<>&]/g,(x)=>f6[x]??x);return`<${$}>${j}</${$}>`}function b6($){return typeof $==="object"&&$!==null&&typeof $.toMention==="function"}var k6={toMention:()=>({tag:a$("m-group-mention",{groupAlias:"here"}),mention:{entity_type:"group",entity_id:"here"}})};function g6($,...O){let j="",x=[];for(let[S,K]of $.entries()){j+=K;let Z=O[S];if(Z===void 0)continue;if(b6(Z)){let X=Z.toMention();j+=X.tag,x.push(X.mention)}else j+=String(Z)}return{content:j,mentions:y6(x)}}function y6($){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 W$ extends P{static byId($,O){return new W$($,O)}static from($,O){return new W$($,O.id,O)}async fetch(){let $=G(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 I$ extends P{static byId($,O){return new I$($,O)}static from($,O){return new I$($,O.bot.id,O)}async fetch(){let $=G(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",($)=>$?W$.byId(this.client,$):void 0);async update($){await this.mutate((O)=>O.storage.updateAgent({path:{agent_id:this.id},body:yx($)}))}}function yx($){let{channels:O,team:j,host:x,autoAcceptPermissions:S,avatarUrl:K,channelScope:Z,defaultModel:X,isCoding:Y,...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:Y}}async function Wj($,O,j){let{channelId:x,thread:S}=v6(O);if(await h6($)){let{id:Z}=G(await $.storage.entityMessageCreate({path:{parent_type:"channel",parent_id:x},body:{content:j.content,mentions:j.mentions,attachments:[],thread_id:S?.rootId??null,nonce:crypto.randomUUID()}}));return Z}if(S)throw new f("a user-owned bot can only post via the channel webhook endpoint, which "+"does not support threads — use a team-owned bot, or requestedAs(user), "+"to reply in a thread");let{message_id:K}=G(await $.storage.postChannelBotWebhook({path:{channel_id:x},body:{content:j.content},headers:{"x-macro-bot-scope":"user"}}));return K}function v6($){return"rootId"in $?{channelId:$.channelId,thread:$}:{channelId:$.id}}async function h6($){if($.authConfig.type!=="bot"||$.hasActingUser())return!0;let{owner:O}=await $.selfBot();return O?.type==="team"}class h${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:$}=G(await this.client.storage.entityMessageGetThread({path:{parent_type:"channel",parent_id:this.channelId,id:this.rootId}}));return $.map((O)=>e.from(this.client,this.channelId,O))}async reply($){let O=await Wj(this.client,this,O$($));return e.byId(this.client,this.channelId,O)}}class e extends z${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 G(await this.client.storage.entityMessageGetMessage({path:this.path}))}static byId($,O,j,x=[]){return new e($,O,j,x)}static from($,O,j){return new e($,O,j.id,j.mentions,j)}content=this.field("content");createdAt=this.field("created_at");editedAt=this.field("edited_at");updatedAt=this.field("updated_at");async author(){return M.byId(this.client,(await this.detail.get()).sender_id)}channel(){return b.byId(this.client,this.channelId)}thread(){return new h$(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 I$.byId(this.client,this.record.botId)}sessions(){return this.record.sessions.map(($)=>({session:i.byId(this.client,$.sessionId),isCurrent:$.isCurrent,createdAt:$.createdAt}))}turns(){return this.record.turns.map(($)=>new vx(this.client,this,$))}async startFresh($){G(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 vx{client;conversation;record;constructor($,O,j){this.client=$;this.conversation=O;this.record=j}source(){return e.byId(this.client,this.conversation.channel.id,this.record.sourceMessageId)}session(){return i.byId(this.client,this.record.sessionId)}async retry($){G(await this.client.agentHarness.retryAgentConversationTurn({path:{channel_id:this.conversation.channel.id,bot_id:this.conversation.agent().id,source:this.record.sourceMessageId},body:{actionId:$}}))}toJSON(){return{channelId:this.conversation.channel.id,sourceMessageId:this.record.sourceMessageId}}}class L$ extends 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 L$($,O,j)}get path(){return{parent_type:this.parent.type,parent_id:this.parent.entity.id,id:this.id}}async fetch(){return G(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 w$($,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=G(await $.storage.messageTimelineEntries({path:{parent_type:O.type,parent_id:O.entity.id},query:{selection:x?JSON.stringify({cursor:x.cursor,around:x.around?.id,ids:x.messages?.map((K)=>K.id),activity_after:x.activityAfter,activity_before:x.activityBefore,anchored:x.anchored,direction:x.direction,include_deleted_threads:x.includeDeletedThreads,limit:x.limit}):void 0}}));return{entries:S.entries.map((K)=>{if(K.type==="activity")return{type:"activity",activity:{...K.activity,actor:M.byId($,K.activity.actor_id)}};return{type:"message",message:j(K.message)}}),nextCursor:S.next_cursor??void 0,previousCursor:S.previous_cursor??void 0}}var m6=50;function x$($){let{filters:O,type:j,make:x,includeCrm:S}=$;return(K,Z,X)=>{let Y=X?.searchOn??"name_content",L=X?.pageSize??m6;return u(async(Q)=>{let{results:J,next_cursor:I}=G(await K.search.unifiedSearch({body:{query:Z,match_type:"partial",search_on:Y,...O?{filters:O}:{},...S?{include_crm:!0}:{}},query:{page_size:L,...Q?{cursor:Q}:{}}}));return{items:J.filter((B)=>B.type===j).map((B)=>x(K,B)),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 M.byId(this.client,this.record.user_id)}createdAt(){return this.record.created_at}async recordInteraction($){return new JO(this.client,this.channel,G(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,G(await this.client.storage.postActivity({body:{activity_type:$,channel_id:this.id}})))}async setPicture($){await this.mutate((O)=>O.storage.setChannelPicture({path:{channel_id:this.id},body:{profile_picture_id:$?.id??null}}))}messageThreadById($){return L$.byId(this.client,{type:"channel",entity:this},$)}timelinePage($){return w$(this.client,{type:"channel",entity:this},(O)=>e.from(this.client,this.id,O),$)}async agentConversations(){return G(await this.client.agentHarness.listAgentConversations({path:{channel_id:this.id}})).conversations.map(($)=>new Lj(this.client,this,$))}entityType="channel";propertyEntityType="CHANNEL";async fetch(){return G(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}=G(await $.storage.getOrCreateDm({body:{recipient_id:O.id}}));return new b($,j)}static async private($,O){let{channel_id:j}=G(await $.storage.getOrCreatePrivate({body:{recipients:O.map((x)=>x.id)}}));return new b($,j)}static async create($,O){let{id:j}=G(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 Wj(this.client,O?.thread??this,O$($));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 u(async(O)=>{let j=G(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:$}=G(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 G(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){G(await this.client.storage.entityMessageTyping({path:{parent_type:"channel",parent_id:this.id},body:{active:$==="start",thread_id:O?.thread?.rootId??null}}))}attachments($){return u(async(O)=>{let j=G(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 M extends X${entityType="user";propertyEntityType="USER";async fetch(){let{names:$}=G(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 M($,O)}static fromName($,O){return new M($,O.id,O)}static async me($){let{user_id:O}=G(await $.auth.getUserInfo());return new M($,O)}async name(){let $=await this.detail.get();return[$.first_name,$.last_name].filter(Boolean).join(" ")||void 0}email(){let $=this.id.startsWith("macro|")?this.id.slice(6):void 0;return $?.includes("@")?$:void 0}dm(){return b.dm(this.client,this)}toMention(){return{tag:a$("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=G(await this.client.storage.accessRequestsState({path:this.path,query:{offset:$}}));return{accessLevel:O.accessLevel??void 0,canReview:O.canReview,owner:O.owner?M.byId(this.client,O.owner):void 0,pendingCount:O.pendingCount,supportedLevels:O.supportedLevels,nextOffset:O.nextOffset??void 0,mine:O.mine?TO.from(this.client,this,O.mine):void 0,requests:O.requests.map((j)=>TO.from(this.client,this,j))}}async submit($,O){return TO.from(this.client,this,G(await this.client.storage.accessRequestsSubmit({path:this.path,body:{requestedLevel:$,revision:O}})))}async cancel($){G(await this.client.storage.accessRequestsCancel({path:this.path,query:{revision:$}}))}async direct(){return G(await this.client.storage.accessRequestsDirect({path:this.path})).map(($)=>({user:M.byId(this.client,$.userId),accessLevel:$.accessLevel}))}async grant($,O){G(await this.client.storage.accessRequestsSetDirect({path:{...this.path,user_id:$.id},body:{accessLevel:O}}))}async remove($){G(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 G(await this.client.storage.accessRequestsResolve({path:{...this.path,request_id:$.id},body:O}))}toJSON(){return this.path}}class TO extends P{access;resolvedRecord;constructor($,O,j){super($,j.id,j);this.access=O}static from($,O,j){return new TO($,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",($)=>M.byId(this.client,$));async resolve($){this.resolvedRecord=await this.access.resolve(this,{revision:await this.revision(),grantedLevel:$}),this.detail.clear()}}function i$($){return{...$,channelSharePermissions:$.channelSharePermissions===void 0||$.channelSharePermissions===null?$.channelSharePermissions:$.channelSharePermissions.map((O)=>({channelId:O.channel.id,accessLevel:O.accessLevel,operation:O.operation}))}}class N$ extends P{parent;constructor($,O,j,x){super($,j,x);this.parent=O}static byId($,O,j){return new N$($,O,j)}static fromRecord($,O,j){return new N$($,O,j.id,j)}static async create($,O,j){return N$.createForSession($,O.session(),j,O)}static async createForSession($,O,j,x){let S=G(await $.agentHarness.createSessionReview({path:{session_id:O.id},body:{...j,executionId:x?.id??null}}));return N$.fromRecord($,O,S)}static async list($,O){return G(await $.agentHarness.listExecutionReviews({path:{session_id:O.session().id,execution_id:O.id}})).map((x)=>N$.fromRecord($,O.session(),x))}async fetch(){return G(await this.client.agentHarness.getSessionReview({path:{session_id:this.parent.id,review_id:this.id}}))}title=this.field("title");kind=this.field("kind");session(){return this.parent}async reference(){return{kind:await this.kind(),id:this.id}}async items(){return(await this.detail.get()).items.map(($)=>new hx($,{edit:(O)=>this.decide({action:"edit",item:$.id,draft:O}),submit:()=>this.decide({action:"submit",items:[$.id]}),dismiss:()=>this.decide({action:"dismiss",items:[$.id]})}))}async refresh(){return this.detail.clear(),await this.detail.get(),this}async submitAll(){await this.decide({action:"submit",items:[]})}async dismissAll(){await this.decide({action:"dismiss",items:[]})}async decide($){let O=(await this.detail.get()).revision;await this.mutate((j)=>j.agentHarness.decideSessionReview({path:{session_id:this.parent.id,review_id:this.id},body:{...$,revision:O}}))}}class hx{snapshot;actions;constructor($,O){this.snapshot=$;this.actions=O}get id(){return this.snapshot.id}get status(){return this.snapshot.status}get draft(){return this.snapshot.draft}get result(){return this.snapshot.result}async edit($){await this.actions.edit($)}async submit(){await this.actions.submit()}async dismiss(){await this.actions.dismiss()}}class dO extends P{parent;constructor($,O,j){super($,O);this.parent=j}static byId($,O,j){return new dO($,j,O)}async fetch(){return G(await this.client.agentHarness.getCodeExecution({path:{session_id:this.parent.id,execution_id:this.id}}))}reviews={create:($)=>N$.create(this.client,this,$),list:()=>N$.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 G(await this.client.agentHarness.editQueuedAction({path:{session_id:this.sessionId,action_id:this.actionId},body:{prompt:$}})),this.dto={...this.dto,prompt:$},this}async steer(){G(await this.client.agentHarness.steerQueuedAction({path:{session_id:this.sessionId,action_id:this.actionId}}))}async remove(){G(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 G(await this.client.agentHarness.answerAgentSessionToolApproval({path:{session_id:this.session.id,approval_id:this.id},body:{answer:$}}))}toJSON(){return{id:this.id,sessionId:this.session.id}}}class i extends P{access=new o(this.client,"agent_session",this);toolApprovalById($){return lO.byId(this.client,this,$)}async sharePermissions(){return G(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:i$($)}))}static byId($,O){return new i($,O)}static async createManaged($,O){let{session:j}=G(await $.agentHarness.createAgentSession({body:{prompt:O?.prompt,instructions:O?.instructions,model:O?.model,repoUrl:O?.repoUrl,repoBranch:O?.repoBranch}}));return new i($,j.id,j)}static async repositories($){let{repositories:O}=G(await $.agentHarness.listAgentRepositories());return O.map((j)=>({url:j.url,defaultBranch:j.defaultBranch??void 0}))}static async repositoryBranches($,O){let{branches:j}=G(await $.agentHarness.listAgentRepositoryBranches({query:{repoUrl:O}}));return j}async fetch(){return G(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}=G(await $.agentHarness.agentSessionsForPullRequest({body:{url:O}}));return j.map((x)=>i.byId($,x))}async pullRequests(){let{pullRequests:$}=G(await this.client.agentHarness.listAgentSessionPullRequests({path:{session_id:this.id}}));return $.map((O)=>({githubKey:O.githubKey,url:O.url,source:O.source,linkedBy:O.linkedBy?M.byId(this.client,O.linkedBy):void 0,createdAt:O.createdAt}))}async linkPullRequest($){G(await this.client.agentHarness.linkAgentSessionPullRequest({path:{session_id:this.id},body:{url:$}}))}async unlinkPullRequest($){G(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 G(await $.agentHarness.getAgentSandboxSize()).size}static async setDefaultSandboxSize($,O){return G(await $.agentHarness.putAgentSandboxSize({body:{size:O}})).size}static async codingPreferences($){return G(await $.agentHarness.getAgentCodingPreferences())}static async setCodingPreferences($,O){return G(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:$}=G(await this.client.agentHarness.getAgentSessionQueue({path:{session_id:this.id}}));return $.map((O)=>Nj.from(this.client,this.id,O))}async changes(){return G(await this.client.agentHarness.getAgentSessionChanges({path:{session_id:this.id}}))}async changesPatch(){return G(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}=G(await this.client.agentHarness.getAgentSessionFoldedLog({path:{session_id:this.id}}));return{bot:$,messages:O}}async log(){return G(await this.client.agentHarness.getAgentSessionLog({path:{session_id:this.id}}))}reviews={create:($)=>N$.createForSession(this.client,this,$),byId:($)=>N$.byId(this.client,this,$)};codeExecutions={byId:($)=>dO.byId(this.client,this,$)};async delete(){await this.mutate(($)=>$.agentHarness.deleteAgentSession({path:{session_id:this.id}}))}}class mx{client;constructor($){this.client=$}byId($){return i.byId(this.client,$)}createManaged($){return i.createManaged(this.client,$)}repositories(){return i.repositories(this.client)}repositoryBranches($){return i.repositoryBranches(this.client,$)}forPullRequest($){return i.forPullRequest(this.client,$)}defaultSandboxSize(){return i.defaultSandboxSize(this.client)}setDefaultSandboxSize($){return i.setDefaultSandboxSize(this.client,$)}codingPreferences(){return i.codingPreferences(this.client)}setCodingPreferences($){return i.setCodingPreferences(this.client,$)}}class cx{client;constructor($){this.client=$}byId($){return I$.byId(this.client,$)}async list(){return G(await this.client.storage.listAgents()).map(($)=>I$.from(this.client,$))}async create($){return I$.from(this.client,G(await this.client.storage.createAgent({body:yx($)})))}}class ux{client;async usage($={}){let{users:O,...j}=$;return G(await this.client.cognition.getUsageHandler({body:{...j,include_users:O?.map((x)=>x.id)}}))}constructor($){this.client=$}async structuredCompletion($){return G(await this.client.cognition.structuredCompletion({body:$}))}async decide($){return G(await this.client.cognition.decisions({body:$}))}}class n$ extends P{static byId($,O){return new n$($,O)}static from($,O){return new n$($,O.id,{id:O.id,name:O.name,createdAt:O.createdAt})}async fetch(){let $=G(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 dx{client;constructor($){this.client=$}byId($){return n$.byId(this.client,$)}async list(){return G(await this.client.storage.listUserApiKeys()).keys.map(($)=>n$.from(this.client,$))}async create($){let O=G(await this.client.storage.createUserApiKey({body:{name:$}}));return{key:n$.from(this.client,O),secret:O.key}}async tokenForEmail($){return G(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 G(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 G(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=G(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=G(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 G(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",($)=>M.byId(this.client,$));async members(){let $=G(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:M.byId(this.client,O.user_id),role:O.role}))}}class T$ extends P{async fetch(){let{links:$}=G(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 T$($,O)}static async list($){let{links:O}=G(await $.email.listLinks());return O.map((j)=>new T$($,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 G(await this.client.email.mailboxSettingsOperations({headers:{"X-Email-Link-Id":this.id}}))}}class m$ extends P{async setContributesToAvailability($){await this.mutate((O)=>O.calendar.setAvailabilityCalendar({path:{calendar_id:this.id},body:{contributesToAvailability:$}}))}async fetch(){let{calendars:$}=G(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 m$($,O)}static async list($){let{calendars:O}=G(await $.calendar.listCalendars());return O.map((j)=>new m$($,j.id,j))}name=this.field("name");emailAddress=this.field("emailAddress");isPrimary=this.field("isPrimary");isWritable=this.field("isWritable");isSubscription=this.field("isSubscription");color=this.field("color");syncError=this.field("syncError");emailLink=this.mappedField("emailLinkId",($)=>T$.byId(this.client,$))}class pO{client;id;constructor($,O){this.client=$;this.id=O}async status(){return G(await this.client.calendar.calendarReplacementStatus({path:{operation_id:this.id}}))}async confirm(){return G(await this.client.calendar.confirmCalendarReplacement({path:{operation_id:this.id}}))}async discard(){G(await this.client.calendar.discardCalendarReplacement({path:{operation_id:this.id}}))}}class $$ extends P{async notes($){return this.requireOwnOccurrence($),G(await this.client.calendar.eventNotes({path:{event_id:this.id},query:{occurrenceKey:$.occurrenceKey}})).map((j)=>q$.fromRecord(this.client,this,$,j))}async linkNote($,O,j={}){return this.requireOwnOccurrence(O),G(await this.client.calendar.linkEventNote({path:{event_id:this.id,document_id:$.id},query:{occurrenceKey:O.occurrenceKey},body:{teamId:j.team?.id??null}})),q$.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",($)=>$?m$.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:c6($)}));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=G(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 G(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 G(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 c6($){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 q$ 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 q$($,$$.byId($,j.eventId),j,O,{documentId:O.id,name:j.documentName,team:j.team,canManage:!0},!0)}static forDocument($,O,j,x){return new q$($,O,j,x)}static fromRecord($,O,j,x){return new q$($,O,j,w.byId($,x.documentId),x)}async fetch(){if(this.fromDocument){let x=G(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=G(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",($)=>w.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 G(await this.client.storage.getProjectPermissionsV2({path:{id:this.id}}))}async accessLevel(){return G(await this.client.storage.getProjectUserAccessLevel({path:{id:this.id}}))}access=new o(this.client,"project",this);entityType="project";propertyEntityType="PROJECT";async fetch(){let{data:$}=G(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}=G(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:$}=G(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 $=G(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 G(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 w.byId(this.client,this.documentId)}async author(){return M.byId(this.client,(await this.detail.get()).sender_id)}async reply($){return this.document().comment($,{threadId:await this.threadId()})}async edit($){let{content:O,mentions:j}=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()=>G(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 u6=8;class w extends X${async meetingNotes(){return G(await this.client.calendar.documentNoteLinks({path:{document_id:this.id}})).map((O)=>({note:q$.fromDocumentLink(this.client,this,O),eventTitle:O.eventTitle}))}async anchors(){return G(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,G(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 G(await this.client.storage.getDocumentPermissionsV2({path:{document_id:this.id}})).documentPermissions}async permissionsToken(){return G(await this.client.storage.getDocumentPermissionsToken({path:{document_id:this.id}})).token}async prepareSave($){return G(await this.client.storage.presaveDocumentHandler({path:{document_id:this.id},body:{newBom:$}})).data}async save($){return(await this.mutate((O)=>O.storage.saveDocumentHandler({path:{document_id:this.id},body:$}))).data}async simpleSave(){return(await this.mutate(($)=>$.storage.simpleSave({path:{document_id:this.id}}))).data}messageThreadById($){return L$.byId(this.client,{type:"document",entity:this},$)}timelinePage($){return w$(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:$}=G(await this.client.storage.getDocument({path:{document_id:this.id}}));return $.documentMetadata}static byId($,O){return new w($,O)}static async create($,O){let{documentId:j}=G(await $.storage.createMarkdownHandler({body:{documentName:O.name,markdown:O.markdown??null,projectId:O.project?.id??null}}));return new w($,j)}static async createSnippet($,O){let{documentId:j}=G(await $.storage.createSnippetHandler({body:{snippetName:O.name,markdown:O.markdown??null,projectId:O.project?.id??null}}));return new w($,j)}static async createSkill($,O){let{documentId:j}=G(await $.storage.createSkillHandler({body:{skillName:O.name,markdown:O.markdown??null,projectId:O.project?.id??null}}));return new w($,j)}static recent($,O){let j=O?.pageSize??50;return u(async(x)=>{let S=G(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 w($,Z.documentId)),nextCursor:K!=null?String(K):null}})}static async recentlyDeleted($){let{data:O}=G(await $.storage.recentlyDeleted({}));return O.items.filter((j)=>j.type==="document").map((j)=>new w($,j.id))}entityType="document";propertyEntityType="DOCUMENT";name=this.field("documentName");fileType=this.field("fileType");project=this.mappedField("projectId",($)=>$?n.byId(this.client,$):void 0);owner=this.mappedField("owner",($)=>M.byId(this.client,$));branchedFrom=this.mappedField("branchedFromId",($)=>$?w.byId(this.client,$):void 0);createdAt=this.field("createdAt");updatedAt=this.field("updatedAt");deletedAt=this.field("deletedAt");async content(){let{text:$}=G(await this.client.storage.getDocumentTextContent({path:{document_id:this.id}}));if($!==null)return $;let{presigned_url:O}=G(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}=G(await this.client.storage.copyDocument({path:{document_id:this.id},query:$.versionId!==void 0?{version_id:$.versionId}:void 0,body:{documentName:$.name}}));return new w(this.client,O.documentMetadata.documentId)}async comments(){let $={parent_type:"document",parent_id:this.id},O=u(async(x)=>{let S=G(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 uO(j,u6,async(x)=>{let{state:S,root:K,replies:Z}=G(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 G(await this.client.storage.getDocumentShortId({path:{document_id:this.id}}))}async teamShare(){return G(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:$}=G(await this.client.storage.getDocumentGithubPullRequests({path:{document_id:this.id}}));return $}async branchName(){let{branchName:$}=G(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 w($,O.document_id)});toMention(){let $=this.detail.peek();return{tag:a$("m-document-mention",{documentId:this.id,documentName:$?.documentName??"",blockName:$?.fileType??"md"}),mention:{entity_type:"document",entity_id:this.id}}}}class lx{client;async noteDocuments($=""){let O=G(await this.client.calendar.noteDocuments({query:{query:$}}));return{documents:O.documents.map((j)=>({document:w.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 G(await this.client.calendar.getAvailabilityCalendars()).calendars.map(($)=>({calendar:m$.byId(this.client,$.calendarId),name:$.name,isPrimary:$.isPrimary,contributesToAvailability:$.contributesToAvailability}))}async teamSharing(){return G(await this.client.calendar.getTeamSharing()).sharing}async setTeamSharing($){return G(await this.client.calendar.setTeamSharing({body:{sharing:$}})).sharing}occurrences($){let O;return u(async(j)=>{let x=G(await this.client.storage.listOccurrences({query:{...$,cursor:j}}));O??=l6(this.client);let S=await O;return{items:x.items.map((K)=>({event:$$.fromRecord(this.client,K.event),occurrence:K.occurrence,inbox:K.event.calendarId?S.get(K.event.calendarId):void 0,role:r6(K.event)})),nextCursor:x.nextCursor}})}async teamPage($){let O=G(await this.client.storage.listTeamCalendar({query:$}));return{items:O.items.map(({ownerId:j,...x})=>({...x,owner:M.byId(this.client,j)})),members:O.members.map((j)=>({user:M.byId(this.client,j.userId),sharing:j.sharing,coverage:j.coverage})),nextCursor:O.nextCursor??void 0}}async teamOutOfOffice($){let O=G(await this.client.storage.listTeamOutOfOffice({query:$}));return{items:O.items.map((j)=>({event:$$.byId(this.client,j.eventId),owner:M.byId(this.client,j.ownerId),occurrenceKey:j.occurrenceKey,time:j.time,title:j.title??void 0})),hasMore:O.hasMore}}constructor($){this.client=$}calendars(){return m$.list(this.client)}calendar($){return m$.byId(this.client,$)}event($){return $$.byId(this.client,$)}replacement($){return new pO(this.client,$)}async createEvent($){let O=G(await this.client.calendar.createCalendarEvent({body:d6($)}));return $$.fromRecord(this.client,O)}}function d6($){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 l6($){let{calendars:O}=G(await $.calendar.listCalendars());return new Map(O.map((j)=>[j.id,j.emailAddress]))}function r6($){let O=$.attendees.find((j)=>j.isSelf);if($.viewerCan.organize||O?.isOrganizer)return"organizer";return O?"guest":void 0}class H$ extends P{lookupToken;constructor($,O,j){super($,O,j);this.lookupToken=j?.shareToken}static byId($,O){return new H$($,O)}static from($,O){return new H$($,O.id,O)}async fetch(){if(this.lookupToken)return G(await this.client.storage.meetingLookup({path:{token:this.lookupToken}}));let $=G(await this.client.storage.meetingList()).meetings.find((O)=>O.id===this.id);if(!$)throw new E(`Meeting ${this.id} is unavailable`);return this.lookupToken=$.shareToken,$}title=this.field("title");scheduledStart=this.field("scheduledStart");scheduledEnd=this.field("scheduledEnd");channel=this.mappedField("channelId",($)=>$?b.byId(this.client,$):void 0);call=this.mappedField("callId",($)=>$?Q$.byId(this.client,$):void 0);async update($){await this.mutate((O)=>O.storage.meetingUpdate({path:{meeting_id:this.id},body:$}))}async cancel(){await this.mutate(($)=>$.storage.meetingCancel({path:{meeting_id:this.id}}))}async invitePermissions(){return G(await this.client.storage.meetingInvitePermissions({path:{token:(await this.detail.get()).shareToken}}))}async invite($){G(await this.client.storage.meetingInvite({path:{token:(await this.detail.get()).shareToken},body:{email:$}}))}async inviteUsers($){G(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 u$ 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 G(await this.client.storage.entityMessageGetMessage({path:this.path}))}static byId($,O,j){return new u$($,O,j)}static from($,O,j){return new u$($,O,j.id,j)}content=this.field("content");createdAt=this.field("created_at");updatedAt=this.field("updated_at");call(){return Q$.byId(this.client,this.callId)}async author(){return M.byId(this.client,(await this.detail.get()).sender_id)}async reply($){let O=G(await this.client.storage.entityMessageCreate({path:{parent_type:"call",parent_id:this.callId},body:{...O$($),thread_id:this.callId}}));return u$.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 Q$ extends z${messageThreadById($){return L$.byId(this.client,{type:"call",entity:this},$)}timelinePage($){return w$(this.client,{type:"call",entity:this},(O)=>u$.from(this.client,this.id,O),$)}access=new o(this.client,"call",this);async meeting(){return H$.from(this.client,G(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 G(await this.client.storage.getCallRecord({path:{call_id:this.id}}))}static byId($,O){return new Q$($,O)}message($){return u$.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",($)=>M.byId(this.client,$));isActive=this.field("isActive");status=this.field("status");roomName=this.field("roomName");startedAt=this.field("startedAt");endedAt=this.field("endedAt");durationMs=this.field("durationMs");summary=this.field("summary");transcript=this.field("transcript");participants=this.field("participants");guests=this.field("guests");teamShareAccessLevel=this.field("teamShareAccessLevel");shareWithTeam=this.field("shareWithTeam");recordingUrl=this.field("recordingUrl");recordingPreviewUrl=this.field("recordingPreviewUrl");recordingStartedAt=this.field("recordingStartedAt");async rename($){await this.mutate((O)=>O.storage.editCallRecord({path:{call_id:this.id},body:{customName:$??""}}))}async setTeamShare($){await this.mutate((O)=>O.storage.editCallRecord({path:{call_id:this.id},body:{sharePermission:{teamShareAccessLevel:$?"view":null}}}))}async delete(){await this.mutate(($)=>$.storage.deleteCallRecord({path:{call_id:this.id}}))}static search=x$({filters:{call_filters:{}},type:"call",make:($,O)=>new Q$($,O.call_id)})}class rx{client;constructor($){this.client=$}byId($){return Q$.byId(this.client,$)}search($,O){return Q$.search(this.client,$,O)}}class px{client;constructor($){this.client=$}async list(){let{labels:$}=G(await this.client.storage.listChannelLabels());return $}async create($,O=[]){return G(await this.client.storage.createChannelLabel({body:{name:$,channelIds:O.map((j)=>j.id)}}))}async createSmartTag($,O){return G(await this.client.storage.createChannelLabel({body:{name:$,rule:O}}))}async previewSmartTag($){return G(await this.client.storage.previewSmartTag({body:$}))}async updateSmartTag($,O,j){return G(await this.client.storage.renameChannelLabel({path:{label_id:$.id},body:{name:O,rule:j}}))}async rename($,O){return G(await this.client.storage.renameChannelLabel({path:{label_id:$.id},body:{name:O}}))}async delete($){G(await this.client.storage.deleteChannelLabel({path:{label_id:$.id}}))}async setLabel($,O){G(await this.client.storage.setChannelLabel({path:{channel_id:$.id},body:{labelId:O?.id??null}}))}}class ax{client;async activity(){return G(await this.client.storage.getActivity()).map(($)=>new JO(this.client,b.byId(this.client,$.channel_id),$))}labels;constructor($){this.client=$;this.labels=new px($)}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:$}=G(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}=G(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(){G(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 $=G(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:$}=G(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}=G(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:$}=G(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:a$("m-document-mention",{documentId:this.id,documentName:this.detail.peek()?.name??"",blockName:"chat",blockParams:{}}),mention:{entity_type:"chat",entity_id:this.id}}}}class ix{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 p6=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 G(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 M.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=u(async(K)=>{let Z=G(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 uO(S,p6,async(K)=>{let{state:Z,root:X,replies:Y}=G(await $.storage.entityMessageGetThread({path:{...j,id:K.id}}));return{thread:Z,comments:[X,...Y].map((L)=>P$.from($,O,L))}})}async function sO($,O,j,x){let S=G(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 z${messageThreadById($){return L$.byId(this.client,{type:"crm_contact",entity:this},$)}timelinePage($){return w$(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 G(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 L$.byId(this.client,{type:"crm_company",entity:this},$)}timelinePage($){return w$(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 G(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 G(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 s$ extends P{tableDetail=new B$(async()=>G(await this.client.storage.getCrmPipelineTable({path:{id:this.id}})));static byId($,O){return new s$($,O)}static from($,O){return new s$($,O.id,O)}async fetch(){return G(await this.client.storage.getCrmPipeline({path:{id:this.id}}))}name=this.field("name");recordType=this.field("recordType");accessLevel=this.field("grant");sharing=this.field("sharing");owner=this.mappedField("userId",($)=>M.byId(this.client,$));team=this.mappedField("teamId",($)=>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 G(await this.client.storage.getCrmPipelinePermissions({path:{id:this.id}}))}async updateSharePermissions($){return this.mutate((O)=>O.storage.updateCrmPipelinePermissions({path:{id:this.id},body:i$($)}))}async table(){return zj.from(this.client,this,await this.tableRecord())}tableRecord(){return this.tableDetail.get()}rows(){return u(async($)=>{let O=G(await this.client.storage.getCrmPipelineRows({path:{id:this.id},query:{after:$}}));return{items:O.rows.map((j)=>BO.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 u(async(O)=>{let j=G(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)=>BO.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 BO.byId(this.client,this.pipeline,$)}rows(){return this.pipeline.rows()}}class BO 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 BO($,O,j)}static from($,O,j){return new BO($,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 nx{client;constructor($){this.client=$}byId($){return s$.byId(this.client,$)}async list(){return G(await this.client.storage.listCrmPipelines()).map(($)=>s$.from(this.client,$))}async create($){return s$.from(this.client,G(await this.client.storage.createCrmPipeline({body:$})))}}class sx{client;pipelines;constructor($){this.client=$;this.pipelines=new nx($)}companyById($){return b$.byId(this.client,$)}contactById($){return f$.byId(this.client,$)}async contactByEmail($){let{contact:O}=G(await this.client.storage.getContactByEmail({query:{email:$}}));return O?f$.from(this.client,O):void 0}async searchContacts($,O={}){let{contacts:j}=G(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,G(await this.client.storage.createCrmCompany({body:$})))}async settings(){return G(await this.client.storage.getCrmTeamSettings())}async updateSettings($){return G(await this.client.storage.putCrmTeamSettings({body:$}))}async setStages($){return G(await this.client.storage.putCrmTeamStages({body:$}))}async resetStages(){G(await this.client.storage.resetCrmTeamStages())}searchCompanies($){return b$.search(this.client,$)}}var G$=Symbol.for("@ts-pattern/matcher"),m1=Symbol.for("@ts-pattern/isVariadic");var tx=($)=>Boolean($&&typeof $=="object"),Tj=($)=>$&&!!$[G$],s=($,O,j)=>{if(Tj($)){let x=$[G$](),{matched:S,selections:K}=x.match(O);return S&&K&&Object.keys(K).forEach((Z)=>j(Z,K[Z])),S}if(tx($)){if(!tx(O))return!1;if(Array.isArray($)){if(!Array.isArray(O))return!1;let x=[],S=[],K=[];for(let Z of $.keys()){let X=$[Z];Tj(X)&&X[m1]?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),Y=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],Y,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)||Tj(K=S)&&K[G$]().matcherType==="optional")&&s(S,O[x],j);var K})}return Object.is(O,$)},Y$=($)=>{var O,j,x;return tx($)?Tj($)?(O=(j=(x=$[G$]()).getSelectionKeys)==null?void 0:j.call(x))!=null?O:[]:Array.isArray($)?tO($,Y$):tO(Object.values($),Y$):[]},tO=($,O)=>$.reduce((j,x)=>j.concat(O(x)),[]);function a6(...$){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:()=>$0($),and:(O)=>d($,O),or:(O)=>c1($,O),select:(O)=>O===void 0?eO($):eO(O,$)})}function ex($){return Object.assign(((O)=>Object.assign(O,{[Symbol.iterator](){let j=0,x=[{value:Object.assign(O,{[m1]:!0}),done:!1},{done:!0,value:void 0}];return{next:()=>{var S;return(S=x[j++])!=null?S:x.at(-1)}}}}))($),{optional:()=>ex($0($)),select:(O)=>ex(O===void 0?eO($):eO(O,$))})}function $0($){return t({[G$]:()=>({match:(O)=>{let j={},x=(S,K)=>{j[S]=K};return O===void 0?(Y$($).forEach((S)=>x(S,void 0)),{matched:!0,selections:j}):{matched:s($,O,x),selections:j}},getSelectionKeys:()=>Y$($),matcherType:"optional"})})}var i6=($,O)=>{for(let j of $)if(!O(j))return!1;return!0},n6=($,O)=>{for(let[j,x]of $.entries())if(!O(x,j))return!1;return!0},s6=($,O)=>{let j=Reflect.ownKeys($);for(let x of j)if(!O(x,$[x]))return!1;return!0};function d(...$){return t({[G$]:()=>({match:(O)=>{let j={},x=(S,K)=>{j[S]=K};return{matched:$.every((S)=>s(S,O,x)),selections:j}},getSelectionKeys:()=>tO($,Y$),matcherType:"and"})})}function c1(...$){return t({[G$]:()=>({match:(O)=>{let j={},x=(S,K)=>{j[S]=K};return tO($,Y$).forEach((S)=>x(S,void 0)),{matched:$.some((S)=>s(S,O,x)),selections:j}},getSelectionKeys:()=>tO($,Y$),matcherType:"or"})})}function m($){return{[G$]:()=>({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({[G$]:()=>({match:(x)=>{let S={[O!=null?O:"@ts-pattern/anonymous-select-key"]:x};return{matched:j===void 0||s(j,x,(K,Z)=>{S[K]=Z}),selections:S}},getSelectionKeys:()=>[O!=null?O:"@ts-pattern/anonymous-select-key"].concat(j===void 0?[]:Y$(j))})})}function u1($){return!0}function k$($){return typeof $=="number"}function t$($){return typeof $=="string"}function e$($){return typeof $=="bigint"}var d1=t(m(u1)),t6=t(m(u1)),e6=d1,o$=($)=>Object.assign(t($),{startsWith:(O)=>{return o$(d($,(j=O,m((x)=>t$(x)&&x.startsWith(j)))));var j},endsWith:(O)=>{return o$(d($,(j=O,m((x)=>t$(x)&&x.endsWith(j)))));var j},minLength:(O)=>o$(d($,((j)=>m((x)=>t$(x)&&x.length>=j))(O))),length:(O)=>o$(d($,((j)=>m((x)=>t$(x)&&x.length===j))(O))),maxLength:(O)=>o$(d($,((j)=>m((x)=>t$(x)&&x.length<=j))(O))),includes:(O)=>{return o$(d($,(j=O,m((x)=>t$(x)&&x.includes(j)))));var j},regex:(O)=>{return o$(d($,(j=O,m((x)=>t$(x)&&Boolean(x.match(j))))));var j}}),h1=o$(m(t$)),g$=($)=>Object.assign(t($),{between:(O,j)=>g$(d($,((x,S)=>m((K)=>k$(K)&&x<=K&&S>=K))(O,j))),lt:(O)=>g$(d($,((j)=>m((x)=>k$(x)&&x<j))(O))),gt:(O)=>g$(d($,((j)=>m((x)=>k$(x)&&x>j))(O))),lte:(O)=>g$(d($,((j)=>m((x)=>k$(x)&&x<=j))(O))),gte:(O)=>g$(d($,((j)=>m((x)=>k$(x)&&x>=j))(O))),int:()=>g$(d($,m((O)=>k$(O)&&Number.isInteger(O)))),finite:()=>g$(d($,m((O)=>k$(O)&&Number.isFinite(O)))),positive:()=>g$(d($,m((O)=>k$(O)&&O>0))),negative:()=>g$(d($,m((O)=>k$(O)&&O<0)))}),o6=g$(m(k$)),$O=($)=>Object.assign(t($),{between:(O,j)=>$O(d($,((x,S)=>m((K)=>e$(K)&&x<=K&&S>=K))(O,j))),lt:(O)=>$O(d($,((j)=>m((x)=>e$(x)&&x<j))(O))),gt:(O)=>$O(d($,((j)=>m((x)=>e$(x)&&x>j))(O))),lte:(O)=>$O(d($,((j)=>m((x)=>e$(x)&&x<=j))(O))),gte:(O)=>$O(d($,((j)=>m((x)=>e$(x)&&x>=j))(O))),positive:()=>$O(d($,m((O)=>e$(O)&&O>0))),negative:()=>$O(d($,m((O)=>e$(O)&&O<0)))}),$7=$O(m(e$)),O7=t(m(function($){return typeof $=="boolean"})),j7=t(m(function($){return typeof $=="symbol"})),x7=t(m(function($){return $==null})),S7=t(m(function($){return $!=null})),Z$={__proto__:null,matcher:G$,optional:$0,array:function(...$){return ex({[G$]:()=>({match:(O)=>{if(!Array.isArray(O))return{matched:!1};if($.length===0)return{matched:!0};let j=$[0],x={};if(O.length===0)return Y$(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?[]:Y$($[0])})})},set:function(...$){return t({[G$]:()=>({match:(O)=>{if(!(O instanceof Set))return{matched:!1};let j={};if(O.size===0)return{matched:!0,selections:j};if($.length===0)return{matched:!0};let x=(K,Z)=>{j[K]=(j[K]||[]).concat([Z])},S=$[0];return{matched:i6(O,(K)=>s(S,K,x)),selections:j}},getSelectionKeys:()=>$.length===0?[]:Y$($[0])})})},map:function(...$){return t({[G$]:()=>({match:(O)=>{if(!(O instanceof Map))return{matched:!1};let j={};if(O.size===0)return{matched:!0,selections:j};let x=(X,Y)=>{j[X]=(j[X]||[]).concat([Y])};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:n6(O,(X,Y)=>{let L=s(K,Y,x),Q=s(Z,X,x);return L&&Q}),selections:j}},getSelectionKeys:()=>$.length===0?[]:[...Y$($[0]),...Y$($[1])]})})},record:function(...$){return t({[G$]:()=>({match:(O)=>{if(O===null||typeof O!="object"||Array.isArray(O))return{matched:!1};var j;if($.length===0)throw Error(`\`P.record\` wasn't given enough arguments. Expected (value) or (key, value), received ${(j=$[0])==null?void 0:j.toString()}`);let x={},S=(X,Y)=>{x[X]=(x[X]||[]).concat([Y])},[K,Z]=$.length===1?[h1,$[0]]:$;return{matched:s6(O,(X,Y)=>{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,Y,S);return(J||Q)&&I}),selections:x}},getSelectionKeys:()=>$.length===0?[]:[...Y$($[0]),...Y$($[1])]})})},intersection:d,union:c1,not:function($){return t({[G$]:()=>({match:(O)=>({matched:!s($,O,()=>{})}),getSelectionKeys:()=>[],matcherType:"not"})})},when:m,select:eO,any:d1,unknown:t6,_:e6,string:h1,number:o6,bigint:$7,boolean:O7,symbol:j7,nullish:x7,nonNullable:S7,instanceOf:function($){return t(m(function(O){return(j)=>j instanceof O}($)))},shape:function($){return t(m(a6($)))}};class l1 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 ox={matched:!1,value:void 0};function c($){return new Hj($,ox)}class Hj{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=(Y,L)=>{S=!0,K[Y]=L},X=!j.some((Y)=>s(Y,this.input,Z))||x&&!Boolean(x(this.input))?ox:{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 Hj(this.input,X)}when($,O){if(this.state.matched)return this;let j=Boolean($(this.input));return new Hj(this.input,j?{matched:!0,value:O(this.input,this.input)}:ox)}otherwise($){return this.state.matched?this.state.value:$(this.input)}exhaustive($=Z7){return this.state.matched?this.state.value:$(this.input)}run(){return this.exhaustive()}returnType(){return this}narrow(){return this}}function Z7($){throw new l1($)}var O0,X7=new Uint8Array(16);function Rj(){if(!O0){if(typeof crypto>"u"||!crypto.getRandomValues)throw Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");O0=crypto.getRandomValues.bind(crypto)}return O0(X7)}var j$=[];for(let $=0;$<256;++$)j$.push(($+256).toString(16).slice(1));function r1($,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 j0={};function K7($,O,j){let x;if($)x=p1($.random??$.rng?.()??Rj(),$.msecs,$.seq,O,j);else{let S=Date.now(),K=Rj();Y7(j0,S,K),x=p1(K,j0.msecs,j0.seq,O,j)}return O??r1(x)}function Y7($,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 p1($,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 d$=K7;class A${table;id;constructor($,O){this.table=$;this.id=O}static byId($,O){return new A$($,O)}async detail(){let{columns:$}=await this.table.detail(),O=$.find((j)=>j.column.id===this.id);if(!O)throw new E(`column ${this.id} is not on table ${this.table.id}`);return O}async name(){let $=await this.detail();return $.column.display_name??$.definition.definition.display_name}async rename($){return await this.table.database.renameColumn(this,$),this}async inferType($){return await this.table.database.inferColumnType(this,$),this}changeType($){return this.table.database.changeColumnType(this,$)}convertIntoNewColumn($){return this.table.database.convertColumnIntoNewColumn(this,$)}casts(){return this.table.database.columnCasts(this)}async delete(){await this.table.database.deleteColumn(this)}async dataType(){return(await this.detail()).definition.definition.data_type}async isMultiSelect(){return(await this.detail()).definition.definition.is_multi_select}async position(){return(await this.detail()).column.position}async definition(){return(await this.detail()).definition}async config(){return(await this.detail()).column.config??void 0}async addOptions($){return await this.table.database.addColumnOptions(this,$),this}toJSON(){return{id:this.id,tableId:this.table.id}}}class 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 J${database;id;constructor($,O){this.database=$;this.id=O}static byId($,O){return new J$($,O)}async detail(){let{tables:$}=await this.database.schema(),O=$.find((j)=>j.table.id===this.id);if(!O)throw new E(`table ${this.id} is not in database ${this.database.id}`);return O}async name(){return(await this.detail()).table.name}async rename($){return await this.database.renameTable(this,$),this}async version(){return(await this.detail()).table.version}async position(){return(await this.detail()).table.position}async columns(){let{columns:$}=await this.detail();return $.map((O)=>A$.byId(this,O.column.id))}addColumn($){return this.database.addColumn(this,$)}async reorderColumns($){return await this.database.reorderColumns(this,$),this}row($){return 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=G(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 J$.byId(Z(J),Q)},Y=new Set(Object.keys(S.newVersions).map((Q)=>X(Q).database.id));if(S.statement.kind==="schema")Y.add(S.statement.databaseId);for(let Q of Y)for(let J of K.get(Q)??[])J.invalidateSchema();let L=c(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:B})=>{let V=X(Q);return{kind:"alterColumnType",table:V,tableName:J,column:A$.byId(V,I),columnName:z,to:B}}).exhaustive();return{result:S.result?G7(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 G7($,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 Cj{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 Cj($,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 Z0 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 Mj($){return c($).with({type:"relation"},({table:O})=>({type:"relation",database:O.database.id,table:O.id})).with({type:Z$.not("relation")},(O)=>O).exhaustive()}var Q7={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 J7($){return c($).with({type:"text"},()=>"Text").with({type:"number"},()=>"Number").with({type:"boolean"},()=>"Checkbox").with({type:"date"},()=>"Date").with({type:"link"},()=>"URL").with({type:"select",multi:!0},()=>"Multi-select").with({type:"select",multi:!1},()=>"Select").with({type:"select_number",multi:!0},()=>"Multi-number select").with({type:"select_number",multi:!1},()=>"Number select").with({type:"tag"},()=>"Tag").with({type:"entity"},({target:O})=>Q7[O]).with({type:"relation"},()=>"Relation").exhaustive(()=>"Column")}function x0($){return $.map((O)=>({id:d$(),label:O}))}function a1($,O,j){return $?.kind===O&&"change"in $&&$.change.kind===j}function S0($){return c($).with({kind:"reorder_tables"},({kind:O})=>O).with({kind:Z$.union("table","column","rows","view")},({kind:O,change:j})=>`${O}.${j.kind}`).exhaustive(()=>"unknown")}function l$($,O,j){let[x]=$;if($.length!==1||!a1(x,O,j))throw new f(`expected one ${O}.${j} result, got ${$.map(S0).join(", ")||"none"}`);return x}class V$ extends P{access=new o(this.client,"database",this);async fetch(){return G(await this.client.storage.getDatabase({path:{id:this.id}}))}assertOwns($,O){if(O.id!==this.id)throw new f(`${$} does not belong to database ${this.id}`)}static byId($,O){return new V$($,O)}static async create($,O){let j=G(await $.storage.createDatabase({body:{name:O.name}}));return new V$($,j.id)}static async list($){return G(await $.storage.listDatabases()).map((j)=>new V$($,j.database.id))}query($,O){return _j(this.client,V$.byId,$,{...O,database:this})}invalidateSchema(){this.detail.clear()}schema(){return this.detail.get()}name=this.mappedField("database",($)=>$.name);owner=this.mappedField("database",($)=>M.byId(this.client,$.owner_id));createdAt=this.mappedField("database",($)=>$.created_at);trashedAt=this.mappedField("database",($)=>$.trashed_at??void 0);grant=this.field("grant");tables=this.mappedField("tables",($)=>$.map((O)=>J$.byId(this,O.table.id)));async table($){let{tables:O}=await this.schema(),j=O.find((x)=>x.table.name===$);return j?J$.byId(this,j.table.id):void 0}async createTable($){let{table:O}=l$(await this.applyOps([{kind:"table",table:d$(),change:{kind:"create",name:$.name}}]),"table","created");return J$.byId(this,O)}async applyOps($,O={}){let j={ops:$};if(O.baseVersions!==void 0){for(let{table:S}of O.baseVersions)this.assertOwns(`table ${S.id}`,S.database);j.baseVersions=Object.fromEntries(O.baseVersions.map(({table:S,version:K})=>[S.id,K]))}let{results:x}=await this.mutate(async(S)=>{let K=await S.storage.applyDatabaseOps({path:{id:this.id},body:j});if(K.error!==void 0&&"op"in K.error)throw new Z0(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(S0).join(", ")||"none"}`);return j.tables.map(({table:x})=>J$.byId(this,x))}async deleteTable($){this.assertOwns(`table ${$.id}`,$.database),l$(await this.applyOps([{kind:"table",table:$.id,change:{kind:"delete"}}]),"table","deleted")}async columnCasts($){return this.assertOwns(`column ${$.id}`,$.table.database),G(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}=G(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}=G(await this.client.storage.getDatabaseRowHistory({path:{id:this.id,table_id:$.table.id,row_id:$.id}}));return O}async importTable($){let O=await this.mutate((j)=>j.storage.importDatabaseTable({path:{id:this.id},body:$}));return J$.byId(this,O.id)}webhookOf($){return Cj.fromRecord(J$.byId(this,$.tableId),M.byId(this.client,$.createdBy),$)}async webhooks(){let{webhooks:$}=G(await this.client.storage.listDatabaseWebhooks({path:{id:this.id}}));return $.map((O)=>this.webhookOf(O))}async createWebhook($){this.assertOwns("table",$.database);let O=G(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),G(await this.client.storage.deleteDatabaseWebhook({path:{id:this.id,webhook_id:$.id}}))}async sharePermissions(){return G(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 l$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"change_type",to:Mj(O.to)}}],{baseVersions:[{table:$.table,version:j}]}),"column","type_changed")}async columnConversion($,O){return this.assertOwns(`column ${$.id}`,$.table.database),G(await this.client.storage.convertDatabaseColumn({path:{id:this.id,table_id:$.table.id,column_id:$.id},body:{to:Mj(O)}}))}async convertColumnIntoNewColumn($,O){let j=await this.columnConversion($,O.to),x=O.name??`${await $.name()} (${J7(O.to)})`,S=d$(),K=[{kind:"column",table:$.table.id,column:S,change:{kind:"create",definition:{source:"new",name:x,type:Mj(O.to),options:x0(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:Y})=>({row:X,cells:[{column:S,value:Y}]}))}}});let[Z]=await this.applyOps(K,{baseVersions:[{table:$.table,version:j.tableVersion}]});if(!a1(Z,"column","created"))throw new f(`expected a column.created result, got ${Z?S0(Z):"none"}`);return A$.byId($.table,Z.column)}async deleteColumn($){this.assertOwns(`column ${$.id}`,$.table.database);let O=await $.table.version(),{tableVersion:j}=l$(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}=l$(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}=l$(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}=l$(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:Mj(O.type),...O.options!==void 0?{options:x0(O.options)}:{},...O.inferType!==void 0?{inferType:O.inferType}:{}},{column:x}=l$(await this.applyOps([{kind:"column",table:$.id,column:d$(),change:{kind:"create",definition:j,...O.after!==void 0?{after:O.after.id}:{}}}]),"column","created");return A$.byId($,x)}async addColumnOptions($,O){return this.assertOwns(`column ${$.id}`,$.table.database),l$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"add_options",options:x0(O)}}]),"column","options_added")}}class X0{client;constructor($){this.client=$}query($,O){return _j(this.client,V$.byId,$,O)}byId($){return V$.byId(this.client,$)}create($){return V$.create(this.client,$)}list(){return V$.list(this.client)}}class Pj{id;name;constructor($,O){this.id=$;this.name=O}static async list($){let{skills:O}=G(await $.storage.getSystemSkillsHandler());return O.map((j)=>new Pj(j.id,j.name))}}class K0{client;async byTeamSlug($){let O=G(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 w.byId(this.client,O.data.documentMetadata.documentId)}async validatePermissionsToken($){let O=G(await this.client.storage.validateDocumentPermissionsToken({body:{token:$}}));return{document:w.byId(this.client,O.document_id),user:O.user_id?M.byId(this.client,O.user_id):void 0,accessLevel:O.access_level,expiresAt:O.exp,issuer:O.iss}}async createUpload($){let O={documentName:$.name,sha:$.sha,fileType:$.fileType,mimeType:$.mimeType,projectId:$.project?.id,teamId:$.team?.id,branchedFromId:$.branchedFrom?.id,emailAttachmentId:$.attachment?.id,isTask:$.isTask},j=G(await this.client.storage.createDocument({body:O})).data;return{document:w.byId(this.client,j.documentMetadata.documentId),uploadUrl:j.presignedUrl??void 0,contentType:j.contentType,content:j.documentMetadata.content}}constructor($){this.client=$}byId($){return w.byId(this.client,$)}create($){return w.create(this.client,$)}async createCanvas($){let O=G(await this.client.storage.createCanvasHandler({body:{documentName:$.name,projectId:$.project?.id}}));return w.byId(this.client,O.documentId)}createSnippet($){return w.createSnippet(this.client,$)}createSkill($){return w.createSkill(this.client,$)}systemSkills(){return Pj.list(this.client)}search($,O){return w.search(this.client,$,O)}recent($){return w.recent(this.client,$)}recentlyDeleted(){return w.recentlyDeleted(this.client)}}class WO extends P{async fetch(){let{attachment:$}=G(await this.client.email.getAttachment({path:{id:this.id}}));return $}static byId($,O){return new WO($,O)}static from($,O){return new WO($,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:$}=G(await this.client.email.getAttachmentDocumentId({path:{id:this.id}}));return w.byId(this.client,$)}}class R$ extends X${access=new o(this.client,"email_thread",this);async followup(){return G(await this.client.storage.getEmailFollowup({path:{thread_id:this.id}}))}async setFollowup($){return G(await this.client.storage.setEmailFollowup({path:{thread_id:this.id},body:$}))}async calendarInvitations(){return G(await this.client.email.getThreadCalendarInvitations({path:{thread_id:this.id}}))}async addEventToCalendar($,O,j={}){let x=G(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?i$($.sharePermission):void 0}}))}entityType="email_thread";propertyEntityType="THREAD";async fetch(){let{thread:$}=G(await this.client.email.getThread({path:{thread_id:this.id},query:{limit:100}}));return $}static byId($,O){return new R$($,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",($)=>T$.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 G(await this.client.email.getThreadMessagesHandler({path:{id:this.id},query:{...$?.since?{since:$.since}:{},...$?.limit?{limit:$.limit}:{}}})).map((j)=>D$.from(this.client,j))}async attachments(){let{messages:$}=await this.detail.get();return $.flatMap((O)=>O.attachments.map((j)=>WO.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?D$.byId(this.client,j.db_id):void 0}async archive($=!0){await this.mutate((O)=>O.email.archiveThread({path:{id:this.id},body:{value:$}}))}async updateState($){await this.mutate((O)=>O.email.updateThreadState({path:{id:this.id},body:$}))}async operations(){return G(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 R$($,O.thread_id)})}class D$ extends P{async fetch(){return G(await this.client.email.getMessage({path:{id:this.id}}))}static byId($,O){return new D$($,O)}static from($,O){return new D$($,O.db_id,O)}static async send($,O){let{message:j}=G(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?D$.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",($)=>T$.byId(this.client,$));async operationStatus(){return G(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 R$.byId(this.client,(await this.detail.get()).thread_db_id)}}class LO extends D${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:{...Y0($),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 Y0($){let{bodyText:O,bodyHtml:j,bodyMacro:x,headers:S,includeSignature:K,draftGeneration:Z,thread:X,replyingTo:Y,...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:Y?.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 $=G(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 OO extends P{async fetch(){let{labels:$}=G(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 OO($,O)}static async list($){let{labels:O}=G(await $.email.listLabels());return O.map((j)=>new OO($,j.id,j))}static async create($,O){let{label:j}=G(await $.email.createLabel({body:{label_name:O}}));if(!j.id)throw new f("created label has no id");return new OO($,j.id)}async delete(){G(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 G0{client;async createDraft($,O){let j=G(await this.client.email.createDraft({body:{draft:Y0($)},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=G(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 G(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,G(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 G(await this.client.email.listContacts()).contacts}reminders($){let{inboxes:O,...j}=$??{};return u(async(x)=>{let S=G(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:R$.byId(this.client,K)})),nextCursor:S.nextCursor}})}constructor($){this.client=$}byId($){return R$.byId(this.client,$)}message($){return D$.byId(this.client,$)}attachment($){return WO.byId(this.client,$)}link($){return T$.byId(this.client,$)}links(){return T$.list(this.client)}async connectionProviders(){return G(await this.client.auth.emailConnectionProviders())}async recoverDraftTransfer($){return G(await this.client.email.recoverDraftTransfer({path:{id:$}}))}send($){return D$.send(this.client,$)}search($,O){return R$.search(this.client,$,O)}inbox($){return u(async(O)=>{let j=G(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)=>R$.byId(this.client,x.id)),nextCursor:j.next_cursor}})}label($){return OO.byId(this.client,$)}labels(){return OO.list(this.client)}createLabel($){return OO.create(this.client,$)}async deleteLabel($){G(await this.client.email.deleteLabel({path:{id:$.id}}))}async blockSender($){G(await this.client.email.blockSender({body:{email_address:$}}))}async unblockSender($){G(await this.client.email.unblockSender({body:{email_address:$}}))}async blockedSenders(){return G(await this.client.email.listBlockedSenders()).blocked_emails}}class HO{client;id;constructor($,O){this.client=$;this.id=O}static byId($,O){return new HO($,O)}async delete(){G(await this.client.storage.deleteEntityMention({path:{mention_id:this.id}}))}toJSON(){return{id:this.id}}}class Q0{client;constructor($){this.client=$}byId($){return HO.byId(this.client,$)}async create($,O){let j=G(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 HO.byId(this.client,j.id)}}class J0{client;constructor($){this.client=$}async list($={}){let{favorites:O}=G(await this.client.storage.listFavorites({query:{entityType:$.entityTypes,entityId:$.entityIds}}));return O}async add($){return G(await this.client.storage.addFavorite({body:{entityId:$.id,entityType:$.entityType}}))}async remove($){G(await this.client.storage.removeFavoriteByEntity({path:{entity_type:$.entityType,entity_id:$.id}}))}async reorder($){G(await this.client.storage.reorderFavorites({body:{favorites:$}}))}}class jO extends z${entityType="foreign_entity";async fetch(){return G(await this.client.storage.getForeignEntity({path:{id:this.id}}))}static byId($,O){return new jO($,O)}static fromRecord($,O){return new jO($,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 i1({login:$,...O}){return{...O,login:$??void 0}}class V0{client;constructor($){this.client=$}byId($){return jO.byId(this.client,$)}async bySource($,O){return jO.fromRecord(this.client,G(await this.client.storage.getForeignEntityBySource({path:{source:$,foreign_entity_id:O}})))}async githubPullRequestFacets(){let{repositories:$,authors:O,assignees:j,labels:x}=G(await this.client.storage.getGithubPullRequestFacets());return{repositories:$,authors:O.map(i1),assignees:j.map(i1),labels:x.map(({color:S,...K})=>({...K,color:S??void 0}))}}}class r${form;id;constructor($,O){this.form=$;this.id=O}static byId($,O){return new r$($,O)}async detail(){let O=(await this.form.schema()).sections.flatMap((j)=>j.kind==="questions"?j.questions:[]).find((j)=>j.id===this.id);if(!O)throw new E(`question ${this.id} is not on form ${this.form.id}`);return O}async title(){return(await this.detail()).title}async column(){return A$.byId(await this.form.table(),(await this.detail()).column)}async options(){return(await this.detail()).options.map(($)=>UO.byId(this,$.id))}}class UO{question;id;constructor($,O){this.question=$;this.id=O}static byId($,O){return new UO($,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 p${form;id;constructor($,O){this.form=$;this.id=O}static byId($,O){return new p$($,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)=>r$.byId(this.form,O.id)):[]}}class Aj{entityType;id;constructor($,O){this.entityType=$;this.id=O}static byId($,O){return new Aj($,O)}}class y$ extends P{async fetch(){return G(await this.client.storage.getForm({path:{id:this.id}}))}static byId($,O){return new y$($,O)}static async create($,O){let j=G(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 y$($,j.form.id,j)}static async list($,O){if(!O)return G(await $.storage.listAccessibleForms()).map(({form:S})=>new y$($,S.id));return G(await $.storage.listForms({query:{databaseId:O.id}})).map((x)=>new y$($,x.id))}schema(){return this.detail.get()}name=this.mappedField("form",($)=>$.name);description=this.mappedField("form",($)=>$.description);owner=this.mappedField("form",($)=>M.byId(this.client,$.ownerId));database=this.mappedField("form",($)=>V$.byId(this.client,$.databaseId));table=this.mappedField("form",($)=>J$.byId(V$.byId(this.client,$.databaseId),$.tableId));audience=this.mappedField("form",($)=>$.audience);status=this.mappedField("form",($)=>$.status);closesAt=this.mappedField("form",($)=>$.closesAt??void 0);access=this.field("access");async sections(){return(await this.detail.get()).sections.map(($)=>p$.byId(this,$.id))}async questions(){return(await this.detail.get()).sections.flatMap(($)=>$.kind==="questions"?$.questions.map((O)=>r$.byId(this,O.id)):[])}async update($){return await this.mutate((O)=>O.storage.updateForm({path:{id:this.id},body:$})),this}assertOwns($){if($.form.id!==this.id)throw new f(`question or section does not belong to form ${this.id}`)}async replaceLayout($){let O=await this.table(),j=(Z)=>{if(Z.table.id!==O.id||Z.table.database.id!==O.database.id)throw new f(`column does not belong to form ${this.id}'s table`);return Z.id},x=(Z)=>({conjunction:Z.conjunction,conditions:Z.conditions.map((X)=>c(X).with({kind:"group"},(Y)=>({kind:"group",...x(Y)})).with({kind:"condition"},(Y)=>({kind:"condition",column:j(Y.column),test:c(Y.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","checkbox")},(L)=>L).exhaustive()})).exhaustive())}),S={sections:$.map((Z)=>{if(Z.section)this.assertOwns(Z.section);let X={id:Z.section?.id??d$(),title:Z.title,description:Z.description??""};return c(Z).with({kind:"booking"},(Y)=>({...X,kind:"booking",target:Y.target})).with({kind:"gate"},(Y)=>({...X,kind:"gate",rules:x(Y.rules),message:Y.message})).with({kind:"questions"},(Y)=>({...X,kind:"questions",questions:Y.questions.map((L)=>{if(L.question)this.assertOwns(L.question);return{id:L.question?.id??d$(),column:j(L.column),helpText:L.helpText??"",required:L.required??!1,widget:L.widget??null}})})).exhaustive()})},K=await this.mutate((Z)=>Z.storage.putFormLayout({path:{id:this.id},body:S}));return{form:this,publicationError:K.publicationError}}wireAnswers($){return $.map(({question:O,value:j})=>{this.assertOwns(O);let x=c(j).with({type:"rows"},(S)=>({type:"rows",value:S.value.map((K)=>K.id)})).with({type:"options"},(S)=>({type:"options",value:S.value.map((K)=>{if(K.question.id!==O.id||K.question.form.id!==this.id)throw new f("option does not belong to the answered question");return{id:K.id}})})).with({type:"entities"},(S)=>({type:"entities",value:S.value.map(({entityType:K,entity:Z})=>({entityType:K,entityId:Z.id}))})).with({type:Z$.union("text","number","boolean","date","link","clear")},(S)=>S).exhaustive();return{question:O.id,value:x}})}unlockedBooking($){return $?{...$,section:p$.byId(this,$.section)}:void 0}async outcome($,O){return c($).with({outcome:"stopped"},(j)=>({...j,section:p$.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(G(await this.client.storage.submitFormResponse({path:{id:this.id},body:O})),$)}async editResponse($){let O={answers:this.wireAnswers($)};return this.outcome(G(await this.client.storage.editMyFormResponse({path:{id:this.id},body:O})),$)}async myResponse(){let $=G(await this.client.storage.getMyFormResponse({path:{id:this.id}})),O=await this.table(),j=await Promise.all($.answers.map(async(K)=>{let Z=r$.byId(this,K.question),X=await c(K.value).with({type:"options"},(Y)=>({type:"options",value:Y.value.map((L)=>{if(!("id"in L))throw new f("stored form answers must reference options by id");return UO.byId(Z,L.id)})})).with({type:"entities"},(Y)=>({type:"entities",value:Y.value.map((L)=>({entityType:L.entityType,entity:Aj.byId(L.entityType,L.entityId)}))})).with({type:"rows"},async(Y)=>{let L=await Z.detail();if(L.kind.type!=="relation")throw new f("row answer requires a relation question");let Q=J$.byId(V$.byId(this.client,L.kind.database),L.kind.table);return{type:"rows",value:Y.value.map((J)=>F$.byId(Q,J))}}).with({type:Z$.union("text","number","boolean","date","link","clear")},(Y)=>Y).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?p$.byId(this,$.response.stoppedAtSection):void 0,row:x,submittedAt:$.response.submittedAt,updatedAt:$.response.updatedAt,answers:j}}async responseSummary(){let $=G(await this.client.storage.getFormResponseSummary({path:{id:this.id}}));return{...$,stoppedBySection:$.stoppedBySection.map((O)=>({section:p$.byId(this,O.section),count:O.count}))}}async tally(){return G(await this.client.storage.getFormTally({path:{id:this.id}})).questions.map((O)=>{let j=r$.byId(this,O.question);return{question:j,responses:O.responses,buckets:O.buckets.flatMap((x)=>c(x.value).with({kind:"option"},(S)=>[{count:x.count,value:{kind:"option",option:UO.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 G(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 B0{client;constructor($){this.client=$}byId($){return y$.byId(this.client,$)}create($){return y$.create(this.client,$)}list($){return y$.list(this.client,$)}}class DO extends P{static byId($,O){return new DO($,O)}async fetch(){return G(await this.client.storage.getGithubPullRequest({path:{id:this.id}}))}title=this.field("title");url=this.field("url");status=this.field("status");async changes(){let $=G(await this.client.storage.getGithubPullRequestChanges({path:{id:this.id}}));return{changeset:$.changeset?new W0(this.client,this,$.changeset):void 0,error:$.error??void 0}}}class W0{client;pullRequest;record;constructor($,O,j){this.client=$;this.pullRequest=O;this.record=j}get id(){return this.record.id}async patch(){return G(await this.client.storage.getGithubPullRequestChangesPatch({path:{id:this.pullRequest.id},query:{changeset:this.id}})).patch}toJSON(){return{pullRequestId:this.pullRequest.id,...this.record}}}class L0{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 G(await this.client.storage.getHarnessPairing({path:{code:this.id}}))}name=this.field("requested_name");expiresAt=this.field("expires_at");async approve($){let O={name:$?.name,team_id:$?.team?.id,allow_permission_bypass:$?.allowPermissionBypass};return W$.from(this.client,await this.mutate((j)=>j.storage.approveHarnessPairing({path:{code:this.id},body:O})))}}class $j{client;id;constructor($,O){this.client=$;this.id=O}static byId($,O){return new $j($,O)}async claim($){let O=G(await this.client.storage.claimHarnessPairing({path:{pairing_id:this.id},body:{device_secret:$}}));return"harness"in O?{harness:W$.from(this.client,O.harness),token:O.token}:void 0}toJSON(){return{id:this.id}}}class N0{client;constructor($){this.client=$}byId($){return W$.byId(this.client,$)}async list(){return G(await this.client.storage.listHarnesses()).map(($)=>W$.from(this.client,$))}async me(){return W$.from(this.client,G(await this.client.storage.getSelfHarness()))}async deleteSelf(){G(await this.client.storage.deleteSelfHarness())}async agents(){return G(await this.client.storage.listHarnessAgents()).map(($)=>I$.byId(this.client,$.bot_id))}async sessions(){return G(await this.client.storage.listHarnessSessions()).map(($)=>i.byId(this.client,$.session_id))}pairing($){return _O.byId(this.client,$)}async createPairing($){let O=G(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}}}var V7="00000001-0000-0000-0000-000000000002",B7="00000001-0000-0000-0002-000000000004";function W7($){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 _$ extends w{static byId($,O){return new _$($,O)}static async create($,O){let{documentId:j}=G(await $.storage.createTaskHandler({body:{taskName:O.name,markdown:O.markdown??null,projectId:O.project?.id??null,teamId:O.team?.id??null,shareWithTeam:O.shareWithTeam??!0}}));return new _$($,j)}static async forPullRequest($,O){let j=W7(O),{pullRequests:x}=G(await $.storage.getGithubPullRequestTasks({body:{githubKeys:[j]}}));return(x[0]?.taskIds??[]).map((S)=>new _$($,S))}async completed(){let{subType:$}=await this.detail.get();if($!=="task")return;let j=(await this.properties()).find((x)=>x.definition.id===V7)?.value;return j?.type==="SelectOption"&&j.value.includes(B7)}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 _$($,O.document_id)})}class xO extends P{access=new o(this.client,"initiative",this);static byId($,O){return new xO($,O)}static from($,O){return new xO($,O.id,O)}async fetch(){return G(await this.client.storage.getInitiative({path:{initiative_id:this.id}}))}name=this.field("name");owner=this.mappedField("ownerId",($)=>M.byId(this.client,$));members=this.mappedField("memberIds",($)=>$.map((O)=>M.byId(this.client,O)));tasks=this.mappedField("taskIds",($)=>$.map((O)=>_$.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?i$($.sharePermission):void 0}}))}async delete(){await this.mutate(($)=>$.storage.deleteInitiative({path:{initiative_id:this.id}}))}}class U0{client;constructor($){this.client=$}byId($){return xO.byId(this.client,$)}async list(){return G(await this.client.storage.listInitiatives()).initiatives.map(($)=>xO.byId(this.client,$.id))}async create($){return xO.from(this.client,G(await this.client.storage.createInitiative({body:{name:$.name,description:$.description,memberIds:$.members?.map((O)=>O.id),shareWithTeam:$.shareWithTeam,propertyValues:$.propertyValues}})))}}class z0{client;constructor($){this.client=$}byId($){return H$.byId(this.client,$)}async create($){return H$.from(this.client,G(await this.client.storage.meetingCreate({body:$})))}async list(){return G(await this.client.storage.meetingList()).meetings.map(($)=>H$.from(this.client,$))}async active(){return G(await this.client.storage.meetingListActive()).meetings.map(($)=>H$.from(this.client,$))}async lookup($){return H$.from(this.client,G(await this.client.storage.meetingLookup({path:{token:$}})))}}class zO extends P{async fetch(){return G(await this.client.notification.getTypedNotificationById({path:{notification_id:this.id}}))}static byId($,O){return new zO($,O)}static from($,O){return new zO($,O.id,O)}static list($,O){return u(async(j)=>{let x=G(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)=>zO.from($,S)),nextCursor:x.next_cursor}})}type=this.field("notification_event_type");createdAt=this.field("created_at");updatedAt=this.field("updated_at");state=this.field("state");done=this.mappedField("state",($)=>$==="done");sent=this.field("sent");viewedAt=this.field("viewed_at");deletedAt=this.field("deleted_at");owner=this.mappedField("owner_id",($)=>M.byId(this.client,$));sender=this.mappedField("sender_id",($)=>$?M.byId(this.client,$):void 0);metadata=this.field("notification_metadata");async seen(){return await this.state()!=="unseen"}async markSeen(){await this.mutate(($)=>$.notification.bulkMarkNotificationsSeen({body:{notificationIds:[this.id]}}))}async markDone(){await this.mutate(($)=>$.notification.bulkMarkNotificationsDone({body:{notificationIds:[this.id]}}))}async markUndone(){await this.mutate(($)=>$.notification.bulkMarkNotificationsUndone({body:{notificationIds:[this.id]}}))}async delete(){await this.mutate(($)=>$.notification.deleteUserNotificationV2({path:{notification_id:this.id}}))}}class I0{client;constructor($){this.client=$}byId($){return zO.byId(this.client,$)}list($){return zO.list(this.client,$)}async markSeen($){G(await this.client.notification.bulkMarkNotificationsSeen({body:{notificationIds:$}}))}async markDone($){G(await this.client.notification.bulkMarkNotificationsDone({body:{notificationIds:$}}))}async delete($){G(await this.client.notification.bulkDeleteUserNotificationsV2({body:{notificationIds:$}}))}async preferences(){return G(await this.client.notification.getNotificationTypePreferences())}async enableType($){G(await this.client.notification.enableNotificationType({path:{notification_event_type:$}}))}async disableType($){G(await this.client.notification.disableNotificationType({path:{notification_event_type:$}}))}}class T0{client;constructor($){this.client=$}async list(){let{data:$}=G(await this.client.storage.getPinsHandler({}));return $?.recent??[]}async add($,O){G(await this.client.storage.addPinHandler({path:{pinned_item_id:$.id},body:{pinType:$.entityType,pinIndex:O.index}}))}async remove($){G(await this.client.storage.removePinHandler({path:{pinned_item_id:$.id},body:{pinType:$.entityType}}))}async reorder($){G(await this.client.storage.reorderPinsHandler({body:$}))}}class H0{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 CO{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 CO($,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=G(await this.client.properties.updatePropertyOption({path:{definition_id:this.definitionId,option_id:this.id},body:$})),this}async delete(){G(await this.client.properties.deletePropertyOption({path:{definition_id:this.definitionId,option_id:this.id}}))}}class SO{client;id;detail;constructor($,O,j){this.client=$;this.id=O;this.detail=new B$(()=>this.fetch(),j)}async fetch(){return G(await this.client.properties.getPropertyDefinition({path:{definition_id:this.id}}))}static async create($,O){let j=G(await $.properties.createPropertyDefinition({body:{display_name:O.displayName,scope:O.scope,data_type:O.dataType}}));return new SO($,j.id,j)}static byId($,O){return new SO($,O)}static fromRecord($,O){return new SO($,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 G(await this.client.properties.deletePropertyDefinition({path:{definition_id:this.id}}))}async options(){return G(await this.client.properties.getPropertyOptions({path:{definition_id:this.id}})).map((O)=>CO.from(this.client,this.id,O))}async addOption($){let O=G(await this.client.properties.addPropertyOption({path:{definition_id:this.id},body:$}));return CO.from(this.client,this.id,O)}async updateOption($,O){let j=G(await this.client.properties.updatePropertyOption({path:{definition_id:this.id,option_id:$.id},body:O}));return CO.from(this.client,this.id,j)}async deleteOption($){return G(await this.client.properties.deletePropertyOption({path:{definition_id:this.id,option_id:$.id}}))}}class R0{client;constructor($){this.client=$}async list($){return G(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 SO.fromRecord(this.client,x)})}create($){return SO.create(this.client,$)}definition($){return SO.byId(this.client,$)}async bulkEntityProperties($){return G(await this.client.properties.getBulkEntityProperties({body:$}))}async updateEntityPropertyOptions($,O){return G(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 G(await this.client.properties.addEntityPropertyOption({path:{...$.entity.propertyReference(),property_id:$.property.id,option_id:$.option.id}}))}async removeEntityPropertyOption($){return G(await this.client.properties.removeEntityPropertyOption({path:{...$.entity.propertyReference(),property_id:$.property.id,option_id:$.option.id}}))}async tags(){return G(await this.client.properties.listTags({}))}}function D0($){return c($).with({type:"cron"},(O)=>O).with({type:"events"},(O)=>({type:"events",filters:O.filters.map(({entities:j,...x})=>({...x,ids:j?.map((S)=>S.entity.id)}))})).exhaustive()}function L7($){return c($).with({type:"multiple"},(O)=>({type:"multiple",triggers:O.triggers.map(D0)})).with({type:"cron"},D0).with({type:"events"},D0).exhaustive()}class ZO extends P{static byId($,O){return new ZO($,O)}static from($,O){if(!O.id)throw Error("Routine response has no id");return new ZO($,O.id,O)}async fetch(){return G(await this.client.scheduledAction.getScheduledAction({path:{id:this.id}}))}name=this.field("name");trigger=this.field("trigger");enabled=this.field("enabled");runVisibility=this.field("run_visibility");nextRunAt=this.field("next_run_at");revision=this.field("configuration_revision");owner=this.mappedField("owner",($)=>M.byId(this.client,$));async update($){await this.mutate((O)=>O.scheduledAction.updateScheduledAction({path:{id:this.id},body:C0($)}))}async setEnabled($){await this.mutate((O)=>O.scheduledAction.setScheduledActionEnabled({path:{id:this.id},body:{enabled:$}}))}async execute(){let $=G(await this.client.scheduledAction.executeScheduledActionNow({path:{id:this.id}}));if($.resource)return c($.resource).with({type:"agent"},(O)=>i.byId(this.client,O.id)).with({type:"chat"},(O)=>K$.byId(this.client,O.id)).exhaustive();return $.chat_id?K$.byId(this.client,$.chat_id):void 0}async history(){return G(await this.client.scheduledAction.listScheduledActionHistory({path:{id:this.id}})).map(($)=>new _0(this,$))}async delete(){await this.mutate(($)=>$.scheduledAction.deleteScheduledAction({path:{id:this.id}}))}}class _0{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 C0($){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:L7($.trigger),task:{...O}}}class M0{client;constructor($){this.client=$}byId($){return ZO.byId(this.client,$)}async create($){return ZO.from(this.client,G(await this.client.scheduledAction.createScheduledAction({body:{...C0($),enabled:$.enabled??!0}})))}async list($){return G(await this.client.scheduledAction.listScheduledActions({query:{include_events:$?.includeEvents}})).map((O)=>ZO.from(this.client,O))}}class P0{client;constructor($){this.client=$}byId($){return _$.byId(this.client,$)}create($){return _$.create(this.client,$)}forPullRequest($){return _$.forPullRequest(this.client,$)}search($,O){return _$.search(this.client,$,O)}}class A0{client;constructor($){this.client=$}byId($){return S$.byId(this.client,$)}current(){return S$.current(this.client)}list(){return S$.list(this.client)}}class F0{client;constructor($){this.client=$}async get($){return G(await this.client.unfurl.getUnfurl({query:{url:$}}))}async bulk($){return G(await this.client.unfurl.getUnfurlBulk({body:{url_list:$}}))}}class E0{client;constructor($){this.client=$}byId($){return M.byId(this.client,$)}me(){return M.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}=G(j),S=[...new Set(x)],K=[];for(let Z=0;Z<S.length;Z+=100){let X=S.slice(Z,Z+100),{names:Y}=G(await this.client.auth.getUserNamesWithEmail({body:{user_ids:X}})),L=new Map(Y.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(M.fromName(this.client,J))}}return K}}class XO extends P{signingSecret;constructor($,O,j,x){super($,O,j);this.signingSecret=x}async fetch(){return G(await this.client.storage.getWebhook({path:{webhook_id:this.id}}))}static async create($,O){let j=G(await $.storage.createWebhook({body:{endpoint_url:O.url,namespace:O.namespace,name:O.name,filters:O.filters,scope:O.scope??"user",...O.headers!==void 0?{headers:O.headers}:{}}}));return new XO($,j.id,j,j.signing_secret)}static byId($,O){return new XO($,O)}static fromRecord($,O){return new XO($,O.id,O)}name=this.field("name");namespace=this.field("namespace");endpointUrl=this.field("endpoint_url");status=this.field("status");isValid=this.field("is_valid");filters=this.field("filters");createdAt=this.field("created_at");workspaceId=this.field("workspace_id");createdBy=this.mappedField("created_by_user_id",($)=>M.byId(this.client,$));async scope(){let $=await this.detail.get();return $.workspace_id===$.created_by_user_id?"user":"team"}async update($){await this.mutate((O)=>O.storage.patchWebhook({path:{webhook_id:this.id},body:$}))}async rename($){await this.update({name:$})}async setUrl($){await this.update({endpoint_url:$})}async setFilters($){await this.update({filters:$})}async pause(){await this.update({status:"paused"})}async resume(){await this.update({status:"active"})}async delete(){await this.mutate(($)=>$.storage.deleteWebhook({path:{webhook_id:this.id}}))}async validate(){return this.mutate(($)=>$.storage.validateWebhook({path:{webhook_id:this.id}}))}}class w0{client;constructor($){this.client=$}create($){return XO.create(this.client,$)}byId($){return XO.byId(this.client,$)}async list(){let{webhooks:$}=G(await this.client.storage.listWebhooks());return $.map((O)=>XO.fromRecord(this.client,O))}}class MO extends P{static byId($,O){return new MO($,O)}static from($,O){return new MO($,O.id,O)}async fetch(){let{account:$}=G(await this.client.storage.linkedAccount());if($?.id!==this.id)throw new E("WhatsApp account is not available");return $}state=this.field("state");identity=this.field("identity_jid");owner=this.mappedField("user_id",($)=>M.byId(this.client,$));async refresh(){return this.detail.clear(),await this.detail.get(),this}}class C$ extends P{group;constructor($,O,j,x){super($,j,x);this.group=O}static byId($,O,j){return new C$($,O,j)}static from($,O,j){return new C$($,O,j.id,j)}async fetch(){for await(let $ of this.group.messages({limit:100}))if($.id===this.id)return $.detail.get();throw new E("WhatsApp message is not available")}body=this.field("body");sender=this.field("sender");sentAt=this.field("sent_at");editedAt=this.field("edited_at");deleted=this.field("deleted");reactions=this.field("reactions");deliveryState=this.field("delivery_state");kind=this.field("kind");forwarded=this.field("forwarded");viewOnce=this.field("view_once");mentions=this.field("mentions");rich=this.field("rich");replyTo=this.mappedField("reply_to",($)=>$?C$.byId(this.client,this.group,$):void 0);attachments=this.mappedField("attachments",($)=>$.map((O)=>({ordinal:O.ordinal,state:O.state,fileName:O.file_name,mime:O.mime,size:O.size,width:O.width??void 0,height:O.height??void 0,durationSeconds:O.duration_seconds??void 0,presentation:O.presentation??void 0,document:O.document_id?w.byId(this.client,O.document_id):void 0})))}class KO{group;id;record;constructor($,O,j){this.group=$;this.id=O;this.record=j}static byId($,O){return new KO($,O)}static from($,O){return new KO($,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,group:this.group.id,displayName:this.displayName,admin:this.admin}}}class YO{id;group;filename;kind;constructor($,O,j,x){this.id=$;this.group=O;this.filename=j;this.kind=x}static byId($,O){return new YO(O,$)}static from($,O){return new YO(O.upload_id,$,O.filename,O.kind)}toJSON(){return{id:this.id,group:this.group.id,filename:this.filename,kind:this.kind}}}class GO extends P{group;constructor($,O,j,x){super($,j,x);this.group=O}static byId($,O,j){return new GO($,O,j)}static from($,O,j){return new GO($,O,j.id,j)}async fetch(){let O=G(await this.client.storage.linkedDelivery({path:{group_id:this.group.id},body:[this.id]})).find((j)=>j.id===this.id);if(!O)throw new E("WhatsApp send is not available");return O}state=this.field("state");errorCode=this.field("error_code");createdAt=this.field("created_at");message=this.mappedField("message_id",($)=>$?C$.byId(this.client,this.group,$):void 0);async request(){let{payload:$}=await this.detail.get(),O=$.message,j=c(O).returnType().with({type:"media"},(x)=>({type:"media",upload:YO.byId(this.group,x.upload_id),caption:x.caption??void 0})).with({type:"mutation"},(x)=>({type:"mutation",message:C$.byId(this.client,this.group,x.message_id),operation:x.operation,text:x.text??void 0})).with({type:"text"},(x)=>({type:"text",text:x.text,mentions:(x.mentions??[]).map((S)=>KO.byId(this.group,S))})).exhaustive();return{idempotencyKey:$.idempotency_key,message:j,replyTo:$.reply_to?C$.byId(this.client,this.group,$.reply_to):void 0}}async refresh(){return this.detail.clear(),await this.detail.get(),this}}class v$ extends z${entityType="whatsapp_group";static byId($,O){return new v$($,O)}async fetch(){return G(await this.client.storage.whatsappGroup({path:{group_id:this.id}}))}name=this.field("name");kind=this.field("kind");canSend=this.field("can_send");sendReason=this.field("send_reason");sendingIdentity=this.field("sending_identity");unreadCount=this.field("unread_count");backfill=this.field("backfill");limits=this.field("limits");roster=this.field("roster");participants=this.mappedField("roster",($)=>($?.participants??[]).map((O)=>KO.from(this,O)));disappearingSeconds=this.field("disappearing_seconds");community=this.mappedField("community",($)=>$?q0(this.client,$):void 0);owner=this.mappedField("user_id",($)=>M.byId(this.client,$));async*messages($={}){yield*u(async(O)=>{let j=G(await this.client.storage.whatsappGroupMessages({path:{group_id:this.id},query:{before:O,limit:$.limit}}));return{items:j.messages.map((x)=>C$.from(this.client,this,x)),nextCursor:j.next_cursor}})}async markRead($){this.assertGroup($.group),await this.mutate((O)=>O.storage.whatsappGroupRead({path:{group_id:this.id},body:{message_id:$.id}}))}async permissions(){return G(await this.client.storage.whatsappGroupPermissions({path:{group_id:this.id}}))}async updatePermissions($){await this.mutate((O)=>O.storage.whatsappGroupUpdatePermissions({path:{group_id:this.id},body:$}))}async detach(){await this.mutate(($)=>$.storage.linkedDetach({path:{group_id:this.id}}))}async upload($){let O=G(await this.client.storage.linkedUpload({path:{group_id:this.id},body:{file:$}}));return YO.from(this,O)}async reply($,O){if(O.replyTo)this.assertGroup(O.replyTo.group);let j=c($).returnType().with({type:"text"},(S)=>{let K=S.mentions??[];for(let Z of K)this.assertGroup(Z.group);return{type:"text",text:S.text,mentions:K.map((Z)=>Z.id)}}).with({type:"media"},(S)=>{return this.assertGroup(S.upload.group),{type:"media",upload_id:S.upload.id,caption:S.caption}}).with({type:"mutation"},(S)=>{return this.assertGroup(S.message.group),{type:"mutation",message_id:S.message.id,operation:S.operation,text:S.text}}).exhaustive(),x=await this.mutate((S)=>S.storage.linkedReply({path:{group_id:this.id},body:{idempotency_key:O.idempotencyKey,message:j,reply_to:O.replyTo?.id}}));return GO.from(this.client,this,x)}async sends(){return G(await this.client.storage.whatsappGroupSends({path:{group_id:this.id}})).map(($)=>GO.from(this.client,this,$))}async delivery($){for(let O of $)this.assertGroup(O.group);return G(await this.client.storage.linkedDelivery({path:{group_id:this.id},body:$.map((O)=>O.id)})).map((O)=>GO.from(this.client,this,O))}async messageAttachments($){for(let O of $)this.assertGroup(O.group);return G(await this.client.storage.linkedMessageAttachments({path:{group_id:this.id},body:$.map((O)=>O.id)})).map((O)=>({message:C$.byId(this.client,this,O.message_id),attachments:O.linked_attachments.map((j)=>({ordinal:j.ordinal,state:j.state,fileName:j.file_name,mime:j.mime,size:j.size,document:j.document_id?w.byId(this.client,j.document_id):void 0}))}))}async refresh(){return this.detail.clear(),await this.detail.get(),this}assertGroup($){if($.id!==this.id)throw Error("WhatsApp reference belongs to another group")}}function q0($,O){return{chat:IO.byId($,O.id),name:O.name,announcements:O.announcements}}class IO extends P{static byId($,O){return new IO($,O)}static from($,O){return new IO($,O.jid,O)}async fetch(){let{chats:$}=G(await this.client.storage.linkedChats()),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");lastActivityAt=this.field("lastActivityAt");archived=this.field("archived");pinned=this.field("pinned");canAdd=this.field("canAdd");cannotAddReason=this.field("cannotAddReason");community=this.mappedField("community",($)=>$?q0(this.client,$):void 0);group=this.mappedField("group",($)=>$?v$.byId(this.client,$.id):void 0);shared=this.mappedField("shared",($)=>$?v$.byId(this.client,$.id):void 0);async adopt(){let $=await this.mutate((O)=>O.storage.linkedAdopt({body:{group_jid:this.id}}));return v$.byId(this.client,$.group_id)}async refresh(){return this.detail.clear(),await this.detail.get(),this}}class f0{client;constructor($){this.client=$}async account(){let{account:$}=G(await this.client.storage.linkedAccount());return $?MO.from(this.client,$):void 0}async groups(){return G(await this.client.storage.whatsappGroups()).map(($)=>v$.byId(this.client,$.id))}async chats(){return G(await this.client.storage.linkedChats()).chats.map(($)=>IO.from(this.client,$))}byId($){return v$.byId(this.client,$)}}function b0($){if("properties"in $.data)return $.data.properties;if($.tag==="calendarEvent")return $.data.extra.properties;return[]}function n1($,O,j){let x=[];for(let S of b0(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:w.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:R$.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 h$($,O.data.channel_id,O.data.id),snapshot:O,tags:x,channelId:O.data.channel_id};case"call":return{type:"call",id:O.data.callId,entity:Q$.byId($,O.data.callId),snapshot:O,tags:x,createdBy:O.data.createdBy};case"calendarEvent":return{type:"calendar_event",id:O.data.id,entity:$$.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:jO.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 s1="00000000-0000-0000-0000-000000000000",k0={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"]},Fj=($)=>$.replace(/[A-Z]/g,(O)=>O.toLowerCase()),t1=($,O)=>$==null?O:{"&":[$,O]};function g0($,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==="!"){g0(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)=>{g0(Z,`${O}.${S}[${X}]`)})}class Ej{client;tagSets;constructor($){this.client=$}sets(){return this.tagSets??=this.client.properties.listTags({}).then(G),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(k0,S))))throw Error(`Invalid workspace includeTypes. Supported values: ${Object.keys(k0).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)g0($[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:s1}},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}=G(await this.client.email.listLinks()),K=S.filter((X)=>Fj(X.email_address)===Fj(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=t1(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(k0))if(!x.includes(S))O[K]={l:{[Z]:s1}}}if($.tags?.length){let S=(await this.sets()).flatMap((Y)=>{let L=Y.definition;if(!L)return[];return Y.options.flatMap((Q)=>Q.value.type==="string"?[{id:Q.id,definitionId:L.id,label:Q.value.value,scope:Y.scope==="user"?"personal":"team"}]:[])}),K=new Map;for(let Y of $.tags){let L=S.filter((Q)=>Fj(Q.label)===Fj(Y.label.trim())&&(!Y.scope||Q.scope===Y.scope));if(!L.length)throw Error(`Unknown tag "${Y.label}". Available tags: ${S.map((Q)=>`${Q.label} (${Q.scope})`).join(", ")}.`);if($.tagsMatch==="all"&&L.length>1)throw Error(`Tag "${Y.label}" is ambiguous; specify personal or team scope.`);for(let Q of L)K.set(Q.id,Q)}let X=[...K.values()].map((Y)=>({l:{pd:Y.definitionId,v:{so:Y.id}}})).reduce((Y,L)=>Y===void 0?L:{[$.tagsMatch==="all"?"&":"|"]:[Y,L]},void 0);O.propf=t1(O.propf,X)}return O}}class y0{client;constructor($){this.client=$}async page($={}){let O=new Ej(this.client);return this.fetch(O,await O.body($),$.cursor)}async*list($={}){let O=new Ej(this.client),j=await O.body($);yield*u((x)=>this.fetch(O,j,x))}async fetch($,O,j){let x=G(await this.client.storage.postItemsSoupAst({body:O,query:j?{cursor:j}:void 0})),K=x.items.some((Z)=>b0(Z).some((X)=>X.definition.data_type==="TAG"))?await $.tagMap():new Map;return{items:x.items.map((Z)=>n1(this.client,Z,K)),nextCursor:x.next_cursor,hasMore:x.next_cursor!=null}}}function e1({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...Q}){let J,I=Y??((V)=>new Promise((W)=>setTimeout(W,V)));return{stream:async function*(){let V=K??3000,W=0,T=Q.signal??new AbortController().signal;while(!0){if(T.aborted)break;W++;let A=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)A.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:A,signal:T},_=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 H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",k=()=>{try{H.cancel()}catch{}};T.addEventListener("abort",k);try{while(!0){let{done:l,value:r}=await H.read();if(l)break;U+=r,U=U.replace(/\r\n?/g,``);let g=U.split(``);U=g.pop()??"";for(let p of g){let a=p.split(``),F=[],y;for(let R of a)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))y=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let h=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(h))V=h}let C,v=!1;if(F.length){let R=F.join(`-`);try{C=JSON.parse(R),v=!0}catch{C=R}}if(v){if(S)await S(C);if(x)C=await x(C)}if(j?.({data:C,event:y,id:J,retry:V}),F.length)yield C}}}finally{T.removeEventListener("abort",k),H.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 B7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},L7=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},N7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},Ej=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((Y)=>encodeURIComponent(Y))).join(L7(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=B7(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return PO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},PO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},wj=({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 Y=[];Object.entries(S).forEach(([Q,J])=>{Y=[...Y,Q,$?J:encodeURIComponent(J)]});let L=Y.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=N7(x),X=Object.entries(S).map(([Y,L])=>PO({allowReserved:$,name:x==="deepObject"?`${j}[${Y}]`:Y,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var U7=/\{[^{}]+\}/g,z7=({path:$,url:O})=>{let j=O,x=O.match(U7);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 Y=$[Z];if(Y===void 0||Y===null)continue;if(Array.isArray(Y)){j=j.replace(S,Ej({explode:K,name:Z,style:X,value:Y}));continue}if(typeof Y==="object"){j=j.replace(S,wj({explode:K,name:Z,style:X,value:Y,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${PO({name:Z,value:Y})}`);continue}let L=encodeURIComponent(X==="label"?`.${Y}`:Y);j=j.replace(S,L)}return j},t1=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=z7({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function g0($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var e1=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 o1={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var $2=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let Y=Ej({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(Y)S.push(Y)}else if(typeof Z==="object"){let Y=wj({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(Y)S.push(Y)}else{let Y=PO({allowReserved:X.allowReserved,name:K,value:Z});if(Y)S.push(Y)}}return S.join("&")}},O2=($)=>{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},I7=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function j2($){for(let O of $.security??[]){if(I7($,O.name))continue;let j=await e1(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var y0=($)=>t1({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:$2($.querySerializer),url:$.url}),v0=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=fj($.headers,O.headers),j},T7=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},fj=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?T7(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 qj{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var x2=()=>({error:new qj,request:new qj,response:new qj}),H7=$2({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),R7={"Content-Type":"application/json"},$j=($={})=>({...o1,headers:R7,parseAs:"auto",querySerializer:H7,...$});var h0=($={})=>{let O=v0($j(),$),j=()=>({...O}),x=(Q)=>{return O=v0(O,Q),j()},S=x2(),K=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:fj(O.headers,Q.headers),serializedBody:void 0};if(J.security)await j2(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=y0(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),T={redirect:"follow",...V,body:g0(V)};z=new Request(B,T);for(let N of S.request.fns)if(N)z=await N(z,V);let A=V.fetch;W=await A(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"?O2(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await W[N]();break;case"json":{let U=await W.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let _=await W.text(),q;try{q=JSON.parse(_)}catch{}throw q??_}catch(V){let B=V;for(let T of S.error.fns)if(T)B=await T(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}),Y=(Q)=>async(J)=>{let{opts:I,url:z}=await K(J);return s1({...I,body:I.body,method:Q,onRequest:async(W,V)=>{let B=new Request(W,V);for(let T of S.request.fns)if(T)B=await T(B,I);return B},serializedBody:g0(I),url:z})};return{buildUrl:(Q)=>y0({...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:Y("CONNECT"),delete:Y("DELETE"),get:Y("GET"),head:Y("HEAD"),options:Y("OPTIONS"),patch:Y("PATCH"),post:Y("POST"),put:Y("PUT"),trace:Y("TRACE")},trace:X("TRACE")}};var S2=h0($j());class Z2{client;constructor($){this.client=$?.client??S2}}class X2{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 bj extends Z2{static __registry=new X2;constructor($){super($);bj.__registry.set(this,$?.key)}discoverAgentCapabilitiesHandler($){return($.client??this.client).post({security:[{scheme:"bearer",type:"http"}],url:"/agent-capabilities/discover",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAgentCodingPreferences($){return($?.client??this.client).get({url:"/agent-coding-preferences",...$})}putAgentCodingPreferences($){return($.client??this.client).put({url:"/agent-coding-preferences",...$,headers:{"Content-Type":"application/json",...$.headers}})}listAgentConversations($){return($.client??this.client).get({security:[{scheme:"bearer",type:"http"}],url:"/agent-conversations/{channel_id}",...$})}startFreshAgentConversation($){return($.client??this.client).post({security:[{scheme:"bearer",type:"http"}],url:"/agent-conversations/{channel_id}/{bot_id}/start-fresh",...$,headers:{"Content-Type":"application/json",...$.headers}})}retryAgentConversationTurn($){return($.client??this.client).post({security:[{scheme:"bearer",type:"http"}],url:"/agent-conversations/{channel_id}/{bot_id}/turns/{source}/retry",...$,headers:{"Content-Type":"application/json",...$.headers}})}loadAgentModelsHandler($){return($.client??this.client).post({security:[{scheme:"bearer",type:"http"}],url:"/agent-models/load",...$,headers:{"Content-Type":"application/json",...$.headers}})}listAgentRepositories($){return($?.client??this.client).get({security:[{scheme:"bearer",type:"http"}],url:"/agent-repositories",...$})}listAgentRepositoryBranches($){return($.client??this.client).get({security:[{scheme:"bearer",type:"http"}],url:"/agent-repositories/branches",...$})}getAgentSandboxSize($){return($?.client??this.client).get({url:"/agent-sandbox-size",...$})}putAgentSandboxSize($){return($.client??this.client).put({url:"/agent-sandbox-size",...$,headers:{"Content-Type":"application/json",...$.headers}})}createAgentSession($){return($.client??this.client).post({url:"/agent-sessions",...$,headers:{"Content-Type":"application/json",...$.headers}})}agentSessionsForPullRequest($){return($.client??this.client).post({url:"/agent-sessions/by-pull-request",...$,headers:{"Content-Type":"application/json",...$.headers}})}agentSessionsForPullRequests($){return($.client??this.client).post({url:"/agent-sessions/by-pull-requests",...$,headers:{"Content-Type":"application/json",...$.headers}})}previewAgentSessions($){return($.client??this.client).post({url:"/agent-sessions/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}warmAgentSessionHandler($){return($.client??this.client).post({url:"/agent-sessions/warm",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteAgentSession($){return($.client??this.client).delete({url:"/agent-sessions/{session_id}",...$})}getAgentSession($){return($.client??this.client).get({url:"/agent-sessions/{session_id}",...$})}reportAgentSessionAppConnected($){return($.client??this.client).post({url:"/agent-sessions/{session_id}/app-connections",...$,headers:{"Content-Type":"application/json",...$.headers}})}setAgentSessionArchived($){return($.client??this.client).put({url:"/agent-sessions/{session_id}/archived",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAgentSessionChanges($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/changes",...$})}getAgentSessionChangesPatch($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/changes/patch",...$})}refreshAgentSessionChanges($){return($.client??this.client).post({url:"/agent-sessions/{session_id}/changes/refresh",...$})}getCodeExecution($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/code-executions/{execution_id}",...$})}listExecutionReviews($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/code-executions/{execution_id}/reviews",...$})}controlAgentSession($){return($.client??this.client).post({url:"/agent-sessions/{session_id}/control",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAgentSessionLog($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/log",...$})}getAgentSessionFoldedLog($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/log/folded",...$})}renameAgentSession($){return($.client??this.client).put({url:"/agent-sessions/{session_id}/name",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAgentSessionPermissions($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/permissions",...$})}updateAgentSessionPermissions($){return($.client??this.client).patch({url:"/agent-sessions/{session_id}/permissions",...$,headers:{"Content-Type":"application/json",...$.headers}})}unlinkAgentSessionPullRequest($){return($.client??this.client).delete({url:"/agent-sessions/{session_id}/pull-requests",...$})}listAgentSessionPullRequests($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/pull-requests",...$})}linkAgentSessionPullRequest($){return($.client??this.client).put({url:"/agent-sessions/{session_id}/pull-requests",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAgentSessionQueue($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/queue",...$})}removeQueuedAction($){return($.client??this.client).delete({url:"/agent-sessions/{session_id}/queue/{action_id}",...$})}editQueuedAction($){return($.client??this.client).put({url:"/agent-sessions/{session_id}/queue/{action_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}steerQueuedAction($){return($.client??this.client).post({url:"/agent-sessions/{session_id}/queue/{action_id}/steer",...$})}createSessionReview($){return($.client??this.client).post({url:"/agent-sessions/{session_id}/reviews",...$,headers:{"Content-Type":"application/json",...$.headers}})}getSessionReview($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/reviews/{review_id}",...$})}decideSessionReview($){return($.client??this.client).post({url:"/agent-sessions/{session_id}/reviews/{review_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}putAgentSessionSandboxSize($){return($.client??this.client).put({url:"/agent-sessions/{session_id}/sandbox-size",...$,headers:{"Content-Type":"application/json",...$.headers}})}answerAgentSessionToolApproval($){return($.client??this.client).post({url:"/agent-sessions/{session_id}/tool-approvals/{approval_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}}function K2({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...Q}){let J,I=Y??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,T=Q.signal??new AbortController().signal;while(!0){if(T.aborted)break;B++;let A=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)A.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:A,signal:T},_=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 H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",k=()=>{try{H.cancel()}catch{}};T.addEventListener("abort",k);try{while(!0){let{done:l,value:r}=await H.read();if(l)break;U+=r,U=U.replace(/\r\n?/g,`+`);try{C=JSON.parse(R),v=!0}catch{C=R}}if(v){if(S)await S(C);if(x)C=await x(C)}if(j?.({data:C,event:y,id:J,retry:V}),F.length)yield C}}}finally{T.removeEventListener("abort",k),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&W>=Z)break;let _=Math.min(V*2**(W-1),X??30000);await I(_)}}}()}}var N7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},U7=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},z7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},wj=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((Y)=>encodeURIComponent(Y))).join(U7(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=N7(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return PO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},PO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},qj=({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 Y=[];Object.entries(S).forEach(([Q,J])=>{Y=[...Y,Q,$?J:encodeURIComponent(J)]});let L=Y.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=z7(x),X=Object.entries(S).map(([Y,L])=>PO({allowReserved:$,name:x==="deepObject"?`${j}[${Y}]`:Y,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var I7=/\{[^{}]+\}/g,T7=({path:$,url:O})=>{let j=O,x=O.match(I7);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 Y=$[Z];if(Y===void 0||Y===null)continue;if(Array.isArray(Y)){j=j.replace(S,wj({explode:K,name:Z,style:X,value:Y}));continue}if(typeof Y==="object"){j=j.replace(S,qj({explode:K,name:Z,style:X,value:Y,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${PO({name:Z,value:Y})}`);continue}let L=encodeURIComponent(X==="label"?`.${Y}`:Y);j=j.replace(S,L)}return j},o1=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=T7({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function v0($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var $2=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var O2={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var j2=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let Y=wj({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(Y)S.push(Y)}else if(typeof Z==="object"){let Y=qj({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(Y)S.push(Y)}else{let Y=PO({allowReserved:X.allowReserved,name:K,value:Z});if(Y)S.push(Y)}}return S.join("&")}},x2=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},H7=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function S2($){for(let O of $.security??[]){if(H7($,O.name))continue;let j=await $2(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var h0=($)=>o1({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:j2($.querySerializer),url:$.url}),m0=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=bj($.headers,O.headers),j},R7=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},bj=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?R7(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 fj{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var Z2=()=>({error:new fj,request:new fj,response:new fj}),D7=j2({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),_7={"Content-Type":"application/json"},Oj=($={})=>({...O2,headers:_7,parseAs:"auto",querySerializer:D7,...$});var c0=($={})=>{let O=m0(Oj(),$),j=()=>({...O}),x=(Q)=>{return O=m0(O,Q),j()},S=Z2(),K=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:bj(O.headers,Q.headers),serializedBody:void 0};if(J.security)await S2(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let I=J,z=h0(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,B;try{let{opts:V,url:W}=await K(Q),T={redirect:"follow",...V,body:v0(V)};z=new Request(W,T);for(let N of S.request.fns)if(N)z=await N(z,V);let A=V.fetch;B=await A(z);for(let N of S.response.fns)if(N)B=await N(B,z,V);let D={request:z,response:B};if(B.ok){let N=(V.parseAs==="auto"?x2(B.headers.get("Content-Type")):V.parseAs)??"json";if(B.status===204||B.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await B[N]();break;case"formData":U=new FormData;break;case"stream":U=B.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await B[N]();break;case"json":{let U=await B.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?B.body:{data:B.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let _=await B.text(),q;try{q=JSON.parse(_)}catch{}throw q??_}catch(V){let W=V;for(let T of S.error.fns)if(T)W=await T(W,B,z,Q);if(W=W||{},J)throw W;return I==="data"?void 0:{error:W,request:z,response:B}}},X=(Q)=>(J)=>Z({...J,method:Q}),Y=(Q)=>async(J)=>{let{opts:I,url:z}=await K(J);return e1({...I,body:I.body,method:Q,onRequest:async(B,V)=>{let W=new Request(B,V);for(let T of S.request.fns)if(T)W=await T(W,I);return W},serializedBody:v0(I),url:z})};return{buildUrl:(Q)=>h0({...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:Y("CONNECT"),delete:Y("DELETE"),get:Y("GET"),head:Y("HEAD"),options:Y("OPTIONS"),patch:Y("PATCH"),post:Y("POST"),put:Y("PUT"),trace:Y("TRACE")},trace:X("TRACE")}};var X2=c0(Oj());class K2{client;constructor($){this.client=$?.client??X2}}class Y2{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class kj extends K2{static __registry=new Y2;constructor($){super($);kj.__registry.set(this,$?.key)}discoverAgentCapabilitiesHandler($){return($.client??this.client).post({security:[{scheme:"bearer",type:"http"}],url:"/agent-capabilities/discover",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAgentCodingPreferences($){return($?.client??this.client).get({url:"/agent-coding-preferences",...$})}putAgentCodingPreferences($){return($.client??this.client).put({url:"/agent-coding-preferences",...$,headers:{"Content-Type":"application/json",...$.headers}})}listAgentConversations($){return($.client??this.client).get({security:[{scheme:"bearer",type:"http"}],url:"/agent-conversations/{channel_id}",...$})}startFreshAgentConversation($){return($.client??this.client).post({security:[{scheme:"bearer",type:"http"}],url:"/agent-conversations/{channel_id}/{bot_id}/start-fresh",...$,headers:{"Content-Type":"application/json",...$.headers}})}retryAgentConversationTurn($){return($.client??this.client).post({security:[{scheme:"bearer",type:"http"}],url:"/agent-conversations/{channel_id}/{bot_id}/turns/{source}/retry",...$,headers:{"Content-Type":"application/json",...$.headers}})}loadAgentModelsHandler($){return($.client??this.client).post({security:[{scheme:"bearer",type:"http"}],url:"/agent-models/load",...$,headers:{"Content-Type":"application/json",...$.headers}})}listAgentRepositories($){return($?.client??this.client).get({security:[{scheme:"bearer",type:"http"}],url:"/agent-repositories",...$})}listAgentRepositoryBranches($){return($.client??this.client).get({security:[{scheme:"bearer",type:"http"}],url:"/agent-repositories/branches",...$})}getAgentSandboxSize($){return($?.client??this.client).get({url:"/agent-sandbox-size",...$})}putAgentSandboxSize($){return($.client??this.client).put({url:"/agent-sandbox-size",...$,headers:{"Content-Type":"application/json",...$.headers}})}createAgentSession($){return($.client??this.client).post({url:"/agent-sessions",...$,headers:{"Content-Type":"application/json",...$.headers}})}agentSessionsForPullRequest($){return($.client??this.client).post({url:"/agent-sessions/by-pull-request",...$,headers:{"Content-Type":"application/json",...$.headers}})}agentSessionsForPullRequests($){return($.client??this.client).post({url:"/agent-sessions/by-pull-requests",...$,headers:{"Content-Type":"application/json",...$.headers}})}previewAgentSessions($){return($.client??this.client).post({url:"/agent-sessions/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}warmAgentSessionHandler($){return($.client??this.client).post({url:"/agent-sessions/warm",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteAgentSession($){return($.client??this.client).delete({url:"/agent-sessions/{session_id}",...$})}getAgentSession($){return($.client??this.client).get({url:"/agent-sessions/{session_id}",...$})}reportAgentSessionAppConnected($){return($.client??this.client).post({url:"/agent-sessions/{session_id}/app-connections",...$,headers:{"Content-Type":"application/json",...$.headers}})}setAgentSessionArchived($){return($.client??this.client).put({url:"/agent-sessions/{session_id}/archived",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAgentSessionChanges($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/changes",...$})}getAgentSessionChangesPatch($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/changes/patch",...$})}refreshAgentSessionChanges($){return($.client??this.client).post({url:"/agent-sessions/{session_id}/changes/refresh",...$})}getCodeExecution($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/code-executions/{execution_id}",...$})}listExecutionReviews($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/code-executions/{execution_id}/reviews",...$})}controlAgentSession($){return($.client??this.client).post({url:"/agent-sessions/{session_id}/control",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAgentSessionLog($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/log",...$})}getAgentSessionFoldedLog($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/log/folded",...$})}renameAgentSession($){return($.client??this.client).put({url:"/agent-sessions/{session_id}/name",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAgentSessionPermissions($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/permissions",...$})}updateAgentSessionPermissions($){return($.client??this.client).patch({url:"/agent-sessions/{session_id}/permissions",...$,headers:{"Content-Type":"application/json",...$.headers}})}unlinkAgentSessionPullRequest($){return($.client??this.client).delete({url:"/agent-sessions/{session_id}/pull-requests",...$})}listAgentSessionPullRequests($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/pull-requests",...$})}linkAgentSessionPullRequest($){return($.client??this.client).put({url:"/agent-sessions/{session_id}/pull-requests",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAgentSessionQueue($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/queue",...$})}removeQueuedAction($){return($.client??this.client).delete({url:"/agent-sessions/{session_id}/queue/{action_id}",...$})}editQueuedAction($){return($.client??this.client).put({url:"/agent-sessions/{session_id}/queue/{action_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}steerQueuedAction($){return($.client??this.client).post({url:"/agent-sessions/{session_id}/queue/{action_id}/steer",...$})}createSessionReview($){return($.client??this.client).post({url:"/agent-sessions/{session_id}/reviews",...$,headers:{"Content-Type":"application/json",...$.headers}})}getSessionReview($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/reviews/{review_id}",...$})}decideSessionReview($){return($.client??this.client).post({url:"/agent-sessions/{session_id}/reviews/{review_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}putAgentSessionSandboxSize($){return($.client??this.client).put({url:"/agent-sessions/{session_id}/sandbox-size",...$,headers:{"Content-Type":"application/json",...$.headers}})}answerAgentSessionToolApproval($){return($.client??this.client).post({url:"/agent-sessions/{session_id}/tool-approvals/{approval_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}}function G2({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...Q}){let J,I=Y??((V)=>new Promise((W)=>setTimeout(W,V)));return{stream:async function*(){let V=K??3000,W=0,T=Q.signal??new AbortController().signal;while(!0){if(T.aborted)break;W++;let A=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)A.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:A,signal:T},_=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 H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",k=()=>{try{H.cancel()}catch{}};T.addEventListener("abort",k);try{while(!0){let{done:l,value:r}=await H.read();if(l)break;U+=r,U=U.replace(/\r\n?/g,``);let g=U.split(``);U=g.pop()??"";for(let p of g){let a=p.split(``),F=[],y;for(let R of a)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))y=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let h=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(h))V=h}let C,v=!1;if(F.length){let R=F.join(`-`);try{C=JSON.parse(R),v=!0}catch{C=R}}if(v){if(S)await S(C);if(x)C=await x(C)}if(j?.({data:C,event:y,id:J,retry:V}),F.length)yield C}}}finally{T.removeEventListener("abort",k),H.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 D7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},_7=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},C7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},kj=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((Y)=>encodeURIComponent(Y))).join(_7(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=D7(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return MO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},MO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},gj=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let Y=[];Object.entries(S).forEach(([Q,J])=>{Y=[...Y,Q,$?J:encodeURIComponent(J)]});let L=Y.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=C7(x),X=Object.entries(S).map(([Y,L])=>MO({allowReserved:$,name:x==="deepObject"?`${j}[${Y}]`:Y,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var P7=/\{[^{}]+\}/g,M7=({path:$,url:O})=>{let j=O,x=O.match(P7);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 Y=$[Z];if(Y===void 0||Y===null)continue;if(Array.isArray(Y)){j=j.replace(S,kj({explode:K,name:Z,style:X,value:Y}));continue}if(typeof Y==="object"){j=j.replace(S,gj({explode:K,name:Z,style:X,value:Y,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${MO({name:Z,value:Y})}`);continue}let L=encodeURIComponent(X==="label"?`.${Y}`:Y);j=j.replace(S,L)}return j},Y2=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=M7({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function m0($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var G2=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 Q2={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var J2=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let Y=kj({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(Y)S.push(Y)}else if(typeof Z==="object"){let Y=gj({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(Y)S.push(Y)}else{let Y=MO({allowReserved:X.allowReserved,name:K,value:Z});if(Y)S.push(Y)}}return S.join("&")}},V2=($)=>{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},A7=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function W2($){for(let O of $.security??[]){if(A7($,O.name))continue;let j=await G2(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var c0=($)=>Y2({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:J2($.querySerializer),url:$.url}),u0=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=vj($.headers,O.headers),j},F7=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},vj=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?F7(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 yj{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 B2=()=>({error:new yj,request:new yj,response:new yj}),E7=J2({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),w7={"Content-Type":"application/json"},Oj=($={})=>({...Q2,headers:w7,parseAs:"auto",querySerializer:E7,...$});var d0=($={})=>{let O=u0(Oj(),$),j=()=>({...O}),x=(Q)=>{return O=u0(O,Q),j()},S=B2(),K=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:vj(O.headers,Q.headers),serializedBody:void 0};if(J.security)await W2(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=c0(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),T={redirect:"follow",...V,body:m0(V)};z=new Request(B,T);for(let N of S.request.fns)if(N)z=await N(z,V);let A=V.fetch;W=await A(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"?V2(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await W[N]();break;case"json":{let U=await W.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let _=await W.text(),q;try{q=JSON.parse(_)}catch{}throw q??_}catch(V){let B=V;for(let T of S.error.fns)if(T)B=await T(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}),Y=(Q)=>async(J)=>{let{opts:I,url:z}=await K(J);return K2({...I,body:I.body,method:Q,onRequest:async(W,V)=>{let B=new Request(W,V);for(let T of S.request.fns)if(T)B=await T(B,I);return B},serializedBody:m0(I),url:z})};return{buildUrl:(Q)=>c0({...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:Y("CONNECT"),delete:Y("DELETE"),get:Y("GET"),head:Y("HEAD"),options:Y("OPTIONS"),patch:Y("PATCH"),post:Y("POST"),put:Y("PUT"),trace:Y("TRACE")},trace:X("TRACE")}};var L2=d0(Oj());class N2{client;constructor($){this.client=$?.client??L2}}class U2{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class hj extends N2{static __registry=new U2;constructor($){super($);hj.__registry.set(this,$?.key)}deleteAgentApiKey($){return($.client??this.client).delete({url:"/agents/{agent_id}/api-key",...$})}getAgentApiKey($){return($.client??this.client).get({url:"/agents/{agent_id}/api-key",...$})}putAgentApiKey($){return($.client??this.client).put({url:"/agents/{agent_id}/api-key",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateAiBillingAutoReload($){return($.client??this.client).patch({url:"/ai-billing/auto-reload",...$,headers:{"Content-Type":"application/json",...$.headers}})}createAiCreditCheckout($){return($.client??this.client).post({url:"/ai-billing/credits/checkout",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateAiBillingOverage($){return($.client??this.client).patch({url:"/ai-billing/overage",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAiBillingPlans($){return($?.client??this.client).get({url:"/ai-billing/plans",...$})}getAiBillingSummary($){return($?.client??this.client).get({url:"/ai-billing/summary",...$})}disconnectCodex($){return($?.client??this.client).delete({url:"/codex",...$})}getCodexConnection($){return($?.client??this.client).get({url:"/codex",...$})}configureCodex($){return($.client??this.client).put({url:"/codex/config",...$,headers:{"Content-Type":"application/json",...$.headers}})}listCodexEnvironments($){return($?.client??this.client).get({url:"/codex/environments",...$})}startCodexLogin($){return($?.client??this.client).post({url:"/codex/login",...$})}cancelCodexLogin($){return($.client??this.client).delete({url:"/codex/login/{attempt_id}",...$})}pollCodexLogin($){return($.client??this.client).get({url:"/codex/login/{attempt_id}",...$})}deleteCursorApiKey($){return($?.client??this.client).delete({url:"/cursor-api-key",...$})}getCursorApiKey($){return($?.client??this.client).get({url:"/cursor-api-key",...$})}putCursorApiKey($){return($.client??this.client).put({url:"/cursor-api-key",...$,headers:{"Content-Type":"application/json",...$.headers}})}putCursorDefaultModel($){return($.client??this.client).put({url:"/cursor-api-key/default-model",...$,headers:{"Content-Type":"application/json",...$.headers}})}listCursorModels($){return($?.client??this.client).get({url:"/cursor-api-key/models",...$})}verifyFusionauthUserEmail($){return($.client??this.client).get({url:"/email/fusionauth/verify/{verification_id}",...$})}resendFusionauthVerifyUserEmail($){return($.client??this.client).post({url:"/email/fusionauth_resend",...$,headers:{"Content-Type":"application/json",...$.headers}})}generateEmailLink($){return($.client??this.client).post({url:"/email/generate/link",...$,headers:{"Content-Type":"application/json",...$.headers}})}verifyEmailLink($){return($.client??this.client).get({url:"/email/verify/{verification_id}",...$})}setGithubPullRequestDraft($){return($.client??this.client).post({url:"/github_pull_requests/draft",...$,headers:{"Content-Type":"application/json",...$.headers}})}enrichGithubPullRequests($){return($.client??this.client).post({url:"/github_pull_requests/enrich",...$,headers:{"Content-Type":"application/json",...$.headers}})}mergeGithubPullRequest($){return($.client??this.client).post({url:"/github_pull_requests/merge",...$,headers:{"Content-Type":"application/json",...$.headers}})}getGithubPullRequestMergeability($){return($.client??this.client).post({url:"/github_pull_requests/mergeability",...$,headers:{"Content-Type":"application/json",...$.headers}})}listGtmInviteLinks($){return($?.client??this.client).get({url:"/gtm-invite/links",...$})}createGtmInviteLink($){return($.client??this.client).post({url:"/gtm-invite/links",...$,headers:{"Content-Type":"application/json",...$.headers}})}revokeGtmInviteLink($){return($.client??this.client).delete({url:"/gtm-invite/links/{id}",...$})}getGtmInviteOffer($){return($?.client??this.client).get({url:"/gtm-invite/offer",...$})}resolveGtmInviteLink($){return($.client??this.client).get({url:"/gtm-invite/public/{token}",...$})}redeemGtmInviteLink($){return($.client??this.client).post({url:"/gtm-invite/redeem",...$,headers:{"Content-Type":"application/json",...$.headers}})}healthHandler($){return($?.client??this.client).get({url:"/health",...$})}macroApiToken($){return($.client??this.client).get({url:"/jwt/macro_api_token",...$})}refresh($){return($?.client??this.client).post({url:"/jwt/refresh",...$})}createInProgressLink($){return($?.client??this.client).post({url:"/link",...$})}emailConnectionProviders($){return($?.client??this.client).get({url:"/link/email/providers",...$})}deleteGithubLink($){return($?.client??this.client).delete({url:"/link/github",...$})}initGithubLink($){return($.client??this.client).post({url:"/link/github",...$})}checkGithubLinkStatus($){return($?.client??this.client).get({url:"/link/github/status",...$})}initGmailLink($){return($.client??this.client).post({url:"/link/gmail",...$})}checkGmailLinkStatus($){return($?.client??this.client).get({url:"/link/gmail/status",...$})}initOutlookLink($){return($?.client??this.client).post({url:"/link/outlook",...$})}appleLogin($){return($.client??this.client).post({url:"/login/apple",...$,headers:{"Content-Type":"application/json",...$.headers}})}passwordLogin($){return($.client??this.client).post({url:"/login/password",...$,headers:{"Content-Type":"application/json",...$.headers}})}passwordlessLogin($){return($.client??this.client).post({url:"/login/passwordless",...$,headers:{"Content-Type":"application/json",...$.headers}})}ssoLogin($){return($.client??this.client).get({url:"/login/sso",...$})}logout($){return($?.client??this.client).post({url:"/logout",...$})}createMergeRequest($){return($.client??this.client).post({url:"/merge",...$,headers:{"Content-Type":"application/json",...$.headers}})}verifyMergeRequest($){return($.client??this.client).get({url:"/merge/verify/{code}",...$})}sendMobileWelcomeEmail($){return($.client??this.client).post({url:"/mobile-welcome-email",...$,headers:{"Content-Type":"application/json",...$.headers}})}passwordlessCallback($){return($.client??this.client).get({url:"/oauth/passwordless/{code}",...$})}oauthRedirect($){return($?.client??this.client).get({url:"/oauth/redirect",...$})}oauth2Callback($){return($.client??this.client).get({url:"/oauth2/{provider}/callback",...$})}getPermissions($){return($?.client??this.client).get({url:"/permissions",...$})}getUserPermissions($){return($?.client??this.client).get({url:"/permissions/me",...$})}getReferralCode($){return($?.client??this.client).get({url:"/referral/code",...$})}sendReferralCode($){return($.client??this.client).post({url:"/referral/send",...$,headers:{"Content-Type":"application/json",...$.headers}})}sessionCreation($){return($?.client??this.client).post({url:"/session",...$})}sessionLogin($){return($.client??this.client).get({url:"/session/login/{session_code}",...$})}deleteTeam($){return($?.client??this.client).delete({url:"/team",...$})}getTeam($){return($?.client??this.client).get({url:"/team",...$})}patchTeam($){return($.client??this.client).patch({url:"/team",...$,headers:{"Content-Type":"application/json",...$.headers}})}createTeam($){return($.client??this.client).post({url:"/team",...$,headers:{"Content-Type":"application/json",...$.headers}})}toggleTeamAutoJoinDomain($){return($?.client??this.client).post({url:"/team/auto-join-domain/toggle",...$})}patchTeamCrmSettings($){return($.client??this.client).patch({url:"/team/crm",...$,headers:{"Content-Type":"application/json",...$.headers}})}inviteToTeam($){return($.client??this.client).post({url:"/team/invite",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteTeamInviteLink($){return($?.client??this.client).delete({url:"/team/invite-link",...$})}getTeamInviteLink($){return($?.client??this.client).get({url:"/team/invite-link",...$})}createTeamInviteLink($){return($?.client??this.client).post({url:"/team/invite-link",...$})}joinTeamByInviteLink($){return($.client??this.client).post({url:"/team/invite-link/join",...$,headers:{"Content-Type":"application/json",...$.headers}})}getTeamByInviteLink($){return($.client??this.client).post({url:"/team/invite-link/team",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteTeamInviteHandler($){return($.client??this.client).delete({url:"/team/invite/{team_invite_id}",...$})}getTeamInvites($){return($?.client??this.client).get({url:"/team/invites",...$})}rejectInvitation($){return($.client??this.client).delete({url:"/team/join/{team_invite_id}",...$})}joinTeam($){return($.client??this.client).get({url:"/team/join/{team_invite_id}",...$})}patchTeamMemberPlan($){return($.client??this.client).patch({url:"/team/members/{member_user_id}/plan",...$,headers:{"Content-Type":"application/json",...$.headers}})}toggleTeamNonAdminInvites($){return($?.client??this.client).post({url:"/team/non-admin-invites/toggle",...$})}removeUserFromTeam($){return($.client??this.client).delete({url:"/team/remove/{remove_user_id}",...$})}getUserTeams($){return($?.client??this.client).get({url:"/team/user",...$})}getUserInvites($){return($?.client??this.client).get({url:"/team/user/invites",...$})}getUserNames($){return($.client??this.client).post({url:"/user/get_names",...$,headers:{"Content-Type":"application/json",...$.headers}})}getUserNamesWithEmail($){return($.client??this.client).post({url:"/user/get_names_with_email",...$,headers:{"Content-Type":"application/json",...$.headers}})}patchUserGroup($){return($.client??this.client).patch({url:"/user/group",...$,headers:{"Content-Type":"application/json",...$.headers}})}getLegacyUserPermissions($){return($?.client??this.client).get({url:"/user/legacy_user_permissions",...$})}getUserLinkExists($){return($.client??this.client).get({url:"/user/link_exists",...$})}deleteUser($){return($?.client??this.client).delete({url:"/user/me",...$})}getUserInfo($){return($?.client??this.client).get({url:"/user/me",...$})}getUserName($){return($?.client??this.client).get({url:"/user/name",...$})}putUserName($){return($?.client??this.client).put({url:"/user/name",...$})}patchUserOnboarding($){return($.client??this.client).patch({url:"/user/onboarding",...$,headers:{"Content-Type":"application/json",...$.headers}})}getUserOrganization($){return($?.client??this.client).get({url:"/user/organization",...$})}putProfilePicture($){return($.client??this.client).put({url:"/user/profile_picture",...$})}postProfilePictures($){return($.client??this.client).post({url:"/user/profile_pictures",...$,headers:{"Content-Type":"application/json",...$.headers}})}getUserQuota($){return($?.client??this.client).get({url:"/user/quota",...$})}createCheckoutSessionV2($){return($.client??this.client).post({url:"/user/stripe/checkoutv2",...$,headers:{"Content-Type":"application/json",...$.headers}})}getSubscriptionStatus($){return($?.client??this.client).get({url:"/user/stripe/plan",...$})}changePlan($){return($.client??this.client).post({url:"/user/stripe/plan",...$,headers:{"Content-Type":"application/json",...$.headers}})}createPortalSession($){return($.client??this.client).post({url:"/user/stripe/portal",...$,headers:{"Content-Type":"application/json",...$.headers}})}getTrialEligibility($){return($?.client??this.client).get({url:"/user/stripe/trial_eligibility",...$})}patchUserTutorial($){return($.client??this.client).patch({url:"/user/tutorial",...$,headers:{"Content-Type":"application/json",...$.headers}})}}function z2({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...Q}){let J,I=Y??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,T=Q.signal??new AbortController().signal;while(!0){if(T.aborted)break;B++;let A=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)A.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:A,signal:T},_=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 H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",k=()=>{try{H.cancel()}catch{}};T.addEventListener("abort",k);try{while(!0){let{done:l,value:r}=await H.read();if(l)break;U+=r,U=U.replace(/\r\n?/g,`+`);try{C=JSON.parse(R),v=!0}catch{C=R}}if(v){if(S)await S(C);if(x)C=await x(C)}if(j?.({data:C,event:y,id:J,retry:V}),F.length)yield C}}}finally{T.removeEventListener("abort",k),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&W>=Z)break;let _=Math.min(V*2**(W-1),X??30000);await I(_)}}}()}}var C7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},M7=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},P7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},gj=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((Y)=>encodeURIComponent(Y))).join(M7(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=C7(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return AO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},AO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},yj=({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 Y=[];Object.entries(S).forEach(([Q,J])=>{Y=[...Y,Q,$?J:encodeURIComponent(J)]});let L=Y.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=P7(x),X=Object.entries(S).map(([Y,L])=>AO({allowReserved:$,name:x==="deepObject"?`${j}[${Y}]`:Y,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var A7=/\{[^{}]+\}/g,F7=({path:$,url:O})=>{let j=O,x=O.match(A7);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 Y=$[Z];if(Y===void 0||Y===null)continue;if(Array.isArray(Y)){j=j.replace(S,gj({explode:K,name:Z,style:X,value:Y}));continue}if(typeof Y==="object"){j=j.replace(S,yj({explode:K,name:Z,style:X,value:Y,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${AO({name:Z,value:Y})}`);continue}let L=encodeURIComponent(X==="label"?`.${Y}`:Y);j=j.replace(S,L)}return j},Q2=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=F7({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function u0($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var J2=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var V2={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var B2=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let Y=gj({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(Y)S.push(Y)}else if(typeof Z==="object"){let Y=yj({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(Y)S.push(Y)}else{let Y=AO({allowReserved:X.allowReserved,name:K,value:Z});if(Y)S.push(Y)}}return S.join("&")}},W2=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},E7=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function L2($){for(let O of $.security??[]){if(E7($,O.name))continue;let j=await J2(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var d0=($)=>Q2({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:B2($.querySerializer),url:$.url}),l0=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=hj($.headers,O.headers),j},w7=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},hj=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?w7(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 vj{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var N2=()=>({error:new vj,request:new vj,response:new vj}),q7=B2({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),f7={"Content-Type":"application/json"},jj=($={})=>({...V2,headers:f7,parseAs:"auto",querySerializer:q7,...$});var r0=($={})=>{let O=l0(jj(),$),j=()=>({...O}),x=(Q)=>{return O=l0(O,Q),j()},S=N2(),K=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:hj(O.headers,Q.headers),serializedBody:void 0};if(J.security)await L2(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let I=J,z=d0(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,B;try{let{opts:V,url:W}=await K(Q),T={redirect:"follow",...V,body:u0(V)};z=new Request(W,T);for(let N of S.request.fns)if(N)z=await N(z,V);let A=V.fetch;B=await A(z);for(let N of S.response.fns)if(N)B=await N(B,z,V);let D={request:z,response:B};if(B.ok){let N=(V.parseAs==="auto"?W2(B.headers.get("Content-Type")):V.parseAs)??"json";if(B.status===204||B.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await B[N]();break;case"formData":U=new FormData;break;case"stream":U=B.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await B[N]();break;case"json":{let U=await B.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?B.body:{data:B.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let _=await B.text(),q;try{q=JSON.parse(_)}catch{}throw q??_}catch(V){let W=V;for(let T of S.error.fns)if(T)W=await T(W,B,z,Q);if(W=W||{},J)throw W;return I==="data"?void 0:{error:W,request:z,response:B}}},X=(Q)=>(J)=>Z({...J,method:Q}),Y=(Q)=>async(J)=>{let{opts:I,url:z}=await K(J);return G2({...I,body:I.body,method:Q,onRequest:async(B,V)=>{let W=new Request(B,V);for(let T of S.request.fns)if(T)W=await T(W,I);return W},serializedBody:u0(I),url:z})};return{buildUrl:(Q)=>d0({...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:Y("CONNECT"),delete:Y("DELETE"),get:Y("GET"),head:Y("HEAD"),options:Y("OPTIONS"),patch:Y("PATCH"),post:Y("POST"),put:Y("PUT"),trace:Y("TRACE")},trace:X("TRACE")}};var U2=r0(jj());class z2{client;constructor($){this.client=$?.client??U2}}class I2{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class mj extends z2{static __registry=new I2;constructor($){super($);mj.__registry.set(this,$?.key)}deleteAgentApiKey($){return($.client??this.client).delete({url:"/agents/{agent_id}/api-key",...$})}getAgentApiKey($){return($.client??this.client).get({url:"/agents/{agent_id}/api-key",...$})}putAgentApiKey($){return($.client??this.client).put({url:"/agents/{agent_id}/api-key",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateAiBillingAutoReload($){return($.client??this.client).patch({url:"/ai-billing/auto-reload",...$,headers:{"Content-Type":"application/json",...$.headers}})}createAiCreditCheckout($){return($.client??this.client).post({url:"/ai-billing/credits/checkout",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateAiBillingOverage($){return($.client??this.client).patch({url:"/ai-billing/overage",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAiBillingPlans($){return($?.client??this.client).get({url:"/ai-billing/plans",...$})}getAiBillingSummary($){return($?.client??this.client).get({url:"/ai-billing/summary",...$})}disconnectCodex($){return($?.client??this.client).delete({url:"/codex",...$})}getCodexConnection($){return($?.client??this.client).get({url:"/codex",...$})}configureCodex($){return($.client??this.client).put({url:"/codex/config",...$,headers:{"Content-Type":"application/json",...$.headers}})}listCodexEnvironments($){return($?.client??this.client).get({url:"/codex/environments",...$})}startCodexLogin($){return($?.client??this.client).post({url:"/codex/login",...$})}cancelCodexLogin($){return($.client??this.client).delete({url:"/codex/login/{attempt_id}",...$})}pollCodexLogin($){return($.client??this.client).get({url:"/codex/login/{attempt_id}",...$})}deleteCursorApiKey($){return($?.client??this.client).delete({url:"/cursor-api-key",...$})}getCursorApiKey($){return($?.client??this.client).get({url:"/cursor-api-key",...$})}putCursorApiKey($){return($.client??this.client).put({url:"/cursor-api-key",...$,headers:{"Content-Type":"application/json",...$.headers}})}putCursorDefaultModel($){return($.client??this.client).put({url:"/cursor-api-key/default-model",...$,headers:{"Content-Type":"application/json",...$.headers}})}listCursorModels($){return($?.client??this.client).get({url:"/cursor-api-key/models",...$})}verifyFusionauthUserEmail($){return($.client??this.client).get({url:"/email/fusionauth/verify/{verification_id}",...$})}resendFusionauthVerifyUserEmail($){return($.client??this.client).post({url:"/email/fusionauth_resend",...$,headers:{"Content-Type":"application/json",...$.headers}})}generateEmailLink($){return($.client??this.client).post({url:"/email/generate/link",...$,headers:{"Content-Type":"application/json",...$.headers}})}verifyEmailLink($){return($.client??this.client).get({url:"/email/verify/{verification_id}",...$})}setGithubPullRequestDraft($){return($.client??this.client).post({url:"/github_pull_requests/draft",...$,headers:{"Content-Type":"application/json",...$.headers}})}enrichGithubPullRequests($){return($.client??this.client).post({url:"/github_pull_requests/enrich",...$,headers:{"Content-Type":"application/json",...$.headers}})}mergeGithubPullRequest($){return($.client??this.client).post({url:"/github_pull_requests/merge",...$,headers:{"Content-Type":"application/json",...$.headers}})}getGithubPullRequestMergeability($){return($.client??this.client).post({url:"/github_pull_requests/mergeability",...$,headers:{"Content-Type":"application/json",...$.headers}})}listGtmInviteLinks($){return($?.client??this.client).get({url:"/gtm-invite/links",...$})}createGtmInviteLink($){return($.client??this.client).post({url:"/gtm-invite/links",...$,headers:{"Content-Type":"application/json",...$.headers}})}revokeGtmInviteLink($){return($.client??this.client).delete({url:"/gtm-invite/links/{id}",...$})}getGtmInviteOffer($){return($?.client??this.client).get({url:"/gtm-invite/offer",...$})}resolveGtmInviteLink($){return($.client??this.client).get({url:"/gtm-invite/public/{token}",...$})}redeemGtmInviteLink($){return($.client??this.client).post({url:"/gtm-invite/redeem",...$,headers:{"Content-Type":"application/json",...$.headers}})}healthHandler($){return($?.client??this.client).get({url:"/health",...$})}macroApiToken($){return($.client??this.client).get({url:"/jwt/macro_api_token",...$})}refresh($){return($?.client??this.client).post({url:"/jwt/refresh",...$})}createInProgressLink($){return($?.client??this.client).post({url:"/link",...$})}emailConnectionProviders($){return($?.client??this.client).get({url:"/link/email/providers",...$})}deleteGithubLink($){return($?.client??this.client).delete({url:"/link/github",...$})}initGithubLink($){return($.client??this.client).post({url:"/link/github",...$})}checkGithubLinkStatus($){return($?.client??this.client).get({url:"/link/github/status",...$})}initGmailLink($){return($.client??this.client).post({url:"/link/gmail",...$})}checkGmailLinkStatus($){return($?.client??this.client).get({url:"/link/gmail/status",...$})}initOutlookLink($){return($?.client??this.client).post({url:"/link/outlook",...$})}appleLogin($){return($.client??this.client).post({url:"/login/apple",...$,headers:{"Content-Type":"application/json",...$.headers}})}passwordLogin($){return($.client??this.client).post({url:"/login/password",...$,headers:{"Content-Type":"application/json",...$.headers}})}passwordlessLogin($){return($.client??this.client).post({url:"/login/passwordless",...$,headers:{"Content-Type":"application/json",...$.headers}})}ssoLogin($){return($.client??this.client).get({url:"/login/sso",...$})}logout($){return($?.client??this.client).post({url:"/logout",...$})}createMergeRequest($){return($.client??this.client).post({url:"/merge",...$,headers:{"Content-Type":"application/json",...$.headers}})}verifyMergeRequest($){return($.client??this.client).get({url:"/merge/verify/{code}",...$})}sendMobileWelcomeEmail($){return($.client??this.client).post({url:"/mobile-welcome-email",...$,headers:{"Content-Type":"application/json",...$.headers}})}passwordlessCallback($){return($.client??this.client).get({url:"/oauth/passwordless/{code}",...$})}oauthRedirect($){return($?.client??this.client).get({url:"/oauth/redirect",...$})}oauth2Callback($){return($.client??this.client).get({url:"/oauth2/{provider}/callback",...$})}getPermissions($){return($?.client??this.client).get({url:"/permissions",...$})}getUserPermissions($){return($?.client??this.client).get({url:"/permissions/me",...$})}getReferralCode($){return($?.client??this.client).get({url:"/referral/code",...$})}sendReferralCode($){return($.client??this.client).post({url:"/referral/send",...$,headers:{"Content-Type":"application/json",...$.headers}})}sessionCreation($){return($?.client??this.client).post({url:"/session",...$})}sessionLogin($){return($.client??this.client).get({url:"/session/login/{session_code}",...$})}deleteTeam($){return($?.client??this.client).delete({url:"/team",...$})}getTeam($){return($?.client??this.client).get({url:"/team",...$})}patchTeam($){return($.client??this.client).patch({url:"/team",...$,headers:{"Content-Type":"application/json",...$.headers}})}createTeam($){return($.client??this.client).post({url:"/team",...$,headers:{"Content-Type":"application/json",...$.headers}})}toggleTeamAutoJoinDomain($){return($?.client??this.client).post({url:"/team/auto-join-domain/toggle",...$})}patchTeamCrmSettings($){return($.client??this.client).patch({url:"/team/crm",...$,headers:{"Content-Type":"application/json",...$.headers}})}inviteToTeam($){return($.client??this.client).post({url:"/team/invite",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteTeamInviteLink($){return($?.client??this.client).delete({url:"/team/invite-link",...$})}getTeamInviteLink($){return($?.client??this.client).get({url:"/team/invite-link",...$})}createTeamInviteLink($){return($?.client??this.client).post({url:"/team/invite-link",...$})}joinTeamByInviteLink($){return($.client??this.client).post({url:"/team/invite-link/join",...$,headers:{"Content-Type":"application/json",...$.headers}})}getTeamByInviteLink($){return($.client??this.client).post({url:"/team/invite-link/team",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteTeamInviteHandler($){return($.client??this.client).delete({url:"/team/invite/{team_invite_id}",...$})}getTeamInvites($){return($?.client??this.client).get({url:"/team/invites",...$})}rejectInvitation($){return($.client??this.client).delete({url:"/team/join/{team_invite_id}",...$})}joinTeam($){return($.client??this.client).get({url:"/team/join/{team_invite_id}",...$})}patchTeamMemberPlan($){return($.client??this.client).patch({url:"/team/members/{member_user_id}/plan",...$,headers:{"Content-Type":"application/json",...$.headers}})}toggleTeamNonAdminInvites($){return($?.client??this.client).post({url:"/team/non-admin-invites/toggle",...$})}removeUserFromTeam($){return($.client??this.client).delete({url:"/team/remove/{remove_user_id}",...$})}getUserTeams($){return($?.client??this.client).get({url:"/team/user",...$})}getUserInvites($){return($?.client??this.client).get({url:"/team/user/invites",...$})}getUserNames($){return($.client??this.client).post({url:"/user/get_names",...$,headers:{"Content-Type":"application/json",...$.headers}})}getUserNamesWithEmail($){return($.client??this.client).post({url:"/user/get_names_with_email",...$,headers:{"Content-Type":"application/json",...$.headers}})}patchUserGroup($){return($.client??this.client).patch({url:"/user/group",...$,headers:{"Content-Type":"application/json",...$.headers}})}getLegacyUserPermissions($){return($?.client??this.client).get({url:"/user/legacy_user_permissions",...$})}getUserLinkExists($){return($.client??this.client).get({url:"/user/link_exists",...$})}deleteUser($){return($?.client??this.client).delete({url:"/user/me",...$})}getUserInfo($){return($?.client??this.client).get({url:"/user/me",...$})}getUserName($){return($?.client??this.client).get({url:"/user/name",...$})}putUserName($){return($?.client??this.client).put({url:"/user/name",...$})}patchUserOnboarding($){return($.client??this.client).patch({url:"/user/onboarding",...$,headers:{"Content-Type":"application/json",...$.headers}})}getUserOrganization($){return($?.client??this.client).get({url:"/user/organization",...$})}putProfilePicture($){return($.client??this.client).put({url:"/user/profile_picture",...$})}postProfilePictures($){return($.client??this.client).post({url:"/user/profile_pictures",...$,headers:{"Content-Type":"application/json",...$.headers}})}getUserQuota($){return($?.client??this.client).get({url:"/user/quota",...$})}createCheckoutSessionV2($){return($.client??this.client).post({url:"/user/stripe/checkoutv2",...$,headers:{"Content-Type":"application/json",...$.headers}})}getSubscriptionStatus($){return($?.client??this.client).get({url:"/user/stripe/plan",...$})}changePlan($){return($.client??this.client).post({url:"/user/stripe/plan",...$,headers:{"Content-Type":"application/json",...$.headers}})}createPortalSession($){return($.client??this.client).post({url:"/user/stripe/portal",...$,headers:{"Content-Type":"application/json",...$.headers}})}getTrialEligibility($){return($?.client??this.client).get({url:"/user/stripe/trial_eligibility",...$})}patchUserTutorial($){return($.client??this.client).patch({url:"/user/tutorial",...$,headers:{"Content-Type":"application/json",...$.headers}})}}function T2({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...Q}){let J,I=Y??((V)=>new Promise((W)=>setTimeout(W,V)));return{stream:async function*(){let V=K??3000,W=0,T=Q.signal??new AbortController().signal;while(!0){if(T.aborted)break;W++;let A=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)A.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:A,signal:T},_=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 H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",k=()=>{try{H.cancel()}catch{}};T.addEventListener("abort",k);try{while(!0){let{done:l,value:r}=await H.read();if(l)break;U+=r,U=U.replace(/\r\n?/g,``);let g=U.split(``);U=g.pop()??"";for(let p of g){let a=p.split(``),F=[],y;for(let R of a)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))y=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let h=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(h))V=h}let C,v=!1;if(F.length){let R=F.join(`-`);try{C=JSON.parse(R),v=!0}catch{C=R}}if(v){if(S)await S(C);if(x)C=await x(C)}if(j?.({data:C,event:y,id:J,retry:V}),F.length)yield C}}}finally{T.removeEventListener("abort",k),H.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 q7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},f7=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},b7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},mj=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((Y)=>encodeURIComponent(Y))).join(f7(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=q7(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return AO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},AO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},cj=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let Y=[];Object.entries(S).forEach(([Q,J])=>{Y=[...Y,Q,$?J:encodeURIComponent(J)]});let L=Y.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=b7(x),X=Object.entries(S).map(([Y,L])=>AO({allowReserved:$,name:x==="deepObject"?`${j}[${Y}]`:Y,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var k7=/\{[^{}]+\}/g,g7=({path:$,url:O})=>{let j=O,x=O.match(k7);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 Y=$[Z];if(Y===void 0||Y===null)continue;if(Array.isArray(Y)){j=j.replace(S,mj({explode:K,name:Z,style:X,value:Y}));continue}if(typeof Y==="object"){j=j.replace(S,cj({explode:K,name:Z,style:X,value:Y,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${AO({name:Z,value:Y})}`);continue}let L=encodeURIComponent(X==="label"?`.${Y}`:Y);j=j.replace(S,L)}return j},I2=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=g7({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function l0($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var T2=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 H2={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var R2=({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 Y=mj({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(Y)S.push(Y)}else if(typeof Z==="object"){let Y=cj({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(Y)S.push(Y)}else{let Y=AO({allowReserved:X.allowReserved,name:K,value:Z});if(Y)S.push(Y)}}return S.join("&")}},D2=($)=>{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},y7=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function _2($){for(let O of $.security??[]){if(y7($,O.name))continue;let j=await T2(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var r0=($)=>I2({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:R2($.querySerializer),url:$.url}),p0=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=dj($.headers,O.headers),j},v7=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},dj=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?v7(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 uj{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 C2=()=>({error:new uj,request:new uj,response:new uj}),h7=R2({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),m7={"Content-Type":"application/json"},jj=($={})=>({...H2,headers:m7,parseAs:"auto",querySerializer:h7,...$});var a0=($={})=>{let O=p0(jj(),$),j=()=>({...O}),x=(Q)=>{return O=p0(O,Q),j()},S=C2(),K=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:dj(O.headers,Q.headers),serializedBody:void 0};if(J.security)await _2(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=r0(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),T={redirect:"follow",...V,body:l0(V)};z=new Request(B,T);for(let N of S.request.fns)if(N)z=await N(z,V);let A=V.fetch;W=await A(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"?D2(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await W[N]();break;case"json":{let U=await W.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let _=await W.text(),q;try{q=JSON.parse(_)}catch{}throw q??_}catch(V){let B=V;for(let T of S.error.fns)if(T)B=await T(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}),Y=(Q)=>async(J)=>{let{opts:I,url:z}=await K(J);return z2({...I,body:I.body,method:Q,onRequest:async(W,V)=>{let B=new Request(W,V);for(let T of S.request.fns)if(T)B=await T(B,I);return B},serializedBody:l0(I),url:z})};return{buildUrl:(Q)=>r0({...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:Y("CONNECT"),delete:Y("DELETE"),get:Y("GET"),head:Y("HEAD"),options:Y("OPTIONS"),patch:Y("PATCH"),post:Y("POST"),put:Y("PUT"),trace:Y("TRACE")},trace:X("TRACE")}};var P2=a0(jj());class M2{client;constructor($){this.client=$?.client??P2}}class A2{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 lj extends M2{static __registry=new A2;constructor($){super($);lj.__registry.set(this,$?.key)}getAvailabilityCalendars($){return($?.client??this.client).get({url:"/availability-calendars",...$})}setAvailabilityCalendar($){return($.client??this.client).put({url:"/availability-calendars/{calendar_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}listCalendars($){return($?.client??this.client).get({url:"/calendars",...$})}createCalendarEvent($){return($.client??this.client).post({url:"/events",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteCalendarEvent($){return($.client??this.client).delete({url:"/events/{event_id}",...$})}updateCalendarEvent($){return($.client??this.client).patch({url:"/events/{event_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}copyCalendarEvent($){return($.client??this.client).post({url:"/events/{event_id}/copy",...$,headers:{"Content-Type":"application/json",...$.headers}})}inviteCalendarEventGuests($){return($.client??this.client).post({url:"/events/{event_id}/guests",...$,headers:{"Content-Type":"application/json",...$.headers}})}eventNotes($){return($.client??this.client).get({url:"/events/{event_id}/notes",...$})}unlinkEventNote($){return($.client??this.client).delete({url:"/events/{event_id}/notes/{document_id}",...$})}linkEventNote($){return($.client??this.client).put({url:"/events/{event_id}/notes/{document_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}calendarEventProviderUrl($){return($.client??this.client).get({url:"/events/{event_id}/provider-url",...$})}prepareCalendarReplacement($){return($.client??this.client).post({url:"/events/{event_id}/replacement",...$,headers:{"Content-Type":"application/json",...$.headers}})}rsvpCalendarEvent($){return($.client??this.client).put({url:"/events/{event_id}/rsvp",...$,headers:{"Content-Type":"application/json",...$.headers}})}healthHandler($){return($?.client??this.client).get({url:"/health",...$})}respondToJoinRequest($){return($.client??this.client).put({url:"/join-requests/{request_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}noteDocuments($){return($?.client??this.client).get({url:"/meeting-notes/documents",...$})}documentNoteLinks($){return($.client??this.client).get({url:"/meeting-notes/documents/{document_id}/links",...$})}discardCalendarReplacement($){return($.client??this.client).delete({url:"/replacements/{operation_id}",...$})}calendarReplacementStatus($){return($.client??this.client).get({url:"/replacements/{operation_id}",...$})}confirmCalendarReplacement($){return($.client??this.client).post({url:"/replacements/{operation_id}/confirm",...$})}getTeamSharing($){return($?.client??this.client).get({url:"/team-sharing",...$})}setTeamSharing($){return($.client??this.client).put({url:"/team-sharing",...$,headers:{"Content-Type":"application/json",...$.headers}})}}function F2({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...Q}){let J,I=Y??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,T=Q.signal??new AbortController().signal;while(!0){if(T.aborted)break;B++;let A=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)A.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:A,signal:T},_=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 H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",k=()=>{try{H.cancel()}catch{}};T.addEventListener("abort",k);try{while(!0){let{done:l,value:r}=await H.read();if(l)break;U+=r,U=U.replace(/\r\n?/g,`+`);try{C=JSON.parse(R),v=!0}catch{C=R}}if(v){if(S)await S(C);if(x)C=await x(C)}if(j?.({data:C,event:y,id:J,retry:V}),F.length)yield C}}}finally{T.removeEventListener("abort",k),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&W>=Z)break;let _=Math.min(V*2**(W-1),X??30000);await I(_)}}}()}}var b7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},k7=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},g7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},cj=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((Y)=>encodeURIComponent(Y))).join(k7(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=b7(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return FO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},FO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},uj=({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 Y=[];Object.entries(S).forEach(([Q,J])=>{Y=[...Y,Q,$?J:encodeURIComponent(J)]});let L=Y.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=g7(x),X=Object.entries(S).map(([Y,L])=>FO({allowReserved:$,name:x==="deepObject"?`${j}[${Y}]`:Y,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var y7=/\{[^{}]+\}/g,v7=({path:$,url:O})=>{let j=O,x=O.match(y7);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 Y=$[Z];if(Y===void 0||Y===null)continue;if(Array.isArray(Y)){j=j.replace(S,cj({explode:K,name:Z,style:X,value:Y}));continue}if(typeof Y==="object"){j=j.replace(S,uj({explode:K,name:Z,style:X,value:Y,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${FO({name:Z,value:Y})}`);continue}let L=encodeURIComponent(X==="label"?`.${Y}`:Y);j=j.replace(S,L)}return j},H2=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=v7({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function p0($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var R2=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var D2={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var _2=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let Y=cj({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(Y)S.push(Y)}else if(typeof Z==="object"){let Y=uj({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(Y)S.push(Y)}else{let Y=FO({allowReserved:X.allowReserved,name:K,value:Z});if(Y)S.push(Y)}}return S.join("&")}},C2=($)=>{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},h7=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function M2($){for(let O of $.security??[]){if(h7($,O.name))continue;let j=await R2(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var a0=($)=>H2({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:_2($.querySerializer),url:$.url}),i0=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=lj($.headers,O.headers),j},m7=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},lj=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?m7(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 dj{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var P2=()=>({error:new dj,request:new dj,response:new dj}),c7=_2({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),u7={"Content-Type":"application/json"},xj=($={})=>({...D2,headers:u7,parseAs:"auto",querySerializer:c7,...$});var n0=($={})=>{let O=i0(xj(),$),j=()=>({...O}),x=(Q)=>{return O=i0(O,Q),j()},S=P2(),K=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:lj(O.headers,Q.headers),serializedBody:void 0};if(J.security)await M2(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let I=J,z=a0(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,B;try{let{opts:V,url:W}=await K(Q),T={redirect:"follow",...V,body:p0(V)};z=new Request(W,T);for(let N of S.request.fns)if(N)z=await N(z,V);let A=V.fetch;B=await A(z);for(let N of S.response.fns)if(N)B=await N(B,z,V);let D={request:z,response:B};if(B.ok){let N=(V.parseAs==="auto"?C2(B.headers.get("Content-Type")):V.parseAs)??"json";if(B.status===204||B.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await B[N]();break;case"formData":U=new FormData;break;case"stream":U=B.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await B[N]();break;case"json":{let U=await B.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?B.body:{data:B.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let _=await B.text(),q;try{q=JSON.parse(_)}catch{}throw q??_}catch(V){let W=V;for(let T of S.error.fns)if(T)W=await T(W,B,z,Q);if(W=W||{},J)throw W;return I==="data"?void 0:{error:W,request:z,response:B}}},X=(Q)=>(J)=>Z({...J,method:Q}),Y=(Q)=>async(J)=>{let{opts:I,url:z}=await K(J);return T2({...I,body:I.body,method:Q,onRequest:async(B,V)=>{let W=new Request(B,V);for(let T of S.request.fns)if(T)W=await T(W,I);return W},serializedBody:p0(I),url:z})};return{buildUrl:(Q)=>a0({...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:Y("CONNECT"),delete:Y("DELETE"),get:Y("GET"),head:Y("HEAD"),options:Y("OPTIONS"),patch:Y("PATCH"),post:Y("POST"),put:Y("PUT"),trace:Y("TRACE")},trace:X("TRACE")}};var A2=n0(xj());class F2{client;constructor($){this.client=$?.client??A2}}class E2{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class rj extends F2{static __registry=new E2;constructor($){super($);rj.__registry.set(this,$?.key)}getAvailabilityCalendars($){return($?.client??this.client).get({url:"/availability-calendars",...$})}setAvailabilityCalendar($){return($.client??this.client).put({url:"/availability-calendars/{calendar_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}listCalendars($){return($?.client??this.client).get({url:"/calendars",...$})}createCalendarEvent($){return($.client??this.client).post({url:"/events",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteCalendarEvent($){return($.client??this.client).delete({url:"/events/{event_id}",...$})}updateCalendarEvent($){return($.client??this.client).patch({url:"/events/{event_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}copyCalendarEvent($){return($.client??this.client).post({url:"/events/{event_id}/copy",...$,headers:{"Content-Type":"application/json",...$.headers}})}inviteCalendarEventGuests($){return($.client??this.client).post({url:"/events/{event_id}/guests",...$,headers:{"Content-Type":"application/json",...$.headers}})}eventNotes($){return($.client??this.client).get({url:"/events/{event_id}/notes",...$})}unlinkEventNote($){return($.client??this.client).delete({url:"/events/{event_id}/notes/{document_id}",...$})}linkEventNote($){return($.client??this.client).put({url:"/events/{event_id}/notes/{document_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}calendarEventProviderUrl($){return($.client??this.client).get({url:"/events/{event_id}/provider-url",...$})}prepareCalendarReplacement($){return($.client??this.client).post({url:"/events/{event_id}/replacement",...$,headers:{"Content-Type":"application/json",...$.headers}})}rsvpCalendarEvent($){return($.client??this.client).put({url:"/events/{event_id}/rsvp",...$,headers:{"Content-Type":"application/json",...$.headers}})}healthHandler($){return($?.client??this.client).get({url:"/health",...$})}respondToJoinRequest($){return($.client??this.client).put({url:"/join-requests/{request_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}noteDocuments($){return($?.client??this.client).get({url:"/meeting-notes/documents",...$})}documentNoteLinks($){return($.client??this.client).get({url:"/meeting-notes/documents/{document_id}/links",...$})}discardCalendarReplacement($){return($.client??this.client).delete({url:"/replacements/{operation_id}",...$})}calendarReplacementStatus($){return($.client??this.client).get({url:"/replacements/{operation_id}",...$})}confirmCalendarReplacement($){return($.client??this.client).post({url:"/replacements/{operation_id}/confirm",...$})}getTeamSharing($){return($?.client??this.client).get({url:"/team-sharing",...$})}setTeamSharing($){return($.client??this.client).put({url:"/team-sharing",...$,headers:{"Content-Type":"application/json",...$.headers}})}}function w2({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...Q}){let J,I=Y??((V)=>new Promise((W)=>setTimeout(W,V)));return{stream:async function*(){let V=K??3000,W=0,T=Q.signal??new AbortController().signal;while(!0){if(T.aborted)break;W++;let A=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)A.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:A,signal:T},_=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 H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",k=()=>{try{H.cancel()}catch{}};T.addEventListener("abort",k);try{while(!0){let{done:l,value:r}=await H.read();if(l)break;U+=r,U=U.replace(/\r\n?/g,``);let g=U.split(``);U=g.pop()??"";for(let p of g){let a=p.split(``),F=[],y;for(let R of a)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))y=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let h=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(h))V=h}let C,v=!1;if(F.length){let R=F.join(`-`);try{C=JSON.parse(R),v=!0}catch{C=R}}if(v){if(S)await S(C);if(x)C=await x(C)}if(j?.({data:C,event:y,id:J,retry:V}),F.length)yield C}}}finally{T.removeEventListener("abort",k),H.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 c7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},u7=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},d7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},rj=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((Y)=>encodeURIComponent(Y))).join(u7(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=c7(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return FO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},FO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},pj=({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 Y=[];Object.entries(S).forEach(([Q,J])=>{Y=[...Y,Q,$?J:encodeURIComponent(J)]});let L=Y.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=d7(x),X=Object.entries(S).map(([Y,L])=>FO({allowReserved:$,name:x==="deepObject"?`${j}[${Y}]`:Y,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var l7=/\{[^{}]+\}/g,r7=({path:$,url:O})=>{let j=O,x=O.match(l7);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 Y=$[Z];if(Y===void 0||Y===null)continue;if(Array.isArray(Y)){j=j.replace(S,rj({explode:K,name:Z,style:X,value:Y}));continue}if(typeof Y==="object"){j=j.replace(S,pj({explode:K,name:Z,style:X,value:Y,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${FO({name:Z,value:Y})}`);continue}let L=encodeURIComponent(X==="label"?`.${Y}`:Y);j=j.replace(S,L)}return j},E2=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=r7({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function i0($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var w2=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 q2={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var f2=({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 Y=rj({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(Y)S.push(Y)}else if(typeof Z==="object"){let Y=pj({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(Y)S.push(Y)}else{let Y=FO({allowReserved:X.allowReserved,name:K,value:Z});if(Y)S.push(Y)}}return S.join("&")}},b2=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},p7=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function k2($){for(let O of $.security??[]){if(p7($,O.name))continue;let j=await w2(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var n0=($)=>E2({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:f2($.querySerializer),url:$.url}),s0=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=ij($.headers,O.headers),j},a7=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},ij=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?a7(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class aj{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var g2=()=>({error:new aj,request:new aj,response:new aj}),i7=f2({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),n7={"Content-Type":"application/json"},xj=($={})=>({...q2,headers:n7,parseAs:"auto",querySerializer:i7,...$});var t0=($={})=>{let O=s0(xj(),$),j=()=>({...O}),x=(Q)=>{return O=s0(O,Q),j()},S=g2(),K=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:ij(O.headers,Q.headers),serializedBody:void 0};if(J.security)await k2(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=n0(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),T={redirect:"follow",...V,body:i0(V)};z=new Request(B,T);for(let N of S.request.fns)if(N)z=await N(z,V);let A=V.fetch;W=await A(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?b2(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await W[N]();break;case"json":{let U=await W.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let _=await W.text(),q;try{q=JSON.parse(_)}catch{}throw q??_}catch(V){let B=V;for(let T of S.error.fns)if(T)B=await T(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}),Y=(Q)=>async(J)=>{let{opts:I,url:z}=await K(J);return F2({...I,body:I.body,method:Q,onRequest:async(W,V)=>{let B=new Request(W,V);for(let T of S.request.fns)if(T)B=await T(B,I);return B},serializedBody:i0(I),url:z})};return{buildUrl:(Q)=>n0({...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:Y("CONNECT"),delete:Y("DELETE"),get:Y("GET"),head:Y("HEAD"),options:Y("OPTIONS"),patch:Y("PATCH"),post:Y("POST"),put:Y("PUT"),trace:Y("TRACE")},trace:X("TRACE")}};var y2=t0(xj());class v2{client;constructor($){this.client=$?.client??y2}}class h2{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 nj extends v2{static __registry=new h2;constructor($){super($);nj.__registry.set(this,$?.key)}setPricingHandler($){return($.client??this.client).post({url:"/ai-cost/pricing",...$,headers:{"Content-Type":"application/json",...$.headers}})}getUsageHandler($){return($.client??this.client).post({url:"/ai-cost/usage",...$,headers:{"Content-Type":"application/json",...$.headers}})}upsertAiProjection($){return($.client??this.client).post({url:"/ai-projections",...$,headers:{"Content-Type":"application/json",...$.headers}})}getChatsForAttachmentHandler($){return($.client??this.client).get({url:"/attachments/{attachment_id}/chats",...$})}deleteChat($){return($.client??this.client).delete({url:"/chat/{chat_id}",...$})}patchChat($){return($.client??this.client).patch({url:"/chat/{chat_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}permanentlyDeleteChat($){return($.client??this.client).delete({url:"/chat/{chat_id}/permanent",...$})}createChat($){return($.client??this.client).post({url:"/chats",...$,headers:{"Content-Type":"application/json",...$.headers}})}getChatHistoryHandler($){return($.client??this.client).get({url:"/chats/history/{chat_id}",...$})}getChatHistoryBatchMessagesHandler($){return($.client??this.client).post({url:"/chats/history_batch_messages",...$,headers:{"Content-Type":"application/json",...$.headers}})}getChat($){return($.client??this.client).get({url:"/chats/{chat_id}",...$})}copyChat($){return($.client??this.client).post({url:"/chats/{chat_id}/copy",...$})}getChatPermissions($){return($.client??this.client).get({url:"/chats/{chat_id}/permissions",...$})}revertDeleteChat($){return($.client??this.client).put({url:"/chats/{chat_id}/revert_delete",...$})}callTool($){return($.client??this.client).post({url:"/chats/{chat_id}/tool/call",...$,headers:{"Content-Type":"application/json",...$.headers}})}rejectToolCall($){return($.client??this.client).post({url:"/chats/{chat_id}/tool/reject",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateToolResponse($){return($.client??this.client).post({url:"/chats/{chat_id}/tool/response/update",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateToolCall($){return($.client??this.client).post({url:"/chats/{chat_id}/tool/update",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCitationHandler($){return($.client??this.client).get({url:"/citations/{id}",...$})}decisions($){return($.client??this.client).post({url:"/decisions",...$,headers:{"Content-Type":"application/json",...$.headers}})}healthHandler($){return($?.client??this.client).get({url:"/health",...$})}notionReportHandler($){return($?.client??this.client).get({url:"/import/notion",...$})}cancelNotionHandler($){return($?.client??this.client).post({url:"/import/notion/cancel",...$})}runImportHandler($){return($.client??this.client).post({url:"/import/run",...$,headers:{"Content-Type":"application/json",...$.headers}})}discoverHandler($){return($.client??this.client).post({url:"/import/runs/{source}/discover",...$})}getStateHandler($){return($?.client??this.client).get({url:"/import/state",...$})}workspaceReportHandler($){return($.client??this.client).get({url:"/import/workspaces/{source}",...$})}cancelWorkspaceHandler($){return($.client??this.client).post({url:"/import/workspaces/{source}/cancel",...$})}deleteMcpServer($){return($.client??this.client).delete({url:"/mcp/servers",...$})}listMcpServers($){return($?.client??this.client).get({url:"/mcp/servers",...$})}addMcpServer($){return($.client??this.client).post({url:"/mcp/servers",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateMcpServer($){return($.client??this.client).put({url:"/mcp/servers",...$,headers:{"Content-Type":"application/json",...$.headers}})}mcpAuthCallback($){return($?.client??this.client).get({url:"/mcp/servers/auth/callback",...$})}mcpOauthClientMetadata($){return($?.client??this.client).get({url:"/mcp/servers/auth/client-metadata",...$})}startMcpAuth($){return($.client??this.client).post({url:"/mcp/servers/auth/start",...$,headers:{"Content-Type":"application/json",...$.headers}})}getMemoryHandler($){return($?.client??this.client).get({url:"/memory",...$})}getStateHandler2($){return($?.client??this.client).get({url:"/onboarding",...$})}completeHandler($){return($.client??this.client).post({url:"/onboarding/complete",...$,headers:{"Content-Type":"application/json",...$.headers}})}dismissedPromptsHandler($){return($?.client??this.client).get({url:"/onboarding/prompts",...$})}dismissPromptHandler($){return($.client??this.client).post({url:"/onboarding/prompts/{prompt_id}/dismiss",...$})}browsePipedreamMcpCatalog($){return($?.client??this.client).get({url:"/pipedream/mcp/catalog",...$})}completePipedreamMcpConnection($){return($.client??this.client).post({url:"/pipedream/mcp/complete",...$,headers:{"Content-Type":"application/json",...$.headers}})}deletePipedreamMcpConnection($){return($.client??this.client).delete({url:"/pipedream/mcp/connections",...$})}listPipedreamMcpConnections($){return($?.client??this.client).get({url:"/pipedream/mcp/connections",...$})}updatePipedreamMcpConnection($){return($.client??this.client).put({url:"/pipedream/mcp/connections",...$,headers:{"Content-Type":"application/json",...$.headers}})}createPipedreamMcpToken($){return($?.client??this.client).post({url:"/pipedream/mcp/token",...$})}getBatchPreview($){return($.client??this.client).post({url:"/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}sendChatMessage($){return($.client??this.client).post({url:"/stream/chat/message",...$,headers:{"Content-Type":"application/json",...$.headers}})}stopChatStream($){return($.client??this.client).post({url:"/stream/chat/message/stop",...$,headers:{"Content-Type":"application/json",...$.headers}})}structuredCompletion($){return($.client??this.client).post({url:"/structured-completion",...$,headers:{"Content-Type":"application/json",...$.headers}})}}function m2({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...Q}){let J,I=Y??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,T=Q.signal??new AbortController().signal;while(!0){if(T.aborted)break;B++;let A=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)A.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:A,signal:T},_=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 H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",k=()=>{try{H.cancel()}catch{}};T.addEventListener("abort",k);try{while(!0){let{done:l,value:r}=await H.read();if(l)break;U+=r,U=U.replace(/\r\n?/g,`+`);try{C=JSON.parse(R),v=!0}catch{C=R}}if(v){if(S)await S(C);if(x)C=await x(C)}if(j?.({data:C,event:y,id:J,retry:V}),F.length)yield C}}}finally{T.removeEventListener("abort",k),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&W>=Z)break;let _=Math.min(V*2**(W-1),X??30000);await I(_)}}}()}}var d7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},l7=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},r7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},pj=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((Y)=>encodeURIComponent(Y))).join(l7(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=d7(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return EO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},EO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},aj=({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 Y=[];Object.entries(S).forEach(([Q,J])=>{Y=[...Y,Q,$?J:encodeURIComponent(J)]});let L=Y.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=r7(x),X=Object.entries(S).map(([Y,L])=>EO({allowReserved:$,name:x==="deepObject"?`${j}[${Y}]`:Y,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var p7=/\{[^{}]+\}/g,a7=({path:$,url:O})=>{let j=O,x=O.match(p7);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 Y=$[Z];if(Y===void 0||Y===null)continue;if(Array.isArray(Y)){j=j.replace(S,pj({explode:K,name:Z,style:X,value:Y}));continue}if(typeof Y==="object"){j=j.replace(S,aj({explode:K,name:Z,style:X,value:Y,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${EO({name:Z,value:Y})}`);continue}let L=encodeURIComponent(X==="label"?`.${Y}`:Y);j=j.replace(S,L)}return j},q2=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=a7({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function s0($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var f2=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var b2={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var k2=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let Y=pj({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(Y)S.push(Y)}else if(typeof Z==="object"){let Y=aj({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(Y)S.push(Y)}else{let Y=EO({allowReserved:X.allowReserved,name:K,value:Z});if(Y)S.push(Y)}}return S.join("&")}},g2=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},i7=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function y2($){for(let O of $.security??[]){if(i7($,O.name))continue;let j=await f2(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var t0=($)=>q2({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:k2($.querySerializer),url:$.url}),e0=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=nj($.headers,O.headers),j},n7=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},nj=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?n7(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class ij{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var v2=()=>({error:new ij,request:new ij,response:new ij}),s7=k2({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),t7={"Content-Type":"application/json"},Sj=($={})=>({...b2,headers:t7,parseAs:"auto",querySerializer:s7,...$});var o0=($={})=>{let O=e0(Sj(),$),j=()=>({...O}),x=(Q)=>{return O=e0(O,Q),j()},S=v2(),K=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:nj(O.headers,Q.headers),serializedBody:void 0};if(J.security)await y2(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let I=J,z=t0(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,B;try{let{opts:V,url:W}=await K(Q),T={redirect:"follow",...V,body:s0(V)};z=new Request(W,T);for(let N of S.request.fns)if(N)z=await N(z,V);let A=V.fetch;B=await A(z);for(let N of S.response.fns)if(N)B=await N(B,z,V);let D={request:z,response:B};if(B.ok){let N=(V.parseAs==="auto"?g2(B.headers.get("Content-Type")):V.parseAs)??"json";if(B.status===204||B.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await B[N]();break;case"formData":U=new FormData;break;case"stream":U=B.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await B[N]();break;case"json":{let U=await B.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?B.body:{data:B.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let _=await B.text(),q;try{q=JSON.parse(_)}catch{}throw q??_}catch(V){let W=V;for(let T of S.error.fns)if(T)W=await T(W,B,z,Q);if(W=W||{},J)throw W;return I==="data"?void 0:{error:W,request:z,response:B}}},X=(Q)=>(J)=>Z({...J,method:Q}),Y=(Q)=>async(J)=>{let{opts:I,url:z}=await K(J);return w2({...I,body:I.body,method:Q,onRequest:async(B,V)=>{let W=new Request(B,V);for(let T of S.request.fns)if(T)W=await T(W,I);return W},serializedBody:s0(I),url:z})};return{buildUrl:(Q)=>t0({...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:Y("CONNECT"),delete:Y("DELETE"),get:Y("GET"),head:Y("HEAD"),options:Y("OPTIONS"),patch:Y("PATCH"),post:Y("POST"),put:Y("PUT"),trace:Y("TRACE")},trace:X("TRACE")}};var h2=o0(Sj());class m2{client;constructor($){this.client=$?.client??h2}}class c2{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class sj extends m2{static __registry=new c2;constructor($){super($);sj.__registry.set(this,$?.key)}setPricingHandler($){return($.client??this.client).post({url:"/ai-cost/pricing",...$,headers:{"Content-Type":"application/json",...$.headers}})}getUsageHandler($){return($.client??this.client).post({url:"/ai-cost/usage",...$,headers:{"Content-Type":"application/json",...$.headers}})}upsertAiProjection($){return($.client??this.client).post({url:"/ai-projections",...$,headers:{"Content-Type":"application/json",...$.headers}})}getChatsForAttachmentHandler($){return($.client??this.client).get({url:"/attachments/{attachment_id}/chats",...$})}deleteChat($){return($.client??this.client).delete({url:"/chat/{chat_id}",...$})}patchChat($){return($.client??this.client).patch({url:"/chat/{chat_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}permanentlyDeleteChat($){return($.client??this.client).delete({url:"/chat/{chat_id}/permanent",...$})}createChat($){return($.client??this.client).post({url:"/chats",...$,headers:{"Content-Type":"application/json",...$.headers}})}getChatHistoryHandler($){return($.client??this.client).get({url:"/chats/history/{chat_id}",...$})}getChatHistoryBatchMessagesHandler($){return($.client??this.client).post({url:"/chats/history_batch_messages",...$,headers:{"Content-Type":"application/json",...$.headers}})}getChat($){return($.client??this.client).get({url:"/chats/{chat_id}",...$})}copyChat($){return($.client??this.client).post({url:"/chats/{chat_id}/copy",...$})}getChatPermissions($){return($.client??this.client).get({url:"/chats/{chat_id}/permissions",...$})}revertDeleteChat($){return($.client??this.client).put({url:"/chats/{chat_id}/revert_delete",...$})}callTool($){return($.client??this.client).post({url:"/chats/{chat_id}/tool/call",...$,headers:{"Content-Type":"application/json",...$.headers}})}rejectToolCall($){return($.client??this.client).post({url:"/chats/{chat_id}/tool/reject",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateToolResponse($){return($.client??this.client).post({url:"/chats/{chat_id}/tool/response/update",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateToolCall($){return($.client??this.client).post({url:"/chats/{chat_id}/tool/update",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCitationHandler($){return($.client??this.client).get({url:"/citations/{id}",...$})}decisions($){return($.client??this.client).post({url:"/decisions",...$,headers:{"Content-Type":"application/json",...$.headers}})}healthHandler($){return($?.client??this.client).get({url:"/health",...$})}notionReportHandler($){return($?.client??this.client).get({url:"/import/notion",...$})}cancelNotionHandler($){return($?.client??this.client).post({url:"/import/notion/cancel",...$})}runImportHandler($){return($.client??this.client).post({url:"/import/run",...$,headers:{"Content-Type":"application/json",...$.headers}})}discoverHandler($){return($.client??this.client).post({url:"/import/runs/{source}/discover",...$})}getStateHandler($){return($?.client??this.client).get({url:"/import/state",...$})}workspaceReportHandler($){return($.client??this.client).get({url:"/import/workspaces/{source}",...$})}cancelWorkspaceHandler($){return($.client??this.client).post({url:"/import/workspaces/{source}/cancel",...$})}deleteMcpServer($){return($.client??this.client).delete({url:"/mcp/servers",...$})}listMcpServers($){return($?.client??this.client).get({url:"/mcp/servers",...$})}addMcpServer($){return($.client??this.client).post({url:"/mcp/servers",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateMcpServer($){return($.client??this.client).put({url:"/mcp/servers",...$,headers:{"Content-Type":"application/json",...$.headers}})}mcpAuthCallback($){return($?.client??this.client).get({url:"/mcp/servers/auth/callback",...$})}mcpOauthClientMetadata($){return($?.client??this.client).get({url:"/mcp/servers/auth/client-metadata",...$})}startMcpAuth($){return($.client??this.client).post({url:"/mcp/servers/auth/start",...$,headers:{"Content-Type":"application/json",...$.headers}})}getMemoryHandler($){return($?.client??this.client).get({url:"/memory",...$})}getStateHandler2($){return($?.client??this.client).get({url:"/onboarding",...$})}completeHandler($){return($.client??this.client).post({url:"/onboarding/complete",...$,headers:{"Content-Type":"application/json",...$.headers}})}dismissedPromptsHandler($){return($?.client??this.client).get({url:"/onboarding/prompts",...$})}dismissPromptHandler($){return($.client??this.client).post({url:"/onboarding/prompts/{prompt_id}/dismiss",...$})}browsePipedreamMcpCatalog($){return($?.client??this.client).get({url:"/pipedream/mcp/catalog",...$})}completePipedreamMcpConnection($){return($.client??this.client).post({url:"/pipedream/mcp/complete",...$,headers:{"Content-Type":"application/json",...$.headers}})}deletePipedreamMcpConnection($){return($.client??this.client).delete({url:"/pipedream/mcp/connections",...$})}listPipedreamMcpConnections($){return($?.client??this.client).get({url:"/pipedream/mcp/connections",...$})}updatePipedreamMcpConnection($){return($.client??this.client).put({url:"/pipedream/mcp/connections",...$,headers:{"Content-Type":"application/json",...$.headers}})}createPipedreamMcpToken($){return($?.client??this.client).post({url:"/pipedream/mcp/token",...$})}getBatchPreview($){return($.client??this.client).post({url:"/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}sendChatMessage($){return($.client??this.client).post({url:"/stream/chat/message",...$,headers:{"Content-Type":"application/json",...$.headers}})}stopChatStream($){return($.client??this.client).post({url:"/stream/chat/message/stop",...$,headers:{"Content-Type":"application/json",...$.headers}})}structuredCompletion($){return($.client??this.client).post({url:"/structured-completion",...$,headers:{"Content-Type":"application/json",...$.headers}})}}function u2({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...Q}){let J,I=Y??((V)=>new Promise((W)=>setTimeout(W,V)));return{stream:async function*(){let V=K??3000,W=0,T=Q.signal??new AbortController().signal;while(!0){if(T.aborted)break;W++;let A=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)A.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:A,signal:T},_=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 H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",k=()=>{try{H.cancel()}catch{}};T.addEventListener("abort",k);try{while(!0){let{done:l,value:r}=await H.read();if(l)break;U+=r,U=U.replace(/\r\n?/g,``);let g=U.split(``);U=g.pop()??"";for(let p of g){let a=p.split(``),F=[],y;for(let R of a)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))y=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let h=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(h))V=h}let C,v=!1;if(F.length){let R=F.join(`-`);try{C=JSON.parse(R),v=!0}catch{C=R}}if(v){if(S)await S(C);if(x)C=await x(C)}if(j?.({data:C,event:y,id:J,retry:V}),F.length)yield C}}}finally{T.removeEventListener("abort",k),H.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 s7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},t7=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},e7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},sj=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((Y)=>encodeURIComponent(Y))).join(t7(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=s7(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return EO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},EO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},tj=({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 Y=[];Object.entries(S).forEach(([Q,J])=>{Y=[...Y,Q,$?J:encodeURIComponent(J)]});let L=Y.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=e7(x),X=Object.entries(S).map(([Y,L])=>EO({allowReserved:$,name:x==="deepObject"?`${j}[${Y}]`:Y,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var o7=/\{[^{}]+\}/g,$5=({path:$,url:O})=>{let j=O,x=O.match(o7);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 Y=$[Z];if(Y===void 0||Y===null)continue;if(Array.isArray(Y)){j=j.replace(S,sj({explode:K,name:Z,style:X,value:Y}));continue}if(typeof Y==="object"){j=j.replace(S,tj({explode:K,name:Z,style:X,value:Y,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${EO({name:Z,value:Y})}`);continue}let L=encodeURIComponent(X==="label"?`.${Y}`:Y);j=j.replace(S,L)}return j},c2=({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 e0($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var u2=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var d2={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var l2=({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 Y=sj({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(Y)S.push(Y)}else if(typeof Z==="object"){let Y=tj({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(Y)S.push(Y)}else{let Y=EO({allowReserved:X.allowReserved,name:K,value:Z});if(Y)S.push(Y)}}return S.join("&")}},r2=($)=>{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},O5=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function p2($){for(let O of $.security??[]){if(O5($,O.name))continue;let j=await u2(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var o0=($)=>c2({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:l2($.querySerializer),url:$.url}),$1=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=oj($.headers,O.headers),j},j5=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},oj=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?j5(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class ej{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var a2=()=>({error:new ej,request:new ej,response:new ej}),x5=l2({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),S5={"Content-Type":"application/json"},Sj=($={})=>({...d2,headers:S5,parseAs:"auto",querySerializer:x5,...$});var O1=($={})=>{let O=$1(Sj(),$),j=()=>({...O}),x=(Q)=>{return O=$1(O,Q),j()},S=a2(),K=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:oj(O.headers,Q.headers),serializedBody:void 0};if(J.security)await p2(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=o0(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),T={redirect:"follow",...V,body:e0(V)};z=new Request(B,T);for(let N of S.request.fns)if(N)z=await N(z,V);let A=V.fetch;W=await A(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"?r2(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await W[N]();break;case"json":{let U=await W.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let _=await W.text(),q;try{q=JSON.parse(_)}catch{}throw q??_}catch(V){let B=V;for(let T of S.error.fns)if(T)B=await T(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}),Y=(Q)=>async(J)=>{let{opts:I,url:z}=await K(J);return m2({...I,body:I.body,method:Q,onRequest:async(W,V)=>{let B=new Request(W,V);for(let T of S.request.fns)if(T)B=await T(B,I);return B},serializedBody:e0(I),url:z})};return{buildUrl:(Q)=>o0({...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:Y("CONNECT"),delete:Y("DELETE"),get:Y("GET"),head:Y("HEAD"),options:Y("OPTIONS"),patch:Y("PATCH"),post:Y("POST"),put:Y("PUT"),trace:Y("TRACE")},trace:X("TRACE")}};var i2=O1(Sj());class n2{client;constructor($){this.client=$?.client??i2}}class s2{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 $x extends n2{static __registry=new s2;constructor($){super($);$x.__registry.set(this,$?.key)}getContacts($){return($?.client??this.client).get({url:"/contacts",...$})}addContact($){return($.client??this.client).post({url:"/contacts",...$,headers:{"Content-Type":"application/json",...$.headers}})}}function t2({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...Q}){let J,I=Y??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,T=Q.signal??new AbortController().signal;while(!0){if(T.aborted)break;B++;let A=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)A.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:A,signal:T},_=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 H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",k=()=>{try{H.cancel()}catch{}};T.addEventListener("abort",k);try{while(!0){let{done:l,value:r}=await H.read();if(l)break;U+=r,U=U.replace(/\r\n?/g,`+`);try{C=JSON.parse(R),v=!0}catch{C=R}}if(v){if(S)await S(C);if(x)C=await x(C)}if(j?.({data:C,event:y,id:J,retry:V}),F.length)yield C}}}finally{T.removeEventListener("abort",k),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&W>=Z)break;let _=Math.min(V*2**(W-1),X??30000);await I(_)}}}()}}var e7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},o7=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},$5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},tj=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((Y)=>encodeURIComponent(Y))).join(o7(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=e7(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)}`},ej=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let Y=[];Object.entries(S).forEach(([Q,J])=>{Y=[...Y,Q,$?J:encodeURIComponent(J)]});let L=Y.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=$5(x),X=Object.entries(S).map(([Y,L])=>wO({allowReserved:$,name:x==="deepObject"?`${j}[${Y}]`:Y,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var O5=/\{[^{}]+\}/g,j5=({path:$,url:O})=>{let j=O,x=O.match(O5);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 Y=$[Z];if(Y===void 0||Y===null)continue;if(Array.isArray(Y)){j=j.replace(S,tj({explode:K,name:Z,style:X,value:Y}));continue}if(typeof Y==="object"){j=j.replace(S,ej({explode:K,name:Z,style:X,value:Y,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${wO({name:Z,value:Y})}`);continue}let L=encodeURIComponent(X==="label"?`.${Y}`:Y);j=j.replace(S,L)}return j},d2=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=j5({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function $1($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var l2=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var r2={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var p2=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let Y=tj({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(Y)S.push(Y)}else if(typeof Z==="object"){let Y=ej({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(Y)S.push(Y)}else{let Y=wO({allowReserved:X.allowReserved,name:K,value:Z});if(Y)S.push(Y)}}return S.join("&")}},a2=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},x5=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function i2($){for(let O of $.security??[]){if(x5($,O.name))continue;let j=await l2(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var O1=($)=>d2({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:p2($.querySerializer),url:$.url}),j1=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=$x($.headers,O.headers),j},S5=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},$x=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?S5(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 oj{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var n2=()=>({error:new oj,request:new oj,response:new oj}),Z5=p2({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),X5={"Content-Type":"application/json"},Zj=($={})=>({...r2,headers:X5,parseAs:"auto",querySerializer:Z5,...$});var x1=($={})=>{let O=j1(Zj(),$),j=()=>({...O}),x=(Q)=>{return O=j1(O,Q),j()},S=n2(),K=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:$x(O.headers,Q.headers),serializedBody:void 0};if(J.security)await i2(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let I=J,z=O1(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,B;try{let{opts:V,url:W}=await K(Q),T={redirect:"follow",...V,body:$1(V)};z=new Request(W,T);for(let N of S.request.fns)if(N)z=await N(z,V);let A=V.fetch;B=await A(z);for(let N of S.response.fns)if(N)B=await N(B,z,V);let D={request:z,response:B};if(B.ok){let N=(V.parseAs==="auto"?a2(B.headers.get("Content-Type")):V.parseAs)??"json";if(B.status===204||B.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await B[N]();break;case"formData":U=new FormData;break;case"stream":U=B.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await B[N]();break;case"json":{let U=await B.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?B.body:{data:B.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let _=await B.text(),q;try{q=JSON.parse(_)}catch{}throw q??_}catch(V){let W=V;for(let T of S.error.fns)if(T)W=await T(W,B,z,Q);if(W=W||{},J)throw W;return I==="data"?void 0:{error:W,request:z,response:B}}},X=(Q)=>(J)=>Z({...J,method:Q}),Y=(Q)=>async(J)=>{let{opts:I,url:z}=await K(J);return u2({...I,body:I.body,method:Q,onRequest:async(B,V)=>{let W=new Request(B,V);for(let T of S.request.fns)if(T)W=await T(W,I);return W},serializedBody:$1(I),url:z})};return{buildUrl:(Q)=>O1({...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:Y("CONNECT"),delete:Y("DELETE"),get:Y("GET"),head:Y("HEAD"),options:Y("OPTIONS"),patch:Y("PATCH"),post:Y("POST"),put:Y("PUT"),trace:Y("TRACE")},trace:X("TRACE")}};var s2=x1(Zj());class t2{client;constructor($){this.client=$?.client??s2}}class e2{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class Ox extends t2{static __registry=new e2;constructor($){super($);Ox.__registry.set(this,$?.key)}getContacts($){return($?.client??this.client).get({url:"/contacts",...$})}addContact($){return($.client??this.client).post({url:"/contacts",...$,headers:{"Content-Type":"application/json",...$.headers}})}}function o2({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...Q}){let J,I=Y??((V)=>new Promise((W)=>setTimeout(W,V)));return{stream:async function*(){let V=K??3000,W=0,T=Q.signal??new AbortController().signal;while(!0){if(T.aborted)break;W++;let A=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)A.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:A,signal:T},_=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 H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",k=()=>{try{H.cancel()}catch{}};T.addEventListener("abort",k);try{while(!0){let{done:l,value:r}=await H.read();if(l)break;U+=r,U=U.replace(/\r\n?/g,``);let g=U.split(``);U=g.pop()??"";for(let p of g){let a=p.split(``),F=[],y;for(let R of a)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))y=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let h=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(h))V=h}let C,v=!1;if(F.length){let R=F.join(`-`);try{C=JSON.parse(R),v=!0}catch{C=R}}if(v){if(S)await S(C);if(x)C=await x(C)}if(j?.({data:C,event:y,id:J,retry:V}),F.length)yield C}}}finally{T.removeEventListener("abort",k),H.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 Z5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},X5=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},K5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},Ox=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((Y)=>encodeURIComponent(Y))).join(X5(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=Z5(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)}`},jx=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let Y=[];Object.entries(S).forEach(([Q,J])=>{Y=[...Y,Q,$?J:encodeURIComponent(J)]});let L=Y.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=K5(x),X=Object.entries(S).map(([Y,L])=>wO({allowReserved:$,name:x==="deepObject"?`${j}[${Y}]`:Y,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var Y5=/\{[^{}]+\}/g,G5=({path:$,url:O})=>{let j=O,x=O.match(Y5);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 Y=$[Z];if(Y===void 0||Y===null)continue;if(Array.isArray(Y)){j=j.replace(S,Ox({explode:K,name:Z,style:X,value:Y}));continue}if(typeof Y==="object"){j=j.replace(S,jx({explode:K,name:Z,style:X,value:Y,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${wO({name:Z,value:Y})}`);continue}let L=encodeURIComponent(X==="label"?`.${Y}`:Y);j=j.replace(S,L)}return j},e2=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=G5({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function j1($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var o2=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var $S={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var OS=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let Y=Ox({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(Y)S.push(Y)}else if(typeof Z==="object"){let Y=jx({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(Y)S.push(Y)}else{let Y=wO({allowReserved:X.allowReserved,name:K,value:Z});if(Y)S.push(Y)}}return S.join("&")}},jS=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},Q5=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function xS($){for(let O of $.security??[]){if(Q5($,O.name))continue;let j=await o2(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var x1=($)=>e2({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:OS($.querySerializer),url:$.url}),S1=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=Sx($.headers,O.headers),j},J5=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},Sx=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?J5(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class xx{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var SS=()=>({error:new xx,request:new xx,response:new xx}),V5=OS({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),W5={"Content-Type":"application/json"},Zj=($={})=>({...$S,headers:W5,parseAs:"auto",querySerializer:V5,...$});var Z1=($={})=>{let O=S1(Zj(),$),j=()=>({...O}),x=(Q)=>{return O=S1(O,Q),j()},S=SS(),K=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:Sx(O.headers,Q.headers),serializedBody:void 0};if(J.security)await xS(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let I=J,z=x1(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),T={redirect:"follow",...V,body:j1(V)};z=new Request(B,T);for(let N of S.request.fns)if(N)z=await N(z,V);let A=V.fetch;W=await A(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?jS(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await W[N]();break;case"json":{let U=await W.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let _=await W.text(),q;try{q=JSON.parse(_)}catch{}throw q??_}catch(V){let B=V;for(let T of S.error.fns)if(T)B=await T(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}),Y=(Q)=>async(J)=>{let{opts:I,url:z}=await K(J);return t2({...I,body:I.body,method:Q,onRequest:async(W,V)=>{let B=new Request(W,V);for(let T of S.request.fns)if(T)B=await T(B,I);return B},serializedBody:j1(I),url:z})};return{buildUrl:(Q)=>x1({...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:Y("CONNECT"),delete:Y("DELETE"),get:Y("GET"),head:Y("HEAD"),options:Y("OPTIONS"),patch:Y("PATCH"),post:Y("POST"),put:Y("PUT"),trace:Y("TRACE")},trace:X("TRACE")}};var ZS=Z1(Zj());class XS{client;constructor($){this.client=$?.client??ZS}}class KS{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class Zx extends XS{static __registry=new KS;constructor($){super($);Zx.__registry.set(this,$?.key)}getAttachment($){return($.client??this.client).get({url:"/email/attachments/{id}",...$})}getAttachmentDocumentId($){return($.client??this.client).get({url:"/email/attachments/{id}/document_id",...$})}cancelBackfillGmail($){return($.client??this.client).delete({url:"/email/backfill/gmail",...$,headers:{"Content-Type":"application/json",...$.headers}})}listBackfillGmail($){return($?.client??this.client).get({url:"/email/backfill/gmail",...$})}getBackfillGmailActive($){return($?.client??this.client).get({url:"/email/backfill/gmail/active",...$})}getBackfillGmail($){return($.client??this.client).get({url:"/email/backfill/gmail/{id}",...$})}listContacts($){return($?.client??this.client).get({url:"/email/contacts",...$})}blockSender($){return($.client??this.client).post({url:"/email/contacts/block",...$,headers:{"Content-Type":"application/json",...$.headers}})}listBlockedSenders($){return($?.client??this.client).get({url:"/email/contacts/blocked",...$})}unblockSender($){return($.client??this.client).post({url:"/email/contacts/unblock",...$,headers:{"Content-Type":"application/json",...$.headers}})}recoverDraftTransfer($){return($.client??this.client).post({url:"/email/draft-transfers/{id}/recover",...$})}createDraft($){return($.client??this.client).post({url:"/email/drafts",...$,headers:{"Content-Type":"application/json",...$.headers}})}getScheduledMessages($){return($?.client??this.client).get({url:"/email/drafts/scheduled",...$})}upsertScheduledMessage($){return($.client??this.client).put({url:"/email/drafts/scheduled/{id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteScheduledDraft($){return($.client??this.client).delete({url:"/email/drafts/scheduled/{message_id}",...$})}deleteDraft($){return($.client??this.client).delete({url:"/email/drafts/{id}",...$})}addDraftAttachment($){return($.client??this.client).post({url:"/email/drafts/{id}/attachments",...$,headers:{"Content-Type":"application/json",...$.headers}})}removeDraftAttachment($){return($.client??this.client).delete({url:"/email/drafts/{id}/attachments/{attachment_id}",...$})}completeDraftAttachment($){return($.client??this.client).post({url:"/email/drafts/{id}/attachments/{attachment_id}/complete",...$})}addForwardedAttachment($){return($.client??this.client).post({url:"/email/drafts/{id}/forwarded-attachments",...$,headers:{"Content-Type":"application/json",...$.headers}})}removeForwardedAttachment($){return($.client??this.client).delete({url:"/email/drafts/{id}/forwarded-attachments/{attachment_id}",...$})}messageOperationStatus($){return($.client??this.client).get({url:"/email/drafts/{id}/operation",...$})}resolveMessageOperation($){return($.client??this.client).post({url:"/email/drafts/{id}/resolve",...$,headers:{"Content-Type":"application/json",...$.headers}})}transferDraft($){return($.client??this.client).post({url:"/email/drafts/{id}/transfer",...$,headers:{"Content-Type":"application/json",...$.headers}})}listEmailFilters($){return($?.client??this.client).get({url:"/email/filters",...$})}upsertEmailFilter($){return($.client??this.client).put({url:"/email/filters",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteEmailFilter($){return($.client??this.client).delete({url:"/email/filters/{id}",...$})}initUser($){return($?.client??this.client).post({url:"/email/init",...$})}listLabels($){return($?.client??this.client).get({url:"/email/labels",...$})}createLabel($){return($.client??this.client).post({url:"/email/labels",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteLabel($){return($.client??this.client).delete({url:"/email/labels/{id}",...$})}listLinks($){return($?.client??this.client).get({url:"/email/links",...$})}healthCheckLinks($){return($?.client??this.client).post({url:"/email/links/health-check",...$})}deleteLink($){return($.client??this.client).delete({url:"/email/links/{link_id}",...$})}disableLinkCalendar($){return($.client??this.client).delete({url:"/email/links/{link_id}/calendar",...$})}resyncLink($){return($.client??this.client).post({url:"/email/links/{link_id}/resync",...$})}sendMessage($){return($.client??this.client).post({url:"/email/messages",...$,headers:{"Content-Type":"application/json",...$.headers}})}getMessagesBatch($){return($.client??this.client).post({url:"/email/messages/batch",...$,headers:{"Content-Type":"application/json",...$.headers}})}addRemoveLabel($){return($.client??this.client).patch({url:"/email/messages/labels",...$,headers:{"Content-Type":"application/json",...$.headers}})}getMessage($){return($.client??this.client).get({url:"/email/messages/{id}",...$})}patchSettings($){return($.client??this.client).patch({url:"/email/settings",...$,headers:{"Content-Type":"application/json",...$.headers}})}mailboxSettingsOperations($){return($?.client??this.client).get({url:"/email/settings/operations",...$})}disableSync($){return($?.client??this.client).delete({url:"/email/sync",...$})}previewsInboxCursor($){return($.client??this.client).get({url:"/email/threads/previews/cursor/{view}",...$})}archiveThread($){return($.client??this.client).patch({url:"/email/threads/{id}/archived",...$,headers:{"Content-Type":"application/json",...$.headers}})}addRemoveThreadLabel($){return($.client??this.client).patch({url:"/email/threads/{id}/labels",...$,headers:{"Content-Type":"application/json",...$.headers}})}getThreadMessagesHandler($){return($.client??this.client).get({url:"/email/threads/{id}/messages",...$})}threadOperations($){return($.client??this.client).get({url:"/email/threads/{id}/operations",...$})}threadSeen($){return($.client??this.client).post({url:"/email/threads/{id}/seen",...$})}updateThreadState($){return($.client??this.client).patch({url:"/email/threads/{id}/state",...$,headers:{"Content-Type":"application/json",...$.headers}})}getThread($){return($.client??this.client).get({url:"/email/threads/{thread_id}",...$})}getThreadCalendarInvitations($){return($.client??this.client).get({url:"/email/threads/{thread_id}/calendar-invitations",...$})}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 YS({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...Q}){let J,I=Y??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,T=Q.signal??new AbortController().signal;while(!0){if(T.aborted)break;B++;let A=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)A.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:A,signal:T},_=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 H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",k=()=>{try{H.cancel()}catch{}};T.addEventListener("abort",k);try{while(!0){let{done:l,value:r}=await H.read();if(l)break;U+=r,U=U.replace(/\r\n?/g,`+`);try{C=JSON.parse(R),v=!0}catch{C=R}}if(v){if(S)await S(C);if(x)C=await x(C)}if(j?.({data:C,event:y,id:J,retry:V}),F.length)yield C}}}finally{T.removeEventListener("abort",k),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&W>=Z)break;let _=Math.min(V*2**(W-1),X??30000);await I(_)}}}()}}var K5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},Y5=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},G5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},jx=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((Y)=>encodeURIComponent(Y))).join(Y5(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=K5(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return qO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},qO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},xx=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let Y=[];Object.entries(S).forEach(([Q,J])=>{Y=[...Y,Q,$?J:encodeURIComponent(J)]});let L=Y.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=G5(x),X=Object.entries(S).map(([Y,L])=>qO({allowReserved:$,name:x==="deepObject"?`${j}[${Y}]`:Y,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var Q5=/\{[^{}]+\}/g,J5=({path:$,url:O})=>{let j=O,x=O.match(Q5);if(x)for(let S of x){let K=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))K=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let Y=$[Z];if(Y===void 0||Y===null)continue;if(Array.isArray(Y)){j=j.replace(S,jx({explode:K,name:Z,style:X,value:Y}));continue}if(typeof Y==="object"){j=j.replace(S,xx({explode:K,name:Z,style:X,value:Y,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${qO({name:Z,value:Y})}`);continue}let L=encodeURIComponent(X==="label"?`.${Y}`:Y);j=j.replace(S,L)}return j},$S=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=J5({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function S1($){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 OS=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var jS={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var xS=({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 Y=jx({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(Y)S.push(Y)}else if(typeof Z==="object"){let Y=xx({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(Y)S.push(Y)}else{let Y=qO({allowReserved:X.allowReserved,name:K,value:Z});if(Y)S.push(Y)}}return S.join("&")}},SS=($)=>{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},V5=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function ZS($){for(let O of $.security??[]){if(V5($,O.name))continue;let j=await OS(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var Z1=($)=>$S({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:xS($.querySerializer),url:$.url}),X1=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=Zx($.headers,O.headers),j},B5=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},Zx=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?B5(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class Sx{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 XS=()=>({error:new Sx,request:new Sx,response:new Sx}),W5=xS({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),L5={"Content-Type":"application/json"},Xj=($={})=>({...jS,headers:L5,parseAs:"auto",querySerializer:W5,...$});var K1=($={})=>{let O=X1(Xj(),$),j=()=>({...O}),x=(Q)=>{return O=X1(O,Q),j()},S=XS(),K=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:Zx(O.headers,Q.headers),serializedBody:void 0};if(J.security)await ZS(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=Z1(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,B;try{let{opts:V,url:W}=await K(Q),T={redirect:"follow",...V,body:S1(V)};z=new Request(W,T);for(let N of S.request.fns)if(N)z=await N(z,V);let A=V.fetch;B=await A(z);for(let N of S.response.fns)if(N)B=await N(B,z,V);let D={request:z,response:B};if(B.ok){let N=(V.parseAs==="auto"?SS(B.headers.get("Content-Type")):V.parseAs)??"json";if(B.status===204||B.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await B[N]();break;case"formData":U=new FormData;break;case"stream":U=B.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await B[N]();break;case"json":{let U=await B.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?B.body:{data:B.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let _=await B.text(),q;try{q=JSON.parse(_)}catch{}throw q??_}catch(V){let W=V;for(let T of S.error.fns)if(T)W=await T(W,B,z,Q);if(W=W||{},J)throw W;return I==="data"?void 0:{error:W,request:z,response:B}}},X=(Q)=>(J)=>Z({...J,method:Q}),Y=(Q)=>async(J)=>{let{opts:I,url:z}=await K(J);return o2({...I,body:I.body,method:Q,onRequest:async(B,V)=>{let W=new Request(B,V);for(let T of S.request.fns)if(T)W=await T(W,I);return W},serializedBody:S1(I),url:z})};return{buildUrl:(Q)=>Z1({...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:Y("CONNECT"),delete:Y("DELETE"),get:Y("GET"),head:Y("HEAD"),options:Y("OPTIONS"),patch:Y("PATCH"),post:Y("POST"),put:Y("PUT"),trace:Y("TRACE")},trace:X("TRACE")}};var KS=K1(Xj());class YS{client;constructor($){this.client=$?.client??KS}}class GS{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class Xx extends YS{static __registry=new GS;constructor($){super($);Xx.__registry.set(this,$?.key)}getAttachment($){return($.client??this.client).get({url:"/email/attachments/{id}",...$})}getAttachmentDocumentId($){return($.client??this.client).get({url:"/email/attachments/{id}/document_id",...$})}cancelBackfillGmail($){return($.client??this.client).delete({url:"/email/backfill/gmail",...$,headers:{"Content-Type":"application/json",...$.headers}})}listBackfillGmail($){return($?.client??this.client).get({url:"/email/backfill/gmail",...$})}getBackfillGmailActive($){return($?.client??this.client).get({url:"/email/backfill/gmail/active",...$})}getBackfillGmail($){return($.client??this.client).get({url:"/email/backfill/gmail/{id}",...$})}listContacts($){return($?.client??this.client).get({url:"/email/contacts",...$})}blockSender($){return($.client??this.client).post({url:"/email/contacts/block",...$,headers:{"Content-Type":"application/json",...$.headers}})}listBlockedSenders($){return($?.client??this.client).get({url:"/email/contacts/blocked",...$})}unblockSender($){return($.client??this.client).post({url:"/email/contacts/unblock",...$,headers:{"Content-Type":"application/json",...$.headers}})}recoverDraftTransfer($){return($.client??this.client).post({url:"/email/draft-transfers/{id}/recover",...$})}createDraft($){return($.client??this.client).post({url:"/email/drafts",...$,headers:{"Content-Type":"application/json",...$.headers}})}getScheduledMessages($){return($?.client??this.client).get({url:"/email/drafts/scheduled",...$})}upsertScheduledMessage($){return($.client??this.client).put({url:"/email/drafts/scheduled/{id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteScheduledDraft($){return($.client??this.client).delete({url:"/email/drafts/scheduled/{message_id}",...$})}deleteDraft($){return($.client??this.client).delete({url:"/email/drafts/{id}",...$})}addDraftAttachment($){return($.client??this.client).post({url:"/email/drafts/{id}/attachments",...$,headers:{"Content-Type":"application/json",...$.headers}})}removeDraftAttachment($){return($.client??this.client).delete({url:"/email/drafts/{id}/attachments/{attachment_id}",...$})}completeDraftAttachment($){return($.client??this.client).post({url:"/email/drafts/{id}/attachments/{attachment_id}/complete",...$})}addForwardedAttachment($){return($.client??this.client).post({url:"/email/drafts/{id}/forwarded-attachments",...$,headers:{"Content-Type":"application/json",...$.headers}})}removeForwardedAttachment($){return($.client??this.client).delete({url:"/email/drafts/{id}/forwarded-attachments/{attachment_id}",...$})}messageOperationStatus($){return($.client??this.client).get({url:"/email/drafts/{id}/operation",...$})}resolveMessageOperation($){return($.client??this.client).post({url:"/email/drafts/{id}/resolve",...$,headers:{"Content-Type":"application/json",...$.headers}})}transferDraft($){return($.client??this.client).post({url:"/email/drafts/{id}/transfer",...$,headers:{"Content-Type":"application/json",...$.headers}})}listEmailFilters($){return($?.client??this.client).get({url:"/email/filters",...$})}upsertEmailFilter($){return($.client??this.client).put({url:"/email/filters",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteEmailFilter($){return($.client??this.client).delete({url:"/email/filters/{id}",...$})}initUser($){return($?.client??this.client).post({url:"/email/init",...$})}listLabels($){return($?.client??this.client).get({url:"/email/labels",...$})}createLabel($){return($.client??this.client).post({url:"/email/labels",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteLabel($){return($.client??this.client).delete({url:"/email/labels/{id}",...$})}listLinks($){return($?.client??this.client).get({url:"/email/links",...$})}healthCheckLinks($){return($?.client??this.client).post({url:"/email/links/health-check",...$})}deleteLink($){return($.client??this.client).delete({url:"/email/links/{link_id}",...$})}disableLinkCalendar($){return($.client??this.client).delete({url:"/email/links/{link_id}/calendar",...$})}resyncLink($){return($.client??this.client).post({url:"/email/links/{link_id}/resync",...$})}sendMessage($){return($.client??this.client).post({url:"/email/messages",...$,headers:{"Content-Type":"application/json",...$.headers}})}getMessagesBatch($){return($.client??this.client).post({url:"/email/messages/batch",...$,headers:{"Content-Type":"application/json",...$.headers}})}addRemoveLabel($){return($.client??this.client).patch({url:"/email/messages/labels",...$,headers:{"Content-Type":"application/json",...$.headers}})}getMessage($){return($.client??this.client).get({url:"/email/messages/{id}",...$})}patchSettings($){return($.client??this.client).patch({url:"/email/settings",...$,headers:{"Content-Type":"application/json",...$.headers}})}mailboxSettingsOperations($){return($?.client??this.client).get({url:"/email/settings/operations",...$})}disableSync($){return($?.client??this.client).delete({url:"/email/sync",...$})}previewsInboxCursor($){return($.client??this.client).get({url:"/email/threads/previews/cursor/{view}",...$})}archiveThread($){return($.client??this.client).patch({url:"/email/threads/{id}/archived",...$,headers:{"Content-Type":"application/json",...$.headers}})}addRemoveThreadLabel($){return($.client??this.client).patch({url:"/email/threads/{id}/labels",...$,headers:{"Content-Type":"application/json",...$.headers}})}getThreadMessagesHandler($){return($.client??this.client).get({url:"/email/threads/{id}/messages",...$})}threadOperations($){return($.client??this.client).get({url:"/email/threads/{id}/operations",...$})}threadSeen($){return($.client??this.client).post({url:"/email/threads/{id}/seen",...$})}updateThreadState($){return($.client??this.client).patch({url:"/email/threads/{id}/state",...$,headers:{"Content-Type":"application/json",...$.headers}})}getThread($){return($.client??this.client).get({url:"/email/threads/{thread_id}",...$})}getThreadCalendarInvitations($){return($.client??this.client).get({url:"/email/threads/{thread_id}/calendar-invitations",...$})}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 QS({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...Q}){let J,I=Y??((V)=>new Promise((W)=>setTimeout(W,V)));return{stream:async function*(){let V=K??3000,W=0,T=Q.signal??new AbortController().signal;while(!0){if(T.aborted)break;W++;let A=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)A.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:A,signal:T},_=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 H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",k=()=>{try{H.cancel()}catch{}};T.addEventListener("abort",k);try{while(!0){let{done:l,value:r}=await H.read();if(l)break;U+=r,U=U.replace(/\r\n?/g,``);let g=U.split(``);U=g.pop()??"";for(let p of g){let a=p.split(``),F=[],y;for(let R of a)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))y=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let h=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(h))V=h}let C,v=!1;if(F.length){let R=F.join(`-`);try{C=JSON.parse(R),v=!0}catch{C=R}}if(v){if(S)await S(C);if(x)C=await x(C)}if(j?.({data:C,event:y,id:J,retry:V}),F.length)yield C}}}finally{T.removeEventListener("abort",k),H.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 B5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},L5=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},N5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},Xx=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((Y)=>encodeURIComponent(Y))).join(L5(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=B5(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return qO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},qO=({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)}`},Kx=({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 Y=[];Object.entries(S).forEach(([Q,J])=>{Y=[...Y,Q,$?J:encodeURIComponent(J)]});let L=Y.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=N5(x),X=Object.entries(S).map(([Y,L])=>qO({allowReserved:$,name:x==="deepObject"?`${j}[${Y}]`:Y,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var U5=/\{[^{}]+\}/g,z5=({path:$,url:O})=>{let j=O,x=O.match(U5);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 Y=$[Z];if(Y===void 0||Y===null)continue;if(Array.isArray(Y)){j=j.replace(S,Xx({explode:K,name:Z,style:X,value:Y}));continue}if(typeof Y==="object"){j=j.replace(S,Kx({explode:K,name:Z,style:X,value:Y,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${qO({name:Z,value:Y})}`);continue}let L=encodeURIComponent(X==="label"?`.${Y}`:Y);j=j.replace(S,L)}return j},GS=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=z5({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function X1($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var QS=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var JS={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var VS=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let Y=Xx({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(Y)S.push(Y)}else if(typeof Z==="object"){let Y=Kx({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(Y)S.push(Y)}else{let Y=qO({allowReserved:X.allowReserved,name:K,value:Z});if(Y)S.push(Y)}}return S.join("&")}},WS=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},I5=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function BS($){for(let O of $.security??[]){if(I5($,O.name))continue;let j=await QS(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var K1=($)=>GS({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:VS($.querySerializer),url:$.url}),Y1=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=Gx($.headers,O.headers),j},T5=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},Gx=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?T5(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 Yx{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var LS=()=>({error:new Yx,request:new Yx,response:new Yx}),H5=VS({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),R5={"Content-Type":"application/json"},Xj=($={})=>({...JS,headers:R5,parseAs:"auto",querySerializer:H5,...$});var G1=($={})=>{let O=Y1(Xj(),$),j=()=>({...O}),x=(Q)=>{return O=Y1(O,Q),j()},S=LS(),K=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:Gx(O.headers,Q.headers),serializedBody:void 0};if(J.security)await BS(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let I=J,z=K1(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),T={redirect:"follow",...V,body:X1(V)};z=new Request(B,T);for(let N of S.request.fns)if(N)z=await N(z,V);let A=V.fetch;W=await A(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?WS(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await W[N]();break;case"json":{let U=await W.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let _=await W.text(),q;try{q=JSON.parse(_)}catch{}throw q??_}catch(V){let B=V;for(let T of S.error.fns)if(T)B=await T(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}),Y=(Q)=>async(J)=>{let{opts:I,url:z}=await K(J);return YS({...I,body:I.body,method:Q,onRequest:async(W,V)=>{let B=new Request(W,V);for(let T of S.request.fns)if(T)B=await T(B,I);return B},serializedBody:X1(I),url:z})};return{buildUrl:(Q)=>K1({...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:Y("CONNECT"),delete:Y("DELETE"),get:Y("GET"),head:Y("HEAD"),options:Y("OPTIONS"),patch:Y("PATCH"),post:Y("POST"),put:Y("PUT"),trace:Y("TRACE")},trace:X("TRACE")}};var NS=G1(Xj());class US{client;constructor($){this.client=$?.client??NS}}class zS{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class Qx extends US{static __registry=new zS;constructor($){super($);Qx.__registry.set(this,$?.key)}healthHandler($){return($?.client??this.client).get({url:"/health",...$})}getUnsubscribes($){return($?.client??this.client).get({url:"/unsubscribe",...$})}unsubscribeEmail($){return($?.client??this.client).post({url:"/unsubscribe/email",...$})}removeUnsubscribeItem($){return($.client??this.client).delete({url:"/unsubscribe/item/{item_type}/{item_id}",...$})}unsubscribeItem($){return($.client??this.client).post({url:"/unsubscribe/item/{item_type}/{item_id}",...$})}removeUnsubscribeAll($){return($?.client??this.client).delete({url:"/unsubscribe/mute",...$})}unsubscribeAll($){return($?.client??this.client).post({url:"/unsubscribe/mute",...$})}listTypedNotifications($){return($?.client??this.client).get({url:"/v1/user_notifications",...$})}bulkGetTypedNotificationsByEventItemIds($){return($.client??this.client).post({url:"/v1/user_notifications/item/bulk",...$,headers:{"Content-Type":"application/json",...$.headers}})}getTypedNotificationsByEventItemId($){return($.client??this.client).get({url:"/v1/user_notifications/item/{event_item_id}",...$})}getNotificationTypePreferences($){return($?.client??this.client).get({url:"/v1/user_notifications/preferences",...$})}disableNotificationType($){return($.client??this.client).put({url:"/v1/user_notifications/preferences/{notification_event_type}/disable",...$})}enableNotificationType($){return($.client??this.client).put({url:"/v1/user_notifications/preferences/{notification_event_type}/enable",...$})}getTypedNotificationById($){return($.client??this.client).get({url:"/v1/user_notifications/{notification_id}",...$})}bulkDeleteUserNotificationsV2($){return($.client??this.client).delete({url:"/v2/user_notifications/bulk",...$,headers:{"Content-Type":"application/json",...$.headers}})}bulkMarkNotificationsDone($){return($.client??this.client).patch({url:"/v2/user_notifications/bulk/done",...$,headers:{"Content-Type":"application/json",...$.headers}})}bulkMarkNotificationsSeen($){return($.client??this.client).patch({url:"/v2/user_notifications/bulk/seen",...$,headers:{"Content-Type":"application/json",...$.headers}})}bulkMarkNotificationsUndone($){return($.client??this.client).patch({url:"/v2/user_notifications/bulk/undone",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteUserNotificationV2($){return($.client??this.client).delete({url:"/v2/user_notifications/{notification_id}",...$})}}function IS({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...Q}){let J,I=Y??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,T=Q.signal??new AbortController().signal;while(!0){if(T.aborted)break;B++;let A=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)A.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:A,signal:T},_=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 H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",k=()=>{try{H.cancel()}catch{}};T.addEventListener("abort",k);try{while(!0){let{done:l,value:r}=await H.read();if(l)break;U+=r,U=U.replace(/\r\n?/g,`+`);try{C=JSON.parse(R),v=!0}catch{C=R}}if(v){if(S)await S(C);if(x)C=await x(C)}if(j?.({data:C,event:y,id:J,retry:V}),F.length)yield C}}}finally{T.removeEventListener("abort",k),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&W>=Z)break;let _=Math.min(V*2**(W-1),X??30000);await I(_)}}}()}}var N5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},U5=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},z5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},Kx=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((Y)=>encodeURIComponent(Y))).join(U5(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=N5(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return fO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},fO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},Yx=({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 Y=[];Object.entries(S).forEach(([Q,J])=>{Y=[...Y,Q,$?J:encodeURIComponent(J)]});let L=Y.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=z5(x),X=Object.entries(S).map(([Y,L])=>fO({allowReserved:$,name:x==="deepObject"?`${j}[${Y}]`:Y,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var I5=/\{[^{}]+\}/g,T5=({path:$,url:O})=>{let j=O,x=O.match(I5);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 Y=$[Z];if(Y===void 0||Y===null)continue;if(Array.isArray(Y)){j=j.replace(S,Kx({explode:K,name:Z,style:X,value:Y}));continue}if(typeof Y==="object"){j=j.replace(S,Yx({explode:K,name:Z,style:X,value:Y,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${fO({name:Z,value:Y})}`);continue}let L=encodeURIComponent(X==="label"?`.${Y}`:Y);j=j.replace(S,L)}return j},JS=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=T5({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function Y1($){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 VS=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var BS={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var WS=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let Y=Kx({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(Y)S.push(Y)}else if(typeof Z==="object"){let Y=Yx({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(Y)S.push(Y)}else{let Y=fO({allowReserved:X.allowReserved,name:K,value:Z});if(Y)S.push(Y)}}return S.join("&")}},LS=($)=>{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},H5=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function NS($){for(let O of $.security??[]){if(H5($,O.name))continue;let j=await VS(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var G1=($)=>JS({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:WS($.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=Qx($.headers,O.headers),j},R5=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},Qx=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?R5(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class Gx{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var US=()=>({error:new Gx,request:new Gx,response:new Gx}),D5=WS({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),_5={"Content-Type":"application/json"},Kj=($={})=>({...BS,headers:_5,parseAs:"auto",querySerializer:D5,...$});var J1=($={})=>{let O=Q1(Kj(),$),j=()=>({...O}),x=(Q)=>{return O=Q1(O,Q),j()},S=US(),K=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:Qx(O.headers,Q.headers),serializedBody:void 0};if(J.security)await NS(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=G1(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,B;try{let{opts:V,url:W}=await K(Q),T={redirect:"follow",...V,body:Y1(V)};z=new Request(W,T);for(let N of S.request.fns)if(N)z=await N(z,V);let A=V.fetch;B=await A(z);for(let N of S.response.fns)if(N)B=await N(B,z,V);let D={request:z,response:B};if(B.ok){let N=(V.parseAs==="auto"?LS(B.headers.get("Content-Type")):V.parseAs)??"json";if(B.status===204||B.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await B[N]();break;case"formData":U=new FormData;break;case"stream":U=B.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await B[N]();break;case"json":{let U=await B.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?B.body:{data:B.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let _=await B.text(),q;try{q=JSON.parse(_)}catch{}throw q??_}catch(V){let W=V;for(let T of S.error.fns)if(T)W=await T(W,B,z,Q);if(W=W||{},J)throw W;return I==="data"?void 0:{error:W,request:z,response:B}}},X=(Q)=>(J)=>Z({...J,method:Q}),Y=(Q)=>async(J)=>{let{opts:I,url:z}=await K(J);return QS({...I,body:I.body,method:Q,onRequest:async(B,V)=>{let W=new Request(B,V);for(let T of S.request.fns)if(T)W=await T(W,I);return W},serializedBody:Y1(I),url:z})};return{buildUrl:(Q)=>G1({...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:Y("CONNECT"),delete:Y("DELETE"),get:Y("GET"),head:Y("HEAD"),options:Y("OPTIONS"),patch:Y("PATCH"),post:Y("POST"),put:Y("PUT"),trace:Y("TRACE")},trace:X("TRACE")}};var zS=J1(Kj());class IS{client;constructor($){this.client=$?.client??zS}}class TS{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class Jx extends IS{static __registry=new TS;constructor($){super($);Jx.__registry.set(this,$?.key)}healthHandler($){return($?.client??this.client).get({url:"/health",...$})}getUnsubscribes($){return($?.client??this.client).get({url:"/unsubscribe",...$})}unsubscribeEmail($){return($?.client??this.client).post({url:"/unsubscribe/email",...$})}removeUnsubscribeItem($){return($.client??this.client).delete({url:"/unsubscribe/item/{item_type}/{item_id}",...$})}unsubscribeItem($){return($.client??this.client).post({url:"/unsubscribe/item/{item_type}/{item_id}",...$})}removeUnsubscribeAll($){return($?.client??this.client).delete({url:"/unsubscribe/mute",...$})}unsubscribeAll($){return($?.client??this.client).post({url:"/unsubscribe/mute",...$})}listTypedNotifications($){return($?.client??this.client).get({url:"/v1/user_notifications",...$})}bulkGetTypedNotificationsByEventItemIds($){return($.client??this.client).post({url:"/v1/user_notifications/item/bulk",...$,headers:{"Content-Type":"application/json",...$.headers}})}getTypedNotificationsByEventItemId($){return($.client??this.client).get({url:"/v1/user_notifications/item/{event_item_id}",...$})}getNotificationTypePreferences($){return($?.client??this.client).get({url:"/v1/user_notifications/preferences",...$})}disableNotificationType($){return($.client??this.client).put({url:"/v1/user_notifications/preferences/{notification_event_type}/disable",...$})}enableNotificationType($){return($.client??this.client).put({url:"/v1/user_notifications/preferences/{notification_event_type}/enable",...$})}getTypedNotificationById($){return($.client??this.client).get({url:"/v1/user_notifications/{notification_id}",...$})}bulkDeleteUserNotificationsV2($){return($.client??this.client).delete({url:"/v2/user_notifications/bulk",...$,headers:{"Content-Type":"application/json",...$.headers}})}bulkMarkNotificationsDone($){return($.client??this.client).patch({url:"/v2/user_notifications/bulk/done",...$,headers:{"Content-Type":"application/json",...$.headers}})}bulkMarkNotificationsSeen($){return($.client??this.client).patch({url:"/v2/user_notifications/bulk/seen",...$,headers:{"Content-Type":"application/json",...$.headers}})}bulkMarkNotificationsUndone($){return($.client??this.client).patch({url:"/v2/user_notifications/bulk/undone",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteUserNotificationV2($){return($.client??this.client).delete({url:"/v2/user_notifications/{notification_id}",...$})}}function HS({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...Q}){let J,I=Y??((V)=>new Promise((W)=>setTimeout(W,V)));return{stream:async function*(){let V=K??3000,W=0,T=Q.signal??new AbortController().signal;while(!0){if(T.aborted)break;W++;let A=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)A.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:A,signal:T},_=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 H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",k=()=>{try{H.cancel()}catch{}};T.addEventListener("abort",k);try{while(!0){let{done:l,value:r}=await H.read();if(l)break;U+=r,U=U.replace(/\r\n?/g,``);let g=U.split(``);U=g.pop()??"";for(let p of g){let a=p.split(``),F=[],y;for(let R of a)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))y=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let h=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(h))V=h}let C,v=!1;if(F.length){let R=F.join(`-`);try{C=JSON.parse(R),v=!0}catch{C=R}}if(v){if(S)await S(C);if(x)C=await x(C)}if(j?.({data:C,event:y,id:J,retry:V}),F.length)yield C}}}finally{T.removeEventListener("abort",k),H.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 D5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},_5=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},C5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},Jx=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((Y)=>encodeURIComponent(Y))).join(_5(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=D5(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return fO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},fO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},Vx=({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 Y=[];Object.entries(S).forEach(([Q,J])=>{Y=[...Y,Q,$?J:encodeURIComponent(J)]});let L=Y.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=C5(x),X=Object.entries(S).map(([Y,L])=>fO({allowReserved:$,name:x==="deepObject"?`${j}[${Y}]`:Y,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var P5=/\{[^{}]+\}/g,M5=({path:$,url:O})=>{let j=O,x=O.match(P5);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 Y=$[Z];if(Y===void 0||Y===null)continue;if(Array.isArray(Y)){j=j.replace(S,Jx({explode:K,name:Z,style:X,value:Y}));continue}if(typeof Y==="object"){j=j.replace(S,Vx({explode:K,name:Z,style:X,value:Y,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${fO({name:Z,value:Y})}`);continue}let L=encodeURIComponent(X==="label"?`.${Y}`:Y);j=j.replace(S,L)}return j},TS=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=M5({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function Q1($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var HS=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var RS={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var DS=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let Y=Jx({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(Y)S.push(Y)}else if(typeof Z==="object"){let Y=Vx({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(Y)S.push(Y)}else{let Y=fO({allowReserved:X.allowReserved,name:K,value:Z});if(Y)S.push(Y)}}return S.join("&")}},_S=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},A5=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function CS($){for(let O of $.security??[]){if(A5($,O.name))continue;let j=await HS(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var J1=($)=>TS({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:DS($.querySerializer),url:$.url}),V1=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=Bx($.headers,O.headers),j},F5=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},Bx=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?F5(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 Wx{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 PS=()=>({error:new Wx,request:new Wx,response:new Wx}),E5=DS({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),w5={"Content-Type":"application/json"},Kj=($={})=>({...RS,headers:w5,parseAs:"auto",querySerializer:E5,...$});var W1=($={})=>{let O=V1(Kj(),$),j=()=>({...O}),x=(Q)=>{return O=V1(O,Q),j()},S=PS(),K=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:Bx(O.headers,Q.headers),serializedBody:void 0};if(J.security)await CS(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=J1(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),T={redirect:"follow",...V,body:Q1(V)};z=new Request(B,T);for(let N of S.request.fns)if(N)z=await N(z,V);let A=V.fetch;W=await A(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"?_S(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await W[N]();break;case"json":{let U=await W.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let _=await W.text(),q;try{q=JSON.parse(_)}catch{}throw q??_}catch(V){let B=V;for(let T of S.error.fns)if(T)B=await T(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}),Y=(Q)=>async(J)=>{let{opts:I,url:z}=await K(J);return IS({...I,body:I.body,method:Q,onRequest:async(W,V)=>{let B=new Request(W,V);for(let T of S.request.fns)if(T)B=await T(B,I);return B},serializedBody:Q1(I),url:z})};return{buildUrl:(Q)=>J1({...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:Y("CONNECT"),delete:Y("DELETE"),get:Y("GET"),head:Y("HEAD"),options:Y("OPTIONS"),patch:Y("PATCH"),post:Y("POST"),put:Y("PUT"),trace:Y("TRACE")},trace:X("TRACE")}};var MS=W1(Kj());class AS{client;constructor($){this.client=$?.client??MS}}class FS{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class Lx extends AS{static __registry=new FS;constructor($){super($);Lx.__registry.set(this,$?.key)}listProperties($){return($.client??this.client).get({url:"/properties/definitions",...$})}createPropertyDefinition($){return($.client??this.client).post({url:"/properties/definitions",...$,headers:{"Content-Type":"application/json",...$.headers}})}deletePropertyDefinition($){return($.client??this.client).delete({url:"/properties/definitions/{definition_id}",...$})}getPropertyDefinition($){return($.client??this.client).get({url:"/properties/definitions/{definition_id}",...$})}getPropertyOptions($){return($.client??this.client).get({url:"/properties/definitions/{definition_id}/options",...$})}addPropertyOption($){return($.client??this.client).post({url:"/properties/definitions/{definition_id}/options",...$,headers:{"Content-Type":"application/json",...$.headers}})}deletePropertyOption($){return($.client??this.client).delete({url:"/properties/definitions/{definition_id}/options/{option_id}",...$})}updatePropertyOption($){return($.client??this.client).patch({url:"/properties/definitions/{definition_id}/options/{option_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getBulkEntityProperties($){return($.client??this.client).post({url:"/properties/entities/bulk",...$,headers:{"Content-Type":"application/json",...$.headers}})}getEntityProperties($){return($.client??this.client).get({url:"/properties/entities/{entity_type}/{entity_id}",...$})}bulkUpdateEntityPropertyOptions($){return($.client??this.client).post({url:"/properties/entities/{entity_type}/{entity_id}/options/bulk",...$,headers:{"Content-Type":"application/json",...$.headers}})}setEntityProperty($){return($.client??this.client).put({url:"/properties/entities/{entity_type}/{entity_id}/{property_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}removeEntityPropertyOption($){return($.client??this.client).delete({url:"/properties/entities/{entity_type}/{entity_id}/{property_id}/options/{option_id}",...$})}addEntityPropertyOption($){return($.client??this.client).post({url:"/properties/entities/{entity_type}/{entity_id}/{property_id}/options/{option_id}",...$})}deleteEntityProperty($){return($.client??this.client).delete({url:"/properties/entity_properties/{entity_property_id}",...$})}bulkUpdateEntitiesPropertyOptions($){return($.client??this.client).post({url:"/properties/options/bulk",...$,headers:{"Content-Type":"application/json",...$.headers}})}listTags($){return($?.client??this.client).get({url:"/properties/tags",...$})}ensureTagSet($){return($.client??this.client).post({url:"/properties/tags",...$,headers:{"Content-Type":"application/json",...$.headers}})}mergeTag($){return($.client??this.client).post({url:"/properties/tags/merge",...$,headers:{"Content-Type":"application/json",...$.headers}})}promoteTag($){return($.client??this.client).post({url:"/properties/tags/promote",...$,headers:{"Content-Type":"application/json",...$.headers}})}}function ES({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...Q}){let J,I=Y??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,T=Q.signal??new AbortController().signal;while(!0){if(T.aborted)break;B++;let A=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)A.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:A,signal:T},_=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 H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",k=()=>{try{H.cancel()}catch{}};T.addEventListener("abort",k);try{while(!0){let{done:l,value:r}=await H.read();if(l)break;U+=r,U=U.replace(/\r\n?/g,`+`);try{C=JSON.parse(R),v=!0}catch{C=R}}if(v){if(S)await S(C);if(x)C=await x(C)}if(j?.({data:C,event:y,id:J,retry:V}),F.length)yield C}}}finally{T.removeEventListener("abort",k),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&W>=Z)break;let _=Math.min(V*2**(W-1),X??30000);await I(_)}}}()}}var C5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},M5=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},P5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},Vx=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((Y)=>encodeURIComponent(Y))).join(M5(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=C5(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return bO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},bO=({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)}`},Bx=({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 Y=[];Object.entries(S).forEach(([Q,J])=>{Y=[...Y,Q,$?J:encodeURIComponent(J)]});let L=Y.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=P5(x),X=Object.entries(S).map(([Y,L])=>bO({allowReserved:$,name:x==="deepObject"?`${j}[${Y}]`:Y,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var A5=/\{[^{}]+\}/g,F5=({path:$,url:O})=>{let j=O,x=O.match(A5);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 Y=$[Z];if(Y===void 0||Y===null)continue;if(Array.isArray(Y)){j=j.replace(S,Vx({explode:K,name:Z,style:X,value:Y}));continue}if(typeof Y==="object"){j=j.replace(S,Bx({explode:K,name:Z,style:X,value:Y,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${bO({name:Z,value:Y})}`);continue}let L=encodeURIComponent(X==="label"?`.${Y}`:Y);j=j.replace(S,L)}return j},RS=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=F5({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function V1($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var DS=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var _S={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var CS=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let Y=Vx({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(Y)S.push(Y)}else if(typeof Z==="object"){let Y=Bx({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(Y)S.push(Y)}else{let Y=bO({allowReserved:X.allowReserved,name:K,value:Z});if(Y)S.push(Y)}}return S.join("&")}},MS=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},E5=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function PS($){for(let O of $.security??[]){if(E5($,O.name))continue;let j=await DS(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var B1=($)=>RS({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:CS($.querySerializer),url:$.url}),W1=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=Lx($.headers,O.headers),j},w5=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},Lx=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?w5(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 Wx{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 AS=()=>({error:new Wx,request:new Wx,response:new Wx}),q5=CS({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),f5={"Content-Type":"application/json"},Yj=($={})=>({..._S,headers:f5,parseAs:"auto",querySerializer:q5,...$});var L1=($={})=>{let O=W1(Yj(),$),j=()=>({...O}),x=(Q)=>{return O=W1(O,Q),j()},S=AS(),K=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:Lx(O.headers,Q.headers),serializedBody:void 0};if(J.security)await PS(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,B;try{let{opts:V,url:W}=await K(Q),T={redirect:"follow",...V,body:V1(V)};z=new Request(W,T);for(let N of S.request.fns)if(N)z=await N(z,V);let A=V.fetch;B=await A(z);for(let N of S.response.fns)if(N)B=await N(B,z,V);let D={request:z,response:B};if(B.ok){let N=(V.parseAs==="auto"?MS(B.headers.get("Content-Type")):V.parseAs)??"json";if(B.status===204||B.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await B[N]();break;case"formData":U=new FormData;break;case"stream":U=B.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await B[N]();break;case"json":{let U=await B.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?B.body:{data:B.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let _=await B.text(),q;try{q=JSON.parse(_)}catch{}throw q??_}catch(V){let W=V;for(let T of S.error.fns)if(T)W=await T(W,B,z,Q);if(W=W||{},J)throw W;return I==="data"?void 0:{error:W,request:z,response:B}}},X=(Q)=>(J)=>Z({...J,method:Q}),Y=(Q)=>async(J)=>{let{opts:I,url:z}=await K(J);return HS({...I,body:I.body,method:Q,onRequest:async(B,V)=>{let W=new Request(B,V);for(let T of S.request.fns)if(T)W=await T(W,I);return W},serializedBody:V1(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:Y("CONNECT"),delete:Y("DELETE"),get:Y("GET"),head:Y("HEAD"),options:Y("OPTIONS"),patch:Y("PATCH"),post:Y("POST"),put:Y("PUT"),trace:Y("TRACE")},trace:X("TRACE")}};var FS=L1(Yj());class ES{client;constructor($){this.client=$?.client??FS}}class wS{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 Nx extends ES{static __registry=new wS;constructor($){super($);Nx.__registry.set(this,$?.key)}listProperties($){return($.client??this.client).get({url:"/properties/definitions",...$})}createPropertyDefinition($){return($.client??this.client).post({url:"/properties/definitions",...$,headers:{"Content-Type":"application/json",...$.headers}})}deletePropertyDefinition($){return($.client??this.client).delete({url:"/properties/definitions/{definition_id}",...$})}getPropertyDefinition($){return($.client??this.client).get({url:"/properties/definitions/{definition_id}",...$})}getPropertyOptions($){return($.client??this.client).get({url:"/properties/definitions/{definition_id}/options",...$})}addPropertyOption($){return($.client??this.client).post({url:"/properties/definitions/{definition_id}/options",...$,headers:{"Content-Type":"application/json",...$.headers}})}deletePropertyOption($){return($.client??this.client).delete({url:"/properties/definitions/{definition_id}/options/{option_id}",...$})}updatePropertyOption($){return($.client??this.client).patch({url:"/properties/definitions/{definition_id}/options/{option_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getBulkEntityProperties($){return($.client??this.client).post({url:"/properties/entities/bulk",...$,headers:{"Content-Type":"application/json",...$.headers}})}getEntityProperties($){return($.client??this.client).get({url:"/properties/entities/{entity_type}/{entity_id}",...$})}bulkUpdateEntityPropertyOptions($){return($.client??this.client).post({url:"/properties/entities/{entity_type}/{entity_id}/options/bulk",...$,headers:{"Content-Type":"application/json",...$.headers}})}setEntityProperty($){return($.client??this.client).put({url:"/properties/entities/{entity_type}/{entity_id}/{property_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}removeEntityPropertyOption($){return($.client??this.client).delete({url:"/properties/entities/{entity_type}/{entity_id}/{property_id}/options/{option_id}",...$})}addEntityPropertyOption($){return($.client??this.client).post({url:"/properties/entities/{entity_type}/{entity_id}/{property_id}/options/{option_id}",...$})}deleteEntityProperty($){return($.client??this.client).delete({url:"/properties/entity_properties/{entity_property_id}",...$})}bulkUpdateEntitiesPropertyOptions($){return($.client??this.client).post({url:"/properties/options/bulk",...$,headers:{"Content-Type":"application/json",...$.headers}})}listTags($){return($?.client??this.client).get({url:"/properties/tags",...$})}ensureTagSet($){return($.client??this.client).post({url:"/properties/tags",...$,headers:{"Content-Type":"application/json",...$.headers}})}mergeTag($){return($.client??this.client).post({url:"/properties/tags/merge",...$,headers:{"Content-Type":"application/json",...$.headers}})}promoteTag($){return($.client??this.client).post({url:"/properties/tags/promote",...$,headers:{"Content-Type":"application/json",...$.headers}})}}function qS({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...Q}){let J,I=Y??((V)=>new Promise((W)=>setTimeout(W,V)));return{stream:async function*(){let V=K??3000,W=0,T=Q.signal??new AbortController().signal;while(!0){if(T.aborted)break;W++;let A=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)A.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:A,signal:T},_=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 H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",k=()=>{try{H.cancel()}catch{}};T.addEventListener("abort",k);try{while(!0){let{done:l,value:r}=await H.read();if(l)break;U+=r,U=U.replace(/\r\n?/g,``);let g=U.split(``);U=g.pop()??"";for(let p of g){let a=p.split(``),F=[],y;for(let R of a)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))y=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let h=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(h))V=h}let C,v=!1;if(F.length){let R=F.join(`-`);try{C=JSON.parse(R),v=!0}catch{C=R}}if(v){if(S)await S(C);if(x)C=await x(C)}if(j?.({data:C,event:y,id:J,retry:V}),F.length)yield C}}}finally{T.removeEventListener("abort",k),H.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 q5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},f5=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},b5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},Nx=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((Y)=>encodeURIComponent(Y))).join(f5(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=q5(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return bO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},bO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},Ux=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let Y=[];Object.entries(S).forEach(([Q,J])=>{Y=[...Y,Q,$?J:encodeURIComponent(J)]});let L=Y.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=b5(x),X=Object.entries(S).map(([Y,L])=>bO({allowReserved:$,name:x==="deepObject"?`${j}[${Y}]`:Y,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var k5=/\{[^{}]+\}/g,g5=({path:$,url:O})=>{let j=O,x=O.match(k5);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 Y=$[Z];if(Y===void 0||Y===null)continue;if(Array.isArray(Y)){j=j.replace(S,Nx({explode:K,name:Z,style:X,value:Y}));continue}if(typeof Y==="object"){j=j.replace(S,Ux({explode:K,name:Z,style:X,value:Y,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${bO({name:Z,value:Y})}`);continue}let L=encodeURIComponent(X==="label"?`.${Y}`:Y);j=j.replace(S,L)}return j},wS=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=g5({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function B1($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var qS=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var fS={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var bS=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let Y=Nx({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(Y)S.push(Y)}else if(typeof Z==="object"){let Y=Ux({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(Y)S.push(Y)}else{let Y=bO({allowReserved:X.allowReserved,name:K,value:Z});if(Y)S.push(Y)}}return S.join("&")}},kS=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},y5=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function gS($){for(let O of $.security??[]){if(y5($,O.name))continue;let j=await qS(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var L1=($)=>wS({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:bS($.querySerializer),url:$.url}),N1=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=Ix($.headers,O.headers),j},v5=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},Ix=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?v5(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 zx{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var yS=()=>({error:new zx,request:new zx,response:new zx}),h5=bS({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),m5={"Content-Type":"application/json"},Yj=($={})=>({...fS,headers:m5,parseAs:"auto",querySerializer:h5,...$});var U1=($={})=>{let O=N1(Yj(),$),j=()=>({...O}),x=(Q)=>{return O=N1(O,Q),j()},S=yS(),K=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:Ix(O.headers,Q.headers),serializedBody:void 0};if(J.security)await gS(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let I=J,z=L1(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),T={redirect:"follow",...V,body:B1(V)};z=new Request(B,T);for(let N of S.request.fns)if(N)z=await N(z,V);let A=V.fetch;W=await A(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?kS(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await W[N]();break;case"json":{let U=await W.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let _=await W.text(),q;try{q=JSON.parse(_)}catch{}throw q??_}catch(V){let B=V;for(let T of S.error.fns)if(T)B=await T(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}),Y=(Q)=>async(J)=>{let{opts:I,url:z}=await K(J);return ES({...I,body:I.body,method:Q,onRequest:async(W,V)=>{let B=new Request(W,V);for(let T of S.request.fns)if(T)B=await T(B,I);return B},serializedBody:B1(I),url:z})};return{buildUrl:(Q)=>L1({...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:Y("CONNECT"),delete:Y("DELETE"),get:Y("GET"),head:Y("HEAD"),options:Y("OPTIONS"),patch:Y("PATCH"),post:Y("POST"),put:Y("PUT"),trace:Y("TRACE")},trace:X("TRACE")}};var vS=U1(Yj());class hS{client;constructor($){this.client=$?.client??vS}}class mS{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class Tx extends hS{static __registry=new mS;constructor($){super($);Tx.__registry.set(this,$?.key)}scheduledActionHealth($){return($?.client??this.client).get({url:"/health",...$})}listScheduledActions($){return($?.client??this.client).get({url:"/scheduled-actions",...$})}createScheduledAction($){return($.client??this.client).post({url:"/scheduled-actions",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteScheduledAction($){return($.client??this.client).delete({url:"/scheduled-actions/{id}",...$})}getScheduledAction($){return($.client??this.client).get({url:"/scheduled-actions/{id}",...$})}updateScheduledAction($){return($.client??this.client).put({url:"/scheduled-actions/{id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}setScheduledActionEnabled($){return($.client??this.client).put({url:"/scheduled-actions/{id}/enabled",...$,headers:{"Content-Type":"application/json",...$.headers}})}executeScheduledActionNow($){return($.client??this.client).post({url:"/scheduled-actions/{id}/execute",...$})}listScheduledActionHistory($){return($.client??this.client).get({url:"/scheduled-actions/{id}/history",...$})}}function cS({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...Q}){let J,I=Y??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,T=Q.signal??new AbortController().signal;while(!0){if(T.aborted)break;B++;let A=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)A.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:A,signal:T},_=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 H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",k=()=>{try{H.cancel()}catch{}};T.addEventListener("abort",k);try{while(!0){let{done:l,value:r}=await H.read();if(l)break;U+=r,U=U.replace(/\r\n?/g,`+`);try{C=JSON.parse(R),v=!0}catch{C=R}}if(v){if(S)await S(C);if(x)C=await x(C)}if(j?.({data:C,event:y,id:J,retry:V}),F.length)yield C}}}finally{T.removeEventListener("abort",k),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&W>=Z)break;let _=Math.min(V*2**(W-1),X??30000);await I(_)}}}()}}var b5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},k5=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},g5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},Ux=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((Y)=>encodeURIComponent(Y))).join(k5(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=b5(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return kO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},kO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},zx=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let Y=[];Object.entries(S).forEach(([Q,J])=>{Y=[...Y,Q,$?J:encodeURIComponent(J)]});let L=Y.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=g5(x),X=Object.entries(S).map(([Y,L])=>kO({allowReserved:$,name:x==="deepObject"?`${j}[${Y}]`:Y,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var y5=/\{[^{}]+\}/g,v5=({path:$,url:O})=>{let j=O,x=O.match(y5);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 Y=$[Z];if(Y===void 0||Y===null)continue;if(Array.isArray(Y)){j=j.replace(S,Ux({explode:K,name:Z,style:X,value:Y}));continue}if(typeof Y==="object"){j=j.replace(S,zx({explode:K,name:Z,style:X,value:Y,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${kO({name:Z,value:Y})}`);continue}let L=encodeURIComponent(X==="label"?`.${Y}`:Y);j=j.replace(S,L)}return j},fS=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=v5({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function N1($){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 bS=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 kS={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var gS=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let Y=Ux({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(Y)S.push(Y)}else if(typeof Z==="object"){let Y=zx({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(Y)S.push(Y)}else{let Y=kO({allowReserved:X.allowReserved,name:K,value:Z});if(Y)S.push(Y)}}return S.join("&")}},yS=($)=>{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},h5=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function vS($){for(let O of $.security??[]){if(h5($,O.name))continue;let j=await bS(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var U1=($)=>fS({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:gS($.querySerializer),url:$.url}),z1=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=Tx($.headers,O.headers),j},m5=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},Tx=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?m5(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 Ix{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 hS=()=>({error:new Ix,request:new Ix,response:new Ix}),c5=gS({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),u5={"Content-Type":"application/json"},Gj=($={})=>({...kS,headers:u5,parseAs:"auto",querySerializer:c5,...$});var I1=($={})=>{let O=z1(Gj(),$),j=()=>({...O}),x=(Q)=>{return O=z1(O,Q),j()},S=hS(),K=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:Tx(O.headers,Q.headers),serializedBody:void 0};if(J.security)await vS(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=U1(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,B;try{let{opts:V,url:W}=await K(Q),T={redirect:"follow",...V,body:N1(V)};z=new Request(W,T);for(let N of S.request.fns)if(N)z=await N(z,V);let A=V.fetch;B=await A(z);for(let N of S.response.fns)if(N)B=await N(B,z,V);let D={request:z,response:B};if(B.ok){let N=(V.parseAs==="auto"?yS(B.headers.get("Content-Type")):V.parseAs)??"json";if(B.status===204||B.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await B[N]();break;case"formData":U=new FormData;break;case"stream":U=B.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await B[N]();break;case"json":{let U=await B.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?B.body:{data:B.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let _=await B.text(),q;try{q=JSON.parse(_)}catch{}throw q??_}catch(V){let W=V;for(let T of S.error.fns)if(T)W=await T(W,B,z,Q);if(W=W||{},J)throw W;return I==="data"?void 0:{error:W,request:z,response:B}}},X=(Q)=>(J)=>Z({...J,method:Q}),Y=(Q)=>async(J)=>{let{opts:I,url:z}=await K(J);return qS({...I,body:I.body,method:Q,onRequest:async(B,V)=>{let W=new Request(B,V);for(let T of S.request.fns)if(T)W=await T(W,I);return W},serializedBody:N1(I),url:z})};return{buildUrl:(Q)=>U1({...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:Y("CONNECT"),delete:Y("DELETE"),get:Y("GET"),head:Y("HEAD"),options:Y("OPTIONS"),patch:Y("PATCH"),post:Y("POST"),put:Y("PUT"),trace:Y("TRACE")},trace:X("TRACE")}};var mS=I1(Gj());class cS{client;constructor($){this.client=$?.client??mS}}class uS{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 Hx extends cS{static __registry=new uS;constructor($){super($);Hx.__registry.set(this,$?.key)}scheduledActionHealth($){return($?.client??this.client).get({url:"/health",...$})}listScheduledActions($){return($?.client??this.client).get({url:"/scheduled-actions",...$})}createScheduledAction($){return($.client??this.client).post({url:"/scheduled-actions",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteScheduledAction($){return($.client??this.client).delete({url:"/scheduled-actions/{id}",...$})}getScheduledAction($){return($.client??this.client).get({url:"/scheduled-actions/{id}",...$})}updateScheduledAction($){return($.client??this.client).put({url:"/scheduled-actions/{id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}setScheduledActionEnabled($){return($.client??this.client).put({url:"/scheduled-actions/{id}/enabled",...$,headers:{"Content-Type":"application/json",...$.headers}})}executeScheduledActionNow($){return($.client??this.client).post({url:"/scheduled-actions/{id}/execute",...$})}listScheduledActionHistory($){return($.client??this.client).get({url:"/scheduled-actions/{id}/history",...$})}}function dS({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...Q}){let J,I=Y??((V)=>new Promise((W)=>setTimeout(W,V)));return{stream:async function*(){let V=K??3000,W=0,T=Q.signal??new AbortController().signal;while(!0){if(T.aborted)break;W++;let A=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)A.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:A,signal:T},_=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 H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",k=()=>{try{H.cancel()}catch{}};T.addEventListener("abort",k);try{while(!0){let{done:l,value:r}=await H.read();if(l)break;U+=r,U=U.replace(/\r\n?/g,``);let g=U.split(``);U=g.pop()??"";for(let p of g){let a=p.split(``),F=[],y;for(let R of a)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))y=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let h=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(h))V=h}let C,v=!1;if(F.length){let R=F.join(`-`);try{C=JSON.parse(R),v=!0}catch{C=R}}if(v){if(S)await S(C);if(x)C=await x(C)}if(j?.({data:C,event:y,id:J,retry:V}),F.length)yield C}}}finally{T.removeEventListener("abort",k),H.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 c5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},u5=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},d5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},Hx=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((Y)=>encodeURIComponent(Y))).join(u5(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=c5(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return kO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},kO=({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)}`},Rx=({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 Y=[];Object.entries(S).forEach(([Q,J])=>{Y=[...Y,Q,$?J:encodeURIComponent(J)]});let L=Y.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=d5(x),X=Object.entries(S).map(([Y,L])=>kO({allowReserved:$,name:x==="deepObject"?`${j}[${Y}]`:Y,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var l5=/\{[^{}]+\}/g,r5=({path:$,url:O})=>{let j=O,x=O.match(l5);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 Y=$[Z];if(Y===void 0||Y===null)continue;if(Array.isArray(Y)){j=j.replace(S,Hx({explode:K,name:Z,style:X,value:Y}));continue}if(typeof Y==="object"){j=j.replace(S,Rx({explode:K,name:Z,style:X,value:Y,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${kO({name:Z,value:Y})}`);continue}let L=encodeURIComponent(X==="label"?`.${Y}`:Y);j=j.replace(S,L)}return j},uS=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=r5({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function z1($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var dS=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var lS={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var rS=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let Y=Hx({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(Y)S.push(Y)}else if(typeof Z==="object"){let Y=Rx({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(Y)S.push(Y)}else{let Y=kO({allowReserved:X.allowReserved,name:K,value:Z});if(Y)S.push(Y)}}return S.join("&")}},pS=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},p5=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function aS($){for(let O of $.security??[]){if(p5($,O.name))continue;let j=await dS(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var I1=($)=>uS({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:rS($.querySerializer),url:$.url}),T1=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=_x($.headers,O.headers),j},a5=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},_x=(...$)=>{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 Dx{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var iS=()=>({error:new Dx,request:new Dx,response:new Dx}),i5=rS({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),n5={"Content-Type":"application/json"},Gj=($={})=>({...lS,headers:n5,parseAs:"auto",querySerializer:i5,...$});var H1=($={})=>{let O=T1(Gj(),$),j=()=>({...O}),x=(Q)=>{return O=T1(O,Q),j()},S=iS(),K=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:_x(O.headers,Q.headers),serializedBody:void 0};if(J.security)await aS(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let I=J,z=I1(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),T={redirect:"follow",...V,body:z1(V)};z=new Request(B,T);for(let N of S.request.fns)if(N)z=await N(z,V);let A=V.fetch;W=await A(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?pS(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await W[N]();break;case"json":{let U=await W.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let _=await W.text(),q;try{q=JSON.parse(_)}catch{}throw q??_}catch(V){let B=V;for(let T of S.error.fns)if(T)B=await T(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}),Y=(Q)=>async(J)=>{let{opts:I,url:z}=await K(J);return cS({...I,body:I.body,method:Q,onRequest:async(W,V)=>{let B=new Request(W,V);for(let T of S.request.fns)if(T)B=await T(B,I);return B},serializedBody:z1(I),url:z})};return{buildUrl:(Q)=>I1({...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:Y("CONNECT"),delete:Y("DELETE"),get:Y("GET"),head:Y("HEAD"),options:Y("OPTIONS"),patch:Y("PATCH"),post:Y("POST"),put:Y("PUT"),trace:Y("TRACE")},trace:X("TRACE")}};var nS=H1(Gj());class sS{client;constructor($){this.client=$?.client??nS}}class tS{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class Cx extends sS{static __registry=new tS;constructor($){super($);Cx.__registry.set(this,$?.key)}unifiedSearch($){return($.client??this.client).post({url:"/search",...$,headers:{"Content-Type":"application/json",...$.headers}})}simpleUnifiedSearch($){return($.client??this.client).post({url:"/search/simple",...$,headers:{"Content-Type":"application/json",...$.headers}})}}var eS=($,O,j)=>{if(typeof j==="string"||j instanceof Blob)$.append(O,j);else if(j instanceof Date)$.append(O,j.toISOString());else $.append(O,JSON.stringify(j))};var R1={bodySerializer:($)=>{let O=new FormData;return Object.entries($).forEach(([j,x])=>{if(x===void 0||x===null)return;if(Array.isArray(x))x.forEach((S)=>eS(O,j,S));else eS(O,j,x)}),O}},D1={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};function oS({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...Q}){let J,I=Y??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,T=Q.signal??new AbortController().signal;while(!0){if(T.aborted)break;B++;let A=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)A.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:A,signal:T},_=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 H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",k=()=>{try{H.cancel()}catch{}};T.addEventListener("abort",k);try{while(!0){let{done:l,value:r}=await H.read();if(l)break;U+=r,U=U.replace(/\r\n?/g,`+`);try{C=JSON.parse(R),v=!0}catch{C=R}}if(v){if(S)await S(C);if(x)C=await x(C)}if(j?.({data:C,event:y,id:J,retry:V}),F.length)yield C}}}finally{T.removeEventListener("abort",k),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&W>=Z)break;let _=Math.min(V*2**(W-1),X??30000);await I(_)}}}()}}var d5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},l5=($)=>{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"&"}},Rx=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((Y)=>encodeURIComponent(Y))).join(l5(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=d5(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return gO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},gO=({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)}`},Dx=({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 Y=[];Object.entries(S).forEach(([Q,J])=>{Y=[...Y,Q,$?J:encodeURIComponent(J)]});let L=Y.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(([Y,L])=>gO({allowReserved:$,name:x==="deepObject"?`${j}[${Y}]`:Y,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var p5=/\{[^{}]+\}/g,a5=({path:$,url:O})=>{let j=O,x=O.match(p5);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 Y=$[Z];if(Y===void 0||Y===null)continue;if(Array.isArray(Y)){j=j.replace(S,Rx({explode:K,name:Z,style:X,value:Y}));continue}if(typeof Y==="object"){j=j.replace(S,Dx({explode:K,name:Z,style:X,value:Y,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${gO({name:Z,value:Y})}`);continue}let L=encodeURIComponent(X==="label"?`.${Y}`:Y);j=j.replace(S,L)}return j},lS=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=a5({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function T1($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var rS=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var pS={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var aS=({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 Y=Rx({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(Y)S.push(Y)}else if(typeof Z==="object"){let Y=Dx({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(Y)S.push(Y)}else{let Y=gO({allowReserved:X.allowReserved,name:K,value:Z});if(Y)S.push(Y)}}return S.join("&")}},iS=($)=>{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},i5=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function nS($){for(let O of $.security??[]){if(i5($,O.name))continue;let j=await rS(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var H1=($)=>lS({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:aS($.querySerializer),url:$.url}),R1=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=Cx($.headers,O.headers),j},n5=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},Cx=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?n5(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class _x{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var sS=()=>({error:new _x,request:new _x,response:new _x}),s5=aS({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),t5={"Content-Type":"application/json"},Qj=($={})=>({...pS,headers:t5,parseAs:"auto",querySerializer:s5,...$});var D1=($={})=>{let O=R1(Qj(),$),j=()=>({...O}),x=(Q)=>{return O=R1(O,Q),j()},S=sS(),K=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:Cx(O.headers,Q.headers),serializedBody:void 0};if(J.security)await nS(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=H1(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,B;try{let{opts:V,url:W}=await K(Q),T={redirect:"follow",...V,body:T1(V)};z=new Request(W,T);for(let N of S.request.fns)if(N)z=await N(z,V);let A=V.fetch;B=await A(z);for(let N of S.response.fns)if(N)B=await N(B,z,V);let D={request:z,response:B};if(B.ok){let N=(V.parseAs==="auto"?iS(B.headers.get("Content-Type")):V.parseAs)??"json";if(B.status===204||B.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await B[N]();break;case"formData":U=new FormData;break;case"stream":U=B.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await B[N]();break;case"json":{let U=await B.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?B.body:{data:B.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let _=await B.text(),q;try{q=JSON.parse(_)}catch{}throw q??_}catch(V){let W=V;for(let T of S.error.fns)if(T)W=await T(W,B,z,Q);if(W=W||{},J)throw W;return I==="data"?void 0:{error:W,request:z,response:B}}},X=(Q)=>(J)=>Z({...J,method:Q}),Y=(Q)=>async(J)=>{let{opts:I,url:z}=await K(J);return dS({...I,body:I.body,method:Q,onRequest:async(B,V)=>{let W=new Request(B,V);for(let T of S.request.fns)if(T)W=await T(W,I);return W},serializedBody:T1(I),url:z})};return{buildUrl:(Q)=>H1({...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:Y("CONNECT"),delete:Y("DELETE"),get:Y("GET"),head:Y("HEAD"),options:Y("OPTIONS"),patch:Y("PATCH"),post:Y("POST"),put:Y("PUT"),trace:Y("TRACE")},trace:X("TRACE")}};var tS=D1(Qj());class eS{client;constructor($){this.client=$?.client??tS}}class oS{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 Mx extends eS{static __registry=new oS;constructor($){super($);Mx.__registry.set(this,$?.key)}unifiedSearch($){return($.client??this.client).post({url:"/search",...$,headers:{"Content-Type":"application/json",...$.headers}})}simpleUnifiedSearch($){return($.client??this.client).post({url:"/search/simple",...$,headers:{"Content-Type":"application/json",...$.headers}})}}var $6=($,O,j)=>{if(typeof j==="string"||j instanceof Blob)$.append(O,j);else if(j instanceof Date)$.append(O,j.toISOString());else $.append(O,JSON.stringify(j))};var _1={bodySerializer:($)=>{let O=new FormData;return Object.entries($).forEach(([j,x])=>{if(x===void 0||x===null)return;if(Array.isArray(x))x.forEach((S)=>$6(O,j,S));else $6(O,j,x)}),O}},C1={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};function O6({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...Q}){let J,I=Y??((V)=>new Promise((W)=>setTimeout(W,V)));return{stream:async function*(){let V=K??3000,W=0,T=Q.signal??new AbortController().signal;while(!0){if(T.aborted)break;W++;let A=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)A.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:A,signal:T},_=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 H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",k=()=>{try{H.cancel()}catch{}};T.addEventListener("abort",k);try{while(!0){let{done:l,value:r}=await H.read();if(l)break;U+=r,U=U.replace(/\r\n?/g,``);let g=U.split(``);U=g.pop()??"";for(let p of g){let a=p.split(``),F=[],y;for(let R of a)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))y=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let h=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(h))V=h}let C,v=!1;if(F.length){let R=F.join(`-`);try{C=JSON.parse(R),v=!0}catch{C=R}}if(v){if(S)await S(C);if(x)C=await x(C)}if(j?.({data:C,event:y,id:J,retry:V}),F.length)yield C}}}finally{T.removeEventListener("abort",k),H.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 s5=($)=>{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","}},e5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},Px=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((Y)=>encodeURIComponent(Y))).join(t5(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=s5(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return gO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},gO=({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)}`},Mx=({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 Y=[];Object.entries(S).forEach(([Q,J])=>{Y=[...Y,Q,$?J:encodeURIComponent(J)]});let L=Y.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=e5(x),X=Object.entries(S).map(([Y,L])=>gO({allowReserved:$,name:x==="deepObject"?`${j}[${Y}]`:Y,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var o5=/\{[^{}]+\}/g,$4=({path:$,url:O})=>{let j=O,x=O.match(o5);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 Y=$[Z];if(Y===void 0||Y===null)continue;if(Array.isArray(Y)){j=j.replace(S,Px({explode:K,name:Z,style:X,value:Y}));continue}if(typeof Y==="object"){j=j.replace(S,Mx({explode:K,name:Z,style:X,value:Y,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${gO({name:Z,value:Y})}`);continue}let L=encodeURIComponent(X==="label"?`.${Y}`:Y);j=j.replace(S,L)}return j},$6=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=$4({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function _1($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var O6=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var j6=({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 Y=Px({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(Y)S.push(Y)}else if(typeof Z==="object"){let Y=Mx({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(Y)S.push(Y)}else{let Y=gO({allowReserved:X.allowReserved,name:K,value:Z});if(Y)S.push(Y)}}return S.join("&")}},x6=($)=>{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},O4=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function S6($){for(let O of $.security??[]){if(O4($,O.name))continue;let j=await O6(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var C1=($)=>$6({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:j6($.querySerializer),url:$.url}),P1=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=Fx($.headers,O.headers),j},j4=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},Fx=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?j4(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 Ax{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 Z6=()=>({error:new Ax,request:new Ax,response:new Ax}),x4=j6({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),S4={"Content-Type":"application/json"},Qj=($={})=>({...D1,headers:S4,parseAs:"auto",querySerializer:x4,...$});var Jj=($={})=>{let O=P1(Qj(),$),j=()=>({...O}),x=(Q)=>{return O=P1(O,Q),j()},S=Z6(),K=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:Fx(O.headers,Q.headers),serializedBody:void 0};if(J.security)await S6(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=C1(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),T={redirect:"follow",...V,body:_1(V)};z=new Request(B,T);for(let N of S.request.fns)if(N)z=await N(z,V);let A=V.fetch;W=await A(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"?x6(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await W[N]();break;case"json":{let U=await W.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let _=await W.text(),q;try{q=JSON.parse(_)}catch{}throw q??_}catch(V){let B=V;for(let T of S.error.fns)if(T)B=await T(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}),Y=(Q)=>async(J)=>{let{opts:I,url:z}=await K(J);return oS({...I,body:I.body,method:Q,onRequest:async(W,V)=>{let B=new Request(W,V);for(let T of S.request.fns)if(T)B=await T(B,I);return B},serializedBody:_1(I),url:z})};return{buildUrl:(Q)=>C1({...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:Y("CONNECT"),delete:Y("DELETE"),get:Y("GET"),head:Y("HEAD"),options:Y("OPTIONS"),patch:Y("PATCH"),post:Y("POST"),put:Y("PUT"),trace:Y("TRACE")},trace:X("TRACE")}};var X6=Jj(Qj());class K6{client;constructor($){this.client=$?.client??X6}}class Y6{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class Ex extends K6{static __registry=new Y6;constructor($){super($);Ex.__registry.set(this,$?.key)}listAgents($){return($?.client??this.client).get({url:"/agents",...$})}createAgent($){return($.client??this.client).post({url:"/agents",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateAgent($){return($.client??this.client).put({url:"/agents/{agent_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteAnchor($){return($.client??this.client).delete({url:"/annotations/anchors",...$,headers:{"Content-Type":"application/json",...$.headers}})}editAnchor($){return($.client??this.client).patch({url:"/annotations/anchors",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDocumentAnchors($){return($.client??this.client).get({url:"/annotations/anchors/document/{document_id}",...$})}createAnchor($){return($.client??this.client).post({url:"/annotations/anchors/document/{document_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getSelfBot($){return($?.client??this.client).get({url:"/bots/me",...$})}getBotOwnerProfiles($){return($?.client??this.client).get({url:"/bots/profiles",...$})}listBotChannels($){return($.client??this.client).get({url:"/bots/{bot_id}/channels",...$})}removeBotFromChannelByBot($){return($.client??this.client).delete({url:"/bots/{bot_id}/channels/{channel_id}",...$})}listOccurrences($){return($.client??this.client).get({url:"/calendar-events",...$})}mentionPreviews($){return($.client??this.client).post({url:"/calendar-events/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}listTeamCalendar($){return($.client??this.client).get({url:"/calendar-events/team",...$})}listTeamOutOfOffice($){return($.client??this.client).get({url:"/calendar-events/team-out-of-office",...$})}eventIcs($){return($.client??this.client).get({url:"/calendar-events/{event_id}/ics",...$})}listJoinRequests($){return($.client??this.client).get({url:"/calendar-events/{event_id}/join-requests",...$})}requestToJoin($){return($.client??this.client).post({url:"/calendar-events/{event_id}/join-requests",...$})}getActiveCalls($){return($?.client??this.client).get({url:"/call/active",...$})}guestCallChatRead($){return($.client??this.client).get({url:"/call/guest-chat/{call_id}",...$})}guestCallChatPost($){return($.client??this.client).post({url:"/call/guest-chat/{call_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}meetingLookup($){return($.client??this.client).get({url:"/call/join/{token}",...$})}meetingGuestJoin($){return($.client??this.client).post({url:"/call/join/{token}",...$,headers:{"Content-Type":"application/json",...$.headers}})}meetingLeave($){return($.client??this.client).post({url:"/call/join/{token}/leave",...$})}meetingGuestParticipants($){return($.client??this.client).get({url:"/call/join/{token}/participants",...$})}meetingList($){return($?.client??this.client).get({url:"/call/meetings",...$})}meetingCreate($){return($.client??this.client).post({url:"/call/meetings",...$,headers:{"Content-Type":"application/json",...$.headers}})}meetingListActive($){return($?.client??this.client).get({url:"/call/meetings/active",...$})}meetingInvitePermissions($){return($.client??this.client).get({url:"/call/meetings/invite/{token}",...$})}meetingInvite($){return($.client??this.client).post({url:"/call/meetings/invite/{token}",...$,headers:{"Content-Type":"application/json",...$.headers}})}meetingInviteUsers($){return($.client??this.client).post({url:"/call/meetings/invite/{token}/users",...$,headers:{"Content-Type":"application/json",...$.headers}})}meetingJoin($){return($.client??this.client).post({url:"/call/meetings/join/{token}",...$})}meetingParticipants($){return($.client??this.client).get({url:"/call/meetings/join/{token}/participants",...$})}meetingPrepare($){return($?.client??this.client).post({url:"/call/meetings/prepare",...$})}meetingCancelPreparation($){return($.client??this.client).delete({url:"/call/meetings/prepare/{preparation_id}",...$})}meetingCancel($){return($.client??this.client).delete({url:"/call/meetings/{meeting_id}",...$})}meetingUpdate($){return($.client??this.client).patch({url:"/call/meetings/{meeting_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getBatchCallRecordPreview($){return($.client??this.client).post({url:"/call/record/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteCallRecord($){return($.client??this.client).delete({url:"/call/record/{call_id}",...$})}getCallRecord($){return($.client??this.client).get({url:"/call/record/{call_id}",...$})}editCallRecord($){return($.client??this.client).patch({url:"/call/record/{call_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}declineCall($){return($.client??this.client).post({url:"/call/record/{call_id}/decline",...$})}meetingShare($){return($.client??this.client).post({url:"/call/record/{call_id}/link",...$})}toggleShareWithTeam($){return($.client??this.client).post({url:"/call/record/{call_id}/share-with-team/toggle",...$})}editCallTranscript($){return($.client??this.client).patch({url:"/call/record/{call_id}/transcript",...$,headers:{"Content-Type":"application/json",...$.headers}})}getRingStatus($){return($.client??this.client).get({url:"/call/ring-status/{call_id}",...$})}declineRing($){return($.client??this.client).post({url:"/call/ring-status/{call_id}/decline",...$})}callWebhook($){return($?.client??this.client).post({url:"/call/webhook",...$})}leaveOrEndCall($){return($.client??this.client).delete({url:"/call/{channel_id}",...$})}getOrCreateCall($){return($.client??this.client).get({url:"/call/{channel_id}",...$})}checkActiveCall($){return($.client??this.client).get({url:"/call/{channel_id}/active",...$})}ingestTranscript($){return($.client??this.client).post({url:"/call/{room_name}/transcript",...$,headers:{"Content-Type":"application/json",...$.headers}})}listChannelLabels($){return($?.client??this.client).get({url:"/channel-labels",...$})}createChannelLabel($){return($.client??this.client).post({url:"/channel-labels",...$,headers:{"Content-Type":"application/json",...$.headers}})}setChannelLabel($){return($.client??this.client).put({url:"/channel-labels/channels/{channel_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}previewSmartTag($){return($.client??this.client).post({url:"/channel-labels/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteChannelLabel($){return($.client??this.client).delete({url:"/channel-labels/{label_id}",...$})}renameChannelLabel($){return($.client??this.client).patch({url:"/channel-labels/{label_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}createChannel($){return($.client??this.client).post({url:"/channels",...$,headers:{"Content-Type":"application/json",...$.headers}})}getActivity($){return($?.client??this.client).get({url:"/channels/activity",...$})}postActivity($){return($.client??this.client).post({url:"/channels/activity",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAttachmentReferences($){return($.client??this.client).get({url:"/channels/attachments/{entity_type}/{entity_id}/references",...$})}getOrCreateDm($){return($.client??this.client).post({url:"/channels/get_or_create_dm",...$,headers:{"Content-Type":"application/json",...$.headers}})}getOrCreatePrivate($){return($.client??this.client).post({url:"/channels/get_or_create_private",...$,headers:{"Content-Type":"application/json",...$.headers}})}joinChannelByCode($){return($.client??this.client).post({url:"/channels/join/{join_code}",...$})}createEntityMention($){return($.client??this.client).post({url:"/channels/mentions",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteEntityMention($){return($.client??this.client).delete({url:"/channels/mentions/{mention_id}",...$})}getBatchChannelPreview($){return($.client??this.client).post({url:"/channels/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteChannel($){return($.client??this.client).delete({url:"/channels/{channel_id}",...$})}getChannel($){return($.client??this.client).get({url:"/channels/{channel_id}",...$})}patchChannel($){return($.client??this.client).patch({url:"/channels/{channel_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getChannelAttachments($){return($.client??this.client).get({url:"/channels/{channel_id}/attachments",...$})}createChannelScopedBot($){return($.client??this.client).post({url:"/channels/{channel_id}/bots/scoped",...$,headers:{"Content-Type":"application/json",...$.headers}})}joinChannel($){return($.client??this.client).post({url:"/channels/{channel_id}/join",...$})}getChannelJoinLink($){return($.client??this.client).get({url:"/channels/{channel_id}/join-link",...$})}leaveChannel($){return($.client??this.client).post({url:"/channels/{channel_id}/leave",...$})}removeParticipants($){return($.client??this.client).delete({url:"/channels/{channel_id}/participants",...$,headers:{"Content-Type":"application/json",...$.headers}})}getChannelParticipants($){return($.client??this.client).get({url:"/channels/{channel_id}/participants",...$})}addParticipants($){return($.client??this.client).post({url:"/channels/{channel_id}/participants",...$,headers:{"Content-Type":"application/json",...$.headers}})}setChannelPicture($){return($.client??this.client).put({url:"/channels/{channel_id}/profile_picture",...$,headers:{"Content-Type":"application/json",...$.headers}})}postChannelBotWebhook($){return($.client??this.client).post({url:"/channels/{channel_id}/webhook",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteCollabSurface($){return($.client??this.client).delete({url:"/collab_surfaces/{id}",...$})}getCollabSurface($){return($.client??this.client).get({url:"/collab_surfaces/{id}",...$})}ensureCollabSurface($){return($.client??this.client).put({url:"/collab_surfaces/{id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}createCollabSurfaceToken($){return($.client??this.client).post({url:"/collab_surfaces/{id}/token",...$})}getChannels($){return($?.client??this.client).get({url:"/comms/channels",...$})}createCrmCompany($){return($.client??this.client).post({url:"/crm/companies",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCompany($){return($.client??this.client).get({url:"/crm/companies/{company_id}",...$})}listCompanyContacts($){return($.client??this.client).get({url:"/crm/companies/{company_id}/contacts",...$})}createCrmContact($){return($.client??this.client).post({url:"/crm/companies/{company_id}/contacts",...$,headers:{"Content-Type":"application/json",...$.headers}})}setEmailSync($){return($.client??this.client).put({url:"/crm/companies/{company_id}/email-sync",...$,headers:{"Content-Type":"application/json",...$.headers}})}setCompanyHidden($){return($.client??this.client).put({url:"/crm/companies/{company_id}/hidden",...$,headers:{"Content-Type":"application/json",...$.headers}})}setCrmCompanyName($){return($.client??this.client).put({url:"/crm/companies/{company_id}/name",...$,headers:{"Content-Type":"application/json",...$.headers}})}searchContacts($){return($?.client??this.client).get({url:"/crm/contacts",...$})}getContactByEmail($){return($.client??this.client).get({url:"/crm/contacts/by-email",...$})}getContact($){return($.client??this.client).get({url:"/crm/contacts/{contact_id}",...$})}setContactHidden($){return($.client??this.client).put({url:"/crm/contacts/{contact_id}/hidden",...$,headers:{"Content-Type":"application/json",...$.headers}})}setCrmContactName($){return($.client??this.client).put({url:"/crm/contacts/{contact_id}/name",...$,headers:{"Content-Type":"application/json",...$.headers}})}listCrmPipelines($){return($?.client??this.client).get({url:"/crm/pipelines",...$})}createCrmPipeline($){return($.client??this.client).post({url:"/crm/pipelines",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCrmPipeline($){return($.client??this.client).get({url:"/crm/pipelines/{id}",...$})}renameCrmPipeline($){return($.client??this.client).put({url:"/crm/pipelines/{id}/name",...$,headers:{"Content-Type":"application/json",...$.headers}})}applyCrmPipelineOps($){return($.client??this.client).post({url:"/crm/pipelines/{id}/ops",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCrmPipelinePermissions($){return($.client??this.client).get({url:"/crm/pipelines/{id}/permissions",...$})}updateCrmPipelinePermissions($){return($.client??this.client).patch({url:"/crm/pipelines/{id}/permissions",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCrmPipelineRows($){return($.client??this.client).get({url:"/crm/pipelines/{id}/rows",...$})}queryCrmPipelineRows($){return($.client??this.client).post({url:"/crm/pipelines/{id}/rows",...$,headers:{"Content-Type":"application/json",...$.headers}})}shareCrmPipeline($){return($.client??this.client).put({url:"/crm/pipelines/{id}/sharing",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCrmPipelineTable($){return($.client??this.client).get({url:"/crm/pipelines/{id}/table",...$})}trashCrmPipeline($){return($.client??this.client).put({url:"/crm/pipelines/{id}/trash",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCrmTeamSettings($){return($?.client??this.client).get({url:"/crm/settings",...$})}putCrmTeamSettings($){return($.client??this.client).put({url:"/crm/settings",...$,headers:{"Content-Type":"application/json",...$.headers}})}resetCrmTeamStages($){return($?.client??this.client).delete({url:"/crm/stages",...$})}putCrmTeamStages($){return($.client??this.client).put({url:"/crm/stages",...$,headers:{"Content-Type":"application/json",...$.headers}})}listDatabases($){return($?.client??this.client).get({url:"/databases",...$})}createDatabase($){return($.client??this.client).post({url:"/databases",...$,headers:{"Content-Type":"application/json",...$.headers}})}saveDatabaseQuery($){return($.client??this.client).post({url:"/databases/queries",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDatabaseQuery($){return($.client??this.client).get({url:"/databases/queries/{query_id}",...$})}queryDatabases($){return($.client??this.client).post({url:"/databases/query",...$,headers:{"Content-Type":"application/json",...$.headers}})}ensureStarterHandler($){return($?.client??this.client).post({url:"/databases/starter",...$})}deliverDatabaseWebhook($){return($.client??this.client).post({url:"/databases/webhooks/{token}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDatabase($){return($.client??this.client).get({url:"/databases/{id}",...$})}shareDatabaseAwareness($){return($.client??this.client).put({url:"/databases/{id}/awareness",...$,headers:{"Content-Type":"application/json",...$.headers}})}undoDatabaseChange($){return($.client??this.client).post({url:"/databases/{id}/changes/{change}/undo",...$})}importDatabaseTable($){return($.client??this.client).post({url:"/databases/{id}/import",...$,headers:{"Content-Type":"application/json",...$.headers}})}applyDatabaseOps($){return($.client??this.client).post({url:"/databases/{id}/ops",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDatabasePermissions($){return($.client??this.client).get({url:"/databases/{id}/permissions",...$})}updateDatabasePermissions($){return($.client??this.client).patch({url:"/databases/{id}/permissions",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDatabaseTableChanges($){return($.client??this.client).get({url:"/databases/{id}/tables/{table_id}/changes",...$})}listDatabaseColumnCasts($){return($.client??this.client).get({url:"/databases/{id}/tables/{table_id}/columns/{column_id}/casts",...$})}convertDatabaseColumn($){return($.client??this.client).post({url:"/databases/{id}/tables/{table_id}/columns/{column_id}/conversion",...$,headers:{"Content-Type":"application/json",...$.headers}})}inferDatabaseColumnType($){return($.client??this.client).post({url:"/databases/{id}/tables/{table_id}/columns/{column_id}/infer-type",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDatabaseRowHistory($){return($.client??this.client).get({url:"/databases/{id}/tables/{table_id}/rows/{row_id}/history",...$})}getDatabaseViewPositions($){return($.client??this.client).get({url:"/databases/{id}/views/{view_id}/positions",...$})}listDatabaseWebhooks($){return($.client??this.client).get({url:"/databases/{id}/webhooks",...$})}createDatabaseWebhook($){return($.client??this.client).post({url:"/databases/{id}/webhooks",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteDatabaseWebhook($){return($.client??this.client).delete({url:"/databases/{id}/webhooks/{webhook_id}",...$})}transcribeDictation($){return($.client??this.client).post({bodySerializer:null,url:"/dictation/transcribe",...$,headers:{"Content-Type":"audio/webm",...$.headers}})}getUserDocumentsHandler($){return($.client??this.client).get({url:"/documents",...$})}createDocument($){return($.client??this.client).post({url:"/documents",...$,headers:{"Content-Type":"application/json",...$.headers}})}createCanvasHandler($){return($.client??this.client).post({url:"/documents/create_canvas",...$,headers:{"Content-Type":"application/json",...$.headers}})}createMarkdownHandler($){return($.client??this.client).post({url:"/documents/create_markdown",...$,headers:{"Content-Type":"application/json",...$.headers}})}createSkillHandler($){return($.client??this.client).post({url:"/documents/create_skill",...$,headers:{"Content-Type":"application/json",...$.headers}})}createSnippetHandler($){return($.client??this.client).post({url:"/documents/create_snippet",...$,headers:{"Content-Type":"application/json",...$.headers}})}createTaskHandler($){return($.client??this.client).post({url:"/documents/create_task",...$,headers:{"Content-Type":"application/json",...$.headers}})}getGithubPullRequestTasks($){return($.client??this.client).post({url:"/documents/github_prs/tasks",...$,headers:{"Content-Type":"application/json",...$.headers}})}initializeUserDocuments($){return($?.client??this.client).post({url:"/documents/initialize_user_documents",...$})}getDocumentListHandler($){return($?.client??this.client).get({url:"/documents/list",...$})}validateDocumentPermissionsToken($){return($.client??this.client).post({url:"/documents/permissions_token/validate",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDocumentPermissionsToken($){return($.client??this.client).post({url:"/documents/permissions_token/{document_id}",...$})}presaveDocumentHandler($){return($.client??this.client).put({url:"/documents/presave/{document_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getBatchPreviewHandler($){return($.client??this.client).post({url:"/documents/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDocumentByTeamSlug($){return($.client??this.client).get({url:"/documents/slug/{slug}",...$})}handler($){return($?.client??this.client).get({url:"/documents/starter_docs",...$})}getSystemSkillsHandler($){return($?.client??this.client).get({url:"/documents/system_skills",...$})}deleteDocument($){return($.client??this.client).delete({url:"/documents/{document_id}",...$})}getDocument($){return($.client??this.client).get({url:"/documents/{document_id}",...$})}editDocument($){return($.client??this.client).patch({url:"/documents/{document_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}saveDocumentHandler($){return($.client??this.client).put({url:"/documents/{document_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDocumentBranchName($){return($.client??this.client).get({url:"/documents/{document_id}/branch_name",...$})}copyDocument($){return($.client??this.client).post({url:"/documents/{document_id}/copy",...$,headers:{"Content-Type":"application/json",...$.headers}})}exportDocument($){return($.client??this.client).get({url:"/documents/{document_id}/export",...$})}getDocumentGithubPullRequests($){return($.client??this.client).get({url:"/documents/{document_id}/github_prs",...$})}getLocationHandler($){return($.client??this.client).get({url:"/documents/{document_id}/location",...$})}getDocumentLocationV3($){return($.client??this.client).get({url:"/documents/{document_id}/location_v3",...$})}permanentlyDeleteDocument($){return($.client??this.client).delete({url:"/documents/{document_id}/permanent",...$})}getDocumentProcessingResult($){return($.client??this.client).get({url:"/documents/{document_id}/processing",...$})}jobProcessingResultHandler($){return($.client??this.client).get({url:"/documents/{document_id}/processing/{job_id}",...$})}revertDeleteDocument($){return($.client??this.client).put({url:"/documents/{document_id}/revert_delete",...$})}getDocumentShortId($){return($.client??this.client).get({url:"/documents/{document_id}/short_id",...$})}simpleSave($){return($.client??this.client).put({url:"/documents/{document_id}/simple_save",...$})}getDocumentTeamShare($){return($.client??this.client).get({url:"/documents/{document_id}/team_share",...$})}setDocumentTeamShare($){return($.client??this.client).put({url:"/documents/{document_id}/team_share",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDocumentTextContent($){return($.client??this.client).get({url:"/documents/{document_id}/text-content",...$})}getDocumentViewsHandler($){return($.client??this.client).get({url:"/documents/{document_id}/views",...$})}getDocumentVersion($){return($.client??this.client).get({url:"/documents/{document_id}/{document_version_id}",...$})}accessRequestsState($){return($.client??this.client).get({url:"/entities/{entity_type}/{entity_id}/access-requests",...$})}accessRequestsCancel($){return($.client??this.client).delete({url:"/entities/{entity_type}/{entity_id}/access-requests/mine",...$})}accessRequestsSubmit($){return($.client??this.client).put({url:"/entities/{entity_type}/{entity_id}/access-requests/mine",...$,headers:{"Content-Type":"application/json",...$.headers}})}accessRequestsResolve($){return($.client??this.client).post({url:"/entities/{entity_type}/{entity_id}/access-requests/{request_id}/resolve",...$,headers:{"Content-Type":"application/json",...$.headers}})}accessRequestsDirect($){return($.client??this.client).get({url:"/entities/{entity_type}/{entity_id}/direct-access",...$})}accessRequestsRemoveDirect($){return($.client??this.client).delete({url:"/entities/{entity_type}/{entity_id}/direct-access/{user_id}",...$})}accessRequestsSetDirect($){return($.client??this.client).put({url:"/entities/{entity_type}/{entity_id}/direct-access/{user_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getEntityPermission($){return($.client??this.client).get({url:"/entity/{entity_type}/{entity_id}/permissions",...$})}listFavorites($){return($?.client??this.client).get({url:"/favorites",...$})}addFavorite($){return($.client??this.client).post({url:"/favorites",...$,headers:{"Content-Type":"application/json",...$.headers}})}reorderFavorites($){return($.client??this.client).patch({url:"/favorites/reorder",...$,headers:{"Content-Type":"application/json",...$.headers}})}removeFavoriteByEntity($){return($.client??this.client).delete({url:"/favorites/{entity_type}/{entity_id}",...$})}getForeignEntityBySource($){return($.client??this.client).get({url:"/foreign_entity/by_source/{source}/{foreign_entity_id}",...$})}getForeignEntity($){return($.client??this.client).get({url:"/foreign_entity/{id}",...$})}listForms($){return($.client??this.client).get({url:"/forms",...$})}createForm($){return($.client??this.client).post({url:"/forms",...$,headers:{"Content-Type":"application/json",...$.headers}})}listAccessibleForms($){return($?.client??this.client).get({url:"/forms/accessible",...$})}getForm($){return($.client??this.client).get({url:"/forms/{id}",...$})}updateForm($){return($.client??this.client).patch({url:"/forms/{id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}collaborateForm($){return($.client??this.client).post({url:"/forms/{id}/collaboration",...$})}putFormLayout($){return($.client??this.client).put({url:"/forms/{id}/layout",...$,headers:{"Content-Type":"application/json",...$.headers}})}getFormPermissions($){return($.client??this.client).get({url:"/forms/{id}/permissions",...$})}updateFormPermissions($){return($.client??this.client).patch({url:"/forms/{id}/permissions",...$,headers:{"Content-Type":"application/json",...$.headers}})}submitFormResponse($){return($.client??this.client).post({url:"/forms/{id}/responses",...$,headers:{"Content-Type":"application/json",...$.headers}})}getMyFormResponse($){return($.client??this.client).get({url:"/forms/{id}/responses/mine",...$})}editMyFormResponse($){return($.client??this.client).put({url:"/forms/{id}/responses/mine",...$,headers:{"Content-Type":"application/json",...$.headers}})}getFormResponseSummary($){return($.client??this.client).get({url:"/forms/{id}/responses/summary",...$})}getFormTally($){return($.client??this.client).get({url:"/forms/{id}/tally",...$})}installSync($){return($?.client??this.client).get({url:"/github/install-sync",...$})}getGithubPullRequestFacets($){return($?.client??this.client).get({url:"/github_pull_requests/facets",...$})}getGithubPullRequest($){return($.client??this.client).get({url:"/github_pull_requests/{id}",...$})}getGithubPullRequestChanges($){return($.client??this.client).get({url:"/github_pull_requests/{id}/changes",...$})}getGithubPullRequestChangesPatch($){return($.client??this.client).get({url:"/github_pull_requests/{id}/changes/patch",...$})}createHarnessPairing($){return($.client??this.client).post({url:"/harness-pairings",...$,headers:{"Content-Type":"application/json",...$.headers}})}getHarnessPairing($){return($.client??this.client).get({url:"/harness-pairings/{code}",...$})}approveHarnessPairing($){return($.client??this.client).post({url:"/harness-pairings/{code}/approve",...$,headers:{"Content-Type":"application/json",...$.headers}})}claimHarnessPairing($){return($.client??this.client).post({url:"/harness-pairings/{pairing_id}/claim",...$,headers:{"Content-Type":"application/json",...$.headers}})}listHarnesses($){return($?.client??this.client).get({url:"/harnesses",...$})}deleteSelfHarness($){return($?.client??this.client).delete({url:"/harnesses/me",...$})}getSelfHarness($){return($?.client??this.client).get({url:"/harnesses/me",...$})}listHarnessAgents($){return($?.client??this.client).get({url:"/harnesses/me/agents",...$})}listHarnessSessions($){return($?.client??this.client).get({url:"/harnesses/me/sessions",...$})}deleteHarness($){return($.client??this.client).delete({url:"/harnesses/{harness_id}",...$})}healthHandler($){return($?.client??this.client).get({url:"/health",...$})}getHistoryHandler($){return($?.client??this.client).get({url:"/history",...$})}deleteHistoryHandler($){return($.client??this.client).delete({url:"/history/{item_type}/{item_id}",...$})}upsertHistoryHandler($){return($.client??this.client).post({url:"/history/{item_type}/{item_id}",...$})}listInitiatives($){return($?.client??this.client).get({url:"/initiatives",...$})}createInitiative($){return($.client??this.client).post({url:"/initiatives",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteInitiative($){return($.client??this.client).delete({url:"/initiatives/{initiative_id}",...$})}getInitiative($){return($.client??this.client).get({url:"/initiatives/{initiative_id}",...$})}updateInitiative($){return($.client??this.client).patch({url:"/initiatives/{initiative_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getInstructionsHandler($){return($?.client??this.client).get({url:"/instructions",...$})}createInstructionsHandler($){return($?.client??this.client).post({url:"/instructions",...$})}getItemsSoup($){return($?.client??this.client).get({url:"/items/soup",...$})}postItemsSoup($){return($.client??this.client).post({url:"/items/soup",...$,headers:{"Content-Type":"application/json",...$.headers}})}postItemsSoupAst($){return($.client??this.client).post({url:"/items/soup/ast",...$,headers:{"Content-Type":"application/json",...$.headers}})}postItemsSoupAstGrouped($){return($.client??this.client).post({url:"/items/soup/ast/grouped",...$,headers:{"Content-Type":"application/json",...$.headers}})}messageTimeline($){return($.client??this.client).get({url:"/messages/{parent_type}/{parent_id}",...$})}entityMessageCreate($){return($.client??this.client).post({url:"/messages/{parent_type}/{parent_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}entityMessageDeleteMessage($){return($.client??this.client).delete({url:"/messages/{parent_type}/{parent_id}/items/{id}",...$})}entityMessageGetMessage($){return($.client??this.client).get({url:"/messages/{parent_type}/{parent_id}/items/{id}",...$})}entityMessageEdit($){return($.client??this.client).patch({url:"/messages/{parent_type}/{parent_id}/items/{id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}entityMessageReact($){return($.client??this.client).post({url:"/messages/{parent_type}/{parent_id}/items/{id}/reactions",...$,headers:{"Content-Type":"application/json",...$.headers}})}entityMessageLegacy($){return($.client??this.client).get({url:"/messages/{parent_type}/{parent_id}/legacy/{legacy_id}",...$})}entityMessageDeleteThread($){return($.client??this.client).delete({url:"/messages/{parent_type}/{parent_id}/threads/{id}",...$})}entityMessageGetThread($){return($.client??this.client).get({url:"/messages/{parent_type}/{parent_id}/threads/{id}",...$})}entityMessagePatchThread($){return($.client??this.client).patch({url:"/messages/{parent_type}/{parent_id}/threads/{id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}messageTimelineEntries($){return($.client??this.client).get({url:"/messages/{parent_type}/{parent_id}/timeline",...$})}entityMessageTyping($){return($.client??this.client).post({url:"/messages/{parent_type}/{parent_id}/typing",...$,headers:{"Content-Type":"application/json",...$.headers}})}linkedAccount($){return($?.client??this.client).get({url:"/meta/linked/account",...$})}linkedChats($){return($?.client??this.client).get({url:"/meta/linked/chats",...$})}linkedConfiguration($){return($?.client??this.client).get({url:"/meta/linked/configuration",...$})}linkedConnect($){return($.client??this.client).post({url:"/meta/linked/connect",...$,headers:{"Content-Type":"application/json",...$.headers}})}linkedDisconnect($){return($.client??this.client).post({url:"/meta/linked/disconnect",...$,headers:{"Content-Type":"application/json",...$.headers}})}linkedGroups($){return($?.client??this.client).get({url:"/meta/linked/groups",...$})}linkedAdopt($){return($.client??this.client).post({url:"/meta/linked/groups/adopt",...$,headers:{"Content-Type":"application/json",...$.headers}})}linkedCancelPairing($){return($.client??this.client).delete({url:"/meta/linked/pairing/{id}",...$})}linkedPairing($){return($.client??this.client).get({url:"/meta/linked/pairing/{id}",...$})}linkedPasskey($){return($.client??this.client).post({url:"/meta/linked/pairing/{id}/passkey",...$,headers:{"Content-Type":"application/json",...$.headers}})}whatsappGroups($){return($?.client??this.client).get({url:"/meta/linked/whatsapp-groups",...$})}linkedDetach($){return($.client??this.client).delete({url:"/meta/linked/whatsapp-groups/{group_id}",...$})}whatsappGroup($){return($.client??this.client).get({url:"/meta/linked/whatsapp-groups/{group_id}",...$})}linkedUpload($){return($.client??this.client).post({...R1,url:"/meta/linked/whatsapp-groups/{group_id}/attachments",...$,headers:{"Content-Type":null,...$.headers}})}linkedDelivery($){return($.client??this.client).post({url:"/meta/linked/whatsapp-groups/{group_id}/delivery",...$,headers:{"Content-Type":"application/json",...$.headers}})}whatsappGroupMessages($){return($.client??this.client).get({url:"/meta/linked/whatsapp-groups/{group_id}/messages",...$})}linkedMessageAttachments($){return($.client??this.client).post({url:"/meta/linked/whatsapp-groups/{group_id}/messages/attachments",...$,headers:{"Content-Type":"application/json",...$.headers}})}whatsappGroupPermissions($){return($.client??this.client).get({url:"/meta/linked/whatsapp-groups/{group_id}/permissions",...$})}whatsappGroupUpdatePermissions($){return($.client??this.client).patch({url:"/meta/linked/whatsapp-groups/{group_id}/permissions",...$,headers:{"Content-Type":"application/json",...$.headers}})}whatsappGroupRead($){return($.client??this.client).post({url:"/meta/linked/whatsapp-groups/{group_id}/read",...$,headers:{"Content-Type":"application/json",...$.headers}})}whatsappGroupSends($){return($.client??this.client).get({url:"/meta/linked/whatsapp-groups/{group_id}/sends",...$})}linkedReply($){return($.client??this.client).post({url:"/meta/linked/whatsapp-groups/{group_id}/sends",...$,headers:{"Content-Type":"application/json",...$.headers}})}getPinsHandler($){return($?.client??this.client).get({url:"/pins",...$})}reorderPinsHandler($){return($.client??this.client).patch({url:"/pins",...$,headers:{"Content-Type":"application/json",...$.headers}})}removePinHandler($){return($.client??this.client).delete({url:"/pins/{pinned_item_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}addPinHandler($){return($.client??this.client).post({url:"/pins/{pinned_item_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getProjectsHandler($){return($?.client??this.client).get({url:"/projects",...$})}createProjectHandler($){return($.client??this.client).post({url:"/projects",...$,headers:{"Content-Type":"application/json",...$.headers}})}getPendingProjectsHandler($){return($?.client??this.client).get({url:"/projects/pending",...$})}getBatchProjectPreview($){return($.client??this.client).post({url:"/projects/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}uploadFolderHandler($){return($.client??this.client).post({url:"/projects/upload",...$,headers:{"Content-Type":"application/json",...$.headers}})}uploadExtractFolderHandler($){return($.client??this.client).post({url:"/projects/upload_extract",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteProjectHandler($){return($.client??this.client).delete({url:"/projects/{id}",...$})}getProjectHandler($){return($.client??this.client).get({url:"/projects/{id}",...$})}getProjectUserAccessLevel($){return($.client??this.client).get({url:"/projects/{id}/access_level",...$})}getProjectContentHandler($){return($.client??this.client).get({url:"/projects/{id}/content",...$})}permanentlyDeleteProject($){return($.client??this.client).delete({url:"/projects/{id}/permanent",...$})}getProjectPermissionsV2($){return($.client??this.client).get({url:"/projects/{id}/permissions",...$})}revertDeleteProject($){return($.client??this.client).put({url:"/projects/{id}/revert_delete",...$})}recentlyDeleted($){return($?.client??this.client).get({url:"/recents/deleted",...$})}listEmailReminders($){return($?.client??this.client).get({url:"/reminders/email/collection",...$})}getEmailFollowup($){return($.client??this.client).get({url:"/reminders/email/{thread_id}",...$})}setEmailFollowup($){return($.client??this.client).put({url:"/reminders/email/{thread_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getViewsHandler($){return($?.client??this.client).get({url:"/saved_views",...$})}createViewHandler($){return($.client??this.client).post({url:"/saved_views",...$,headers:{"Content-Type":"application/json",...$.headers}})}excludeDefaultViewHandler($){return($.client??this.client).post({url:"/saved_views/exclude_default",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteViewHandler($){return($.client??this.client).delete({url:"/saved_views/{saved_view_id}",...$})}patchViewHandler($){return($.client??this.client).patch({url:"/saved_views/{saved_view_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}listSlackImports($){return($?.client??this.client).get({url:"/slack/imports",...$})}createSlackImport($){return($.client??this.client).post({url:"/slack/imports",...$,headers:{"Content-Type":"application/json",...$.headers}})}getSlackImport($){return($.client??this.client).get({url:"/slack/imports/{job_id}",...$})}cancelSlackImport($){return($.client??this.client).post({url:"/slack/imports/{job_id}/cancel",...$})}finalizeSlackImport($){return($.client??this.client).post({url:"/slack/imports/{job_id}/finalize",...$})}registerSlackImportUploads($){return($.client??this.client).post({url:"/slack/imports/{job_id}/uploads",...$,headers:{"Content-Type":"application/json",...$.headers}})}completeSlackImportUploads($){return($.client??this.client).post({url:"/slack/imports/{job_id}/uploads/complete",...$,headers:{"Content-Type":"application/json",...$.headers}})}bulkWakeupSyncServiceDocuments($){return($.client??this.client).post({url:"/sync_service/wakeup",...$,headers:{"Content-Type":"application/json",...$.headers}})}editThreadV2($){return($.client??this.client).patch({url:"/threads/{thread_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}listUserApiKeys($){return($?.client??this.client).get({url:"/user-api-keys",...$})}createUserApiKey($){return($.client??this.client).post({url:"/user-api-keys",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteUserApiKey($){return($.client??this.client).delete({url:"/user-api-keys/{id}",...$})}deleteUserDocumentViewLocation($){return($.client??this.client).delete({url:"/user_document_view_location/{document_id}",...$})}getUserDocumentViewLocation($){return($.client??this.client).get({url:"/user_document_view_location/{document_id}",...$})}upsertUserDocumentViewLocation($){return($.client??this.client).post({url:"/user_document_view_location/{document_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDocumentPermissionsV2($){return($.client??this.client).get({url:"/v2/documents/{document_id}/permissions",...$})}editProjectV2($){return($.client??this.client).patch({url:"/v2/projects/{id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}streamEvents($){return($.client??this.client).sse.get({url:"/webhook/events/stream",...$})}listWebhooks($){return($?.client??this.client).get({url:"/webhook/webhooks",...$})}createWebhook($){return($.client??this.client).post({url:"/webhook/webhooks",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteWebhook($){return($.client??this.client).delete({url:"/webhook/webhooks/{webhook_id}",...$})}getWebhook($){return($.client??this.client).get({url:"/webhook/webhooks/{webhook_id}",...$})}patchWebhook($){return($.client??this.client).patch({url:"/webhook/webhooks/{webhook_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}validateWebhook($){return($.client??this.client).post({url:"/webhook/webhooks/{webhook_id}/validate",...$})}}function G6({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...Q}){let J,I=Y??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,T=Q.signal??new AbortController().signal;while(!0){if(T.aborted)break;B++;let A=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)A.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:A,signal:T},_=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 H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",k=()=>{try{H.cancel()}catch{}};T.addEventListener("abort",k);try{while(!0){let{done:l,value:r}=await H.read();if(l)break;U+=r,U=U.replace(/\r\n?/g,`+`);try{C=JSON.parse(R),v=!0}catch{C=R}}if(v){if(S)await S(C);if(x)C=await x(C)}if(j?.({data:C,event:y,id:J,retry:V}),F.length)yield C}}}finally{T.removeEventListener("abort",k),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&W>=Z)break;let _=Math.min(V*2**(W-1),X??30000);await I(_)}}}()}}var e5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},o5=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},$4=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},Px=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((Y)=>encodeURIComponent(Y))).join(o5(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=e5(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return yO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},yO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},Ax=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let Y=[];Object.entries(S).forEach(([Q,J])=>{Y=[...Y,Q,$?J:encodeURIComponent(J)]});let L=Y.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=$4(x),X=Object.entries(S).map(([Y,L])=>yO({allowReserved:$,name:x==="deepObject"?`${j}[${Y}]`:Y,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var O4=/\{[^{}]+\}/g,j4=({path:$,url:O})=>{let j=O,x=O.match(O4);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 Y=$[Z];if(Y===void 0||Y===null)continue;if(Array.isArray(Y)){j=j.replace(S,Px({explode:K,name:Z,style:X,value:Y}));continue}if(typeof Y==="object"){j=j.replace(S,Ax({explode:K,name:Z,style:X,value:Y,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${yO({name:Z,value:Y})}`);continue}let L=encodeURIComponent(X==="label"?`.${Y}`:Y);j=j.replace(S,L)}return j},j6=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=j4({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function M1($){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 x6=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 S6=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let Y=Px({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(Y)S.push(Y)}else if(typeof Z==="object"){let Y=Ax({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(Y)S.push(Y)}else{let Y=yO({allowReserved:X.allowReserved,name:K,value:Z});if(Y)S.push(Y)}}return S.join("&")}},Z6=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},x4=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function X6($){for(let O of $.security??[]){if(x4($,O.name))continue;let j=await x6(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 P1=($)=>j6({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:S6($.querySerializer),url:$.url}),A1=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=Ex($.headers,O.headers),j},S4=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},Ex=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?S4(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 Fx{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 K6=()=>({error:new Fx,request:new Fx,response:new Fx}),Z4=S6({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),X4={"Content-Type":"application/json"},Jj=($={})=>({...C1,headers:X4,parseAs:"auto",querySerializer:Z4,...$});var Vj=($={})=>{let O=A1(Jj(),$),j=()=>({...O}),x=(Q)=>{return O=A1(O,Q),j()},S=K6(),K=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:Ex(O.headers,Q.headers),serializedBody:void 0};if(J.security)await X6(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let I=J,z=P1(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,B;try{let{opts:V,url:W}=await K(Q),T={redirect:"follow",...V,body:M1(V)};z=new Request(W,T);for(let N of S.request.fns)if(N)z=await N(z,V);let A=V.fetch;B=await A(z);for(let N of S.response.fns)if(N)B=await N(B,z,V);let D={request:z,response:B};if(B.ok){let N=(V.parseAs==="auto"?Z6(B.headers.get("Content-Type")):V.parseAs)??"json";if(B.status===204||B.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await B[N]();break;case"formData":U=new FormData;break;case"stream":U=B.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await B[N]();break;case"json":{let U=await B.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?B.body:{data:B.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let _=await B.text(),q;try{q=JSON.parse(_)}catch{}throw q??_}catch(V){let W=V;for(let T of S.error.fns)if(T)W=await T(W,B,z,Q);if(W=W||{},J)throw W;return I==="data"?void 0:{error:W,request:z,response:B}}},X=(Q)=>(J)=>Z({...J,method:Q}),Y=(Q)=>async(J)=>{let{opts:I,url:z}=await K(J);return O6({...I,body:I.body,method:Q,onRequest:async(B,V)=>{let W=new Request(B,V);for(let T of S.request.fns)if(T)W=await T(W,I);return W},serializedBody:M1(I),url:z})};return{buildUrl:(Q)=>P1({...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:Y("CONNECT"),delete:Y("DELETE"),get:Y("GET"),head:Y("HEAD"),options:Y("OPTIONS"),patch:Y("PATCH"),post:Y("POST"),put:Y("PUT"),trace:Y("TRACE")},trace:X("TRACE")}};var Y6=Vj(Jj());class G6{client;constructor($){this.client=$?.client??Y6}}class Q6{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class wx extends G6{static __registry=new Q6;constructor($){super($);wx.__registry.set(this,$?.key)}listAgents($){return($?.client??this.client).get({url:"/agents",...$})}createAgent($){return($.client??this.client).post({url:"/agents",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateAgent($){return($.client??this.client).put({url:"/agents/{agent_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteAnchor($){return($.client??this.client).delete({url:"/annotations/anchors",...$,headers:{"Content-Type":"application/json",...$.headers}})}editAnchor($){return($.client??this.client).patch({url:"/annotations/anchors",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDocumentAnchors($){return($.client??this.client).get({url:"/annotations/anchors/document/{document_id}",...$})}createAnchor($){return($.client??this.client).post({url:"/annotations/anchors/document/{document_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getSelfBot($){return($?.client??this.client).get({url:"/bots/me",...$})}getBotOwnerProfiles($){return($?.client??this.client).get({url:"/bots/profiles",...$})}listBotChannels($){return($.client??this.client).get({url:"/bots/{bot_id}/channels",...$})}removeBotFromChannelByBot($){return($.client??this.client).delete({url:"/bots/{bot_id}/channels/{channel_id}",...$})}listOccurrences($){return($.client??this.client).get({url:"/calendar-events",...$})}mentionPreviews($){return($.client??this.client).post({url:"/calendar-events/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}listTeamCalendar($){return($.client??this.client).get({url:"/calendar-events/team",...$})}listTeamOutOfOffice($){return($.client??this.client).get({url:"/calendar-events/team-out-of-office",...$})}eventIcs($){return($.client??this.client).get({url:"/calendar-events/{event_id}/ics",...$})}listJoinRequests($){return($.client??this.client).get({url:"/calendar-events/{event_id}/join-requests",...$})}requestToJoin($){return($.client??this.client).post({url:"/calendar-events/{event_id}/join-requests",...$})}getActiveCalls($){return($?.client??this.client).get({url:"/call/active",...$})}guestCallChatRead($){return($.client??this.client).get({url:"/call/guest-chat/{call_id}",...$})}guestCallChatPost($){return($.client??this.client).post({url:"/call/guest-chat/{call_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}meetingLookup($){return($.client??this.client).get({url:"/call/join/{token}",...$})}meetingGuestJoin($){return($.client??this.client).post({url:"/call/join/{token}",...$,headers:{"Content-Type":"application/json",...$.headers}})}meetingLeave($){return($.client??this.client).post({url:"/call/join/{token}/leave",...$})}meetingGuestParticipants($){return($.client??this.client).get({url:"/call/join/{token}/participants",...$})}meetingList($){return($?.client??this.client).get({url:"/call/meetings",...$})}meetingCreate($){return($.client??this.client).post({url:"/call/meetings",...$,headers:{"Content-Type":"application/json",...$.headers}})}meetingListActive($){return($?.client??this.client).get({url:"/call/meetings/active",...$})}meetingInvitePermissions($){return($.client??this.client).get({url:"/call/meetings/invite/{token}",...$})}meetingInvite($){return($.client??this.client).post({url:"/call/meetings/invite/{token}",...$,headers:{"Content-Type":"application/json",...$.headers}})}meetingInviteUsers($){return($.client??this.client).post({url:"/call/meetings/invite/{token}/users",...$,headers:{"Content-Type":"application/json",...$.headers}})}meetingJoin($){return($.client??this.client).post({url:"/call/meetings/join/{token}",...$})}meetingParticipants($){return($.client??this.client).get({url:"/call/meetings/join/{token}/participants",...$})}meetingPrepare($){return($?.client??this.client).post({url:"/call/meetings/prepare",...$})}meetingCancelPreparation($){return($.client??this.client).delete({url:"/call/meetings/prepare/{preparation_id}",...$})}meetingCancel($){return($.client??this.client).delete({url:"/call/meetings/{meeting_id}",...$})}meetingUpdate($){return($.client??this.client).patch({url:"/call/meetings/{meeting_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getBatchCallRecordPreview($){return($.client??this.client).post({url:"/call/record/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteCallRecord($){return($.client??this.client).delete({url:"/call/record/{call_id}",...$})}getCallRecord($){return($.client??this.client).get({url:"/call/record/{call_id}",...$})}editCallRecord($){return($.client??this.client).patch({url:"/call/record/{call_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}declineCall($){return($.client??this.client).post({url:"/call/record/{call_id}/decline",...$})}meetingShare($){return($.client??this.client).post({url:"/call/record/{call_id}/link",...$})}toggleShareWithTeam($){return($.client??this.client).post({url:"/call/record/{call_id}/share-with-team/toggle",...$})}editCallTranscript($){return($.client??this.client).patch({url:"/call/record/{call_id}/transcript",...$,headers:{"Content-Type":"application/json",...$.headers}})}getRingStatus($){return($.client??this.client).get({url:"/call/ring-status/{call_id}",...$})}declineRing($){return($.client??this.client).post({url:"/call/ring-status/{call_id}/decline",...$})}callWebhook($){return($?.client??this.client).post({url:"/call/webhook",...$})}leaveOrEndCall($){return($.client??this.client).delete({url:"/call/{channel_id}",...$})}getOrCreateCall($){return($.client??this.client).get({url:"/call/{channel_id}",...$})}checkActiveCall($){return($.client??this.client).get({url:"/call/{channel_id}/active",...$})}ingestTranscript($){return($.client??this.client).post({url:"/call/{room_name}/transcript",...$,headers:{"Content-Type":"application/json",...$.headers}})}listChannelLabels($){return($?.client??this.client).get({url:"/channel-labels",...$})}createChannelLabel($){return($.client??this.client).post({url:"/channel-labels",...$,headers:{"Content-Type":"application/json",...$.headers}})}setChannelLabel($){return($.client??this.client).put({url:"/channel-labels/channels/{channel_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}previewSmartTag($){return($.client??this.client).post({url:"/channel-labels/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteChannelLabel($){return($.client??this.client).delete({url:"/channel-labels/{label_id}",...$})}renameChannelLabel($){return($.client??this.client).patch({url:"/channel-labels/{label_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}createChannel($){return($.client??this.client).post({url:"/channels",...$,headers:{"Content-Type":"application/json",...$.headers}})}getActivity($){return($?.client??this.client).get({url:"/channels/activity",...$})}postActivity($){return($.client??this.client).post({url:"/channels/activity",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAttachmentReferences($){return($.client??this.client).get({url:"/channels/attachments/{entity_type}/{entity_id}/references",...$})}getOrCreateDm($){return($.client??this.client).post({url:"/channels/get_or_create_dm",...$,headers:{"Content-Type":"application/json",...$.headers}})}getOrCreatePrivate($){return($.client??this.client).post({url:"/channels/get_or_create_private",...$,headers:{"Content-Type":"application/json",...$.headers}})}joinChannelByCode($){return($.client??this.client).post({url:"/channels/join/{join_code}",...$})}createEntityMention($){return($.client??this.client).post({url:"/channels/mentions",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteEntityMention($){return($.client??this.client).delete({url:"/channels/mentions/{mention_id}",...$})}getBatchChannelPreview($){return($.client??this.client).post({url:"/channels/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteChannel($){return($.client??this.client).delete({url:"/channels/{channel_id}",...$})}getChannel($){return($.client??this.client).get({url:"/channels/{channel_id}",...$})}patchChannel($){return($.client??this.client).patch({url:"/channels/{channel_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getChannelAttachments($){return($.client??this.client).get({url:"/channels/{channel_id}/attachments",...$})}createChannelScopedBot($){return($.client??this.client).post({url:"/channels/{channel_id}/bots/scoped",...$,headers:{"Content-Type":"application/json",...$.headers}})}joinChannel($){return($.client??this.client).post({url:"/channels/{channel_id}/join",...$})}getChannelJoinLink($){return($.client??this.client).get({url:"/channels/{channel_id}/join-link",...$})}leaveChannel($){return($.client??this.client).post({url:"/channels/{channel_id}/leave",...$})}removeParticipants($){return($.client??this.client).delete({url:"/channels/{channel_id}/participants",...$,headers:{"Content-Type":"application/json",...$.headers}})}getChannelParticipants($){return($.client??this.client).get({url:"/channels/{channel_id}/participants",...$})}addParticipants($){return($.client??this.client).post({url:"/channels/{channel_id}/participants",...$,headers:{"Content-Type":"application/json",...$.headers}})}setChannelPicture($){return($.client??this.client).put({url:"/channels/{channel_id}/profile_picture",...$,headers:{"Content-Type":"application/json",...$.headers}})}postChannelBotWebhook($){return($.client??this.client).post({url:"/channels/{channel_id}/webhook",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteCollabSurface($){return($.client??this.client).delete({url:"/collab_surfaces/{id}",...$})}getCollabSurface($){return($.client??this.client).get({url:"/collab_surfaces/{id}",...$})}ensureCollabSurface($){return($.client??this.client).put({url:"/collab_surfaces/{id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}createCollabSurfaceToken($){return($.client??this.client).post({url:"/collab_surfaces/{id}/token",...$})}getChannels($){return($?.client??this.client).get({url:"/comms/channels",...$})}createCrmCompany($){return($.client??this.client).post({url:"/crm/companies",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCompany($){return($.client??this.client).get({url:"/crm/companies/{company_id}",...$})}listCompanyContacts($){return($.client??this.client).get({url:"/crm/companies/{company_id}/contacts",...$})}createCrmContact($){return($.client??this.client).post({url:"/crm/companies/{company_id}/contacts",...$,headers:{"Content-Type":"application/json",...$.headers}})}setEmailSync($){return($.client??this.client).put({url:"/crm/companies/{company_id}/email-sync",...$,headers:{"Content-Type":"application/json",...$.headers}})}setCompanyHidden($){return($.client??this.client).put({url:"/crm/companies/{company_id}/hidden",...$,headers:{"Content-Type":"application/json",...$.headers}})}setCrmCompanyName($){return($.client??this.client).put({url:"/crm/companies/{company_id}/name",...$,headers:{"Content-Type":"application/json",...$.headers}})}searchContacts($){return($?.client??this.client).get({url:"/crm/contacts",...$})}getContactByEmail($){return($.client??this.client).get({url:"/crm/contacts/by-email",...$})}getContact($){return($.client??this.client).get({url:"/crm/contacts/{contact_id}",...$})}setContactHidden($){return($.client??this.client).put({url:"/crm/contacts/{contact_id}/hidden",...$,headers:{"Content-Type":"application/json",...$.headers}})}setCrmContactName($){return($.client??this.client).put({url:"/crm/contacts/{contact_id}/name",...$,headers:{"Content-Type":"application/json",...$.headers}})}listCrmPipelines($){return($?.client??this.client).get({url:"/crm/pipelines",...$})}createCrmPipeline($){return($.client??this.client).post({url:"/crm/pipelines",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCrmPipeline($){return($.client??this.client).get({url:"/crm/pipelines/{id}",...$})}renameCrmPipeline($){return($.client??this.client).put({url:"/crm/pipelines/{id}/name",...$,headers:{"Content-Type":"application/json",...$.headers}})}applyCrmPipelineOps($){return($.client??this.client).post({url:"/crm/pipelines/{id}/ops",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCrmPipelinePermissions($){return($.client??this.client).get({url:"/crm/pipelines/{id}/permissions",...$})}updateCrmPipelinePermissions($){return($.client??this.client).patch({url:"/crm/pipelines/{id}/permissions",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCrmPipelineRows($){return($.client??this.client).get({url:"/crm/pipelines/{id}/rows",...$})}queryCrmPipelineRows($){return($.client??this.client).post({url:"/crm/pipelines/{id}/rows",...$,headers:{"Content-Type":"application/json",...$.headers}})}shareCrmPipeline($){return($.client??this.client).put({url:"/crm/pipelines/{id}/sharing",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCrmPipelineTable($){return($.client??this.client).get({url:"/crm/pipelines/{id}/table",...$})}trashCrmPipeline($){return($.client??this.client).put({url:"/crm/pipelines/{id}/trash",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCrmTeamSettings($){return($?.client??this.client).get({url:"/crm/settings",...$})}putCrmTeamSettings($){return($.client??this.client).put({url:"/crm/settings",...$,headers:{"Content-Type":"application/json",...$.headers}})}resetCrmTeamStages($){return($?.client??this.client).delete({url:"/crm/stages",...$})}putCrmTeamStages($){return($.client??this.client).put({url:"/crm/stages",...$,headers:{"Content-Type":"application/json",...$.headers}})}listDatabases($){return($?.client??this.client).get({url:"/databases",...$})}createDatabase($){return($.client??this.client).post({url:"/databases",...$,headers:{"Content-Type":"application/json",...$.headers}})}saveDatabaseQuery($){return($.client??this.client).post({url:"/databases/queries",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDatabaseQuery($){return($.client??this.client).get({url:"/databases/queries/{query_id}",...$})}queryDatabases($){return($.client??this.client).post({url:"/databases/query",...$,headers:{"Content-Type":"application/json",...$.headers}})}ensureStarterHandler($){return($?.client??this.client).post({url:"/databases/starter",...$})}deliverDatabaseWebhook($){return($.client??this.client).post({url:"/databases/webhooks/{token}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDatabase($){return($.client??this.client).get({url:"/databases/{id}",...$})}shareDatabaseAwareness($){return($.client??this.client).put({url:"/databases/{id}/awareness",...$,headers:{"Content-Type":"application/json",...$.headers}})}undoDatabaseChange($){return($.client??this.client).post({url:"/databases/{id}/changes/{change}/undo",...$})}importDatabaseTable($){return($.client??this.client).post({url:"/databases/{id}/import",...$,headers:{"Content-Type":"application/json",...$.headers}})}applyDatabaseOps($){return($.client??this.client).post({url:"/databases/{id}/ops",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDatabasePermissions($){return($.client??this.client).get({url:"/databases/{id}/permissions",...$})}updateDatabasePermissions($){return($.client??this.client).patch({url:"/databases/{id}/permissions",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDatabaseTableChanges($){return($.client??this.client).get({url:"/databases/{id}/tables/{table_id}/changes",...$})}listDatabaseColumnCasts($){return($.client??this.client).get({url:"/databases/{id}/tables/{table_id}/columns/{column_id}/casts",...$})}convertDatabaseColumn($){return($.client??this.client).post({url:"/databases/{id}/tables/{table_id}/columns/{column_id}/conversion",...$,headers:{"Content-Type":"application/json",...$.headers}})}inferDatabaseColumnType($){return($.client??this.client).post({url:"/databases/{id}/tables/{table_id}/columns/{column_id}/infer-type",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDatabaseRowHistory($){return($.client??this.client).get({url:"/databases/{id}/tables/{table_id}/rows/{row_id}/history",...$})}getDatabaseViewPositions($){return($.client??this.client).get({url:"/databases/{id}/views/{view_id}/positions",...$})}listDatabaseWebhooks($){return($.client??this.client).get({url:"/databases/{id}/webhooks",...$})}createDatabaseWebhook($){return($.client??this.client).post({url:"/databases/{id}/webhooks",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteDatabaseWebhook($){return($.client??this.client).delete({url:"/databases/{id}/webhooks/{webhook_id}",...$})}transcribeDictation($){return($.client??this.client).post({bodySerializer:null,url:"/dictation/transcribe",...$,headers:{"Content-Type":"audio/webm",...$.headers}})}getUserDocumentsHandler($){return($.client??this.client).get({url:"/documents",...$})}createDocument($){return($.client??this.client).post({url:"/documents",...$,headers:{"Content-Type":"application/json",...$.headers}})}createCanvasHandler($){return($.client??this.client).post({url:"/documents/create_canvas",...$,headers:{"Content-Type":"application/json",...$.headers}})}createMarkdownHandler($){return($.client??this.client).post({url:"/documents/create_markdown",...$,headers:{"Content-Type":"application/json",...$.headers}})}createSkillHandler($){return($.client??this.client).post({url:"/documents/create_skill",...$,headers:{"Content-Type":"application/json",...$.headers}})}createSnippetHandler($){return($.client??this.client).post({url:"/documents/create_snippet",...$,headers:{"Content-Type":"application/json",...$.headers}})}createTaskHandler($){return($.client??this.client).post({url:"/documents/create_task",...$,headers:{"Content-Type":"application/json",...$.headers}})}getGithubPullRequestTasks($){return($.client??this.client).post({url:"/documents/github_prs/tasks",...$,headers:{"Content-Type":"application/json",...$.headers}})}initializeUserDocuments($){return($?.client??this.client).post({url:"/documents/initialize_user_documents",...$})}getDocumentListHandler($){return($?.client??this.client).get({url:"/documents/list",...$})}validateDocumentPermissionsToken($){return($.client??this.client).post({url:"/documents/permissions_token/validate",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDocumentPermissionsToken($){return($.client??this.client).post({url:"/documents/permissions_token/{document_id}",...$})}presaveDocumentHandler($){return($.client??this.client).put({url:"/documents/presave/{document_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getBatchPreviewHandler($){return($.client??this.client).post({url:"/documents/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDocumentByTeamSlug($){return($.client??this.client).get({url:"/documents/slug/{slug}",...$})}handler($){return($?.client??this.client).get({url:"/documents/starter_docs",...$})}getSystemSkillsHandler($){return($?.client??this.client).get({url:"/documents/system_skills",...$})}deleteDocument($){return($.client??this.client).delete({url:"/documents/{document_id}",...$})}getDocument($){return($.client??this.client).get({url:"/documents/{document_id}",...$})}editDocument($){return($.client??this.client).patch({url:"/documents/{document_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}saveDocumentHandler($){return($.client??this.client).put({url:"/documents/{document_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDocumentBranchName($){return($.client??this.client).get({url:"/documents/{document_id}/branch_name",...$})}copyDocument($){return($.client??this.client).post({url:"/documents/{document_id}/copy",...$,headers:{"Content-Type":"application/json",...$.headers}})}exportDocument($){return($.client??this.client).get({url:"/documents/{document_id}/export",...$})}getDocumentGithubPullRequests($){return($.client??this.client).get({url:"/documents/{document_id}/github_prs",...$})}getLocationHandler($){return($.client??this.client).get({url:"/documents/{document_id}/location",...$})}getDocumentLocationV3($){return($.client??this.client).get({url:"/documents/{document_id}/location_v3",...$})}permanentlyDeleteDocument($){return($.client??this.client).delete({url:"/documents/{document_id}/permanent",...$})}getDocumentProcessingResult($){return($.client??this.client).get({url:"/documents/{document_id}/processing",...$})}jobProcessingResultHandler($){return($.client??this.client).get({url:"/documents/{document_id}/processing/{job_id}",...$})}revertDeleteDocument($){return($.client??this.client).put({url:"/documents/{document_id}/revert_delete",...$})}getDocumentShortId($){return($.client??this.client).get({url:"/documents/{document_id}/short_id",...$})}simpleSave($){return($.client??this.client).put({url:"/documents/{document_id}/simple_save",...$})}getDocumentTeamShare($){return($.client??this.client).get({url:"/documents/{document_id}/team_share",...$})}setDocumentTeamShare($){return($.client??this.client).put({url:"/documents/{document_id}/team_share",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDocumentTextContent($){return($.client??this.client).get({url:"/documents/{document_id}/text-content",...$})}getDocumentViewsHandler($){return($.client??this.client).get({url:"/documents/{document_id}/views",...$})}getDocumentVersion($){return($.client??this.client).get({url:"/documents/{document_id}/{document_version_id}",...$})}accessRequestsState($){return($.client??this.client).get({url:"/entities/{entity_type}/{entity_id}/access-requests",...$})}accessRequestsCancel($){return($.client??this.client).delete({url:"/entities/{entity_type}/{entity_id}/access-requests/mine",...$})}accessRequestsSubmit($){return($.client??this.client).put({url:"/entities/{entity_type}/{entity_id}/access-requests/mine",...$,headers:{"Content-Type":"application/json",...$.headers}})}accessRequestsResolve($){return($.client??this.client).post({url:"/entities/{entity_type}/{entity_id}/access-requests/{request_id}/resolve",...$,headers:{"Content-Type":"application/json",...$.headers}})}accessRequestsDirect($){return($.client??this.client).get({url:"/entities/{entity_type}/{entity_id}/direct-access",...$})}accessRequestsRemoveDirect($){return($.client??this.client).delete({url:"/entities/{entity_type}/{entity_id}/direct-access/{user_id}",...$})}accessRequestsSetDirect($){return($.client??this.client).put({url:"/entities/{entity_type}/{entity_id}/direct-access/{user_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getEntityPermission($){return($.client??this.client).get({url:"/entity/{entity_type}/{entity_id}/permissions",...$})}listFavorites($){return($?.client??this.client).get({url:"/favorites",...$})}addFavorite($){return($.client??this.client).post({url:"/favorites",...$,headers:{"Content-Type":"application/json",...$.headers}})}reorderFavorites($){return($.client??this.client).patch({url:"/favorites/reorder",...$,headers:{"Content-Type":"application/json",...$.headers}})}removeFavoriteByEntity($){return($.client??this.client).delete({url:"/favorites/{entity_type}/{entity_id}",...$})}getForeignEntityBySource($){return($.client??this.client).get({url:"/foreign_entity/by_source/{source}/{foreign_entity_id}",...$})}getForeignEntity($){return($.client??this.client).get({url:"/foreign_entity/{id}",...$})}listForms($){return($.client??this.client).get({url:"/forms",...$})}createForm($){return($.client??this.client).post({url:"/forms",...$,headers:{"Content-Type":"application/json",...$.headers}})}listAccessibleForms($){return($?.client??this.client).get({url:"/forms/accessible",...$})}getForm($){return($.client??this.client).get({url:"/forms/{id}",...$})}updateForm($){return($.client??this.client).patch({url:"/forms/{id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}collaborateForm($){return($.client??this.client).post({url:"/forms/{id}/collaboration",...$})}putFormLayout($){return($.client??this.client).put({url:"/forms/{id}/layout",...$,headers:{"Content-Type":"application/json",...$.headers}})}getFormPermissions($){return($.client??this.client).get({url:"/forms/{id}/permissions",...$})}updateFormPermissions($){return($.client??this.client).patch({url:"/forms/{id}/permissions",...$,headers:{"Content-Type":"application/json",...$.headers}})}submitFormResponse($){return($.client??this.client).post({url:"/forms/{id}/responses",...$,headers:{"Content-Type":"application/json",...$.headers}})}getMyFormResponse($){return($.client??this.client).get({url:"/forms/{id}/responses/mine",...$})}editMyFormResponse($){return($.client??this.client).put({url:"/forms/{id}/responses/mine",...$,headers:{"Content-Type":"application/json",...$.headers}})}getFormResponseSummary($){return($.client??this.client).get({url:"/forms/{id}/responses/summary",...$})}getFormTally($){return($.client??this.client).get({url:"/forms/{id}/tally",...$})}installSync($){return($?.client??this.client).get({url:"/github/install-sync",...$})}getGithubPullRequestFacets($){return($?.client??this.client).get({url:"/github_pull_requests/facets",...$})}getGithubPullRequest($){return($.client??this.client).get({url:"/github_pull_requests/{id}",...$})}getGithubPullRequestChanges($){return($.client??this.client).get({url:"/github_pull_requests/{id}/changes",...$})}getGithubPullRequestChangesPatch($){return($.client??this.client).get({url:"/github_pull_requests/{id}/changes/patch",...$})}createHarnessPairing($){return($.client??this.client).post({url:"/harness-pairings",...$,headers:{"Content-Type":"application/json",...$.headers}})}getHarnessPairing($){return($.client??this.client).get({url:"/harness-pairings/{code}",...$})}approveHarnessPairing($){return($.client??this.client).post({url:"/harness-pairings/{code}/approve",...$,headers:{"Content-Type":"application/json",...$.headers}})}claimHarnessPairing($){return($.client??this.client).post({url:"/harness-pairings/{pairing_id}/claim",...$,headers:{"Content-Type":"application/json",...$.headers}})}listHarnesses($){return($?.client??this.client).get({url:"/harnesses",...$})}deleteSelfHarness($){return($?.client??this.client).delete({url:"/harnesses/me",...$})}getSelfHarness($){return($?.client??this.client).get({url:"/harnesses/me",...$})}listHarnessAgents($){return($?.client??this.client).get({url:"/harnesses/me/agents",...$})}listHarnessSessions($){return($?.client??this.client).get({url:"/harnesses/me/sessions",...$})}deleteHarness($){return($.client??this.client).delete({url:"/harnesses/{harness_id}",...$})}healthHandler($){return($?.client??this.client).get({url:"/health",...$})}getHistoryHandler($){return($?.client??this.client).get({url:"/history",...$})}deleteHistoryHandler($){return($.client??this.client).delete({url:"/history/{item_type}/{item_id}",...$})}upsertHistoryHandler($){return($.client??this.client).post({url:"/history/{item_type}/{item_id}",...$})}listInitiatives($){return($?.client??this.client).get({url:"/initiatives",...$})}createInitiative($){return($.client??this.client).post({url:"/initiatives",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteInitiative($){return($.client??this.client).delete({url:"/initiatives/{initiative_id}",...$})}getInitiative($){return($.client??this.client).get({url:"/initiatives/{initiative_id}",...$})}updateInitiative($){return($.client??this.client).patch({url:"/initiatives/{initiative_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getInstructionsHandler($){return($?.client??this.client).get({url:"/instructions",...$})}createInstructionsHandler($){return($?.client??this.client).post({url:"/instructions",...$})}getItemsSoup($){return($?.client??this.client).get({url:"/items/soup",...$})}postItemsSoup($){return($.client??this.client).post({url:"/items/soup",...$,headers:{"Content-Type":"application/json",...$.headers}})}postItemsSoupAst($){return($.client??this.client).post({url:"/items/soup/ast",...$,headers:{"Content-Type":"application/json",...$.headers}})}postItemsSoupAstGrouped($){return($.client??this.client).post({url:"/items/soup/ast/grouped",...$,headers:{"Content-Type":"application/json",...$.headers}})}messageTimeline($){return($.client??this.client).get({url:"/messages/{parent_type}/{parent_id}",...$})}entityMessageCreate($){return($.client??this.client).post({url:"/messages/{parent_type}/{parent_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}entityMessageDeleteMessage($){return($.client??this.client).delete({url:"/messages/{parent_type}/{parent_id}/items/{id}",...$})}entityMessageGetMessage($){return($.client??this.client).get({url:"/messages/{parent_type}/{parent_id}/items/{id}",...$})}entityMessageEdit($){return($.client??this.client).patch({url:"/messages/{parent_type}/{parent_id}/items/{id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}entityMessageReact($){return($.client??this.client).post({url:"/messages/{parent_type}/{parent_id}/items/{id}/reactions",...$,headers:{"Content-Type":"application/json",...$.headers}})}entityMessageLegacy($){return($.client??this.client).get({url:"/messages/{parent_type}/{parent_id}/legacy/{legacy_id}",...$})}entityMessageDeleteThread($){return($.client??this.client).delete({url:"/messages/{parent_type}/{parent_id}/threads/{id}",...$})}entityMessageGetThread($){return($.client??this.client).get({url:"/messages/{parent_type}/{parent_id}/threads/{id}",...$})}entityMessagePatchThread($){return($.client??this.client).patch({url:"/messages/{parent_type}/{parent_id}/threads/{id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}messageTimelineEntries($){return($.client??this.client).get({url:"/messages/{parent_type}/{parent_id}/timeline",...$})}entityMessageTyping($){return($.client??this.client).post({url:"/messages/{parent_type}/{parent_id}/typing",...$,headers:{"Content-Type":"application/json",...$.headers}})}linkedAccount($){return($?.client??this.client).get({url:"/meta/linked/account",...$})}linkedChats($){return($?.client??this.client).get({url:"/meta/linked/chats",...$})}linkedConfiguration($){return($?.client??this.client).get({url:"/meta/linked/configuration",...$})}linkedConnect($){return($.client??this.client).post({url:"/meta/linked/connect",...$,headers:{"Content-Type":"application/json",...$.headers}})}linkedDisconnect($){return($.client??this.client).post({url:"/meta/linked/disconnect",...$,headers:{"Content-Type":"application/json",...$.headers}})}linkedAdopt($){return($.client??this.client).post({url:"/meta/linked/groups/adopt",...$,headers:{"Content-Type":"application/json",...$.headers}})}linkedCancelPairing($){return($.client??this.client).delete({url:"/meta/linked/pairing/{id}",...$})}linkedPairing($){return($.client??this.client).get({url:"/meta/linked/pairing/{id}",...$})}linkedPasskey($){return($.client??this.client).post({url:"/meta/linked/pairing/{id}/passkey",...$,headers:{"Content-Type":"application/json",...$.headers}})}whatsappGroups($){return($?.client??this.client).get({url:"/meta/linked/whatsapp-groups",...$})}linkedDetach($){return($.client??this.client).delete({url:"/meta/linked/whatsapp-groups/{group_id}",...$})}whatsappGroup($){return($.client??this.client).get({url:"/meta/linked/whatsapp-groups/{group_id}",...$})}linkedUpload($){return($.client??this.client).post({..._1,url:"/meta/linked/whatsapp-groups/{group_id}/attachments",...$,headers:{"Content-Type":null,...$.headers}})}linkedDelivery($){return($.client??this.client).post({url:"/meta/linked/whatsapp-groups/{group_id}/delivery",...$,headers:{"Content-Type":"application/json",...$.headers}})}whatsappGroupMessages($){return($.client??this.client).get({url:"/meta/linked/whatsapp-groups/{group_id}/messages",...$})}linkedMessageAttachments($){return($.client??this.client).post({url:"/meta/linked/whatsapp-groups/{group_id}/messages/attachments",...$,headers:{"Content-Type":"application/json",...$.headers}})}whatsappGroupPermissions($){return($.client??this.client).get({url:"/meta/linked/whatsapp-groups/{group_id}/permissions",...$})}whatsappGroupUpdatePermissions($){return($.client??this.client).patch({url:"/meta/linked/whatsapp-groups/{group_id}/permissions",...$,headers:{"Content-Type":"application/json",...$.headers}})}whatsappGroupRead($){return($.client??this.client).post({url:"/meta/linked/whatsapp-groups/{group_id}/read",...$,headers:{"Content-Type":"application/json",...$.headers}})}whatsappGroupSends($){return($.client??this.client).get({url:"/meta/linked/whatsapp-groups/{group_id}/sends",...$})}linkedReply($){return($.client??this.client).post({url:"/meta/linked/whatsapp-groups/{group_id}/sends",...$,headers:{"Content-Type":"application/json",...$.headers}})}getPinsHandler($){return($?.client??this.client).get({url:"/pins",...$})}reorderPinsHandler($){return($.client??this.client).patch({url:"/pins",...$,headers:{"Content-Type":"application/json",...$.headers}})}removePinHandler($){return($.client??this.client).delete({url:"/pins/{pinned_item_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}addPinHandler($){return($.client??this.client).post({url:"/pins/{pinned_item_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getProjectsHandler($){return($?.client??this.client).get({url:"/projects",...$})}createProjectHandler($){return($.client??this.client).post({url:"/projects",...$,headers:{"Content-Type":"application/json",...$.headers}})}getPendingProjectsHandler($){return($?.client??this.client).get({url:"/projects/pending",...$})}getBatchProjectPreview($){return($.client??this.client).post({url:"/projects/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}uploadFolderHandler($){return($.client??this.client).post({url:"/projects/upload",...$,headers:{"Content-Type":"application/json",...$.headers}})}uploadExtractFolderHandler($){return($.client??this.client).post({url:"/projects/upload_extract",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteProjectHandler($){return($.client??this.client).delete({url:"/projects/{id}",...$})}getProjectHandler($){return($.client??this.client).get({url:"/projects/{id}",...$})}getProjectUserAccessLevel($){return($.client??this.client).get({url:"/projects/{id}/access_level",...$})}getProjectContentHandler($){return($.client??this.client).get({url:"/projects/{id}/content",...$})}permanentlyDeleteProject($){return($.client??this.client).delete({url:"/projects/{id}/permanent",...$})}getProjectPermissionsV2($){return($.client??this.client).get({url:"/projects/{id}/permissions",...$})}revertDeleteProject($){return($.client??this.client).put({url:"/projects/{id}/revert_delete",...$})}recentlyDeleted($){return($?.client??this.client).get({url:"/recents/deleted",...$})}listEmailReminders($){return($?.client??this.client).get({url:"/reminders/email/collection",...$})}getEmailFollowup($){return($.client??this.client).get({url:"/reminders/email/{thread_id}",...$})}setEmailFollowup($){return($.client??this.client).put({url:"/reminders/email/{thread_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getViewsHandler($){return($?.client??this.client).get({url:"/saved_views",...$})}createViewHandler($){return($.client??this.client).post({url:"/saved_views",...$,headers:{"Content-Type":"application/json",...$.headers}})}excludeDefaultViewHandler($){return($.client??this.client).post({url:"/saved_views/exclude_default",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteViewHandler($){return($.client??this.client).delete({url:"/saved_views/{saved_view_id}",...$})}patchViewHandler($){return($.client??this.client).patch({url:"/saved_views/{saved_view_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}listSlackImports($){return($?.client??this.client).get({url:"/slack/imports",...$})}createSlackImport($){return($.client??this.client).post({url:"/slack/imports",...$,headers:{"Content-Type":"application/json",...$.headers}})}getSlackImport($){return($.client??this.client).get({url:"/slack/imports/{job_id}",...$})}cancelSlackImport($){return($.client??this.client).post({url:"/slack/imports/{job_id}/cancel",...$})}finalizeSlackImport($){return($.client??this.client).post({url:"/slack/imports/{job_id}/finalize",...$})}registerSlackImportUploads($){return($.client??this.client).post({url:"/slack/imports/{job_id}/uploads",...$,headers:{"Content-Type":"application/json",...$.headers}})}completeSlackImportUploads($){return($.client??this.client).post({url:"/slack/imports/{job_id}/uploads/complete",...$,headers:{"Content-Type":"application/json",...$.headers}})}bulkWakeupSyncServiceDocuments($){return($.client??this.client).post({url:"/sync_service/wakeup",...$,headers:{"Content-Type":"application/json",...$.headers}})}editThreadV2($){return($.client??this.client).patch({url:"/threads/{thread_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}listUserApiKeys($){return($?.client??this.client).get({url:"/user-api-keys",...$})}createUserApiKey($){return($.client??this.client).post({url:"/user-api-keys",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteUserApiKey($){return($.client??this.client).delete({url:"/user-api-keys/{id}",...$})}deleteUserDocumentViewLocation($){return($.client??this.client).delete({url:"/user_document_view_location/{document_id}",...$})}getUserDocumentViewLocation($){return($.client??this.client).get({url:"/user_document_view_location/{document_id}",...$})}upsertUserDocumentViewLocation($){return($.client??this.client).post({url:"/user_document_view_location/{document_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDocumentPermissionsV2($){return($.client??this.client).get({url:"/v2/documents/{document_id}/permissions",...$})}editProjectV2($){return($.client??this.client).patch({url:"/v2/projects/{id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}streamEvents($){return($.client??this.client).sse.get({url:"/webhook/events/stream",...$})}listWebhooks($){return($?.client??this.client).get({url:"/webhook/webhooks",...$})}createWebhook($){return($.client??this.client).post({url:"/webhook/webhooks",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteWebhook($){return($.client??this.client).delete({url:"/webhook/webhooks/{webhook_id}",...$})}getWebhook($){return($.client??this.client).get({url:"/webhook/webhooks/{webhook_id}",...$})}patchWebhook($){return($.client??this.client).patch({url:"/webhook/webhooks/{webhook_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}validateWebhook($){return($.client??this.client).post({url:"/webhook/webhooks/{webhook_id}/validate",...$})}}function J6({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...Q}){let J,I=Y??((V)=>new Promise((W)=>setTimeout(W,V)));return{stream:async function*(){let V=K??3000,W=0,T=Q.signal??new AbortController().signal;while(!0){if(T.aborted)break;W++;let A=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)A.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:A,signal:T},_=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 H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",k=()=>{try{H.cancel()}catch{}};T.addEventListener("abort",k);try{while(!0){let{done:l,value:r}=await H.read();if(l)break;U+=r,U=U.replace(/\r\n?/g,``);let g=U.split(``);U=g.pop()??"";for(let p of g){let a=p.split(``),F=[],y;for(let R of a)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))y=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let h=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(h))V=h}let C,v=!1;if(F.length){let R=F.join(`-`);try{C=JSON.parse(R),v=!0}catch{C=R}}if(v){if(S)await S(C);if(x)C=await x(C)}if(j?.({data:C,event:y,id:J,retry:V}),F.length)yield C}}}finally{T.removeEventListener("abort",k),H.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 Z4=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},X4=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},K4=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},wx=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((Y)=>encodeURIComponent(Y))).join(X4(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=Z4(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return yO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},yO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},qx=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let Y=[];Object.entries(S).forEach(([Q,J])=>{Y=[...Y,Q,$?J:encodeURIComponent(J)]});let L=Y.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=K4(x),X=Object.entries(S).map(([Y,L])=>yO({allowReserved:$,name:x==="deepObject"?`${j}[${Y}]`:Y,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var Y4=/\{[^{}]+\}/g,G4=({path:$,url:O})=>{let j=O,x=O.match(Y4);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 Y=$[Z];if(Y===void 0||Y===null)continue;if(Array.isArray(Y)){j=j.replace(S,wx({explode:K,name:Z,style:X,value:Y}));continue}if(typeof Y==="object"){j=j.replace(S,qx({explode:K,name:Z,style:X,value:Y,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${yO({name:Z,value:Y})}`);continue}let L=encodeURIComponent(X==="label"?`.${Y}`:Y);j=j.replace(S,L)}return j},Q6=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=G4({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function M1($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var J6=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var V6={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var W6=({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 Y=wx({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(Y)S.push(Y)}else if(typeof Z==="object"){let Y=qx({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(Y)S.push(Y)}else{let Y=yO({allowReserved:X.allowReserved,name:K,value:Z});if(Y)S.push(Y)}}return S.join("&")}},B6=($)=>{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},Q4=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function L6($){for(let O of $.security??[]){if(Q4($,O.name))continue;let j=await J6(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var A1=($)=>Q6({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:W6($.querySerializer),url:$.url}),F1=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=bx($.headers,O.headers),j},J4=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},bx=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?J4(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 fx{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 N6=()=>({error:new fx,request:new fx,response:new fx}),V4=W6({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),W4={"Content-Type":"application/json"},Vj=($={})=>({...V6,headers:W4,parseAs:"auto",querySerializer:V4,...$});var E1=($={})=>{let O=F1(Vj(),$),j=()=>({...O}),x=(Q)=>{return O=F1(O,Q),j()},S=N6(),K=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:bx(O.headers,Q.headers),serializedBody:void 0};if(J.security)await L6(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=A1(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),T={redirect:"follow",...V,body:M1(V)};z=new Request(B,T);for(let N of S.request.fns)if(N)z=await N(z,V);let A=V.fetch;W=await A(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"?B6(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await W[N]();break;case"json":{let U=await W.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let _=await W.text(),q;try{q=JSON.parse(_)}catch{}throw q??_}catch(V){let B=V;for(let T of S.error.fns)if(T)B=await T(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}),Y=(Q)=>async(J)=>{let{opts:I,url:z}=await K(J);return G6({...I,body:I.body,method:Q,onRequest:async(W,V)=>{let B=new Request(W,V);for(let T of S.request.fns)if(T)B=await T(B,I);return B},serializedBody:M1(I),url:z})};return{buildUrl:(Q)=>A1({...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:Y("CONNECT"),delete:Y("DELETE"),get:Y("GET"),head:Y("HEAD"),options:Y("OPTIONS"),patch:Y("PATCH"),post:Y("POST"),put:Y("PUT"),trace:Y("TRACE")},trace:X("TRACE")}};var U6=E1(Vj());class z6{client;constructor($){this.client=$?.client??U6}}class I6{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class kx extends z6{static __registry=new I6;constructor($){super($);kx.__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 T6={dev:"https://dev.macro.com",prod:"https://macro.com",local:"http://localhost:3000"},w1={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 B4($,O){let j=O?.channel_id;return O&&j?{channel:b.byId($,j),thread:new h$($,j,O.thread_id)}:{channel:void 0,thread:void 0}}function E$($,O){return{session:i.byId($,O.session_id),owner:P.byId($,O.owner_id),...B4($,O.origin)}}function vO($,O,j){let x=O.origin?.channel_id;return x&&j?e.byId($,x,j):void 0}function hO($,O){return O?P.byId($,O):void 0}function H6($,O){return c(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:hO($,j.actor),announcement:vO($,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:hO($,j.actor),announcement:vO($,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:hO($,j.actor),announcement:vO($,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:hO($,j.last_turn?.actor),announcement:vO($,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:vO($,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:hO($,j.mentioned_by),mentioned:j.mentioned.map((x)=>P.byId($,x))})).with({event_type:"agent_session.stopped"},({metadata:j})=>({event_type:"agent_session.stopped",metadata:j,...E$($,j.identity),actor:hO($,j.turn_in_flight?.actor),announcement:vO($,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 R6="macro|";function P$($,O){return O.startsWith(R6)&&O.length>R6.length?P.byId($,O.toLowerCase()):void 0}function D6($,O){return c(O).with({event_type:"channel.created"},({metadata:j})=>({event_type:"channel.created",metadata:j,channel:b.byId($,j.channel_id),actor:P$($,j.actor),participants:j.participant_user_ids.map((x)=>P.byId($,x))})).with({event_type:"channel.updated"},({metadata:j})=>({event_type:"channel.updated",metadata:j,channel:b.byId($,j.channel_id),actor:P$($,j.actor)})).with({event_type:"channel.deleted"},({metadata:j})=>({event_type:"channel.deleted",metadata:j,channel:b.byId($,j.channel_id),actor:P$($,j.actor)})).with({event_type:"channel.picture_changed"},({metadata:j})=>({event_type:"channel.picture_changed",metadata:j,channel:b.byId($,j.channel_id),actor:P$($,j.actor)})).with({event_type:"channel.participant_added"},({metadata:j})=>({event_type:"channel.participant_added",metadata:j,channel:b.byId($,j.channel_id),addedBy:P$($,j.added_by),addedUsers:j.added_user_ids.map((x)=>P.byId($,x))})).with({event_type:"channel.participant_removed"},({metadata:j})=>({event_type:"channel.participant_removed",metadata:j,channel:b.byId($,j.channel_id),removedBy:P.byId($,j.removed_by),removedUsers:j.removed_user_ids.map((x)=>P.byId($,x))})).exhaustive((j)=>{console.warn("macro sdk: unknown channel event",j);return})}function _6($,O){return c(O).with({event_type:"document.created"},({metadata:j})=>({event_type:"document.created",metadata:j,document:w.byId($,j.document_id),owner:P.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:w.byId($,j.document_id),owner:P.byId($,j.owner),actor:j.actor_user_id?P.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:w.byId($,j.document_id),actor:j.actor_user_id?P.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:w.byId($,j.document_id),owner:P.byId($,j.owner)})).with({event_type:"document.sync_content_updated"},({metadata:j})=>({event_type:"document.sync_content_updated",metadata:j,document:w.byId($,j.document_id)})).with({event_type:"document.purged"},({metadata:j})=>({event_type:"document.purged",metadata:j,document:w.byId($,j.document_id)})).with({event_type:"document.copied"},({metadata:j})=>({event_type:"document.copied",metadata:j,document:w.byId($,j.document_id),sourceDocument:w.byId($,j.source_document_id),owner:P.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:w.byId($,j.document_id)})).exhaustive((j)=>{console.warn("macro sdk: unknown document event",j);return})}function mO($,O,j=[]){let x=O.parent;if(x.type==="call")return{type:"call",call:Q$.byId($,x.id),message:u$.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 h$($,x.id,O.thread_id):void 0};return{type:"document",document:w.byId($,x.id),comment:c$.byId($,x.id,O.message_id),threadId:O.root_id}}function C6($,O){return c(O).with({event_type:"message.posted"},({metadata:j})=>({event_type:"message.posted",metadata:j,target:mO($,j,j.mentions),sender:P$($,j.sender)})).with({event_type:"message.mentioned"},({metadata:j})=>({event_type:"message.mentioned",metadata:j,target:mO($,j),sender:P$($,j.sender)})).with({event_type:"message.patched"},({metadata:j})=>({event_type:"message.patched",metadata:j,target:mO($,j),actor:P$($,j.actor)})).with({event_type:"message.deleted"},({metadata:j})=>({event_type:"message.deleted",metadata:j,target:mO($,j),actor:P$($,j.actor)})).with({event_type:"message.attachment_created"},({metadata:j})=>({event_type:"message.attachment_created",metadata:j,target:mO($,j),actor:P$($,j.actor)})).with({event_type:"message.attachment_removed"},({metadata:j})=>({event_type:"message.attachment_removed",metadata:j,target:mO($,j),actor:P$($,j.actor)})).exhaustive((j)=>{console.warn("macro sdk: unknown message event",j);return})}async function P6($){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 L4="webhook.validation.test";function N4($,O){return c(O).with({event_type:Z$.string.startsWith("document.")},(j)=>_6($,j)).with({event_type:Z$.string.startsWith("channel.")},(j)=>D6($,j)).with({event_type:Z$.string.startsWith("message.")},(j)=>C6($,j)).with({event_type:Z$.string.startsWith("agent_session.")},(j)=>H6($,j)).otherwise(()=>{return})}class q1{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 P6({secret:this.secret,timestamp:O.timestamp??"",rawBody:$,signature:O.signature??""}))throw new f("invalid webhook signature");if(O.event===L4)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=N4(this.client,j);if(!S)return;await Promise.all([...x].map((K)=>K(S)))}}function M6(){return}var U4=0,f1;function z4($){f1=$}function U$($,O,j){if(!j&&!f1)return $;let x=(S)=>{for(let K of[f1,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(...Y)=>{let L={id:++U4,service:O,operation:K};x({...L,status:"started"});try{let Q=await Reflect.apply(X,S,Y),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 F6="x-macro-user-api-key",I4="mak_",b1="mbot_";function T4($){return c($).with(Z$.string.startsWith(b1),()=>{throw Error("bot token passed as a user credential. Use auth: { type: 'bot', token } or MACRO_BOT_TOKEN.")}).with(Z$.string.startsWith(I4),(O)=>[F6,O]).otherwise((O)=>["Authorization",`Bearer ${O}`])}async function A6($){return typeof $==="function"?await $():$}async function H4($,O,j){return c($).with({type:"bot"},async(x)=>{let S=await A6(x.token);if(!S.startsWith(b1))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(b1))throw Error("bot token passed as a user credential. Use auth: { type: 'bot', token } or MACRO_BOT_TOKEN.");return[[F6,x]]}).with({type:"user"},async({token:x})=>{return[T4(await A6(x))]}).exhaustive()}class k1{scheduledAction;unfurl;agentHarness;auth;calendar;cognition;contacts;email;notification;properties;search;storage;webAppUrl;wsVerify;events;authConfig;hosts;localPortmap;requestedAs;selfBotRecord;selfPrincipal;constructor($){let O=R4($),j=O==="local"?M6():void 0,x={...w1[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??T6[O],this.authConfig=D4($),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=U$(new Tx({client:this.makeClient(x["scheduled-action"])}),"scheduled-action",$.onRequest),this.unfurl=U$(new kx({client:this.makeClient(x.unfurl)}),"unfurl",$.onRequest),this.agentHarness=U$(new bj({client:this.makeClient(x["agent-harness"])}),"agent-harness",$.onRequest),this.auth=U$(new hj({client:this.makeClient(x.auth)}),"auth",$.onRequest),this.calendar=U$(new lj({client:this.makeClient(x.calendar)}),"calendar",$.onRequest),this.cognition=U$(new nj({client:this.makeClient(x.cognition)}),"cognition",$.onRequest),this.contacts=U$(new $x({client:this.makeClient(x.contacts)}),"contacts",$.onRequest),this.email=U$(new Zx({client:this.makeClient(x.email)}),"email",$.onRequest),this.notification=U$(new Qx({client:this.makeClient(x.notification)}),"notification",$.onRequest),this.properties=U$(new Lx({client:this.makeClient(x.properties)}),"properties",$.onRequest),this.search=U$(new Cx({client:this.makeClient(x.search)}),"search",$.onRequest),this.storage=U$(new Ex({client:this.makeClient(x.storage)}),"storage",$.onRequest);let K=typeof process<"u"?{}.MACRO_WEBHOOK_SECRET:void 0,Z=$.webhookSecret??K;this.events=new q1(this,Z)}hasActingUser(){return this.authConfig.type==="user"||this.requestedAs!==void 0}selfBot(){return this.selfBotRecord??=new lO(this).me().catch(($)=>{throw this.selfBotRecord=void 0,$}),this.selfBotRecord}myPrincipalId(){return this.selfPrincipal??=(this.authConfig.type==="bot"?this.selfBot().then(($)=>`bot|${$.id}`):P.me(this).then(($)=>$.id)).catch(($)=>{throw this.selfPrincipal=void 0,$}),this.selfPrincipal}makeClient($){let O=Jj({baseUrl:$});return O.interceptors.request.use(async(j)=>{let x=await H4(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 R4($){if($.env)return $.env;let O=typeof process<"u"?{}.MACRO_ENV:void 0;if(!O)return"prod";if(!(O in w1))throw Error(`invalid MACRO_ENV "${O}" — expected local, dev, or prod`);return O}function D4($){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 g1{id;constructor($){this.id=$}static byId($){return new g1($)}toJSON(){return{id:this.id}}}class E6{routines;unfurls;agents;initiatives;apiKeys;harnesses;meetings;githubPullRequests;entityMentions;agentSessions;ai;bots;calendar;calls;channels;whatsapp;chats;crm;databases;documents;email;favorites;foreignEntities;forms;notifications;pins;projects;properties;tasks;teams;users;webhooks;workspace;events;webAppUrl;_client;opts;constructor($){this.opts=$;let O=new k1($);this._client=O,this.routines=new C0(O),this.unfurls=new A0(O),this.agents=new mx(O),this.initiatives=new N0(O),this.apiKeys=new ux(O),this.harnesses=new L0(O),this.meetings=new U0(O),this.githubPullRequests=new B0(O),this.entityMentions=new G0(O),this.agentSessions=new hx(O),this.ai=new cx(O),this.bots=new lO(O),this.calendar=new dx(O),this.calls=new lx(O),this.channels=new px(O),this.whatsapp=new w0(O),this.chats=new ax(O),this.crm=new nx(O),this.databases=new Z0(O),this.documents=new X0(O),this.email=new Y0(O),this.favorites=new Q0(O),this.foreignEntities=new J0(O),this.forms=new V0(O),this.notifications=new z0(O),this.pins=new I0(O),this.projects=new T0(O),this.properties=new H0(O),this.tasks=new P0(O),this.teams=new M0(O),this.users=new F0(O),this.webhooks=new E0(O),this.workspace=new k0(O),this.events=O.events,this.webAppUrl=O.webAppUrl}myPrincipalId(){return this._client.myPrincipalId()}requestedAs($){return new E6({...this.opts,requestedAs:$.id})}}export{i$ as wrapXml,O$ as toBody,z4 as observeRequests,b6 as msg,f6 as here,YO as WhatsAppUpload,a$ as WhatsAppSend,C$ as WhatsAppMessage,v$ as WhatsAppGroup,CO as WhatsAppChat,_O as WhatsAppAccount,s$ as UserApiKey,dO as ToolApproval,N$ as SessionReview,D0 as RoutineExecution,XO as Routine,vx as ReviewItem,W0 as PullRequestChangeset,Uj as PipelineTable,VO as PipelineRow,zj as PipelineColumn,L$ as MessageThread,H$ as Meeting,S0 as MacroOpRefusedError,E6 as Macro,SO as Initiative,RO as HarnessPairing,B$ as Harness,HO as GithubPullRequest,p$ as FormSection,TO as FormResponse,Mj as FormReference,r$ as FormQuestion,NO as FormOption,y$ as Form,IO as EntityMention,o as EntityAccess,LO as EmailFilter,BO as EmailDraft,eO as DraftAttachment,pO as DocumentVersion,JO as DocumentAnchor,oO as DevicePairing,t$ as CrmPipeline,yx as ConversationTurn,uO as CodeExecution,iO as ChatMessage,aO as ChatGeneration,g1 as ChannelPicture,QO as ChannelActivity,q$ as CalendarNote,Bj as AgentConversation,I$ as Agent,zO as AccessRequest};+`);try{C=JSON.parse(R),v=!0}catch{C=R}}if(v){if(S)await S(C);if(x)C=await x(C)}if(j?.({data:C,event:y,id:J,retry:V}),F.length)yield C}}}finally{T.removeEventListener("abort",k),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&W>=Z)break;let _=Math.min(V*2**(W-1),X??30000);await I(_)}}}()}}var K4=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},Y4=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},G4=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},qx=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((Y)=>encodeURIComponent(Y))).join(Y4(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=K4(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)}`},fx=({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 Y=[];Object.entries(S).forEach(([Q,J])=>{Y=[...Y,Q,$?J:encodeURIComponent(J)]});let L=Y.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=G4(x),X=Object.entries(S).map(([Y,L])=>vO({allowReserved:$,name:x==="deepObject"?`${j}[${Y}]`:Y,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var Q4=/\{[^{}]+\}/g,J4=({path:$,url:O})=>{let j=O,x=O.match(Q4);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 Y=$[Z];if(Y===void 0||Y===null)continue;if(Array.isArray(Y)){j=j.replace(S,qx({explode:K,name:Z,style:X,value:Y}));continue}if(typeof Y==="object"){j=j.replace(S,fx({explode:K,name:Z,style:X,value:Y,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${vO({name:Z,value:Y})}`);continue}let L=encodeURIComponent(X==="label"?`.${Y}`:Y);j=j.replace(S,L)}return j},V6=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=J4({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 B6=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 W6={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var L6=({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 Y=qx({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(Y)S.push(Y)}else if(typeof Z==="object"){let Y=fx({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(Y)S.push(Y)}else{let Y=vO({allowReserved:X.allowReserved,name:K,value:Z});if(Y)S.push(Y)}}return S.join("&")}},N6=($)=>{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},V4=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function U6($){for(let O of $.security??[]){if(V4($,O.name))continue;let j=await B6(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 E1=($)=>V6({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:L6($.querySerializer),url:$.url}),w1=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=kx($.headers,O.headers),j},B4=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},kx=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?B4(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 bx{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 z6=()=>({error:new bx,request:new bx,response:new bx}),W4=L6({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),L4={"Content-Type":"application/json"},Bj=($={})=>({...W6,headers:L4,parseAs:"auto",querySerializer:W4,...$});var q1=($={})=>{let O=w1(Bj(),$),j=()=>({...O}),x=(Q)=>{return O=w1(O,Q),j()},S=z6(),K=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:kx(O.headers,Q.headers),serializedBody:void 0};if(J.security)await U6(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=E1(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,B;try{let{opts:V,url:W}=await K(Q),T={redirect:"follow",...V,body:F1(V)};z=new Request(W,T);for(let N of S.request.fns)if(N)z=await N(z,V);let A=V.fetch;B=await A(z);for(let N of S.response.fns)if(N)B=await N(B,z,V);let D={request:z,response:B};if(B.ok){let N=(V.parseAs==="auto"?N6(B.headers.get("Content-Type")):V.parseAs)??"json";if(B.status===204||B.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await B[N]();break;case"formData":U=new FormData;break;case"stream":U=B.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await B[N]();break;case"json":{let U=await B.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?B.body:{data:B.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let _=await B.text(),q;try{q=JSON.parse(_)}catch{}throw q??_}catch(V){let W=V;for(let T of S.error.fns)if(T)W=await T(W,B,z,Q);if(W=W||{},J)throw W;return I==="data"?void 0:{error:W,request:z,response:B}}},X=(Q)=>(J)=>Z({...J,method:Q}),Y=(Q)=>async(J)=>{let{opts:I,url:z}=await K(J);return J6({...I,body:I.body,method:Q,onRequest:async(B,V)=>{let W=new Request(B,V);for(let T of S.request.fns)if(T)W=await T(W,I);return W},serializedBody:F1(I),url:z})};return{buildUrl:(Q)=>E1({...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:Y("CONNECT"),delete:Y("DELETE"),get:Y("GET"),head:Y("HEAD"),options:Y("OPTIONS"),patch:Y("PATCH"),post:Y("POST"),put:Y("PUT"),trace:Y("TRACE")},trace:X("TRACE")}};var I6=q1(Bj());class T6{client;constructor($){this.client=$?.client??I6}}class H6{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 gx extends T6{static __registry=new H6;constructor($){super($);gx.__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 R6={dev:"https://dev.macro.com",prod:"https://macro.com",local:"http://localhost:3000"},f1={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 N4($,O){let j=O?.channel_id;return O&&j?{channel:b.byId($,j),thread:new h$($,j,O.thread_id)}:{channel:void 0,thread:void 0}}function E$($,O){return{session:i.byId($,O.session_id),owner:M.byId($,O.owner_id),...N4($,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?M.byId($,O):void 0}function D6($,O){return c(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)=>M.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 _6="macro|";function M$($,O){return O.startsWith(_6)&&O.length>_6.length?M.byId($,O.toLowerCase()):void 0}function C6($,O){return c(O).with({event_type:"channel.created"},({metadata:j})=>({event_type:"channel.created",metadata:j,channel:b.byId($,j.channel_id),actor:M$($,j.actor),participants:j.participant_user_ids.map((x)=>M.byId($,x))})).with({event_type:"channel.updated"},({metadata:j})=>({event_type:"channel.updated",metadata:j,channel:b.byId($,j.channel_id),actor:M$($,j.actor)})).with({event_type:"channel.deleted"},({metadata:j})=>({event_type:"channel.deleted",metadata:j,channel:b.byId($,j.channel_id),actor:M$($,j.actor)})).with({event_type:"channel.picture_changed"},({metadata:j})=>({event_type:"channel.picture_changed",metadata:j,channel:b.byId($,j.channel_id),actor:M$($,j.actor)})).with({event_type:"channel.participant_added"},({metadata:j})=>({event_type:"channel.participant_added",metadata:j,channel:b.byId($,j.channel_id),addedBy:M$($,j.added_by),addedUsers:j.added_user_ids.map((x)=>M.byId($,x))})).with({event_type:"channel.participant_removed"},({metadata:j})=>({event_type:"channel.participant_removed",metadata:j,channel:b.byId($,j.channel_id),removedBy:M.byId($,j.removed_by),removedUsers:j.removed_user_ids.map((x)=>M.byId($,x))})).exhaustive((j)=>{console.warn("macro sdk: unknown channel event",j);return})}function M6($,O){return c(O).with({event_type:"document.created"},({metadata:j})=>({event_type:"document.created",metadata:j,document:w.byId($,j.document_id),owner:M.byId($,j.owner),project:j.project_id?n.byId($,j.project_id):void 0})).with({event_type:"document.updated"},({metadata:j})=>({event_type:"document.updated",metadata:j,document:w.byId($,j.document_id),owner:M.byId($,j.owner),actor:j.actor_user_id?M.byId($,j.actor_user_id):void 0,project:j.project_id?n.byId($,j.project_id):void 0,previousProject:j.previous_project_id?n.byId($,j.previous_project_id):void 0})).with({event_type:"document.deleted"},({metadata:j})=>({event_type:"document.deleted",metadata:j,document:w.byId($,j.document_id),actor:j.actor_user_id?M.byId($,j.actor_user_id):void 0,project:j.project_id?n.byId($,j.project_id):void 0})).with({event_type:"document.content_uploaded"},({metadata:j})=>({event_type:"document.content_uploaded",metadata:j,document:w.byId($,j.document_id),owner:M.byId($,j.owner)})).with({event_type:"document.sync_content_updated"},({metadata:j})=>({event_type:"document.sync_content_updated",metadata:j,document:w.byId($,j.document_id)})).with({event_type:"document.purged"},({metadata:j})=>({event_type:"document.purged",metadata:j,document:w.byId($,j.document_id)})).with({event_type:"document.copied"},({metadata:j})=>({event_type:"document.copied",metadata:j,document:w.byId($,j.document_id),sourceDocument:w.byId($,j.source_document_id),owner:M.byId($,j.owner),project:j.project_id?n.byId($,j.project_id):void 0})).with({event_type:"document.interaction"},({metadata:j})=>({event_type:"document.interaction",metadata:j,document:w.byId($,j.document_id)})).exhaustive((j)=>{console.warn("macro sdk: unknown document event",j);return})}function cO($,O,j=[]){let x=O.parent;if(x.type==="call")return{type:"call",call:Q$.byId($,x.id),message:u$.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 h$($,x.id,O.thread_id):void 0};return{type:"document",document:w.byId($,x.id),comment:c$.byId($,x.id,O.message_id),threadId:O.root_id}}function P6($,O){return c(O).with({event_type:"message.posted"},({metadata:j})=>({event_type:"message.posted",metadata:j,target:cO($,j,j.mentions),sender:M$($,j.sender)})).with({event_type:"message.mentioned"},({metadata:j})=>({event_type:"message.mentioned",metadata:j,target:cO($,j),sender:M$($,j.sender)})).with({event_type:"message.patched"},({metadata:j})=>({event_type:"message.patched",metadata:j,target:cO($,j),actor:M$($,j.actor)})).with({event_type:"message.deleted"},({metadata:j})=>({event_type:"message.deleted",metadata:j,target:cO($,j),actor:M$($,j.actor)})).with({event_type:"message.attachment_created"},({metadata:j})=>({event_type:"message.attachment_created",metadata:j,target:cO($,j),actor:M$($,j.actor)})).with({event_type:"message.attachment_removed"},({metadata:j})=>({event_type:"message.attachment_removed",metadata:j,target:cO($,j),actor:M$($,j.actor)})).exhaustive((j)=>{console.warn("macro sdk: unknown message event",j);return})}async function A6($){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 U4="webhook.validation.test";function z4($,O){return c(O).with({event_type:Z$.string.startsWith("document.")},(j)=>M6($,j)).with({event_type:Z$.string.startsWith("channel.")},(j)=>C6($,j)).with({event_type:Z$.string.startsWith("message.")},(j)=>P6($,j)).with({event_type:Z$.string.startsWith("agent_session.")},(j)=>D6($,j)).otherwise(()=>{return})}class b1{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 A6({secret:this.secret,timestamp:O.timestamp??"",rawBody:$,signature:O.signature??""}))throw new f("invalid webhook signature");if(O.event===U4)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=z4(this.client,j);if(!S)return;await Promise.all([...x].map((K)=>K(S)))}}function F6(){return}var I4=0,k1;function T4($){k1=$}function U$($,O,j){if(!j&&!k1)return $;let x=(S)=>{for(let K of[k1,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(...Y)=>{let L={id:++I4,service:O,operation:K};x({...L,status:"started"});try{let Q=await Reflect.apply(X,S,Y),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 w6="x-macro-user-api-key",H4="mak_",g1="mbot_";function R4($){return c($).with(Z$.string.startsWith(g1),()=>{throw Error("bot token passed as a user credential. Use auth: { type: 'bot', token } or MACRO_BOT_TOKEN.")}).with(Z$.string.startsWith(H4),(O)=>[w6,O]).otherwise((O)=>["Authorization",`Bearer ${O}`])}async function E6($){return typeof $==="function"?await $():$}async function D4($,O,j){return c($).with({type:"bot"},async(x)=>{let S=await E6(x.token);if(!S.startsWith(g1))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(g1))throw Error("bot token passed as a user credential. Use auth: { type: 'bot', token } or MACRO_BOT_TOKEN.");return[[w6,x]]}).with({type:"user"},async({token:x})=>{return[R4(await E6(x))]}).exhaustive()}class y1{scheduledAction;unfurl;agentHarness;auth;calendar;cognition;contacts;email;notification;properties;search;storage;webAppUrl;wsVerify;events;authConfig;hosts;localPortmap;requestedAs;selfBotRecord;selfPrincipal;constructor($){let O=_4($),j=O==="local"?F6():void 0,x={...f1[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??R6[O],this.authConfig=C4($),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=U$(new Hx({client:this.makeClient(x["scheduled-action"])}),"scheduled-action",$.onRequest),this.unfurl=U$(new gx({client:this.makeClient(x.unfurl)}),"unfurl",$.onRequest),this.agentHarness=U$(new kj({client:this.makeClient(x["agent-harness"])}),"agent-harness",$.onRequest),this.auth=U$(new mj({client:this.makeClient(x.auth)}),"auth",$.onRequest),this.calendar=U$(new rj({client:this.makeClient(x.calendar)}),"calendar",$.onRequest),this.cognition=U$(new sj({client:this.makeClient(x.cognition)}),"cognition",$.onRequest),this.contacts=U$(new Ox({client:this.makeClient(x.contacts)}),"contacts",$.onRequest),this.email=U$(new Xx({client:this.makeClient(x.email)}),"email",$.onRequest),this.notification=U$(new Jx({client:this.makeClient(x.notification)}),"notification",$.onRequest),this.properties=U$(new Nx({client:this.makeClient(x.properties)}),"properties",$.onRequest),this.search=U$(new Mx({client:this.makeClient(x.search)}),"search",$.onRequest),this.storage=U$(new wx({client:this.makeClient(x.storage)}),"storage",$.onRequest);let K=typeof process<"u"?{}.MACRO_WEBHOOK_SECRET:void 0,Z=$.webhookSecret??K;this.events=new b1(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}`):M.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 D4(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 _4($){if($.env)return $.env;let O=typeof process<"u"?{}.MACRO_ENV:void 0;if(!O)return"prod";if(!(O in f1))throw Error(`invalid MACRO_ENV "${O}" — expected local, dev, or prod`);return O}function C4($){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 v1{id;constructor($){this.id=$}static byId($){return new v1($)}toJSON(){return{id:this.id}}}class q6{routines;unfurls;agents;initiatives;apiKeys;harnesses;meetings;githubPullRequests;entityMentions;agentSessions;ai;bots;calendar;calls;channels;whatsapp;chats;crm;databases;documents;email;favorites;foreignEntities;forms;notifications;pins;projects;properties;tasks;teams;users;webhooks;workspace;events;webAppUrl;_client;opts;constructor($){this.opts=$;let O=new y1($);this._client=O,this.routines=new M0(O),this.unfurls=new F0(O),this.agents=new cx(O),this.initiatives=new U0(O),this.apiKeys=new dx(O),this.harnesses=new N0(O),this.meetings=new z0(O),this.githubPullRequests=new L0(O),this.entityMentions=new Q0(O),this.agentSessions=new mx(O),this.ai=new ux(O),this.bots=new rO(O),this.calendar=new lx(O),this.calls=new rx(O),this.channels=new ax(O),this.whatsapp=new f0(O),this.chats=new ix(O),this.crm=new sx(O),this.databases=new X0(O),this.documents=new K0(O),this.email=new G0(O),this.favorites=new J0(O),this.foreignEntities=new V0(O),this.forms=new B0(O),this.notifications=new I0(O),this.pins=new T0(O),this.projects=new H0(O),this.properties=new R0(O),this.tasks=new P0(O),this.teams=new A0(O),this.users=new E0(O),this.webhooks=new w0(O),this.workspace=new y0(O),this.events=O.events,this.webAppUrl=O.webAppUrl}myPrincipalId(){return this._client.myPrincipalId()}requestedAs($){return new q6({...this.opts,requestedAs:$.id})}}export{a$ as wrapXml,O$ as toBody,T4 as observeRequests,g6 as msg,k6 as here,YO as WhatsAppUpload,GO as WhatsAppSend,KO as WhatsAppParticipant,C$ as WhatsAppMessage,v$ as WhatsAppGroup,IO as WhatsAppChat,MO as WhatsAppAccount,n$ as UserApiKey,lO as ToolApproval,N$ as SessionReview,_0 as RoutineExecution,ZO as Routine,hx as ReviewItem,W0 as PullRequestChangeset,zj as PipelineTable,BO as PipelineRow,Ij as PipelineColumn,L$ as MessageThread,H$ as Meeting,Z0 as MacroOpRefusedError,q6 as Macro,xO as Initiative,_O as HarnessPairing,W$ as Harness,DO as GithubPullRequest,p$ as FormSection,RO as FormResponse,Aj as FormReference,r$ as FormQuestion,UO as FormOption,y$ as Form,HO as EntityMention,o as EntityAccess,NO as EmailFilter,LO as EmailDraft,oO as DraftAttachment,aO as DocumentVersion,VO as DocumentAnchor,$j as DevicePairing,s$ as CrmPipeline,vx as ConversationTurn,dO as CodeExecution,nO as ChatMessage,iO as ChatGeneration,v1 as ChannelPicture,JO as ChannelActivity,q$ as CalendarNote,Lj as AgentConversation,I$ as Agent,TO as AccessRequest};diff --git a/crates/whatsapp_e2e/AGENTS.md b/crates/whatsapp_e2e/AGENTS.mdindex fe0acbd941..6c478e66b6 100644--- a/crates/whatsapp_e2e/AGENTS.md+++ b/crates/whatsapp_e2e/AGENTS.md@@ -29,11 +29,19 @@ database. Nothing talks to WhatsApp or AWS (the KMS isis a system line without an actor).- Message types (`src/test/message_types.rs`): media dimensions, durationsand presentation (sticker, GIF, voice note), a media reply keeping its- quote, view-once as a placeholder without an attachment; mentions and+ quote, view-once media imported and downloaded like any media; mentions andforwards, polls with a vote and a changed vote, places, contact cards,events, pins and call logs as structured content; a mention sent fromMacro; group changes made by a member (added, left, renamed) as systemlines once with two observing accounts, never unread or notified.+- Group kinds (`src/test/group_kinds.rs`): a disappearing group is added, an+ ephemeral-wrapped phone message is kept, Macro's sends carry the timer+ until it is turned off live; a community's group and announcement group+ are added and used, the community itself is refused.+- Direct chats (`src/test/direct_chats.rs`): a direct chat from the chat+ list is added, its earlier messages imported from the phone, messages by+ LID and by phone number and from the owner's phone land in it, Macro sends+ to it, and a shared viewer reads but can't send.## Checksdiff --git a/crates/whatsapp_e2e/src/test.rs b/crates/whatsapp_e2e/src/test.rsindex 83c73330f6..b4ff63319f 100644--- a/crates/whatsapp_e2e/src/test.rs+++ b/crates/whatsapp_e2e/src/test.rs@@ -23,6 +23,8 @@ use whatsmeow::types::Jid;use super::*;+mod direct_chats;+mod group_kinds;mod message_types;const TIMEOUT: Duration = Duration::from_secs(60);@@ -160,8 +162,11 @@ impl World {async fn adopt(&self, user: &str, users: &[&str]) -> Binding {let group = self.group.to_string();wait_for_rows(&self.pool, TIMEOUT, || async {- let groups = self.linked.groups(user).await.ok()?;- groups.iter().any(|info| info.jid == group).then_some(())+ let chats = self.linked.chats(user).await.ok()?.chats;+ chats+ .iter()+ .any(|chat| chat.jid == group && chat.can_add)+ .then_some(())}).await.expect("the replica lists the group");@@ -190,7 +195,7 @@ impl World {/// A viewer opens the WhatsApp page; their account's refreshed roster/// makes it an observer of a group shared with them.async fn observe(&self, user: &str, binding: &Binding) {- self.linked.groups(user).await.unwrap();+ self.linked.chats(user).await.unwrap();let observing = wait_for_rows(&self.pool, TIMEOUT, || async {sqlx::query_scalar!(r#"SELECT m.account_id FROM whatsapp_group_membership m@@ -1195,11 +1200,8 @@ async fn the_chat_list_follows_history_sync_and_live_messages(pool: PgPool) {.await;assert_eq!(direct.kind, ChatKind::Direct);assert_eq!(direct.name, "Customer");- assert!(!direct.can_add);- assert_eq!(- direct.cannot_add_reason.as_deref(),- Some("direct chats can't be added to Macro yet")- );+ assert!(direct.can_add);+ assert_eq!(direct.cannot_add_reason, None);assert_eq!(group.kind, ChatKind::Group);assert_eq!(group.name, "Customer escalations");assert!(group.can_add);diff --git a/crates/whatsapp_e2e/src/test/direct_chats.rs b/crates/whatsapp_e2e/src/test/direct_chats.rsnew file mode 100644index 0000000000..94ef35dfb0--- /dev/null+++ b/crates/whatsapp_e2e/src/test/direct_chats.rs@@ -0,0 +1,204 @@+//! Direct chats end to end: added from the chat list, earlier messages+//! imported from the phone, both sides live, sends from Macro, addressing by+//! phone number or LID landing in the same chat, and shared viewers reading+//! without sending.++use whatsapp_linked::domain::models::ReplyBlock;++use super::*;++/// The customer's chat in Alice's chat list, once listed.+async fn listed_customer_chat(world: &World) -> whatsapp_linked::domain::models::Chat {+ let jid = world.customer.jid().to_string();+ let chat = wait_for_rows(&world.pool, TIMEOUT, || async {+ world+ .linked+ .chats(ALICE)+ .await+ .ok()?+ .chats+ .into_iter()+ .find(|chat| chat.jid == jid)+ })+ .await;+ world+ .expect(chat, "Alice's chat list has the customer's chat")+ .await+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn a_direct_chat_imports_its_history_and_works_both_ways(pool: PgPool) {+ let world = World::new(pool).await;+ let replica = world.replica().await;+ world.pair(ALICE, &world.alice).await;+ world.pair(BOB, &world.bob).await;++ // An earlier conversation, before the chat is added.+ let question = world+ .customer+ .send_text(&world.alice.lid(), "do you ship to Lisbon?")+ .await+ .unwrap();+ world+ .alice+ .wait_for_message(TIMEOUT, |message| message.id == question)+ .await+ .expect("Alice's phone receives the question");+ let answer = world+ .alice+ .send_text(&world.customer.lid(), "yes, in three days")+ .await+ .unwrap();+ let anchored = wait_for_rows(&world.pool, TIMEOUT, || async {+ sqlx::query_scalar!(+ "SELECT 1 AS found FROM whatsapp_chat WHERE chat_jid = $1 AND anchor->>'id' = $2",+ world.customer.jid().to_string(),+ answer+ )+ .fetch_optional(&world.pool)+ .await+ .unwrap()+ })+ .await;+ world+ .expect(anchored, "the chat list knows the chat's newest message")+ .await;++ let chat = listed_customer_chat(&world).await;+ assert_eq!(+ (chat.kind, chat.can_add, chat.name.as_str()),+ (ChatKind::Direct, true, "Customer")+ );+ let binding = world+ .linked+ .adopt(+ ALICE,+ &AdoptGroup {+ group_jid: chat.jid.clone(),+ },+ SendAuthority::Human,+ )+ .await+ .unwrap();+ assert_eq!(binding.kind, ChatKind::Direct);+ assert_eq!(+ backfill_state(&world, &binding, &["done", "partial"])+ .await+ .0,+ "done"+ );+ let imported = wait_for_rows(&world.pool, TIMEOUT, || async {+ let stored = origins(&world.pool, binding.id).await;+ (stored.len() == 2).then_some(stored)+ })+ .await;+ assert_eq!(+ world.expect(imported, "both earlier messages land").await,+ [+ ("do you ship to Lisbon?".to_owned(), "history".to_owned()),+ ("yes, in three days".to_owned(), "history".to_owned()),+ ]+ );+ assert_eq!(world.timeline(&binding, &question).await.len(), 1);++ // Live: the customer by LID and by phone number, and Alice's phone.+ let by_lid = world+ .customer+ .send_text(&world.alice.lid(), "great, ordering now")+ .await+ .unwrap();+ let by_phone = world+ .customer+ .send_text(&world.alice.jid(), "order 1042")+ .await+ .unwrap();+ let from_phone = world+ .alice+ .send_text(&world.customer.lid(), "thanks!")+ .await+ .unwrap();+ for (source, text) in [+ (&by_lid, "great, ordering now"),+ (&by_phone, "order 1042"),+ (&from_phone, "thanks!"),+ ] {+ assert_eq!(world.timeline(&binding, source).await, [text]);+ }+ let senders = sqlx::query_scalar!(+ r#"SELECT p.user_id FROM whatsapp_group_message m JOIN whatsapp_external_person p ON p.id = m.person_id+ WHERE m.binding_id = $1 AND m.source_id = $2"#,+ binding.id,+ from_phone+ )+ .fetch_one(&world.pool)+ .await+ .unwrap();+ assert_eq!(+ senders.as_deref(),+ Some(ALICE),+ "Alice's own message is hers"+ );++ // From Macro.+ let send = world.send(ALICE, &binding, "it ships tomorrow").await;+ world+ .customer+ .wait_for_message(TIMEOUT, |message| {+ message.text() == Some("it ships tomorrow")+ })+ .await+ .expect("the customer's phone receives Alice's message");+ world+ .wait_send(send, &["accepted", "sent", "delivered", "read"])+ .await;++ // Shared with Bob: he reads, never sends; his account isn't in the chat.+ let mut tx = world.pool.begin().await.unwrap();+ entity_access_db_utils::direct_share::set(+ &mut tx,+ &binding.id,+ EntityType::WhatsAppGroup,+ &BOB.to_owned().try_into().unwrap(),+ Some(AccessLevel::View),+ false,+ )+ .await+ .unwrap();+ tx.commit().await.unwrap();+ let bobs = world+ .linked+ .group_detail(&receipt::<ViewAccessLevel>(BOB, binding.id))+ .await+ .unwrap();+ assert_eq!(+ (bobs.group.can_send, bobs.group.send_reason),+ (false, Some(ReplyBlock::NotObserving))+ );+ assert!(+ world+ .linked+ .send_reply(+ &receipt::<ViewAccessLevel>(BOB, binding.id),+ &SendReply {+ idempotency_key: Uuid::now_v7(),+ message: ReplyContent::Text {+ text: "hi from Bob".to_owned(),+ mentions: vec![],+ },+ reply_to: None,+ },+ SendAuthority::Human,+ )+ .await+ .is_err()+ );+ let read = world+ .linked+ .messages(&receipt::<ViewAccessLevel>(BOB, binding.id), None, 100)+ .await+ .unwrap()+ .messages;+ assert_eq!(read.len(), 6, "Bob reads the whole conversation");++ replica.drain(TIMEOUT).await.unwrap();+}diff --git a/crates/whatsapp_e2e/src/test/group_kinds.rs b/crates/whatsapp_e2e/src/test/group_kinds.rsnew file mode 100644index 0000000000..c51cdbf87f--- /dev/null+++ b/crates/whatsapp_e2e/src/test/group_kinds.rs@@ -0,0 +1,218 @@+//! Groups with disappearing messages and the groups of a community, end to+//! end: added, kept and sent to like any other group; the community itself+//! can't be added.++use whatsapp_fake_server::GroupChange;+use whatsapp_linked::domain::models::{CannotAdd, CommunityReference, LinkedError, ReplyBlock};+use whatsmeow::proto::wa_e2e::{ContextInfo, ExtendedTextMessage, FutureProofMessage, Message};++use super::*;++const WEEK: u32 = 7 * 24 * 60 * 60;++/// The context of an extended text the customer's phone received.+fn context(received: &whatsapp_fake_server::ReceivedMessage) -> Option<&ContextInfo> {+ received+ .message+ .extended_text_message+ .as_ref()+ .and_then(|extended| extended.context_info.as_deref())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn a_disappearing_group_is_kept_in_macro_and_macro_sends_disappear(pool: PgPool) {+ let world = World::new(pool).await;+ world.whatsapp.change_group(+ &world.group,+ Some(&world.customer),+ GroupChange::Disappearing(Some(WEEK)),+ );+ let replica = world.replica().await;+ let (_, binding) = world.alice_adopted().await;+ let detail = world+ .linked+ .group_detail(&receipt::<ViewAccessLevel>(ALICE, binding.id))+ .await+ .unwrap();+ assert_eq!(detail.disappearing_seconds, Some(WEEK));+ assert!(detail.group.can_send);++ // The customer's phone wraps its messages as disappearing.+ let gone = world+ .customer+ .send_message(+ &world.group,+ Message {+ ephemeral_message: Some(Box::new(FutureProofMessage {+ message: Some(Box::new(Message {+ extended_text_message: Some(Box::new(ExtendedTextMessage {+ text: Some("this vanishes on phones".to_owned()),+ context_info: Some(Box::new(ContextInfo {+ expiration: Some(WEEK),+ ..ContextInfo::default()+ })),+ ..ExtendedTextMessage::default()+ })),+ ..Message::default()+ })),+ })),+ ..Message::default()+ },+ )+ .await+ .unwrap();+ assert_eq!(+ world.timeline(&binding, &gone).await,+ ["this vanishes on phones"],+ "Macro keeps it"+ );++ let send = world.send(ALICE, &binding, "kept in Macro").await;+ let received = world+ .customer+ .wait_for_message(TIMEOUT, |message| message.text() == Some("kept in Macro"))+ .await+ .expect("the customer's phone receives Alice's message");+ assert_eq!(+ context(&received).and_then(|context| context.expiration),+ Some(WEEK),+ "it disappears on phones like the group's own messages"+ );+ world+ .wait_send(send, &["accepted", "sent", "delivered", "read"])+ .await;++ // Turning it off reaches Macro live, and sends stop carrying a timer.+ world.whatsapp.change_group(+ &world.group,+ Some(&world.customer),+ GroupChange::Disappearing(None),+ );+ let off = wait_for_rows(&world.pool, TIMEOUT, || async {+ let detail = world+ .linked+ .group_detail(&receipt::<ViewAccessLevel>(ALICE, binding.id))+ .await+ .ok()?;+ detail.disappearing_seconds.is_none().then_some(())+ })+ .await;+ world.expect(off, "the timer is gone from the detail").await;+ world.send(ALICE, &binding, "plain again").await;+ let received = world+ .customer+ .wait_for_message(TIMEOUT, |message| message.text() == Some("plain again"))+ .await+ .expect("the customer's phone receives the next message");+ assert_eq!(+ context(&received).and_then(|context| context.expiration),+ None+ );++ replica.drain(TIMEOUT).await.unwrap();+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn a_communitys_groups_are_added_and_used_but_not_the_community(pool: PgPool) {+ let world = World::new(pool).await;+ let members = [&world.customer, &world.alice];+ let (community, announcements) = world.whatsapp.create_community("Neighbours", &members);+ let garden = world+ .create_community_group(&community, "Garden", &members);+ let replica = world.replica().await;+ world.pair(ALICE, &world.alice).await;++ let garden_jid = garden.to_string();+ let chats = wait_for_rows(&world.pool, TIMEOUT, || async {+ let chats = world.linked.chats(ALICE).await.ok()?.chats;+ chats+ .iter()+ .any(|chat| chat.jid == garden_jid)+ .then_some(chats)+ })+ .await;+ let chats = world.expect(chats, "the replica lists the community").await;+ let listed = |jid: &Jid| {+ let chat = chats+ .iter()+ .find(|chat| chat.jid == jid.to_string())+ .expect("listed");+ (chat.can_add, chat.cannot_add_reason, chat.community.clone())+ };+ let neighbours = |announcements| CommunityReference {+ id: community.to_string(),+ name: "Neighbours".to_owned(),+ announcements,+ };+ assert_eq!(+ listed(&community),+ (false, Some(CannotAdd::Community), None)+ );+ assert_eq!(listed(&garden), (true, None, Some(neighbours(false))));+ assert_eq!(listed(&announcements), (true, None, Some(neighbours(true))));++ let adopt = |jid: &Jid| {+ let request = AdoptGroup {+ group_jid: jid.to_string(),+ };+ let linked = &world.linked;+ async move { linked.adopt(ALICE, &request, SendAuthority::Human).await }+ };+ assert!(matches!(+ adopt(&community).await.unwrap_err().current_context(),+ LinkedError::CannotAdd(CannotAdd::Community)+ ));++ // A community's group works like any group, both ways.+ let binding = adopt(&garden).await.unwrap();+ let detail = world+ .linked+ .group_detail(&receipt::<ViewAccessLevel>(ALICE, binding.id))+ .await+ .unwrap();+ assert_eq!(detail.community, Some(neighbours(false)));+ assert!(detail.group.can_send);+ let tomatoes = world+ .customer+ .send_text(&garden, "tomatoes are ready")+ .await+ .unwrap();+ assert_eq!(+ world.timeline(&binding, &tomatoes).await,+ ["tomatoes are ready"]+ );+ let send = world.send(ALICE, &binding, "I'll take some").await;+ world+ .customer+ .wait_for_message(TIMEOUT, |message| message.text() == Some("I'll take some"))+ .await+ .expect("the customer's phone receives Alice's message");+ world+ .wait_send(send, &["accepted", "sent", "delivered", "read"])+ .await;++ // Everyone reads the announcement group; only its admins post.+ let notices = adopt(&announcements).await.unwrap();+ let detail = world+ .linked+ .group_detail(&receipt::<ViewAccessLevel>(ALICE, notices.id))+ .await+ .unwrap();+ assert_eq!(detail.community, Some(neighbours(true)));+ assert_eq!(+ detail.group.send_reason,+ Some(ReplyBlock::NotAllowedInGroup)+ );+ let notice = world+ .customer+ .send_text(&announcements, "street party on Sunday")+ .await+ .unwrap();+ assert_eq!(+ world.timeline(¬ices, ¬ice).await,+ ["street party on Sunday"]+ );++ replica.drain(TIMEOUT).await.unwrap();+}diff --git a/crates/whatsapp_e2e/src/test/message_types.rs b/crates/whatsapp_e2e/src/test/message_types.rsindex 6c23e54a0c..7ba05f6486 100644--- a/crates/whatsapp_e2e/src/test/message_types.rs+++ b/crates/whatsapp_e2e/src/test/message_types.rs@@ -1,7 +1,7 @@//! What phones send besides plain text, end to end: media with its shape,//! replies to media, mentions and forwards, polls and votes, places,-//! contact cards, events, pins, calls, view-once media, and group changes-//! as system lines.+//! contact cards, events, pins, calls, view-once media (kept like any+//! media), and group changes as system lines.use std::sync::Mutex;@@ -254,7 +254,7 @@ async fn media_keeps_its_shape_and_a_media_reply_keeps_its_quote(pool: PgPool) {.await.unwrap();- // View-once media is only ever shown on the phone.+ // View-once media is kept and shown like any media.let secret_bytes = b"jpeg seen once".repeat(40);let uploaded = world.customer@@ -276,6 +276,7 @@ async fn media_keeps_its_shape_and_a_media_reply_keeps_its_quote(pool: PgPool) {file_sha256: Some(uploaded.file_sha256),file_length: Some(uploaded.file_length),mimetype: Some("image/jpeg".to_owned()),+ caption: Some("look once".to_owned()),view_once: Some(true),..ImageMessage::default()})),@@ -292,10 +293,7 @@ async fn media_keeps_its_shape_and_a_media_reply_keeps_its_quote(pool: PgPool) {for source in [&video, &gif, &sticker, &voice] {assert_eq!(world.timeline(&binding, source).await, [""]);}- assert_eq!(- world.timeline(&binding, &view_once).await,- ["View-once message \u{2014} open it on your phone"]- );+ assert_eq!(world.timeline(&binding, &view_once).await, ["look once"]);assert_eq!(attachment_shapes(&world.pool, binding.id, &reply).await,@@ -349,7 +347,26 @@ async fn media_keeps_its_shape_and_a_media_reply_keeps_its_quote(pool: PgPool) {);assert_eq!(attachment_shapes(&world.pool, binding.id, &view_once).await,- []+ [(Some("image/jpeg".to_owned()), None, None, None, None)]+ );+ let downloaded = wait_for_rows(&world.pool, TIMEOUT, || async {+ sqlx::query_scalar!(+ "SELECT b.bytes FROM whatsapp_group_attachment a+ JOIN whatsapp_media_blob b ON b.document_id = a.document_id+ WHERE a.binding_id = $1 AND a.source_id = $2 AND a.state = 'downloaded'",+ binding.id,+ &view_once+ )+ .fetch_optional(&world.pool)+ .await+ .unwrap()+ })+ .await;+ assert_eq!(+ world+ .expect(downloaded, "the view-once image is downloaded for import")+ .await,+ secret_bytes);// The timeline shows the quote and the shapes.@@ -381,12 +398,10 @@ async fn media_keeps_its_shape_and_a_media_reply_keeps_its_quote(pool: PgPool) {gif_shown.attachments[0].presentation,Some(MediaPresentation::Gif));- assert!(- shown(&world, &binding, &view_once)- .await- .attachments- .is_empty()- );+ let view_once_shown = shown(&world, &binding, &view_once).await;+ assert!(view_once_shown.view_once);+ assert_eq!(view_once_shown.attachments.len(), 1);+ assert!(!reply_shown.view_once);replica.drain(TIMEOUT).await.unwrap();}diff --git a/crates/whatsapp_fake_server/AGENTS.md b/crates/whatsapp_fake_server/AGENTS.mdindex 574664ab5e..77ae093284 100644--- a/crates/whatsapp_fake_server/AGENTS.md+++ b/crates/whatsapp_fake_server/AGENTS.md@@ -29,10 +29,13 @@ Lets the session service and its tests run end to end without WhatsApp.- `src/lib.rs`: the `FakeWhatsApp` API (users, groups, kick, drop connection,delivery counters, waiters).- `src/group_change.rs`: `change_group` adds, removes (a user removing- themselves left), renames, describes, promotes and demotes, and sends the+ themselves left), renames, describes, promotes and demotes, turns+ disappearing messages on or off, and sends the`w:gp2` notification (one id and `t` for every device) naming who did it as`participant` / `participant_pn`; `rename_group` / `remove_from_group` nameno one, as changes WhatsApp makes.+- `FakeWhatsApp::create_community` makes a community and its announcement+ group (admins-only); `create_community_group` adds a group to it.- `src/state.rs`: routing, IQ handlers (encrypt, usync, w:g2, w:m), offline queues.- `src/phone.rs`: fake phones: send/receive with real Signal, QR approval.Phones remember chat messages and answer their linked devices' peerdiff --git a/crates/whatsapp_fake_server/src/group_change.rs b/crates/whatsapp_fake_server/src/group_change.rsindex fbdbdb7069..7ca8981163 100644--- a/crates/whatsapp_fake_server/src/group_change.rs+++ b/crates/whatsapp_fake_server/src/group_change.rs@@ -22,6 +22,8 @@ pub enum GroupChange<'phone> {Promote(&'phone FakePhone),/// Removes a member as admin.Demote(&'phone FakePhone),+ /// Turns disappearing messages on with a timer in seconds, or off.+ Disappearing(Option<u32>),}impl FakeWhatsApp {@@ -38,6 +40,7 @@ impl FakeWhatsApp {let mut admins = stored.admins.clone();let mut subject = stored.subject.clone();let mut description = stored.description.clone();+ let mut disappearing = stored.disappearing;let actor = by.and_then(|phone| state.users.get(phone.phone())).map(|user| {@@ -90,6 +93,17 @@ impl FakeWhatsApp {admins.retain(|admin| admin != phone.phone());participants_node("demote", &state, phone)}+ GroupChange::Disappearing(timer) => {+ disappearing = timer.or(disappearing.map(|_| 0));+ match timer {+ Some(seconds) => node(+ "ephemeral",+ vec![("expiration", text(seconds.to_string()))],+ None,+ ),+ None => node("not_ephemeral", vec![], None),+ }+ }};let mut attrs = vec![("from", jid(group)),@@ -107,6 +121,7 @@ impl FakeWhatsApp {stored.admins = admins;stored.subject = subject;stored.description = description;+ stored.disappearing = disappearing;}let targets: Vec<DeviceAddress> = notified.iter()diff --git a/crates/whatsapp_fake_server/src/lib.rs b/crates/whatsapp_fake_server/src/lib.rsindex 35d0d89a01..0c8a351b46 100644--- a/crates/whatsapp_fake_server/src/lib.rs+++ b/crates/whatsapp_fake_server/src/lib.rs@@ -331,13 +331,47 @@ impl FakeWhatsApp {/// Creates a group of the given phones' users (the first is the/// creator) and notifies their linked devices; returns the group JID.pub fn create_group(&self, subject: &str, members: &[&FakePhone]) -> Jid {+ self.new_group(subject, members, |_| {})+ }++ /// Creates a community of the given phones' users with its announcement+ /// group, as WhatsApp does; returns the community and announcement JIDs.+ pub fn create_community(&self, subject: &str, members: &[&FakePhone]) -> (Jid, Jid) {+ let community = self.new_group(subject, members, |group| {+ group.community_parent = true;+ });+ let announcements = self.new_group(subject, members, |group| {+ group.community = Some(community.user.clone());+ group.announcements = true;+ });+ (community, announcements)+ }++ /// Creates a group inside a community; returns its JID.+ pub fn create_community_group(+ &self,+ community: &Jid,+ subject: &str,+ members: &[&FakePhone],+ ) -> Jid {+ self.new_group(subject, members, |group| {+ group.community = Some(community.user.clone());+ })+ }++ fn new_group(+ &self,+ subject: &str,+ members: &[&FakePhone],+ settings: impl FnOnce(&mut state::Group),+ ) -> Jid {let mut state = self.shared.lock();let id = format!("120363{:012}", state.number());let created = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|elapsed| elapsed.as_secs()).unwrap_or_default();- let group = Group {+ let mut group = Group {id: id.clone(),subject: subject.to_owned(),creator: members@@ -351,7 +385,12 @@ impl FakeWhatsApp {.collect(),admins: Vec::new(),description: None,+ disappearing: None,+ community_parent: false,+ community: None,+ announcements: false,};+ settings(&mut group);let group_node = state.group_node(&group);let creator = state.usersdiff --git a/crates/whatsapp_fake_server/src/state.rs b/crates/whatsapp_fake_server/src/state.rsindex ea99411fd9..8b56036b39 100644--- a/crates/whatsapp_fake_server/src/state.rs+++ b/crates/whatsapp_fake_server/src/state.rs@@ -79,6 +79,15 @@ pub(crate) struct Group {pub(crate) admins: Vec<String>,/// The group description, if set.pub(crate) description: Option<String>,+ /// Disappearing-messages timer in seconds; `Some(0)` once turned off,+ /// which WhatsApp still lists as `<ephemeral expiration="0"/>`.+ pub(crate) disappearing: Option<u32>,+ /// This is a community (it has no chat of its own).+ pub(crate) community_parent: bool,+ /// The community this group belongs to, by group id.+ pub(crate) community: Option<String>,+ /// The community's announcement group.+ pub(crate) announcements: bool,}/// A connection that is pairing a new device.@@ -294,7 +303,37 @@ impl State {children(vec![node("body", vec![], bytes(description.as_bytes()))]),)});- let group_children = participants.into_iter().chain(description).collect();+ let mut settings = vec![];+ if let Some(seconds) = group.disappearing {+ settings.push(node(+ "ephemeral",+ vec![("expiration", text(seconds.to_string()))],+ None,+ ));+ }+ if group.community_parent {+ settings.push(node(+ "parent",+ vec![("default_membership_approval_mode", text("request_required"))],+ None,+ ));+ }+ if let Some(community) = &group.community {+ settings.push(node(+ "linked_parent",+ vec![("jid", jid(&group_jid(community)))],+ None,+ ));+ }+ if group.announcements {+ settings.push(node("announcement", vec![], None));+ settings.push(node("default_sub_group", vec![], None));+ }+ let group_children = participants+ .into_iter()+ .chain(description)+ .chain(settings)+ .collect();let creator_lid = self.users.get(&group.creator)diff --git a/crates/whatsapp_linked/AGENTS.md b/crates/whatsapp_linked/AGENTS.mdindex 4ac5007159..0f63a674db 100644--- a/crates/whatsapp_linked/AGENTS.md+++ b/crates/whatsapp_linked/AGENTS.md@@ -3,9 +3,12 @@## What it isPersonal WhatsApp accounts linked as devices: owner-bound pairing, adopting an-existing group as the adopter's own, independently shared `WhatsAppGroup`-entity (one per owner and WhatsApp group, named after WhatsApp), ingesting group traffic, and-deliberate sends from each person's own account. DSS serves the HTTP API+existing group or direct chat as the adopter's own, independently shared+`WhatsAppGroup` entity (one per owner and WhatsApp chat, named after WhatsApp),+ingesting chat traffic, and deliberate sends from each person's own account.+"Group" in table, column, type and route names means any added chat;+`Binding.kind` / `whatsapp_group.kind` says group or direct (only the owner+sends in a direct chat). DSS serves the HTTP API(`/meta/linked/*`); the WhatsApp session service calls`domain::session::SessionService` in-process. They share no HTTP: only MacroDBrows and `NOTIFY` (the `outbound::pg` notify helper).@@ -81,7 +84,9 @@ rows and `NOTIFY` (the `outbound::pg` notify helper).session service has no document storage; DSS imports and deletes them.`events::Media::locator` is sealed by the session service; never read it.- `src/domain/media.rs` + `src/outbound/pg/media.rs`: download claims, import- queue. Not implemented: participant-receipt UI.+ queue. `src/domain/shape.rs` reads a staged upload's pixel size and length+ (stored on `whatsapp_media_blob`, sent with the message). Not implemented:+ participant-receipt UI.## Relateddiff --git a/crates/whatsapp_linked/Cargo.toml b/crates/whatsapp_linked/Cargo.tomlindex 11872a45f4..1bd2246453 100644--- a/crates/whatsapp_linked/Cargo.toml+++ b/crates/whatsapp_linked/Cargo.toml@@ -10,7 +10,9 @@ default = []ports = ["dep:async-trait","dep:entity_access",+ "dep:image","dep:macro_user_id",+ "dep:nom","dep:rootcause","entity_access/ports",]@@ -52,8 +54,10 @@ async-trait = { workspace = true, optional = true }axum = { workspace = true, features = ["multipart"], optional = true }chrono = { workspace = true }entity_access = { path = "../entity_access", default-features = false, optional = true }+image = { workspace = true, optional = true }macro_authorization = { path = "../macro_authorization", default-features = false, features = ["axum"], optional = true }macro_user_id = { path = "../macro_user_id", optional = true }+nom = { workspace = true, optional = true }rootcause = { workspace = true, optional = true }serde = { workspace = true }serde_json = { workspace = true }diff --git a/crates/whatsapp_linked/src/domain.rs b/crates/whatsapp_linked/src/domain.rsindex 5736903a7e..35ee0f0c64 100644--- a/crates/whatsapp_linked/src/domain.rs+++ b/crates/whatsapp_linked/src/domain.rs@@ -20,6 +20,9 @@ pub mod service;/// In-process API for the session service.#[cfg(feature = "ports")]pub mod session;+/// Pixel size and length of files sent from Macro.+#[cfg(feature = "ports")]+pub mod shape;#[cfg(feature = "ports")]pub mod timeline;diff --git a/crates/whatsapp_linked/src/domain/events.rs b/crates/whatsapp_linked/src/domain/events.rsindex 51f5a35520..e7999e99f8 100644--- a/crates/whatsapp_linked/src/domain/events.rs+++ b/crates/whatsapp_linked/src/domain/events.rs@@ -197,6 +197,9 @@ pub struct Message {/// Forwarded from another chat.#[serde(default)]pub forwarded: bool,+ /// Sent as view-once; kept and shown like any media.+ #[serde(default)]+ pub view_once: bool,/// Structured content of rich, system and poll-vote messages.#[serde(default)]pub rich: Option<RichContent>,@@ -251,8 +254,13 @@ pub enum InboundKind {pub struct InboundEvent {/// Stable id for deferral and quarantine.pub event_id: Uuid,- /// Group JID.+ /// Chat JID: the group, or a direct chat's other person (by phone number+ /// when known).pub group_jid: String,+ /// A direct chat's other address for the same person (LID for a phone+ /// number, or the reverse), so either addressing reaches the added chat.+ #[serde(default)]+ pub chat_alternate_jid: Option<String>,/// Protocol timestamp.pub source_at: DateTime<Utc>,/// When the replica observed it.@@ -318,9 +326,22 @@ pub enum OutgoingContent {caption: Option<String>,/// Quoted message.quote: Option<Target>,+ /// Pixel size and length, read from the file when it was staged.+ shape: MediaShape,},}+/// Pixel size and length of an attachment, where known.+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]+pub struct MediaShape {+ /// Width in pixels (images and videos).+ pub width: Option<u32>,+ /// Height in pixels.+ pub height: Option<u32>,+ /// Length in whole seconds (audio and video).+ pub duration_seconds: Option<u32>,+}+/// One attachment of one source message.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pub struct AttachmentRef {@@ -386,6 +407,9 @@ pub struct ClaimedSend {pub group_sequence: i64,/// Content.pub content: OutgoingContent,+ /// The group's disappearing-messages timer in seconds, as the sending+ /// account last saw it; the message carries it like a phone's would.+ pub disappearing_seconds: Option<u32>,/// W3C trace context of the request that recorded the send.pub traceparent: Option<String>,}diff --git a/crates/whatsapp_linked/src/domain/models.rs b/crates/whatsapp_linked/src/domain/models.rsindex 9f3f1a75c6..ee8af37f33 100644--- a/crates/whatsapp_linked/src/domain/models.rs+++ b/crates/whatsapp_linked/src/domain/models.rs@@ -178,7 +178,8 @@ pub struct PairState {#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]#[cfg_attr(feature = "schema", schema(as = LinkedAdoptGroup))]pub struct AdoptGroup {- /// Group the requester's account has joined.+ /// A group the requester's account has joined, or a direct chat from+ /// their chat list (the other person's JID, as the list names it).pub group_jid: String,}@@ -201,8 +202,11 @@ pub enum BindingState {pub struct Binding {/// Stable binding identity, independent of any observing account.pub id: Uuid,- /// Remote group identity, never its display name.+ /// Remote chat identity, never its display name: the group, or a direct+ /// chat's other person.pub group_jid: String,+ /// Group or direct chat.+ pub kind: ChatKind,/// The person who added the group, its owner.pub user_id: String,/// Lifecycle.@@ -270,21 +274,21 @@ pub struct GroupInfo {pub participants: Vec<Participant>,/// Only admins may post.pub announce: bool,- /// Disappearing messages are on; content is not retained.- pub disappearing: bool,- /// Community announcement or parent group, outside the supported surface.- pub community: bool,- /// When the session service read this metadata.- pub observed_at: DateTime<Utc>,- /// The caller's own Macro group for this remote group, once they added- /// it. Only set by the groups listing.+ /// Disappearing-messages timer in seconds while it is on. Macro keeps the+ /// messages; its sends carry the timer so phones treat them like their own.#[serde(default)]- pub group: Option<GroupReference>,- /// Someone else's Macro group for this remote group that was shared with- /// the caller, when the caller has not added their own. Only set by the- /// groups listing.+ pub disappearing_seconds: Option<u32>,+ /// The community itself: it has no messages of its own and can't be added.#[serde(default)]- pub shared: Option<SharedGroupReference>,+ pub community_parent: bool,+ /// The community a linked subgroup or announcement group belongs to.+ #[serde(default)]+ pub community_jid: Option<String>,+ /// The community's announcement group (everyone reads, admins post).+ #[serde(default)]+ pub community_announcements: bool,+ /// When the session service read this metadata.+ pub observed_at: DateTime<Utc>,}/// A group entity bound to a remote group.@@ -298,8 +302,26 @@ pub struct GroupReference {pub name: String,}+/// The WhatsApp community a group belongs to.+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]+#[serde(rename_all = "camelCase")]+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]+#[cfg_attr(feature = "schema", schema(as = LinkedCommunityReference))]+pub struct CommunityReference {+ /// The community's WhatsApp JID.+ pub id: String,+ /// The community's name.+ pub name: String,+ /// This group is the community's announcement group.+ pub announcements: bool,+}++/// Shown when the community itself is not in the account's group list.+const UNKNOWN_COMMUNITY_NAME: &str = "WhatsApp community";+/// Another person's group entity the caller can view.#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]+#[serde(rename_all = "camelCase")]#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]#[cfg_attr(feature = "schema", schema(as = LinkedSharedGroupReference))]pub struct SharedGroupReference {@@ -349,12 +371,27 @@ impl GroupInfo {}}+ /// The community this group belongs to, named after `parent` (the+ /// community's own metadata) when known.+ pub fn community(&self, parent: Option<&GroupInfo>) -> Option<CommunityReference> {+ let id = self.community_jid.clone()?;+ let name = parent+ .map(|parent| parent.name.trim())+ .filter(|name| !name.is_empty())+ .unwrap_or(UNKNOWN_COMMUNITY_NAME)+ .to_owned();+ Some(CommunityReference {+ id,+ name,+ announcements: self.community_announcements,+ })+ }+/// Whether the given identity may post under the group's current settings.pub fn can_post(&self, identity: &str) -> bool {self.participant(identity).is_some_and(|p| !self.announce || p.admin)- && !self.community- && !self.disappearing+ && !self.community_parent}}@@ -389,16 +426,24 @@ impl ChatKind {}}-/// Why a chat can't be added to Macro. The same sentences adoption refuses with.-pub mod cannot_add {+/// Why a chat can't be added to Macro; the app words it from the code.+#[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq, thiserror::Error)]+#[serde(rename_all = "snake_case")]+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]+#[cfg_attr(feature = "schema", schema(as = LinkedCannotAdd))]+pub enum CannotAdd {/// The account's WhatsApp left the group or was removed.- pub const NOT_IN_GROUP: &str = "your WhatsApp is not in this group any more";- /// Community announcement or parent groups.- pub const COMMUNITY: &str = "community groups can't be added to Macro";- /// Disappearing messages are on.- pub const DISAPPEARING: &str = "groups with disappearing messages can't be added to Macro";- /// Direct chats are listed but not addable yet.- pub const DIRECT: &str = "direct chats can't be added to Macro yet";+ #[error("your WhatsApp is not in this group any more")]+ NotInGroup,+ /// A community itself has no messages; its groups can be added.+ #[error("a community has no messages of its own; add one of its groups")]+ Community,+ /// The chat with yourself.+ #[error("your chat with yourself can't be added to Macro")]+ OwnChat,+ /// A direct chat that is not in the account's chat list.+ #[error("this chat is not in your WhatsApp chat list")]+ NotInChatList,}/// One chat of the caller's WhatsApp chat list, as WhatsApp Web lists it.@@ -430,7 +475,10 @@ pub struct Chat {/// "Add to Macro" works now.pub can_add: bool,/// Why it can't be added, when it is neither added, shared nor addable.- pub cannot_add_reason: Option<String>,+ pub cannot_add_reason: Option<CannotAdd>,+ /// The community a group belongs to (a community's group or its+ /// announcement group); `null` otherwise.+ pub community: Option<CommunityReference>,}/// The caller's WhatsApp chat list.@@ -859,7 +907,7 @@ pub enum ReplyBlock {NotObserving,/// The viewer is not in the group, or only admins may post.NotAllowedInGroup,- /// The group is detached.+ /// The group is detached, or needs a new content owner.GroupUnavailable,}@@ -899,6 +947,9 @@ pub enum LinkedError {/// Invalid input with actionable detail.#[error("{0}")]Invalid(&'static str),+ /// The chat can't be added to Macro.+ #[error("{0}")]+ CannotAdd(CannotAdd),/// This operation is switched off on the server.#[error("WhatsApp linking is not enabled")]ConfigurationRequired,@@ -936,6 +987,10 @@ impl LinkedError {pub const fn code(&self) -> &'static str {match self {Self::Invalid(_) => "invalid_input",+ Self::CannotAdd(CannotAdd::NotInGroup) => "cannot_add_not_in_group",+ Self::CannotAdd(CannotAdd::Community) => "cannot_add_community",+ Self::CannotAdd(CannotAdd::OwnChat) => "cannot_add_own_chat",+ Self::CannotAdd(CannotAdd::NotInChatList) => "cannot_add_not_in_chat_list",Self::ConfigurationRequired => "configuration_required",Self::NotFound => "not_found",Self::Forbidden => "forbidden",diff --git a/crates/whatsapp_linked/src/domain/ports.rs b/crates/whatsapp_linked/src/domain/ports.rsindex 1d342b2e22..deaabda4b1 100644--- a/crates/whatsapp_linked/src/domain/ports.rs+++ b/crates/whatsapp_linked/src/domain/ports.rs@@ -91,6 +91,13 @@ pub trait GroupRepository: Send + Sync {) -> LinkedResult<Vec<VisibleAdoption>>;/// Latest metadata for a binding's group from any account consenting to it.async fn binding_roster(&self, binding: &Binding) -> LinkedResult<Option<GroupInfo>>;+ /// Latest metadata for the binding's community (`community_jid`) from any+ /// account consenting to the binding.+ async fn binding_community(+ &self,+ binding: &Binding,+ community_jid: &str,+ ) -> LinkedResult<Option<GroupInfo>>;/// The account's stored chat list (without the roster), newest first.async fn account_chats(&self, account: Uuid) -> LinkedResult<Vec<StoredChat>>;@@ -113,16 +120,29 @@ pub struct StoredChat {pub pinned: bool,}+/// What the domain authorized adding.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct Adoption {+ /// The chat's JID.+ pub jid: String,+ /// Group or direct chat.+ pub kind: ChatKind,+ /// Display name, following WhatsApp.+ pub name: String,+ /// The account may post now (always for a direct chat).+ pub can_post: bool,+ /// When the facts that authorized it were observed.+ pub observed_at: DateTime<Utc>,+}+/// A new binding, authorized by the domain.pub struct AdoptionRecord<'a> {/// Adopting person.pub user: &'a str,/// Their account at the generation that authorized adoption.pub account: &'a Account,- /// Display name, following WhatsApp.- pub name: &'a str,- /// Stored metadata that authorized adoption.- pub group: &'a GroupInfo,+ /// What to add.+ pub adoption: &'a Adoption,}/// Result of adoption.@@ -164,6 +184,16 @@ pub struct SendingFacts {pub can_post: bool,}+/// A direct chat has two people: only its owner's own account is in it.+pub(crate) fn direct_sending_facts(account: &Account, binding: &Binding) -> SendingFacts {+ let owner = account.user_id == binding.user_id;+ SendingFacts {+ observing: owner,+ remote_member: owner,+ can_post: owner,+ }+}+/// Membership eligibility derived only from the caller's own protocol metadata.pub(crate) fn sending_facts_from_roster(account: &Account,@@ -225,6 +255,8 @@ pub struct StagedUpload<'a> {pub bytes: &'a [u8],/// SHA-256 of `bytes`.pub sha256: [u8; 32],+ /// Pixel size and length read from the file.+ pub shape: crate::domain::events::MediaShape,}/// Durable send intents.diff --git a/crates/whatsapp_linked/src/domain/service.rs b/crates/whatsapp_linked/src/domain/service.rsindex 9a49ebb159..235bf17300 100644--- a/crates/whatsapp_linked/src/domain/service.rs+++ b/crates/whatsapp_linked/src/domain/service.rs@@ -152,33 +152,11 @@ impl LinkedService {Ok((account, identity))}- /// Only a person's own joined groups are discoverable. The stored list is- /// returned at once and a refresh is requested (rate limited per account).- /// Each group points at the caller's own Macro group once added, or at- /// someone else's group that was shared with them.- #[tracing::instrument(name = "whatsapp.linked.groups", skip_all, err, fields(count))]- pub async fn groups(&self, user: &str) -> LinkedResult<Vec<GroupInfo>> {- if !self.features.adoption {- return Err(LinkedError::ConfigurationRequired.into());- }- let (account, identity) = self.connected(user).await?;- self.groups.request_groups_refresh(&[account.id]).await?;- let mut groups = self.groups.account_groups(account.id).await?;- let jids: Vec<String> = groups.iter().map(|g| g.jid.clone()).collect();- let adoptions = self.groups.visible_adoptions(user, &jids).await?;- for group in &mut groups {- (group.group, group.shared) = adoption_of(user, &adoptions, &group.jid);- group.name = group.display_name(&identity);- }- groups.sort_by(|a, b| a.name.to_lowercase().cmp(&b.name.to_lowercase()));- tracing::Span::current().record("count", groups.len());- Ok(groups)- }-/// The person's WhatsApp chat list, as WhatsApp Web shows it: groups and- /// direct chats, newest activity first. Groups carry the same added /- /// shared / addable facts as [`Self::groups`]; direct chats are listed but- /// not addable yet. Returns stored data and requests a group refresh.+ /// direct chats, newest activity first. Each chat says whether it is+ /// added, shared with the caller or addable; direct chats are addable (not+ /// your own chat) and never shown as shared. Returns stored data+ /// and requests a group refresh.#[tracing::instrument(name = "whatsapp.linked.chats", skip_all, err, fields(count))]pub async fn chats(&self, user: &str) -> LinkedResult<ChatList> {if !self.features.adoption {@@ -189,12 +167,7 @@ impl LinkedService {let roster = self.groups.account_groups(account.id).await?;let stored = self.groups.account_chats(account.id).await?;let mut group_jids: Vec<String> = roster.iter().map(|g| g.jid.clone()).collect();- group_jids.extend(- stored- .iter()- .filter(|chat| chat.kind == ChatKind::Group)- .map(|chat| chat.jid.clone()),- );+ group_jids.extend(stored.iter().map(|chat| chat.jid.clone()));group_jids.sort();group_jids.dedup();let adoptions = self.groups.visible_adoptions(user, &group_jids).await?;@@ -203,16 +176,21 @@ impl LinkedService {for chat in stored {listed.insert(chat.jid.clone(), chats.len());let (group, shared) = adoption_of(user, &adoptions, &chat.jid);+ // Someone else's chat with the same person is their own+ // conversation, not this one.+ let shared = shared.filter(|_| chat.kind == ChatKind::Group);let name = chat.name.clone().filter(|name| !name.trim().is_empty()).unwrap_or_else(|| chat_fallback_name(&chat.jid, chat.kind, &identity));let reason = match chat.kind {- ChatKind::Direct => cannot_add::DIRECT,+ ChatKind::Direct if chat.jid == identity => Some(CannotAdd::OwnChat),+ ChatKind::Direct => None,// Listed by WhatsApp but not in the account's groups any more.- ChatKind::Group => cannot_add::NOT_IN_GROUP,+ ChatKind::Group => Some(CannotAdd::NotInGroup),};+ let open = group.is_none() && shared.is_none();chats.push(Chat {name: if chat.jid == identity {"You".to_owned()@@ -224,13 +202,14 @@ impl LinkedService {last_activity_at: chat.last_activity_at,archived: chat.archived,pinned: chat.pinned,- can_add: false,- cannot_add_reason: (group.is_none() && shared.is_none()).then(|| reason.to_owned()),+ can_add: open && reason.is_none(),+ cannot_add_reason: reason.filter(|_| open),group,shared,+ community: None,});}- for info in roster {+ for info in &roster {let index = match listed.get(&info.jid) {Some(index) => *index,None => {@@ -245,6 +224,7 @@ impl LinkedService {shared: None,can_add: false,cannot_add_reason: None,+ community: None,});chats.len() - 1}@@ -253,18 +233,21 @@ impl LinkedService {chat.kind = ChatKind::Group;chat.name = info.display_name(&identity);(chat.group, chat.shared) = adoption_of(user, &adoptions, &info.jid);- let reason = if info.community {- Some(cannot_add::COMMUNITY)- } else if info.disappearing {- Some(cannot_add::DISAPPEARING)+ chat.community = info.community(+ info.community_jid+ .as_ref()+ .and_then(|parent| roster.iter().find(|group| &group.jid == parent)),+ );+ let reason = if info.community_parent {+ Some(CannotAdd::Community)} else if info.participant(&identity).is_none() {- Some(cannot_add::NOT_IN_GROUP)+ Some(CannotAdd::NotInGroup)} else {None};let open = chat.group.is_none() && chat.shared.is_none();chat.can_add = open && reason.is_none();- chat.cannot_add_reason = reason.filter(|_| open).map(str::to_owned);+ chat.cannot_add_reason = reason.filter(|_| open);}chats.sort_by(|a, b| {b.last_activity_at@@ -275,14 +258,15 @@ impl LinkedService {Ok(ChatList { chats })}- /// Add an existing group the person has joined as their own Macro group;- /// never creates or joins a group in WhatsApp. Adding the same group twice- /// returns the existing one.+ /// Add an existing group the person has joined, or a direct chat from+ /// their chat list, as their own Macro chat; never creates or joins+ /// anything in WhatsApp. Adding the same chat twice returns the existing+ /// one.#[tracing::instrument(name = "whatsapp.linked.adopt",skip_all,err,- fields(binding_id, created)+ fields(binding_id, created, kind))]pub async fn adopt(&self,@@ -294,41 +278,60 @@ impl LinkedService {if !self.features.adoption {return Err(LinkedError::ConfigurationRequired.into());}- if !is_group_jid(&request.group_jid) {- return Err(LinkedError::Invalid("invalid WhatsApp group").into());- }let (account, identity) = self.connected(user).await?;- let group = self- .groups- .account_group(account.id, &request.group_jid)- .await?- .ok_or(LinkedError::Invalid(- "your WhatsApp is not in this group any more",- ))?;- if group.community {- return Err(LinkedError::Invalid("community groups can't be added to Macro").into());- }- if group.disappearing {- return Err(LinkedError::Invalid(- "groups with disappearing messages can't be added to Macro",- )- .into());- }- if group.participant(&identity).is_none() {- return Err(LinkedError::Invalid("your WhatsApp is not in this group any more").into());- }+ let adoption = if is_group_jid(&request.group_jid) {+ let group = self+ .groups+ .account_group(account.id, &request.group_jid)+ .await?+ .ok_or(LinkedError::CannotAdd(CannotAdd::NotInGroup))?;+ if group.community_parent {+ return Err(LinkedError::CannotAdd(CannotAdd::Community).into());+ }+ if group.participant(&identity).is_none() {+ return Err(LinkedError::CannotAdd(CannotAdd::NotInGroup).into());+ }+ Adoption {+ jid: group.jid.clone(),+ kind: ChatKind::Group,+ name: group.display_name(&identity),+ can_post: group.can_post(&identity),+ observed_at: group.observed_at,+ }+ } else {+ if request.group_jid == identity {+ return Err(LinkedError::CannotAdd(CannotAdd::OwnChat).into());+ }+ let chat = self+ .groups+ .account_chats(account.id)+ .await?+ .into_iter()+ .find(|chat| chat.kind == ChatKind::Direct && chat.jid == request.group_jid)+ .ok_or(LinkedError::CannotAdd(CannotAdd::NotInChatList))?;+ Adoption {+ name: chat+ .name+ .filter(|name| !name.trim().is_empty())+ .unwrap_or_else(|| chat_fallback_name(&chat.jid, chat.kind, &identity)),+ jid: chat.jid,+ kind: ChatKind::Direct,+ can_post: true,+ observed_at: chrono::Utc::now(),+ }+ };let adopted = self.bindings.adopt(AdoptionRecord {user,account: &account,- name: &group.display_name(&identity),- group: &group,+ adoption: &adoption,}).await?;let span = tracing::Span::current();span.record("binding_id", tracing::field::display(adopted.binding.id));span.record("created", adopted.created);+ span.record("kind", adoption.kind.as_str());Ok(adopted.binding)}@@ -533,6 +536,7 @@ impl LinkedService {mime,bytes,sha256: Sha256::digest(bytes).into(),+ shape: super::shape::measure(kind, mime, bytes),}).await?;Ok(UploadedAttachment {diff --git a/crates/whatsapp_linked/src/domain/service/test.rs b/crates/whatsapp_linked/src/domain/service/test.rsindex 6102d829cb..24d53af095 100644--- a/crates/whatsapp_linked/src/domain/service/test.rs+++ b/crates/whatsapp_linked/src/domain/service/test.rs@@ -13,6 +13,7 @@ fn account(state: AccountState) -> Account {fn binding(state: BindingState) -> Binding {Binding {+ kind: ChatKind::Group,id: Uuid::from_u128(2),group_jid: "[email protected]".into(),user_id: "macro|[email protected]".into(),@@ -103,11 +104,11 @@ fn unnamed_groups_are_called_after_their_other_members() {person("99@lid", None),],announce: false,- disappearing: false,- community: false,+ disappearing_seconds: None,+ community_parent: false,+ community_jid: None,+ community_announcements: false,observed_at: Utc::now(),- group: None,- shared: None,};assert_eq!(group.display_name(me), "Ana, +15550000003, +2");group.participants.truncate(3);@@ -227,3 +228,51 @@ fn group_jids_are_validated_by_shape() {assert!(!is_group_jid("@g.us"));assert!(!is_group_jid("[email protected]"));}++#[test]+fn communities_name_their_groups_and_only_the_community_itself_is_closed() {+ let me = "[email protected]";+ let parent = GroupInfo {+ jid: "[email protected]".into(),+ name: "Neighbours".into(),+ participants: vec![Participant {+ identity: Identity {+ jid: me.into(),+ alternate_jid: None,+ display_name: None,+ },+ admin: false,+ }],+ announce: false,+ disappearing_seconds: None,+ community_parent: true,+ community_jid: None,+ community_announcements: false,+ observed_at: Utc::now(),+ };+ assert!(!parent.can_post(me), "a community has no chat of its own");+ assert_eq!(parent.community(None), None);++ let subgroup = GroupInfo {+ jid: "[email protected]".into(),+ name: "Garden".into(),+ community_parent: false,+ community_jid: Some(parent.jid.clone()),+ disappearing_seconds: Some(86_400),+ ..parent.clone()+ };+ assert!(subgroup.can_post(me), "disappearing messages don't block");+ assert_eq!(+ subgroup.community(Some(&parent)),+ Some(CommunityReference {+ id: parent.jid.clone(),+ name: "Neighbours".into(),+ announcements: false,+ })+ );+ assert_eq!(+ subgroup.community(None).map(|community| community.name),+ Some("WhatsApp community".into()),+ "a community missing from the list still names itself"+ );+}diff --git a/crates/whatsapp_linked/src/domain/service/timeline.rs b/crates/whatsapp_linked/src/domain/service/timeline.rsindex 838cd277bb..3ae1d51fe2 100644--- a/crates/whatsapp_linked/src/domain/service/timeline.rs+++ b/crates/whatsapp_linked/src/domain/service/timeline.rs@@ -16,9 +16,10 @@ impl LinkedService {let groups = records.into_iter().map(|record| {- let facts = account- .as_ref()- .map(|a| sending_facts_from_roster(a, record.roster));+ let facts = account.as_ref().map(|a| match record.binding.kind {+ ChatKind::Group => sending_facts_from_roster(a, record.roster),+ ChatKind::Direct => direct_sending_facts(a, &record.binding),+ });let mut group = record.summary;group.send_reason = reply_block(self.features,@@ -53,11 +54,24 @@ impl LinkedService {EntityPermission::AccessLevel { access_level } => *access_level,_ => return Err(LinkedError::Forbidden.into()),};+ let roster = self.groups.binding_roster(&binding).await?;+ let community = match roster.as_ref().and_then(|r| r.community_jid.as_deref()) {+ Some(community_jid) => {+ let parent = self+ .groups+ .binding_community(&binding, community_jid)+ .await?;+ roster.as_ref().and_then(|r| r.community(parent.as_ref()))+ }+ None => None,+ };Ok(WhatsAppGroupDetail {group,share_permission: self.timeline.permissions(id).await?,access_level,- roster: self.groups.binding_roster(&binding).await?,+ disappearing_seconds: roster.as_ref().and_then(|r| r.disappearing_seconds),+ community,+ roster,sending_identity: account.and_then(|a| a.identity_jid),limits: Capabilities::default(),})diff --git a/crates/whatsapp_linked/src/domain/session.rs b/crates/whatsapp_linked/src/domain/session.rsindex bbb8b10d3e..cb88d997dc 100644--- a/crates/whatsapp_linked/src/domain/session.rs+++ b/crates/whatsapp_linked/src/domain/session.rs@@ -276,7 +276,7 @@ impl SessionService {scope: SessionScope,page: &HistoryPage,) -> LinkedResult<Vec<(Uuid, BackfillState)>> {- if !is_group_jid(&page.chat_jid) {+ if !is_group_jid(&page.chat_jid) && !is_person_jid(&page.chat_jid) {return Ok(vec![]);}self.repository.backfill_page(scope, page).await@@ -412,8 +412,16 @@ fn is_person_jid(jid: &str) -> bool {}pub(crate) fn validate_event(event: &InboundEvent) -> LinkedResult<()> {- if !is_group_jid(&event.group_jid) {- return Err(LinkedError::Invalid("invalid group").into());+ let direct = is_person_jid(&event.group_jid);+ if !is_group_jid(&event.group_jid) && !direct {+ return Err(LinkedError::Invalid("invalid chat").into());+ }+ if event+ .chat_alternate_jid+ .as_deref()+ .is_some_and(|alternate| !direct || !is_person_jid(alternate))+ {+ return Err(LinkedError::Invalid("invalid chat").into());}match &event.kind {InboundKind::Left => Ok(()),diff --git a/crates/whatsapp_linked/src/domain/session/test.rs b/crates/whatsapp_linked/src/domain/session/test.rsindex a6d6241845..022a399ef2 100644--- a/crates/whatsapp_linked/src/domain/session/test.rs+++ b/crates/whatsapp_linked/src/domain/session/test.rs@@ -6,6 +6,7 @@ fn message(kind: MessageKind, sender: &str, target: Option<&str>) -> InboundEvenInboundEvent {event_id: Uuid::from_u128(1),group_jid: "[email protected]".into(),+ chat_alternate_jid: None,source_at: Utc::now(),observed_at: Utc::now(),kind: InboundKind::Message(Message {@@ -27,6 +28,7 @@ fn message(kind: MessageKind, sender: &str, target: Option<&str>) -> InboundEvenmedia: vec![],mentions: vec![],forwarded: false,+ view_once: false,rich: None,}),}@@ -61,9 +63,19 @@ fn malformed_events_are_rejected_before_storage() {let author = "[email protected]";assert!(validate_event(&message(MessageKind::Reaction, author, None)).is_err());assert!(validate_event(&message(MessageKind::Text, "alice", None)).is_err());- let mut other_chat = message(MessageKind::Text, author, None);- other_chat.group_jid = "[email protected]".into();- assert!(validate_event(&other_chat).is_err());+ let mut broadcast = message(MessageKind::Text, author, None);+ broadcast.group_jid = "status@broadcast".into();+ assert!(validate_event(&broadcast).is_err());+ // A direct chat is a person; only it has another address.+ let mut direct = message(MessageKind::Text, author, None);+ direct.group_jid = "[email protected]".into();+ direct.chat_alternate_jid = Some("99@lid".into());+ assert!(validate_event(&direct).is_ok());+ direct.chat_alternate_jid = Some("[email protected]".into());+ assert!(validate_event(&direct).is_err());+ let mut group_with_alternate = message(MessageKind::Text, author, None);+ group_with_alternate.chat_alternate_jid = Some("99@lid".into());+ assert!(validate_event(&group_with_alternate).is_err());let mut huge = message(MessageKind::Text, author, None);if let InboundKind::Message(m) = &mut huge.kind {m.text = "x".repeat(INBOUND_TEXT_LIMIT_BYTES + 1);diff --git a/crates/whatsapp_linked/src/domain/shape.rs b/crates/whatsapp_linked/src/domain/shape.rsnew file mode 100644index 0000000000..34cae79679--- /dev/null+++ b/crates/whatsapp_linked/src/domain/shape.rs@@ -0,0 +1,155 @@+//! Pixel size and length of a file someone sends from Macro, read from its+//! headers so the timeline and recipients' phones can reserve space for it.++use super::events::MediaShape;+use super::models::MediaKind;+use nom::IResult;+use nom::bytes::complete::take;+use nom::number::complete::{be_i32, be_u8, be_u24, be_u32, be_u64};++/// Whatever the file's headers say; unknown parts stay `None`.+pub fn measure(kind: MediaKind, mime: &str, bytes: &[u8]) -> MediaShape {+ match kind {+ MediaKind::Image => image_shape(bytes),+ MediaKind::Video => mp4_shape(bytes),+ MediaKind::Audio if mime == "audio/ogg" => MediaShape {+ duration_seconds: opus_seconds(bytes),+ ..MediaShape::default()+ },+ MediaKind::Audio if mime == "audio/mp4" || mime == "audio/aac" => MediaShape {+ duration_seconds: mp4_shape(bytes).duration_seconds,+ ..MediaShape::default()+ },+ MediaKind::Audio | MediaKind::Document => MediaShape::default(),+ }+}++fn image_shape(bytes: &[u8]) -> MediaShape {+ let dimensions = image::ImageReader::new(std::io::Cursor::new(bytes))+ .with_guessed_format()+ .ok()+ .and_then(|reader| reader.into_dimensions().ok());+ MediaShape {+ width: dimensions.map(|(width, _)| width),+ height: dimensions.map(|(_, height)| height),+ duration_seconds: None,+ }+}++/// One ISO-BMFF box: its four-letter type and payload.+fn mp4_box(input: &[u8]) -> IResult<&[u8], (&[u8], &[u8])> {+ let (input, size) = be_u32(input)?;+ let (input, kind) = take(4usize)(input)?;+ let (input, payload_len) = match size {+ // To the end of the file.+ 0 => (input, input.len()),+ // A 64-bit size follows the type.+ 1 => {+ let (input, large) = be_u64(input)?;+ (input, (large as usize).saturating_sub(16))+ }+ size => (input, (size as usize).saturating_sub(8)),+ };+ let (input, payload) = take(payload_len)(input)?;+ Ok((input, (kind, payload)))+}++/// The payloads of the boxes of type `kind` directly inside `input`.+fn children<'file>(input: &'file [u8], kind: &'static [u8]) -> Vec<&'file [u8]> {+ let mut found = vec![];+ let mut rest = input;+ while let Ok((next, (child, payload))) = mp4_box(rest) {+ if child == kind {+ found.push(payload);+ }+ rest = next;+ }+ found+}++/// Movie header: length in seconds.+fn mvhd(input: &[u8]) -> IResult<&[u8], Option<u32>> {+ let (input, version) = be_u8(input)?;+ let (input, _flags) = be_u24(input)?;+ let (input, (timescale, duration)) = if version == 1 {+ let (input, _times) = take(16usize)(input)?;+ let (input, timescale) = be_u32(input)?;+ let (input, duration) = be_u64(input)?;+ (input, (timescale, duration))+ } else {+ let (input, _times) = take(8usize)(input)?;+ let (input, timescale) = be_u32(input)?;+ let (input, duration) = be_u32(input)?;+ (input, (timescale, u64::from(duration)))+ };+ let seconds = (timescale > 0)+ .then(|| (duration as f64 / f64::from(timescale)).round())+ .filter(|seconds| *seconds >= 0.0 && *seconds <= f64::from(u32::MAX))+ .map(|seconds| seconds as u32);+ Ok((input, seconds))+}++/// Track header: the displayed width and height (rotation applied).+fn tkhd(input: &[u8]) -> IResult<&[u8], Option<(u32, u32)>> {+ let (input, version) = be_u8(input)?;+ let (input, _flags) = be_u24(input)?;+ // Times, track id, reserved, duration.+ let (input, _) = take(if version == 1 { 32usize } else { 20usize })(input)?;+ // Reserved, layer, alternate group, volume, reserved.+ let (input, _) = take(16usize)(input)?;+ let (input, a) = be_i32(input)?;+ let (input, b) = be_i32(input)?;+ let (input, _) = take(28usize)(input)?;+ let (input, width) = be_u32(input)?;+ let (input, height) = be_u32(input)?;+ // 16.16 fixed point.+ let (width, height) = (width >> 16, height >> 16);+ if width == 0 || height == 0 {+ return Ok((input, None));+ }+ // A quarter turn shows the frame on its side.+ let turned = a == 0 && b != 0;+ Ok((+ input,+ Some(if turned {+ (height, width)+ } else {+ (width, height)+ }),+ ))+}++fn mp4_shape(bytes: &[u8]) -> MediaShape {+ let Some(moov) = children(bytes, b"moov").into_iter().next() else {+ return MediaShape::default();+ };+ let duration_seconds = children(moov, b"mvhd")+ .into_iter()+ .next()+ .and_then(|header| mvhd(header).ok())+ .and_then(|(_, seconds)| seconds);+ let size = children(moov, b"trak")+ .into_iter()+ .flat_map(|track| children(track, b"tkhd"))+ .find_map(|header| tkhd(header).ok().and_then(|(_, size)| size));+ MediaShape {+ width: size.map(|(width, _)| width),+ height: size.map(|(_, height)| height),+ duration_seconds,+ }+}++/// Ogg/Opus length: the last page's granule position at Opus's fixed 48 kHz,+/// less the stream's pre-skip.+fn opus_seconds(bytes: &[u8]) -> Option<u32> {+ let head = bytes.windows(8).position(|window| window == b"OpusHead")?;+ let pre_skip: [u8; 2] = bytes.get(head + 10..head + 12)?.try_into().ok()?;+ let pre_skip = u64::from(u16::from_le_bytes(pre_skip));+ let last_page = bytes.windows(4).rposition(|window| window == b"OggS")?;+ let granule: [u8; 8] = bytes.get(last_page + 6..last_page + 14)?.try_into().ok()?;+ let samples = u64::from_le_bytes(granule).checked_sub(pre_skip)?;+ u32::try_from((samples + 24_000) / 48_000).ok()+}++#[cfg(test)]+mod test;diff --git a/crates/whatsapp_linked/src/domain/shape/test.rs b/crates/whatsapp_linked/src/domain/shape/test.rsnew file mode 100644index 0000000000..c02203ac38--- /dev/null+++ b/crates/whatsapp_linked/src/domain/shape/test.rs@@ -0,0 +1,120 @@+use super::*;++fn png(width: u32, height: u32) -> Vec<u8> {+ let mut bytes = Vec::new();+ image::RgbImage::new(width, height)+ .write_to(+ &mut std::io::Cursor::new(&mut bytes),+ image::ImageFormat::Png,+ )+ .unwrap();+ bytes+}++fn mp4_box(kind: &[u8; 4], payload: &[u8]) -> Vec<u8> {+ let mut bytes = ((payload.len() + 8) as u32).to_be_bytes().to_vec();+ bytes.extend_from_slice(kind);+ bytes.extend_from_slice(payload);+ bytes+}++/// A version-0 movie header: `duration` units at `timescale` per second.+fn mvhd_box(timescale: u32, duration: u32) -> Vec<u8> {+ let mut payload = vec![0; 4 + 8];+ payload.extend_from_slice(×cale.to_be_bytes());+ payload.extend_from_slice(&duration.to_be_bytes());+ payload.extend_from_slice(&[0; 80]);+ mp4_box(b"mvhd", &payload)+}++/// A version-0 track header with the given rotation matrix start and size.+fn tkhd_box(a: i32, b: i32, width: u32, height: u32) -> Vec<u8> {+ let mut payload = vec![0; 4 + 20 + 16];+ payload.extend_from_slice(&a.to_be_bytes());+ payload.extend_from_slice(&b.to_be_bytes());+ payload.extend_from_slice(&[0; 28]);+ payload.extend_from_slice(&(width << 16).to_be_bytes());+ payload.extend_from_slice(&(height << 16).to_be_bytes());+ mp4_box(b"tkhd", &payload)+}++fn mp4(tracks: &[Vec<u8>]) -> Vec<u8> {+ let mut moov = mvhd_box(600, 7500);+ for track in tracks {+ moov.extend(mp4_box(b"trak", track));+ }+ // The media data comes first, as many encoders write it.+ let mut file = mp4_box(b"ftyp", b"isom\0\0\0\0");+ file.extend(mp4_box(b"mdat", &[7; 64]));+ file.extend(mp4_box(b"moov", &moov));+ file+}++#[test]+fn an_image_has_its_pixel_size() {+ assert_eq!(+ measure(MediaKind::Image, "image/png", &png(640, 480)),+ MediaShape {+ width: Some(640),+ height: Some(480),+ duration_seconds: None,+ }+ );+}++#[test]+fn a_video_has_its_track_size_and_length() {+ let audio = tkhd_box(1 << 16, 0, 0, 0);+ let video = tkhd_box(1 << 16, 0, 1920, 1080);+ assert_eq!(+ measure(MediaKind::Video, "video/mp4", &mp4(&[audio, video])),+ MediaShape {+ width: Some(1920),+ height: Some(1080),+ duration_seconds: Some(13),+ }+ );+}++#[test]+fn a_portrait_video_is_measured_as_shown() {+ let turned = tkhd_box(0, 1 << 16, 1920, 1080);+ let shape = measure(MediaKind::Video, "video/mp4", &mp4(&[turned]));+ assert_eq!((shape.width, shape.height), (Some(1080), Some(1920)));+}++#[test]+fn an_opus_voice_note_has_its_length() {+ let mut head = b"OggS".to_vec();+ head.extend_from_slice(&[0; 22]);+ head.extend_from_slice(b"OpusHead");+ head.extend_from_slice(&[1, 1]);+ head.extend_from_slice(&312u16.to_le_bytes());+ head.extend_from_slice(&[0; 7]);+ let mut last = b"OggS".to_vec();+ last.extend_from_slice(&[0, 4]);+ last.extend_from_slice(&(312u64 + 48_000 * 9).to_le_bytes());+ last.extend_from_slice(&[0; 12]);+ let file = [head, last].concat();+ assert_eq!(+ measure(MediaKind::Audio, "audio/ogg", &file).duration_seconds,+ Some(9)+ );+}++#[test]+fn unreadable_files_have_no_shape() {+ for (kind, mime) in [+ (MediaKind::Image, "image/jpeg"),+ (MediaKind::Video, "video/mp4"),+ (MediaKind::Audio, "audio/ogg"),+ (MediaKind::Audio, "audio/mpeg"),+ (MediaKind::Document, "application/pdf"),+ ] {+ assert_eq!(+ measure(kind, mime, b"not really a file"),+ MediaShape::default(),+ "{mime}"+ );+ }+}diff --git a/crates/whatsapp_linked/src/domain/timeline.rs b/crates/whatsapp_linked/src/domain/timeline.rsindex 98f72f16f7..a33457051f 100644--- a/crates/whatsapp_linked/src/domain/timeline.rs+++ b/crates/whatsapp_linked/src/domain/timeline.rs@@ -15,8 +15,10 @@ pub mod view;pub struct WhatsAppGroupSummary {/// Entity identifier.pub id: Uuid,- /// Display name.+ /// Display name: the group's, or a direct chat's other person.pub name: String,+ /// A group, or a direct chat with one person (only its owner sends).+ pub kind: ChatKind,/// Actual entity owner.pub user_id: String,/// Unread live messages for this viewer.@@ -44,6 +46,11 @@ pub struct WhatsAppGroupDetail {pub access_level: models_permissions::share_permission::access_level::AccessLevel,/// Latest remote metadata, absent when no observer is connected.pub roster: Option<GroupInfo>,+ /// WhatsApp's disappearing-messages timer in seconds while it is on;+ /// Macro keeps the messages anyway. `null` when off or unknown.+ pub disappearing_seconds: Option<u32>,+ /// The WhatsApp community this group belongs to, if any.+ pub community: Option<CommunityReference>,/// Caller's own phone identity, never another account's identity.pub sending_identity: Option<String>,/// Size and mutation limits.@@ -101,6 +108,8 @@ pub struct WhatsAppGroupMessage {pub kind: WhatsAppMessageKind,/// Forwarded from another chat.pub forwarded: bool,+ /// Sent as view-once in WhatsApp; Macro shows it like any media.+ pub view_once: bool,/// People the body @-mentions.pub mentions: Vec<WhatsAppMention>,/// Poll, location, contact cards, event or system line.diff --git a/crates/whatsapp_linked/src/inbound/router.rs b/crates/whatsapp_linked/src/inbound/router.rsindex 132dc45097..fee171116f 100644--- a/crates/whatsapp_linked/src/inbound/router.rs+++ b/crates/whatsapp_linked/src/inbound/router.rs@@ -73,7 +73,7 @@ impl From<rootcause::Report<LinkedError>> for ApiError {impl IntoResponse for ApiError {fn into_response(self) -> Response {let status = match self.0 {- LinkedError::Invalid(_) => StatusCode::BAD_REQUEST,+ LinkedError::Invalid(_) | LinkedError::CannotAdd(_) => StatusCode::BAD_REQUEST,LinkedError::Forbidden => StatusCode::FORBIDDEN,LinkedError::RateLimited => StatusCode::TOO_MANY_REQUESTS,LinkedError::NotFound | LinkedError::ConfigurationRequired => StatusCode::NOT_FOUND,@@ -142,7 +142,6 @@ where"/pairing/{id}",get(pairing::<Eas, Auth>).delete(cancel::<Eas, Auth>),)- .route("/groups", get(groups::<Eas, Auth>)).route("/chats", get(chats::<Eas, Auth>)).route("/groups/adopt", post(adopt::<Eas, Auth>)).route("/whatsapp-groups", get(adopted_groups::<Eas, Auth>))@@ -363,20 +362,6 @@ pub async fn disconnect<Eas, Auth: MacroAuthorizationService>())}-/// Groups the caller's account has joined.-#[utoipa::path(get, path = "/meta/linked/groups", operation_id = "linked_groups", responses((status = 200, body = Vec<GroupInfo>)))]-pub async fn groups<Eas, Auth: MacroAuthorizationService>(- State(state): State<LinkedRouterState<Eas, Auth>>,- auth: MacroAuthorizationExtractor<Auth, UserOnly>,-) -> Result<Json<Vec<GroupInfo>>, ApiError> {- Ok(Json(- state- .service- .groups(auth.authorization.macro_user_id.as_ref())- .await?,- ))-}-/// The caller's WhatsApp chat list (groups and direct chats), newest/// activity first, with what can be added to Macro.#[utoipa::path(get, path = "/meta/linked/chats", operation_id = "linked_chats", responses((status = 200, body = ChatList)))]diff --git a/crates/whatsapp_linked/src/outbound/pg/bindings.rs b/crates/whatsapp_linked/src/outbound/pg/bindings.rsindex 3b0bfea681..943b7950ba 100644--- a/crates/whatsapp_linked/src/outbound/pg/bindings.rs+++ b/crates/whatsapp_linked/src/outbound/pg/bindings.rs@@ -8,6 +8,7 @@ use model_owner::Owner;pub(super) struct BindingRow {pub id: Uuid,pub group_jid: String,+ pub kind: String,pub user_id: String,pub state: String,pub adopted_at: chrono::DateTime<Utc>,@@ -17,6 +18,7 @@ pub(super) fn binding(row: BindingRow) -> LinkedResult<Binding> {Ok(Binding {id: row.id,group_jid: row.group_jid,+ kind: ChatKind::parse(&row.kind).ok_or(LinkedError::Unavailable)?,user_id: row.user_id,state: match row.state.as_str() {"active" => BindingState::Active,@@ -30,25 +32,16 @@ pub(super) fn binding(row: BindingRow) -> LinkedResult<Binding> {#[async_trait]impl BindingRepository for PgLinkedRepository {async fn binding(&self, group: Uuid) -> LinkedResult<Option<Binding>> {- sqlx::query_as!(- BindingRow,- "SELECT id, group_jid, user_id, state, adopted_at FROM whatsapp_group WHERE id = $1",- group- )- .fetch_optional(&self.pool)- .await- .map_err(failure)?- .map(binding)- .transpose()+ sqlx::query_as!(BindingRow, "SELECT id, group_jid, kind, user_id, state, adopted_at FROM whatsapp_group WHERE id = $1", group)+ .fetch_optional(&self.pool).await.map_err(failure)?.map(binding).transpose()}async fn adopt(&self, record: AdoptionRecord<'_>) -> LinkedResult<Adopted> {let AdoptionRecord {user,account,- name,- group,+ adoption,} = record;- let identity = account+ account.identity_jid.as_deref().ok_or(LinkedError::Forbidden)?;@@ -56,14 +49,14 @@ impl BindingRepository for PgLinkedRepository {sqlx::query!("SELECT pg_advisory_xact_lock(hashtextextended('whatsapp-group:' || $1 || ':' || $2, 0))",user,- group.jid+ adoption.jid).execute(&mut *tx).await.map_err(failure)?;sqlx::query_scalar!("SELECT id FROM whatsapp_linked_account WHERE id = $1 AND user_id = $2 AND generation = $3 AND state = 'connected' FOR SHARE", account.id,user,account.authorization_generation).fetch_optional(&mut *tx).await.map_err(failure)?.ok_or(LinkedError::Disconnected)?;- let existing = sqlx::query_as!(BindingRow,"SELECT id, group_jid, user_id, state, adopted_at FROM whatsapp_group WHERE user_id = $1 AND group_jid = $2 AND state <> 'detached' FOR UPDATE",user,group.jid)+ let existing = sqlx::query_as!(BindingRow,"SELECT id, group_jid, kind, user_id, state, adopted_at FROM whatsapp_group WHERE user_id = $1 AND group_jid = $2 AND state <> 'detached' FOR UPDATE",user,adoption.jid).fetch_optional(&mut *tx).await.map_err(failure)?;let adopted = match existing {Some(row) => Adopted {@@ -76,7 +69,7 @@ impl BindingRepository for PgLinkedRepository {share_permission_db_utils::insert_private_permission(&mut *tx, &permission).await.map_err(failure)?;- let row = sqlx::query_as!(BindingRow,"INSERT INTO whatsapp_group (id, group_jid, name, user_id, state, share_permission_id, backfill_state) VALUES ($1,$2,$3,$4,'active',$5,'pending') RETURNING id, group_jid, user_id, state, adopted_at",id,group.jid,name,user,permission)+ let row = sqlx::query_as!(BindingRow,"INSERT INTO whatsapp_group (id, group_jid, kind, name, user_id, state, share_permission_id, backfill_state) VALUES ($1,$2,$3,$4,$5,'active',$6,'pending') RETURNING id, group_jid, kind, user_id, state, adopted_at",id,adoption.jid,adoption.kind.as_str(),adoption.name,user,permission).fetch_one(&mut *tx).await.map_err(failure)?;let owner = Owner::from_principal_str(user).map_err(failure)?;entity_registry_db_utils::insert_entity(@@ -108,7 +101,7 @@ impl BindingRepository for PgLinkedRepository {VALUES ($1,$2,$3,clock_timestamp(),true,$4,$5,true)ON CONFLICT (binding_id,account_id) DO UPDATE SET generation = excluded.generation,consent_ended_at = NULL,remote_member = true,can_post = excluded.can_post,observed_at = excluded.observed_at,reconciled = true"#,- adopted.binding.id,account.id,account.authorization_generation,group.can_post(identity),group.observed_at)+ adopted.binding.id,account.id,account.authorization_generation,adoption.can_post,adoption.observed_at).execute(&mut *tx).await.map_err(failure)?;notify(&mut tx, signals::ACCOUNT_CHANGED, account.id).await?;tx.commit().await.map_err(failure)?;diff --git a/crates/whatsapp_linked/src/outbound/pg/chats.rs b/crates/whatsapp_linked/src/outbound/pg/chats.rsindex 362e145b72..430e60bc5b 100644--- a/crates/whatsapp_linked/src/outbound/pg/chats.rs+++ b/crates/whatsapp_linked/src/outbound/pg/chats.rs@@ -81,6 +81,25 @@ pub(super) async fn update_chats_in(}.map_err(failure)?;changed |= rows.rows_affected() > 0;+ // The owner's added direct chat follows the person's name.+ if chat.kind == ChatKind::Direct+ && let Some(name) = &name+ {+ let renamed = sqlx::query_scalar!(+ r#"UPDATE whatsapp_group SET name = $3+ WHERE user_id = $1 AND group_jid = $2 AND kind = 'direct' AND state = 'active' AND name <> $3+ RETURNING id"#,+ account.user_id,+ chat.jid,+ name+ )+ .fetch_all(&mut **tx)+ .await+ .map_err(failure)?;+ for group_id in renamed {+ notify_change(tx, signals::Change::Group { group_id }).await?;+ }+ }}if changed {notify_change(diff --git a/crates/whatsapp_linked/src/outbound/pg/groups.rs b/crates/whatsapp_linked/src/outbound/pg/groups.rsindex fa58058834..7b4235bbbd 100644--- a/crates/whatsapp_linked/src/outbound/pg/groups.rs+++ b/crates/whatsapp_linked/src/outbound/pg/groups.rs@@ -9,8 +9,6 @@ use chrono::{DateTime, Utc};fn same_facts(stored: &GroupInfo, observed: &GroupInfo) -> bool {let normalize = |group: &GroupInfo| GroupInfo {observed_at: DateTime::<Utc>::UNIX_EPOCH,- group: None,- shared: None,..group.clone()};normalize(stored) == normalize(observed)@@ -138,6 +136,24 @@ pub(super) async fn store_groups_in(changed_groups.extend(left_selected_in(tx, account, &group, observed_at, Some(&locked)).await?);}+ // The owner's account is always in its own direct chats: keep+ // observing them at the account's current generation.+ sqlx::query!(+ r#"INSERT INTO whatsapp_group_membership (binding_id,account_id,generation,consent_at,remote_member,can_post,reconciled,observed_at)+ SELECT g.id,$1,$2,clock_timestamp(),true,true,true,$4 FROM whatsapp_group g+ WHERE g.kind = 'direct' AND g.user_id = $3 AND g.state = 'active'+ ON CONFLICT (binding_id,account_id) DO UPDATE SET generation = excluded.generation, consent_ended_at = NULL,+ remote_member = true, can_post = true, reconciled = true, observed_at = excluded.observed_at+ WHERE whatsapp_group_membership.generation <> excluded.generation+ OR whatsapp_group_membership.consent_ended_at IS NOT NULL"#,+ account.id,+ account.generation,+ account.user_id,+ observed_at+ )+ .execute(&mut **tx)+ .await+ .map_err(failure)?;}signal_changes_in(tx, account, list_changed, changed_groups).await}@@ -355,6 +371,26 @@ impl GroupRepository for PgLinkedRepository {.map_err(failure)}+ async fn binding_community(+ &self,+ binding: &Binding,+ community_jid: &str,+ ) -> LinkedResult<Option<GroupInfo>> {+ sqlx::query_scalar!(+ r#"SELECT r.metadata FROM whatsapp_group_roster r+ JOIN whatsapp_group_membership m ON m.account_id = r.account_id+ WHERE m.binding_id = $1 AND m.consent_ended_at IS NULL AND r.group_jid = $2+ ORDER BY r.observed_at DESC LIMIT 1"#,+ binding.id,+ community_jid+ )+ .fetch_optional(&self.pool)+ .await+ .map_err(failure)?+ .map(decode::<GroupInfo>)+ .transpose()+ }+async fn binding_roster(&self, binding: &Binding) -> LinkedResult<Option<GroupInfo>> {let roster = sqlx::query_scalar!(r#"SELECT r.metadata FROM whatsapp_group_roster rdiff --git a/crates/whatsapp_linked/src/outbound/pg/ingest.rs b/crates/whatsapp_linked/src/outbound/pg/ingest.rsindex 8726ee5503..ee28fba664 100644--- a/crates/whatsapp_linked/src/outbound/pg/ingest.rs+++ b/crates/whatsapp_linked/src/outbound/pg/ingest.rs@@ -69,7 +69,7 @@ pub(super) async fn observed_bindings_in() -> LinkedResult<Vec<Binding>> {sqlx::query_as!(bindings::BindingRow,- r#"SELECT b.id, b.group_jid, b.user_id, b.state, b.adopted_at+ r#"SELECT b.id, b.group_jid, b.kind, b.user_id, b.state, b.adopted_atFROM whatsapp_group b JOIN whatsapp_group_membership m ON m.binding_id = b.idWHERE b.group_jid = $1 AND b.state = 'active'AND m.account_id = $2 AND m.generation = $3 AND m.consent_ended_at IS NULL@@ -270,8 +270,8 @@ pub(super) async fn reserve_in(// revisions carry none of it and keep what is stored.sqlx::query!(r#"INSERT INTO whatsapp_group_message (id, binding_id, person_id, source_id, origin, source_at, content_revision, deleted_at, revision_content, revised_at,- kind, rich, mentions, forwarded)- VALUES ($11, $1, $2, $3, $4, $5, $6, $7, $8, $9, $12, $13, $14, $15)+ kind, rich, mentions, forwarded, view_once)+ VALUES ($11, $1, $2, $3, $4, $5, $6, $7, $8, $9, $12, $13, $14, $15, $16)ON CONFLICT (binding_id, person_id, source_id) DO UPDATE SETdeleted_at = COALESCE(whatsapp_group_message.deleted_at, excluded.deleted_at),revision_content = CASE WHEN excluded.content_revision > whatsapp_group_message.content_revision@@ -283,7 +283,8 @@ pub(super) async fn reserve_in(kind = CASE WHEN $10 THEN whatsapp_group_message.kind ELSE excluded.kind END,rich = CASE WHEN $10 THEN whatsapp_group_message.rich ELSE COALESCE(excluded.rich, whatsapp_group_message.rich) END,mentions = CASE WHEN $10 OR cardinality(excluded.mentions) = 0 THEN whatsapp_group_message.mentions ELSE excluded.mentions END,- forwarded = whatsapp_group_message.forwarded OR excluded.forwarded"#,+ forwarded = whatsapp_group_message.forwarded OR excluded.forwarded,+ view_once = whatsapp_group_message.view_once OR excluded.view_once"#,binding.id,person,source,@@ -298,7 +299,8 @@ pub(super) async fn reserve_in(entry_kind,rich,&message.mentions,- message.forwarded+ message.forwarded,+ message.view_once).execute(&mut **tx).awaitdiff --git a/crates/whatsapp_linked/src/outbound/pg/sends.rs b/crates/whatsapp_linked/src/outbound/pg/sends.rsindex fd64294c14..0355377e65 100644--- a/crates/whatsapp_linked/src/outbound/pg/sends.rs+++ b/crates/whatsapp_linked/src/outbound/pg/sends.rs@@ -34,20 +34,33 @@ fn progress(row: SendRow) -> LinkedResult<SendProgress> {})}+/// A shape value as an integer column.+fn column(value: Option<u32>) -> Option<i32> {+ value.map(|value| value.min(i32::MAX as u32) as i32)+}++/// An integer column as a shape value.+fn unsigned(value: Option<i32>) -> Option<u32> {+ value.and_then(|value| u32::try_from(value).ok())+}+#[async_trait]impl SendRepository for PgLinkedRepository {async fn stage_upload(&self, upload: StagedUpload<'_>) -> LinkedResult<Uuid> {let id = Uuid::now_v7();sqlx::query!(- r#"INSERT INTO whatsapp_media_blob (document_id, group_id, user_id, mime, filename, sha256, bytes)- VALUES ($1, $2, $3, $4, $5, $6, $7)"#,+ r#"INSERT INTO whatsapp_media_blob (document_id, group_id, user_id, mime, filename, sha256, bytes, width, height, duration_seconds)+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)"#,id,upload.group_id,upload.user,upload.mime,upload.filename,&upload.sha256[..],- upload.bytes+ upload.bytes,+ column(upload.shape.width.filter(|width| *width > 0)),+ column(upload.shape.height.filter(|height| *height > 0)),+ column(upload.shape.duration_seconds)).execute(&self.pool).await@@ -80,6 +93,9 @@ impl SendRepository for PgLinkedRepository {account: &Account,binding: &Binding,) -> LinkedResult<SendingFacts> {+ if binding.kind == ChatKind::Direct {+ return Ok(crate::domain::ports::direct_sending_facts(account, binding));+ }let group = sqlx::query_scalar!("SELECT metadata FROM whatsapp_group_roster WHERE account_id = $1 AND group_jid = $2",account.id,@@ -182,29 +198,37 @@ impl SendRepository for PgLinkedRepository {.await.map_err(failure)?.is_some();- let metadata = sqlx::query_scalar!(- "SELECT metadata FROM whatsapp_group_roster WHERE account_id = $1 AND group_jid = $2",- account.id,- binding.group_jid- )- .fetch_optional(&mut *tx)- .await- .map_err(failure)?- .map(decode::<GroupInfo>)- .transpose()?- .ok_or(LinkedError::Forbidden)?;let identity = account.identity_jid.as_deref().ok_or(LinkedError::Forbidden)?;- if !metadata.can_post(identity) {- return Err(LinkedError::Forbidden.into());- }+ let observed_at = match binding.kind {+ ChatKind::Group => {+ let metadata = sqlx::query_scalar!(+ "SELECT metadata FROM whatsapp_group_roster WHERE account_id = $1 AND group_jid = $2",+ account.id,+ binding.group_jid+ )+ .fetch_optional(&mut *tx)+ .await+ .map_err(failure)?+ .map(decode::<GroupInfo>)+ .transpose()?+ .ok_or(LinkedError::Forbidden)?;+ if !metadata.can_post(identity) {+ return Err(LinkedError::Forbidden.into());+ }+ metadata.observed_at+ }+ // Only the owner's own account is in a direct chat.+ ChatKind::Direct if binding.user_id == user => Utc::now(),+ ChatKind::Direct => return Err(LinkedError::Forbidden.into()),+ };sqlx::query!(r#"INSERT INTO whatsapp_group_membership (binding_id,account_id,generation,consent_at,remote_member,can_post,reconciled,observed_at)VALUES ($1,$2,$3,clock_timestamp(),true,true,true,$4)ON CONFLICT (binding_id,account_id) DO UPDATE SET generation = excluded.generation,consent_ended_at = NULL,remote_member = true,can_post = true,reconciled = true,observed_at = excluded.observed_at"#,- binding.id,account.id,account.authorization_generation,metadata.observed_at).execute(&mut *tx).await.map_err(failure)?;+ binding.id,account.id,account.authorization_generation,observed_at).execute(&mut *tx).await.map_err(failure)?;// The group lock also serializes idempotency and sequence allocation.let sequence = if replayed {None@@ -357,7 +381,7 @@ async fn content_in(Ok(match &request.message {ReplyContent::Media { upload_id, caption } => {let Some(blob) = sqlx::query!(- "SELECT mime, filename FROM whatsapp_media_blob WHERE document_id = $1",+ "SELECT mime, filename, width, height, duration_seconds FROM whatsapp_media_blob WHERE document_id = $1",upload_id).fetch_optional(&mut **tx)@@ -378,6 +402,11 @@ async fn content_in(Some(quoted) => target_in(tx, binding, quoted, identity).await?,None => None,},+ shape: MediaShape {+ width: unsigned(blob.width),+ height: unsigned(blob.height),+ duration_seconds: unsigned(blob.duration_seconds),+ },})}ReplyContent::Text { text, mentions } => Some(OutgoingContent::Text {@@ -436,7 +465,8 @@ impl PgLinkedRepository {SELECT id FROM whatsapp_send WHERE account_id = $1 AND generation = $3 AND state = 'pending'ORDER BY group_id, group_sequence LIMIT $4 FOR UPDATE SKIP LOCKED)AND b.id = s.group_id- RETURNING s.id, s.group_id AS binding_id, s.group_sequence, s.payload, s.traceparent, b.group_jid"#,+ RETURNING s.id, s.group_id AS binding_id, s.group_sequence, s.payload, s.traceparent, b.group_jid,+ (SELECT r.metadata FROM whatsapp_group_roster r WHERE r.account_id = s.account_id AND r.group_jid = b.group_jid) AS roster"#,account.id,scope.lease_epoch,account.generation,@@ -461,6 +491,11 @@ impl PgLinkedRepository {group_jid: row.group_jid,group_sequence: row.group_sequence,content,+ disappearing_seconds: row+ .roster+ .map(decode::<GroupInfo>)+ .transpose()?+ .and_then(|roster| roster.disappearing_seconds),traceparent: row.traceparent,}),None => {@@ -601,7 +636,7 @@ impl PgLinkedRepository {let request: SendReply = decode(row.payload)?;let binding = sqlx::query_as!(bindings::BindingRow,- "SELECT id, group_jid, user_id, state, adopted_at FROM whatsapp_group WHERE id = $1",+ "SELECT id, group_jid, kind, user_id, state, adopted_at FROM whatsapp_group WHERE id = $1",row.binding_id).fetch_one(&mut *tx)@@ -613,7 +648,7 @@ impl PgLinkedRepository {let (kind, text, target) = match &request.message {ReplyContent::Media { upload_id, caption } => {let blob = sqlx::query!(- "SELECT mime, filename, sha256, octet_length(bytes) AS \"size!\" FROM whatsapp_media_blob WHERE document_id = $1",+ "SELECT mime, filename, sha256, octet_length(bytes) AS \"size!\", width, height, duration_seconds FROM whatsapp_media_blob WHERE document_id = $1",upload_id).fetch_one(&mut *tx)@@ -628,9 +663,9 @@ impl PgLinkedRepository {.try_into().map_err(|_| LinkedError::Unavailable)?,locator: vec![],- width: None,- height: None,- duration_seconds: None,+ width: unsigned(blob.width),+ height: unsigned(blob.height),+ duration_seconds: unsigned(blob.duration_seconds),presentation: None,});upload = Some(*upload_id);@@ -683,6 +718,7 @@ impl PgLinkedRepository {let event = InboundEvent {event_id: send,group_jid: binding.group_jid.clone(),+ chat_alternate_jid: None,source_at: *server_at,observed_at: Utc::now(),kind: InboundKind::Message(Message {@@ -704,6 +740,7 @@ impl PgLinkedRepository {_ => vec![],},forwarded: false,+ view_once: false,rich: None,}),};diff --git a/crates/whatsapp_linked/src/outbound/pg/test.rs b/crates/whatsapp_linked/src/outbound/pg/test.rsindex 6481bf0dd2..868a7a7944 100644--- a/crates/whatsapp_linked/src/outbound/pg/test.rs+++ b/crates/whatsapp_linked/src/outbound/pg/test.rs@@ -148,11 +148,11 @@ fn group(members: &[&str]) -> GroupInfo {}).collect(),announce: false,- disappearing: false,- community: false,+ disappearing_seconds: None,+ community_parent: false,+ community_jid: None,+ community_announcements: false,observed_at: Utc::now(),- group: None,- shared: None,}}@@ -160,6 +160,7 @@ fn text(event: u128, sender: &str, source: &str, body: &str) -> InboundEvent {InboundEvent {event_id: Uuid::from_u128(event),group_jid: GROUP.into(),+ chat_alternate_jid: None,source_at: Utc::now(),observed_at: Utc::now(),kind: InboundKind::Message(Message {@@ -178,6 +179,7 @@ fn text(event: u128, sender: &str, source: &str, body: &str) -> InboundEvent {media: vec![],mentions: vec![],forwarded: false,+ view_once: false,rich: None,}),}@@ -256,7 +258,7 @@ async fn adopted(async fn adoption_creates_a_shared_entity_and_leaving_whatsapp_keeps_view_access(pool: PgPool) {let (linked, session, _, binding, _, bob) = adopted(&pool).await;assert_eq!(binding.user_id, ALICE);- let mine = &linked.groups(ALICE).await.unwrap()[0];+ let mine = &linked.chats(ALICE).await.unwrap().chats[0];assert_eq!((mine.group.clone(), mine.shared.clone()),(@@ -267,7 +269,7 @@ async fn adoption_creates_a_shared_entity_and_leaving_whatsapp_keeps_view_accessNone));- let shared = &linked.groups(BOB).await.unwrap()[0];+ let shared = &linked.chats(BOB).await.unwrap().chats[0];assert_eq!((shared.group.clone(), shared.shared.clone()),(@@ -332,7 +334,7 @@ async fn each_person_adds_their_own_group_once(pool: PgPool) {.unwrap();assert_ne!(bobs.id, binding.id);assert_eq!(bobs.user_id, BOB);- let listed = &linked.groups(BOB).await.unwrap()[0];+ let listed = &linked.chats(BOB).await.unwrap().chats[0];assert_eq!((listed.group.as_ref().map(|g| g.id), listed.shared.clone()),(Some(bobs.id), None),@@ -527,6 +529,7 @@ async fn a_reaction_before_its_message_is_deferred_and_replayed(pool: PgPool) {media: vec![],mentions: vec![],forwarded: false,+ view_once: false,rich: None,}),..text(1, BOB_JID, "unused", "")@@ -587,6 +590,7 @@ async fn edits_apply_in_source_order_and_deletes_are_permanent(pool: PgPool) {media: vec![],mentions: vec![],forwarded: false,+ view_once: false,rich: None,}),..text(event, CUSTOMER_JID, "unused", "")@@ -975,7 +979,7 @@ async fn stored_group_facts_authorize_adoption_and_sending_however_old(pool: PgP.unwrap();let mut community = group(&[ALICE_JID]);community.jid = "[email protected]".into();- community.community = true;+ community.community_parent = true;session.update_groups(alice, &[info, community], true).await@@ -992,7 +996,7 @@ async fn stored_group_facts_authorize_adoption_and_sending_however_old(pool: PgP.await.unwrap_err().current_context(),- LinkedError::Invalid(_)+ LinkedError::CannotAdd(CannotAdd::Community)));}@@ -1066,3 +1070,5 @@ async fn rate_limited_send_never_creates_a_dispatchable_intent(pool: PgPool) {}mod chats;+mod communities;+mod direct;diff --git a/crates/whatsapp_linked/src/outbound/pg/test/changes.rs b/crates/whatsapp_linked/src/outbound/pg/test/changes.rsindex e0255d805b..6b88d75564 100644--- a/crates/whatsapp_linked/src/outbound/pg/test/changes.rs+++ b/crates/whatsapp_linked/src/outbound/pg/test/changes.rs@@ -59,7 +59,15 @@ async fn rosters_signal_only_real_changes_and_rename_the_owners_group(pool: PgPogroup_id: binding.id});- assert!(linked.groups(ALICE).await.unwrap().is_empty());+ assert!(+ linked+ .chats(ALICE)+ .await+ .unwrap()+ .chats+ .iter()+ .all(|chat| !chat.can_add)+ );let detail = linked.group_detail(&receipt::<MessageView>(ALICE, binding.id)).awaitdiff --git a/crates/whatsapp_linked/src/outbound/pg/test/chats.rs b/crates/whatsapp_linked/src/outbound/pg/test/chats.rsindex c04f6d6f41..f5695e7154 100644--- a/crates/whatsapp_linked/src/outbound/pg/test/chats.rs+++ b/crates/whatsapp_linked/src/outbound/pg/test/chats.rs@@ -82,7 +82,7 @@ async fn the_chat_list_merges_history_activity_and_the_roster(pool: PgPool) {chat.name.as_str(),chat.archived,chat.can_add,- chat.cannot_add_reason.as_deref(),+ chat.cannot_add_reason,chat.group.as_ref().map(|group| group.id),)})@@ -95,8 +95,8 @@ async fn the_chat_list_merges_history_activity_and_the_roster(pool: PgPool) {ChatKind::Direct,"Customer",false,- false,- Some(cannot_add::DIRECT),+ true,+ None,None),(@@ -105,7 +105,7 @@ async fn the_chat_list_merges_history_activity_and_the_roster(pool: PgPool) {"Old group",true,false,- Some(cannot_add::NOT_IN_GROUP),+ Some(CannotAdd::NotInGroup),None),(diff --git a/crates/whatsapp_linked/src/outbound/pg/test/communities.rs b/crates/whatsapp_linked/src/outbound/pg/test/communities.rsnew file mode 100644index 0000000000..a0b9d24a8c--- /dev/null+++ b/crates/whatsapp_linked/src/outbound/pg/test/communities.rs@@ -0,0 +1,150 @@+//! Groups with disappearing messages and the groups of a community are added,+//! kept and sent to like any other group; only the community itself can't be.++use super::*;++const WEEK: u32 = 7 * 24 * 60 * 60;+const COMMUNITY: &str = "[email protected]";+const ANNOUNCEMENTS: &str = "[email protected]";+const SUBGROUP: &str = "[email protected]";++fn named(jid: &str, name: &str, members: &[&str]) -> GroupInfo {+ GroupInfo {+ jid: jid.to_owned(),+ name: name.to_owned(),+ ..group(members)+ }+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn disappearing_and_community_groups_are_added_like_any_other(pool: PgPool) {+ workspace(&pool).await;+ let (linked, session, _) = services(&pool);+ let alice = pair(&linked, &session, ALICE, ALICE_JID).await;+ let members = [ALICE_JID, CUSTOMER_JID];+ let disappearing = GroupInfo {+ disappearing_seconds: Some(WEEK),+ ..named(GROUP, "Vanishing", &members)+ };+ let community = GroupInfo {+ community_parent: true,+ ..named(COMMUNITY, "Neighbours", &members)+ };+ let announcements = GroupInfo {+ community_jid: Some(COMMUNITY.to_owned()),+ community_announcements: true,+ announce: true,+ ..named(ANNOUNCEMENTS, "Neighbours", &members)+ };+ let subgroup = GroupInfo {+ community_jid: Some(COMMUNITY.to_owned()),+ ..named(SUBGROUP, "Garden", &members)+ };+ session+ .update_groups(+ alice,+ &[disappearing, community, announcements, subgroup],+ true,+ )+ .await+ .unwrap();++ let chats = linked.chats(ALICE).await.unwrap().chats;+ let listed = |jid: &str| {+ let chat = chats.iter().find(|chat| chat.jid == jid).unwrap();+ (+ chat.can_add,+ chat.cannot_add_reason.clone(),+ chat.community.clone(),+ )+ };+ let neighbours = |announcements| CommunityReference {+ id: COMMUNITY.to_owned(),+ name: "Neighbours".to_owned(),+ announcements,+ };+ assert_eq!(listed(GROUP), (true, None, None));+ assert_eq!(listed(COMMUNITY), (false, Some(CannotAdd::Community), None));+ assert_eq!(listed(ANNOUNCEMENTS), (true, None, Some(neighbours(true))));+ assert_eq!(listed(SUBGROUP), (true, None, Some(neighbours(false))));++ let adopt = |jid: &str| {+ let request = AdoptGroup {+ group_jid: jid.to_owned(),+ };+ let linked = &linked;+ async move { linked.adopt(ALICE, &request, SendAuthority::Human).await }+ };+ assert!(matches!(+ adopt(COMMUNITY).await.unwrap_err().current_context(),+ LinkedError::CannotAdd(CannotAdd::Community)+ ));+ let detail = |binding: Binding| {+ let linked = &linked;+ async move {+ linked+ .group_detail(&receipt::<MessageView>(ALICE, binding.id))+ .await+ .unwrap()+ }+ };++ let vanishing = adopt(GROUP).await.unwrap();+ let shown = detail(vanishing.clone()).await;+ assert_eq!(shown.disappearing_seconds, Some(WEEK));+ assert_eq!(shown.community, None);+ assert!(shown.group.can_send);++ let garden = detail(adopt(SUBGROUP).await.unwrap()).await;+ assert_eq!(garden.community, Some(neighbours(false)));+ assert_eq!(garden.disappearing_seconds, None);+ assert!(garden.group.can_send);++ // Everyone reads the announcement group; only admins post.+ let notices = detail(adopt(ANNOUNCEMENTS).await.unwrap()).await;+ assert_eq!(notices.community, Some(neighbours(true)));+ assert_eq!(+ notices.group.send_reason,+ Some(ReplyBlock::NotAllowedInGroup)+ );++ // A message in the disappearing group is kept like any other.+ assert_eq!(+ session+ .ingest_event(alice, &text(1, CUSTOMER_JID, "3EB0GONE", "see you"))+ .await+ .unwrap(),+ IngestOutcome::Applied+ );+ let kept = linked+ .messages(&receipt::<MessageView>(ALICE, vanishing.id), None, 10)+ .await+ .unwrap()+ .messages;+ assert_eq!(+ kept.iter()+ .map(|message| message.body.as_str())+ .collect::<Vec<_>>(),+ ["see you"]+ );++ // Macro's sends carry the group's timer.+ linked+ .send_reply(+ &receipt::<MessageWrite>(ALICE, vanishing.id),+ &SendReply {+ idempotency_key: Uuid::now_v7(),+ message: ReplyContent::Text {+ text: "noted".into(),+ mentions: vec![],+ },+ reply_to: None,+ },+ SendAuthority::Human,+ )+ .await+ .unwrap();+ let claimed = session.claim_sends(alice, 8).await.unwrap();+ assert_eq!(claimed.len(), 1);+ assert_eq!(claimed[0].disappearing_seconds, Some(WEEK));+}diff --git a/crates/whatsapp_linked/src/outbound/pg/test/direct.rs b/crates/whatsapp_linked/src/outbound/pg/test/direct.rsnew file mode 100644index 0000000000..7d109cdb71--- /dev/null+++ b/crates/whatsapp_linked/src/outbound/pg/test/direct.rs@@ -0,0 +1,224 @@+//! Direct chats: added from the chat list like groups, both sides of the+//! conversation kept, named after the person, sent to only by the owner.++use super::*;++fn customer_chat(name: &str) -> ChatUpdate {+ ChatUpdate {+ jid: CUSTOMER_JID.to_owned(),+ kind: ChatKind::Direct,+ name: Some(name.to_owned()),+ last_activity_at: Some(Utc::now()),+ archived: None,+ pinned: None,+ anchor: None,+ create: true,+ }+}++fn direct_text(event: u128, sender: &str, from_me: bool, source: &str, body: &str) -> InboundEvent {+ let mut event = text(event, sender, source, body);+ event.group_jid = CUSTOMER_JID.into();+ if let InboundKind::Message(message) = &mut event.kind {+ message.from_me = from_me;+ }+ event+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn a_direct_chat_is_added_kept_and_sent_to_only_by_its_owner(pool: PgPool) {+ workspace(&pool).await;+ let (linked, session, _) = services(&pool);+ let alice = pair(&linked, &session, ALICE, ALICE_JID).await;+ let bob = pair(&linked, &session, BOB, BOB_JID).await;+ session+ .update_chats(alice, &[customer_chat("Customer")])+ .await+ .unwrap();+ // Bob talks to the same person in his own chat.+ session+ .update_chats(bob, &[customer_chat("Customer")])+ .await+ .unwrap();++ let listed = linked.chats(ALICE).await.unwrap().chats;+ let chat = listed.iter().find(|chat| chat.jid == CUSTOMER_JID).unwrap();+ assert_eq!(+ (chat.kind, chat.can_add, chat.cannot_add_reason),+ (ChatKind::Direct, true, None)+ );+ let own = AdoptGroup {+ group_jid: ALICE_JID.into(),+ };+ assert!(matches!(+ linked+ .adopt(ALICE, &own, SendAuthority::Human)+ .await+ .unwrap_err()+ .current_context(),+ LinkedError::CannotAdd(CannotAdd::OwnChat)+ ));+ let request = AdoptGroup {+ group_jid: CUSTOMER_JID.into(),+ };+ let binding = linked+ .adopt(ALICE, &request, SendAuthority::Human)+ .await+ .unwrap();+ assert_eq!(binding.kind, ChatKind::Direct);+ assert_eq!(+ linked+ .adopt(ALICE, &request, SendAuthority::Human)+ .await+ .unwrap()+ .id,+ binding.id,+ "adding it again returns the same chat"+ );++ let detail = linked+ .group_detail(&receipt::<MessageView>(ALICE, binding.id))+ .await+ .unwrap();+ assert_eq!(+ (+ detail.group.kind,+ detail.group.name.as_str(),+ detail.group.can_send+ ),+ (ChatKind::Direct, "Customer", true)+ );+ assert!(detail.roster.is_none());+ let bobs_list = linked.chats(BOB).await.unwrap().chats;+ let bobs = bobs_list+ .iter()+ .find(|chat| chat.jid == CUSTOMER_JID)+ .unwrap();+ assert_eq!(+ (bobs.can_add, bobs.shared.is_none()),+ (true, true),+ "Alice's chat with the customer is not Bob's"+ );++ // Both sides of the conversation land.+ for event in [+ direct_text(1, CUSTOMER_JID, false, "3EB0HELLO", "hi, is my order out?"),+ direct_text(2, ALICE_JID, true, "3EB0REPLY", "shipping today"),+ ] {+ assert_eq!(+ session.ingest_event(alice, &event).await.unwrap(),+ IngestOutcome::Applied+ );+ }+ let messages = linked+ .messages(&receipt::<MessageView>(ALICE, binding.id), None, 10)+ .await+ .unwrap()+ .messages;+ let shown: Vec<(&str, Option<&str>)> = messages+ .iter()+ .map(|message| (message.body.as_str(), message.sender.user_id.as_deref()))+ .collect();+ assert_eq!(+ shown,+ [+ ("shipping today", Some(ALICE)),+ ("hi, is my order out?", None)+ ]+ );+ // Bob's account is not in Alice's chat: nothing it sees reaches it.+ assert_eq!(+ session+ .ingest_event(+ bob,+ &direct_text(3, CUSTOMER_JID, false, "3EB0BOB", "for Bob")+ )+ .await+ .unwrap(),+ IngestOutcome::NotObserved+ );++ // Shared with Bob: he reads, never sends.+ let mut tx = pool.begin().await.unwrap();+ entity_access_db_utils::direct_share::set(+ &mut tx,+ &binding.id,+ EntityType::WhatsAppGroup,+ &BOB.to_owned().try_into().unwrap(),+ Some(AccessLevel::View),+ false,+ )+ .await+ .unwrap();+ tx.commit().await.unwrap();+ session.update_groups(bob, &[], true).await.unwrap();+ let bobs_view = linked+ .group_detail(&receipt::<MessageView>(BOB, binding.id))+ .await+ .unwrap();+ assert_eq!(+ (bobs_view.group.can_send, bobs_view.group.send_reason),+ (false, Some(ReplyBlock::NotObserving))+ );+ let send = |user: &'static str| SendReply {+ idempotency_key: Uuid::now_v7(),+ message: ReplyContent::Text {+ text: format!("from {user}"),+ mentions: vec![],+ },+ reply_to: None,+ };+ assert!(+ linked+ .send_reply(+ &receipt::<MessageWrite>(BOB, binding.id),+ &send(BOB),+ SendAuthority::Human+ )+ .await+ .is_err()+ );+ linked+ .send_reply(+ &receipt::<MessageWrite>(ALICE, binding.id),+ &send(ALICE),+ SendAuthority::Human,+ )+ .await+ .unwrap();+ let claimed = session.claim_sends(alice, 8).await.unwrap();+ assert_eq!(+ claimed+ .iter()+ .map(|send| send.group_jid.as_str())+ .collect::<Vec<_>>(),+ [CUSTOMER_JID]+ );++ // The chat follows the person's name, and the owner's next full refresh+ // keeps observing it.+ session+ .update_chats(alice, &[customer_chat("Customer (Acme)")])+ .await+ .unwrap();+ session.update_groups(alice, &[], true).await.unwrap();+ assert_eq!(+ linked+ .group_detail(&receipt::<MessageView>(ALICE, binding.id))+ .await+ .unwrap()+ .group+ .name,+ "Customer (Acme)"+ );+ assert_eq!(+ session+ .ingest_event(+ alice,+ &direct_text(4, CUSTOMER_JID, false, "3EB0LATER", "thanks!")+ )+ .await+ .unwrap(),+ IngestOutcome::Applied+ );+}diff --git a/crates/whatsapp_linked/src/outbound/pg/test/media.rs b/crates/whatsapp_linked/src/outbound/pg/test/media.rsindex 33b865bdad..112121ec84 100644--- a/crates/whatsapp_linked/src/outbound/pg/test/media.rs+++ b/crates/whatsapp_linked/src/outbound/pg/test/media.rs@@ -359,6 +359,7 @@ async fn an_uploaded_attachment_is_sent_once_and_becomes_the_messages_document(pfilename: "quote.pdf".into(),caption: Some("Signed quote".into()),quote: None,+ shape: MediaShape::default(),});let outbound = session.outbound_media(alice, progress.id).await.unwrap();@@ -491,3 +492,73 @@ async fn a_failed_attachment_preserves_the_plain_caption(pool: PgPool) {.unwrap();assert_eq!(content(&pool, binding.id).await, vec!["Look at this"]);}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn a_sent_image_keeps_the_size_read_from_its_file(pool: PgPool) {+ let (linked, session, _, binding, alice, _) = adopted(&pool).await;+ let mut png = Vec::new();+ image::RgbImage::new(64, 48)+ .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)+ .unwrap();+ let uploaded = linked+ .upload_attachment(+ &receipt::<MessageWrite>(ALICE, binding.id),+ "plan.png",+ "image/png",+ &png,+ SendAuthority::Human,+ )+ .await+ .unwrap();+ let progress = linked+ .send_reply(+ &receipt::<MessageWrite>(ALICE, binding.id),+ &SendReply {+ idempotency_key: Uuid::now_v7(),+ message: ReplyContent::Media {+ upload_id: uploaded.upload_id,+ caption: None,+ },+ reply_to: None,+ },+ SendAuthority::Human,+ )+ .await+ .unwrap();+ let claimed = session.claim_sends(alice, 8).await.unwrap();+ let OutgoingContent::Media { shape, .. } = &claimed[0].content else {+ panic!("a media send");+ };+ let size = MediaShape {+ width: Some(64),+ height: Some(48),+ duration_seconds: None,+ };+ assert_eq!(*shape, size, "the phone gets the size with the message");+ session+ .begin_dispatch(alice, progress.id, "3EB0PNG")+ .await+ .unwrap();+ session+ .record_send_outcome(+ alice,+ progress.id,+ SendOutcome::Accepted {+ server_at: Utc::now(),+ },+ )+ .await+ .unwrap();+ let stored = sqlx::query!(+ "SELECT width, height, duration_seconds FROM whatsapp_group_attachment WHERE binding_id = $1 AND source_id = '3EB0PNG'",+ binding.id+ )+ .fetch_one(&pool)+ .await+ .unwrap();+ assert_eq!(+ (stored.width, stored.height, stored.duration_seconds),+ (Some(64), Some(48), None),+ "the timeline reserves the space like for a received image"+ );+}diff --git a/crates/whatsapp_linked/src/outbound/pg/timeline.rs b/crates/whatsapp_linked/src/outbound/pg/timeline.rsindex d240fcc900..9599f1482f 100644--- a/crates/whatsapp_linked/src/outbound/pg/timeline.rs+++ b/crates/whatsapp_linked/src/outbound/pg/timeline.rs@@ -102,7 +102,7 @@ impl PgLinkedRepository {#[async_trait]impl TimelineRepository for PgLinkedRepository {async fn visible_groups(&self, user: &str) -> LinkedResult<Vec<VisibleGroup>> {- let rows = sqlx::query!(r#"SELECT g.id,g.name,g.user_id,g.group_jid,g.state,g.adopted_at,g.backfill_state,g.backfill_imported,+ let rows = sqlx::query!(r#"SELECT g.id,g.name,g.kind,g.user_id,g.group_jid,g.state,g.adopted_at,g.backfill_state,g.backfill_imported,(SELECT count(*) FROM whatsapp_group_message m WHERE m.binding_id=g.id AND m.message_id IS NOT NULLAND m.deleted_at IS NULL AND m.origin<>'history' AND m.kind<>'system'AND NOT EXISTS(SELECT 1 FROM whatsapp_external_person p WHERE p.id=m.person_id AND p.user_id=$1)@@ -126,6 +126,7 @@ impl TimelineRepository for PgLinkedRepository {summary: WhatsAppGroupSummary {id: row.id,name: row.name,+ kind: ChatKind::parse(&row.kind).ok_or(LinkedError::Unavailable)?,user_id: row.user_id.clone(),unread_count: row.unread_count,last_message_at: row.last_message_at,@@ -136,6 +137,7 @@ impl TimelineRepository for PgLinkedRepository {binding: bindings::binding(bindings::BindingRow {id: row.id,group_jid: row.group_jid,+ kind: row.kind,user_id: row.user_id,state: row.state,adopted_at: row.adopted_at,@@ -146,7 +148,7 @@ impl TimelineRepository for PgLinkedRepository {.collect()}async fn summary(&self, group: Uuid, user: &str) -> LinkedResult<WhatsAppGroupSummary> {- let row = sqlx::query!(r#"SELECT g.id,g.name,g.user_id,g.backfill_state,g.backfill_imported,+ let row = sqlx::query!(r#"SELECT g.id,g.name,g.kind,g.user_id,g.backfill_state,g.backfill_imported,(SELECT count(*) FROM whatsapp_group_message m WHERE m.binding_id = g.id AND m.message_id IS NOT NULLAND m.deleted_at IS NULL AND m.origin <> 'history' AND m.kind <> 'system'AND NOT EXISTS (SELECT 1 FROM whatsapp_external_person p WHERE p.id = m.person_id AND p.user_id = $2)@@ -157,6 +159,7 @@ impl TimelineRepository for PgLinkedRepository {Ok(WhatsAppGroupSummary {id: row.id,name: row.name,+ kind: ChatKind::parse(&row.kind).ok_or(LinkedError::Unavailable)?,user_id: row.user_id,unread_count: row.unread_count,last_message_at: row.last_message_at,@@ -173,7 +176,7 @@ impl TimelineRepository for PgLinkedRepository {limit: i64,) -> LinkedResult<WhatsAppGroupMessages> {let rows = sqlx::query!(r#"SELECT m.id,m.person_id,p.user_id,COALESCE(p.display_name,'WhatsApp participant') AS "name!",- m.body,m.reply_to,m.source_at,m.ingested_at,m.revised_at,m.deleted_at,m.kind,m.rich,m.mentions,m.forwarded,+ m.body,m.reply_to,m.source_at,m.ingested_at,m.revised_at,m.deleted_at,m.kind,m.rich,m.mentions,m.forwarded,m.view_once,(SELECT state FROM whatsapp_send s WHERE s.message_id = m.id AND s.user_id = $2 ORDER BY s.created_at DESC LIMIT 1) AS deliveryFROM whatsapp_group_message m JOIN whatsapp_external_person p ON p.id = m.person_idWHERE m.binding_id = $1 AND m.message_id IS NOT NULL@@ -276,6 +279,7 @@ impl TimelineRepository for PgLinkedRepository {WhatsAppMessageKind::Message},forwarded: row.forwarded,+ view_once: row.view_once,mentions: if row.deleted_at.is_some() {vec![]} else {diff --git a/docs/agent-guide/external.md b/docs/agent-guide/external.mdindex c79870b104..9557f302c6 100644--- a/docs/agent-guide/external.md+++ b/docs/agent-guide/external.md@@ -19,7 +19,8 @@ it on locally with `VITE_ENABLE_WHATSAPP_LINKED=true`.## SidebarDesktop's External sidebar has **WhatsApp** (the page below) with every-WhatsApp group the viewer can read (their own and shared ones) nested under it,+WhatsApp chat the viewer can read (their own and shared ones; a person icon for+direct chats, a group icon for groups) nested under it,each with its unread count and a **Read-only** tag when the viewer's WhatsAppcan't send there. The caret on WhatsApp folds the groups; folded, WhatsApp showstheir total unread count. The open group's row is highlighted.@@ -33,7 +34,7 @@ re-fetches once ~3 s after opening.| Not linked | Outlined WhatsApp row, the unofficial-client account-risk note, **Connect** (disabled with a tooltip when the server turns pairing off). A signed-out device reads **Reconnect**. || Passkey | When WhatsApp asks for a passkey, the dialog says **Confirm on your desktop**. In Macro desktop, **Confirm with passkey** runs the native `whatsapp_passkey_authenticate` command (its caBLE QR shows in the dialog) and posts the assertion to `pairing/<id>/passkey`; a returned code then shows to type on the phone. In a browser, **Continue in Macro desktop** opens `macro:///external?whatsappPairing=<id>`, which reopens the same pairing there; closing the browser dialog then doesn't cancel it. || Pairing | Dialog **Link WhatsApp**: a locally encoded QR (`role="img"`, name "Scan this code with WhatsApp on your phone"), **Expires in m:ss**, four numbered steps, **Cancel**. The dialog carries `ph-no-capture`. A code confirmation step shows **The codes match**; expiry or failure shows **Show a new code**. |-| Linked | A full-width list like Drive's. Its header has **Search chats** (filters every section by name or phone digits) and a slim account strip: the phone number, "Connected" and a **WhatsApp account options** menu with **Disconnect** (asks to confirm). One account at a time: to switch, disconnect and connect again. Below, the account's WhatsApp chat list (`GET chats`), newest activity first, one line per chat: a group or person icon, the name, "Group" / "Direct chat · Archived", and the last activity on the right. Row actions show on hover or keyboard focus (always on touch). While searching, **In Macro** lists matching added groups with **Open** (otherwise they are only in the sidebar). **Add to Macro**: addable groups with a one-click **Add to Macro** (no dialog, no name: the Macro group follows the WhatsApp name; unnamed groups show member names), and groups someone already shared with the viewer as "Shared with you by <owner>" with **Open**. **Can't be added (n)** is collapsed (searching unfolds it) and lists direct chats ("Can't add direct chats yet"), community and disappearing-message groups, and groups the account left, with DSS's reason. A refused add shows DSS's specific reason in that chat's row. An account paired before the chat list existed shows only groups and chats with new messages until it is re-linked. |+| Linked | A full-width list like Drive's. Its header has **Search chats** (filters every section by name or phone digits) and a slim account strip: the phone number, "Connected" and a **WhatsApp account options** menu with **Disconnect** (asks to confirm). One account at a time: to switch, disconnect and connect again. Below, the account's WhatsApp chat list (`GET chats`), newest activity first, one line per chat: a group, person or (announcement group) megaphone icon, the name ("Community · Group", or "Community · Announcements"), "Group" / "Community group" / "Announcement group" / "Direct chat · Archived", and the last activity on the right. Row actions show on hover or keyboard focus (always on touch). While searching, **In Macro** lists matching added groups with **Open** (otherwise they are only in the sidebar). **Add to Macro**: addable chats (direct chats, community groups and disappearing-message groups included), with a one-click **Add to Macro** (no dialog, no name: the Macro group follows the WhatsApp name; unnamed groups show member names), and groups someone already shared with the viewer as "Shared with you by <owner>" with **Open**. **Can't be added (n)** is collapsed (searching unfolds it) and lists the chat with yourself, communities themselves ("A community has no messages of its own; add one of its groups"), and groups the account left, with DSS's reason. A refused add shows DSS's specific reason in that chat's row. An account paired before the chat list existed shows only groups and chats with new messages until it is re-linked. |Cancel sends `DELETE /meta/linked/pairing/<id>`; closing after the phone linksdoes not. Disconnect that WhatsApp did not confirm tells the person to remove@@ -49,23 +50,34 @@ answers `configuration`, `account`, `connect`, `pairing/<id>` (poll andto `success` to simulate the phone scanning. Never link a real account from anautomated run.-## Adopted group view+## Adopted chat view++A group and a direct (one-to-one) chat open in the same view; API routes and+the `whatsapp_group` entity type keep "group" for both, user-facing copy says+"chat". A direct chat's header is the person (no **N members** button, no+roster); only its owner can send, and anyone it's shared with reads "Only+<owner> can reply in this chat" in place of the composer.Open the adopted group from External's sidebar or a shared link at-`/app/external/whatsapp/:id`, in External's main pane. The retired-`/app/whatsapp-group/:id` links and saved `whatsapp-group:<id>` layouts redirect there.+`/app/external/whatsapp/:id`, in External's main pane.The group has its own timeline, data layer and entity sharing; it does not appearas a native channel. **Share** uses ordinary people grants, access requests,team sharing and link sharing for `whatsapp_group`. Viewers can read the wholetimeline without connecting WhatsApp or belonging to the remote group.-In a channel composer, `@` offers **WhatsApp groups** (behind the WhatsApp flag);-posting the mention shares the group with the channel's members (View), and the-chip opens the group in External.+In a channel composer, `@` offers **WhatsApp chats**: the viewer's own (behind+the WhatsApp flag); posting the mention shares the group with the channel's+members (View), and the chip opens the group in External. The owner sees those+channels in **Share** and can remove them.The timeline pages newest-first from`GET /meta/linked/whatsapp-groups/<id>/messages`, including verified sender names,replies, grouped reactions, edit/delete flags, attachment states, and deliveryfor the caller's own sends. Entering the view marks messages read through `/read`.+The timeline uses Chat's layout: rows and the composer share Chat's centered+message column (`macro-message-width`) and custom scrollbar, and the view+stays at the bottom while media loads unless the reader scrolled up. A sent+image shows its local preview at once and keeps it, sized, when the stored+message replaces the pending one.Ready images and videos show inline in Chat's media grid (click opens theviewer), sized from WhatsApp's declared width/height before they load so thetimeline opens at the bottom. Stickers show small and unframed, GIFs loop muted@@ -80,8 +92,11 @@ Maps**, no map tiles), contact cards and WhatsApp events render as small cards(`data-whatsapp-card="poll|location|contacts|event"`). Group changes, pins andcalls (`kind: "system"`) are one-line system rows like Chat's(`data-system-activity="<id>"`, e.g. "Ana added Ben", "Missed group video-call"): no avatar, no actions, never unread. View-once and unknown types keep-DSS's placeholder text. The header has the group name, a **N members** button that+call"): no avatar, no actions, never unread. View-once media show like any+media; unknown types keep DSS's placeholder text. The header has the group name ("Community · Group"+for a community's group), a timer icon when WhatsApp's disappearing messages+are on (the timeline's start also says "Disappearing messages are on in+WhatsApp (7 days). Macro keeps them."), a **N members** button thattoggles the WhatsApp roster, and **Share**. The layout supports phone-width panes.The composer placeholder names the caller's own sending phone ("Message Test 11diff --git a/docs/architecture/whatsapp-linked-devices.md b/docs/architecture/whatsapp-linked-devices.mdindex 916329740a..8cc1853a65 100644--- a/docs/architecture/whatsapp-linked-devices.md+++ b/docs/architecture/whatsapp-linked-devices.md@@ -64,6 +64,15 @@ at most once per 30 s. There is no periodic refresh and no freshness rule:adoption and can-send read the stored roster, and WhatsApp's own rejection ofa send is the final check.+Groups with disappearing messages are added like any other: Macro keeps their+messages permanently, the roster keeps WhatsApp's timer+(`GroupInfo.disappearing_seconds`, shown on the detail), and Macro's sends+carry it as `contextInfo.expiration` so members' phones expire them like their+own. A community's own entry (`community_parent`) has no messages and can't be+added; its groups and announcement group (`community_jid`, named on the chat+list and detail as `community`) are ordinary groups, the announcement group+under the usual admins-only posting rule.+Adoption (`{group_jid}`) makes the group the adopter's own entity: one live`whatsapp_group` per (owner, WhatsApp group), so two people adding the sameWhatsApp group get two Macro groups, and adding it again returns the existing@@ -82,7 +91,22 @@ it (initial, recent and full bundles; push-name bundles rename direct chats);live messages in any chat bump activity and add new chats; contact, push-name,archive and pin updates change existing rows. It never holds message content.`GET /chats` merges it with the roster (the roster names groups and decides-what can be added; direct chats are listed but not addable yet), newest first.+which groups can be added), newest first.++Direct chats are added like groups (`whatsapp_group.kind = 'direct'`, keyed on+the other person's JID, by phone number when known) and named after the+person as the chat list names them. The owner's account is the only member: it+observes the chat from adoption on (renewed on every full roster refresh), and+only the owner sends; people it is shared with read. Someone else's chat with+the same person is their own conversation, never "shared with you". WhatsApp+addresses a direct chat by LID or phone number: each message carries the+chat's other address (`InboundEvent.chat_alternate_jid`, from the message or+the LID store) and the session gate files it under whichever the chat was+added by; history is requested in the chat as the phone keys it (by LID).+Internal names stay `group` (table, columns, entity type `whatsapp_group`,+API types such as `WhatsAppGroupDetail`): renaming them across GraphQL,+notifications and sharing enums would churn deployed contracts; `kind` tells+them apart.An account paired before the list existed only gets groups and chats with newmessages: WhatsApp sends the full list once, at pairing.@@ -145,8 +169,8 @@ stable synthetic source id), group icon changes, pins, call logs and the stubmessages of history pages (including group creation). They never notify andnever count as unread. The timeline resolves the ids in mentions, system linesand votes to names (people seen in the group, then the roster, then the phone-number). View-once media and shapes Macro does not read stay readable-placeholders. Attachments keep WhatsApp's declared width, height and length,+number). View-once media is kept and shown like any media (marked+`view_once`); shapes Macro does not read stay readable placeholders. Attachments keep WhatsApp's declared width, height and length,and whether WhatsApp shows them as a sticker, GIF or voice note.`GET /meta/linked/whatsapp-groups` lists shared groups with viewer-specific unread@@ -200,6 +224,9 @@ bytes are never rewritten. Failures retry with backoff and then expose anOutbound: the attachments route stages one file per send in the blob table;`ReplyContent::Media` names it, the replica fetches it with `outbound_media`,and on acceptance it becomes the message's document, owned by the sender.+Staging reads the file's pixel size and length from its headers+(`domain::shape`: image headers, MP4 `tkhd`/`mvhd`, Ogg/Opus granule); the+sent WhatsApp message and the stored attachment carry them like received ones.A text send may @-mention participants (`ReplyContent::Text.mentions`, theirWhatsApp ids; the text names each as `@<digits>`); the replica sends them asthe message's `mentionedJid`.diff --git a/packages/code-mode-sdk/scripts/catalog.ts b/packages/code-mode-sdk/scripts/catalog.tsindex 86d8740e9c..7ba096d9c4 100644--- a/packages/code-mode-sdk/scripts/catalog.ts+++ b/packages/code-mode-sdk/scripts/catalog.ts@@ -18,7 +18,7 @@ export const descriptions: Record<string, string> = {calendar: 'Find and manage calendar events.',calls: 'Read and edit call records, transcripts and meeting links.',channels:- 'Read and send channel messages; read and share standalone WhatsApp groups, discover remote groups, and send from the credential owner’s own member account with media and delivery. Pairing stays in the app.',+ "Read and send channel messages; list the WhatsApp chat list (groups and direct chats), add chats to Macro, read and share added chats, and send from the credential owner's own account with mentions, media and delivery. Pairing stays in the app.",crm: 'Work with CRM records and pipeline tables, columns, rows and sharing.',databases: 'Read and edit database schemas, rows, and cells.',documents: 'Search, read, create, and manage documents and tasks.',diff --git a/packages/sdk-docs/reference/generated/storage/types.gen/README.md b/packages/sdk-docs/reference/generated/storage/types.gen/README.mdindex 533f972410..274dbaa5af 100644--- a/packages/sdk-docs/reference/generated/storage/types.gen/README.md+++ b/packages/sdk-docs/reference/generated/storage/types.gen/README.md@@ -1350,6 +1350,7 @@- [LinkedCancelPairingData](type-aliases/LinkedCancelPairingData.md)- [LinkedCancelPairingResponse](type-aliases/LinkedCancelPairingResponse.md)- [LinkedCancelPairingResponses](type-aliases/LinkedCancelPairingResponses.md)+- [LinkedCannotAdd](type-aliases/LinkedCannotAdd.md)- [LinkedCapabilities](type-aliases/LinkedCapabilities.md)- [LinkedChat](type-aliases/LinkedChat.md)- [LinkedChatKind](type-aliases/LinkedChatKind.md)@@ -1357,6 +1358,7 @@- [LinkedChatsData](type-aliases/LinkedChatsData.md)- [LinkedChatsResponse](type-aliases/LinkedChatsResponse.md)- [LinkedChatsResponses](type-aliases/LinkedChatsResponses.md)+- [LinkedCommunityReference](type-aliases/LinkedCommunityReference.md)- [LinkedConfigurationData](type-aliases/LinkedConfigurationData.md)- [LinkedConfigurationResponse](type-aliases/LinkedConfigurationResponse.md)- [LinkedConfigurationResponses](type-aliases/LinkedConfigurationResponses.md)@@ -1379,9 +1381,6 @@- [LinkedFeatures](type-aliases/LinkedFeatures.md)- [LinkedGroupInfo](type-aliases/LinkedGroupInfo.md)- [LinkedGroupReference](type-aliases/LinkedGroupReference.md)-- [LinkedGroupsData](type-aliases/LinkedGroupsData.md)-- [LinkedGroupsResponse](type-aliases/LinkedGroupsResponse.md)-- [LinkedGroupsResponses](type-aliases/LinkedGroupsResponses.md)- [LinkedIdentity](type-aliases/LinkedIdentity.md)- [LinkedMediaKind](type-aliases/LinkedMediaKind.md)- [LinkedMediaPresentation](type-aliases/LinkedMediaPresentation.md)diff --git a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedAdoptGroup.md b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedAdoptGroup.mdindex 382c6faaea..e857850838 100644--- a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedAdoptGroup.md+++ b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedAdoptGroup.md@@ -9,4 +9,4 @@ group's name always follows WhatsApp.| Property | Type | Description || ------ | ------ | ------ |-| <a id="property-group_jid"></a> `group_jid` | `string` | Group the requester's account has joined. |+| <a id="property-group_jid"></a> `group_jid` | `string` | A group the requester's account has joined, or a direct chat from their chat list (the other person's JID, as the list names it). |diff --git a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedCannotAdd.md b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedCannotAdd.mdnew file mode 100644index 0000000000..788b0ca95c--- /dev/null+++ b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedCannotAdd.md@@ -0,0 +1,5 @@+# Type Alias: LinkedCannotAdd++> **LinkedCannotAdd** = `"not_in_group"` \| `"community"` \| `"own_chat"` \| `"not_in_chat_list"`++Why a chat can't be added to Macro; the app words it from the code.diff --git a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedChat.md b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedChat.mdindex 11b66c7751..3fed6e353b 100644--- a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedChat.md+++ b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedChat.md@@ -1,6 +1,6 @@# Type Alias: LinkedChat-> **LinkedChat** = \{ `archived`: `boolean`; `canAdd`: `boolean`; `cannotAddReason?`: `string` \| `null`; `group?`: `null` \| [`LinkedGroupReference`](LinkedGroupReference.md); `jid`: `string`; `kind`: [`LinkedChatKind`](LinkedChatKind.md); `lastActivityAt?`: `string` \| `null`; `name`: `string`; `pinned`: `boolean`; `shared?`: `null` \| [`LinkedSharedGroupReference`](LinkedSharedGroupReference.md); \}+> **LinkedChat** = \{ `archived`: `boolean`; `canAdd`: `boolean`; `cannotAddReason?`: `null` \| [`LinkedCannotAdd`](LinkedCannotAdd.md); `community?`: `null` \| [`LinkedCommunityReference`](LinkedCommunityReference.md); `group?`: `null` \| [`LinkedGroupReference`](LinkedGroupReference.md); `jid`: `string`; `kind`: [`LinkedChatKind`](LinkedChatKind.md); `lastActivityAt?`: `string` \| `null`; `name`: `string`; `pinned`: `boolean`; `shared?`: `null` \| [`LinkedSharedGroupReference`](LinkedSharedGroupReference.md); \}One chat of the caller's WhatsApp chat list, as WhatsApp Web lists it.@@ -10,7 +10,8 @@ One chat of the caller's WhatsApp chat list, as WhatsApp Web lists it.| ------ | ------ | ------ || <a id="property-archived"></a> `archived` | `boolean` | Archived in WhatsApp. || <a id="property-canadd"></a> `canAdd` | `boolean` | "Add to Macro" works now. |-| <a id="property-cannotaddreason"></a> `cannotAddReason?` | `string` \| `null` | Why it can't be added, when it is neither added, shared nor addable. |+| <a id="property-cannotaddreason"></a> `cannotAddReason?` | `null` \| [`LinkedCannotAdd`](LinkedCannotAdd.md) | - |+| <a id="property-community"></a> `community?` | `null` \| [`LinkedCommunityReference`](LinkedCommunityReference.md) | - || <a id="property-group"></a> `group?` | `null` \| [`LinkedGroupReference`](LinkedGroupReference.md) | - || <a id="property-jid"></a> `jid` | `string` | WhatsApp chat JID: a group, or the other person's phone-number JID (LID when WhatsApp never told us the number). || <a id="property-kind"></a> `kind` | [`LinkedChatKind`](LinkedChatKind.md) | Group or direct chat. |diff --git a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedCommunityReference.md b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedCommunityReference.mdnew file mode 100644index 0000000000..2266c6f841--- /dev/null+++ b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedCommunityReference.md@@ -0,0 +1,13 @@+# Type Alias: LinkedCommunityReference++> **LinkedCommunityReference** = \{ `announcements`: `boolean`; `id`: `string`; `name`: `string`; \}++The WhatsApp community a group belongs to.++## Properties++| Property | Type | Description |+| ------ | ------ | ------ |+| <a id="property-announcements"></a> `announcements` | `boolean` | This group is the community's announcement group. |+| <a id="property-id"></a> `id` | `string` | The community's WhatsApp JID. |+| <a id="property-name"></a> `name` | `string` | The community's name. |diff --git a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedGroupInfo.md b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedGroupInfo.mdindex cebe5d9b43..cad885c773 100644--- a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedGroupInfo.md+++ b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedGroupInfo.md@@ -1,6 +1,6 @@# Type Alias: LinkedGroupInfo-> **LinkedGroupInfo** = \{ `announce`: `boolean`; `community`: `boolean`; `disappearing`: `boolean`; `group?`: `null` \| [`LinkedGroupReference`](LinkedGroupReference.md); `jid`: `string`; `name`: `string`; `observedAt`: `string`; `participants`: [`LinkedParticipant`](LinkedParticipant.md)[]; `shared?`: `null` \| [`LinkedSharedGroupReference`](LinkedSharedGroupReference.md); \}+> **LinkedGroupInfo** = \{ `announce`: `boolean`; `communityAnnouncements?`: `boolean`; `communityJid?`: `string` \| `null`; `communityParent?`: `boolean`; `disappearingSeconds?`: `number` \| `null`; `jid`: `string`; `name`: `string`; `observedAt`: `string`; `participants`: [`LinkedParticipant`](LinkedParticipant.md)[]; \}One full metadata read of a group, never an incomplete membership delta.@@ -9,11 +9,11 @@ One full metadata read of a group, never an incomplete membership delta.| Property | Type | Description || ------ | ------ | ------ || <a id="property-announce"></a> `announce` | `boolean` | Only admins may post. |-| <a id="property-community"></a> `community` | `boolean` | Community announcement or parent group, outside the supported surface. |-| <a id="property-disappearing"></a> `disappearing` | `boolean` | Disappearing messages are on; content is not retained. |-| <a id="property-group"></a> `group?` | `null` \| [`LinkedGroupReference`](LinkedGroupReference.md) | - |+| <a id="property-communityannouncements"></a> `communityAnnouncements?` | `boolean` | The community's announcement group (everyone reads, admins post). |+| <a id="property-communityjid"></a> `communityJid?` | `string` \| `null` | The community a linked subgroup or announcement group belongs to. |+| <a id="property-communityparent"></a> `communityParent?` | `boolean` | The community itself: it has no messages of its own and can't be added. |+| <a id="property-disappearingseconds"></a> `disappearingSeconds?` | `number` \| `null` | Disappearing-messages timer in seconds while it is on. Macro keeps the messages; its sends carry the timer so phones treat them like their own. || <a id="property-jid"></a> `jid` | `string` | Remote group JID. || <a id="property-name"></a> `name` | `string` | Current subject. || <a id="property-observedat"></a> `observedAt` | `string` | When the session service read this metadata. || <a id="property-participants"></a> `participants` | [`LinkedParticipant`](LinkedParticipant.md)[] | Full roster. |-| <a id="property-shared"></a> `shared?` | `null` \| [`LinkedSharedGroupReference`](LinkedSharedGroupReference.md) | - |diff --git a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedGroupsData.md b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedGroupsData.mddeleted file mode 100644index 77546ed812..0000000000--- a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedGroupsData.md+++ /dev/null@@ -1,12 +0,0 @@-# Type Alias: LinkedGroupsData--> **LinkedGroupsData** = \{ `body?`: `never`; `path?`: `never`; `query?`: `never`; `url`: `"/meta/linked/groups"`; \}--## Properties--| Property | Type |-| ------ | ------ |-| <a id="property-body"></a> `body?` | `never` |-| <a id="property-path"></a> `path?` | `never` |-| <a id="property-query"></a> `query?` | `never` |-| <a id="property-url"></a> `url` | `"/meta/linked/groups"` |diff --git a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedGroupsResponse.md b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedGroupsResponse.mddeleted file mode 100644index 346744a72b..0000000000--- a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedGroupsResponse.md+++ /dev/null@@ -1,3 +0,0 @@-# Type Alias: LinkedGroupsResponse--> **LinkedGroupsResponse** = [`LinkedGroupsResponses`](LinkedGroupsResponses.md)\[keyof [`LinkedGroupsResponses`](LinkedGroupsResponses.md)\]diff --git a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedGroupsResponses.md b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedGroupsResponses.mddeleted file mode 100644index 8af54b29d6..0000000000--- a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedGroupsResponses.md+++ /dev/null@@ -1,9 +0,0 @@-# Type Alias: LinkedGroupsResponses--> **LinkedGroupsResponses** = \{ `200`: [`LinkedGroupInfo`](LinkedGroupInfo.md)[]; \}--## Properties--| Property | Type |-| ------ | ------ |-| <a id="property-200"></a> `200` | [`LinkedGroupInfo`](LinkedGroupInfo.md)[] |diff --git a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedSharedGroupReference.md b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedSharedGroupReference.mdindex 24077c9fa1..d0cf7f2383 100644--- a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedSharedGroupReference.md+++ b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedSharedGroupReference.md@@ -1,6 +1,6 @@# Type Alias: LinkedSharedGroupReference-> **LinkedSharedGroupReference** = \{ `id`: `string`; `name`: `string`; `owner_id`: `string`; \}+> **LinkedSharedGroupReference** = \{ `id`: `string`; `name`: `string`; `ownerId`: `string`; \}Another person's group entity the caller can view.@@ -10,4 +10,4 @@ Another person's group entity the caller can view.| ------ | ------ | ------ || <a id="property-id"></a> `id` | `string` | Group entity id. || <a id="property-name"></a> `name` | `string` | Display name, following WhatsApp. |-| <a id="property-owner_id"></a> `owner_id` | `string` | Macro user who added the group and shared it. |+| <a id="property-ownerid"></a> `ownerId` | `string` | Macro user who added the group and shared it. |diff --git a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/WhatsAppGroupDetail.md b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/WhatsAppGroupDetail.mdindex d38347bdb4..f45bb0a8b3 100644--- a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/WhatsAppGroupDetail.md+++ b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/WhatsAppGroupDetail.md@@ -1,6 +1,6 @@# Type Alias: WhatsAppGroupDetail-> **WhatsAppGroupDetail** = [`WhatsAppGroupSummary`](WhatsAppGroupSummary.md) & \{ `access_level`: [`AccessLevel`](AccessLevel.md); `limits`: [`LinkedCapabilities`](LinkedCapabilities.md); `roster?`: `null` \| [`LinkedGroupInfo`](LinkedGroupInfo.md); `sending_identity?`: `string` \| `null`; `share_permission`: [`SharePermissionV2`](SharePermissionV2.md); \}+> **WhatsAppGroupDetail** = [`WhatsAppGroupSummary`](WhatsAppGroupSummary.md) & \{ `access_level`: [`AccessLevel`](AccessLevel.md); `community?`: `null` \| [`LinkedCommunityReference`](LinkedCommunityReference.md); `disappearing_seconds?`: `number` \| `null`; `limits`: [`LinkedCapabilities`](LinkedCapabilities.md); `roster?`: `null` \| [`LinkedGroupInfo`](LinkedGroupInfo.md); `sending_identity?`: `string` \| `null`; `share_permission`: [`SharePermissionV2`](SharePermissionV2.md); \}Full group detail and current viewer capabilities.@@ -9,6 +9,8 @@ Full group detail and current viewer capabilities.| Name | Type | Description || ------ | ------ | ------ || `access_level` | [`AccessLevel`](AccessLevel.md) | Caller's effective permission. |+| `community?` | `null` \| [`LinkedCommunityReference`](LinkedCommunityReference.md) | - |+| `disappearing_seconds?` | `number` \| `null` | WhatsApp's disappearing-messages timer in seconds while it is on; Macro keeps the messages anyway. `null` when off or unknown. || `limits` | [`LinkedCapabilities`](LinkedCapabilities.md) | Size and mutation limits. || `roster?` | `null` \| [`LinkedGroupInfo`](LinkedGroupInfo.md) | - || `sending_identity?` | `string` \| `null` | Caller's own phone identity, never another account's identity. |diff --git a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/WhatsAppGroupMessage.md b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/WhatsAppGroupMessage.mdindex 7e4e9c6dfd..ae25dd48c3 100644--- a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/WhatsAppGroupMessage.md+++ b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/WhatsAppGroupMessage.md@@ -1,6 +1,6 @@# Type Alias: WhatsAppGroupMessage-> **WhatsAppGroupMessage** = \{ `attachments`: [`LinkedAttachment`](LinkedAttachment.md)[]; `body`: `string`; `deleted`: `boolean`; `delivery_state?`: `null` \| [`LinkedDeliveryState`](LinkedDeliveryState.md); `edited_at?`: `string` \| `null`; `forwarded`: `boolean`; `id`: `string`; `kind`: [`WhatsAppMessageKind`](WhatsAppMessageKind.md); `mentions`: [`WhatsAppMention`](WhatsAppMention.md)[]; `reactions`: [`WhatsAppGroupReaction`](WhatsAppGroupReaction.md)[]; `received_at`: `string`; `reply_to?`: `string` \| `null`; `rich?`: `null` \| [`WhatsAppRichContent`](WhatsAppRichContent.md); `sender`: [`WhatsAppGroupSender`](WhatsAppGroupSender.md); `sent_at`: `string`; \}+> **WhatsAppGroupMessage** = \{ `attachments`: [`LinkedAttachment`](LinkedAttachment.md)[]; `body`: `string`; `deleted`: `boolean`; `delivery_state?`: `null` \| [`LinkedDeliveryState`](LinkedDeliveryState.md); `edited_at?`: `string` \| `null`; `forwarded`: `boolean`; `id`: `string`; `kind`: [`WhatsAppMessageKind`](WhatsAppMessageKind.md); `mentions`: [`WhatsAppMention`](WhatsAppMention.md)[]; `reactions`: [`WhatsAppGroupReaction`](WhatsAppGroupReaction.md)[]; `received_at`: `string`; `reply_to?`: `string` \| `null`; `rich?`: `null` \| [`WhatsAppRichContent`](WhatsAppRichContent.md); `sender`: [`WhatsAppGroupSender`](WhatsAppGroupSender.md); `sent_at`: `string`; `view_once`: `boolean`; \}One message in an adopted group.@@ -23,3 +23,4 @@ One message in an adopted group.| <a id="property-rich"></a> `rich?` | `null` \| [`WhatsAppRichContent`](WhatsAppRichContent.md) | - || <a id="property-sender"></a> `sender` | [`WhatsAppGroupSender`](WhatsAppGroupSender.md) | Sender. || <a id="property-sent_at"></a> `sent_at` | `string` | Timestamp assigned by WhatsApp. |+| <a id="property-view_once"></a> `view_once` | `boolean` | Sent as view-once in WhatsApp; Macro shows it like any media. |diff --git a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/WhatsAppGroupSummary.md b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/WhatsAppGroupSummary.mdindex bef52a5dc5..6b46e28551 100644--- a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/WhatsAppGroupSummary.md+++ b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/WhatsAppGroupSummary.md@@ -1,6 +1,6 @@# Type Alias: WhatsAppGroupSummary-> **WhatsAppGroupSummary** = \{ `backfill?`: `null` \| [`LinkedBackfill`](LinkedBackfill.md); `can_send`: `boolean`; `id`: `string`; `last_message_at?`: `string` \| `null`; `name`: `string`; `send_reason?`: `null` \| [`LinkedReplyBlock`](LinkedReplyBlock.md); `unread_count`: `number`; `user_id`: `string`; \}+> **WhatsAppGroupSummary** = \{ `backfill?`: `null` \| [`LinkedBackfill`](LinkedBackfill.md); `can_send`: `boolean`; `id`: `string`; `kind`: [`LinkedChatKind`](LinkedChatKind.md); `last_message_at?`: `string` \| `null`; `name`: `string`; `send_reason?`: `null` \| [`LinkedReplyBlock`](LinkedReplyBlock.md); `unread_count`: `number`; `user_id`: `string`; \}Adopted group visible through ordinary entity sharing.@@ -11,8 +11,9 @@ Adopted group visible through ordinary entity sharing.| <a id="property-backfill"></a> `backfill?` | `null` \| [`LinkedBackfill`](LinkedBackfill.md) | - || <a id="property-can_send"></a> `can_send` | `boolean` | Caller may currently send from their own account. || <a id="property-id"></a> `id` | `string` | Entity identifier. |+| <a id="property-kind"></a> `kind` | [`LinkedChatKind`](LinkedChatKind.md) | A group, or a direct chat with one person (only its owner sends). || <a id="property-last_message_at"></a> `last_message_at?` | `string` \| `null` | Latest message timestamp. |-| <a id="property-name"></a> `name` | `string` | Display name. |+| <a id="property-name"></a> `name` | `string` | Display name: the group's, or a direct chat's other person. || <a id="property-send_reason"></a> `send_reason?` | `null` \| [`LinkedReplyBlock`](LinkedReplyBlock.md) | - || <a id="property-unread_count"></a> `unread_count` | `number` | Unread live messages for this viewer. || <a id="property-user_id"></a> `user_id` | `string` | Actual entity owner. |diff --git a/packages/sdk-docs/reference/modules.md b/packages/sdk-docs/reference/modules.mdindex c37bed2d65..6e1abddcee 100644--- a/packages/sdk-docs/reference/modules.md+++ b/packages/sdk-docs/reference/modules.md@@ -126,6 +126,7 @@- [src/entities/whatsapp/group](src/entities/whatsapp/group/README.md)- [src/entities/whatsapp/message](src/entities/whatsapp/message/README.md)- [src/entities/whatsapp/namespace](src/entities/whatsapp/namespace/README.md)+- [src/entities/whatsapp/participant](src/entities/whatsapp/participant/README.md)- [src/entities/whatsapp/send](src/entities/whatsapp/send/README.md)- [src/entities/whatsapp/upload](src/entities/whatsapp/upload/README.md)- [src/entities/workspace/items](src/entities/workspace/items/README.md)diff --git a/packages/sdk-docs/reference/src/entities/whatsapp/chat/README.md b/packages/sdk-docs/reference/src/entities/whatsapp/chat/README.mdindex 1c3abbc4fe..4e57a300b5 100644--- a/packages/sdk-docs/reference/src/entities/whatsapp/chat/README.md+++ b/packages/sdk-docs/reference/src/entities/whatsapp/chat/README.md@@ -3,3 +3,11 @@## Classes- [WhatsAppChat](classes/WhatsAppChat.md)++## Type Aliases++- [WhatsAppCommunity](type-aliases/WhatsAppCommunity.md)++## Functions++- [communityOf](functions/communityOf.md)diff --git a/packages/sdk-docs/reference/src/entities/whatsapp/chat/classes/WhatsAppChat.md b/packages/sdk-docs/reference/src/entities/whatsapp/chat/classes/WhatsAppChat.mdindex b096f96780..a1da431e17 100644--- a/packages/sdk-docs/reference/src/entities/whatsapp/chat/classes/WhatsAppChat.md+++ b/packages/sdk-docs/reference/src/entities/whatsapp/chat/classes/WhatsAppChat.md@@ -12,7 +12,8 @@ One chat of the current user's WhatsApp chat list: a group or a direct chat.| ------ | ------ | ------ | ------ | ------ || <a id="property-archived"></a> `archived` | `readonly` | () => `Promise`\<`boolean`\> | Archived in WhatsApp. | - || <a id="property-canadd"></a> `canAdd` | `readonly` | () => `Promise`\<`boolean`\> | Whether adding it to Macro works now. | - |-| <a id="property-cannotaddreason"></a> `cannotAddReason` | `readonly` | () => `Promise`\<`string` \| `undefined`\> | Why it can't be added, when it is neither added, shared nor addable. | - |+| <a id="property-cannotaddreason"></a> `cannotAddReason` | `readonly` | () => `Promise`\<`NonNullable`\<LinkedCannotAdd \| null \| undefined\> \| `undefined`\> | Why it can't be added (`not_in_group`, `community`, `own_chat`, `not_in_chat_list`), when it is neither added, shared nor addable. | - |+| <a id="property-community"></a> `community` | `readonly` | () => `Promise`\<[`WhatsAppCommunity`](../type-aliases/WhatsAppCommunity.md) \| `undefined`\> | The WhatsApp community a group belongs to, if any: the community's own chat, its name, and whether this is its announcement group. | - || <a id="property-group"></a> `group` | `readonly` | () => `Promise`\<[`WhatsAppGroup`](../../group/classes/WhatsAppGroup.md) \| `undefined`\> | The current user's own Macro group for this chat, once added. | - || <a id="property-id"></a> `id` | `public readonly` | `string` | - | [`MacroEntity`](../../../entity/classes/MacroEntity.md).[`id`](../../../entity/classes/MacroEntity.md#property-id) || <a id="property-kind"></a> `kind` | `readonly` | () => `Promise`\<[`LinkedChatKind`](../../../../../generated/storage/types.gen/type-aliases/LinkedChatKind.md)\> | `group` or `direct`. | - |@@ -27,9 +28,9 @@ One chat of the current user's WhatsApp chat list: a group or a direct chat.> **adopt**(): `Promise`\<[`WhatsAppGroup`](../../group/classes/WhatsAppGroup.md)\>-Add a group chat to Macro as the current user's own group; its earlier-messages are imported from the phone. Adding it again returns the same-group. Direct chats can't be added yet.+Add the chat (a group or a direct chat) to Macro as the current user's+own; its earlier messages are imported from the phone. Adding it again+returns the same chat. Only the owner sends in a direct chat.#### Returnsdiff --git a/packages/sdk-docs/reference/src/entities/whatsapp/chat/functions/communityOf.md b/packages/sdk-docs/reference/src/entities/whatsapp/chat/functions/communityOf.mdnew file mode 100644index 0000000000..27c587c79e--- /dev/null+++ b/packages/sdk-docs/reference/src/entities/whatsapp/chat/functions/communityOf.md@@ -0,0 +1,16 @@+# Function: communityOf()++> **communityOf**(`client`, `record`): [`WhatsAppCommunity`](../type-aliases/WhatsAppCommunity.md)++A community reference as a handle on the community's own chat.++## Parameters++| Parameter | Type |+| ------ | ------ |+| `client` | `MacroClient` |+| `record` | [`LinkedCommunityReference`](../../../../../generated/storage/types.gen/type-aliases/LinkedCommunityReference.md) |++## Returns++[`WhatsAppCommunity`](../type-aliases/WhatsAppCommunity.md)diff --git a/packages/sdk-docs/reference/src/entities/whatsapp/chat/type-aliases/WhatsAppCommunity.md b/packages/sdk-docs/reference/src/entities/whatsapp/chat/type-aliases/WhatsAppCommunity.mdnew file mode 100644index 0000000000..6a90b22060--- /dev/null+++ b/packages/sdk-docs/reference/src/entities/whatsapp/chat/type-aliases/WhatsAppCommunity.md@@ -0,0 +1,13 @@+# Type Alias: WhatsAppCommunity++> **WhatsAppCommunity** = \{ `announcements`: `boolean`; `chat`: [`WhatsAppChat`](../classes/WhatsAppChat.md); `name`: `string`; \}++The WhatsApp community a group belongs to.++## Properties++| Property | Type | Description |+| ------ | ------ | ------ |+| <a id="property-announcements"></a> `announcements` | `boolean` | This group is the community's announcement group. |+| <a id="property-chat"></a> `chat` | [`WhatsAppChat`](../classes/WhatsAppChat.md) | The community itself, as a chat of the list (it can't be added). |+| <a id="property-name"></a> `name` | `string` | The community's name. |diff --git a/packages/sdk-docs/reference/src/entities/whatsapp/group/classes/WhatsAppGroup.md b/packages/sdk-docs/reference/src/entities/whatsapp/group/classes/WhatsAppGroup.mdindex c552655c91..e02aafc517 100644--- a/packages/sdk-docs/reference/src/entities/whatsapp/group/classes/WhatsAppGroup.md+++ b/packages/sdk-docs/reference/src/entities/whatsapp/group/classes/WhatsAppGroup.md@@ -1,6 +1,6 @@# Class: WhatsAppGroup-Independently shareable adopted WhatsApp group entity.+Independently shareable added WhatsApp chat: a group or a direct chat.## Extends@@ -12,12 +12,16 @@ Independently shareable adopted WhatsApp group entity.| ------ | ------ | ------ | ------ | ------ | ------ || <a id="property-backfill"></a> `backfill` | `readonly` | () => `Promise`\<[`LinkedBackfill`](../../../../../generated/storage/types.gen/type-aliases/LinkedBackfill.md) \| `undefined`\> | Importing earlier messages from the owner's phone after adding, if any. | - | - || <a id="property-cansend"></a> `canSend` | `readonly` | () => `Promise`\<`boolean`\> | Whether the caller can send from their own connected account. | - | - |+| <a id="property-community"></a> `community` | `readonly` | () => `Promise`\<[`WhatsAppCommunity`](../../chat/type-aliases/WhatsAppCommunity.md) \| `undefined`\> | The WhatsApp community this group belongs to, if any: the community's own chat, its name, and whether this is its announcement group. | - | - |+| <a id="property-disappearingseconds"></a> `disappearingSeconds` | `readonly` | () => `Promise`\<`number` \| `undefined`\> | WhatsApp's disappearing-messages timer in seconds while on; Macro keeps the messages. | - | - || <a id="property-entitytype"></a> `entityType` | `readonly` | `"whatsapp_group"` | Canonical sharing and favorites kind. | [`FavoritableEntity`](../../../entity/classes/FavoritableEntity.md).[`entityType`](../../../entity/classes/FavoritableEntity.md#property-entitytype) | - || <a id="property-id"></a> `id` | `public readonly` | `string` | - | - | [`FavoritableEntity`](../../../entity/classes/FavoritableEntity.md).[`id`](../../../entity/classes/FavoritableEntity.md#property-id) |+| <a id="property-kind"></a> `kind` | `readonly` | () => `Promise`\<[`LinkedChatKind`](../../../../../generated/storage/types.gen/type-aliases/LinkedChatKind.md)\> | `group`, or `direct` for a one-to-one chat (only its owner sends). | - | - || <a id="property-limits"></a> `limits` | `readonly` | () => `Promise`\<[`LinkedCapabilities`](../../../../../generated/storage/types.gen/type-aliases/LinkedCapabilities.md)\> | Supported sizes and mutation window. | - | - |-| <a id="property-name"></a> `name` | `readonly` | () => `Promise`\<`string`\> | Display name. | - | - |+| <a id="property-name"></a> `name` | `readonly` | () => `Promise`\<`string`\> | Display name: the group's, or a direct chat's other person. | - | - || <a id="property-owner"></a> `owner` | `readonly` | () => `Promise`\<[`User`](../../../users/user/classes/User.md)\> | Actual owner, independent of WhatsApp membership. | - | - |-| <a id="property-roster"></a> `roster` | `readonly` | () => `Promise`\<[`LinkedGroupInfo`](../../../../../generated/storage/types.gen/type-aliases/LinkedGroupInfo.md) \| `undefined`\> | Current remote roster, when available. | - | - |+| <a id="property-participants"></a> `participants` | `readonly` | () => `Promise`\<[`WhatsAppParticipant`](../../participant/classes/WhatsAppParticipant.md)[]\> | Everyone in the chat, from its roster; empty when no roster is known. | - | - |+| <a id="property-roster"></a> `roster` | `readonly` | () => `Promise`\<[`LinkedGroupInfo`](../../../../../generated/storage/types.gen/type-aliases/LinkedGroupInfo.md) \| `undefined`\> | Current remote roster (name, participants, announce), when available. | - | - || <a id="property-sendingidentity"></a> `sendingIdentity` | `readonly` | () => `Promise`\<`string` \| `undefined`\> | Caller's own verified sending identity. | - | - || <a id="property-sendreason"></a> `sendReason` | `readonly` | () => `Promise`\<`NonNullable`\<LinkedReplyBlock \| null \| undefined\> \| `undefined`\> | Reason sending is blocked. | - | - || <a id="property-unreadcount"></a> `unreadCount` | `readonly` | () => `Promise`\<`number`\> | Per-user unread count. | - | - |diff --git a/packages/sdk-docs/reference/src/entities/whatsapp/group/type-aliases/WhatsAppReply.md b/packages/sdk-docs/reference/src/entities/whatsapp/group/type-aliases/WhatsAppReply.mdindex 51beda92d8..4e6f113152 100644--- a/packages/sdk-docs/reference/src/entities/whatsapp/group/type-aliases/WhatsAppReply.md+++ b/packages/sdk-docs/reference/src/entities/whatsapp/group/type-aliases/WhatsAppReply.md@@ -1,6 +1,6 @@# Type Alias: WhatsAppReply-> **WhatsAppReply** = \{ `mentions?`: `string`[]; `text`: `string`; `type`: `"text"`; \} \| \{ `caption?`: `string`; `type`: `"media"`; `upload`: [`WhatsAppUpload`](../../upload/classes/WhatsAppUpload.md); \} \| \{ `message`: [`WhatsAppMessage`](../../message/classes/WhatsAppMessage.md); `operation`: `"reaction"` \| `"edit"` \| `"delete"`; `text?`: `string`; `type`: `"mutation"`; \}+> **WhatsAppReply** = \{ `mentions?`: [`WhatsAppParticipant`](../../participant/classes/WhatsAppParticipant.md)[]; `text`: `string`; `type`: `"text"`; \} \| \{ `caption?`: `string`; `type`: `"media"`; `upload`: [`WhatsAppUpload`](../../upload/classes/WhatsAppUpload.md); \} \| \{ `message`: [`WhatsAppMessage`](../../message/classes/WhatsAppMessage.md); `operation`: `"reaction"` \| `"edit"` \| `"delete"`; `text?`: `string`; `type`: `"mutation"`; \}Deliberate content from the credential owner's own WhatsApp account.@@ -8,11 +8,11 @@ Deliberate content from the credential owner's own WhatsApp account.### Type Literal-\{ `mentions?`: `string`[]; `text`: `string`; `type`: `"text"`; \}+\{ `mentions?`: [`WhatsAppParticipant`](../../participant/classes/WhatsAppParticipant.md)[]; `text`: `string`; `type`: `"text"`; \}| Name | Type | Description || ------ | ------ | ------ |-| `mentions?` | `string`[] | WhatsApp ids of mentioned participants (`roster.participants[].jid`); the text names each as `@<digits>`. |+| `mentions?` | [`WhatsAppParticipant`](../../participant/classes/WhatsAppParticipant.md)[] | Participants mentioned (from `participants()`); the text names each as `@<mentionToken>`. || `text` | `string` | - || `type` | `"text"` | - |diff --git a/packages/sdk-docs/reference/src/entities/whatsapp/message/classes/WhatsAppMessage.md b/packages/sdk-docs/reference/src/entities/whatsapp/message/classes/WhatsAppMessage.mdindex 5539192bd5..3334d707a8 100644--- a/packages/sdk-docs/reference/src/entities/whatsapp/message/classes/WhatsAppMessage.md+++ b/packages/sdk-docs/reference/src/entities/whatsapp/message/classes/WhatsAppMessage.md@@ -16,6 +16,7 @@ Message in an independently shared WhatsApp group.| <a id="property-deliverystate"></a> `deliveryState` | `readonly` | () => `Promise`\<`NonNullable`\<LinkedDeliveryState \| null \| undefined\> \| `undefined`\> | Caller-owned send's delivery state, when present. | - || <a id="property-editedat"></a> `editedAt` | `readonly` | () => `Promise`\<`string` \| `undefined`\> | Last edit time. | - || <a id="property-forwarded"></a> `forwarded` | `readonly` | () => `Promise`\<`boolean`\> | Forwarded from another chat. | - |+| <a id="property-group"></a> `group` | `readonly` | [`WhatsAppGroup`](../../group/classes/WhatsAppGroup.md) | The chat this message is in. | - || <a id="property-id"></a> `id` | `public readonly` | `string` | - | [`MacroEntity`](../../../entity/classes/MacroEntity.md).[`id`](../../../entity/classes/MacroEntity.md#property-id) || <a id="property-kind"></a> `kind` | `readonly` | () => `Promise`\<[`WhatsAppMessageKind`](../../../../../generated/storage/types.gen/type-aliases/WhatsAppMessageKind.md)\> | `message`, or `system` for something that happened in the group (see `rich`). | - || <a id="property-mentions"></a> `mentions` | `readonly` | () => `Promise`\<[`WhatsAppMention`](../../../../../generated/storage/types.gen/type-aliases/WhatsAppMention.md)[]\> | People the body @-mentions: `@<token>` in the body is this person. | - |@@ -24,20 +25,7 @@ Message in an independently shared WhatsApp group.| <a id="property-rich"></a> `rich` | `readonly` | () => `Promise`\<`NonNullable`\<WhatsAppRichContent \| null \| undefined\> \| `undefined`\> | Poll (with tallies), location, contact cards, event or system line. | - || <a id="property-sender"></a> `sender` | `readonly` | () => `Promise`\<[`WhatsAppGroupSender`](../../../../../generated/storage/types.gen/type-aliases/WhatsAppGroupSender.md)\> | Protocol-verified sender association and display name. | - || <a id="property-sentat"></a> `sentAt` | `readonly` | () => `Promise`\<`string`\> | WhatsApp timestamp. | - |--## Accessors--### groupId--#### Get Signature--> **get** **groupId**(): `string`--Group identity for checking reply/mutation scope.--##### Returns--`string`+| <a id="property-viewonce"></a> `viewOnce` | `readonly` | () => `Promise`\<`boolean`\> | Sent as view-once in WhatsApp; Macro keeps and shows it like any media. | - |## Methodsdiff --git a/packages/sdk-docs/reference/src/entities/whatsapp/participant/README.md b/packages/sdk-docs/reference/src/entities/whatsapp/participant/README.mdnew file mode 100644index 0000000000..38576f230e--- /dev/null+++ b/packages/sdk-docs/reference/src/entities/whatsapp/participant/README.md@@ -0,0 +1,5 @@+# src/entities/whatsapp/participant++## Classes++- [WhatsAppParticipant](classes/WhatsAppParticipant.md)diff --git a/packages/sdk-docs/reference/src/entities/whatsapp/participant/classes/WhatsAppParticipant.md b/packages/sdk-docs/reference/src/entities/whatsapp/participant/classes/WhatsAppParticipant.mdnew file mode 100644index 0000000000..f9fa3adb85--- /dev/null+++ b/packages/sdk-docs/reference/src/entities/whatsapp/participant/classes/WhatsAppParticipant.md@@ -0,0 +1,109 @@+# Class: WhatsAppParticipant++Someone in an added WhatsApp chat, from its roster; mention them in a text reply.++## Properties++| Property | Modifier | Type | Description |+| ------ | ------ | ------ | ------ |+| <a id="property-group"></a> `group` | `readonly` | [`WhatsAppGroup`](../../group/classes/WhatsAppGroup.md) | The chat whose roster lists them. |+| <a id="property-id"></a> `id` | `readonly` | `string` | Their WhatsApp id: correlation data, not a Macro user. |++## Accessors++### admin++#### Get Signature++> **get** **admin**(): `boolean` \| `undefined`++Whether they administer the group, when read from the roster.++##### Returns++`boolean` \| `undefined`++***++### displayName++#### Get Signature++> **get** **displayName**(): `string` \| `undefined`++Their WhatsApp name, untrusted, when the roster had one.++##### Returns++`string` \| `undefined`++***++### mentionToken++#### Get Signature++> **get** **mentionToken**(): `string`++The digits a text reply writes as `@<digits>` to mention them.++##### Returns++`string`++## Methods++### toJSON()++> **toJSON**(): \{ `admin`: `boolean` \| `undefined`; `displayName`: `string` \| `undefined`; `group`: `string`; `id`: `string`; \}++Serialize the participant reference without credentials.++#### Returns++\{ `admin`: `boolean` \| `undefined`; `displayName`: `string` \| `undefined`; `group`: `string`; `id`: `string`; \}++| Name | Type |+| ------ | ------ |+| `admin` | `boolean` \| `undefined` |+| `displayName` | `string` \| `undefined` |+| `group` | `string` |+| `id` | `string` |++***++### byId()++> `static` **byId**(`group`, `id`): `WhatsAppParticipant`++Reference a participant of a chat by WhatsApp id.++#### Parameters++| Parameter | Type |+| ------ | ------ |+| `group` | [`WhatsAppGroup`](../../group/classes/WhatsAppGroup.md) |+| `id` | `string` |++#### Returns++`WhatsAppParticipant`++***++### from()++> `static` **from**(`group`, `record`): `WhatsAppParticipant`++Seed a participant from the chat's roster.++#### Parameters++| Parameter | Type |+| ------ | ------ |+| `group` | [`WhatsAppGroup`](../../group/classes/WhatsAppGroup.md) |+| `record` | [`LinkedParticipant`](../../../../../generated/storage/types.gen/type-aliases/LinkedParticipant.md) |++#### Returns++`WhatsAppParticipant`diff --git a/packages/sdk-docs/reference/src/entities/whatsapp/upload/classes/WhatsAppUpload.md b/packages/sdk-docs/reference/src/entities/whatsapp/upload/classes/WhatsAppUpload.mdindex e54ebfc70d..92bb984a93 100644--- a/packages/sdk-docs/reference/src/entities/whatsapp/upload/classes/WhatsAppUpload.md+++ b/packages/sdk-docs/reference/src/entities/whatsapp/upload/classes/WhatsAppUpload.md@@ -7,7 +7,7 @@ A staged attachment scoped to one adopted group; use it in a deliberate media se| Property | Modifier | Type | Description || ------ | ------ | ------ | ------ || <a id="property-filename"></a> `filename?` | `readonly` | `string` | Display filename supplied by the server. |-| <a id="property-groupid"></a> `groupId` | `readonly` | `string` | The group this upload can be sent to. |+| <a id="property-group"></a> `group` | `readonly` | [`WhatsAppGroup`](../../group/classes/WhatsAppGroup.md) | The chat this upload can be sent to. || <a id="property-id"></a> `id` | `readonly` | `string` | Correlation identity of the staged upload. || <a id="property-kind"></a> `kind?` | `readonly` | [`LinkedMediaKind`](../../../../../generated/storage/types.gen/type-aliases/LinkedMediaKind.md) | Media category supplied by the server. |@@ -15,18 +15,18 @@ A staged attachment scoped to one adopted group; use it in a deliberate media se### toJSON()-> **toJSON**(): \{ `filename`: `string` \| `undefined`; `groupId`: `string`; `id`: `string`; `kind`: [`LinkedMediaKind`](../../../../../generated/storage/types.gen/type-aliases/LinkedMediaKind.md) \| `undefined`; \}+> **toJSON**(): \{ `filename`: `string` \| `undefined`; `group`: `string`; `id`: `string`; `kind`: [`LinkedMediaKind`](../../../../../generated/storage/types.gen/type-aliases/LinkedMediaKind.md) \| `undefined`; \}Serialize the upload reference without credentials.#### Returns-\{ `filename`: `string` \| `undefined`; `groupId`: `string`; `id`: `string`; `kind`: [`LinkedMediaKind`](../../../../../generated/storage/types.gen/type-aliases/LinkedMediaKind.md) \| `undefined`; \}+\{ `filename`: `string` \| `undefined`; `group`: `string`; `id`: `string`; `kind`: [`LinkedMediaKind`](../../../../../generated/storage/types.gen/type-aliases/LinkedMediaKind.md) \| `undefined`; \}| Name | Type || ------ | ------ || `filename` | `string` \| `undefined` |-| `groupId` | `string` |+| `group` | `string` || `id` | `string` || `kind` | [`LinkedMediaKind`](../../../../../generated/storage/types.gen/type-aliases/LinkedMediaKind.md) \| `undefined` |diff --git a/packages/sdk-docs/reference/src/macro/README.md b/packages/sdk-docs/reference/src/macro/README.mdindex f397e0ea92..09bc8e9211 100644--- a/packages/sdk-docs/reference/src/macro/README.md+++ b/packages/sdk-docs/reference/src/macro/README.md@@ -640,6 +640,12 @@ Re-exports [WhatsAppMessage](../entities/whatsapp/message/classes/WhatsAppMessag***+### WhatsAppParticipant++Re-exports [WhatsAppParticipant](../entities/whatsapp/participant/classes/WhatsAppParticipant.md)++***+### WhatsAppReplyRe-exports [WhatsAppReply](../entities/whatsapp/group/type-aliases/WhatsAppReply.md)diff --git a/packages/sdk/generated/storage/index.ts b/packages/sdk/generated/storage/index.tsindex 083965cda6..c591cdec5c 100644--- a/packages/sdk/generated/storage/index.ts+++ b/packages/sdk/generated/storage/index.ts@@ -1,4 +1,4 @@// This file is auto-generated by @hey-api/openapi-tsexport { type Options, Sdk } from './sdk.gen';-export type { AccessiblePipeline, AccessLevel, AccessRequest, AccessRequestsCancelData, AccessRequestsCancelErrors, AccessRequestsCancelResponses, AccessRequestsDirectData, AccessRequestsDirectErrors, AccessRequestsDirectResponse, AccessRequestsDirectResponses, AccessRequestsRemoveDirectData, AccessRequestsRemoveDirectErrors, AccessRequestsRemoveDirectResponses, AccessRequestsResolveData, AccessRequestsResolveErrors, AccessRequestsResolveResponse, AccessRequestsResolveResponses, AccessRequestsSetDirectData, AccessRequestsSetDirectErrors, AccessRequestsSetDirectResponses, AccessRequestsStateData, AccessRequestsStateErrors, AccessRequestsStateResponse, AccessRequestsStateResponses, AccessRequestsSubmitData, AccessRequestsSubmitErrors, AccessRequestsSubmitResponse, AccessRequestsSubmitResponses, AccessRequestState, ActiveCallsResponse, ActiveCallSummary, ActiveMeeting, ActiveMeetingsResponse, ActivityType, AddFavoriteData, AddFavoriteError, AddFavoriteErrors, AddFavoriteRequest, AddFavoriteResponse, AddFavoriteResponses, AddParticipantsData, AddParticipantsError, AddParticipantsErrors, AddParticipantsRequest, AddParticipantsResponses, AddPinHandlerData, AddPinHandlerError, AddPinHandlerErrors, AddPinHandlerResponse, AddPinHandlerResponses, AddPinRequest, AdoptedGroup, Agent, AgentActionId, AgentChannelScope, AgentDmProfile, AgentMcpServer, AgentMcpServers, AgentPullRequestState, AgentSessionFilters, AgentSessionLifecycleEvent, AgentSessionSource, AgentSessionVisibility, AgentTyping, AgentTypingPhase, Anchor, AnchorId, AnchorResponse, AnnotationIncrementalUpdate, Answer, ApiActivity, ApiAttachmentChannelReference, ApiAttachmentCommentReference, ApiAttachmentEntityReference, ApiAttachmentGenericReference, ApiChannelAttachment, ApiChannelAttachmentsPage, ApiChannelDetail, ApiChannelListMessage, ApiChannelListPage, ApiChannelListParticipant, ApiChannelListType, ApiChannelParticipant, ApiChannelWithLatest, ApiEntityFilterAst, ApiGroupByField, ApiGroupMeta, ApiParticipantListRole, ApiParticipantRole, ApiPropertyEntityType, AppliedOps, ApplyCrmPipelineOpsData, ApplyCrmPipelineOpsResponse, ApplyCrmPipelineOpsResponses, ApplyDatabaseOpsData, ApplyDatabaseOpsError, ApplyDatabaseOpsErrors, ApplyDatabaseOpsResponse, ApplyDatabaseOpsResponses, ApplyOpsRequest, ApplyOpsResponse, ApproveHarnessPairingData, ApproveHarnessPairingError, ApproveHarnessPairingErrors, ApproveHarnessPairingResponse, ApproveHarnessPairingResponses, ApprovePairingRequest, AttachmentChange, AttendeeResponseStatus, Audience, Awareness, AwarenessRelay, BasicDocument, BasicDocumentSubType, BomPart, BookingTarget, Bot, BotChannel, BotChannelType, BotId, BotKind, BotOwner, BotOwnerProfile, BotSenderProfile, BotToken, BranchNameResponse, BTreeMap, BulkWakeupRequest, BulkWakeupResponse, BulkWakeupSyncServiceDocumentsData, BulkWakeupSyncServiceDocumentsErrors, BulkWakeupSyncServiceDocumentsResponse, BulkWakeupSyncServiceDocumentsResponses, CalendarAttendee, CalendarEvent, CalendarEventFilters, CalendarEventSourceContent, CalendarJoinRequest, CalendarJoinRequestApiError, CalendarJoinRequestErrorCode, CalendarJoinRequestsResponse, CalendarJoinRequestStatus, CalendarMentionEvent, CalendarMentionPreviewItem, CalendarMentionPreviewKind, CalendarMentionPreviewRequest, CalendarMentionPreviewRequestItem, CalendarMentionPreviewResponse, CalendarMentionViewerCopy, CalendarOccurrence, CalendarOccurrenceItem, CalendarOccurrenceResponse, CalendarSyncStatus, CallActiveResponse, CallFilters, CallProvider, CallRecord, CallRecordGuest, CallRecordParticipant, CallRecordPreview, CallRecordPreviewData, CallRecordSource, CallRecordTranscriptSegment, CallStatus, CallTokenResponse, CallWebhookData, CallWebhookError, CallWebhookErrors, CallWebhookResponses, CancelSlackImportData, CancelSlackImportErrors, CancelSlackImportResponse, CancelSlackImportResponses, CardPosition, CastVerdict, CellValue, CellWrite, ChangedFileDto, ChangesetDto, ChangesetSourceDto, Channel, ChannelCreatedMetadata, ChannelDeletedMetadata, ChannelFilters, ChannelJoinCodeResponse, ChannelLabel, ChannelLabelRule, ChannelLabelsList, ChannelMessage, ChannelParticipant, ChannelParticipantAddedMetadata, ChannelParticipantRemovedMetadata, ChannelPictureChangedMetadata, ChannelPreview, ChannelPreviewData, ChannelSender, ChannelSharePermission, ChannelThreadFilters, ChannelTopicEvent, ChannelType, ChannelUpdatedMetadata, ChannelWebhookRequest, ChannelWebhookResponse, ChannelWithParticipants, Chat, ChatFilters, CheckActiveCallData, CheckActiveCallError, CheckActiveCallErrors, CheckActiveCallResponse, CheckActiveCallResponses, ClaimedPairing, ClaimHarnessPairingData, ClaimHarnessPairingError, ClaimHarnessPairingErrors, ClaimHarnessPairingResponse, ClaimHarnessPairingResponses, ClaimPairingRequest, ClientOptions, CloudStorageItemType, CollaborateFormData, CollaborateFormError, CollaborateFormErrors, CollaborateFormResponse, CollaborateFormResponses, CollabSurfaceResponse, CollabSurfaceTokenResponse, Column, ColumnCast, ColumnChange, ColumnChangeKind, ColumnConfig, ColumnConversion, ColumnConversionRequest, ColumnDetail, ColumnId, ColumnKind, ColumnProtection, ColumnResult, CommandFailure, CommandRejectedMetadata, CommittedChange, CompleteSlackImportUploadsData, CompleteSlackImportUploadsErrors, CompleteSlackImportUploadsResponse, CompleteSlackImportUploadsResponses, CompleteUploads, ConferenceProvider, Conjunction, ConversationId, ConversationKind, ConversationMetadata, ConversationProgress, ConversationSeal, ConversationStatus, ConvertDatabaseColumnData, ConvertDatabaseColumnError, ConvertDatabaseColumnErrors, ConvertDatabaseColumnResponse, ConvertDatabaseColumnResponses, ConvertedCell, CopyDocumentData, CopyDocumentError, CopyDocumentErrors, CopyDocumentQueryParams, CopyDocumentRequest, CopyDocumentResponse, CopyDocumentResponse2, CopyDocumentResponses, CountedReaction, CreateAgentData, CreateAgentError, CreateAgentErrors, CreateAgentRequest, CreateAgentResponse, CreateAgentResponses, CreateAnchorData, CreateAnchorError, CreateAnchorErrors, CreateAnchorResponse, CreateAnchorResponses, CreateBotRequest, CreateBulkDocumentResponse, CreateBulkDocumentResponseData, CreateCanvasDocumentRequest, CreateCanvasDocumentResponse, CreateCanvasHandlerData, CreateCanvasHandlerError, CreateCanvasHandlerErrors, CreateCanvasHandlerResponse, CreateCanvasHandlerResponses, CreateChannelData, CreateChannelError, CreateChannelErrors, CreateChannelLabelData, CreateChannelLabelError, CreateChannelLabelErrors, CreateChannelLabelRequest, CreateChannelLabelResponse, CreateChannelLabelResponses, CreateChannelRequest, CreateChannelResponse, CreateChannelResponse2, CreateChannelResponses, CreateChannelScopedBotData, CreateChannelScopedBotError, CreateChannelScopedBotErrors, CreateChannelScopedBotRequest, CreateChannelScopedBotResponse, CreateChannelScopedBotResponse2, CreateChannelScopedBotResponses, CreateCollabSurfaceTokenData, CreateCollabSurfaceTokenError, CreateCollabSurfaceTokenErrors, CreateCollabSurfaceTokenResponse, CreateCollabSurfaceTokenResponses, CreateCrmCompanyData, CreateCrmCompanyError, CreateCrmCompanyErrors, CreateCrmCompanyRequest, CreateCrmCompanyResponse, CreateCrmCompanyResponses, CreateCrmContactData, CreateCrmContactError, CreateCrmContactErrors, CreateCrmContactRequest, CreateCrmContactResponse, CreateCrmContactResponses, CreateCrmPipelineData, CreateCrmPipelineResponse, CreateCrmPipelineResponses, CreateDatabaseData, CreateDatabaseError, CreateDatabaseErrors, CreateDatabaseRequest, CreateDatabaseResponse, CreateDatabaseResponses, CreateDatabaseWebhookData, CreateDatabaseWebhookError, CreateDatabaseWebhookErrors, CreateDatabaseWebhookRequest, CreateDatabaseWebhookResponse, CreateDatabaseWebhookResponses, CreatedDatabaseWebhookResponse, CreateDocumentData, CreateDocumentError, CreateDocumentErrors, CreateDocumentRequest, CreateDocumentResponse, CreateDocumentResponseData, CreateDocumentResponses, CreatedPairing, CreatedUserApiKey, CreateEntityMentionData, CreateEntityMentionError, CreateEntityMentionErrors, CreateEntityMentionRequest, CreateEntityMentionResponse, CreateEntityMentionResponse2, CreateEntityMentionResponses, CreateForm, CreateFormData, CreateFormError, CreateFormErrors, CreateFormResponse, CreateFormResponses, CreateHarnessPairingData, CreateHarnessPairingError, CreateHarnessPairingErrors, CreateHarnessPairingResponse, CreateHarnessPairingResponses, CreateImport, CreateInitiativeData, CreateInitiativeError, CreateInitiativeErrors, CreateInitiativeRequest, CreateInitiativeResponse, CreateInitiativeResponses, CreateInstructionsDocumentResponse, CreateInstructionsHandlerData, CreateInstructionsHandlerError, CreateInstructionsHandlerErrors, CreateInstructionsHandlerResponse, CreateInstructionsHandlerResponses, CreateMarkdownDocumentRequest, CreateMarkdownDocumentResponse, CreateMarkdownHandlerData, CreateMarkdownHandlerError, CreateMarkdownHandlerErrors, CreateMarkdownHandlerResponse, CreateMarkdownHandlerResponses, CreateMeetingRequest, CreatePairingRequest, CreatePipeline, CreateProjectHandlerData, CreateProjectHandlerError, CreateProjectHandlerErrors, CreateProjectHandlerResponse, CreateProjectHandlerResponses, CreateProjectRequest, CreateProjectResponse, CreateSkillHandlerData, CreateSkillHandlerError, CreateSkillHandlerErrors, CreateSkillHandlerResponse, CreateSkillHandlerResponses, CreateSkillRequest, CreateSkillResponse, CreateSlackImportData, CreateSlackImportErrors, CreateSlackImportResponse, CreateSlackImportResponses, CreateSnippetHandlerData, CreateSnippetHandlerError, CreateSnippetHandlerErrors, CreateSnippetHandlerResponse, CreateSnippetHandlerResponses, CreateSnippetRequest, CreateSnippetResponse, CreateTaskHandlerData, CreateTaskHandlerError, CreateTaskHandlerErrors, CreateTaskHandlerResponse, CreateTaskHandlerResponses, CreateTaskRequest, CreateTaskResponse, CreateToken, CreateUnthreadedAnchorRequest, CreateUnthreadedAnchorResponse, CreateUnthreadedPdfAnchorRequest, CreateUserApiKeyData, CreateUserApiKeyError, CreateUserApiKeyErrors, CreateUserApiKeyRequest, CreateUserApiKeyResponse, CreateUserApiKeyResponses, CreateViewHandlerData, CreateViewHandlerError, CreateViewHandlerErrors, CreateViewHandlerResponse, CreateViewHandlerResponses, CreateViewRequest, CreateWebhookData, CreateWebhookError, CreateWebhookErrors, CreateWebhookRequest, CreateWebhookResponse, CreateWebhookResponse2, CreateWebhookResponses, CrmAssociation, CrmCompanyFilters, CrmCompanyResponse, CrmContactResponse, CrmDomainResponse, CrmPermissionRole, CrmStageInput, CrmStageResponse, CrmStagesResponse, CrmTeamSettingsResponse, CustomSpeakerAssignment, Database, DatabaseDetail, DatabaseId, DatabaseOp, DatabaseQueryRequest, DatabaseView, DatabaseWebhookDeliveryResponse, DatabaseWebhookPayloadProblem, DatabaseWebhookResponse, DataType, DateOperator, DeclineCallData, DeclineCallError, DeclineCallErrors, DeclineCallResponse, DeclineCallResponses, DeclineRingData, DeclineRingError, DeclineRingErrors, DeclineRingResponse, DeclineRingResponses, DeleteAnchorData, DeleteAnchorError, DeleteAnchorErrors, DeleteAnchorResponse, DeleteAnchorResponses, DeleteCallRecordData, DeleteCallRecordError, DeleteCallRecordErrors, DeleteCallRecordResponse, DeleteCallRecordResponses, DeleteChannelData, DeleteChannelError, DeleteChannelErrors, DeleteChannelLabelData, DeleteChannelLabelError, DeleteChannelLabelErrors, DeleteChannelLabelResponse, DeleteChannelLabelResponses, DeleteChannelResponse, DeleteChannelResponses, DeleteCollabSurfaceData, DeleteCollabSurfaceError, DeleteCollabSurfaceErrors, DeleteCollabSurfaceResponse, DeleteCollabSurfaceResponses, DeleteDatabaseWebhookData, DeleteDatabaseWebhookError, DeleteDatabaseWebhookErrors, DeleteDatabaseWebhookResponse, DeleteDatabaseWebhookResponses, DeleteDocumentData, DeleteDocumentError, DeleteDocumentErrors, DeleteDocumentResponse, DeleteDocumentResponses, DeleteEntityMentionData, DeleteEntityMentionError, DeleteEntityMentionErrors, DeleteEntityMentionResponse, DeleteEntityMentionResponse2, DeleteEntityMentionResponses, DeleteHarnessData, DeleteHarnessError, DeleteHarnessErrors, DeleteHarnessResponse, DeleteHarnessResponses, DeleteHistoryHandlerData, DeleteHistoryHandlerError, DeleteHistoryHandlerErrors, DeleteHistoryHandlerResponse, DeleteHistoryHandlerResponses, DeleteInitiativeData, DeleteInitiativeError, DeleteInitiativeErrors, DeleteInitiativeResponse, DeleteInitiativeResponses, DeleteProjectHandlerData, DeleteProjectHandlerError, DeleteProjectHandlerErrors, DeleteProjectHandlerResponse, DeleteProjectHandlerResponses, DeleteSelfHarnessData, DeleteSelfHarnessError, DeleteSelfHarnessErrors, DeleteSelfHarnessResponse, DeleteSelfHarnessResponses, DeleteUnthreadedAnchorRequest, DeleteUnthreadedAnchorResponse, DeleteUnthreadedPdfAnchorRequest, DeleteUserApiKeyData, DeleteUserApiKeyError, DeleteUserApiKeyErrors, DeleteUserApiKeyResponse, DeleteUserApiKeyResponses, DeleteUserDocumentViewLocationData, DeleteUserDocumentViewLocationError, DeleteUserDocumentViewLocationErrors, DeleteUserDocumentViewLocationResponse, DeleteUserDocumentViewLocationResponses, DeleteViewHandlerData, DeleteViewHandlerError, DeleteViewHandlerErrors, DeleteViewHandlerResponses, DeleteWebhookData, DeleteWebhookError, DeleteWebhookErrors, DeleteWebhookResponse, DeleteWebhookResponses, DeliverDatabaseWebhookData, DeliverDatabaseWebhookError, DeliverDatabaseWebhookErrors, DeliverDatabaseWebhookResponse, DeliverDatabaseWebhookResponses, DirectAccess, DocumentBasic, DocumentContent, DocumentContentLocation, DocumentContentState, DocumentContentUploadedMetadata, DocumentCopiedMetadata, DocumentCreatedMetadata, DocumentDeletedMetadata, DocumentFilters, DocumentId, DocumentInteractionMetadata, DocumentMetadata, DocumentMetadataWithContent, DocumentPermissionsToken, DocumentPermissionsTokenRequest, DocumentPermissionsTokenResponse, DocumentPreview, DocumentPreviewData, DocumentPreviewDataSubType, DocumentPurgedMetadata, DocumentResponse, DocumentResponseMetadata, DocumentResponseMetadataWithContent, DocumentStorageServiceApiVersion, DocumentSubType, DocumentSyncContentUpdatedMetadata, DocumentSyncEditor, DocumentTeamShareResponse, DocumentTextContent, DocumentTopicEvent, DocumentUpdatedMetadata, EditAnchorData, EditAnchorError, EditAnchorErrors, EditAnchorRequest, EditAnchorResponse, EditAnchorResponse2, EditAnchorResponses, EditCallRecordData, EditCallRecordError, EditCallRecordErrors, EditCallRecordRequest, EditCallRecordResponse, EditCallRecordResponses, EditCallTranscriptData, EditCallTranscriptError, EditCallTranscriptErrors, EditCallTranscriptRequest, EditCallTranscriptResponse, EditCallTranscriptResponses, EditDocumentData, EditDocumentError, EditDocumentErrors, EditDocumentResponse, EditDocumentResponse2, EditDocumentResponses, EditDocumentServiceArgs, EditMyFormResponseData, EditMyFormResponseError, EditMyFormResponseErrors, EditMyFormResponseResponse, EditMyFormResponseResponses, EditPdfAnchorRequest, EditPdfPlaceableCommentAnchorRequest, EditProjectV2Data, EditProjectV2Error, EditProjectV2Errors, EditProjectV2Response, EditProjectV2Responses, EditThreadV2Data, EditThreadV2Error, EditThreadV2Errors, EditThreadV2Response, EditThreadV2Responses, EmailFilters, EmailFollowup, EmailFollowupCommand, EmailFollowupResponse, EmailReminderCondition, EmailReminderPage, EmailReminderSummary, EmptyResponse, EnsureCollabSurfaceData, EnsureCollabSurfaceError, EnsureCollabSurfaceErrors, EnsureCollabSurfaceRequest, EnsureCollabSurfaceResponse, EnsureCollabSurfaceResponses, EnsureStarterHandlerData, EnsureStarterHandlerErrors, EnsureStarterHandlerResponse, EnsureStarterHandlerResponses, EntityFilters, EntityKind, EntityMessageCreateData, EntityMessageCreateResponse, EntityMessageCreateResponses, EntityMessageDeleteMessageData, EntityMessageDeleteMessageResponse, EntityMessageDeleteMessageResponses, EntityMessageDeleteThreadData, EntityMessageDeleteThreadResponse, EntityMessageDeleteThreadResponses, EntityMessageEditData, EntityMessageEditResponse, EntityMessageEditResponses, EntityMessageGetMessageData, EntityMessageGetMessageResponse, EntityMessageGetMessageResponses, EntityMessageGetThreadData, EntityMessageGetThreadResponse, EntityMessageGetThreadResponses, EntityMessageLegacyData, EntityMessageLegacyResponse, EntityMessageLegacyResponses, EntityMessagePatchThreadData, EntityMessagePatchThreadResponse, EntityMessagePatchThreadResponses, EntityMessageReactData, EntityMessageReactResponse, EntityMessageReactResponses, EntityMessageTypingData, EntityMessageTypingResponse, EntityMessageTypingResponses, EntityPermission, EntityPermissionResponse, EntityRef, EntityReference, EntityType, ErrorResponse, EventIcsData, EventIcsErrors, EventIcsResponse, EventIcsResponses, EventReminderOverride, EventReminders, EventStatus, EventTime, EventTransparency, EventType, EventVisibility, ExcludedDefaultView, ExcludeDefaultViewHandlerData, ExcludeDefaultViewHandlerError, ExcludeDefaultViewHandlerErrors, ExcludeDefaultViewHandlerResponses, ExcludeDefaultViewRequest, ExportDocumentData, ExportDocumentError, ExportDocumentErrors, ExportDocumentResponse, ExportDocumentResponse2, ExportDocumentResponses, Favorite, FavoriteEntityRef, FavoritesList, FileChangeKindDto, FileSystemNodeWithIds, FileType, FileTypeUpdate, FilterCondition, FilterGroup, FilterNode, FilterTest, FinalizeSlackImportData, FinalizeSlackImportErrors, FinalizeSlackImportResponse, FinalizeSlackImportResponses, FolderItem, FollowupState, ForeignEntity, ForeignEntityFilters, Form, FormAccess, FormCollaboration, FormDetail, FormErrorCode, FormErrorResponse, FormLayout, FormPublicationProblem, FormQuestionDetail, FormResponse, FormSection, FormSectionDetail, FormSource, FormStatus, FormTally, Formula, GenericErrorResponse, GenericResponse, GenericSuccessResponse, GetActiveCallsData, GetActiveCallsError, GetActiveCallsErrors, GetActiveCallsResponse, GetActiveCallsResponses, GetActivityData, GetActivityError, GetActivityErrors, GetActivityResponse, GetActivityResponses, GetAttachmentReferencesData, GetAttachmentReferencesError, GetAttachmentReferencesErrors, GetAttachmentReferencesResponse, GetAttachmentReferencesResponse2, GetAttachmentReferencesResponses, GetBatchCallRecordPreviewData, GetBatchCallRecordPreviewError, GetBatchCallRecordPreviewErrors, GetBatchCallRecordPreviewRequest, GetBatchCallRecordPreviewResponse, GetBatchCallRecordPreviewResponse2, GetBatchCallRecordPreviewResponses, GetBatchChannelPreviewData, GetBatchChannelPreviewError, GetBatchChannelPreviewErrors, GetBatchChannelPreviewRequest, GetBatchChannelPreviewResponse, GetBatchChannelPreviewResponse2, GetBatchChannelPreviewResponses, GetBatchPreviewHandlerData, GetBatchPreviewHandlerError, GetBatchPreviewHandlerErrors, GetBatchPreviewHandlerResponse, GetBatchPreviewHandlerResponses, GetBatchPreviewRequest, GetBatchPreviewResponse, GetBatchProjectPreviewData, GetBatchProjectPreviewError, GetBatchProjectPreviewErrors, GetBatchProjectPreviewRequest, GetBatchProjectPreviewResponse, GetBatchProjectPreviewResponse2, GetBatchProjectPreviewResponses, GetBotOwnerProfilesData, GetBotOwnerProfilesError, GetBotOwnerProfilesErrors, GetBotOwnerProfilesResponse, GetBotOwnerProfilesResponses, GetCallRecordData, GetCallRecordError, GetCallRecordErrors, GetCallRecordResponse, GetCallRecordResponses, GetChannelAttachmentsData, GetChannelAttachmentsError, GetChannelAttachmentsErrors, GetChannelAttachmentsResponse, GetChannelAttachmentsResponses, GetChannelData, GetChannelError, GetChannelErrors, GetChannelJoinLinkData, GetChannelJoinLinkError, GetChannelJoinLinkErrors, GetChannelJoinLinkResponse, GetChannelJoinLinkResponses, GetChannelParticipantsData, GetChannelParticipantsError, GetChannelParticipantsErrors, GetChannelParticipantsResponse, GetChannelParticipantsResponses, GetChannelResponse, GetChannelResponses, GetChannelsData, GetChannelsError, GetChannelsErrors, GetChannelsResponse, GetChannelsResponses, GetCollabSurfaceData, GetCollabSurfaceError, GetCollabSurfaceErrors, GetCollabSurfaceResponse, GetCollabSurfaceResponses, GetCompanyData, GetCompanyError, GetCompanyErrors, GetCompanyResponse, GetCompanyResponses, GetContactByEmailData, GetContactByEmailError, GetContactByEmailErrors, GetContactByEmailResponse, GetContactByEmailResponse2, GetContactByEmailResponses, GetContactData, GetContactError, GetContactErrors, GetContactResponse, GetContactResponses, GetCrmPipelineData, GetCrmPipelinePermissionsData, GetCrmPipelinePermissionsResponse, GetCrmPipelinePermissionsResponses, GetCrmPipelineResponse, GetCrmPipelineResponses, GetCrmPipelineRowsData, GetCrmPipelineRowsResponse, GetCrmPipelineRowsResponses, GetCrmPipelineTableData, GetCrmPipelineTableResponse, GetCrmPipelineTableResponses, GetCrmTeamSettingsData, GetCrmTeamSettingsError, GetCrmTeamSettingsErrors, GetCrmTeamSettingsResponse, GetCrmTeamSettingsResponses, GetDatabaseData, GetDatabaseError, GetDatabaseErrors, GetDatabasePermissionsData, GetDatabasePermissionsError, GetDatabasePermissionsErrors, GetDatabasePermissionsResponse, GetDatabasePermissionsResponses, GetDatabaseQueryData, GetDatabaseQueryError, GetDatabaseQueryErrors, GetDatabaseQueryResponse, GetDatabaseQueryResponses, GetDatabaseResponse, GetDatabaseResponses, GetDatabaseRowHistoryData, GetDatabaseRowHistoryError, GetDatabaseRowHistoryErrors, GetDatabaseRowHistoryResponse, GetDatabaseRowHistoryResponses, GetDatabaseTableChangesData, GetDatabaseTableChangesError, GetDatabaseTableChangesErrors, GetDatabaseTableChangesResponse, GetDatabaseTableChangesResponses, GetDatabaseViewPositionsData, GetDatabaseViewPositionsError, GetDatabaseViewPositionsErrors, GetDatabaseViewPositionsResponse, GetDatabaseViewPositionsResponses, GetDocumentAnchorsData, GetDocumentAnchorsError, GetDocumentAnchorsErrors, GetDocumentAnchorsResponse, GetDocumentAnchorsResponses, GetDocumentBranchNameData, GetDocumentBranchNameError, GetDocumentBranchNameErrors, GetDocumentBranchNameResponse, GetDocumentBranchNameResponses, GetDocumentByTeamSlugData, GetDocumentByTeamSlugError, GetDocumentByTeamSlugErrors, GetDocumentByTeamSlugResponse, GetDocumentByTeamSlugResponses, GetDocumentData, GetDocumentError, GetDocumentErrors, GetDocumentGithubPullRequestsData, GetDocumentGithubPullRequestsError, GetDocumentGithubPullRequestsErrors, GetDocumentGithubPullRequestsResponse, GetDocumentGithubPullRequestsResponses, GetDocumentKeyResponse, GetDocumentKeyResponseData, GetDocumentListHandlerData, GetDocumentListHandlerError, GetDocumentListHandlerErrors, GetDocumentListHandlerResponse, GetDocumentListHandlerResponses, GetDocumentListResult, GetDocumentLocationV3Data, GetDocumentLocationV3Error, GetDocumentLocationV3Errors, GetDocumentLocationV3Response, GetDocumentLocationV3Responses, GetDocumentPermissionsResponseDataV2, GetDocumentPermissionsTokenData, GetDocumentPermissionsTokenError, GetDocumentPermissionsTokenErrors, GetDocumentPermissionsTokenResponse, GetDocumentPermissionsTokenResponses, GetDocumentPermissionsV2Data, GetDocumentPermissionsV2Error, GetDocumentPermissionsV2Errors, GetDocumentPermissionsV2Response, GetDocumentPermissionsV2Responses, GetDocumentProcessingResult, GetDocumentProcessingResultData, GetDocumentProcessingResultError, GetDocumentProcessingResultErrors, GetDocumentProcessingResultResponse, GetDocumentProcessingResultResponse2, GetDocumentProcessingResultResponses, GetDocumentResponse, GetDocumentResponse2, GetDocumentResponseData, GetDocumentResponses, GetDocumentSearchResponse, GetDocumentShortIdData, GetDocumentShortIdError, GetDocumentShortIdErrors, GetDocumentShortIdResponse, GetDocumentShortIdResponses, GetDocumentsResponse, GetDocumentTeamShareData, GetDocumentTeamShareError, GetDocumentTeamShareErrors, GetDocumentTeamShareResponse, GetDocumentTeamShareResponses, GetDocumentTextContentData, GetDocumentTextContentErrors, GetDocumentTextContentResponse, GetDocumentTextContentResponses, GetDocumentUserAccessLevelResponse, GetDocumentVersionData, GetDocumentVersionError, GetDocumentVersionErrors, GetDocumentVersionResponse, GetDocumentVersionResponses, GetDocumentViewsHandlerData, GetDocumentViewsHandlerError, GetDocumentViewsHandlerErrors, GetDocumentViewsHandlerResponse, GetDocumentViewsHandlerResponses, GetEmailFollowupData, GetEmailFollowupError, GetEmailFollowupErrors, GetEmailFollowupResponse, GetEmailFollowupResponses, GetEntityPermissionData, GetEntityPermissionErrors, GetEntityPermissionResponse, GetEntityPermissionResponses, GetForeignEntityBySourceData, GetForeignEntityBySourceError, GetForeignEntityBySourceErrors, GetForeignEntityBySourceResponse, GetForeignEntityBySourceResponses, GetForeignEntityData, GetForeignEntityError, GetForeignEntityErrors, GetForeignEntityResponse, GetForeignEntityResponses, GetFormData, GetFormError, GetFormErrors, GetFormPermissionsData, GetFormPermissionsError, GetFormPermissionsErrors, GetFormPermissionsResponse, GetFormPermissionsResponses, GetFormResponse, GetFormResponses, GetFormResponseSummaryData, GetFormResponseSummaryError, GetFormResponseSummaryErrors, GetFormResponseSummaryResponse, GetFormResponseSummaryResponses, GetFormTallyData, GetFormTallyError, GetFormTallyErrors, GetFormTallyResponse, GetFormTallyResponses, GetGithubPullRequestChangesData, GetGithubPullRequestChangesError, GetGithubPullRequestChangesErrors, GetGithubPullRequestChangesPatchData, GetGithubPullRequestChangesPatchError, GetGithubPullRequestChangesPatchErrors, GetGithubPullRequestChangesPatchResponse, GetGithubPullRequestChangesPatchResponses, GetGithubPullRequestChangesResponse, GetGithubPullRequestChangesResponses, GetGithubPullRequestData, GetGithubPullRequestError, GetGithubPullRequestErrors, GetGithubPullRequestFacetsData, GetGithubPullRequestFacetsError, GetGithubPullRequestFacetsErrors, GetGithubPullRequestFacetsResponse, GetGithubPullRequestFacetsResponses, GetGithubPullRequestResponse, GetGithubPullRequestResponses, GetGithubPullRequestTasksData, GetGithubPullRequestTasksError, GetGithubPullRequestTasksErrors, GetGithubPullRequestTasksResponse, GetGithubPullRequestTasksResponses, GetHarnessPairingData, GetHarnessPairingError, GetHarnessPairingErrors, GetHarnessPairingResponse, GetHarnessPairingResponses, GetHistoryHandlerData, GetHistoryHandlerError, GetHistoryHandlerErrors, GetHistoryHandlerResponse, GetHistoryHandlerResponses, GetInitiativeData, GetInitiativeError, GetInitiativeErrors, GetInitiativeResponse, GetInitiativeResponses, GetInstructionsDocumentResponse, GetInstructionsHandlerData, GetInstructionsHandlerError, GetInstructionsHandlerErrors, GetInstructionsHandlerResponse, GetInstructionsHandlerResponses, GetItemsSoupData, GetItemsSoupError, GetItemsSoupErrors, GetItemsSoupResponse, GetItemsSoupResponses, GetLocationHandlerData, GetLocationHandlerError, GetLocationHandlerErrors, GetLocationHandlerResponse, GetLocationHandlerResponses, GetMyFormResponseData, GetMyFormResponseError, GetMyFormResponseErrors, GetMyFormResponseResponse, GetMyFormResponseResponses, GetOrCreateAction, GetOrCreateCallData, GetOrCreateCallError, GetOrCreateCallErrors, GetOrCreateCallResponse, GetOrCreateCallResponses, GetOrCreateChannelResponse, GetOrCreateDmData, GetOrCreateDmError, GetOrCreateDmErrors, GetOrCreateDmRequest, GetOrCreateDmResponse, GetOrCreateDmResponses, GetOrCreatePrivateData, GetOrCreatePrivateError, GetOrCreatePrivateErrors, GetOrCreatePrivateRequest, GetOrCreatePrivateResponse, GetOrCreatePrivateResponses, GetPendingProjectsHandlerData, GetPendingProjectsHandlerError, GetPendingProjectsHandlerErrors, GetPendingProjectsHandlerResponse, GetPendingProjectsHandlerResponses, GetPinsHandlerData, GetPinsHandlerError, GetPinsHandlerErrors, GetPinsHandlerResponse, GetPinsHandlerResponses, GetPinsResponse, GetProjectContentHandlerData, GetProjectContentHandlerError, GetProjectContentHandlerErrors, GetProjectContentHandlerResponse, GetProjectContentHandlerResponses, GetProjectContentResponse, GetProjectHandlerData, GetProjectHandlerError, GetProjectHandlerErrors, GetProjectHandlerResponse, GetProjectHandlerResponses, GetProjectPermissionsV2Data, GetProjectPermissionsV2Error, GetProjectPermissionsV2Errors, GetProjectPermissionsV2Response, GetProjectPermissionsV2Responses, GetProjectResponse, GetProjectResponseData, GetProjectsHandlerData, GetProjectsHandlerError, GetProjectsHandlerErrors, GetProjectsHandlerResponse, GetProjectsHandlerResponses, GetProjectsResponse, GetProjectUserAccessLevelData, GetProjectUserAccessLevelError, GetProjectUserAccessLevelErrors, GetProjectUserAccessLevelResponse, GetProjectUserAccessLevelResponses, GetRingStatusData, GetRingStatusError, GetRingStatusErrors, GetRingStatusResponse, GetRingStatusResponses, GetSelfBotData, GetSelfBotError, GetSelfBotErrors, GetSelfBotResponse, GetSelfBotResponses, GetSelfHarnessData, GetSelfHarnessError, GetSelfHarnessErrors, GetSelfHarnessResponse, GetSelfHarnessResponses, GetSlackImportData, GetSlackImportErrors, GetSlackImportResponse, GetSlackImportResponses, GetSystemSkillsHandlerData, GetSystemSkillsHandlerError, GetSystemSkillsHandlerErrors, GetSystemSkillsHandlerResponse, GetSystemSkillsHandlerResponses, GetUserDocumentsHandlerData, GetUserDocumentsHandlerError, GetUserDocumentsHandlerErrors, GetUserDocumentsHandlerResponse, GetUserDocumentsHandlerResponses, GetUserDocumentViewLocationData, GetUserDocumentViewLocationError, GetUserDocumentViewLocationErrors, GetUserDocumentViewLocationResponse, GetUserDocumentViewLocationResponses, GetUserHistoryResponse, GetViewsHandlerData, GetViewsHandlerError, GetViewsHandlerErrors, GetViewsHandlerResponse, GetViewsHandlerResponses, GetWebhookData, GetWebhookError, GetWebhookErrors, GetWebhookResponse, GetWebhookResponses, GithubLabelFacet, GithubPullRequest, GithubPullRequestChangesPatchResponse, GithubPullRequestChangesResponse, GithubPullRequestCheckRun, GithubPullRequestComment, GithubPullRequestFacets, GithubPullRequestLabel, GithubPullRequestReview, GithubPullRequestReviewDecision, GithubPullRequestReviewState, GithubPullRequestsResponse, GithubPullRequestTasks, GithubPullRequestTasksRequest, GithubPullRequestTasksResponse, GithubPullRequestUser, GithubRepositoryFacet, GithubUserFacet, GitRefDto, GroupedInitialParams, GroupedPageParams, GroupedSoupGroupPage, GroupedSoupInitialPage, GroupedSoupPage, GroupedSoupSort, GuestCallChatPostData, GuestCallChatPostErrors, GuestCallChatPostResponse, GuestCallChatPostResponses, GuestCallChatReadData, GuestCallChatReadErrors, GuestCallChatReadResponse, GuestCallChatReadResponses, GuestChatMessage, GuestChatPage, GuestChatPost, GuestId, GuestJoinRequest, GuestPolicy, HandlerData, HandlerError, HandlerErrors, HandlerResponse, HandlerResponses, Harness, HarnessAgent, HarnessId, HarnessOwner, HarnessSession, HashMap, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, HighlightType, ImportCounters, ImportDatabaseTableData, ImportDatabaseTableError, ImportDatabaseTableErrors, ImportDatabaseTableResponse, ImportDatabaseTableResponses, ImportedAuthor, ImportError, ImportLimits, ImportPage, ImportProgress, ImportTable, ImportWarning, InferColumnTypeOutcome, InferColumnTypeRequest, InferDatabaseColumnTypeData, InferDatabaseColumnTypeError, InferDatabaseColumnTypeErrors, InferDatabaseColumnTypeResponse, InferDatabaseColumnTypeResponses, InFlightTurnSummary, IngestTranscriptData, IngestTranscriptError, IngestTranscriptErrors, IngestTranscriptResponses, InitializeUserDocumentsData, InitializeUserDocumentsError, InitializeUserDocumentsErrors, InitializeUserDocumentsResponse, InitializeUserDocumentsResponses, InitialPropertyValue, InitiativeDetail, InitiativeFilters, InitiativeId, InitiativeList, InitiativeSummary, InputReceivedMetadata, InstallSyncData, InstallSyncErrors, InteractionReason, InvalidDatabaseWebhookPayloadResponse, InviteMeetingRequest, InviteMeetingUsersRequest, Item, ItemWithUserAccessLevel, JobId, JobProcessingResultHandlerData, JobProcessingResultHandlerError, JobProcessingResultHandlerErrors, JobProcessingResultHandlerResponse, JobProcessingResultHandlerResponses, JobStatus, JoinChannelByCodeData, JoinChannelByCodeError, JoinChannelByCodeErrors, JoinChannelByCodeResponses, JoinChannelData, JoinChannelError, JoinChannelErrors, JoinChannelResponses, KeySegment, Lane, LaneKey, LatestMessage, LayoutProblem, LeaveCallResponse, LeaveChannelData, LeaveChannelError, LeaveChannelErrors, LeaveChannelResponses, LeaveOrEndCallData, LeaveOrEndCallError, LeaveOrEndCallErrors, LeaveOrEndCallResponse, LeaveOrEndCallResponses, LinkedAccount, LinkedAccountData, LinkedAccountResponse, LinkedAccountResponses, LinkedAccountState, LinkedAccountView, LinkedAdoptData, LinkedAdoptGroup, LinkedAdoptResponse, LinkedAdoptResponses, LinkedAttachment, LinkedAttachmentState, LinkedBackfill, LinkedBackfillState, LinkedCancelPairingData, LinkedCancelPairingResponse, LinkedCancelPairingResponses, LinkedCapabilities, LinkedChat, LinkedChatKind, LinkedChats, LinkedChatsData, LinkedChatsResponse, LinkedChatsResponses, LinkedConfigurationData, LinkedConfigurationResponse, LinkedConfigurationResponses, LinkedConnect, LinkedConnectData, LinkedConnectResponse, LinkedConnectResponses, LinkedDeliveryData, LinkedDeliveryResponse, LinkedDeliveryResponses, LinkedDeliveryState, LinkedDetachData, LinkedDetachResponse, LinkedDetachResponses, LinkedDisconnect, LinkedDisconnectData, LinkedDisconnectRequest, LinkedDisconnectResponse, LinkedDisconnectResponses, LinkedFeatures, LinkedGroupInfo, LinkedGroupReference, LinkedGroupsData, LinkedGroupsResponse, LinkedGroupsResponses, LinkedIdentity, LinkedMediaKind, LinkedMediaPresentation, LinkedMessageAttachments, LinkedMessageAttachmentsData, LinkedMessageAttachmentsResponse, LinkedMessageAttachmentsResponses, LinkedMutation, LinkedPairing, LinkedPairingData, LinkedPairingResponse, LinkedPairingResponses, LinkedPairingState, LinkedPairState, LinkedParticipant, LinkedPasskeyData, LinkedPasskeyResponse, LinkedPasskeyResponses, LinkedReplyBlock, LinkedReplyContent, LinkedReplyData, LinkedReplyErrors, LinkedReplyResponse, LinkedReplyResponses, LinkedSendProgress, LinkedSendReply, LinkedSharedGroupReference, LinkedUploadData, LinkedUploadedAttachment, LinkedUploadRequest, LinkedUploadResponse, LinkedUploadResponses, LinkShare, ListAccessibleFormsData, ListAccessibleFormsError, ListAccessibleFormsErrors, ListAccessibleFormsResponse, ListAccessibleFormsResponses, ListAgentsData, ListAgentsError, ListAgentsErrors, ListAgentsResponse, ListAgentsResponses, ListBotChannelsData, ListBotChannelsError, ListBotChannelsErrors, ListBotChannelsResponse, ListBotChannelsResponses, ListChannelLabelsData, ListChannelLabelsError, ListChannelLabelsErrors, ListChannelLabelsResponse, ListChannelLabelsResponses, ListCompanyContactsData, ListCompanyContactsError, ListCompanyContactsErrors, ListCompanyContactsResponse, ListCompanyContactsResponses, ListCrmPipelinesData, ListCrmPipelinesResponse, ListCrmPipelinesResponses, ListDatabaseColumnCastsData, ListDatabaseColumnCastsError, ListDatabaseColumnCastsErrors, ListDatabaseColumnCastsResponse, ListDatabaseColumnCastsResponses, ListDatabasesData, ListDatabasesError, ListDatabasesErrors, ListDatabasesResponse, ListDatabasesResponses, ListDatabaseWebhooksData, ListDatabaseWebhooksError, ListDatabaseWebhooksErrors, ListDatabaseWebhooksResponse, ListDatabaseWebhooksResponse2, ListDatabaseWebhooksResponses, ListedDatabase, ListedForm, ListEmailRemindersData, ListEmailRemindersError, ListEmailRemindersErrors, ListEmailRemindersResponse, ListEmailRemindersResponses, ListFavoritesData, ListFavoritesError, ListFavoritesErrors, ListFavoritesResponse, ListFavoritesResponses, ListFormsData, ListFormsError, ListFormsErrors, ListFormsResponse, ListFormsResponses, ListHarnessAgentsData, ListHarnessAgentsError, ListHarnessAgentsErrors, ListHarnessAgentsResponse, ListHarnessAgentsResponses, ListHarnessesData, ListHarnessesError, ListHarnessesErrors, ListHarnessesResponse, ListHarnessesResponses, ListHarnessSessionsData, ListHarnessSessionsError, ListHarnessSessionsErrors, ListHarnessSessionsResponse, ListHarnessSessionsResponses, ListInitiativesData, ListInitiativesError, ListInitiativesErrors, ListInitiativesResponse, ListInitiativesResponses, ListJoinRequestsData, ListJoinRequestsError, ListJoinRequestsErrors, ListJoinRequestsResponse, ListJoinRequestsResponses, ListOccurrencesData, ListOccurrencesErrors, ListOccurrencesResponse, ListOccurrencesResponses, ListSlackImportsData, ListSlackImportsResponse, ListSlackImportsResponses, ListTeamCalendarData, ListTeamCalendarResponse, ListTeamCalendarResponses, ListTeamOutOfOfficeData, ListTeamOutOfOfficeErrors, ListTeamOutOfOfficeResponse, ListTeamOutOfOfficeResponses, ListUserApiKeysData, ListUserApiKeysError, ListUserApiKeysErrors, ListUserApiKeysResponse, ListUserApiKeysResponses, ListWebhooksData, ListWebhooksError, ListWebhooksErrors, ListWebhooksResponse, ListWebhooksResponse2, ListWebhooksResponses, LocationResponseData, LocationResponseV3, MacroUserIdStr, MarkRead, Meeting, MeetingCancelData, MeetingCancelError, MeetingCancelErrors, MeetingCancelPreparationData, MeetingCancelPreparationError, MeetingCancelPreparationErrors, MeetingCancelPreparationResponse, MeetingCancelPreparationResponses, MeetingCancelResponse, MeetingCancelResponses, MeetingCreateData, MeetingCreateError, MeetingCreateErrors, MeetingCreateResponse, MeetingCreateResponses, MeetingGuestJoinData, MeetingGuestJoinError, MeetingGuestJoinErrors, MeetingGuestJoinResponse, MeetingGuestJoinResponses, MeetingGuestParticipantsData, MeetingGuestParticipantsError, MeetingGuestParticipantsErrors, MeetingGuestParticipantsResponse, MeetingGuestParticipantsResponses, MeetingInviteData, MeetingInviteError, MeetingInviteErrors, MeetingInvitePermissions, MeetingInvitePermissionsData, MeetingInvitePermissionsError, MeetingInvitePermissionsErrors, MeetingInvitePermissionsResponse, MeetingInvitePermissionsResponses, MeetingInviteResponse, MeetingInviteResponses, MeetingInviteUsersData, MeetingInviteUsersError, MeetingInviteUsersErrors, MeetingInviteUsersResponse, MeetingInviteUsersResponses, MeetingJoinData, MeetingJoinError, MeetingJoinErrors, MeetingJoinResponse, MeetingJoinResponses, MeetingLeaveData, MeetingLeaveError, MeetingLeaveErrors, MeetingLeaveResponse, MeetingLeaveResponses, MeetingListActiveData, MeetingListActiveError, MeetingListActiveErrors, MeetingListActiveResponse, MeetingListActiveResponses, MeetingListData, MeetingListError, MeetingListErrors, MeetingListResponse, MeetingListResponses, MeetingLookupData, MeetingLookupError, MeetingLookupErrors, MeetingLookupResponse, MeetingLookupResponses, MeetingParticipant, MeetingParticipants, MeetingParticipantsData, MeetingParticipantsError, MeetingParticipantsErrors, MeetingParticipantsResponse, MeetingParticipantsResponses, MeetingPreparation, MeetingPrepareData, MeetingPrepareError, MeetingPrepareErrors, MeetingPrepareResponse, MeetingPrepareResponses, MeetingShareData, MeetingShareError, MeetingShareErrors, MeetingShareResponse, MeetingShareResponses, MeetingsResponse, MeetingToken, MeetingUpdateData, MeetingUpdateError, MeetingUpdateErrors, MeetingUpdateResponse, MeetingUpdateResponses, MentionPreviewsData, MentionPreviewsErrors, MentionPreviewsResponse, MentionPreviewsResponses, Message, MessageAttachment, MessageAttachmentCreatedMetadata, MessageAttachmentRemovedMetadata, MessageChange, MessageCursor, MessageDeletedMetadata, MessageDirection, MessageEvent, MessageEventAttachment, MessageListItem, MessageMentionedMetadata, MessagePage, MessageParent, MessagePatch, MessagePatchedMetadata, MessagePostedMetadata, MessageThread, MessageThreadPreview, MessageTimelineData, MessageTimelineEntriesData, MessageTimelineEntriesResponse, MessageTimelineEntriesResponses, MessageTimelineEntry, MessageTimelinePage, MessageTimelineQuery, MessageTimelineResponse, MessageTimelineResponses, MessageTopicEvent, MyResponse, NewAttachment, NewColumn, NewOption, NewThreadAnchor, NewView, NotificationFilters, NotificationState, NumberOperator, OpBatch, Operator, OpRefusalResponse, OpResult, OptionId, OptionRef, PairingDetails, Params, ParticipantRole, PatchBotRequest, PatchChannelData, PatchChannelError, PatchChannelErrors, PatchChannelRequest, PatchChannelResponse, PatchChannelResponses, PatchMessageNotificationPolicy, PatchProjectRequestV2, PatchThreadRequestV2, PatchViewHandlerData, PatchViewHandlerError, PatchViewHandlerErrors, PatchViewHandlerResponses, PatchWebhookData, PatchWebhookError, PatchWebhookErrors, PatchWebhookRequest, PatchWebhookResponse, PatchWebhookResponses, PdfAnchor, PdfAnchorId, PdfHighlightAnchor, PdfHighlightAnchorRequest, PdfHighlightRect, PdfHighlightRectAnchorRequest, PdfPlaceableCommentAnchor, PendingClaimResponse, PermanentlyDeleteDocumentData, PermanentlyDeleteDocumentError, PermanentlyDeleteDocumentErrors, PermanentlyDeleteDocumentResponse, PermanentlyDeleteDocumentResponses, PermanentlyDeleteProjectData, PermanentlyDeleteProjectError, PermanentlyDeleteProjectErrors, PermanentlyDeleteProjectResponse, PermanentlyDeleteProjectResponses, PinnedItem, PinRequest, Pipeline, PipelineRecordType, PipelineSharing, PostActivityData, PostActivityError, PostActivityErrors, PostActivityRequest, PostActivityResponse, PostActivityResponses, PostChannelBotWebhookData, PostChannelBotWebhookError, PostChannelBotWebhookErrors, PostChannelBotWebhookResponse, PostChannelBotWebhookResponses, PostGroupedSoupAstGroupPageRequest, PostGroupedSoupAstInitialRequest, PostGroupedSoupAstRequest, PostItemsSoupAstData, PostItemsSoupAstError, PostItemsSoupAstErrors, PostItemsSoupAstGroupedData, PostItemsSoupAstGroupedError, PostItemsSoupAstGroupedErrors, PostItemsSoupAstGroupedResponse, PostItemsSoupAstGroupedResponses, PostItemsSoupAstResponse, PostItemsSoupAstResponses, PostItemsSoupData, PostItemsSoupError, PostItemsSoupErrors, PostItemsSoupResponse, PostItemsSoupResponses, PostMessage, PostMessageNotificationPolicy, PostSoupAstRequest, PostSoupRequest, PresaveDocumentHandlerData, PresaveDocumentHandlerError, PresaveDocumentHandlerErrors, PresaveDocumentHandlerResponse, PresaveDocumentHandlerResponses, PreSaveDocumentRequest, PreSaveDocumentResponse, PreSaveDocumentResponseData, PresenceOperator, PresignedUrl, PreviewSmartTagData, PreviewSmartTagError, PreviewSmartTagErrors, PreviewSmartTagResponse, PreviewSmartTagResponses, Project, ProjectDeleteResponseData, ProjectDocumentStatus, ProjectFilters, ProjectPreview, ProjectPreviewData, PropertyDefinition, PropertyDefinitionWithOptions, PropertyFilter, PropertyInput, PropertyOption, PropertyOptionValue, PropertyOwner, PropertyValue, PutCrmTeamSettingsData, PutCrmTeamSettingsError, PutCrmTeamSettingsErrors, PutCrmTeamSettingsResponse, PutCrmTeamSettingsResponses, PutCrmTeamStagesData, PutCrmTeamStagesError, PutCrmTeamStagesErrors, PutCrmTeamStagesResponse, PutCrmTeamStagesResponses, PutFormLayoutData, PutFormLayoutError, PutFormLayoutErrors, PutFormLayoutResponse, PutFormLayoutResponses, QueryCrmPipelineRowsData, QueryCrmPipelineRowsResponse, QueryCrmPipelineRowsResponses, QueryDatabasesData, QueryDatabasesError, QueryDatabasesErrors, QueryDatabasesResponse, QueryDatabasesResponses, QueryDefinition, QuestionLayout, QuestionOption, QuestionTally, ReactionInput, RecentlyDeletedData, RecentlyDeletedError, RecentlyDeletedErrors, RecentlyDeletedResponse, RecentlyDeletedResponseData, RecentlyDeletedResponses, RegisterSlackImportUploadsData, RegisterSlackImportUploadsErrors, RegisterSlackImportUploadsResponse, RegisterSlackImportUploadsResponses, RegisterUploads, RemoveBotFromChannelByBotData, RemoveBotFromChannelByBotError, RemoveBotFromChannelByBotErrors, RemoveBotFromChannelByBotResponse, RemoveBotFromChannelByBotResponses, RemoveFavoriteByEntityData, RemoveFavoriteByEntityError, RemoveFavoriteByEntityErrors, RemoveFavoriteByEntityResponses, RemoveParticipantsData, RemoveParticipantsError, RemoveParticipantsErrors, RemoveParticipantsRequest, RemoveParticipantsResponses, RemovePinHandlerData, RemovePinHandlerError, RemovePinHandlerErrors, RemovePinHandlerResponse, RemovePinHandlerResponses, RenameChannelLabelData, RenameChannelLabelError, RenameChannelLabelErrors, RenameChannelLabelRequest, RenameChannelLabelResponse, RenameChannelLabelResponses, RenameCrmPipelineData, RenameCrmPipelineResponse, RenameCrmPipelineResponses, RenamePipeline, ReorderFavoritesData, ReorderFavoritesError, ReorderFavoritesErrors, ReorderFavoritesRequest, ReorderFavoritesResponses, ReorderPinRequest, ReorderPinsHandlerData, ReorderPinsHandlerError, ReorderPinsHandlerErrors, ReorderPinsHandlerResponse, ReorderPinsHandlerResponses, ReplaceCrmStagesRequest, RequestAccess, RequestedHarnessScope, RequestedLayout, RequestStatus, RequestToJoinData, RequestToJoinError, RequestToJoinErrors, RequestToJoinResponse, RequestToJoinResponses, ResetCrmTeamStagesData, ResetCrmTeamStagesError, ResetCrmTeamStagesErrors, ResetCrmTeamStagesResponse, ResetCrmTeamStagesResponses, ResolveRequest, ResponseStatus, ResponseSummary, ResultColumn, ResultSet, RevertDeleteDocumentData, RevertDeleteDocumentError, RevertDeleteDocumentErrors, RevertDeleteDocumentResponse, RevertDeleteDocumentResponses, RevertDeleteProjectData, RevertDeleteProjectError, RevertDeleteProjectErrors, RevertDeleteProjectResponse, RevertDeleteProjectResponses, RingStatus, RingStatusResponse, RowChange, RowChangeKind, RowChanges, RowHistoryEntry, RowHistoryResponse, RowId, RowsChange, RowsResult, S3ObjectInfo, SaveBomPart, SaveDatabaseQueryData, SaveDatabaseQueryError, SaveDatabaseQueryErrors, SaveDatabaseQueryResponse, SaveDatabaseQueryResponses, SaveDocumentHandlerData, SaveDocumentHandlerError, SaveDocumentHandlerErrors, SaveDocumentHandlerResponse, SaveDocumentHandlerResponses, SaveDocumentRequest, SaveDocumentResponse, SaveDocumentResponseData, SavedQuery, SaveQueryRequest, SearchContactsData, SearchContactsError, SearchContactsErrors, SearchContactsResponse, SearchContactsResponse2, SearchContactsResponses, SearchState, SectionCount, SessionDeletedMetadata, SessionIdentity, SessionMentionedMetadata, SessionOpenedMetadata, SessionRenamedMetadata, SessionSettledMetadata, SessionSource, SessionStoppedMetadata, SetChannelLabelData, SetChannelLabelError, SetChannelLabelErrors, SetChannelLabelRequest, SetChannelLabelResponse, SetChannelLabelResponses, SetChannelPictureData, SetChannelPictureError, SetChannelPictureErrors, SetChannelPictureRequest, SetChannelPictureResponse, SetChannelPictureResponses, SetCompanyHiddenData, SetCompanyHiddenError, SetCompanyHiddenErrors, SetCompanyHiddenRequest, SetCompanyHiddenResponse, SetCompanyHiddenResponses, SetCompanyNameRequest, SetContactHiddenData, SetContactHiddenError, SetContactHiddenErrors, SetContactHiddenRequest, SetContactHiddenResponse, SetContactHiddenResponses, SetContactNameRequest, SetCrmCompanyNameData, SetCrmCompanyNameError, SetCrmCompanyNameErrors, SetCrmCompanyNameResponse, SetCrmCompanyNameResponses, SetCrmContactNameData, SetCrmContactNameError, SetCrmContactNameErrors, SetCrmContactNameResponse, SetCrmContactNameResponses, SetDirectAccess, SetDocumentTeamShareData, SetDocumentTeamShareError, SetDocumentTeamShareErrors, SetDocumentTeamShareRequest, SetDocumentTeamShareResponse, SetDocumentTeamShareResponses, SetEmailFollowupData, SetEmailFollowupError, SetEmailFollowupErrors, SetEmailFollowupResponse, SetEmailFollowupResponses, SetEmailSyncData, SetEmailSyncError, SetEmailSyncErrors, SetEmailSyncRequest, SetEmailSyncResponse, SetEmailSyncResponses, SetOperator, SetPropertyValue, Sha256Digest, ShareCrmPipelineData, ShareCrmPipelineResponse, ShareCrmPipelineResponses, ShareDatabaseAwarenessData, ShareDatabaseAwarenessError, ShareDatabaseAwarenessErrors, ShareDatabaseAwarenessResponse, ShareDatabaseAwarenessResponses, SharedEmailFilter, ShareEntity, ShareEntityType, SharePermissionV2, SharePipeline, ShortIdResponse, SimpleMention, SimpleSaveData, SimpleSaveError, SimpleSaveErrors, SimpleSaveResponse, SimpleSaveResponses, SkippedCell, SlackCompleteRequest, SlackCreateRequest, SlackRegisterRequest, SlackTimestamp, SlackUserId, SmartTagChannelMatch, SmartTagPreview, SortDirection, SortKey, SoupAgentSessionSoupPropertiesField, SoupApiItem, SoupApiSort, SoupApiSortDirection, SoupAttachment, SoupCalendarEventSoupPropertiesField, SoupCalendarEventTime, SoupCallRecordGuest, SoupCallRecordParticipant, SoupCallRecordSoupPropertiesField, SoupChannel, SoupChannelThread, SoupChatSoupPropertiesField, SoupContact, SoupCountedReaction, SoupCrmCompanySoupPropertiesField, SoupCrmContactSoupPropertiesField, SoupCrmDomain, SoupDatabaseRowSoupPropertiesField, SoupDocumentSoupPropertiesField, SoupDocumentSubType, SoupEmailThreadPreview, SoupEnrichedEmailThreadPreviewSoupPropertiesField, SoupForeignEntity, SoupInitiativeSoupPropertiesField, SoupItem, SoupLabel, SoupLabelListVisibility, SoupLabelType, SoupMessageAttachment, SoupMessageListVisibility, SoupMessageSender, SoupMessageSenderType, SoupPage, SoupProjectSoupPropertiesField, SoupPropertiesField, SoupProperty, SoupThreadInfo, SoupThreadReply, SourceBinding, SourceId, SourceIdentity, SqlCell, SqlEntityKind, SqlOutcome, SqlOutcomeKind, SqlSelectOption, SqlStatement, StarterDatabase, StarterDocumentsResponse, StorageRow, StorageRows, StorageRowsQuery, StoredGithubPullRequest, StreamEventsData, StreamEventsError, StreamEventsErrors, StreamEventsResponse, StreamEventsResponses, String, Submission, SubmissionOutcome, SubmitFormResponseData, SubmitFormResponseError, SubmitFormResponseErrors, SubmitFormResponseResponse, SubmitFormResponseResponses, SuccessResponse, SurfaceState, SyncServiceVersionId, SystemSkillSummary, Table, TableChange, TableChanged, TableChanges, TableDetail, TableId, TableResult, TableVersion, TagFilterMode, TakenId, TallyBucket, TallyValue, TaskFilters, TeamCalendarContent, TeamCalendarCoverage, TeamCalendarDetails, TeamCalendarItem, TeamCalendarMember, TeamCalendarPage, TeamCalendarSharing, TeamOutOfOfficeItem, TeamOutOfOfficeResponse, TeamRole, TextOperator, ThreadAnchor, ThreadOrigin, ThreadPatch, ThreadState, TimelineActivity, ToggleShareWithTeamData, ToggleShareWithTeamError, ToggleShareWithTeamErrors, ToggleShareWithTeamResponse, ToggleShareWithTeamResponses, TouchedColumn, TouchedRow, TranscribeDictationData, TranscribeDictationError, TranscribeDictationErrors, TranscribeDictationResponse, TranscribeDictationResponses, TranscribeResponse, TranscriptSegmentRequest, TrashCrmPipelineData, TrashCrmPipelineResponse, TrashCrmPipelineResponses, TrashPipeline, TurnEndedMetadata, TurnStartedMetadata, TurnSummary, TypedSuccessResponse, TypedSuccessResponseGetDocumentResponseData, TypingInput, UndoChangeResponse, UndoDatabaseChangeData, UndoDatabaseChangeError, UndoDatabaseChangeErrors, UndoDatabaseChangeResponse, UndoDatabaseChangeResponses, UndoOutcome, UndoRefusal, UnlockedBooking, UpdateAgentData, UpdateAgentError, UpdateAgentErrors, UpdateAgentRequest, UpdateAgentResponse, UpdateAgentResponses, UpdateChannelSharePermission, UpdateCrmPipelinePermissionsData, UpdateCrmPipelinePermissionsResponse, UpdateCrmPipelinePermissionsResponses, UpdateCrmTeamSettingsRequest, UpdateDatabasePermissionsData, UpdateDatabasePermissionsError, UpdateDatabasePermissionsErrors, UpdateDatabasePermissionsResponse, UpdateDatabasePermissionsResponses, UpdateForm, UpdateFormData, UpdateFormError, UpdateFormErrors, UpdateFormPermissionsData, UpdateFormPermissionsError, UpdateFormPermissionsErrors, UpdateFormPermissionsResponse, UpdateFormPermissionsResponses, UpdateFormResponse, UpdateFormResponses, UpdateInitiativeData, UpdateInitiativeError, UpdateInitiativeErrors, UpdateInitiativeRequest, UpdateInitiativeResponse, UpdateInitiativeResponses, UpdateMeetingRequest, UpdateOperation, UpdateSharePermissionRequestV2, UploadDescriptor, UploadDocumentStatus, UploadExtractFolderHandlerData, UploadExtractFolderHandlerError, UploadExtractFolderHandlerErrors, UploadExtractFolderHandlerResponse, UploadExtractFolderHandlerResponses, UploadExtractFolderRequest, UploadFolderHandlerData, UploadFolderHandlerError, UploadFolderHandlerErrors, UploadFolderHandlerResponse, UploadFolderHandlerResponses, UploadFolderRequest, UploadGrant, UploadId, UpsertHistoryHandlerData, UpsertHistoryHandlerError, UpsertHistoryHandlerErrors, UpsertHistoryHandlerResponse, UpsertHistoryHandlerResponses, UpsertUserDocumentViewLocationData, UpsertUserDocumentViewLocationError, UpsertUserDocumentViewLocationErrors, UpsertUserDocumentViewLocationRequest, UpsertUserDocumentViewLocationResponse, UpsertUserDocumentViewLocationResponses, UserApiKeyId, UserApiKeyInfo, UserApiKeysList, UserDocumentsResponse, UserDocumentViewLocation, UserDocumentViewLocationResponse, UserPinsResponse, UserViewsResponse, ValidateDocumentPermissionsTokenData, ValidateDocumentPermissionsTokenError, ValidateDocumentPermissionsTokenErrors, ValidateDocumentPermissionsTokenResponse, ValidateDocumentPermissionsTokenResponses, ValidateWebhookData, ValidateWebhookError, ValidateWebhookErrors, ValidateWebhookResponse, ValidateWebhookResponse2, ValidateWebhookResponses, Vec, VersionedTable, View, ViewChange, ViewColumn, ViewerCapabilities, ViewLayout, ViewPatch, ViewPosition, ViewPositionsResponse, ViewQuery, ViewResult, ViewsResponse, WaitingForInputMetadata, Webhook, WebhookEvent, WebhookFilter, WebhookScope, WebhookStatus, WebhookValidationTestEvent, WhatsAppCall, WhatsAppCallOutcome, WhatsAppContactCard, WhatsAppContacts, WhatsAppEvent, WhatsappGroupData, WhatsAppGroupDetail, WhatsAppGroupMessage, WhatsAppGroupMessages, WhatsappGroupMessagesData, WhatsappGroupMessagesResponse, WhatsappGroupMessagesResponses, WhatsappGroupPermissionsData, WhatsappGroupPermissionsResponse, WhatsappGroupPermissionsResponses, WhatsAppGroupReaction, WhatsappGroupReadData, WhatsappGroupReadResponse, WhatsappGroupReadResponses, WhatsappGroupResponse, WhatsappGroupResponses, WhatsappGroupsData, WhatsAppGroupSender, WhatsappGroupSendsData, WhatsappGroupSendsResponse, WhatsappGroupSendsResponses, WhatsappGroupsResponse, WhatsappGroupsResponses, WhatsAppGroupSummary, WhatsappGroupUpdatePermissionsData, WhatsappGroupUpdatePermissionsResponse, WhatsappGroupUpdatePermissionsResponses, WhatsAppLocation, WhatsAppMention, WhatsAppMessageKind, WhatsAppPersonRef, WhatsAppPoll, WhatsAppPollOption, WhatsAppRichContent, WhatsAppSystemAction, WhatsAppSystemLine, Widget, WithCallId, WithChannelId, WithDocumentId, WithProjectId } from './types.gen';+export type { AccessiblePipeline, AccessLevel, AccessRequest, AccessRequestsCancelData, AccessRequestsCancelErrors, AccessRequestsCancelResponses, AccessRequestsDirectData, AccessRequestsDirectErrors, AccessRequestsDirectResponse, AccessRequestsDirectResponses, AccessRequestsRemoveDirectData, AccessRequestsRemoveDirectErrors, AccessRequestsRemoveDirectResponses, AccessRequestsResolveData, AccessRequestsResolveErrors, AccessRequestsResolveResponse, AccessRequestsResolveResponses, AccessRequestsSetDirectData, AccessRequestsSetDirectErrors, AccessRequestsSetDirectResponses, AccessRequestsStateData, AccessRequestsStateErrors, AccessRequestsStateResponse, AccessRequestsStateResponses, AccessRequestsSubmitData, AccessRequestsSubmitErrors, AccessRequestsSubmitResponse, AccessRequestsSubmitResponses, AccessRequestState, ActiveCallsResponse, ActiveCallSummary, ActiveMeeting, ActiveMeetingsResponse, ActivityType, AddFavoriteData, AddFavoriteError, AddFavoriteErrors, AddFavoriteRequest, AddFavoriteResponse, AddFavoriteResponses, AddParticipantsData, AddParticipantsError, AddParticipantsErrors, AddParticipantsRequest, AddParticipantsResponses, AddPinHandlerData, AddPinHandlerError, AddPinHandlerErrors, AddPinHandlerResponse, AddPinHandlerResponses, AddPinRequest, AdoptedGroup, Agent, AgentActionId, AgentChannelScope, AgentDmProfile, AgentMcpServer, AgentMcpServers, AgentPullRequestState, AgentSessionFilters, AgentSessionLifecycleEvent, AgentSessionSource, AgentSessionVisibility, AgentTyping, AgentTypingPhase, Anchor, AnchorId, AnchorResponse, AnnotationIncrementalUpdate, Answer, ApiActivity, ApiAttachmentChannelReference, ApiAttachmentCommentReference, ApiAttachmentEntityReference, ApiAttachmentGenericReference, ApiChannelAttachment, ApiChannelAttachmentsPage, ApiChannelDetail, ApiChannelListMessage, ApiChannelListPage, ApiChannelListParticipant, ApiChannelListType, ApiChannelParticipant, ApiChannelWithLatest, ApiEntityFilterAst, ApiGroupByField, ApiGroupMeta, ApiParticipantListRole, ApiParticipantRole, ApiPropertyEntityType, AppliedOps, ApplyCrmPipelineOpsData, ApplyCrmPipelineOpsResponse, ApplyCrmPipelineOpsResponses, ApplyDatabaseOpsData, ApplyDatabaseOpsError, ApplyDatabaseOpsErrors, ApplyDatabaseOpsResponse, ApplyDatabaseOpsResponses, ApplyOpsRequest, ApplyOpsResponse, ApproveHarnessPairingData, ApproveHarnessPairingError, ApproveHarnessPairingErrors, ApproveHarnessPairingResponse, ApproveHarnessPairingResponses, ApprovePairingRequest, AttachmentChange, AttendeeResponseStatus, Audience, Awareness, AwarenessRelay, BasicDocument, BasicDocumentSubType, BomPart, BookingTarget, Bot, BotChannel, BotChannelType, BotId, BotKind, BotOwner, BotOwnerProfile, BotSenderProfile, BotToken, BranchNameResponse, BTreeMap, BulkWakeupRequest, BulkWakeupResponse, BulkWakeupSyncServiceDocumentsData, BulkWakeupSyncServiceDocumentsErrors, BulkWakeupSyncServiceDocumentsResponse, BulkWakeupSyncServiceDocumentsResponses, CalendarAttendee, CalendarEvent, CalendarEventFilters, CalendarEventSourceContent, CalendarJoinRequest, CalendarJoinRequestApiError, CalendarJoinRequestErrorCode, CalendarJoinRequestsResponse, CalendarJoinRequestStatus, CalendarMentionEvent, CalendarMentionPreviewItem, CalendarMentionPreviewKind, CalendarMentionPreviewRequest, CalendarMentionPreviewRequestItem, CalendarMentionPreviewResponse, CalendarMentionViewerCopy, CalendarOccurrence, CalendarOccurrenceItem, CalendarOccurrenceResponse, CalendarSyncStatus, CallActiveResponse, CallFilters, CallProvider, CallRecord, CallRecordGuest, CallRecordParticipant, CallRecordPreview, CallRecordPreviewData, CallRecordSource, CallRecordTranscriptSegment, CallStatus, CallTokenResponse, CallWebhookData, CallWebhookError, CallWebhookErrors, CallWebhookResponses, CancelSlackImportData, CancelSlackImportErrors, CancelSlackImportResponse, CancelSlackImportResponses, CardPosition, CastVerdict, CellValue, CellWrite, ChangedFileDto, ChangesetDto, ChangesetSourceDto, Channel, ChannelCreatedMetadata, ChannelDeletedMetadata, ChannelFilters, ChannelJoinCodeResponse, ChannelLabel, ChannelLabelRule, ChannelLabelsList, ChannelMessage, ChannelParticipant, ChannelParticipantAddedMetadata, ChannelParticipantRemovedMetadata, ChannelPictureChangedMetadata, ChannelPreview, ChannelPreviewData, ChannelSender, ChannelSharePermission, ChannelThreadFilters, ChannelTopicEvent, ChannelType, ChannelUpdatedMetadata, ChannelWebhookRequest, ChannelWebhookResponse, ChannelWithParticipants, Chat, ChatFilters, CheckActiveCallData, CheckActiveCallError, CheckActiveCallErrors, CheckActiveCallResponse, CheckActiveCallResponses, ClaimedPairing, ClaimHarnessPairingData, ClaimHarnessPairingError, ClaimHarnessPairingErrors, ClaimHarnessPairingResponse, ClaimHarnessPairingResponses, ClaimPairingRequest, ClientOptions, CloudStorageItemType, CollaborateFormData, CollaborateFormError, CollaborateFormErrors, CollaborateFormResponse, CollaborateFormResponses, CollabSurfaceResponse, CollabSurfaceTokenResponse, Column, ColumnCast, ColumnChange, ColumnChangeKind, ColumnConfig, ColumnConversion, ColumnConversionRequest, ColumnDetail, ColumnId, ColumnKind, ColumnProtection, ColumnResult, CommandFailure, CommandRejectedMetadata, CommittedChange, CompleteSlackImportUploadsData, CompleteSlackImportUploadsErrors, CompleteSlackImportUploadsResponse, CompleteSlackImportUploadsResponses, CompleteUploads, ConferenceProvider, Conjunction, ConversationId, ConversationKind, ConversationMetadata, ConversationProgress, ConversationSeal, ConversationStatus, ConvertDatabaseColumnData, ConvertDatabaseColumnError, ConvertDatabaseColumnErrors, ConvertDatabaseColumnResponse, ConvertDatabaseColumnResponses, ConvertedCell, CopyDocumentData, CopyDocumentError, CopyDocumentErrors, CopyDocumentQueryParams, CopyDocumentRequest, CopyDocumentResponse, CopyDocumentResponse2, CopyDocumentResponses, CountedReaction, CreateAgentData, CreateAgentError, CreateAgentErrors, CreateAgentRequest, CreateAgentResponse, CreateAgentResponses, CreateAnchorData, CreateAnchorError, CreateAnchorErrors, CreateAnchorResponse, CreateAnchorResponses, CreateBotRequest, CreateBulkDocumentResponse, CreateBulkDocumentResponseData, CreateCanvasDocumentRequest, CreateCanvasDocumentResponse, CreateCanvasHandlerData, CreateCanvasHandlerError, CreateCanvasHandlerErrors, CreateCanvasHandlerResponse, CreateCanvasHandlerResponses, CreateChannelData, CreateChannelError, CreateChannelErrors, CreateChannelLabelData, CreateChannelLabelError, CreateChannelLabelErrors, CreateChannelLabelRequest, CreateChannelLabelResponse, CreateChannelLabelResponses, CreateChannelRequest, CreateChannelResponse, CreateChannelResponse2, CreateChannelResponses, CreateChannelScopedBotData, CreateChannelScopedBotError, CreateChannelScopedBotErrors, CreateChannelScopedBotRequest, CreateChannelScopedBotResponse, CreateChannelScopedBotResponse2, CreateChannelScopedBotResponses, CreateCollabSurfaceTokenData, CreateCollabSurfaceTokenError, CreateCollabSurfaceTokenErrors, CreateCollabSurfaceTokenResponse, CreateCollabSurfaceTokenResponses, CreateCrmCompanyData, CreateCrmCompanyError, CreateCrmCompanyErrors, CreateCrmCompanyRequest, CreateCrmCompanyResponse, CreateCrmCompanyResponses, CreateCrmContactData, CreateCrmContactError, CreateCrmContactErrors, CreateCrmContactRequest, CreateCrmContactResponse, CreateCrmContactResponses, CreateCrmPipelineData, CreateCrmPipelineResponse, CreateCrmPipelineResponses, CreateDatabaseData, CreateDatabaseError, CreateDatabaseErrors, CreateDatabaseRequest, CreateDatabaseResponse, CreateDatabaseResponses, CreateDatabaseWebhookData, CreateDatabaseWebhookError, CreateDatabaseWebhookErrors, CreateDatabaseWebhookRequest, CreateDatabaseWebhookResponse, CreateDatabaseWebhookResponses, CreatedDatabaseWebhookResponse, CreateDocumentData, CreateDocumentError, CreateDocumentErrors, CreateDocumentRequest, CreateDocumentResponse, CreateDocumentResponseData, CreateDocumentResponses, CreatedPairing, CreatedUserApiKey, CreateEntityMentionData, CreateEntityMentionError, CreateEntityMentionErrors, CreateEntityMentionRequest, CreateEntityMentionResponse, CreateEntityMentionResponse2, CreateEntityMentionResponses, CreateForm, CreateFormData, CreateFormError, CreateFormErrors, CreateFormResponse, CreateFormResponses, CreateHarnessPairingData, CreateHarnessPairingError, CreateHarnessPairingErrors, CreateHarnessPairingResponse, CreateHarnessPairingResponses, CreateImport, CreateInitiativeData, CreateInitiativeError, CreateInitiativeErrors, CreateInitiativeRequest, CreateInitiativeResponse, CreateInitiativeResponses, CreateInstructionsDocumentResponse, CreateInstructionsHandlerData, CreateInstructionsHandlerError, CreateInstructionsHandlerErrors, CreateInstructionsHandlerResponse, CreateInstructionsHandlerResponses, CreateMarkdownDocumentRequest, CreateMarkdownDocumentResponse, CreateMarkdownHandlerData, CreateMarkdownHandlerError, CreateMarkdownHandlerErrors, CreateMarkdownHandlerResponse, CreateMarkdownHandlerResponses, CreateMeetingRequest, CreatePairingRequest, CreatePipeline, CreateProjectHandlerData, CreateProjectHandlerError, CreateProjectHandlerErrors, CreateProjectHandlerResponse, CreateProjectHandlerResponses, CreateProjectRequest, CreateProjectResponse, CreateSkillHandlerData, CreateSkillHandlerError, CreateSkillHandlerErrors, CreateSkillHandlerResponse, CreateSkillHandlerResponses, CreateSkillRequest, CreateSkillResponse, CreateSlackImportData, CreateSlackImportErrors, CreateSlackImportResponse, CreateSlackImportResponses, CreateSnippetHandlerData, CreateSnippetHandlerError, CreateSnippetHandlerErrors, CreateSnippetHandlerResponse, CreateSnippetHandlerResponses, CreateSnippetRequest, CreateSnippetResponse, CreateTaskHandlerData, CreateTaskHandlerError, CreateTaskHandlerErrors, CreateTaskHandlerResponse, CreateTaskHandlerResponses, CreateTaskRequest, CreateTaskResponse, CreateToken, CreateUnthreadedAnchorRequest, CreateUnthreadedAnchorResponse, CreateUnthreadedPdfAnchorRequest, CreateUserApiKeyData, CreateUserApiKeyError, CreateUserApiKeyErrors, CreateUserApiKeyRequest, CreateUserApiKeyResponse, CreateUserApiKeyResponses, CreateViewHandlerData, CreateViewHandlerError, CreateViewHandlerErrors, CreateViewHandlerResponse, CreateViewHandlerResponses, CreateViewRequest, CreateWebhookData, CreateWebhookError, CreateWebhookErrors, CreateWebhookRequest, CreateWebhookResponse, CreateWebhookResponse2, CreateWebhookResponses, CrmAssociation, CrmCompanyFilters, CrmCompanyResponse, CrmContactResponse, CrmDomainResponse, CrmPermissionRole, CrmStageInput, CrmStageResponse, CrmStagesResponse, CrmTeamSettingsResponse, CustomSpeakerAssignment, Database, DatabaseDetail, DatabaseId, DatabaseOp, DatabaseQueryRequest, DatabaseView, DatabaseWebhookDeliveryResponse, DatabaseWebhookPayloadProblem, DatabaseWebhookResponse, DataType, DateOperator, DeclineCallData, DeclineCallError, DeclineCallErrors, DeclineCallResponse, DeclineCallResponses, DeclineRingData, DeclineRingError, DeclineRingErrors, DeclineRingResponse, DeclineRingResponses, DeleteAnchorData, DeleteAnchorError, DeleteAnchorErrors, DeleteAnchorResponse, DeleteAnchorResponses, DeleteCallRecordData, DeleteCallRecordError, DeleteCallRecordErrors, DeleteCallRecordResponse, DeleteCallRecordResponses, DeleteChannelData, DeleteChannelError, DeleteChannelErrors, DeleteChannelLabelData, DeleteChannelLabelError, DeleteChannelLabelErrors, DeleteChannelLabelResponse, DeleteChannelLabelResponses, DeleteChannelResponse, DeleteChannelResponses, DeleteCollabSurfaceData, DeleteCollabSurfaceError, DeleteCollabSurfaceErrors, DeleteCollabSurfaceResponse, DeleteCollabSurfaceResponses, DeleteDatabaseWebhookData, DeleteDatabaseWebhookError, DeleteDatabaseWebhookErrors, DeleteDatabaseWebhookResponse, DeleteDatabaseWebhookResponses, DeleteDocumentData, DeleteDocumentError, DeleteDocumentErrors, DeleteDocumentResponse, DeleteDocumentResponses, DeleteEntityMentionData, DeleteEntityMentionError, DeleteEntityMentionErrors, DeleteEntityMentionResponse, DeleteEntityMentionResponse2, DeleteEntityMentionResponses, DeleteHarnessData, DeleteHarnessError, DeleteHarnessErrors, DeleteHarnessResponse, DeleteHarnessResponses, DeleteHistoryHandlerData, DeleteHistoryHandlerError, DeleteHistoryHandlerErrors, DeleteHistoryHandlerResponse, DeleteHistoryHandlerResponses, DeleteInitiativeData, DeleteInitiativeError, DeleteInitiativeErrors, DeleteInitiativeResponse, DeleteInitiativeResponses, DeleteProjectHandlerData, DeleteProjectHandlerError, DeleteProjectHandlerErrors, DeleteProjectHandlerResponse, DeleteProjectHandlerResponses, DeleteSelfHarnessData, DeleteSelfHarnessError, DeleteSelfHarnessErrors, DeleteSelfHarnessResponse, DeleteSelfHarnessResponses, DeleteUnthreadedAnchorRequest, DeleteUnthreadedAnchorResponse, DeleteUnthreadedPdfAnchorRequest, DeleteUserApiKeyData, DeleteUserApiKeyError, DeleteUserApiKeyErrors, DeleteUserApiKeyResponse, DeleteUserApiKeyResponses, DeleteUserDocumentViewLocationData, DeleteUserDocumentViewLocationError, DeleteUserDocumentViewLocationErrors, DeleteUserDocumentViewLocationResponse, DeleteUserDocumentViewLocationResponses, DeleteViewHandlerData, DeleteViewHandlerError, DeleteViewHandlerErrors, DeleteViewHandlerResponses, DeleteWebhookData, DeleteWebhookError, DeleteWebhookErrors, DeleteWebhookResponse, DeleteWebhookResponses, DeliverDatabaseWebhookData, DeliverDatabaseWebhookError, DeliverDatabaseWebhookErrors, DeliverDatabaseWebhookResponse, DeliverDatabaseWebhookResponses, DirectAccess, DocumentBasic, DocumentContent, DocumentContentLocation, DocumentContentState, DocumentContentUploadedMetadata, DocumentCopiedMetadata, DocumentCreatedMetadata, DocumentDeletedMetadata, DocumentFilters, DocumentId, DocumentInteractionMetadata, DocumentMetadata, DocumentMetadataWithContent, DocumentPermissionsToken, DocumentPermissionsTokenRequest, DocumentPermissionsTokenResponse, DocumentPreview, DocumentPreviewData, DocumentPreviewDataSubType, DocumentPurgedMetadata, DocumentResponse, DocumentResponseMetadata, DocumentResponseMetadataWithContent, DocumentStorageServiceApiVersion, DocumentSubType, DocumentSyncContentUpdatedMetadata, DocumentSyncEditor, DocumentTeamShareResponse, DocumentTextContent, DocumentTopicEvent, DocumentUpdatedMetadata, EditAnchorData, EditAnchorError, EditAnchorErrors, EditAnchorRequest, EditAnchorResponse, EditAnchorResponse2, EditAnchorResponses, EditCallRecordData, EditCallRecordError, EditCallRecordErrors, EditCallRecordRequest, EditCallRecordResponse, EditCallRecordResponses, EditCallTranscriptData, EditCallTranscriptError, EditCallTranscriptErrors, EditCallTranscriptRequest, EditCallTranscriptResponse, EditCallTranscriptResponses, EditDocumentData, EditDocumentError, EditDocumentErrors, EditDocumentResponse, EditDocumentResponse2, EditDocumentResponses, EditDocumentServiceArgs, EditMyFormResponseData, EditMyFormResponseError, EditMyFormResponseErrors, EditMyFormResponseResponse, EditMyFormResponseResponses, EditPdfAnchorRequest, EditPdfPlaceableCommentAnchorRequest, EditProjectV2Data, EditProjectV2Error, EditProjectV2Errors, EditProjectV2Response, EditProjectV2Responses, EditThreadV2Data, EditThreadV2Error, EditThreadV2Errors, EditThreadV2Response, EditThreadV2Responses, EmailFilters, EmailFollowup, EmailFollowupCommand, EmailFollowupResponse, EmailReminderCondition, EmailReminderPage, EmailReminderSummary, EmptyResponse, EnsureCollabSurfaceData, EnsureCollabSurfaceError, EnsureCollabSurfaceErrors, EnsureCollabSurfaceRequest, EnsureCollabSurfaceResponse, EnsureCollabSurfaceResponses, EnsureStarterHandlerData, EnsureStarterHandlerErrors, EnsureStarterHandlerResponse, EnsureStarterHandlerResponses, EntityFilters, EntityKind, EntityMessageCreateData, EntityMessageCreateResponse, EntityMessageCreateResponses, EntityMessageDeleteMessageData, EntityMessageDeleteMessageResponse, EntityMessageDeleteMessageResponses, EntityMessageDeleteThreadData, EntityMessageDeleteThreadResponse, EntityMessageDeleteThreadResponses, EntityMessageEditData, EntityMessageEditResponse, EntityMessageEditResponses, EntityMessageGetMessageData, EntityMessageGetMessageResponse, EntityMessageGetMessageResponses, EntityMessageGetThreadData, EntityMessageGetThreadResponse, EntityMessageGetThreadResponses, EntityMessageLegacyData, EntityMessageLegacyResponse, EntityMessageLegacyResponses, EntityMessagePatchThreadData, EntityMessagePatchThreadResponse, EntityMessagePatchThreadResponses, EntityMessageReactData, EntityMessageReactResponse, EntityMessageReactResponses, EntityMessageTypingData, EntityMessageTypingResponse, EntityMessageTypingResponses, EntityPermission, EntityPermissionResponse, EntityRef, EntityReference, EntityType, ErrorResponse, EventIcsData, EventIcsErrors, EventIcsResponse, EventIcsResponses, EventReminderOverride, EventReminders, EventStatus, EventTime, EventTransparency, EventType, EventVisibility, ExcludedDefaultView, ExcludeDefaultViewHandlerData, ExcludeDefaultViewHandlerError, ExcludeDefaultViewHandlerErrors, ExcludeDefaultViewHandlerResponses, ExcludeDefaultViewRequest, ExportDocumentData, ExportDocumentError, ExportDocumentErrors, ExportDocumentResponse, ExportDocumentResponse2, ExportDocumentResponses, Favorite, FavoriteEntityRef, FavoritesList, FileChangeKindDto, FileSystemNodeWithIds, FileType, FileTypeUpdate, FilterCondition, FilterGroup, FilterNode, FilterTest, FinalizeSlackImportData, FinalizeSlackImportErrors, FinalizeSlackImportResponse, FinalizeSlackImportResponses, FolderItem, FollowupState, ForeignEntity, ForeignEntityFilters, Form, FormAccess, FormCollaboration, FormDetail, FormErrorCode, FormErrorResponse, FormLayout, FormPublicationProblem, FormQuestionDetail, FormResponse, FormSection, FormSectionDetail, FormSource, FormStatus, FormTally, Formula, GenericErrorResponse, GenericResponse, GenericSuccessResponse, GetActiveCallsData, GetActiveCallsError, GetActiveCallsErrors, GetActiveCallsResponse, GetActiveCallsResponses, GetActivityData, GetActivityError, GetActivityErrors, GetActivityResponse, GetActivityResponses, GetAttachmentReferencesData, GetAttachmentReferencesError, GetAttachmentReferencesErrors, GetAttachmentReferencesResponse, GetAttachmentReferencesResponse2, GetAttachmentReferencesResponses, GetBatchCallRecordPreviewData, GetBatchCallRecordPreviewError, GetBatchCallRecordPreviewErrors, GetBatchCallRecordPreviewRequest, GetBatchCallRecordPreviewResponse, GetBatchCallRecordPreviewResponse2, GetBatchCallRecordPreviewResponses, GetBatchChannelPreviewData, GetBatchChannelPreviewError, GetBatchChannelPreviewErrors, GetBatchChannelPreviewRequest, GetBatchChannelPreviewResponse, GetBatchChannelPreviewResponse2, GetBatchChannelPreviewResponses, GetBatchPreviewHandlerData, GetBatchPreviewHandlerError, GetBatchPreviewHandlerErrors, GetBatchPreviewHandlerResponse, GetBatchPreviewHandlerResponses, GetBatchPreviewRequest, GetBatchPreviewResponse, GetBatchProjectPreviewData, GetBatchProjectPreviewError, GetBatchProjectPreviewErrors, GetBatchProjectPreviewRequest, GetBatchProjectPreviewResponse, GetBatchProjectPreviewResponse2, GetBatchProjectPreviewResponses, GetBotOwnerProfilesData, GetBotOwnerProfilesError, GetBotOwnerProfilesErrors, GetBotOwnerProfilesResponse, GetBotOwnerProfilesResponses, GetCallRecordData, GetCallRecordError, GetCallRecordErrors, GetCallRecordResponse, GetCallRecordResponses, GetChannelAttachmentsData, GetChannelAttachmentsError, GetChannelAttachmentsErrors, GetChannelAttachmentsResponse, GetChannelAttachmentsResponses, GetChannelData, GetChannelError, GetChannelErrors, GetChannelJoinLinkData, GetChannelJoinLinkError, GetChannelJoinLinkErrors, GetChannelJoinLinkResponse, GetChannelJoinLinkResponses, GetChannelParticipantsData, GetChannelParticipantsError, GetChannelParticipantsErrors, GetChannelParticipantsResponse, GetChannelParticipantsResponses, GetChannelResponse, GetChannelResponses, GetChannelsData, GetChannelsError, GetChannelsErrors, GetChannelsResponse, GetChannelsResponses, GetCollabSurfaceData, GetCollabSurfaceError, GetCollabSurfaceErrors, GetCollabSurfaceResponse, GetCollabSurfaceResponses, GetCompanyData, GetCompanyError, GetCompanyErrors, GetCompanyResponse, GetCompanyResponses, GetContactByEmailData, GetContactByEmailError, GetContactByEmailErrors, GetContactByEmailResponse, GetContactByEmailResponse2, GetContactByEmailResponses, GetContactData, GetContactError, GetContactErrors, GetContactResponse, GetContactResponses, GetCrmPipelineData, GetCrmPipelinePermissionsData, GetCrmPipelinePermissionsResponse, GetCrmPipelinePermissionsResponses, GetCrmPipelineResponse, GetCrmPipelineResponses, GetCrmPipelineRowsData, GetCrmPipelineRowsResponse, GetCrmPipelineRowsResponses, GetCrmPipelineTableData, GetCrmPipelineTableResponse, GetCrmPipelineTableResponses, GetCrmTeamSettingsData, GetCrmTeamSettingsError, GetCrmTeamSettingsErrors, GetCrmTeamSettingsResponse, GetCrmTeamSettingsResponses, GetDatabaseData, GetDatabaseError, GetDatabaseErrors, GetDatabasePermissionsData, GetDatabasePermissionsError, GetDatabasePermissionsErrors, GetDatabasePermissionsResponse, GetDatabasePermissionsResponses, GetDatabaseQueryData, GetDatabaseQueryError, GetDatabaseQueryErrors, GetDatabaseQueryResponse, GetDatabaseQueryResponses, GetDatabaseResponse, GetDatabaseResponses, GetDatabaseRowHistoryData, GetDatabaseRowHistoryError, GetDatabaseRowHistoryErrors, GetDatabaseRowHistoryResponse, GetDatabaseRowHistoryResponses, GetDatabaseTableChangesData, GetDatabaseTableChangesError, GetDatabaseTableChangesErrors, GetDatabaseTableChangesResponse, GetDatabaseTableChangesResponses, GetDatabaseViewPositionsData, GetDatabaseViewPositionsError, GetDatabaseViewPositionsErrors, GetDatabaseViewPositionsResponse, GetDatabaseViewPositionsResponses, GetDocumentAnchorsData, GetDocumentAnchorsError, GetDocumentAnchorsErrors, GetDocumentAnchorsResponse, GetDocumentAnchorsResponses, GetDocumentBranchNameData, GetDocumentBranchNameError, GetDocumentBranchNameErrors, GetDocumentBranchNameResponse, GetDocumentBranchNameResponses, GetDocumentByTeamSlugData, GetDocumentByTeamSlugError, GetDocumentByTeamSlugErrors, GetDocumentByTeamSlugResponse, GetDocumentByTeamSlugResponses, GetDocumentData, GetDocumentError, GetDocumentErrors, GetDocumentGithubPullRequestsData, GetDocumentGithubPullRequestsError, GetDocumentGithubPullRequestsErrors, GetDocumentGithubPullRequestsResponse, GetDocumentGithubPullRequestsResponses, GetDocumentKeyResponse, GetDocumentKeyResponseData, GetDocumentListHandlerData, GetDocumentListHandlerError, GetDocumentListHandlerErrors, GetDocumentListHandlerResponse, GetDocumentListHandlerResponses, GetDocumentListResult, GetDocumentLocationV3Data, GetDocumentLocationV3Error, GetDocumentLocationV3Errors, GetDocumentLocationV3Response, GetDocumentLocationV3Responses, GetDocumentPermissionsResponseDataV2, GetDocumentPermissionsTokenData, GetDocumentPermissionsTokenError, GetDocumentPermissionsTokenErrors, GetDocumentPermissionsTokenResponse, GetDocumentPermissionsTokenResponses, GetDocumentPermissionsV2Data, GetDocumentPermissionsV2Error, GetDocumentPermissionsV2Errors, GetDocumentPermissionsV2Response, GetDocumentPermissionsV2Responses, GetDocumentProcessingResult, GetDocumentProcessingResultData, GetDocumentProcessingResultError, GetDocumentProcessingResultErrors, GetDocumentProcessingResultResponse, GetDocumentProcessingResultResponse2, GetDocumentProcessingResultResponses, GetDocumentResponse, GetDocumentResponse2, GetDocumentResponseData, GetDocumentResponses, GetDocumentSearchResponse, GetDocumentShortIdData, GetDocumentShortIdError, GetDocumentShortIdErrors, GetDocumentShortIdResponse, GetDocumentShortIdResponses, GetDocumentsResponse, GetDocumentTeamShareData, GetDocumentTeamShareError, GetDocumentTeamShareErrors, GetDocumentTeamShareResponse, GetDocumentTeamShareResponses, GetDocumentTextContentData, GetDocumentTextContentErrors, GetDocumentTextContentResponse, GetDocumentTextContentResponses, GetDocumentUserAccessLevelResponse, GetDocumentVersionData, GetDocumentVersionError, GetDocumentVersionErrors, GetDocumentVersionResponse, GetDocumentVersionResponses, GetDocumentViewsHandlerData, GetDocumentViewsHandlerError, GetDocumentViewsHandlerErrors, GetDocumentViewsHandlerResponse, GetDocumentViewsHandlerResponses, GetEmailFollowupData, GetEmailFollowupError, GetEmailFollowupErrors, GetEmailFollowupResponse, GetEmailFollowupResponses, GetEntityPermissionData, GetEntityPermissionErrors, GetEntityPermissionResponse, GetEntityPermissionResponses, GetForeignEntityBySourceData, GetForeignEntityBySourceError, GetForeignEntityBySourceErrors, GetForeignEntityBySourceResponse, GetForeignEntityBySourceResponses, GetForeignEntityData, GetForeignEntityError, GetForeignEntityErrors, GetForeignEntityResponse, GetForeignEntityResponses, GetFormData, GetFormError, GetFormErrors, GetFormPermissionsData, GetFormPermissionsError, GetFormPermissionsErrors, GetFormPermissionsResponse, GetFormPermissionsResponses, GetFormResponse, GetFormResponses, GetFormResponseSummaryData, GetFormResponseSummaryError, GetFormResponseSummaryErrors, GetFormResponseSummaryResponse, GetFormResponseSummaryResponses, GetFormTallyData, GetFormTallyError, GetFormTallyErrors, GetFormTallyResponse, GetFormTallyResponses, GetGithubPullRequestChangesData, GetGithubPullRequestChangesError, GetGithubPullRequestChangesErrors, GetGithubPullRequestChangesPatchData, GetGithubPullRequestChangesPatchError, GetGithubPullRequestChangesPatchErrors, GetGithubPullRequestChangesPatchResponse, GetGithubPullRequestChangesPatchResponses, GetGithubPullRequestChangesResponse, GetGithubPullRequestChangesResponses, GetGithubPullRequestData, GetGithubPullRequestError, GetGithubPullRequestErrors, GetGithubPullRequestFacetsData, GetGithubPullRequestFacetsError, GetGithubPullRequestFacetsErrors, GetGithubPullRequestFacetsResponse, GetGithubPullRequestFacetsResponses, GetGithubPullRequestResponse, GetGithubPullRequestResponses, GetGithubPullRequestTasksData, GetGithubPullRequestTasksError, GetGithubPullRequestTasksErrors, GetGithubPullRequestTasksResponse, GetGithubPullRequestTasksResponses, GetHarnessPairingData, GetHarnessPairingError, GetHarnessPairingErrors, GetHarnessPairingResponse, GetHarnessPairingResponses, GetHistoryHandlerData, GetHistoryHandlerError, GetHistoryHandlerErrors, GetHistoryHandlerResponse, GetHistoryHandlerResponses, GetInitiativeData, GetInitiativeError, GetInitiativeErrors, GetInitiativeResponse, GetInitiativeResponses, GetInstructionsDocumentResponse, GetInstructionsHandlerData, GetInstructionsHandlerError, GetInstructionsHandlerErrors, GetInstructionsHandlerResponse, GetInstructionsHandlerResponses, GetItemsSoupData, GetItemsSoupError, GetItemsSoupErrors, GetItemsSoupResponse, GetItemsSoupResponses, GetLocationHandlerData, GetLocationHandlerError, GetLocationHandlerErrors, GetLocationHandlerResponse, GetLocationHandlerResponses, GetMyFormResponseData, GetMyFormResponseError, GetMyFormResponseErrors, GetMyFormResponseResponse, GetMyFormResponseResponses, GetOrCreateAction, GetOrCreateCallData, GetOrCreateCallError, GetOrCreateCallErrors, GetOrCreateCallResponse, GetOrCreateCallResponses, GetOrCreateChannelResponse, GetOrCreateDmData, GetOrCreateDmError, GetOrCreateDmErrors, GetOrCreateDmRequest, GetOrCreateDmResponse, GetOrCreateDmResponses, GetOrCreatePrivateData, GetOrCreatePrivateError, GetOrCreatePrivateErrors, GetOrCreatePrivateRequest, GetOrCreatePrivateResponse, GetOrCreatePrivateResponses, GetPendingProjectsHandlerData, GetPendingProjectsHandlerError, GetPendingProjectsHandlerErrors, GetPendingProjectsHandlerResponse, GetPendingProjectsHandlerResponses, GetPinsHandlerData, GetPinsHandlerError, GetPinsHandlerErrors, GetPinsHandlerResponse, GetPinsHandlerResponses, GetPinsResponse, GetProjectContentHandlerData, GetProjectContentHandlerError, GetProjectContentHandlerErrors, GetProjectContentHandlerResponse, GetProjectContentHandlerResponses, GetProjectContentResponse, GetProjectHandlerData, GetProjectHandlerError, GetProjectHandlerErrors, GetProjectHandlerResponse, GetProjectHandlerResponses, GetProjectPermissionsV2Data, GetProjectPermissionsV2Error, GetProjectPermissionsV2Errors, GetProjectPermissionsV2Response, GetProjectPermissionsV2Responses, GetProjectResponse, GetProjectResponseData, GetProjectsHandlerData, GetProjectsHandlerError, GetProjectsHandlerErrors, GetProjectsHandlerResponse, GetProjectsHandlerResponses, GetProjectsResponse, GetProjectUserAccessLevelData, GetProjectUserAccessLevelError, GetProjectUserAccessLevelErrors, GetProjectUserAccessLevelResponse, GetProjectUserAccessLevelResponses, GetRingStatusData, GetRingStatusError, GetRingStatusErrors, GetRingStatusResponse, GetRingStatusResponses, GetSelfBotData, GetSelfBotError, GetSelfBotErrors, GetSelfBotResponse, GetSelfBotResponses, GetSelfHarnessData, GetSelfHarnessError, GetSelfHarnessErrors, GetSelfHarnessResponse, GetSelfHarnessResponses, GetSlackImportData, GetSlackImportErrors, GetSlackImportResponse, GetSlackImportResponses, GetSystemSkillsHandlerData, GetSystemSkillsHandlerError, GetSystemSkillsHandlerErrors, GetSystemSkillsHandlerResponse, GetSystemSkillsHandlerResponses, GetUserDocumentsHandlerData, GetUserDocumentsHandlerError, GetUserDocumentsHandlerErrors, GetUserDocumentsHandlerResponse, GetUserDocumentsHandlerResponses, GetUserDocumentViewLocationData, GetUserDocumentViewLocationError, GetUserDocumentViewLocationErrors, GetUserDocumentViewLocationResponse, GetUserDocumentViewLocationResponses, GetUserHistoryResponse, GetViewsHandlerData, GetViewsHandlerError, GetViewsHandlerErrors, GetViewsHandlerResponse, GetViewsHandlerResponses, GetWebhookData, GetWebhookError, GetWebhookErrors, GetWebhookResponse, GetWebhookResponses, GithubLabelFacet, GithubPullRequest, GithubPullRequestChangesPatchResponse, GithubPullRequestChangesResponse, GithubPullRequestCheckRun, GithubPullRequestComment, GithubPullRequestFacets, GithubPullRequestLabel, GithubPullRequestReview, GithubPullRequestReviewDecision, GithubPullRequestReviewState, GithubPullRequestsResponse, GithubPullRequestTasks, GithubPullRequestTasksRequest, GithubPullRequestTasksResponse, GithubPullRequestUser, GithubRepositoryFacet, GithubUserFacet, GitRefDto, GroupedInitialParams, GroupedPageParams, GroupedSoupGroupPage, GroupedSoupInitialPage, GroupedSoupPage, GroupedSoupSort, GuestCallChatPostData, GuestCallChatPostErrors, GuestCallChatPostResponse, GuestCallChatPostResponses, GuestCallChatReadData, GuestCallChatReadErrors, GuestCallChatReadResponse, GuestCallChatReadResponses, GuestChatMessage, GuestChatPage, GuestChatPost, GuestId, GuestJoinRequest, GuestPolicy, HandlerData, HandlerError, HandlerErrors, HandlerResponse, HandlerResponses, Harness, HarnessAgent, HarnessId, HarnessOwner, HarnessSession, HashMap, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, HighlightType, ImportCounters, ImportDatabaseTableData, ImportDatabaseTableError, ImportDatabaseTableErrors, ImportDatabaseTableResponse, ImportDatabaseTableResponses, ImportedAuthor, ImportError, ImportLimits, ImportPage, ImportProgress, ImportTable, ImportWarning, InferColumnTypeOutcome, InferColumnTypeRequest, InferDatabaseColumnTypeData, InferDatabaseColumnTypeError, InferDatabaseColumnTypeErrors, InferDatabaseColumnTypeResponse, InferDatabaseColumnTypeResponses, InFlightTurnSummary, IngestTranscriptData, IngestTranscriptError, IngestTranscriptErrors, IngestTranscriptResponses, InitializeUserDocumentsData, InitializeUserDocumentsError, InitializeUserDocumentsErrors, InitializeUserDocumentsResponse, InitializeUserDocumentsResponses, InitialPropertyValue, InitiativeDetail, InitiativeFilters, InitiativeId, InitiativeList, InitiativeSummary, InputReceivedMetadata, InstallSyncData, InstallSyncErrors, InteractionReason, InvalidDatabaseWebhookPayloadResponse, InviteMeetingRequest, InviteMeetingUsersRequest, Item, ItemWithUserAccessLevel, JobId, JobProcessingResultHandlerData, JobProcessingResultHandlerError, JobProcessingResultHandlerErrors, JobProcessingResultHandlerResponse, JobProcessingResultHandlerResponses, JobStatus, JoinChannelByCodeData, JoinChannelByCodeError, JoinChannelByCodeErrors, JoinChannelByCodeResponses, JoinChannelData, JoinChannelError, JoinChannelErrors, JoinChannelResponses, KeySegment, Lane, LaneKey, LatestMessage, LayoutProblem, LeaveCallResponse, LeaveChannelData, LeaveChannelError, LeaveChannelErrors, LeaveChannelResponses, LeaveOrEndCallData, LeaveOrEndCallError, LeaveOrEndCallErrors, LeaveOrEndCallResponse, LeaveOrEndCallResponses, LinkedAccount, LinkedAccountData, LinkedAccountResponse, LinkedAccountResponses, LinkedAccountState, LinkedAccountView, LinkedAdoptData, LinkedAdoptGroup, LinkedAdoptResponse, LinkedAdoptResponses, LinkedAttachment, LinkedAttachmentState, LinkedBackfill, LinkedBackfillState, LinkedCancelPairingData, LinkedCancelPairingResponse, LinkedCancelPairingResponses, LinkedCannotAdd, LinkedCapabilities, LinkedChat, LinkedChatKind, LinkedChats, LinkedChatsData, LinkedChatsResponse, LinkedChatsResponses, LinkedCommunityReference, LinkedConfigurationData, LinkedConfigurationResponse, LinkedConfigurationResponses, LinkedConnect, LinkedConnectData, LinkedConnectResponse, LinkedConnectResponses, LinkedDeliveryData, LinkedDeliveryResponse, LinkedDeliveryResponses, LinkedDeliveryState, LinkedDetachData, LinkedDetachResponse, LinkedDetachResponses, LinkedDisconnect, LinkedDisconnectData, LinkedDisconnectRequest, LinkedDisconnectResponse, LinkedDisconnectResponses, LinkedFeatures, LinkedGroupInfo, LinkedGroupReference, LinkedIdentity, LinkedMediaKind, LinkedMediaPresentation, LinkedMessageAttachments, LinkedMessageAttachmentsData, LinkedMessageAttachmentsResponse, LinkedMessageAttachmentsResponses, LinkedMutation, LinkedPairing, LinkedPairingData, LinkedPairingResponse, LinkedPairingResponses, LinkedPairingState, LinkedPairState, LinkedParticipant, LinkedPasskeyData, LinkedPasskeyResponse, LinkedPasskeyResponses, LinkedReplyBlock, LinkedReplyContent, LinkedReplyData, LinkedReplyErrors, LinkedReplyResponse, LinkedReplyResponses, LinkedSendProgress, LinkedSendReply, LinkedSharedGroupReference, LinkedUploadData, LinkedUploadedAttachment, LinkedUploadRequest, LinkedUploadResponse, LinkedUploadResponses, LinkShare, ListAccessibleFormsData, ListAccessibleFormsError, ListAccessibleFormsErrors, ListAccessibleFormsResponse, ListAccessibleFormsResponses, ListAgentsData, ListAgentsError, ListAgentsErrors, ListAgentsResponse, ListAgentsResponses, ListBotChannelsData, ListBotChannelsError, ListBotChannelsErrors, ListBotChannelsResponse, ListBotChannelsResponses, ListChannelLabelsData, ListChannelLabelsError, ListChannelLabelsErrors, ListChannelLabelsResponse, ListChannelLabelsResponses, ListCompanyContactsData, ListCompanyContactsError, ListCompanyContactsErrors, ListCompanyContactsResponse, ListCompanyContactsResponses, ListCrmPipelinesData, ListCrmPipelinesResponse, ListCrmPipelinesResponses, ListDatabaseColumnCastsData, ListDatabaseColumnCastsError, ListDatabaseColumnCastsErrors, ListDatabaseColumnCastsResponse, ListDatabaseColumnCastsResponses, ListDatabasesData, ListDatabasesError, ListDatabasesErrors, ListDatabasesResponse, ListDatabasesResponses, ListDatabaseWebhooksData, ListDatabaseWebhooksError, ListDatabaseWebhooksErrors, ListDatabaseWebhooksResponse, ListDatabaseWebhooksResponse2, ListDatabaseWebhooksResponses, ListedDatabase, ListedForm, ListEmailRemindersData, ListEmailRemindersError, ListEmailRemindersErrors, ListEmailRemindersResponse, ListEmailRemindersResponses, ListFavoritesData, ListFavoritesError, ListFavoritesErrors, ListFavoritesResponse, ListFavoritesResponses, ListFormsData, ListFormsError, ListFormsErrors, ListFormsResponse, ListFormsResponses, ListHarnessAgentsData, ListHarnessAgentsError, ListHarnessAgentsErrors, ListHarnessAgentsResponse, ListHarnessAgentsResponses, ListHarnessesData, ListHarnessesError, ListHarnessesErrors, ListHarnessesResponse, ListHarnessesResponses, ListHarnessSessionsData, ListHarnessSessionsError, ListHarnessSessionsErrors, ListHarnessSessionsResponse, ListHarnessSessionsResponses, ListInitiativesData, ListInitiativesError, ListInitiativesErrors, ListInitiativesResponse, ListInitiativesResponses, ListJoinRequestsData, ListJoinRequestsError, ListJoinRequestsErrors, ListJoinRequestsResponse, ListJoinRequestsResponses, ListOccurrencesData, ListOccurrencesErrors, ListOccurrencesResponse, ListOccurrencesResponses, ListSlackImportsData, ListSlackImportsResponse, ListSlackImportsResponses, ListTeamCalendarData, ListTeamCalendarResponse, ListTeamCalendarResponses, ListTeamOutOfOfficeData, ListTeamOutOfOfficeErrors, ListTeamOutOfOfficeResponse, ListTeamOutOfOfficeResponses, ListUserApiKeysData, ListUserApiKeysError, ListUserApiKeysErrors, ListUserApiKeysResponse, ListUserApiKeysResponses, ListWebhooksData, ListWebhooksError, ListWebhooksErrors, ListWebhooksResponse, ListWebhooksResponse2, ListWebhooksResponses, LocationResponseData, LocationResponseV3, MacroUserIdStr, MarkRead, Meeting, MeetingCancelData, MeetingCancelError, MeetingCancelErrors, MeetingCancelPreparationData, MeetingCancelPreparationError, MeetingCancelPreparationErrors, MeetingCancelPreparationResponse, MeetingCancelPreparationResponses, MeetingCancelResponse, MeetingCancelResponses, MeetingCreateData, MeetingCreateError, MeetingCreateErrors, MeetingCreateResponse, MeetingCreateResponses, MeetingGuestJoinData, MeetingGuestJoinError, MeetingGuestJoinErrors, MeetingGuestJoinResponse, MeetingGuestJoinResponses, MeetingGuestParticipantsData, MeetingGuestParticipantsError, MeetingGuestParticipantsErrors, MeetingGuestParticipantsResponse, MeetingGuestParticipantsResponses, MeetingInviteData, MeetingInviteError, MeetingInviteErrors, MeetingInvitePermissions, MeetingInvitePermissionsData, MeetingInvitePermissionsError, MeetingInvitePermissionsErrors, MeetingInvitePermissionsResponse, MeetingInvitePermissionsResponses, MeetingInviteResponse, MeetingInviteResponses, MeetingInviteUsersData, MeetingInviteUsersError, MeetingInviteUsersErrors, MeetingInviteUsersResponse, MeetingInviteUsersResponses, MeetingJoinData, MeetingJoinError, MeetingJoinErrors, MeetingJoinResponse, MeetingJoinResponses, MeetingLeaveData, MeetingLeaveError, MeetingLeaveErrors, MeetingLeaveResponse, MeetingLeaveResponses, MeetingListActiveData, MeetingListActiveError, MeetingListActiveErrors, MeetingListActiveResponse, MeetingListActiveResponses, MeetingListData, MeetingListError, MeetingListErrors, MeetingListResponse, MeetingListResponses, MeetingLookupData, MeetingLookupError, MeetingLookupErrors, MeetingLookupResponse, MeetingLookupResponses, MeetingParticipant, MeetingParticipants, MeetingParticipantsData, MeetingParticipantsError, MeetingParticipantsErrors, MeetingParticipantsResponse, MeetingParticipantsResponses, MeetingPreparation, MeetingPrepareData, MeetingPrepareError, MeetingPrepareErrors, MeetingPrepareResponse, MeetingPrepareResponses, MeetingShareData, MeetingShareError, MeetingShareErrors, MeetingShareResponse, MeetingShareResponses, MeetingsResponse, MeetingToken, MeetingUpdateData, MeetingUpdateError, MeetingUpdateErrors, MeetingUpdateResponse, MeetingUpdateResponses, MentionPreviewsData, MentionPreviewsErrors, MentionPreviewsResponse, MentionPreviewsResponses, Message, MessageAttachment, MessageAttachmentCreatedMetadata, MessageAttachmentRemovedMetadata, MessageChange, MessageCursor, MessageDeletedMetadata, MessageDirection, MessageEvent, MessageEventAttachment, MessageListItem, MessageMentionedMetadata, MessagePage, MessageParent, MessagePatch, MessagePatchedMetadata, MessagePostedMetadata, MessageThread, MessageThreadPreview, MessageTimelineData, MessageTimelineEntriesData, MessageTimelineEntriesResponse, MessageTimelineEntriesResponses, MessageTimelineEntry, MessageTimelinePage, MessageTimelineQuery, MessageTimelineResponse, MessageTimelineResponses, MessageTopicEvent, MyResponse, NewAttachment, NewColumn, NewOption, NewThreadAnchor, NewView, NotificationFilters, NotificationState, NumberOperator, OpBatch, Operator, OpRefusalResponse, OpResult, OptionId, OptionRef, PairingDetails, Params, ParticipantRole, PatchBotRequest, PatchChannelData, PatchChannelError, PatchChannelErrors, PatchChannelRequest, PatchChannelResponse, PatchChannelResponses, PatchMessageNotificationPolicy, PatchProjectRequestV2, PatchThreadRequestV2, PatchViewHandlerData, PatchViewHandlerError, PatchViewHandlerErrors, PatchViewHandlerResponses, PatchWebhookData, PatchWebhookError, PatchWebhookErrors, PatchWebhookRequest, PatchWebhookResponse, PatchWebhookResponses, PdfAnchor, PdfAnchorId, PdfHighlightAnchor, PdfHighlightAnchorRequest, PdfHighlightRect, PdfHighlightRectAnchorRequest, PdfPlaceableCommentAnchor, PendingClaimResponse, PermanentlyDeleteDocumentData, PermanentlyDeleteDocumentError, PermanentlyDeleteDocumentErrors, PermanentlyDeleteDocumentResponse, PermanentlyDeleteDocumentResponses, PermanentlyDeleteProjectData, PermanentlyDeleteProjectError, PermanentlyDeleteProjectErrors, PermanentlyDeleteProjectResponse, PermanentlyDeleteProjectResponses, PinnedItem, PinRequest, Pipeline, PipelineRecordType, PipelineSharing, PostActivityData, PostActivityError, PostActivityErrors, PostActivityRequest, PostActivityResponse, PostActivityResponses, PostChannelBotWebhookData, PostChannelBotWebhookError, PostChannelBotWebhookErrors, PostChannelBotWebhookResponse, PostChannelBotWebhookResponses, PostGroupedSoupAstGroupPageRequest, PostGroupedSoupAstInitialRequest, PostGroupedSoupAstRequest, PostItemsSoupAstData, PostItemsSoupAstError, PostItemsSoupAstErrors, PostItemsSoupAstGroupedData, PostItemsSoupAstGroupedError, PostItemsSoupAstGroupedErrors, PostItemsSoupAstGroupedResponse, PostItemsSoupAstGroupedResponses, PostItemsSoupAstResponse, PostItemsSoupAstResponses, PostItemsSoupData, PostItemsSoupError, PostItemsSoupErrors, PostItemsSoupResponse, PostItemsSoupResponses, PostMessage, PostMessageNotificationPolicy, PostSoupAstRequest, PostSoupRequest, PresaveDocumentHandlerData, PresaveDocumentHandlerError, PresaveDocumentHandlerErrors, PresaveDocumentHandlerResponse, PresaveDocumentHandlerResponses, PreSaveDocumentRequest, PreSaveDocumentResponse, PreSaveDocumentResponseData, PresenceOperator, PresignedUrl, PreviewSmartTagData, PreviewSmartTagError, PreviewSmartTagErrors, PreviewSmartTagResponse, PreviewSmartTagResponses, Project, ProjectDeleteResponseData, ProjectDocumentStatus, ProjectFilters, ProjectPreview, ProjectPreviewData, PropertyDefinition, PropertyDefinitionWithOptions, PropertyFilter, PropertyInput, PropertyOption, PropertyOptionValue, PropertyOwner, PropertyValue, PutCrmTeamSettingsData, PutCrmTeamSettingsError, PutCrmTeamSettingsErrors, PutCrmTeamSettingsResponse, PutCrmTeamSettingsResponses, PutCrmTeamStagesData, PutCrmTeamStagesError, PutCrmTeamStagesErrors, PutCrmTeamStagesResponse, PutCrmTeamStagesResponses, PutFormLayoutData, PutFormLayoutError, PutFormLayoutErrors, PutFormLayoutResponse, PutFormLayoutResponses, QueryCrmPipelineRowsData, QueryCrmPipelineRowsResponse, QueryCrmPipelineRowsResponses, QueryDatabasesData, QueryDatabasesError, QueryDatabasesErrors, QueryDatabasesResponse, QueryDatabasesResponses, QueryDefinition, QuestionLayout, QuestionOption, QuestionTally, ReactionInput, RecentlyDeletedData, RecentlyDeletedError, RecentlyDeletedErrors, RecentlyDeletedResponse, RecentlyDeletedResponseData, RecentlyDeletedResponses, RegisterSlackImportUploadsData, RegisterSlackImportUploadsErrors, RegisterSlackImportUploadsResponse, RegisterSlackImportUploadsResponses, RegisterUploads, RemoveBotFromChannelByBotData, RemoveBotFromChannelByBotError, RemoveBotFromChannelByBotErrors, RemoveBotFromChannelByBotResponse, RemoveBotFromChannelByBotResponses, RemoveFavoriteByEntityData, RemoveFavoriteByEntityError, RemoveFavoriteByEntityErrors, RemoveFavoriteByEntityResponses, RemoveParticipantsData, RemoveParticipantsError, RemoveParticipantsErrors, RemoveParticipantsRequest, RemoveParticipantsResponses, RemovePinHandlerData, RemovePinHandlerError, RemovePinHandlerErrors, RemovePinHandlerResponse, RemovePinHandlerResponses, RenameChannelLabelData, RenameChannelLabelError, RenameChannelLabelErrors, RenameChannelLabelRequest, RenameChannelLabelResponse, RenameChannelLabelResponses, RenameCrmPipelineData, RenameCrmPipelineResponse, RenameCrmPipelineResponses, RenamePipeline, ReorderFavoritesData, ReorderFavoritesError, ReorderFavoritesErrors, ReorderFavoritesRequest, ReorderFavoritesResponses, ReorderPinRequest, ReorderPinsHandlerData, ReorderPinsHandlerError, ReorderPinsHandlerErrors, ReorderPinsHandlerResponse, ReorderPinsHandlerResponses, ReplaceCrmStagesRequest, RequestAccess, RequestedHarnessScope, RequestedLayout, RequestStatus, RequestToJoinData, RequestToJoinError, RequestToJoinErrors, RequestToJoinResponse, RequestToJoinResponses, ResetCrmTeamStagesData, ResetCrmTeamStagesError, ResetCrmTeamStagesErrors, ResetCrmTeamStagesResponse, ResetCrmTeamStagesResponses, ResolveRequest, ResponseStatus, ResponseSummary, ResultColumn, ResultSet, RevertDeleteDocumentData, RevertDeleteDocumentError, RevertDeleteDocumentErrors, RevertDeleteDocumentResponse, RevertDeleteDocumentResponses, RevertDeleteProjectData, RevertDeleteProjectError, RevertDeleteProjectErrors, RevertDeleteProjectResponse, RevertDeleteProjectResponses, RingStatus, RingStatusResponse, RowChange, RowChangeKind, RowChanges, RowHistoryEntry, RowHistoryResponse, RowId, RowsChange, RowsResult, S3ObjectInfo, SaveBomPart, SaveDatabaseQueryData, SaveDatabaseQueryError, SaveDatabaseQueryErrors, SaveDatabaseQueryResponse, SaveDatabaseQueryResponses, SaveDocumentHandlerData, SaveDocumentHandlerError, SaveDocumentHandlerErrors, SaveDocumentHandlerResponse, SaveDocumentHandlerResponses, SaveDocumentRequest, SaveDocumentResponse, SaveDocumentResponseData, SavedQuery, SaveQueryRequest, SearchContactsData, SearchContactsError, SearchContactsErrors, SearchContactsResponse, SearchContactsResponse2, SearchContactsResponses, SearchState, SectionCount, SessionDeletedMetadata, SessionIdentity, SessionMentionedMetadata, SessionOpenedMetadata, SessionRenamedMetadata, SessionSettledMetadata, SessionSource, SessionStoppedMetadata, SetChannelLabelData, SetChannelLabelError, SetChannelLabelErrors, SetChannelLabelRequest, SetChannelLabelResponse, SetChannelLabelResponses, SetChannelPictureData, SetChannelPictureError, SetChannelPictureErrors, SetChannelPictureRequest, SetChannelPictureResponse, SetChannelPictureResponses, SetCompanyHiddenData, SetCompanyHiddenError, SetCompanyHiddenErrors, SetCompanyHiddenRequest, SetCompanyHiddenResponse, SetCompanyHiddenResponses, SetCompanyNameRequest, SetContactHiddenData, SetContactHiddenError, SetContactHiddenErrors, SetContactHiddenRequest, SetContactHiddenResponse, SetContactHiddenResponses, SetContactNameRequest, SetCrmCompanyNameData, SetCrmCompanyNameError, SetCrmCompanyNameErrors, SetCrmCompanyNameResponse, SetCrmCompanyNameResponses, SetCrmContactNameData, SetCrmContactNameError, SetCrmContactNameErrors, SetCrmContactNameResponse, SetCrmContactNameResponses, SetDirectAccess, SetDocumentTeamShareData, SetDocumentTeamShareError, SetDocumentTeamShareErrors, SetDocumentTeamShareRequest, SetDocumentTeamShareResponse, SetDocumentTeamShareResponses, SetEmailFollowupData, SetEmailFollowupError, SetEmailFollowupErrors, SetEmailFollowupResponse, SetEmailFollowupResponses, SetEmailSyncData, SetEmailSyncError, SetEmailSyncErrors, SetEmailSyncRequest, SetEmailSyncResponse, SetEmailSyncResponses, SetOperator, SetPropertyValue, Sha256Digest, ShareCrmPipelineData, ShareCrmPipelineResponse, ShareCrmPipelineResponses, ShareDatabaseAwarenessData, ShareDatabaseAwarenessError, ShareDatabaseAwarenessErrors, ShareDatabaseAwarenessResponse, ShareDatabaseAwarenessResponses, SharedEmailFilter, ShareEntity, ShareEntityType, SharePermissionV2, SharePipeline, ShortIdResponse, SimpleMention, SimpleSaveData, SimpleSaveError, SimpleSaveErrors, SimpleSaveResponse, SimpleSaveResponses, SkippedCell, SlackCompleteRequest, SlackCreateRequest, SlackRegisterRequest, SlackTimestamp, SlackUserId, SmartTagChannelMatch, SmartTagPreview, SortDirection, SortKey, SoupAgentSessionSoupPropertiesField, SoupApiItem, SoupApiSort, SoupApiSortDirection, SoupAttachment, SoupCalendarEventSoupPropertiesField, SoupCalendarEventTime, SoupCallRecordGuest, SoupCallRecordParticipant, SoupCallRecordSoupPropertiesField, SoupChannel, SoupChannelThread, SoupChatSoupPropertiesField, SoupContact, SoupCountedReaction, SoupCrmCompanySoupPropertiesField, SoupCrmContactSoupPropertiesField, SoupCrmDomain, SoupDatabaseRowSoupPropertiesField, SoupDocumentSoupPropertiesField, SoupDocumentSubType, SoupEmailThreadPreview, SoupEnrichedEmailThreadPreviewSoupPropertiesField, SoupForeignEntity, SoupInitiativeSoupPropertiesField, SoupItem, SoupLabel, SoupLabelListVisibility, SoupLabelType, SoupMessageAttachment, SoupMessageListVisibility, SoupMessageSender, SoupMessageSenderType, SoupPage, SoupProjectSoupPropertiesField, SoupPropertiesField, SoupProperty, SoupThreadInfo, SoupThreadReply, SourceBinding, SourceId, SourceIdentity, SqlCell, SqlEntityKind, SqlOutcome, SqlOutcomeKind, SqlSelectOption, SqlStatement, StarterDatabase, StarterDocumentsResponse, StorageRow, StorageRows, StorageRowsQuery, StoredGithubPullRequest, StreamEventsData, StreamEventsError, StreamEventsErrors, StreamEventsResponse, StreamEventsResponses, String, Submission, SubmissionOutcome, SubmitFormResponseData, SubmitFormResponseError, SubmitFormResponseErrors, SubmitFormResponseResponse, SubmitFormResponseResponses, SuccessResponse, SurfaceState, SyncServiceVersionId, SystemSkillSummary, Table, TableChange, TableChanged, TableChanges, TableDetail, TableId, TableResult, TableVersion, TagFilterMode, TakenId, TallyBucket, TallyValue, TaskFilters, TeamCalendarContent, TeamCalendarCoverage, TeamCalendarDetails, TeamCalendarItem, TeamCalendarMember, TeamCalendarPage, TeamCalendarSharing, TeamOutOfOfficeItem, TeamOutOfOfficeResponse, TeamRole, TextOperator, ThreadAnchor, ThreadOrigin, ThreadPatch, ThreadState, TimelineActivity, ToggleShareWithTeamData, ToggleShareWithTeamError, ToggleShareWithTeamErrors, ToggleShareWithTeamResponse, ToggleShareWithTeamResponses, TouchedColumn, TouchedRow, TranscribeDictationData, TranscribeDictationError, TranscribeDictationErrors, TranscribeDictationResponse, TranscribeDictationResponses, TranscribeResponse, TranscriptSegmentRequest, TrashCrmPipelineData, TrashCrmPipelineResponse, TrashCrmPipelineResponses, TrashPipeline, TurnEndedMetadata, TurnStartedMetadata, TurnSummary, TypedSuccessResponse, TypedSuccessResponseGetDocumentResponseData, TypingInput, UndoChangeResponse, UndoDatabaseChangeData, UndoDatabaseChangeError, UndoDatabaseChangeErrors, UndoDatabaseChangeResponse, UndoDatabaseChangeResponses, UndoOutcome, UndoRefusal, UnlockedBooking, UpdateAgentData, UpdateAgentError, UpdateAgentErrors, UpdateAgentRequest, UpdateAgentResponse, UpdateAgentResponses, UpdateChannelSharePermission, UpdateCrmPipelinePermissionsData, UpdateCrmPipelinePermissionsResponse, UpdateCrmPipelinePermissionsResponses, UpdateCrmTeamSettingsRequest, UpdateDatabasePermissionsData, UpdateDatabasePermissionsError, UpdateDatabasePermissionsErrors, UpdateDatabasePermissionsResponse, UpdateDatabasePermissionsResponses, UpdateForm, UpdateFormData, UpdateFormError, UpdateFormErrors, UpdateFormPermissionsData, UpdateFormPermissionsError, UpdateFormPermissionsErrors, UpdateFormPermissionsResponse, UpdateFormPermissionsResponses, UpdateFormResponse, UpdateFormResponses, UpdateInitiativeData, UpdateInitiativeError, UpdateInitiativeErrors, UpdateInitiativeRequest, UpdateInitiativeResponse, UpdateInitiativeResponses, UpdateMeetingRequest, UpdateOperation, UpdateSharePermissionRequestV2, UploadDescriptor, UploadDocumentStatus, UploadExtractFolderHandlerData, UploadExtractFolderHandlerError, UploadExtractFolderHandlerErrors, UploadExtractFolderHandlerResponse, UploadExtractFolderHandlerResponses, UploadExtractFolderRequest, UploadFolderHandlerData, UploadFolderHandlerError, UploadFolderHandlerErrors, UploadFolderHandlerResponse, UploadFolderHandlerResponses, UploadFolderRequest, UploadGrant, UploadId, UpsertHistoryHandlerData, UpsertHistoryHandlerError, UpsertHistoryHandlerErrors, UpsertHistoryHandlerResponse, UpsertHistoryHandlerResponses, UpsertUserDocumentViewLocationData, UpsertUserDocumentViewLocationError, UpsertUserDocumentViewLocationErrors, UpsertUserDocumentViewLocationRequest, UpsertUserDocumentViewLocationResponse, UpsertUserDocumentViewLocationResponses, UserApiKeyId, UserApiKeyInfo, UserApiKeysList, UserDocumentsResponse, UserDocumentViewLocation, UserDocumentViewLocationResponse, UserPinsResponse, UserViewsResponse, ValidateDocumentPermissionsTokenData, ValidateDocumentPermissionsTokenError, ValidateDocumentPermissionsTokenErrors, ValidateDocumentPermissionsTokenResponse, ValidateDocumentPermissionsTokenResponses, ValidateWebhookData, ValidateWebhookError, ValidateWebhookErrors, ValidateWebhookResponse, ValidateWebhookResponse2, ValidateWebhookResponses, Vec, VersionedTable, View, ViewChange, ViewColumn, ViewerCapabilities, ViewLayout, ViewPatch, ViewPosition, ViewPositionsResponse, ViewQuery, ViewResult, ViewsResponse, WaitingForInputMetadata, Webhook, WebhookEvent, WebhookFilter, WebhookScope, WebhookStatus, WebhookValidationTestEvent, WhatsAppCall, WhatsAppCallOutcome, WhatsAppContactCard, WhatsAppContacts, WhatsAppEvent, WhatsappGroupData, WhatsAppGroupDetail, WhatsAppGroupMessage, WhatsAppGroupMessages, WhatsappGroupMessagesData, WhatsappGroupMessagesResponse, WhatsappGroupMessagesResponses, WhatsappGroupPermissionsData, WhatsappGroupPermissionsResponse, WhatsappGroupPermissionsResponses, WhatsAppGroupReaction, WhatsappGroupReadData, WhatsappGroupReadResponse, WhatsappGroupReadResponses, WhatsappGroupResponse, WhatsappGroupResponses, WhatsappGroupsData, WhatsAppGroupSender, WhatsappGroupSendsData, WhatsappGroupSendsResponse, WhatsappGroupSendsResponses, WhatsappGroupsResponse, WhatsappGroupsResponses, WhatsAppGroupSummary, WhatsappGroupUpdatePermissionsData, WhatsappGroupUpdatePermissionsResponse, WhatsappGroupUpdatePermissionsResponses, WhatsAppLocation, WhatsAppMention, WhatsAppMessageKind, WhatsAppPersonRef, WhatsAppPoll, WhatsAppPollOption, WhatsAppRichContent, WhatsAppSystemAction, WhatsAppSystemLine, Widget, WithCallId, WithChannelId, WithDocumentId, WithProjectId } from './types.gen';diff --git a/packages/sdk/generated/storage/sdk.gen.ts b/packages/sdk/generated/storage/sdk.gen.tsindex 216fde3060..9c7e0e4976 100644--- a/packages/sdk/generated/storage/sdk.gen.ts+++ b/packages/sdk/generated/storage/sdk.gen.ts@@ -2,7 +2,7 @@import { type Client, type ClientMeta, formDataBodySerializer, type Options as Options2, type RequestResult, type ServerSentEventsResult, type TDataShape } from './client';import { client } from './client.gen';-import type { AccessRequestsCancelData, AccessRequestsCancelErrors, AccessRequestsCancelResponses, AccessRequestsDirectData, AccessRequestsDirectErrors, AccessRequestsDirectResponses, AccessRequestsRemoveDirectData, AccessRequestsRemoveDirectErrors, AccessRequestsRemoveDirectResponses, AccessRequestsResolveData, AccessRequestsResolveErrors, AccessRequestsResolveResponses, AccessRequestsSetDirectData, AccessRequestsSetDirectErrors, AccessRequestsSetDirectResponses, AccessRequestsStateData, AccessRequestsStateErrors, AccessRequestsStateResponses, AccessRequestsSubmitData, AccessRequestsSubmitErrors, AccessRequestsSubmitResponses, AddFavoriteData, AddFavoriteErrors, AddFavoriteResponses, AddParticipantsData, AddParticipantsErrors, AddParticipantsResponses, AddPinHandlerData, AddPinHandlerErrors, AddPinHandlerResponses, ApplyCrmPipelineOpsData, ApplyCrmPipelineOpsResponses, ApplyDatabaseOpsData, ApplyDatabaseOpsErrors, ApplyDatabaseOpsResponses, ApproveHarnessPairingData, ApproveHarnessPairingErrors, ApproveHarnessPairingResponses, BulkWakeupSyncServiceDocumentsData, BulkWakeupSyncServiceDocumentsErrors, BulkWakeupSyncServiceDocumentsResponses, CallWebhookData, CallWebhookErrors, CallWebhookResponses, CancelSlackImportData, CancelSlackImportErrors, CancelSlackImportResponses, CheckActiveCallData, CheckActiveCallErrors, CheckActiveCallResponses, ClaimHarnessPairingData, ClaimHarnessPairingErrors, ClaimHarnessPairingResponses, CollaborateFormData, CollaborateFormErrors, CollaborateFormResponses, CompleteSlackImportUploadsData, CompleteSlackImportUploadsErrors, CompleteSlackImportUploadsResponses, ConvertDatabaseColumnData, ConvertDatabaseColumnErrors, ConvertDatabaseColumnResponses, CopyDocumentData, CopyDocumentErrors, CopyDocumentResponses, CreateAgentData, CreateAgentErrors, CreateAgentResponses, CreateAnchorData, CreateAnchorErrors, CreateAnchorResponses, CreateCanvasHandlerData, CreateCanvasHandlerErrors, CreateCanvasHandlerResponses, CreateChannelData, CreateChannelErrors, CreateChannelLabelData, CreateChannelLabelErrors, CreateChannelLabelResponses, CreateChannelResponses, CreateChannelScopedBotData, CreateChannelScopedBotErrors, CreateChannelScopedBotResponses, CreateCollabSurfaceTokenData, CreateCollabSurfaceTokenErrors, CreateCollabSurfaceTokenResponses, CreateCrmCompanyData, CreateCrmCompanyErrors, CreateCrmCompanyResponses, CreateCrmContactData, CreateCrmContactErrors, CreateCrmContactResponses, CreateCrmPipelineData, CreateCrmPipelineResponses, CreateDatabaseData, CreateDatabaseErrors, CreateDatabaseResponses, CreateDatabaseWebhookData, CreateDatabaseWebhookErrors, CreateDatabaseWebhookResponses, CreateDocumentData, CreateDocumentErrors, CreateDocumentResponses, CreateEntityMentionData, CreateEntityMentionErrors, CreateEntityMentionResponses, CreateFormData, CreateFormErrors, CreateFormResponses, CreateHarnessPairingData, CreateHarnessPairingErrors, CreateHarnessPairingResponses, CreateInitiativeData, CreateInitiativeErrors, CreateInitiativeResponses, CreateInstructionsHandlerData, CreateInstructionsHandlerErrors, CreateInstructionsHandlerResponses, CreateMarkdownHandlerData, CreateMarkdownHandlerErrors, CreateMarkdownHandlerResponses, CreateProjectHandlerData, CreateProjectHandlerErrors, CreateProjectHandlerResponses, CreateSkillHandlerData, CreateSkillHandlerErrors, CreateSkillHandlerResponses, CreateSlackImportData, CreateSlackImportErrors, CreateSlackImportResponses, CreateSnippetHandlerData, CreateSnippetHandlerErrors, CreateSnippetHandlerResponses, CreateTaskHandlerData, CreateTaskHandlerErrors, CreateTaskHandlerResponses, CreateUserApiKeyData, CreateUserApiKeyErrors, CreateUserApiKeyResponses, CreateViewHandlerData, CreateViewHandlerErrors, CreateViewHandlerResponses, CreateWebhookData, CreateWebhookErrors, CreateWebhookResponses, DeclineCallData, DeclineCallErrors, DeclineCallResponses, DeclineRingData, DeclineRingErrors, DeclineRingResponses, DeleteAnchorData, DeleteAnchorErrors, DeleteAnchorResponses, DeleteCallRecordData, DeleteCallRecordErrors, DeleteCallRecordResponses, DeleteChannelData, DeleteChannelErrors, DeleteChannelLabelData, DeleteChannelLabelErrors, DeleteChannelLabelResponses, DeleteChannelResponses, DeleteCollabSurfaceData, DeleteCollabSurfaceErrors, DeleteCollabSurfaceResponses, DeleteDatabaseWebhookData, DeleteDatabaseWebhookErrors, DeleteDatabaseWebhookResponses, DeleteDocumentData, DeleteDocumentErrors, DeleteDocumentResponses, DeleteEntityMentionData, DeleteEntityMentionErrors, DeleteEntityMentionResponses, DeleteHarnessData, DeleteHarnessErrors, DeleteHarnessResponses, DeleteHistoryHandlerData, DeleteHistoryHandlerErrors, DeleteHistoryHandlerResponses, DeleteInitiativeData, DeleteInitiativeErrors, DeleteInitiativeResponses, DeleteProjectHandlerData, DeleteProjectHandlerErrors, DeleteProjectHandlerResponses, DeleteSelfHarnessData, DeleteSelfHarnessErrors, DeleteSelfHarnessResponses, DeleteUserApiKeyData, DeleteUserApiKeyErrors, DeleteUserApiKeyResponses, DeleteUserDocumentViewLocationData, DeleteUserDocumentViewLocationErrors, DeleteUserDocumentViewLocationResponses, DeleteViewHandlerData, DeleteViewHandlerErrors, DeleteViewHandlerResponses, DeleteWebhookData, DeleteWebhookErrors, DeleteWebhookResponses, DeliverDatabaseWebhookData, DeliverDatabaseWebhookErrors, DeliverDatabaseWebhookResponses, EditAnchorData, EditAnchorErrors, EditAnchorResponses, EditCallRecordData, EditCallRecordErrors, EditCallRecordResponses, EditCallTranscriptData, EditCallTranscriptErrors, EditCallTranscriptResponses, EditDocumentData, EditDocumentErrors, EditDocumentResponses, EditMyFormResponseData, EditMyFormResponseErrors, EditMyFormResponseResponses, EditProjectV2Data, EditProjectV2Errors, EditProjectV2Responses, EditThreadV2Data, EditThreadV2Errors, EditThreadV2Responses, EnsureCollabSurfaceData, EnsureCollabSurfaceErrors, EnsureCollabSurfaceResponses, EnsureStarterHandlerData, EnsureStarterHandlerErrors, EnsureStarterHandlerResponses, EntityMessageCreateData, EntityMessageCreateResponses, EntityMessageDeleteMessageData, EntityMessageDeleteMessageResponses, EntityMessageDeleteThreadData, EntityMessageDeleteThreadResponses, EntityMessageEditData, EntityMessageEditResponses, EntityMessageGetMessageData, EntityMessageGetMessageResponses, EntityMessageGetThreadData, EntityMessageGetThreadResponses, EntityMessageLegacyData, EntityMessageLegacyResponses, EntityMessagePatchThreadData, EntityMessagePatchThreadResponses, EntityMessageReactData, EntityMessageReactResponses, EntityMessageTypingData, EntityMessageTypingResponses, EventIcsData, EventIcsErrors, EventIcsResponses, ExcludeDefaultViewHandlerData, ExcludeDefaultViewHandlerErrors, ExcludeDefaultViewHandlerResponses, ExportDocumentData, ExportDocumentErrors, ExportDocumentResponses, FinalizeSlackImportData, FinalizeSlackImportErrors, FinalizeSlackImportResponses, GetActiveCallsData, GetActiveCallsErrors, GetActiveCallsResponses, GetActivityData, GetActivityErrors, GetActivityResponses, GetAttachmentReferencesData, GetAttachmentReferencesErrors, GetAttachmentReferencesResponses, GetBatchCallRecordPreviewData, GetBatchCallRecordPreviewErrors, GetBatchCallRecordPreviewResponses, GetBatchChannelPreviewData, GetBatchChannelPreviewErrors, GetBatchChannelPreviewResponses, GetBatchPreviewHandlerData, GetBatchPreviewHandlerErrors, GetBatchPreviewHandlerResponses, GetBatchProjectPreviewData, GetBatchProjectPreviewErrors, GetBatchProjectPreviewResponses, GetBotOwnerProfilesData, GetBotOwnerProfilesErrors, GetBotOwnerProfilesResponses, GetCallRecordData, GetCallRecordErrors, GetCallRecordResponses, GetChannelAttachmentsData, GetChannelAttachmentsErrors, GetChannelAttachmentsResponses, GetChannelData, GetChannelErrors, GetChannelJoinLinkData, GetChannelJoinLinkErrors, GetChannelJoinLinkResponses, GetChannelParticipantsData, GetChannelParticipantsErrors, GetChannelParticipantsResponses, GetChannelResponses, GetChannelsData, GetChannelsErrors, GetChannelsResponses, GetCollabSurfaceData, GetCollabSurfaceErrors, GetCollabSurfaceResponses, GetCompanyData, GetCompanyErrors, GetCompanyResponses, GetContactByEmailData, GetContactByEmailErrors, GetContactByEmailResponses, GetContactData, GetContactErrors, GetContactResponses, GetCrmPipelineData, GetCrmPipelinePermissionsData, GetCrmPipelinePermissionsResponses, GetCrmPipelineResponses, GetCrmPipelineRowsData, GetCrmPipelineRowsResponses, GetCrmPipelineTableData, GetCrmPipelineTableResponses, GetCrmTeamSettingsData, GetCrmTeamSettingsErrors, GetCrmTeamSettingsResponses, GetDatabaseData, GetDatabaseErrors, GetDatabasePermissionsData, GetDatabasePermissionsErrors, GetDatabasePermissionsResponses, GetDatabaseQueryData, GetDatabaseQueryErrors, GetDatabaseQueryResponses, GetDatabaseResponses, GetDatabaseRowHistoryData, GetDatabaseRowHistoryErrors, GetDatabaseRowHistoryResponses, GetDatabaseTableChangesData, GetDatabaseTableChangesErrors, GetDatabaseTableChangesResponses, GetDatabaseViewPositionsData, GetDatabaseViewPositionsErrors, GetDatabaseViewPositionsResponses, GetDocumentAnchorsData, GetDocumentAnchorsErrors, GetDocumentAnchorsResponses, GetDocumentBranchNameData, GetDocumentBranchNameErrors, GetDocumentBranchNameResponses, GetDocumentByTeamSlugData, GetDocumentByTeamSlugErrors, GetDocumentByTeamSlugResponses, GetDocumentData, GetDocumentErrors, GetDocumentGithubPullRequestsData, GetDocumentGithubPullRequestsErrors, GetDocumentGithubPullRequestsResponses, GetDocumentListHandlerData, GetDocumentListHandlerErrors, GetDocumentListHandlerResponses, GetDocumentLocationV3Data, GetDocumentLocationV3Errors, GetDocumentLocationV3Responses, GetDocumentPermissionsTokenData, GetDocumentPermissionsTokenErrors, GetDocumentPermissionsTokenResponses, GetDocumentPermissionsV2Data, GetDocumentPermissionsV2Errors, GetDocumentPermissionsV2Responses, GetDocumentProcessingResultData, GetDocumentProcessingResultErrors, GetDocumentProcessingResultResponses, GetDocumentResponses, GetDocumentShortIdData, GetDocumentShortIdErrors, GetDocumentShortIdResponses, GetDocumentTeamShareData, GetDocumentTeamShareErrors, GetDocumentTeamShareResponses, GetDocumentTextContentData, GetDocumentTextContentErrors, GetDocumentTextContentResponses, GetDocumentVersionData, GetDocumentVersionErrors, GetDocumentVersionResponses, GetDocumentViewsHandlerData, GetDocumentViewsHandlerErrors, GetDocumentViewsHandlerResponses, GetEmailFollowupData, GetEmailFollowupErrors, GetEmailFollowupResponses, GetEntityPermissionData, GetEntityPermissionErrors, GetEntityPermissionResponses, GetForeignEntityBySourceData, GetForeignEntityBySourceErrors, GetForeignEntityBySourceResponses, GetForeignEntityData, GetForeignEntityErrors, GetForeignEntityResponses, GetFormData, GetFormErrors, GetFormPermissionsData, GetFormPermissionsErrors, GetFormPermissionsResponses, GetFormResponses, GetFormResponseSummaryData, GetFormResponseSummaryErrors, GetFormResponseSummaryResponses, GetFormTallyData, GetFormTallyErrors, GetFormTallyResponses, GetGithubPullRequestChangesData, GetGithubPullRequestChangesErrors, GetGithubPullRequestChangesPatchData, GetGithubPullRequestChangesPatchErrors, GetGithubPullRequestChangesPatchResponses, GetGithubPullRequestChangesResponses, GetGithubPullRequestData, GetGithubPullRequestErrors, GetGithubPullRequestFacetsData, GetGithubPullRequestFacetsErrors, GetGithubPullRequestFacetsResponses, GetGithubPullRequestResponses, GetGithubPullRequestTasksData, GetGithubPullRequestTasksErrors, GetGithubPullRequestTasksResponses, GetHarnessPairingData, GetHarnessPairingErrors, GetHarnessPairingResponses, GetHistoryHandlerData, GetHistoryHandlerErrors, GetHistoryHandlerResponses, GetInitiativeData, GetInitiativeErrors, GetInitiativeResponses, GetInstructionsHandlerData, GetInstructionsHandlerErrors, GetInstructionsHandlerResponses, GetItemsSoupData, GetItemsSoupErrors, GetItemsSoupResponses, GetLocationHandlerData, GetLocationHandlerErrors, GetLocationHandlerResponses, GetMyFormResponseData, GetMyFormResponseErrors, GetMyFormResponseResponses, GetOrCreateCallData, GetOrCreateCallErrors, GetOrCreateCallResponses, GetOrCreateDmData, GetOrCreateDmErrors, GetOrCreateDmResponses, GetOrCreatePrivateData, GetOrCreatePrivateErrors, GetOrCreatePrivateResponses, GetPendingProjectsHandlerData, GetPendingProjectsHandlerErrors, GetPendingProjectsHandlerResponses, GetPinsHandlerData, GetPinsHandlerErrors, GetPinsHandlerResponses, GetProjectContentHandlerData, GetProjectContentHandlerErrors, GetProjectContentHandlerResponses, GetProjectHandlerData, GetProjectHandlerErrors, GetProjectHandlerResponses, GetProjectPermissionsV2Data, GetProjectPermissionsV2Errors, GetProjectPermissionsV2Responses, GetProjectsHandlerData, GetProjectsHandlerErrors, GetProjectsHandlerResponses, GetProjectUserAccessLevelData, GetProjectUserAccessLevelErrors, GetProjectUserAccessLevelResponses, GetRingStatusData, GetRingStatusErrors, GetRingStatusResponses, GetSelfBotData, GetSelfBotErrors, GetSelfBotResponses, GetSelfHarnessData, GetSelfHarnessErrors, GetSelfHarnessResponses, GetSlackImportData, GetSlackImportErrors, GetSlackImportResponses, GetSystemSkillsHandlerData, GetSystemSkillsHandlerErrors, GetSystemSkillsHandlerResponses, GetUserDocumentsHandlerData, GetUserDocumentsHandlerErrors, GetUserDocumentsHandlerResponses, GetUserDocumentViewLocationData, GetUserDocumentViewLocationErrors, GetUserDocumentViewLocationResponses, GetViewsHandlerData, GetViewsHandlerErrors, GetViewsHandlerResponses, GetWebhookData, GetWebhookErrors, GetWebhookResponses, GuestCallChatPostData, GuestCallChatPostErrors, GuestCallChatPostResponses, GuestCallChatReadData, GuestCallChatReadErrors, GuestCallChatReadResponses, HandlerData, HandlerErrors, HandlerResponses, HealthHandlerData, HealthHandlerResponses, ImportDatabaseTableData, ImportDatabaseTableErrors, ImportDatabaseTableResponses, InferDatabaseColumnTypeData, InferDatabaseColumnTypeErrors, InferDatabaseColumnTypeResponses, IngestTranscriptData, IngestTranscriptErrors, IngestTranscriptResponses, InitializeUserDocumentsData, InitializeUserDocumentsErrors, InitializeUserDocumentsResponses, InstallSyncData, InstallSyncErrors, JobProcessingResultHandlerData, JobProcessingResultHandlerErrors, JobProcessingResultHandlerResponses, JoinChannelByCodeData, JoinChannelByCodeErrors, JoinChannelByCodeResponses, JoinChannelData, JoinChannelErrors, JoinChannelResponses, LeaveChannelData, LeaveChannelErrors, LeaveChannelResponses, LeaveOrEndCallData, LeaveOrEndCallErrors, LeaveOrEndCallResponses, LinkedAccountData, LinkedAccountResponses, LinkedAdoptData, LinkedAdoptResponses, LinkedCancelPairingData, LinkedCancelPairingResponses, LinkedChatsData, LinkedChatsResponses, LinkedConfigurationData, LinkedConfigurationResponses, LinkedConnectData, LinkedConnectResponses, LinkedDeliveryData, LinkedDeliveryResponses, LinkedDetachData, LinkedDetachResponses, LinkedDisconnectData, LinkedDisconnectResponses, LinkedGroupsData, LinkedGroupsResponses, LinkedMessageAttachmentsData, LinkedMessageAttachmentsResponses, LinkedPairingData, LinkedPairingResponses, LinkedPasskeyData, LinkedPasskeyResponses, LinkedReplyData, LinkedReplyErrors, LinkedReplyResponses, LinkedUploadData, LinkedUploadResponses, ListAccessibleFormsData, ListAccessibleFormsErrors, ListAccessibleFormsResponses, ListAgentsData, ListAgentsErrors, ListAgentsResponses, ListBotChannelsData, ListBotChannelsErrors, ListBotChannelsResponses, ListChannelLabelsData, ListChannelLabelsErrors, ListChannelLabelsResponses, ListCompanyContactsData, ListCompanyContactsErrors, ListCompanyContactsResponses, ListCrmPipelinesData, ListCrmPipelinesResponses, ListDatabaseColumnCastsData, ListDatabaseColumnCastsErrors, ListDatabaseColumnCastsResponses, ListDatabasesData, ListDatabasesErrors, ListDatabasesResponses, ListDatabaseWebhooksData, ListDatabaseWebhooksErrors, ListDatabaseWebhooksResponses, ListEmailRemindersData, ListEmailRemindersErrors, ListEmailRemindersResponses, ListFavoritesData, ListFavoritesErrors, ListFavoritesResponses, ListFormsData, ListFormsErrors, ListFormsResponses, ListHarnessAgentsData, ListHarnessAgentsErrors, ListHarnessAgentsResponses, ListHarnessesData, ListHarnessesErrors, ListHarnessesResponses, ListHarnessSessionsData, ListHarnessSessionsErrors, ListHarnessSessionsResponses, ListInitiativesData, ListInitiativesErrors, ListInitiativesResponses, ListJoinRequestsData, ListJoinRequestsErrors, ListJoinRequestsResponses, ListOccurrencesData, ListOccurrencesErrors, ListOccurrencesResponses, ListSlackImportsData, ListSlackImportsResponses, ListTeamCalendarData, ListTeamCalendarResponses, ListTeamOutOfOfficeData, ListTeamOutOfOfficeErrors, ListTeamOutOfOfficeResponses, ListUserApiKeysData, ListUserApiKeysErrors, ListUserApiKeysResponses, ListWebhooksData, ListWebhooksErrors, ListWebhooksResponses, MeetingCancelData, MeetingCancelErrors, MeetingCancelPreparationData, MeetingCancelPreparationErrors, MeetingCancelPreparationResponses, MeetingCancelResponses, MeetingCreateData, MeetingCreateErrors, MeetingCreateResponses, MeetingGuestJoinData, MeetingGuestJoinErrors, MeetingGuestJoinResponses, MeetingGuestParticipantsData, MeetingGuestParticipantsErrors, MeetingGuestParticipantsResponses, MeetingInviteData, MeetingInviteErrors, MeetingInvitePermissionsData, MeetingInvitePermissionsErrors, MeetingInvitePermissionsResponses, MeetingInviteResponses, MeetingInviteUsersData, MeetingInviteUsersErrors, MeetingInviteUsersResponses, MeetingJoinData, MeetingJoinErrors, MeetingJoinResponses, MeetingLeaveData, MeetingLeaveErrors, MeetingLeaveResponses, MeetingListActiveData, MeetingListActiveErrors, MeetingListActiveResponses, MeetingListData, MeetingListErrors, MeetingListResponses, MeetingLookupData, MeetingLookupErrors, MeetingLookupResponses, MeetingParticipantsData, MeetingParticipantsErrors, MeetingParticipantsResponses, MeetingPrepareData, MeetingPrepareErrors, MeetingPrepareResponses, MeetingShareData, MeetingShareErrors, MeetingShareResponses, MeetingUpdateData, MeetingUpdateErrors, MeetingUpdateResponses, MentionPreviewsData, MentionPreviewsErrors, MentionPreviewsResponses, MessageTimelineData, MessageTimelineEntriesData, MessageTimelineEntriesResponses, MessageTimelineResponses, PatchChannelData, PatchChannelErrors, PatchChannelResponses, PatchViewHandlerData, PatchViewHandlerErrors, PatchViewHandlerResponses, PatchWebhookData, PatchWebhookErrors, PatchWebhookResponses, PermanentlyDeleteDocumentData, PermanentlyDeleteDocumentErrors, PermanentlyDeleteDocumentResponses, PermanentlyDeleteProjectData, PermanentlyDeleteProjectErrors, PermanentlyDeleteProjectResponses, PostActivityData, PostActivityErrors, PostActivityResponses, PostChannelBotWebhookData, PostChannelBotWebhookErrors, PostChannelBotWebhookResponses, PostItemsSoupAstData, PostItemsSoupAstErrors, PostItemsSoupAstGroupedData, PostItemsSoupAstGroupedErrors, PostItemsSoupAstGroupedResponses, PostItemsSoupAstResponses, PostItemsSoupData, PostItemsSoupErrors, PostItemsSoupResponses, PresaveDocumentHandlerData, PresaveDocumentHandlerErrors, PresaveDocumentHandlerResponses, PreviewSmartTagData, PreviewSmartTagErrors, PreviewSmartTagResponses, PutCrmTeamSettingsData, PutCrmTeamSettingsErrors, PutCrmTeamSettingsResponses, PutCrmTeamStagesData, PutCrmTeamStagesErrors, PutCrmTeamStagesResponses, PutFormLayoutData, PutFormLayoutErrors, PutFormLayoutResponses, QueryCrmPipelineRowsData, QueryCrmPipelineRowsResponses, QueryDatabasesData, QueryDatabasesErrors, QueryDatabasesResponses, RecentlyDeletedData, RecentlyDeletedErrors, RecentlyDeletedResponses, RegisterSlackImportUploadsData, RegisterSlackImportUploadsErrors, RegisterSlackImportUploadsResponses, RemoveBotFromChannelByBotData, RemoveBotFromChannelByBotErrors, RemoveBotFromChannelByBotResponses, RemoveFavoriteByEntityData, RemoveFavoriteByEntityErrors, RemoveFavoriteByEntityResponses, RemoveParticipantsData, RemoveParticipantsErrors, RemoveParticipantsResponses, RemovePinHandlerData, RemovePinHandlerErrors, RemovePinHandlerResponses, RenameChannelLabelData, RenameChannelLabelErrors, RenameChannelLabelResponses, RenameCrmPipelineData, RenameCrmPipelineResponses, ReorderFavoritesData, ReorderFavoritesErrors, ReorderFavoritesResponses, ReorderPinsHandlerData, ReorderPinsHandlerErrors, ReorderPinsHandlerResponses, RequestToJoinData, RequestToJoinErrors, RequestToJoinResponses, ResetCrmTeamStagesData, ResetCrmTeamStagesErrors, ResetCrmTeamStagesResponses, RevertDeleteDocumentData, RevertDeleteDocumentErrors, RevertDeleteDocumentResponses, RevertDeleteProjectData, RevertDeleteProjectErrors, RevertDeleteProjectResponses, SaveDatabaseQueryData, SaveDatabaseQueryErrors, SaveDatabaseQueryResponses, SaveDocumentHandlerData, SaveDocumentHandlerErrors, SaveDocumentHandlerResponses, SearchContactsData, SearchContactsErrors, SearchContactsResponses, SetChannelLabelData, SetChannelLabelErrors, SetChannelLabelResponses, SetChannelPictureData, SetChannelPictureErrors, SetChannelPictureResponses, SetCompanyHiddenData, SetCompanyHiddenErrors, SetCompanyHiddenResponses, SetContactHiddenData, SetContactHiddenErrors, SetContactHiddenResponses, SetCrmCompanyNameData, SetCrmCompanyNameErrors, SetCrmCompanyNameResponses, SetCrmContactNameData, SetCrmContactNameErrors, SetCrmContactNameResponses, SetDocumentTeamShareData, SetDocumentTeamShareErrors, SetDocumentTeamShareResponses, SetEmailFollowupData, SetEmailFollowupErrors, SetEmailFollowupResponses, SetEmailSyncData, SetEmailSyncErrors, SetEmailSyncResponses, ShareCrmPipelineData, ShareCrmPipelineResponses, ShareDatabaseAwarenessData, ShareDatabaseAwarenessErrors, ShareDatabaseAwarenessResponses, SimpleSaveData, SimpleSaveErrors, SimpleSaveResponses, StreamEventsData, StreamEventsErrors, StreamEventsResponse, StreamEventsResponses, SubmitFormResponseData, SubmitFormResponseErrors, SubmitFormResponseResponses, ToggleShareWithTeamData, ToggleShareWithTeamErrors, ToggleShareWithTeamResponses, TranscribeDictationData, TranscribeDictationErrors, TranscribeDictationResponses, TrashCrmPipelineData, TrashCrmPipelineResponses, UndoDatabaseChangeData, UndoDatabaseChangeErrors, UndoDatabaseChangeResponses, UpdateAgentData, UpdateAgentErrors, UpdateAgentResponses, UpdateCrmPipelinePermissionsData, UpdateCrmPipelinePermissionsResponses, UpdateDatabasePermissionsData, UpdateDatabasePermissionsErrors, UpdateDatabasePermissionsResponses, UpdateFormData, UpdateFormErrors, UpdateFormPermissionsData, UpdateFormPermissionsErrors, UpdateFormPermissionsResponses, UpdateFormResponses, UpdateInitiativeData, UpdateInitiativeErrors, UpdateInitiativeResponses, UploadExtractFolderHandlerData, UploadExtractFolderHandlerErrors, UploadExtractFolderHandlerResponses, UploadFolderHandlerData, UploadFolderHandlerErrors, UploadFolderHandlerResponses, UpsertHistoryHandlerData, UpsertHistoryHandlerErrors, UpsertHistoryHandlerResponses, UpsertUserDocumentViewLocationData, UpsertUserDocumentViewLocationErrors, UpsertUserDocumentViewLocationResponses, ValidateDocumentPermissionsTokenData, ValidateDocumentPermissionsTokenErrors, ValidateDocumentPermissionsTokenResponses, ValidateWebhookData, ValidateWebhookErrors, ValidateWebhookResponses, WhatsappGroupData, WhatsappGroupMessagesData, WhatsappGroupMessagesResponses, WhatsappGroupPermissionsData, WhatsappGroupPermissionsResponses, WhatsappGroupReadData, WhatsappGroupReadResponses, WhatsappGroupResponses, WhatsappGroupsData, WhatsappGroupSendsData, WhatsappGroupSendsResponses, WhatsappGroupsResponses, WhatsappGroupUpdatePermissionsData, WhatsappGroupUpdatePermissionsResponses } from './types.gen';+import type { AccessRequestsCancelData, AccessRequestsCancelErrors, AccessRequestsCancelResponses, AccessRequestsDirectData, AccessRequestsDirectErrors, AccessRequestsDirectResponses, AccessRequestsRemoveDirectData, AccessRequestsRemoveDirectErrors, AccessRequestsRemoveDirectResponses, AccessRequestsResolveData, AccessRequestsResolveErrors, AccessRequestsResolveResponses, AccessRequestsSetDirectData, AccessRequestsSetDirectErrors, AccessRequestsSetDirectResponses, AccessRequestsStateData, AccessRequestsStateErrors, AccessRequestsStateResponses, AccessRequestsSubmitData, AccessRequestsSubmitErrors, AccessRequestsSubmitResponses, AddFavoriteData, AddFavoriteErrors, AddFavoriteResponses, AddParticipantsData, AddParticipantsErrors, AddParticipantsResponses, AddPinHandlerData, AddPinHandlerErrors, AddPinHandlerResponses, ApplyCrmPipelineOpsData, ApplyCrmPipelineOpsResponses, ApplyDatabaseOpsData, ApplyDatabaseOpsErrors, ApplyDatabaseOpsResponses, ApproveHarnessPairingData, ApproveHarnessPairingErrors, ApproveHarnessPairingResponses, BulkWakeupSyncServiceDocumentsData, BulkWakeupSyncServiceDocumentsErrors, BulkWakeupSyncServiceDocumentsResponses, CallWebhookData, CallWebhookErrors, CallWebhookResponses, CancelSlackImportData, CancelSlackImportErrors, CancelSlackImportResponses, CheckActiveCallData, CheckActiveCallErrors, CheckActiveCallResponses, ClaimHarnessPairingData, ClaimHarnessPairingErrors, ClaimHarnessPairingResponses, CollaborateFormData, CollaborateFormErrors, CollaborateFormResponses, CompleteSlackImportUploadsData, CompleteSlackImportUploadsErrors, CompleteSlackImportUploadsResponses, ConvertDatabaseColumnData, ConvertDatabaseColumnErrors, ConvertDatabaseColumnResponses, CopyDocumentData, CopyDocumentErrors, CopyDocumentResponses, CreateAgentData, CreateAgentErrors, CreateAgentResponses, CreateAnchorData, CreateAnchorErrors, CreateAnchorResponses, CreateCanvasHandlerData, CreateCanvasHandlerErrors, CreateCanvasHandlerResponses, CreateChannelData, CreateChannelErrors, CreateChannelLabelData, CreateChannelLabelErrors, CreateChannelLabelResponses, CreateChannelResponses, CreateChannelScopedBotData, CreateChannelScopedBotErrors, CreateChannelScopedBotResponses, CreateCollabSurfaceTokenData, CreateCollabSurfaceTokenErrors, CreateCollabSurfaceTokenResponses, CreateCrmCompanyData, CreateCrmCompanyErrors, CreateCrmCompanyResponses, CreateCrmContactData, CreateCrmContactErrors, CreateCrmContactResponses, CreateCrmPipelineData, CreateCrmPipelineResponses, CreateDatabaseData, CreateDatabaseErrors, CreateDatabaseResponses, CreateDatabaseWebhookData, CreateDatabaseWebhookErrors, CreateDatabaseWebhookResponses, CreateDocumentData, CreateDocumentErrors, CreateDocumentResponses, CreateEntityMentionData, CreateEntityMentionErrors, CreateEntityMentionResponses, CreateFormData, CreateFormErrors, CreateFormResponses, CreateHarnessPairingData, CreateHarnessPairingErrors, CreateHarnessPairingResponses, CreateInitiativeData, CreateInitiativeErrors, CreateInitiativeResponses, CreateInstructionsHandlerData, CreateInstructionsHandlerErrors, CreateInstructionsHandlerResponses, CreateMarkdownHandlerData, CreateMarkdownHandlerErrors, CreateMarkdownHandlerResponses, CreateProjectHandlerData, CreateProjectHandlerErrors, CreateProjectHandlerResponses, CreateSkillHandlerData, CreateSkillHandlerErrors, CreateSkillHandlerResponses, CreateSlackImportData, CreateSlackImportErrors, CreateSlackImportResponses, CreateSnippetHandlerData, CreateSnippetHandlerErrors, CreateSnippetHandlerResponses, CreateTaskHandlerData, CreateTaskHandlerErrors, CreateTaskHandlerResponses, CreateUserApiKeyData, CreateUserApiKeyErrors, CreateUserApiKeyResponses, CreateViewHandlerData, CreateViewHandlerErrors, CreateViewHandlerResponses, CreateWebhookData, CreateWebhookErrors, CreateWebhookResponses, DeclineCallData, DeclineCallErrors, DeclineCallResponses, DeclineRingData, DeclineRingErrors, DeclineRingResponses, DeleteAnchorData, DeleteAnchorErrors, DeleteAnchorResponses, DeleteCallRecordData, DeleteCallRecordErrors, DeleteCallRecordResponses, DeleteChannelData, DeleteChannelErrors, DeleteChannelLabelData, DeleteChannelLabelErrors, DeleteChannelLabelResponses, DeleteChannelResponses, DeleteCollabSurfaceData, DeleteCollabSurfaceErrors, DeleteCollabSurfaceResponses, DeleteDatabaseWebhookData, DeleteDatabaseWebhookErrors, DeleteDatabaseWebhookResponses, DeleteDocumentData, DeleteDocumentErrors, DeleteDocumentResponses, DeleteEntityMentionData, DeleteEntityMentionErrors, DeleteEntityMentionResponses, DeleteHarnessData, DeleteHarnessErrors, DeleteHarnessResponses, DeleteHistoryHandlerData, DeleteHistoryHandlerErrors, DeleteHistoryHandlerResponses, DeleteInitiativeData, DeleteInitiativeErrors, DeleteInitiativeResponses, DeleteProjectHandlerData, DeleteProjectHandlerErrors, DeleteProjectHandlerResponses, DeleteSelfHarnessData, DeleteSelfHarnessErrors, DeleteSelfHarnessResponses, DeleteUserApiKeyData, DeleteUserApiKeyErrors, DeleteUserApiKeyResponses, DeleteUserDocumentViewLocationData, DeleteUserDocumentViewLocationErrors, DeleteUserDocumentViewLocationResponses, DeleteViewHandlerData, DeleteViewHandlerErrors, DeleteViewHandlerResponses, DeleteWebhookData, DeleteWebhookErrors, DeleteWebhookResponses, DeliverDatabaseWebhookData, DeliverDatabaseWebhookErrors, DeliverDatabaseWebhookResponses, EditAnchorData, EditAnchorErrors, EditAnchorResponses, EditCallRecordData, EditCallRecordErrors, EditCallRecordResponses, EditCallTranscriptData, EditCallTranscriptErrors, EditCallTranscriptResponses, EditDocumentData, EditDocumentErrors, EditDocumentResponses, EditMyFormResponseData, EditMyFormResponseErrors, EditMyFormResponseResponses, EditProjectV2Data, EditProjectV2Errors, EditProjectV2Responses, EditThreadV2Data, EditThreadV2Errors, EditThreadV2Responses, EnsureCollabSurfaceData, EnsureCollabSurfaceErrors, EnsureCollabSurfaceResponses, EnsureStarterHandlerData, EnsureStarterHandlerErrors, EnsureStarterHandlerResponses, EntityMessageCreateData, EntityMessageCreateResponses, EntityMessageDeleteMessageData, EntityMessageDeleteMessageResponses, EntityMessageDeleteThreadData, EntityMessageDeleteThreadResponses, EntityMessageEditData, EntityMessageEditResponses, EntityMessageGetMessageData, EntityMessageGetMessageResponses, EntityMessageGetThreadData, EntityMessageGetThreadResponses, EntityMessageLegacyData, EntityMessageLegacyResponses, EntityMessagePatchThreadData, EntityMessagePatchThreadResponses, EntityMessageReactData, EntityMessageReactResponses, EntityMessageTypingData, EntityMessageTypingResponses, EventIcsData, EventIcsErrors, EventIcsResponses, ExcludeDefaultViewHandlerData, ExcludeDefaultViewHandlerErrors, ExcludeDefaultViewHandlerResponses, ExportDocumentData, ExportDocumentErrors, ExportDocumentResponses, FinalizeSlackImportData, FinalizeSlackImportErrors, FinalizeSlackImportResponses, GetActiveCallsData, GetActiveCallsErrors, GetActiveCallsResponses, GetActivityData, GetActivityErrors, GetActivityResponses, GetAttachmentReferencesData, GetAttachmentReferencesErrors, GetAttachmentReferencesResponses, GetBatchCallRecordPreviewData, GetBatchCallRecordPreviewErrors, GetBatchCallRecordPreviewResponses, GetBatchChannelPreviewData, GetBatchChannelPreviewErrors, GetBatchChannelPreviewResponses, GetBatchPreviewHandlerData, GetBatchPreviewHandlerErrors, GetBatchPreviewHandlerResponses, GetBatchProjectPreviewData, GetBatchProjectPreviewErrors, GetBatchProjectPreviewResponses, GetBotOwnerProfilesData, GetBotOwnerProfilesErrors, GetBotOwnerProfilesResponses, GetCallRecordData, GetCallRecordErrors, GetCallRecordResponses, GetChannelAttachmentsData, GetChannelAttachmentsErrors, GetChannelAttachmentsResponses, GetChannelData, GetChannelErrors, GetChannelJoinLinkData, GetChannelJoinLinkErrors, GetChannelJoinLinkResponses, GetChannelParticipantsData, GetChannelParticipantsErrors, GetChannelParticipantsResponses, GetChannelResponses, GetChannelsData, GetChannelsErrors, GetChannelsResponses, GetCollabSurfaceData, GetCollabSurfaceErrors, GetCollabSurfaceResponses, GetCompanyData, GetCompanyErrors, GetCompanyResponses, GetContactByEmailData, GetContactByEmailErrors, GetContactByEmailResponses, GetContactData, GetContactErrors, GetContactResponses, GetCrmPipelineData, GetCrmPipelinePermissionsData, GetCrmPipelinePermissionsResponses, GetCrmPipelineResponses, GetCrmPipelineRowsData, GetCrmPipelineRowsResponses, GetCrmPipelineTableData, GetCrmPipelineTableResponses, GetCrmTeamSettingsData, GetCrmTeamSettingsErrors, GetCrmTeamSettingsResponses, GetDatabaseData, GetDatabaseErrors, GetDatabasePermissionsData, GetDatabasePermissionsErrors, GetDatabasePermissionsResponses, GetDatabaseQueryData, GetDatabaseQueryErrors, GetDatabaseQueryResponses, GetDatabaseResponses, GetDatabaseRowHistoryData, GetDatabaseRowHistoryErrors, GetDatabaseRowHistoryResponses, GetDatabaseTableChangesData, GetDatabaseTableChangesErrors, GetDatabaseTableChangesResponses, GetDatabaseViewPositionsData, GetDatabaseViewPositionsErrors, GetDatabaseViewPositionsResponses, GetDocumentAnchorsData, GetDocumentAnchorsErrors, GetDocumentAnchorsResponses, GetDocumentBranchNameData, GetDocumentBranchNameErrors, GetDocumentBranchNameResponses, GetDocumentByTeamSlugData, GetDocumentByTeamSlugErrors, GetDocumentByTeamSlugResponses, GetDocumentData, GetDocumentErrors, GetDocumentGithubPullRequestsData, GetDocumentGithubPullRequestsErrors, GetDocumentGithubPullRequestsResponses, GetDocumentListHandlerData, GetDocumentListHandlerErrors, GetDocumentListHandlerResponses, GetDocumentLocationV3Data, GetDocumentLocationV3Errors, GetDocumentLocationV3Responses, GetDocumentPermissionsTokenData, GetDocumentPermissionsTokenErrors, GetDocumentPermissionsTokenResponses, GetDocumentPermissionsV2Data, GetDocumentPermissionsV2Errors, GetDocumentPermissionsV2Responses, GetDocumentProcessingResultData, GetDocumentProcessingResultErrors, GetDocumentProcessingResultResponses, GetDocumentResponses, GetDocumentShortIdData, GetDocumentShortIdErrors, GetDocumentShortIdResponses, GetDocumentTeamShareData, GetDocumentTeamShareErrors, GetDocumentTeamShareResponses, GetDocumentTextContentData, GetDocumentTextContentErrors, GetDocumentTextContentResponses, GetDocumentVersionData, GetDocumentVersionErrors, GetDocumentVersionResponses, GetDocumentViewsHandlerData, GetDocumentViewsHandlerErrors, GetDocumentViewsHandlerResponses, GetEmailFollowupData, GetEmailFollowupErrors, GetEmailFollowupResponses, GetEntityPermissionData, GetEntityPermissionErrors, GetEntityPermissionResponses, GetForeignEntityBySourceData, GetForeignEntityBySourceErrors, GetForeignEntityBySourceResponses, GetForeignEntityData, GetForeignEntityErrors, GetForeignEntityResponses, GetFormData, GetFormErrors, GetFormPermissionsData, GetFormPermissionsErrors, GetFormPermissionsResponses, GetFormResponses, GetFormResponseSummaryData, GetFormResponseSummaryErrors, GetFormResponseSummaryResponses, GetFormTallyData, GetFormTallyErrors, GetFormTallyResponses, GetGithubPullRequestChangesData, GetGithubPullRequestChangesErrors, GetGithubPullRequestChangesPatchData, GetGithubPullRequestChangesPatchErrors, GetGithubPullRequestChangesPatchResponses, GetGithubPullRequestChangesResponses, GetGithubPullRequestData, GetGithubPullRequestErrors, GetGithubPullRequestFacetsData, GetGithubPullRequestFacetsErrors, GetGithubPullRequestFacetsResponses, GetGithubPullRequestResponses, GetGithubPullRequestTasksData, GetGithubPullRequestTasksErrors, GetGithubPullRequestTasksResponses, GetHarnessPairingData, GetHarnessPairingErrors, GetHarnessPairingResponses, GetHistoryHandlerData, GetHistoryHandlerErrors, GetHistoryHandlerResponses, GetInitiativeData, GetInitiativeErrors, GetInitiativeResponses, GetInstructionsHandlerData, GetInstructionsHandlerErrors, GetInstructionsHandlerResponses, GetItemsSoupData, GetItemsSoupErrors, GetItemsSoupResponses, GetLocationHandlerData, GetLocationHandlerErrors, GetLocationHandlerResponses, GetMyFormResponseData, GetMyFormResponseErrors, GetMyFormResponseResponses, GetOrCreateCallData, GetOrCreateCallErrors, GetOrCreateCallResponses, GetOrCreateDmData, GetOrCreateDmErrors, GetOrCreateDmResponses, GetOrCreatePrivateData, GetOrCreatePrivateErrors, GetOrCreatePrivateResponses, GetPendingProjectsHandlerData, GetPendingProjectsHandlerErrors, GetPendingProjectsHandlerResponses, GetPinsHandlerData, GetPinsHandlerErrors, GetPinsHandlerResponses, GetProjectContentHandlerData, GetProjectContentHandlerErrors, GetProjectContentHandlerResponses, GetProjectHandlerData, GetProjectHandlerErrors, GetProjectHandlerResponses, GetProjectPermissionsV2Data, GetProjectPermissionsV2Errors, GetProjectPermissionsV2Responses, GetProjectsHandlerData, GetProjectsHandlerErrors, GetProjectsHandlerResponses, GetProjectUserAccessLevelData, GetProjectUserAccessLevelErrors, GetProjectUserAccessLevelResponses, GetRingStatusData, GetRingStatusErrors, GetRingStatusResponses, GetSelfBotData, GetSelfBotErrors, GetSelfBotResponses, GetSelfHarnessData, GetSelfHarnessErrors, GetSelfHarnessResponses, GetSlackImportData, GetSlackImportErrors, GetSlackImportResponses, GetSystemSkillsHandlerData, GetSystemSkillsHandlerErrors, GetSystemSkillsHandlerResponses, GetUserDocumentsHandlerData, GetUserDocumentsHandlerErrors, GetUserDocumentsHandlerResponses, GetUserDocumentViewLocationData, GetUserDocumentViewLocationErrors, GetUserDocumentViewLocationResponses, GetViewsHandlerData, GetViewsHandlerErrors, GetViewsHandlerResponses, GetWebhookData, GetWebhookErrors, GetWebhookResponses, GuestCallChatPostData, GuestCallChatPostErrors, GuestCallChatPostResponses, GuestCallChatReadData, GuestCallChatReadErrors, GuestCallChatReadResponses, HandlerData, HandlerErrors, HandlerResponses, HealthHandlerData, HealthHandlerResponses, ImportDatabaseTableData, ImportDatabaseTableErrors, ImportDatabaseTableResponses, InferDatabaseColumnTypeData, InferDatabaseColumnTypeErrors, InferDatabaseColumnTypeResponses, IngestTranscriptData, IngestTranscriptErrors, IngestTranscriptResponses, InitializeUserDocumentsData, InitializeUserDocumentsErrors, InitializeUserDocumentsResponses, InstallSyncData, InstallSyncErrors, JobProcessingResultHandlerData, JobProcessingResultHandlerErrors, JobProcessingResultHandlerResponses, JoinChannelByCodeData, JoinChannelByCodeErrors, JoinChannelByCodeResponses, JoinChannelData, JoinChannelErrors, JoinChannelResponses, LeaveChannelData, LeaveChannelErrors, LeaveChannelResponses, LeaveOrEndCallData, LeaveOrEndCallErrors, LeaveOrEndCallResponses, LinkedAccountData, LinkedAccountResponses, LinkedAdoptData, LinkedAdoptResponses, LinkedCancelPairingData, LinkedCancelPairingResponses, LinkedChatsData, LinkedChatsResponses, LinkedConfigurationData, LinkedConfigurationResponses, LinkedConnectData, LinkedConnectResponses, LinkedDeliveryData, LinkedDeliveryResponses, LinkedDetachData, LinkedDetachResponses, LinkedDisconnectData, LinkedDisconnectResponses, LinkedMessageAttachmentsData, LinkedMessageAttachmentsResponses, LinkedPairingData, LinkedPairingResponses, LinkedPasskeyData, LinkedPasskeyResponses, LinkedReplyData, LinkedReplyErrors, LinkedReplyResponses, LinkedUploadData, LinkedUploadResponses, ListAccessibleFormsData, ListAccessibleFormsErrors, ListAccessibleFormsResponses, ListAgentsData, ListAgentsErrors, ListAgentsResponses, ListBotChannelsData, ListBotChannelsErrors, ListBotChannelsResponses, ListChannelLabelsData, ListChannelLabelsErrors, ListChannelLabelsResponses, ListCompanyContactsData, ListCompanyContactsErrors, ListCompanyContactsResponses, ListCrmPipelinesData, ListCrmPipelinesResponses, ListDatabaseColumnCastsData, ListDatabaseColumnCastsErrors, ListDatabaseColumnCastsResponses, ListDatabasesData, ListDatabasesErrors, ListDatabasesResponses, ListDatabaseWebhooksData, ListDatabaseWebhooksErrors, ListDatabaseWebhooksResponses, ListEmailRemindersData, ListEmailRemindersErrors, ListEmailRemindersResponses, ListFavoritesData, ListFavoritesErrors, ListFavoritesResponses, ListFormsData, ListFormsErrors, ListFormsResponses, ListHarnessAgentsData, ListHarnessAgentsErrors, ListHarnessAgentsResponses, ListHarnessesData, ListHarnessesErrors, ListHarnessesResponses, ListHarnessSessionsData, ListHarnessSessionsErrors, ListHarnessSessionsResponses, ListInitiativesData, ListInitiativesErrors, ListInitiativesResponses, ListJoinRequestsData, ListJoinRequestsErrors, ListJoinRequestsResponses, ListOccurrencesData, ListOccurrencesErrors, ListOccurrencesResponses, ListSlackImportsData, ListSlackImportsResponses, ListTeamCalendarData, ListTeamCalendarResponses, ListTeamOutOfOfficeData, ListTeamOutOfOfficeErrors, ListTeamOutOfOfficeResponses, ListUserApiKeysData, ListUserApiKeysErrors, ListUserApiKeysResponses, ListWebhooksData, ListWebhooksErrors, ListWebhooksResponses, MeetingCancelData, MeetingCancelErrors, MeetingCancelPreparationData, MeetingCancelPreparationErrors, MeetingCancelPreparationResponses, MeetingCancelResponses, MeetingCreateData, MeetingCreateErrors, MeetingCreateResponses, MeetingGuestJoinData, MeetingGuestJoinErrors, MeetingGuestJoinResponses, MeetingGuestParticipantsData, MeetingGuestParticipantsErrors, MeetingGuestParticipantsResponses, MeetingInviteData, MeetingInviteErrors, MeetingInvitePermissionsData, MeetingInvitePermissionsErrors, MeetingInvitePermissionsResponses, MeetingInviteResponses, MeetingInviteUsersData, MeetingInviteUsersErrors, MeetingInviteUsersResponses, MeetingJoinData, MeetingJoinErrors, MeetingJoinResponses, MeetingLeaveData, MeetingLeaveErrors, MeetingLeaveResponses, MeetingListActiveData, MeetingListActiveErrors, MeetingListActiveResponses, MeetingListData, MeetingListErrors, MeetingListResponses, MeetingLookupData, MeetingLookupErrors, MeetingLookupResponses, MeetingParticipantsData, MeetingParticipantsErrors, MeetingParticipantsResponses, MeetingPrepareData, MeetingPrepareErrors, MeetingPrepareResponses, MeetingShareData, MeetingShareErrors, MeetingShareResponses, MeetingUpdateData, MeetingUpdateErrors, MeetingUpdateResponses, MentionPreviewsData, MentionPreviewsErrors, MentionPreviewsResponses, MessageTimelineData, MessageTimelineEntriesData, MessageTimelineEntriesResponses, MessageTimelineResponses, PatchChannelData, PatchChannelErrors, PatchChannelResponses, PatchViewHandlerData, PatchViewHandlerErrors, PatchViewHandlerResponses, PatchWebhookData, PatchWebhookErrors, PatchWebhookResponses, PermanentlyDeleteDocumentData, PermanentlyDeleteDocumentErrors, PermanentlyDeleteDocumentResponses, PermanentlyDeleteProjectData, PermanentlyDeleteProjectErrors, PermanentlyDeleteProjectResponses, PostActivityData, PostActivityErrors, PostActivityResponses, PostChannelBotWebhookData, PostChannelBotWebhookErrors, PostChannelBotWebhookResponses, PostItemsSoupAstData, PostItemsSoupAstErrors, PostItemsSoupAstGroupedData, PostItemsSoupAstGroupedErrors, PostItemsSoupAstGroupedResponses, PostItemsSoupAstResponses, PostItemsSoupData, PostItemsSoupErrors, PostItemsSoupResponses, PresaveDocumentHandlerData, PresaveDocumentHandlerErrors, PresaveDocumentHandlerResponses, PreviewSmartTagData, PreviewSmartTagErrors, PreviewSmartTagResponses, PutCrmTeamSettingsData, PutCrmTeamSettingsErrors, PutCrmTeamSettingsResponses, PutCrmTeamStagesData, PutCrmTeamStagesErrors, PutCrmTeamStagesResponses, PutFormLayoutData, PutFormLayoutErrors, PutFormLayoutResponses, QueryCrmPipelineRowsData, QueryCrmPipelineRowsResponses, QueryDatabasesData, QueryDatabasesErrors, QueryDatabasesResponses, RecentlyDeletedData, RecentlyDeletedErrors, RecentlyDeletedResponses, RegisterSlackImportUploadsData, RegisterSlackImportUploadsErrors, RegisterSlackImportUploadsResponses, RemoveBotFromChannelByBotData, RemoveBotFromChannelByBotErrors, RemoveBotFromChannelByBotResponses, RemoveFavoriteByEntityData, RemoveFavoriteByEntityErrors, RemoveFavoriteByEntityResponses, RemoveParticipantsData, RemoveParticipantsErrors, RemoveParticipantsResponses, RemovePinHandlerData, RemovePinHandlerErrors, RemovePinHandlerResponses, RenameChannelLabelData, RenameChannelLabelErrors, RenameChannelLabelResponses, RenameCrmPipelineData, RenameCrmPipelineResponses, ReorderFavoritesData, ReorderFavoritesErrors, ReorderFavoritesResponses, ReorderPinsHandlerData, ReorderPinsHandlerErrors, ReorderPinsHandlerResponses, RequestToJoinData, RequestToJoinErrors, RequestToJoinResponses, ResetCrmTeamStagesData, ResetCrmTeamStagesErrors, ResetCrmTeamStagesResponses, RevertDeleteDocumentData, RevertDeleteDocumentErrors, RevertDeleteDocumentResponses, RevertDeleteProjectData, RevertDeleteProjectErrors, RevertDeleteProjectResponses, SaveDatabaseQueryData, SaveDatabaseQueryErrors, SaveDatabaseQueryResponses, SaveDocumentHandlerData, SaveDocumentHandlerErrors, SaveDocumentHandlerResponses, SearchContactsData, SearchContactsErrors, SearchContactsResponses, SetChannelLabelData, SetChannelLabelErrors, SetChannelLabelResponses, SetChannelPictureData, SetChannelPictureErrors, SetChannelPictureResponses, SetCompanyHiddenData, SetCompanyHiddenErrors, SetCompanyHiddenResponses, SetContactHiddenData, SetContactHiddenErrors, SetContactHiddenResponses, SetCrmCompanyNameData, SetCrmCompanyNameErrors, SetCrmCompanyNameResponses, SetCrmContactNameData, SetCrmContactNameErrors, SetCrmContactNameResponses, SetDocumentTeamShareData, SetDocumentTeamShareErrors, SetDocumentTeamShareResponses, SetEmailFollowupData, SetEmailFollowupErrors, SetEmailFollowupResponses, SetEmailSyncData, SetEmailSyncErrors, SetEmailSyncResponses, ShareCrmPipelineData, ShareCrmPipelineResponses, ShareDatabaseAwarenessData, ShareDatabaseAwarenessErrors, ShareDatabaseAwarenessResponses, SimpleSaveData, SimpleSaveErrors, SimpleSaveResponses, StreamEventsData, StreamEventsErrors, StreamEventsResponse, StreamEventsResponses, SubmitFormResponseData, SubmitFormResponseErrors, SubmitFormResponseResponses, ToggleShareWithTeamData, ToggleShareWithTeamErrors, ToggleShareWithTeamResponses, TranscribeDictationData, TranscribeDictationErrors, TranscribeDictationResponses, TrashCrmPipelineData, TrashCrmPipelineResponses, UndoDatabaseChangeData, UndoDatabaseChangeErrors, UndoDatabaseChangeResponses, UpdateAgentData, UpdateAgentErrors, UpdateAgentResponses, UpdateCrmPipelinePermissionsData, UpdateCrmPipelinePermissionsResponses, UpdateDatabasePermissionsData, UpdateDatabasePermissionsErrors, UpdateDatabasePermissionsResponses, UpdateFormData, UpdateFormErrors, UpdateFormPermissionsData, UpdateFormPermissionsErrors, UpdateFormPermissionsResponses, UpdateFormResponses, UpdateInitiativeData, UpdateInitiativeErrors, UpdateInitiativeResponses, UploadExtractFolderHandlerData, UploadExtractFolderHandlerErrors, UploadExtractFolderHandlerResponses, UploadFolderHandlerData, UploadFolderHandlerErrors, UploadFolderHandlerResponses, UpsertHistoryHandlerData, UpsertHistoryHandlerErrors, UpsertHistoryHandlerResponses, UpsertUserDocumentViewLocationData, UpsertUserDocumentViewLocationErrors, UpsertUserDocumentViewLocationResponses, ValidateDocumentPermissionsTokenData, ValidateDocumentPermissionsTokenErrors, ValidateDocumentPermissionsTokenResponses, ValidateWebhookData, ValidateWebhookErrors, ValidateWebhookResponses, WhatsappGroupData, WhatsappGroupMessagesData, WhatsappGroupMessagesResponses, WhatsappGroupPermissionsData, WhatsappGroupPermissionsResponses, WhatsappGroupReadData, WhatsappGroupReadResponses, WhatsappGroupResponses, WhatsappGroupsData, WhatsappGroupSendsData, WhatsappGroupSendsResponses, WhatsappGroupsResponses, WhatsappGroupUpdatePermissionsData, WhatsappGroupUpdatePermissionsResponses } from './types.gen';export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown> = Options2<TData, ThrowOnError, TResponse> & {/**@@ -2771,13 +2771,6 @@ export class Sdk extends HeyApiClient {});}- /**- * Groups the caller's account has joined.- */- public linkedGroups<ThrowOnError extends boolean = false>(options?: Options<LinkedGroupsData, ThrowOnError>): RequestResult<LinkedGroupsResponses, unknown, ThrowOnError> {- return (options?.client ?? this.client).get<LinkedGroupsResponses, unknown, ThrowOnError>({ url: '/meta/linked/groups', ...options });- }-/*** Adopt one of the caller's groups into a standalone group entity.*/diff --git a/packages/sdk/generated/storage/types.gen.ts b/packages/sdk/generated/storage/types.gen.tsindex cee4ef35ea..52443bdb34 100644--- a/packages/sdk/generated/storage/types.gen.ts+++ b/packages/sdk/generated/storage/types.gen.ts@@ -8987,7 +8987,8 @@ export type LinkedAccountView = {*/export type LinkedAdoptGroup = {/**- * Group the requester's account has joined.+ * A group the requester's account has joined, or a direct chat from+ * their chat list (the other person's JID, as the list names it).*/group_jid: string;};@@ -9059,6 +9060,11 @@ export type LinkedBackfill = {*/export type LinkedBackfillState = 'pending' | 'running' | 'waiting_for_phone' | 'done' | 'partial';+/**+ * Why a chat can't be added to Macro; the app words it from the code.+ */+export type LinkedCannotAdd = 'not_in_group' | 'community' | 'own_chat' | 'not_in_chat_list';+/*** Operations implemented for linked groups, independent of current permission.*/@@ -9101,10 +9107,8 @@ export type LinkedChat = {* "Add to Macro" works now.*/canAdd: boolean;- /**- * Why it can't be added, when it is neither added, shared nor addable.- */- cannotAddReason?: string | null;+ cannotAddReason?: null | LinkedCannotAdd;+ community?: null | LinkedCommunityReference;group?: null | LinkedGroupReference;/*** WhatsApp chat JID: a group, or the other person's phone-number JID@@ -9147,6 +9151,24 @@ export type LinkedChats = {chats: Array<LinkedChat>;};+/**+ * The WhatsApp community a group belongs to.+ */+export type LinkedCommunityReference = {+ /**+ * This group is the community's announcement group.+ */+ announcements: boolean;+ /**+ * The community's WhatsApp JID.+ */+ id: string;+ /**+ * The community's name.+ */+ name: string;+};+/*** Explicit pairing intent; replacement is a separate deliberate action.*/@@ -9211,14 +9233,22 @@ export type LinkedGroupInfo = {*/announce: boolean;/**- * Community announcement or parent group, outside the supported surface.+ * The community's announcement group (everyone reads, admins post).*/- community: boolean;+ communityAnnouncements?: boolean;/**- * Disappearing messages are on; content is not retained.+ * The community a linked subgroup or announcement group belongs to.*/- disappearing: boolean;- group?: null | LinkedGroupReference;+ communityJid?: string | null;+ /**+ * The community itself: it has no messages of its own and can't be added.+ */+ communityParent?: boolean;+ /**+ * Disappearing-messages timer in seconds while it is on. Macro keeps the+ * messages; its sends carry the timer so phones treat them like their own.+ */+ disappearingSeconds?: number | null;/*** Remote group JID.*/@@ -9235,7 +9265,6 @@ export type LinkedGroupInfo = {* Full roster.*/participants: Array<LinkedParticipant>;- shared?: null | LinkedSharedGroupReference;};/**@@ -9487,7 +9516,7 @@ export type LinkedSharedGroupReference = {/*** Macro user who added the group and shared it.*/- owner_id: string;+ ownerId: string;};/**@@ -16174,6 +16203,12 @@ export type WhatsAppGroupDetail = WhatsAppGroupSummary & {* Caller's effective permission.*/access_level: AccessLevel;+ community?: null | LinkedCommunityReference;+ /**+ * WhatsApp's disappearing-messages timer in seconds while it is on;+ * Macro keeps the messages anyway. `null` when off or unknown.+ */+ disappearing_seconds?: number | null;/*** Size and mutation limits.*/@@ -16247,6 +16282,10 @@ export type WhatsAppGroupMessage = {* Timestamp assigned by WhatsApp.*/sent_at: string;+ /**+ * Sent as view-once in WhatsApp; Macro shows it like any media.+ */+ view_once: boolean;};/**@@ -16312,12 +16351,16 @@ export type WhatsAppGroupSummary = {* Entity identifier.*/id: string;+ /**+ * A group, or a direct chat with one person (only its owner sends).+ */+ kind: LinkedChatKind;/*** Latest message timestamp.*/last_message_at?: string | null;/**- * Display name.+ * Display name: the group's, or a direct chat's other person.*/name: string;send_reason?: null | LinkedReplyBlock;@@ -23183,19 +23226,6 @@ export type LinkedDisconnectResponses = {export type LinkedDisconnectResponse = LinkedDisconnectResponses[keyof LinkedDisconnectResponses];-export type LinkedGroupsData = {- body?: never;- path?: never;- query?: never;- url: '/meta/linked/groups';-};--export type LinkedGroupsResponses = {- 200: Array<LinkedGroupInfo>;-};--export type LinkedGroupsResponse = LinkedGroupsResponses[keyof LinkedGroupsResponses];-export type LinkedAdoptData = {body: LinkedAdoptGroup;path?: never;diff --git a/packages/sdk/specs/storage.json b/packages/sdk/specs/storage.jsonindex 40ef0d2c47..5228f51a53 100644--- a/packages/sdk/specs/storage.json+++ b/packages/sdk/specs/storage.json@@ -16143,28 +16143,6 @@}}},- "/meta/linked/groups": {- "get": {- "tags": ["whatsapp_linked::inbound::router"],- "summary": "Groups the caller's account has joined.",- "operationId": "linked_groups",- "responses": {- "200": {- "description": "",- "content": {- "application/json": {- "schema": {- "type": "array",- "items": {- "$ref": "#/components/schemas/LinkedGroupInfo"- }- }- }- }- }- }- }- },"/meta/linked/groups/adopt": {"post": {"tags": ["whatsapp_linked::inbound::router"],@@ -33365,7 +33343,7 @@"properties": {"group_jid": {"type": "string",- "description": "Group the requester's account has joined."+ "description": "A group the requester's account has joined, or a direct chat from\ntheir chat list (the other person's JID, as the list names it)."}}},@@ -33460,6 +33438,11 @@"description": "Where importing a group's earlier messages stands.","enum": ["pending", "running", "waiting_for_phone", "done", "partial"]},+ "LinkedCannotAdd": {+ "type": "string",+ "description": "Why a chat can't be added to Macro; the app words it from the code.",+ "enum": ["not_in_group", "community", "own_chat", "not_in_chat_list"]+ },"LinkedCapabilities": {"type": "object","description": "Operations implemented for linked groups, independent of current permission.",@@ -33526,8 +33509,26 @@"description": "\"Add to Macro\" works now."},"cannotAddReason": {- "type": ["string", "null"],- "description": "Why it can't be added, when it is neither added, shared nor addable."+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/LinkedCannotAdd",+ "description": "Why it can't be added, when it is neither added, shared nor addable."+ }+ ]+ },+ "community": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/LinkedCommunityReference",+ "description": "The community a group belongs to (a community's group or its\nannouncement group); `null` otherwise."+ }+ ]},"group": {"oneOf": [@@ -33593,6 +33594,25 @@}}},+ "LinkedCommunityReference": {+ "type": "object",+ "description": "The WhatsApp community a group belongs to.",+ "required": ["id", "name", "announcements"],+ "properties": {+ "announcements": {+ "type": "boolean",+ "description": "This group is the community's announcement group."+ },+ "id": {+ "type": "string",+ "description": "The community's WhatsApp JID."+ },+ "name": {+ "type": "string",+ "description": "The community's name."+ }+ }+ },"LinkedConnect": {"type": "object","description": "Explicit pairing intent; replacement is a separate deliberate action.",@@ -33662,38 +33682,29 @@"LinkedGroupInfo": {"type": "object","description": "One full metadata read of a group, never an incomplete membership delta.",- "required": [- "jid",- "name",- "participants",- "announce",- "disappearing",- "community",- "observedAt"- ],+ "required": ["jid", "name", "participants", "announce", "observedAt"],"properties": {"announce": {"type": "boolean","description": "Only admins may post."},- "community": {+ "communityAnnouncements": {"type": "boolean",- "description": "Community announcement or parent group, outside the supported surface."+ "description": "The community's announcement group (everyone reads, admins post)."+ },+ "communityJid": {+ "type": ["string", "null"],+ "description": "The community a linked subgroup or announcement group belongs to."},- "disappearing": {+ "communityParent": {"type": "boolean",- "description": "Disappearing messages are on; content is not retained."+ "description": "The community itself: it has no messages of its own and can't be added."},- "group": {- "oneOf": [- {- "type": "null"- },- {- "$ref": "#/components/schemas/LinkedGroupReference",- "description": "The caller's own Macro group for this remote group, once they added\nit. Only set by the groups listing."- }- ]+ "disappearingSeconds": {+ "type": ["integer", "null"],+ "format": "int32",+ "description": "Disappearing-messages timer in seconds while it is on. Macro keeps the\nmessages; its sends carry the timer so phones treat them like their own.",+ "minimum": 0},"jid": {"type": "string",@@ -33714,17 +33725,6 @@"$ref": "#/components/schemas/LinkedParticipant"},"description": "Full roster."- },- "shared": {- "oneOf": [- {- "type": "null"- },- {- "$ref": "#/components/schemas/LinkedSharedGroupReference",- "description": "Someone else's Macro group for this remote group that was shared with\nthe caller, when the caller has not added their own. Only set by the\ngroups listing."- }- ]}}},@@ -34044,7 +34044,7 @@"LinkedSharedGroupReference": {"type": "object","description": "Another person's group entity the caller can view.",- "required": ["id", "name", "owner_id"],+ "required": ["id", "name", "ownerId"],"properties": {"id": {"type": "string",@@ -34055,7 +34055,7 @@"type": "string","description": "Display name, following WhatsApp."},- "owner_id": {+ "ownerId": {"type": "string","description": "Macro user who added the group and shared it."}@@ -44690,6 +44690,23 @@"$ref": "#/components/schemas/AccessLevel","description": "Caller's effective permission."},+ "community": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/LinkedCommunityReference",+ "description": "The WhatsApp community this group belongs to, if any."+ }+ ]+ },+ "disappearing_seconds": {+ "type": ["integer", "null"],+ "format": "int32",+ "description": "WhatsApp's disappearing-messages timer in seconds while it is on;\nMacro keeps the messages anyway. `null` when off or unknown.",+ "minimum": 0+ },"limits": {"$ref": "#/components/schemas/LinkedCapabilities","description": "Size and mutation limits."@@ -44732,6 +44749,7 @@"attachments","kind","forwarded",+ "view_once","mentions"],"properties": {@@ -44822,6 +44840,10 @@"type": "string","format": "date-time","description": "Timestamp assigned by WhatsApp."+ },+ "view_once": {+ "type": "boolean",+ "description": "Sent as view-once in WhatsApp; Macro shows it like any media."}}},@@ -44887,7 +44909,14 @@"WhatsAppGroupSummary": {"type": "object","description": "Adopted group visible through ordinary entity sharing.",- "required": ["id", "name", "user_id", "unread_count", "can_send"],+ "required": [+ "id",+ "name",+ "kind",+ "user_id",+ "unread_count",+ "can_send"+ ],"properties": {"backfill": {"oneOf": [@@ -44909,6 +44938,10 @@"format": "uuid","description": "Entity identifier."},+ "kind": {+ "$ref": "#/components/schemas/LinkedChatKind",+ "description": "A group, or a direct chat with one person (only its owner sends)."+ },"last_message_at": {"type": ["string", "null"],"format": "date-time",@@ -44916,7 +44949,7 @@},"name": {"type": "string",- "description": "Display name."+ "description": "Display name: the group's, or a direct chat's other person."},"send_reason": {"oneOf": [diff --git a/packages/sdk/src/coverage/skipped.ts b/packages/sdk/src/coverage/skipped.tsindex 98c4d5b30d..575538313e 100644--- a/packages/sdk/src/coverage/skipped.ts+++ b/packages/sdk/src/coverage/skipped.ts@@ -364,8 +364,6 @@ export const storageExcluded = ['linkedDisconnect','linkedPairing','linkedPasskey',- // The roster group listing is superseded by the chat list (linkedChats).- 'linkedGroups',// Live meeting admission and participant previews are app session flows.'meetingGuestJoin',// Browser setup reserves an empty RTC room before creating a meeting.diff --git a/packages/sdk/src/entities/whatsapp/chat.ts b/packages/sdk/src/entities/whatsapp/chat.tsindex f90ad09381..65bb200316 100644--- a/packages/sdk/src/entities/whatsapp/chat.ts+++ b/packages/sdk/src/entities/whatsapp/chat.ts@@ -1,9 +1,34 @@-import type { LinkedChat } from '../../../generated/storage/types.gen';+import type {+ LinkedChat,+ LinkedCommunityReference,+} from '../../../generated/storage/types.gen';import { MacroNotFoundError, unwrap } from '../../utils';import type { MacroClient } from '../../utils/client';import { MacroEntity } from '../entity';import { WhatsAppGroup } from './group';+/** The WhatsApp community a group belongs to. */+export type WhatsAppCommunity = {+ /** The community itself, as a chat of the list (it can't be added). */+ chat: WhatsAppChat;+ /** The community's name. */+ name: string;+ /** This group is the community's announcement group. */+ announcements: boolean;+};++/** A community reference as a handle on the community's own chat. */+export function communityOf(+ client: MacroClient,+ record: LinkedCommunityReference,+): WhatsAppCommunity {+ return {+ chat: WhatsAppChat.byId(client, record.id),+ name: record.name,+ announcements: record.announcements,+ };+}+/** One chat of the current user's WhatsApp chat list: a group or a direct chat. */export class WhatsAppChat extends MacroEntity<LinkedChat> {/** Reference a chat by its WhatsApp JID. */@@ -41,9 +66,14 @@ export class WhatsAppChat extends MacroEntity<LinkedChat> {/** Whether adding it to Macro works now. */readonly canAdd = this.field('canAdd');- /** Why it can't be added, when it is neither added, shared nor addable. */+ /** Why it can't be added (`not_in_group`, `community`, `own_chat`, `not_in_chat_list`), when it is neither added, shared nor addable. */readonly cannotAddReason = this.field('cannotAddReason');+ /** The WhatsApp community a group belongs to, if any: the community's own chat, its name, and whether this is its announcement group. */+ readonly community = this.mappedField('community', (record) =>+ record ? communityOf(this.client, record) : undefined,+ );+/** The current user's own Macro group for this chat, once added. */readonly group = this.mappedField('group', (record) =>record ? WhatsAppGroup.byId(this.client, record.id) : undefined,@@ -55,9 +85,9 @@ export class WhatsAppChat extends MacroEntity<LinkedChat> {);/**- * Add a group chat to Macro as the current user's own group; its earlier- * messages are imported from the phone. Adding it again returns the same- * group. Direct chats can't be added yet.+ * Add the chat (a group or a direct chat) to Macro as the current user's+ * own; its earlier messages are imported from the phone. Adding it again+ * returns the same chat. Only the owner sends in a direct chat.*/async adopt(): Promise<WhatsAppGroup> {const result = await this.mutate((client) =>diff --git a/packages/sdk/src/entities/whatsapp/group.ts b/packages/sdk/src/entities/whatsapp/group.tsindex f912fe35ef..70f9e6907d 100644--- a/packages/sdk/src/entities/whatsapp/group.ts+++ b/packages/sdk/src/entities/whatsapp/group.ts@@ -9,7 +9,9 @@ import type { MacroClient } from '../../utils/client';import { Document } from '../documents/document';import { FavoritableEntity } from '../entity';import { User } from '../users/user';+import { communityOf } from './chat';import { WhatsAppMessage } from './message';+import { WhatsAppParticipant } from './participant';import { WhatsAppSend } from './send';import { WhatsAppUpload } from './upload';@@ -18,8 +20,8 @@ export type WhatsAppReply =| {type: 'text';text: string;- /** WhatsApp ids of mentioned participants (`roster.participants[].jid`); the text names each as `@<digits>`. */- mentions?: string[];+ /** Participants mentioned (from `participants()`); the text names each as `@<mentionToken>`. */+ mentions?: WhatsAppParticipant[];}| { type: 'media'; upload: WhatsAppUpload; caption?: string }| {@@ -29,7 +31,7 @@ export type WhatsAppReply =text?: string;};-/** Independently shareable adopted WhatsApp group entity. */+/** Independently shareable added WhatsApp chat: a group or a direct chat. */export class WhatsAppGroup extends FavoritableEntity<WhatsAppGroupDetail> {/** Canonical sharing and favorites kind. */readonly entityType = 'whatsapp_group' as const;@@ -45,8 +47,10 @@ export class WhatsAppGroup extends FavoritableEntity<WhatsAppGroupDetail> {);}- /** Display name. */+ /** Display name: the group's, or a direct chat's other person. */readonly name = this.field('name');+ /** `group`, or `direct` for a one-to-one chat (only its owner sends). */+ readonly kind = this.field('kind');/** Whether the caller can send from their own connected account. */readonly canSend = this.field('can_send');/** Reason sending is blocked. */@@ -59,8 +63,20 @@ export class WhatsAppGroup extends FavoritableEntity<WhatsAppGroupDetail> {readonly backfill = this.field('backfill');/** Supported sizes and mutation window. */readonly limits = this.field('limits');- /** Current remote roster, when available. */+ /** Current remote roster (name, participants, announce), when available. */readonly roster = this.field('roster');+ /** Everyone in the chat, from its roster; empty when no roster is known. */+ readonly participants = this.mappedField('roster', (roster) =>+ (roster?.participants ?? []).map((record) =>+ WhatsAppParticipant.from(this, record),+ ),+ );+ /** WhatsApp's disappearing-messages timer in seconds while on; Macro keeps the messages. */+ readonly disappearingSeconds = this.field('disappearing_seconds');+ /** The WhatsApp community this group belongs to, if any: the community's own chat, its name, and whether this is its announcement group. */+ readonly community = this.mappedField('community', (record) =>+ record ? communityOf(this.client, record) : undefined,+ );/** Actual owner, independent of WhatsApp membership. */readonly owner = this.mappedField('user_id', (id) =>User.byId(this.client, id),@@ -88,7 +104,7 @@ export class WhatsAppGroup extends FavoritableEntity<WhatsAppGroupDetail> {/** Advance the caller's own read cursor. */async markRead(message: WhatsAppMessage): Promise<void> {- this.assertGroup(message.groupId);+ this.assertGroup(message.group);await this.mutate((client) =>client.storage.whatsappGroupRead({path: { group_id: this.id },@@ -144,16 +160,20 @@ export class WhatsAppGroup extends FavoritableEntity<WhatsAppGroupDetail> {content: WhatsAppReply,options: { idempotencyKey: string; replyTo?: WhatsAppMessage },): Promise<WhatsAppSend> {- if (options.replyTo) this.assertGroup(options.replyTo.groupId);+ if (options.replyTo) this.assertGroup(options.replyTo.group);const message = match(content).returnType<LinkedReplyContent>()- .with({ type: 'text' }, (value) => ({- type: 'text',- text: value.text,- mentions: value.mentions ?? [],- }))+ .with({ type: 'text' }, (value) => {+ const mentions = value.mentions ?? [];+ for (const participant of mentions) this.assertGroup(participant.group);+ return {+ type: 'text',+ text: value.text,+ mentions: mentions.map((participant) => participant.id),+ };+ }).with({ type: 'media' }, (value) => {- this.assertGroup(value.upload.groupId);+ this.assertGroup(value.upload.group);return {type: 'media',upload_id: value.upload.id,@@ -161,7 +181,7 @@ export class WhatsAppGroup extends FavoritableEntity<WhatsAppGroupDetail> {};}).with({ type: 'mutation' }, (value) => {- this.assertGroup(value.message.groupId);+ this.assertGroup(value.message.group);return {type: 'mutation',message_id: value.message.id,@@ -196,10 +216,7 @@ export class WhatsAppGroup extends FavoritableEntity<WhatsAppGroupDetail> {async delivery(sends: Array<WhatsAppSend | WhatsAppMessage>,): Promise<WhatsAppSend[]> {- for (const send of sends)- this.assertGroup(- send instanceof WhatsAppSend ? send.group.id : send.groupId,- );+ for (const send of sends) this.assertGroup(send.group);return unwrap(await this.client.storage.linkedDelivery({path: { group_id: this.id },@@ -210,7 +227,7 @@ export class WhatsAppGroup extends FavoritableEntity<WhatsAppGroupDetail> {/** Read attachment states for selected messages. */async messageAttachments(messages: WhatsAppMessage[]) {- for (const message of messages) this.assertGroup(message.groupId);+ for (const message of messages) this.assertGroup(message.group);return unwrap(await this.client.storage.linkedMessageAttachments({path: { group_id: this.id },@@ -238,8 +255,8 @@ export class WhatsAppGroup extends FavoritableEntity<WhatsAppGroupDetail> {return this;}- private assertGroup(groupId: string): void {- if (groupId !== this.id)+ private assertGroup(group: WhatsAppGroup): void {+ if (group.id !== this.id)throw new Error('WhatsApp reference belongs to another group');}}diff --git a/packages/sdk/src/entities/whatsapp/message.ts b/packages/sdk/src/entities/whatsapp/message.tsindex 975adb30b1..eb66ca6207 100644--- a/packages/sdk/src/entities/whatsapp/message.ts+++ b/packages/sdk/src/entities/whatsapp/message.ts@@ -9,7 +9,8 @@ import type { WhatsAppGroup } from './group';export class WhatsAppMessage extends MacroEntity<WhatsAppGroupMessage> {private constructor(client: MacroClient,- private readonly group: WhatsAppGroup,+ /** The chat this message is in. */+ readonly group: WhatsAppGroup,id: string,seed?: WhatsAppGroupMessage,) {@@ -34,11 +35,6 @@ export class WhatsAppMessage extends MacroEntity<WhatsAppGroupMessage> {return new WhatsAppMessage(client, group, record.id, record);}- /** Group identity for checking reply/mutation scope. */- get groupId(): string {- return this.group.id;- }-protected async fetch(): Promise<WhatsAppGroupMessage> {for await (const message of this.group.messages({ limit: 100 })) {if (message.id === this.id) return message.detail.get();@@ -64,6 +60,8 @@ export class WhatsAppMessage extends MacroEntity<WhatsAppGroupMessage> {readonly kind = this.field('kind');/** Forwarded from another chat. */readonly forwarded = this.field('forwarded');+ /** Sent as view-once in WhatsApp; Macro keeps and shows it like any media. */+ readonly viewOnce = this.field('view_once');/** People the body @-mentions: `@<token>` in the body is this person. */readonly mentions = this.field('mentions');/** Poll (with tallies), location, contact cards, event or system line. */diff --git a/packages/sdk/src/entities/whatsapp/participant.ts b/packages/sdk/src/entities/whatsapp/participant.tsnew file mode 100644index 0000000000..d8c1eb533b--- /dev/null+++ b/packages/sdk/src/entities/whatsapp/participant.ts@@ -0,0 +1,51 @@+import type { LinkedParticipant as WhatsAppParticipantRecord } from '../../../generated/storage/types.gen';+import type { WhatsAppGroup } from './group';++/** Someone in an added WhatsApp chat, from its roster; mention them in a text reply. */+export class WhatsAppParticipant {+ private constructor(+ /** The chat whose roster lists them. */+ readonly group: WhatsAppGroup,+ /** Their WhatsApp id: correlation data, not a Macro user. */+ readonly id: string,+ private readonly record?: WhatsAppParticipantRecord,+ ) {}++ /** Reference a participant of a chat by WhatsApp id. */+ static byId(group: WhatsAppGroup, id: string): WhatsAppParticipant {+ return new WhatsAppParticipant(group, id);+ }++ /** Seed a participant from the chat's roster. */+ static from(+ group: WhatsAppGroup,+ record: WhatsAppParticipantRecord,+ ): WhatsAppParticipant {+ return new WhatsAppParticipant(group, record.jid, record);+ }++ /** Their WhatsApp name, untrusted, when the roster had one. */+ get displayName(): string | undefined {+ return this.record?.displayName ?? undefined;+ }++ /** The digits a text reply writes as `@<digits>` to mention them. */+ get mentionToken(): string {+ return this.id.split('@')[0] ?? this.id;+ }++ /** Whether they administer the group, when read from the roster. */+ get admin(): boolean | undefined {+ return this.record?.admin;+ }++ /** Serialize the participant reference without credentials. */+ toJSON() {+ return {+ id: this.id,+ group: this.group.id,+ displayName: this.displayName,+ admin: this.admin,+ };+ }+}diff --git a/packages/sdk/src/entities/whatsapp/send.ts b/packages/sdk/src/entities/whatsapp/send.tsindex 989ae58419..e3dcf81c73 100644--- a/packages/sdk/src/entities/whatsapp/send.ts+++ b/packages/sdk/src/entities/whatsapp/send.ts@@ -5,6 +5,7 @@ import type { MacroClient } from '../../utils/client';import { MacroEntity } from '../entity';import type { WhatsAppGroup, WhatsAppReply } from './group';import { WhatsAppMessage } from './message';+import { WhatsAppParticipant } from './participant';import { WhatsAppUpload } from './upload';/** One deliberate send intent. Unknown outcomes must never be automatically resent. */@@ -87,7 +88,9 @@ export class WhatsAppSend extends MacroEntity<LinkedSendProgress> {.with({ type: 'text' }, (wire) => ({type: 'text',text: wire.text,- mentions: wire.mentions ?? [],+ mentions: (wire.mentions ?? []).map((jid) =>+ WhatsAppParticipant.byId(this.group, jid),+ ),})).exhaustive();return {diff --git a/packages/sdk/src/entities/whatsapp/upload.ts b/packages/sdk/src/entities/whatsapp/upload.tsindex 03729d655b..fcbb33a7d3 100644--- a/packages/sdk/src/entities/whatsapp/upload.ts+++ b/packages/sdk/src/entities/whatsapp/upload.ts@@ -6,8 +6,8 @@ export class WhatsAppUpload {private constructor(/** Correlation identity of the staged upload. */readonly id: string,- /** The group this upload can be sent to. */- readonly groupId: string,+ /** The chat this upload can be sent to. */+ readonly group: WhatsAppGroup,/** Display filename supplied by the server. */readonly filename?: string,/** Media category supplied by the server. */@@ -16,7 +16,7 @@ export class WhatsAppUpload {/** Reference a previously staged upload in its original group. */static byId(group: WhatsAppGroup, id: string): WhatsAppUpload {- return new WhatsAppUpload(id, group.id);+ return new WhatsAppUpload(id, group);}/** Seed a handle from the server's upload receipt. */@@ -26,7 +26,7 @@ export class WhatsAppUpload {): WhatsAppUpload {return new WhatsAppUpload(record.upload_id,- group.id,+ group,record.filename,record.kind,);@@ -36,7 +36,7 @@ export class WhatsAppUpload {toJSON() {return {id: this.id,- groupId: this.groupId,+ group: this.group.id,filename: this.filename,kind: this.kind,};diff --git a/packages/sdk/src/macro.ts b/packages/sdk/src/macro.tsindex 2e52febf3b..b65d543eb8 100644--- a/packages/sdk/src/macro.ts+++ b/packages/sdk/src/macro.ts@@ -309,6 +309,7 @@ export {type WhatsAppReply,} from './entities/whatsapp/group';export { WhatsAppMessage } from './entities/whatsapp/message';+export { WhatsAppParticipant } from './entities/whatsapp/participant';export { WhatsAppSend } from './entities/whatsapp/send';export { WhatsAppUpload } from './entities/whatsapp/upload';export type {diff --git a/packages/sdk/tests/whatsapp.test.ts b/packages/sdk/tests/whatsapp.test.tsindex c2e0400a59..174a5346d0 100644--- a/packages/sdk/tests/whatsapp.test.ts+++ b/packages/sdk/tests/whatsapp.test.ts@@ -1,7 +1,9 @@import { afterEach, expect, test } from 'bun:test';import {Macro,+ WhatsAppChat,WhatsAppMessage,+ WhatsAppParticipant,WhatsAppSend,WhatsAppUpload,} from '../src/macro';@@ -21,26 +23,32 @@ const account = {const summary = {id: 'group',name: 'Support',+ kind: 'group',user_id: 'owner',unread_count: 1,last_message_at: '2026-10-21',can_send: true,send_reason: null,};-const remote = {- jid: '[email protected]',+const remote = { jid: '[email protected]' };+const roster = {name: 'Remote support',- observedAt: '2026-10-21',- participants: [],+ observed_at: '2026-10-21',announce: false,- disappearing: false,- community: false,- group: null,- shared: null,+ participants: [+ {+ jid: '[email protected]',+ alternateJid: null,+ displayName: 'Customer',+ admin: false,+ },+ ],};const detail = {...summary,- roster: remote,+ roster,+ disappearing_seconds: 604800,+ community: { id: '[email protected]', name: 'Neighbours', announcements: false },sending_identity: account.identity_jid,access_level: 'owner',share_permission: {@@ -111,6 +119,10 @@ test('shared groups can be listed without a WhatsApp connection and handles fetcexpect(groups[0].entityType).toBe('whatsapp_group');expect(await groups[0].name()).toBe('Support');expect(await groups[0].canSend()).toBe(true);+ expect(await groups[0].kind()).toBe('group');+ expect(await groups[0].disappearingSeconds()).toBe(604800);+ expect((await groups[0].community())?.name).toBe('Neighbours');+ expect((await groups[0].community())?.chat.id).toBe('[email protected]');expect(requests.map((r) => new URL(r.url).pathname)).toEqual(['/meta/linked/whatsapp-groups','/meta/linked/whatsapp-groups/group',@@ -118,6 +130,49 @@ test('shared groups can be listed without a WhatsApp connection and handles fetcexpect(JSON.stringify(groups[0])).not.toContain('owner-api-token');});+test('the chat list shows a group someone else shared instead of adding it again', async () => {+ const { macro } = fixture(() =>+ Response.json({+ chats: [+ {+ jid: remote.jid,+ kind: 'group',+ name: 'Remote support',+ lastActivityAt: null,+ archived: false,+ pinned: false,+ group: null,+ shared: {+ id: 'theirs',+ name: 'Remote support',+ owner_id: 'macro|[email protected]',+ },+ canAdd: false,+ cannotAddReason: null,+ community: null,+ },+ {+ jid: '[email protected]',+ kind: 'group',+ name: 'Neighbours',+ lastActivityAt: null,+ archived: false,+ pinned: false,+ group: null,+ shared: null,+ canAdd: false,+ cannotAddReason: 'community',+ community: null,+ },+ ],+ }),+ );+ const [shared, community] = await macro.whatsapp.chats();+ expect(await shared.group()).toBeUndefined();+ expect((await shared.shared())?.id).toBe('theirs');+ expect(await community.cannotAddReason()).toBe('community');+});+test('the chat list lists groups and direct chats and adds a group by its handle', async () => {const { macro, requests } = fixture((request) =>Response.json(@@ -134,8 +189,9 @@ test('the chat list lists groups and direct chats and adds a group by its handlepinned: true,group: null,shared: null,- canAdd: false,- cannotAddReason: "direct chats can't be added to Macro yet",+ canAdd: true,+ cannotAddReason: null,+ community: null,},{jid: remote.jid,@@ -148,6 +204,11 @@ test('the chat list lists groups and direct chats and adds a group by its handleshared: null,canAdd: true,cannotAddReason: null,+ community: {+ id: '[email protected]',+ name: 'Neighbours',+ announcements: false,+ },},],},@@ -155,10 +216,11 @@ test('the chat list lists groups and direct chats and adds a group by its handle);const [direct, group] = await macro.whatsapp.chats();expect(await direct.kind()).toBe('direct');- expect(await direct.cannotAddReason()).toBe(- "direct chats can't be added to Macro yet",- );+ expect(await direct.canAdd()).toBe(true);expect(await group.canAdd()).toBe(true);+ expect((await group.community())?.name).toBe('Neighbours');+ expect((await group.community())?.chat.id).toBe('[email protected]');+ expect(await direct.community()).toBeUndefined();const adopted = await group.adopt();expect(adopted.id).toBe('group');expect(requests.map((r) => new URL(r.url).pathname)).toEqual([@@ -259,7 +321,7 @@ test('staged uploads stay scoped to their adopted group and carry no credentialsnew File(['hello'], 'note.txt', { type: 'text/plain' }),);expect(upload).toBeInstanceOf(WhatsAppUpload);- expect(upload.groupId).toBe(group.id);+ expect(upload.group.id).toBe(group.id);expect(JSON.stringify(upload)).not.toContain('owner-api-token');const other = WhatsAppUpload.byId(macro.whatsapp.byId('other'),@@ -289,17 +351,18 @@ test('mutations and replies accept only standalone WhatsApp messages', async ()});});-test('a text reply names the participants it mentions by their WhatsApp ids', async () => {- const { group, requests } = fixture(() => Response.json(progress));+test("a text reply mentions roster participants and refuses another chat's", async () => {+ const { macro, group, requests } = fixture((request) =>+ Response.json(request.method === 'POST' ? progress : detail),+ );+ const [customer] = await group.participants();+ expect(customer.displayName).toBe('Customer');+ expect(customer.mentionToken).toBe('15550001111');await group.reply(- {- type: 'text',- text: 'hi @15550001111',- mentions: ['[email protected]'],- },+ { type: 'text', text: 'hi @15550001111', mentions: [customer] },{ idempotencyKey: 'mention' },);- expect(await requests[0].json()).toEqual({+ expect(await requests[1].json()).toEqual({idempotency_key: 'mention',message: {type: 'text',@@ -307,4 +370,124 @@ test('a text reply names the participants it mentions by their WhatsApp ids', asmentions: ['[email protected]'],},});+ const stranger = WhatsAppParticipant.byId(+ macro.whatsapp.byId('other'),+ '[email protected]',+ );+ await expect(+ group.reply(+ { type: 'text', text: 'hi @15550002222', mentions: [stranger] },+ { idempotencyKey: 'stranger' },+ ),+ ).rejects.toThrow('another group');+ expect(requests).toHaveLength(2);+});++test('a chat handle reads its entry from the chat list', async () => {+ const { macro, requests } = fixture(() =>+ Response.json({+ chats: [+ {+ jid: remote.jid,+ kind: 'group',+ name: 'Remote support',+ lastActivityAt: null,+ archived: false,+ pinned: false,+ group: { id: 'group', name: 'Remote support' },+ shared: null,+ canAdd: false,+ cannotAddReason: null,+ community: null,+ },+ ],+ }),+ );+ const chat = WhatsAppChat.byId(macro._client, remote.jid);+ expect((await chat.group())?.id).toBe('group');+ expect(new URL(requests[0].url).pathname).toBe('/meta/linked/chats');+ await expect(+ WhatsAppChat.byId(macro._client, '[email protected]').name(),+ ).rejects.toThrow('not available');+});++test('sends, delivery and attachment states stay scoped to the chat', async () => {+ const { macro, group, requests } = fixture((request) => {+ const path = new URL(request.url).pathname;+ if (path.endsWith('/messages/attachments'))+ return Response.json([+ {+ message_id: 'message',+ linked_attachments: [+ {+ ordinal: 0,+ state: 'ready',+ file_name: 'note.txt',+ mime: 'text/plain',+ size: 5,+ document_id: 'document',+ },+ ],+ },+ ]);+ return Response.json([progress]);+ });+ const [open] = await group.sends();+ expect(open.id).toBe('intent');+ const target = WhatsAppMessage.byId(macro._client, group, 'message');+ const delivered = await group.delivery([open, target]);+ expect(delivered[0].id).toBe('intent');+ expect(await requests[1].json()).toEqual(['intent', 'message']);+ const [states] = await group.messageAttachments([target]);+ expect(states.message.id).toBe('message');+ expect(states.attachments[0].document?.id).toBe('document');+ const other = macro.whatsapp.byId('other');+ await expect(+ group.messageAttachments([+ WhatsAppMessage.byId(macro._client, other, 'message'),+ ]),+ ).rejects.toThrow('another group');+ await expect(+ group.delivery([WhatsAppSend.byId(macro._client, other, 'intent')]),+ ).rejects.toThrow('another group');+ expect(requests).toHaveLength(3);+});++test('a send recovers its original intent as handles', async () => {+ const { macro, group } = fixture(() =>+ Response.json([+ {+ ...progress,+ payload: {+ idempotency_key: 'stable',+ reply_to: 'quoted',+ message: {+ type: 'text',+ text: 'hi @15550001111',+ mentions: ['[email protected]'],+ },+ },+ },+ ]),+ );+ const send = WhatsAppSend.byId(macro._client, group, 'intent');+ const intent = await send.request();+ expect(intent.idempotencyKey).toBe('stable');+ expect(intent.replyTo?.id).toBe('quoted');+ expect(intent.replyTo?.group.id).toBe('group');+ if (intent.message.type !== 'text') throw new Error('expected text');+ expect(intent.message.mentions?.map((mention) => mention.id)).toEqual([+ '[email protected]',+ ]);+});++test('detach stops syncing through the owner route', async () => {+ const { group, requests } = fixture(+ () => new Response(null, { status: 204 }),+ );+ await group.detach();+ expect(requests[0].method).toBe('DELETE');+ expect(new URL(requests[0].url).pathname).toBe(+ '/meta/linked/whatsapp-groups/group',+ );});diff --git a/services/document_storage_service/src/api/swagger.rs b/services/document_storage_service/src/api/swagger.rsindex 2eaa3096e8..6af3d5d759 100644--- a/services/document_storage_service/src/api/swagger.rs+++ b/services/document_storage_service/src/api/swagger.rs@@ -457,7 +457,6 @@ use utoipa::OpenApi;whatsapp_linked::inbound::router::cancel,whatsapp_linked::inbound::router::passkey,whatsapp_linked::inbound::router::disconnect,- whatsapp_linked::inbound::router::groups,whatsapp_linked::inbound::router::chats,whatsapp_linked::inbound::router::adopt,whatsapp_linked::inbound::router::group,diff --git a/services/whatsapp_session_service/AGENTS.md b/services/whatsapp_session_service/AGENTS.mdindex 40771f69c7..28e93538e6 100644--- a/services/whatsapp_session_service/AGENTS.md+++ b/services/whatsapp_session_service/AGENTS.md@@ -48,12 +48,17 @@ current, ingests standalone `whatsapp_group` traffic through `whatsapp_linked`'sNo periodic refresh. The domain signals `whatsapp_changed` only when a rosterwrite changed something.- `outbound/whatsapp.rs` (+ `events.rs`): `whatsapp_store_pg` device store,- whatsmeow `Client` (`whatsmeow_signal::libsignal()`), event mapping. Only- group events become inbound events; the gate drops groups the account has- not adopted. Before storing, `events::complete_sender` fills the other half- of a sender's phone-number/LID pair from the account's LID store (pairing,+ whatsmeow `Client` (`whatsmeow_signal::libsignal()`), event mapping. Group+ and direct-chat events become inbound events (`events::chat_of`: a direct+ chat by phone number, its LID alongside); the gate drops chats the account+ has not adopted, matching a direct chat by either address. Before storing,+ `events::complete_addresses` fills the other half of a sender's and a+ direct chat's phone-number/LID pair from the account's LID store (pairing,group participant lists, message addressing); `from_me` carries WhatsApp's- own-message flag. Adopted groups stay cached until `whatsapp_account_changed`;+ own-message flag. If the LID store can't be read, the event is left+ unacknowledged (WhatsApp redelivers it) rather than gated without its+ other address. History requests name a direct chat by LID+ (`events::phone_chat`), as phones key it. Adopted groups stay cached until `whatsapp_account_changed`;a miss always waits for a load that started after the event arrived(single-flight), so an adoption that committed just before is seen. Media locators (direct path, media key, hashes) are sealed with`PgWhatsAppStore::seal("media-locator", …)` before they leave the process.@@ -65,7 +70,8 @@ current, ingests standalone `whatsapp_group` traffic through `whatsapp_linked`'ssystem line per change), group icon changes and history stub messages.Poll votes are decrypted in `Forwarder::poll_vote` with the poll's storedmessage secret (undecryptable ones are acked and dropped). View-once media- is a placeholder.+ (unwrapped by the port, or flagged on the media) is imported like any media+ and marked `view_once`.- Chat list and history: `outbound/whatsapp.rs` `Forwarder` turns historysync bundles, live messages (any chat) and contact/archive/pin events into`ChatUpdate`s (`events.rs`: `history_chats`, `message_chat`,diff --git a/services/whatsapp_session_service/src/domain/account/test.rs b/services/whatsapp_session_service/src/domain/account/test.rsindex c3698dc86f..e3cd449d4d 100644--- a/services/whatsapp_session_service/src/domain/account/test.rs+++ b/services/whatsapp_session_service/src/domain/account/test.rs@@ -180,11 +180,11 @@ impl WhatsAppSession for FakeSession {admin: true,}],announce: false,- disappearing: false,- community: false,+ disappearing_seconds: None,+ community_parent: false,+ community_jid: None,+ community_announcements: false,observed_at: Utc::now(),- group: None,- shared: None,}])}@@ -525,6 +525,7 @@ fn group_text(event: u128) -> InboundEvent {InboundEvent {event_id: Uuid::from_u128(event),group_jid: GROUP.to_owned(),+ chat_alternate_jid: None,source_at: Utc::now(),observed_at: Utc::now(),kind: InboundKind::Message(Message {@@ -543,6 +544,7 @@ fn group_text(event: u128) -> InboundEvent {media: vec![],mentions: vec![],forwarded: false,+ view_once: false,rich: None,}),}@@ -702,11 +704,11 @@ async fn live_group_events_update_the_one_group(pool: PgPool) {admin: false,}],announce: false,- disappearing: false,- community: false,+ disappearing_seconds: None,+ community_parent: false,+ community_jid: None,+ community_announcements: false,observed_at: Utc::now(),- group: None,- shared: None,};event_sender(&whatsapp).send(SessionEvent::GroupChanged {diff --git a/services/whatsapp_session_service/src/domain/inbound.rs b/services/whatsapp_session_service/src/domain/inbound.rsindex da9cf22829..3515dc2777 100644--- a/services/whatsapp_session_service/src/domain/inbound.rs+++ b/services/whatsapp_session_service/src/domain/inbound.rs@@ -146,9 +146,25 @@ impl<Store: InboundStore> InboundSink for InboundGate<Store> {return false;}// Undecided (or fenced) leaves the node unacknowledged for redelivery.- let Some(observed) = self.observes(&event.group_jid).await else {+ let Some(mut observed) = self.observes(&event.group_jid).await else {return false;};+ // A direct chat added under the person's other address.+ let mut readdressed = None;+ if !observed && let Some(alternate) = &event.chat_alternate_jid {+ let Some(alternate_observed) = self.observes(alternate).await else {+ return false;+ };+ if alternate_observed {+ observed = true;+ readdressed = Some(InboundEvent {+ group_jid: alternate.clone(),+ chat_alternate_jid: Some(event.group_jid.clone()),+ ..event.clone()+ });+ }+ }+ let event = readdressed.as_ref().unwrap_or(event);let span = tracing::info_span!("whatsapp.inbound.ingest",account_id = %self.scope.account_id,diff --git a/services/whatsapp_session_service/src/domain/inbound/test.rs b/services/whatsapp_session_service/src/domain/inbound/test.rsindex 5060eeedc7..0a32b1ad1f 100644--- a/services/whatsapp_session_service/src/domain/inbound/test.rs+++ b/services/whatsapp_session_service/src/domain/inbound/test.rs@@ -23,6 +23,7 @@ struct FakeStore {adopted: Mutex<Vec<String>>,loads: Mutex<usize>,stored: Mutex<Vec<Uuid>>,+ stored_chats: Mutex<Vec<String>>,}impl InboundStore for FakeStore {@@ -37,6 +38,10 @@ impl InboundStore for FakeStore {event: &InboundEvent,) -> LinkedResult<()> {self.stored.lock().unwrap().push(event.event_id);+ self.stored_chats+ .lock()+ .unwrap()+ .push(event.group_jid.clone());Ok(())}}@@ -45,6 +50,7 @@ fn text(event: u128) -> InboundEvent {InboundEvent {event_id: Uuid::from_u128(event),group_jid: GROUP.to_owned(),+ chat_alternate_jid: None,source_at: Utc::now(),observed_at: Utc::now(),kind: InboundKind::Message(Message {@@ -63,6 +69,7 @@ fn text(event: u128) -> InboundEvent {media: vec![],mentions: vec![],forwarded: false,+ view_once: false,rich: None,}),}@@ -100,3 +107,28 @@ async fn adopted_groups_stay_cached_and_unadopted_ones_are_checked_every_time()vec![Uuid::from_u128(1), Uuid::from_u128(2)]);}++#[tokio::test]+async fn a_direct_chat_added_by_one_address_takes_messages_sent_to_the_other() {+ const PHONE: &str = "[email protected]";+ const LID: &str = "987654321@lid";+ let gate = InboundGate::new(FakeStore::default(), SCOPE);+ gate.store.adopted.lock().unwrap().push(LID.to_owned());+ gate.reload().await;++ let mut by_phone = text(1);+ by_phone.group_jid = PHONE.to_owned();+ by_phone.chat_alternate_jid = Some(LID.to_owned());+ assert!(gate.accept(&by_phone).await);+ let mut unknown = text(2);+ unknown.group_jid = "[email protected]".to_owned();+ unknown.chat_alternate_jid = Some("111@lid".to_owned());+ assert!(gate.accept(&unknown).await, "someone else's chat is acked");++ assert_eq!(*gate.store.stored.lock().unwrap(), vec![Uuid::from_u128(1)]);+ assert_eq!(+ *gate.store.stored_chats.lock().unwrap(),+ vec![LID.to_owned()],+ "stored under the address it was added by"+ );+}diff --git a/services/whatsapp_session_service/src/outbound/whatsapp.rs b/services/whatsapp_session_service/src/outbound/whatsapp.rsindex e4ed745b4d..e1831463e9 100644--- a/services/whatsapp_session_service/src/outbound/whatsapp.rs+++ b/services/whatsapp_session_service/src/outbound/whatsapp.rs@@ -12,8 +12,8 @@ use tokio_util::sync::CancellationToken;use tracing::Instrument;use uuid::Uuid;use whatsapp_linked::domain::events::{- ChatUpdate, ClaimedSend, MediaImport, MessageAnchor, OutboundMedia, OutgoingContent,- SessionScope, Target,+ ChatUpdate, ClaimedSend, InboundEvent, MediaImport, MediaShape, MessageAnchor, OutboundMedia,+ OutgoingContent, SessionScope, Target,};use whatsapp_linked::domain::models::{GroupInfo, Identity, MediaKind, Participant};use whatsapp_store_pg::kms::WhatsAppKms;@@ -202,6 +202,22 @@ struct Forwarder {}impl Forwarder {+ /// [`events::complete_addresses`]; `false` when the LID store failed, so+ /// the event is left unacknowledged and WhatsApp redelivers it.+ async fn complete_addresses(&self, event: &mut InboundEvent) -> bool {+ match events::complete_addresses(self.store.as_ref(), event).await {+ Ok(()) => true,+ Err(error) => {+ tracing::warn!(+ account_id = %self.account,+ error = %error,+ "Reading the WhatsApp LID store failed; leaving the event unacknowledged"+ );+ false+ }+ }+ }+fn seal(&self, locator: &MediaLocator) -> Option<Vec<u8>> {let plaintext = serde_json::to_vec(locator).ok()?;self.store@@ -252,9 +268,13 @@ impl Forwarder {/// reports the page. A page whose messages could not all be stored is not/// reported: the request times out and is asked again.async fn history_page(&self, conversation: &Conversation) {- let Some(page) = events::history_page(conversation) else {+ let Some(mut page) = events::history_page(conversation) else {return;};+ // Messages are read in the chat as the page names it; the page is+ // reported under the chat Macro knows (by phone number).+ let phone_chat = page.chat_jid.clone();+ page.chat_jid = events::macro_chat(self.store.as_ref(), &page.chat_jid).await;let Some(client) = self.client.upgrade() else {return;};@@ -270,7 +290,7 @@ impl Forwarder {outcome = tracing::field::Empty,);async {- let Ok(chat) = page.chat_jid.parse::<Jid>() else {+ let Ok(chat) = phone_chat.parse::<Jid>() else {return;};let mut stored = 0usize;@@ -307,8 +327,8 @@ impl Forwarder {let votes = events::history_poll_votes(self.account, &parsed, now);let mut message_kept = true;for mut event in std::iter::once(event).chain(votes) {- events::complete_sender(self.store.as_ref(), &mut event).await;- message_kept &= Box::pin(self.inbound.accept(&event)).await;+ message_kept &= self.complete_addresses(&mut event).await+ && Box::pin(self.inbound.accept(&event)).await;}if message_kept {stored += 1;@@ -366,7 +386,9 @@ impl Forwarder {else {return Some(true);};- events::complete_sender(self.store.as_ref(), &mut event).await;+ if !self.complete_addresses(&mut event).await {+ return Some(false);+ }Some(self.inbound.accept(&event).await)}}@@ -408,8 +430,8 @@ impl EventHandler for Forwarder {for mapped in mapped {match mapped {Mapped::Inbound(mut event) => {- events::complete_sender(self.store.as_ref(), &mut event).await;- stored &= self.inbound.accept(&event).await;+ stored &= self.complete_addresses(&mut event).await+ && self.inbound.accept(&event).await;}Mapped::Session(event) => {let _ = self.events.send(event);@@ -488,19 +510,21 @@ fn download_failure(error: &ClientError) -> DownloadFailure {}}-fn quote_context(quote: Option<&Target>) -> Option<Box<wa_e2e::ContextInfo>> {- quote.map(- |Target {- source_id,- sender_jid,- }| {- Box::new(wa_e2e::ContextInfo {- stanza_id: Some(source_id.clone()),- participant: Some(sender_jid.clone()),- ..Default::default()- })- },- )+/// The context a sent message carries: the quoted message, and the group's+/// disappearing timer so members' phones treat it like their own messages.+fn send_context(+ quote: Option<&Target>,+ expiration: Option<u32>,+) -> Option<Box<wa_e2e::ContextInfo>> {+ if quote.is_none() && expiration.is_none() {+ return None;+ }+ Some(Box::new(wa_e2e::ContextInfo {+ stanza_id: quote.map(|quote| quote.source_id.clone()),+ participant: quote.map(|quote| quote.sender_jid.clone()),+ expiration,+ ..Default::default()+ }))}/// The message part carrying an uploaded attachment.@@ -509,11 +533,11 @@ fn media_message(mime: &str,filename: &str,caption: Option<&str>,- quote: Option<&Target>,+ context_info: Option<Box<wa_e2e::ContextInfo>>,+ shape: MediaShape,uploaded: &UploadedMedia,) -> wa_e2e::Message {let caption = caption.map(str::to_owned);- let context_info = quote_context(quote);let url = Some(uploaded.url.clone());let direct_path = Some(uploaded.direct_path.clone());let media_key = Some(uploaded.media_key.clone());@@ -532,6 +556,8 @@ fn media_message(file_length,mimetype,caption,+ width: shape.width,+ height: shape.height,context_info,..Default::default()})),@@ -547,6 +573,9 @@ fn media_message(file_length,mimetype,caption,+ width: shape.width,+ height: shape.height,+ seconds: shape.duration_seconds,context_info,..Default::default()})),@@ -562,6 +591,7 @@ fn media_message(file_sha256,file_length,mimetype,+ seconds: shape.duration_seconds,context_info,..Default::default()})),@@ -592,6 +622,7 @@ impl WhatsmeowSession {&self,chat: &Jid,content: &OutgoingContent,+ expiration: Option<u32>,media: Option<&UploadedMedia>,) -> Result<wa_e2e::Message, SendFailure> {Ok(match content {@@ -599,7 +630,7 @@ impl WhatsmeowSession {text,quote: None,mentions,- } if mentions.is_empty() => wa_e2e::Message {+ } if mentions.is_empty() && expiration.is_none() => wa_e2e::Message {conversation: Some(text.clone()),..Default::default()},@@ -608,7 +639,7 @@ impl WhatsmeowSession {quote,mentions,} => {- let mut context_info = quote_context(quote.as_ref()).unwrap_or_default();+ let mut context_info = send_context(quote.as_ref(), expiration).unwrap_or_default();context_info.mentioned_jid = mentions.clone();wa_e2e::Message {extended_text_message: Some(Box::new(wa_e2e::ExtendedTextMessage {@@ -625,6 +656,7 @@ impl WhatsmeowSession {filename,caption,quote,+ shape,} => {let uploaded = media.ok_or(SendFailure::Rejected("media_not_uploaded"))?;media_message(@@ -632,7 +664,8 @@ impl WhatsmeowSession {mime,filename,caption.as_deref(),- quote.as_ref(),+ send_context(quote.as_ref(), expiration),+ *shape,uploaded,)}@@ -709,11 +742,25 @@ fn group_info(group: whatsmeow::types::GroupInfo, observed_at: DateTime<Utc>) ->}).collect(),announce: group.announce.is_announce,- disappearing: group.ephemeral.is_ephemeral,- community: group.parent.is_parent || !group.linked_parent.linked_parent_jid.is_empty(),+ // WhatsApp lists a group that turned disappearing messages off as+ // `<ephemeral expiration="0"/>`: only a timer means on.+ disappearing_seconds: (group.ephemeral.is_ephemeral+ && group.ephemeral.disappearing_timer > 0)+ .then_some(group.ephemeral.disappearing_timer),+ community_parent: group.parent.is_parent,+ community_jid: (!group.parent.is_parent+ && !group.linked_parent.linked_parent_jid.is_empty())+ .then(|| {+ group+ .linked_parent+ .linked_parent_jid+ .to_non_ad()+ .to_string()+ }),+ community_announcements: !group.parent.is_parent+ && !group.linked_parent.linked_parent_jid.is_empty()+ && group.is_default_sub.is_default_sub_group,observed_at,- group: None,- shared: None,}}@@ -799,7 +846,9 @@ impl WhatsAppSession for WhatsmeowSession {media: Option<&UploadedMedia>,) -> Result<DateTime<Utc>, SendFailure> {let chat = parse_jid(&send.group_jid)?;- let message = self.outgoing(&chat, &send.content, media).await?;+ let message = self+ .outgoing(&chat, &send.content, send.disappearing_seconds, media)+ .await?;let response = Box::pin(self.client.send_message(&chat,message,@@ -869,7 +918,8 @@ impl WhatsAppSession for WhatsmeowSession {before: &MessageAnchor,count: u32,) -> Result<(), SessionError> {- let info = anchor_info(chat_jid, before)?;+ let mut info = anchor_info(chat_jid, before)?;+ info.source.chat = events::phone_chat(self.store.as_ref(), info.source.chat.clone()).await;let request = self.client.build_history_sync_request(&info, i32::try_from(count).unwrap_or(i32::MAX));@@ -884,7 +934,8 @@ impl WhatsAppSession for WhatsmeowSession {chat_jid: &str,message: &MessageAnchor,) -> Result<(), SessionError> {- let info = anchor_info(chat_jid, message)?;+ let mut info = anchor_info(chat_jid, message)?;+ info.source.chat = events::phone_chat(self.store.as_ref(), info.source.chat.clone()).await;let request =self.client.build_unavailable_message_request(&info.chat, &info.sender, &info.id);diff --git a/services/whatsapp_session_service/src/outbound/whatsapp/events.rs b/services/whatsapp_session_service/src/outbound/whatsapp/events.rsindex d52f4432e2..86fb6d3304 100644--- a/services/whatsapp_session_service/src/outbound/whatsapp/events.rs+++ b/services/whatsapp_session_service/src/outbound/whatsapp/events.rs@@ -19,9 +19,9 @@ use whatsmeow::proto::wa_e2e::protocol_message;use whatsmeow::proto::wa_history_sync::conversation::EndOfHistoryTransferType;use whatsmeow::proto::wa_history_sync::{Conversation, HistorySync, Pushname};use whatsmeow::proto::wa_web::WebMessageInfo;-use whatsmeow::store::{ContactStore, LidStore};+use whatsmeow::store::{ContactStore, LidStore, StoreError};use whatsmeow::types::events::GroupInfo;-use whatsmeow::types::{DEFAULT_USER_SERVER, GROUP_SERVER, HIDDEN_USER_SERVER, Jid};+use whatsmeow::types::{DEFAULT_USER_SERVER, GROUP_SERVER, HIDDEN_USER_SERVER, Jid, MessageSource};use crate::domain::ports::SessionEvent;@@ -35,9 +35,6 @@ const EVENT_NAMESPACE: Uuid = Uuid::from_u128(0x6c1e_4f0a_93d2_4b7e_8a55_0f3c_2d/// Readable stand-in for message shapes Macro does not import.const UNSUPPORTED_TEXT: &str = "Sent something Macro can't show yet";-/// Stand-in for view-once media, which WhatsApp shows only on the phone.-const VIEW_ONCE_TEXT: &str = "View-once message \u{2014} open it on your phone";-/// What a whatsmeow event means for the account.#[derive(Debug)]pub enum Mapped {@@ -166,33 +163,99 @@ fn map_session(event: &Event) -> Option<SessionEvent> {}}+/// A direct chat as the account's phone keys it: by LID when the store knows+/// the person's LID (phones keep direct chats by LID), else as given.+pub async fn phone_chat(lids: &dyn LidStore, chat: Jid) -> Jid {+ if chat.server != DEFAULT_USER_SERVER {+ return chat;+ }+ match lids.get_lid_for_pn(&chat).await {+ Ok(Some(lid)) => lid.to_non_ad(),+ Ok(None) => chat,+ Err(error) => {+ tracing::debug!(error = %error, "Reading a chat's LID mapping failed");+ chat+ }+ }+}++/// A direct chat as Macro keys it: by phone number when the store knows it.+pub async fn macro_chat(lids: &dyn LidStore, chat: &str) -> String {+ let Ok(jid) = chat.parse::<Jid>() else {+ return chat.to_owned();+ };+ if jid.server != HIDDEN_USER_SERVER {+ return chat.to_owned();+ }+ match lids.get_pn_for_lid(&jid).await {+ Ok(Some(phone)) => phone.to_non_ad().to_string(),+ Ok(None) => chat.to_owned(),+ Err(error) => {+ tracing::debug!(error = %error, "Reading a chat's LID mapping failed");+ chat.to_owned()+ }+ }+}++/// Fills in addresses the message didn't carry from the account's LID store:+/// the sender's other address (see [`complete_sender`]) and a direct chat's+/// other address, so either addressing reaches the added chat. A store+/// failure is returned: without the other address the gate could drop a+/// message of an added chat, so the caller leaves it unacknowledged and+/// WhatsApp redelivers it.+pub async fn complete_addresses(+ lids: &dyn LidStore,+ event: &mut InboundEvent,+) -> Result<(), StoreError> {+ complete_sender(lids, event).await?;+ if event.chat_alternate_jid.is_some() {+ return Ok(());+ }+ let Ok(chat) = event.group_jid.parse::<Jid>() else {+ return Ok(());+ };+ let alternate = match chat.server.as_str() {+ HIDDEN_USER_SERVER => lids.get_pn_for_lid(&chat).await?,+ DEFAULT_USER_SERVER => lids.get_lid_for_pn(&chat).await?,+ _ => return Ok(()),+ };+ match alternate {+ Some(alternate) if alternate.server == DEFAULT_USER_SERVER => {+ // Direct chats go by phone number when it is known.+ event.chat_alternate_jid = Some(event.group_jid.clone());+ event.group_jid = alternate.to_non_ad().to_string();+ }+ alternate => event.chat_alternate_jid = alternate.as_ref().and_then(person),+ }+ Ok(())+}+/// Fills the other half of a message sender's phone-number/LID pair from the/// account's LID store, which whatsmeow fills at pairing (the account's own/// pair), from group participant lists and from message addressing. Without/// it a LID-only sender cannot be matched to the person already seen by phone/// number and is quarantined.-pub async fn complete_sender(lids: &dyn LidStore, event: &mut InboundEvent) {+pub async fn complete_sender(+ lids: &dyn LidStore,+ event: &mut InboundEvent,+) -> Result<(), StoreError> {let InboundKind::Message(message) = &mut event.kind else {- return;+ return Ok(());};let sender = &mut message.sender;if sender.alternate_jid.is_some() {- return;+ return Ok(());}let Ok(jid) = sender.jid.parse::<Jid>() else {- return;+ return Ok(());};let alternate = match jid.server.as_str() {- HIDDEN_USER_SERVER => lids.get_pn_for_lid(&jid).await,- DEFAULT_USER_SERVER => lids.get_lid_for_pn(&jid).await,- _ => return,+ HIDDEN_USER_SERVER => lids.get_pn_for_lid(&jid).await?,+ DEFAULT_USER_SERVER => lids.get_lid_for_pn(&jid).await?,+ _ => return Ok(()),};- match alternate {- Ok(alternate) => sender.alternate_jid = alternate.as_ref().and_then(person),- Err(error) => {- tracing::debug!(error = %error, "Reading a sender's LID mapping failed");- }- }+ sender.alternate_jid = alternate.as_ref().and_then(person);+ Ok(())}fn person(jid: &Jid) -> Option<String> {@@ -451,9 +514,7 @@ fn map_message(history: bool,) -> Option<InboundEvent> {let info = &event.info;- if info.chat.server != GROUP_SERVER {- return None;- }+ chat_of(info)?;let author = person(&info.sender)?;let source_at = info.timestamp.unwrap_or(now);let content = match event.message.as_ref() {@@ -461,7 +522,7 @@ fn map_message(if carries_only_keys(message) || message.poll_update_message.is_some() {return None;}- message_content(message, event.is_view_once, &author, source_at, seal)?+ message_content(message, &author, source_at, seal)?}// A history page keeps what happened in the group as stub messages.None => {@@ -516,9 +577,32 @@ impl Content<'_> {}}+/// Media WhatsApp shows once on the phone (the port unwraps the view-once+/// wrappers; the flag can also sit on the media itself). Macro keeps it.+fn message_view_once(message: Option<&wa_e2e::Message>) -> bool {+ message.is_some_and(|message| {+ message+ .image_message+ .as_ref()+ .and_then(|part| part.view_once)+ .or_else(|| {+ message+ .video_message+ .as_ref()+ .and_then(|part| part.view_once)+ })+ .or_else(|| {+ message+ .audio_message+ .as_ref()+ .and_then(|part| part.view_once)+ })+ .unwrap_or(false)+ })+}+fn message_content<'message>(message: &'message wa_e2e::Message,- view_once: bool,author: &str,source_at: DateTime<Utc>,seal: &dyn Fn(&MediaLocator) -> Option<Vec<u8>>,@@ -564,10 +648,6 @@ fn message_content<'message>(reaction.sender_timestamp_ms.unwrap_or(0),));}- // Shown once on the phone; Macro never keeps it.- if view_once {- return Some(Content::unsupported(VIEW_ONCE_TEXT));- }if let Some(pin) = message.pin_in_chat_message.as_ref() {let line = rich::pin_line(pin)?;return Some(Content {@@ -645,6 +725,8 @@ fn inbound_message(.collect()}).unwrap_or_default();+ let (group_jid, chat_alternate_jid) =+ chat_of(info).unwrap_or_else(|| (info.chat.to_non_ad().to_string(), None));InboundEvent {event_id: event_id(account,@@ -657,7 +739,8 @@ fn inbound_message(&revision_text,],),- group_jid: info.chat.to_non_ad().to_string(),+ group_jid,+ chat_alternate_jid,source_at: info.timestamp.unwrap_or(now),observed_at: now,kind: InboundKind::Message(Message {@@ -674,6 +757,7 @@ fn inbound_message(forwarded: content.context.is_some_and(|context| context.is_forwarded.unwrap_or(false)),+ view_once: event.is_view_once || message_view_once(event.message.as_ref()),rich: content.rich,}),}@@ -687,9 +771,7 @@ pub fn map_poll_vote(now: DateTime<Utc>,) -> Option<InboundEvent> {let info = &event.info;- if info.chat.server != GROUP_SERVER {- return None;- }+ chat_of(info)?;let author = person(&info.sender)?;let update = event.message.as_ref()?.poll_update_message.as_ref()?;let poll = target(update.poll_creation_message_key.as_ref()?, &author)?;@@ -725,6 +807,10 @@ pub fn history_poll_votes(let Some(poll_author) = person(&event.info.sender) else {return vec![];};+ let Some((group_jid, chat_alternate_jid)) = chat_of(&event.info) else {+ return vec![];+ };+ let direct = event.info.chat.server != GROUP_SERVER;let poll = Target {source_id: event.info.id.clone(),sender_jid: poll_author,@@ -735,6 +821,9 @@ pub fn history_poll_votes(let key = update.poll_update_message_key.as_ref()?;let voter = if key.from_me.unwrap_or(false) {person(&event.info.sender).filter(|_| event.info.is_from_me)?+ } else if direct {+ // A direct chat's only other voter is the other person.+ person_text(key.participant.as_deref().unwrap_or(&group_jid))?} else {person_text(key.participant.as_deref()?)?};@@ -754,7 +843,8 @@ pub fn history_poll_votes(&revision.to_string(),],),- group_jid: event.info.chat.to_non_ad().to_string(),+ group_jid: group_jid.clone(),+ chat_alternate_jid: chat_alternate_jid.clone(),source_at,observed_at: now,kind: InboundKind::Message(Message {@@ -773,6 +863,7 @@ pub fn history_poll_votes(media: vec![],mentions: vec![],forwarded: false,+ view_once: false,rich: Some(rich::poll_vote(&vote.selected_options)),}),})@@ -825,9 +916,11 @@ fn system_event(media: vec![],mentions: vec![],forwarded: false,+ view_once: false,rich: Some(RichContent::System(line)),}),group_jid: group,+ chat_alternate_jid: None,}}@@ -875,9 +968,10 @@ fn map_receipt(now: DateTime<Utc>,) -> Option<InboundEvent> {let source = &receipt.source;- if source.chat.server != GROUP_SERVER || receipt.message_ids.is_empty() {+ if receipt.message_ids.is_empty() {return None;}+ let (group_jid, chat_alternate_jid) = chat_of(source)?;let participant = person(&source.sender)?;let state = match receipt.r#type.as_str() {"" => ReceiptState::Delivered,@@ -902,7 +996,8 @@ fn map_receipt(&joined,],),- group_jid: source.chat.to_non_ad().to_string(),+ group_jid,+ chat_alternate_jid,source_at: receipt.timestamp.unwrap_or(now),observed_at: now,kind: InboundKind::Receipt(Receipt {@@ -913,6 +1008,32 @@ fn map_receipt(})}+/// The chat a message or receipt belongs to: the group, or a direct chat's+/// other person, by phone number when the addressing carries it, with their+/// other address. `None` for what isn't a chat (status, broadcasts, channels).+fn chat_of(source: &MessageSource) -> Option<(String, Option<String>)> {+ let chat = source.chat.to_non_ad();+ match chat_kind(&chat)? {+ ChatKind::Group => Some((chat.to_string(), None)),+ ChatKind::Direct => {+ let alternate = if source.is_from_me {+ &source.recipient_alt+ } else {+ &source.sender_alt+ };+ let other = (!alternate.is_empty() && alternate.server != chat.server)+ .then(|| alternate.to_non_ad())+ .filter(|other| chat_kind(other) == Some(ChatKind::Direct));+ Some(match other {+ Some(phone) if phone.server == DEFAULT_USER_SERVER => {+ (phone.to_string(), Some(chat.to_string()))+ }+ other => (chat.to_string(), other.map(|other| other.to_string())),+ })+ }+ }+}+/// A chat in the account's list: groups, and direct chats with people./// Status updates, broadcasts and channels are not chats.fn chat_kind(jid: &Jid) -> Option<ChatKind> {diff --git a/services/whatsapp_session_service/src/outbound/whatsapp/events/test.rs b/services/whatsapp_session_service/src/outbound/whatsapp/events/test.rsindex d2bde419a1..e2b0d46183 100644--- a/services/whatsapp_session_service/src/outbound/whatsapp/events/test.rs+++ b/services/whatsapp_session_service/src/outbound/whatsapp/events/test.rs@@ -202,7 +202,7 @@ fn a_quote_reaction_edit_and_delete_point_at_their_target() {}#[test]-fn media_becomes_a_placeholder_and_direct_chats_are_ignored() {+fn media_becomes_a_placeholder_and_status_updates_are_ignored() {let media = inbound(map_event(ACCOUNT,&group_message(@@ -220,10 +220,10 @@ fn media_becomes_a_placeholder_and_direct_chats_are_ignored() {};assert_eq!(media.kind, MessageKind::Unsupported);- let direct = Event::Message(Box::new(Message {+ let status = Event::Message(Box::new(Message {info: MessageInfo {source: MessageSource {- chat: "[email protected]".parse().unwrap(),+ chat: "status@broadcast".parse().unwrap(),sender: "[email protected]".parse().unwrap(),..MessageSource::default()},@@ -231,12 +231,96 @@ fn media_becomes_a_placeholder_and_direct_chats_are_ignored() {..MessageInfo::default()},message: Some(wa_e2e::Message {- conversation: Some("private".to_owned()),+ conversation: Some("my status".to_owned()),..Default::default()}),..Message::default()}));- assert!(map_event(ACCOUNT, &direct, now(), &plain_locator).is_empty());+ assert!(map_event(ACCOUNT, &status, now(), &plain_locator).is_empty());+}++fn direct_message(source: MessageSource, text: &str) -> Event {+ Event::Message(Box::new(Message {+ info: MessageInfo {+ source,+ id: "3EB0DM".to_owned(),+ timestamp: Some(Utc.with_ymd_and_hms(2026, 10, 21, 11, 59, 0).unwrap()),+ ..MessageInfo::default()+ },+ message: Some(wa_e2e::Message {+ conversation: Some(text.to_owned()),+ ..Default::default()+ }),+ ..Message::default()+ }))+}++#[test]+fn a_direct_chat_goes_by_the_persons_number_with_their_lid_alongside() {+ // WhatsApp addresses the chat by LID and names the number alongside.+ let by_lid = inbound(map_event(+ ACCOUNT,+ &direct_message(+ MessageSource {+ chat: "987654321@lid".parse().unwrap(),+ sender: "987654321@lid".parse().unwrap(),+ sender_alt: "[email protected]".parse().unwrap(),+ ..MessageSource::default()+ },+ "hi",+ ),+ now(),+ &plain_locator,+ ));+ assert_eq!(+ (+ by_lid.group_jid.as_str(),+ by_lid.chat_alternate_jid.as_deref()+ ),+ ("[email protected]", Some("987654321@lid"))+ );+ // Our own message from the phone names the recipient's other address.+ let own = inbound(map_event(+ ACCOUNT,+ &direct_message(+ MessageSource {+ chat: "[email protected]".parse().unwrap(),+ sender: "[email protected]".parse().unwrap(),+ recipient_alt: "987654321@lid".parse().unwrap(),+ is_from_me: true,+ ..MessageSource::default()+ },+ "on it",+ ),+ now(),+ &plain_locator,+ ));+ assert_eq!(+ (own.group_jid.as_str(), own.chat_alternate_jid.as_deref()),+ ("[email protected]", Some("987654321@lid"))+ );+ let InboundKind::Message(message) = own.kind else {+ panic!("expected a message");+ };+ assert!(message.from_me);+ // Without the other address, the chat stays as addressed.+ let bare = inbound(map_event(+ ACCOUNT,+ &direct_message(+ MessageSource {+ chat: "987654321@lid".parse().unwrap(),+ sender: "987654321@lid".parse().unwrap(),+ ..MessageSource::default()+ },+ "hello",+ ),+ now(),+ &plain_locator,+ ));+ assert_eq!(+ (bare.group_jid.as_str(), bare.chat_alternate_jid),+ ("987654321@lid", None)+ );}#[test]@@ -493,7 +577,7 @@ async fn a_message_from_me_addressed_by_lid_carries_the_from_me_flag_and_own_pai&plain_locator,));- super::complete_sender(&lids, &mut event).await;+ super::complete_sender(&lids, &mut event).await.unwrap();assert_eq!(sender_of(&event),@@ -528,8 +612,8 @@ async fn another_member_addressed_only_by_lid_is_paired_from_the_lid_store() {&plain_locator,));- super::complete_sender(&lids, &mut known).await;- super::complete_sender(&lids, &mut unknown).await;+ super::complete_sender(&lids, &mut known).await.unwrap();+ super::complete_sender(&lids, &mut unknown).await.unwrap();assert_eq!(sender_of(&known),@@ -929,33 +1013,37 @@ fn pins_and_call_logs_become_system_lines() {}#[test]-fn view_once_media_stays_a_placeholder() {- let mut event = group_message(- "3EB0ONCE",- wa_e2e::Message {- image_message: Some(Box::new(wa_e2e::ImageMessage {- media_key: Some(vec![1; 32]),- file_enc_sha256: Some(vec![2; 32]),- file_sha256: Some(vec![3; 32]),- file_length: Some(10),- mimetype: Some("image/jpeg".to_owned()),- ..Default::default()- })),+fn view_once_media_is_kept_like_any_media_and_marked() {+ let image = |view_once_flag: Option<bool>| wa_e2e::Message {+ image_message: Some(Box::new(wa_e2e::ImageMessage {+ direct_path: Some("/v/once".to_owned()),+ media_key: Some(vec![1; 32]),+ file_enc_sha256: Some(vec![2; 32]),+ file_sha256: Some(vec![3; 32]),+ file_length: Some(10),+ mimetype: Some("image/jpeg".to_owned()),+ caption: Some("just once".to_owned()),+ view_once: view_once_flag,..Default::default()- },- );- if let Event::Message(message) = &mut event {+ })),+ ..Default::default()+ };+ // Unwrapped from a view-once wrapper by the port.+ let mut wrapped = group_message("3EB0ONCE", image(None));+ if let Event::Message(message) = &mut wrapped {message.is_view_once = true;}+ // Flagged on the media itself.+ let flagged = group_message("3EB0ONCE2", image(Some(true)));- let message = media_message(&event);-- assert_eq!(message.kind, MessageKind::Unsupported);- assert_eq!(- message.text,- "View-once message \u{2014} open it on your phone"- );- assert!(message.media.is_empty());+ for event in [wrapped, flagged] {+ let message = media_message(&event);+ assert_eq!(message.kind, MessageKind::Text);+ assert_eq!(message.text, "just once");+ assert_eq!(message.media.len(), 1, "the image is imported");+ assert!(message.view_once);+ }+ assert!(!media_message(&group_message("3EB0PLAIN", image(None))).view_once);}#[test]@@ -1139,3 +1227,72 @@ fn history_stub_messages_become_system_lines() {assert_eq!(line.action, SystemAction::ParticipantsAdded);assert_eq!(line.participants, vec!["[email protected]"]);}++/// A LID store that cannot be read.+struct BrokenLids;++#[async_trait::async_trait]+impl whatsmeow::store::LidStore for BrokenLids {+ async fn put_many_lid_mappings(+ &self,+ _mappings: &[whatsmeow::store::LidMapping],+ ) -> Result<(), whatsmeow::store::StoreError> {+ Err(whatsmeow::store::StoreError::StoreIsNil)+ }++ async fn put_lid_mapping(+ &self,+ _lid: &whatsmeow::types::Jid,+ _jid: &whatsmeow::types::Jid,+ ) -> Result<(), whatsmeow::store::StoreError> {+ Err(whatsmeow::store::StoreError::StoreIsNil)+ }++ async fn get_pn_for_lid(+ &self,+ _lid: &whatsmeow::types::Jid,+ ) -> Result<Option<whatsmeow::types::Jid>, whatsmeow::store::StoreError> {+ Err(whatsmeow::store::StoreError::StoreIsNil)+ }++ async fn get_lid_for_pn(+ &self,+ _pn: &whatsmeow::types::Jid,+ ) -> Result<Option<whatsmeow::types::Jid>, whatsmeow::store::StoreError> {+ Err(whatsmeow::store::StoreError::StoreIsNil)+ }++ async fn get_many_lids_for_pns(+ &self,+ _pns: &[whatsmeow::types::Jid],+ ) -> Result<+ std::collections::HashMap<whatsmeow::types::Jid, whatsmeow::types::Jid>,+ whatsmeow::store::StoreError,+ > {+ Err(whatsmeow::store::StoreError::StoreIsNil)+ }+}++/// Without the other address the gate could drop a message of an added+/// direct chat as unadopted, so a store failure must reach the caller, which+/// leaves the message unacknowledged for WhatsApp to redeliver.+#[tokio::test]+async fn a_lid_store_failure_is_reported_instead_of_completing_nothing() {+ let mut event = inbound(map_event(+ ACCOUNT,+ &lid_message("3EB0F004", "987654321@lid", false),+ now(),+ &plain_locator,+ ));++ assert!(+ super::complete_addresses(&BrokenLids, &mut event)+ .await+ .is_err()+ );+ assert!(+ super::complete_sender(&BrokenLids, &mut event)+ .await+ .is_err()+ );+}diff --git a/services/whatsapp_session_service/src/outbound/whatsapp/test.rs b/services/whatsapp_session_service/src/outbound/whatsapp/test.rsindex b8fc8718c8..721420ed29 100644--- a/services/whatsapp_session_service/src/outbound/whatsapp/test.rs+++ b/services/whatsapp_session_service/src/outbound/whatsapp/test.rs@@ -12,7 +12,7 @@ use tokio_util::sync::CancellationToken;use uuid::Uuid;use whatsapp_fake_server::{FakeWhatsApp, test_signal};use whatsapp_linked::domain::events::{- AttachmentRef, ClaimedSend, InboundEvent, InboundKind, MediaImport, OutboundMedia,+ AttachmentRef, ClaimedSend, InboundEvent, InboundKind, MediaImport, MediaShape, OutboundMedia,OutgoingContent, SessionScope,};use whatsapp_linked::domain::models::MediaKind;@@ -343,7 +343,13 @@ async fn attachments_travel_both_ways_with_a_sealed_locator(pool: PgPool) {filename: "reply.jpg".to_owned(),caption: Some("from macro".to_owned()),quote: None,+ shape: MediaShape {+ width: Some(800),+ height: Some(600),+ duration_seconds: None,+ },},+ disappearing_seconds: Some(86_400),traceparent: None,};let message_id = session.new_message_id().await;@@ -356,9 +362,110 @@ async fn attachments_travel_both_ways_with_a_sealed_locator(pool: PgPool) {.await.expect("the peer's phone receives the image");assert_eq!(peer.download_image(&delivered).await.unwrap(), reply);+ let image = delivered+ .message+ .image_message+ .as_deref()+ .expect("an image message");+ assert_eq!(+ (image.width, image.height),+ (Some(800), Some(600)),+ "the phone can reserve the space"+ );+ assert_eq!(+ image+ .context_info+ .as_ref()+ .and_then(|context| context.expiration),+ Some(86_400),+ "the image disappears like the group's own messages"+ );session.disconnect().await;}+#[test]+fn group_metadata_keeps_the_timer_and_tells_a_community_from_its_groups() {+ use whatsmeow::types::{+ GroupEphemeral, GroupInfo as WhatsAppGroup, GroupIsDefaultSub, GroupLinkedParent,+ GroupName, GroupParent,+ };+ let community: whatsmeow::types::Jid = "[email protected]".parse().unwrap();+ let group = |jid: &str| WhatsAppGroup {+ jid: jid.parse().unwrap(),+ name: GroupName {+ name: "Neighbours".to_owned(),+ ..GroupName::default()+ },+ ..WhatsAppGroup::default()+ };+ let observed_at = chrono::Utc::now();++ let parent = super::group_info(+ WhatsAppGroup {+ parent: GroupParent {+ is_parent: true,+ ..GroupParent::default()+ },+ ..group("[email protected]")+ },+ observed_at,+ );+ assert!(parent.community_parent);+ assert_eq!(parent.community_jid, None);++ let announcements = super::group_info(+ WhatsAppGroup {+ linked_parent: GroupLinkedParent {+ linked_parent_jid: community.clone(),+ },+ is_default_sub: GroupIsDefaultSub {+ is_default_sub_group: true,+ },+ ..group("[email protected]")+ },+ observed_at,+ );+ assert!(!announcements.community_parent);+ assert_eq!(+ announcements.community_jid.as_deref(),+ Some("[email protected]")+ );+ assert!(announcements.community_announcements);++ let vanishing = super::group_info(+ WhatsAppGroup {+ ephemeral: GroupEphemeral {+ is_ephemeral: true,+ disappearing_timer: 604_800,+ },+ linked_parent: GroupLinkedParent {+ linked_parent_jid: community,+ },+ ..group("[email protected]")+ },+ observed_at,+ );+ assert_eq!(vanishing.disappearing_seconds, Some(604_800));+ assert!(!vanishing.community_announcements);+ assert_eq!(+ super::group_info(group("[email protected]"), observed_at).disappearing_seconds,+ None+ );+ // A group that had disappearing messages and turned them off: WhatsApp+ // still lists `<ephemeral expiration="0"/>`.+ let turned_off = super::group_info(+ WhatsAppGroup {+ ephemeral: GroupEphemeral {+ is_ephemeral: true,+ disappearing_timer: 0,+ },+ ..group("[email protected]")+ },+ observed_at,+ );+ assert_eq!(turned_off.disappearing_seconds, None);+}+/// IQ errors keep the whole response node, whose attributes carry JIDs; the/// session error's message (what `%error` logs) must not repeat them.#[test]