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(auth): add agent accounts (#9520)
Eric Hayes43776ecb84d6
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.jsonindex 8320fa47dd..d11766c28b 100644--- a/.github/workspace-dep-closures.json+++ b/.github/workspace-dep-closures.json@@ -2487,6 +2487,7 @@"crates/trigger_context","crates/unfurl","crates/upstream_error",+ "crates/user_api_key","crates/user_language","crates/user_quota","crates/workspace-hack",diff --git a/.sqlx/query-beeb3f92cd18664a6d748be12f52f8051602e6d2aaf7d5194af235e77902265b.json b/.sqlx/query-039cee00e19f73d0699d04933834137f83b5eae4755d35e04355a43e780295a9.jsonsimilarity index 60%rename from .sqlx/query-beeb3f92cd18664a6d748be12f52f8051602e6d2aaf7d5194af235e77902265b.jsonrename to .sqlx/query-039cee00e19f73d0699d04933834137f83b5eae4755d35e04355a43e780295a9.jsonindex 2fc35ddbb8..d2c3b07ee7 100644--- a/.sqlx/query-beeb3f92cd18664a6d748be12f52f8051602e6d2aaf7d5194af235e77902265b.json+++ b/.sqlx/query-039cee00e19f73d0699d04933834137f83b5eae4755d35e04355a43e780295a9.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n WITH requested_ids AS (\n SELECT DISTINCT id\n FROM UNNEST($2::text[]) AS requested(id)\n )\n SELECT\n req.id as \"user_profile_id!\",\n CASE\n WHEN NULLIF(mui.first_name, 'N/A') IS NOT NULL\n OR NULLIF(mui.last_name, 'N/A') IS NOT NULL\n THEN NULLIF(mui.first_name, 'N/A')\n ELSE SPLIT_PART(contact.name, ' ', 1)\n END as \"first_name\",\n CASE\n WHEN NULLIF(mui.first_name, 'N/A') IS NOT NULL\n OR NULLIF(mui.last_name, 'N/A') IS NOT NULL\n THEN NULLIF(mui.last_name, 'N/A')\n ELSE CASE\n WHEN POSITION(' ' IN contact.name) > 0\n THEN NULLIF(TRIM(SUBSTRING(contact.name FROM POSITION(' ' IN contact.name) + 1)), '')\n ELSE NULL\n END\n END as \"last_name\"\n FROM requested_ids req\n LEFT JOIN \"User\" u ON u.id = req.id\n LEFT JOIN macro_user_info mui ON mui.macro_user_id = u.macro_user_id\n LEFT JOIN LATERAL (\n SELECT ec.name\n FROM email_links li\n JOIN email_contacts ec\n ON ec.link_id = li.id\n AND ec.email_address = REPLACE(req.id, 'macro|', '')\n AND ec.name IS NOT NULL\n WHERE li.macro_id = $1\n AND NULLIF(mui.first_name, 'N/A') IS NULL\n AND NULLIF(mui.last_name, 'N/A') IS NULL\n LIMIT 1\n ) contact ON TRUE\n WHERE u.id IS NOT NULL OR contact.name IS NOT NULL\n ",+ "query": "\n WITH requested_ids AS (\n SELECT DISTINCT id\n FROM UNNEST($2::text[]) AS requested(id)\n )\n SELECT\n req.id as \"user_profile_id!\",\n CASE\n WHEN NULLIF(mui.first_name, 'N/A') IS NOT NULL\n OR NULLIF(mui.last_name, 'N/A') IS NOT NULL\n THEN NULLIF(mui.first_name, 'N/A')\n ELSE SPLIT_PART(contact.name, ' ', 1)\n END as \"first_name\",\n CASE\n WHEN NULLIF(mui.first_name, 'N/A') IS NOT NULL\n OR NULLIF(mui.last_name, 'N/A') IS NOT NULL\n THEN NULLIF(mui.last_name, 'N/A')\n ELSE CASE\n WHEN POSITION(' ' IN contact.name) > 0\n THEN NULLIF(TRIM(SUBSTRING(contact.name FROM POSITION(' ' IN contact.name) + 1)), '')\n ELSE NULL\n END\n END as \"last_name\",\n COALESCE(u.\"isAgent\", FALSE) as \"is_agent!\"\n FROM requested_ids req\n LEFT JOIN \"User\" u ON u.id = req.id\n LEFT JOIN macro_user_info mui ON mui.macro_user_id = u.macro_user_id\n LEFT JOIN LATERAL (\n SELECT ec.name\n FROM email_links li\n JOIN email_contacts ec\n ON ec.link_id = li.id\n AND ec.email_address = REPLACE(req.id, 'macro|', '')\n AND ec.name IS NOT NULL\n WHERE li.macro_id = $1\n AND NULLIF(mui.first_name, 'N/A') IS NULL\n AND NULLIF(mui.last_name, 'N/A') IS NULL\n LIMIT 1\n ) contact ON TRUE\n WHERE u.id IS NOT NULL OR contact.name IS NOT NULL\n ","describe": {"columns": [{@@ -17,6 +17,11 @@"ordinal": 2,"name": "last_name","type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "is_agent!",+ "type_info": "Bool"}],"parameters": {@@ -26,10 +31,11 @@]},"nullable": [+ null,null,null,null]},- "hash": "beeb3f92cd18664a6d748be12f52f8051602e6d2aaf7d5194af235e77902265b"+ "hash": "039cee00e19f73d0699d04933834137f83b5eae4755d35e04355a43e780295a9"}diff --git a/.sqlx/query-0dfab4ecc9eaf44b8968baedf3c0d41d33324787a7adc56c978ba0766baa2776.json b/.sqlx/query-0dfab4ecc9eaf44b8968baedf3c0d41d33324787a7adc56c978ba0766baa2776.jsonnew file mode 100644index 0000000000..df3e4b2975--- /dev/null+++ b/.sqlx/query-0dfab4ecc9eaf44b8968baedf3c0d41d33324787a7adc56c978ba0766baa2776.json@@ -0,0 +1,57 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO team_invite (id, team_id, email, team_role, invited_by, created_at, last_sent_at, is_agent)\n SELECT\n t.id,\n $1::uuid,\n t.email,\n $2,\n $3::text,\n NOW(),\n NOW(),\n $7\n FROM UNNEST($4::uuid[], $5::text[], $6::text[]) AS t(id, email, user_id)\n WHERE NOT EXISTS (\n SELECT 1 FROM team_invite ti\n WHERE ti.team_id = $1 AND ti.email = t.email\n )\n AND NOT EXISTS (\n SELECT 1 FROM team_user tu\n WHERE tu.team_id = $1 AND tu.user_id = t.user_id\n )\n RETURNING id, team_id, email, is_agent\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "team_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 2,+ "name": "email",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "is_agent",+ "type_info": "Bool"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ {+ "Custom": {+ "name": "team_role",+ "kind": {+ "Enum": [+ "member",+ "admin",+ "owner"+ ]+ }+ }+ },+ "Text",+ "UuidArray",+ "TextArray",+ "TextArray",+ "Bool"+ ]+ },+ "nullable": [+ false,+ false,+ false,+ false+ ]+ },+ "hash": "0dfab4ecc9eaf44b8968baedf3c0d41d33324787a7adc56c978ba0766baa2776"+}diff --git a/.sqlx/query-0e433db925889fcec1e978b5665608874656ee98d7f7753c9fed812acf497a7d.json b/.sqlx/query-0e433db925889fcec1e978b5665608874656ee98d7f7753c9fed812acf497a7d.jsonnew file mode 100644index 0000000000..fdfb3b7534--- /dev/null+++ b/.sqlx/query-0e433db925889fcec1e978b5665608874656ee98d7f7753c9fed812acf497a7d.json@@ -0,0 +1,40 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n u.macro_user_id,\n mui.first_name as \"first_name?\",\n mui.last_name as \"last_name?\",\n BOOL_OR(u.\"isAgent\") as \"is_agent!\"\n FROM \"User\" u\n LEFT JOIN macro_user_info mui ON mui.macro_user_id = u.macro_user_id\n WHERE u.macro_user_id = $1\n GROUP BY u.macro_user_id, mui.first_name, mui.last_name\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "macro_user_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "first_name?",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "last_name?",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "is_agent!",+ "type_info": "Bool"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false,+ true,+ true,+ null+ ]+ },+ "hash": "0e433db925889fcec1e978b5665608874656ee98d7f7753c9fed812acf497a7d"+}diff --git a/.sqlx/query-24fac9cdfa3f780c4ca0454b7ac500ea58384a4e6fd0ae0ca389f61550d3aabb.json b/.sqlx/query-4b73da8b8a6d136cecb16e632b30ed66531ffd6ffbcd616c448655e46b906cdb.jsonsimilarity index 91%rename from .sqlx/query-24fac9cdfa3f780c4ca0454b7ac500ea58384a4e6fd0ae0ca389f61550d3aabb.jsonrename to .sqlx/query-4b73da8b8a6d136cecb16e632b30ed66531ffd6ffbcd616c448655e46b906cdb.jsonindex 739ea60507..0f178c57f7 100644--- a/.sqlx/query-24fac9cdfa3f780c4ca0454b7ac500ea58384a4e6fd0ae0ca389f61550d3aabb.json+++ b/.sqlx/query-4b73da8b8a6d136cecb16e632b30ed66531ffd6ffbcd616c448655e46b906cdb.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n WITH due AS (\n SELECT ti.id\n FROM team_invite ti\n JOIN team t ON t.id = ti.team_id\n WHERE ti.created_at > NOW() - INTERVAL '14 days'\n AND (\n (ti.reminders_sent = 0 AND ti.last_sent_at <= NOW() - INTERVAL '3 days')\n OR (ti.reminders_sent = 1 AND ti.last_sent_at <= NOW() - INTERVAL '4 days')\n )\n AND (t.enterprise OR t.paying OR t.subscription_id IS NULL)\n AND EXISTS (\n SELECT 1 FROM team_user tu\n WHERE tu.team_id = ti.team_id AND tu.user_id = ti.invited_by\n )\n AND NOT EXISTS (\n SELECT 1 FROM team_user tu\n WHERE tu.team_id = ti.team_id AND tu.user_id = 'macro|' || ti.email\n )\n ORDER BY ti.created_at\n LIMIT $1\n FOR UPDATE OF ti SKIP LOCKED\n )\n UPDATE team_invite ti\n SET reminders_sent = ti.reminders_sent + 1,\n last_sent_at = NOW()\n FROM due, team t\n WHERE ti.id = due.id AND t.id = ti.team_id\n RETURNING\n ti.id,\n ti.team_id,\n t.name AS team_name,\n ti.email,\n ti.invited_by,\n ti.reminders_sent,\n t.enterprise,\n t.paying,\n t.subscription_id IS NOT NULL AS \"has_subscription!\"\n ",+ "query": "\n WITH due AS (\n SELECT ti.id\n FROM team_invite ti\n JOIN team t ON t.id = ti.team_id\n WHERE ti.created_at > NOW() - INTERVAL '14 days'\n AND (\n (ti.reminders_sent = 0 AND ti.last_sent_at <= NOW() - INTERVAL '3 days')\n OR (ti.reminders_sent = 1 AND ti.last_sent_at <= NOW() - INTERVAL '4 days')\n )\n AND (t.enterprise OR t.paying OR t.subscription_id IS NULL)\n AND EXISTS (\n SELECT 1 FROM team_user tu\n WHERE tu.team_id = ti.team_id AND tu.user_id = ti.invited_by\n )\n AND NOT EXISTS (\n SELECT 1 FROM team_user tu\n WHERE tu.team_id = ti.team_id AND tu.user_id = 'macro|' || ti.email\n )\n ORDER BY ti.created_at\n LIMIT $1\n FOR UPDATE OF ti SKIP LOCKED\n )\n UPDATE team_invite ti\n SET reminders_sent = ti.reminders_sent + 1,\n last_sent_at = NOW()\n FROM due, team t\n WHERE ti.id = due.id AND t.id = ti.team_id\n RETURNING\n ti.id,\n ti.team_id,\n t.name AS team_name,\n ti.email,\n ti.invited_by,\n ti.reminders_sent,\n t.enterprise,\n t.paying,\n t.subscription_id IS NOT NULL AS \"has_subscription!\",\n ti.is_agent\n ","describe": {"columns": [{@@ -47,6 +47,11 @@"ordinal": 8,"name": "has_subscription!","type_info": "Bool"+ },+ {+ "ordinal": 9,+ "name": "is_agent",+ "type_info": "Bool"}],"parameters": {@@ -63,8 +68,9 @@false,false,false,- null+ null,+ false]},- "hash": "24fac9cdfa3f780c4ca0454b7ac500ea58384a4e6fd0ae0ca389f61550d3aabb"+ "hash": "4b73da8b8a6d136cecb16e632b30ed66531ffd6ffbcd616c448655e46b906cdb"}diff --git a/.sqlx/query-4c32958c36e27ce1c888c698d4a9acab528633579fa562f4b287cb4ee7c7fa2e.json b/.sqlx/query-4c32958c36e27ce1c888c698d4a9acab528633579fa562f4b287cb4ee7c7fa2e.jsondeleted file mode 100644index 16492a93d5..0000000000--- a/.sqlx/query-4c32958c36e27ce1c888c698d4a9acab528633579fa562f4b287cb4ee7c7fa2e.json+++ /dev/null@@ -1,14 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "INSERT INTO pipedream_mcp_connections (user_id, app_slug, server_name, account_id)\n VALUES ($1, 'linear', 'Linear', 'apn_linear')",- "describe": {- "columns": [],- "parameters": {- "Left": [- "Text"- ]- },- "nullable": []- },- "hash": "4c32958c36e27ce1c888c698d4a9acab528633579fa562f4b287cb4ee7c7fa2e"-}diff --git a/.sqlx/query-ae5a21740f17c450f53a07e833b6ab8dc226dd06869786792add6fe5535da1e7.json b/.sqlx/query-4cd34eaa61747332f77748c9f591fbf7a4841de9990414010d3cba9926b1fcb3.jsonsimilarity index 59%rename from .sqlx/query-ae5a21740f17c450f53a07e833b6ab8dc226dd06869786792add6fe5535da1e7.jsonrename to .sqlx/query-4cd34eaa61747332f77748c9f591fbf7a4841de9990414010d3cba9926b1fcb3.jsonindex 508ef4caee..548746bf24 100644--- a/.sqlx/query-ae5a21740f17c450f53a07e833b6ab8dc226dd06869786792add6fe5535da1e7.json+++ b/.sqlx/query-4cd34eaa61747332f77748c9f591fbf7a4841de9990414010d3cba9926b1fcb3.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT id, email, team_id\n FROM team_invite\n WHERE id = $1\n ",+ "query": "\n SELECT id, email, team_id, is_agent\n FROM team_invite\n WHERE id = $1\n ","describe": {"columns": [{@@ -17,6 +17,11 @@"ordinal": 2,"name": "team_id","type_info": "Uuid"+ },+ {+ "ordinal": 3,+ "name": "is_agent",+ "type_info": "Bool"}],"parameters": {@@ -25,10 +30,11 @@]},"nullable": [+ false,false,false,false]},- "hash": "ae5a21740f17c450f53a07e833b6ab8dc226dd06869786792add6fe5535da1e7"+ "hash": "4cd34eaa61747332f77748c9f591fbf7a4841de9990414010d3cba9926b1fcb3"}diff --git a/.sqlx/query-d8dfd71f5f0d103ff143998cb13f4ab6360b2e3b937aef86365ca9fa4a2385df.json b/.sqlx/query-5cacb4da574145a70273b08312c495f84e41fca3a0a44ce88bdd064883b438bd.jsonsimilarity index 54%rename from .sqlx/query-d8dfd71f5f0d103ff143998cb13f4ab6360b2e3b937aef86365ca9fa4a2385df.jsonrename to .sqlx/query-5cacb4da574145a70273b08312c495f84e41fca3a0a44ce88bdd064883b438bd.jsonindex 656d1b2ad8..cc56f7fc98 100644--- a/.sqlx/query-d8dfd71f5f0d103ff143998cb13f4ab6360b2e3b937aef86365ca9fa4a2385df.json+++ b/.sqlx/query-5cacb4da574145a70273b08312c495f84e41fca3a0a44ce88bdd064883b438bd.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT id, team_id, email\n FROM team_invite\n WHERE team_id = $1\n AND email = ANY($2::text[])\n AND last_sent_at <= NOW() - make_interval(secs => $3)\n ",+ "query": "\n SELECT id, team_id, email, is_agent\n FROM team_invite\n WHERE team_id = $1\n AND email = ANY($2::text[])\n AND last_sent_at <= NOW() - make_interval(secs => $3)\n ","describe": {"columns": [{@@ -17,6 +17,11 @@"ordinal": 2,"name": "email","type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "is_agent",+ "type_info": "Bool"}],"parameters": {@@ -27,10 +32,11 @@]},"nullable": [+ false,false,false,false]},- "hash": "d8dfd71f5f0d103ff143998cb13f4ab6360b2e3b937aef86365ca9fa4a2385df"+ "hash": "5cacb4da574145a70273b08312c495f84e41fca3a0a44ce88bdd064883b438bd"}diff --git a/.sqlx/query-61e82a1be0d1352b8a1147bbff2dc3bd8e945b75380f112bb1118491b3d03f96.json b/.sqlx/query-61e82a1be0d1352b8a1147bbff2dc3bd8e945b75380f112bb1118491b3d03f96.jsondeleted file mode 100644index d8e19e46a0..0000000000--- a/.sqlx/query-61e82a1be0d1352b8a1147bbff2dc3bd8e945b75380f112bb1118491b3d03f96.json+++ /dev/null@@ -1,50 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n INSERT INTO team_invite (id, team_id, email, team_role, invited_by, created_at, last_sent_at)\n SELECT\n t.id,\n $1::uuid,\n t.email,\n $2,\n $3::text,\n NOW(),\n NOW()\n FROM UNNEST($4::uuid[], $5::text[], $6::text[]) AS t(id, email, user_id)\n WHERE NOT EXISTS (\n SELECT 1 FROM team_invite ti\n WHERE ti.team_id = $1 AND ti.email = t.email\n )\n AND NOT EXISTS (\n SELECT 1 FROM team_user tu\n WHERE tu.team_id = $1 AND tu.user_id = t.user_id\n )\n RETURNING id, team_id, email\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "id",- "type_info": "Uuid"- },- {- "ordinal": 1,- "name": "team_id",- "type_info": "Uuid"- },- {- "ordinal": 2,- "name": "email",- "type_info": "Text"- }- ],- "parameters": {- "Left": [- "Uuid",- {- "Custom": {- "name": "team_role",- "kind": {- "Enum": [- "member",- "admin",- "owner"- ]- }- }- },- "Text",- "UuidArray",- "TextArray",- "TextArray"- ]- },- "nullable": [- false,- false,- false- ]- },- "hash": "61e82a1be0d1352b8a1147bbff2dc3bd8e945b75380f112bb1118491b3d03f96"-}diff --git a/.sqlx/query-64b7fea5e183b50cebc03b9332ecd854b5f3bf535d835300e7c772f568677bce.json b/.sqlx/query-64b7fea5e183b50cebc03b9332ecd854b5f3bf535d835300e7c772f568677bce.jsonnew file mode 100644index 0000000000..64767220f4--- /dev/null+++ b/.sqlx/query-64b7fea5e183b50cebc03b9332ecd854b5f3bf535d835300e7c772f568677bce.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT 1 AS \"locked!\" FROM \"User\" WHERE id = $1 FOR UPDATE",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "locked!",+ "type_info": "Int4"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ null+ ]+ },+ "hash": "64b7fea5e183b50cebc03b9332ecd854b5f3bf535d835300e7c772f568677bce"+}diff --git a/.sqlx/query-76caf706a1f0846ad3a7075878e941a9293a5eeeb1de3900c3c39386d5dc57c0.json b/.sqlx/query-76caf706a1f0846ad3a7075878e941a9293a5eeeb1de3900c3c39386d5dc57c0.jsondeleted file mode 100644index 8f83e9a7d1..0000000000--- a/.sqlx/query-76caf706a1f0846ad3a7075878e941a9293a5eeeb1de3900c3c39386d5dc57c0.json+++ /dev/null@@ -1,34 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n SELECT macro_user_id, first_name, last_name FROM macro_user_info WHERE macro_user_id = $1\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "macro_user_id",- "type_info": "Uuid"- },- {- "ordinal": 1,- "name": "first_name",- "type_info": "Text"- },- {- "ordinal": 2,- "name": "last_name",- "type_info": "Text"- }- ],- "parameters": {- "Left": [- "Uuid"- ]- },- "nullable": [- false,- true,- true- ]- },- "hash": "76caf706a1f0846ad3a7075878e941a9293a5eeeb1de3900c3c39386d5dc57c0"-}diff --git a/.sqlx/query-92d726292a9cbe88efbfbb2a07c245b0dfd0dfcdd308f23084b7f076c26462b7.json b/.sqlx/query-7fea7c108193d97c72fd70cee441f196cfc65e9320e4838a06878447a664270b.jsonsimilarity index 71%rename from .sqlx/query-92d726292a9cbe88efbfbb2a07c245b0dfd0dfcdd308f23084b7f076c26462b7.jsonrename to .sqlx/query-7fea7c108193d97c72fd70cee441f196cfc65e9320e4838a06878447a664270b.jsonindex a7d36b84a3..11e5913c70 100644--- a/.sqlx/query-92d726292a9cbe88efbfbb2a07c245b0dfd0dfcdd308f23084b7f076c26462b7.json+++ b/.sqlx/query-7fea7c108193d97c72fd70cee441f196cfc65e9320e4838a06878447a664270b.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT\n u.\"id\" as \"user_id\",\n u.\"email\" as \"email\",\n u.\"stripeCustomerId\" as \"stripe_customer_id?\",\n u.\"name\" as name,\n u.\"tutorialComplete\" as tutorial_complete,\n u.\"group\" as \"group?\",\n u.\"hasChromeExt\" as has_chrome_ext,\n u.\"aiDataConsent\" as ai_data_consent,\n mu.has_trialed as has_trialed,\n u.macro_user_id as \"macro_user_id\",\n u.\"createdAt\" as \"created_at?\"\n FROM \"User\" u\n JOIN \"macro_user\" mu ON u.macro_user_id = mu.id\n WHERE u.\"id\" = $1\n ",+ "query": "\n SELECT\n u.\"id\" as \"user_id\",\n u.\"email\" as \"email\",\n u.\"stripeCustomerId\" as \"stripe_customer_id?\",\n u.\"name\" as name,\n u.\"tutorialComplete\" as tutorial_complete,\n u.\"isAgent\" as is_agent,\n u.\"group\" as \"group?\",\n u.\"hasChromeExt\" as has_chrome_ext,\n u.\"aiDataConsent\" as ai_data_consent,\n mu.has_trialed as has_trialed,\n u.macro_user_id as \"macro_user_id\",\n u.\"createdAt\" as \"created_at?\"\n FROM \"User\" u\n JOIN \"macro_user\" mu ON u.macro_user_id = mu.id\n WHERE u.\"id\" = $1\n ","describe": {"columns": [{@@ -30,31 +30,36 @@},{"ordinal": 5,+ "name": "is_agent",+ "type_info": "Bool"+ },+ {+ "ordinal": 6,"name": "group?","type_info": "Varchar"},{- "ordinal": 6,+ "ordinal": 7,"name": "has_chrome_ext","type_info": "Bool"},{- "ordinal": 7,+ "ordinal": 8,"name": "ai_data_consent","type_info": "Bool"},{- "ordinal": 8,+ "ordinal": 9,"name": "has_trialed","type_info": "Bool"},{- "ordinal": 9,+ "ordinal": 10,"name": "macro_user_id","type_info": "Uuid"},{- "ordinal": 10,+ "ordinal": 11,"name": "created_at?","type_info": "Timestamptz"}@@ -70,6 +75,7 @@true,true,false,+ false,true,false,false,@@ -78,5 +84,5 @@true]},- "hash": "92d726292a9cbe88efbfbb2a07c245b0dfd0dfcdd308f23084b7f076c26462b7"+ "hash": "7fea7c108193d97c72fd70cee441f196cfc65e9320e4838a06878447a664270b"}diff --git a/.sqlx/query-2f1f54eaf23c0c277b0685c35ae75eea5921057be13e25a9609410d6ac5b17ba.json b/.sqlx/query-84dc7179f804bfd2078efb0ad88c049cd9226983382f398d94bde73268862b49.jsonsimilarity index 59%rename from .sqlx/query-2f1f54eaf23c0c277b0685c35ae75eea5921057be13e25a9609410d6ac5b17ba.jsonrename to .sqlx/query-84dc7179f804bfd2078efb0ad88c049cd9226983382f398d94bde73268862b49.jsonindex 1428af8b0e..4df0d7ffc3 100644--- a/.sqlx/query-2f1f54eaf23c0c277b0685c35ae75eea5921057be13e25a9609410d6ac5b17ba.json+++ b/.sqlx/query-84dc7179f804bfd2078efb0ad88c049cd9226983382f398d94bde73268862b49.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n INSERT INTO \"User\" (\"id\", \"email\", \"stripeCustomerId\", \"organizationId\", \"macro_user_id\")\n VALUES ($1, $2, $3, $4, $5)\n RETURNING id\n ",+ "query": "\n INSERT INTO \"User\" (\"id\", \"email\", \"stripeCustomerId\", \"organizationId\", \"macro_user_id\", \"isAgent\")\n VALUES ($1, $2, $3, $4, $5, $6)\n RETURNING id\n ","describe": {"columns": [{@@ -15,12 +15,13 @@"Text","Text","Int4",- "Uuid"+ "Uuid",+ "Bool"]},"nullable": [false]},- "hash": "2f1f54eaf23c0c277b0685c35ae75eea5921057be13e25a9609410d6ac5b17ba"+ "hash": "84dc7179f804bfd2078efb0ad88c049cd9226983382f398d94bde73268862b49"}diff --git a/.sqlx/query-853abfd157ed4a2da7e9b1e1a536b339c1013229f89e8b2da32e2124e23473d1.json b/.sqlx/query-853abfd157ed4a2da7e9b1e1a536b339c1013229f89e8b2da32e2124e23473d1.jsonnew file mode 100644index 0000000000..d81436584f--- /dev/null+++ b/.sqlx/query-853abfd157ed4a2da7e9b1e1a536b339c1013229f89e8b2da32e2124e23473d1.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "\n DELETE FROM \"UserApiKey\"\n WHERE user_id = $1 AND name = $2\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "853abfd157ed4a2da7e9b1e1a536b339c1013229f89e8b2da32e2124e23473d1"+}diff --git a/.sqlx/query-4656631949bab512d00e10664be31128b89c8047812362331ded6b6e0a12e1ac.json b/.sqlx/query-8c7ac5b5003f69e7c80991bcd78d64d11e96895c2d37ac622a351a6bcd6ef71f.jsonsimilarity index 82%rename from .sqlx/query-4656631949bab512d00e10664be31128b89c8047812362331ded6b6e0a12e1ac.jsonrename to .sqlx/query-8c7ac5b5003f69e7c80991bcd78d64d11e96895c2d37ac622a351a6bcd6ef71f.jsonindex f621865b2b..8a75adef05 100644--- a/.sqlx/query-4656631949bab512d00e10664be31128b89c8047812362331ded6b6e0a12e1ac.json+++ b/.sqlx/query-8c7ac5b5003f69e7c80991bcd78d64d11e96895c2d37ac622a351a6bcd6ef71f.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT\n id,\n email,\n team_id,\n team_role as \"team_role!: TeamRole\",\n invited_by,\n created_at as \"created_at!: chrono::DateTime<chrono::Utc>\",\n last_sent_at as \"last_sent_at!: chrono::DateTime<chrono::Utc>\"\n FROM team_invite\n WHERE email = $1\n ",+ "query": "\n SELECT\n id,\n email,\n team_id,\n team_role as \"team_role!: TeamRole\",\n invited_by,\n created_at as \"created_at!: chrono::DateTime<chrono::Utc>\",\n last_sent_at as \"last_sent_at!: chrono::DateTime<chrono::Utc>\",\n is_agent\n FROM team_invite\n WHERE email = $1\n ","describe": {"columns": [{@@ -48,6 +48,11 @@"ordinal": 6,"name": "last_sent_at!: chrono::DateTime<chrono::Utc>","type_info": "Timestamp"+ },+ {+ "ordinal": 7,+ "name": "is_agent",+ "type_info": "Bool"}],"parameters": {@@ -62,8 +67,9 @@false,false,false,+ false,false]},- "hash": "4656631949bab512d00e10664be31128b89c8047812362331ded6b6e0a12e1ac"+ "hash": "8c7ac5b5003f69e7c80991bcd78d64d11e96895c2d37ac622a351a6bcd6ef71f"}diff --git a/.sqlx/query-3e161b7906ba15490634a5375e300d649e4aa06841adb1645d4f17507cf15694.json b/.sqlx/query-9f0b7f2504d85c9f017e85c13892400f11734bf4079097c8a0fd5cb6d62f160f.jsonsimilarity index 53%rename from .sqlx/query-3e161b7906ba15490634a5375e300d649e4aa06841adb1645d4f17507cf15694.jsonrename to .sqlx/query-9f0b7f2504d85c9f017e85c13892400f11734bf4079097c8a0fd5cb6d62f160f.jsonindex 8a601b1311..327d65de36 100644--- a/.sqlx/query-3e161b7906ba15490634a5375e300d649e4aa06841adb1645d4f17507cf15694.json+++ b/.sqlx/query-9f0b7f2504d85c9f017e85c13892400f11734bf4079097c8a0fd5cb6d62f160f.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n INSERT INTO \"User\" (\"id\", \"email\", \"organizationId\", \"macro_user_id\")\n VALUES ($1, $2, $3, $4)\n RETURNING id\n ",+ "query": "\n INSERT INTO \"User\" (\"id\", \"email\", \"organizationId\", \"macro_user_id\", \"isAgent\")\n VALUES (\n $1, $2, $3, $4,\n COALESCE((SELECT BOOL_OR(u.\"isAgent\") FROM \"User\" u WHERE u.macro_user_id = $4), FALSE)\n )\n RETURNING id\n ","describe": {"columns": [{@@ -21,5 +21,5 @@false]},- "hash": "3e161b7906ba15490634a5375e300d649e4aa06841adb1645d4f17507cf15694"+ "hash": "9f0b7f2504d85c9f017e85c13892400f11734bf4079097c8a0fd5cb6d62f160f"}diff --git a/.sqlx/query-b3d092e08c04b80153179a25d557f47d30e12564210656a527637e64a7568af3.json b/.sqlx/query-b3d092e08c04b80153179a25d557f47d30e12564210656a527637e64a7568af3.jsondeleted file mode 100644index 17281dbb67..0000000000--- a/.sqlx/query-b3d092e08c04b80153179a25d557f47d30e12564210656a527637e64a7568af3.json+++ /dev/null@@ -1,15 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "UPDATE \"User\" SET id = $1 WHERE id = $2",- "describe": {- "columns": [],- "parameters": {- "Left": [- "Text",- "Text"- ]- },- "nullable": []- },- "hash": "b3d092e08c04b80153179a25d557f47d30e12564210656a527637e64a7568af3"-}diff --git a/.sqlx/query-c8bb1ba1a9013126a7a6e925080dcee285a274fbbc53acc996d9db69f852a329.json b/.sqlx/query-c8bb1ba1a9013126a7a6e925080dcee285a274fbbc53acc996d9db69f852a329.jsonnew file mode 100644index 0000000000..3e5b1f669e--- /dev/null+++ b/.sqlx/query-c8bb1ba1a9013126a7a6e925080dcee285a274fbbc53acc996d9db69f852a329.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE \"User\" u\n SET \"isAgent\" = FALSE\n WHERE u.\"email\" = $1\n AND u.\"isAgent\"\n AND NOT u.\"tutorialComplete\"\n AND NOT EXISTS (SELECT 1 FROM \"UserApiKey\" k WHERE k.user_id = u.\"id\")\n AND NOT EXISTS (\n SELECT 1 FROM team_invite ti WHERE ti.email = u.\"email\" AND ti.is_agent\n )\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "c8bb1ba1a9013126a7a6e925080dcee285a274fbbc53acc996d9db69f852a329"+}diff --git a/.sqlx/query-5b5a3e0954cb8130b507b73e771624fa3af4166de80e72dbcae524f63af9ae2e.json b/.sqlx/query-e0a6a8ae758a24369960cf374141c06ecf0f434f196e53557ff7d10c8992737c.jsonsimilarity index 82%rename from .sqlx/query-5b5a3e0954cb8130b507b73e771624fa3af4166de80e72dbcae524f63af9ae2e.jsonrename to .sqlx/query-e0a6a8ae758a24369960cf374141c06ecf0f434f196e53557ff7d10c8992737c.jsonindex 18f74966db..d9b5ba714c 100644--- a/.sqlx/query-5b5a3e0954cb8130b507b73e771624fa3af4166de80e72dbcae524f63af9ae2e.json+++ b/.sqlx/query-e0a6a8ae758a24369960cf374141c06ecf0f434f196e53557ff7d10c8992737c.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT\n id,\n email,\n team_id,\n team_role as \"team_role!: TeamRole\",\n invited_by,\n created_at as \"created_at!: chrono::DateTime<chrono::Utc>\",\n last_sent_at as \"last_sent_at!: chrono::DateTime<chrono::Utc>\"\n FROM team_invite\n WHERE team_id = $1\n ",+ "query": "\n SELECT\n id,\n email,\n team_id,\n team_role as \"team_role!: TeamRole\",\n invited_by,\n created_at as \"created_at!: chrono::DateTime<chrono::Utc>\",\n last_sent_at as \"last_sent_at!: chrono::DateTime<chrono::Utc>\",\n is_agent\n FROM team_invite\n WHERE team_id = $1\n ","describe": {"columns": [{@@ -48,6 +48,11 @@"ordinal": 6,"name": "last_sent_at!: chrono::DateTime<chrono::Utc>","type_info": "Timestamp"+ },+ {+ "ordinal": 7,+ "name": "is_agent",+ "type_info": "Bool"}],"parameters": {@@ -62,8 +67,9 @@false,false,false,+ false,false]},- "hash": "5b5a3e0954cb8130b507b73e771624fa3af4166de80e72dbcae524f63af9ae2e"+ "hash": "e0a6a8ae758a24369960cf374141c06ecf0f434f196e53557ff7d10c8992737c"}diff --git a/.sqlx/query-e70aca5f3f9b1712b5f08a75b84f7f86f66cd5846e8f465388504e80cac69c51.json b/.sqlx/query-e70aca5f3f9b1712b5f08a75b84f7f86f66cd5846e8f465388504e80cac69c51.jsonnew file mode 100644index 0000000000..5f3f6a7874--- /dev/null+++ b/.sqlx/query-e70aca5f3f9b1712b5f08a75b84f7f86f66cd5846e8f465388504e80cac69c51.json@@ -0,0 +1,40 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT \n u.id as user_profile_id, \n mui.first_name, \n mui.last_name,\n u.\"isAgent\" as is_agent\n FROM macro_user_info mui\n JOIN \"User\" u ON mui.macro_user_id = u.macro_user_id\n WHERE u.id = ANY($1)\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "user_profile_id",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "first_name",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "last_name",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "is_agent",+ "type_info": "Bool"+ }+ ],+ "parameters": {+ "Left": [+ "TextArray"+ ]+ },+ "nullable": [+ false,+ true,+ true,+ false+ ]+ },+ "hash": "e70aca5f3f9b1712b5f08a75b84f7f86f66cd5846e8f465388504e80cac69c51"+}diff --git a/Cargo.lock b/Cargo.lockindex d5e460a464..ac12a8379e 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -2233,6 +2233,7 @@ dependencies = ["model_notifications","models_email","models_permissions",+ "models_sfs","native_app_service","non_empty","notification",@@ -2256,6 +2257,7 @@ dependencies = ["sha2 0.10.9","sqlx","sqs_client",+ "static_file_service_client","strum 0.27.2","system_status","teams",@@ -2270,6 +2272,7 @@ dependencies = ["upstream_error","url","urlencoding",+ "user_api_key","user_language","user_quota","utoipa",diff --git a/apps/web/src/components/app/InitialInteractiveOnboardingModal.tsx b/apps/web/src/components/app/InitialInteractiveOnboardingModal.tsxindex f0034121f2..f10e12a5cc 100644--- a/apps/web/src/components/app/InitialInteractiveOnboardingModal.tsx+++ b/apps/web/src/components/app/InitialInteractiveOnboardingModal.tsx@@ -26,6 +26,7 @@ export function InitialInteractiveOnboardingModal() {isMobile() &&!isNativeMobilePlatform() &&userInfoQuery.data?.authenticated === true &&+ !userInfoQuery.data.isAgent &&(userInfoQuery.data.tutorialComplete === false || onboardingStarted());createEffect(() => {@@ -44,6 +45,7 @@ export function InitialInteractiveOnboardingModal() {createEffect(() => {const data = userInfoQuery.data;if (data?.authenticated !== true || data.tutorialComplete !== false) return;+ if (data.isAgent) return;if (emailInitForUserId === data.id) return;emailInitForUserId = data.id;diff --git a/apps/web/src/components/app/Layout.tsx b/apps/web/src/components/app/Layout.tsxindex 1f198f86af..5c205ee530 100644--- a/apps/web/src/components/app/Layout.tsx+++ b/apps/web/src/components/app/Layout.tsx@@ -1,5 +1,6 @@import { ViewSwitcherContext } from '@app/components/view-shell';import { ROUTER_BASE_CONCAT } from '@app/constants/routerBase';+import { AgentSetupModal } from '@app/features/agent-setup/agent-setup-modal';import Banner from '@app/features/auth/banner/Banner';import { CalendarPermissionPrompt } from '@app/features/auth/CalendarPermissionPrompt';import { GithubReauthenticationPrompt } from '@app/features/auth/GithubReauthenticationPrompt';@@ -237,6 +238,8 @@ function useNewOnboardingRedirect() {if (data?.authenticated !== true || data.tutorialComplete !== false) {return;}+ // Agents skip onboarding: AgentSetupModal shows their SDK token.+ if (data.isAgent) return;// Preserve the deep link the user arrived on (a shared doc, an invite)// as ?next, and a lifecycle-email ?step, so finish() and the flow can// resume. Base-relative so navigate() can resolve it against the router.@@ -375,6 +378,7 @@ export function AppChrome(props: ParentProps) {</FloatRegion></Show><InitialInteractiveOnboardingModal />+ <AgentSetupModal /><Suspense><Show when={isAuthenticated()}><Launcher open={createMenuOpen()} onOpenChange={setCreateMenuOpen} />diff --git a/apps/web/src/features/agent-setup/agent-setup-dialog.tsx b/apps/web/src/features/agent-setup/agent-setup-dialog.tsxnew file mode 100644index 0000000000..e29b400f8a--- /dev/null+++ b/apps/web/src/features/agent-setup/agent-setup-dialog.tsx@@ -0,0 +1,137 @@+import { t } from '@app/lib/i18n';+import { CredentialField } from '@channel/Bots/CredentialField';+import { LoadingSpinner } from '@core/component/LoadingSpinner';+import { toast } from '@core/component/Toast/Toast';+import { useAgentSetupMutation } from '@queries/auth/agent-setup';+import { useCompleteTutorialMutation } from '@queries/auth/tutorial';+import { Button, Dialog, Panel } from '@ui';+import { createEffect, Match, Show, Switch } from 'solid-js';++const SDK_DOCS_URL = 'https://sdk.macro.com';++const QUICK_START = `npm install @macro-inc/sdk+export MACRO_API_KEY="<your token>"`;++const PROFILE_SNIPPET = `const macro = new Macro({});+const image = await macro.me.uploadProfilePicture(bytes, {+ fileName: 'avatar.png',+ contentType: 'image/png',+});+await macro.me.update({ name: 'Your Name', profilePicture: image });`;++const NEW_TOKEN_SNIPPET = `const { secret } = await macro.apiKeys.create('my token');`;++function Snippet(props: { code: string }) {+ return (+ <pre class="overflow-x-auto rounded-lg border border-edge-muted bg-ink/[0.025] px-3 py-2 font-mono text-xs text-ink">+ {props.code}+ </pre>+ );+}++/**+ * An agent account's first screen: its SDK token and how to use it. Stays open+ * until the agent confirms it saved the token. The token is plain page text so+ * an agent driving a browser can read it. Reloading replaces the token, since a+ * key can only be shown once.+ */+export function AgentSetupDialog() {+ const setup = useAgentSetupMutation();+ const confirm = useCompleteTutorialMutation({+ onError: () => toast.failure(t('agentSetup.confirmFailed')),+ });++ createEffect(() => {+ if (setup.isIdle) setup.mutate();+ });++ return (+ <Dialog open position="center" class="w-140 max-w-full">+ <Panel depth={2} active class="rounded-xl text-ink">+ <Panel.Header class="px-5">+ <Dialog.Title class="text-sm font-semibold">+ {t('agentSetup.title')}+ </Dialog.Title>+ </Panel.Header>+ <Panel.Body class="flex max-h-[80dvh] flex-col gap-4 overflow-y-auto p-5 text-sm">+ <Switch>+ <Match when={setup.isError}>+ <p class="text-ink-muted">{t('agentSetup.loadFailed')}</p>+ <Button+ variant="primary"+ size="sm"+ onClick={() => setup.mutate()}+ >+ {t('agentSetup.tryAgain')}+ </Button>+ </Match>+ <Match when={setup.data}>+ {(result) => (+ <>+ <p>{t('agentSetup.intro')}</p>+ <Show when={result().team_join_failed}>+ <p class="text-ink-muted">+ {t('agentSetup.teamJoinFailed')}+ </p>+ </Show>+ <CredentialField+ label={t('agentSetup.tokenLabel')}+ value={result().api_key}+ />+ <p class="break-all font-mono text-xs text-ink-muted">+ {result().api_key}+ </p>+ <div class="flex flex-col gap-1.5">+ <span class="text-xs font-medium">+ {t('agentSetup.useToken')}+ </span>+ <Snippet code={QUICK_START} />+ <span class="text-xs text-ink-muted">+ {t('agentSetup.readDocs')}{' '}+ <a+ href={SDK_DOCS_URL}+ target="_blank"+ rel="noreferrer"+ class="underline"+ >+ sdk.macro.com+ </a>+ </span>+ </div>+ <div class="flex flex-col gap-1.5">+ <span class="text-xs font-medium">+ {t('agentSetup.setProfile')}+ </span>+ <Snippet code={PROFILE_SNIPPET} />+ </div>+ <div class="flex flex-col gap-1.5">+ <span class="text-xs font-medium">+ {t('agentSetup.anotherToken')}+ </span>+ <Snippet code={NEW_TOKEN_SNIPPET} />+ <span class="text-xs text-ink-muted">+ {t('agentSetup.anotherTokenSettings')}+ </span>+ </div>+ <Button+ variant="primary"+ size="sm"+ disabled={confirm.isPending}+ onClick={() => confirm.mutate()}+ >+ {t('agentSetup.confirm')}+ </Button>+ </>+ )}+ </Match>+ <Match when={true}>+ <div class="flex min-h-36 items-center justify-center">+ <LoadingSpinner class="size-10 p-2" />+ </div>+ </Match>+ </Switch>+ </Panel.Body>+ </Panel>+ </Dialog>+ );+}diff --git a/apps/web/src/features/agent-setup/agent-setup-modal.tsx b/apps/web/src/features/agent-setup/agent-setup-modal.tsxnew file mode 100644index 0000000000..3be719c48e--- /dev/null+++ b/apps/web/src/features/agent-setup/agent-setup-modal.tsx@@ -0,0 +1,35 @@+import { lazyNamed } from '@core/util/lazyNamed';+import { useUserInfoQuery } from '@queries/auth/user-info';+import { Show, Suspense } from 'solid-js';++// Only an agent that has not confirmed its token ever sees it.+const AgentSetupDialog = lazyNamed(+ () => import('./agent-setup-dialog'),+ 'AgentSetupDialog'+);++/** Opens an agent's setup dialog until it confirms it saved its token. */+export function AgentSetupModal() {+ const userInfoQuery = useUserInfoQuery();++ const open = () => {+ // A pending read would suspend the chrome, so wait for the user. A failed+ // background refetch keeps its data: unmounting the dialog then would mint+ // a new token and revoke the one the agent already saw.+ const settled = userInfoQuery.isSuccess || userInfoQuery.isRefetchError;+ const data = settled ? userInfoQuery.data : undefined;+ return (+ data?.authenticated === true &&+ data.isAgent === true &&+ data.tutorialComplete === false+ );+ };++ return (+ <Show when={open()}>+ <Suspense>+ <AgentSetupDialog />+ </Suspense>+ </Show>+ );+}diff --git a/apps/web/src/features/auth/EmailAuth.tsx b/apps/web/src/features/auth/EmailAuth.tsxindex 7496a9e20a..882d2eab94 100644--- a/apps/web/src/features/auth/EmailAuth.tsx+++ b/apps/web/src/features/auth/EmailAuth.tsx@@ -254,7 +254,8 @@ function EmailLinkCallback(props: Pick<EmailAuthParams, 'successPath'>) {if (!isMobile() &&!isNativeMobilePlatform() &&- userInfoQuery.data?.tutorialComplete === false+ userInfoQuery.data?.tutorialComplete === false &&+ !userInfoQuery.data.isAgent) {navigate(onboardingPathWithStep(searchParams.step), { replace: true });return;diff --git a/apps/web/src/features/auth/auth.tsx b/apps/web/src/features/auth/auth.tsxindex add1912767..11073c7afb 100644--- a/apps/web/src/features/auth/auth.tsx+++ b/apps/web/src/features/auth/auth.tsx@@ -60,7 +60,11 @@ export function Login(props: { signupMode?: boolean }) {function PostAuthGate(props: { user: AuthUser }) {const needsOnboarding = () =>- !isMobile() && !isNativeMobilePlatform() && !props.user.tutorialComplete;+ !isMobile() &&+ !isNativeMobilePlatform() &&+ !props.user.tutorialComplete &&+ // Agents get an SDK token from the app shell instead.+ !props.user.isAgent;return (<Show when={needsOnboarding()} fallback={<PostLoginRedirect />}><Onboarding />diff --git a/apps/web/src/features/auth/browser-test/fixture.tsx b/apps/web/src/features/auth/browser-test/fixture.tsxindex 1af4d02c29..7f53163d01 100644--- a/apps/web/src/features/auth/browser-test/fixture.tsx+++ b/apps/web/src/features/auth/browser-test/fixture.tsx@@ -60,6 +60,7 @@ const auth = createFakeAuth(id: `macro|${email}`,email,tutorialComplete: draft.accounts[email].tutorialComplete,+ isAgent: false,};});location.assign(location.href);diff --git a/apps/web/src/features/auth/components/email-form.tsx b/apps/web/src/features/auth/components/email-form.tsxindex 0c7ddda99b..bd0afea5c1 100644--- a/apps/web/src/features/auth/components/email-form.tsx+++ b/apps/web/src/features/auth/components/email-form.tsx@@ -1,5 +1,6 @@import ArrowLeft from '@icon/system/regular/arrow-left.svg';import ArrowRight from '@icon/system/regular/arrow-right.svg';+import { ToggleSwitch } from '@ui';import { Show } from 'solid-js';import { AuthButton, FormError, FormInput } from './form-fields';@@ -7,6 +8,9 @@ export function EmailForm(props: {email: string;password: string;passwordRequired: boolean;+ showAgentToggle: boolean;+ isAgent: boolean;+ onIsAgentChange: (isAgent: boolean) => void;sending: boolean;error?: string;onEmailInput: (value: string) => void;@@ -41,6 +45,15 @@ export function EmailForm(props: {onInput={props.onPasswordInput}/></Show>+ <Show when={props.showAgentToggle}>+ <ToggleSwitch+ size="sm"+ label="I'm an agent"+ labelClass="text-xs text-ink-muted"+ checked={props.isAgent}+ onChange={props.onIsAgentChange}+ />+ </Show><FormError message={props.error} /><AuthButton type="submit" disabled={props.sending}>Continuediff --git a/apps/web/src/features/auth/context/auth-context.tsx b/apps/web/src/features/auth/context/auth-context.tsxindex bb123b6d11..f979533125 100644--- a/apps/web/src/features/auth/context/auth-context.tsx+++ b/apps/web/src/features/auth/context/auth-context.tsx@@ -6,6 +6,7 @@ export type AuthUser = {id: string;email: string | undefined;tutorialComplete: boolean;+ isAgent: boolean;};export type AuthSession =@@ -50,9 +51,12 @@ export type AuthContext = {session: Accessor<AuthSession>;/** Leaves for the identity provider; on web the page navigates away. */startSso(provider: SsoProvider, intent: AuthIntent): Promise<void>;+ /** Whether the email step offers the "I'm an agent" toggle. */+ agentSignupEnabled: Accessor<boolean>;sendEmailCode(input: {email: string;password?: string;+ isAgent: boolean;}): Promise<SendCodeResult>;verifyEmailCode(input: {email: string;diff --git a/apps/web/src/features/auth/create-app-auth-context.ts b/apps/web/src/features/auth/create-app-auth-context.tsindex a919806b8b..2c5caa87f3 100644--- a/apps/web/src/features/auth/create-app-auth-context.ts+++ b/apps/web/src/features/auth/create-app-auth-context.ts@@ -1,8 +1,10 @@import { useAnalytics } from '@app/lib/analytics/analytics-context';import { MOBILE_WEB_SIGNUP_LEAD_VALUE } from '@app/lib/analytics/leadValues';+import { useFeatureFlag } from '@app/lib/analytics/posthog';import { adAttributionForCapture } from '@app/lib/analytics/signupAttribution';import { GOOGLE_GMAIL_IDP } from '@core/auth/email';import { toast } from '@core/component/Toast/Toast';+import { enableAgentSignup } from '@core/constant/featureFlags';import { deriveIsAuthenticated } from '@core/context/user';import { useEmailLinks } from '@core/email-link';import { unsetTokenPromise } from '@core/util/fetchWithToken';@@ -47,6 +49,7 @@ export function createAppAuthContext(): AuthContext {id: data.userId,email: data.email ?? undefined,tutorialComplete: data.tutorialComplete === true,+ isAgent: data.isAgent === true,},};};@@ -65,12 +68,15 @@ export function createAppAuthContext(): AuthContext {);};+ const agentSignupFlag = useFeatureFlag(enableAgentSignup);+return {session,startSso: (provider, intent) =>(intent === 'signup' ? signupSso : loginSso)(provider === 'google' ? GOOGLE_GMAIL_IDP : 'Apple'),+ agentSignupEnabled: () => agentSignupFlag().enabled === true,sendEmailCode,verifyEmailCode,redeemSessionToken: async (token) => {diff --git a/apps/web/src/features/auth/primitives/email-login.ts b/apps/web/src/features/auth/primitives/email-login.tsindex ebd970d1ff..3d4a654b8e 100644--- a/apps/web/src/features/auth/primitives/email-login.ts+++ b/apps/web/src/features/auth/primitives/email-login.ts@@ -18,6 +18,7 @@ const VERIFY_ERRORS = {type EmailLoginCapabilities = Pick<AuthContext,| 'session'+ | 'agentSignupEnabled'| 'sendEmailCode'| 'verifyEmailCode'| 'completeLogin'@@ -45,6 +46,7 @@ export function createEmailLogin();const [email, setEmail] = createSignal(options.initialEmail ?? '');const [password, setPassword] = createSignal('');+ const [isAgent, setIsAgent] = createSignal(false);const [passwordRequired, setPasswordRequired] = createSignal(false);const [sending, setSending] = createSignal(false);const [sendError, setSendError] = createSignal<string>();@@ -104,6 +106,7 @@ export function createEmailLogin(const result = await context.sendEmailCode({email: address,password: passwordRequired() ? password() : undefined,+ isAgent: context.agentSignupEnabled() && isAgent(),});switch (result.t) {case 'code-sent':@@ -142,6 +145,9 @@ export function createEmailLogin(setEmail,password,setPassword,+ isAgent,+ setIsAgent,+ showAgentToggle: context.agentSignupEnabled,passwordRequired,sending,sendError,diff --git a/apps/web/src/features/auth/queries/auth-requests.ts b/apps/web/src/features/auth/queries/auth-requests.tsindex 4952119841..a90c3b2bd6 100644--- a/apps/web/src/features/auth/queries/auth-requests.ts+++ b/apps/web/src/features/auth/queries/auth-requests.ts@@ -28,8 +28,9 @@ const referralCode = () =>export async function sendEmailCode(input: {email: string;password?: string;+ isAgent: boolean;}): Promise<SendCodeResult> {- const { email, password } = input;+ const { email, password, isAgent } = input;if (await isPasswordLogin(email)) {if (!password) return { t: 'password-required' };const tokens = await authServiceClient.passwordLogin({ password, email });@@ -52,6 +53,7 @@ export async function sendEmailCode(input: {redirect_uri: REDIRECT_URI,email,...(referral_code && { referral_code }),+ ...(isAgent && { is_agent: true }),}),}).catch(() => undefined);diff --git a/apps/web/src/features/auth/tests/fake-auth-context.ts b/apps/web/src/features/auth/tests/fake-auth-context.tsindex 20f673b004..f83eddab9f 100644--- a/apps/web/src/features/auth/tests/fake-auth-context.ts+++ b/apps/web/src/features/auth/tests/fake-auth-context.ts@@ -63,6 +63,7 @@ const userFor = (id: `macro|${email}`,email,tutorialComplete: account?.tutorialComplete ?? false,+ isAgent: false,});/**@@ -128,6 +129,7 @@ export function createFakeAuth(return options.ssoRedirect(provider, intent, email);signIn(email);},+ agentSignupEnabled: () => false,sendEmailCode: async ({ email, password }) => {call(`sendCode:${email}`);const failure = world.failures.sendCode;diff --git a/apps/web/src/features/auth/views/auth-view.test.tsx b/apps/web/src/features/auth/views/auth-view.test.tsxindex cfe537f77d..e783c93a0a 100644--- a/apps/web/src/features/auth/views/auth-view.test.tsx+++ b/apps/web/src/features/auth/views/auth-view.test.tsx@@ -98,6 +98,7 @@ describe('email sign-in', () => {id: 'macro|[email protected]',email: '[email protected]',tutorialComplete: false,+ isAgent: false,},},});@@ -115,6 +116,7 @@ describe('email sign-in', () => {id: 'macro|[email protected]',email: '[email protected]',tutorialComplete: false,+ isAgent: false,};});expect(screen.getByTestId('signed-in')).not.toBe(workspace);diff --git a/apps/web/src/features/auth/views/auth-view.tsx b/apps/web/src/features/auth/views/auth-view.tsxindex bf938d4ddd..13ae5170c5 100644--- a/apps/web/src/features/auth/views/auth-view.tsx+++ b/apps/web/src/features/auth/views/auth-view.tsx@@ -154,6 +154,9 @@ function EmailStep(props: { login: EmailLogin }) {email={props.login.email()}password={props.login.password()}passwordRequired={props.login.passwordRequired()}+ showAgentToggle={props.login.showAgentToggle()}+ isAgent={props.login.isAgent()}+ onIsAgentChange={props.login.setIsAgent}sending={props.login.sending()}error={props.login.sendError()}onEmailInput={props.login.setEmail}diff --git a/apps/web/src/features/channel/Message/AgentBadge.tsx b/apps/web/src/features/channel/Message/AgentBadge.tsxindex a3712c8ed0..4b6739ca4f 100644--- a/apps/web/src/features/channel/Message/AgentBadge.tsx+++ b/apps/web/src/features/channel/Message/AgentBadge.tsx@@ -1,5 +1,6 @@+import { AgentTag } from '@core/component/AgentTag';+import { isAgentAccount, tryMacroId } from '@core/user';import { isBotSenderId } from '@queries/messages/message-sender';-import { cn } from '@ui';import { Show } from 'solid-js';import { useMessage } from './context';@@ -8,24 +9,19 @@ type AgentBadgeProps = {};/**- * Small "Agent" badge shown next to a bot sender's name so it's clear the- * message is from an agent rather than a person.+ * Small "Agent" badge shown next to a bot or agent account's name so it's+ * clear the message is from an agent rather than a person.*/export function AgentBadge(props: AgentBadgeProps) {const message = useMessage();- const isAgent = () => isBotSenderId(message().sender_id);+ const isAgent = () => {+ const senderId = message().sender_id;+ return isBotSenderId(senderId) || isAgentAccount(tryMacroId(senderId));+ };return (<Show when={isAgent()}>- <span- class={cn(- 'inline-flex shrink-0 items-center rounded-full bg-hover px-1.5 py-0.5',- 'text-xs font-medium leading-none text-ink-muted',- props.class- )}- >- Agent- </span>+ <AgentTag class={props.class} /></Show>);}diff --git a/apps/web/src/features/onboarding/onboarding.tsx b/apps/web/src/features/onboarding/onboarding.tsxindex ba02687754..30cd2e0bdd 100644--- a/apps/web/src/features/onboarding/onboarding.tsx+++ b/apps/web/src/features/onboarding/onboarding.tsx@@ -1,7 +1,8 @@import { InviteOfferPanel } from '@app/features/gtm-invite/InviteOfferPanel';+import { useUserInfoQuery } from '@queries/auth/user-info';import { useNavigate, useSearchParams } from '@solidjs/router';import type { JSX } from 'solid-js';-import { onMount } from 'solid-js';+import { createEffect, onMount } from 'solid-js';import { OnboardingProvider } from './context/onboarding-context';import { parseCheckoutReturn } from './core/checkout';import { parseOnboardingStepParam } from './core/steps';@@ -13,6 +14,11 @@ import { SignupJourneyView } from './views/signup-journey-view';export function Onboarding() {const context = createAppOnboardingContext();const navigate = useNavigate();+ const userInfoQuery = useUserInfoQuery();+ // Agents never onboard, even when they open the link directly.+ createEffect(() => {+ if (userInfoQuery.data?.isAgent) navigate('/', { replace: true });+ });const [params, setParams] = useSearchParams();// Captured once. The link is removed below, and later progress must win// on reload instead of the original step.diff --git a/apps/web/src/features/settings/TeamMembers.tsx b/apps/web/src/features/settings/TeamMembers.tsxindex c3609f37b3..f0d8e51c01 100644--- a/apps/web/src/features/settings/TeamMembers.tsx+++ b/apps/web/src/features/settings/TeamMembers.tsx@@ -1,10 +1,16 @@import { ListSkeleton } from '@app/components/view-shell/ListSkeleton';import { SearchBar } from '@app/components/view-shell/SearchBar';import { useFeatureFlag } from '@app/lib/analytics/posthog';+import { AgentTag } from '@core/component/AgentTag';import { UserIcon } from '@core/component/UserIcon';import { enableAiUsageBilling } from '@core/constant/featureFlags';import { useUserId } from '@core/context/user';-import { getDisplayName, macroIdToEmail, tryMacroId } from '@core/user';+import {+ getDisplayName,+ isAgentAccount,+ macroIdToEmail,+ tryMacroId,+} from '@core/user';import { debouncedDependent } from '@core/util/debounce';import { fuzzyFilter } from '@core/util/fuzzy';import CaretDownIcon from '@icon/system/regular/caret-down.svg';@@ -156,11 +162,16 @@ function MemberRow(props: {<UserIcon id={props.member.user_id} isDeleted={false} size="lg" /></div><div class="min-w-0 flex-1">- <div class="text-sm font-medium text-ink truncate">- {displayName()}- {props.isCurrentUser && (- <span class="text-ink-muted font-normal"> (you)</span>- )}+ <div class="flex items-center gap-1.5 min-w-0">+ <div class="text-sm font-medium text-ink truncate">+ {displayName()}+ {props.isCurrentUser && (+ <span class="text-ink-muted font-normal"> (you)</span>+ )}+ </div>+ <Show when={isAgentAccount(tryMacroId(props.member.user_id))}>+ <AgentTag />+ </Show></div><Show when={showEmail()}><div class="text-xs text-ink-muted truncate">{email()}</div>diff --git a/apps/web/src/features/settings/components/team-invite-row.test.tsx b/apps/web/src/features/settings/components/team-invite-row.test.tsxindex 1c4fd9eefc..fbfe641a7e 100644--- a/apps/web/src/features/settings/components/team-invite-row.test.tsx+++ b/apps/web/src/features/settings/components/team-invite-row.test.tsx@@ -26,6 +26,7 @@ function invite(lastSentHoursAgo: number): TeamInviteDetails {invited_by: 'macro|[email protected]',created_at: lastSent,last_sent_at: lastSent,+ is_agent: false,};}diff --git a/apps/web/src/lib/core/auth/logout.ts b/apps/web/src/lib/core/auth/logout.tsindex 3938755333..87f3d3057e 100644--- a/apps/web/src/lib/core/auth/logout.ts+++ b/apps/web/src/lib/core/auth/logout.ts@@ -44,6 +44,7 @@ const unauthenticatedUserInfo: UserInfoData = {name: null,licenseStatus: 'inactive',tutorialComplete: false,+ isAgent: false,group: null,hasChromeExt: false,authenticated: false,diff --git a/apps/web/src/lib/core/component/AgentTag.tsx b/apps/web/src/lib/core/component/AgentTag.tsxnew file mode 100644index 0000000000..c686ad60dd--- /dev/null+++ b/apps/web/src/lib/core/component/AgentTag.tsx@@ -0,0 +1,17 @@+import { t } from '@app/lib/i18n';+import { cn } from '@ui';++/** Marks a name as an agent rather than a person. */+export function AgentTag(props: { class?: string }) {+ return (+ <span+ class={cn(+ 'inline-flex shrink-0 items-center rounded-full bg-hover px-1.5 py-0.5',+ 'text-xs font-medium leading-none text-ink-muted',+ props.class+ )}+ >+ {t('agentSetup.tag')}+ </span>+ );+}diff --git a/apps/web/src/lib/core/component/UserCardDrawer.test.tsx b/apps/web/src/lib/core/component/UserCardDrawer.test.tsxindex 1e467ab215..597192ebae 100644--- a/apps/web/src/lib/core/component/UserCardDrawer.test.tsx+++ b/apps/web/src/lib/core/component/UserCardDrawer.test.tsx@@ -40,6 +40,8 @@ vi.mock('@core/context/user', () => ({}));vi.mock('@core/user', () => ({+ isAgentAccount: () => false,+ tryMacroId: () => undefined,useIsConnectedSecondaryInbox: () => () => false,}));diff --git a/apps/web/src/lib/core/component/UserCardDrawer.tsx b/apps/web/src/lib/core/component/UserCardDrawer.tsxindex 8cac2845d0..7d051f8573 100644--- a/apps/web/src/lib/core/component/UserCardDrawer.tsx+++ b/apps/web/src/lib/core/component/UserCardDrawer.tsx@@ -1,6 +1,8 @@import { MobileDrawer } from '@components/app/mobile/MobileDrawer';+import { isAgentAccount, tryMacroId } from '@core/user';import { createSignal, For, Show } from 'solid-js';import { Dynamic } from 'solid-js/web';+import { AgentTag } from './AgentTag';import { UserIcon } from './UserIcon';import {type UserCardAction,@@ -91,8 +93,13 @@ function UserCardBody(props: {class="pointer-events-none"/><div class="min-w-0 flex-1">- <div class="truncate text-base font-semibold text-ink">- {props.user.displayName}+ <div class="flex items-center gap-1.5 min-w-0">+ <div class="truncate text-base font-semibold text-ink">+ {props.user.displayName}+ </div>+ <Show when={isAgentAccount(tryMacroId(props.user.id ?? ''))}>+ <AgentTag />+ </Show></div><Showwhen={diff --git a/apps/web/src/lib/core/constant/featureFlags.ts b/apps/web/src/lib/core/constant/featureFlags.tsindex 6c97add6a3..08bcec2fa9 100644--- a/apps/web/src/lib/core/constant/featureFlags.ts+++ b/apps/web/src/lib/core/constant/featureFlags.ts@@ -1009,3 +1009,14 @@ export const enableWhatsappLinked = defineFlag({key: 'enable-whatsapp-linked',env: 'ENABLE_WHATSAPP_LINKED',});++/**+ * Experimental: the "I'm an agent" toggle on the email sign-in step. Only the+ * toggle is gated; agent invites and the setup modal do not depend on it.+ * Follows PostHog in production; on in dev.+ */+export const enableAgentSignup = defineFlag({+ key: 'enable-agent-signup',+ env: 'ENABLE_AGENT_SIGNUP',+ default: DEV_MODE_ENV || undefined,+});diff --git a/apps/web/src/lib/core/user/displayName.ts b/apps/web/src/lib/core/user/displayName.tsindex c0850a3666..0489e060e8 100644--- a/apps/web/src/lib/core/user/displayName.ts+++ b/apps/web/src/lib/core/user/displayName.ts@@ -134,6 +134,7 @@ async function fetchDisplayNames(ids: string[]): Promise<UserNameItem[]> {id: name.id,firstName: name.first_name as string,lastName: name.last_name as string,+ isAgent: name.is_agent,loading: false,};});@@ -191,6 +192,12 @@ export function getDisplayName(return defaultNameTransform(getUserNameItem(id), options);}+/** Whether this user is an agent account, from the shared reactive cache. */+export function isAgentAccount(id: MacroId | undefined | null): boolean {+ if (!id) return false;+ return getUserNameItem(id).isAgent === true;+}+/** Resolves structured display name parts from the shared reactive cache. */export function getDisplayNameParts(id: MacroId | undefined | null,diff --git a/apps/web/src/lib/core/user/index.ts b/apps/web/src/lib/core/user/index.tsindex 8bb417318a..31fc99adda 100644--- a/apps/web/src/lib/core/user/index.ts+++ b/apps/web/src/lib/core/user/index.ts@@ -12,6 +12,7 @@ export {getDisplayNameParts,getInitials,getInitialsFromName,+ isAgentAccount,seedMockDisplayNames,useDisplayName,useDisplayNameParts,diff --git a/apps/web/src/lib/core/user/types.ts b/apps/web/src/lib/core/user/types.tsindex a636725f97..e8043357e4 100644--- a/apps/web/src/lib/core/user/types.ts+++ b/apps/web/src/lib/core/user/types.ts@@ -23,6 +23,7 @@ type BaseUserName = {id: string;firstName?: string;lastName?: string;+ isAgent?: boolean;};type UserNameLoading = { loading: true } & BaseUserName;diff --git a/apps/web/src/lib/i18n/locales/en.ts b/apps/web/src/lib/i18n/locales/en.tsindex 2cb2d0167f..ea9b991ead 100644--- a/apps/web/src/lib/i18n/locales/en.ts+++ b/apps/web/src/lib/i18n/locales/en.ts@@ -1,4 +1,5 @@import agentAutoArchive from './en/agent-auto-archive';+import agentSetup from './en/agent-setup';import calls from './en/calls';import channelLabels from './en/channel-labels';import channelSections from './en/channel-sections';@@ -23,6 +24,7 @@ import viewMenus from './en/view-menus';*/export default {agentAutoArchive,+ agentSetup,calls,channelLabels,channelSections,diff --git a/apps/web/src/lib/i18n/locales/en/agent-setup.ts b/apps/web/src/lib/i18n/locales/en/agent-setup.tsnew file mode 100644index 0000000000..817323a0fa--- /dev/null+++ b/apps/web/src/lib/i18n/locales/en/agent-setup.ts@@ -0,0 +1,19 @@+/** An agent account's setup dialog and the tag that marks agent accounts. */+export default {+ tag: 'Agent',+ title: 'Your agent account is ready',+ loadFailed: 'Couldn’t create your SDK token.',+ tryAgain: 'Try again',+ intro:+ 'Use this token to work in Macro through the SDK. Save it now: it is shown only once, and reloading this page replaces it.',+ teamJoinFailed:+ 'We couldn’t add you to the team that invited you. Reload this page to try again, which replaces this token, or join later from the link in your invite email.',+ tokenLabel: 'SDK token',+ useToken: '1. Use the token',+ readDocs: 'Read the docs:',+ setProfile: '2. Set your name and profile picture',+ anotherToken: '3. Need another token later?',+ anotherTokenSettings: 'You can also create one in Settings → API Keys.',+ confirm: 'I saved this token',+ confirmFailed: 'Failed to save. Try again.',+};diff --git a/apps/web/src/lib/queries/auth/agent-setup.ts b/apps/web/src/lib/queries/auth/agent-setup.tsnew file mode 100644index 0000000000..47eecfca6b--- /dev/null+++ b/apps/web/src/lib/queries/auth/agent-setup.ts@@ -0,0 +1,17 @@+import { throwOnErr } from '@core/util/result';+import { Telemetry } from '@macro-inc/observability';+import { authServiceClient } from '@service-auth/client';+import { useMutation } from '@tanstack/solid-query';++/**+ * Mints an agent's SDK token, replacing any earlier one. Never retried+ * automatically: overlapping attempts could revoke each other's token.+ */+export function useAgentSetupMutation() {+ return useMutation(() => ({+ mutationFn: () =>+ Telemetry.span('agent.setup', () =>+ throwOnErr(async () => await authServiceClient.agentSetup())+ ),+ }));+}diff --git a/apps/web/src/lib/service-clients/service-auth/client.ts b/apps/web/src/lib/service-clients/service-auth/client.tsindex 3104dce8e7..85d8b59962 100644--- a/apps/web/src/lib/service-clients/service-auth/client.ts+++ b/apps/web/src/lib/service-clients/service-auth/client.ts@@ -49,6 +49,7 @@ import type {UserQuota,} from './generated/schemas';import type { AgentApiKey } from './generated/schemas/agentApiKey';+import type { AgentSetupResponse } from './generated/schemas/agentSetupResponse';import type { AppleLoginRequest } from './generated/schemas/appleLoginRequest';import type { CreatedTeamInviteLinkResponse } from './generated/schemas/createdTeamInviteLinkResponse';import type { CreateGtmInviteLinkRequest } from './generated/schemas/createGtmInviteLinkRequest';@@ -465,6 +466,12 @@ export const authServiceClient = {)).map((result) => result);},+ async agentSetup() {+ return await fetchWithAuth<AgentSetupResponse>(+ `${authHost}/user/agent_setup`,+ { method: 'POST' }+ );+ },async putProfilePicture(args: PutProfilePictureParams) {return (await fetchWithAuth<EmptyResponse>(@@ -666,6 +673,7 @@ export const authServiceClient = {name: data.name,licenseStatus: data.licenseStatus,tutorialComplete: data.tutorialComplete,+ isAgent: data.isAgent,group: data.group,hasChromeExt: data.hasChromeExt,authenticated: !!data.userId,diff --git a/apps/web/src/lib/service-clients/service-auth/generated/client.ts b/apps/web/src/lib/service-clients/service-auth/generated/client.tsindex a902099ef2..87c26fb1a9 100644--- a/apps/web/src/lib/service-clients/service-auth/generated/client.ts+++ b/apps/web/src/lib/service-clients/service-auth/generated/client.ts@@ -6,6 +6,7 @@*/import type {AgentApiKey,+ AgentSetupResponse,AiBillingErrorBody,AppleLoginRequest,ChangePlanRequest,@@ -22,6 +23,7 @@ import type {CreateGtmInviteLinkRequest,CreateInProgressLinkResponse,CreatePortalSessionRequest,+ CreateProfilePictureUploadRequest,CreateTeamRequest,CreditCheckoutRequestBody,CreditCheckoutResponse,@@ -80,10 +82,12 @@ import type {PlanCatalogResponse,PostGetNamesRequestBody,ProfilePictures,+ ProfilePictureUpload,PublicGtmInviteLink,PutAgentApiKeyRequest,PutCursorApiKeyRequest,PutCursorDefaultModelRequest,+ PutProfilePictureFileRequest,PutProfilePictureParams,PutUserNameParams,RedeemGtmInviteLinkRequest,@@ -5947,6 +5951,75 @@ export const getUserInvites = async (} as getUserInvitesResponse;};+/**+ * Safe to repeat until the agent confirms it saved the token: a reload replaces+the key, and a failed join stays pending for the next attempt.+ * @summary Finishes an agent's signup: joins the team that invited it and mints its+SDK token.+ */+export type agentSetupResponse200 = {+ data: AgentSetupResponse;+ status: 200;+};++export type agentSetupResponse401 = {+ data: string;+ status: 401;+};++export type agentSetupResponse403 = {+ data: ErrorResponse;+ status: 403;+};++export type agentSetupResponse409 = {+ data: ErrorResponse;+ status: 409;+};++export type agentSetupResponse500 = {+ data: ErrorResponse;+ status: 500;+};++export type agentSetupResponseSuccess = agentSetupResponse200 & {+ headers: Headers;+};+export type agentSetupResponseError = (+ | agentSetupResponse401+ | agentSetupResponse403+ | agentSetupResponse409+ | agentSetupResponse500+) & {+ headers: Headers;+};++export type agentSetupResponse =+ | agentSetupResponseSuccess+ | agentSetupResponseError;++export const getAgentSetupUrl = () => {+ return `/user/agent_setup`;+};++export const agentSetup = async (+ options?: RequestInit+): Promise<agentSetupResponse> => {+ const res = await fetch(getAgentSetupUrl(), {+ ...options,+ method: 'POST',+ });++ const body = [204, 205, 304].includes(res.status) ? null : await res.text();++ const data: agentSetupResponse['data'] = body ? JSON.parse(body) : {};+ return {+ data,+ status: res.status,+ headers: res.headers,+ } as agentSetupResponse;+};+/*** @summary Retrieves user names in bulk*/@@ -6823,6 +6896,145 @@ export const putProfilePicture = async (} as putProfilePictureResponse;};+/**+ * @summary Sets the caller's profile picture to an image they uploaded.+ */+export type putProfilePictureFileResponse200 = {+ data: EmptyResponse;+ status: 200;+};++export type putProfilePictureFileResponse400 = {+ data: ErrorResponse;+ status: 400;+};++export type putProfilePictureFileResponse401 = {+ data: string;+ status: 401;+};++export type putProfilePictureFileResponse404 = {+ data: ErrorResponse;+ status: 404;+};++export type putProfilePictureFileResponse500 = {+ data: ErrorResponse;+ status: 500;+};++export type putProfilePictureFileResponseSuccess =+ putProfilePictureFileResponse200 & {+ headers: Headers;+ };+export type putProfilePictureFileResponseError = (+ | putProfilePictureFileResponse400+ | putProfilePictureFileResponse401+ | putProfilePictureFileResponse404+ | putProfilePictureFileResponse500+) & {+ headers: Headers;+};++export type putProfilePictureFileResponse =+ | putProfilePictureFileResponseSuccess+ | putProfilePictureFileResponseError;++export const getPutProfilePictureFileUrl = () => {+ return `/user/profile_picture/file`;+};++export const putProfilePictureFile = async (+ putProfilePictureFileRequest: PutProfilePictureFileRequest,+ options?: RequestInit+): Promise<putProfilePictureFileResponse> => {+ const res = await fetch(getPutProfilePictureFileUrl(), {+ ...options,+ method: 'PUT',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(putProfilePictureFileRequest),+ });++ const body = [204, 205, 304].includes(res.status) ? null : await res.text();++ const data: putProfilePictureFileResponse['data'] = body+ ? JSON.parse(body)+ : {};+ return {+ data,+ status: res.status,+ headers: res.headers,+ } as putProfilePictureFileResponse;+};++/**+ * @summary Reserves storage for a new profile picture. Static file storage has no+MacroDB, so it cannot check API keys; this route lets key holders upload.+ */+export type createProfilePictureUploadResponse200 = {+ data: ProfilePictureUpload;+ status: 200;+};++export type createProfilePictureUploadResponse400 = {+ data: ErrorResponse;+ status: 400;+};++export type createProfilePictureUploadResponse401 = {+ data: string;+ status: 401;+};++export type createProfilePictureUploadResponse500 = {+ data: ErrorResponse;+ status: 500;+};++export type createProfilePictureUploadResponseSuccess =+ createProfilePictureUploadResponse200 & {+ headers: Headers;+ };+export type createProfilePictureUploadResponseError = (+ | createProfilePictureUploadResponse400+ | createProfilePictureUploadResponse401+ | createProfilePictureUploadResponse500+) & {+ headers: Headers;+};++export type createProfilePictureUploadResponse =+ | createProfilePictureUploadResponseSuccess+ | createProfilePictureUploadResponseError;++export const getCreateProfilePictureUploadUrl = () => {+ return `/user/profile_picture/file`;+};++export const createProfilePictureUpload = async (+ createProfilePictureUploadRequest: CreateProfilePictureUploadRequest,+ options?: RequestInit+): Promise<createProfilePictureUploadResponse> => {+ const res = await fetch(getCreateProfilePictureUploadUrl(), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(createProfilePictureUploadRequest),+ });++ const body = [204, 205, 304].includes(res.status) ? null : await res.text();++ const data: createProfilePictureUploadResponse['data'] = body+ ? JSON.parse(body)+ : {};+ return {+ data,+ status: res.status,+ headers: res.headers,+ } as createProfilePictureUploadResponse;+};+/*** @summary Retrieves profile picture URLs for a list of users*/diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/agentSetupResponse.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/agentSetupResponse.tsnew file mode 100644index 0000000000..e5d75b9102--- /dev/null+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/agentSetupResponse.ts@@ -0,0 +1,17 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * authentication_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * What an agent needs to start using the SDK.+ */+export interface AgentSetupResponse {+ /** The agent's API key. Shown only here; repeating setup revokes it. */+ api_key: string;+ /** Whether joining the inviting team failed. The invite stays pending:+repeating setup tries again, and the invite link works after confirming. */+ team_join_failed: boolean;+}diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/createProfilePictureUploadRequest.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/createProfilePictureUploadRequest.tsnew file mode 100644index 0000000000..d1117c22bf--- /dev/null+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/createProfilePictureUploadRequest.ts@@ -0,0 +1,13 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * authentication_service+ * OpenAPI spec version: 0.1.0+ */++export interface CreateProfilePictureUploadRequest {+ /** Mime type of the image. */+ content_type: string;+ /** File name, such as `avatar.png`. */+ file_name: string;+}diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/getLegacyUserPermissionsResponse.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/getLegacyUserPermissionsResponse.tsindex 7eed1cf08d..fdbee34848 100644--- a/apps/web/src/lib/service-clients/service-auth/generated/schemas/getLegacyUserPermissionsResponse.ts+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/getLegacyUserPermissionsResponse.ts@@ -21,6 +21,8 @@ creation-time tracking. */hasChromeExt: boolean;/** Whether the user has trialed through stripe */hasTrialed: boolean;+ /** Whether this is an agent account rather than a person */+ isAgent: boolean;/** The user's license status */licenseStatus: string;/** The user's name */diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/index.tsindex c3eb54baca..4d93360260 100644--- a/apps/web/src/lib/service-clients/service-auth/generated/schemas/index.ts+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/index.ts@@ -9,6 +9,7 @@ export * from './aBGroup';export * from './agentApiKey';export * from './agentApiKeyKey';export * from './agentApiKeyProvider';+export * from './agentSetupResponse';export * from './aiBillingErrorBody';export * from './appleLoginRequest';export * from './autoReloadDefaults';@@ -45,6 +46,7 @@ export * from './createGtmInviteLinkRequestNote';export * from './createGtmInviteLinkRequestRecipientEmail';export * from './createInProgressLinkResponse';export * from './createPortalSessionRequest';+export * from './createProfilePictureUploadRequest';export * from './createTeamRequest';export * from './creditCheckoutRequestBody';export * from './creditCheckoutResponse';@@ -192,11 +194,13 @@ export * from './planTier';export * from './postGetNamesRequestBody';export * from './profilePictureQueryParams';export * from './profilePictures';+export * from './profilePictureUpload';export * from './publicGtmInviteLink';export * from './putAgentApiKeyRequest';export * from './putCursorApiKeyRequest';export * from './putCursorDefaultModelRequest';export * from './putCursorDefaultModelRequestModelId';+export * from './putProfilePictureFileRequest';export * from './putProfilePictureParams';export * from './putUserNameParams';export * from './putUserNameQueryParams';diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/inviteToTeamRequest.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/inviteToTeamRequest.tsindex c7036342a4..2de7c2e0dd 100644--- a/apps/web/src/lib/service-clients/service-auth/generated/schemas/inviteToTeamRequest.ts+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/inviteToTeamRequest.ts@@ -13,6 +13,9 @@ import type { InviteToTeamRequestTeamId } from './inviteToTeamRequestTeamId';export interface InviteToTeamRequest {/** The invites to send, each with an email and tier */invites: InviteEntry[];+ /** Invite these addresses as agents: an address with no account signs up+as an agent and joins the team when it first signs in. */+ is_agent?: boolean;/** The team the caller means to invite to. Invites always go to thecaller's current team; when this names another team, nothing is sentand the request answers 409. */diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/passwordlessRequest.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/passwordlessRequest.tsindex 9e2dc31bef..40015a1902 100644--- a/apps/web/src/lib/service-clients/service-auth/generated/schemas/passwordlessRequest.ts+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/passwordlessRequest.ts@@ -9,6 +9,10 @@ import type { PasswordlessRequestReferralCode } from './passwordlessRequestReferexport interface PasswordlessRequest {/** The email to initiate passwordless authentication for */email: string;+ /** Create an agent account if this address has no account yet. Otherwise+`true` has no effect, and `false` reverts an agent flag nobody has proven:+see `revert_unconfirmed_agent`. */+ is_agent?: boolean;/** The redirect uri to redirect to after login */redirect_uri: string;/** The referral code */diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/profilePictureUpload.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/profilePictureUpload.tsnew file mode 100644index 0000000000..79692a38a9--- /dev/null+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/profilePictureUpload.ts@@ -0,0 +1,16 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * authentication_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Where to upload a new profile picture, and the file id to set afterwards.+ */+export interface ProfilePictureUpload {+ /** Id to pass to `PUT /user/profile_picture/file` once uploaded. */+ file_id: string;+ /** Expiring URL to `PUT` the image bytes to. */+ upload_url: string;+}diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/putProfilePictureFileRequest.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/putProfilePictureFileRequest.tsnew file mode 100644index 0000000000..01771620a7--- /dev/null+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/putProfilePictureFileRequest.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * authentication_service+ * OpenAPI spec version: 0.1.0+ */++export interface PutProfilePictureFileRequest {+ /** Id of an image the caller uploaded to static file storage. */+ file_id: string;+}diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/teamInviteDetails.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/teamInviteDetails.tsindex 886b126f87..e39b9c63db 100644--- a/apps/web/src/lib/service-clients/service-auth/generated/schemas/teamInviteDetails.ts+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/teamInviteDetails.ts@@ -18,6 +18,8 @@ export interface TeamInviteDetails {id: string;/** The user who sent the invitation */invited_by: string;+ /** Whether the invite creates an agent account */+ is_agent: boolean;/** When the invite was last sent */last_sent_at: string;/** The team id */diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/userName.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/userName.tsindex 95cb072fca..4ca1a2759a 100644--- a/apps/web/src/lib/service-clients/service-auth/generated/schemas/userName.ts+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/userName.ts@@ -10,5 +10,7 @@ import type { UserNameLastName } from './userNameLastName';export interface UserName {first_name?: UserNameFirstName;id: string;+ /** Whether this is an agent account rather than a person. */+ is_agent?: boolean;last_name?: UserNameLastName;}diff --git a/apps/web/src/lib/service-clients/service-auth/openapi.json b/apps/web/src/lib/service-clients/service-auth/openapi.jsonindex 348566bb13..d6f8b9c67e 100644--- a/apps/web/src/lib/service-clients/service-auth/openapi.json+++ b/apps/web/src/lib/service-clients/service-auth/openapi.json@@ -5128,6 +5128,66 @@}}},+ "/user/agent_setup": {+ "post": {+ "tags": ["user::agent_setup"],+ "summary": "Finishes an agent's signup: joins the team that invited it and mints its\nSDK token.",+ "description": "Safe to repeat until the agent confirms it saved the token: a reload replaces\nthe key, and a failed join stays pending for the next attempt.",+ "operationId": "agent_setup",+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/AgentSetupResponse"+ }+ }+ }+ },+ "401": {+ "description": "",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "403": {+ "description": "The account is not an agent",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "409": {+ "description": "Setup is already confirmed",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ }+ },"/user/get_names": {"post": {"tags": ["user::post_get_names"],@@ -5835,6 +5895,132 @@}}},+ "/user/profile_picture/file": {+ "put": {+ "tags": ["user::put_profile_picture_file"],+ "summary": "Sets the caller's profile picture to an image they uploaded.",+ "operationId": "put_profile_picture_file",+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/PutProfilePictureFileRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/EmptyResponse"+ }+ }+ }+ },+ "400": {+ "description": "The file is not a supported image",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "401": {+ "description": "",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "404": {+ "description": "The caller has no such file",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ },+ "post": {+ "tags": ["user::put_profile_picture_file"],+ "summary": "Reserves storage for a new profile picture. Static file storage has no\nMacroDB, so it cannot check API keys; this route lets key holders upload.",+ "operationId": "create_profile_picture_upload",+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CreateProfilePictureUploadRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ProfilePictureUpload"+ }+ }+ }+ },+ "400": {+ "description": "Not a supported image type",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "401": {+ "description": "",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ }+ },"/user/profile_pictures": {"post": {"tags": ["user::post_profile_pictures"],@@ -6322,6 +6508,21 @@"description": "A provider an agent can bring its own key for.","enum": ["anthropic", "openai"]},+ "AgentSetupResponse": {+ "type": "object",+ "description": "What an agent needs to start using the SDK.",+ "required": ["api_key", "team_join_failed"],+ "properties": {+ "api_key": {+ "type": "string",+ "description": "The agent's API key. Shown only here; repeating setup revokes it."+ },+ "team_join_failed": {+ "type": "boolean",+ "description": "Whether joining the inviting team failed. The invite stays pending:\nrepeating setup tries again, and the invite link works after confirming."+ }+ }+ },"AiBillingErrorBody": {"type": "object","description": "Error response body.",@@ -6703,6 +6904,20 @@}}},+ "CreateProfilePictureUploadRequest": {+ "type": "object",+ "required": ["file_name", "content_type"],+ "properties": {+ "content_type": {+ "type": "string",+ "description": "Mime type of the image."+ },+ "file_name": {+ "type": "string",+ "description": "File name, such as `avatar.png`."+ }+ }+ },"CreateTeamRequest": {"type": "object","description": "The request body to create a new team",@@ -7125,6 +7340,7 @@"email","licenseStatus","tutorialComplete",+ "isAgent","hasChromeExt","hasTrialed","aiDataConsent",@@ -7163,6 +7379,10 @@"type": "boolean","description": "Whether the user has trialed through stripe"},+ "isAgent": {+ "type": "boolean",+ "description": "Whether this is an agent account rather than a person"+ },"licenseStatus": {"type": "string","description": "The user's license status"@@ -7821,6 +8041,10 @@},"description": "The invites to send, each with an email and tier"},+ "is_agent": {+ "type": "boolean",+ "description": "Invite these addresses as agents: an address with no account signs up\nas an agent and joins the team when it first signs in."+ },"team_id": {"type": ["string", "null"],"format": "uuid",@@ -7965,6 +8189,10 @@"type": "string","description": "The email to initiate passwordless authentication for"},+ "is_agent": {+ "type": "boolean",+ "description": "Create an agent account if this address has no account yet. Otherwise\n`true` has no effect, and `false` reverts an agent flag nobody has proven:\nsee `revert_unconfirmed_agent`."+ },"redirect_uri": {"type": "string","description": "The redirect uri to redirect to after login"@@ -8264,6 +8492,21 @@}}},+ "ProfilePictureUpload": {+ "type": "object",+ "description": "Where to upload a new profile picture, and the file id to set afterwards.",+ "required": ["file_id", "upload_url"],+ "properties": {+ "file_id": {+ "type": "string",+ "description": "Id to pass to `PUT /user/profile_picture/file` once uploaded."+ },+ "upload_url": {+ "type": "string",+ "description": "Expiring URL to `PUT` the image bytes to."+ }+ }+ },"ProfilePictures": {"type": "object","required": ["pictures"],@@ -8329,6 +8572,16 @@}}},+ "PutProfilePictureFileRequest": {+ "type": "object",+ "required": ["file_id"],+ "properties": {+ "file_id": {+ "type": "string",+ "description": "Id of an image the caller uploaded to static file storage."+ }+ }+ },"PutUserNameQueryParams": {"type": "object","properties": {@@ -8746,7 +8999,8 @@"team_role","invited_by","created_at",- "last_sent_at"+ "last_sent_at",+ "is_agent"],"properties": {"created_at": {@@ -8767,6 +9021,10 @@"type": "string","description": "The user who sent the invitation"},+ "is_agent": {+ "type": "boolean",+ "description": "Whether the invite creates an agent account"+ },"last_sent_at": {"type": "string","format": "date-time",@@ -9183,6 +9441,10 @@"id": {"type": "string"},+ "is_agent": {+ "type": "boolean",+ "description": "Whether this is an agent account rather than a person."+ },"last_name": {"type": ["string", "null"]}diff --git a/apps/web/src/lib/service-clients/service-notification/generated/schemas/inviteToTeamMetadata.ts b/apps/web/src/lib/service-clients/service-notification/generated/schemas/inviteToTeamMetadata.tsindex 5b1c0a73c3..cc64ccae65 100644--- a/apps/web/src/lib/service-clients/service-notification/generated/schemas/inviteToTeamMetadata.ts+++ b/apps/web/src/lib/service-clients/service-notification/generated/schemas/inviteToTeamMetadata.ts@@ -16,6 +16,8 @@ export interface InviteToTeamMetadata {invitedBy: string;/** What the invitee gets by joining, as the team stood when the invite was sent. */inviteePlan?: InviteePlan;+ /** Whether the invite creates an agent account. */+ isAgent?: boolean;/** Whether this email reminds the invitee of an invite they have not answered. */reminder?: boolean;/** Role/permission level in the team */diff --git a/apps/web/src/lib/service-clients/service-notification/generated/zod.ts b/apps/web/src/lib/service-clients/service-notification/generated/zod.tsindex 1981e8fda4..dcb7f00535 100644--- a/apps/web/src/lib/service-clients/service-notification/generated/zod.ts+++ b/apps/web/src/lib/service-clients/service-notification/generated/zod.ts@@ -1064,6 +1064,12 @@ export const listTypedNotificationsResponse = zod.enum(['free', 'premium']).optional().describe('What a team invitee gets by joining.'),+ isAgent: zod+ .boolean()+ .optional()+ .describe(+ 'Whether the invite creates an agent account.'+ ),reminder: zod.boolean().optional()@@ -3113,6 +3119,12 @@ export const bulkGetTypedNotificationsByEventItemIdsResponse = zod.enum(['free', 'premium']).optional().describe('What a team invitee gets by joining.'),+ isAgent: zod+ .boolean()+ .optional()+ .describe(+ 'Whether the invite creates an agent account.'+ ),reminder: zod.boolean().optional()@@ -5156,6 +5168,12 @@ export const getTypedNotificationsByEventItemIdResponse = zod.enum(['free', 'premium']).optional().describe('What a team invitee gets by joining.'),+ isAgent: zod+ .boolean()+ .optional()+ .describe(+ 'Whether the invite creates an agent account.'+ ),reminder: zod.boolean().optional()@@ -7138,6 +7156,10 @@ export const getTypedNotificationByIdResponse = zod.enum(['free', 'premium']).optional().describe('What a team invitee gets by joining.'),+ isAgent: zod+ .boolean()+ .optional()+ .describe('Whether the invite creates an agent account.'),reminder: zod.boolean().optional()diff --git a/apps/web/src/lib/service-clients/service-notification/openapi.json b/apps/web/src/lib/service-clients/service-notification/openapi.jsonindex 5536b23ac1..7a55d7e056 100644--- a/apps/web/src/lib/service-clients/service-notification/openapi.json+++ b/apps/web/src/lib/service-clients/service-notification/openapi.json@@ -2474,6 +2474,10 @@"$ref": "#/components/schemas/InviteePlan","description": "What the invitee gets by joining, as the team stood when the invite was sent."},+ "isAgent": {+ "type": "boolean",+ "description": "Whether the invite creates an agent account."+ },"reminder": {"type": "boolean","description": "Whether this email reminds the invitee of an invite they have not answered."diff --git a/crates/agent_code_mode/src/domain/documentation.json b/crates/agent_code_mode/src/domain/documentation.jsonindex 4896904ff5..7a72852545 100644--- a/crates/agent_code_mode/src/domain/documentation.json+++ b/crates/agent_code_mode/src/domain/documentation.json@@ -138,12 +138,12 @@{"name": "teams","description": "Manage teams and membership: invite people to the team by email, list and revoke pending invites.",- "index": "## teams\nManage teams and membership: invite people to the team by email, list and revoke pending invites.\nRead any symbol below, or one a reference names, with ReadCodeDocs.\n\n### TeamInvite\nA pending invite to the caller's current team.\nExtends `MacroEntity`.\nFields: createdAt, email, id, invitedBy, lastSentAt, role\n- `TeamInvite.revoke`: revoke(): Promise<void> — Revoke this invite so it can no longer be accepted; only a team admin or owner may revoke.\n- `TeamInvite.byId`: static byId(client, id): TeamInvite — A handle to a pending team invite by id.\n- `TeamInvite.from`: static from(client, record): TeamInvite — Build an invite from an already-fetched record (pre-seeded, no fetch).\n\n### TeamNamespace (`macro.teams`)\n- `TeamNamespace.byId`: byId(id): Team — A handle to a team by id.\n- `TeamNamespace.current`: current(): Promise<Team> — The caller's current team.\n- `TeamNamespace.list`: list(): Promise<Team[]> — The teams the caller belongs to.\n\n### Team\nA Macro team.\nExtends `MacroEntity`.\nFields: defaultLinkShare, id, name, owner, slug\n- `Team.invite`: invite(emails): Promise<boolean> — Invite people to this team by email; only invite addresses the user asked you to invite.\n- `Team.invites`: invites(): Promise<TeamInvite[]> — Pending invites to this team; only a team admin or owner may list them.\n- `Team.members`: members(): Promise<TeamMembership[]> — The team's members, with their roles.\n- `Team.byId`: static byId(client, id): Team — A handle to a team by id.\n- `Team.current`: static current(client): Promise<Team> — The caller's current team.\n- `Team.list`: static list(client): Promise<Team[]> — The teams the caller belongs to.\n\nTypes: `TeamMembership`\n"+ "index": "## teams\nManage teams and membership: invite people to the team by email, list and revoke pending invites.\nRead any symbol below, or one a reference names, with ReadCodeDocs.\n\n### TeamInvite\nA pending invite to the caller's current team.\nExtends `MacroEntity`.\nFields: createdAt, email, id, invitedBy, lastSentAt, role\n- `TeamInvite.revoke`: revoke(): Promise<void> — Revoke this invite so it can no longer be accepted; only a team admin or owner may revoke.\n- `TeamInvite.byId`: static byId(client, id): TeamInvite — A handle to a pending team invite by id.\n- `TeamInvite.from`: static from(client, record): TeamInvite — Build an invite from an already-fetched record (pre-seeded, no fetch).\n\n### TeamNamespace (`macro.teams`)\n- `TeamNamespace.byId`: byId(id): Team — A handle to a team by id.\n- `TeamNamespace.current`: current(): Promise<Team> — The caller's current team.\n- `TeamNamespace.list`: list(): Promise<Team[]> — The teams the caller belongs to.\n\n### Team\nA Macro team.\nExtends `MacroEntity`.\nFields: defaultLinkShare, id, name, owner, slug\n- `Team.invite`: invite(emails, options?): Promise<boolean> — Invite people to this team by email; only invite addresses the user asked you to invite.\n- `Team.invites`: invites(): Promise<TeamInvite[]> — Pending invites to this team; only a team admin or owner may list them.\n- `Team.members`: members(): Promise<TeamMembership[]> — The team's members, with their roles.\n- `Team.byId`: static byId(client, id): Team — A handle to a team by id.\n- `Team.current`: static current(client): Promise<Team> — The caller's current team.\n- `Team.list`: static list(client): Promise<Team[]> — The teams the caller belongs to.\n\nTypes: `TeamMembership`\n"},{"name": "users",- "description": "Look up users and their profiles.",- "index": "## users\nLook up users and their profiles.\nRead any symbol below, or one a reference names, with ReadCodeDocs.\n\n### UserNamespace (`macro.users`)\n- `UserNamespace.byId`: byId(id): User — A handle to a user by id.\n- `UserNamespace.me`: me(): Promise<User> — The current authenticated user.\n- `UserNamespace.search`: search(query): Promise<User[]> — Find people in your existing Macro contacts by name or email, as in the mention picker.\n\n### User\nA Macro user.\nExtends `PropertiedEntity`.\nFields: entityType, id\n- `User.dm`: dm(): Promise<Channel> — Open (or create) your direct-message channel with this user.\n- `User.email`: email(): string | undefined — This user's email address.\n- `User.name`: name(): Promise<string | undefined> — This user's display name, fetched from the auth service (falling back to your email contacts when the Macro profile has none).\n- `User.toMention`: toMention(): MentionPart — MentionPart\n- `User.byId`: static byId(client, id): User — A handle to a user by id.\n- `User.fromName`: static fromName(client, name): User — A user handle seeded with an already loaded auth-service name.\n- `User.me`: static me(client): Promise<User> — A handle to the current authenticated user.\n"+ "description": "Look up users and their profiles; set your own name and picture (`macro.me.update`).",+ "index": "## users\nLook up users and their profiles; set your own name and picture (`macro.me.update`).\nRead any symbol below, or one a reference names, with ReadCodeDocs.\n\n### MeNamespace (`macro.me`)\nThe authenticated user's own profile.\n- `MeNamespace.update`: update(options): Promise<void> — Set your display name and profile picture.\n- `MeNamespace.uploadProfilePicture`: uploadProfilePicture(data, options): Promise<StaticImage> — Upload an image to use as your profile picture.\n\n### UserNamespace (`macro.users`)\n- `UserNamespace.byId`: byId(id): User — A handle to a user by id.\n- `UserNamespace.me`: me(): Promise<User> — The current authenticated user.\n- `UserNamespace.search`: search(query): Promise<User[]> — Find people in your existing Macro contacts by name or email, as in the mention picker.\n\n### User\nA Macro user.\nExtends `PropertiedEntity`.\nFields: entityType, id\n- `User.dm`: dm(): Promise<Channel> — Open (or create) your direct-message channel with this user.\n- `User.email`: email(): string | undefined — This user's email address.\n- `User.isAgent`: isAgent(): Promise<boolean> — Whether this user is an agent account rather than a person.\n- `User.name`: name(): Promise<string | undefined> — This user's display name, fetched from the auth service (falling back to your email contacts when the Macro profile has none).\n- `User.toMention`: toMention(): MentionPart — MentionPart\n- `User.byId`: static byId(client, id): User — A handle to a user by id.\n- `User.fromName`: static fromName(client, name): User — A user handle seeded with an already loaded auth-service name.\n- `User.me`: static me(client): Promise<User> — A handle to the current authenticated user.\n\nTypes: `UpdateMeOptions`, `UploadProfilePictureOptions`\n"},{"name": "webhooks",@@ -153,7 +153,7 @@{"name": "core","description": "SDK construction, entity handles, lazy fields, search options, events and shared types.",- "index": "## core\nSDK construction, entity handles, lazy fields, search options, events and shared types.\nRead any symbol below, or one a reference names, with ReadCodeDocs.\n\n### FavoritableEntity\nAn entity the favorites API can address, and so can be (un)favorited.\nExtends `MacroEntity`.\nFields: entityType, id\n- `FavoritableEntity.favorite`: favorite(): Promise<FavoritableEntity<Detail>> — Add this entity to the user's favorites.\n- `FavoritableEntity.permission`: permission(): Promise<{ permission: EntityPermission; status: \"access\"; } | { status: \"no_access\"; }> — Read the caller's effective permission on this entity.\n- `FavoritableEntity.unfavorite`: unfavorite(): Promise<FavoritableEntity<Detail>> — Remove this entity from the user's favorites.\n\n### MacroEntity\nBase for entity handles: a free-to-construct (client, id) pair whose detail record loads lazily on first field access and is dropped after any mutation.\nFields: id\n- `MacroEntity.toJSON`: toJSON(): { detail?: Detail; id: string; } — { detail?: Detail; id: string; }\n\n### PropertiedEntity\nA favoritable entity that also carries user-defined properties.\nExtends `FavoritableEntity`.\nFields: entityType, id\n- `PropertiedEntity.deleteProperty`: deleteProperty(assignment): Promise<void> — Remove a property from this entity, given its [properties](#properties) entry.\n- `PropertiedEntity.properties`: properties(opts?): Promise<EntityPropertyWithDefinition[]> — The properties set on this entity, each with its definition, value, and options.\n- `PropertiedEntity.propertyReference`: propertyReference(): PropertyTargetReference — This entity's reference for bulk property operations.\n- `PropertiedEntity.setProperty`: setProperty(property, value?): Promise<void> — Set a property value on this entity, or attach the property without a value when value is omitted.\n- `PropertiedEntity.updatePropertyOptions`: updatePropertyOptions(changes): Promise<BulkUpdateEntityPropertyOptionsResponse> — Apply multi-select option deltas atomically across this entity's properties.\n\n### MessageThread\nA shared message thread with resolution and deletion operations.\nExtends `MacroEntity`.\nFields: id, parent, resolved\n- `MessageThread.delete`: delete(nonce?): Promise<void> — Delete the entire thread, including replies.\n- `MessageThread.toJSON`: toJSON(): { detail?: ThreadState; id: string; parentId: string; parentType: \"channel\" | \"document\" | \"call\" | \"crm_company\" | \"crm_contact\"; } — Serialize identity with its owning resource.\n- `MessageThread.update`: update(options): Promise<void> — Resolve the thread or detach its annotation anchor.\n- `MessageThread.byId`: static byId(client, parent, id): MessageThread — Construct a scoped thread handle.\n\n### AccessRequest\nOne access request; resolutions preserve optimistic concurrency.\nExtends `MacroEntity`.\nFields: access, id, requestedLevel, requester, revision, status\n- `AccessRequest.resolve`: resolve(grantedLevel?): Promise<void> — Approve with an access level, or decline by omitting it.\n- `AccessRequest.from`: static from(client, access, record): AccessRequest — Seed a request from a state or submission response.\n\n### EntityAccess\nAccess requests and direct grants scoped to a shareable entity.\n- `EntityAccess.cancel`: cancel(revision): Promise<void> — Cancel the caller's own request at its observed revision.\n- `EntityAccess.direct`: direct(): Promise<{ accessLevel: storage.AccessLevel; user: User; }[]> — Direct grants expressed as user handles.\n- `EntityAccess.grant`: grant(user, accessLevel?): Promise<void> — Grant direct access, or remove it by omitting the access level.\n- `EntityAccess.remove`: remove(user): Promise<void> — Remove one user's direct grant.\n- `EntityAccess.request`: request(requestedLevel): Promise<AccessRequest> — Ask the item's reviewers for more access in the caller's name, as the Share menu's Request access does, superseding the caller's latest request.\n- `EntityAccess.resolve`: resolve(request, resolution): Promise<storage.AccessRequest> — Resolve a request belonging to this entity at an observed revision.\n- `EntityAccess.state`: state(offset?): Promise<{ accessLevel: storage.AccessLevel | undefined; canReview: boolean; mine: AccessRequest | undefined; nextOffset: number | undefined; owner: User | undefined; pendingCount: number; requests: AccessRequest[]; supportedLevels: storage.AccessLevel[]; }> — A page of access requests, including the caller's own request and review rights.\n- `EntityAccess.submit`: submit(requestedLevel, revision?): Promise<AccessRequest> — Request access, optionally naming the revision of an earlier request.\n- `EntityAccess.toJSON`: toJSON(): { entity_id: string; entity_type: ShareEntityType; } — Serialize the entity reference without credentials.\n\n### MacroEvents (`macro.events`)\nPer-instance event receiver.\n- `MacroEvents.handle`: handle(rawBody, headers): Promise<void> — Feed a raw webhook delivery in: verifies the signature, parses, and dispatches to matching handlers.\n- `MacroEvents.listen`: listen(opts?): Promise<() => void> — Open a live Server-Sent Events stream of matching broker events.\n- `MacroEvents.on`: on<E>(event, handler): () => void — Subscribe to an event across all entities.\n- `MacroEvents.onSelfMention`: onSelfMention(handler): () => void — Subscribe to @-mentions of the authenticated caller: message.mentioned deliveries whose mentioned entity is this bot (bot auth) or this user (user auth), in ...\n- `MacroEvents.webhook`: webhook(): (req) => Promise<Response> — A Fetch-style handler to mount at your persisted webhook route.\n\n### Macro\nFields: _client, agents, agentSessions, ai, apiKeys, bots, calendar, calls, channels, crm, databases, documents, email, entityMentions, events, externalChats, favorites, foreignEntities, forms, githubPullRequests, harnesses, images, initiatives, meetings, notifications, pins, projects, properties, referrals, routines, tasks, teams, unfurls, users, webAppUrl, webhooks, whatsapp\n- `Macro.myPrincipalId`: myPrincipalId(): Promise<string> — The authenticated caller's mentionable principal — bot|<uuid> for bot auth, macro|<email> for user auth — fetched once and cached.\n- `Macro.requestedAs`: requestedAs(user): Macro<T> — Clone of this SDK acting on behalf of user (sent as x-macro-bot-for-macro-user-id).\n\n### Lazy\nA value fetched on first access and cached thereafter.\n- `Lazy.clear`: clear(): void — Drop the cached value so the next read refetches.\n- `Lazy.get`: get(): Promise<T> — Promise<T>\n- `Lazy.peek`: peek(): T | undefined — The cached value, if already loaded — never triggers a fetch.\n\n### MacroApiError\nA non-2xx HTTP response (Macro API, or a raw fetch like presigned downloads).\nExtends `MacroError`.\nFields: data, status\n\n### MacroError\nBase for every error the SDK throws.\nExtends `Error`.\n\n### MacroForbiddenError\nA 403: the caller lacks the access the request needs.\nExtends `MacroApiError`.\nFields: data, status\n\n### MacroNotFoundError\nThe API succeeded but the addressed entity doesn't exist in the result.\nExtends `MacroError`.\n\nFunctions: `timeline`, `entitySearch`, `sharePermissionBody`, `msg`, `toBody`, `wrapXml`, `paginate`, `unwrap`\n\nTypes: `MacroOpts`, `BotScope`, `Env`, `MacroAuth`, `ServiceName`, `TokenSource`, `HOSTS`, `WEB_APP_URLS`, `Favoritable`, `Propertied`, `PropertyOptionDelta`, `MacroEntityType`, `TimelineOptions`, `MessageParent`, `TimelineMessage`, `EntityReference`, `SearchOpts`, `SearchOn`, `SharePermissionOptions`, `ListenOptions`, `RequestActivity`, `MentionPart`, `Mentionable`, `RichMessage`, `Interpolation`, `here`, `Page`\n"+ "index": "## core\nSDK construction, entity handles, lazy fields, search options, events and shared types.\nRead any symbol below, or one a reference names, with ReadCodeDocs.\n\n### FavoritableEntity\nAn entity the favorites API can address, and so can be (un)favorited.\nExtends `MacroEntity`.\nFields: entityType, id\n- `FavoritableEntity.favorite`: favorite(): Promise<FavoritableEntity<Detail>> — Add this entity to the user's favorites.\n- `FavoritableEntity.permission`: permission(): Promise<{ permission: EntityPermission; status: \"access\"; } | { status: \"no_access\"; }> — Read the caller's effective permission on this entity.\n- `FavoritableEntity.unfavorite`: unfavorite(): Promise<FavoritableEntity<Detail>> — Remove this entity from the user's favorites.\n\n### MacroEntity\nBase for entity handles: a free-to-construct (client, id) pair whose detail record loads lazily on first field access and is dropped after any mutation.\nFields: id\n- `MacroEntity.toJSON`: toJSON(): { detail?: Detail; id: string; } — { detail?: Detail; id: string; }\n\n### PropertiedEntity\nA favoritable entity that also carries user-defined properties.\nExtends `FavoritableEntity`.\nFields: entityType, id\n- `PropertiedEntity.deleteProperty`: deleteProperty(assignment): Promise<void> — Remove a property from this entity, given its [properties](#properties) entry.\n- `PropertiedEntity.properties`: properties(opts?): Promise<EntityPropertyWithDefinition[]> — The properties set on this entity, each with its definition, value, and options.\n- `PropertiedEntity.propertyReference`: propertyReference(): PropertyTargetReference — This entity's reference for bulk property operations.\n- `PropertiedEntity.setProperty`: setProperty(property, value?): Promise<void> — Set a property value on this entity, or attach the property without a value when value is omitted.\n- `PropertiedEntity.updatePropertyOptions`: updatePropertyOptions(changes): Promise<BulkUpdateEntityPropertyOptionsResponse> — Apply multi-select option deltas atomically across this entity's properties.\n\n### MessageThread\nA shared message thread with resolution and deletion operations.\nExtends `MacroEntity`.\nFields: id, parent, resolved\n- `MessageThread.delete`: delete(nonce?): Promise<void> — Delete the entire thread, including replies.\n- `MessageThread.toJSON`: toJSON(): { detail?: ThreadState; id: string; parentId: string; parentType: \"channel\" | \"document\" | \"call\" | \"crm_company\" | \"crm_contact\"; } — Serialize identity with its owning resource.\n- `MessageThread.update`: update(options): Promise<void> — Resolve the thread or detach its annotation anchor.\n- `MessageThread.byId`: static byId(client, parent, id): MessageThread — Construct a scoped thread handle.\n\n### AccessRequest\nOne access request; resolutions preserve optimistic concurrency.\nExtends `MacroEntity`.\nFields: access, id, requestedLevel, requester, revision, status\n- `AccessRequest.resolve`: resolve(grantedLevel?): Promise<void> — Approve with an access level, or decline by omitting it.\n- `AccessRequest.from`: static from(client, access, record): AccessRequest — Seed a request from a state or submission response.\n\n### EntityAccess\nAccess requests and direct grants scoped to a shareable entity.\n- `EntityAccess.cancel`: cancel(revision): Promise<void> — Cancel the caller's own request at its observed revision.\n- `EntityAccess.direct`: direct(): Promise<{ accessLevel: storage.AccessLevel; user: User; }[]> — Direct grants expressed as user handles.\n- `EntityAccess.grant`: grant(user, accessLevel?): Promise<void> — Grant direct access, or remove it by omitting the access level.\n- `EntityAccess.remove`: remove(user): Promise<void> — Remove one user's direct grant.\n- `EntityAccess.request`: request(requestedLevel): Promise<AccessRequest> — Ask the item's reviewers for more access in the caller's name, as the Share menu's Request access does, superseding the caller's latest request.\n- `EntityAccess.resolve`: resolve(request, resolution): Promise<storage.AccessRequest> — Resolve a request belonging to this entity at an observed revision.\n- `EntityAccess.state`: state(offset?): Promise<{ accessLevel: storage.AccessLevel | undefined; canReview: boolean; mine: AccessRequest | undefined; nextOffset: number | undefined; owner: User | undefined; pendingCount: number; requests: AccessRequest[]; supportedLevels: storage.AccessLevel[]; }> — A page of access requests, including the caller's own request and review rights.\n- `EntityAccess.submit`: submit(requestedLevel, revision?): Promise<AccessRequest> — Request access, optionally naming the revision of an earlier request.\n- `EntityAccess.toJSON`: toJSON(): { entity_id: string; entity_type: ShareEntityType; } — Serialize the entity reference without credentials.\n\n### MacroEvents (`macro.events`)\nPer-instance event receiver.\n- `MacroEvents.handle`: handle(rawBody, headers): Promise<void> — Feed a raw webhook delivery in: verifies the signature, parses, and dispatches to matching handlers.\n- `MacroEvents.listen`: listen(opts?): Promise<() => void> — Open a live Server-Sent Events stream of matching broker events.\n- `MacroEvents.on`: on<E>(event, handler): () => void — Subscribe to an event across all entities.\n- `MacroEvents.onSelfMention`: onSelfMention(handler): () => void — Subscribe to @-mentions of the authenticated caller: message.mentioned deliveries whose mentioned entity is this bot (bot auth) or this user (user auth), in ...\n- `MacroEvents.webhook`: webhook(): (req) => Promise<Response> — A Fetch-style handler to mount at your persisted webhook route.\n\n### Macro\nFields: _client, agents, agentSessions, ai, apiKeys, bots, calendar, calls, channels, crm, databases, documents, email, entityMentions, events, externalChats, favorites, foreignEntities, forms, githubPullRequests, harnesses, images, initiatives, me, meetings, notifications, pins, projects, properties, referrals, routines, tasks, teams, unfurls, users, webAppUrl, webhooks, whatsapp\n- `Macro.myPrincipalId`: myPrincipalId(): Promise<string> — The authenticated caller's mentionable principal — bot|<uuid> for bot auth, macro|<email> for user auth — fetched once and cached.\n- `Macro.requestedAs`: requestedAs(user): Macro<T> — Clone of this SDK acting on behalf of user (sent as x-macro-bot-for-macro-user-id).\n\n### Lazy\nA value fetched on first access and cached thereafter.\n- `Lazy.clear`: clear(): void — Drop the cached value so the next read refetches.\n- `Lazy.get`: get(): Promise<T> — Promise<T>\n- `Lazy.peek`: peek(): T | undefined — The cached value, if already loaded — never triggers a fetch.\n\n### MacroApiError\nA non-2xx HTTP response (Macro API, or a raw fetch like presigned downloads).\nExtends `MacroError`.\nFields: data, status\n\n### MacroError\nBase for every error the SDK throws.\nExtends `Error`.\n\n### MacroForbiddenError\nA 403: the caller lacks the access the request needs.\nExtends `MacroApiError`.\nFields: data, status\n\n### MacroNotFoundError\nThe API succeeded but the addressed entity doesn't exist in the result.\nExtends `MacroError`.\n\nFunctions: `timeline`, `entitySearch`, `sharePermissionBody`, `msg`, `toBody`, `wrapXml`, `paginate`, `unwrap`\n\nTypes: `MacroOpts`, `BotScope`, `Env`, `MacroAuth`, `ServiceName`, `TokenSource`, `HOSTS`, `WEB_APP_URLS`, `Favoritable`, `Propertied`, `PropertyOptionDelta`, `MacroEntityType`, `TimelineOptions`, `MessageParent`, `TimelineMessage`, `EntityReference`, `SearchOpts`, `SearchOn`, `SharePermissionOptions`, `ListenOptions`, `RequestActivity`, `MentionPart`, `Mentionable`, `RichMessage`, `Interpolation`, `here`, `Page`\n"}],"symbols": {@@ -260,9 +260,9 @@"auth.LinkShare": "# Type Alias: LinkShare\n\n> **LinkShare** = `\"PUBLIC\"` \\| `\"TEAM\"`\n\nDefines who can access an item through its share link.","MacroApiTokenResponse": "# Type Alias: MacroApiTokenResponse\n\n> **MacroApiTokenResponse** = \\{ `macro_api_token`: `string`; \\}\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-macro_api_token\"></a> `macro_api_token` | `string` | The newly created macro_api_token |","auth.Team": "# Type Alias: Team\n\n> **Team** = \\{ `allow_non_admin_invites`: `boolean`; `auto_join_domain?`: `string` \\| `null`; `crm_enabled`: `boolean`; `default_link_share?`: `null` \\| `auth.LinkShare`; `enterprise`: `boolean`; `id`: `string`; `language?`: `null` \\| `Language`; `name`: `string`; `owner_id`: `string`; `slug`: `string`; \\}\n\nThe Team struct\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-allow_non_admin_invites\"></a> `allow_non_admin_invites` | `boolean` | Whether non-admin members may invite users to the team. Defaults to true; admins can turn it off so only admins/owners may invite. |\n| <a id=\"property-auto_join_domain\"></a> `auto_join_domain?` | `string` \\| `null` | The email domain new users are automatically joined to this team with, when automatic domain joining is enabled (None otherwise). |\n| <a id=\"property-crm_enabled\"></a> `crm_enabled` | `boolean` | Whether the CRM is enabled for this team (from `team_crm_settings`; `false` when no row exists). |\n| <a id=\"property-default_link_share\"></a> `default_link_share?` | `null` \\| `auth.LinkShare` | - |\n| <a id=\"property-enterprise\"></a> `enterprise` | `boolean` | Whether this team is on an enterprise license. Enterprise teams are billed out-of-band; membership changes skip all Stripe subscription bookkeeping (no seat counts, no subscription backfill, no paying check). |\n| <a id=\"property-id\"></a> `id` | `string` | - |\n| <a id=\"property-language\"></a> `language?` | `null` \\| `Language` | - |\n| <a id=\"property-name\"></a> `name` | `string` | - |\n| <a id=\"property-owner_id\"></a> `owner_id` | `string` | - |\n| <a id=\"property-slug\"></a> `slug` | `string` | - |",- "TeamInviteDetails": "# Type Alias: TeamInviteDetails\n\n> **TeamInviteDetails** = \\{ `created_at`: `string`; `email`: `string`; `id`: `string`; `invited_by`: `string`; `last_sent_at`: `string`; `team_id`: `string`; `team_role`: `auth.TeamRole`; \\}\n\nDetailed information about a team invite\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-created_at\"></a> `created_at` | `string` | When the invite was created |\n| <a id=\"property-email\"></a> `email` | `string` | The invited email |\n| <a id=\"property-id\"></a> `id` | `string` | The invite id |\n| <a id=\"property-invited_by\"></a> `invited_by` | `string` | The user who sent the invitation |\n| <a id=\"property-last_sent_at\"></a> `last_sent_at` | `string` | When the invite was last sent |\n| <a id=\"property-team_id\"></a> `team_id` | `string` | The team id |\n| <a id=\"property-team_role\"></a> `team_role` | `auth.TeamRole` | The role being invited as |",+ "TeamInviteDetails": "# Type Alias: TeamInviteDetails\n\n> **TeamInviteDetails** = \\{ `created_at`: `string`; `email`: `string`; `id`: `string`; `invited_by`: `string`; `is_agent`: `boolean`; `last_sent_at`: `string`; `team_id`: `string`; `team_role`: `auth.TeamRole`; \\}\n\nDetailed information about a team invite\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-created_at\"></a> `created_at` | `string` | When the invite was created |\n| <a id=\"property-email\"></a> `email` | `string` | The invited email |\n| <a id=\"property-id\"></a> `id` | `string` | The invite id |\n| <a id=\"property-invited_by\"></a> `invited_by` | `string` | The user who sent the invitation |\n| <a id=\"property-is_agent\"></a> `is_agent` | `boolean` | Whether the invite creates an agent account |\n| <a id=\"property-last_sent_at\"></a> `last_sent_at` | `string` | When the invite was last sent |\n| <a id=\"property-team_id\"></a> `team_id` | `string` | The team id |\n| <a id=\"property-team_role\"></a> `team_role` | `auth.TeamRole` | The role being invited as |","auth.TeamRole": "# Type Alias: TeamRole\n\n> **TeamRole** = `\"member\"` \\| `\"admin\"` \\| `\"owner\"`\n\nOrdered from least to most access top -> bottom",- "UserName": "# Type Alias: UserName\n\n> **UserName** = \\{ `first_name?`: `string` \\| `null`; `id`: `string`; `last_name?`: `string` \\| `null`; \\}\n\n## Properties\n\n| Property | Type |\n| ------ | ------ |\n| <a id=\"property-first_name\"></a> `first_name?` | `string` \\| `null` |\n| <a id=\"property-id\"></a> `id` | `string` |\n| <a id=\"property-last_name\"></a> `last_name?` | `string` \\| `null` |",+ "UserName": "# Type Alias: UserName\n\n> **UserName** = \\{ `first_name?`: `string` \\| `null`; `id`: `string`; `is_agent?`: `boolean`; `last_name?`: `string` \\| `null`; \\}\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-first_name\"></a> `first_name?` | `string` \\| `null` | - |\n| <a id=\"property-id\"></a> `id` | `string` | - |\n| <a id=\"property-is_agent\"></a> `is_agent?` | `boolean` | Whether this is an agent account rather than a person. |\n| <a id=\"property-last_name\"></a> `last_name?` | `string` \\| `null` | - |","calendar.AttendeeResponseStatus": "# Type Alias: AttendeeResponseStatus\n\n> **AttendeeResponseStatus** = `\"needs_action\"` \\| `\"accepted\"` \\| `\"declined\"` \\| `\"tentative\"`\n\nRSVP state for an attendee.","calendar.CalendarAttendee": "# Type Alias: CalendarAttendee\n\n> **CalendarAttendee** = \\{ `comment?`: `string` \\| `null`; `displayName?`: `string` \\| `null`; `email`: `string`; `isOptional`: `boolean`; `isOrganizer`: `boolean`; `isSelf`: `boolean`; `responseStatus`: `calendar.AttendeeResponseStatus`; \\}\n\nAn attendee on a calendar event.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-comment\"></a> `comment?` | `string` \\| `null` | Optional attendee comment. |\n| <a id=\"property-displayname\"></a> `displayName?` | `string` \\| `null` | Provider display name. |\n| <a id=\"property-email\"></a> `email` | `string` | Normalized email address. |\n| <a id=\"property-isoptional\"></a> `isOptional` | `boolean` | Whether attendance is optional. |\n| <a id=\"property-isorganizer\"></a> `isOrganizer` | `boolean` | Whether this attendee is the organizer. |\n| <a id=\"property-isself\"></a> `isSelf` | `boolean` | Whether this attendee is one of the viewing requester's inboxes. |\n| <a id=\"property-responsestatus\"></a> `responseStatus` | `calendar.AttendeeResponseStatus` | RSVP state. |","CalendarAttendeeInputBody": "# Type Alias: CalendarAttendeeInputBody\n\n> **CalendarAttendeeInputBody** = \\{ `email`: `string`; `isOptional?`: `boolean`; \\}\n\nAn attendee supplied to a calendar mutation.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-email\"></a> `email` | `string` | Attendee email address. |\n| <a id=\"property-isoptional\"></a> `isOptional?` | `boolean` | Whether attendance is optional. |",@@ -422,7 +422,7 @@"InboxReauthRequiredMetadata": "# Type Alias: InboxReauthRequiredMetadata\n\n> **InboxReauthRequiredMetadata** = \\{ `emailAddress`: `string`; \\}\n\nMetadata for a notification that a linked inbox's grant has died and the\ninbox must be reconnected. Fanned out to the inbox owner and every delegate,\nsince any of them holding the Google grant can restore sync.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-emailaddress\"></a> `emailAddress` | `string` | The address of the inbox that needs to be reconnected. |","InitiativeDiscussionMetadata": "# Type Alias: InitiativeDiscussionMetadata\n\n> **InitiativeDiscussionMetadata** = \\{ `messageId`: `string`; `owner`: `string`; `projectName`: `string`; `reason`: `InitiativeDiscussionReason`; `senderDisplayName?`: `string` \\| `null`; `senderProfilePictureUrl?`: `string` \\| `null`; `text`: `string`; `threadId`: `string`; \\}\n\nProject discussion metadata. The notification entity identifies the initiative;\nmessage and thread UUIDs select the discussion inside that project.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-messageid\"></a> `messageId` | `string` | Canonical shared message UUID. |\n| <a id=\"property-owner\"></a> `owner` | `string` | Authenticated project owner. |\n| <a id=\"property-projectname\"></a> `projectName` | `string` | Name displayed in the project header. |\n| <a id=\"property-reason\"></a> `reason` | `InitiativeDiscussionReason` | Semantic reason selected by the message delivery domain. |\n| <a id=\"property-senderdisplayname\"></a> `senderDisplayName?` | `string` \\| `null` | Public display name for a bot author. |\n| <a id=\"property-senderprofilepictureurl\"></a> `senderProfilePictureUrl?` | `string` \\| `null` | Optional avatar for push notification attachments. |\n| <a id=\"property-text\"></a> `text` | `string` | Posted Markdown content. |\n| <a id=\"property-threadid\"></a> `threadId` | `string` | Canonical discussion root UUID. |","InitiativeDiscussionReason": "# Type Alias: InitiativeDiscussionReason\n\n> **InitiativeDiscussionReason** = `\"mention\"` \\| `\"reply\"` \\| `\"assignee\"` \\| `\"owner\"`\n\nWhy a project discussion notification was delivered.",- "InviteToTeamMetadata": "# Type Alias: InviteToTeamMetadata\n\n> **InviteToTeamMetadata** = \\{ `invitedBy`: `string`; `inviteePlan?`: `InviteePlan`; `reminder?`: `boolean`; `role?`: `string` \\| `null`; `senderProfilePictureUrl?`: `string` \\| `null`; `teamId`: `string`; `teamInviteId`: `string`; `teamName`: `string`; \\}\n\nMetadata for when a user is invited to a team.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-invitedby\"></a> `invitedBy` | `string` | The user who sent the invitation |\n| <a id=\"property-inviteeplan\"></a> `inviteePlan?` | `InviteePlan` | What the invitee gets by joining, as the team stood when the invite was sent. |\n| <a id=\"property-reminder\"></a> `reminder?` | `boolean` | Whether this email reminds the invitee of an invite they have not answered. |\n| <a id=\"property-role\"></a> `role?` | `string` \\| `null` | Role/permission level in the team |\n| <a id=\"property-senderprofilepictureurl\"></a> `senderProfilePictureUrl?` | `string` \\| `null` | The sender's profile picture URL, if available. |\n| <a id=\"property-teamid\"></a> `teamId` | `string` | The unique identifier of the team |\n| <a id=\"property-teaminviteid\"></a> `teamInviteId` | `string` | The unique identifier of the team invite |\n| <a id=\"property-teamname\"></a> `teamName` | `string` | The name of the team being invited to |",+ "InviteToTeamMetadata": "# Type Alias: InviteToTeamMetadata\n\n> **InviteToTeamMetadata** = \\{ `invitedBy`: `string`; `inviteePlan?`: `InviteePlan`; `isAgent?`: `boolean`; `reminder?`: `boolean`; `role?`: `string` \\| `null`; `senderProfilePictureUrl?`: `string` \\| `null`; `teamId`: `string`; `teamInviteId`: `string`; `teamName`: `string`; \\}\n\nMetadata for when a user is invited to a team.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-invitedby\"></a> `invitedBy` | `string` | The user who sent the invitation |\n| <a id=\"property-inviteeplan\"></a> `inviteePlan?` | `InviteePlan` | What the invitee gets by joining, as the team stood when the invite was sent. |\n| <a id=\"property-isagent\"></a> `isAgent?` | `boolean` | Whether the invite creates an agent account. |\n| <a id=\"property-reminder\"></a> `reminder?` | `boolean` | Whether this email reminds the invitee of an invite they have not answered. |\n| <a id=\"property-role\"></a> `role?` | `string` \\| `null` | Role/permission level in the team |\n| <a id=\"property-senderprofilepictureurl\"></a> `senderProfilePictureUrl?` | `string` \\| `null` | The sender's profile picture URL, if available. |\n| <a id=\"property-teamid\"></a> `teamId` | `string` | The unique identifier of the team |\n| <a id=\"property-teaminviteid\"></a> `teamInviteId` | `string` | The unique identifier of the team invite |\n| <a id=\"property-teamname\"></a> `teamName` | `string` | The name of the team being invited to |","InviteePlan": "# Type Alias: InviteePlan\n\n> **InviteePlan** = `\"free\"` \\| `\"premium\"`\n\nWhat a team invitee gets by joining.","MentionedInDocumentCommentMetadata": "# Type Alias: MentionedInDocumentCommentMetadata\n\n> **MentionedInDocumentCommentMetadata** = \\{ `commentId`: `CommentRef`; `documentName`: `string`; `fileType?`: `string` \\| `null`; `mentionId`: `string`; `owner`: `string`; `senderDisplayName?`: `string` \\| `null`; `senderProfilePictureUrl?`: `string` \\| `null`; `subType?`: `null` \\| `NotificationDocumentSubType`; `text`: `string`; `threadId`: `CommentRef`; \\}\n\nNotification sent when a user is mentioned in a document comment.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-commentid\"></a> `commentId` | `CommentRef` | the comment id |\n| <a id=\"property-documentname\"></a> `documentName` | `string` | The name of the document. |\n| <a id=\"property-filetype\"></a> `fileType?` | `string` \\| `null` | The file type of the document. |\n| <a id=\"property-mentionid\"></a> `mentionId` | `string` | The mention ID. |\n| <a id=\"property-owner\"></a> `owner` | `string` | The owner of the document. |\n| <a id=\"property-senderdisplayname\"></a> `senderDisplayName?` | `string` \\| `null` | Public bot name when the author is an agent rather than a Macro user. |\n| <a id=\"property-senderprofilepictureurl\"></a> `senderProfilePictureUrl?` | `string` \\| `null` | - |\n| <a id=\"property-subtype\"></a> `subType?` | `null` \\| `NotificationDocumentSubType` | - |\n| <a id=\"property-text\"></a> `text` | `string` | the text of the comment |\n| <a id=\"property-threadid\"></a> `threadId` | `CommentRef` | the thread id |","NewEmailMetadata": "# Type Alias: NewEmailMetadata\n\n> **NewEmailMetadata** = \\{ `sender?`: `string` \\| `null`; `snippet`: `string`; `subject`: `string`; `threadId`: `string`; `toEmail`: `string`; \\}\n\n## Properties\n\n| Property | Type |\n| ------ | ------ |\n| <a id=\"property-sender\"></a> `sender?` | `string` \\| `null` |\n| <a id=\"property-snippet\"></a> `snippet` | `string` |\n| <a id=\"property-subject\"></a> `subject` | `string` |\n| <a id=\"property-threadid\"></a> `threadId` | `string` |\n| <a id=\"property-toemail\"></a> `toEmail` | `string` |",@@ -1745,6 +1745,11 @@"InitiativeNamespace.list": "### list()\n\n> **list**(): `Promise`\\<`Initiative`[]\\>\n\nList accessible initiatives as handles; use `summaries()` for their names.\n\n#### Returns\n\n`Promise`\\<`Initiative`[]\\>","InitiativeNamespace.summaries": "### summaries()\n\n> **summaries**(): `Promise`\\<`InitiativeSummary`[]\\>\n\nEvery accessible initiative with its name, in one request.\n\n#### Returns\n\n`Promise`\\<`InitiativeSummary`[]\\>","InitiativeSummary": "# Interface: InitiativeSummary\n\nAn initiative with the name and update time its listing already carries.\n\n## Properties\n\n| Property | Type |\n| ------ | ------ |\n| <a id=\"property-initiative\"></a> `initiative` | `Initiative` |\n| <a id=\"property-name\"></a> `name` | `string` |\n| <a id=\"property-updatedat\"></a> `updatedAt` | `string` |",+ "MeNamespace": "# Class: MeNamespace\n\nThe authenticated user's own profile.",+ "MeNamespace.update": "### update()\n\n> **update**(`options`): `Promise`\\<`void`\\>\n\nSet your display name and profile picture. Agents should do this after\nsigning in, so teammates can tell who they are working with.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `options` | `UpdateMeOptions` |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n#### Example\n\n```ts\nconst image = await macro.me.uploadProfilePicture(bytes, {\n fileName: 'avatar.png',\n contentType: 'image/png',\n});\nawait macro.me.update({ name: 'Research Agent', profilePicture: image });\n```",+ "MeNamespace.uploadProfilePicture": "### uploadProfilePicture()\n\n> **uploadProfilePicture**(`data`, `options`): `Promise`\\<`StaticImage`\\>\n\nUpload an image to use as your profile picture. This only stores it; pass\nthe result to [MeNamespace.update](#update) to start using it.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `data` | `Blob` \\| `Uint8Array`\\<`ArrayBuffer`\\> |\n| `options` | `UploadProfilePictureOptions` |\n\n#### Returns\n\n`Promise`\\<`StaticImage`\\>",+ "UpdateMeOptions": "# Interface: UpdateMeOptions\n\nWhat to change on the authenticated user's profile.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-name\"></a> `name?` | `string` | Display name. The first word becomes the first name. |\n| <a id=\"property-profilepicture\"></a> `profilePicture?` | `StaticImage` | An image from `MeNamespace.uploadProfilePicture`. |",+ "UploadProfilePictureOptions": "# Interface: UploadProfilePictureOptions\n\nHow to store an uploaded profile picture.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-contenttype\"></a> `contentType` | `string` | `image/png`, `image/jpeg`, `image/webp` or `image/gif`. |\n| <a id=\"property-filename\"></a> `fileName` | `string` | File name, such as `avatar.png`. |","Meeting": "# Class: Meeting\n\nA meeting's schedule and invitation link.\n\n## Extends\n\n- `MacroEntity`\\<`storage.Meeting`\\>\n\n## Properties\n\n| Property | Modifier | Type | Description | Inherited from |\n| ------ | ------ | ------ | ------ | ------ |\n| <a id=\"property-call\"></a> `call` | `readonly` | () => `Promise`\\<`CallRecord` \\| `undefined`\\> | Associated call record. | - |\n| <a id=\"property-channel\"></a> `channel` | `readonly` | () => `Promise`\\<`Channel` \\| `undefined`\\> | Associated channel. | - |\n| <a id=\"property-id\"></a> `id` | `public readonly` | `string` | - | `MacroEntity.id` |\n| <a id=\"property-scheduledend\"></a> `scheduledEnd` | `readonly` | () => `Promise`\\<`string` \\| `undefined`\\> | Scheduled end. | - |\n| <a id=\"property-scheduledstart\"></a> `scheduledStart` | `readonly` | () => `Promise`\\<`string` \\| `undefined`\\> | Scheduled start. | - |\n| <a id=\"property-title\"></a> `title` | `readonly` | () => `Promise`\\<`string`\\> | Display title. | - |","Meeting.cancel": "### cancel()\n\n> **cancel**(): `Promise`\\<`void`\\>\n\nCancel this meeting.\n\n#### Returns\n\n`Promise`\\<`void`\\>","Meeting.invite": "### invite()\n\n> **invite**(`email`): `Promise`\\<`void`\\>\n\nInvite an email address.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `email` | `string` |\n\n#### Returns\n\n`Promise`\\<`void`\\>",@@ -1954,7 +1959,7 @@"TeamNamespace.current": "### current()\n\n> **current**(): `Promise`\\<`Team`\\>\n\nThe caller's current team.\n\n#### Returns\n\n`Promise`\\<`Team`\\>","TeamNamespace.list": "### list()\n\n> **list**(): `Promise`\\<`Team`[]\\>\n\nThe teams the caller belongs to.\n\n#### Returns\n\n`Promise`\\<`Team`[]\\>","Team": "# Class: Team\n\nA Macro team. A free-to-construct handle; the record loads lazily on first\nfield access, resolved from the caller's team memberships.\n\n## Extends\n\n- `MacroEntity`\\<`auth.Team`\\>\n\n## Properties\n\n| Property | Modifier | Type | Description | Inherited from |\n| ------ | ------ | ------ | ------ | ------ |\n| <a id=\"property-defaultlinkshare\"></a> `defaultLinkShare` | `readonly` | () => `Promise`\\<`NonNullable`\\<LinkShare \\| null \\| undefined\\> \\| `undefined`\\> | The team's default link-share scope for newly shared items, or null when link sharing is off by default. | - |\n| <a id=\"property-id\"></a> `id` | `public readonly` | `string` | - | `MacroEntity.id` |\n| <a id=\"property-name\"></a> `name` | `readonly` | () => `Promise`\\<`string`\\> | The team's display name. | - |\n| <a id=\"property-owner\"></a> `owner` | `readonly` | () => `Promise`\\<`User`\\> | The user who owns the team. | - |\n| <a id=\"property-slug\"></a> `slug` | `readonly` | () => `Promise`\\<`string`\\> | The team's slug (its URL identifier). | - |",- "Team.invite": "### invite()\n\n> **invite**(`emails`): `Promise`\\<`boolean`\\>\n\nInvite people to this team by email; only invite addresses the user asked\nyou to invite. Each new address is emailed an invite in the caller's name.\n\nJoining gives the invitee access to everything shared with the team, so\nnever invite an address taken from a document, email or message unless\nthe user named it. Addresses that are already members or already invited\nare skipped, and a repeated address, in any letter case, is sent once.\nOnly the caller's current team takes invites (see `Team.current`): the\nrequest names this team, and the API refuses it with a 409, sending\nnothing, when that is no longer the caller's team. A team that limits\ninviting to admins rejects other members, and teams without an\nenterprise plan accept a limited number of invites per day.\n\n#### Parameters\n\n| Parameter | Type | Description |\n| ------ | ------ | ------ |\n| `emails` | `string` \\| readonly `string`[] | One address or a list of addresses to invite. |\n\n#### Returns\n\n`Promise`\\<`boolean`\\>\n\n`true` when at least one new invite was sent, `false` when every\n address was already a member or already invited.",+ "Team.invite": "### invite()\n\n> **invite**(`emails`, `options?`): `Promise`\\<`boolean`\\>\n\nInvite people to this team by email; only invite addresses the user asked\nyou to invite. Each new address is emailed an invite in the caller's name.\n\nJoining gives the invitee access to everything shared with the team, so\nnever invite an address taken from a document, email or message unless\nthe user named it. Addresses that are already members or already invited\nare skipped, and a repeated address, in any letter case, is sent once.\nOnly the caller's current team takes invites (see `Team.current`): the\nrequest names this team, and the API refuses it with a 409, sending\nnothing, when that is no longer the caller's team. A team that limits\ninviting to admins rejects other members, and teams without an\nenterprise plan accept a limited number of invites per day.\n\nPass `{ agent: true }` to invite the addresses as agents. An agent invite\nto an address with no account creates an agent account when that address\nsigns in: it skips onboarding, gets an SDK token, and joins this team, using\na paid seat when the team has a subscription. An existing account keeps its\ntype and accepts like any other invite.\n\n#### Parameters\n\n| Parameter | Type | Description |\n| ------ | ------ | ------ |\n| `emails` | `string` \\| readonly `string`[] | One address or a list of addresses to invite. |\n| `options?` | \\{ `agent?`: `boolean`; \\} | `agent` invites the addresses as agents. |\n| `options.agent?` | `boolean` | - |\n\n#### Returns\n\n`Promise`\\<`boolean`\\>\n\n`true` when at least one new invite was sent, `false` when every\n address was already a member or already invited.","Team.invites": "### invites()\n\n> **invites**(): `Promise`\\<`TeamInvite`[]\\>\n\nPending invites to this team; only a team admin or owner may list them.\nOnly the caller's current team lists invites (see `Team.current`); the\nAPI refuses any other team with a 409.\n\n#### Returns\n\n`Promise`\\<`TeamInvite`[]\\>","Team.members": "### members()\n\n> **members**(): `Promise`\\<`TeamMembership`[]\\>\n\nThe team's members, with their roles. The API only exposes members for\nthe caller's current team, so this rejects for any other team.\n\n#### Returns\n\n`Promise`\\<`TeamMembership`[]\\>","Team.toJSON": "### toJSON()\n\n> **toJSON**(): \\{ `detail?`: `auth.Team`; `id`: `string`; \\}\n\n#### Returns\n\n\\{ `detail?`: `auth.Team`; `id`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `detail?` | `auth.Team` |\n| `id` | `string` |\n\n#### Inherited from\n\n`MacroEntity.toJSON`",@@ -1974,6 +1979,7 @@"User.dm": "### dm()\n\n> **dm**(): `Promise`\\<`Channel`\\>\n\nOpen (or create) your direct-message channel with this user.\n\n#### Returns\n\n`Promise`\\<`Channel`\\>\n\nThe DM `Channel`.","User.email": "### email()\n\n> **email**(): `string` \\| `undefined`\n\nThis user's email address. Macro user ids encode it as `macro|<email>`,\nso this reads straight off the id — no auth-service endpoint returns\nemails for arbitrary users.\n\n#### Returns\n\n`string` \\| `undefined`\n\nThe email, or `undefined` if the id is not email-derived.","User.favorite": "### favorite()\n\n> **favorite**(): `Promise`\\<`User`\\>\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`\\<`User`\\>\n\n#### Inherited from\n\n`PropertiedEntity.favorite`",+ "User.isAgent": "### isAgent()\n\n> **isAgent**(): `Promise`\\<`boolean`\\>\n\nWhether this user is an agent account rather than a person.\n\n#### Returns\n\n`Promise`\\<`boolean`\\>\n\n`true` for an agent account.","User.name": "### name()\n\n> **name**(): `Promise`\\<`string` \\| `undefined`\\>\n\nThis user's display name, fetched from the auth service (falling back to\nyour email contacts when the Macro profile has none).\n\n#### Returns\n\n`Promise`\\<`string` \\| `undefined`\\>\n\nThe full name, or `undefined` if the user has no name on record.","User.permission": "### permission()\n\n> **permission**(): `Promise`\\<\\{ `permission`: `EntityPermission`; `status`: `\"access\"`; \\} \\| \\{ `status`: `\"no_access\"`; \\}\\>\n\nRead the caller's effective permission on this entity.\n\n#### Returns\n\n`Promise`\\<\\{ `permission`: `EntityPermission`; `status`: `\"access\"`; \\} \\| \\{ `status`: `\"no_access\"`; \\}\\>\n\n#### Inherited from\n\n`PropertiedEntity.permission`","User.properties": "### properties()\n\n> **properties**(`opts?`): `Promise`\\<`EntityPropertyWithDefinition`[]\\>\n\nThe properties set on this entity, each with its definition, value, and options.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `opts?` | \\{ `includeMetadata?`: `boolean`; \\} |\n| `opts.includeMetadata?` | `boolean` |\n\n#### Returns\n\n`Promise`\\<`EntityPropertyWithDefinition`[]\\>\n\n#### Inherited from\n\n`PropertiedEntity.properties`",@@ -2027,7 +2033,7 @@"MacroEvents.onSelfMention": "### onSelfMention()\n\n> **onSelfMention**(`handler`): () => `void`\n\nSubscribe to @-mentions of the authenticated caller: `message.mentioned`\ndeliveries whose mentioned entity is this bot (bot auth) or this user\n(user auth), in channels and in document comments alike.\n\n`message.mentioned` deliveries cover every mention the stream's (or\nwebhook's) workspace can access (its `ids` filter holds channel or\ndocument ids); picking out \"me\" happens here, client-side. The caller's\nidentity is resolved lazily (once) on the first delivery.\n\nFor SSE, register this handler before [listen](#listen) so the derived\nfilters include `message.mentioned`. For persisted webhooks, register the\nwebhook separately, e.g. `macro.webhooks.create({ filters: [{ events:\n['message.mentioned'] }], … })`.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `handler` | `EventHandler`\\<`\"message.mentioned\"`\\> |\n\n#### Returns\n\nAn unsubscribe function.\n\n() => `void`","MacroEvents.webhook": "### webhook()\n\n> **webhook**(): (`req`) => `Promise`\\<`Response`\\>\n\nA Fetch-style handler to mount at your persisted webhook route.\n\nRequires `webhookSecret` (or `MACRO_WEBHOOK_SECRET`).\n\n#### Returns\n\n(`req`) => `Promise`\\<`Response`\\>\n\n#### Example\n\n```ts\napp.post('/webhook', macro.events.webhook()); // Hono\n```","ListenOptions": "# Interface: ListenOptions\n\nOptions for `MacroEvents.listen`.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-filters\"></a> `filters?` | `WebhookFilter`[] | Event/entity-id filters, identical to persisted webhook `filters`. Defaults to one filter covering every event currently registered with `MacroEvents.on`. |\n| <a id=\"property-scope\"></a> `scope?` | `WebhookScope` | Personal or team workspace whose webhook lifecycle events are delivered. Defaults to `'user'`. |\n| <a id=\"property-signal\"></a> `signal?` | `AbortSignal` | Abort the stream. |",- "Macro": "# Class: Macro\\<T\\>\n\n## Type Parameters\n\n| Type Parameter | Default type |\n| ------ | ------ |\n| <a id=\"type-parameter-t\"></a> `T` *extends* `MacroOpts` | `MacroOpts` |\n\n## Properties\n\n| Property | Modifier | Type | Description |\n| ------ | ------ | ------ | ------ |\n| <a id=\"property-_client\"></a> `_client` | `readonly` | `MacroClient` | Direct access to the underlying hey-api service clients. |\n| <a id=\"property-agents\"></a> `agents` | `readonly` | `AgentNamespace` | agents resources and operations. |\n| <a id=\"property-agentsessions\"></a> `agentSessions` | `readonly` | `AgentSessionNamespace` | - |\n| <a id=\"property-ai\"></a> `ai` | `readonly` | `AiNamespace` | - |\n| <a id=\"property-apikeys\"></a> `apiKeys` | `readonly` | `ApiKeyNamespace` | apiKeys resources and operations. |\n| <a id=\"property-bots\"></a> `bots` | `readonly` | `BotsNamespace` | - |\n| <a id=\"property-calendar\"></a> `calendar` | `readonly` | `CalendarNamespace` | - |\n| <a id=\"property-calls\"></a> `calls` | `readonly` | `CallRecordNamespace` | - |\n| <a id=\"property-channels\"></a> `channels` | `readonly` | `ChannelNamespace` | - |\n| <a id=\"property-crm\"></a> `crm` | `readonly` | `CrmNamespace` | - |\n| <a id=\"property-databases\"></a> `databases` | `readonly` | `DatabaseNamespace` | - |\n| <a id=\"property-documents\"></a> `documents` | `readonly` | `DocumentNamespace` | - |\n| <a id=\"property-email\"></a> `email` | `readonly` | `EmailNamespace` | - |\n| <a id=\"property-entitymentions\"></a> `entityMentions` | `readonly` | `EntityMentionNamespace` | entityMentions resources and operations. |\n| <a id=\"property-events\"></a> `events` | `readonly` | `MacroEvents` | - |\n| <a id=\"property-externalchats\"></a> `externalChats` | `readonly` | `ExternalChatsNamespace` | Chats from external providers (WhatsApp) added to Macro: read, share and send. |\n| <a id=\"property-favorites\"></a> `favorites` | `readonly` | `FavoritesNamespace` | - |\n| <a id=\"property-foreignentities\"></a> `foreignEntities` | `readonly` | `ForeignEntityNamespace` | - |\n| <a id=\"property-forms\"></a> `forms` | `readonly` | `FormNamespace` | Build forms and submit answers without granting respondents database access. |\n| <a id=\"property-githubpullrequests\"></a> `githubPullRequests` | `readonly` | `GithubPullRequestNamespace` | githubPullRequests resources and operations. |\n| <a id=\"property-harnesses\"></a> `harnesses` | `readonly` | `HarnessNamespace` | harnesses resources and operations. |\n| <a id=\"property-images\"></a> `images` | `readonly` | `ImagesNamespace` | Generate images with AI and attach them to messages. |\n| <a id=\"property-initiatives\"></a> `initiatives` | `readonly` | `InitiativeNamespace` | initiatives resources and operations. |\n| <a id=\"property-meetings\"></a> `meetings` | `readonly` | `MeetingNamespace` | meetings resources and operations. |\n| <a id=\"property-notifications\"></a> `notifications` | `readonly` | `NotificationNamespace` | - |\n| <a id=\"property-pins\"></a> `pins` | `readonly` | `PinsNamespace` | - |\n| <a id=\"property-projects\"></a> `projects` | `readonly` | `ProjectNamespace` | - |\n| <a id=\"property-properties\"></a> `properties` | `readonly` | `PropertiesNamespace` | - |\n| <a id=\"property-referrals\"></a> `referrals` | `readonly` | `ReferralNamespace` | Share the caller's referral link and email invites to join Macro. |\n| <a id=\"property-routines\"></a> `routines` | `readonly` | `RoutineNamespace` | routines resources and operations. |\n| <a id=\"property-tasks\"></a> `tasks` | `readonly` | `TaskNamespace` | - |\n| <a id=\"property-teams\"></a> `teams` | `readonly` | `TeamNamespace` | - |\n| <a id=\"property-unfurls\"></a> `unfurls` | `readonly` | `UnfurlNamespace` | unfurls resources and operations. |\n| <a id=\"property-users\"></a> `users` | `readonly` | `UserNamespace` | - |\n| <a id=\"property-webappurl\"></a> `webAppUrl` | `readonly` | `string` | Base URL of the Macro web app, used to build entity URLs. |\n| <a id=\"property-webhooks\"></a> `webhooks` | `readonly` | `WebhooksNamespace` | - |\n| <a id=\"property-whatsapp\"></a> `whatsapp` | `readonly` | `WhatsAppNamespace` | The current user's WhatsApp account and chat list; add chats from it. |",+ "Macro": "# Class: Macro\\<T\\>\n\n## Type Parameters\n\n| Type Parameter | Default type |\n| ------ | ------ |\n| <a id=\"type-parameter-t\"></a> `T` *extends* `MacroOpts` | `MacroOpts` |\n\n## Properties\n\n| Property | Modifier | Type | Description |\n| ------ | ------ | ------ | ------ |\n| <a id=\"property-_client\"></a> `_client` | `readonly` | `MacroClient` | Direct access to the underlying hey-api service clients. |\n| <a id=\"property-agents\"></a> `agents` | `readonly` | `AgentNamespace` | agents resources and operations. |\n| <a id=\"property-agentsessions\"></a> `agentSessions` | `readonly` | `AgentSessionNamespace` | - |\n| <a id=\"property-ai\"></a> `ai` | `readonly` | `AiNamespace` | - |\n| <a id=\"property-apikeys\"></a> `apiKeys` | `readonly` | `ApiKeyNamespace` | apiKeys resources and operations. |\n| <a id=\"property-bots\"></a> `bots` | `readonly` | `BotsNamespace` | - |\n| <a id=\"property-calendar\"></a> `calendar` | `readonly` | `CalendarNamespace` | - |\n| <a id=\"property-calls\"></a> `calls` | `readonly` | `CallRecordNamespace` | - |\n| <a id=\"property-channels\"></a> `channels` | `readonly` | `ChannelNamespace` | - |\n| <a id=\"property-crm\"></a> `crm` | `readonly` | `CrmNamespace` | - |\n| <a id=\"property-databases\"></a> `databases` | `readonly` | `DatabaseNamespace` | - |\n| <a id=\"property-documents\"></a> `documents` | `readonly` | `DocumentNamespace` | - |\n| <a id=\"property-email\"></a> `email` | `readonly` | `EmailNamespace` | - |\n| <a id=\"property-entitymentions\"></a> `entityMentions` | `readonly` | `EntityMentionNamespace` | entityMentions resources and operations. |\n| <a id=\"property-events\"></a> `events` | `readonly` | `MacroEvents` | - |\n| <a id=\"property-externalchats\"></a> `externalChats` | `readonly` | `ExternalChatsNamespace` | Chats from external providers (WhatsApp) added to Macro: read, share and send. |\n| <a id=\"property-favorites\"></a> `favorites` | `readonly` | `FavoritesNamespace` | - |\n| <a id=\"property-foreignentities\"></a> `foreignEntities` | `readonly` | `ForeignEntityNamespace` | - |\n| <a id=\"property-forms\"></a> `forms` | `readonly` | `FormNamespace` | Build forms and submit answers without granting respondents database access. |\n| <a id=\"property-githubpullrequests\"></a> `githubPullRequests` | `readonly` | `GithubPullRequestNamespace` | githubPullRequests resources and operations. |\n| <a id=\"property-harnesses\"></a> `harnesses` | `readonly` | `HarnessNamespace` | harnesses resources and operations. |\n| <a id=\"property-images\"></a> `images` | `readonly` | `ImagesNamespace` | Generate images with AI and attach them to messages. |\n| <a id=\"property-initiatives\"></a> `initiatives` | `readonly` | `InitiativeNamespace` | initiatives resources and operations. |\n| <a id=\"property-me\"></a> `me` | `readonly` | `MeNamespace` | Your own profile: set your name and profile picture. |\n| <a id=\"property-meetings\"></a> `meetings` | `readonly` | `MeetingNamespace` | meetings resources and operations. |\n| <a id=\"property-notifications\"></a> `notifications` | `readonly` | `NotificationNamespace` | - |\n| <a id=\"property-pins\"></a> `pins` | `readonly` | `PinsNamespace` | - |\n| <a id=\"property-projects\"></a> `projects` | `readonly` | `ProjectNamespace` | - |\n| <a id=\"property-properties\"></a> `properties` | `readonly` | `PropertiesNamespace` | - |\n| <a id=\"property-referrals\"></a> `referrals` | `readonly` | `ReferralNamespace` | Share the caller's referral link and email invites to join Macro. |\n| <a id=\"property-routines\"></a> `routines` | `readonly` | `RoutineNamespace` | routines resources and operations. |\n| <a id=\"property-tasks\"></a> `tasks` | `readonly` | `TaskNamespace` | - |\n| <a id=\"property-teams\"></a> `teams` | `readonly` | `TeamNamespace` | - |\n| <a id=\"property-unfurls\"></a> `unfurls` | `readonly` | `UnfurlNamespace` | unfurls resources and operations. |\n| <a id=\"property-users\"></a> `users` | `readonly` | `UserNamespace` | - |\n| <a id=\"property-webappurl\"></a> `webAppUrl` | `readonly` | `string` | Base URL of the Macro web app, used to build entity URLs. |\n| <a id=\"property-webhooks\"></a> `webhooks` | `readonly` | `WebhooksNamespace` | - |\n| <a id=\"property-whatsapp\"></a> `whatsapp` | `readonly` | `WhatsAppNamespace` | The current user's WhatsApp account and chat list; add chats from it. |","Macro.myPrincipalId": "### myPrincipalId()\n\n> **myPrincipalId**(): `Promise`\\<`string`\\>\n\nThe authenticated caller's mentionable principal — `bot|<uuid>` for bot\nauth, `macro|<email>` for user auth — fetched once and cached.\n\n#### Returns\n\n`Promise`\\<`string`\\>","Macro.requestedAs": "### requestedAs()\n\n> **requestedAs**(`user`): `Macro`\\<`T`\\>\n\nClone of this SDK acting on behalf of `user` (sent as\n`x-macro-bot-for-macro-user-id`). Bot auth only — throws for user auth,\nsince a user token always acts as its own user.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `user` | `User` |\n\n#### Returns\n\n`Macro`\\<`T`\\>","RequestActivity": "# Type Alias: RequestActivity\n\n> **RequestActivity** = \\{ `id`: `number`; `operation`: `string`; `service`: `string`; `status`: `\"started\"` \\| `\"completed\"` \\| `\"failed\"`; \\}\n\nA generated SDK operation lifecycle. Contains no arguments, URLs or response data.\n\n## Properties\n\n| Property | Type |\n| ------ | ------ |\n| <a id=\"property-id\"></a> `id` | `number` |\n| <a id=\"property-operation\"></a> `operation` | `string` |\n| <a id=\"property-service\"></a> `service` | `string` |\n| <a id=\"property-status\"></a> `status` | `\"started\"` \\| `\"completed\"` \\| `\"failed\"` |",diff --git a/crates/agent_code_mode/src/domain/operations.json b/crates/agent_code_mode/src/domain/operations.jsonindex eb6ca90579..57a24a9761 100644--- a/crates/agent_code_mode/src/domain/operations.json+++ b/crates/agent_code_mode/src/domain/operations.json@@ -139,6 +139,7 @@"auth.removeUserFromTeam": "Remove User From Team","auth.getUserTeams": "Get User Teams","auth.getUserInvites": "Get User Invites",+ "auth.agentSetup": "Agent Setup","auth.getUserNames": "Get User Names","auth.getUserNamesWithEmail": "Get User Names With Email","auth.patchUserGroup": "Patch User Group",@@ -153,6 +154,8 @@"auth.patchUserOnboarding": "Patch User Onboarding","auth.getUserOrganization": "Get User Organization","auth.putProfilePicture": "Put Profile Picture",+ "auth.createProfilePictureUpload": "Create Profile Picture Upload",+ "auth.putProfilePictureFile": "Put Profile Picture File","auth.postProfilePictures": "Post Profile Pictures","auth.getUserQuota": "Get User Quota","auth.createCheckoutSessionV2": "Create Checkout Session V2",diff --git a/crates/code_execution/src/outbound/deno/sdk.mjs b/crates/code_execution/src/outbound/deno/sdk.mjsindex 86e830f66e..2f4cc7dd3a 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*c($){let O;do{let j=await $(O),x=j.nextCursor??void 0;if(O!==void 0&&x!==void 0&&JSON.stringify(x)===JSON.stringify(O))throw Error("Pagination cursor did not advance");yield*j.items,O=x}while(O!==void 0)}var X$=Symbol.for("@ts-pattern/matcher"),n1=Symbol.for("@ts-pattern/isVariadic");var c0=($)=>Boolean($&&typeof $=="object"),Bj=($)=>$&&!!$[X$],s=($,O,j)=>{if(Bj($)){let x=$[X$](),{matched:S,selections:K}=x.match(O);return S&&K&&Object.keys(K).forEach((Z)=>j(Z,K[Z])),S}if(c0($)){if(!c0(O))return!1;if(Array.isArray($)){if(!Array.isArray(O))return!1;let x=[],S=[],K=[];for(let Z of $.keys()){let X=$[Z];Bj(X)&&X[n1]?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,G)=>s(L,Z[G],j))&&S.every((L,G)=>s(L,X[G],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)||Bj(K=S)&&K[X$]().matcherType==="optional")&&s(S,O[x],j);var K})}return Object.is(O,$)},Z$=($)=>{var O,j,x;return c0($)?Bj($)?(O=(j=(x=$[X$]()).getSelectionKeys)==null?void 0:j.call(x))!=null?O:[]:Array.isArray($)?dO($,Z$):dO(Object.values($),Z$):[]},dO=($,O)=>$.reduce((j,x)=>j.concat(O(x)),[]);function p7(...$){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 e($){return Object.assign($,{optional:()=>r0($),and:(O)=>l($,O),or:(O)=>s1($,O),select:(O)=>O===void 0?lO($):lO(O,$)})}function d0($){return Object.assign(((O)=>Object.assign(O,{[Symbol.iterator](){let j=0,x=[{value:Object.assign(O,{[n1]:!0}),done:!1},{done:!0,value:void 0}];return{next:()=>{var S;return(S=x[j++])!=null?S:x.at(-1)}}}}))($),{optional:()=>d0(r0($)),select:(O)=>d0(O===void 0?lO($):lO(O,$))})}function r0($){return e({[X$]:()=>({match:(O)=>{let j={},x=(S,K)=>{j[S]=K};return O===void 0?(Z$($).forEach((S)=>x(S,void 0)),{matched:!0,selections:j}):{matched:s($,O,x),selections:j}},getSelectionKeys:()=>Z$($),matcherType:"optional"})})}var a7=($,O)=>{for(let j of $)if(!O(j))return!1;return!0},i7=($,O)=>{for(let[j,x]of $.entries())if(!O(x,j))return!1;return!0},n7=($,O)=>{let j=Reflect.ownKeys($);for(let x of j)if(!O(x,$[x]))return!1;return!0};function l(...$){return e({[X$]:()=>({match:(O)=>{let j={},x=(S,K)=>{j[S]=K};return{matched:$.every((S)=>s(S,O,x)),selections:j}},getSelectionKeys:()=>dO($,Z$),matcherType:"and"})})}function s1(...$){return e({[X$]:()=>({match:(O)=>{let j={},x=(S,K)=>{j[S]=K};return dO($,Z$).forEach((S)=>x(S,void 0)),{matched:$.some((S)=>s(S,O,x)),selections:j}},getSelectionKeys:()=>dO($,Z$),matcherType:"or"})})}function u($){return{[X$]:()=>({match:(O)=>({matched:Boolean($(O))})})}}function lO(...$){let O=typeof $[0]=="string"?$[0]:void 0,j=$.length===2?$[1]:typeof $[0]=="string"?void 0:$[0];return e({[X$]:()=>({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?[]:Z$(j))})})}function t1($){return!0}function w$($){return typeof $=="number"}function i$($){return typeof $=="string"}function n$($){return typeof $=="bigint"}var e1=e(u(t1)),s7=e(u(t1)),t7=e1,s$=($)=>Object.assign(e($),{startsWith:(O)=>{return s$(l($,(j=O,u((x)=>i$(x)&&x.startsWith(j)))));var j},endsWith:(O)=>{return s$(l($,(j=O,u((x)=>i$(x)&&x.endsWith(j)))));var j},minLength:(O)=>s$(l($,((j)=>u((x)=>i$(x)&&x.length>=j))(O))),length:(O)=>s$(l($,((j)=>u((x)=>i$(x)&&x.length===j))(O))),maxLength:(O)=>s$(l($,((j)=>u((x)=>i$(x)&&x.length<=j))(O))),includes:(O)=>{return s$(l($,(j=O,u((x)=>i$(x)&&x.includes(j)))));var j},regex:(O)=>{return s$(l($,(j=O,u((x)=>i$(x)&&Boolean(x.match(j))))));var j}}),i1=s$(u(i$)),f$=($)=>Object.assign(e($),{between:(O,j)=>f$(l($,((x,S)=>u((K)=>w$(K)&&x<=K&&S>=K))(O,j))),lt:(O)=>f$(l($,((j)=>u((x)=>w$(x)&&x<j))(O))),gt:(O)=>f$(l($,((j)=>u((x)=>w$(x)&&x>j))(O))),lte:(O)=>f$(l($,((j)=>u((x)=>w$(x)&&x<=j))(O))),gte:(O)=>f$(l($,((j)=>u((x)=>w$(x)&&x>=j))(O))),int:()=>f$(l($,u((O)=>w$(O)&&Number.isInteger(O)))),finite:()=>f$(l($,u((O)=>w$(O)&&Number.isFinite(O)))),positive:()=>f$(l($,u((O)=>w$(O)&&O>0))),negative:()=>f$(l($,u((O)=>w$(O)&&O<0)))}),e7=f$(u(w$)),t$=($)=>Object.assign(e($),{between:(O,j)=>t$(l($,((x,S)=>u((K)=>n$(K)&&x<=K&&S>=K))(O,j))),lt:(O)=>t$(l($,((j)=>u((x)=>n$(x)&&x<j))(O))),gt:(O)=>t$(l($,((j)=>u((x)=>n$(x)&&x>j))(O))),lte:(O)=>t$(l($,((j)=>u((x)=>n$(x)&&x<=j))(O))),gte:(O)=>t$(l($,((j)=>u((x)=>n$(x)&&x>=j))(O))),positive:()=>t$(l($,u((O)=>n$(O)&&O>0))),negative:()=>t$(l($,u((O)=>n$(O)&&O<0)))}),o7=t$(u(n$)),$5=e(u(function($){return typeof $=="boolean"})),O5=e(u(function($){return typeof $=="symbol"})),j5=e(u(function($){return $==null})),x5=e(u(function($){return $!=null})),t={__proto__:null,matcher:X$,optional:r0,array:function(...$){return d0({[X$]:()=>({match:(O)=>{if(!Array.isArray(O))return{matched:!1};if($.length===0)return{matched:!0};let j=$[0],x={};if(O.length===0)return Z$(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?[]:Z$($[0])})})},set:function(...$){return e({[X$]:()=>({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:a7(O,(K)=>s(S,K,x)),selections:j}},getSelectionKeys:()=>$.length===0?[]:Z$($[0])})})},map:function(...$){return e({[X$]:()=>({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:i7(O,(X,Y)=>{let L=s(K,Y,x),G=s(Z,X,x);return L&&G}),selections:j}},getSelectionKeys:()=>$.length===0?[]:[...Z$($[0]),...Z$($[1])]})})},record:function(...$){return e({[X$]:()=>({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?[i1,$[0]]:$;return{matched:n7(O,(X,Y)=>{let L=typeof X!="string"||Number.isNaN(Number(X))?null:Number(X),G=L!==null&&s(K,L,S),J=s(K,X,S),I=s(Z,Y,S);return(J||G)&&I}),selections:x}},getSelectionKeys:()=>$.length===0?[]:[...Z$($[0]),...Z$($[1])]})})},intersection:l,union:s1,not:function($){return e({[X$]:()=>({match:(O)=>({matched:!s($,O,()=>{})}),getSelectionKeys:()=>[],matcherType:"not"})})},when:u,select:lO,any:e1,unknown:s7,_:t7,string:i1,number:e7,bigint:o7,boolean:$5,symbol:O5,nullish:j5,nonNullable:x5,instanceOf:function($){return e(u(function(O){return(j)=>j instanceof O}($)))},shape:function($){return e(u(p7($)))}};class o1 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 l0={matched:!1,value:void 0};function k($){return new Lj($,l0)}class Lj{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))?l0:{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 Lj(this.input,X)}when($,O){if(this.state.matched)return this;let j=Boolean($(this.input));return new Lj(this.input,j?{matched:!0,value:O(this.input,this.input)}:l0)}otherwise($){return this.state.matched?this.state.value:$(this.input)}exhaustive($=S5){return this.state.matched?this.state.value:$(this.input)}run(){return this.exhaustive()}returnType(){return this}narrow(){return this}}function S5($){throw new o1($)}class f extends Error{constructor($){super($);this.name="MacroError"}}var $2=500;function Z5($){let O=k($).with(t.string,(j)=>j).with({message:t.string},({message:j})=>j).with({error:t.string},({error:j})=>j).otherwise(()=>"").trim();return O.length>$2?`${O.slice(0,$2)}…`:O}class e$ extends f{status;data;constructor($,O){let j=Z5(O);super(j?`Macro API error ${$}: ${j}`:`Macro API error ${$}`);this.status=$;this.data=O;this.name="MacroApiError"}}class p0 extends e${constructor($){super(403,$);this.name="MacroForbiddenError"}}function X5($,O){return $===403?new p0(O):new e$($,O)}class E extends f{constructor($){super($);this.name="MacroNotFoundError"}}function Q($){if($.error!==void 0)throw X5($.response?.status??0,$.error);return $.data}class A{client;id;detail;constructor($,O,j){this.client=$;this.id=O;this.detail=new W$(()=>this.fetch(),j)}field($){return async()=>(await this.detail.get())[$]??void 0}mappedField($,O){return async()=>O((await this.detail.get())[$]??void 0)}toJSON(){let $=this.detail.peek();return $===void 0?{id:this.id}:{id:this.id,detail:$}}async mutate($){let O=Q(await $(this.client));return this.detail.clear(),O}}class H$ extends A{async permission(){return Q(await this.client.storage.getEntityPermission({path:{entity_type:this.entityType,entity_id:this.id}}))}async favorite(){return Q(await this.client.storage.addFavorite({body:{entityId:this.id,entityType:this.entityType}})),this}async unfavorite(){return Q(await this.client.storage.removeFavoriteByEntity({path:{entity_type:this.entityType,entity_id:this.id}})),this}}class K$ extends H${propertyReference(){return{entity_type:this.propertyEntityType,entity_id:this.id}}async properties($){let{properties:O}=Q(await this.client.properties.getEntityProperties({path:{entity_type:this.propertyEntityType,entity_id:this.id},query:$?.includeMetadata!==void 0?{include_metadata:$.includeMetadata}:void 0}));return O}async setProperty($,O){Q(await this.client.properties.setEntityProperty({path:{...this.propertyReference(),property_id:$.id},body:{value:O??null}}))}async updatePropertyOptions($){return Q(await this.client.properties.bulkUpdateEntityPropertyOptions({path:this.propertyReference(),body:{properties:$.map((O)=>({property_id:O.property.id,...O.add?{add_option_ids:O.add.map((j)=>j.id)}:{},...O.remove?{remove_option_ids:O.remove.map((j)=>j.id)}:{}}))}}))}async deleteProperty($){Q(await this.client.properties.deleteEntityProperty({path:{entity_property_id:$.property.id}}))}}var K5={"<":"\\u003c",">":"\\u003e","&":"\\u0026"};function o$($,O){let j=JSON.stringify(O).replace(/[<>&]/g,(x)=>K5[x]??x);return`<${$}>${j}</${$}>`}function Y5($){return typeof $==="object"&&$!==null&&typeof $.toMention==="function"}var Q5={toMention:()=>({tag:o$("m-group-mention",{groupAlias:"here"}),mention:{entity_type:"group",entity_id:"here"}})};function G5($,...O){let j="",x=[];for(let[S,K]of $.entries()){j+=K;let Z=O[S];if(Z===void 0)continue;if(Y5(Z)){let X=Z.toMention();j+=X.tag,x.push(X.mention)}else j+=String(Z)}return{content:j,mentions:J5(x)}}function J5($){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 A{static byId($,O){return new B$($,O)}static from($,O){return new B$($,O.id,O)}async fetch(){let $=Q(await this.client.storage.listHarnesses()).find((O)=>O.id===this.id);if(!$)throw new E(`Harness ${this.id} is unavailable`);return $}name=this.field("name");connected=this.field("connected");kind=this.field("kind");async delete(){await this.mutate(($)=>$.storage.deleteHarness({path:{harness_id:this.id}}))}}class T$ extends A{static byId($,O){return new T$($,O)}static from($,O){return new T$($,O.bot.id,O)}async fetch(){let $=Q(await this.client.storage.listAgents()).find((O)=>O.bot.id===this.id);if(!$)throw new E(`Agent ${this.id} is unavailable`);return $}name=this.mappedField("bot",($)=>$.name);instructions=this.field("instructions");defaultModel=this.field("default_model");channels=this.mappedField("channel_ids",($)=>$.map((O)=>b.byId(this.client,O)));host=this.mappedField("harness_id",($)=>$?B$.byId(this.client,$):void 0);async update($){await this.mutate((O)=>O.storage.updateAgent({path:{agent_id:this.id},body:a0($)}))}}function a0($){let{channels:O,team:j,host:x,autoAcceptPermissions:S,avatarUrl:K,channelScope:Z,defaultModel:X,isCoding:Y,...L}=$;return{...L,channel_ids:O?.map((G)=>G.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 Nj($,O,j,x=[]){let{channelId:S,thread:K}=W5(O);if(await B5($)){let{id:X}=Q(await $.storage.entityMessageCreate({path:{parent_type:"channel",parent_id:S},body:{content:j.content,mentions:j.mentions,attachments:x.map((Y)=>({entity_type:V5,entity_id:Y.id,width:Y.width??null,height:Y.height??null})),thread_id:K?.rootId??null,nonce:crypto.randomUUID()}}));return X}if(x.length>0)throw new f("a user-owned bot can only post via the channel webhook endpoint, which "+"does not support images — use a team-owned bot, or requestedAs(user), "+"to attach images");if(K)throw new f("a user-owned bot can only post via the channel webhook endpoint, which "+"does not support threads — use a team-owned bot, or requestedAs(user), "+"to reply in a thread");let{message_id:Z}=Q(await $.storage.postChannelBotWebhook({path:{channel_id:S},body:{content:j.content},headers:{"x-macro-bot-scope":"user"}}));return Z}var V5="static/image";function W5($){return"rootId"in $?{channelId:$.channelId,thread:$}:{channelId:$.id}}async function B5($){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 o.byId(this.client,this.channelId,this.rootId)}async replies(){let{replies:$}=Q(await this.client.storage.entityMessageGetThread({path:{parent_type:"channel",parent_id:this.channelId,id:this.rootId}}));return $.map((O)=>o.from(this.client,this.channelId,O))}async reply($,O){let j=await Nj(this.client,this,O$($),O?.images);return o.byId(this.client,this.channelId,j)}}class o extends H${channelId;mentions;entityType="channel_message";constructor($,O,j,x=[],S){super($,j,S);this.channelId=O;this.mentions=x}get path(){return{parent_type:"channel",parent_id:this.channelId,id:this.id}}async fetch(){return Q(await this.client.storage.entityMessageGetMessage({path:this.path}))}static byId($,O,j,x=[]){return new o($,O,j,x)}static from($,O,j){return new o($,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 C.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 Uj{client;channel;record;constructor($,O,j){this.client=$;this.channel=O;this.record=j}agent(){return T$.byId(this.client,this.record.botId)}sessions(){return this.record.sessions.map(($)=>({session:d.byId(this.client,$.sessionId),isCurrent:$.isCurrent,createdAt:$.createdAt}))}turns(){return this.record.turns.map(($)=>new i0(this.client,this,$))}async startFresh($){Q(await this.client.agentHarness.startFreshAgentConversation({path:{channel_id:this.channel.id,bot_id:this.record.botId},body:{sessionId:$.id}}))}toJSON(){return{channelId:this.channel.id,agentId:this.record.botId}}}class i0{client;conversation;record;constructor($,O,j){this.client=$;this.conversation=O;this.record=j}source(){return o.byId(this.client,this.conversation.channel.id,this.record.sourceMessageId)}session(){return d.byId(this.client,this.record.sessionId)}async retry($){Q(await this.client.agentHarness.retryAgentConversationTurn({path:{channel_id:this.conversation.channel.id,bot_id:this.conversation.agent().id,source:this.record.sourceMessageId},body:{actionId:$}}))}toJSON(){return{channelId:this.conversation.channel.id,sourceMessageId:this.record.sourceMessageId}}}class L$ extends A{parent;toJSON(){return{...super.toJSON(),parentType:this.parent.type,parentId:this.parent.entity.id}}constructor($,O,j){super($,j);this.parent=O}static byId($,O,j){return new L$($,O,j)}get path(){return{parent_type:this.parent.type,parent_id:this.parent.entity.id,id:this.id}}async fetch(){return Q(await this.client.storage.entityMessageGetThread({path:this.path})).state}resolved=this.field("resolved");async update($){let O={resolved:$.resolved,detach_anchor:$.detachAnchor,nonce:$.nonce};await this.mutate((j)=>j.storage.entityMessagePatchThread({path:this.path,body:O}))}async delete($){await this.mutate((O)=>O.storage.entityMessageDeleteThread({path:this.path,query:{nonce:$}}))}}async function b$($,O,j,x){for(let K of[...x?.messages??[],...x?.around?[x.around]:[]]){let Z="channelId"in K?{type:"channel",id:K.channelId}:("documentId"in K)?{type:"document",id:K.documentId}:("callId"in K)?{type:"call",id:K.callId}:K.parent;if(Z.type!==O.type||Z.id!==O.entity.id)throw Error("Timeline message belongs to another resource")}let S=Q(await $.storage.messageTimelineEntries({path:{parent_type:O.type,parent_id:O.entity.id},query:{selection:x?JSON.stringify({cursor:x.cursor,around:x.around?.id,ids:x.messages?.map((K)=>K.id),activity_after:x.activityAfter,activity_before:x.activityBefore,anchored:x.anchored,direction:x.direction,include_deleted_threads:x.includeDeletedThreads,limit:x.limit}):void 0}}));return{entries:S.entries.map((K)=>{if(K.type==="activity")return{type:"activity",activity:{...K.activity,actor:C.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 L5=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??L5;return c(async(G)=>{let{results:J,next_cursor:I}=Q(await K.search.unifiedSearch({body:{query:Z,match_type:"partial",search_on:Y,...O?{filters:O}:{},...S?{include_crm:!0}:{}},query:{page_size:L,...G?{cursor:G}:{}}}));return{items:J.filter((W)=>W.type===j).map((W)=>x(K,W)),nextCursor:I}})}}class GO{client;channel;record;constructor($,O,j){this.client=$;this.channel=O;this.record=j}get id(){return this.record.id}user(){return C.byId(this.client,this.record.user_id)}createdAt(){return this.record.created_at}async recordInteraction($){return new GO(this.client,this.channel,Q(await this.client.storage.postActivity({body:{activity_type:$,channel_id:this.channel.id}})))}toJSON(){return this.record}}class b extends K${async recordActivity($){return new GO(this.client,this,Q(await this.client.storage.postActivity({body:{activity_type:$,channel_id:this.id}})))}async setPicture($){await this.mutate((O)=>O.storage.setChannelPicture({path:{channel_id:this.id},body:{profile_picture_id:$?.id??null}}))}messageThreadById($){return L$.byId(this.client,{type:"channel",entity:this},$)}timelinePage($){return b$(this.client,{type:"channel",entity:this},(O)=>o.from(this.client,this.id,O),$)}async agentConversations(){return Q(await this.client.agentHarness.listAgentConversations({path:{channel_id:this.id}})).conversations.map(($)=>new Uj(this.client,this,$))}entityType="channel";propertyEntityType="CHANNEL";async fetch(){return Q(await this.client.storage.getChannel({path:{channel_id:this.id}}))}static byId($,O){return new b($,O)}static async dm($,O){let{channel_id:j}=Q(await $.storage.getOrCreateDm({body:{recipient_id:O.id}}));return new b($,j)}static async private($,O){let{channel_id:j}=Q(await $.storage.getOrCreatePrivate({body:{recipients:O.map((x)=>x.id)}}));return new b($,j)}static async create($,O){let{id:j}=Q(await $.storage.createChannel({body:{channel_type:O.type,name:O.name??null,participants:(O.participants??[]).map((x)=>x.id),team_id:O.team?.id??null}}));return new b($,j)}name=this.field("channel_name");type=this.field("channel_type");async send($,O){let j=await Nj(this.client,O?.thread??this,O$($),O?.images);return o.byId(this.client,this.id,j)}messages($){return this.timeline({limit:$?.pageSize})}messagesAfter($,O){return this.timeline({activity_after:$ instanceof Date?$.toISOString():$,limit:O?.pageSize})}timeline($){return c(async(O)=>{let j=Q(await this.client.storage.messageTimeline({path:{parent_type:"channel",parent_id:this.id},query:{selection:JSON.stringify({...$,cursor:O})}}));return{items:j.items.map((x)=>o.from(this.client,this.id,x)),nextCursor:j.next_cursor}})}message($){return o.byId(this.client,this.id,$)}async rename($){await this.mutate((O)=>O.storage.patchChannel({path:{channel_id:this.id},body:{channel_name:$}}))}async delete(){await this.mutate(($)=>$.storage.deleteChannel({path:{channel_id:this.id}}))}async join(){await this.mutate(($)=>$.storage.joinChannel({path:{channel_id:this.id}}))}async joinCode(){let{join_code:$}=Q(await this.client.storage.getChannelJoinLink({path:{channel_id:this.id}}));return $}async leave(){await this.mutate(($)=>$.storage.leaveChannel({path:{channel_id:this.id}}))}async participants(){return Q(await this.client.storage.getChannelParticipants({path:{channel_id:this.id}}))}async addParticipants($){await this.mutate((O)=>O.storage.addParticipants({path:{channel_id:this.id},body:{participants:$.map((j)=>j.id)}}))}async removeParticipants($){await this.mutate((O)=>O.storage.removeParticipants({path:{channel_id:this.id},body:{participants:$.map((j)=>j.id)}}))}async typing($,O){Q(await this.client.storage.entityMessageTyping({path:{parent_type:"channel",parent_id:this.id},body:{active:$==="start",thread_id:O?.thread?.rootId??null}}))}attachments($){return c(async(O)=>{let j=Q(await this.client.storage.getChannelAttachments({path:{channel_id:this.id},query:{...$?.pageSize?{limit:$.pageSize}:{},...$?.type?{attachment_type:$.type}:{},...O?{cursor:O}:{}}}));return{items:j.items,nextCursor:j.next_cursor}})}webUrl(){return`${this.client.webAppUrl}/app/channel/${this.id}`}static search=x$({type:"channel",make:($,O)=>new b($,O.channel_id)})}class C extends K${entityType="user";propertyEntityType="USER";async fetch(){let{names:$}=Q(await this.client.auth.getUserNamesWithEmail({body:{user_ids:[this.id]}})),O=$.find((j)=>j.id===this.id);if(!O)throw new E(`user ${this.id} not found`);return O}static byId($,O){return new C($,O)}static fromName($,O){return new C($,O.id,O)}static async me($){let{user_id:O}=Q(await $.auth.getUserInfo());return new C($,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:o$("m-user-mention",{userId:this.id}),mention:{entity_type:"user",entity_id:this.id}}}}class $${client;entityType;entity;constructor($,O,j){this.client=$;this.entityType=O;this.entity=j}get path(){return{entity_type:this.entityType,entity_id:this.entity.id}}async state($){let O=Q(await this.client.storage.accessRequestsState({path:this.path,query:{offset:$}}));return{accessLevel:O.accessLevel??void 0,canReview:O.canReview,owner:O.owner?C.byId(this.client,O.owner):void 0,pendingCount:O.pendingCount,supportedLevels:O.supportedLevels,nextOffset:O.nextOffset??void 0,mine:O.mine?IO.from(this.client,this,O.mine):void 0,requests:O.requests.map((j)=>IO.from(this.client,this,j))}}async request($){let{mine:O}=await this.state();return this.submit($,O?await O.revision():void 0)}async submit($,O){return IO.from(this.client,this,Q(await this.client.storage.accessRequestsSubmit({path:this.path,body:{requestedLevel:$,revision:O}})))}async cancel($){Q(await this.client.storage.accessRequestsCancel({path:this.path,query:{revision:$}}))}async direct(){return Q(await this.client.storage.accessRequestsDirect({path:this.path})).map(($)=>({user:C.byId(this.client,$.userId),accessLevel:$.accessLevel}))}async grant($,O){Q(await this.client.storage.accessRequestsSetDirect({path:{...this.path,user_id:$.id},body:{accessLevel:O}}))}async remove($){Q(await this.client.storage.accessRequestsRemoveDirect({path:{...this.path,user_id:$.id}}))}async resolve($,O){let j=$.access.toJSON();if(j.entity_type!==this.entityType||j.entity_id!==this.entity.id)throw Error("Access request belongs to another entity");return Q(await this.client.storage.accessRequestsResolve({path:{...this.path,request_id:$.id},body:O}))}toJSON(){return this.path}}class IO extends A{access;resolvedRecord;constructor($,O,j){super($,j.id,j);this.access=O}static from($,O,j){return new IO($,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",($)=>C.byId(this.client,$));async resolve($){this.resolvedRecord=await this.access.resolve(this,{revision:await this.revision(),grantedLevel:$}),this.detail.clear()}}function $O($){return{...$,channelSharePermissions:$.channelSharePermissions===void 0||$.channelSharePermissions===null?$.channelSharePermissions:$.channelSharePermissions.map((O)=>({channelId:O.channel.id,accessLevel:O.accessLevel,operation:O.operation}))}}function n0($){return $}class N$ extends A{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=Q(await $.agentHarness.createSessionReview({path:{session_id:O.id},body:{...j,executionId:x?.id??null}}));return N$.fromRecord($,O,n0(S))}static async list($,O){return Q(await $.agentHarness.listExecutionReviews({path:{session_id:O.session().id,execution_id:O.id}})).map((x)=>N$.fromRecord($,O.session(),n0(x)))}async fetch(){return n0(Q(await this.client.agentHarness.getSessionReview({path:{session_id:this.parent.id,review_id:this.id}})))}title=this.field("title");kind=this.field("kind");session(){return this.parent}async reference(){return{kind:await this.kind(),id:this.id}}async items(){return(await this.detail.get()).items.map((j)=>new s0(j,{edit:(x)=>this.decide({action:"edit",item:j.id,draft:x}),submit:()=>this.decide({action:"submit",items:[j.id]}),dismiss:()=>this.decide({action:"dismiss",items:[j.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 s0{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()}}async function zj($,O,j,x){Q(await $.agentHarness.presentSessionView({path:{session_id:O.id},body:{view:j,executionId:x?.id??null}}))}class rO extends A{parent;constructor($,O,j){super($,O);this.parent=j}static byId($,O,j){return new rO($,j,O)}async fetch(){return Q(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)};views={present:($)=>zj(this.client,this.parent,$,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 Ij{client;sessionId;dto;constructor($,O,j){this.client=$;this.sessionId=O;this.dto=j}static from($,O,j){return new Ij($,O,j)}get actionId(){return this.dto.actionId}get kind(){return this.dto.kind}get prompt(){return this.dto.prompt??void 0}get attachments(){return this.dto.attachments??[]}get actorUserId(){return this.dto.actorUserId??void 0}get createdAt(){return this.dto.createdAt}async edit($){return Q(await this.client.agentHarness.editQueuedAction({path:{session_id:this.sessionId,action_id:this.actionId},body:{prompt:$}})),this.dto={...this.dto,prompt:$},this}async steer(){Q(await this.client.agentHarness.steerQueuedAction({path:{session_id:this.sessionId,action_id:this.actionId}}))}async remove(){Q(await this.client.agentHarness.removeQueuedAction({path:{session_id:this.sessionId,action_id:this.actionId}}))}}class pO{client;session;id;constructor($,O,j){this.client=$;this.session=O;this.id=j}static byId($,O,j){return new pO($,O,j)}async answer($){return Q(await this.client.agentHarness.answerAgentSessionToolApproval({path:{session_id:this.session.id,approval_id:this.id},body:{answer:$}}))}toJSON(){return{id:this.id,sessionId:this.session.id}}}class d extends A{access=new $$(this.client,"agent_session",this);toolApprovalById($){return pO.byId(this.client,this,$)}async sharePermissions(){return Q(await this.client.agentHarness.getAgentSessionPermissions({path:{session_id:this.id}}))}async updateSharePermissions($){return this.mutate((O)=>O.agentHarness.updateAgentSessionPermissions({path:{session_id:this.id},body:$O($)}))}static byId($,O){return new d($,O)}static async createManaged($,O){let{session:j}=Q(await $.agentHarness.createAgentSession({body:{botId:O?.agent?.id,prompt:O?.prompt,instructions:O?.instructions,model:O?.model,repoUrl:O?.repoUrl,repoBranch:O?.repoBranch}}));return new d($,j.id,j)}static async repositories($){let{repositories:O}=Q(await $.agentHarness.listAgentRepositories());return O.map((j)=>({url:j.url,defaultBranch:j.defaultBranch??void 0}))}static async repositoryBranches($,O){let{branches:j}=Q(await $.agentHarness.listAgentRepositoryBranches({query:{repoUrl:O}}));return j}static async chooseMode($,O){let{mode:j}=Q(await $.agentHarness.chooseAgentMode({body:{prompt:O}}));return j}async fetch(){return Q(await this.client.agentHarness.getAgentSession({path:{session_id:this.id}}))}name=this.field("name");archivedBy=this.field("archivedBy");archivedAt=this.field("archivedAt");model=this.field("model");harness=this.field("harness");repoUrl=this.field("repoUrl");workspace=this.field("workspace");instructions=this.field("instructions");status=this.field("status");sandboxSize=this.field("sandboxSize");createdAt=this.field("createdAt");modifiedAt=this.field("modifiedAt");static async forPullRequest($,O){let{sessionIds:j}=Q(await $.agentHarness.agentSessionsForPullRequest({body:{url:O}}));return j.map((x)=>d.byId($,x))}async pullRequests(){let{pullRequests:$}=Q(await this.client.agentHarness.listAgentSessionPullRequests({path:{session_id:this.id}}));return $.map((O)=>({githubKey:O.githubKey,url:O.url,source:O.source,linkedBy:O.linkedBy?C.byId(this.client,O.linkedBy):void 0,createdAt:O.createdAt}))}async linkPullRequest($){Q(await this.client.agentHarness.linkAgentSessionPullRequest({path:{session_id:this.id},body:{url:$}}))}async unlinkPullRequest($){Q(await this.client.agentHarness.unlinkAgentSessionPullRequest({path:{session_id:this.id},query:{url:$}}))}async autoArchive(){let{overrides:$,defaults:O,autoArchivedAt:j}=Q(await this.client.agentHarness.getAgentSessionAutoArchive({path:{session_id:this.id}}));return{overrides:{onPullRequestMerged:$.onPullRequestMerged??void 0,onRuntimeClosed:$.onRuntimeClosed??void 0},defaults:O,autoArchivedAt:j??void 0}}async setAutoArchive($){Q(await this.client.agentHarness.putAgentSessionAutoArchive({path:{session_id:this.id},body:{onPullRequestMerged:$.onPullRequestMerged??null,onRuntimeClosed:$.onRuntimeClosed??null}}))}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:{archived:$}}))}async setSandboxSize($){let{size:O}=await this.mutate((j)=>j.agentHarness.putAgentSessionSandboxSize({path:{session_id:this.id},body:{size:$}}));return O}static async defaultSandboxSize($){return Q(await $.agentHarness.getAgentSandboxSize()).size}static async setDefaultSandboxSize($,O){return Q(await $.agentHarness.putAgentSandboxSize({body:{size:O}})).size}static async codingPreferences($){return Q(await $.agentHarness.getAgentCodingPreferences())}static async autoArchivePreferences($){return Q(await $.agentHarness.getAgentAutoArchivePreferences())}static async setAutoArchivePreferences($,O){return Q(await $.agentHarness.putAgentAutoArchivePreferences({body:O}))}static async setCodingPreferences($,O){return Q(await $.agentHarness.putAgentCodingPreferences({body:O}))}async control($){return this.mutate((O)=>O.agentHarness.controlAgentSession({path:{session_id:this.id},body:$}))}prompt($,O){return this.control({type:"prompt",prompt:$,...O&&O.length>0?{attachments:O}:{}})}async queue(){let{entries:$}=Q(await this.client.agentHarness.getAgentSessionQueue({path:{session_id:this.id}}));return $.map((O)=>Ij.from(this.client,this.id,O))}async changes(){return Q(await this.client.agentHarness.getAgentSessionChanges({path:{session_id:this.id}}))}async changesPatch(){return Q(await this.client.agentHarness.getAgentSessionChangesPatch({path:{session_id:this.id}})).patch}async refreshChanges(){return this.mutate(($)=>$.agentHarness.refreshAgentSessionChanges({path:{session_id:this.id}}))}async foldedLog(){let{bot:$,messages:O}=Q(await this.client.agentHarness.getAgentSessionFoldedLog({path:{session_id:this.id}}));return{bot:$,messages:O}}async log(){return Q(await this.client.agentHarness.getAgentSessionLog({path:{session_id:this.id}}))}reviews={create:($)=>N$.createForSession(this.client,this,$),byId:($)=>N$.byId(this.client,this,$)};views={present:($)=>zj(this.client,this,$)};codeExecutions={byId:($)=>rO.byId(this.client,this,$)};async delete(){await this.mutate(($)=>$.agentHarness.deleteAgentSession({path:{session_id:this.id}}))}}class t0{client;constructor($){this.client=$}byId($){return d.byId(this.client,$)}createManaged($){return d.createManaged(this.client,$)}chooseMode($){return d.chooseMode(this.client,$)}repositories(){return d.repositories(this.client)}repositoryBranches($){return d.repositoryBranches(this.client,$)}forPullRequest($){return d.forPullRequest(this.client,$)}defaultSandboxSize(){return d.defaultSandboxSize(this.client)}setDefaultSandboxSize($){return d.setDefaultSandboxSize(this.client,$)}codingPreferences(){return d.codingPreferences(this.client)}autoArchivePreferences(){return d.autoArchivePreferences(this.client)}setAutoArchivePreferences($){return d.setAutoArchivePreferences(this.client,$)}setCodingPreferences($){return d.setCodingPreferences(this.client,$)}}class e0{client;constructor($){this.client=$}byId($){return T$.byId(this.client,$)}async list(){return Q(await this.client.storage.listAgents()).map(($)=>T$.from(this.client,$))}async create($){return T$.from(this.client,Q(await this.client.storage.createAgent({body:a0($)})))}}class o0{client;async usage($={}){let{users:O,...j}=$;return Q(await this.client.cognition.getUsageHandler({body:{...j,include_users:O?.map((x)=>x.id)}}))}constructor($){this.client=$}async structuredCompletion($){return Q(await this.client.cognition.structuredCompletion({body:$}))}async decide($){return Q(await this.client.cognition.decisions({body:$}))}}class OO extends A{static byId($,O){return new OO($,O)}static from($,O){return new OO($,O.id,{id:O.id,name:O.name,createdAt:O.createdAt})}async fetch(){let $=Q(await this.client.storage.listUserApiKeys()).keys.find((O)=>O.id===this.id);if(!$)throw new E(`API key ${this.id} is unavailable`);return $}name=this.field("name");createdAt=this.field("createdAt");async delete(){await this.mutate(($)=>$.storage.deleteUserApiKey({path:{id:this.id}}))}}class $x{client;constructor($){this.client=$}byId($){return OO.byId(this.client,$)}async list(){return Q(await this.client.storage.listUserApiKeys()).keys.map(($)=>OO.from(this.client,$))}async create($){let O=Q(await this.client.storage.createUserApiKey({body:{name:$}}));return{key:OO.from(this.client,O),secret:O.key}}async tokenForEmail($){return Q(await this.client.auth.macroApiToken({query:{email:$}}))}}class aO{client;constructor($){this.client=$}async me(){if(this.client.authConfig.type!=="bot")throw new f("bots.me() requires bot auth — a user API key has no bot identity");return Q(await this.client.storage.getSelfBot())}async channels(){if(this.client.authConfig.type!=="bot")throw new f("bots.channels() requires bot auth — a user API key has no bot identity");let $=await this.me();return Q(await this.client.storage.listBotChannels({path:{bot_id:$.id}}))}async myPrincipalId(){if(this.client.authConfig.type!=="bot")throw new f("bots.myPrincipalId() requires bot auth — a user API key has no bot identity");return this.client.myPrincipalId()}}class R$ extends A{async fetch(){let{links:$}=Q(await this.client.email.listLinks()),O=$.find((j)=>j.id===this.id);if(!O)throw new E(`email link ${this.id} not found`);return O}static byId($,O){return new R$($,O)}static async list($){let{links:O}=Q(await $.email.listLinks());return O.map((j)=>new R$($,j.id,j))}emailAddress=this.field("email_address");provider=this.field("provider");isPrimary=this.field("is_primary");isSyncActive=this.field("is_sync_active");syncStatus=this.field("sync_status");needsReauth=this.field("needs_reauth");photoUrl=this.field("photo_url");async settingsOperations(){return Q(await this.client.email.mailboxSettingsOperations({headers:{"X-Email-Link-Id":this.id}}))}}class m$ extends A{async setContributesToAvailability($){await this.mutate((O)=>O.calendar.setAvailabilityCalendar({path:{calendar_id:this.id},body:{contributesToAvailability:$}}))}async fetch(){let{calendars:$}=Q(await this.client.calendar.listCalendars()),O=$.find((j)=>j.id===this.id);if(!O)throw new E(`calendar ${this.id} not found`);return O}static byId($,O){return new m$($,O)}static async list($){let{calendars:O}=Q(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");contributesToAvailability=this.field("contributesToAvailability");isSubscription=this.field("isSubscription");color=this.field("color");syncError=this.field("syncError");emailLink=this.mappedField("emailLinkId",($)=>R$.byId(this.client,$))}class iO{client;id;constructor($,O){this.client=$;this.id=O}async status(){return Q(await this.client.calendar.calendarReplacementStatus({path:{operation_id:this.id}}))}async confirm(){return Q(await this.client.calendar.confirmCalendarReplacement({path:{operation_id:this.id}}))}async discard(){Q(await this.client.calendar.discardCalendarReplacement({path:{operation_id:this.id}}))}}class S$ extends A{async fetch(){throw new f(`calendar event ${this.id} has no fetch-by-id endpoint; read the record returned by calendar.createEvent / event.update / event.rsvp instead`)}static byId($,O){return new S$($,O)}static fromRecord($,O){return new S$($,O.id,O)}title=this.field("title");description=this.field("description");location=this.field("location");time=this.field("time");status=this.field("status");attendees=this.field("attendees");transparency=this.field("transparency");isReadOnly=this.field("isReadOnly");recurrenceLines=this.field("recurrenceLines");guestPolicy=this.field("guestPolicy");viewerCan=this.field("viewerCan");calendar=this.mappedField("calendarId",($)=>$?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:N5($)}));return S$.fromRecord(this.client,O)}async delete($={}){await this.mutate((O)=>O.calendar.deleteCalendarEvent({path:{event_id:this.id},query:{calendarId:$.calendar?.id,scope:$.scope,recurrenceId:$.recurrenceId,inbox:$.inbox}}))}async prepareReplacement($){let O=Q(await this.client.calendar.prepareCalendarReplacement({path:{event_id:this.id},body:{removeConference:$.removeConference,recurrenceId:$.recurrenceId,calendarId:$.calendar?.id}}));return new iO(this.client,O.operationId)}async providerUrl($={}){return Q(await this.client.calendar.calendarEventProviderUrl({path:{event_id:this.id},query:{recurrenceId:$.recurrenceId,calendarId:$.calendar?.id}})).url??void 0}async inviteGuests($){let O=await this.mutate((j)=>j.calendar.inviteCalendarEventGuests({path:{event_id:this.id},body:{guests:$.guests,scope:$.scope,recurrenceId:$.recurrenceId,calendarId:$.calendar?.id,inbox:$.inbox}}));return S$.fromRecord(this.client,O)}async addToCalendar($={}){let O=await this.mutate((j)=>j.calendar.copyCalendarEvent({path:{event_id:this.id},body:{calendarId:$.calendar?.id}}));return S$.fromRecord(this.client,O)}async ics(){return Q(await this.client.storage.eventIcs({path:{event_id:this.id}}))}async rsvp($){let O=await this.mutate((j)=>j.calendar.rsvpCalendarEvent({path:{event_id:this.id},body:{response:$.response,scope:$.scope,recurrenceId:$.recurrenceId,calendarId:$.calendar?.id}}));return S$.fromRecord(this.client,O)}}function N5($){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 Ox{client;async availabilityCalendars(){return Q(await this.client.calendar.getAvailabilityCalendars()).calendars.map(($)=>({calendar:m$.byId(this.client,$.calendarId),name:$.name,isPrimary:$.isPrimary,contributesToAvailability:$.contributesToAvailability}))}async teamSharing(){return Q(await this.client.calendar.getTeamSharing()).sharing}async setTeamSharing($){return Q(await this.client.calendar.setTeamSharing({body:{sharing:$}})).sharing}occurrences($){let O;return c(async(j)=>{let x=Q(await this.client.storage.listOccurrences({query:{...$,cursor:j}}));O??=z5(this.client);let S=await O;return{items:x.items.map((K)=>{let Z=K.event.calendarId?S.get(K.event.calendarId):void 0;return{event:S$.fromRecord(this.client,K.event),occurrence:K.occurrence,calendarName:Z?.name,contributesToAvailability:O2(K.event,S),inbox:Z?.emailAddress,role:I5(K.event,S)}}),nextCursor:x.nextCursor}})}async teamPage($){let O=Q(await this.client.storage.listTeamCalendar({query:$}));return{items:O.items.map(({ownerId:j,...x})=>({...x,owner:C.byId(this.client,j)})),members:O.members.map((j)=>({user:C.byId(this.client,j.userId),sharing:j.sharing,coverage:j.coverage})),nextCursor:O.nextCursor??void 0}}async teamOutOfOffice($){let O=Q(await this.client.storage.listTeamOutOfOffice({query:$}));return{items:O.items.map((j)=>({event:S$.byId(this.client,j.eventId),owner:C.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 S$.byId(this.client,$)}replacement($){return new iO(this.client,$)}async createEvent($){let O=Q(await this.client.calendar.createCalendarEvent({body:U5($)}));return S$.fromRecord(this.client,O)}}function U5($){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 z5($){let{calendars:O}=Q(await $.calendar.listCalendars());return new Map(O.map((j)=>[j.id,j]))}function O2($,O){let j=[$.calendarId,...($.sources??[]).map((x)=>x.calendarId)].flatMap((x)=>{let S=x?O.get(x):void 0;return S?[S.contributesToAvailability]:[]});if(j.some(Boolean))return!0;return j.length>0&&j.every((x)=>x===!1)?!1:void 0}function I5($,O){let j=$.attendees.find((S)=>S.isSelf);if(j?.isOrganizer)return $.isReadOnly?void 0:"organizer";let x=$.attendees.some((S)=>S.isOrganizer);if($.viewerCan.organize&&O2($,O)&&!x)return"organizer";return j?"guest":void 0}class D$ extends A{lookupToken;constructor($,O,j){super($,O,j);this.lookupToken=j?.shareToken}static byId($,O){return new D$($,O)}static from($,O){return new D$($,O.id,O)}async fetch(){if(this.lookupToken)return Q(await this.client.storage.meetingLookup({path:{token:this.lookupToken}}));let $=Q(await this.client.storage.meetingList()).meetings.find((O)=>O.id===this.id);if(!$)throw new E(`Meeting ${this.id} is unavailable`);return this.lookupToken=$.shareToken,$}title=this.field("title");scheduledStart=this.field("scheduledStart");scheduledEnd=this.field("scheduledEnd");channel=this.mappedField("channelId",($)=>$?b.byId(this.client,$):void 0);call=this.mappedField("callId",($)=>$?J$.byId(this.client,$):void 0);async update($){await this.mutate((O)=>O.storage.meetingUpdate({path:{meeting_id:this.id},body:$}))}async cancel(){await this.mutate(($)=>$.storage.meetingCancel({path:{meeting_id:this.id}}))}async invitePermissions(){return Q(await this.client.storage.meetingInvitePermissions({path:{token:(await this.detail.get()).shareToken}}))}async invite($){Q(await this.client.storage.meetingInvite({path:{token:(await this.detail.get()).shareToken},body:{email:$}}))}async inviteUsers($){Q(await this.client.storage.meetingInviteUsers({path:{token:(await this.detail.get()).shareToken},body:{userIds:$.map((O)=>O.id)}}))}async webUrl(){return`${this.client.webAppUrl}/app/meet/join/${encodeURIComponent((await this.detail.get()).shareToken)}`}}class u$ extends A{callId;constructor($,O,j,x){super($,j,x);this.callId=O}get path(){return{parent_type:"call",parent_id:this.callId,id:this.id}}async fetch(){return Q(await this.client.storage.entityMessageGetMessage({path:this.path}))}static byId($,O,j){return new 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 J$.byId(this.client,this.callId)}async author(){return C.byId(this.client,(await this.detail.get()).sender_id)}async reply($){let O=Q(await this.client.storage.entityMessageCreate({path:{parent_type:"call",parent_id:this.callId},body:{...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 J$ extends H${messageThreadById($){return L$.byId(this.client,{type:"call",entity:this},$)}timelinePage($){return b$(this.client,{type:"call",entity:this},(O)=>u$.from(this.client,this.id,O),$)}access=new $$(this.client,"call",this);async meeting(){return D$.from(this.client,Q(await this.client.storage.meetingShare({path:{call_id:this.id}})))}async editTranscript($){await this.mutate((O)=>O.storage.editCallTranscript({path:{call_id:this.id},body:{assignments:$}}))}async toggleTeamShare(){return this.mutate(($)=>$.storage.toggleShareWithTeam({path:{call_id:this.id}}))}entityType="call";async fetch(){return Q(await this.client.storage.getCallRecord({path:{call_id:this.id}}))}static byId($,O){return new J$($,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",($)=>C.byId(this.client,$));isActive=this.field("isActive");status=this.field("status");roomName=this.field("roomName");startedAt=this.field("startedAt");endedAt=this.field("endedAt");durationMs=this.field("durationMs");summary=this.field("summary");transcript=this.field("transcript");participants=this.field("participants");guests=this.field("guests");teamShareAccessLevel=this.field("teamShareAccessLevel");shareWithTeam=this.field("shareWithTeam");recordingUrl=this.field("recordingUrl");recordingPreviewUrl=this.field("recordingPreviewUrl");recordingStartedAt=this.field("recordingStartedAt");async rename($){await this.mutate((O)=>O.storage.editCallRecord({path:{call_id:this.id},body:{customName:$??""}}))}async setTeamShare($){await this.mutate((O)=>O.storage.editCallRecord({path:{call_id:this.id},body:{sharePermission:{teamShareAccessLevel:$?"view":null}}}))}async delete(){await this.mutate(($)=>$.storage.deleteCallRecord({path:{call_id:this.id}}))}static search=x$({filters:{call_filters:{}},type:"call",make:($,O)=>new J$($,O.call_id)})}class jx{client;constructor($){this.client=$}byId($){return J$.byId(this.client,$)}search($,O){return J$.search(this.client,$,O)}}class xx{client;constructor($){this.client=$}async list(){let{labels:$}=Q(await this.client.storage.listChannelLabels());return $}async create($,O=[]){return Q(await this.client.storage.createChannelLabel({body:{name:$,channelIds:O.map((j)=>j.id)}}))}async createSmartTag($,O){return Q(await this.client.storage.createChannelLabel({body:{name:$,rule:O}}))}async previewSmartTag($){return Q(await this.client.storage.previewSmartTag({body:$}))}async updateSmartTag($,O,j){return Q(await this.client.storage.renameChannelLabel({path:{label_id:$.id},body:{name:O,rule:j}}))}async rename($,O){return Q(await this.client.storage.renameChannelLabel({path:{label_id:$.id},body:{name:O}}))}async delete($){Q(await this.client.storage.deleteChannelLabel({path:{label_id:$.id}}))}async setLabel($,O){Q(await this.client.storage.setChannelLabel({path:{channel_id:$.id},body:{labelId:O?.id??null}}))}}var H5=100;class Sx{client;async activity(){return Q(await this.client.storage.getActivity()).map(($)=>new GO(this.client,b.byId(this.client,$.channel_id),$))}labels;constructor($){this.client=$;this.labels=new xx($)}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(){for await(let $ of this.records())yield b.byId(this.client,$.id)}async*search($,O){if(!O?.searchOn||O.searchOn==="name"){let j=$.toLowerCase();for await(let x of this.records())if(x.name?.toLowerCase().includes(j))yield b.byId(this.client,x.id)}else yield*b.search(this.client,$,O)}records(){return c(async($)=>{let O=Q(await this.client.storage.getChannels({query:{limit:H5,...$?{cursor:$}:{}}}));return{items:O.items,nextCursor:O.next_cursor}})}}class n extends K${async sharePermissions(){return Q(await this.client.storage.getProjectPermissionsV2({path:{id:this.id}}))}async accessLevel(){return Q(await this.client.storage.getProjectUserAccessLevel({path:{id:this.id}}))}access=new $$(this.client,"project",this);entityType="project";propertyEntityType="PROJECT";async fetch(){let{data:$}=Q(await this.client.storage.getProjectHandler({path:{id:this.id}}));return $.projectMetadata}static byId($,O){return new n($,O)}static async create($,O){let{data:j}=Q(await $.storage.createProjectHandler({body:{name:O.name,projectParentId:O.parent?.id??null}}));return new n($,j.id,j)}name=this.field("name");parent=this.mappedField("parentId",($)=>$?n.byId(this.client,$):void 0);createdAt=this.field("createdAt");async items(){let{data:$}=Q(await this.client.storage.getProjectContentHandler({path:{id:this.id}}));return $.map((O)=>O.item)}async rename($){await this.mutate((O)=>O.storage.editProjectV2({path:{id:this.id},body:{name:$}}))}async delete($){await this.mutate((O)=>$?.permanent?O.storage.permanentlyDeleteProject({path:{id:this.id}}):O.storage.deleteProjectHandler({path:{id:this.id}}))}async restore(){await this.mutate(($)=>$.storage.revertDeleteProject({path:{id:this.id}}))}static search=x$({filters:{project_filters:{}},type:"project",make:($,O)=>new n($,O.id)})}class nO{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 nO($,O,j,x)}async stop(){Q(await this.client.cognition.stopChatStream({body:{chat_id:this.chat.id,stream_id:this.id}}))}toJSON(){return{id:this.id,chatId:this.chat.id,messageId:this.message.id}}}class sO extends A{chat;constructor($,O,j){super($,j);this.chat=O}static byId($,O,j){return new sO($,O,j)}async fetch(){let $=Q(await this.client.cognition.getChat({path:{chat_id:this.chat.id}})).chat.messages.find((O)=>O.id===this.id);if(!$)throw new E(`Chat message ${this.id} is not yet available`);return $}content=this.field("content");role=this.field("role");async refresh(){this.detail.clear(),await this.detail.get()}toJSON(){return{...super.toJSON(),chatId:this.chat.id}}}class Y$ extends K${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=Y$.byId(this.client,S.chat_id);return nO.byId(this.client,K,S.stream_id,sO.byId(this.client,K,S.message_id))}access=new $$(this.client,"chat",this);entityType="chat";propertyEntityType="CHAT";async fetch(){let{chat:$}=Q(await this.client.cognition.getChat({path:{chat_id:this.id}}));return $}static byId($,O){return new Y$($,O)}static async create($,O){let{id:j}=Q(await $.cognition.createChat({body:{name:O?.name??null,projectId:O?.project?.id??null}}));return new Y$($,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 Y$(this.client,$)}async restore(){await this.mutate(($)=>$.cognition.revertDeleteChat({path:{chat_id:this.id}}))}async history(){let{conversation:$}=Q(await this.client.cognition.getChatHistoryHandler({path:{chat_id:this.id}}));return $}webUrl(){return`${this.client.webAppUrl}/app/chat/${this.id}`}static search=x$({filters:{chat_filters:{}},type:"chat",make:($,O)=>new Y$($,O.chat_id)});toMention(){return{tag:o$("m-document-mention",{documentId:this.id,documentName:this.detail.peek()?.name??"",blockName:"chat",blockParams:{}}),mention:{entity_type:"chat",entity_id:this.id}}}}class Zx{client;constructor($){this.client=$}byId($){return Y$.byId(this.client,$)}create($){return Y$.create(this.client,$)}search($,O){return Y$.search(this.client,$,O)}}class HO extends A{static byId($,O){return new HO($,O)}static from($,O){return new HO($,O.id,O)}async fetch(){let $=Q(await this.client.auth.getTeamInvites()).invites.find((O)=>O.id===this.id);if(!$)throw new E(`team invite ${this.id} not found`);return $}email=this.field("email");role=this.field("team_role");invitedBy=this.mappedField("invited_by",($)=>C.byId(this.client,$));createdAt=this.field("created_at");lastSentAt=this.field("last_sent_at");async revoke(){await this.mutate(($)=>$.auth.deleteTeamInviteHandler({path:{team_invite_id:this.id}}))}}class _$ extends A{async fetch(){let O=Q(await this.client.auth.getUserTeams()).find((j)=>j.id===this.id);if(!O)throw new E(`team ${this.id} not found`);return O}static byId($,O){return new _$($,O)}static async current($){let O=Q(await $.auth.getTeam());if(!O?.team)throw new E("caller has no current team");return new _$($,O.team.id,O.team)}static async list($){return Q(await $.auth.getUserTeams()).map((j)=>new _$($,j.id,j))}name=this.field("name");slug=this.field("slug");defaultLinkShare=this.field("default_link_share");owner=this.mappedField("owner_id",($)=>C.byId(this.client,$));async members(){return(await this.requireCurrent("members")).members.map((O)=>({user:C.byId(this.client,O.user_id),role:O.role}))}async invite($){let O=[],j=new Set;for(let S of typeof $==="string"?[$]:$){let K=S.trim(),Z=K.toLowerCase();if(K&&!j.has(Z))j.add(Z),O.push(K)}if(O.length===0)throw new f("invite needs at least one email address");let x=await this.client.auth.inviteToTeam({body:{invites:O.map((S)=>({email:S})),team_id:this.id}});if(x.response?.status===304)return!1;return Q(x),!0}async invites(){return Q(await this.client.auth.getTeamInvites({query:{team_id:this.id}})).invites.map(($)=>HO.from(this.client,$))}async requireCurrent($){let O=Q(await this.client.auth.getTeam());if(!O?.team||O.team.id!==this.id)throw new f(`${$} are only available for the current team (see Team.current)`);return O}}var T5=8;class A$ extends A{parent;constructor($,O,j,x){super($,j,x);this.parent=O}get path(){return{parent_type:this.parent.type,parent_id:this.parent.id,id:this.id}}async fetch(){return Q(await this.client.storage.entityMessageGetMessage({path:this.path}))}static byId($,O,j){return new A$($,O,j)}static from($,O,j){return new A$($,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 C.byId(this.client,(await this.detail.get()).sender_id)}async reply($){return tO(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 Hj($,O){let j={parent_type:O.type,parent_id:O.id},x=c(async(K)=>{let Z=Q(await $.storage.messageTimeline({path:j,query:{selection:JSON.stringify({limit:100,cursor:K})}}));return{items:Z.items,nextCursor:Z.next_cursor}}),S=[];for await(let K of x)S.push(K);return cO(S,T5,async(K)=>{let{state:Z,root:X,replies:Y}=Q(await $.storage.entityMessageGetThread({path:{...j,id:K.id}}));return{thread:Z,comments:[X,...Y].map((L)=>A$.from($,O,L))}})}async function tO($,O,j,x){let S=Q(await $.storage.entityMessageCreate({path:{parent_type:O.type,parent_id:O.id},body:{...O$(j),thread_id:x?.threadId??null}}));return A$.from($,O,S)}class P$ extends H${messageThreadById($){return L$.byId(this.client,{type:"crm_contact",entity:this},$)}timelinePage($){return b$(this.client,{type:"crm_contact",entity:this},(O)=>A$.from(this.client,{type:"crm_contact",id:this.id},O),$)}entityType="crm_contact";async fetch(){return Q(await this.client.storage.getContact({path:{contact_id:this.id}}))}static byId($,O){return new P$($,O)}static from($,O){return new P$($,O.id,O)}name=this.field("name");email=this.field("email");company=this.mappedField("companyId",($)=>$?k$.byId(this.client,$):void 0);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 Hj(this.client,this.commentParent)}async comment($,O){return tO(this.client,this.commentParent,$,O)}commentById($){return A$.byId(this.client,this.commentParent,$)}}class k$ extends K${messageThreadById($){return L$.byId(this.client,{type:"crm_company",entity:this},$)}timelinePage($){return b$(this.client,{type:"crm_company",entity:this},(O)=>A$.from(this.client,{type:"crm_company",id:this.id},O),$)}entityType="crm_company";propertyEntityType="COMPANY";async fetch(){return Q(await this.client.storage.getCompany({path:{company_id:this.id}}))}static byId($,O){return new k$($,O)}static from($,O){return new k$($,O.id,O)}name=this.field("name");description=this.field("description");hidden=this.field("hidden");emailSync=this.field("emailSync");team=this.mappedField("teamId",($)=>_$.byId(this.client,$));createdAt=this.field("createdAt");updatedAt=this.field("updatedAt");async domain(){let{domains:$}=await this.detail.get();return $[0]?.domain}async domains(){let{domains:$}=await this.detail.get();return $.map((O)=>O.domain)}async contacts(){return Q(await this.client.storage.listCompanyContacts({path:{company_id:this.id}})).map((O)=>P$.from(this.client,O))}static search=x$({filters:{crm_company_filters:{}},type:"company",includeCrm:!0,make:($,O)=>new k$($,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 P$.from(this.client,O)}get commentParent(){return{type:"crm_company",id:this.id}}async comments(){return Hj(this.client,this.commentParent)}async comment($,O){return tO(this.client,this.commentParent,$,O)}commentById($){return A$.byId(this.client,this.commentParent,$)}}class jO extends A{tableDetail=new W$(async()=>Q(await this.client.storage.getCrmPipelineTable({path:{id:this.id}})));static byId($,O){return new jO($,O)}static from($,O){return new jO($,O.id,O)}async fetch(){return Q(await this.client.storage.getCrmPipeline({path:{id:this.id}}))}name=this.field("name");recordType=this.field("recordType");accessLevel=this.field("grant");sharing=this.field("sharing");owner=this.mappedField("userId",($)=>C.byId(this.client,$));team=this.mappedField("teamId",($)=>_$.byId(this.client,$));async rename($){await this.mutate((O)=>O.storage.renameCrmPipeline({path:{id:this.id},body:{name:$}}))}async setSharing($){if($===void 0)throw Error("Sharing is required");await this.mutate((O)=>O.storage.shareCrmPipeline({path:{id:this.id},body:{sharing:$}}))}async setTrashed($){await this.mutate((O)=>O.storage.trashCrmPipeline({path:{id:this.id},body:{trashed:$}}))}async sharePermissions(){return Q(await this.client.storage.getCrmPipelinePermissions({path:{id:this.id}}))}async updateSharePermissions($){return this.mutate((O)=>O.storage.updateCrmPipelinePermissions({path:{id:this.id},body:$O($)}))}async table(){return Tj.from(this.client,this,await this.tableRecord())}async viewPositions($){if($.table.pipeline.id!==this.id)throw Error("View belongs to another pipeline");return Q(await this.client.storage.getCrmPipelineViewPositions({path:{id:this.id,view:$.id}}))}tableRecord(){return this.tableDetail.get()}rows(){return c(async($)=>{let O=Q(await this.client.storage.getCrmPipelineRows({path:{id:this.id},query:{after:$}}));return{items:O.rows.map((j)=>JO.from(this.client,this,j)),nextCursor:O.next}})}queryRows($={}){if($.rows?.some((O)=>O.pipeline.id!==this.id))throw Error("Rows belong to another pipeline");return c(async(O)=>{let j=Q(await this.client.storage.queryCrmPipelineRows({path:{id:this.id},body:{after:O,query:$.query,rowIds:$.rows?.map((x)=>x.id)}}));return{items:j.rows.map((x)=>JO.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 Tj extends A{pipeline;toJSON(){return{...super.toJSON(),pipelineId:this.pipeline.id}}constructor($,O,j){super($,j.table.id,j);this.pipeline=O}static from($,O,j){return new Tj($,O,j)}fetch(){return this.pipeline.tableRecord()}async columns(){return(await this.pipeline.tableRecord()).columns.map(($)=>Dj.from(this.client,this,$))}async views(){return(await this.pipeline.tableRecord()).views.map(($)=>Rj.byId(this,$.id))}async version(){return(await this.pipeline.tableRecord()).table.version}rowById($){return JO.byId(this.client,this.pipeline,$)}rows(){return this.pipeline.rows()}}class Rj{table;id;constructor($,O){this.table=$;this.id=O}static byId($,O){return new Rj($,O)}async detail(){let $=(await this.table.pipeline.tableRecord()).views.find((O)=>O.id===this.id);if(!$)throw new E(`view ${this.id} is not on table ${this.table.id}`);return $}positions(){return this.table.pipeline.viewPositions(this)}toJSON(){return{id:this.id,tableId:this.table.id,pipelineId:this.table.pipeline.id}}}class JO extends A{pipeline;toJSON(){return{...super.toJSON(),pipelineId:this.pipeline.id}}constructor($,O,j,x){super($,j,x);this.pipeline=O}static byId($,O,j){return new JO($,O,j)}static from($,O,j){return new JO($,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 Dj extends A{table;toJSON(){return{...super.toJSON(),pipelineId:this.table.pipeline.id,tableId:this.table.id}}constructor($,O,j){super($,j.column.id,j);this.table=O}static from($,O,j){return new Dj($,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 Xx{client;constructor($){this.client=$}byId($){return jO.byId(this.client,$)}async list(){return Q(await this.client.storage.listCrmPipelines()).map(($)=>jO.from(this.client,$))}async create($){return jO.from(this.client,Q(await this.client.storage.createCrmPipeline({body:$})))}}class Kx{client;pipelines;constructor($){this.client=$;this.pipelines=new Xx($)}companyById($){return k$.byId(this.client,$)}contactById($){return P$.byId(this.client,$)}async contactByEmail($){let{contact:O}=Q(await this.client.storage.getContactByEmail({query:{email:$}}));return O?P$.from(this.client,O):void 0}async searchContacts($,O={}){let{contacts:j}=Q(await this.client.storage.searchContacts({query:{query:$,limit:O.limit}}));return j.map((x)=>P$.from(this.client,x))}async createCompany($){return k$.from(this.client,Q(await this.client.storage.createCrmCompany({body:$})))}async createContact($){return P$.from(this.client,Q(await this.client.storage.createCrmTeamContact({body:$})))}async blockedDomains(){return Q(await this.client.storage.listCrmBlockedDomains()).map(($)=>$.domain)}async blockDomain($){Q(await this.client.storage.blockCrmDomain({path:{domain:$}}))}async unblockDomain($){Q(await this.client.storage.unblockCrmDomain({path:{domain:$}}))}async settings(){return Q(await this.client.storage.getCrmTeamSettings())}async updateSettings($){return Q(await this.client.storage.putCrmTeamSettings({body:$}))}async setStages($){return Q(await this.client.storage.putCrmTeamStages({body:$}))}async resetStages(){Q(await this.client.storage.resetCrmTeamStages())}searchCompanies($){return k$.search(this.client,$)}}var Yx,R5=new Uint8Array(16);function _j(){if(!Yx){if(typeof crypto>"u"||!crypto.getRandomValues)throw Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Yx=crypto.getRandomValues.bind(crypto)}return Yx(R5)}var j$=[];for(let $=0;$<256;++$)j$.push(($+256).toString(16).slice(1));function j2($,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 Qx={};function D5($,O,j){let x;if($)x=x2($.random??$.rng?.()??_j(),$.msecs,$.seq,O,j);else{let S=Date.now(),K=_j();_5(Qx,S,K),x=x2(K,Qx.msecs,Qx.seq,O,j)}return O??j2(x)}function _5($,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 x2($,O,j,x,S=0){if($.length<16)throw Error("Random bytes length must be >= 16");if(!x)x=new Uint8Array(16),S=0;else if(S<0||S+16>x.length)throw RangeError(`UUID byte range ${S}:${S+15} is out of buffer bounds`);return O??=Date.now(),j??=$[6]*127<<24|$[7]<<16|$[8]<<8|$[9],x[S++]=O/1099511627776&255,x[S++]=O/4294967296&255,x[S++]=O/16777216&255,x[S++]=O/65536&255,x[S++]=O/256&255,x[S++]=O&255,x[S++]=112|j>>>28&15,x[S++]=j>>>20&255,x[S++]=128|j>>>14&63,x[S++]=j>>>6&255,x[S++]=j<<2&255|$[10]&3,x[S++]=$[11],x[S++]=$[12],x[S++]=$[13],x[S++]=$[14],x[S++]=$[15],x}var c$=D5;class F${table;id;constructor($,O){this.table=$;this.id=O}static byId($,O){return new F$($,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 E${table;id;constructor($,O){this.table=$;this.id=O}static byId($,O){return new E$($,O)}history(){return this.table.database.rowHistory(this)}toJSON(){return{id:this.id,tableId:this.table.id}}}class Mj{table;id;constructor($,O){this.table=$;this.id=O}static byId($,O){return new Mj($,O)}async detail(){let{views:$}=await this.table.detail(),O=$.find((j)=>j.id===this.id);if(!O)throw new E(`view ${this.id} is not on table ${this.table.id}`);return O}async name(){return(await this.detail()).name}async position(){return(await this.detail()).position}async layout(){return(await this.detail()).layout}async query(){return(await this.detail()).query}positions(){return this.table.database.viewPositions(this)}toJSON(){return{id:this.id,tableId:this.table.id}}}class V${database;id;constructor($,O){this.database=$;this.id=O}static byId($,O){return new V$($,O)}async detail(){let{tables:$}=await this.database.schema(),O=$.find((j)=>j.table.id===this.id);if(!O)throw new E(`table ${this.id} is not in database ${this.database.id}`);return O}async name(){return(await this.detail()).table.name}async rename($){return await this.database.renameTable(this,$),this}async version(){return(await this.detail()).table.version}async position(){return(await this.detail()).table.position}async columns(){let{columns:$}=await this.detail();return $.map((O)=>F$.byId(this,O.column.id))}addColumn($){return this.database.addColumn(this,$)}async reorderColumns($){return await this.database.reorderColumns(this,$),this}row($){return E$.byId(this,$)}async views(){let{views:$}=await this.detail();return $.map((O)=>Mj.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 Cj($,O,j,x={}){let S=Q(await $.storage.queryDatabases({body:{sql:j,databaseId:x.database?.id,baseVersions:Object.fromEntries((x.baseVersions??[]).map(({table:G,version:J})=>[G.id,J]))}})),K=new Map;for(let G of[x.database,...(x.baseVersions??[]).map(({table:J})=>J.database)]){if(!G)continue;let J=K.get(G.id);if(J)J.add(G);else K.set(G.id,new Set([G]))}let Z=(G)=>{let J=K.get(G)?.values().next().value;if(J)return J;let I=O($,G);return K.set(G,new Set([I])),I},X=(G)=>{let J=S.tableDatabases[G];if(!J)throw Error(`SQL response is missing the owner of table ${G}`);return V$.byId(Z(J),G)},Y=new Set(Object.keys(S.newVersions).map((G)=>X(G).database.id));if(S.statement.kind==="schema")Y.add(S.statement.databaseId);for(let G of Y)for(let J of K.get(G)??[])J.invalidateSchema();let L=k(S.statement).with({kind:"select"},(G)=>G).with({kind:"schema"},({databaseId:G,summary:J})=>({kind:"schema",database:Z(G),summary:J})).with({kind:"insert"},{kind:"update"},{kind:"delete"},({kind:G,tableId:J,tableName:I})=>({kind:G,table:X(J),tableName:I})).with({kind:"alterColumnType"},({tableId:G,tableName:J,columnId:I,columnName:z,to:W})=>{let V=X(G);return{kind:"alterColumnType",table:V,tableName:J,column:F$.byId(V,I),columnName:z,to:W}}).exhaustive();return{result:S.result?M5(S.result,X,S.tableDatabases):void 0,changesApplied:S.changesApplied,insertedRows:L.kind==="insert"?S.insertedRowIds.map((G)=>E$.byId(L.table,G)):[],newVersions:Object.entries(S.newVersions).map(([G,J])=>({table:X(G),version:J})),readVersions:Object.entries(S.readVersions).map(([G,J])=>({table:X(G),version:J})),truncatedTables:S.truncatedTables,statement:L}}function M5($,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)=>E$.byId(x,S)):[]}}class Aj{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 Aj($,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 Vx extends e${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 Pj($){return k($).with({type:"relation"},({table:O})=>({type:"relation",database:O.database.id,table:O.id})).with({type:t.not("relation")},(O)=>O).exhaustive()}var C5={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 A5($){return k($).with({type:"text"},()=>"Text").with({type:"number"},()=>"Number").with({type:"boolean"},()=>"Checkbox").with({type:"date"},()=>"Date").with({type:"date_range"},()=>"Time range").with({type:"link"},()=>"URL").with({type:"select",multi:!0},()=>"Multi-select").with({type:"select",multi:!1},()=>"Select").with({type:"select_number",multi:!0},()=>"Multi-number select").with({type:"select_number",multi:!1},()=>"Number select").with({type:"tag"},()=>"Tag").with({type:"entity"},({target:O})=>C5[O]).with({type:"relation"},()=>"Relation").exhaustive(()=>"Column")}function Gx($){return $.map((O)=>({id:c$(),label:O}))}function S2($,O,j){return $?.kind===O&&"change"in $&&$.change.kind===j}function Jx($){return k($).with({kind:"reorder_tables"},({kind:O})=>O).with({kind:t.union("table","column","rows","view")},({kind:O,change:j})=>`${O}.${j.kind}`).exhaustive(()=>"unknown")}function d$($,O,j){let[x]=$;if($.length!==1||!S2(x,O,j))throw new f(`expected one ${O}.${j} result, got ${$.map(Jx).join(", ")||"none"}`);return x}class Q$ extends A{access=new $$(this.client,"database",this);async fetch(){return Q(await this.client.storage.getDatabase({path:{id:this.id}}))}assertOwns($,O){if(O.id!==this.id)throw new f(`${$} does not belong to database ${this.id}`)}static byId($,O){return new Q$($,O)}static async create($,O){let j=Q(await $.storage.createDatabase({body:{name:O.name}}));return new Q$($,j.id)}async duplicate($){let O=Q(await this.client.storage.duplicateDatabase({path:{id:this.id},body:{name:$?.name}}));return new Q$(this.client,O.id)}static async list($){return Q(await $.storage.listDatabases()).map((j)=>new Q$($,j.database.id))}query($,O){return Cj(this.client,Q$.byId,$,{...O,database:this})}invalidateSchema(){this.detail.clear()}schema(){return this.detail.get()}name=this.mappedField("database",($)=>$.name);owner=this.mappedField("database",($)=>C.byId(this.client,$.owner_id));createdAt=this.mappedField("database",($)=>$.created_at);trashedAt=this.mappedField("database",($)=>$.trashed_at??void 0);grant=this.field("grant");tables=this.mappedField("tables",($)=>$.map((O)=>V$.byId(this,O.table.id)));async table($){let{tables:O}=await this.schema(),j=O.find((x)=>x.table.name===$);return j?V$.byId(this,j.table.id):void 0}async createTable($){let{table:O}=d$(await this.applyOps([{kind:"table",table:c$(),change:{kind:"create",name:$.name}}]),"table","created");return V$.byId(this,O)}async applyOps($,O={}){let j={ops:$};if(O.baseVersions!==void 0){for(let{table:S}of O.baseVersions)this.assertOwns(`table ${S.id}`,S.database);j.baseVersions=Object.fromEntries(O.baseVersions.map(({table:S,version:K})=>[S.id,K]))}let{results:x}=await this.mutate(async(S)=>{let K=await S.storage.applyDatabaseOps({path:{id:this.id},body:j});if(K.error!==void 0&&"op"in K.error)throw new Vx(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(Jx).join(", ")||"none"}`);return j.tables.map(({table:x})=>V$.byId(this,x))}async deleteTable($){this.assertOwns(`table ${$.id}`,$.database),d$(await this.applyOps([{kind:"table",table:$.id,change:{kind:"delete"}}]),"table","deleted")}async columnCasts($){return this.assertOwns(`column ${$.id}`,$.table.database),Q(await this.client.storage.listDatabaseColumnCasts({path:{id:this.id,table_id:$.table.id,column_id:$.id}}))}async viewPositions($){this.assertOwns(`view ${$.id}`,$.table.database);let{positions:O}=Q(await this.client.storage.getDatabaseViewPositions({path:{id:this.id,view_id:$.id}}));return O}async rowHistory($){this.assertOwns(`row ${$.id}`,$.table.database);let{changes:O}=Q(await this.client.storage.getDatabaseRowHistory({path:{id:this.id,table_id:$.table.id,row_id:$.id}}));return O}async importTable($){let O=await this.mutate((j)=>j.storage.importDatabaseTable({path:{id:this.id},body:$}));return V$.byId(this,O.id)}webhookOf($){return Aj.fromRecord(V$.byId(this,$.tableId),C.byId(this.client,$.createdBy),$)}async webhooks(){let{webhooks:$}=Q(await this.client.storage.listDatabaseWebhooks({path:{id:this.id}}));return $.map((O)=>this.webhookOf(O))}async createWebhook($){this.assertOwns("table",$.database);let O=Q(await this.client.storage.createDatabaseWebhook({path:{id:this.id},body:{tableId:$.id}}));return{webhook:this.webhookOf(O.webhook),token:O.token}}async deleteWebhook($){this.assertOwns("webhook",$.table.database),Q(await this.client.storage.deleteDatabaseWebhook({path:{id:this.id,webhook_id:$.id}}))}async sharePermissions(){return Q(await this.client.storage.getDatabasePermissions({path:{id:this.id}}))}updateSharePermissions($){return this.mutate((O)=>O.storage.updateDatabasePermissions({path:{id:this.id},body:$}))}async changeColumnType($,O){this.assertOwns(`column ${$.id}`,$.table.database);let j=await $.table.version();return d$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"change_type",to:Pj(O.to)}}],{baseVersions:[{table:$.table,version:j}]}),"column","type_changed")}async columnConversion($,O){return this.assertOwns(`column ${$.id}`,$.table.database),Q(await this.client.storage.convertDatabaseColumn({path:{id:this.id,table_id:$.table.id,column_id:$.id},body:{to:Pj(O)}}))}async convertColumnIntoNewColumn($,O){let j=await this.columnConversion($,O.to),x=O.name??`${await $.name()} (${A5(O.to)})`,S=c$(),K=[{kind:"column",table:$.table.id,column:S,change:{kind:"create",definition:{source:"new",name:x,type:Pj(O.to),options:Gx(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(!S2(Z,"column","created"))throw new f(`expected a column.created result, got ${Z?Jx(Z):"none"}`);return F$.byId($.table,Z.column)}async deleteColumn($){this.assertOwns(`column ${$.id}`,$.table.database);let O=await $.table.version(),{tableVersion:j}=d$(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}=d$(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}=d$(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}=d$(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:Pj(O.type),...O.options!==void 0?{options:Gx(O.options)}:{},...O.inferType!==void 0?{inferType:O.inferType}:{}},{column:x}=d$(await this.applyOps([{kind:"column",table:$.id,column:c$(),change:{kind:"create",definition:j,...O.after!==void 0?{after:O.after.id}:{}}}]),"column","created");return F$.byId($,x)}async addColumnOptions($,O){return this.assertOwns(`column ${$.id}`,$.table.database),d$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"add_options",options:Gx(O)}}]),"column","options_added")}}class Wx{client;constructor($){this.client=$}query($,O){return Cj(this.client,Q$.byId,$,O)}byId($){return Q$.byId(this.client,$)}create($){return Q$.create(this.client,$)}list(){return Q$.list(this.client)}}class VO extends A{document;toJSON(){return{...super.toJSON(),documentId:this.document.id}}constructor($,O,j,x){super($,j,x);this.document=O}static byId($,O,j){return new VO($,O,j)}static from($,O,j){return new VO($,O,j.uuid,j)}async fetch(){let $=Q(await this.client.storage.getDocumentAnchors({path:{document_id:this.document.id}})).data.find((O)=>O.uuid===this.id);if(!$)throw new E(`Annotation ${this.id} is unavailable`);return $}kind=this.field("anchorType");page=this.field("page");async edit($){if(await this.kind()!=="placeable")throw Error("Only placeable comment annotations can be edited");await this.mutate((O)=>O.storage.editAnchor({body:{...$,uuid:this.id,anchorType:"free-comment",fileType:"pdf"}}))}async delete(){if(await this.kind()!=="highlight")throw Error("Only standalone highlights can be deleted with this endpoint");await this.mutate(($)=>$.storage.deleteAnchor({body:{uuid:this.id,anchorType:"highlight",fileType:"pdf"}}))}}class l$ extends A{documentId;constructor($,O,j,x){super($,j,x);this.documentId=O}get path(){return{parent_type:"document",parent_id:this.documentId,id:this.id}}async fetch(){return Q(await this.client.storage.entityMessageGetMessage({path:this.path}))}static byId($,O,j){return new l$($,O,j)}static from($,O,j){return new l$($,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 C.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 eO{client;document;id;detail;constructor($,O,j){this.client=$;this.document=O;this.id=j;this.detail=new W$(async()=>Q(await this.client.storage.getDocumentVersion({path:{document_id:O.id,document_version_id:j}})).data)}static byId($,O,j){return new eO($,O,j)}read(){return this.detail.get()}toJSON(){return{id:this.id,documentId:this.document.id}}}var P5=8;class w extends K${async anchors(){return Q(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,Q(await this.client.storage.createAnchor({path:{document_id:this.id},body:{...$,fileType:"pdf",anchorType:"highlight"}})))}version($){return eO.byId(this.client,this,$)}async sharePermissions(){return Q(await this.client.storage.getDocumentPermissionsV2({path:{document_id:this.id}})).documentPermissions}async permissionsToken(){return Q(await this.client.storage.getDocumentPermissionsToken({path:{document_id:this.id}})).token}async prepareSave($){return Q(await this.client.storage.presaveDocumentHandler({path:{document_id:this.id},body:{newBom:$}})).data}async save($){return(await this.mutate((O)=>O.storage.saveDocumentHandler({path:{document_id:this.id},body:$}))).data}async simpleSave(){return(await this.mutate(($)=>$.storage.simpleSave({path:{document_id:this.id}}))).data}messageThreadById($){return L$.byId(this.client,{type:"document",entity:this},$)}timelinePage($){return b$(this.client,{type:"document",entity:this},(O)=>l$.from(this.client,this.id,O),$)}access=new $$(this.client,"document",this);async fetch(){let{data:$}=Q(await this.client.storage.getDocument({path:{document_id:this.id}}));return $.documentMetadata}static byId($,O){return new w($,O)}static async create($,O){let{documentId:j}=Q(await $.storage.createMarkdownHandler({body:{documentName:O.name,markdown:O.markdown??null,projectId:O.project?.id??null}}));return new w($,j)}static async createSnippet($,O){let{documentId:j}=Q(await $.storage.createSnippetHandler({body:{snippetName:O.name,markdown:O.markdown??null,projectId:O.project?.id??null}}));return new w($,j)}static async createSkill($,O){let{documentId:j}=Q(await $.storage.createSkillHandler({body:{skillName:O.name,markdown:O.markdown??null,projectId:O.project?.id??null}}));return new w($,j)}static recent($,O){let j=O?.pageSize??50;return c(async(x)=>{let S=Q(await $.storage.getUserDocumentsHandler({query:{limit:j,offset:x?Number(x):0,...O?.fileType!==void 0?{file_type:O.fileType}:{}}})),K=S.data?.next_offset;return{items:(S.data?.documents??[]).map((Z)=>new w($,Z.documentId)),nextCursor:K!=null?String(K):null}})}static async recentlyDeleted($){let{data:O}=Q(await $.storage.recentlyDeleted({}));return O.items.filter((j)=>j.type==="document").map((j)=>new 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",($)=>C.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:$}=Q(await this.client.storage.getDocumentTextContent({path:{document_id:this.id}}));if($!==null)return $;let{presigned_url:O}=Q(await this.client.storage.exportDocument({path:{document_id:this.id}})),j=await fetch(O);if(!j.ok)throw new e$(j.status,{message:"failed to download document content"});return j.text()}async rename($){await this.mutate((O)=>O.storage.editDocument({path:{document_id:this.id},body:{documentName:$}}))}async move($){await this.mutate((O)=>O.storage.editDocument({path:{document_id:this.id},body:{projectId:$?.id??""}}))}async delete($){await this.mutate((O)=>$?.permanent?O.storage.permanentlyDeleteDocument({path:{document_id:this.id}}):O.storage.deleteDocument({path:{document_id:this.id}}))}async restore(){await this.mutate(($)=>$.storage.revertDeleteDocument({path:{document_id:this.id}}))}async copy($){let{data:O}=Q(await this.client.storage.copyDocument({path:{document_id:this.id},query:$.versionId!==void 0?{version_id:$.versionId}:void 0,body:{documentName:$.name}}));return new w(this.client,O.documentMetadata.documentId)}async comments(){let $={parent_type:"document",parent_id:this.id},O=c(async(x)=>{let S=Q(await this.client.storage.messageTimeline({path:$,query:{selection:JSON.stringify({limit:100,cursor:x})}}));return{items:S.items,nextCursor:S.next_cursor}}),j=[];for await(let x of O)j.push(x);return cO(j,P5,async(x)=>{let{state:S,root:K,replies:Z}=Q(await this.client.storage.entityMessageGetThread({path:{...$,id:x.id}}));return{thread:S,comments:[K,...Z].map((X)=>l$.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 l$.from(this.client,this.id,j)}async shortId(){return Q(await this.client.storage.getDocumentShortId({path:{document_id:this.id}}))}async teamShare(){return Q(await this.client.storage.getDocumentTeamShare({path:{document_id:this.id}}))}async setTeamShare($){await this.mutate((O)=>O.storage.setDocumentTeamShare({path:{document_id:this.id},body:{shareWithTeam:$}}))}async githubPullRequests(){let{pullRequests:$}=Q(await this.client.storage.getDocumentGithubPullRequests({path:{document_id:this.id}}));return $}async branchName(){let{branchName:$}=Q(await this.client.storage.getDocumentBranchName({path:{document_id:this.id}}));return $}webUrl(){return`${this.client.webAppUrl}/app/md/${this.id}`}static search=x$({filters:{document_filters:{}},type:"document",make:($,O)=>new w($,O.document_id)});toMention(){let $=this.detail.peek();return{tag:o$("m-document-mention",{documentId:this.id,documentName:$?.documentName??"",blockName:$?.fileType??"md"}),mention:{entity_type:"document",entity_id:this.id}}}}class Fj{id;name;constructor($,O){this.id=$;this.name=O}static async list($){let{skills:O}=Q(await $.storage.getSystemSkillsHandler());return O.map((j)=>new Fj(j.id,j.name))}}class Bx{client;async byTeamSlug($){let O=Q(await this.client.storage.getDocumentByTeamSlug({path:{slug:$}}));if(typeof O!=="object"||O===null||!("data"in O)||typeof O.data!=="object"||O.data===null||!("documentMetadata"in O.data)||typeof O.data.documentMetadata!=="object"||O.data.documentMetadata===null||!("documentId"in O.data.documentMetadata)||typeof O.data.documentMetadata.documentId!=="string")throw Error("Invalid team task document response");return w.byId(this.client,O.data.documentMetadata.documentId)}async validatePermissionsToken($){let O=Q(await this.client.storage.validateDocumentPermissionsToken({body:{token:$}}));return{document:w.byId(this.client,O.document_id),user:O.user_id?C.byId(this.client,O.user_id):void 0,accessLevel:O.access_level,expiresAt:O.exp,issuer:O.iss}}async createUpload($){let O={documentName:$.name,sha:$.sha,fileType:$.fileType,mimeType:$.mimeType,projectId:$.project?.id,teamId:$.team?.id,branchedFromId:$.branchedFrom?.id,emailAttachmentId:$.attachment?.id,isTask:$.isTask},j=Q(await this.client.storage.createDocument({body:O})).data;return{document: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=Q(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 Fj.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 A{async fetch(){let{attachment:$}=Q(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:$}=Q(await this.client.email.getAttachmentDocumentId({path:{id:this.id}}));return w.byId(this.client,$)}}class z$ extends K${access=new $$(this.client,"email_thread",this);async followup(){return Q(await this.client.storage.getEmailFollowup({path:{thread_id:this.id}}))}async setFollowup($){return Q(await this.client.storage.setEmailFollowup({path:{thread_id:this.id},body:$}))}async calendarInvitations(){return Q(await this.client.email.getThreadCalendarInvitations({path:{thread_id:this.id}}))}async addEventToCalendar($,O,j={}){let x=Q(await this.client.email.copyThreadCalendarInvitation({path:{thread_id:this.id,message_id:$.id,invitation_id:O.id},body:{calendarId:j.calendar?.id}}));return S$.fromRecord(this.client,x)}async readReceipts(){let{receipts:$}=Q(await this.client.email.getThreadReadReceipts({path:{thread_id:this.id}}));return $.map((O)=>({message:U$.byId(this.client,O.message_id),openCount:O.open_count,firstOpenedAt:O.first_opened_at??void 0,lastOpenedAt:O.last_opened_at??void 0}))}async update($){await this.mutate((O)=>O.storage.editThreadV2({path:{thread_id:this.id},body:{projectId:$.project===void 0?void 0:$.project?.id??null,sharePermission:$.sharePermission?$O($.sharePermission):void 0}}))}entityType="email_thread";propertyEntityType="THREAD";async fetch(){let{thread:$}=Q(await this.client.email.getThread({path:{thread_id:this.id},query:{limit:100}}));return $}static byId($,O){return new z$($,O)}createdAt=this.field("created_at");updatedAt=this.field("updated_at");isRead=this.field("is_read");inboxVisible=this.field("inbox_visible");accessLevel=this.field("access_level");providerId=this.field("provider_id");link=this.mappedField("link_id",($)=>R$.byId(this.client,$));project=this.mappedField("project_id",($)=>$?n.byId(this.client,$):void 0);latestInboundAt=this.field("latest_inbound_message_ts");latestOutboundAt=this.field("latest_outbound_message_ts");latestNonSpamAt=this.field("latest_non_spam_message_ts");async subject(){let{messages:$}=await this.detail.get();for(let O of $)if(O.subject)return O.subject;return}async participants(){let{messages:$}=await this.detail.get(),O=new Map;for(let j of $)for(let x of[j.from,...j.to,...j.cc,...j.bcc])if(x&&!O.has(x.email))O.set(x.email,x);return[...O.values()]}async messages($){return Q(await this.client.email.getThreadMessagesHandler({path:{id:this.id},query:{...$?.since?{since:$.since}:{},...$?.limit?{limit:$.limit}:{}}})).map((j)=>U$.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?U$.byId(this.client,j.db_id):void 0}async archive($=!0){await this.mutate((O)=>O.email.archiveThread({path:{id:this.id},body:{value:$}}))}static async archiveMany($,O,j=!0){let x=[];for(let S=0;S<O.length;S+=100){let K=O.slice(S,S+100),Z=Q(await $.email.archiveThreads({body:{thread_ids:K.map((Y)=>Y.id),value:j}})),X=new Set(Z.failed_thread_ids);for(let Y of K)if(Y.detail.clear(),X.has(Y.id))x.push(Y)}return x}async updateState($){await this.mutate((O)=>O.email.updateThreadState({path:{id:this.id},body:$}))}async operations(){return Q(await this.client.email.threadOperations({path:{id:this.id}}))}async markSeen(){await this.mutate(($)=>$.email.threadSeen({path:{id:this.id}}))}async addLabel($){await this.mutate((O)=>O.email.addRemoveThreadLabel({path:{id:this.id},body:{label_id:$.id,value:!0}}))}async removeLabel($){await this.mutate((O)=>O.email.addRemoveThreadLabel({path:{id:this.id},body:{label_id:$.id,value:!1}}))}async moveToProject($){await this.mutate((O)=>O.email.updateThreadProject({path:{thread_id:this.id},body:{projectId:$?.id??null}}))}static search=x$({filters:{email_filters:{}},type:"email",make:($,O)=>new z$($,O.thread_id)})}class U$ extends A{async fetch(){return Q(await this.client.email.getMessage({path:{id:this.id}}))}static byId($,O){return new U$($,O)}static from($,O){return new U$($,O.db_id,O)}static async send($,O){let{message:j}=Q(await $.email.sendMessage({body:{message:{to:O.to,cc:O.cc??null,bcc:O.bcc??null,subject:O.subject,body_text:O.bodyText}}}));return j.db_id?U$.byId($,j.db_id):void 0}subject=this.field("subject");from=this.field("from");to=this.field("to");cc=this.field("cc");bcc=this.field("bcc");body=this.field("body_parsed");sentAt=this.field("internal_date_ts");labels=this.field("labels");link=this.mappedField("link_id",($)=>R$.byId(this.client,$));async operationStatus(){return Q(await this.client.email.messageOperationStatus({path:{id:this.id}}))}async resolveOperation($){await this.mutate((O)=>O.email.resolveMessageOperation({path:{id:this.id},body:$}))}async completeDraftAttachment($,O=0){let j=await this.link();await this.mutate((x)=>x.email.completeDraftAttachment({path:{id:this.id,attachment_id:$},query:{draft_generation:O},headers:{"X-Email-Link-Id":j.id}}))}async transferDraft($){let O=await this.detail.get();return this.mutate((j)=>j.email.transferDraft({path:{id:this.id},body:{...$,draft_generation:$.draft_generation??O.draft_generation??0},headers:{"X-Email-Link-Id":O.link_id}}))}async addLabel($){await this.mutate((O)=>O.email.addRemoveLabel({body:{label_id:$.id,message_ids:[this.id],value:!0}}))}async removeLabel($){await this.mutate((O)=>O.email.addRemoveLabel({body:{label_id:$.id,message_ids:[this.id],value:!1}}))}async thread(){return z$.byId(this.client,(await this.detail.get()).thread_db_id)}async downloadEml(){return Q(await this.client.email.getMessageEml({path:{id:this.id},parseAs:"blob"}))}}class BO extends U${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:{...Lx($),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 Lx($){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),(G)=>String.fromCharCode(G)).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 A{inbox;constructor($,O,j,x){super($,O,j);this.inbox=x}get headers(){return this.inbox?{"X-Email-Link-Id":this.inbox.id}:void 0}static byId($,O,j){return new LO($,O,void 0,j)}static from($,O,j){return new LO($,O.id,O,j)}async fetch(){let $=Q(await this.client.email.listEmailFilters({headers:this.headers})).filters.find((O)=>O.id===this.id);if(!$)throw new E(`Email filter ${this.id} is unavailable`);return $}emailAddress=this.field("email_address");emailDomain=this.field("email_domain");isImportant=this.field("is_important");async setImportant($){let O=await this.detail.get();await this.mutate((j)=>j.email.upsertEmailFilter({headers:this.headers,body:{email_address:O.email_address,email_domain:O.email_domain,is_important:$}}))}async delete(){await this.mutate(($)=>$.email.deleteEmailFilter({path:{id:this.id},headers:this.headers}))}}class xO extends A{async fetch(){let{labels:$}=Q(await this.client.email.listLabels()),O=$.find((j)=>j.id===this.id);if(!O)throw new E(`label ${this.id} not found`);return O}static byId($,O){return new xO($,O)}static async list($){let{labels:O}=Q(await $.email.listLabels());return O.map((j)=>new xO($,j.id,j))}static async create($,O){let{label:j}=Q(await $.email.createLabel({body:{label_name:O}}));if(!j.id)throw new f("created label has no id");return new xO($,j.id)}async delete(){Q(await this.client.email.deleteLabel({path:{id:this.id}}))}name=this.field("name");linkId=this.field("linkId");type=this.field("type");createdAt=this.field("createdAt");labelListVisibility=this.field("labelListVisibility");messageListVisibility=this.field("messageListVisibility")}class Nx{client;async createDraft($,O){let j=Q(await this.client.email.createDraft({body:{draft:Lx($)},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=Q(await this.client.email.getScheduledMessages({query:{offset:x,limit:j},headers:$?.inbox?{"X-Email-Link-Id":$.inbox.id}:void 0}));for(let K of S.messages)yield BO.byId(this.client,K.db_id);if(S.messages.length<j)return}}async filters($){return Q(await this.client.email.listEmailFilters({headers:$?{"X-Email-Link-Id":$.id}:void 0})).filters.map((O)=>LO.from(this.client,O,$))}async upsertFilter($,O){return LO.from(this.client,Q(await this.client.email.upsertEmailFilter({headers:O?{"X-Email-Link-Id":O.id}:void 0,body:{email_address:$.emailAddress,email_domain:$.emailDomain,is_important:$.isImportant}})).filter,O)}async contacts(){return Q(await this.client.email.listContacts()).contacts}reminders($){let{inboxes:O,...j}=$??{};return c(async(x)=>{let S=Q(await this.client.storage.listEmailReminders({query:{...j,inboxIds:O?.map((K)=>K.id),cursor:x}}));return{items:S.items.map(({threadId:K,...Z})=>({...Z,thread:z$.byId(this.client,K)})),nextCursor:S.nextCursor}})}constructor($){this.client=$}byId($){return z$.byId(this.client,$)}message($){return U$.byId(this.client,$)}attachment($){return WO.byId(this.client,$)}link($){return R$.byId(this.client,$)}links(){return R$.list(this.client)}async connectionProviders(){return Q(await this.client.auth.emailConnectionProviders())}async recoverDraftTransfer($){return Q(await this.client.email.recoverDraftTransfer({path:{id:$}}))}send($){return U$.send(this.client,$)}search($,O){return z$.search(this.client,$,O)}inbox($){return c(async(O)=>{let j=Q(await this.client.email.previewsInboxCursor({path:{view:"inbox"},query:{...$?.pageSize?{limit:$.pageSize}:{},...$?.sort?{sort_method:$.sort}:{},...O?{cursor:O}:{}}}));return{items:j.items.map((x)=>z$.byId(this.client,x.id)),nextCursor:j.next_cursor}})}label($){return xO.byId(this.client,$)}labels(){return xO.list(this.client)}createLabel($){return xO.create(this.client,$)}archive($,O=!0){return z$.archiveMany(this.client,$,O)}async deleteLabel($){Q(await this.client.email.deleteLabel({path:{id:$.id}}))}async blockSender($){Q(await this.client.email.blockSender({body:{email_address:$}}))}async unblockSender($){Q(await this.client.email.unblockSender({body:{email_address:$}}))}async blockedSenders(){return Q(await this.client.email.listBlockedSenders()).blocked_emails}}class TO{client;id;constructor($,O){this.client=$;this.id=O}static byId($,O){return new TO($,O)}async delete(){Q(await this.client.storage.deleteEntityMention({path:{mention_id:this.id}}))}toJSON(){return{id:this.id}}}class Ux{client;constructor($){this.client=$}byId($){return TO.byId(this.client,$)}async create($,O){let j=Q(await this.client.storage.createEntityMention({body:{source_entity_id:$.entity.id,source_entity_type:$.type,entity_id:O.entity.id,entity_type:O.type}}));return TO.byId(this.client,j.id)}}function zx($,O){return{chat:NO.byId($,O.id),name:O.name,announcements:O.announcements}}class NO extends A{static byId($,O){return new NO($,O)}static from($,O){return new NO($,O.jid,O)}async fetch(){let{chats:$}=Q(await this.client.storage.whatsappChats()),O=$.find((j)=>j.jid===this.id);if(!O)throw new E("WhatsApp chat is not available");return O}kind=this.field("kind");name=this.field("name");phoneNumber=this.field("phoneNumber");lastActivityAt=this.field("lastActivityAt");archived=this.field("archived");pinned=this.field("pinned");canAdd=this.field("canAdd");cannotAddReason=this.field("cannotAddReason");community=this.mappedField("community",($)=>$?zx(this.client,$):void 0);added=this.mappedField("added",($)=>$?g$.byId(this.client,$.id):void 0);shared=this.mappedField("shared",($)=>$?g$.byId(this.client,$.id):void 0);async add(){let $=await this.kind(),O=await this.mutate((j)=>j.storage.externalChatAdd({body:{provider:"whatsapp",remoteId:this.id,kind:$}}));return g$.byId(this.client,O.chatId)}async refresh(){return this.detail.clear(),await this.detail.get(),this}}class M$ extends A{chat;constructor($,O,j,x){super($,j,x);this.chat=O}static byId($,O,j){return new M$($,O,j)}static from($,O,j){return new M$($,O,j.id,j)}async fetch(){return Q(await this.client.storage.externalChatMessage({path:{chat_id:this.chat.id,message_id:this.id}}))}body=this.field("body");sender=this.field("sender");sentAt=this.field("sentAt");editedAt=this.field("editedAt");deleted=this.field("deleted");reactions=this.field("reactions");deliveryState=this.field("deliveryState");kind=this.field("kind");forwarded=this.field("forwarded");viewOnce=this.field("viewOnce");mentions=this.field("mentions");rich=this.field("rich");replyTo=this.mappedField("replyTo",($)=>$?M$.byId(this.client,this.chat,$):void 0);attachments=this.mappedField("attachments",($)=>$.map((O)=>({ordinal:O.ordinal,state:O.state,fileName:O.fileName,mime:O.mime,size:O.size,width:O.width??void 0,height:O.height??void 0,durationSeconds:O.durationSeconds??void 0,presentation:O.presentation??void 0,url:O.fileId?`${this.client.hosts["static-files"]}/file/${O.fileId}`:void 0})))}class SO{chat;id;record;constructor($,O,j){this.chat=$;this.id=O;this.record=j}static byId($,O){return new SO($,O)}static from($,O){return new SO($,O.jid,O)}get displayName(){return this.record?.displayName??void 0}get mentionToken(){return this.id.split("@")[0]??this.id}get admin(){return this.record?.admin}toJSON(){return{id:this.id,chat:this.chat.id,displayName:this.displayName,admin:this.admin}}}class ZO{id;chat;filename;kind;constructor($,O,j,x){this.id=$;this.chat=O;this.filename=j;this.kind=x}static byId($,O){return new ZO(O,$)}static from($,O){return new ZO(O.uploadId,$,O.filename,O.kind)}toJSON(){return{id:this.id,chat:this.chat.id,filename:this.filename,kind:this.kind}}}class XO extends A{chat;constructor($,O,j,x){super($,j,x);this.chat=O}static byId($,O,j){return new XO($,O,j)}static from($,O,j){return new XO($,O,j.id,j)}async fetch(){let O=Q(await this.client.storage.externalChatDelivery({path:{chat_id:this.chat.id},body:[this.id]})).find((j)=>j.id===this.id);if(!O)throw new E("External chat send is not available");return O}state=this.field("state");errorCode=this.field("errorCode");createdAt=this.field("createdAt");message=this.mappedField("messageId",($)=>$?M$.byId(this.client,this.chat,$):void 0);async request(){let{payload:$}=await this.detail.get(),O=$.message,j=k(O).returnType().with({type:"media"},(x)=>({type:"media",upload:ZO.byId(this.chat,x.uploadId),caption:x.caption??void 0})).with({type:"mutation"},(x)=>({type:"mutation",message:M$.byId(this.client,this.chat,x.messageId),operation:x.operation,text:x.text??void 0})).with({type:"text"},(x)=>({type:"text",text:x.text,mentions:(x.mentions??[]).map((S)=>SO.byId(this.chat,S))})).exhaustive();return{idempotencyKey:$.idempotencyKey,message:j,replyTo:$.replyTo?M$.byId(this.client,this.chat,$.replyTo):void 0}}async refresh(){return this.detail.clear(),await this.detail.get(),this}}class g$ extends H${entityType="external_chat";static byId($,O){return new g$($,O)}async fetch(){return Q(await this.client.storage.externalChat({path:{chat_id:this.id}}))}provider=this.field("provider");name=this.field("name");kind=this.field("kind");canSend=this.field("canSend");sendReason=this.field("sendReason");sendingIdentity=this.field("sendingIdentity");unreadCount=this.field("unreadCount");backfill=this.field("backfill");limits=this.field("limits");members=this.field("members");participants=this.mappedField("members",($)=>($?.participants??[]).map((O)=>SO.from(this,O)));disappearingSeconds=this.field("disappearingSeconds");owner=this.mappedField("userId",($)=>C.byId(this.client,$));async community(){let{provider:$,community:O}=await this.detail.get();if(!O)return;return k($).with("whatsapp",()=>zx(this.client,O)).exhaustive()}async*messages($={}){yield*c(async(O)=>{let j=Q(await this.client.storage.externalChatMessages({path:{chat_id:this.id},query:{before:O,limit:$.limit}}));return{items:j.messages.map((x)=>M$.from(this.client,this,x)),nextCursor:j.nextCursor}})}async markRead($){this.assertChat($.chat),await this.mutate((O)=>O.storage.externalChatRead({path:{chat_id:this.id},body:{messageId:$.id}}))}async permissions(){return Q(await this.client.storage.externalChatPermissions({path:{chat_id:this.id}}))}async updatePermissions($){await this.mutate((O)=>O.storage.externalChatUpdatePermissions({path:{chat_id:this.id},body:$}))}async remove(){await this.mutate(($)=>$.storage.externalChatRemove({path:{chat_id:this.id}}))}async upload($){let O=Q(await this.client.storage.externalChatUpload({path:{chat_id:this.id},body:{file:$}}));return ZO.from(this,O)}async send($,O){if(O.replyTo)this.assertChat(O.replyTo.chat);let j=k($).returnType().with({type:"text"},(S)=>{let K=S.mentions??[];for(let Z of K)this.assertChat(Z.chat);return{type:"text",text:S.text,mentions:K.map((Z)=>Z.id)}}).with({type:"media"},(S)=>{return this.assertChat(S.upload.chat),{type:"media",uploadId:S.upload.id,caption:S.caption}}).with({type:"mutation"},(S)=>{return this.assertChat(S.message.chat),{type:"mutation",messageId:S.message.id,operation:S.operation,text:S.text}}).exhaustive(),x=await this.mutate((S)=>S.storage.externalChatSend({path:{chat_id:this.id},body:{idempotencyKey:O.idempotencyKey,message:j,replyTo:O.replyTo?.id}}));return XO.from(this.client,this,x)}async sends(){return Q(await this.client.storage.externalChatSends({path:{chat_id:this.id}})).map(($)=>XO.from(this.client,this,$))}async delivery($){for(let O of $)this.assertChat(O.chat);return Q(await this.client.storage.externalChatDelivery({path:{chat_id:this.id},body:$.map((O)=>O.id)})).map((O)=>XO.from(this.client,this,O))}async messageAttachments($){for(let O of $)this.assertChat(O.chat);return Q(await this.client.storage.externalChatMessageAttachments({path:{chat_id:this.id},body:$.map((O)=>O.id)})).map((O)=>({message:M$.byId(this.client,this,O.messageId),attachments:O.attachments.map((j)=>({ordinal:j.ordinal,state:j.state,fileName:j.fileName,mime:j.mime,size:j.size,url:j.fileId?`${this.client.hosts["static-files"]}/file/${j.fileId}`:void 0}))}))}async refresh(){return this.detail.clear(),await this.detail.get(),this}assertChat($){if($.id!==this.id)throw Error("External chat reference belongs to another chat")}}class Ix{client;constructor($){this.client=$}async list(){return Q(await this.client.storage.externalChats()).map(($)=>g$.byId(this.client,$.id))}byId($){return g$.byId(this.client,$)}}class Hx{client;constructor($){this.client=$}async list($={}){let{favorites:O}=Q(await this.client.storage.listFavorites({query:{entityType:$.entityTypes,entityId:$.entityIds}}));return O}async add($){return Q(await this.client.storage.addFavorite({body:{entityId:$.id,entityType:$.entityType}}))}async remove($){Q(await this.client.storage.removeFavoriteByEntity({path:{entity_type:$.entityType,entity_id:$.id}}))}async reorder($){Q(await this.client.storage.reorderFavorites({body:{favorites:$}}))}}class KO extends H${entityType="foreign_entity";async fetch(){return Q(await this.client.storage.getForeignEntity({path:{id:this.id}}))}static byId($,O){return new KO($,O)}static fromRecord($,O){return new KO($,O.id,O)}foreignEntityId=this.field("foreignEntityId");source=this.field("foreignEntitySource");storedForId=this.field("storedForId");storedForAuthEntity=this.field("storedForAuthEntity");createdAt=this.field("createdAt");updatedAt=this.field("updatedAt");async metadata(){return(await this.detail.get()).metadata}}function Z2({login:$,...O}){return{...O,login:$??void 0}}class Tx{client;constructor($){this.client=$}byId($){return KO.byId(this.client,$)}async bySource($,O){return KO.fromRecord(this.client,Q(await this.client.storage.getForeignEntityBySource({path:{source:$,foreign_entity_id:O}})))}async githubPullRequestFacets(){let{repositories:$,authors:O,assignees:j,labels:x}=Q(await this.client.storage.getGithubPullRequestFacets());return{repositories:$,authors:O.map(Z2),assignees:j.map(Z2),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 F$.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 W$(()=>this.load(),j)}async load(){let $=await this.form.myResponse();if($.kind==="anonymous"||$.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 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 Ej{entityType;id;constructor($,O){this.entityType=$;this.id=O}static byId($,O){return new Ej($,O)}}class y$ extends A{async fetch(){return Q(await this.client.storage.getForm({path:{id:this.id}}))}static byId($,O){return new y$($,O)}static async create($,O){let j=Q(await $.storage.createForm({body:{name:O.name,source:O.table?{kind:"table",databaseId:O.table.database.id,tableId:O.table.id}:{kind:"new"}}}));return new y$($,j.form.id,j)}static async list($,O){if(!O)return Q(await $.storage.listAccessibleForms()).map(({form:S})=>new y$($,S.id));return Q(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",($)=>C.byId(this.client,$.ownerId));database=this.mappedField("form",($)=>Q$.byId(this.client,$.databaseId));table=this.mappedField("form",($)=>V$.byId(Q$.byId(this.client,$.databaseId),$.tableId));audience=this.mappedField("form",($)=>$.audience);status=this.mappedField("form",($)=>$.status);closesAt=this.mappedField("form",($)=>$.closesAt??void 0);access=this.field("access");async sections(){return(await this.detail.get()).sections.map(($)=>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)=>k(X).with({kind:"group"},(Y)=>({kind:"group",...x(Y)})).with({kind:"condition"},(Y)=>({kind:"condition",column:j(Y.column),test:k(Y.test).with({kind:"options"},(L)=>({...L,options:L.options.map((G)=>G.id)})).with({kind:"entities"},(L)=>({...L,entities:L.entities.map((G)=>G.id)})).with({kind:t.union("presence","text","number","date","dateRange","checkbox")},(L)=>L).exhaustive()})).exhaustive())}),S={sections:$.map((Z)=>{if(Z.section)this.assertOwns(Z.section);let X={id:Z.section?.id??c$(),title:Z.title,description:Z.description??""};return k(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??c$(),column:j(L.column),helpText:L.helpText??"",required:L.required??!1,widget:L.widget??null}})})).exhaustive()})},K=await this.mutate((Z)=>Z.storage.putFormLayout({path:{id:this.id},body:S}));return{form:this,publicationError:K.publicationError}}wireAnswers($){return $.map(({question:O,value:j})=>{this.assertOwns(O);let x=k(j).with({type:"rows"},(S)=>({type:"rows",value:S.value.map((K)=>K.id)})).with({type:"options"},(S)=>({type:"options",value:S.value.map((K)=>{if(K.question.id!==O.id||K.question.form.id!==this.id)throw new f("option does not belong to the answered question");return{id:K.id}})})).with({type:"entities"},(S)=>({type:"entities",value:S.value.map(({entityType:K,entity:Z})=>({entityType:K,entityId:Z.id}))})).with({type:t.union("text","number","boolean","date","date_range","link","clear")},(S)=>S).exhaustive();return{question:O.id,value:x}})}unlockedBooking($){return $?{...$,section:p$.byId(this,$.section)}:void 0}async outcome($,O){return k($).with({outcome:"stopped"},(j)=>({...j,section:p$.byId(this,j.section)})).with({outcome:"submitted"},async(j)=>{let x=E$.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(Q(await this.client.storage.submitFormResponse({path:{id:this.id},body:O})),$)}async editResponse($){let O={answers:this.wireAnswers($)};return this.outcome(Q(await this.client.storage.editMyFormResponse({path:{id:this.id},body:O})),$)}async myResponse(){let $=Q(await this.client.storage.getMyFormResponse({path:{id:this.id}}));if($.kind==="anonymous")return{kind:"anonymous"};let O=await this.table(),j=await Promise.all($.answers.map(async(K)=>{let Z=r$.byId(this,K.question),X=await k(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:Ej.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 G=V$.byId(Q$.byId(this.client,L.kind.database),L.kind.table);return{type:"rows",value:Y.value.map((J)=>E$.byId(G,J))}}).with({type:t.union("text","number","boolean","date","date_range","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?E$.byId(O,$.response.row):void 0,S=this.unlockedBooking($.booking);return{kind:"saved",...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 $=Q(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 Q(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)=>k(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 Q(await this.client.storage.getFormPermissions({path:{id:this.id}}))}updateSharePermissions($){return this.mutate((O)=>O.storage.updateFormPermissions({path:{id:this.id},body:$}))}webUrl(){return`${this.client.webAppUrl}/app/form/${this.id}`}respondUrl(){return`${this.client.webAppUrl}/app/form/${this.id}/respond`}}class Rx{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 A{static byId($,O){return new DO($,O)}async fetch(){return Q(await this.client.storage.getGithubPullRequest({path:{id:this.id}}))}title=this.field("title");url=this.field("url");status=this.field("status");async changes(){let $=Q(await this.client.storage.getGithubPullRequestChanges({path:{id:this.id}}));return{changeset:$.changeset?new Dx(this.client,this,$.changeset):void 0,error:$.error??void 0}}}class Dx{client;pullRequest;record;constructor($,O,j){this.client=$;this.pullRequest=O;this.record=j}get id(){return this.record.id}async patch(){return Q(await this.client.storage.getGithubPullRequestChangesPatch({path:{id:this.pullRequest.id},query:{changeset:this.id}})).patch}toJSON(){return{pullRequestId:this.pullRequest.id,...this.record}}}class _x{client;constructor($){this.client=$}byId($){return DO.byId(this.client,$)}forEntity($){return DO.byId(this.client,$.id)}}class _O extends A{static byId($,O){return new _O($,O)}async fetch(){return Q(await this.client.storage.getHarnessPairing({path:{code:this.id}}))}name=this.field("requested_name");expiresAt=this.field("expires_at");async approve($){let O={name:$?.name,team_id:$?.team?.id,allow_permission_bypass:$?.allowPermissionBypass};return B$.from(this.client,await this.mutate((j)=>j.storage.approveHarnessPairing({path:{code:this.id},body:O})))}}class $j{client;id;constructor($,O){this.client=$;this.id=O}static byId($,O){return new $j($,O)}async claim($){let O=Q(await this.client.storage.claimHarnessPairing({path:{pairing_id:this.id},body:{device_secret:$}}));return"harness"in O?{harness:B$.from(this.client,O.harness),token:O.token}:void 0}toJSON(){return{id:this.id}}}class Mx{client;constructor($){this.client=$}byId($){return B$.byId(this.client,$)}async list(){return Q(await this.client.storage.listHarnesses()).map(($)=>B$.from(this.client,$))}async me(){return B$.from(this.client,Q(await this.client.storage.getSelfHarness()))}async deleteSelf(){Q(await this.client.storage.deleteSelfHarness())}async agents(){return Q(await this.client.storage.listHarnessAgents()).map(($)=>T$.byId(this.client,$.bot_id))}async sessions(){return Q(await this.client.storage.listHarnessSessions()).map(($)=>d.byId(this.client,$.session_id))}pairing($){return _O.byId(this.client,$)}async createPairing($){let O=Q(await this.client.storage.createHarnessPairing({body:$}));return{pairing:_O.byId(this.client,O.code),device:$j.byId(this.client,O.pairing_id),deviceSecret:O.device_secret,expiresAt:O.expires_at,pollIntervalSeconds:O.poll_interval_seconds}}}class qj{id;url;width;height;constructor($,O,j,x){this.id=$;this.url=O;this.width=j;this.height=x}static byId($,O,j){return new qj(O,`${$.hosts["static-files"]}/file/${O}`,j?.width,j?.height)}toJSON(){return{id:this.id,url:this.url,width:this.width,height:this.height}}}class wj extends qj{width;height;mimeType;sizeBytes;note;constructor($,O,j,x,S,K,Z){super($,O,j,x);this.width=j;this.height=x;this.mimeType=S;this.sizeBytes=K;this.note=Z}toJSON(){return{...super.toJSON(),mimeType:this.mimeType,sizeBytes:this.sizeBytes,note:this.note}}}class Cx{client;constructor($){this.client=$}async generate($){let O=Q(await this.client.cognition.generateImage({body:{prompt:$.prompt,aspectRatio:$.aspectRatio??null,referenceImages:($.referenceImages??[]).map(F5)}}));return new wj(O.staticFileId,O.url,O.width,O.height,O.mimeType,O.sizeBytes,O.note??void 0)}}function F5($){return $ instanceof w?{type:"document",id:$.id}:{type:"staticFile",id:$.id}}var E5="00000001-0000-0000-0000-000000000001",X2="00000001-0000-0000-0000-000000000002",q5="00000001-0000-0000-0000-000000000004",w5="00000001-0000-0000-0000-000000000014",f5="00000001-0000-0000-0002-000000000001",b5="00000001-0000-0000-0002-000000000004";function k5($){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 G$ extends w{static byId($,O){return new G$($,O)}static async create($,O){let{documentId:j}=Q(await $.storage.createTaskHandler({body:{taskName:O.name,markdown:O.markdown??null,projectId:O.project?.id??null,teamId:O.team?.id??null,shareWithTeam:O.shareWithTeam??!0,propertyValues:await g5($,O)}}));return new G$($,j)}static async summaries($,O){if(O.length===0)return[];let{previews:j}=Q(await $.storage.getBatchPreviewHandler({body:{document_ids:O.map((S)=>S.id)}})),x=new Map(j.flatMap((S)=>S.type==="access"?[[S.document_id,S]]:[]));return O.flatMap((S)=>{let K=x.get(S.id);if(!K)return[];return[{task:S,name:K.document_name,owner:C.byId($,K.owner),updatedAt:K.updated_at??void 0,completed:K.sub_type?.type==="task"&&K.sub_type.is_completed}]})}static async findSimilar($,O){let{results:j}=Q(await $.storage.taskSimilaritySearchHandler({body:{taskName:O.title,markdown:O.body??null}}));return j.map((x)=>({task:new G$($,x.taskId),name:x.taskName,similarity:x.vectorScore}))}static async forPullRequest($,O){let j=k5(O),{pullRequests:x}=Q(await $.storage.getGithubPullRequestTasks({body:{githubKeys:[j]}}));return(x[0]?.taskIds??[]).map((S)=>new G$($,S))}async completed(){let{subType:$}=await this.detail.get();if($!=="task")return;let j=(await this.properties()).find((x)=>x.definition.id===X2)?.value;return j?.type==="SelectOption"&&j.value.includes(b5)}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 G$($,O.document_id)})}async function g5($,O){if(!O.initiative&&!O.assignees&&!O.dueDate)return null;let j=O.assignees??[await C.me($)],x=[{propertyId:X2,value:{type:"select_option",option_id:f5}}];if(j.length>0)x.push({propertyId:E5,value:{type:"multi_entity_reference",references:j.map((S)=>({entity_id:S.id,entity_type:"USER"}))}});if(O.initiative)x.push({propertyId:w5,value:{type:"entity_reference",reference:{entity_id:O.initiative.id,entity_type:"INITIATIVE"}}});if(O.dueDate)x.push({propertyId:q5,value:{type:"date",value:O.dueDate.toISOString()}});return x}class a$ extends A{access=new $$(this.client,"initiative",this);static byId($,O){return new a$($,O)}static from($,O){return new a$($,O.id,O)}async fetch(){return Q(await this.client.storage.getInitiative({path:{initiative_id:this.id}}))}name=this.field("name");owner=this.mappedField("ownerId",($)=>C.byId(this.client,$));members=this.mappedField("memberIds",($)=>$.map((O)=>C.byId(this.client,O)));tasks=this.mappedField("taskIds",($)=>$.map((O)=>G$.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?$O($.sharePermission):void 0}}))}async delete(){await this.mutate(($)=>$.storage.deleteInitiative({path:{initiative_id:this.id}}))}}class Ax{client;constructor($){this.client=$}byId($){return a$.byId(this.client,$)}async list(){return Q(await this.client.storage.listInitiatives()).initiatives.map(($)=>a$.byId(this.client,$.id))}async summaries(){return Q(await this.client.storage.listInitiatives()).initiatives.map(($)=>({initiative:a$.byId(this.client,$.id),name:$.name,updatedAt:$.updatedAt}))}async create($){return a$.from(this.client,Q(await this.client.storage.createInitiative({body:{name:$.name,description:$.description,memberIds:$.members?.map((O)=>O.id),shareWithTeam:$.shareWithTeam,propertyValues:$.propertyValues}})))}}class Px{client;constructor($){this.client=$}byId($){return D$.byId(this.client,$)}async create($){return D$.from(this.client,Q(await this.client.storage.meetingCreate({body:$})))}async list(){return Q(await this.client.storage.meetingList()).meetings.map(($)=>D$.from(this.client,$))}async active(){return Q(await this.client.storage.meetingListActive()).meetings.map(($)=>D$.from(this.client,$))}async lookup($){return D$.from(this.client,Q(await this.client.storage.meetingLookup({path:{token:$}})))}}class zO extends A{async fetch(){return Q(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 c(async(j)=>{let x=Q(await $.notification.listTypedNotifications({query:{...O?.pageSize?{limit:O.pageSize}:{},...O?.states!==void 0?{states:O.states.join(",")}:{},...j?{cursor:j}:{}}}));return{items:x.items.map((S)=>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",($)=>C.byId(this.client,$));sender=this.mappedField("sender_id",($)=>$?C.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 Fx{client;constructor($){this.client=$}byId($){return zO.byId(this.client,$)}list($){return zO.list(this.client,$)}async markSeen($){Q(await this.client.notification.bulkMarkNotificationsSeen({body:{notificationIds:$}}))}async markDone($){Q(await this.client.notification.bulkMarkNotificationsDone({body:{notificationIds:$}}))}async delete($){Q(await this.client.notification.bulkDeleteUserNotificationsV2({body:{notificationIds:$}}))}async preferences(){return Q(await this.client.notification.getNotificationTypePreferences())}async enableType($){Q(await this.client.notification.enableNotificationType({path:{notification_event_type:$}}))}async disableType($){Q(await this.client.notification.disableNotificationType({path:{notification_event_type:$}}))}}class Ex{client;constructor($){this.client=$}async list(){let{data:$}=Q(await this.client.storage.getPinsHandler({}));return $?.recent??[]}async add($,O){Q(await this.client.storage.addPinHandler({path:{pinned_item_id:$.id},body:{pinType:$.entityType,pinIndex:O.index}}))}async remove($){Q(await this.client.storage.removePinHandler({path:{pinned_item_id:$.id},body:{pinType:$.entityType}}))}async reorder($){Q(await this.client.storage.reorderPinsHandler({body:$}))}}class qx{client;constructor($){this.client=$}byId($){return n.byId(this.client,$)}create($){return n.create(this.client,$)}search($,O){return n.search(this.client,$,O)}}class MO{client;definitionId;id;record;constructor($,O,j,x){this.client=$;this.definitionId=O;this.id=j;this.record=x}static from($,O,j){return new MO($,O,j.id,j)}get value(){return this.record.value}get color(){return this.record.color??void 0}get displayOrder(){return this.record.display_order}get createdAt(){return this.record.created_at}get updatedAt(){return this.record.updated_at}async update($){return this.record=Q(await this.client.properties.updatePropertyOption({path:{definition_id:this.definitionId,option_id:this.id},body:$})),this}async delete(){Q(await this.client.properties.deletePropertyOption({path:{definition_id:this.definitionId,option_id:this.id}}))}}class YO{client;id;detail;constructor($,O,j){this.client=$;this.id=O;this.detail=new W$(()=>this.fetch(),j)}async fetch(){return Q(await this.client.properties.getPropertyDefinition({path:{definition_id:this.id}}))}static async create($,O){let j=Q(await $.properties.createPropertyDefinition({body:{display_name:O.displayName,scope:O.scope,data_type:O.dataType}}));return new YO($,j.id,j)}static byId($,O){return new YO($,O)}static fromRecord($,O){return new YO($,O.id,O)}get displayName(){return this.detail.get().then(($)=>$.display_name)}get dataType(){return this.detail.get().then(($)=>$.data_type)}get owner(){return this.detail.get().then(($)=>$.owner)}get isSystem(){return this.detail.get().then(($)=>$.is_system)}get isMultiSelect(){return this.detail.get().then(($)=>$.is_multi_select)}get createdAt(){return this.detail.get().then(($)=>$.created_at)}get updatedAt(){return this.detail.get().then(($)=>$.updated_at)}async delete(){return Q(await this.client.properties.deletePropertyDefinition({path:{definition_id:this.id}}))}async options(){return Q(await this.client.properties.getPropertyOptions({path:{definition_id:this.id}})).map((O)=>MO.from(this.client,this.id,O))}async addOption($){let O=Q(await this.client.properties.addPropertyOption({path:{definition_id:this.id},body:$}));return MO.from(this.client,this.id,O)}async updateOption($,O){let j=Q(await this.client.properties.updatePropertyOption({path:{definition_id:this.id,option_id:$.id},body:O}));return MO.from(this.client,this.id,j)}async deleteOption($){return Q(await this.client.properties.deletePropertyOption({path:{definition_id:this.id,option_id:$.id}}))}}class wx{client;constructor($){this.client=$}async list($){return Q(await this.client.properties.listProperties({query:{scope:$?.scope??"all",...$?.forEntityType!==void 0?{for_entity_type:$.forEntityType}:{}}})).map((j)=>{let x="definition"in j?j.definition:j;return YO.fromRecord(this.client,x)})}create($){return YO.create(this.client,$)}definition($){return YO.byId(this.client,$)}async bulkEntityProperties($){return Q(await this.client.properties.getBulkEntityProperties({body:$}))}async updateEntityPropertyOptions($,O){return Q(await this.client.properties.bulkUpdateEntitiesPropertyOptions({body:{entities:$.map((x)=>x.propertyReference()),property_id:O.property.id,...O.add?{add_option_ids:O.add.map((x)=>x.id)}:{},...O.remove?{remove_option_ids:O.remove.map((x)=>x.id)}:{}}})).results}async addEntityPropertyOption($){return Q(await this.client.properties.addEntityPropertyOption({path:{...$.entity.propertyReference(),property_id:$.property.id,option_id:$.option.id}}))}async removeEntityPropertyOption($){return Q(await this.client.properties.removeEntityPropertyOption({path:{...$.entity.propertyReference(),property_id:$.property.id,option_id:$.option.id}}))}async tags(){return Q(await this.client.properties.listTags({}))}}class fx{client;constructor($){this.client=$}async link(){let $=Q(await this.client.auth.getReferralCode()),O=new URL("/app/signup",this.client.webAppUrl);return O.searchParams.set("referral_code",$),{code:$,url:O.toString()}}async invite($){let O=$.trim();if(!O)throw new f("invite needs an email address");Q(await this.client.auth.sendReferralCode({body:{recipient:O}}))}}function bx($){return k($).with({type:"cron"},(O)=>O).with({type:"events"},(O)=>({type:"events",filters:O.filters.map(({entities:j,...x})=>({...x,ids:j?.map((S)=>S.entity.id)}))})).exhaustive()}function y5($){return k($).with({type:"multiple"},(O)=>({type:"multiple",triggers:O.triggers.map(bx)})).with({type:"cron"},bx).with({type:"events"},bx).exhaustive()}class v$ extends A{static byId($,O){return new v$($,O)}static from($,O){if(!O.id)throw Error("Routine response has no id");return new v$($,O.id,O)}async fetch(){return Q(await this.client.scheduledAction.getScheduledAction({path:{id:this.id}}))}name=this.field("name");trigger=this.field("trigger");enabled=this.field("enabled");runVisibility=this.field("run_visibility");nextRunAt=this.field("next_run_at");revision=this.field("configuration_revision");owner=this.mappedField("owner",($)=>C.byId(this.client,$));sourceTemplate=this.mappedField("template_id",($)=>$?v$.byId(this.client,$):void 0);async template(){let $=await this.client.scheduledAction.getScheduledActionTemplate({path:{id:this.id}});if($.response?.status===404)return;return this.toTemplate(Q($))}async shareAsTemplate($){return this.toTemplate(Q(await this.client.scheduledAction.shareScheduledActionTemplate({path:{id:this.id},body:$})))}async activateTemplate($){return v$.from(this.client,Q(await this.client.scheduledAction.activateScheduledActionTemplate({path:{id:this.id},body:{...fj($),enabled:$.enabled??!0}})))}toTemplate($){return new K2(this,C.byId(this.client,$.author),$)}async stopSharingTemplate(){Q(await this.client.scheduledAction.unshareScheduledActionTemplate({path:{id:this.id}}))}async update($){await this.mutate((O)=>O.scheduledAction.updateScheduledAction({path:{id:this.id},body:fj($)}))}async setEnabled($){await this.mutate((O)=>O.scheduledAction.setScheduledActionEnabled({path:{id:this.id},body:{enabled:$}}))}async execute(){let $=Q(await this.client.scheduledAction.executeScheduledActionNow({path:{id:this.id}}));if($.resource)return k($.resource).with({type:"agent"},(O)=>d.byId(this.client,O.id)).with({type:"chat"},(O)=>Y$.byId(this.client,O.id)).exhaustive();return $.chat_id?Y$.byId(this.client,$.chat_id):void 0}async history(){return Q(await this.client.scheduledAction.listScheduledActionHistory({path:{id:this.id}})).map(($)=>new kx(this,$))}async delete(){await this.mutate(($)=>$.scheduledAction.deleteScheduledAction({path:{id:this.id}}))}}class K2{routine;author;record;constructor($,O,j){this.routine=$;this.author=O;this.record=j}activate($){return this.routine.activateTemplate($)}toJSON(){return this.record}}class kx{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 fj($){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:y5($.trigger),task:{...O}}}class gx{client;constructor($){this.client=$}byId($){return v$.byId(this.client,$)}async create($){return v$.from(this.client,Q(await this.client.scheduledAction.createScheduledAction({body:{...fj($),enabled:$.enabled??!0}})))}async list($){return Q(await this.client.scheduledAction.listScheduledActions({query:{include_events:$?.includeEvents}})).map((O)=>v$.from(this.client,O))}}class yx{client;constructor($){this.client=$}byId($){return G$.byId(this.client,$)}create($){return G$.create(this.client,$)}summaries($){return G$.summaries(this.client,$)}findSimilar($){return G$.findSimilar(this.client,$)}forPullRequest($){return G$.forPullRequest(this.client,$)}search($,O){return G$.search(this.client,$,O)}}class vx{client;constructor($){this.client=$}byId($){return _$.byId(this.client,$)}current(){return _$.current(this.client)}list(){return _$.list(this.client)}}class hx{client;constructor($){this.client=$}async get($){return Q(await this.client.unfurl.getUnfurl({query:{url:$}}))}async bulk($){return Q(await this.client.unfurl.getUnfurlBulk({body:{url_list:$}}))}}class mx{client;constructor($){this.client=$}byId($){return C.byId(this.client,$)}me(){return C.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}=Q(j),S=[...new Set(x)],K=[];for(let Z=0;Z<S.length;Z+=100){let X=S.slice(Z,Z+100),{names:Y}=Q(await this.client.auth.getUserNamesWithEmail({body:{user_ids:X}})),L=new Map(Y.map((G)=>[G.id,G]));for(let G of X){let J=L.get(G)??{id:G};if(`${[J.first_name,J.last_name].filter(Boolean).join(" ")} ${G}`.toLocaleLowerCase().includes(O))K.push(C.fromName(this.client,J))}}return K}}class QO extends A{signingSecret;constructor($,O,j,x){super($,O,j);this.signingSecret=x}async fetch(){return Q(await this.client.storage.getWebhook({path:{webhook_id:this.id}}))}static async create($,O){let j=Q(await $.storage.createWebhook({body:{endpoint_url:O.url,namespace:O.namespace,name:O.name,filters:O.filters,scope:O.scope??"user",...O.headers!==void 0?{headers:O.headers}:{}}}));return new QO($,j.id,j,j.signing_secret)}static byId($,O){return new QO($,O)}static fromRecord($,O){return new QO($,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",($)=>C.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 ux{client;constructor($){this.client=$}create($){return QO.create(this.client,$)}byId($){return QO.byId(this.client,$)}async list(){let{webhooks:$}=Q(await this.client.storage.listWebhooks());return $.map((O)=>QO.fromRecord(this.client,O))}}class CO extends A{static byId($,O){return new CO($,O)}static from($,O){return new CO($,O.id,O)}async fetch(){let{account:$}=Q(await this.client.storage.whatsappAccount());if($?.id!==this.id)throw new E("WhatsApp account is not available");return $}state=this.field("state");identity=this.field("identityJid");owner=this.mappedField("userId",($)=>C.byId(this.client,$));async refresh(){return this.detail.clear(),await this.detail.get(),this}}class cx{client;constructor($){this.client=$}async account(){let{account:$}=Q(await this.client.storage.whatsappAccount());return $?CO.from(this.client,$):void 0}async chats(){return Q(await this.client.storage.whatsappChats()).chats.map(($)=>NO.from(this.client,$))}}function dx($){if("properties"in $.data)return $.data.properties;if($.tag==="calendarEvent")return $.data.extra.properties;return[]}function Y2($,O,j){let x=[];for(let S of dx(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:Y$.byId($,O.data.id),snapshot:O,tags:x,name:O.data.name};case"project":return{type:"project",id:O.data.id,entity:n.byId($,O.data.id),snapshot:O,tags:x,name:O.data.name};case"emailThread":return{type:"email",id:O.data.id,entity:z$.byId($,O.data.id),snapshot:O,tags:x,subject:O.data.name,snippet:O.data.snippet,senderName:O.data.senderName,senderEmail:O.data.senderEmail,inboxVisible:O.data.inboxVisible,isRead:O.data.isRead,isDraft:O.data.isDraft};case"channel":return{type:"channel",id:O.data.channel.id,entity:b.byId($,O.data.channel.id),snapshot:O,tags:x,name:O.data.channel.name};case"channelThread":return{type:"channel_thread",id:O.data.id,entity:new 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:J$.byId($,O.data.callId),snapshot:O,tags:x,createdBy:O.data.createdBy};case"calendarEvent":return{type:"calendar_event",id:O.data.id,entity:S$.byId($,O.data.id),snapshot:O,tags:x,title:O.data.title,status:O.data.status,location:O.data.location,conferenceUrl:O.data.conferenceUrl,conferenceProvider:O.data.conferenceProvider,time:O.data.time};case"foreignEntity":return{type:"foreign_entity",id:O.data.id,entity:KO.byId($,O.data.id),snapshot:O,tags:x,foreignEntityId:O.data.foreignEntityId,foreignEntitySource:O.data.foreignEntitySource,metadata:O.data.metadata};default:throw Error(`Unexpected workspace entity type: ${O.tag}`)}}var Q2="00000000-0000-0000-0000-000000000000",lx={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"]},bj=($)=>$.replace(/[A-Z]/g,(O)=>O.toLowerCase()),G2=($,O)=>$==null?O:{"&":[$,O]};function rx($,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==="!"){rx(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)=>{rx(Z,`${O}.${S}[${X}]`)})}class kj{client;tagSets;constructor($){this.client=$}sets(){return this.tagSets??=this.client.properties.listTags({}).then(Q),this.tagSets}async tagMap(){let $=new Map;for(let O of await this.sets())for(let j of O.options)if(j.value.type==="string")$.set(j.id,{label:j.value.value,scope:O.scope==="user"?"personal":"team"});return $}async body($){for(let[S,K,Z]of[["sortBy",$.sortBy,["recently_viewed","recently_updated","recently_created"]],["emailPreset",$.emailPreset,["signal"]],["tagsMatch",$.tagsMatch,["any","all"]]])if(K!==void 0&&!Z.includes(K))throw Error(`Invalid workspace ${S}: ${K}`);if($.includeTypes!==void 0&&(!Array.isArray($.includeTypes)||$.includeTypes.some((S)=>!Object.hasOwn(lx,S))))throw Error(`Invalid workspace includeTypes. Supported values: ${Object.keys(lx).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)rx($[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:Q2}},favorites_only:$.favoritesOnly,expand:!0,limit:Math.max(1,Math.min(500,Math.trunc($.limit??50))),sort_method:$.sortBy==="recently_viewed"?"viewed_at":$.sortBy==="recently_created"?"created_at":"updated_at",sort_direction:"desc",emailView:$.emailView??"inbox"};if($.emailPreset==="signal")O.ef={"&":[{l:{Importance:!0}},{l:{Shared:"exclude"}}]};let j=$.inbox?.trim();if(j){let{links:S}=Q(await this.client.email.listLinks()),K=S.filter((X)=>bj(X.email_address)===bj(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=G2(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(lx))if(!x.includes(S))O[K]={l:{[Z]:Q2}}}if($.tags?.length){let S=(await this.sets()).flatMap((Y)=>{let L=Y.definition;if(!L)return[];return Y.options.flatMap((G)=>G.value.type==="string"?[{id:G.id,definitionId:L.id,label:G.value.value,scope:Y.scope==="user"?"personal":"team"}]:[])}),K=new Map;for(let Y of $.tags){let L=S.filter((G)=>bj(G.label)===bj(Y.label.trim())&&(!Y.scope||G.scope===Y.scope));if(!L.length)throw Error(`Unknown tag "${Y.label}". Available tags: ${S.map((G)=>`${G.label} (${G.scope})`).join(", ")}.`);if($.tagsMatch==="all"&&L.length>1)throw Error(`Tag "${Y.label}" is ambiguous; specify personal or team scope.`);for(let G of L)K.set(G.id,G)}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=G2(O.propf,X)}return O}}class px{client;constructor($){this.client=$}async page($={}){let O=new kj(this.client);return this.fetch(O,await O.body($),$.cursor)}async*list($={}){let O=new kj(this.client),j=await O.body($);yield*c((x)=>this.fetch(O,j,x))}async fetch($,O,j){let x=Q(await this.client.storage.postItemsSoupAst({body:O,query:j?{cursor:j}:void 0})),K=x.items.some((Z)=>dx(Z).some((X)=>X.definition.data_type==="TAG"))?await $.tagMap():new Map;return{items:x.items.map((Z)=>Y2(this.client,Z,K)),nextCursor:x.next_cursor,hasMore:x.next_cursor!=null}}}function J2({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...G}){let J,I=Y??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,H=G.signal??new AbortController().signal;while(!0){if(H.aborted)break;B++;let P=G.headers instanceof Headers?G.headers:new Headers(G.headers);if(J!==void 0)P.set("Last-Event-ID",J);try{let D={redirect:"follow",...G,body:G.serializedBody,headers:P,signal:H},_=new Request(L,D);if($)_=await $(L,D);let N=await(G.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let T=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{T.cancel()}catch{}};H.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await T.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`+async function dO($,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*c($){let O;do{let j=await $(O),x=j.nextCursor??void 0;if(O!==void 0&&x!==void 0&&JSON.stringify(x)===JSON.stringify(O))throw Error("Pagination cursor did not advance");yield*j.items,O=x}while(O!==void 0)}var X$=Symbol.for("@ts-pattern/matcher"),s1=Symbol.for("@ts-pattern/isVariadic");var d0=($)=>Boolean($&&typeof $=="object"),Lj=($)=>$&&!!$[X$],s=($,O,j)=>{if(Lj($)){let x=$[X$](),{matched:S,selections:K}=x.match(O);return S&&K&&Object.keys(K).forEach((Z)=>j(Z,K[Z])),S}if(d0($)){if(!d0(O))return!1;if(Array.isArray($)){if(!Array.isArray(O))return!1;let x=[],S=[],K=[];for(let Z of $.keys()){let X=$[Z];Lj(X)&&X[s1]?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),Q=O.slice(x.length,S.length===0?1/0:-S.length);return x.every((L,G)=>s(L,Z[G],j))&&S.every((L,G)=>s(L,X[G],j))&&(K.length===0||s(K[0],Q,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)||Lj(K=S)&&K[X$]().matcherType==="optional")&&s(S,O[x],j);var K})}return Object.is(O,$)},Z$=($)=>{var O,j,x;return d0($)?Lj($)?(O=(j=(x=$[X$]()).getSelectionKeys)==null?void 0:j.call(x))!=null?O:[]:Array.isArray($)?lO($,Z$):lO(Object.values($),Z$):[]},lO=($,O)=>$.reduce((j,x)=>j.concat(O(x)),[]);function a7(...$){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 e($){return Object.assign($,{optional:()=>p0($),and:(O)=>l($,O),or:(O)=>t1($,O),select:(O)=>O===void 0?rO($):rO(O,$)})}function l0($){return Object.assign(((O)=>Object.assign(O,{[Symbol.iterator](){let j=0,x=[{value:Object.assign(O,{[s1]:!0}),done:!1},{done:!0,value:void 0}];return{next:()=>{var S;return(S=x[j++])!=null?S:x.at(-1)}}}}))($),{optional:()=>l0(p0($)),select:(O)=>l0(O===void 0?rO($):rO(O,$))})}function p0($){return e({[X$]:()=>({match:(O)=>{let j={},x=(S,K)=>{j[S]=K};return O===void 0?(Z$($).forEach((S)=>x(S,void 0)),{matched:!0,selections:j}):{matched:s($,O,x),selections:j}},getSelectionKeys:()=>Z$($),matcherType:"optional"})})}var i7=($,O)=>{for(let j of $)if(!O(j))return!1;return!0},n7=($,O)=>{for(let[j,x]of $.entries())if(!O(x,j))return!1;return!0},s7=($,O)=>{let j=Reflect.ownKeys($);for(let x of j)if(!O(x,$[x]))return!1;return!0};function l(...$){return e({[X$]:()=>({match:(O)=>{let j={},x=(S,K)=>{j[S]=K};return{matched:$.every((S)=>s(S,O,x)),selections:j}},getSelectionKeys:()=>lO($,Z$),matcherType:"and"})})}function t1(...$){return e({[X$]:()=>({match:(O)=>{let j={},x=(S,K)=>{j[S]=K};return lO($,Z$).forEach((S)=>x(S,void 0)),{matched:$.some((S)=>s(S,O,x)),selections:j}},getSelectionKeys:()=>lO($,Z$),matcherType:"or"})})}function u($){return{[X$]:()=>({match:(O)=>({matched:Boolean($(O))})})}}function rO(...$){let O=typeof $[0]=="string"?$[0]:void 0,j=$.length===2?$[1]:typeof $[0]=="string"?void 0:$[0];return e({[X$]:()=>({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?[]:Z$(j))})})}function e1($){return!0}function w$($){return typeof $=="number"}function i$($){return typeof $=="string"}function n$($){return typeof $=="bigint"}var o1=e(u(e1)),t7=e(u(e1)),e7=o1,s$=($)=>Object.assign(e($),{startsWith:(O)=>{return s$(l($,(j=O,u((x)=>i$(x)&&x.startsWith(j)))));var j},endsWith:(O)=>{return s$(l($,(j=O,u((x)=>i$(x)&&x.endsWith(j)))));var j},minLength:(O)=>s$(l($,((j)=>u((x)=>i$(x)&&x.length>=j))(O))),length:(O)=>s$(l($,((j)=>u((x)=>i$(x)&&x.length===j))(O))),maxLength:(O)=>s$(l($,((j)=>u((x)=>i$(x)&&x.length<=j))(O))),includes:(O)=>{return s$(l($,(j=O,u((x)=>i$(x)&&x.includes(j)))));var j},regex:(O)=>{return s$(l($,(j=O,u((x)=>i$(x)&&Boolean(x.match(j))))));var j}}),n1=s$(u(i$)),f$=($)=>Object.assign(e($),{between:(O,j)=>f$(l($,((x,S)=>u((K)=>w$(K)&&x<=K&&S>=K))(O,j))),lt:(O)=>f$(l($,((j)=>u((x)=>w$(x)&&x<j))(O))),gt:(O)=>f$(l($,((j)=>u((x)=>w$(x)&&x>j))(O))),lte:(O)=>f$(l($,((j)=>u((x)=>w$(x)&&x<=j))(O))),gte:(O)=>f$(l($,((j)=>u((x)=>w$(x)&&x>=j))(O))),int:()=>f$(l($,u((O)=>w$(O)&&Number.isInteger(O)))),finite:()=>f$(l($,u((O)=>w$(O)&&Number.isFinite(O)))),positive:()=>f$(l($,u((O)=>w$(O)&&O>0))),negative:()=>f$(l($,u((O)=>w$(O)&&O<0)))}),o7=f$(u(w$)),t$=($)=>Object.assign(e($),{between:(O,j)=>t$(l($,((x,S)=>u((K)=>n$(K)&&x<=K&&S>=K))(O,j))),lt:(O)=>t$(l($,((j)=>u((x)=>n$(x)&&x<j))(O))),gt:(O)=>t$(l($,((j)=>u((x)=>n$(x)&&x>j))(O))),lte:(O)=>t$(l($,((j)=>u((x)=>n$(x)&&x<=j))(O))),gte:(O)=>t$(l($,((j)=>u((x)=>n$(x)&&x>=j))(O))),positive:()=>t$(l($,u((O)=>n$(O)&&O>0))),negative:()=>t$(l($,u((O)=>n$(O)&&O<0)))}),$5=t$(u(n$)),O5=e(u(function($){return typeof $=="boolean"})),j5=e(u(function($){return typeof $=="symbol"})),x5=e(u(function($){return $==null})),S5=e(u(function($){return $!=null})),t={__proto__:null,matcher:X$,optional:p0,array:function(...$){return l0({[X$]:()=>({match:(O)=>{if(!Array.isArray(O))return{matched:!1};if($.length===0)return{matched:!0};let j=$[0],x={};if(O.length===0)return Z$(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?[]:Z$($[0])})})},set:function(...$){return e({[X$]:()=>({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:i7(O,(K)=>s(S,K,x)),selections:j}},getSelectionKeys:()=>$.length===0?[]:Z$($[0])})})},map:function(...$){return e({[X$]:()=>({match:(O)=>{if(!(O instanceof Map))return{matched:!1};let j={};if(O.size===0)return{matched:!0,selections:j};let x=(X,Q)=>{j[X]=(j[X]||[]).concat([Q])};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:n7(O,(X,Q)=>{let L=s(K,Q,x),G=s(Z,X,x);return L&&G}),selections:j}},getSelectionKeys:()=>$.length===0?[]:[...Z$($[0]),...Z$($[1])]})})},record:function(...$){return e({[X$]:()=>({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,Q)=>{x[X]=(x[X]||[]).concat([Q])},[K,Z]=$.length===1?[n1,$[0]]:$;return{matched:s7(O,(X,Q)=>{let L=typeof X!="string"||Number.isNaN(Number(X))?null:Number(X),G=L!==null&&s(K,L,S),J=s(K,X,S),I=s(Z,Q,S);return(J||G)&&I}),selections:x}},getSelectionKeys:()=>$.length===0?[]:[...Z$($[0]),...Z$($[1])]})})},intersection:l,union:t1,not:function($){return e({[X$]:()=>({match:(O)=>({matched:!s($,O,()=>{})}),getSelectionKeys:()=>[],matcherType:"not"})})},when:u,select:rO,any:o1,unknown:t7,_:e7,string:n1,number:o7,bigint:$5,boolean:O5,symbol:j5,nullish:x5,nonNullable:S5,instanceOf:function($){return e(u(function(O){return(j)=>j instanceof O}($)))},shape:function($){return e(u(a7($)))}};class $2 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 r0={matched:!1,value:void 0};function k($){return new Nj($,r0)}class Nj{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=(Q,L)=>{S=!0,K[Q]=L},X=!j.some((Q)=>s(Q,this.input,Z))||x&&!Boolean(x(this.input))?r0:{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 Nj(this.input,X)}when($,O){if(this.state.matched)return this;let j=Boolean($(this.input));return new Nj(this.input,j?{matched:!0,value:O(this.input,this.input)}:r0)}otherwise($){return this.state.matched?this.state.value:$(this.input)}exhaustive($=Z5){return this.state.matched?this.state.value:$(this.input)}run(){return this.exhaustive()}returnType(){return this}narrow(){return this}}function Z5($){throw new $2($)}class w extends Error{constructor($){super($);this.name="MacroError"}}var O2=500;function X5($){let O=k($).with(t.string,(j)=>j).with({message:t.string},({message:j})=>j).with({error:t.string},({error:j})=>j).otherwise(()=>"").trim();return O.length>O2?`${O.slice(0,O2)}…`:O}class e$ extends w{status;data;constructor($,O){let j=X5(O);super(j?`Macro API error ${$}: ${j}`:`Macro API error ${$}`);this.status=$;this.data=O;this.name="MacroApiError"}}class a0 extends e${constructor($){super(403,$);this.name="MacroForbiddenError"}}function K5($,O){return $===403?new a0(O):new e$($,O)}class E extends w{constructor($){super($);this.name="MacroNotFoundError"}}function Y($){if($.error!==void 0)throw K5($.response?.status??0,$.error);return $.data}class A{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=Y(await $(this.client));return this.detail.clear(),O}}class H$ extends A{async permission(){return Y(await this.client.storage.getEntityPermission({path:{entity_type:this.entityType,entity_id:this.id}}))}async favorite(){return Y(await this.client.storage.addFavorite({body:{entityId:this.id,entityType:this.entityType}})),this}async unfavorite(){return Y(await this.client.storage.removeFavoriteByEntity({path:{entity_type:this.entityType,entity_id:this.id}})),this}}class K$ extends H${propertyReference(){return{entity_type:this.propertyEntityType,entity_id:this.id}}async properties($){let{properties:O}=Y(await this.client.properties.getEntityProperties({path:{entity_type:this.propertyEntityType,entity_id:this.id},query:$?.includeMetadata!==void 0?{include_metadata:$.includeMetadata}:void 0}));return O}async setProperty($,O){Y(await this.client.properties.setEntityProperty({path:{...this.propertyReference(),property_id:$.id},body:{value:O??null}}))}async updatePropertyOptions($){return Y(await this.client.properties.bulkUpdateEntityPropertyOptions({path:this.propertyReference(),body:{properties:$.map((O)=>({property_id:O.property.id,...O.add?{add_option_ids:O.add.map((j)=>j.id)}:{},...O.remove?{remove_option_ids:O.remove.map((j)=>j.id)}:{}}))}}))}async deleteProperty($){Y(await this.client.properties.deleteEntityProperty({path:{entity_property_id:$.property.id}}))}}var Q5={"<":"\\u003c",">":"\\u003e","&":"\\u0026"};function o$($,O){let j=JSON.stringify(O).replace(/[<>&]/g,(x)=>Q5[x]??x);return`<${$}>${j}</${$}>`}function Y5($){return typeof $==="object"&&$!==null&&typeof $.toMention==="function"}var G5={toMention:()=>({tag:o$("m-group-mention",{groupAlias:"here"}),mention:{entity_type:"group",entity_id:"here"}})};function J5($,...O){let j="",x=[];for(let[S,K]of $.entries()){j+=K;let Z=O[S];if(Z===void 0)continue;if(Y5(Z)){let X=Z.toMention();j+=X.tag,x.push(X.mention)}else j+=String(Z)}return{content:j,mentions:V5(x)}}function V5($){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 A{static byId($,O){return new B$($,O)}static from($,O){return new B$($,O.id,O)}async fetch(){let $=Y(await this.client.storage.listHarnesses()).find((O)=>O.id===this.id);if(!$)throw new E(`Harness ${this.id} is unavailable`);return $}name=this.field("name");connected=this.field("connected");kind=this.field("kind");async delete(){await this.mutate(($)=>$.storage.deleteHarness({path:{harness_id:this.id}}))}}class T$ extends A{static byId($,O){return new T$($,O)}static from($,O){return new T$($,O.bot.id,O)}async fetch(){let $=Y(await this.client.storage.listAgents()).find((O)=>O.bot.id===this.id);if(!$)throw new E(`Agent ${this.id} is unavailable`);return $}name=this.mappedField("bot",($)=>$.name);instructions=this.field("instructions");defaultModel=this.field("default_model");channels=this.mappedField("channel_ids",($)=>$.map((O)=>b.byId(this.client,O)));host=this.mappedField("harness_id",($)=>$?B$.byId(this.client,$):void 0);async update($){await this.mutate((O)=>O.storage.updateAgent({path:{agent_id:this.id},body:i0($)}))}}function i0($){let{channels:O,team:j,host:x,autoAcceptPermissions:S,avatarUrl:K,channelScope:Z,defaultModel:X,isCoding:Q,...L}=$;return{...L,channel_ids:O?.map((G)=>G.id),team_id:j?.id,harness_id:x?.id,auto_accept_permissions:S,avatar_url:K,channel_scope:Z,default_model:X,is_coding:Q}}async function Uj($,O,j,x=[]){let{channelId:S,thread:K}=B5(O);if(await L5($)){let{id:X}=Y(await $.storage.entityMessageCreate({path:{parent_type:"channel",parent_id:S},body:{content:j.content,mentions:j.mentions,attachments:x.map((Q)=>({entity_type:W5,entity_id:Q.id,width:Q.width??null,height:Q.height??null})),thread_id:K?.rootId??null,nonce:crypto.randomUUID()}}));return X}if(x.length>0)throw new w("a user-owned bot can only post via the channel webhook endpoint, which "+"does not support images — use a team-owned bot, or requestedAs(user), "+"to attach images");if(K)throw new w("a user-owned bot can only post via the channel webhook endpoint, which "+"does not support threads — use a team-owned bot, or requestedAs(user), "+"to reply in a thread");let{message_id:Z}=Y(await $.storage.postChannelBotWebhook({path:{channel_id:S},body:{content:j.content},headers:{"x-macro-bot-scope":"user"}}));return Z}var W5="static/image";function B5($){return"rootId"in $?{channelId:$.channelId,thread:$}:{channelId:$.id}}async function L5($){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 o.byId(this.client,this.channelId,this.rootId)}async replies(){let{replies:$}=Y(await this.client.storage.entityMessageGetThread({path:{parent_type:"channel",parent_id:this.channelId,id:this.rootId}}));return $.map((O)=>o.from(this.client,this.channelId,O))}async reply($,O){let j=await Uj(this.client,this,O$($),O?.images);return o.byId(this.client,this.channelId,j)}}class o extends H${channelId;mentions;entityType="channel_message";constructor($,O,j,x=[],S){super($,j,S);this.channelId=O;this.mentions=x}get path(){return{parent_type:"channel",parent_id:this.channelId,id:this.id}}async fetch(){return Y(await this.client.storage.entityMessageGetMessage({path:this.path}))}static byId($,O,j,x=[]){return new o($,O,j,x)}static from($,O,j){return new o($,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 zj{client;channel;record;constructor($,O,j){this.client=$;this.channel=O;this.record=j}agent(){return T$.byId(this.client,this.record.botId)}sessions(){return this.record.sessions.map(($)=>({session:d.byId(this.client,$.sessionId),isCurrent:$.isCurrent,createdAt:$.createdAt}))}turns(){return this.record.turns.map(($)=>new n0(this.client,this,$))}async startFresh($){Y(await this.client.agentHarness.startFreshAgentConversation({path:{channel_id:this.channel.id,bot_id:this.record.botId},body:{sessionId:$.id}}))}toJSON(){return{channelId:this.channel.id,agentId:this.record.botId}}}class n0{client;conversation;record;constructor($,O,j){this.client=$;this.conversation=O;this.record=j}source(){return o.byId(this.client,this.conversation.channel.id,this.record.sourceMessageId)}session(){return d.byId(this.client,this.record.sessionId)}async retry($){Y(await this.client.agentHarness.retryAgentConversationTurn({path:{channel_id:this.conversation.channel.id,bot_id:this.conversation.agent().id,source:this.record.sourceMessageId},body:{actionId:$}}))}toJSON(){return{channelId:this.conversation.channel.id,sourceMessageId:this.record.sourceMessageId}}}class L$ extends A{parent;toJSON(){return{...super.toJSON(),parentType:this.parent.type,parentId:this.parent.entity.id}}constructor($,O,j){super($,j);this.parent=O}static byId($,O,j){return new L$($,O,j)}get path(){return{parent_type:this.parent.type,parent_id:this.parent.entity.id,id:this.id}}async fetch(){return Y(await this.client.storage.entityMessageGetThread({path:this.path})).state}resolved=this.field("resolved");async update($){let O={resolved:$.resolved,detach_anchor:$.detachAnchor,nonce:$.nonce};await this.mutate((j)=>j.storage.entityMessagePatchThread({path:this.path,body:O}))}async delete($){await this.mutate((O)=>O.storage.entityMessageDeleteThread({path:this.path,query:{nonce:$}}))}}async function b$($,O,j,x){for(let K of[...x?.messages??[],...x?.around?[x.around]:[]]){let Z="channelId"in K?{type:"channel",id:K.channelId}:("documentId"in K)?{type:"document",id:K.documentId}:("callId"in K)?{type:"call",id:K.callId}:K.parent;if(Z.type!==O.type||Z.id!==O.entity.id)throw Error("Timeline message belongs to another resource")}let S=Y(await $.storage.messageTimelineEntries({path:{parent_type:O.type,parent_id:O.entity.id},query:{selection:x?JSON.stringify({cursor:x.cursor,around:x.around?.id,ids:x.messages?.map((K)=>K.id),activity_after:x.activityAfter,activity_before:x.activityBefore,anchored:x.anchored,direction:x.direction,include_deleted_threads:x.includeDeletedThreads,limit:x.limit}):void 0}}));return{entries:S.entries.map((K)=>{if(K.type==="activity")return{type:"activity",activity:{...K.activity,actor: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 N5=50;function x$($){let{filters:O,type:j,make:x,includeCrm:S}=$;return(K,Z,X)=>{let Q=X?.searchOn??"name_content",L=X?.pageSize??N5;return c(async(G)=>{let{results:J,next_cursor:I}=Y(await K.search.unifiedSearch({body:{query:Z,match_type:"partial",search_on:Q,...O?{filters:O}:{},...S?{include_crm:!0}:{}},query:{page_size:L,...G?{cursor:G}:{}}}));return{items:J.filter((W)=>W.type===j).map((W)=>x(K,W)),nextCursor:I}})}}class GO{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 GO(this.client,this.channel,Y(await this.client.storage.postActivity({body:{activity_type:$,channel_id:this.channel.id}})))}toJSON(){return this.record}}class b extends K${async recordActivity($){return new GO(this.client,this,Y(await this.client.storage.postActivity({body:{activity_type:$,channel_id:this.id}})))}async setPicture($){await this.mutate((O)=>O.storage.setChannelPicture({path:{channel_id:this.id},body:{profile_picture_id:$?.id??null}}))}messageThreadById($){return L$.byId(this.client,{type:"channel",entity:this},$)}timelinePage($){return b$(this.client,{type:"channel",entity:this},(O)=>o.from(this.client,this.id,O),$)}async agentConversations(){return Y(await this.client.agentHarness.listAgentConversations({path:{channel_id:this.id}})).conversations.map(($)=>new zj(this.client,this,$))}entityType="channel";propertyEntityType="CHANNEL";async fetch(){return Y(await this.client.storage.getChannel({path:{channel_id:this.id}}))}static byId($,O){return new b($,O)}static async dm($,O){let{channel_id:j}=Y(await $.storage.getOrCreateDm({body:{recipient_id:O.id}}));return new b($,j)}static async private($,O){let{channel_id:j}=Y(await $.storage.getOrCreatePrivate({body:{recipients:O.map((x)=>x.id)}}));return new b($,j)}static async create($,O){let{id:j}=Y(await $.storage.createChannel({body:{channel_type:O.type,name:O.name??null,participants:(O.participants??[]).map((x)=>x.id),team_id:O.team?.id??null}}));return new b($,j)}name=this.field("channel_name");type=this.field("channel_type");async send($,O){let j=await Uj(this.client,O?.thread??this,O$($),O?.images);return o.byId(this.client,this.id,j)}messages($){return this.timeline({limit:$?.pageSize})}messagesAfter($,O){return this.timeline({activity_after:$ instanceof Date?$.toISOString():$,limit:O?.pageSize})}timeline($){return c(async(O)=>{let j=Y(await this.client.storage.messageTimeline({path:{parent_type:"channel",parent_id:this.id},query:{selection:JSON.stringify({...$,cursor:O})}}));return{items:j.items.map((x)=>o.from(this.client,this.id,x)),nextCursor:j.next_cursor}})}message($){return o.byId(this.client,this.id,$)}async rename($){await this.mutate((O)=>O.storage.patchChannel({path:{channel_id:this.id},body:{channel_name:$}}))}async delete(){await this.mutate(($)=>$.storage.deleteChannel({path:{channel_id:this.id}}))}async join(){await this.mutate(($)=>$.storage.joinChannel({path:{channel_id:this.id}}))}async joinCode(){let{join_code:$}=Y(await this.client.storage.getChannelJoinLink({path:{channel_id:this.id}}));return $}async leave(){await this.mutate(($)=>$.storage.leaveChannel({path:{channel_id:this.id}}))}async participants(){return Y(await this.client.storage.getChannelParticipants({path:{channel_id:this.id}}))}async addParticipants($){await this.mutate((O)=>O.storage.addParticipants({path:{channel_id:this.id},body:{participants:$.map((j)=>j.id)}}))}async removeParticipants($){await this.mutate((O)=>O.storage.removeParticipants({path:{channel_id:this.id},body:{participants:$.map((j)=>j.id)}}))}async typing($,O){Y(await this.client.storage.entityMessageTyping({path:{parent_type:"channel",parent_id:this.id},body:{active:$==="start",thread_id:O?.thread?.rootId??null}}))}attachments($){return c(async(O)=>{let j=Y(await this.client.storage.getChannelAttachments({path:{channel_id:this.id},query:{...$?.pageSize?{limit:$.pageSize}:{},...$?.type?{attachment_type:$.type}:{},...O?{cursor:O}:{}}}));return{items:j.items,nextCursor:j.next_cursor}})}webUrl(){return`${this.client.webAppUrl}/app/channel/${this.id}`}static search=x$({type:"channel",make:($,O)=>new b($,O.channel_id)})}class M extends K${entityType="user";propertyEntityType="USER";async fetch(){let{names:$}=Y(await this.client.auth.getUserNamesWithEmail({body:{user_ids:[this.id]}})),O=$.find((j)=>j.id===this.id);if(!O)throw new E(`user ${this.id} not found`);return O}static byId($,O){return new M($,O)}static fromName($,O){return new M($,O.id,O)}static async me($){let{user_id:O}=Y(await $.auth.getUserInfo());return new M($,O)}async name(){let $=await this.detail.get();return[$.first_name,$.last_name].filter(Boolean).join(" ")||void 0}async isAgent(){return(await this.detail.get()).is_agent===!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:o$("m-user-mention",{userId:this.id}),mention:{entity_type:"user",entity_id:this.id}}}}class $${client;entityType;entity;constructor($,O,j){this.client=$;this.entityType=O;this.entity=j}get path(){return{entity_type:this.entityType,entity_id:this.entity.id}}async state($){let O=Y(await this.client.storage.accessRequestsState({path:this.path,query:{offset:$}}));return{accessLevel:O.accessLevel??void 0,canReview:O.canReview,owner:O.owner?M.byId(this.client,O.owner):void 0,pendingCount:O.pendingCount,supportedLevels:O.supportedLevels,nextOffset:O.nextOffset??void 0,mine:O.mine?IO.from(this.client,this,O.mine):void 0,requests:O.requests.map((j)=>IO.from(this.client,this,j))}}async request($){let{mine:O}=await this.state();return this.submit($,O?await O.revision():void 0)}async submit($,O){return IO.from(this.client,this,Y(await this.client.storage.accessRequestsSubmit({path:this.path,body:{requestedLevel:$,revision:O}})))}async cancel($){Y(await this.client.storage.accessRequestsCancel({path:this.path,query:{revision:$}}))}async direct(){return Y(await this.client.storage.accessRequestsDirect({path:this.path})).map(($)=>({user:M.byId(this.client,$.userId),accessLevel:$.accessLevel}))}async grant($,O){Y(await this.client.storage.accessRequestsSetDirect({path:{...this.path,user_id:$.id},body:{accessLevel:O}}))}async remove($){Y(await this.client.storage.accessRequestsRemoveDirect({path:{...this.path,user_id:$.id}}))}async resolve($,O){let j=$.access.toJSON();if(j.entity_type!==this.entityType||j.entity_id!==this.entity.id)throw Error("Access request belongs to another entity");return Y(await this.client.storage.accessRequestsResolve({path:{...this.path,request_id:$.id},body:O}))}toJSON(){return this.path}}class IO extends A{access;resolvedRecord;constructor($,O,j){super($,j.id,j);this.access=O}static from($,O,j){return new IO($,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 $O($){return{...$,channelSharePermissions:$.channelSharePermissions===void 0||$.channelSharePermissions===null?$.channelSharePermissions:$.channelSharePermissions.map((O)=>({channelId:O.channel.id,accessLevel:O.accessLevel,operation:O.operation}))}}function s0($){return $}class N$ extends A{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=Y(await $.agentHarness.createSessionReview({path:{session_id:O.id},body:{...j,executionId:x?.id??null}}));return N$.fromRecord($,O,s0(S))}static async list($,O){return Y(await $.agentHarness.listExecutionReviews({path:{session_id:O.session().id,execution_id:O.id}})).map((x)=>N$.fromRecord($,O.session(),s0(x)))}async fetch(){return s0(Y(await this.client.agentHarness.getSessionReview({path:{session_id:this.parent.id,review_id:this.id}})))}title=this.field("title");kind=this.field("kind");session(){return this.parent}async reference(){return{kind:await this.kind(),id:this.id}}async items(){return(await this.detail.get()).items.map((j)=>new t0(j,{edit:(x)=>this.decide({action:"edit",item:j.id,draft:x}),submit:()=>this.decide({action:"submit",items:[j.id]}),dismiss:()=>this.decide({action:"dismiss",items:[j.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 t0{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()}}async function Ij($,O,j,x){Y(await $.agentHarness.presentSessionView({path:{session_id:O.id},body:{view:j,executionId:x?.id??null}}))}class pO extends A{parent;constructor($,O,j){super($,O);this.parent=j}static byId($,O,j){return new pO($,j,O)}async fetch(){return Y(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)};views={present:($)=>Ij(this.client,this.parent,$,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 Hj{client;sessionId;dto;constructor($,O,j){this.client=$;this.sessionId=O;this.dto=j}static from($,O,j){return new Hj($,O,j)}get actionId(){return this.dto.actionId}get kind(){return this.dto.kind}get prompt(){return this.dto.prompt??void 0}get attachments(){return this.dto.attachments??[]}get actorUserId(){return this.dto.actorUserId??void 0}get createdAt(){return this.dto.createdAt}async edit($){return Y(await this.client.agentHarness.editQueuedAction({path:{session_id:this.sessionId,action_id:this.actionId},body:{prompt:$}})),this.dto={...this.dto,prompt:$},this}async steer(){Y(await this.client.agentHarness.steerQueuedAction({path:{session_id:this.sessionId,action_id:this.actionId}}))}async remove(){Y(await this.client.agentHarness.removeQueuedAction({path:{session_id:this.sessionId,action_id:this.actionId}}))}}class aO{client;session;id;constructor($,O,j){this.client=$;this.session=O;this.id=j}static byId($,O,j){return new aO($,O,j)}async answer($){return Y(await this.client.agentHarness.answerAgentSessionToolApproval({path:{session_id:this.session.id,approval_id:this.id},body:{answer:$}}))}toJSON(){return{id:this.id,sessionId:this.session.id}}}class d extends A{access=new $$(this.client,"agent_session",this);toolApprovalById($){return aO.byId(this.client,this,$)}async sharePermissions(){return Y(await this.client.agentHarness.getAgentSessionPermissions({path:{session_id:this.id}}))}async updateSharePermissions($){return this.mutate((O)=>O.agentHarness.updateAgentSessionPermissions({path:{session_id:this.id},body:$O($)}))}static byId($,O){return new d($,O)}static async createManaged($,O){let{session:j}=Y(await $.agentHarness.createAgentSession({body:{botId:O?.agent?.id,prompt:O?.prompt,instructions:O?.instructions,model:O?.model,repoUrl:O?.repoUrl,repoBranch:O?.repoBranch}}));return new d($,j.id,j)}static async repositories($){let{repositories:O}=Y(await $.agentHarness.listAgentRepositories());return O.map((j)=>({url:j.url,defaultBranch:j.defaultBranch??void 0}))}static async repositoryBranches($,O){let{branches:j}=Y(await $.agentHarness.listAgentRepositoryBranches({query:{repoUrl:O}}));return j}static async chooseMode($,O){let{mode:j}=Y(await $.agentHarness.chooseAgentMode({body:{prompt:O}}));return j}async fetch(){return Y(await this.client.agentHarness.getAgentSession({path:{session_id:this.id}}))}name=this.field("name");archivedBy=this.field("archivedBy");archivedAt=this.field("archivedAt");model=this.field("model");harness=this.field("harness");repoUrl=this.field("repoUrl");workspace=this.field("workspace");instructions=this.field("instructions");status=this.field("status");sandboxSize=this.field("sandboxSize");createdAt=this.field("createdAt");modifiedAt=this.field("modifiedAt");static async forPullRequest($,O){let{sessionIds:j}=Y(await $.agentHarness.agentSessionsForPullRequest({body:{url:O}}));return j.map((x)=>d.byId($,x))}async pullRequests(){let{pullRequests:$}=Y(await this.client.agentHarness.listAgentSessionPullRequests({path:{session_id:this.id}}));return $.map((O)=>({githubKey:O.githubKey,url:O.url,source:O.source,linkedBy:O.linkedBy?M.byId(this.client,O.linkedBy):void 0,createdAt:O.createdAt}))}async linkPullRequest($){Y(await this.client.agentHarness.linkAgentSessionPullRequest({path:{session_id:this.id},body:{url:$}}))}async unlinkPullRequest($){Y(await this.client.agentHarness.unlinkAgentSessionPullRequest({path:{session_id:this.id},query:{url:$}}))}async autoArchive(){let{overrides:$,defaults:O,autoArchivedAt:j}=Y(await this.client.agentHarness.getAgentSessionAutoArchive({path:{session_id:this.id}}));return{overrides:{onPullRequestMerged:$.onPullRequestMerged??void 0,onRuntimeClosed:$.onRuntimeClosed??void 0},defaults:O,autoArchivedAt:j??void 0}}async setAutoArchive($){Y(await this.client.agentHarness.putAgentSessionAutoArchive({path:{session_id:this.id},body:{onPullRequestMerged:$.onPullRequestMerged??null,onRuntimeClosed:$.onRuntimeClosed??null}}))}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:{archived:$}}))}async setSandboxSize($){let{size:O}=await this.mutate((j)=>j.agentHarness.putAgentSessionSandboxSize({path:{session_id:this.id},body:{size:$}}));return O}static async defaultSandboxSize($){return Y(await $.agentHarness.getAgentSandboxSize()).size}static async setDefaultSandboxSize($,O){return Y(await $.agentHarness.putAgentSandboxSize({body:{size:O}})).size}static async codingPreferences($){return Y(await $.agentHarness.getAgentCodingPreferences())}static async autoArchivePreferences($){return Y(await $.agentHarness.getAgentAutoArchivePreferences())}static async setAutoArchivePreferences($,O){return Y(await $.agentHarness.putAgentAutoArchivePreferences({body:O}))}static async setCodingPreferences($,O){return Y(await $.agentHarness.putAgentCodingPreferences({body:O}))}async control($){return this.mutate((O)=>O.agentHarness.controlAgentSession({path:{session_id:this.id},body:$}))}prompt($,O){return this.control({type:"prompt",prompt:$,...O&&O.length>0?{attachments:O}:{}})}async queue(){let{entries:$}=Y(await this.client.agentHarness.getAgentSessionQueue({path:{session_id:this.id}}));return $.map((O)=>Hj.from(this.client,this.id,O))}async changes(){return Y(await this.client.agentHarness.getAgentSessionChanges({path:{session_id:this.id}}))}async changesPatch(){return Y(await this.client.agentHarness.getAgentSessionChangesPatch({path:{session_id:this.id}})).patch}async refreshChanges(){return this.mutate(($)=>$.agentHarness.refreshAgentSessionChanges({path:{session_id:this.id}}))}async foldedLog(){let{bot:$,messages:O}=Y(await this.client.agentHarness.getAgentSessionFoldedLog({path:{session_id:this.id}}));return{bot:$,messages:O}}async log(){return Y(await this.client.agentHarness.getAgentSessionLog({path:{session_id:this.id}}))}reviews={create:($)=>N$.createForSession(this.client,this,$),byId:($)=>N$.byId(this.client,this,$)};views={present:($)=>Ij(this.client,this,$)};codeExecutions={byId:($)=>pO.byId(this.client,this,$)};async delete(){await this.mutate(($)=>$.agentHarness.deleteAgentSession({path:{session_id:this.id}}))}}class e0{client;constructor($){this.client=$}byId($){return d.byId(this.client,$)}createManaged($){return d.createManaged(this.client,$)}chooseMode($){return d.chooseMode(this.client,$)}repositories(){return d.repositories(this.client)}repositoryBranches($){return d.repositoryBranches(this.client,$)}forPullRequest($){return d.forPullRequest(this.client,$)}defaultSandboxSize(){return d.defaultSandboxSize(this.client)}setDefaultSandboxSize($){return d.setDefaultSandboxSize(this.client,$)}codingPreferences(){return d.codingPreferences(this.client)}autoArchivePreferences(){return d.autoArchivePreferences(this.client)}setAutoArchivePreferences($){return d.setAutoArchivePreferences(this.client,$)}setCodingPreferences($){return d.setCodingPreferences(this.client,$)}}class o0{client;constructor($){this.client=$}byId($){return T$.byId(this.client,$)}async list(){return Y(await this.client.storage.listAgents()).map(($)=>T$.from(this.client,$))}async create($){return T$.from(this.client,Y(await this.client.storage.createAgent({body:i0($)})))}}class $x{client;async usage($={}){let{users:O,...j}=$;return Y(await this.client.cognition.getUsageHandler({body:{...j,include_users:O?.map((x)=>x.id)}}))}constructor($){this.client=$}async structuredCompletion($){return Y(await this.client.cognition.structuredCompletion({body:$}))}async decide($){return Y(await this.client.cognition.decisions({body:$}))}}class OO extends A{static byId($,O){return new OO($,O)}static from($,O){return new OO($,O.id,{id:O.id,name:O.name,createdAt:O.createdAt})}async fetch(){let $=Y(await this.client.storage.listUserApiKeys()).keys.find((O)=>O.id===this.id);if(!$)throw new E(`API key ${this.id} is unavailable`);return $}name=this.field("name");createdAt=this.field("createdAt");async delete(){await this.mutate(($)=>$.storage.deleteUserApiKey({path:{id:this.id}}))}}class Ox{client;constructor($){this.client=$}byId($){return OO.byId(this.client,$)}async list(){return Y(await this.client.storage.listUserApiKeys()).keys.map(($)=>OO.from(this.client,$))}async create($){let O=Y(await this.client.storage.createUserApiKey({body:{name:$}}));return{key:OO.from(this.client,O),secret:O.key}}async tokenForEmail($){return Y(await this.client.auth.macroApiToken({query:{email:$}}))}}class iO{client;constructor($){this.client=$}async me(){if(this.client.authConfig.type!=="bot")throw new w("bots.me() requires bot auth — a user API key has no bot identity");return Y(await this.client.storage.getSelfBot())}async channels(){if(this.client.authConfig.type!=="bot")throw new w("bots.channels() requires bot auth — a user API key has no bot identity");let $=await this.me();return Y(await this.client.storage.listBotChannels({path:{bot_id:$.id}}))}async myPrincipalId(){if(this.client.authConfig.type!=="bot")throw new w("bots.myPrincipalId() requires bot auth — a user API key has no bot identity");return this.client.myPrincipalId()}}class R$ extends A{async fetch(){let{links:$}=Y(await this.client.email.listLinks()),O=$.find((j)=>j.id===this.id);if(!O)throw new E(`email link ${this.id} not found`);return O}static byId($,O){return new R$($,O)}static async list($){let{links:O}=Y(await $.email.listLinks());return O.map((j)=>new R$($,j.id,j))}emailAddress=this.field("email_address");provider=this.field("provider");isPrimary=this.field("is_primary");isSyncActive=this.field("is_sync_active");syncStatus=this.field("sync_status");needsReauth=this.field("needs_reauth");photoUrl=this.field("photo_url");async settingsOperations(){return Y(await this.client.email.mailboxSettingsOperations({headers:{"X-Email-Link-Id":this.id}}))}}class m$ extends A{async setContributesToAvailability($){await this.mutate((O)=>O.calendar.setAvailabilityCalendar({path:{calendar_id:this.id},body:{contributesToAvailability:$}}))}async fetch(){let{calendars:$}=Y(await this.client.calendar.listCalendars()),O=$.find((j)=>j.id===this.id);if(!O)throw new E(`calendar ${this.id} not found`);return O}static byId($,O){return new m$($,O)}static async list($){let{calendars:O}=Y(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");contributesToAvailability=this.field("contributesToAvailability");isSubscription=this.field("isSubscription");color=this.field("color");syncError=this.field("syncError");emailLink=this.mappedField("emailLinkId",($)=>R$.byId(this.client,$))}class nO{client;id;constructor($,O){this.client=$;this.id=O}async status(){return Y(await this.client.calendar.calendarReplacementStatus({path:{operation_id:this.id}}))}async confirm(){return Y(await this.client.calendar.confirmCalendarReplacement({path:{operation_id:this.id}}))}async discard(){Y(await this.client.calendar.discardCalendarReplacement({path:{operation_id:this.id}}))}}class S$ extends A{async fetch(){throw new w(`calendar event ${this.id} has no fetch-by-id endpoint; read the record returned by calendar.createEvent / event.update / event.rsvp instead`)}static byId($,O){return new S$($,O)}static fromRecord($,O){return new S$($,O.id,O)}title=this.field("title");description=this.field("description");location=this.field("location");time=this.field("time");status=this.field("status");attendees=this.field("attendees");transparency=this.field("transparency");isReadOnly=this.field("isReadOnly");recurrenceLines=this.field("recurrenceLines");guestPolicy=this.field("guestPolicy");viewerCan=this.field("viewerCan");calendar=this.mappedField("calendarId",($)=>$?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:U5($)}));return S$.fromRecord(this.client,O)}async delete($={}){await this.mutate((O)=>O.calendar.deleteCalendarEvent({path:{event_id:this.id},query:{calendarId:$.calendar?.id,scope:$.scope,recurrenceId:$.recurrenceId,inbox:$.inbox}}))}async prepareReplacement($){let O=Y(await this.client.calendar.prepareCalendarReplacement({path:{event_id:this.id},body:{removeConference:$.removeConference,recurrenceId:$.recurrenceId,calendarId:$.calendar?.id}}));return new nO(this.client,O.operationId)}async providerUrl($={}){return Y(await this.client.calendar.calendarEventProviderUrl({path:{event_id:this.id},query:{recurrenceId:$.recurrenceId,calendarId:$.calendar?.id}})).url??void 0}async inviteGuests($){let O=await this.mutate((j)=>j.calendar.inviteCalendarEventGuests({path:{event_id:this.id},body:{guests:$.guests,scope:$.scope,recurrenceId:$.recurrenceId,calendarId:$.calendar?.id,inbox:$.inbox}}));return S$.fromRecord(this.client,O)}async addToCalendar($={}){let O=await this.mutate((j)=>j.calendar.copyCalendarEvent({path:{event_id:this.id},body:{calendarId:$.calendar?.id}}));return S$.fromRecord(this.client,O)}async ics(){return Y(await this.client.storage.eventIcs({path:{event_id:this.id}}))}async rsvp($){let O=await this.mutate((j)=>j.calendar.rsvpCalendarEvent({path:{event_id:this.id},body:{response:$.response,scope:$.scope,recurrenceId:$.recurrenceId,calendarId:$.calendar?.id}}));return S$.fromRecord(this.client,O)}}function U5($){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 jx{client;async availabilityCalendars(){return Y(await this.client.calendar.getAvailabilityCalendars()).calendars.map(($)=>({calendar:m$.byId(this.client,$.calendarId),name:$.name,isPrimary:$.isPrimary,contributesToAvailability:$.contributesToAvailability}))}async teamSharing(){return Y(await this.client.calendar.getTeamSharing()).sharing}async setTeamSharing($){return Y(await this.client.calendar.setTeamSharing({body:{sharing:$}})).sharing}occurrences($){let O;return c(async(j)=>{let x=Y(await this.client.storage.listOccurrences({query:{...$,cursor:j}}));O??=I5(this.client);let S=await O;return{items:x.items.map((K)=>{let Z=K.event.calendarId?S.get(K.event.calendarId):void 0;return{event:S$.fromRecord(this.client,K.event),occurrence:K.occurrence,calendarName:Z?.name,contributesToAvailability:j2(K.event,S),inbox:Z?.emailAddress,role:H5(K.event,S)}}),nextCursor:x.nextCursor}})}async teamPage($){let O=Y(await this.client.storage.listTeamCalendar({query:$}));return{items:O.items.map(({ownerId:j,...x})=>({...x,owner: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=Y(await this.client.storage.listTeamOutOfOffice({query:$}));return{items:O.items.map((j)=>({event:S$.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 S$.byId(this.client,$)}replacement($){return new nO(this.client,$)}async createEvent($){let O=Y(await this.client.calendar.createCalendarEvent({body:z5($)}));return S$.fromRecord(this.client,O)}}function z5($){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 I5($){let{calendars:O}=Y(await $.calendar.listCalendars());return new Map(O.map((j)=>[j.id,j]))}function j2($,O){let j=[$.calendarId,...($.sources??[]).map((x)=>x.calendarId)].flatMap((x)=>{let S=x?O.get(x):void 0;return S?[S.contributesToAvailability]:[]});if(j.some(Boolean))return!0;return j.length>0&&j.every((x)=>x===!1)?!1:void 0}function H5($,O){let j=$.attendees.find((S)=>S.isSelf);if(j?.isOrganizer)return $.isReadOnly?void 0:"organizer";let x=$.attendees.some((S)=>S.isOrganizer);if($.viewerCan.organize&&j2($,O)&&!x)return"organizer";return j?"guest":void 0}class D$ extends A{lookupToken;constructor($,O,j){super($,O,j);this.lookupToken=j?.shareToken}static byId($,O){return new D$($,O)}static from($,O){return new D$($,O.id,O)}async fetch(){if(this.lookupToken)return Y(await this.client.storage.meetingLookup({path:{token:this.lookupToken}}));let $=Y(await this.client.storage.meetingList()).meetings.find((O)=>O.id===this.id);if(!$)throw new E(`Meeting ${this.id} is unavailable`);return this.lookupToken=$.shareToken,$}title=this.field("title");scheduledStart=this.field("scheduledStart");scheduledEnd=this.field("scheduledEnd");channel=this.mappedField("channelId",($)=>$?b.byId(this.client,$):void 0);call=this.mappedField("callId",($)=>$?J$.byId(this.client,$):void 0);async update($){await this.mutate((O)=>O.storage.meetingUpdate({path:{meeting_id:this.id},body:$}))}async cancel(){await this.mutate(($)=>$.storage.meetingCancel({path:{meeting_id:this.id}}))}async invitePermissions(){return Y(await this.client.storage.meetingInvitePermissions({path:{token:(await this.detail.get()).shareToken}}))}async invite($){Y(await this.client.storage.meetingInvite({path:{token:(await this.detail.get()).shareToken},body:{email:$}}))}async inviteUsers($){Y(await this.client.storage.meetingInviteUsers({path:{token:(await this.detail.get()).shareToken},body:{userIds:$.map((O)=>O.id)}}))}async webUrl(){return`${this.client.webAppUrl}/app/meet/join/${encodeURIComponent((await this.detail.get()).shareToken)}`}}class u$ extends A{callId;constructor($,O,j,x){super($,j,x);this.callId=O}get path(){return{parent_type:"call",parent_id:this.callId,id:this.id}}async fetch(){return Y(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 J$.byId(this.client,this.callId)}async author(){return M.byId(this.client,(await this.detail.get()).sender_id)}async reply($){let O=Y(await this.client.storage.entityMessageCreate({path:{parent_type:"call",parent_id:this.callId},body:{...O$($),thread_id:this.callId}}));return 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 J$ extends H${messageThreadById($){return L$.byId(this.client,{type:"call",entity:this},$)}timelinePage($){return b$(this.client,{type:"call",entity:this},(O)=>u$.from(this.client,this.id,O),$)}access=new $$(this.client,"call",this);async meeting(){return D$.from(this.client,Y(await this.client.storage.meetingShare({path:{call_id:this.id}})))}async editTranscript($){await this.mutate((O)=>O.storage.editCallTranscript({path:{call_id:this.id},body:{assignments:$}}))}async toggleTeamShare(){return this.mutate(($)=>$.storage.toggleShareWithTeam({path:{call_id:this.id}}))}entityType="call";async fetch(){return Y(await this.client.storage.getCallRecord({path:{call_id:this.id}}))}static byId($,O){return new J$($,O)}message($){return 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 J$($,O.call_id)})}class xx{client;constructor($){this.client=$}byId($){return J$.byId(this.client,$)}search($,O){return J$.search(this.client,$,O)}}class Sx{client;constructor($){this.client=$}async list(){let{labels:$}=Y(await this.client.storage.listChannelLabels());return $}async create($,O=[]){return Y(await this.client.storage.createChannelLabel({body:{name:$,channelIds:O.map((j)=>j.id)}}))}async createSmartTag($,O){return Y(await this.client.storage.createChannelLabel({body:{name:$,rule:O}}))}async previewSmartTag($){return Y(await this.client.storage.previewSmartTag({body:$}))}async updateSmartTag($,O,j){return Y(await this.client.storage.renameChannelLabel({path:{label_id:$.id},body:{name:O,rule:j}}))}async rename($,O){return Y(await this.client.storage.renameChannelLabel({path:{label_id:$.id},body:{name:O}}))}async delete($){Y(await this.client.storage.deleteChannelLabel({path:{label_id:$.id}}))}async setLabel($,O){Y(await this.client.storage.setChannelLabel({path:{channel_id:$.id},body:{labelId:O?.id??null}}))}}var T5=100;class Zx{client;async activity(){return Y(await this.client.storage.getActivity()).map(($)=>new GO(this.client,b.byId(this.client,$.channel_id),$))}labels;constructor($){this.client=$;this.labels=new Sx($)}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(){for await(let $ of this.records())yield b.byId(this.client,$.id)}async*search($,O){if(!O?.searchOn||O.searchOn==="name"){let j=$.toLowerCase();for await(let x of this.records())if(x.name?.toLowerCase().includes(j))yield b.byId(this.client,x.id)}else yield*b.search(this.client,$,O)}records(){return c(async($)=>{let O=Y(await this.client.storage.getChannels({query:{limit:T5,...$?{cursor:$}:{}}}));return{items:O.items,nextCursor:O.next_cursor}})}}class n extends K${async sharePermissions(){return Y(await this.client.storage.getProjectPermissionsV2({path:{id:this.id}}))}async accessLevel(){return Y(await this.client.storage.getProjectUserAccessLevel({path:{id:this.id}}))}access=new $$(this.client,"project",this);entityType="project";propertyEntityType="PROJECT";async fetch(){let{data:$}=Y(await this.client.storage.getProjectHandler({path:{id:this.id}}));return $.projectMetadata}static byId($,O){return new n($,O)}static async create($,O){let{data:j}=Y(await $.storage.createProjectHandler({body:{name:O.name,projectParentId:O.parent?.id??null}}));return new n($,j.id,j)}name=this.field("name");parent=this.mappedField("parentId",($)=>$?n.byId(this.client,$):void 0);createdAt=this.field("createdAt");async items(){let{data:$}=Y(await this.client.storage.getProjectContentHandler({path:{id:this.id}}));return $.map((O)=>O.item)}async rename($){await this.mutate((O)=>O.storage.editProjectV2({path:{id:this.id},body:{name:$}}))}async delete($){await this.mutate((O)=>$?.permanent?O.storage.permanentlyDeleteProject({path:{id:this.id}}):O.storage.deleteProjectHandler({path:{id:this.id}}))}async restore(){await this.mutate(($)=>$.storage.revertDeleteProject({path:{id:this.id}}))}static search=x$({filters:{project_filters:{}},type:"project",make:($,O)=>new n($,O.id)})}class sO{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 sO($,O,j,x)}async stop(){Y(await this.client.cognition.stopChatStream({body:{chat_id:this.chat.id,stream_id:this.id}}))}toJSON(){return{id:this.id,chatId:this.chat.id,messageId:this.message.id}}}class tO extends A{chat;constructor($,O,j){super($,j);this.chat=O}static byId($,O,j){return new tO($,O,j)}async fetch(){let $=Y(await this.client.cognition.getChat({path:{chat_id:this.chat.id}})).chat.messages.find((O)=>O.id===this.id);if(!$)throw new E(`Chat message ${this.id} is not yet available`);return $}content=this.field("content");role=this.field("role");async refresh(){this.detail.clear(),await this.detail.get()}toJSON(){return{...super.toJSON(),chatId:this.chat.id}}}class Q$ extends K${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=Q$.byId(this.client,S.chat_id);return sO.byId(this.client,K,S.stream_id,tO.byId(this.client,K,S.message_id))}access=new $$(this.client,"chat",this);entityType="chat";propertyEntityType="CHAT";async fetch(){let{chat:$}=Y(await this.client.cognition.getChat({path:{chat_id:this.id}}));return $}static byId($,O){return new Q$($,O)}static async create($,O){let{id:j}=Y(await $.cognition.createChat({body:{name:O?.name??null,projectId:O?.project?.id??null}}));return new Q$($,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 Q$(this.client,$)}async restore(){await this.mutate(($)=>$.cognition.revertDeleteChat({path:{chat_id:this.id}}))}async history(){let{conversation:$}=Y(await this.client.cognition.getChatHistoryHandler({path:{chat_id:this.id}}));return $}webUrl(){return`${this.client.webAppUrl}/app/chat/${this.id}`}static search=x$({filters:{chat_filters:{}},type:"chat",make:($,O)=>new Q$($,O.chat_id)});toMention(){return{tag:o$("m-document-mention",{documentId:this.id,documentName:this.detail.peek()?.name??"",blockName:"chat",blockParams:{}}),mention:{entity_type:"chat",entity_id:this.id}}}}class Xx{client;constructor($){this.client=$}byId($){return Q$.byId(this.client,$)}create($){return Q$.create(this.client,$)}search($,O){return Q$.search(this.client,$,O)}}class HO extends A{static byId($,O){return new HO($,O)}static from($,O){return new HO($,O.id,O)}async fetch(){let $=Y(await this.client.auth.getTeamInvites()).invites.find((O)=>O.id===this.id);if(!$)throw new E(`team invite ${this.id} not found`);return $}email=this.field("email");role=this.field("team_role");invitedBy=this.mappedField("invited_by",($)=>M.byId(this.client,$));createdAt=this.field("created_at");lastSentAt=this.field("last_sent_at");async revoke(){await this.mutate(($)=>$.auth.deleteTeamInviteHandler({path:{team_invite_id:this.id}}))}}class _$ extends A{async fetch(){let O=Y(await this.client.auth.getUserTeams()).find((j)=>j.id===this.id);if(!O)throw new E(`team ${this.id} not found`);return O}static byId($,O){return new _$($,O)}static async current($){let O=Y(await $.auth.getTeam());if(!O?.team)throw new E("caller has no current team");return new _$($,O.team.id,O.team)}static async list($){return Y(await $.auth.getUserTeams()).map((j)=>new _$($,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(){return(await this.requireCurrent("members")).members.map((O)=>({user:M.byId(this.client,O.user_id),role:O.role}))}async invite($,O){let j=[],x=new Set;for(let K of typeof $==="string"?[$]:$){let Z=K.trim(),X=Z.toLowerCase();if(Z&&!x.has(X))x.add(X),j.push(Z)}if(j.length===0)throw new w("invite needs at least one email address");let S=await this.client.auth.inviteToTeam({body:{invites:j.map((K)=>({email:K})),team_id:this.id,...O?.agent&&{is_agent:!0}}});if(S.response?.status===304)return!1;return Y(S),!0}async invites(){return Y(await this.client.auth.getTeamInvites({query:{team_id:this.id}})).invites.map(($)=>HO.from(this.client,$))}async requireCurrent($){let O=Y(await this.client.auth.getTeam());if(!O?.team||O.team.id!==this.id)throw new w(`${$} are only available for the current team (see Team.current)`);return O}}var R5=8;class A$ extends A{parent;constructor($,O,j,x){super($,j,x);this.parent=O}get path(){return{parent_type:this.parent.type,parent_id:this.parent.id,id:this.id}}async fetch(){return Y(await this.client.storage.entityMessageGetMessage({path:this.path}))}static byId($,O,j){return new A$($,O,j)}static from($,O,j){return new A$($,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 eO(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 Tj($,O){let j={parent_type:O.type,parent_id:O.id},x=c(async(K)=>{let Z=Y(await $.storage.messageTimeline({path:j,query:{selection:JSON.stringify({limit:100,cursor:K})}}));return{items:Z.items,nextCursor:Z.next_cursor}}),S=[];for await(let K of x)S.push(K);return dO(S,R5,async(K)=>{let{state:Z,root:X,replies:Q}=Y(await $.storage.entityMessageGetThread({path:{...j,id:K.id}}));return{thread:Z,comments:[X,...Q].map((L)=>A$.from($,O,L))}})}async function eO($,O,j,x){let S=Y(await $.storage.entityMessageCreate({path:{parent_type:O.type,parent_id:O.id},body:{...O$(j),thread_id:x?.threadId??null}}));return A$.from($,O,S)}class P$ extends H${messageThreadById($){return L$.byId(this.client,{type:"crm_contact",entity:this},$)}timelinePage($){return b$(this.client,{type:"crm_contact",entity:this},(O)=>A$.from(this.client,{type:"crm_contact",id:this.id},O),$)}entityType="crm_contact";async fetch(){return Y(await this.client.storage.getContact({path:{contact_id:this.id}}))}static byId($,O){return new P$($,O)}static from($,O){return new P$($,O.id,O)}name=this.field("name");email=this.field("email");company=this.mappedField("companyId",($)=>$?k$.byId(this.client,$):void 0);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 Tj(this.client,this.commentParent)}async comment($,O){return eO(this.client,this.commentParent,$,O)}commentById($){return A$.byId(this.client,this.commentParent,$)}}class k$ extends K${messageThreadById($){return L$.byId(this.client,{type:"crm_company",entity:this},$)}timelinePage($){return b$(this.client,{type:"crm_company",entity:this},(O)=>A$.from(this.client,{type:"crm_company",id:this.id},O),$)}entityType="crm_company";propertyEntityType="COMPANY";async fetch(){return Y(await this.client.storage.getCompany({path:{company_id:this.id}}))}static byId($,O){return new k$($,O)}static from($,O){return new k$($,O.id,O)}name=this.field("name");description=this.field("description");hidden=this.field("hidden");emailSync=this.field("emailSync");team=this.mappedField("teamId",($)=>_$.byId(this.client,$));createdAt=this.field("createdAt");updatedAt=this.field("updatedAt");async domain(){let{domains:$}=await this.detail.get();return $[0]?.domain}async domains(){let{domains:$}=await this.detail.get();return $.map((O)=>O.domain)}async contacts(){return Y(await this.client.storage.listCompanyContacts({path:{company_id:this.id}})).map((O)=>P$.from(this.client,O))}static search=x$({filters:{crm_company_filters:{}},type:"company",includeCrm:!0,make:($,O)=>new k$($,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 P$.from(this.client,O)}get commentParent(){return{type:"crm_company",id:this.id}}async comments(){return Tj(this.client,this.commentParent)}async comment($,O){return eO(this.client,this.commentParent,$,O)}commentById($){return A$.byId(this.client,this.commentParent,$)}}class jO extends A{tableDetail=new W$(async()=>Y(await this.client.storage.getCrmPipelineTable({path:{id:this.id}})));static byId($,O){return new jO($,O)}static from($,O){return new jO($,O.id,O)}async fetch(){return Y(await this.client.storage.getCrmPipeline({path:{id:this.id}}))}name=this.field("name");recordType=this.field("recordType");accessLevel=this.field("grant");sharing=this.field("sharing");owner=this.mappedField("userId",($)=>M.byId(this.client,$));team=this.mappedField("teamId",($)=>_$.byId(this.client,$));async rename($){await this.mutate((O)=>O.storage.renameCrmPipeline({path:{id:this.id},body:{name:$}}))}async setSharing($){if($===void 0)throw Error("Sharing is required");await this.mutate((O)=>O.storage.shareCrmPipeline({path:{id:this.id},body:{sharing:$}}))}async setTrashed($){await this.mutate((O)=>O.storage.trashCrmPipeline({path:{id:this.id},body:{trashed:$}}))}async sharePermissions(){return Y(await this.client.storage.getCrmPipelinePermissions({path:{id:this.id}}))}async updateSharePermissions($){return this.mutate((O)=>O.storage.updateCrmPipelinePermissions({path:{id:this.id},body:$O($)}))}async table(){return Rj.from(this.client,this,await this.tableRecord())}async viewPositions($){if($.table.pipeline.id!==this.id)throw Error("View belongs to another pipeline");return Y(await this.client.storage.getCrmPipelineViewPositions({path:{id:this.id,view:$.id}}))}tableRecord(){return this.tableDetail.get()}rows(){return c(async($)=>{let O=Y(await this.client.storage.getCrmPipelineRows({path:{id:this.id},query:{after:$}}));return{items:O.rows.map((j)=>JO.from(this.client,this,j)),nextCursor:O.next}})}queryRows($={}){if($.rows?.some((O)=>O.pipeline.id!==this.id))throw Error("Rows belong to another pipeline");return c(async(O)=>{let j=Y(await this.client.storage.queryCrmPipelineRows({path:{id:this.id},body:{after:O,query:$.query,rowIds:$.rows?.map((x)=>x.id)}}));return{items:j.rows.map((x)=>JO.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 Rj extends A{pipeline;toJSON(){return{...super.toJSON(),pipelineId:this.pipeline.id}}constructor($,O,j){super($,j.table.id,j);this.pipeline=O}static from($,O,j){return new Rj($,O,j)}fetch(){return this.pipeline.tableRecord()}async columns(){return(await this.pipeline.tableRecord()).columns.map(($)=>_j.from(this.client,this,$))}async views(){return(await this.pipeline.tableRecord()).views.map(($)=>Dj.byId(this,$.id))}async version(){return(await this.pipeline.tableRecord()).table.version}rowById($){return JO.byId(this.client,this.pipeline,$)}rows(){return this.pipeline.rows()}}class Dj{table;id;constructor($,O){this.table=$;this.id=O}static byId($,O){return new Dj($,O)}async detail(){let $=(await this.table.pipeline.tableRecord()).views.find((O)=>O.id===this.id);if(!$)throw new E(`view ${this.id} is not on table ${this.table.id}`);return $}positions(){return this.table.pipeline.viewPositions(this)}toJSON(){return{id:this.id,tableId:this.table.id,pipelineId:this.table.pipeline.id}}}class JO extends A{pipeline;toJSON(){return{...super.toJSON(),pipelineId:this.pipeline.id}}constructor($,O,j,x){super($,j,x);this.pipeline=O}static byId($,O,j){return new JO($,O,j)}static from($,O,j){return new JO($,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 _j extends A{table;toJSON(){return{...super.toJSON(),pipelineId:this.table.pipeline.id,tableId:this.table.id}}constructor($,O,j){super($,j.column.id,j);this.table=O}static from($,O,j){return new _j($,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 Kx{client;constructor($){this.client=$}byId($){return jO.byId(this.client,$)}async list(){return Y(await this.client.storage.listCrmPipelines()).map(($)=>jO.from(this.client,$))}async create($){return jO.from(this.client,Y(await this.client.storage.createCrmPipeline({body:$})))}}class Qx{client;pipelines;constructor($){this.client=$;this.pipelines=new Kx($)}companyById($){return k$.byId(this.client,$)}contactById($){return P$.byId(this.client,$)}async contactByEmail($){let{contact:O}=Y(await this.client.storage.getContactByEmail({query:{email:$}}));return O?P$.from(this.client,O):void 0}async searchContacts($,O={}){let{contacts:j}=Y(await this.client.storage.searchContacts({query:{query:$,limit:O.limit}}));return j.map((x)=>P$.from(this.client,x))}async createCompany($){return k$.from(this.client,Y(await this.client.storage.createCrmCompany({body:$})))}async createContact($){return P$.from(this.client,Y(await this.client.storage.createCrmTeamContact({body:$})))}async blockedDomains(){return Y(await this.client.storage.listCrmBlockedDomains()).map(($)=>$.domain)}async blockDomain($){Y(await this.client.storage.blockCrmDomain({path:{domain:$}}))}async unblockDomain($){Y(await this.client.storage.unblockCrmDomain({path:{domain:$}}))}async settings(){return Y(await this.client.storage.getCrmTeamSettings())}async updateSettings($){return Y(await this.client.storage.putCrmTeamSettings({body:$}))}async setStages($){return Y(await this.client.storage.putCrmTeamStages({body:$}))}async resetStages(){Y(await this.client.storage.resetCrmTeamStages())}searchCompanies($){return k$.search(this.client,$)}}var Yx,D5=new Uint8Array(16);function Cj(){if(!Yx){if(typeof crypto>"u"||!crypto.getRandomValues)throw Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Yx=crypto.getRandomValues.bind(crypto)}return Yx(D5)}var j$=[];for(let $=0;$<256;++$)j$.push(($+256).toString(16).slice(1));function x2($,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 Gx={};function _5($,O,j){let x;if($)x=S2($.random??$.rng?.()??Cj(),$.msecs,$.seq,O,j);else{let S=Date.now(),K=Cj();C5(Gx,S,K),x=S2(K,Gx.msecs,Gx.seq,O,j)}return O??x2(x)}function C5($,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 S2($,O,j,x,S=0){if($.length<16)throw Error("Random bytes length must be >= 16");if(!x)x=new Uint8Array(16),S=0;else if(S<0||S+16>x.length)throw RangeError(`UUID byte range ${S}:${S+15} is out of buffer bounds`);return O??=Date.now(),j??=$[6]*127<<24|$[7]<<16|$[8]<<8|$[9],x[S++]=O/1099511627776&255,x[S++]=O/4294967296&255,x[S++]=O/16777216&255,x[S++]=O/65536&255,x[S++]=O/256&255,x[S++]=O&255,x[S++]=112|j>>>28&15,x[S++]=j>>>20&255,x[S++]=128|j>>>14&63,x[S++]=j>>>6&255,x[S++]=j<<2&255|$[10]&3,x[S++]=$[11],x[S++]=$[12],x[S++]=$[13],x[S++]=$[14],x[S++]=$[15],x}var c$=_5;class F${table;id;constructor($,O){this.table=$;this.id=O}static byId($,O){return new F$($,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 E${table;id;constructor($,O){this.table=$;this.id=O}static byId($,O){return new E$($,O)}history(){return this.table.database.rowHistory(this)}toJSON(){return{id:this.id,tableId:this.table.id}}}class Mj{table;id;constructor($,O){this.table=$;this.id=O}static byId($,O){return new Mj($,O)}async detail(){let{views:$}=await this.table.detail(),O=$.find((j)=>j.id===this.id);if(!O)throw new E(`view ${this.id} is not on table ${this.table.id}`);return O}async name(){return(await this.detail()).name}async position(){return(await this.detail()).position}async layout(){return(await this.detail()).layout}async query(){return(await this.detail()).query}positions(){return this.table.database.viewPositions(this)}toJSON(){return{id:this.id,tableId:this.table.id}}}class V${database;id;constructor($,O){this.database=$;this.id=O}static byId($,O){return new V$($,O)}async detail(){let{tables:$}=await this.database.schema(),O=$.find((j)=>j.table.id===this.id);if(!O)throw new E(`table ${this.id} is not in database ${this.database.id}`);return O}async name(){return(await this.detail()).table.name}async rename($){return await this.database.renameTable(this,$),this}async version(){return(await this.detail()).table.version}async position(){return(await this.detail()).table.position}async columns(){let{columns:$}=await this.detail();return $.map((O)=>F$.byId(this,O.column.id))}addColumn($){return this.database.addColumn(this,$)}async reorderColumns($){return await this.database.reorderColumns(this,$),this}row($){return E$.byId(this,$)}async views(){let{views:$}=await this.detail();return $.map((O)=>Mj.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 Aj($,O,j,x={}){let S=Y(await $.storage.queryDatabases({body:{sql:j,databaseId:x.database?.id,baseVersions:Object.fromEntries((x.baseVersions??[]).map(({table:G,version:J})=>[G.id,J]))}})),K=new Map;for(let G of[x.database,...(x.baseVersions??[]).map(({table:J})=>J.database)]){if(!G)continue;let J=K.get(G.id);if(J)J.add(G);else K.set(G.id,new Set([G]))}let Z=(G)=>{let J=K.get(G)?.values().next().value;if(J)return J;let I=O($,G);return K.set(G,new Set([I])),I},X=(G)=>{let J=S.tableDatabases[G];if(!J)throw Error(`SQL response is missing the owner of table ${G}`);return V$.byId(Z(J),G)},Q=new Set(Object.keys(S.newVersions).map((G)=>X(G).database.id));if(S.statement.kind==="schema")Q.add(S.statement.databaseId);for(let G of Q)for(let J of K.get(G)??[])J.invalidateSchema();let L=k(S.statement).with({kind:"select"},(G)=>G).with({kind:"schema"},({databaseId:G,summary:J})=>({kind:"schema",database:Z(G),summary:J})).with({kind:"insert"},{kind:"update"},{kind:"delete"},({kind:G,tableId:J,tableName:I})=>({kind:G,table:X(J),tableName:I})).with({kind:"alterColumnType"},({tableId:G,tableName:J,columnId:I,columnName:z,to:W})=>{let V=X(G);return{kind:"alterColumnType",table:V,tableName:J,column:F$.byId(V,I),columnName:z,to:W}}).exhaustive();return{result:S.result?M5(S.result,X,S.tableDatabases):void 0,changesApplied:S.changesApplied,insertedRows:L.kind==="insert"?S.insertedRowIds.map((G)=>E$.byId(L.table,G)):[],newVersions:Object.entries(S.newVersions).map(([G,J])=>({table:X(G),version:J})),readVersions:Object.entries(S.readVersions).map(([G,J])=>({table:X(G),version:J})),truncatedTables:S.truncatedTables,statement:L}}function M5($,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)=>E$.byId(x,S)):[]}}class Pj{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 Pj($,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 Wx extends e${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 Fj($){return k($).with({type:"relation"},({table:O})=>({type:"relation",database:O.database.id,table:O.id})).with({type:t.not("relation")},(O)=>O).exhaustive()}var A5={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 P5($){return k($).with({type:"text"},()=>"Text").with({type:"number"},()=>"Number").with({type:"boolean"},()=>"Checkbox").with({type:"date"},()=>"Date").with({type:"date_range"},()=>"Time range").with({type:"link"},()=>"URL").with({type:"select",multi:!0},()=>"Multi-select").with({type:"select",multi:!1},()=>"Select").with({type:"select_number",multi:!0},()=>"Multi-number select").with({type:"select_number",multi:!1},()=>"Number select").with({type:"tag"},()=>"Tag").with({type:"entity"},({target:O})=>A5[O]).with({type:"relation"},()=>"Relation").exhaustive(()=>"Column")}function Jx($){return $.map((O)=>({id:c$(),label:O}))}function Z2($,O,j){return $?.kind===O&&"change"in $&&$.change.kind===j}function Vx($){return k($).with({kind:"reorder_tables"},({kind:O})=>O).with({kind:t.union("table","column","rows","view")},({kind:O,change:j})=>`${O}.${j.kind}`).exhaustive(()=>"unknown")}function d$($,O,j){let[x]=$;if($.length!==1||!Z2(x,O,j))throw new w(`expected one ${O}.${j} result, got ${$.map(Vx).join(", ")||"none"}`);return x}class Y$ extends A{access=new $$(this.client,"database",this);async fetch(){return Y(await this.client.storage.getDatabase({path:{id:this.id}}))}assertOwns($,O){if(O.id!==this.id)throw new w(`${$} does not belong to database ${this.id}`)}static byId($,O){return new Y$($,O)}static async create($,O){let j=Y(await $.storage.createDatabase({body:{name:O.name}}));return new Y$($,j.id)}async duplicate($){let O=Y(await this.client.storage.duplicateDatabase({path:{id:this.id},body:{name:$?.name}}));return new Y$(this.client,O.id)}static async list($){return Y(await $.storage.listDatabases()).map((j)=>new Y$($,j.database.id))}query($,O){return Aj(this.client,Y$.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)=>V$.byId(this,O.table.id)));async table($){let{tables:O}=await this.schema(),j=O.find((x)=>x.table.name===$);return j?V$.byId(this,j.table.id):void 0}async createTable($){let{table:O}=d$(await this.applyOps([{kind:"table",table:c$(),change:{kind:"create",name:$.name}}]),"table","created");return V$.byId(this,O)}async applyOps($,O={}){let j={ops:$};if(O.baseVersions!==void 0){for(let{table:S}of O.baseVersions)this.assertOwns(`table ${S.id}`,S.database);j.baseVersions=Object.fromEntries(O.baseVersions.map(({table:S,version:K})=>[S.id,K]))}let{results:x}=await this.mutate(async(S)=>{let K=await S.storage.applyDatabaseOps({path:{id:this.id},body:j});if(K.error!==void 0&&"op"in K.error)throw new Wx(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 w(`expected one reorder_tables result, got ${O.map(Vx).join(", ")||"none"}`);return j.tables.map(({table:x})=>V$.byId(this,x))}async deleteTable($){this.assertOwns(`table ${$.id}`,$.database),d$(await this.applyOps([{kind:"table",table:$.id,change:{kind:"delete"}}]),"table","deleted")}async columnCasts($){return this.assertOwns(`column ${$.id}`,$.table.database),Y(await this.client.storage.listDatabaseColumnCasts({path:{id:this.id,table_id:$.table.id,column_id:$.id}}))}async viewPositions($){this.assertOwns(`view ${$.id}`,$.table.database);let{positions:O}=Y(await this.client.storage.getDatabaseViewPositions({path:{id:this.id,view_id:$.id}}));return O}async rowHistory($){this.assertOwns(`row ${$.id}`,$.table.database);let{changes:O}=Y(await this.client.storage.getDatabaseRowHistory({path:{id:this.id,table_id:$.table.id,row_id:$.id}}));return O}async importTable($){let O=await this.mutate((j)=>j.storage.importDatabaseTable({path:{id:this.id},body:$}));return V$.byId(this,O.id)}webhookOf($){return Pj.fromRecord(V$.byId(this,$.tableId),M.byId(this.client,$.createdBy),$)}async webhooks(){let{webhooks:$}=Y(await this.client.storage.listDatabaseWebhooks({path:{id:this.id}}));return $.map((O)=>this.webhookOf(O))}async createWebhook($){this.assertOwns("table",$.database);let O=Y(await this.client.storage.createDatabaseWebhook({path:{id:this.id},body:{tableId:$.id}}));return{webhook:this.webhookOf(O.webhook),token:O.token}}async deleteWebhook($){this.assertOwns("webhook",$.table.database),Y(await this.client.storage.deleteDatabaseWebhook({path:{id:this.id,webhook_id:$.id}}))}async sharePermissions(){return Y(await this.client.storage.getDatabasePermissions({path:{id:this.id}}))}updateSharePermissions($){return this.mutate((O)=>O.storage.updateDatabasePermissions({path:{id:this.id},body:$}))}async changeColumnType($,O){this.assertOwns(`column ${$.id}`,$.table.database);let j=await $.table.version();return d$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"change_type",to:Fj(O.to)}}],{baseVersions:[{table:$.table,version:j}]}),"column","type_changed")}async columnConversion($,O){return this.assertOwns(`column ${$.id}`,$.table.database),Y(await this.client.storage.convertDatabaseColumn({path:{id:this.id,table_id:$.table.id,column_id:$.id},body:{to:Fj(O)}}))}async convertColumnIntoNewColumn($,O){let j=await this.columnConversion($,O.to),x=O.name??`${await $.name()} (${P5(O.to)})`,S=c$(),K=[{kind:"column",table:$.table.id,column:S,change:{kind:"create",definition:{source:"new",name:x,type:Fj(O.to),options:Jx(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:Q})=>({row:X,cells:[{column:S,value:Q}]}))}}});let[Z]=await this.applyOps(K,{baseVersions:[{table:$.table,version:j.tableVersion}]});if(!Z2(Z,"column","created"))throw new w(`expected a column.created result, got ${Z?Vx(Z):"none"}`);return F$.byId($.table,Z.column)}async deleteColumn($){this.assertOwns(`column ${$.id}`,$.table.database);let O=await $.table.version(),{tableVersion:j}=d$(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 w(`column ${S.id} does not belong to table ${$.id}`);let j=await $.version(),{tableVersion:x}=d$(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 w(`table ${$.id} reordered its columns without a version`);return x}async renameTable($,O){this.assertOwns(`table ${$.id}`,$.database);let j=await $.name(),{tableVersion:x}=d$(await this.applyOps([{kind:"table",table:$.id,change:{kind:"rename",name:O,previousName:j}}]),"table","renamed");if(x===void 0)throw new w(`table ${$.id} was renamed without a version`);return x}async renameColumn($,O){this.assertOwns(`column ${$.id}`,$.table.database);let j=await $.name(),{tableVersion:x}=d$(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 w(`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:Fj(O.type),...O.options!==void 0?{options:Jx(O.options)}:{},...O.inferType!==void 0?{inferType:O.inferType}:{}},{column:x}=d$(await this.applyOps([{kind:"column",table:$.id,column:c$(),change:{kind:"create",definition:j,...O.after!==void 0?{after:O.after.id}:{}}}]),"column","created");return F$.byId($,x)}async addColumnOptions($,O){return this.assertOwns(`column ${$.id}`,$.table.database),d$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"add_options",options:Jx(O)}}]),"column","options_added")}}class Bx{client;constructor($){this.client=$}query($,O){return Aj(this.client,Y$.byId,$,O)}byId($){return Y$.byId(this.client,$)}create($){return Y$.create(this.client,$)}list(){return Y$.list(this.client)}}class VO extends A{document;toJSON(){return{...super.toJSON(),documentId:this.document.id}}constructor($,O,j,x){super($,j,x);this.document=O}static byId($,O,j){return new VO($,O,j)}static from($,O,j){return new VO($,O,j.uuid,j)}async fetch(){let $=Y(await this.client.storage.getDocumentAnchors({path:{document_id:this.document.id}})).data.find((O)=>O.uuid===this.id);if(!$)throw new E(`Annotation ${this.id} is unavailable`);return $}kind=this.field("anchorType");page=this.field("page");async edit($){if(await this.kind()!=="placeable")throw Error("Only placeable comment annotations can be edited");await this.mutate((O)=>O.storage.editAnchor({body:{...$,uuid:this.id,anchorType:"free-comment",fileType:"pdf"}}))}async delete(){if(await this.kind()!=="highlight")throw Error("Only standalone highlights can be deleted with this endpoint");await this.mutate(($)=>$.storage.deleteAnchor({body:{uuid:this.id,anchorType:"highlight",fileType:"pdf"}}))}}class l$ extends A{documentId;constructor($,O,j,x){super($,j,x);this.documentId=O}get path(){return{parent_type:"document",parent_id:this.documentId,id:this.id}}async fetch(){return Y(await this.client.storage.entityMessageGetMessage({path:this.path}))}static byId($,O,j){return new l$($,O,j)}static from($,O,j){return new l$($,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 f.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 oO{client;document;id;detail;constructor($,O,j){this.client=$;this.document=O;this.id=j;this.detail=new W$(async()=>Y(await this.client.storage.getDocumentVersion({path:{document_id:O.id,document_version_id:j}})).data)}static byId($,O,j){return new oO($,O,j)}read(){return this.detail.get()}toJSON(){return{id:this.id,documentId:this.document.id}}}var F5=8;class f extends K${async anchors(){return Y(await this.client.storage.getDocumentAnchors({path:{document_id:this.id}})).data.map(($)=>VO.from(this.client,this,$))}async createHighlight($){return VO.from(this.client,this,Y(await this.client.storage.createAnchor({path:{document_id:this.id},body:{...$,fileType:"pdf",anchorType:"highlight"}})))}version($){return oO.byId(this.client,this,$)}async sharePermissions(){return Y(await this.client.storage.getDocumentPermissionsV2({path:{document_id:this.id}})).documentPermissions}async permissionsToken(){return Y(await this.client.storage.getDocumentPermissionsToken({path:{document_id:this.id}})).token}async prepareSave($){return Y(await this.client.storage.presaveDocumentHandler({path:{document_id:this.id},body:{newBom:$}})).data}async save($){return(await this.mutate((O)=>O.storage.saveDocumentHandler({path:{document_id:this.id},body:$}))).data}async simpleSave(){return(await this.mutate(($)=>$.storage.simpleSave({path:{document_id:this.id}}))).data}messageThreadById($){return L$.byId(this.client,{type:"document",entity:this},$)}timelinePage($){return b$(this.client,{type:"document",entity:this},(O)=>l$.from(this.client,this.id,O),$)}access=new $$(this.client,"document",this);async fetch(){let{data:$}=Y(await this.client.storage.getDocument({path:{document_id:this.id}}));return $.documentMetadata}static byId($,O){return new f($,O)}static async create($,O){let{documentId:j}=Y(await $.storage.createMarkdownHandler({body:{documentName:O.name,markdown:O.markdown??null,projectId:O.project?.id??null}}));return new f($,j)}static async createSnippet($,O){let{documentId:j}=Y(await $.storage.createSnippetHandler({body:{snippetName:O.name,markdown:O.markdown??null,projectId:O.project?.id??null}}));return new f($,j)}static async createSkill($,O){let{documentId:j}=Y(await $.storage.createSkillHandler({body:{skillName:O.name,markdown:O.markdown??null,projectId:O.project?.id??null}}));return new f($,j)}static recent($,O){let j=O?.pageSize??50;return c(async(x)=>{let S=Y(await $.storage.getUserDocumentsHandler({query:{limit:j,offset:x?Number(x):0,...O?.fileType!==void 0?{file_type:O.fileType}:{}}})),K=S.data?.next_offset;return{items:(S.data?.documents??[]).map((Z)=>new f($,Z.documentId)),nextCursor:K!=null?String(K):null}})}static async recentlyDeleted($){let{data:O}=Y(await $.storage.recentlyDeleted({}));return O.items.filter((j)=>j.type==="document").map((j)=>new f($,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",($)=>$?f.byId(this.client,$):void 0);createdAt=this.field("createdAt");updatedAt=this.field("updatedAt");deletedAt=this.field("deletedAt");async content(){let{text:$}=Y(await this.client.storage.getDocumentTextContent({path:{document_id:this.id}}));if($!==null)return $;let{presigned_url:O}=Y(await this.client.storage.exportDocument({path:{document_id:this.id}})),j=await fetch(O);if(!j.ok)throw new e$(j.status,{message:"failed to download document content"});return j.text()}async rename($){await this.mutate((O)=>O.storage.editDocument({path:{document_id:this.id},body:{documentName:$}}))}async move($){await this.mutate((O)=>O.storage.editDocument({path:{document_id:this.id},body:{projectId:$?.id??""}}))}async delete($){await this.mutate((O)=>$?.permanent?O.storage.permanentlyDeleteDocument({path:{document_id:this.id}}):O.storage.deleteDocument({path:{document_id:this.id}}))}async restore(){await this.mutate(($)=>$.storage.revertDeleteDocument({path:{document_id:this.id}}))}async copy($){let{data:O}=Y(await this.client.storage.copyDocument({path:{document_id:this.id},query:$.versionId!==void 0?{version_id:$.versionId}:void 0,body:{documentName:$.name}}));return new f(this.client,O.documentMetadata.documentId)}async comments(){let $={parent_type:"document",parent_id:this.id},O=c(async(x)=>{let S=Y(await this.client.storage.messageTimeline({path:$,query:{selection:JSON.stringify({limit:100,cursor:x})}}));return{items:S.items,nextCursor:S.next_cursor}}),j=[];for await(let x of O)j.push(x);return dO(j,F5,async(x)=>{let{state:S,root:K,replies:Z}=Y(await this.client.storage.entityMessageGetThread({path:{...$,id:x.id}}));return{thread:S,comments:[K,...Z].map((X)=>l$.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 l$.from(this.client,this.id,j)}async shortId(){return Y(await this.client.storage.getDocumentShortId({path:{document_id:this.id}}))}async teamShare(){return Y(await this.client.storage.getDocumentTeamShare({path:{document_id:this.id}}))}async setTeamShare($){await this.mutate((O)=>O.storage.setDocumentTeamShare({path:{document_id:this.id},body:{shareWithTeam:$}}))}async githubPullRequests(){let{pullRequests:$}=Y(await this.client.storage.getDocumentGithubPullRequests({path:{document_id:this.id}}));return $}async branchName(){let{branchName:$}=Y(await this.client.storage.getDocumentBranchName({path:{document_id:this.id}}));return $}webUrl(){return`${this.client.webAppUrl}/app/md/${this.id}`}static search=x$({filters:{document_filters:{}},type:"document",make:($,O)=>new f($,O.document_id)});toMention(){let $=this.detail.peek();return{tag:o$("m-document-mention",{documentId:this.id,documentName:$?.documentName??"",blockName:$?.fileType??"md"}),mention:{entity_type:"document",entity_id:this.id}}}}class Ej{id;name;constructor($,O){this.id=$;this.name=O}static async list($){let{skills:O}=Y(await $.storage.getSystemSkillsHandler());return O.map((j)=>new Ej(j.id,j.name))}}class Lx{client;async byTeamSlug($){let O=Y(await this.client.storage.getDocumentByTeamSlug({path:{slug:$}}));if(typeof O!=="object"||O===null||!("data"in O)||typeof O.data!=="object"||O.data===null||!("documentMetadata"in O.data)||typeof O.data.documentMetadata!=="object"||O.data.documentMetadata===null||!("documentId"in O.data.documentMetadata)||typeof O.data.documentMetadata.documentId!=="string")throw Error("Invalid team task document response");return f.byId(this.client,O.data.documentMetadata.documentId)}async validatePermissionsToken($){let O=Y(await this.client.storage.validateDocumentPermissionsToken({body:{token:$}}));return{document:f.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=Y(await this.client.storage.createDocument({body:O})).data;return{document:f.byId(this.client,j.documentMetadata.documentId),uploadUrl:j.presignedUrl??void 0,contentType:j.contentType,content:j.documentMetadata.content}}constructor($){this.client=$}byId($){return f.byId(this.client,$)}create($){return f.create(this.client,$)}async createCanvas($){let O=Y(await this.client.storage.createCanvasHandler({body:{documentName:$.name,projectId:$.project?.id}}));return f.byId(this.client,O.documentId)}createSnippet($){return f.createSnippet(this.client,$)}createSkill($){return f.createSkill(this.client,$)}systemSkills(){return Ej.list(this.client)}search($,O){return f.search(this.client,$,O)}recent($){return f.recent(this.client,$)}recentlyDeleted(){return f.recentlyDeleted(this.client)}}class WO extends A{async fetch(){let{attachment:$}=Y(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:$}=Y(await this.client.email.getAttachmentDocumentId({path:{id:this.id}}));return f.byId(this.client,$)}}class z$ extends K${access=new $$(this.client,"email_thread",this);async followup(){return Y(await this.client.storage.getEmailFollowup({path:{thread_id:this.id}}))}async setFollowup($){return Y(await this.client.storage.setEmailFollowup({path:{thread_id:this.id},body:$}))}async calendarInvitations(){return Y(await this.client.email.getThreadCalendarInvitations({path:{thread_id:this.id}}))}async addEventToCalendar($,O,j={}){let x=Y(await this.client.email.copyThreadCalendarInvitation({path:{thread_id:this.id,message_id:$.id,invitation_id:O.id},body:{calendarId:j.calendar?.id}}));return S$.fromRecord(this.client,x)}async readReceipts(){let{receipts:$}=Y(await this.client.email.getThreadReadReceipts({path:{thread_id:this.id}}));return $.map((O)=>({message:U$.byId(this.client,O.message_id),openCount:O.open_count,firstOpenedAt:O.first_opened_at??void 0,lastOpenedAt:O.last_opened_at??void 0}))}async update($){await this.mutate((O)=>O.storage.editThreadV2({path:{thread_id:this.id},body:{projectId:$.project===void 0?void 0:$.project?.id??null,sharePermission:$.sharePermission?$O($.sharePermission):void 0}}))}entityType="email_thread";propertyEntityType="THREAD";async fetch(){let{thread:$}=Y(await this.client.email.getThread({path:{thread_id:this.id},query:{limit:100}}));return $}static byId($,O){return new z$($,O)}createdAt=this.field("created_at");updatedAt=this.field("updated_at");isRead=this.field("is_read");inboxVisible=this.field("inbox_visible");accessLevel=this.field("access_level");providerId=this.field("provider_id");link=this.mappedField("link_id",($)=>R$.byId(this.client,$));project=this.mappedField("project_id",($)=>$?n.byId(this.client,$):void 0);latestInboundAt=this.field("latest_inbound_message_ts");latestOutboundAt=this.field("latest_outbound_message_ts");latestNonSpamAt=this.field("latest_non_spam_message_ts");async subject(){let{messages:$}=await this.detail.get();for(let O of $)if(O.subject)return O.subject;return}async participants(){let{messages:$}=await this.detail.get(),O=new Map;for(let j of $)for(let x of[j.from,...j.to,...j.cc,...j.bcc])if(x&&!O.has(x.email))O.set(x.email,x);return[...O.values()]}async messages($){return Y(await this.client.email.getThreadMessagesHandler({path:{id:this.id},query:{...$?.since?{since:$.since}:{},...$?.limit?{limit:$.limit}:{}}})).map((j)=>U$.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?U$.byId(this.client,j.db_id):void 0}async archive($=!0){await this.mutate((O)=>O.email.archiveThread({path:{id:this.id},body:{value:$}}))}static async archiveMany($,O,j=!0){let x=[];for(let S=0;S<O.length;S+=100){let K=O.slice(S,S+100),Z=Y(await $.email.archiveThreads({body:{thread_ids:K.map((Q)=>Q.id),value:j}})),X=new Set(Z.failed_thread_ids);for(let Q of K)if(Q.detail.clear(),X.has(Q.id))x.push(Q)}return x}async updateState($){await this.mutate((O)=>O.email.updateThreadState({path:{id:this.id},body:$}))}async operations(){return Y(await this.client.email.threadOperations({path:{id:this.id}}))}async markSeen(){await this.mutate(($)=>$.email.threadSeen({path:{id:this.id}}))}async addLabel($){await this.mutate((O)=>O.email.addRemoveThreadLabel({path:{id:this.id},body:{label_id:$.id,value:!0}}))}async removeLabel($){await this.mutate((O)=>O.email.addRemoveThreadLabel({path:{id:this.id},body:{label_id:$.id,value:!1}}))}async moveToProject($){await this.mutate((O)=>O.email.updateThreadProject({path:{thread_id:this.id},body:{projectId:$?.id??null}}))}static search=x$({filters:{email_filters:{}},type:"email",make:($,O)=>new z$($,O.thread_id)})}class U$ extends A{async fetch(){return Y(await this.client.email.getMessage({path:{id:this.id}}))}static byId($,O){return new U$($,O)}static from($,O){return new U$($,O.db_id,O)}static async send($,O){let{message:j}=Y(await $.email.sendMessage({body:{message:{to:O.to,cc:O.cc??null,bcc:O.bcc??null,subject:O.subject,body_text:O.bodyText}}}));return j.db_id?U$.byId($,j.db_id):void 0}subject=this.field("subject");from=this.field("from");to=this.field("to");cc=this.field("cc");bcc=this.field("bcc");body=this.field("body_parsed");sentAt=this.field("internal_date_ts");labels=this.field("labels");link=this.mappedField("link_id",($)=>R$.byId(this.client,$));async operationStatus(){return Y(await this.client.email.messageOperationStatus({path:{id:this.id}}))}async resolveOperation($){await this.mutate((O)=>O.email.resolveMessageOperation({path:{id:this.id},body:$}))}async completeDraftAttachment($,O=0){let j=await this.link();await this.mutate((x)=>x.email.completeDraftAttachment({path:{id:this.id,attachment_id:$},query:{draft_generation:O},headers:{"X-Email-Link-Id":j.id}}))}async transferDraft($){let O=await this.detail.get();return this.mutate((j)=>j.email.transferDraft({path:{id:this.id},body:{...$,draft_generation:$.draft_generation??O.draft_generation??0},headers:{"X-Email-Link-Id":O.link_id}}))}async addLabel($){await this.mutate((O)=>O.email.addRemoveLabel({body:{label_id:$.id,message_ids:[this.id],value:!0}}))}async removeLabel($){await this.mutate((O)=>O.email.addRemoveLabel({body:{label_id:$.id,message_ids:[this.id],value:!1}}))}async thread(){return z$.byId(this.client,(await this.detail.get()).thread_db_id)}async downloadEml(){return Y(await this.client.email.getMessageEml({path:{id:this.id},parseAs:"blob"}))}}class BO extends U${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:{...Nx($),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:$j.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 $j.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 $j{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 $j(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 Nx($){let{bodyText:O,bodyHtml:j,bodyMacro:x,headers:S,includeSignature:K,draftGeneration:Z,thread:X,replyingTo:Q,...L}=$;return{...L,body_text:O,body_html:j===void 0?void 0:btoa(Array.from(new TextEncoder().encode(j),(G)=>String.fromCharCode(G)).join("")).replaceAll("+","-").replaceAll("/","_").replaceAll("=",""),body_macro:x,headers_json:S,include_signature:K,draft_generation:Z,thread_db_id:X?.id,replying_to_id:Q?.id}}class LO extends A{inbox;constructor($,O,j,x){super($,O,j);this.inbox=x}get headers(){return this.inbox?{"X-Email-Link-Id":this.inbox.id}:void 0}static byId($,O,j){return new LO($,O,void 0,j)}static from($,O,j){return new LO($,O.id,O,j)}async fetch(){let $=Y(await this.client.email.listEmailFilters({headers:this.headers})).filters.find((O)=>O.id===this.id);if(!$)throw new E(`Email filter ${this.id} is unavailable`);return $}emailAddress=this.field("email_address");emailDomain=this.field("email_domain");isImportant=this.field("is_important");async setImportant($){let O=await this.detail.get();await this.mutate((j)=>j.email.upsertEmailFilter({headers:this.headers,body:{email_address:O.email_address,email_domain:O.email_domain,is_important:$}}))}async delete(){await this.mutate(($)=>$.email.deleteEmailFilter({path:{id:this.id},headers:this.headers}))}}class xO extends A{async fetch(){let{labels:$}=Y(await this.client.email.listLabels()),O=$.find((j)=>j.id===this.id);if(!O)throw new E(`label ${this.id} not found`);return O}static byId($,O){return new xO($,O)}static async list($){let{labels:O}=Y(await $.email.listLabels());return O.map((j)=>new xO($,j.id,j))}static async create($,O){let{label:j}=Y(await $.email.createLabel({body:{label_name:O}}));if(!j.id)throw new w("created label has no id");return new xO($,j.id)}async delete(){Y(await this.client.email.deleteLabel({path:{id:this.id}}))}name=this.field("name");linkId=this.field("linkId");type=this.field("type");createdAt=this.field("createdAt");labelListVisibility=this.field("labelListVisibility");messageListVisibility=this.field("messageListVisibility")}class Ux{client;async createDraft($,O){let j=Y(await this.client.email.createDraft({body:{draft:Nx($)},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=Y(await this.client.email.getScheduledMessages({query:{offset:x,limit:j},headers:$?.inbox?{"X-Email-Link-Id":$.inbox.id}:void 0}));for(let K of S.messages)yield BO.byId(this.client,K.db_id);if(S.messages.length<j)return}}async filters($){return Y(await this.client.email.listEmailFilters({headers:$?{"X-Email-Link-Id":$.id}:void 0})).filters.map((O)=>LO.from(this.client,O,$))}async upsertFilter($,O){return LO.from(this.client,Y(await this.client.email.upsertEmailFilter({headers:O?{"X-Email-Link-Id":O.id}:void 0,body:{email_address:$.emailAddress,email_domain:$.emailDomain,is_important:$.isImportant}})).filter,O)}async contacts(){return Y(await this.client.email.listContacts()).contacts}reminders($){let{inboxes:O,...j}=$??{};return c(async(x)=>{let S=Y(await this.client.storage.listEmailReminders({query:{...j,inboxIds:O?.map((K)=>K.id),cursor:x}}));return{items:S.items.map(({threadId:K,...Z})=>({...Z,thread:z$.byId(this.client,K)})),nextCursor:S.nextCursor}})}constructor($){this.client=$}byId($){return z$.byId(this.client,$)}message($){return U$.byId(this.client,$)}attachment($){return WO.byId(this.client,$)}link($){return R$.byId(this.client,$)}links(){return R$.list(this.client)}async connectionProviders(){return Y(await this.client.auth.emailConnectionProviders())}async recoverDraftTransfer($){return Y(await this.client.email.recoverDraftTransfer({path:{id:$}}))}send($){return U$.send(this.client,$)}search($,O){return z$.search(this.client,$,O)}inbox($){return c(async(O)=>{let j=Y(await this.client.email.previewsInboxCursor({path:{view:"inbox"},query:{...$?.pageSize?{limit:$.pageSize}:{},...$?.sort?{sort_method:$.sort}:{},...O?{cursor:O}:{}}}));return{items:j.items.map((x)=>z$.byId(this.client,x.id)),nextCursor:j.next_cursor}})}label($){return xO.byId(this.client,$)}labels(){return xO.list(this.client)}createLabel($){return xO.create(this.client,$)}archive($,O=!0){return z$.archiveMany(this.client,$,O)}async deleteLabel($){Y(await this.client.email.deleteLabel({path:{id:$.id}}))}async blockSender($){Y(await this.client.email.blockSender({body:{email_address:$}}))}async unblockSender($){Y(await this.client.email.unblockSender({body:{email_address:$}}))}async blockedSenders(){return Y(await this.client.email.listBlockedSenders()).blocked_emails}}class TO{client;id;constructor($,O){this.client=$;this.id=O}static byId($,O){return new TO($,O)}async delete(){Y(await this.client.storage.deleteEntityMention({path:{mention_id:this.id}}))}toJSON(){return{id:this.id}}}class zx{client;constructor($){this.client=$}byId($){return TO.byId(this.client,$)}async create($,O){let j=Y(await this.client.storage.createEntityMention({body:{source_entity_id:$.entity.id,source_entity_type:$.type,entity_id:O.entity.id,entity_type:O.type}}));return TO.byId(this.client,j.id)}}function Ix($,O){return{chat:NO.byId($,O.id),name:O.name,announcements:O.announcements}}class NO extends A{static byId($,O){return new NO($,O)}static from($,O){return new NO($,O.jid,O)}async fetch(){let{chats:$}=Y(await this.client.storage.whatsappChats()),O=$.find((j)=>j.jid===this.id);if(!O)throw new E("WhatsApp chat is not available");return O}kind=this.field("kind");name=this.field("name");phoneNumber=this.field("phoneNumber");lastActivityAt=this.field("lastActivityAt");archived=this.field("archived");pinned=this.field("pinned");canAdd=this.field("canAdd");cannotAddReason=this.field("cannotAddReason");community=this.mappedField("community",($)=>$?Ix(this.client,$):void 0);added=this.mappedField("added",($)=>$?g$.byId(this.client,$.id):void 0);shared=this.mappedField("shared",($)=>$?g$.byId(this.client,$.id):void 0);async add(){let $=await this.kind(),O=await this.mutate((j)=>j.storage.externalChatAdd({body:{provider:"whatsapp",remoteId:this.id,kind:$}}));return g$.byId(this.client,O.chatId)}async refresh(){return this.detail.clear(),await this.detail.get(),this}}class C$ extends A{chat;constructor($,O,j,x){super($,j,x);this.chat=O}static byId($,O,j){return new C$($,O,j)}static from($,O,j){return new C$($,O,j.id,j)}async fetch(){return Y(await this.client.storage.externalChatMessage({path:{chat_id:this.chat.id,message_id:this.id}}))}body=this.field("body");sender=this.field("sender");sentAt=this.field("sentAt");editedAt=this.field("editedAt");deleted=this.field("deleted");reactions=this.field("reactions");deliveryState=this.field("deliveryState");kind=this.field("kind");forwarded=this.field("forwarded");viewOnce=this.field("viewOnce");mentions=this.field("mentions");rich=this.field("rich");replyTo=this.mappedField("replyTo",($)=>$?C$.byId(this.client,this.chat,$):void 0);attachments=this.mappedField("attachments",($)=>$.map((O)=>({ordinal:O.ordinal,state:O.state,fileName:O.fileName,mime:O.mime,size:O.size,width:O.width??void 0,height:O.height??void 0,durationSeconds:O.durationSeconds??void 0,presentation:O.presentation??void 0,url:O.fileId?`${this.client.hosts["static-files"]}/file/${O.fileId}`:void 0})))}class SO{chat;id;record;constructor($,O,j){this.chat=$;this.id=O;this.record=j}static byId($,O){return new SO($,O)}static from($,O){return new SO($,O.jid,O)}get displayName(){return this.record?.displayName??void 0}get mentionToken(){return this.id.split("@")[0]??this.id}get admin(){return this.record?.admin}toJSON(){return{id:this.id,chat:this.chat.id,displayName:this.displayName,admin:this.admin}}}class ZO{id;chat;filename;kind;constructor($,O,j,x){this.id=$;this.chat=O;this.filename=j;this.kind=x}static byId($,O){return new ZO(O,$)}static from($,O){return new ZO(O.uploadId,$,O.filename,O.kind)}toJSON(){return{id:this.id,chat:this.chat.id,filename:this.filename,kind:this.kind}}}class XO extends A{chat;constructor($,O,j,x){super($,j,x);this.chat=O}static byId($,O,j){return new XO($,O,j)}static from($,O,j){return new XO($,O,j.id,j)}async fetch(){let O=Y(await this.client.storage.externalChatDelivery({path:{chat_id:this.chat.id},body:[this.id]})).find((j)=>j.id===this.id);if(!O)throw new E("External chat send is not available");return O}state=this.field("state");errorCode=this.field("errorCode");createdAt=this.field("createdAt");message=this.mappedField("messageId",($)=>$?C$.byId(this.client,this.chat,$):void 0);async request(){let{payload:$}=await this.detail.get(),O=$.message,j=k(O).returnType().with({type:"media"},(x)=>({type:"media",upload:ZO.byId(this.chat,x.uploadId),caption:x.caption??void 0})).with({type:"mutation"},(x)=>({type:"mutation",message:C$.byId(this.client,this.chat,x.messageId),operation:x.operation,text:x.text??void 0})).with({type:"text"},(x)=>({type:"text",text:x.text,mentions:(x.mentions??[]).map((S)=>SO.byId(this.chat,S))})).exhaustive();return{idempotencyKey:$.idempotencyKey,message:j,replyTo:$.replyTo?C$.byId(this.client,this.chat,$.replyTo):void 0}}async refresh(){return this.detail.clear(),await this.detail.get(),this}}class g$ extends H${entityType="external_chat";static byId($,O){return new g$($,O)}async fetch(){return Y(await this.client.storage.externalChat({path:{chat_id:this.id}}))}provider=this.field("provider");name=this.field("name");kind=this.field("kind");canSend=this.field("canSend");sendReason=this.field("sendReason");sendingIdentity=this.field("sendingIdentity");unreadCount=this.field("unreadCount");backfill=this.field("backfill");limits=this.field("limits");members=this.field("members");participants=this.mappedField("members",($)=>($?.participants??[]).map((O)=>SO.from(this,O)));disappearingSeconds=this.field("disappearingSeconds");owner=this.mappedField("userId",($)=>M.byId(this.client,$));async community(){let{provider:$,community:O}=await this.detail.get();if(!O)return;return k($).with("whatsapp",()=>Ix(this.client,O)).exhaustive()}async*messages($={}){yield*c(async(O)=>{let j=Y(await this.client.storage.externalChatMessages({path:{chat_id:this.id},query:{before:O,limit:$.limit}}));return{items:j.messages.map((x)=>C$.from(this.client,this,x)),nextCursor:j.nextCursor}})}async markRead($){this.assertChat($.chat),await this.mutate((O)=>O.storage.externalChatRead({path:{chat_id:this.id},body:{messageId:$.id}}))}async permissions(){return Y(await this.client.storage.externalChatPermissions({path:{chat_id:this.id}}))}async updatePermissions($){await this.mutate((O)=>O.storage.externalChatUpdatePermissions({path:{chat_id:this.id},body:$}))}async remove(){await this.mutate(($)=>$.storage.externalChatRemove({path:{chat_id:this.id}}))}async upload($){let O=Y(await this.client.storage.externalChatUpload({path:{chat_id:this.id},body:{file:$}}));return ZO.from(this,O)}async send($,O){if(O.replyTo)this.assertChat(O.replyTo.chat);let j=k($).returnType().with({type:"text"},(S)=>{let K=S.mentions??[];for(let Z of K)this.assertChat(Z.chat);return{type:"text",text:S.text,mentions:K.map((Z)=>Z.id)}}).with({type:"media"},(S)=>{return this.assertChat(S.upload.chat),{type:"media",uploadId:S.upload.id,caption:S.caption}}).with({type:"mutation"},(S)=>{return this.assertChat(S.message.chat),{type:"mutation",messageId:S.message.id,operation:S.operation,text:S.text}}).exhaustive(),x=await this.mutate((S)=>S.storage.externalChatSend({path:{chat_id:this.id},body:{idempotencyKey:O.idempotencyKey,message:j,replyTo:O.replyTo?.id}}));return XO.from(this.client,this,x)}async sends(){return Y(await this.client.storage.externalChatSends({path:{chat_id:this.id}})).map(($)=>XO.from(this.client,this,$))}async delivery($){for(let O of $)this.assertChat(O.chat);return Y(await this.client.storage.externalChatDelivery({path:{chat_id:this.id},body:$.map((O)=>O.id)})).map((O)=>XO.from(this.client,this,O))}async messageAttachments($){for(let O of $)this.assertChat(O.chat);return Y(await this.client.storage.externalChatMessageAttachments({path:{chat_id:this.id},body:$.map((O)=>O.id)})).map((O)=>({message:C$.byId(this.client,this,O.messageId),attachments:O.attachments.map((j)=>({ordinal:j.ordinal,state:j.state,fileName:j.fileName,mime:j.mime,size:j.size,url:j.fileId?`${this.client.hosts["static-files"]}/file/${j.fileId}`:void 0}))}))}async refresh(){return this.detail.clear(),await this.detail.get(),this}assertChat($){if($.id!==this.id)throw Error("External chat reference belongs to another chat")}}class Hx{client;constructor($){this.client=$}async list(){return Y(await this.client.storage.externalChats()).map(($)=>g$.byId(this.client,$.id))}byId($){return g$.byId(this.client,$)}}class Tx{client;constructor($){this.client=$}async list($={}){let{favorites:O}=Y(await this.client.storage.listFavorites({query:{entityType:$.entityTypes,entityId:$.entityIds}}));return O}async add($){return Y(await this.client.storage.addFavorite({body:{entityId:$.id,entityType:$.entityType}}))}async remove($){Y(await this.client.storage.removeFavoriteByEntity({path:{entity_type:$.entityType,entity_id:$.id}}))}async reorder($){Y(await this.client.storage.reorderFavorites({body:{favorites:$}}))}}class KO extends H${entityType="foreign_entity";async fetch(){return Y(await this.client.storage.getForeignEntity({path:{id:this.id}}))}static byId($,O){return new KO($,O)}static fromRecord($,O){return new KO($,O.id,O)}foreignEntityId=this.field("foreignEntityId");source=this.field("foreignEntitySource");storedForId=this.field("storedForId");storedForAuthEntity=this.field("storedForAuthEntity");createdAt=this.field("createdAt");updatedAt=this.field("updatedAt");async metadata(){return(await this.detail.get()).metadata}}function X2({login:$,...O}){return{...O,login:$??void 0}}class Rx{client;constructor($){this.client=$}byId($){return KO.byId(this.client,$)}async bySource($,O){return KO.fromRecord(this.client,Y(await this.client.storage.getForeignEntityBySource({path:{source:$,foreign_entity_id:O}})))}async githubPullRequestFacets(){let{repositories:$,authors:O,assignees:j,labels:x}=Y(await this.client.storage.getGithubPullRequestFacets());return{repositories:$,authors:O.map(X2),assignees:j.map(X2),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 F$.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 W$(()=>this.load(),j)}async load(){let $=await this.form.myResponse();if($.kind==="anonymous"||$.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 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 qj{entityType;id;constructor($,O){this.entityType=$;this.id=O}static byId($,O){return new qj($,O)}}class y$ extends A{async fetch(){return Y(await this.client.storage.getForm({path:{id:this.id}}))}static byId($,O){return new y$($,O)}static async create($,O){let j=Y(await $.storage.createForm({body:{name:O.name,source:O.table?{kind:"table",databaseId:O.table.database.id,tableId:O.table.id}:{kind:"new"}}}));return new y$($,j.form.id,j)}static async list($,O){if(!O)return Y(await $.storage.listAccessibleForms()).map(({form:S})=>new y$($,S.id));return Y(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",($)=>Y$.byId(this.client,$.databaseId));table=this.mappedField("form",($)=>V$.byId(Y$.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 w(`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 w(`column does not belong to form ${this.id}'s table`);return Z.id},x=(Z)=>({conjunction:Z.conjunction,conditions:Z.conditions.map((X)=>k(X).with({kind:"group"},(Q)=>({kind:"group",...x(Q)})).with({kind:"condition"},(Q)=>({kind:"condition",column:j(Q.column),test:k(Q.test).with({kind:"options"},(L)=>({...L,options:L.options.map((G)=>G.id)})).with({kind:"entities"},(L)=>({...L,entities:L.entities.map((G)=>G.id)})).with({kind:t.union("presence","text","number","date","dateRange","checkbox")},(L)=>L).exhaustive()})).exhaustive())}),S={sections:$.map((Z)=>{if(Z.section)this.assertOwns(Z.section);let X={id:Z.section?.id??c$(),title:Z.title,description:Z.description??""};return k(Z).with({kind:"booking"},(Q)=>({...X,kind:"booking",target:Q.target})).with({kind:"gate"},(Q)=>({...X,kind:"gate",rules:x(Q.rules),message:Q.message})).with({kind:"questions"},(Q)=>({...X,kind:"questions",questions:Q.questions.map((L)=>{if(L.question)this.assertOwns(L.question);return{id:L.question?.id??c$(),column:j(L.column),helpText:L.helpText??"",required:L.required??!1,widget:L.widget??null}})})).exhaustive()})},K=await this.mutate((Z)=>Z.storage.putFormLayout({path:{id:this.id},body:S}));return{form:this,publicationError:K.publicationError}}wireAnswers($){return $.map(({question:O,value:j})=>{this.assertOwns(O);let x=k(j).with({type:"rows"},(S)=>({type:"rows",value:S.value.map((K)=>K.id)})).with({type:"options"},(S)=>({type:"options",value:S.value.map((K)=>{if(K.question.id!==O.id||K.question.form.id!==this.id)throw new w("option does not belong to the answered question");return{id:K.id}})})).with({type:"entities"},(S)=>({type:"entities",value:S.value.map(({entityType:K,entity:Z})=>({entityType:K,entityId:Z.id}))})).with({type:t.union("text","number","boolean","date","date_range","link","clear")},(S)=>S).exhaustive();return{question:O.id,value:x}})}unlockedBooking($){return $?{...$,section:p$.byId(this,$.section)}:void 0}async outcome($,O){return k($).with({outcome:"stopped"},(j)=>({...j,section:p$.byId(this,j.section)})).with({outcome:"submitted"},async(j)=>{let x=E$.byId(await this.table(),j.row),S=this.unlockedBooking(j.booking);return{outcome:"submitted",response:RO.byId(this,j.response,{status:"submitted",row:x,answers:O,booking:S}),row:x,...S?{booking:S}:{}}}).exhaustive()}async submit($){let O={answers:this.wireAnswers($)};return this.outcome(Y(await this.client.storage.submitFormResponse({path:{id:this.id},body:O})),$)}async editResponse($){let O={answers:this.wireAnswers($)};return this.outcome(Y(await this.client.storage.editMyFormResponse({path:{id:this.id},body:O})),$)}async myResponse(){let $=Y(await this.client.storage.getMyFormResponse({path:{id:this.id}}));if($.kind==="anonymous")return{kind:"anonymous"};let O=await this.table(),j=await Promise.all($.answers.map(async(K)=>{let Z=r$.byId(this,K.question),X=await k(K.value).with({type:"options"},(Q)=>({type:"options",value:Q.value.map((L)=>{if(!("id"in L))throw new w("stored form answers must reference options by id");return UO.byId(Z,L.id)})})).with({type:"entities"},(Q)=>({type:"entities",value:Q.value.map((L)=>({entityType:L.entityType,entity:qj.byId(L.entityType,L.entityId)}))})).with({type:"rows"},async(Q)=>{let L=await Z.detail();if(L.kind.type!=="relation")throw new w("row answer requires a relation question");let G=V$.byId(Y$.byId(this.client,L.kind.database),L.kind.table);return{type:"rows",value:Q.value.map((J)=>E$.byId(G,J))}}).with({type:t.union("text","number","boolean","date","date_range","link","clear")},(Q)=>Q).exhaustive(()=>{throw new w(`answer to question ${Z.id} has a type this SDK doesn't know`)});return{question:Z,value:X}})),x=$.response.row?E$.byId(O,$.response.row):void 0,S=this.unlockedBooking($.booking);return{kind:"saved",...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 $=Y(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 Y(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)=>k(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 Y(await this.client.storage.getFormPermissions({path:{id:this.id}}))}updateSharePermissions($){return this.mutate((O)=>O.storage.updateFormPermissions({path:{id:this.id},body:$}))}webUrl(){return`${this.client.webAppUrl}/app/form/${this.id}`}respondUrl(){return`${this.client.webAppUrl}/app/form/${this.id}/respond`}}class Dx{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 A{static byId($,O){return new DO($,O)}async fetch(){return Y(await this.client.storage.getGithubPullRequest({path:{id:this.id}}))}title=this.field("title");url=this.field("url");status=this.field("status");async changes(){let $=Y(await this.client.storage.getGithubPullRequestChanges({path:{id:this.id}}));return{changeset:$.changeset?new _x(this.client,this,$.changeset):void 0,error:$.error??void 0}}}class _x{client;pullRequest;record;constructor($,O,j){this.client=$;this.pullRequest=O;this.record=j}get id(){return this.record.id}async patch(){return Y(await this.client.storage.getGithubPullRequestChangesPatch({path:{id:this.pullRequest.id},query:{changeset:this.id}})).patch}toJSON(){return{pullRequestId:this.pullRequest.id,...this.record}}}class Cx{client;constructor($){this.client=$}byId($){return DO.byId(this.client,$)}forEntity($){return DO.byId(this.client,$.id)}}class _O extends A{static byId($,O){return new _O($,O)}async fetch(){return Y(await this.client.storage.getHarnessPairing({path:{code:this.id}}))}name=this.field("requested_name");expiresAt=this.field("expires_at");async approve($){let O={name:$?.name,team_id:$?.team?.id,allow_permission_bypass:$?.allowPermissionBypass};return B$.from(this.client,await this.mutate((j)=>j.storage.approveHarnessPairing({path:{code:this.id},body:O})))}}class Oj{client;id;constructor($,O){this.client=$;this.id=O}static byId($,O){return new Oj($,O)}async claim($){let O=Y(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 Mx{client;constructor($){this.client=$}byId($){return B$.byId(this.client,$)}async list(){return Y(await this.client.storage.listHarnesses()).map(($)=>B$.from(this.client,$))}async me(){return B$.from(this.client,Y(await this.client.storage.getSelfHarness()))}async deleteSelf(){Y(await this.client.storage.deleteSelfHarness())}async agents(){return Y(await this.client.storage.listHarnessAgents()).map(($)=>T$.byId(this.client,$.bot_id))}async sessions(){return Y(await this.client.storage.listHarnessSessions()).map(($)=>d.byId(this.client,$.session_id))}pairing($){return _O.byId(this.client,$)}async createPairing($){let O=Y(await this.client.storage.createHarnessPairing({body:$}));return{pairing:_O.byId(this.client,O.code),device:Oj.byId(this.client,O.pairing_id),deviceSecret:O.device_secret,expiresAt:O.expires_at,pollIntervalSeconds:O.poll_interval_seconds}}}class CO{id;url;width;height;constructor($,O,j,x){this.id=$;this.url=O;this.width=j;this.height=x}static byId($,O,j){return new CO(O,`${$.hosts["static-files"]}/file/${O}`,j?.width,j?.height)}toJSON(){return{id:this.id,url:this.url,width:this.width,height:this.height}}}class wj extends CO{width;height;mimeType;sizeBytes;note;constructor($,O,j,x,S,K,Z){super($,O,j,x);this.width=j;this.height=x;this.mimeType=S;this.sizeBytes=K;this.note=Z}toJSON(){return{...super.toJSON(),mimeType:this.mimeType,sizeBytes:this.sizeBytes,note:this.note}}}class Ax{client;constructor($){this.client=$}async generate($){let O=Y(await this.client.cognition.generateImage({body:{prompt:$.prompt,aspectRatio:$.aspectRatio??null,referenceImages:($.referenceImages??[]).map(E5)}}));return new wj(O.staticFileId,O.url,O.width,O.height,O.mimeType,O.sizeBytes,O.note??void 0)}}function E5($){return $ instanceof f?{type:"document",id:$.id}:{type:"staticFile",id:$.id}}var q5="00000001-0000-0000-0000-000000000001",K2="00000001-0000-0000-0000-000000000002",w5="00000001-0000-0000-0000-000000000004",f5="00000001-0000-0000-0000-000000000014",b5="00000001-0000-0000-0002-000000000001",k5="00000001-0000-0000-0002-000000000004";function g5($){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 G$ extends f{static byId($,O){return new G$($,O)}static async create($,O){let{documentId:j}=Y(await $.storage.createTaskHandler({body:{taskName:O.name,markdown:O.markdown??null,projectId:O.project?.id??null,teamId:O.team?.id??null,shareWithTeam:O.shareWithTeam??!0,propertyValues:await y5($,O)}}));return new G$($,j)}static async summaries($,O){if(O.length===0)return[];let{previews:j}=Y(await $.storage.getBatchPreviewHandler({body:{document_ids:O.map((S)=>S.id)}})),x=new Map(j.flatMap((S)=>S.type==="access"?[[S.document_id,S]]:[]));return O.flatMap((S)=>{let K=x.get(S.id);if(!K)return[];return[{task:S,name:K.document_name,owner:M.byId($,K.owner),updatedAt:K.updated_at??void 0,completed:K.sub_type?.type==="task"&&K.sub_type.is_completed}]})}static async findSimilar($,O){let{results:j}=Y(await $.storage.taskSimilaritySearchHandler({body:{taskName:O.title,markdown:O.body??null}}));return j.map((x)=>({task:new G$($,x.taskId),name:x.taskName,similarity:x.vectorScore}))}static async forPullRequest($,O){let j=g5(O),{pullRequests:x}=Y(await $.storage.getGithubPullRequestTasks({body:{githubKeys:[j]}}));return(x[0]?.taskIds??[]).map((S)=>new G$($,S))}async completed(){let{subType:$}=await this.detail.get();if($!=="task")return;let j=(await this.properties()).find((x)=>x.definition.id===K2)?.value;return j?.type==="SelectOption"&&j.value.includes(k5)}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 G$($,O.document_id)})}async function y5($,O){if(!O.initiative&&!O.assignees&&!O.dueDate)return null;let j=O.assignees??[await M.me($)],x=[{propertyId:K2,value:{type:"select_option",option_id:b5}}];if(j.length>0)x.push({propertyId:q5,value:{type:"multi_entity_reference",references:j.map((S)=>({entity_id:S.id,entity_type:"USER"}))}});if(O.initiative)x.push({propertyId:f5,value:{type:"entity_reference",reference:{entity_id:O.initiative.id,entity_type:"INITIATIVE"}}});if(O.dueDate)x.push({propertyId:w5,value:{type:"date",value:O.dueDate.toISOString()}});return x}class a$ extends A{access=new $$(this.client,"initiative",this);static byId($,O){return new a$($,O)}static from($,O){return new a$($,O.id,O)}async fetch(){return Y(await this.client.storage.getInitiative({path:{initiative_id:this.id}}))}name=this.field("name");owner=this.mappedField("ownerId",($)=>M.byId(this.client,$));members=this.mappedField("memberIds",($)=>$.map((O)=>M.byId(this.client,O)));tasks=this.mappedField("taskIds",($)=>$.map((O)=>G$.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?$O($.sharePermission):void 0}}))}async delete(){await this.mutate(($)=>$.storage.deleteInitiative({path:{initiative_id:this.id}}))}}class Px{client;constructor($){this.client=$}byId($){return a$.byId(this.client,$)}async list(){return Y(await this.client.storage.listInitiatives()).initiatives.map(($)=>a$.byId(this.client,$.id))}async summaries(){return Y(await this.client.storage.listInitiatives()).initiatives.map(($)=>({initiative:a$.byId(this.client,$.id),name:$.name,updatedAt:$.updatedAt}))}async create($){return a$.from(this.client,Y(await this.client.storage.createInitiative({body:{name:$.name,description:$.description,memberIds:$.members?.map((O)=>O.id),shareWithTeam:$.shareWithTeam,propertyValues:$.propertyValues}})))}}var v5=16000000;class fj{client;constructor($){this.client=$}async uploadProfilePicture($,O){if(($ instanceof Blob?$.size:$.byteLength)>v5)throw new w("profile picture is larger than 16 MB");let{file_id:x,upload_url:S}=Y(await this.client.auth.createProfilePictureUpload({body:{file_name:O.fileName,content_type:O.contentType}})),K=await fetch(S,{method:"PUT",headers:{"Content-Type":O.contentType},body:$});if(!K.ok)throw new w(`image upload failed with ${K.status}`);return CO.byId(this.client,x)}async update($){if($.profilePicture)Y(await this.client.auth.putProfilePictureFile({body:{file_id:$.profilePicture.id}}));let O=$.name?.trim();if(O){let[j,...x]=O.split(/\s+/);Y(await this.client.auth.putUserName({query:{first_name:j,last_name:x.join(" ")}}))}}}class Fx{client;constructor($){this.client=$}byId($){return D$.byId(this.client,$)}async create($){return D$.from(this.client,Y(await this.client.storage.meetingCreate({body:$})))}async list(){return Y(await this.client.storage.meetingList()).meetings.map(($)=>D$.from(this.client,$))}async active(){return Y(await this.client.storage.meetingListActive()).meetings.map(($)=>D$.from(this.client,$))}async lookup($){return D$.from(this.client,Y(await this.client.storage.meetingLookup({path:{token:$}})))}}class zO extends A{async fetch(){return Y(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 c(async(j)=>{let x=Y(await $.notification.listTypedNotifications({query:{...O?.pageSize?{limit:O.pageSize}:{},...O?.states!==void 0?{states:O.states.join(",")}:{},...j?{cursor:j}:{}}}));return{items:x.items.map((S)=>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 Ex{client;constructor($){this.client=$}byId($){return zO.byId(this.client,$)}list($){return zO.list(this.client,$)}async markSeen($){Y(await this.client.notification.bulkMarkNotificationsSeen({body:{notificationIds:$}}))}async markDone($){Y(await this.client.notification.bulkMarkNotificationsDone({body:{notificationIds:$}}))}async delete($){Y(await this.client.notification.bulkDeleteUserNotificationsV2({body:{notificationIds:$}}))}async preferences(){return Y(await this.client.notification.getNotificationTypePreferences())}async enableType($){Y(await this.client.notification.enableNotificationType({path:{notification_event_type:$}}))}async disableType($){Y(await this.client.notification.disableNotificationType({path:{notification_event_type:$}}))}}class qx{client;constructor($){this.client=$}async list(){let{data:$}=Y(await this.client.storage.getPinsHandler({}));return $?.recent??[]}async add($,O){Y(await this.client.storage.addPinHandler({path:{pinned_item_id:$.id},body:{pinType:$.entityType,pinIndex:O.index}}))}async remove($){Y(await this.client.storage.removePinHandler({path:{pinned_item_id:$.id},body:{pinType:$.entityType}}))}async reorder($){Y(await this.client.storage.reorderPinsHandler({body:$}))}}class wx{client;constructor($){this.client=$}byId($){return n.byId(this.client,$)}create($){return n.create(this.client,$)}search($,O){return n.search(this.client,$,O)}}class MO{client;definitionId;id;record;constructor($,O,j,x){this.client=$;this.definitionId=O;this.id=j;this.record=x}static from($,O,j){return new MO($,O,j.id,j)}get value(){return this.record.value}get color(){return this.record.color??void 0}get displayOrder(){return this.record.display_order}get createdAt(){return this.record.created_at}get updatedAt(){return this.record.updated_at}async update($){return this.record=Y(await this.client.properties.updatePropertyOption({path:{definition_id:this.definitionId,option_id:this.id},body:$})),this}async delete(){Y(await this.client.properties.deletePropertyOption({path:{definition_id:this.definitionId,option_id:this.id}}))}}class QO{client;id;detail;constructor($,O,j){this.client=$;this.id=O;this.detail=new W$(()=>this.fetch(),j)}async fetch(){return Y(await this.client.properties.getPropertyDefinition({path:{definition_id:this.id}}))}static async create($,O){let j=Y(await $.properties.createPropertyDefinition({body:{display_name:O.displayName,scope:O.scope,data_type:O.dataType}}));return new QO($,j.id,j)}static byId($,O){return new QO($,O)}static fromRecord($,O){return new QO($,O.id,O)}get displayName(){return this.detail.get().then(($)=>$.display_name)}get dataType(){return this.detail.get().then(($)=>$.data_type)}get owner(){return this.detail.get().then(($)=>$.owner)}get isSystem(){return this.detail.get().then(($)=>$.is_system)}get isMultiSelect(){return this.detail.get().then(($)=>$.is_multi_select)}get createdAt(){return this.detail.get().then(($)=>$.created_at)}get updatedAt(){return this.detail.get().then(($)=>$.updated_at)}async delete(){return Y(await this.client.properties.deletePropertyDefinition({path:{definition_id:this.id}}))}async options(){return Y(await this.client.properties.getPropertyOptions({path:{definition_id:this.id}})).map((O)=>MO.from(this.client,this.id,O))}async addOption($){let O=Y(await this.client.properties.addPropertyOption({path:{definition_id:this.id},body:$}));return MO.from(this.client,this.id,O)}async updateOption($,O){let j=Y(await this.client.properties.updatePropertyOption({path:{definition_id:this.id,option_id:$.id},body:O}));return MO.from(this.client,this.id,j)}async deleteOption($){return Y(await this.client.properties.deletePropertyOption({path:{definition_id:this.id,option_id:$.id}}))}}class fx{client;constructor($){this.client=$}async list($){return Y(await this.client.properties.listProperties({query:{scope:$?.scope??"all",...$?.forEntityType!==void 0?{for_entity_type:$.forEntityType}:{}}})).map((j)=>{let x="definition"in j?j.definition:j;return QO.fromRecord(this.client,x)})}create($){return QO.create(this.client,$)}definition($){return QO.byId(this.client,$)}async bulkEntityProperties($){return Y(await this.client.properties.getBulkEntityProperties({body:$}))}async updateEntityPropertyOptions($,O){return Y(await this.client.properties.bulkUpdateEntitiesPropertyOptions({body:{entities:$.map((x)=>x.propertyReference()),property_id:O.property.id,...O.add?{add_option_ids:O.add.map((x)=>x.id)}:{},...O.remove?{remove_option_ids:O.remove.map((x)=>x.id)}:{}}})).results}async addEntityPropertyOption($){return Y(await this.client.properties.addEntityPropertyOption({path:{...$.entity.propertyReference(),property_id:$.property.id,option_id:$.option.id}}))}async removeEntityPropertyOption($){return Y(await this.client.properties.removeEntityPropertyOption({path:{...$.entity.propertyReference(),property_id:$.property.id,option_id:$.option.id}}))}async tags(){return Y(await this.client.properties.listTags({}))}}class bx{client;constructor($){this.client=$}async link(){let $=Y(await this.client.auth.getReferralCode()),O=new URL("/app/signup",this.client.webAppUrl);return O.searchParams.set("referral_code",$),{code:$,url:O.toString()}}async invite($){let O=$.trim();if(!O)throw new w("invite needs an email address");Y(await this.client.auth.sendReferralCode({body:{recipient:O}}))}}function kx($){return k($).with({type:"cron"},(O)=>O).with({type:"events"},(O)=>({type:"events",filters:O.filters.map(({entities:j,...x})=>({...x,ids:j?.map((S)=>S.entity.id)}))})).exhaustive()}function h5($){return k($).with({type:"multiple"},(O)=>({type:"multiple",triggers:O.triggers.map(kx)})).with({type:"cron"},kx).with({type:"events"},kx).exhaustive()}class v$ extends A{static byId($,O){return new v$($,O)}static from($,O){if(!O.id)throw Error("Routine response has no id");return new v$($,O.id,O)}async fetch(){return Y(await this.client.scheduledAction.getScheduledAction({path:{id:this.id}}))}name=this.field("name");trigger=this.field("trigger");enabled=this.field("enabled");runVisibility=this.field("run_visibility");nextRunAt=this.field("next_run_at");revision=this.field("configuration_revision");owner=this.mappedField("owner",($)=>M.byId(this.client,$));sourceTemplate=this.mappedField("template_id",($)=>$?v$.byId(this.client,$):void 0);async template(){let $=await this.client.scheduledAction.getScheduledActionTemplate({path:{id:this.id}});if($.response?.status===404)return;return this.toTemplate(Y($))}async shareAsTemplate($){return this.toTemplate(Y(await this.client.scheduledAction.shareScheduledActionTemplate({path:{id:this.id},body:$})))}async activateTemplate($){return v$.from(this.client,Y(await this.client.scheduledAction.activateScheduledActionTemplate({path:{id:this.id},body:{...bj($),enabled:$.enabled??!0}})))}toTemplate($){return new Q2(this,M.byId(this.client,$.author),$)}async stopSharingTemplate(){Y(await this.client.scheduledAction.unshareScheduledActionTemplate({path:{id:this.id}}))}async update($){await this.mutate((O)=>O.scheduledAction.updateScheduledAction({path:{id:this.id},body:bj($)}))}async setEnabled($){await this.mutate((O)=>O.scheduledAction.setScheduledActionEnabled({path:{id:this.id},body:{enabled:$}}))}async execute(){let $=Y(await this.client.scheduledAction.executeScheduledActionNow({path:{id:this.id}}));if($.resource)return k($.resource).with({type:"agent"},(O)=>d.byId(this.client,O.id)).with({type:"chat"},(O)=>Q$.byId(this.client,O.id)).exhaustive();return $.chat_id?Q$.byId(this.client,$.chat_id):void 0}async history(){return Y(await this.client.scheduledAction.listScheduledActionHistory({path:{id:this.id}})).map(($)=>new gx(this,$))}async delete(){await this.mutate(($)=>$.scheduledAction.deleteScheduledAction({path:{id:this.id}}))}}class Q2{routine;author;record;constructor($,O,j){this.routine=$;this.author=O;this.record=j}activate($){return this.routine.activateTemplate($)}toJSON(){return this.record}}class gx{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 bj($){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:h5($.trigger),task:{...O}}}class yx{client;constructor($){this.client=$}byId($){return v$.byId(this.client,$)}async create($){return v$.from(this.client,Y(await this.client.scheduledAction.createScheduledAction({body:{...bj($),enabled:$.enabled??!0}})))}async list($){return Y(await this.client.scheduledAction.listScheduledActions({query:{include_events:$?.includeEvents}})).map((O)=>v$.from(this.client,O))}}class vx{client;constructor($){this.client=$}byId($){return G$.byId(this.client,$)}create($){return G$.create(this.client,$)}summaries($){return G$.summaries(this.client,$)}findSimilar($){return G$.findSimilar(this.client,$)}forPullRequest($){return G$.forPullRequest(this.client,$)}search($,O){return G$.search(this.client,$,O)}}class hx{client;constructor($){this.client=$}byId($){return _$.byId(this.client,$)}current(){return _$.current(this.client)}list(){return _$.list(this.client)}}class mx{client;constructor($){this.client=$}async get($){return Y(await this.client.unfurl.getUnfurl({query:{url:$}}))}async bulk($){return Y(await this.client.unfurl.getUnfurlBulk({body:{url_list:$}}))}}class ux{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}=Y(j),S=[...new Set(x)],K=[];for(let Z=0;Z<S.length;Z+=100){let X=S.slice(Z,Z+100),{names:Q}=Y(await this.client.auth.getUserNamesWithEmail({body:{user_ids:X}})),L=new Map(Q.map((G)=>[G.id,G]));for(let G of X){let J=L.get(G)??{id:G};if(`${[J.first_name,J.last_name].filter(Boolean).join(" ")} ${G}`.toLocaleLowerCase().includes(O))K.push(M.fromName(this.client,J))}}return K}}class YO extends A{signingSecret;constructor($,O,j,x){super($,O,j);this.signingSecret=x}async fetch(){return Y(await this.client.storage.getWebhook({path:{webhook_id:this.id}}))}static async create($,O){let j=Y(await $.storage.createWebhook({body:{endpoint_url:O.url,namespace:O.namespace,name:O.name,filters:O.filters,scope:O.scope??"user",...O.headers!==void 0?{headers:O.headers}:{}}}));return new YO($,j.id,j,j.signing_secret)}static byId($,O){return new YO($,O)}static fromRecord($,O){return new YO($,O.id,O)}name=this.field("name");namespace=this.field("namespace");endpointUrl=this.field("endpoint_url");status=this.field("status");isValid=this.field("is_valid");filters=this.field("filters");createdAt=this.field("created_at");workspaceId=this.field("workspace_id");createdBy=this.mappedField("created_by_user_id",($)=>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 cx{client;constructor($){this.client=$}create($){return YO.create(this.client,$)}byId($){return YO.byId(this.client,$)}async list(){let{webhooks:$}=Y(await this.client.storage.listWebhooks());return $.map((O)=>YO.fromRecord(this.client,O))}}class AO extends A{static byId($,O){return new AO($,O)}static from($,O){return new AO($,O.id,O)}async fetch(){let{account:$}=Y(await this.client.storage.whatsappAccount());if($?.id!==this.id)throw new E("WhatsApp account is not available");return $}state=this.field("state");identity=this.field("identityJid");owner=this.mappedField("userId",($)=>M.byId(this.client,$));async refresh(){return this.detail.clear(),await this.detail.get(),this}}class dx{client;constructor($){this.client=$}async account(){let{account:$}=Y(await this.client.storage.whatsappAccount());return $?AO.from(this.client,$):void 0}async chats(){return Y(await this.client.storage.whatsappChats()).chats.map(($)=>NO.from(this.client,$))}}function lx($){if("properties"in $.data)return $.data.properties;if($.tag==="calendarEvent")return $.data.extra.properties;return[]}function Y2($,O,j){let x=[];for(let S of lx(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:f.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:Q$.byId($,O.data.id),snapshot:O,tags:x,name:O.data.name};case"project":return{type:"project",id:O.data.id,entity:n.byId($,O.data.id),snapshot:O,tags:x,name:O.data.name};case"emailThread":return{type:"email",id:O.data.id,entity:z$.byId($,O.data.id),snapshot:O,tags:x,subject:O.data.name,snippet:O.data.snippet,senderName:O.data.senderName,senderEmail:O.data.senderEmail,inboxVisible:O.data.inboxVisible,isRead:O.data.isRead,isDraft:O.data.isDraft};case"channel":return{type:"channel",id:O.data.channel.id,entity:b.byId($,O.data.channel.id),snapshot:O,tags:x,name:O.data.channel.name};case"channelThread":return{type:"channel_thread",id:O.data.id,entity:new 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:J$.byId($,O.data.callId),snapshot:O,tags:x,createdBy:O.data.createdBy};case"calendarEvent":return{type:"calendar_event",id:O.data.id,entity:S$.byId($,O.data.id),snapshot:O,tags:x,title:O.data.title,status:O.data.status,location:O.data.location,conferenceUrl:O.data.conferenceUrl,conferenceProvider:O.data.conferenceProvider,time:O.data.time};case"foreignEntity":return{type:"foreign_entity",id:O.data.id,entity:KO.byId($,O.data.id),snapshot:O,tags:x,foreignEntityId:O.data.foreignEntityId,foreignEntitySource:O.data.foreignEntitySource,metadata:O.data.metadata};default:throw Error(`Unexpected workspace entity type: ${O.tag}`)}}var G2="00000000-0000-0000-0000-000000000000",rx={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"]},kj=($)=>$.replace(/[A-Z]/g,(O)=>O.toLowerCase()),J2=($,O)=>$==null?O:{"&":[$,O]};function px($,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==="!"){px(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)=>{px(Z,`${O}.${S}[${X}]`)})}class gj{client;tagSets;constructor($){this.client=$}sets(){return this.tagSets??=this.client.properties.listTags({}).then(Y),this.tagSets}async tagMap(){let $=new Map;for(let O of await this.sets())for(let j of O.options)if(j.value.type==="string")$.set(j.id,{label:j.value.value,scope:O.scope==="user"?"personal":"team"});return $}async body($){for(let[S,K,Z]of[["sortBy",$.sortBy,["recently_viewed","recently_updated","recently_created"]],["emailPreset",$.emailPreset,["signal"]],["tagsMatch",$.tagsMatch,["any","all"]]])if(K!==void 0&&!Z.includes(K))throw Error(`Invalid workspace ${S}: ${K}`);if($.includeTypes!==void 0&&(!Array.isArray($.includeTypes)||$.includeTypes.some((S)=>!Object.hasOwn(rx,S))))throw Error(`Invalid workspace includeTypes. Supported values: ${Object.keys(rx).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)px($[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:G2}},favorites_only:$.favoritesOnly,expand:!0,limit:Math.max(1,Math.min(500,Math.trunc($.limit??50))),sort_method:$.sortBy==="recently_viewed"?"viewed_at":$.sortBy==="recently_created"?"created_at":"updated_at",sort_direction:"desc",emailView:$.emailView??"inbox"};if($.emailPreset==="signal")O.ef={"&":[{l:{Importance:!0}},{l:{Shared:"exclude"}}]};let j=$.inbox?.trim();if(j){let{links:S}=Y(await this.client.email.listLinks()),K=S.filter((X)=>kj(X.email_address)===kj(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=J2(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(rx))if(!x.includes(S))O[K]={l:{[Z]:G2}}}if($.tags?.length){let S=(await this.sets()).flatMap((Q)=>{let L=Q.definition;if(!L)return[];return Q.options.flatMap((G)=>G.value.type==="string"?[{id:G.id,definitionId:L.id,label:G.value.value,scope:Q.scope==="user"?"personal":"team"}]:[])}),K=new Map;for(let Q of $.tags){let L=S.filter((G)=>kj(G.label)===kj(Q.label.trim())&&(!Q.scope||G.scope===Q.scope));if(!L.length)throw Error(`Unknown tag "${Q.label}". Available tags: ${S.map((G)=>`${G.label} (${G.scope})`).join(", ")}.`);if($.tagsMatch==="all"&&L.length>1)throw Error(`Tag "${Q.label}" is ambiguous; specify personal or team scope.`);for(let G of L)K.set(G.id,G)}let X=[...K.values()].map((Q)=>({l:{pd:Q.definitionId,v:{so:Q.id}}})).reduce((Q,L)=>Q===void 0?L:{[$.tagsMatch==="all"?"&":"|"]:[Q,L]},void 0);O.propf=J2(O.propf,X)}return O}}class ax{client;constructor($){this.client=$}async page($={}){let O=new gj(this.client);return this.fetch(O,await O.body($),$.cursor)}async*list($={}){let O=new gj(this.client),j=await O.body($);yield*c((x)=>this.fetch(O,j,x))}async fetch($,O,j){let x=Y(await this.client.storage.postItemsSoupAst({body:O,query:j?{cursor:j}:void 0})),K=x.items.some((Z)=>lx(Z).some((X)=>X.definition.data_type==="TAG"))?await $.tagMap():new Map;return{items:x.items.map((Z)=>Y2(this.client,Z,K)),nextCursor:x.next_cursor,hasMore:x.next_cursor!=null}}}function V2({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Q,url:L,...G}){let J,I=Q??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,H=G.signal??new AbortController().signal;while(!0){if(H.aborted)break;B++;let P=G.headers instanceof Headers?G.headers:new Headers(G.headers);if(J!==void 0)P.set("Last-Event-ID",J);try{let D={redirect:"follow",...G,body:G.serializedBody,headers:P,signal:H},_=new Request(L,D);if($)_=await $(L,D);let N=await(G.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let T=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{T.cancel()}catch{}};H.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await T.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,``);let y=U.split(``);U=y.pop()??"";for(let a of y){let i=a.split(`-`),F=[],v;for(let R of i)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))v=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let m=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(m))V=m}let M,h=!1;if(F.length){let R=F.join(`-`);try{M=JSON.parse(R),h=!0}catch{M=R}}if(h){if(S)await S(M);if(x)M=await x(M)}if(j?.({data:M,event:v,id:J,retry:V}),F.length)yield M}}}finally{H.removeEventListener("abort",g),T.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var v5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},h5=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},m5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},gj=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((Y)=>encodeURIComponent(Y))).join(h5(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=v5(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return 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(([G,J])=>{Y=[...Y,G,$?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=m5(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 u5=/\{[^{}]+\}/g,c5=({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,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},V2=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=c5({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function ax($){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 B2={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=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("&")}},N2=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},d5=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function U2($){for(let O of $.security??[]){if(d5($,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 ix=($)=>V2({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:L2($.querySerializer),url:$.url}),nx=($,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},l5=($)=>{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?l5(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class 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 z2=()=>({error:new vj,request:new vj,response:new vj}),r5=L2({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),p5={"Content-Type":"application/json"},Oj=($={})=>({...B2,headers:p5,parseAs:"auto",querySerializer:r5,...$});var sx=($={})=>{let O=nx(Oj(),$),j=()=>({...O}),x=(G)=>{return O=nx(O,G),j()},S=z2(),K=async(G)=>{let J={...O,...G,fetch:G.fetch??O.fetch??globalThis.fetch,headers:hj(O.headers,G.headers),serializedBody:void 0};if(J.security)await U2(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let I=J,z=ix(I);return{opts:I,url:z}},Z=async(G)=>{let J=G.throwOnError??O.throwOnError,I=G.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(G),H={redirect:"follow",...V,body:ax(V)};z=new Request(B,H);for(let N of S.request.fns)if(N)z=await N(z,V);let P=V.fetch;W=await P(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?N2(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let T;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":T=await W[N]();break;case"json":{let U=await W.text();T=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(T);if(V.responseTransformer)T=await V.responseTransformer(T)}return V.responseStyle==="data"?T:{data:T,...D}}let _=await W.text(),q;try{q=JSON.parse(_)}catch{}throw q??_}catch(V){let B=V;for(let H of S.error.fns)if(H)B=await H(B,W,z,G);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(G)=>(J)=>Z({...J,method:G}),Y=(G)=>async(J)=>{let{opts:I,url:z}=await K(J);return J2({...I,body:I.body,method:G,onRequest:async(W,V)=>{let B=new Request(W,V);for(let H of S.request.fns)if(H)B=await H(B,I);return B},serializedBody:ax(I),url:z})};return{buildUrl:(G)=>ix({...O,...G}),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=sx(Oj());class H2{client;constructor($){this.client=$?.client??I2}}class T2{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class mj extends H2{static __registry=new T2;constructor($){super($);mj.__registry.set(this,$?.key)}getAgentAutoArchivePreferences($){return($?.client??this.client).get({url:"/agent-auto-archive-preferences",...$})}putAgentAutoArchivePreferences($){return($.client??this.client).put({url:"/agent-auto-archive-preferences",...$,headers:{"Content-Type":"application/json",...$.headers}})}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}})}chooseAgentMode($){return($.client??this.client).post({security:[{scheme:"bearer",type:"http"}],url:"/agent-mode-choice",...$,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}})}getAgentSessionAutoArchive($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/auto-archive",...$})}putAgentSessionAutoArchive($){return($.client??this.client).put({url:"/agent-sessions/{session_id}/auto-archive",...$,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}})}presentSessionView($){return($.client??this.client).post({url:"/agent-sessions/{session_id}/views",...$,headers:{"Content-Type":"application/json",...$.headers}})}classify($){return($.client??this.client).post({url:"/universal_input/classify",...$,headers:{"Content-Type":"application/json",...$.headers}})}extract($){return($.client??this.client).post({url:"/universal_input/extract",...$,headers:{"Content-Type":"application/json",...$.headers}})}}function R2({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...G}){let J,I=Y??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,H=G.signal??new AbortController().signal;while(!0){if(H.aborted)break;B++;let P=G.headers instanceof Headers?G.headers:new Headers(G.headers);if(J!==void 0)P.set("Last-Event-ID",J);try{let D={redirect:"follow",...G,body:G.serializedBody,headers:P,signal:H},_=new Request(L,D);if($)_=await $(L,D);let N=await(G.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let T=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{T.cancel()}catch{}};H.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await T.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`+`),F=[],v;for(let R of i)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))v=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let m=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(m))V=m}let C,h=!1;if(F.length){let R=F.join(`+`);try{C=JSON.parse(R),h=!0}catch{C=R}}if(h){if(S)await S(C);if(x)C=await x(C)}if(j?.({data:C,event:v,id:J,retry:V}),F.length)yield C}}}finally{H.removeEventListener("abort",g),T.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var m5=($)=>{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","}},c5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},yj=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((Q)=>encodeURIComponent(Q))).join(u5(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=m5(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)}`},vj=({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 Q=[];Object.entries(S).forEach(([G,J])=>{Q=[...Q,G,$?J:encodeURIComponent(J)]});let L=Q.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(([Q,L])=>PO({allowReserved:$,name:x==="deepObject"?`${j}[${Q}]`:Q,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var d5=/\{[^{}]+\}/g,l5=({path:$,url:O})=>{let j=O,x=O.match(d5);if(x)for(let S of x){let K=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))K=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let Q=$[Z];if(Q===void 0||Q===null)continue;if(Array.isArray(Q)){j=j.replace(S,yj({explode:K,name:Z,style:X,value:Q}));continue}if(typeof Q==="object"){j=j.replace(S,vj({explode:K,name:Z,style:X,value:Q,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${PO({name:Z,value:Q})}`);continue}let L=encodeURIComponent(X==="label"?`.${Q}`:Q);j=j.replace(S,L)}return j},W2=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=l5({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function ix($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var B2=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var L2={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var N2=({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 Q=yj({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(Q)S.push(Q)}else if(typeof Z==="object"){let Q=vj({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(Q)S.push(Q)}else{let Q=PO({allowReserved:X.allowReserved,name:K,value:Z});if(Q)S.push(Q)}}return S.join("&")}},U2=($)=>{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},r5=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function z2($){for(let O of $.security??[]){if(r5($,O.name))continue;let j=await B2(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var nx=($)=>W2({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:N2($.querySerializer),url:$.url}),sx=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=mj($.headers,O.headers),j},p5=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},mj=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?p5(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 hj{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 I2=()=>({error:new hj,request:new hj,response:new hj}),a5=N2({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),i5={"Content-Type":"application/json"},jj=($={})=>({...L2,headers:i5,parseAs:"auto",querySerializer:a5,...$});var tx=($={})=>{let O=sx(jj(),$),j=()=>({...O}),x=(G)=>{return O=sx(O,G),j()},S=I2(),K=async(G)=>{let J={...O,...G,fetch:G.fetch??O.fetch??globalThis.fetch,headers:mj(O.headers,G.headers),serializedBody:void 0};if(J.security)await z2(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let I=J,z=nx(I);return{opts:I,url:z}},Z=async(G)=>{let J=G.throwOnError??O.throwOnError,I=G.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(G),H={redirect:"follow",...V,body:ix(V)};z=new Request(B,H);for(let N of S.request.fns)if(N)z=await N(z,V);let P=V.fetch;W=await P(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?U2(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let T;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":T=await W[N]();break;case"json":{let U=await W.text();T=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(T);if(V.responseTransformer)T=await V.responseTransformer(T)}return V.responseStyle==="data"?T:{data:T,...D}}let _=await W.text(),q;try{q=JSON.parse(_)}catch{}throw q??_}catch(V){let B=V;for(let H of S.error.fns)if(H)B=await H(B,W,z,G);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(G)=>(J)=>Z({...J,method:G}),Q=(G)=>async(J)=>{let{opts:I,url:z}=await K(J);return V2({...I,body:I.body,method:G,onRequest:async(W,V)=>{let B=new Request(W,V);for(let H of S.request.fns)if(H)B=await H(B,I);return B},serializedBody:ix(I),url:z})};return{buildUrl:(G)=>nx({...O,...G}),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:Q("CONNECT"),delete:Q("DELETE"),get:Q("GET"),head:Q("HEAD"),options:Q("OPTIONS"),patch:Q("PATCH"),post:Q("POST"),put:Q("PUT"),trace:Q("TRACE")},trace:X("TRACE")}};var H2=tx(jj());class T2{client;constructor($){this.client=$?.client??H2}}class R2{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class uj extends T2{static __registry=new R2;constructor($){super($);uj.__registry.set(this,$?.key)}getAgentAutoArchivePreferences($){return($?.client??this.client).get({url:"/agent-auto-archive-preferences",...$})}putAgentAutoArchivePreferences($){return($.client??this.client).put({url:"/agent-auto-archive-preferences",...$,headers:{"Content-Type":"application/json",...$.headers}})}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}})}chooseAgentMode($){return($.client??this.client).post({security:[{scheme:"bearer",type:"http"}],url:"/agent-mode-choice",...$,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}})}getAgentSessionAutoArchive($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/auto-archive",...$})}putAgentSessionAutoArchive($){return($.client??this.client).put({url:"/agent-sessions/{session_id}/auto-archive",...$,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}})}presentSessionView($){return($.client??this.client).post({url:"/agent-sessions/{session_id}/views",...$,headers:{"Content-Type":"application/json",...$.headers}})}classify($){return($.client??this.client).post({url:"/universal_input/classify",...$,headers:{"Content-Type":"application/json",...$.headers}})}extract($){return($.client??this.client).post({url:"/universal_input/extract",...$,headers:{"Content-Type":"application/json",...$.headers}})}}function D2({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Q,url:L,...G}){let J,I=Q??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,H=G.signal??new AbortController().signal;while(!0){if(H.aborted)break;B++;let P=G.headers instanceof Headers?G.headers:new Headers(G.headers);if(J!==void 0)P.set("Last-Event-ID",J);try{let D={redirect:"follow",...G,body:G.serializedBody,headers:P,signal:H},_=new Request(L,D);if($)_=await $(L,D);let N=await(G.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let T=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{T.cancel()}catch{}};H.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await T.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,``);let y=U.split(``);U=y.pop()??"";for(let a of y){let i=a.split(`-`),F=[],v;for(let R of i)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))v=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let m=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(m))V=m}let M,h=!1;if(F.length){let R=F.join(`-`);try{M=JSON.parse(R),h=!0}catch{M=R}}if(h){if(S)await S(M);if(x)M=await x(M)}if(j?.({data:M,event:v,id:J,retry:V}),F.length)yield M}}}finally{H.removeEventListener("abort",g),T.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var a5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},i5=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},n5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},uj=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((Y)=>encodeURIComponent(Y))).join(i5(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=a5(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return 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)}`},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(([G,J])=>{Y=[...Y,G,$?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])=>PO({allowReserved:$,name:x==="deepObject"?`${j}[${Y}]`:Y,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var s5=/\{[^{}]+\}/g,t5=({path:$,url:O})=>{let j=O,x=O.match(s5);if(x)for(let S of x){let K=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))K=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let Y=$[Z];if(Y===void 0||Y===null)continue;if(Array.isArray(Y)){j=j.replace(S,uj({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,`;${PO({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=t5({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function tx($){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 M2={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var C2=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let Y=uj({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=PO({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},e5=($,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(e5($,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 ex=($)=>D2({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:C2($.querySerializer),url:$.url}),ox=($,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},o5=($)=>{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?o5(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class 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 F2=()=>({error:new dj,request:new dj,response:new dj}),$S=C2({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),OS={"Content-Type":"application/json"},jj=($={})=>({...M2,headers:OS,parseAs:"auto",querySerializer:$S,...$});var $1=($={})=>{let O=ox(jj(),$),j=()=>({...O}),x=(G)=>{return O=ox(O,G),j()},S=F2(),K=async(G)=>{let J={...O,...G,fetch:G.fetch??O.fetch??globalThis.fetch,headers:lj(O.headers,G.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=ex(I);return{opts:I,url:z}},Z=async(G)=>{let J=G.throwOnError??O.throwOnError,I=G.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(G),H={redirect:"follow",...V,body:tx(V)};z=new Request(B,H);for(let N of S.request.fns)if(N)z=await N(z,V);let P=V.fetch;W=await P(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?A2(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let T;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":T=await W[N]();break;case"json":{let U=await W.text();T=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(T);if(V.responseTransformer)T=await V.responseTransformer(T)}return V.responseStyle==="data"?T:{data:T,...D}}let _=await W.text(),q;try{q=JSON.parse(_)}catch{}throw q??_}catch(V){let B=V;for(let H of S.error.fns)if(H)B=await H(B,W,z,G);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(G)=>(J)=>Z({...J,method:G}),Y=(G)=>async(J)=>{let{opts:I,url:z}=await K(J);return R2({...I,body:I.body,method:G,onRequest:async(W,V)=>{let B=new Request(W,V);for(let H of S.request.fns)if(H)B=await H(B,I);return B},serializedBody:tx(I),url:z})};return{buildUrl:(G)=>ex({...O,...G}),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 E2=$1(jj());class q2{client;constructor($){this.client=$?.client??E2}}class w2{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class rj extends q2{static __registry=new w2;constructor($){super($);rj.__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}})}purchaseAiCredits($){return($.client??this.client).post({url:"/ai-billing/credits/purchase",...$,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}})}setGithubPullRequestState($){return($.client??this.client).post({url:"/github_pull_requests/state",...$,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}",...$})}getSystemStatus($){return($?.client??this.client).get({url:"/system-status",...$})}setSystemStatus($){return($.client??this.client).post({url:"/system-status",...$,headers:{"Content-Type":"application/json",...$.headers}})}listSystemStatusHistory($){return($?.client??this.client).get({url:"/system-status/history",...$})}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}})}sendTeamDomainNotice($){return($?.client??this.client).post({url:"/team/domain-notice",...$})}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}})}getUserLanguage($){return($?.client??this.client).get({url:"/user/language",...$})}putUserLanguage($){return($.client??this.client).put({url:"/user/language",...$,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 f2({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...G}){let J,I=Y??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,H=G.signal??new AbortController().signal;while(!0){if(H.aborted)break;B++;let P=G.headers instanceof Headers?G.headers:new Headers(G.headers);if(J!==void 0)P.set("Last-Event-ID",J);try{let D={redirect:"follow",...G,body:G.serializedBody,headers:P,signal:H},_=new Request(L,D);if($)_=await $(L,D);let N=await(G.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let T=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{T.cancel()}catch{}};H.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await T.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`+`),F=[],v;for(let R of i)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))v=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let m=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(m))V=m}let C,h=!1;if(F.length){let R=F.join(`+`);try{C=JSON.parse(R),h=!0}catch{C=R}}if(h){if(S)await S(C);if(x)C=await x(C)}if(j?.({data:C,event:v,id:J,retry:V}),F.length)yield C}}}finally{H.removeEventListener("abort",g),T.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var n5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},s5=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},t5=($)=>{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((Q)=>encodeURIComponent(Q))).join(s5(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)}`},dj=({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 Q=[];Object.entries(S).forEach(([G,J])=>{Q=[...Q,G,$?J:encodeURIComponent(J)]});let L=Q.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=t5(x),X=Object.entries(S).map(([Q,L])=>FO({allowReserved:$,name:x==="deepObject"?`${j}[${Q}]`:Q,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var e5=/\{[^{}]+\}/g,o5=({path:$,url:O})=>{let j=O,x=O.match(e5);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 Q=$[Z];if(Q===void 0||Q===null)continue;if(Array.isArray(Q)){j=j.replace(S,cj({explode:K,name:Z,style:X,value:Q}));continue}if(typeof Q==="object"){j=j.replace(S,dj({explode:K,name:Z,style:X,value:Q,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${FO({name:Z,value:Q})}`);continue}let L=encodeURIComponent(X==="label"?`.${Q}`:Q);j=j.replace(S,L)}return j},_2=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=o5({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function ex($){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 C2=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 M2={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var A2=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let Q=cj({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(Q)S.push(Q)}else if(typeof Z==="object"){let Q=dj({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(Q)S.push(Q)}else{let Q=FO({allowReserved:X.allowReserved,name:K,value:Z});if(Q)S.push(Q)}}return S.join("&")}},P2=($)=>{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},$S=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function F2($){for(let O of $.security??[]){if($S($,O.name))continue;let j=await C2(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 ox=($)=>_2({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:A2($.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=rj($.headers,O.headers),j},OS=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},rj=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?OS(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 lj{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 E2=()=>({error:new lj,request:new lj,response:new lj}),jS=A2({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),xS={"Content-Type":"application/json"},xj=($={})=>({...M2,headers:xS,parseAs:"auto",querySerializer:jS,...$});var O1=($={})=>{let O=$1(xj(),$),j=()=>({...O}),x=(G)=>{return O=$1(O,G),j()},S=E2(),K=async(G)=>{let J={...O,...G,fetch:G.fetch??O.fetch??globalThis.fetch,headers:rj(O.headers,G.headers),serializedBody:void 0};if(J.security)await F2(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=ox(I);return{opts:I,url:z}},Z=async(G)=>{let J=G.throwOnError??O.throwOnError,I=G.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(G),H={redirect:"follow",...V,body:ex(V)};z=new Request(B,H);for(let N of S.request.fns)if(N)z=await N(z,V);let P=V.fetch;W=await P(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?P2(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let T;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":T=await W[N]();break;case"json":{let U=await W.text();T=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(T);if(V.responseTransformer)T=await V.responseTransformer(T)}return V.responseStyle==="data"?T:{data:T,...D}}let _=await W.text(),q;try{q=JSON.parse(_)}catch{}throw q??_}catch(V){let B=V;for(let H of S.error.fns)if(H)B=await H(B,W,z,G);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(G)=>(J)=>Z({...J,method:G}),Q=(G)=>async(J)=>{let{opts:I,url:z}=await K(J);return D2({...I,body:I.body,method:G,onRequest:async(W,V)=>{let B=new Request(W,V);for(let H of S.request.fns)if(H)B=await H(B,I);return B},serializedBody:ex(I),url:z})};return{buildUrl:(G)=>ox({...O,...G}),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:Q("CONNECT"),delete:Q("DELETE"),get:Q("GET"),head:Q("HEAD"),options:Q("OPTIONS"),patch:Q("PATCH"),post:Q("POST"),put:Q("PUT"),trace:Q("TRACE")},trace:X("TRACE")}};var q2=O1(xj());class w2{client;constructor($){this.client=$?.client??q2}}class f2{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class pj extends w2{static __registry=new f2;constructor($){super($);pj.__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}})}purchaseAiCredits($){return($.client??this.client).post({url:"/ai-billing/credits/purchase",...$,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}})}setGithubPullRequestState($){return($.client??this.client).post({url:"/github_pull_requests/state",...$,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}",...$})}getSystemStatus($){return($?.client??this.client).get({url:"/system-status",...$})}setSystemStatus($){return($.client??this.client).post({url:"/system-status",...$,headers:{"Content-Type":"application/json",...$.headers}})}listSystemStatusHistory($){return($?.client??this.client).get({url:"/system-status/history",...$})}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}})}sendTeamDomainNotice($){return($?.client??this.client).post({url:"/team/domain-notice",...$})}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",...$})}agentSetup($){return($?.client??this.client).post({url:"/user/agent_setup",...$})}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}})}getUserLanguage($){return($?.client??this.client).get({url:"/user/language",...$})}putUserLanguage($){return($.client??this.client).put({url:"/user/language",...$,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",...$})}createProfilePictureUpload($){return($.client??this.client).post({url:"/user/profile_picture/file",...$,headers:{"Content-Type":"application/json",...$.headers}})}putProfilePictureFile($){return($.client??this.client).put({url:"/user/profile_picture/file",...$,headers:{"Content-Type":"application/json",...$.headers}})}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 b2({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Q,url:L,...G}){let J,I=Q??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,H=G.signal??new AbortController().signal;while(!0){if(H.aborted)break;B++;let P=G.headers instanceof Headers?G.headers:new Headers(G.headers);if(J!==void 0)P.set("Last-Event-ID",J);try{let D={redirect:"follow",...G,body:G.serializedBody,headers:P,signal:H},_=new Request(L,D);if($)_=await $(L,D);let N=await(G.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let T=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{T.cancel()}catch{}};H.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await T.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,``);let y=U.split(``);U=y.pop()??"";for(let a of y){let i=a.split(`-`),F=[],v;for(let R of i)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))v=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let m=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(m))V=m}let M,h=!1;if(F.length){let R=F.join(`-`);try{M=JSON.parse(R),h=!0}catch{M=R}}if(h){if(S)await S(M);if(x)M=await x(M)}if(j?.({data:M,event:v,id:J,retry:V}),F.length)yield M}}}finally{H.removeEventListener("abort",g),T.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var jS=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},xS=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},SS=($)=>{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(xS(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=jS(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)}`},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(([G,J])=>{Y=[...Y,G,$?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=SS(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 ZS=/\{[^{}]+\}/g,XS=({path:$,url:O})=>{let j=O,x=O.match(ZS);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,`;${FO({name:Z,value:Y})}`);continue}let L=encodeURIComponent(X==="label"?`.${Y}`:Y);j=j.replace(S,L)}return j},b2=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=XS({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function O1($){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 k2=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var g2={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var y2=({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=FO({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},KS=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function h2($){for(let O of $.security??[]){if(KS($,O.name))continue;let j=await k2(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=($)=>b2({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:y2($.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=nj($.headers,O.headers),j},YS=($)=>{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?YS(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 m2=()=>({error:new ij,request:new ij,response:new ij}),QS=y2({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),GS={"Content-Type":"application/json"},xj=($={})=>({...g2,headers:GS,parseAs:"auto",querySerializer:QS,...$});var S1=($={})=>{let O=x1(xj(),$),j=()=>({...O}),x=(G)=>{return O=x1(O,G),j()},S=m2(),K=async(G)=>{let J={...O,...G,fetch:G.fetch??O.fetch??globalThis.fetch,headers:nj(O.headers,G.headers),serializedBody:void 0};if(J.security)await h2(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(G)=>{let J=G.throwOnError??O.throwOnError,I=G.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(G),H={redirect:"follow",...V,body:O1(V)};z=new Request(B,H);for(let N of S.request.fns)if(N)z=await N(z,V);let P=V.fetch;W=await P(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?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 T;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":T=await W[N]();break;case"json":{let U=await W.text();T=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(T);if(V.responseTransformer)T=await V.responseTransformer(T)}return V.responseStyle==="data"?T:{data:T,...D}}let _=await W.text(),q;try{q=JSON.parse(_)}catch{}throw q??_}catch(V){let B=V;for(let H of S.error.fns)if(H)B=await H(B,W,z,G);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(G)=>(J)=>Z({...J,method:G}),Y=(G)=>async(J)=>{let{opts:I,url:z}=await K(J);return f2({...I,body:I.body,method:G,onRequest:async(W,V)=>{let B=new Request(W,V);for(let H of S.request.fns)if(H)B=await H(B,I);return B},serializedBody:O1(I),url:z})};return{buildUrl:(G)=>j1({...O,...G}),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=S1(xj());class c2{client;constructor($){this.client=$?.client??u2}}class d2{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 c2{static __registry=new d2;constructor($){super($);sj.__registry.set(this,$?.key)}getAvailabilityCalendars($){return($?.client??this.client).get({url:"/availability-calendars",...$})}setAvailabilityCalendar($){return($.client??this.client).put({url:"/availability-calendars/{calendar_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}listCalendars($){return($?.client??this.client).get({url:"/calendars",...$})}createCalendarEvent($){return($.client??this.client).post({url:"/events",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteCalendarEvent($){return($.client??this.client).delete({url:"/events/{event_id}",...$})}updateCalendarEvent($){return($.client??this.client).patch({url:"/events/{event_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}copyCalendarEvent($){return($.client??this.client).post({url:"/events/{event_id}/copy",...$,headers:{"Content-Type":"application/json",...$.headers}})}inviteCalendarEventGuests($){return($.client??this.client).post({url:"/events/{event_id}/guests",...$,headers:{"Content-Type":"application/json",...$.headers}})}calendarEventProviderUrl($){return($.client??this.client).get({url:"/events/{event_id}/provider-url",...$})}prepareCalendarReplacement($){return($.client??this.client).post({url:"/events/{event_id}/replacement",...$,headers:{"Content-Type":"application/json",...$.headers}})}rsvpCalendarEvent($){return($.client??this.client).put({url:"/events/{event_id}/rsvp",...$,headers:{"Content-Type":"application/json",...$.headers}})}healthHandler($){return($?.client??this.client).get({url:"/health",...$})}respondToJoinRequest($){return($.client??this.client).put({url:"/join-requests/{request_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}discardCalendarReplacement($){return($.client??this.client).delete({url:"/replacements/{operation_id}",...$})}calendarReplacementStatus($){return($.client??this.client).get({url:"/replacements/{operation_id}",...$})}confirmCalendarReplacement($){return($.client??this.client).post({url:"/replacements/{operation_id}/confirm",...$})}getTeamSharing($){return($?.client??this.client).get({url:"/team-sharing",...$})}setTeamSharing($){return($.client??this.client).put({url:"/team-sharing",...$,headers:{"Content-Type":"application/json",...$.headers}})}}function l2({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...G}){let J,I=Y??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,H=G.signal??new AbortController().signal;while(!0){if(H.aborted)break;B++;let P=G.headers instanceof Headers?G.headers:new Headers(G.headers);if(J!==void 0)P.set("Last-Event-ID",J);try{let D={redirect:"follow",...G,body:G.serializedBody,headers:P,signal:H},_=new Request(L,D);if($)_=await $(L,D);let N=await(G.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let T=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{T.cancel()}catch{}};H.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await T.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`+`),F=[],v;for(let R of i)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))v=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let m=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(m))V=m}let C,h=!1;if(F.length){let R=F.join(`+`);try{C=JSON.parse(R),h=!0}catch{C=R}}if(h){if(S)await S(C);if(x)C=await x(C)}if(j?.({data:C,event:v,id:J,retry:V}),F.length)yield C}}}finally{H.removeEventListener("abort",g),T.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var SS=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},ZS=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},XS=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},aj=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((Q)=>encodeURIComponent(Q))).join(ZS(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=SS(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)}`},ij=({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 Q=[];Object.entries(S).forEach(([G,J])=>{Q=[...Q,G,$?J:encodeURIComponent(J)]});let L=Q.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=XS(x),X=Object.entries(S).map(([Q,L])=>EO({allowReserved:$,name:x==="deepObject"?`${j}[${Q}]`:Q,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var KS=/\{[^{}]+\}/g,QS=({path:$,url:O})=>{let j=O,x=O.match(KS);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 Q=$[Z];if(Q===void 0||Q===null)continue;if(Array.isArray(Q)){j=j.replace(S,aj({explode:K,name:Z,style:X,value:Q}));continue}if(typeof Q==="object"){j=j.replace(S,ij({explode:K,name:Z,style:X,value:Q,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${EO({name:Z,value:Q})}`);continue}let L=encodeURIComponent(X==="label"?`.${Q}`:Q);j=j.replace(S,L)}return j},k2=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=QS({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 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 y2={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var v2=({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 Q=aj({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(Q)S.push(Q)}else if(typeof Z==="object"){let Q=ij({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(Q)S.push(Q)}else{let Q=EO({allowReserved:X.allowReserved,name:K,value:Z});if(Q)S.push(Q)}}return S.join("&")}},h2=($)=>{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},YS=($,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(YS($,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 x1=($)=>k2({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:v2($.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=sj($.headers,O.headers),j},GS=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},sj=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?GS(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 nj{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 u2=()=>({error:new nj,request:new nj,response:new nj}),JS=v2({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),VS={"Content-Type":"application/json"},Sj=($={})=>({...y2,headers:VS,parseAs:"auto",querySerializer:JS,...$});var Z1=($={})=>{let O=S1(Sj(),$),j=()=>({...O}),x=(G)=>{return O=S1(O,G),j()},S=u2(),K=async(G)=>{let J={...O,...G,fetch:G.fetch??O.fetch??globalThis.fetch,headers:sj(O.headers,G.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=x1(I);return{opts:I,url:z}},Z=async(G)=>{let J=G.throwOnError??O.throwOnError,I=G.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(G),H={redirect:"follow",...V,body:j1(V)};z=new Request(B,H);for(let N of S.request.fns)if(N)z=await N(z,V);let P=V.fetch;W=await P(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?h2(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let T;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":T=await W[N]();break;case"json":{let U=await W.text();T=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(T);if(V.responseTransformer)T=await V.responseTransformer(T)}return V.responseStyle==="data"?T:{data:T,...D}}let _=await W.text(),q;try{q=JSON.parse(_)}catch{}throw q??_}catch(V){let B=V;for(let H of S.error.fns)if(H)B=await H(B,W,z,G);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(G)=>(J)=>Z({...J,method:G}),Q=(G)=>async(J)=>{let{opts:I,url:z}=await K(J);return b2({...I,body:I.body,method:G,onRequest:async(W,V)=>{let B=new Request(W,V);for(let H of S.request.fns)if(H)B=await H(B,I);return B},serializedBody:j1(I),url:z})};return{buildUrl:(G)=>x1({...O,...G}),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:Q("CONNECT"),delete:Q("DELETE"),get:Q("GET"),head:Q("HEAD"),options:Q("OPTIONS"),patch:Q("PATCH"),post:Q("POST"),put:Q("PUT"),trace:Q("TRACE")},trace:X("TRACE")}};var c2=Z1(Sj());class d2{client;constructor($){this.client=$?.client??c2}}class l2{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 tj extends d2{static __registry=new l2;constructor($){super($);tj.__registry.set(this,$?.key)}getAvailabilityCalendars($){return($?.client??this.client).get({url:"/availability-calendars",...$})}setAvailabilityCalendar($){return($.client??this.client).put({url:"/availability-calendars/{calendar_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}listCalendars($){return($?.client??this.client).get({url:"/calendars",...$})}createCalendarEvent($){return($.client??this.client).post({url:"/events",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteCalendarEvent($){return($.client??this.client).delete({url:"/events/{event_id}",...$})}updateCalendarEvent($){return($.client??this.client).patch({url:"/events/{event_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}copyCalendarEvent($){return($.client??this.client).post({url:"/events/{event_id}/copy",...$,headers:{"Content-Type":"application/json",...$.headers}})}inviteCalendarEventGuests($){return($.client??this.client).post({url:"/events/{event_id}/guests",...$,headers:{"Content-Type":"application/json",...$.headers}})}calendarEventProviderUrl($){return($.client??this.client).get({url:"/events/{event_id}/provider-url",...$})}prepareCalendarReplacement($){return($.client??this.client).post({url:"/events/{event_id}/replacement",...$,headers:{"Content-Type":"application/json",...$.headers}})}rsvpCalendarEvent($){return($.client??this.client).put({url:"/events/{event_id}/rsvp",...$,headers:{"Content-Type":"application/json",...$.headers}})}healthHandler($){return($?.client??this.client).get({url:"/health",...$})}respondToJoinRequest($){return($.client??this.client).put({url:"/join-requests/{request_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}discardCalendarReplacement($){return($.client??this.client).delete({url:"/replacements/{operation_id}",...$})}calendarReplacementStatus($){return($.client??this.client).get({url:"/replacements/{operation_id}",...$})}confirmCalendarReplacement($){return($.client??this.client).post({url:"/replacements/{operation_id}/confirm",...$})}getTeamSharing($){return($?.client??this.client).get({url:"/team-sharing",...$})}setTeamSharing($){return($.client??this.client).put({url:"/team-sharing",...$,headers:{"Content-Type":"application/json",...$.headers}})}}function r2({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Q,url:L,...G}){let J,I=Q??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,H=G.signal??new AbortController().signal;while(!0){if(H.aborted)break;B++;let P=G.headers instanceof Headers?G.headers:new Headers(G.headers);if(J!==void 0)P.set("Last-Event-ID",J);try{let D={redirect:"follow",...G,body:G.serializedBody,headers:P,signal:H},_=new Request(L,D);if($)_=await $(L,D);let N=await(G.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let T=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{T.cancel()}catch{}};H.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await T.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,``);let y=U.split(``);U=y.pop()??"";for(let a of y){let i=a.split(`-`),F=[],v;for(let R of i)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))v=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let m=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(m))V=m}let M,h=!1;if(F.length){let R=F.join(`-`);try{M=JSON.parse(R),h=!0}catch{M=R}}if(h){if(S)await S(M);if(x)M=await x(M)}if(j?.({data:M,event:v,id:J,retry:V}),F.length)yield M}}}finally{H.removeEventListener("abort",g),T.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var JS=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},VS=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},WS=($)=>{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(VS(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=JS(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)}`},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(([G,J])=>{Y=[...Y,G,$?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=WS(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 BS=/\{[^{}]+\}/g,LS=({path:$,url:O})=>{let j=O,x=O.match(BS);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,`;${EO({name:Z,value:Y})}`);continue}let L=encodeURIComponent(X==="label"?`.${Y}`:Y);j=j.replace(S,L)}return j},r2=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=LS({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 p2=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 a2={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var i2=({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=EO({allowReserved:X.allowReserved,name:K,value:Z});if(Y)S.push(Y)}}return S.join("&")}},n2=($)=>{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},NS=($,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(NS($,O.name))continue;let j=await p2(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=($)=>r2({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:i2($.querySerializer),url:$.url}),K1=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=$0($.headers,O.headers),j},US=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},$0=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?US(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 t2=()=>({error:new oj,request:new oj,response:new oj}),zS=i2({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),IS={"Content-Type":"application/json"},Sj=($={})=>({...a2,headers:IS,parseAs:"auto",querySerializer:zS,...$});var Y1=($={})=>{let O=K1(Sj(),$),j=()=>({...O}),x=(G)=>{return O=K1(O,G),j()},S=t2(),K=async(G)=>{let J={...O,...G,fetch:G.fetch??O.fetch??globalThis.fetch,headers:$0(O.headers,G.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=X1(I);return{opts:I,url:z}},Z=async(G)=>{let J=G.throwOnError??O.throwOnError,I=G.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(G),H={redirect:"follow",...V,body:Z1(V)};z=new Request(B,H);for(let N of S.request.fns)if(N)z=await N(z,V);let P=V.fetch;W=await P(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?n2(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let T;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":T=await W[N]();break;case"json":{let U=await W.text();T=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(T);if(V.responseTransformer)T=await V.responseTransformer(T)}return V.responseStyle==="data"?T:{data:T,...D}}let _=await W.text(),q;try{q=JSON.parse(_)}catch{}throw q??_}catch(V){let B=V;for(let H of S.error.fns)if(H)B=await H(B,W,z,G);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(G)=>(J)=>Z({...J,method:G}),Y=(G)=>async(J)=>{let{opts:I,url:z}=await K(J);return l2({...I,body:I.body,method:G,onRequest:async(W,V)=>{let B=new Request(W,V);for(let H of S.request.fns)if(H)B=await H(B,I);return B},serializedBody:Z1(I),url:z})};return{buildUrl:(G)=>X1({...O,...G}),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 e2=Y1(Sj());class o2{client;constructor($){this.client=$?.client??e2}}class $6{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 O0 extends o2{static __registry=new $6;constructor($){super($);O0.__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}",...$})}generateDatabaseQuery($){return($.client??this.client).post({url:"/database-query",...$,headers:{"Content-Type":"application/json",...$.headers}})}decisions($){return($.client??this.client).post({url:"/decisions",...$,headers:{"Content-Type":"application/json",...$.headers}})}healthHandler($){return($?.client??this.client).get({url:"/health",...$})}generateImage($){return($.client??this.client).post({url:"/images/generate",...$,headers:{"Content-Type":"application/json",...$.headers}})}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}})}completePipedreamMcpConnect($){return($.client??this.client).post({url:"/pipedream/mcp/connect/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}})}listPipedreamMcpOverlays($){return($?.client??this.client).get({url:"/pipedream/mcp/overlays",...$})}recoverPipedreamMcpConnection($){return($.client??this.client).post({url:"/pipedream/mcp/recover",...$,headers:{"Content-Type":"application/json",...$.headers}})}createPipedreamMcpToken($){return($?.client??this.client).post({url:"/pipedream/mcp/token",...$,headers:{"Content-Type":"application/json",...$?.headers}})}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 O6({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...G}){let J,I=Y??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,H=G.signal??new AbortController().signal;while(!0){if(H.aborted)break;B++;let P=G.headers instanceof Headers?G.headers:new Headers(G.headers);if(J!==void 0)P.set("Last-Event-ID",J);try{let D={redirect:"follow",...G,body:G.serializedBody,headers:P,signal:H},_=new Request(L,D);if($)_=await $(L,D);let N=await(G.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let T=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{T.cancel()}catch{}};H.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await T.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`+`),F=[],v;for(let R of i)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))v=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let m=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(m))V=m}let C,h=!1;if(F.length){let R=F.join(`+`);try{C=JSON.parse(R),h=!0}catch{C=R}}if(h){if(S)await S(C);if(x)C=await x(C)}if(j?.({data:C,event:v,id:J,retry:V}),F.length)yield C}}}finally{H.removeEventListener("abort",g),T.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var WS=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},BS=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},LS=($)=>{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((Q)=>encodeURIComponent(Q))).join(BS(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=WS(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)}`},oj=({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 Q=[];Object.entries(S).forEach(([G,J])=>{Q=[...Q,G,$?J:encodeURIComponent(J)]});let L=Q.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=LS(x),X=Object.entries(S).map(([Q,L])=>qO({allowReserved:$,name:x==="deepObject"?`${j}[${Q}]`:Q,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var NS=/\{[^{}]+\}/g,US=({path:$,url:O})=>{let j=O,x=O.match(NS);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 Q=$[Z];if(Q===void 0||Q===null)continue;if(Array.isArray(Q)){j=j.replace(S,ej({explode:K,name:Z,style:X,value:Q}));continue}if(typeof Q==="object"){j=j.replace(S,oj({explode:K,name:Z,style:X,value:Q,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${qO({name:Z,value:Q})}`);continue}let L=encodeURIComponent(X==="label"?`.${Q}`:Q);j=j.replace(S,L)}return j},p2=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=US({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 a2=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 i2={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var n2=({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 Q=ej({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(Q)S.push(Q)}else if(typeof Z==="object"){let Q=oj({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(Q)S.push(Q)}else{let Q=qO({allowReserved:X.allowReserved,name:K,value:Z});if(Q)S.push(Q)}}return S.join("&")}},s2=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},zS=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function t2($){for(let O of $.security??[]){if(zS($,O.name))continue;let j=await a2(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=($)=>p2({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:n2($.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=O0($.headers,O.headers),j},IS=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},O0=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?IS(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 $0{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 e2=()=>({error:new $0,request:new $0,response:new $0}),HS=n2({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),TS={"Content-Type":"application/json"},Zj=($={})=>({...i2,headers:TS,parseAs:"auto",querySerializer:HS,...$});var Y1=($={})=>{let O=Q1(Zj(),$),j=()=>({...O}),x=(G)=>{return O=Q1(O,G),j()},S=e2(),K=async(G)=>{let J={...O,...G,fetch:G.fetch??O.fetch??globalThis.fetch,headers:O0(O.headers,G.headers),serializedBody:void 0};if(J.security)await t2(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(G)=>{let J=G.throwOnError??O.throwOnError,I=G.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(G),H={redirect:"follow",...V,body:X1(V)};z=new Request(B,H);for(let N of S.request.fns)if(N)z=await N(z,V);let P=V.fetch;W=await P(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?s2(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let T;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":T=await W[N]();break;case"json":{let U=await W.text();T=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(T);if(V.responseTransformer)T=await V.responseTransformer(T)}return V.responseStyle==="data"?T:{data:T,...D}}let _=await W.text(),q;try{q=JSON.parse(_)}catch{}throw q??_}catch(V){let B=V;for(let H of S.error.fns)if(H)B=await H(B,W,z,G);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(G)=>(J)=>Z({...J,method:G}),Q=(G)=>async(J)=>{let{opts:I,url:z}=await K(J);return r2({...I,body:I.body,method:G,onRequest:async(W,V)=>{let B=new Request(W,V);for(let H of S.request.fns)if(H)B=await H(B,I);return B},serializedBody:X1(I),url:z})};return{buildUrl:(G)=>K1({...O,...G}),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:Q("CONNECT"),delete:Q("DELETE"),get:Q("GET"),head:Q("HEAD"),options:Q("OPTIONS"),patch:Q("PATCH"),post:Q("POST"),put:Q("PUT"),trace:Q("TRACE")},trace:X("TRACE")}};var o2=Y1(Zj());class $6{client;constructor($){this.client=$?.client??o2}}class O6{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 j0 extends $6{static __registry=new O6;constructor($){super($);j0.__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}",...$})}generateDatabaseQuery($){return($.client??this.client).post({url:"/database-query",...$,headers:{"Content-Type":"application/json",...$.headers}})}decisions($){return($.client??this.client).post({url:"/decisions",...$,headers:{"Content-Type":"application/json",...$.headers}})}healthHandler($){return($?.client??this.client).get({url:"/health",...$})}generateImage($){return($.client??this.client).post({url:"/images/generate",...$,headers:{"Content-Type":"application/json",...$.headers}})}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}})}completePipedreamMcpConnect($){return($.client??this.client).post({url:"/pipedream/mcp/connect/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}})}listPipedreamMcpOverlays($){return($?.client??this.client).get({url:"/pipedream/mcp/overlays",...$})}recoverPipedreamMcpConnection($){return($.client??this.client).post({url:"/pipedream/mcp/recover",...$,headers:{"Content-Type":"application/json",...$.headers}})}createPipedreamMcpToken($){return($?.client??this.client).post({url:"/pipedream/mcp/token",...$,headers:{"Content-Type":"application/json",...$?.headers}})}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 j6({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Q,url:L,...G}){let J,I=Q??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,H=G.signal??new AbortController().signal;while(!0){if(H.aborted)break;B++;let P=G.headers instanceof Headers?G.headers:new Headers(G.headers);if(J!==void 0)P.set("Last-Event-ID",J);try{let D={redirect:"follow",...G,body:G.serializedBody,headers:P,signal:H},_=new Request(L,D);if($)_=await $(L,D);let N=await(G.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let T=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{T.cancel()}catch{}};H.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await T.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,``);let y=U.split(``);U=y.pop()??"";for(let a of y){let i=a.split(`-`),F=[],v;for(let R of i)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))v=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let m=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(m))V=m}let M,h=!1;if(F.length){let R=F.join(`-`);try{M=JSON.parse(R),h=!0}catch{M=R}}if(h){if(S)await S(M);if(x)M=await x(M)}if(j?.({data:M,event:v,id:J,retry:V}),F.length)yield M}}}finally{H.removeEventListener("abort",g),T.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var HS=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},TS=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},RS=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},j0=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((Y)=>encodeURIComponent(Y))).join(TS(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=HS(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)}`},x0=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let Y=[];Object.entries(S).forEach(([G,J])=>{Y=[...Y,G,$?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=RS(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 DS=/\{[^{}]+\}/g,_S=({path:$,url:O})=>{let j=O,x=O.match(DS);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,j0({explode:K,name:Z,style:X,value:Y}));continue}if(typeof Y==="object"){j=j.replace(S,x0({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},j6=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=_S({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 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={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var Z6=({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=j0({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=x0({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("&")}},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},MS=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function K6($){for(let O of $.security??[]){if(MS($,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 G1=($)=>j6({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:Z6($.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=Z0($.headers,O.headers),j},CS=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},Z0=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?CS(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 S0{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 Y6=()=>({error:new S0,request:new S0,response:new S0}),AS=Z6({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),PS={"Content-Type":"application/json"},Zj=($={})=>({...S6,headers:PS,parseAs:"auto",querySerializer:AS,...$});var V1=($={})=>{let O=J1(Zj(),$),j=()=>({...O}),x=(G)=>{return O=J1(O,G),j()},S=Y6(),K=async(G)=>{let J={...O,...G,fetch:G.fetch??O.fetch??globalThis.fetch,headers:Z0(O.headers,G.headers),serializedBody:void 0};if(J.security)await K6(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(G)=>{let J=G.throwOnError??O.throwOnError,I=G.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(G),H={redirect:"follow",...V,body:Q1(V)};z=new Request(B,H);for(let N of S.request.fns)if(N)z=await N(z,V);let P=V.fetch;W=await P(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?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 T;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":T=await W[N]();break;case"json":{let U=await W.text();T=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(T);if(V.responseTransformer)T=await V.responseTransformer(T)}return V.responseStyle==="data"?T:{data:T,...D}}let _=await W.text(),q;try{q=JSON.parse(_)}catch{}throw q??_}catch(V){let B=V;for(let H of S.error.fns)if(H)B=await H(B,W,z,G);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(G)=>(J)=>Z({...J,method:G}),Y=(G)=>async(J)=>{let{opts:I,url:z}=await K(J);return O6({...I,body:I.body,method:G,onRequest:async(W,V)=>{let B=new Request(W,V);for(let H of S.request.fns)if(H)B=await H(B,I);return B},serializedBody:Q1(I),url:z})};return{buildUrl:(G)=>G1({...O,...G}),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 Q6=V1(Zj());class G6{client;constructor($){this.client=$?.client??Q6}}class J6{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 X0 extends G6{static __registry=new J6;constructor($){super($);X0.__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 V6({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...G}){let J,I=Y??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,H=G.signal??new AbortController().signal;while(!0){if(H.aborted)break;B++;let P=G.headers instanceof Headers?G.headers:new Headers(G.headers);if(J!==void 0)P.set("Last-Event-ID",J);try{let D={redirect:"follow",...G,body:G.serializedBody,headers:P,signal:H},_=new Request(L,D);if($)_=await $(L,D);let N=await(G.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let T=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{T.cancel()}catch{}};H.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await T.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`+`),F=[],v;for(let R of i)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))v=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let m=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(m))V=m}let C,h=!1;if(F.length){let R=F.join(`+`);try{C=JSON.parse(R),h=!0}catch{C=R}}if(h){if(S)await S(C);if(x)C=await x(C)}if(j?.({data:C,event:v,id:J,retry:V}),F.length)yield C}}}finally{H.removeEventListener("abort",g),T.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var RS=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},DS=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},_S=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},x0=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((Q)=>encodeURIComponent(Q))).join(DS(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=RS(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)}`},S0=({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 Q=[];Object.entries(S).forEach(([G,J])=>{Q=[...Q,G,$?J:encodeURIComponent(J)]});let L=Q.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=_S(x),X=Object.entries(S).map(([Q,L])=>wO({allowReserved:$,name:x==="deepObject"?`${j}[${Q}]`:Q,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var CS=/\{[^{}]+\}/g,MS=({path:$,url:O})=>{let j=O,x=O.match(CS);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 Q=$[Z];if(Q===void 0||Q===null)continue;if(Array.isArray(Q)){j=j.replace(S,x0({explode:K,name:Z,style:X,value:Q}));continue}if(typeof Q==="object"){j=j.replace(S,S0({explode:K,name:Z,style:X,value:Q,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${wO({name:Z,value:Q})}`);continue}let L=encodeURIComponent(X==="label"?`.${Q}`:Q);j=j.replace(S,L)}return j},x6=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=MS({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function G1($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var S6=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 Z6={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var X6=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let Q=x0({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(Q)S.push(Q)}else if(typeof Z==="object"){let Q=S0({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(Q)S.push(Q)}else{let Q=wO({allowReserved:X.allowReserved,name:K,value:Z});if(Q)S.push(Q)}}return S.join("&")}},K6=($)=>{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},AS=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function Q6($){for(let O of $.security??[]){if(AS($,O.name))continue;let j=await S6(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=($)=>x6({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:X6($.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=X0($.headers,O.headers),j},PS=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},X0=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?PS(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 Z0{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 Y6=()=>({error:new Z0,request:new Z0,response:new Z0}),FS=X6({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),ES={"Content-Type":"application/json"},Xj=($={})=>({...Z6,headers:ES,parseAs:"auto",querySerializer:FS,...$});var W1=($={})=>{let O=V1(Xj(),$),j=()=>({...O}),x=(G)=>{return O=V1(O,G),j()},S=Y6(),K=async(G)=>{let J={...O,...G,fetch:G.fetch??O.fetch??globalThis.fetch,headers:X0(O.headers,G.headers),serializedBody:void 0};if(J.security)await Q6(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(G)=>{let J=G.throwOnError??O.throwOnError,I=G.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(G),H={redirect:"follow",...V,body:G1(V)};z=new Request(B,H);for(let N of S.request.fns)if(N)z=await N(z,V);let P=V.fetch;W=await P(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?K6(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let T;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":T=await W[N]();break;case"json":{let U=await W.text();T=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(T);if(V.responseTransformer)T=await V.responseTransformer(T)}return V.responseStyle==="data"?T:{data:T,...D}}let _=await W.text(),q;try{q=JSON.parse(_)}catch{}throw q??_}catch(V){let B=V;for(let H of S.error.fns)if(H)B=await H(B,W,z,G);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(G)=>(J)=>Z({...J,method:G}),Q=(G)=>async(J)=>{let{opts:I,url:z}=await K(J);return j6({...I,body:I.body,method:G,onRequest:async(W,V)=>{let B=new Request(W,V);for(let H of S.request.fns)if(H)B=await H(B,I);return B},serializedBody:G1(I),url:z})};return{buildUrl:(G)=>J1({...O,...G}),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:Q("CONNECT"),delete:Q("DELETE"),get:Q("GET"),head:Q("HEAD"),options:Q("OPTIONS"),patch:Q("PATCH"),post:Q("POST"),put:Q("PUT"),trace:Q("TRACE")},trace:X("TRACE")}};var G6=W1(Xj());class J6{client;constructor($){this.client=$?.client??G6}}class V6{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 K0 extends J6{static __registry=new V6;constructor($){super($);K0.__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 W6({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Q,url:L,...G}){let J,I=Q??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,H=G.signal??new AbortController().signal;while(!0){if(H.aborted)break;B++;let P=G.headers instanceof Headers?G.headers:new Headers(G.headers);if(J!==void 0)P.set("Last-Event-ID",J);try{let D={redirect:"follow",...G,body:G.serializedBody,headers:P,signal:H},_=new Request(L,D);if($)_=await $(L,D);let N=await(G.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let T=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{T.cancel()}catch{}};H.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await T.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,``);let y=U.split(``);U=y.pop()??"";for(let a of y){let i=a.split(`-`),F=[],v;for(let R of i)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))v=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let m=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(m))V=m}let M,h=!1;if(F.length){let R=F.join(`-`);try{M=JSON.parse(R),h=!0}catch{M=R}}if(h){if(S)await S(M);if(x)M=await x(M)}if(j?.({data:M,event:v,id:J,retry:V}),F.length)yield M}}}finally{H.removeEventListener("abort",g),T.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var FS=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},ES=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},qS=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},K0=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((Y)=>encodeURIComponent(Y))).join(ES(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=FS(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)}`},Y0=({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(([G,J])=>{Y=[...Y,G,$?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=qS(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 wS=/\{[^{}]+\}/g,fS=({path:$,url:O})=>{let j=O,x=O.match(wS);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,K0({explode:K,name:Z,style:X,value:Y}));continue}if(typeof Y==="object"){j=j.replace(S,Y0({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},W6=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=fS({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function W1($){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 L6={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var N6=({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=K0({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=Y0({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("&")}},U6=($)=>{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},bS=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function z6($){for(let O of $.security??[]){if(bS($,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 B1=($)=>W6({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:N6($.querySerializer),url:$.url}),L1=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=G0($.headers,O.headers),j},kS=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},G0=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?kS(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 Q0{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 I6=()=>({error:new Q0,request:new Q0,response:new Q0}),gS=N6({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),yS={"Content-Type":"application/json"},Xj=($={})=>({...L6,headers:yS,parseAs:"auto",querySerializer:gS,...$});var N1=($={})=>{let O=L1(Xj(),$),j=()=>({...O}),x=(G)=>{return O=L1(O,G),j()},S=I6(),K=async(G)=>{let J={...O,...G,fetch:G.fetch??O.fetch??globalThis.fetch,headers:G0(O.headers,G.headers),serializedBody:void 0};if(J.security)await z6(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let I=J,z=B1(I);return{opts:I,url:z}},Z=async(G)=>{let J=G.throwOnError??O.throwOnError,I=G.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(G),H={redirect:"follow",...V,body:W1(V)};z=new Request(B,H);for(let N of S.request.fns)if(N)z=await N(z,V);let P=V.fetch;W=await P(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?U6(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let T;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":T=await W[N]();break;case"json":{let U=await W.text();T=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(T);if(V.responseTransformer)T=await V.responseTransformer(T)}return V.responseStyle==="data"?T:{data:T,...D}}let _=await W.text(),q;try{q=JSON.parse(_)}catch{}throw q??_}catch(V){let B=V;for(let H of S.error.fns)if(H)B=await H(B,W,z,G);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(G)=>(J)=>Z({...J,method:G}),Y=(G)=>async(J)=>{let{opts:I,url:z}=await K(J);return V6({...I,body:I.body,method:G,onRequest:async(W,V)=>{let B=new Request(W,V);for(let H of S.request.fns)if(H)B=await H(B,I);return B},serializedBody:W1(I),url:z})};return{buildUrl:(G)=>B1({...O,...G}),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 H6=N1(Xj());class T6{client;constructor($){this.client=$?.client??H6}}class R6{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 J0 extends T6{static __registry=new R6;constructor($){super($);J0.__registry.set(this,$?.key)}getAttachment($){return($.client??this.client).get({url:"/email/attachments/{id}",...$})}getAttachmentDocumentId($){return($.client??this.client).get({url:"/email/attachments/{id}/document_id",...$})}cancelBackfillGmail($){return($.client??this.client).delete({url:"/email/backfill/gmail",...$,headers:{"Content-Type":"application/json",...$.headers}})}listBackfillGmail($){return($?.client??this.client).get({url:"/email/backfill/gmail",...$})}getBackfillGmailActive($){return($?.client??this.client).get({url:"/email/backfill/gmail/active",...$})}getBackfillGmail($){return($.client??this.client).get({url:"/email/backfill/gmail/{id}",...$})}forwardCalendarEvent($){return($.client??this.client).post({url:"/email/calendar-events/{event_id}/forward",...$,headers:{"Content-Type":"application/json",...$.headers}})}listContacts($){return($?.client??this.client).get({url:"/email/contacts",...$})}blockSender($){return($.client??this.client).post({url:"/email/contacts/block",...$,headers:{"Content-Type":"application/json",...$.headers}})}listBlockedSenders($){return($?.client??this.client).get({url:"/email/contacts/blocked",...$})}unblockSender($){return($.client??this.client).post({url:"/email/contacts/unblock",...$,headers:{"Content-Type":"application/json",...$.headers}})}recoverDraftTransfer($){return($.client??this.client).post({url:"/email/draft-transfers/{id}/recover",...$})}createDraft($){return($.client??this.client).post({url:"/email/drafts",...$,headers:{"Content-Type":"application/json",...$.headers}})}getScheduledMessages($){return($?.client??this.client).get({url:"/email/drafts/scheduled",...$})}upsertScheduledMessage($){return($.client??this.client).put({url:"/email/drafts/scheduled/{id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteScheduledDraft($){return($.client??this.client).delete({url:"/email/drafts/scheduled/{message_id}",...$})}deleteDraft($){return($.client??this.client).delete({url:"/email/drafts/{id}",...$})}addDraftAttachment($){return($.client??this.client).post({url:"/email/drafts/{id}/attachments",...$,headers:{"Content-Type":"application/json",...$.headers}})}removeDraftAttachment($){return($.client??this.client).delete({url:"/email/drafts/{id}/attachments/{attachment_id}",...$})}completeDraftAttachment($){return($.client??this.client).post({url:"/email/drafts/{id}/attachments/{attachment_id}/complete",...$})}addForwardedAttachment($){return($.client??this.client).post({url:"/email/drafts/{id}/forwarded-attachments",...$,headers:{"Content-Type":"application/json",...$.headers}})}removeForwardedAttachment($){return($.client??this.client).delete({url:"/email/drafts/{id}/forwarded-attachments/{attachment_id}",...$})}messageOperationStatus($){return($.client??this.client).get({url:"/email/drafts/{id}/operation",...$})}resolveMessageOperation($){return($.client??this.client).post({url:"/email/drafts/{id}/resolve",...$,headers:{"Content-Type":"application/json",...$.headers}})}transferDraft($){return($.client??this.client).post({url:"/email/drafts/{id}/transfer",...$,headers:{"Content-Type":"application/json",...$.headers}})}listEmailFilters($){return($?.client??this.client).get({url:"/email/filters",...$})}upsertEmailFilter($){return($.client??this.client).put({url:"/email/filters",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteEmailFilter($){return($.client??this.client).delete({url:"/email/filters/{id}",...$})}initUser($){return($?.client??this.client).post({url:"/email/init",...$})}listLabels($){return($?.client??this.client).get({url:"/email/labels",...$})}createLabel($){return($.client??this.client).post({url:"/email/labels",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteLabel($){return($.client??this.client).delete({url:"/email/labels/{id}",...$})}listLinks($){return($?.client??this.client).get({url:"/email/links",...$})}healthCheckLinks($){return($?.client??this.client).post({url:"/email/links/health-check",...$})}deleteLink($){return($.client??this.client).delete({url:"/email/links/{link_id}",...$})}disableLinkCalendar($){return($.client??this.client).delete({url:"/email/links/{link_id}/calendar",...$})}resyncLink($){return($.client??this.client).post({url:"/email/links/{link_id}/resync",...$})}sendMessage($){return($.client??this.client).post({url:"/email/messages",...$,headers:{"Content-Type":"application/json",...$.headers}})}getMessagesBatch($){return($.client??this.client).post({url:"/email/messages/batch",...$,headers:{"Content-Type":"application/json",...$.headers}})}addRemoveLabel($){return($.client??this.client).patch({url:"/email/messages/labels",...$,headers:{"Content-Type":"application/json",...$.headers}})}getMessage($){return($.client??this.client).get({url:"/email/messages/{id}",...$})}getMessageEml($){return($.client??this.client).get({url:"/email/messages/{id}/eml",...$})}patchSettings($){return($.client??this.client).patch({url:"/email/settings",...$,headers:{"Content-Type":"application/json",...$.headers}})}mailboxSettingsOperations($){return($?.client??this.client).get({url:"/email/settings/operations",...$})}disableSync($){return($?.client??this.client).delete({url:"/email/sync",...$})}archiveThreads($){return($.client??this.client).patch({url:"/email/threads/archived",...$,headers:{"Content-Type":"application/json",...$.headers}})}previewsInboxCursor($){return($.client??this.client).get({url:"/email/threads/previews/cursor/{view}",...$})}archiveThread($){return($.client??this.client).patch({url:"/email/threads/{id}/archived",...$,headers:{"Content-Type":"application/json",...$.headers}})}addRemoveThreadLabel($){return($.client??this.client).patch({url:"/email/threads/{id}/labels",...$,headers:{"Content-Type":"application/json",...$.headers}})}getThreadMessagesHandler($){return($.client??this.client).get({url:"/email/threads/{id}/messages",...$})}threadOperations($){return($.client??this.client).get({url:"/email/threads/{id}/operations",...$})}threadSeen($){return($.client??this.client).post({url:"/email/threads/{id}/seen",...$})}updateThreadState($){return($.client??this.client).patch({url:"/email/threads/{id}/state",...$,headers:{"Content-Type":"application/json",...$.headers}})}getThread($){return($.client??this.client).get({url:"/email/threads/{thread_id}",...$})}getThreadCalendarInvitations($){return($.client??this.client).get({url:"/email/threads/{thread_id}/calendar-invitations",...$})}copyThreadCalendarInvitation($){return($.client??this.client).post({url:"/email/threads/{thread_id}/messages/{message_id}/calendar-invitations/{invitation_id}/copy",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateThreadProject($){return($.client??this.client).patch({url:"/email/threads/{thread_id}/project",...$,headers:{"Content-Type":"application/json",...$.headers}})}getThreadReadReceipts($){return($.client??this.client).get({url:"/email/threads/{thread_id}/read-receipts",...$})}healthHandler($){return($?.client??this.client).get({url:"/health",...$})}getReadReceiptPixel($){return($.client??this.client).get({url:"/opens/{token}",...$})}}function D6({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...G}){let J,I=Y??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,H=G.signal??new AbortController().signal;while(!0){if(H.aborted)break;B++;let P=G.headers instanceof Headers?G.headers:new Headers(G.headers);if(J!==void 0)P.set("Last-Event-ID",J);try{let D={redirect:"follow",...G,body:G.serializedBody,headers:P,signal:H},_=new Request(L,D);if($)_=await $(L,D);let N=await(G.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let T=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{T.cancel()}catch{}};H.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await T.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`+`),F=[],v;for(let R of i)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))v=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let m=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(m))V=m}let C,h=!1;if(F.length){let R=F.join(`+`);try{C=JSON.parse(R),h=!0}catch{C=R}}if(h){if(S)await S(C);if(x)C=await x(C)}if(j?.({data:C,event:v,id:J,retry:V}),F.length)yield C}}}finally{H.removeEventListener("abort",g),T.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var qS=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},wS=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},fS=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},Q0=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((Q)=>encodeURIComponent(Q))).join(wS(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=qS(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)}`},Y0=({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 Q=[];Object.entries(S).forEach(([G,J])=>{Q=[...Q,G,$?J:encodeURIComponent(J)]});let L=Q.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=fS(x),X=Object.entries(S).map(([Q,L])=>fO({allowReserved:$,name:x==="deepObject"?`${j}[${Q}]`:Q,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var bS=/\{[^{}]+\}/g,kS=({path:$,url:O})=>{let j=O,x=O.match(bS);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 Q=$[Z];if(Q===void 0||Q===null)continue;if(Array.isArray(Q)){j=j.replace(S,Q0({explode:K,name:Z,style:X,value:Q}));continue}if(typeof Q==="object"){j=j.replace(S,Y0({explode:K,name:Z,style:X,value:Q,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${fO({name:Z,value:Q})}`);continue}let L=encodeURIComponent(X==="label"?`.${Q}`:Q);j=j.replace(S,L)}return j},B6=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=kS({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 L6=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 N6={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var U6=({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 Q=Q0({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(Q)S.push(Q)}else if(typeof Z==="object"){let Q=Y0({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(Q)S.push(Q)}else{let Q=fO({allowReserved:X.allowReserved,name:K,value:Z});if(Q)S.push(Q)}}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},gS=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function I6($){for(let O of $.security??[]){if(gS($,O.name))continue;let j=await L6(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=($)=>B6({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:U6($.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=J0($.headers,O.headers),j},yS=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},J0=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?yS(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 G0{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 H6=()=>({error:new G0,request:new G0,response:new G0}),vS=U6({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),hS={"Content-Type":"application/json"},Kj=($={})=>({...N6,headers:hS,parseAs:"auto",querySerializer:vS,...$});var U1=($={})=>{let O=N1(Kj(),$),j=()=>({...O}),x=(G)=>{return O=N1(O,G),j()},S=H6(),K=async(G)=>{let J={...O,...G,fetch:G.fetch??O.fetch??globalThis.fetch,headers:J0(O.headers,G.headers),serializedBody:void 0};if(J.security)await I6(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(G)=>{let J=G.throwOnError??O.throwOnError,I=G.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(G),H={redirect:"follow",...V,body:B1(V)};z=new Request(B,H);for(let N of S.request.fns)if(N)z=await N(z,V);let P=V.fetch;W=await P(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?z6(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let T;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":T=await W[N]();break;case"json":{let U=await W.text();T=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(T);if(V.responseTransformer)T=await V.responseTransformer(T)}return V.responseStyle==="data"?T:{data:T,...D}}let _=await W.text(),q;try{q=JSON.parse(_)}catch{}throw q??_}catch(V){let B=V;for(let H of S.error.fns)if(H)B=await H(B,W,z,G);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(G)=>(J)=>Z({...J,method:G}),Q=(G)=>async(J)=>{let{opts:I,url:z}=await K(J);return W6({...I,body:I.body,method:G,onRequest:async(W,V)=>{let B=new Request(W,V);for(let H of S.request.fns)if(H)B=await H(B,I);return B},serializedBody:B1(I),url:z})};return{buildUrl:(G)=>L1({...O,...G}),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:Q("CONNECT"),delete:Q("DELETE"),get:Q("GET"),head:Q("HEAD"),options:Q("OPTIONS"),patch:Q("PATCH"),post:Q("POST"),put:Q("PUT"),trace:Q("TRACE")},trace:X("TRACE")}};var T6=U1(Kj());class R6{client;constructor($){this.client=$?.client??T6}}class D6{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 V0 extends R6{static __registry=new D6;constructor($){super($);V0.__registry.set(this,$?.key)}getAttachment($){return($.client??this.client).get({url:"/email/attachments/{id}",...$})}getAttachmentDocumentId($){return($.client??this.client).get({url:"/email/attachments/{id}/document_id",...$})}cancelBackfillGmail($){return($.client??this.client).delete({url:"/email/backfill/gmail",...$,headers:{"Content-Type":"application/json",...$.headers}})}listBackfillGmail($){return($?.client??this.client).get({url:"/email/backfill/gmail",...$})}getBackfillGmailActive($){return($?.client??this.client).get({url:"/email/backfill/gmail/active",...$})}getBackfillGmail($){return($.client??this.client).get({url:"/email/backfill/gmail/{id}",...$})}forwardCalendarEvent($){return($.client??this.client).post({url:"/email/calendar-events/{event_id}/forward",...$,headers:{"Content-Type":"application/json",...$.headers}})}listContacts($){return($?.client??this.client).get({url:"/email/contacts",...$})}blockSender($){return($.client??this.client).post({url:"/email/contacts/block",...$,headers:{"Content-Type":"application/json",...$.headers}})}listBlockedSenders($){return($?.client??this.client).get({url:"/email/contacts/blocked",...$})}unblockSender($){return($.client??this.client).post({url:"/email/contacts/unblock",...$,headers:{"Content-Type":"application/json",...$.headers}})}recoverDraftTransfer($){return($.client??this.client).post({url:"/email/draft-transfers/{id}/recover",...$})}createDraft($){return($.client??this.client).post({url:"/email/drafts",...$,headers:{"Content-Type":"application/json",...$.headers}})}getScheduledMessages($){return($?.client??this.client).get({url:"/email/drafts/scheduled",...$})}upsertScheduledMessage($){return($.client??this.client).put({url:"/email/drafts/scheduled/{id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteScheduledDraft($){return($.client??this.client).delete({url:"/email/drafts/scheduled/{message_id}",...$})}deleteDraft($){return($.client??this.client).delete({url:"/email/drafts/{id}",...$})}addDraftAttachment($){return($.client??this.client).post({url:"/email/drafts/{id}/attachments",...$,headers:{"Content-Type":"application/json",...$.headers}})}removeDraftAttachment($){return($.client??this.client).delete({url:"/email/drafts/{id}/attachments/{attachment_id}",...$})}completeDraftAttachment($){return($.client??this.client).post({url:"/email/drafts/{id}/attachments/{attachment_id}/complete",...$})}addForwardedAttachment($){return($.client??this.client).post({url:"/email/drafts/{id}/forwarded-attachments",...$,headers:{"Content-Type":"application/json",...$.headers}})}removeForwardedAttachment($){return($.client??this.client).delete({url:"/email/drafts/{id}/forwarded-attachments/{attachment_id}",...$})}messageOperationStatus($){return($.client??this.client).get({url:"/email/drafts/{id}/operation",...$})}resolveMessageOperation($){return($.client??this.client).post({url:"/email/drafts/{id}/resolve",...$,headers:{"Content-Type":"application/json",...$.headers}})}transferDraft($){return($.client??this.client).post({url:"/email/drafts/{id}/transfer",...$,headers:{"Content-Type":"application/json",...$.headers}})}listEmailFilters($){return($?.client??this.client).get({url:"/email/filters",...$})}upsertEmailFilter($){return($.client??this.client).put({url:"/email/filters",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteEmailFilter($){return($.client??this.client).delete({url:"/email/filters/{id}",...$})}initUser($){return($?.client??this.client).post({url:"/email/init",...$})}listLabels($){return($?.client??this.client).get({url:"/email/labels",...$})}createLabel($){return($.client??this.client).post({url:"/email/labels",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteLabel($){return($.client??this.client).delete({url:"/email/labels/{id}",...$})}listLinks($){return($?.client??this.client).get({url:"/email/links",...$})}healthCheckLinks($){return($?.client??this.client).post({url:"/email/links/health-check",...$})}deleteLink($){return($.client??this.client).delete({url:"/email/links/{link_id}",...$})}disableLinkCalendar($){return($.client??this.client).delete({url:"/email/links/{link_id}/calendar",...$})}resyncLink($){return($.client??this.client).post({url:"/email/links/{link_id}/resync",...$})}sendMessage($){return($.client??this.client).post({url:"/email/messages",...$,headers:{"Content-Type":"application/json",...$.headers}})}getMessagesBatch($){return($.client??this.client).post({url:"/email/messages/batch",...$,headers:{"Content-Type":"application/json",...$.headers}})}addRemoveLabel($){return($.client??this.client).patch({url:"/email/messages/labels",...$,headers:{"Content-Type":"application/json",...$.headers}})}getMessage($){return($.client??this.client).get({url:"/email/messages/{id}",...$})}getMessageEml($){return($.client??this.client).get({url:"/email/messages/{id}/eml",...$})}patchSettings($){return($.client??this.client).patch({url:"/email/settings",...$,headers:{"Content-Type":"application/json",...$.headers}})}mailboxSettingsOperations($){return($?.client??this.client).get({url:"/email/settings/operations",...$})}disableSync($){return($?.client??this.client).delete({url:"/email/sync",...$})}archiveThreads($){return($.client??this.client).patch({url:"/email/threads/archived",...$,headers:{"Content-Type":"application/json",...$.headers}})}previewsInboxCursor($){return($.client??this.client).get({url:"/email/threads/previews/cursor/{view}",...$})}archiveThread($){return($.client??this.client).patch({url:"/email/threads/{id}/archived",...$,headers:{"Content-Type":"application/json",...$.headers}})}addRemoveThreadLabel($){return($.client??this.client).patch({url:"/email/threads/{id}/labels",...$,headers:{"Content-Type":"application/json",...$.headers}})}getThreadMessagesHandler($){return($.client??this.client).get({url:"/email/threads/{id}/messages",...$})}threadOperations($){return($.client??this.client).get({url:"/email/threads/{id}/operations",...$})}threadSeen($){return($.client??this.client).post({url:"/email/threads/{id}/seen",...$})}updateThreadState($){return($.client??this.client).patch({url:"/email/threads/{id}/state",...$,headers:{"Content-Type":"application/json",...$.headers}})}getThread($){return($.client??this.client).get({url:"/email/threads/{thread_id}",...$})}getThreadCalendarInvitations($){return($.client??this.client).get({url:"/email/threads/{thread_id}/calendar-invitations",...$})}copyThreadCalendarInvitation($){return($.client??this.client).post({url:"/email/threads/{thread_id}/messages/{message_id}/calendar-invitations/{invitation_id}/copy",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateThreadProject($){return($.client??this.client).patch({url:"/email/threads/{thread_id}/project",...$,headers:{"Content-Type":"application/json",...$.headers}})}getThreadReadReceipts($){return($.client??this.client).get({url:"/email/threads/{thread_id}/read-receipts",...$})}healthHandler($){return($?.client??this.client).get({url:"/health",...$})}getReadReceiptPixel($){return($.client??this.client).get({url:"/opens/{token}",...$})}}function _6({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Q,url:L,...G}){let J,I=Q??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,H=G.signal??new AbortController().signal;while(!0){if(H.aborted)break;B++;let P=G.headers instanceof Headers?G.headers:new Headers(G.headers);if(J!==void 0)P.set("Last-Event-ID",J);try{let D={redirect:"follow",...G,body:G.serializedBody,headers:P,signal:H},_=new Request(L,D);if($)_=await $(L,D);let N=await(G.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let T=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{T.cancel()}catch{}};H.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await T.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,``);let y=U.split(``);U=y.pop()??"";for(let a of y){let i=a.split(`-`),F=[],v;for(let R of i)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))v=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let m=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(m))V=m}let M,h=!1;if(F.length){let R=F.join(`-`);try{M=JSON.parse(R),h=!0}catch{M=R}}if(h){if(S)await S(M);if(x)M=await x(M)}if(j?.({data:M,event:v,id:J,retry:V}),F.length)yield M}}}finally{H.removeEventListener("abort",g),T.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var vS=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},hS=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},mS=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},V0=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((Y)=>encodeURIComponent(Y))).join(hS(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=vS(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)}`},W0=({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(([G,J])=>{Y=[...Y,G,$?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=mS(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 uS=/\{[^{}]+\}/g,cS=({path:$,url:O})=>{let j=O,x=O.match(uS);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,V0({explode:K,name:Z,style:X,value:Y}));continue}if(typeof Y==="object"){j=j.replace(S,W0({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},_6=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=cS({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function U1($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var M6=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 C6={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var A6=({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=V0({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=W0({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("&")}},P6=($)=>{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},dS=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function F6($){for(let O of $.security??[]){if(dS($,O.name))continue;let j=await M6(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var z1=($)=>_6({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:A6($.querySerializer),url:$.url}),I1=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=L0($.headers,O.headers),j},lS=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},L0=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?lS(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 B0{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 E6=()=>({error:new B0,request:new B0,response:new B0}),rS=A6({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),pS={"Content-Type":"application/json"},Kj=($={})=>({...C6,headers:pS,parseAs:"auto",querySerializer:rS,...$});var H1=($={})=>{let O=I1(Kj(),$),j=()=>({...O}),x=(G)=>{return O=I1(O,G),j()},S=E6(),K=async(G)=>{let J={...O,...G,fetch:G.fetch??O.fetch??globalThis.fetch,headers:L0(O.headers,G.headers),serializedBody:void 0};if(J.security)await F6(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(G)=>{let J=G.throwOnError??O.throwOnError,I=G.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(G),H={redirect:"follow",...V,body:U1(V)};z=new Request(B,H);for(let N of S.request.fns)if(N)z=await N(z,V);let P=V.fetch;W=await P(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?P6(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let T;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":T=await W[N]();break;case"json":{let U=await W.text();T=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(T);if(V.responseTransformer)T=await V.responseTransformer(T)}return V.responseStyle==="data"?T:{data:T,...D}}let _=await W.text(),q;try{q=JSON.parse(_)}catch{}throw q??_}catch(V){let B=V;for(let H of S.error.fns)if(H)B=await H(B,W,z,G);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(G)=>(J)=>Z({...J,method:G}),Y=(G)=>async(J)=>{let{opts:I,url:z}=await K(J);return D6({...I,body:I.body,method:G,onRequest:async(W,V)=>{let B=new Request(W,V);for(let H of S.request.fns)if(H)B=await H(B,I);return B},serializedBody:U1(I),url:z})};return{buildUrl:(G)=>z1({...O,...G}),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 q6=H1(Kj());class w6{client;constructor($){this.client=$?.client??q6}}class f6{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 N0 extends w6{static __registry=new f6;constructor($){super($);N0.__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}",...$})}removeUnsubscribeItems($){return($.client??this.client).delete({url:"/unsubscribe/items",...$,headers:{"Content-Type":"application/json",...$.headers}})}unsubscribeItems($){return($.client??this.client).post({url:"/unsubscribe/items",...$,headers:{"Content-Type":"application/json",...$.headers}})}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 b6({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...G}){let J,I=Y??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,H=G.signal??new AbortController().signal;while(!0){if(H.aborted)break;B++;let P=G.headers instanceof Headers?G.headers:new Headers(G.headers);if(J!==void 0)P.set("Last-Event-ID",J);try{let D={redirect:"follow",...G,body:G.serializedBody,headers:P,signal:H},_=new Request(L,D);if($)_=await $(L,D);let N=await(G.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let T=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{T.cancel()}catch{}};H.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await T.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`+`),F=[],v;for(let R of i)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))v=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let m=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(m))V=m}let C,h=!1;if(F.length){let R=F.join(`+`);try{C=JSON.parse(R),h=!0}catch{C=R}}if(h){if(S)await S(C);if(x)C=await x(C)}if(j?.({data:C,event:v,id:J,retry:V}),F.length)yield C}}}finally{H.removeEventListener("abort",g),T.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var mS=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},uS=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},cS=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},W0=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((Q)=>encodeURIComponent(Q))).join(uS(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=mS(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)}`},B0=({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 Q=[];Object.entries(S).forEach(([G,J])=>{Q=[...Q,G,$?J:encodeURIComponent(J)]});let L=Q.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=cS(x),X=Object.entries(S).map(([Q,L])=>bO({allowReserved:$,name:x==="deepObject"?`${j}[${Q}]`:Q,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var dS=/\{[^{}]+\}/g,lS=({path:$,url:O})=>{let j=O,x=O.match(dS);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 Q=$[Z];if(Q===void 0||Q===null)continue;if(Array.isArray(Q)){j=j.replace(S,W0({explode:K,name:Z,style:X,value:Q}));continue}if(typeof Q==="object"){j=j.replace(S,B0({explode:K,name:Z,style:X,value:Q,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${bO({name:Z,value:Q})}`);continue}let L=encodeURIComponent(X==="label"?`.${Q}`:Q);j=j.replace(S,L)}return j},C6=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=lS({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 M6=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 A6={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var P6=({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 Q=W0({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(Q)S.push(Q)}else if(typeof Z==="object"){let Q=B0({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(Q)S.push(Q)}else{let Q=bO({allowReserved:X.allowReserved,name:K,value:Z});if(Q)S.push(Q)}}return S.join("&")}},F6=($)=>{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},rS=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function E6($){for(let O of $.security??[]){if(rS($,O.name))continue;let j=await M6(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=($)=>C6({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:P6($.querySerializer),url:$.url}),H1=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=N0($.headers,O.headers),j},pS=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},N0=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?pS(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 L0{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 q6=()=>({error:new L0,request:new L0,response:new L0}),aS=P6({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),iS={"Content-Type":"application/json"},Qj=($={})=>({...A6,headers:iS,parseAs:"auto",querySerializer:aS,...$});var T1=($={})=>{let O=H1(Qj(),$),j=()=>({...O}),x=(G)=>{return O=H1(O,G),j()},S=q6(),K=async(G)=>{let J={...O,...G,fetch:G.fetch??O.fetch??globalThis.fetch,headers:N0(O.headers,G.headers),serializedBody:void 0};if(J.security)await E6(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(G)=>{let J=G.throwOnError??O.throwOnError,I=G.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(G),H={redirect:"follow",...V,body:z1(V)};z=new Request(B,H);for(let N of S.request.fns)if(N)z=await N(z,V);let P=V.fetch;W=await P(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?F6(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let T;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":T=await W[N]();break;case"json":{let U=await W.text();T=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(T);if(V.responseTransformer)T=await V.responseTransformer(T)}return V.responseStyle==="data"?T:{data:T,...D}}let _=await W.text(),q;try{q=JSON.parse(_)}catch{}throw q??_}catch(V){let B=V;for(let H of S.error.fns)if(H)B=await H(B,W,z,G);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(G)=>(J)=>Z({...J,method:G}),Q=(G)=>async(J)=>{let{opts:I,url:z}=await K(J);return _6({...I,body:I.body,method:G,onRequest:async(W,V)=>{let B=new Request(W,V);for(let H of S.request.fns)if(H)B=await H(B,I);return B},serializedBody:z1(I),url:z})};return{buildUrl:(G)=>I1({...O,...G}),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:Q("CONNECT"),delete:Q("DELETE"),get:Q("GET"),head:Q("HEAD"),options:Q("OPTIONS"),patch:Q("PATCH"),post:Q("POST"),put:Q("PUT"),trace:Q("TRACE")},trace:X("TRACE")}};var w6=T1(Qj());class f6{client;constructor($){this.client=$?.client??w6}}class b6{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 U0 extends f6{static __registry=new b6;constructor($){super($);U0.__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}",...$})}removeUnsubscribeItems($){return($.client??this.client).delete({url:"/unsubscribe/items",...$,headers:{"Content-Type":"application/json",...$.headers}})}unsubscribeItems($){return($.client??this.client).post({url:"/unsubscribe/items",...$,headers:{"Content-Type":"application/json",...$.headers}})}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 k6({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Q,url:L,...G}){let J,I=Q??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,H=G.signal??new AbortController().signal;while(!0){if(H.aborted)break;B++;let P=G.headers instanceof Headers?G.headers:new Headers(G.headers);if(J!==void 0)P.set("Last-Event-ID",J);try{let D={redirect:"follow",...G,body:G.serializedBody,headers:P,signal:H},_=new Request(L,D);if($)_=await $(L,D);let N=await(G.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let T=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{T.cancel()}catch{}};H.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await T.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,``);let y=U.split(``);U=y.pop()??"";for(let a of y){let i=a.split(`-`),F=[],v;for(let R of i)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))v=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let m=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(m))V=m}let M,h=!1;if(F.length){let R=F.join(`-`);try{M=JSON.parse(R),h=!0}catch{M=R}}if(h){if(S)await S(M);if(x)M=await x(M)}if(j?.({data:M,event:v,id:J,retry:V}),F.length)yield M}}}finally{H.removeEventListener("abort",g),T.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var aS=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},iS=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},nS=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},U0=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((Y)=>encodeURIComponent(Y))).join(iS(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=aS(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)}`},z0=({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(([G,J])=>{Y=[...Y,G,$?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=nS(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 sS=/\{[^{}]+\}/g,tS=({path:$,url:O})=>{let j=O,x=O.match(sS);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,U0({explode:K,name:Z,style:X,value:Y}));continue}if(typeof Y==="object"){j=j.replace(S,z0({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},k6=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=tS({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 g6=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var y6={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var v6=({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=U0({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=z0({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("&")}},h6=($)=>{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},eS=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function m6($){for(let O of $.security??[]){if(eS($,O.name))continue;let j=await g6(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var R1=($)=>k6({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:v6($.querySerializer),url:$.url}),D1=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=H0($.headers,O.headers),j},oS=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},H0=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?oS(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 I0{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 u6=()=>({error:new I0,request:new I0,response:new I0}),$9=v6({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),O9={"Content-Type":"application/json"},Yj=($={})=>({...y6,headers:O9,parseAs:"auto",querySerializer:$9,...$});var _1=($={})=>{let O=D1(Yj(),$),j=()=>({...O}),x=(G)=>{return O=D1(O,G),j()},S=u6(),K=async(G)=>{let J={...O,...G,fetch:G.fetch??O.fetch??globalThis.fetch,headers:H0(O.headers,G.headers),serializedBody:void 0};if(J.security)await m6(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=R1(I);return{opts:I,url:z}},Z=async(G)=>{let J=G.throwOnError??O.throwOnError,I=G.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(G),H={redirect:"follow",...V,body:T1(V)};z=new Request(B,H);for(let N of S.request.fns)if(N)z=await N(z,V);let P=V.fetch;W=await P(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?h6(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let T;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":T=await W[N]();break;case"json":{let U=await W.text();T=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(T);if(V.responseTransformer)T=await V.responseTransformer(T)}return V.responseStyle==="data"?T:{data:T,...D}}let _=await W.text(),q;try{q=JSON.parse(_)}catch{}throw q??_}catch(V){let B=V;for(let H of S.error.fns)if(H)B=await H(B,W,z,G);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(G)=>(J)=>Z({...J,method:G}),Y=(G)=>async(J)=>{let{opts:I,url:z}=await K(J);return b6({...I,body:I.body,method:G,onRequest:async(W,V)=>{let B=new Request(W,V);for(let H of S.request.fns)if(H)B=await H(B,I);return B},serializedBody:T1(I),url:z})};return{buildUrl:(G)=>R1({...O,...G}),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 c6=_1(Yj());class d6{client;constructor($){this.client=$?.client??c6}}class l6{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 T0 extends d6{static __registry=new l6;constructor($){super($);T0.__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 r6({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...G}){let J,I=Y??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,H=G.signal??new AbortController().signal;while(!0){if(H.aborted)break;B++;let P=G.headers instanceof Headers?G.headers:new Headers(G.headers);if(J!==void 0)P.set("Last-Event-ID",J);try{let D={redirect:"follow",...G,body:G.serializedBody,headers:P,signal:H},_=new Request(L,D);if($)_=await $(L,D);let N=await(G.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let T=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{T.cancel()}catch{}};H.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await T.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`+`),F=[],v;for(let R of i)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))v=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let m=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(m))V=m}let C,h=!1;if(F.length){let R=F.join(`+`);try{C=JSON.parse(R),h=!0}catch{C=R}}if(h){if(S)await S(C);if(x)C=await x(C)}if(j?.({data:C,event:v,id:J,retry:V}),F.length)yield C}}}finally{H.removeEventListener("abort",g),T.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var nS=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},sS=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},tS=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},z0=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((Q)=>encodeURIComponent(Q))).join(sS(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=nS(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)}`},I0=({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 Q=[];Object.entries(S).forEach(([G,J])=>{Q=[...Q,G,$?J:encodeURIComponent(J)]});let L=Q.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=tS(x),X=Object.entries(S).map(([Q,L])=>kO({allowReserved:$,name:x==="deepObject"?`${j}[${Q}]`:Q,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var eS=/\{[^{}]+\}/g,oS=({path:$,url:O})=>{let j=O,x=O.match(eS);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 Q=$[Z];if(Q===void 0||Q===null)continue;if(Array.isArray(Q)){j=j.replace(S,z0({explode:K,name:Z,style:X,value:Q}));continue}if(typeof Q==="object"){j=j.replace(S,I0({explode:K,name:Z,style:X,value:Q,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${kO({name:Z,value:Q})}`);continue}let L=encodeURIComponent(X==="label"?`.${Q}`:Q);j=j.replace(S,L)}return j},g6=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=oS({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function R1($){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 y6=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 h6=({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 Q=z0({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(Q)S.push(Q)}else if(typeof Z==="object"){let Q=I0({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(Q)S.push(Q)}else{let Q=kO({allowReserved:X.allowReserved,name:K,value:Z});if(Q)S.push(Q)}}return S.join("&")}},m6=($)=>{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},$9=($,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($9($,O.name))continue;let j=await y6(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 D1=($)=>g6({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:h6($.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=T0($.headers,O.headers),j},O9=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},T0=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?O9(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 H0{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 c6=()=>({error:new H0,request:new H0,response:new H0}),j9=h6({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),x9={"Content-Type":"application/json"},Yj=($={})=>({...v6,headers:x9,parseAs:"auto",querySerializer:j9,...$});var C1=($={})=>{let O=_1(Yj(),$),j=()=>({...O}),x=(G)=>{return O=_1(O,G),j()},S=c6(),K=async(G)=>{let J={...O,...G,fetch:G.fetch??O.fetch??globalThis.fetch,headers:T0(O.headers,G.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=D1(I);return{opts:I,url:z}},Z=async(G)=>{let J=G.throwOnError??O.throwOnError,I=G.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(G),H={redirect:"follow",...V,body:R1(V)};z=new Request(B,H);for(let N of S.request.fns)if(N)z=await N(z,V);let P=V.fetch;W=await P(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?m6(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let T;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":T=await W[N]();break;case"json":{let U=await W.text();T=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(T);if(V.responseTransformer)T=await V.responseTransformer(T)}return V.responseStyle==="data"?T:{data:T,...D}}let _=await W.text(),q;try{q=JSON.parse(_)}catch{}throw q??_}catch(V){let B=V;for(let H of S.error.fns)if(H)B=await H(B,W,z,G);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(G)=>(J)=>Z({...J,method:G}),Q=(G)=>async(J)=>{let{opts:I,url:z}=await K(J);return k6({...I,body:I.body,method:G,onRequest:async(W,V)=>{let B=new Request(W,V);for(let H of S.request.fns)if(H)B=await H(B,I);return B},serializedBody:R1(I),url:z})};return{buildUrl:(G)=>D1({...O,...G}),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:Q("CONNECT"),delete:Q("DELETE"),get:Q("GET"),head:Q("HEAD"),options:Q("OPTIONS"),patch:Q("PATCH"),post:Q("POST"),put:Q("PUT"),trace:Q("TRACE")},trace:X("TRACE")}};var d6=C1(Yj());class l6{client;constructor($){this.client=$?.client??d6}}class r6{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 R0 extends l6{static __registry=new r6;constructor($){super($);R0.__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 p6({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Q,url:L,...G}){let J,I=Q??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,H=G.signal??new AbortController().signal;while(!0){if(H.aborted)break;B++;let P=G.headers instanceof Headers?G.headers:new Headers(G.headers);if(J!==void 0)P.set("Last-Event-ID",J);try{let D={redirect:"follow",...G,body:G.serializedBody,headers:P,signal:H},_=new Request(L,D);if($)_=await $(L,D);let N=await(G.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let T=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{T.cancel()}catch{}};H.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await T.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,``);let y=U.split(``);U=y.pop()??"";for(let a of y){let i=a.split(`-`),F=[],v;for(let R of i)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))v=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let m=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(m))V=m}let M,h=!1;if(F.length){let R=F.join(`-`);try{M=JSON.parse(R),h=!0}catch{M=R}}if(h){if(S)await S(M);if(x)M=await x(M)}if(j?.({data:M,event:v,id:J,retry:V}),F.length)yield M}}}finally{H.removeEventListener("abort",g),T.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var j9=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},x9=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},S9=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},R0=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((Y)=>encodeURIComponent(Y))).join(x9(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=j9(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)}`},D0=({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(([G,J])=>{Y=[...Y,G,$?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=S9(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 Z9=/\{[^{}]+\}/g,X9=({path:$,url:O})=>{let j=O,x=O.match(Z9);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,R0({explode:K,name:Z,style:X,value:Y}));continue}if(typeof Y==="object"){j=j.replace(S,D0({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},p6=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=X9({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 a6=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 i6={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var n6=({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=R0({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=D0({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("&")}},s6=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},K9=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function t6($){for(let O of $.security??[]){if(K9($,O.name))continue;let j=await a6(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=($)=>p6({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:n6($.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=M0($.headers,O.headers),j},Y9=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},M0=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?Y9(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 _0{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 e6=()=>({error:new _0,request:new _0,response:new _0}),Q9=n6({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),G9={"Content-Type":"application/json"},Qj=($={})=>({...i6,headers:G9,parseAs:"auto",querySerializer:Q9,...$});var P1=($={})=>{let O=A1(Qj(),$),j=()=>({...O}),x=(G)=>{return O=A1(O,G),j()},S=e6(),K=async(G)=>{let J={...O,...G,fetch:G.fetch??O.fetch??globalThis.fetch,headers:M0(O.headers,G.headers),serializedBody:void 0};if(J.security)await t6(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(G)=>{let J=G.throwOnError??O.throwOnError,I=G.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(G),H={redirect:"follow",...V,body:M1(V)};z=new Request(B,H);for(let N of S.request.fns)if(N)z=await N(z,V);let P=V.fetch;W=await P(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?s6(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let T;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":T=await W[N]();break;case"json":{let U=await W.text();T=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(T);if(V.responseTransformer)T=await V.responseTransformer(T)}return V.responseStyle==="data"?T:{data:T,...D}}let _=await W.text(),q;try{q=JSON.parse(_)}catch{}throw q??_}catch(V){let B=V;for(let H of S.error.fns)if(H)B=await H(B,W,z,G);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(G)=>(J)=>Z({...J,method:G}),Y=(G)=>async(J)=>{let{opts:I,url:z}=await K(J);return r6({...I,body:I.body,method:G,onRequest:async(W,V)=>{let B=new Request(W,V);for(let H of S.request.fns)if(H)B=await H(B,I);return B},serializedBody:M1(I),url:z})};return{buildUrl:(G)=>C1({...O,...G}),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 o6=P1(Qj());class $7{client;constructor($){this.client=$?.client??o6}}class O7{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 C0 extends $7{static __registry=new O7;constructor($){super($);C0.__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",...$})}unshareScheduledActionTemplate($){return($.client??this.client).delete({url:"/scheduled-actions/{id}/template",...$})}getScheduledActionTemplate($){return($.client??this.client).get({url:"/scheduled-actions/{id}/template",...$})}shareScheduledActionTemplate($){return($.client??this.client).put({url:"/scheduled-actions/{id}/template",...$,headers:{"Content-Type":"application/json",...$.headers}})}activateScheduledActionTemplate($){return($.client??this.client).post({url:"/scheduled-actions/{id}/template/activate",...$,headers:{"Content-Type":"application/json",...$.headers}})}}function j7({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...G}){let J,I=Y??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,H=G.signal??new AbortController().signal;while(!0){if(H.aborted)break;B++;let P=G.headers instanceof Headers?G.headers:new Headers(G.headers);if(J!==void 0)P.set("Last-Event-ID",J);try{let D={redirect:"follow",...G,body:G.serializedBody,headers:P,signal:H},_=new Request(L,D);if($)_=await $(L,D);let N=await(G.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let T=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{T.cancel()}catch{}};H.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await T.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`+`),F=[],v;for(let R of i)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))v=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let m=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(m))V=m}let C,h=!1;if(F.length){let R=F.join(`+`);try{C=JSON.parse(R),h=!0}catch{C=R}}if(h){if(S)await S(C);if(x)C=await x(C)}if(j?.({data:C,event:v,id:J,retry:V}),F.length)yield C}}}finally{H.removeEventListener("abort",g),T.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var S9=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},Z9=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},X9=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},D0=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((Q)=>encodeURIComponent(Q))).join(Z9(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=S9(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)}`},_0=({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 Q=[];Object.entries(S).forEach(([G,J])=>{Q=[...Q,G,$?J:encodeURIComponent(J)]});let L=Q.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=X9(x),X=Object.entries(S).map(([Q,L])=>gO({allowReserved:$,name:x==="deepObject"?`${j}[${Q}]`:Q,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var K9=/\{[^{}]+\}/g,Q9=({path:$,url:O})=>{let j=O,x=O.match(K9);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 Q=$[Z];if(Q===void 0||Q===null)continue;if(Array.isArray(Q)){j=j.replace(S,D0({explode:K,name:Z,style:X,value:Q}));continue}if(typeof Q==="object"){j=j.replace(S,_0({explode:K,name:Z,style:X,value:Q,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${gO({name:Z,value:Q})}`);continue}let L=encodeURIComponent(X==="label"?`.${Q}`:Q);j=j.replace(S,L)}return j},a6=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=Q9({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 i6=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 n6={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var s6=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let Q=D0({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(Q)S.push(Q)}else if(typeof Z==="object"){let Q=_0({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(Q)S.push(Q)}else{let Q=gO({allowReserved:X.allowReserved,name:K,value:Z});if(Q)S.push(Q)}}return S.join("&")}},t6=($)=>{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},Y9=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function e6($){for(let O of $.security??[]){if(Y9($,O.name))continue;let j=await i6(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=($)=>a6({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:s6($.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=M0($.headers,O.headers),j},G9=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},M0=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?G9(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 C0{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 o6=()=>({error:new C0,request:new C0,response:new C0}),J9=s6({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),V9={"Content-Type":"application/json"},Gj=($={})=>({...n6,headers:V9,parseAs:"auto",querySerializer:J9,...$});var F1=($={})=>{let O=P1(Gj(),$),j=()=>({...O}),x=(G)=>{return O=P1(O,G),j()},S=o6(),K=async(G)=>{let J={...O,...G,fetch:G.fetch??O.fetch??globalThis.fetch,headers:M0(O.headers,G.headers),serializedBody:void 0};if(J.security)await e6(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(G)=>{let J=G.throwOnError??O.throwOnError,I=G.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(G),H={redirect:"follow",...V,body:M1(V)};z=new Request(B,H);for(let N of S.request.fns)if(N)z=await N(z,V);let P=V.fetch;W=await P(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?t6(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let T;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":T=await W[N]();break;case"json":{let U=await W.text();T=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(T);if(V.responseTransformer)T=await V.responseTransformer(T)}return V.responseStyle==="data"?T:{data:T,...D}}let _=await W.text(),q;try{q=JSON.parse(_)}catch{}throw q??_}catch(V){let B=V;for(let H of S.error.fns)if(H)B=await H(B,W,z,G);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(G)=>(J)=>Z({...J,method:G}),Q=(G)=>async(J)=>{let{opts:I,url:z}=await K(J);return p6({...I,body:I.body,method:G,onRequest:async(W,V)=>{let B=new Request(W,V);for(let H of S.request.fns)if(H)B=await H(B,I);return B},serializedBody:M1(I),url:z})};return{buildUrl:(G)=>A1({...O,...G}),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:Q("CONNECT"),delete:Q("DELETE"),get:Q("GET"),head:Q("HEAD"),options:Q("OPTIONS"),patch:Q("PATCH"),post:Q("POST"),put:Q("PUT"),trace:Q("TRACE")},trace:X("TRACE")}};var $7=F1(Gj());class O7{client;constructor($){this.client=$?.client??$7}}class j7{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 A0 extends O7{static __registry=new j7;constructor($){super($);A0.__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",...$})}unshareScheduledActionTemplate($){return($.client??this.client).delete({url:"/scheduled-actions/{id}/template",...$})}getScheduledActionTemplate($){return($.client??this.client).get({url:"/scheduled-actions/{id}/template",...$})}shareScheduledActionTemplate($){return($.client??this.client).put({url:"/scheduled-actions/{id}/template",...$,headers:{"Content-Type":"application/json",...$.headers}})}activateScheduledActionTemplate($){return($.client??this.client).post({url:"/scheduled-actions/{id}/template/activate",...$,headers:{"Content-Type":"application/json",...$.headers}})}}function x7({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Q,url:L,...G}){let J,I=Q??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,H=G.signal??new AbortController().signal;while(!0){if(H.aborted)break;B++;let P=G.headers instanceof Headers?G.headers:new Headers(G.headers);if(J!==void 0)P.set("Last-Event-ID",J);try{let D={redirect:"follow",...G,body:G.serializedBody,headers:P,signal:H},_=new Request(L,D);if($)_=await $(L,D);let N=await(G.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let T=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{T.cancel()}catch{}};H.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await T.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,``);let y=U.split(``);U=y.pop()??"";for(let a of y){let i=a.split(`-`),F=[],v;for(let R of i)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))v=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let m=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(m))V=m}let M,h=!1;if(F.length){let R=F.join(`-`);try{M=JSON.parse(R),h=!0}catch{M=R}}if(h){if(S)await S(M);if(x)M=await x(M)}if(j?.({data:M,event:v,id:J,retry:V}),F.length)yield M}}}finally{H.removeEventListener("abort",g),T.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var J9=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},V9=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},W9=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},A0=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((Y)=>encodeURIComponent(Y))).join(V9(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=J9(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)}`},P0=({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(([G,J])=>{Y=[...Y,G,$?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=W9(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 B9=/\{[^{}]+\}/g,L9=({path:$,url:O})=>{let j=O,x=O.match(B9);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,A0({explode:K,name:Z,style:X,value:Y}));continue}if(typeof Y==="object"){j=j.replace(S,P0({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},x7=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=L9({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 S7=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 Z7={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var X7=({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=A0({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=P0({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("&")}},K7=($)=>{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},N9=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function Y7($){for(let O of $.security??[]){if(N9($,O.name))continue;let j=await S7(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=($)=>x7({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:X7($.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=E0($.headers,O.headers),j},U9=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},E0=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?U9(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 F0{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 Q7=()=>({error:new F0,request:new F0,response:new F0}),z9=X7({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),I9={"Content-Type":"application/json"},Gj=($={})=>({...Z7,headers:I9,parseAs:"auto",querySerializer:z9,...$});var w1=($={})=>{let O=q1(Gj(),$),j=()=>({...O}),x=(G)=>{return O=q1(O,G),j()},S=Q7(),K=async(G)=>{let J={...O,...G,fetch:G.fetch??O.fetch??globalThis.fetch,headers:E0(O.headers,G.headers),serializedBody:void 0};if(J.security)await Y7(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(G)=>{let J=G.throwOnError??O.throwOnError,I=G.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(G),H={redirect:"follow",...V,body:F1(V)};z=new Request(B,H);for(let N of S.request.fns)if(N)z=await N(z,V);let P=V.fetch;W=await P(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?K7(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let T;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":T=await W[N]();break;case"json":{let U=await W.text();T=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(T);if(V.responseTransformer)T=await V.responseTransformer(T)}return V.responseStyle==="data"?T:{data:T,...D}}let _=await W.text(),q;try{q=JSON.parse(_)}catch{}throw q??_}catch(V){let B=V;for(let H of S.error.fns)if(H)B=await H(B,W,z,G);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(G)=>(J)=>Z({...J,method:G}),Y=(G)=>async(J)=>{let{opts:I,url:z}=await K(J);return j7({...I,body:I.body,method:G,onRequest:async(W,V)=>{let B=new Request(W,V);for(let H of S.request.fns)if(H)B=await H(B,I);return B},serializedBody:F1(I),url:z})};return{buildUrl:(G)=>E1({...O,...G}),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 G7=w1(Gj());class J7{client;constructor($){this.client=$?.client??G7}}class V7{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 q0 extends J7{static __registry=new V7;constructor($){super($);q0.__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 W7=($,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 f1={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)=>W7(O,j,S));else W7(O,j,x)}),O}},b1={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};function B7({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...G}){let J,I=Y??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,H=G.signal??new AbortController().signal;while(!0){if(H.aborted)break;B++;let P=G.headers instanceof Headers?G.headers:new Headers(G.headers);if(J!==void 0)P.set("Last-Event-ID",J);try{let D={redirect:"follow",...G,body:G.serializedBody,headers:P,signal:H},_=new Request(L,D);if($)_=await $(L,D);let N=await(G.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let T=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{T.cancel()}catch{}};H.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await T.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`+`),F=[],v;for(let R of i)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))v=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let m=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(m))V=m}let C,h=!1;if(F.length){let R=F.join(`+`);try{C=JSON.parse(R),h=!0}catch{C=R}}if(h){if(S)await S(C);if(x)C=await x(C)}if(j?.({data:C,event:v,id:J,retry:V}),F.length)yield C}}}finally{H.removeEventListener("abort",g),T.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var W9=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},B9=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},L9=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},P0=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((Q)=>encodeURIComponent(Q))).join(B9(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=W9(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)}`},F0=({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 Q=[];Object.entries(S).forEach(([G,J])=>{Q=[...Q,G,$?J:encodeURIComponent(J)]});let L=Q.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=L9(x),X=Object.entries(S).map(([Q,L])=>yO({allowReserved:$,name:x==="deepObject"?`${j}[${Q}]`:Q,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var N9=/\{[^{}]+\}/g,U9=({path:$,url:O})=>{let j=O,x=O.match(N9);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 Q=$[Z];if(Q===void 0||Q===null)continue;if(Array.isArray(Q)){j=j.replace(S,P0({explode:K,name:Z,style:X,value:Q}));continue}if(typeof Q==="object"){j=j.replace(S,F0({explode:K,name:Z,style:X,value:Q,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${yO({name:Z,value:Q})}`);continue}let L=encodeURIComponent(X==="label"?`.${Q}`:Q);j=j.replace(S,L)}return j},S7=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=U9({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function E1($){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 Z7=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 X7={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var K7=({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 Q=P0({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(Q)S.push(Q)}else if(typeof Z==="object"){let Q=F0({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(Q)S.push(Q)}else{let Q=yO({allowReserved:X.allowReserved,name:K,value:Z});if(Q)S.push(Q)}}return S.join("&")}},Q7=($)=>{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},z9=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function Y7($){for(let O of $.security??[]){if(z9($,O.name))continue;let j=await Z7(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 q1=($)=>S7({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:K7($.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=q0($.headers,O.headers),j},I9=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},q0=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?I9(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 E0{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 G7=()=>({error:new E0,request:new E0,response:new E0}),H9=K7({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),T9={"Content-Type":"application/json"},Jj=($={})=>({...X7,headers:T9,parseAs:"auto",querySerializer:H9,...$});var f1=($={})=>{let O=w1(Jj(),$),j=()=>({...O}),x=(G)=>{return O=w1(O,G),j()},S=G7(),K=async(G)=>{let J={...O,...G,fetch:G.fetch??O.fetch??globalThis.fetch,headers:q0(O.headers,G.headers),serializedBody:void 0};if(J.security)await Y7(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=q1(I);return{opts:I,url:z}},Z=async(G)=>{let J=G.throwOnError??O.throwOnError,I=G.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(G),H={redirect:"follow",...V,body:E1(V)};z=new Request(B,H);for(let N of S.request.fns)if(N)z=await N(z,V);let P=V.fetch;W=await P(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?Q7(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let T;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":T=await W[N]();break;case"json":{let U=await W.text();T=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(T);if(V.responseTransformer)T=await V.responseTransformer(T)}return V.responseStyle==="data"?T:{data:T,...D}}let _=await W.text(),q;try{q=JSON.parse(_)}catch{}throw q??_}catch(V){let B=V;for(let H of S.error.fns)if(H)B=await H(B,W,z,G);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(G)=>(J)=>Z({...J,method:G}),Q=(G)=>async(J)=>{let{opts:I,url:z}=await K(J);return x7({...I,body:I.body,method:G,onRequest:async(W,V)=>{let B=new Request(W,V);for(let H of S.request.fns)if(H)B=await H(B,I);return B},serializedBody:E1(I),url:z})};return{buildUrl:(G)=>q1({...O,...G}),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:Q("CONNECT"),delete:Q("DELETE"),get:Q("GET"),head:Q("HEAD"),options:Q("OPTIONS"),patch:Q("PATCH"),post:Q("POST"),put:Q("PUT"),trace:Q("TRACE")},trace:X("TRACE")}};var J7=f1(Jj());class V7{client;constructor($){this.client=$?.client??J7}}class W7{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 w0 extends V7{static __registry=new W7;constructor($){super($);w0.__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 B7=($,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 b1={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)=>B7(O,j,S));else B7(O,j,x)}),O}},k1={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};function L7({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Q,url:L,...G}){let J,I=Q??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,H=G.signal??new AbortController().signal;while(!0){if(H.aborted)break;B++;let P=G.headers instanceof Headers?G.headers:new Headers(G.headers);if(J!==void 0)P.set("Last-Event-ID",J);try{let D={redirect:"follow",...G,body:G.serializedBody,headers:P,signal:H},_=new Request(L,D);if($)_=await $(L,D);let N=await(G.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let T=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{T.cancel()}catch{}};H.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await T.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,``);let y=U.split(``);U=y.pop()??"";for(let a of y){let i=a.split(`-`),F=[],v;for(let R of i)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))v=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let m=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(m))V=m}let M,h=!1;if(F.length){let R=F.join(`-`);try{M=JSON.parse(R),h=!0}catch{M=R}}if(h){if(S)await S(M);if(x)M=await x(M)}if(j?.({data:M,event:v,id:J,retry:V}),F.length)yield M}}}finally{H.removeEventListener("abort",g),T.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var H9=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},T9=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},R9=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},w0=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((Y)=>encodeURIComponent(Y))).join(T9(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=H9(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)}`},f0=({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(([G,J])=>{Y=[...Y,G,$?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=R9(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 D9=/\{[^{}]+\}/g,_9=({path:$,url:O})=>{let j=O,x=O.match(D9);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,w0({explode:K,name:Z,style:X,value:Y}));continue}if(typeof Y==="object"){j=j.replace(S,f0({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},L7=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=_9({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function k1($){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 N7=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 U7=({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=w0({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=f0({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("&")}},z7=($)=>{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},M9=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function I7($){for(let O of $.security??[]){if(M9($,O.name))continue;let j=await N7(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=($)=>L7({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:U7($.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=k0($.headers,O.headers),j},C9=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},k0=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?C9(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 b0{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 H7=()=>({error:new b0,request:new b0,response:new b0}),A9=U7({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),P9={"Content-Type":"application/json"},Jj=($={})=>({...b1,headers:P9,parseAs:"auto",querySerializer:A9,...$});var Vj=($={})=>{let O=y1(Jj(),$),j=()=>({...O}),x=(G)=>{return O=y1(O,G),j()},S=H7(),K=async(G)=>{let J={...O,...G,fetch:G.fetch??O.fetch??globalThis.fetch,headers:k0(O.headers,G.headers),serializedBody:void 0};if(J.security)await I7(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(G)=>{let J=G.throwOnError??O.throwOnError,I=G.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(G),H={redirect:"follow",...V,body:k1(V)};z=new Request(B,H);for(let N of S.request.fns)if(N)z=await N(z,V);let P=V.fetch;W=await P(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?z7(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let T;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":T=await W[N]();break;case"json":{let U=await W.text();T=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(T);if(V.responseTransformer)T=await V.responseTransformer(T)}return V.responseStyle==="data"?T:{data:T,...D}}let _=await W.text(),q;try{q=JSON.parse(_)}catch{}throw q??_}catch(V){let B=V;for(let H of S.error.fns)if(H)B=await H(B,W,z,G);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(G)=>(J)=>Z({...J,method:G}),Y=(G)=>async(J)=>{let{opts:I,url:z}=await K(J);return B7({...I,body:I.body,method:G,onRequest:async(W,V)=>{let B=new Request(W,V);for(let H of S.request.fns)if(H)B=await H(B,I);return B},serializedBody:k1(I),url:z})};return{buildUrl:(G)=>g1({...O,...G}),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 T7=Vj(Jj());class R7{client;constructor($){this.client=$?.client??T7}}class D7{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 g0 extends R7{static __registry=new D7;constructor($){super($);g0.__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",...$})}listCrmBlockedDomains($){return($?.client??this.client).get({url:"/crm/blocked-domains",...$})}unblockCrmDomain($){return($.client??this.client).delete({url:"/crm/blocked-domains/{domain}",...$})}blockCrmDomain($){return($.client??this.client).put({url:"/crm/blocked-domains/{domain}",...$})}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",...$})}createCrmTeamContact($){return($.client??this.client).post({url:"/crm/contacts",...$,headers:{"Content-Type":"application/json",...$.headers}})}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}})}getCrmPipelineViewPositions($){return($.client??this.client).get({url:"/crm/pipelines/{id}/views/{view}/positions",...$})}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",...$})}duplicateDatabase($){return($.client??this.client).post({url:"/databases/{id}/duplicate",...$,headers:{"Content-Type":"application/json",...$.headers}})}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}})}taskSimilaritySearchHandler($){return($.client??this.client).post({url:"/documents/similarity_search",...$,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",...$})}externalChats($){return($?.client??this.client).get({url:"/external-chats",...$})}externalChatAdd($){return($.client??this.client).post({url:"/external-chats",...$,headers:{"Content-Type":"application/json",...$.headers}})}externalChatRemove($){return($.client??this.client).delete({url:"/external-chats/{chat_id}",...$})}externalChat($){return($.client??this.client).get({url:"/external-chats/{chat_id}",...$})}externalChatUpload($){return($.client??this.client).post({...f1,url:"/external-chats/{chat_id}/attachments",...$,headers:{"Content-Type":null,...$.headers}})}externalChatDelivery($){return($.client??this.client).post({url:"/external-chats/{chat_id}/delivery",...$,headers:{"Content-Type":"application/json",...$.headers}})}externalChatMessages($){return($.client??this.client).get({url:"/external-chats/{chat_id}/messages",...$})}externalChatMessageAttachments($){return($.client??this.client).post({url:"/external-chats/{chat_id}/messages/attachments",...$,headers:{"Content-Type":"application/json",...$.headers}})}externalChatMessage($){return($.client??this.client).get({url:"/external-chats/{chat_id}/messages/{message_id}",...$})}externalChatPermissions($){return($.client??this.client).get({url:"/external-chats/{chat_id}/permissions",...$})}externalChatUpdatePermissions($){return($.client??this.client).patch({url:"/external-chats/{chat_id}/permissions",...$,headers:{"Content-Type":"application/json",...$.headers}})}externalChatRead($){return($.client??this.client).post({url:"/external-chats/{chat_id}/read",...$,headers:{"Content-Type":"application/json",...$.headers}})}externalChatSends($){return($.client??this.client).get({url:"/external-chats/{chat_id}/sends",...$})}externalChatSend($){return($.client??this.client).post({url:"/external-chats/{chat_id}/sends",...$,headers:{"Content-Type":"application/json",...$.headers}})}listFavorites($){return($?.client??this.client).get({url:"/favorites",...$})}addFavorite($){return($.client??this.client).post({url:"/favorites",...$,headers:{"Content-Type":"application/json",...$.headers}})}reorderFavorites($){return($.client??this.client).patch({url:"/favorites/reorder",...$,headers:{"Content-Type":"application/json",...$.headers}})}removeFavoriteByEntity($){return($.client??this.client).delete({url:"/favorites/{entity_type}/{entity_id}",...$})}getForeignEntityBySource($){return($.client??this.client).get({url:"/foreign_entity/by_source/{source}/{foreign_entity_id}",...$})}getForeignEntity($){return($.client??this.client).get({url:"/foreign_entity/{id}",...$})}listForms($){return($.client??this.client).get({url:"/forms",...$})}createForm($){return($.client??this.client).post({url:"/forms",...$,headers:{"Content-Type":"application/json",...$.headers}})}listAccessibleForms($){return($?.client??this.client).get({url:"/forms/accessible",...$})}getForm($){return($.client??this.client).get({url:"/forms/{id}",...$})}updateForm($){return($.client??this.client).patch({url:"/forms/{id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}collaborateForm($){return($.client??this.client).post({url:"/forms/{id}/collaboration",...$})}putFormLayout($){return($.client??this.client).put({url:"/forms/{id}/layout",...$,headers:{"Content-Type":"application/json",...$.headers}})}getFormPermissions($){return($.client??this.client).get({url:"/forms/{id}/permissions",...$})}updateFormPermissions($){return($.client??this.client).patch({url:"/forms/{id}/permissions",...$,headers:{"Content-Type":"application/json",...$.headers}})}submitFormResponse($){return($.client??this.client).post({url:"/forms/{id}/responses",...$,headers:{"Content-Type":"application/json",...$.headers}})}getMyFormResponse($){return($.client??this.client).get({url:"/forms/{id}/responses/mine",...$})}editMyFormResponse($){return($.client??this.client).put({url:"/forms/{id}/responses/mine",...$,headers:{"Content-Type":"application/json",...$.headers}})}getFormResponseSummary($){return($.client??this.client).get({url:"/forms/{id}/responses/summary",...$})}getFormTally($){return($.client??this.client).get({url:"/forms/{id}/tally",...$})}installSync($){return($?.client??this.client).get({url:"/github/install-sync",...$})}getGithubPullRequestFacets($){return($?.client??this.client).get({url:"/github_pull_requests/facets",...$})}getGithubPullRequest($){return($.client??this.client).get({url:"/github_pull_requests/{id}",...$})}getGithubPullRequestChanges($){return($.client??this.client).get({url:"/github_pull_requests/{id}/changes",...$})}getGithubPullRequestChangesPatch($){return($.client??this.client).get({url:"/github_pull_requests/{id}/changes/patch",...$})}createHarnessPairing($){return($.client??this.client).post({url:"/harness-pairings",...$,headers:{"Content-Type":"application/json",...$.headers}})}getHarnessPairing($){return($.client??this.client).get({url:"/harness-pairings/{code}",...$})}approveHarnessPairing($){return($.client??this.client).post({url:"/harness-pairings/{code}/approve",...$,headers:{"Content-Type":"application/json",...$.headers}})}claimHarnessPairing($){return($.client??this.client).post({url:"/harness-pairings/{pairing_id}/claim",...$,headers:{"Content-Type":"application/json",...$.headers}})}listHarnesses($){return($?.client??this.client).get({url:"/harnesses",...$})}deleteSelfHarness($){return($?.client??this.client).delete({url:"/harnesses/me",...$})}getSelfHarness($){return($?.client??this.client).get({url:"/harnesses/me",...$})}listHarnessAgents($){return($?.client??this.client).get({url:"/harnesses/me/agents",...$})}listHarnessSessions($){return($?.client??this.client).get({url:"/harnesses/me/sessions",...$})}deleteHarness($){return($.client??this.client).delete({url:"/harnesses/{harness_id}",...$})}healthHandler($){return($?.client??this.client).get({url:"/health",...$})}getHistoryHandler($){return($?.client??this.client).get({url:"/history",...$})}deleteHistoryHandler($){return($.client??this.client).delete({url:"/history/{item_type}/{item_id}",...$})}upsertHistoryHandler($){return($.client??this.client).post({url:"/history/{item_type}/{item_id}",...$})}listInitiatives($){return($?.client??this.client).get({url:"/initiatives",...$})}createInitiative($){return($.client??this.client).post({url:"/initiatives",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteInitiative($){return($.client??this.client).delete({url:"/initiatives/{initiative_id}",...$})}getInitiative($){return($.client??this.client).get({url:"/initiatives/{initiative_id}",...$})}updateInitiative($){return($.client??this.client).patch({url:"/initiatives/{initiative_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getInstructionsHandler($){return($?.client??this.client).get({url:"/instructions",...$})}createInstructionsHandler($){return($?.client??this.client).post({url:"/instructions",...$})}getItemsSoup($){return($?.client??this.client).get({url:"/items/soup",...$})}postItemsSoup($){return($.client??this.client).post({url:"/items/soup",...$,headers:{"Content-Type":"application/json",...$.headers}})}postItemsSoupAst($){return($.client??this.client).post({url:"/items/soup/ast",...$,headers:{"Content-Type":"application/json",...$.headers}})}postItemsSoupAstGrouped($){return($.client??this.client).post({url:"/items/soup/ast/grouped",...$,headers:{"Content-Type":"application/json",...$.headers}})}messageTimeline($){return($.client??this.client).get({url:"/messages/{parent_type}/{parent_id}",...$})}entityMessageCreate($){return($.client??this.client).post({url:"/messages/{parent_type}/{parent_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}entityMessageDeleteMessage($){return($.client??this.client).delete({url:"/messages/{parent_type}/{parent_id}/items/{id}",...$})}entityMessageGetMessage($){return($.client??this.client).get({url:"/messages/{parent_type}/{parent_id}/items/{id}",...$})}entityMessageEdit($){return($.client??this.client).patch({url:"/messages/{parent_type}/{parent_id}/items/{id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}entityMessageReact($){return($.client??this.client).post({url:"/messages/{parent_type}/{parent_id}/items/{id}/reactions",...$,headers:{"Content-Type":"application/json",...$.headers}})}entityMessageLegacy($){return($.client??this.client).get({url:"/messages/{parent_type}/{parent_id}/legacy/{legacy_id}",...$})}entityMessageDeleteThread($){return($.client??this.client).delete({url:"/messages/{parent_type}/{parent_id}/threads/{id}",...$})}entityMessageGetThread($){return($.client??this.client).get({url:"/messages/{parent_type}/{parent_id}/threads/{id}",...$})}entityMessagePatchThread($){return($.client??this.client).patch({url:"/messages/{parent_type}/{parent_id}/threads/{id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}messageTimelineEntries($){return($.client??this.client).get({url:"/messages/{parent_type}/{parent_id}/timeline",...$})}entityMessageTyping($){return($.client??this.client).post({url:"/messages/{parent_type}/{parent_id}/typing",...$,headers:{"Content-Type":"application/json",...$.headers}})}getPinsHandler($){return($?.client??this.client).get({url:"/pins",...$})}reorderPinsHandler($){return($.client??this.client).patch({url:"/pins",...$,headers:{"Content-Type":"application/json",...$.headers}})}removePinHandler($){return($.client??this.client).delete({url:"/pins/{pinned_item_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}addPinHandler($){return($.client??this.client).post({url:"/pins/{pinned_item_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getProjectsHandler($){return($?.client??this.client).get({url:"/projects",...$})}createProjectHandler($){return($.client??this.client).post({url:"/projects",...$,headers:{"Content-Type":"application/json",...$.headers}})}getPendingProjectsHandler($){return($?.client??this.client).get({url:"/projects/pending",...$})}getBatchProjectPreview($){return($.client??this.client).post({url:"/projects/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}uploadFolderHandler($){return($.client??this.client).post({url:"/projects/upload",...$,headers:{"Content-Type":"application/json",...$.headers}})}uploadExtractFolderHandler($){return($.client??this.client).post({url:"/projects/upload_extract",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteProjectHandler($){return($.client??this.client).delete({url:"/projects/{id}",...$})}getProjectHandler($){return($.client??this.client).get({url:"/projects/{id}",...$})}getProjectUserAccessLevel($){return($.client??this.client).get({url:"/projects/{id}/access_level",...$})}getProjectContentHandler($){return($.client??this.client).get({url:"/projects/{id}/content",...$})}permanentlyDeleteProject($){return($.client??this.client).delete({url:"/projects/{id}/permanent",...$})}getProjectPermissionsV2($){return($.client??this.client).get({url:"/projects/{id}/permissions",...$})}revertDeleteProject($){return($.client??this.client).put({url:"/projects/{id}/revert_delete",...$})}recentlyDeleted($){return($?.client??this.client).get({url:"/recents/deleted",...$})}listEmailReminders($){return($?.client??this.client).get({url:"/reminders/email/collection",...$})}getEmailFollowup($){return($.client??this.client).get({url:"/reminders/email/{thread_id}",...$})}setEmailFollowup($){return($.client??this.client).put({url:"/reminders/email/{thread_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getViewsHandler($){return($?.client??this.client).get({url:"/saved_views",...$})}createViewHandler($){return($.client??this.client).post({url:"/saved_views",...$,headers:{"Content-Type":"application/json",...$.headers}})}excludeDefaultViewHandler($){return($.client??this.client).post({url:"/saved_views/exclude_default",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteViewHandler($){return($.client??this.client).delete({url:"/saved_views/{saved_view_id}",...$})}patchViewHandler($){return($.client??this.client).patch({url:"/saved_views/{saved_view_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}listSlackImports($){return($?.client??this.client).get({url:"/slack/imports",...$})}createSlackImport($){return($.client??this.client).post({url:"/slack/imports",...$,headers:{"Content-Type":"application/json",...$.headers}})}getSlackImport($){return($.client??this.client).get({url:"/slack/imports/{job_id}",...$})}cancelSlackImport($){return($.client??this.client).post({url:"/slack/imports/{job_id}/cancel",...$})}finalizeSlackImport($){return($.client??this.client).post({url:"/slack/imports/{job_id}/finalize",...$})}registerSlackImportUploads($){return($.client??this.client).post({url:"/slack/imports/{job_id}/uploads",...$,headers:{"Content-Type":"application/json",...$.headers}})}completeSlackImportUploads($){return($.client??this.client).post({url:"/slack/imports/{job_id}/uploads/complete",...$,headers:{"Content-Type":"application/json",...$.headers}})}bulkWakeupSyncServiceDocuments($){return($.client??this.client).post({url:"/sync_service/wakeup",...$,headers:{"Content-Type":"application/json",...$.headers}})}editThreadV2($){return($.client??this.client).patch({url:"/threads/{thread_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}listUserApiKeys($){return($?.client??this.client).get({url:"/user-api-keys",...$})}createUserApiKey($){return($.client??this.client).post({url:"/user-api-keys",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteUserApiKey($){return($.client??this.client).delete({url:"/user-api-keys/{id}",...$})}deleteUserDocumentViewLocation($){return($.client??this.client).delete({url:"/user_document_view_location/{document_id}",...$})}getUserDocumentViewLocation($){return($.client??this.client).get({url:"/user_document_view_location/{document_id}",...$})}upsertUserDocumentViewLocation($){return($.client??this.client).post({url:"/user_document_view_location/{document_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDocumentPermissionsV2($){return($.client??this.client).get({url:"/v2/documents/{document_id}/permissions",...$})}editProjectV2($){return($.client??this.client).patch({url:"/v2/projects/{id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}streamEvents($){return($.client??this.client).sse.get({url:"/webhook/events/stream",...$})}listWebhooks($){return($?.client??this.client).get({url:"/webhook/webhooks",...$})}createWebhook($){return($.client??this.client).post({url:"/webhook/webhooks",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteWebhook($){return($.client??this.client).delete({url:"/webhook/webhooks/{webhook_id}",...$})}getWebhook($){return($.client??this.client).get({url:"/webhook/webhooks/{webhook_id}",...$})}patchWebhook($){return($.client??this.client).patch({url:"/webhook/webhooks/{webhook_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}validateWebhook($){return($.client??this.client).post({url:"/webhook/webhooks/{webhook_id}/validate",...$})}whatsappAccount($){return($?.client??this.client).get({url:"/whatsapp/account",...$})}whatsappChats($){return($?.client??this.client).get({url:"/whatsapp/chats",...$})}whatsappConnect($){return($.client??this.client).post({url:"/whatsapp/connect",...$,headers:{"Content-Type":"application/json",...$.headers}})}whatsappDisconnect($){return($.client??this.client).post({url:"/whatsapp/disconnect",...$,headers:{"Content-Type":"application/json",...$.headers}})}whatsappImportHistory($){return($?.client??this.client).post({url:"/whatsapp/history-import",...$})}whatsappStartLookup($){return($.client??this.client).post({url:"/whatsapp/lookups",...$,headers:{"Content-Type":"application/json",...$.headers}})}whatsappLookup($){return($.client??this.client).get({url:"/whatsapp/lookups/{id}",...$})}whatsappCancelPairing($){return($.client??this.client).delete({url:"/whatsapp/pairing/{id}",...$})}whatsappPairing($){return($.client??this.client).get({url:"/whatsapp/pairing/{id}",...$})}whatsappPasskey($){return($.client??this.client).post({url:"/whatsapp/pairing/{id}/passkey",...$,headers:{"Content-Type":"application/json",...$.headers}})}}function _7({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...G}){let J,I=Y??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,H=G.signal??new AbortController().signal;while(!0){if(H.aborted)break;B++;let P=G.headers instanceof Headers?G.headers:new Headers(G.headers);if(J!==void 0)P.set("Last-Event-ID",J);try{let D={redirect:"follow",...G,body:G.serializedBody,headers:P,signal:H},_=new Request(L,D);if($)_=await $(L,D);let N=await(G.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let T=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{T.cancel()}catch{}};H.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await T.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`+`),F=[],v;for(let R of i)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))v=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let m=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(m))V=m}let C,h=!1;if(F.length){let R=F.join(`+`);try{C=JSON.parse(R),h=!0}catch{C=R}}if(h){if(S)await S(C);if(x)C=await x(C)}if(j?.({data:C,event:v,id:J,retry:V}),F.length)yield C}}}finally{H.removeEventListener("abort",g),T.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var R9=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},D9=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},_9=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},f0=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((Q)=>encodeURIComponent(Q))).join(D9(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=R9(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)}`},b0=({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 Q=[];Object.entries(S).forEach(([G,J])=>{Q=[...Q,G,$?J:encodeURIComponent(J)]});let L=Q.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=_9(x),X=Object.entries(S).map(([Q,L])=>vO({allowReserved:$,name:x==="deepObject"?`${j}[${Q}]`:Q,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var C9=/\{[^{}]+\}/g,M9=({path:$,url:O})=>{let j=O,x=O.match(C9);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 Q=$[Z];if(Q===void 0||Q===null)continue;if(Array.isArray(Q)){j=j.replace(S,f0({explode:K,name:Z,style:X,value:Q}));continue}if(typeof Q==="object"){j=j.replace(S,b0({explode:K,name:Z,style:X,value:Q,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${vO({name:Z,value:Q})}`);continue}let L=encodeURIComponent(X==="label"?`.${Q}`:Q);j=j.replace(S,L)}return j},N7=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=M9({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function g1($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var U7=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 z7=({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 Q=f0({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(Q)S.push(Q)}else if(typeof Z==="object"){let Q=b0({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(Q)S.push(Q)}else{let Q=vO({allowReserved:X.allowReserved,name:K,value:Z});if(Q)S.push(Q)}}return S.join("&")}},I7=($)=>{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},A9=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function H7($){for(let O of $.security??[]){if(A9($,O.name))continue;let j=await U7(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var y1=($)=>N7({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:z7($.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=g0($.headers,O.headers),j},P9=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},g0=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?P9(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class k0{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var T7=()=>({error:new k0,request:new k0,response:new k0}),F9=z7({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),E9={"Content-Type":"application/json"},Vj=($={})=>({...k1,headers:E9,parseAs:"auto",querySerializer:F9,...$});var Wj=($={})=>{let O=v1(Vj(),$),j=()=>({...O}),x=(G)=>{return O=v1(O,G),j()},S=T7(),K=async(G)=>{let J={...O,...G,fetch:G.fetch??O.fetch??globalThis.fetch,headers:g0(O.headers,G.headers),serializedBody:void 0};if(J.security)await H7(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let I=J,z=y1(I);return{opts:I,url:z}},Z=async(G)=>{let J=G.throwOnError??O.throwOnError,I=G.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(G),H={redirect:"follow",...V,body:g1(V)};z=new Request(B,H);for(let N of S.request.fns)if(N)z=await N(z,V);let P=V.fetch;W=await P(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?I7(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let T;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":T=await W[N]();break;case"json":{let U=await W.text();T=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(T);if(V.responseTransformer)T=await V.responseTransformer(T)}return V.responseStyle==="data"?T:{data:T,...D}}let _=await W.text(),q;try{q=JSON.parse(_)}catch{}throw q??_}catch(V){let B=V;for(let H of S.error.fns)if(H)B=await H(B,W,z,G);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(G)=>(J)=>Z({...J,method:G}),Q=(G)=>async(J)=>{let{opts:I,url:z}=await K(J);return L7({...I,body:I.body,method:G,onRequest:async(W,V)=>{let B=new Request(W,V);for(let H of S.request.fns)if(H)B=await H(B,I);return B},serializedBody:g1(I),url:z})};return{buildUrl:(G)=>y1({...O,...G}),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:Q("CONNECT"),delete:Q("DELETE"),get:Q("GET"),head:Q("HEAD"),options:Q("OPTIONS"),patch:Q("PATCH"),post:Q("POST"),put:Q("PUT"),trace:Q("TRACE")},trace:X("TRACE")}};var R7=Wj(Vj());class D7{client;constructor($){this.client=$?.client??R7}}class _7{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class y0 extends D7{static __registry=new _7;constructor($){super($);y0.__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",...$})}listCrmBlockedDomains($){return($?.client??this.client).get({url:"/crm/blocked-domains",...$})}unblockCrmDomain($){return($.client??this.client).delete({url:"/crm/blocked-domains/{domain}",...$})}blockCrmDomain($){return($.client??this.client).put({url:"/crm/blocked-domains/{domain}",...$})}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",...$})}createCrmTeamContact($){return($.client??this.client).post({url:"/crm/contacts",...$,headers:{"Content-Type":"application/json",...$.headers}})}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}})}getCrmPipelineViewPositions($){return($.client??this.client).get({url:"/crm/pipelines/{id}/views/{view}/positions",...$})}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",...$})}duplicateDatabase($){return($.client??this.client).post({url:"/databases/{id}/duplicate",...$,headers:{"Content-Type":"application/json",...$.headers}})}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}})}taskSimilaritySearchHandler($){return($.client??this.client).post({url:"/documents/similarity_search",...$,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",...$})}externalChats($){return($?.client??this.client).get({url:"/external-chats",...$})}externalChatAdd($){return($.client??this.client).post({url:"/external-chats",...$,headers:{"Content-Type":"application/json",...$.headers}})}externalChatRemove($){return($.client??this.client).delete({url:"/external-chats/{chat_id}",...$})}externalChat($){return($.client??this.client).get({url:"/external-chats/{chat_id}",...$})}externalChatUpload($){return($.client??this.client).post({...b1,url:"/external-chats/{chat_id}/attachments",...$,headers:{"Content-Type":null,...$.headers}})}externalChatDelivery($){return($.client??this.client).post({url:"/external-chats/{chat_id}/delivery",...$,headers:{"Content-Type":"application/json",...$.headers}})}externalChatMessages($){return($.client??this.client).get({url:"/external-chats/{chat_id}/messages",...$})}externalChatMessageAttachments($){return($.client??this.client).post({url:"/external-chats/{chat_id}/messages/attachments",...$,headers:{"Content-Type":"application/json",...$.headers}})}externalChatMessage($){return($.client??this.client).get({url:"/external-chats/{chat_id}/messages/{message_id}",...$})}externalChatPermissions($){return($.client??this.client).get({url:"/external-chats/{chat_id}/permissions",...$})}externalChatUpdatePermissions($){return($.client??this.client).patch({url:"/external-chats/{chat_id}/permissions",...$,headers:{"Content-Type":"application/json",...$.headers}})}externalChatRead($){return($.client??this.client).post({url:"/external-chats/{chat_id}/read",...$,headers:{"Content-Type":"application/json",...$.headers}})}externalChatSends($){return($.client??this.client).get({url:"/external-chats/{chat_id}/sends",...$})}externalChatSend($){return($.client??this.client).post({url:"/external-chats/{chat_id}/sends",...$,headers:{"Content-Type":"application/json",...$.headers}})}listFavorites($){return($?.client??this.client).get({url:"/favorites",...$})}addFavorite($){return($.client??this.client).post({url:"/favorites",...$,headers:{"Content-Type":"application/json",...$.headers}})}reorderFavorites($){return($.client??this.client).patch({url:"/favorites/reorder",...$,headers:{"Content-Type":"application/json",...$.headers}})}removeFavoriteByEntity($){return($.client??this.client).delete({url:"/favorites/{entity_type}/{entity_id}",...$})}getForeignEntityBySource($){return($.client??this.client).get({url:"/foreign_entity/by_source/{source}/{foreign_entity_id}",...$})}getForeignEntity($){return($.client??this.client).get({url:"/foreign_entity/{id}",...$})}listForms($){return($.client??this.client).get({url:"/forms",...$})}createForm($){return($.client??this.client).post({url:"/forms",...$,headers:{"Content-Type":"application/json",...$.headers}})}listAccessibleForms($){return($?.client??this.client).get({url:"/forms/accessible",...$})}getForm($){return($.client??this.client).get({url:"/forms/{id}",...$})}updateForm($){return($.client??this.client).patch({url:"/forms/{id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}collaborateForm($){return($.client??this.client).post({url:"/forms/{id}/collaboration",...$})}putFormLayout($){return($.client??this.client).put({url:"/forms/{id}/layout",...$,headers:{"Content-Type":"application/json",...$.headers}})}getFormPermissions($){return($.client??this.client).get({url:"/forms/{id}/permissions",...$})}updateFormPermissions($){return($.client??this.client).patch({url:"/forms/{id}/permissions",...$,headers:{"Content-Type":"application/json",...$.headers}})}submitFormResponse($){return($.client??this.client).post({url:"/forms/{id}/responses",...$,headers:{"Content-Type":"application/json",...$.headers}})}getMyFormResponse($){return($.client??this.client).get({url:"/forms/{id}/responses/mine",...$})}editMyFormResponse($){return($.client??this.client).put({url:"/forms/{id}/responses/mine",...$,headers:{"Content-Type":"application/json",...$.headers}})}getFormResponseSummary($){return($.client??this.client).get({url:"/forms/{id}/responses/summary",...$})}getFormTally($){return($.client??this.client).get({url:"/forms/{id}/tally",...$})}installSync($){return($?.client??this.client).get({url:"/github/install-sync",...$})}getGithubPullRequestFacets($){return($?.client??this.client).get({url:"/github_pull_requests/facets",...$})}getGithubPullRequest($){return($.client??this.client).get({url:"/github_pull_requests/{id}",...$})}getGithubPullRequestChanges($){return($.client??this.client).get({url:"/github_pull_requests/{id}/changes",...$})}getGithubPullRequestChangesPatch($){return($.client??this.client).get({url:"/github_pull_requests/{id}/changes/patch",...$})}createHarnessPairing($){return($.client??this.client).post({url:"/harness-pairings",...$,headers:{"Content-Type":"application/json",...$.headers}})}getHarnessPairing($){return($.client??this.client).get({url:"/harness-pairings/{code}",...$})}approveHarnessPairing($){return($.client??this.client).post({url:"/harness-pairings/{code}/approve",...$,headers:{"Content-Type":"application/json",...$.headers}})}claimHarnessPairing($){return($.client??this.client).post({url:"/harness-pairings/{pairing_id}/claim",...$,headers:{"Content-Type":"application/json",...$.headers}})}listHarnesses($){return($?.client??this.client).get({url:"/harnesses",...$})}deleteSelfHarness($){return($?.client??this.client).delete({url:"/harnesses/me",...$})}getSelfHarness($){return($?.client??this.client).get({url:"/harnesses/me",...$})}listHarnessAgents($){return($?.client??this.client).get({url:"/harnesses/me/agents",...$})}listHarnessSessions($){return($?.client??this.client).get({url:"/harnesses/me/sessions",...$})}deleteHarness($){return($.client??this.client).delete({url:"/harnesses/{harness_id}",...$})}healthHandler($){return($?.client??this.client).get({url:"/health",...$})}getHistoryHandler($){return($?.client??this.client).get({url:"/history",...$})}deleteHistoryHandler($){return($.client??this.client).delete({url:"/history/{item_type}/{item_id}",...$})}upsertHistoryHandler($){return($.client??this.client).post({url:"/history/{item_type}/{item_id}",...$})}listInitiatives($){return($?.client??this.client).get({url:"/initiatives",...$})}createInitiative($){return($.client??this.client).post({url:"/initiatives",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteInitiative($){return($.client??this.client).delete({url:"/initiatives/{initiative_id}",...$})}getInitiative($){return($.client??this.client).get({url:"/initiatives/{initiative_id}",...$})}updateInitiative($){return($.client??this.client).patch({url:"/initiatives/{initiative_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getInstructionsHandler($){return($?.client??this.client).get({url:"/instructions",...$})}createInstructionsHandler($){return($?.client??this.client).post({url:"/instructions",...$})}getItemsSoup($){return($?.client??this.client).get({url:"/items/soup",...$})}postItemsSoup($){return($.client??this.client).post({url:"/items/soup",...$,headers:{"Content-Type":"application/json",...$.headers}})}postItemsSoupAst($){return($.client??this.client).post({url:"/items/soup/ast",...$,headers:{"Content-Type":"application/json",...$.headers}})}postItemsSoupAstGrouped($){return($.client??this.client).post({url:"/items/soup/ast/grouped",...$,headers:{"Content-Type":"application/json",...$.headers}})}messageTimeline($){return($.client??this.client).get({url:"/messages/{parent_type}/{parent_id}",...$})}entityMessageCreate($){return($.client??this.client).post({url:"/messages/{parent_type}/{parent_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}entityMessageDeleteMessage($){return($.client??this.client).delete({url:"/messages/{parent_type}/{parent_id}/items/{id}",...$})}entityMessageGetMessage($){return($.client??this.client).get({url:"/messages/{parent_type}/{parent_id}/items/{id}",...$})}entityMessageEdit($){return($.client??this.client).patch({url:"/messages/{parent_type}/{parent_id}/items/{id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}entityMessageReact($){return($.client??this.client).post({url:"/messages/{parent_type}/{parent_id}/items/{id}/reactions",...$,headers:{"Content-Type":"application/json",...$.headers}})}entityMessageLegacy($){return($.client??this.client).get({url:"/messages/{parent_type}/{parent_id}/legacy/{legacy_id}",...$})}entityMessageDeleteThread($){return($.client??this.client).delete({url:"/messages/{parent_type}/{parent_id}/threads/{id}",...$})}entityMessageGetThread($){return($.client??this.client).get({url:"/messages/{parent_type}/{parent_id}/threads/{id}",...$})}entityMessagePatchThread($){return($.client??this.client).patch({url:"/messages/{parent_type}/{parent_id}/threads/{id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}messageTimelineEntries($){return($.client??this.client).get({url:"/messages/{parent_type}/{parent_id}/timeline",...$})}entityMessageTyping($){return($.client??this.client).post({url:"/messages/{parent_type}/{parent_id}/typing",...$,headers:{"Content-Type":"application/json",...$.headers}})}getPinsHandler($){return($?.client??this.client).get({url:"/pins",...$})}reorderPinsHandler($){return($.client??this.client).patch({url:"/pins",...$,headers:{"Content-Type":"application/json",...$.headers}})}removePinHandler($){return($.client??this.client).delete({url:"/pins/{pinned_item_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}addPinHandler($){return($.client??this.client).post({url:"/pins/{pinned_item_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getProjectsHandler($){return($?.client??this.client).get({url:"/projects",...$})}createProjectHandler($){return($.client??this.client).post({url:"/projects",...$,headers:{"Content-Type":"application/json",...$.headers}})}getPendingProjectsHandler($){return($?.client??this.client).get({url:"/projects/pending",...$})}getBatchProjectPreview($){return($.client??this.client).post({url:"/projects/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}uploadFolderHandler($){return($.client??this.client).post({url:"/projects/upload",...$,headers:{"Content-Type":"application/json",...$.headers}})}uploadExtractFolderHandler($){return($.client??this.client).post({url:"/projects/upload_extract",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteProjectHandler($){return($.client??this.client).delete({url:"/projects/{id}",...$})}getProjectHandler($){return($.client??this.client).get({url:"/projects/{id}",...$})}getProjectUserAccessLevel($){return($.client??this.client).get({url:"/projects/{id}/access_level",...$})}getProjectContentHandler($){return($.client??this.client).get({url:"/projects/{id}/content",...$})}permanentlyDeleteProject($){return($.client??this.client).delete({url:"/projects/{id}/permanent",...$})}getProjectPermissionsV2($){return($.client??this.client).get({url:"/projects/{id}/permissions",...$})}revertDeleteProject($){return($.client??this.client).put({url:"/projects/{id}/revert_delete",...$})}recentlyDeleted($){return($?.client??this.client).get({url:"/recents/deleted",...$})}listEmailReminders($){return($?.client??this.client).get({url:"/reminders/email/collection",...$})}getEmailFollowup($){return($.client??this.client).get({url:"/reminders/email/{thread_id}",...$})}setEmailFollowup($){return($.client??this.client).put({url:"/reminders/email/{thread_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getViewsHandler($){return($?.client??this.client).get({url:"/saved_views",...$})}createViewHandler($){return($.client??this.client).post({url:"/saved_views",...$,headers:{"Content-Type":"application/json",...$.headers}})}excludeDefaultViewHandler($){return($.client??this.client).post({url:"/saved_views/exclude_default",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteViewHandler($){return($.client??this.client).delete({url:"/saved_views/{saved_view_id}",...$})}patchViewHandler($){return($.client??this.client).patch({url:"/saved_views/{saved_view_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}listSlackImports($){return($?.client??this.client).get({url:"/slack/imports",...$})}createSlackImport($){return($.client??this.client).post({url:"/slack/imports",...$,headers:{"Content-Type":"application/json",...$.headers}})}getSlackImport($){return($.client??this.client).get({url:"/slack/imports/{job_id}",...$})}cancelSlackImport($){return($.client??this.client).post({url:"/slack/imports/{job_id}/cancel",...$})}finalizeSlackImport($){return($.client??this.client).post({url:"/slack/imports/{job_id}/finalize",...$})}registerSlackImportUploads($){return($.client??this.client).post({url:"/slack/imports/{job_id}/uploads",...$,headers:{"Content-Type":"application/json",...$.headers}})}completeSlackImportUploads($){return($.client??this.client).post({url:"/slack/imports/{job_id}/uploads/complete",...$,headers:{"Content-Type":"application/json",...$.headers}})}bulkWakeupSyncServiceDocuments($){return($.client??this.client).post({url:"/sync_service/wakeup",...$,headers:{"Content-Type":"application/json",...$.headers}})}editThreadV2($){return($.client??this.client).patch({url:"/threads/{thread_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}listUserApiKeys($){return($?.client??this.client).get({url:"/user-api-keys",...$})}createUserApiKey($){return($.client??this.client).post({url:"/user-api-keys",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteUserApiKey($){return($.client??this.client).delete({url:"/user-api-keys/{id}",...$})}deleteUserDocumentViewLocation($){return($.client??this.client).delete({url:"/user_document_view_location/{document_id}",...$})}getUserDocumentViewLocation($){return($.client??this.client).get({url:"/user_document_view_location/{document_id}",...$})}upsertUserDocumentViewLocation($){return($.client??this.client).post({url:"/user_document_view_location/{document_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDocumentPermissionsV2($){return($.client??this.client).get({url:"/v2/documents/{document_id}/permissions",...$})}editProjectV2($){return($.client??this.client).patch({url:"/v2/projects/{id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}streamEvents($){return($.client??this.client).sse.get({url:"/webhook/events/stream",...$})}listWebhooks($){return($?.client??this.client).get({url:"/webhook/webhooks",...$})}createWebhook($){return($.client??this.client).post({url:"/webhook/webhooks",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteWebhook($){return($.client??this.client).delete({url:"/webhook/webhooks/{webhook_id}",...$})}getWebhook($){return($.client??this.client).get({url:"/webhook/webhooks/{webhook_id}",...$})}patchWebhook($){return($.client??this.client).patch({url:"/webhook/webhooks/{webhook_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}validateWebhook($){return($.client??this.client).post({url:"/webhook/webhooks/{webhook_id}/validate",...$})}whatsappAccount($){return($?.client??this.client).get({url:"/whatsapp/account",...$})}whatsappChats($){return($?.client??this.client).get({url:"/whatsapp/chats",...$})}whatsappConnect($){return($.client??this.client).post({url:"/whatsapp/connect",...$,headers:{"Content-Type":"application/json",...$.headers}})}whatsappDisconnect($){return($.client??this.client).post({url:"/whatsapp/disconnect",...$,headers:{"Content-Type":"application/json",...$.headers}})}whatsappImportHistory($){return($?.client??this.client).post({url:"/whatsapp/history-import",...$})}whatsappStartLookup($){return($.client??this.client).post({url:"/whatsapp/lookups",...$,headers:{"Content-Type":"application/json",...$.headers}})}whatsappLookup($){return($.client??this.client).get({url:"/whatsapp/lookups/{id}",...$})}whatsappCancelPairing($){return($.client??this.client).delete({url:"/whatsapp/pairing/{id}",...$})}whatsappPairing($){return($.client??this.client).get({url:"/whatsapp/pairing/{id}",...$})}whatsappPasskey($){return($.client??this.client).post({url:"/whatsapp/pairing/{id}/passkey",...$,headers:{"Content-Type":"application/json",...$.headers}})}}function C7({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Q,url:L,...G}){let J,I=Q??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,H=G.signal??new AbortController().signal;while(!0){if(H.aborted)break;B++;let P=G.headers instanceof Headers?G.headers:new Headers(G.headers);if(J!==void 0)P.set("Last-Event-ID",J);try{let D={redirect:"follow",...G,body:G.serializedBody,headers:P,signal:H},_=new Request(L,D);if($)_=await $(L,D);let N=await(G.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let T=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{T.cancel()}catch{}};H.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await T.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,``);let y=U.split(``);U=y.pop()??"";for(let a of y){let i=a.split(`-`),F=[],v;for(let R of i)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))v=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let m=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(m))V=m}let M,h=!1;if(F.length){let R=F.join(`-`);try{M=JSON.parse(R),h=!0}catch{M=R}}if(h){if(S)await S(M);if(x)M=await x(M)}if(j?.({data:M,event:v,id:J,retry:V}),F.length)yield M}}}finally{H.removeEventListener("abort",g),T.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var F9=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},E9=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},q9=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},y0=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((Y)=>encodeURIComponent(Y))).join(E9(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=F9(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)}`},v0=({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(([G,J])=>{Y=[...Y,G,$?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=q9(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 w9=/\{[^{}]+\}/g,f9=({path:$,url:O})=>{let j=O,x=O.match(w9);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,y0({explode:K,name:Z,style:X,value:Y}));continue}if(typeof Y==="object"){j=j.replace(S,v0({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},M7=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=f9({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 C7=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 A7={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var P7=({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=y0({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=v0({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("&")}},F7=($)=>{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},b9=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function E7($){for(let O of $.security??[]){if(b9($,O.name))continue;let j=await C7(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=($)=>M7({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:P7($.querySerializer),url:$.url}),m1=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=m0($.headers,O.headers),j},k9=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},m0=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?k9(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 h0{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 q7=()=>({error:new h0,request:new h0,response:new h0}),g9=P7({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),y9={"Content-Type":"application/json"},Wj=($={})=>({...A7,headers:y9,parseAs:"auto",querySerializer:g9,...$});var u1=($={})=>{let O=m1(Wj(),$),j=()=>({...O}),x=(G)=>{return O=m1(O,G),j()},S=q7(),K=async(G)=>{let J={...O,...G,fetch:G.fetch??O.fetch??globalThis.fetch,headers:m0(O.headers,G.headers),serializedBody:void 0};if(J.security)await E7(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(G)=>{let J=G.throwOnError??O.throwOnError,I=G.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(G),H={redirect:"follow",...V,body:v1(V)};z=new Request(B,H);for(let N of S.request.fns)if(N)z=await N(z,V);let P=V.fetch;W=await P(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?F7(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let T;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":T=await W[N]();break;case"json":{let U=await W.text();T=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(T);if(V.responseTransformer)T=await V.responseTransformer(T)}return V.responseStyle==="data"?T:{data:T,...D}}let _=await W.text(),q;try{q=JSON.parse(_)}catch{}throw q??_}catch(V){let B=V;for(let H of S.error.fns)if(H)B=await H(B,W,z,G);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(G)=>(J)=>Z({...J,method:G}),Y=(G)=>async(J)=>{let{opts:I,url:z}=await K(J);return _7({...I,body:I.body,method:G,onRequest:async(W,V)=>{let B=new Request(W,V);for(let H of S.request.fns)if(H)B=await H(B,I);return B},serializedBody:v1(I),url:z})};return{buildUrl:(G)=>h1({...O,...G}),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 w7=u1(Wj());class f7{client;constructor($){this.client=$?.client??w7}}class b7{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 u0 extends f7{static __registry=new b7;constructor($){super($);u0.__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 k7={dev:"https://dev.macro.com",prod:"https://macro.com",local:"http://localhost:3000"},c1={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 v9($,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 q$($,O){return{session:d.byId($,O.session_id),owner:C.byId($,O.owner_id),...v9($,O.origin)}}function hO($,O,j){let x=O.origin?.channel_id;return x&&j?o.byId($,x,j):void 0}function mO($,O){return O?C.byId($,O):void 0}function g7($,O){return k(O).with({event_type:"agent_session.opened"},({metadata:j})=>({event_type:"agent_session.opened",metadata:j,...q$($,j.identity)})).with({event_type:"agent_session.turn_started"},({metadata:j})=>({event_type:"agent_session.turn_started",metadata:j,...q$($,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,...q$($,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,...q$($,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,...q$($,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,...q$($,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,...q$($,j.identity)})).with({event_type:"agent_session.mentioned"},({metadata:j})=>({event_type:"agent_session.mentioned",metadata:j,...q$($,j.identity),mentionedBy:mO($,j.mentioned_by),mentioned:j.mentioned.map((x)=>C.byId($,x))})).with({event_type:"agent_session.stopped"},({metadata:j})=>({event_type:"agent_session.stopped",metadata:j,...q$($,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,...q$($,j.identity)})).with({event_type:"agent_session.deleted"},({metadata:j})=>({event_type:"agent_session.deleted",metadata:j,...q$($,j.identity)})).exhaustive((j)=>{console.warn("macro sdk: unknown agent session event",j);return})}var y7="macro|";function C$($,O){return O.startsWith(y7)&&O.length>y7.length?C.byId($,O.toLowerCase()):void 0}function v7($,O){return k(O).with({event_type:"channel.created"},({metadata:j})=>({event_type:"channel.created",metadata:j,channel:b.byId($,j.channel_id),actor:C$($,j.actor),participants:j.participant_user_ids.map((x)=>C.byId($,x))})).with({event_type:"channel.updated"},({metadata:j})=>({event_type:"channel.updated",metadata:j,channel:b.byId($,j.channel_id),actor:C$($,j.actor)})).with({event_type:"channel.deleted"},({metadata:j})=>({event_type:"channel.deleted",metadata:j,channel:b.byId($,j.channel_id),actor:C$($,j.actor)})).with({event_type:"channel.picture_changed"},({metadata:j})=>({event_type:"channel.picture_changed",metadata:j,channel:b.byId($,j.channel_id),actor:C$($,j.actor)})).with({event_type:"channel.participant_added"},({metadata:j})=>({event_type:"channel.participant_added",metadata:j,channel:b.byId($,j.channel_id),addedBy:C$($,j.added_by),addedUsers:j.added_user_ids.map((x)=>C.byId($,x))})).with({event_type:"channel.participant_removed"},({metadata:j})=>({event_type:"channel.participant_removed",metadata:j,channel:b.byId($,j.channel_id),removedBy:C.byId($,j.removed_by),removedUsers:j.removed_user_ids.map((x)=>C.byId($,x))})).exhaustive((j)=>{console.warn("macro sdk: unknown channel event",j);return})}function h7($,O){return k(O).with({event_type:"document.created"},({metadata:j})=>({event_type:"document.created",metadata:j,document:w.byId($,j.document_id),owner:C.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:C.byId($,j.owner),actor:j.actor_user_id?C.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?C.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:C.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:C.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 uO($,O,j=[]){let x=O.parent;if(x.type==="call")return{type:"call",call:J$.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:o.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:l$.byId($,x.id,O.message_id),threadId:O.root_id}}function m7($,O){return k(O).with({event_type:"message.posted"},({metadata:j})=>({event_type:"message.posted",metadata:j,target:uO($,j,j.mentions),sender:C$($,j.sender)})).with({event_type:"message.mentioned"},({metadata:j})=>({event_type:"message.mentioned",metadata:j,target:uO($,j),sender:C$($,j.sender)})).with({event_type:"message.patched"},({metadata:j})=>({event_type:"message.patched",metadata:j,target:uO($,j),actor:C$($,j.actor)})).with({event_type:"message.deleted"},({metadata:j})=>({event_type:"message.deleted",metadata:j,target:uO($,j),actor:C$($,j.actor)})).with({event_type:"message.attachment_created"},({metadata:j})=>({event_type:"message.attachment_created",metadata:j,target:uO($,j),actor:C$($,j.actor)})).with({event_type:"message.attachment_removed"},({metadata:j})=>({event_type:"message.attachment_removed",metadata:j,target:uO($,j),actor:C$($,j.actor)})).exhaustive((j)=>{console.warn("macro sdk: unknown message event",j);return})}async function u7($){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 h9="webhook.validation.test";function m9($,O){return k(O).with({event_type:t.string.startsWith("document.")},(j)=>h7($,j)).with({event_type:t.string.startsWith("channel.")},(j)=>v7($,j)).with({event_type:t.string.startsWith("message.")},(j)=>m7($,j)).with({event_type:t.string.startsWith("agent_session.")},(j)=>g7($,j)).otherwise(()=>{return})}class d1{client;secret;handlers=new Map;constructor($,O){this.client=$;this.secret=O}on($,O){let j=this.handlers.get($)??new Set;return j.add(O),this.handlers.set($,j),()=>j.delete(O)}onSelfMention($){return this.on("message.mentioned",async(O)=>{if(O.metadata.mentioned.entity_id.toLowerCase()!==(await this.client.myPrincipalId()).toLowerCase())return;await $(O)})}async listen($={}){let O=$.filters??this.filtersFromHandlers();if(O.length===0||O.every((K)=>K.events.length===0))throw new f("listen() needs filters — pass filters or register handlers with .on() first");let j=new AbortController;if($.signal)if($.signal.aborted)j.abort();else $.signal.addEventListener("abort",()=>j.abort(),{once:!0});let{stream:x}=await this.client.storage.streamEvents({query:{scope:$.scope??"user",filters:JSON.stringify(O)},signal:j.signal});return(async()=>{try{for await(let K of x)await this.dispatchEvent(K)}catch{if(j.signal.aborted)return;throw new f("event stream failed")}})().catch(()=>{}),()=>{j.abort()}}async handle($,O){if(!this.secret)throw new f("webhookSecret is required to verify incoming webhook deliveries");if(!await u7({secret:this.secret,timestamp:O.timestamp??"",rawBody:$,signature:O.signature??""}))throw new f("invalid webhook signature");if(O.event===h9)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=m9(this.client,j);if(!S)return;await Promise.all([...x].map((K)=>K(S)))}}function c7(){return}var u9=0,l1;function c9($){l1=$}function I$($,O,j){if(!j&&!l1)return $;let x=(S)=>{for(let K of[l1,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:++u9,service:O,operation:K};x({...L,status:"started"});try{let G=await Reflect.apply(X,S,Y),J=G!==null&&typeof G==="object"&&"error"in G&&G.error!=null;return x({...L,status:J?"failed":"completed"}),G}catch(G){throw x({...L,status:"failed"}),G}}}})}var l7="x-macro-user-api-key",d9="mak_",r1="mbot_";function l9($){return k($).with(t.string.startsWith(r1),()=>{throw Error("bot token passed as a user credential. Use auth: { type: 'bot', token } or MACRO_BOT_TOKEN.")}).with(t.string.startsWith(d9),(O)=>[l7,O]).otherwise((O)=>["Authorization",`Bearer ${O}`])}async function d7($){return typeof $==="function"?await $():$}async function r9($,O,j){return k($).with({type:"bot"},async(x)=>{let S=await d7(x.token);if(!S.startsWith(r1))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:t.string},({apiKey:x})=>{if(x.startsWith(r1))throw Error("bot token passed as a user credential. Use auth: { type: 'bot', token } or MACRO_BOT_TOKEN.");return[[l7,x]]}).with({type:"user"},async({token:x})=>{return[l9(await d7(x))]}).exhaustive()}class p1{scheduledAction;unfurl;agentHarness;auth;calendar;cognition;contacts;email;notification;properties;search;storage;webAppUrl;wsVerify;events;authConfig;hosts;localPortmap;requestedAs;selfBotRecord;selfPrincipal;constructor($){let O=p9($),j=O==="local"?c7():void 0,x={...c1[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??k7[O],this.authConfig=a9($),this.requestedAs=$.requestedAs,this.requestedAs&&this.authConfig.type!=="bot")throw Error("requestedAs() requires bot auth — a user token always acts as its own user");this.wsVerify=$.wsVerify,this.scheduledAction=I$(new C0({client:this.makeClient(x["scheduled-action"])}),"scheduled-action",$.onRequest),this.unfurl=I$(new u0({client:this.makeClient(x.unfurl)}),"unfurl",$.onRequest),this.agentHarness=I$(new mj({client:this.makeClient(x["agent-harness"])}),"agent-harness",$.onRequest),this.auth=I$(new rj({client:this.makeClient(x.auth)}),"auth",$.onRequest),this.calendar=I$(new sj({client:this.makeClient(x.calendar)}),"calendar",$.onRequest),this.cognition=I$(new O0({client:this.makeClient(x.cognition)}),"cognition",$.onRequest),this.contacts=I$(new X0({client:this.makeClient(x.contacts)}),"contacts",$.onRequest),this.email=I$(new J0({client:this.makeClient(x.email)}),"email",$.onRequest),this.notification=I$(new N0({client:this.makeClient(x.notification)}),"notification",$.onRequest),this.properties=I$(new T0({client:this.makeClient(x.properties)}),"properties",$.onRequest),this.search=I$(new q0({client:this.makeClient(x.search)}),"search",$.onRequest),this.storage=I$(new g0({client:this.makeClient(x.storage)}),"storage",$.onRequest);let K=typeof process<"u"?{}.MACRO_WEBHOOK_SECRET:void 0,Z=$.webhookSecret??K;this.events=new d1(this,Z)}hasActingUser(){return this.authConfig.type==="user"||this.requestedAs!==void 0}selfBot(){return this.selfBotRecord??=new aO(this).me().catch(($)=>{throw this.selfBotRecord=void 0,$}),this.selfBotRecord}myPrincipalId(){return this.selfPrincipal??=(this.authConfig.type==="bot"?this.selfBot().then(($)=>`bot|${$.id}`):C.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 r9(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 p9($){if($.env)return $.env;let O=typeof process<"u"?{}.MACRO_ENV:void 0;if(!O)return"prod";if(!(O in c1))throw Error(`invalid MACRO_ENV "${O}" — expected local, dev, or prod`);return O}function a9($){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 a1{id;constructor($){this.id=$}static byId($){return new a1($)}toJSON(){return{id:this.id}}}class r7{routines;unfurls;agents;initiatives;apiKeys;harnesses;meetings;githubPullRequests;entityMentions;agentSessions;ai;bots;calendar;calls;channels;externalChats;whatsapp;chats;crm;databases;documents;email;favorites;foreignEntities;forms;images;notifications;pins;projects;properties;referrals;tasks;teams;users;webhooks;workspace;events;webAppUrl;_client;opts;constructor($){this.opts=$;let O=new p1($);this._client=O,this.routines=new gx(O),this.unfurls=new hx(O),this.agents=new e0(O),this.initiatives=new Ax(O),this.apiKeys=new $x(O),this.harnesses=new Mx(O),this.meetings=new Px(O),this.githubPullRequests=new _x(O),this.entityMentions=new Ux(O),this.agentSessions=new t0(O),this.ai=new o0(O),this.bots=new aO(O),this.calendar=new Ox(O),this.calls=new jx(O),this.channels=new Sx(O),this.externalChats=new Ix(O),this.whatsapp=new cx(O),this.chats=new Zx(O),this.crm=new Kx(O),this.databases=new Wx(O),this.documents=new Bx(O),this.email=new Nx(O),this.favorites=new Hx(O),this.foreignEntities=new Tx(O),this.forms=new Rx(O),this.images=new Cx(O),this.notifications=new Fx(O),this.pins=new Ex(O),this.projects=new qx(O),this.properties=new wx(O),this.referrals=new fx(O),this.tasks=new yx(O),this.teams=new vx(O),this.users=new mx(O),this.webhooks=new ux(O),this.workspace=new px(O),this.events=O.events,this.webAppUrl=O.webAppUrl}myPrincipalId(){return this._client.myPrincipalId()}requestedAs($){return new r7({...this.opts,requestedAs:$.id})}}export{o$ as wrapXml,O$ as toBody,c9 as observeRequests,G5 as msg,Q5 as here,NO as WhatsAppChat,CO as WhatsAppAccount,OO as UserApiKey,pO as ToolApproval,HO as TeamInvite,qj as StaticImage,N$ as SessionReview,kx as RoutineExecution,v$ as Routine,s0 as ReviewItem,Dx as PullRequestChangeset,Rj as PipelineView,Tj as PipelineTable,JO as PipelineRow,Dj as PipelineColumn,L$ as MessageThread,D$ as Meeting,Vx as MacroOpRefusedError,r7 as Macro,a$ as Initiative,_O as HarnessPairing,B$ as Harness,DO as GithubPullRequest,wj as GeneratedImage,p$ as FormSection,RO as FormResponse,Ej as FormReference,r$ as FormQuestion,UO as FormOption,y$ as Form,ZO as ExternalChatUpload,XO as ExternalChatSend,SO as ExternalChatParticipant,M$ as ExternalChatMessage,g$ as ExternalChat,TO as EntityMention,$$ as EntityAccess,LO as EmailFilter,BO as EmailDraft,oO as DraftAttachment,eO as DocumentVersion,VO as DocumentAnchor,$j as DevicePairing,jO as CrmPipeline,i0 as ConversationTurn,rO as CodeExecution,sO as ChatMessage,nO as ChatGeneration,a1 as ChannelPicture,GO as ChannelActivity,Uj as AgentConversation,T$ as Agent,IO as AccessRequest};+`),F=[],v;for(let R of i)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))v=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let m=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(m))V=m}let C,h=!1;if(F.length){let R=F.join(`+`);try{C=JSON.parse(R),h=!0}catch{C=R}}if(h){if(S)await S(C);if(x)C=await x(C)}if(j?.({data:C,event:v,id:J,retry:V}),F.length)yield C}}}finally{H.removeEventListener("abort",g),T.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var q9=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},w9=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},f9=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},v0=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((Q)=>encodeURIComponent(Q))).join(w9(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=q9(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return hO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},hO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},h0=({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 Q=[];Object.entries(S).forEach(([G,J])=>{Q=[...Q,G,$?J:encodeURIComponent(J)]});let L=Q.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=f9(x),X=Object.entries(S).map(([Q,L])=>hO({allowReserved:$,name:x==="deepObject"?`${j}[${Q}]`:Q,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var b9=/\{[^{}]+\}/g,k9=({path:$,url:O})=>{let j=O,x=O.match(b9);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 Q=$[Z];if(Q===void 0||Q===null)continue;if(Array.isArray(Q)){j=j.replace(S,v0({explode:K,name:Z,style:X,value:Q}));continue}if(typeof Q==="object"){j=j.replace(S,h0({explode:K,name:Z,style:X,value:Q,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${hO({name:Z,value:Q})}`);continue}let L=encodeURIComponent(X==="label"?`.${Q}`:Q);j=j.replace(S,L)}return j},M7=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=k9({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function h1($){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 A7=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 P7={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var F7=({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 Q=v0({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(Q)S.push(Q)}else if(typeof Z==="object"){let Q=h0({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(Q)S.push(Q)}else{let Q=hO({allowReserved:X.allowReserved,name:K,value:Z});if(Q)S.push(Q)}}return S.join("&")}},E7=($)=>{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},g9=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function q7($){for(let O of $.security??[]){if(g9($,O.name))continue;let j=await A7(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 m1=($)=>M7({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:F7($.querySerializer),url:$.url}),u1=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=u0($.headers,O.headers),j},y9=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},u0=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?y9(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 m0{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 w7=()=>({error:new m0,request:new m0,response:new m0}),v9=F7({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),h9={"Content-Type":"application/json"},Bj=($={})=>({...P7,headers:h9,parseAs:"auto",querySerializer:v9,...$});var c1=($={})=>{let O=u1(Bj(),$),j=()=>({...O}),x=(G)=>{return O=u1(O,G),j()},S=w7(),K=async(G)=>{let J={...O,...G,fetch:G.fetch??O.fetch??globalThis.fetch,headers:u0(O.headers,G.headers),serializedBody:void 0};if(J.security)await q7(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=m1(I);return{opts:I,url:z}},Z=async(G)=>{let J=G.throwOnError??O.throwOnError,I=G.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(G),H={redirect:"follow",...V,body:h1(V)};z=new Request(B,H);for(let N of S.request.fns)if(N)z=await N(z,V);let P=V.fetch;W=await P(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?E7(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let T;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":T=await W[N]();break;case"json":{let U=await W.text();T=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(T);if(V.responseTransformer)T=await V.responseTransformer(T)}return V.responseStyle==="data"?T:{data:T,...D}}let _=await W.text(),q;try{q=JSON.parse(_)}catch{}throw q??_}catch(V){let B=V;for(let H of S.error.fns)if(H)B=await H(B,W,z,G);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(G)=>(J)=>Z({...J,method:G}),Q=(G)=>async(J)=>{let{opts:I,url:z}=await K(J);return C7({...I,body:I.body,method:G,onRequest:async(W,V)=>{let B=new Request(W,V);for(let H of S.request.fns)if(H)B=await H(B,I);return B},serializedBody:h1(I),url:z})};return{buildUrl:(G)=>m1({...O,...G}),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:Q("CONNECT"),delete:Q("DELETE"),get:Q("GET"),head:Q("HEAD"),options:Q("OPTIONS"),patch:Q("PATCH"),post:Q("POST"),put:Q("PUT"),trace:Q("TRACE")},trace:X("TRACE")}};var f7=c1(Bj());class b7{client;constructor($){this.client=$?.client??f7}}class k7{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 c0 extends b7{static __registry=new k7;constructor($){super($);c0.__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 g7={dev:"https://dev.macro.com",prod:"https://macro.com",local:"http://localhost:3000"},d1={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 m9($,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 q$($,O){return{session:d.byId($,O.session_id),owner:M.byId($,O.owner_id),...m9($,O.origin)}}function mO($,O,j){let x=O.origin?.channel_id;return x&&j?o.byId($,x,j):void 0}function uO($,O){return O?M.byId($,O):void 0}function y7($,O){return k(O).with({event_type:"agent_session.opened"},({metadata:j})=>({event_type:"agent_session.opened",metadata:j,...q$($,j.identity)})).with({event_type:"agent_session.turn_started"},({metadata:j})=>({event_type:"agent_session.turn_started",metadata:j,...q$($,j.identity),actor:uO($,j.actor),announcement:mO($,j.identity,j.announcement_message_id)})).with({event_type:"agent_session.turn_ended"},({metadata:j})=>({event_type:"agent_session.turn_ended",metadata:j,...q$($,j.identity),actor:uO($,j.actor),announcement:mO($,j.identity,j.announcement_message_id)})).with({event_type:"agent_session.command_rejected"},({metadata:j})=>({event_type:"agent_session.command_rejected",metadata:j,...q$($,j.identity),actor:uO($,j.actor),announcement:mO($,j.identity,j.announcement_message_id)})).with({event_type:"agent_session.settled"},({metadata:j})=>({event_type:"agent_session.settled",metadata:j,...q$($,j.identity),actor:uO($,j.last_turn?.actor),announcement:mO($,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,...q$($,j.identity),announcement:mO($,j.identity,j.announcement_message_id)})).with({event_type:"agent_session.input_received"},({metadata:j})=>({event_type:"agent_session.input_received",metadata:j,...q$($,j.identity)})).with({event_type:"agent_session.mentioned"},({metadata:j})=>({event_type:"agent_session.mentioned",metadata:j,...q$($,j.identity),mentionedBy:uO($,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,...q$($,j.identity),actor:uO($,j.turn_in_flight?.actor),announcement:mO($,j.identity,j.turn_in_flight?.announcement_message_id)})).with({event_type:"agent_session.renamed"},({metadata:j})=>({event_type:"agent_session.renamed",metadata:j,...q$($,j.identity)})).with({event_type:"agent_session.deleted"},({metadata:j})=>({event_type:"agent_session.deleted",metadata:j,...q$($,j.identity)})).exhaustive((j)=>{console.warn("macro sdk: unknown agent session event",j);return})}var v7="macro|";function M$($,O){return O.startsWith(v7)&&O.length>v7.length?M.byId($,O.toLowerCase()):void 0}function h7($,O){return k(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 m7($,O){return k(O).with({event_type:"document.created"},({metadata:j})=>({event_type:"document.created",metadata:j,document:f.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:f.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:f.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:f.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:f.byId($,j.document_id)})).with({event_type:"document.purged"},({metadata:j})=>({event_type:"document.purged",metadata:j,document:f.byId($,j.document_id)})).with({event_type:"document.copied"},({metadata:j})=>({event_type:"document.copied",metadata:j,document:f.byId($,j.document_id),sourceDocument:f.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:f.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:J$.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:o.byId($,x.id,O.message_id,j),thread:O.thread_id?new h$($,x.id,O.thread_id):void 0};return{type:"document",document:f.byId($,x.id),comment:l$.byId($,x.id,O.message_id),threadId:O.root_id}}function u7($,O){return k(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 c7($){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 u9="webhook.validation.test";function c9($,O){return k(O).with({event_type:t.string.startsWith("document.")},(j)=>m7($,j)).with({event_type:t.string.startsWith("channel.")},(j)=>h7($,j)).with({event_type:t.string.startsWith("message.")},(j)=>u7($,j)).with({event_type:t.string.startsWith("agent_session.")},(j)=>y7($,j)).otherwise(()=>{return})}class l1{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 w("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 w("event stream failed")}})().catch(()=>{}),()=>{j.abort()}}async handle($,O){if(!this.secret)throw new w("webhookSecret is required to verify incoming webhook deliveries");if(!await c7({secret:this.secret,timestamp:O.timestamp??"",rawBody:$,signature:O.signature??""}))throw new w("invalid webhook signature");if(O.event===u9)return;await this.dispatchEvent(JSON.parse($))}webhook(){if(!this.secret)throw new w("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=c9(this.client,j);if(!S)return;await Promise.all([...x].map((K)=>K(S)))}}function d7(){return}var d9=0,r1;function l9($){r1=$}function I$($,O,j){if(!j&&!r1)return $;let x=(S)=>{for(let K of[r1,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(...Q)=>{let L={id:++d9,service:O,operation:K};x({...L,status:"started"});try{let G=await Reflect.apply(X,S,Q),J=G!==null&&typeof G==="object"&&"error"in G&&G.error!=null;return x({...L,status:J?"failed":"completed"}),G}catch(G){throw x({...L,status:"failed"}),G}}}})}var r7="x-macro-user-api-key",r9="mak_",p1="mbot_";function p9($){return k($).with(t.string.startsWith(p1),()=>{throw Error("bot token passed as a user credential. Use auth: { type: 'bot', token } or MACRO_BOT_TOKEN.")}).with(t.string.startsWith(r9),(O)=>[r7,O]).otherwise((O)=>["Authorization",`Bearer ${O}`])}async function l7($){return typeof $==="function"?await $():$}async function a9($,O,j){return k($).with({type:"bot"},async(x)=>{let S=await l7(x.token);if(!S.startsWith(p1))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:t.string},({apiKey:x})=>{if(x.startsWith(p1))throw Error("bot token passed as a user credential. Use auth: { type: 'bot', token } or MACRO_BOT_TOKEN.");return[[r7,x]]}).with({type:"user"},async({token:x})=>{return[p9(await l7(x))]}).exhaustive()}class a1{scheduledAction;unfurl;agentHarness;auth;calendar;cognition;contacts;email;notification;properties;search;storage;webAppUrl;wsVerify;events;authConfig;hosts;localPortmap;requestedAs;selfBotRecord;selfPrincipal;constructor($){let O=i9($),j=O==="local"?d7():void 0,x={...d1[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??g7[O],this.authConfig=n9($),this.requestedAs=$.requestedAs,this.requestedAs&&this.authConfig.type!=="bot")throw Error("requestedAs() requires bot auth — a user token always acts as its own user");this.wsVerify=$.wsVerify,this.scheduledAction=I$(new A0({client:this.makeClient(x["scheduled-action"])}),"scheduled-action",$.onRequest),this.unfurl=I$(new c0({client:this.makeClient(x.unfurl)}),"unfurl",$.onRequest),this.agentHarness=I$(new uj({client:this.makeClient(x["agent-harness"])}),"agent-harness",$.onRequest),this.auth=I$(new pj({client:this.makeClient(x.auth)}),"auth",$.onRequest),this.calendar=I$(new tj({client:this.makeClient(x.calendar)}),"calendar",$.onRequest),this.cognition=I$(new j0({client:this.makeClient(x.cognition)}),"cognition",$.onRequest),this.contacts=I$(new K0({client:this.makeClient(x.contacts)}),"contacts",$.onRequest),this.email=I$(new V0({client:this.makeClient(x.email)}),"email",$.onRequest),this.notification=I$(new U0({client:this.makeClient(x.notification)}),"notification",$.onRequest),this.properties=I$(new R0({client:this.makeClient(x.properties)}),"properties",$.onRequest),this.search=I$(new w0({client:this.makeClient(x.search)}),"search",$.onRequest),this.storage=I$(new y0({client:this.makeClient(x.storage)}),"storage",$.onRequest);let K=typeof process<"u"?{}.MACRO_WEBHOOK_SECRET:void 0,Z=$.webhookSecret??K;this.events=new l1(this,Z)}hasActingUser(){return this.authConfig.type==="user"||this.requestedAs!==void 0}selfBot(){return this.selfBotRecord??=new iO(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=Wj({baseUrl:$});return O.interceptors.request.use(async(j)=>{let x=await a9(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 i9($){if($.env)return $.env;let O=typeof process<"u"?{}.MACRO_ENV:void 0;if(!O)return"prod";if(!(O in d1))throw Error(`invalid MACRO_ENV "${O}" — expected local, dev, or prod`);return O}function n9($){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 i1{id;constructor($){this.id=$}static byId($){return new i1($)}toJSON(){return{id:this.id}}}class p7{routines;unfurls;agents;initiatives;apiKeys;harnesses;meetings;githubPullRequests;entityMentions;agentSessions;ai;bots;calendar;calls;channels;externalChats;whatsapp;chats;crm;databases;documents;email;favorites;foreignEntities;forms;images;me;notifications;pins;projects;properties;referrals;tasks;teams;users;webhooks;workspace;events;webAppUrl;_client;opts;constructor($){this.opts=$;let O=new a1($);this._client=O,this.routines=new yx(O),this.unfurls=new mx(O),this.agents=new o0(O),this.initiatives=new Px(O),this.apiKeys=new Ox(O),this.me=new fj(O),this.harnesses=new Mx(O),this.meetings=new Fx(O),this.githubPullRequests=new Cx(O),this.entityMentions=new zx(O),this.agentSessions=new e0(O),this.ai=new $x(O),this.bots=new iO(O),this.calendar=new jx(O),this.calls=new xx(O),this.channels=new Zx(O),this.externalChats=new Hx(O),this.whatsapp=new dx(O),this.chats=new Xx(O),this.crm=new Qx(O),this.databases=new Bx(O),this.documents=new Lx(O),this.email=new Ux(O),this.favorites=new Tx(O),this.foreignEntities=new Rx(O),this.forms=new Dx(O),this.images=new Ax(O),this.notifications=new Ex(O),this.pins=new qx(O),this.projects=new wx(O),this.properties=new fx(O),this.referrals=new bx(O),this.tasks=new vx(O),this.teams=new hx(O),this.users=new ux(O),this.webhooks=new cx(O),this.workspace=new ax(O),this.events=O.events,this.webAppUrl=O.webAppUrl}myPrincipalId(){return this._client.myPrincipalId()}requestedAs($){return new p7({...this.opts,requestedAs:$.id})}}export{o$ as wrapXml,O$ as toBody,l9 as observeRequests,J5 as msg,G5 as here,NO as WhatsAppChat,AO as WhatsAppAccount,OO as UserApiKey,aO as ToolApproval,HO as TeamInvite,CO as StaticImage,N$ as SessionReview,gx as RoutineExecution,v$ as Routine,t0 as ReviewItem,_x as PullRequestChangeset,Dj as PipelineView,Rj as PipelineTable,JO as PipelineRow,_j as PipelineColumn,L$ as MessageThread,D$ as Meeting,fj as MeNamespace,Wx as MacroOpRefusedError,p7 as Macro,a$ as Initiative,_O as HarnessPairing,B$ as Harness,DO as GithubPullRequest,wj as GeneratedImage,p$ as FormSection,RO as FormResponse,qj as FormReference,r$ as FormQuestion,UO as FormOption,y$ as Form,ZO as ExternalChatUpload,XO as ExternalChatSend,SO as ExternalChatParticipant,C$ as ExternalChatMessage,g$ as ExternalChat,TO as EntityMention,$$ as EntityAccess,LO as EmailFilter,BO as EmailDraft,$j as DraftAttachment,oO as DocumentVersion,VO as DocumentAnchor,Oj as DevicePairing,jO as CrmPipeline,n0 as ConversationTurn,pO as CodeExecution,tO as ChatMessage,sO as ChatGeneration,i1 as ChannelPicture,GO as ChannelActivity,zj as AgentConversation,T$ as Agent,IO as AccessRequest};diff --git a/crates/fusionauth/src/user/create.rs b/crates/fusionauth/src/user/create.rsindex 0c7e4121fc..d1fd09648f 100644--- a/crates/fusionauth/src/user/create.rs+++ b/crates/fusionauth/src/user/create.rs@@ -14,6 +14,9 @@ pub struct User<'a> {pub password: Cow<'a, str>,/// The username of the user.pub username: Option<Cow<'a, str>>,+ /// Metadata FusionAuth stores on the user and repeats in its webhooks.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub data: Option<serde_json::Value>,}#[derive(serde::Serialize, serde::Deserialize, Debug)]diff --git a/crates/fusionauth/src/user/test.rs b/crates/fusionauth/src/user/test.rsindex 3acf6a07a5..7ddd15c5f7 100644--- a/crates/fusionauth/src/user/test.rs+++ b/crates/fusionauth/src/user/test.rs@@ -20,6 +20,7 @@ fn client(base_url: String) -> FusionAuthClient {fn user() -> create::User<'static> {create::User {+ data: None,email: Cow::Borrowed("[email protected]"),password: Cow::Borrowed("unused-password"),username: None,diff --git a/crates/invite_email/src/lib.rs b/crates/invite_email/src/lib.rsindex fb41a39420..8365c4fc63 100644--- a/crates/invite_email/src/lib.rs+++ b/crates/invite_email/src/lib.rs@@ -312,6 +312,10 @@ pub struct InviteToTeamMetadata {/// Whether this email reminds the invitee of an invite they have not answered.#[serde(default)]pub reminder: bool,++ /// Whether the invite creates an agent account.+ #[serde(default)]+ pub is_agent: bool,}/// What a team invitee gets by joining.diff --git a/crates/invite_email/src/test.rs b/crates/invite_email/src/test.rsindex b94a022f88..744bc082db 100644--- a/crates/invite_email/src/test.rs+++ b/crates/invite_email/src/test.rs@@ -132,6 +132,7 @@ fn team_invite_rate_limit_key_is_per_invite() {sender_profile_picture_url: None,invitee_plan: InviteePlan::Free,reminder: false,+ is_agent: false,};let to_carol = InviteToTeamMetadata {team_invite_id: Uuid::from_u128(11),@@ -320,6 +321,7 @@ fn invitation_logos_keep_the_png_aspect_ratio() {sender_profile_picture_url: None,invitee_plan: InviteePlan::Free,reminder: false,+ is_agent: false,};for email in [make_invite().format_email(),@@ -477,6 +479,7 @@ fn make_team_invite(invitee_plan: InviteePlan) -> InviteToTeamMetadata {sender_profile_picture_url: None,invitee_plan,reminder: false,+ is_agent: false,}}@@ -587,6 +590,7 @@ fn team_invite_sent_before_plans_were_recorded_reads_as_free() {fn team_invite_reminder_says_so_in_the_subject() {let reminder = InviteToTeamMetadata {reminder: true,+ is_agent: false,..make_team_invite(InviteePlan::Free)};assert_eq!(diff --git a/crates/invite_email/templates/invite_to_team.html b/crates/invite_email/templates/invite_to_team.htmlindex ab2431673f..7f5e93c023 100644--- a/crates/invite_email/templates/invite_to_team.html+++ b/crates/invite_email/templates/invite_to_team.html@@ -175,6 +175,23 @@Macro brings your documents, tasks, and conversationstogether in one place.</p>+ {% if is_agent %}+ <p+ style="+ margin: 0 0 24px;+ font-size: 16px;+ line-height: 24px;+ color: #55534e;+ "+ >+ This invite is for an AI agent. Open the link below and sign+ in with this address. Macro shows your SDK token once you+ have verified the emailed code. The SDK guide is at+ <a href="https://sdk.macro.com" style="color: #222222"+ >sdk.macro.com</a+ >.+ </p>+ {% endif %}{% if let Some(r) = role %}<pstyle="diff --git a/crates/macro_db_client/migrations/20261104035905_agent_accounts.sql b/crates/macro_db_client/migrations/20261104035905_agent_accounts.sqlnew file mode 100644index 0000000000..d59f673112--- /dev/null+++ b/crates/macro_db_client/migrations/20261104035905_agent_accounts.sql@@ -0,0 +1,9 @@+-- Agent accounts: set once when the account is created. A pending team invite+-- can ask for one, so the signup that redeems it creates an agent.+SET LOCAL lock_timeout = '5s';++ALTER TABLE "User"+ ADD COLUMN "isAgent" BOOLEAN NOT NULL DEFAULT FALSE;++ALTER TABLE team_invite+ ADD COLUMN is_agent BOOLEAN NOT NULL DEFAULT FALSE;diff --git a/crates/macro_db_client/src/user/create_user.rs b/crates/macro_db_client/src/user/create_user.rsindex c449567bbf..0405a4cabe 100644--- a/crates/macro_db_client/src/user/create_user.rs+++ b/crates/macro_db_client/src/user/create_user.rs@@ -21,6 +21,7 @@ pub async fn create_user(stripe_customer_id: Option<&str>,organization_id: Option<i32>,roles: HashSet<String>,+ is_agent: bool,) -> anyhow::Result<String> {let id = macro_uuid::string_to_uuid(id)?;@@ -60,15 +61,16 @@ pub async fn create_user(let user_id = sqlx::query!(r#"- INSERT INTO "User" ("id", "email", "stripeCustomerId", "organizationId", "macro_user_id")- VALUES ($1, $2, $3, $4, $5)+ INSERT INTO "User" ("id", "email", "stripeCustomerId", "organizationId", "macro_user_id", "isAgent")+ VALUES ($1, $2, $3, $4, $5, $6)RETURNING id"#,&id,email,stripe_customer_id,organization_id,- ¯o_user_id+ ¯o_user_id,+ is_agent).map(|row| row.id).fetch_one(&mut *transaction)@@ -108,8 +110,11 @@ pub async fn create_user_profile(let user_id = sqlx::query!(r#"- INSERT INTO "User" ("id", "email", "organizationId", "macro_user_id")- VALUES ($1, $2, $3, $4)+ INSERT INTO "User" ("id", "email", "organizationId", "macro_user_id", "isAgent")+ VALUES (+ $1, $2, $3, $4,+ COALESCE((SELECT BOOL_OR(u."isAgent") FROM "User" u WHERE u.macro_user_id = $4), FALSE)+ )RETURNING id"#,&user_profile_id,diff --git a/crates/macro_db_client/src/user/create_user/test.rs b/crates/macro_db_client/src/user/create_user/test.rsindex 2fbe83d325..1252d6b03e 100644--- a/crates/macro_db_client/src/user/create_user/test.rs+++ b/crates/macro_db_client/src/user/create_user/test.rs@@ -14,6 +14,7 @@ async fn a_local_placeholder_does_not_become_a_billing_customer(pool: sqlx::PgPoNone,None,HashSet::new(),+ false,).await.unwrap();@@ -40,6 +41,7 @@ async fn a_real_stripe_customer_remains_available_for_billing(pool: sqlx::PgPoolSome(customer_id),None,HashSet::new(),+ false,).await.unwrap();@@ -51,3 +53,42 @@ async fn a_real_stripe_customer_remains_available_for_billing(pool: sqlx::PgPool(user_id, Some(customer_id.to_owned())));}++#[sqlx::test]+async fn a_second_profile_inherits_agent_status(pool: sqlx::PgPool) {+ let macro_user_id = uuid::Uuid::new_v4().to_string();+ let email = "[email protected]";+ create_user(+ &pool,+ ¯o_user_id,+ email,+ email,+ true,+ "cus_agent_profile",+ None,+ None,+ HashSet::new(),+ true,+ )+ .await+ .unwrap();++ let second_email = "[email protected]";+ create_user_profile(&pool, ¯o_user_id, second_email, None, HashSet::new())+ .await+ .unwrap();++ let is_agent = sqlx::query_scalar!(+ r#"SELECT "isAgent" FROM "User" WHERE email = $1"#,+ second_email+ )+ .fetch_one(&pool)+ .await+ .unwrap();+ assert!(is_agent);++ let name = crate::user::get_user_name::get_user_name(&pool, ¯o_user_id)+ .await+ .unwrap();+ assert!(name.is_agent);+}diff --git a/crates/macro_db_client/src/user/get/get_legacy_user_info.rs b/crates/macro_db_client/src/user/get/get_legacy_user_info.rsindex 77f225294e..ae11eb30a0 100644--- a/crates/macro_db_client/src/user/get/get_legacy_user_info.rs+++ b/crates/macro_db_client/src/user/get/get_legacy_user_info.rs@@ -9,6 +9,7 @@ pub struct LegacyUserInfo {pub stripe_customer_id: Option<String>,pub name: Option<String>,pub tutorial_complete: bool,+ pub is_agent: bool,pub group: Option<String>,pub has_chrome_ext: bool,pub ai_data_consent: bool,@@ -35,6 +36,7 @@ pub async fn get_legacy_user_info(u."stripeCustomerId" as "stripe_customer_id?",u."name" as name,u."tutorialComplete" as tutorial_complete,+ u."isAgent" as is_agent,u."group" as "group?",u."hasChromeExt" as has_chrome_ext,u."aiDataConsent" as ai_data_consent,@@ -53,6 +55,7 @@ pub async fn get_legacy_user_info(stripe_customer_id: row.stripe_customer_id,name: row.name,tutorial_complete: row.tutorial_complete,+ is_agent: row.is_agent,group: row.group,has_chrome_ext: row.has_chrome_ext,ai_data_consent: row.ai_data_consent,diff --git a/crates/macro_db_client/src/user/get_user_name.rs b/crates/macro_db_client/src/user/get_user_name.rsindex b74fd5c131..f6f78f1998 100644--- a/crates/macro_db_client/src/user/get_user_name.rs+++ b/crates/macro_db_client/src/user/get_user_name.rs@@ -11,7 +11,15 @@ pub async fn get_user_name(db: &sqlx::PgPool, macro_user_id: &str) -> anyhow::Relet macro_user_id = macro_uuid::string_to_uuid(macro_user_id)?;let name: Option<UserName> = sqlx::query!(r#"- SELECT macro_user_id, first_name, last_name FROM macro_user_info WHERE macro_user_id = $1+ SELECT+ u.macro_user_id,+ mui.first_name as "first_name?",+ mui.last_name as "last_name?",+ BOOL_OR(u."isAgent") as "is_agent!"+ FROM "User" u+ LEFT JOIN macro_user_info mui ON mui.macro_user_id = u.macro_user_id+ WHERE u.macro_user_id = $1+ GROUP BY u.macro_user_id, mui.first_name, mui.last_name"#,¯o_user_id)@@ -19,6 +27,7 @@ pub async fn get_user_name(db: &sqlx::PgPool, macro_user_id: &str) -> anyhow::Reid: row.macro_user_id.to_string(), // TODO: this may mess up FE?first_name: row.first_name,last_name: row.last_name,+ is_agent: row.is_agent,}).fetch_optional(db).await?;@@ -30,6 +39,7 @@ pub async fn get_user_name(db: &sqlx::PgPool, macro_user_id: &str) -> anyhow::Reid: macro_user_id.to_string(),first_name: None,last_name: None,+ is_agent: false,}))}@@ -43,7 +53,8 @@ pub async fn get_user_names(SELECTu.id as user_profile_id,mui.first_name,- mui.last_name+ mui.last_name,+ u."isAgent" as is_agentFROM macro_user_info muiJOIN "User" u ON mui.macro_user_id = u.macro_user_idWHERE u.id = ANY($1)@@ -54,6 +65,7 @@ pub async fn get_user_names(id: row.user_profile_id,first_name: row.first_name,last_name: row.last_name,+ is_agent: row.is_agent,}).fetch_all(db).await?;@@ -93,7 +105,8 @@ pub async fn get_user_names_with_email(THEN NULLIF(TRIM(SUBSTRING(contact.name FROM POSITION(' ' IN contact.name) + 1)), '')ELSE NULLEND- END as "last_name"+ END as "last_name",+ COALESCE(u."isAgent", FALSE) as "is_agent!"FROM requested_ids reqLEFT JOIN "User" u ON u.id = req.idLEFT JOIN macro_user_info mui ON mui.macro_user_id = u.macro_user_id@@ -118,6 +131,7 @@ pub async fn get_user_names_with_email(id: row.user_profile_id,first_name: row.first_name,last_name: row.last_name,+ is_agent: row.is_agent,}).fetch_all(db).await?;diff --git a/crates/macro_db_client/src/user/mod.rs b/crates/macro_db_client/src/user/mod.rsindex b81c206101..a2ede5977a 100644--- a/crates/macro_db_client/src/user/mod.rs+++ b/crates/macro_db_client/src/user/mod.rs@@ -16,6 +16,7 @@ pub mod organization;pub mod patch;pub mod permissions;pub mod remove;+pub mod revert_unconfirmed_agent;pub mod update;pub mod update_profile_picture;pub mod update_user_id;diff --git a/crates/macro_db_client/src/user/revert_unconfirmed_agent.rs b/crates/macro_db_client/src/user/revert_unconfirmed_agent.rsnew file mode 100644index 0000000000..0207d1fbaf--- /dev/null+++ b/crates/macro_db_client/src/user/revert_unconfirmed_agent.rs@@ -0,0 +1,32 @@+#[cfg(test)]+mod test;++/// Reverts an account to human when its agent flag was never proven.+///+/// Signup creates the account before the email is verified, so a request can+/// mark someone else's unused address as an agent. The flag stands once the+/// account has confirmed setup, holds a key (minting one takes a verified+/// session), or has a pending agent invite from a team member.+///+/// Returns whether the account was reverted.+#[tracing::instrument(skip(db), err)]+pub async fn revert_unconfirmed_agent(db: &sqlx::PgPool, email: &str) -> anyhow::Result<bool> {+ let result = sqlx::query!(+ r#"+ UPDATE "User" u+ SET "isAgent" = FALSE+ WHERE u."email" = $1+ AND u."isAgent"+ AND NOT u."tutorialComplete"+ AND NOT EXISTS (SELECT 1 FROM "UserApiKey" k WHERE k.user_id = u."id")+ AND NOT EXISTS (+ SELECT 1 FROM team_invite ti WHERE ti.email = u."email" AND ti.is_agent+ )+ "#,+ email,+ )+ .execute(db)+ .await?;++ Ok(result.rows_affected() > 0)+}diff --git a/crates/macro_db_client/src/user/revert_unconfirmed_agent/test.rs b/crates/macro_db_client/src/user/revert_unconfirmed_agent/test.rsnew file mode 100644index 0000000000..9ca14ca5f2--- /dev/null+++ b/crates/macro_db_client/src/user/revert_unconfirmed_agent/test.rs@@ -0,0 +1,71 @@+use std::collections::HashSet;++use super::revert_unconfirmed_agent;+use crate::user::create_user::create_user;++const EMAIL: &str = "[email protected]";++async fn create_agent(pool: &sqlx::PgPool) -> String {+ create_user(+ pool,+ &uuid::Uuid::new_v4().to_string(),+ EMAIL,+ EMAIL,+ false,+ "cus_agent",+ None,+ None,+ HashSet::new(),+ true,+ )+ .await+ .unwrap()+}++async fn is_agent(pool: &sqlx::PgPool) -> bool {+ sqlx::query_scalar!(r#"SELECT "isAgent" FROM "User" WHERE email = $1"#, EMAIL)+ .fetch_one(pool)+ .await+ .unwrap()+}++#[sqlx::test]+async fn an_unproven_agent_flag_is_reverted(pool: sqlx::PgPool) {+ create_agent(&pool).await;++ assert!(revert_unconfirmed_agent(&pool, EMAIL).await.unwrap());+ assert!(!is_agent(&pool).await);+ assert!(!revert_unconfirmed_agent(&pool, EMAIL).await.unwrap());+}++#[sqlx::test]+async fn a_minted_key_proves_the_agent(pool: sqlx::PgPool) {+ let user_id = create_agent(&pool).await;+ sqlx::query!(+ r#"INSERT INTO "UserApiKey" (id, name, user_id, hash) VALUES ($1, 'Agent signup', $2, $3)"#,+ uuid::Uuid::new_v4(),+ user_id,+ &[0u8; 32][..],+ )+ .execute(&pool)+ .await+ .unwrap();++ assert!(!revert_unconfirmed_agent(&pool, EMAIL).await.unwrap());+ assert!(is_agent(&pool).await);+}++#[sqlx::test]+async fn confirming_setup_proves_the_agent(pool: sqlx::PgPool) {+ create_agent(&pool).await;+ sqlx::query!(+ r#"UPDATE "User" SET "tutorialComplete" = TRUE WHERE email = $1"#,+ )+ .execute(&pool)+ .await+ .unwrap();++ assert!(!revert_unconfirmed_agent(&pool, EMAIL).await.unwrap());+ assert!(is_agent(&pool).await);+}diff --git a/crates/model/src/authentication/login/request.rs b/crates/model/src/authentication/login/request.rsindex a7de5ed320..a8d8899e95 100644--- a/crates/model/src/authentication/login/request.rs+++ b/crates/model/src/authentication/login/request.rs@@ -8,6 +8,11 @@ pub struct PasswordlessRequest {pub redirect_uri: String,/// The referral codepub referral_code: Option<String>,+ /// Create an agent account if this address has no account yet. Otherwise+ /// `true` has no effect, and `false` reverts an agent flag nobody has proven:+ /// see `revert_unconfirmed_agent`.+ #[serde(default)]+ pub is_agent: bool,}#[derive(serde::Serialize, serde::Deserialize, Debug, ToSchema)]diff --git a/crates/model_user/src/lib.rs b/crates/model_user/src/lib.rsindex af18ff897f..1bbf5f4c8a 100644--- a/crates/model_user/src/lib.rs+++ b/crates/model_user/src/lib.rs@@ -74,6 +74,9 @@ pub struct UserName {pub id: String,pub first_name: Option<String>,pub last_name: Option<String>,+ /// Whether this is an agent account rather than a person.+ #[serde(default)]+ pub is_agent: bool,}// HACK: the zod generator on the FE only likes objects, not arrays, so we build silly structs like thesediff --git a/crates/static_file_service_client/src/lib.rs b/crates/static_file_service_client/src/lib.rsindex d6a21896e3..09ec646101 100644--- a/crates/static_file_service_client/src/lib.rs+++ b/crates/static_file_service_client/src/lib.rs@@ -15,13 +15,32 @@ pub struct StaticFileServiceClient {impl StaticFileServiceClient {pub fn new(internal_auth_key: String, url: String) -> Self {+ Self::from_builder(internal_auth_key, url, reqwest::Client::builder())+ }++ /// For callers on a request path, which must not wait forever. Transfers of+ /// large files through this client can outlast a short timeout.+ pub fn with_timeout(+ internal_auth_key: String,+ url: String,+ timeout: std::time::Duration,+ ) -> Self {+ Self::from_builder(+ internal_auth_key,+ url,+ reqwest::Client::builder().timeout(timeout),+ )+ }++ fn from_builder(+ internal_auth_key: String,+ url: String,+ builder: reqwest::ClientBuilder,+ ) -> Self {let mut headers = reqwest::header::HeaderMap::new();headers.insert(INTERNAL_ACCESS_HEADER, internal_auth_key.parse().unwrap());- let client = reqwest::Client::builder()- .default_headers(headers)- .build()- .unwrap();+ let client = builder.default_headers(headers).build().unwrap();Self { url, client }}diff --git a/crates/teams/AGENTS.md b/crates/teams/AGENTS.mdindex e27efea58b..8086c9d9eb 100644--- a/crates/teams/AGENTS.md+++ b/crates/teams/AGENTS.md@@ -71,6 +71,10 @@ event contract (schema, sanitization, delivery semantics).409 in that same request when it is no longer the caller's team; without`team_id` the routes act on whatever team is current.+- `team_invite.is_agent` makes an address with no account sign up as an agent.+ `authentication_service`'s agent setup joins the team, so the seat is added+ without a separate acceptance. Existing accounts accept like any other invite.+## Checks- `cargo test -p teams` (`SQLX_OFFLINE` unset).diff --git a/crates/teams/src/domain/model.rs b/crates/teams/src/domain/model.rsindex c8eee8c557..1a99165d24 100644--- a/crates/teams/src/domain/model.rs+++ b/crates/teams/src/domain/model.rs@@ -366,6 +366,8 @@ pub struct TeamInviteDetails {pub created_at: DateTime<Utc>,/// When the invite was last sentpub last_sent_at: DateTime<Utc>,+ /// Whether the invite creates an agent account+ pub is_agent: bool,}/// Deserializes an optional field while preserving explicit `null` values.@@ -588,6 +590,8 @@ pub struct TeamInvite<'a> {pub team_invite_id: uuid::Uuid,/// The email of the userpub email: Email<Lowercase<'a>>,+ /// Whether the invite creates an agent account+ pub is_agent: bool,}impl TeamInvite<'static> {@@ -597,6 +601,7 @@ impl TeamInvite<'static> {team_id: self.team_id,team_invite_id: self.team_invite_id,email: self.email.to_owned(),+ is_agent: self.is_agent,}}}@@ -623,6 +628,8 @@ pub struct DueInviteReminder {pub paying: bool,/// Whether the team has a subscriptionpub has_subscription: bool,+ /// Whether the invite creates an agent account+ pub is_agent: bool,}/// Snapshot of a team invite before it is accepted.@@ -642,6 +649,8 @@ pub struct TeamInviteSnapshot<'a> {pub created_at: DateTime<Utc>,/// When the invite was last sentpub last_sent_at: DateTime<Utc>,+ /// Whether the invite creates an agent account+ pub is_agent: bool,}/// Result of accepting a team invite, including the data needed to roll it back.diff --git a/crates/teams/src/domain/team_repo.rs b/crates/teams/src/domain/team_repo.rsindex fd3b653b62..3dfbec620a 100644--- a/crates/teams/src/domain/team_repo.rs+++ b/crates/teams/src/domain/team_repo.rs@@ -87,6 +87,7 @@ pub trait TeamRepository: Clone + Send + Sync + 'static {team_id: &uuid::Uuid,invited_by: &MacroUserIdStr<'_>,invites: non_empty::NonEmpty<&[Email<Lowercase<'_>>]>,+ is_agent: bool,) -> impl Future<Output = Result<Vec<TeamInvite<'_>>, InviteUsersToTeamError>> + Send;/// Compares the list of users you are trying to invite to ones already invited@@ -419,6 +420,7 @@ pub trait TeamService: Clone + Send + Sync + 'static {&self,entity_access_receipt: EntityAccessReceipt<MemberTeamRole>,invites: non_empty::NonEmpty<&[Email<Lowercase<'_>>]>,+ is_agent: bool,) -> impl Future<Output = Result<Vec<TeamInvite<'_>>, InviteUsersToTeamError>> + Send;/// Remove user from a team.diff --git a/crates/teams/src/domain/team_service.rs b/crates/teams/src/domain/team_service.rsindex 1deaf3929c..5721975a79 100644--- a/crates/teams/src/domain/team_service.rs+++ b/crates/teams/src/domain/team_service.rs@@ -1509,6 +1509,7 @@ where&self,entity_access_receipt: EntityAccessReceipt<MemberTeamRole>,invites: non_empty::NonEmpty<&[Email<Lowercase<'_>>]>,+ is_agent: bool,) -> Result<Vec<TeamInvite<'_>>, InviteUsersToTeamError> {let team_id =macro_uuid::string_to_uuid(&entity_access_receipt.entity().entity_id).unwrap();@@ -1604,7 +1605,7 @@ wherelet invited = self.team_repository- .invite_users_to_team(&team_id, invited_by, invites)+ .invite_users_to_team(&team_id, invited_by, invites, is_agent).await?;let team_name = if invited.is_empty() {@@ -1634,6 +1635,7 @@ wheresender_profile_picture_url: None,invitee_plan,reminder: false,+ is_agent: invite.is_agent,},).awaitdiff --git a/crates/teams/src/domain/team_service/invite_reminders.rs b/crates/teams/src/domain/team_service/invite_reminders.rsindex b606e0b6f2..fb798ca0cb 100644--- a/crates/teams/src/domain/team_service/invite_reminders.rs+++ b/crates/teams/src/domain/team_service/invite_reminders.rs@@ -167,6 +167,7 @@ wheresender_profile_picture_url: None,invitee_plan: invitee_plan(reminder),reminder: true,+ is_agent: reminder.is_agent,},recipient_ids: HashSet::from([recipient]),}diff --git a/crates/teams/src/domain/team_service/test.rs b/crates/teams/src/domain/team_service/test.rsindex 97ed91350c..9f10b4f0bd 100644--- a/crates/teams/src/domain/team_service/test.rs+++ b/crates/teams/src/domain/team_service/test.rs@@ -413,6 +413,7 @@ impl TeamRepository for MockTeamRepository {_: &uuid::Uuid,_: &MacroUserIdStr<'_>,_: non_empty::NonEmpty<&[Email<Lowercase<'_>>]>,+ _: bool,) -> impl Future<Output = Result<Vec<TeamInvite<'_>>, InviteUsersToTeamError>> + Send {*self.invite_users_to_team_calls.lock().unwrap() += 1;let invites = self.invites_to_return.clone();@@ -1783,6 +1784,7 @@ impl OpenSeatRelease for RecordingOpenSeatRelease {fn make_invite(email: &str, invite_id: uuid::Uuid, team_id: uuid::Uuid) -> TeamInvite<'static> {TeamInvite {+ is_agent: false,team_id,team_invite_id: invite_id,email: Email::parse_from_str(email)@@ -1840,6 +1842,7 @@ fn make_accepted_invite(.into_owned(),created_at: chrono::Utc::now(),last_sent_at: chrono::Utc::now(),+ is_agent: false,},}}@@ -2221,6 +2224,7 @@ async fn invite_team_event_is_published_only_for_new_lowercase_email() {.invite_users_to_team(test_team_receipt::<MemberTeamRole>(team_id, &inviter),non_empty::NonEmpty::new(emails.as_slice()).unwrap(),+ false,).await.unwrap();@@ -2258,6 +2262,7 @@ async fn invite_team_event_repository_failure_emits_nothing_and_broker_failure_i.invite_users_to_team(test_team_receipt::<MemberTeamRole>(team_id, &inviter),non_empty::NonEmpty::new(emails.as_slice()).unwrap(),+ false,).await.is_err()@@ -2275,6 +2280,7 @@ async fn invite_team_event_repository_failure_emits_nothing_and_broker_failure_i.invite_users_to_team(test_team_receipt::<MemberTeamRole>(team_id, &inviter),non_empty::NonEmpty::new(emails.as_slice()).unwrap(),+ false,).await.is_ok()@@ -3320,7 +3326,7 @@ async fn invite_users_to_team_enterprise_bypasses_billing_and_preserves_side_efflet receipt = test_team_receipt::<MemberTeamRole>(team_id, &invited_by);let result = service- .invite_users_to_team(receipt, invites)+ .invite_users_to_team(receipt, invites, false).await.unwrap();@@ -3420,6 +3426,7 @@ async fn invitee_plans_for_team(.invite_users_to_team(test_team_receipt::<MemberTeamRole>(team_id, &owner_id),invites,+ false,).await.unwrap();@@ -3492,7 +3499,7 @@ async fn invite_users_to_team_blocked_for_member_when_non_admin_invites_disabledlet receipt = test_team_receipt::<MemberTeamRole>(team_id, &invited_by);let error = service- .invite_users_to_team(receipt, invites)+ .invite_users_to_team(receipt, invites, false).await.unwrap_err();@@ -3523,6 +3530,7 @@ async fn invite_users_to_team_caps_new_invites_per_day() {invited_by: "macro|[email protected]".to_string(),created_at,last_sent_at: created_at,+ is_agent: false,};let now = chrono::Utc::now();// A day-old invite no longer counts toward today's limit.@@ -3551,6 +3559,7 @@ async fn invite_users_to_team_caps_new_invites_per_day() {.invite_users_to_team(test_team_receipt::<MemberTeamRole>(team_id, &invited_by),non_empty::NonEmpty::new(invite_emails.as_slice()).unwrap(),+ false,).await.unwrap_err();@@ -3596,7 +3605,7 @@ async fn invite_users_to_team_allowed_for_admin_when_non_admin_invites_disabled(let receipt = test_team_receipt::<MemberTeamRole>(team_id, &invited_by);let result = service- .invite_users_to_team(receipt, invites)+ .invite_users_to_team(receipt, invites, false).await.unwrap();@@ -3677,7 +3686,7 @@ async fn invite_users_to_team_enterprise_allows_invites_past_former_plan_limit()let receipt = test_team_receipt::<MemberTeamRole>(team_id, &invited_by);let result = service- .invite_users_to_team(receipt, invites)+ .invite_users_to_team(receipt, invites, false).await.unwrap();@@ -3726,7 +3735,7 @@ async fn invite_users_to_team_enterprise_status_lookup_failure_precedes_persistelet receipt = test_team_receipt::<MemberTeamRole>(team_id, &invited_by);let error = service- .invite_users_to_team(receipt, invites)+ .invite_users_to_team(receipt, invites, false).await.unwrap_err();@@ -3777,7 +3786,7 @@ async fn test_invite_marks_sent_only_for_successful_notifications() {let receipt = test_team_receipt::<MemberTeamRole>(team_id, &invited_by);let result = service- .invite_users_to_team(receipt, invites)+ .invite_users_to_team(receipt, invites, false).await.unwrap();@@ -3819,7 +3828,7 @@ async fn test_invite_does_not_call_mark_sent_when_all_notifications_fail() {let receipt = test_team_receipt::<MemberTeamRole>(team_id, &invited_by);service- .invite_users_to_team(receipt, invites)+ .invite_users_to_team(receipt, invites, false).await.unwrap();@@ -3860,7 +3869,7 @@ async fn test_invite_marks_all_sent_when_all_notifications_succeed() {let receipt = test_team_receipt::<MemberTeamRole>(team_id, &invited_by);service- .invite_users_to_team(receipt, invites)+ .invite_users_to_team(receipt, invites, false).await.unwrap();@@ -3905,7 +3914,7 @@ async fn team_analytics_invite_users_emits_invited_events_with_team_id() {let receipt = test_team_receipt::<MemberTeamRole>(team_id, &invited_by);service- .invite_users_to_team(receipt, invites)+ .invite_users_to_team(receipt, invites, false).await.unwrap();@@ -3959,7 +3968,7 @@ async fn team_analytics_invite_users_does_not_emit_when_invite_creation_fails()let receipt = test_team_receipt::<MemberTeamRole>(team_id, &invited_by);let err = service- .invite_users_to_team(receipt, invites)+ .invite_users_to_team(receipt, invites, false).await.err().unwrap();@@ -4882,7 +4891,7 @@ async fn test_invite_users_to_team_backfills_legacy_team_subscription() {let receipt = test_team_receipt::<MemberTeamRole>(team_id, &owner_id);service- .invite_users_to_team(receipt, invites)+ .invite_users_to_team(receipt, invites, false).await.unwrap();@@ -4952,7 +4961,7 @@ async fn invite_users_to_team_fails_when_the_owners_subscription_lookup_fails()let receipt = test_team_receipt::<MemberTeamRole>(team_id, &owner_id);let err = service- .invite_users_to_team(receipt, invites)+ .invite_users_to_team(receipt, invites, false).await.err().unwrap();@@ -7860,7 +7869,7 @@ async fn invite_users_to_team_free_team_under_cap_skips_billing() {let receipt = test_team_receipt::<MemberTeamRole>(team_id, &invited_by);let result = service- .invite_users_to_team(receipt, invites)+ .invite_users_to_team(receipt, invites, false).await.unwrap();@@ -7910,7 +7919,7 @@ async fn invite_users_to_team_free_team_allows_invites_past_former_limit() {let receipt = test_team_receipt::<MemberTeamRole>(team_id, &invited_by);let result = service- .invite_users_to_team(receipt, invites)+ .invite_users_to_team(receipt, invites, false).await.unwrap();@@ -8816,6 +8825,7 @@ fn due_reminder(invite: u128, reminder_number: u8) -> DueInviteReminder {enterprise: false,paying: true,has_subscription: true,+ is_agent: false,}}diff --git a/crates/teams/src/inbound/axum_router/invite_to_team.rs b/crates/teams/src/inbound/axum_router/invite_to_team.rsindex adc7c2cbe7..f89befb589 100644--- a/crates/teams/src/inbound/axum_router/invite_to_team.rs+++ b/crates/teams/src/inbound/axum_router/invite_to_team.rs@@ -28,6 +28,10 @@ pub struct InviteToTeamRequest {/// and the request answers 409.#[serde(default)]pub team_id: Option<uuid::Uuid>,+ /// Invite these addresses as agents: an address with no account signs up+ /// as an agent and joins the team when it first signs in.+ #[serde(default)]+ pub is_agent: bool,}/// Error type for the invite to team handler@@ -114,7 +118,7 @@ pub async fn handler<T: TeamService, Eas: EntityAccessService, Auth: MacroAuthorlet team_invites = state.service- .invite_users_to_team(access.entity_access_receipt, invites)+ .invite_users_to_team(access.entity_access_receipt, invites, req.is_agent).await.map_err(InviteToTeamError::InviteUsersToTeamError)?;diff --git a/crates/teams/src/inbound/axum_router/test.rs b/crates/teams/src/inbound/axum_router/test.rsindex 5bab58dd54..7c393da8c0 100644--- a/crates/teams/src/inbound/axum_router/test.rs+++ b/crates/teams/src/inbound/axum_router/test.rs@@ -329,6 +329,7 @@ impl TeamService for FakeTeamService {&self,entity_access_receipt: EntityAccessReceipt<MemberTeamRole>,invites: non_empty::NonEmpty<&[Email<Lowercase<'_>>]>,+ _is_agent: bool,) -> Result<Vec<TeamInvite<'_>>, InviteUsersToTeamError> {self.invite_calls.lock()diff --git a/crates/teams/src/outbound/team_repo.rs b/crates/teams/src/outbound/team_repo.rsindex adea1c43fc..0a637981ea 100644--- a/crates/teams/src/outbound/team_repo.rs+++ b/crates/teams/src/outbound/team_repo.rs@@ -401,6 +401,7 @@ impl TeamRepository for TeamRepositoryImpl {team_id: &uuid::Uuid,invited_by: &MacroUserIdStr<'_>,invites: non_empty::NonEmpty<&[Email<Lowercase<'_>>]>,+ is_agent: bool,) -> Result<Vec<TeamInvite<'_>>, InviteUsersToTeamError> {let email_strings: Vec<String> = invites.iter()@@ -420,9 +421,9 @@ impl TeamRepository for TeamRepositoryImpl {let mut transaction = self.pool.begin().await?;// Single query that filters out both already invited AND already on team- let created_invites: Vec<(uuid::Uuid, uuid::Uuid, String)> = sqlx::query!(+ let created_invites: Vec<(uuid::Uuid, uuid::Uuid, String, bool)> = sqlx::query!(r#"- INSERT INTO team_invite (id, team_id, email, team_role, invited_by, created_at, last_sent_at)+ INSERT INTO team_invite (id, team_id, email, team_role, invited_by, created_at, last_sent_at, is_agent)SELECTt.id,$1::uuid,@@ -430,7 +431,8 @@ impl TeamRepository for TeamRepositoryImpl {$2,$3::text,NOW(),- NOW()+ NOW(),+ $7FROM UNNEST($4::uuid[], $5::text[], $6::text[]) AS t(id, email, user_id)WHERE NOT EXISTS (SELECT 1 FROM team_invite ti@@ -440,7 +442,7 @@ impl TeamRepository for TeamRepositoryImpl {SELECT 1 FROM team_user tuWHERE tu.team_id = $1 AND tu.user_id = t.user_id)- RETURNING id, team_id, email+ RETURNING id, team_id, email, is_agent"#,team_id,TeamRole::Member as _,@@ -448,16 +450,17 @@ impl TeamRepository for TeamRepositoryImpl {&team_invite_ids[..],&email_strings[..],¯o_user_ids[..],+ is_agent,)- .map(|r| (r.id, r.team_id, r.email))+ .map(|r| (r.id, r.team_id, r.email, r.is_agent)).fetch_all(&mut *transaction).await?;// Also re-send existing invites whose email rate limit has passed;// sooner, the email would be dropped while `last_sent_at` moved on.- let resent_invites: Vec<(uuid::Uuid, uuid::Uuid, String)> = sqlx::query!(+ let resent_invites: Vec<(uuid::Uuid, uuid::Uuid, String, bool)> = sqlx::query!(r#"- SELECT id, team_id, email+ SELECT id, team_id, email, is_agentFROM team_inviteWHERE team_id = $1AND email = ANY($2::text[])@@ -467,11 +470,11 @@ impl TeamRepository for TeamRepositoryImpl {&email_strings[..],invite_resend_interval().as_secs_f64(),)- .map(|r| (r.id, r.team_id, r.email))+ .map(|r| (r.id, r.team_id, r.email, r.is_agent)).fetch_all(&mut *transaction).await?;- let to_email = |id: uuid::Uuid, team_id: uuid::Uuid, email: String| {+ let to_email = |id: uuid::Uuid, team_id: uuid::Uuid, email: String, is_agent: bool| {Email::parse_from_str(&email).ok().map(|e| e.into_owned().lowercase())@@ -479,6 +482,7 @@ impl TeamRepository for TeamRepositoryImpl {team_id,team_invite_id: id,email,+ is_agent,})};@@ -486,7 +490,7 @@ impl TeamRepository for TeamRepositoryImpl {let all_invites: Vec<TeamInvite<'static>> = created_invites.into_iter().chain(resent_invites)- .filter_map(|(id, team_id, email)| to_email(id, team_id, email))+ .filter_map(|(id, team_id, email, is_agent)| to_email(id, team_id, email, is_agent)).collect();transaction.commit().await?;@@ -611,7 +615,8 @@ impl TeamRepository for TeamRepositoryImpl {ti.reminders_sent,t.enterprise,t.paying,- t.subscription_id IS NOT NULL AS "has_subscription!"+ t.subscription_id IS NOT NULL AS "has_subscription!",+ ti.is_agent"#,limit,)@@ -629,6 +634,7 @@ impl TeamRepository for TeamRepositoryImpl {enterprise: r.enterprise,paying: r.paying,has_subscription: r.has_subscription,+ is_agent: r.is_agent,})}).collect::<Result<Vec<_>, TeamError>>()?;@@ -686,15 +692,15 @@ impl TeamRepository for TeamRepositoryImpl {&self,team_invite_id: &uuid::Uuid,) -> Result<TeamInvite<'_>, TeamError> {- let team_invite: (uuid::Uuid, uuid::Uuid, String) = sqlx::query!(+ let team_invite: (uuid::Uuid, uuid::Uuid, String, bool) = sqlx::query!(r#"- SELECT id, email, team_id+ SELECT id, email, team_id, is_agentFROM team_inviteWHERE id = $1"#,team_invite_id,)- .map(|row| (row.id, row.team_id, row.email))+ .map(|row| (row.id, row.team_id, row.email, row.is_agent)).fetch_one(&self.pool).await.map_err(|e| match e {@@ -702,7 +708,7 @@ impl TeamRepository for TeamRepositoryImpl {_ => e.into(),})?;- let (id, team_id, email) = team_invite;+ let (id, team_id, email, is_agent) = team_invite;let team_invite: TeamInvite = TeamInvite {team_id,@@ -710,6 +716,7 @@ impl TeamRepository for TeamRepositoryImpl {email: Email::parse_from_str(&email).map(|e| e.into_owned().lowercase()).map_err(|e| anyhow::anyhow!("unable to parse email {}", e))?,+ is_agent,};Ok(team_invite.to_owned())@@ -894,7 +901,7 @@ impl TeamRepository for TeamRepositoryImpl {// Get invite data before deleting it so the accept can be rolled back later.let invite = sqlx::query(r#"- SELECT id, email, team_role, team_id, invited_by, created_at, last_sent_at+ SELECT id, email, team_role, team_id, invited_by, created_at, last_sent_at, is_agentFROM team_inviteWHERE id = $1 AND email = $2"#,@@ -924,6 +931,7 @@ impl TeamRepository for TeamRepositoryImpl {invite.try_get("last_sent_at")?,chrono::Utc,),+ is_agent: invite.try_get("is_agent")?,};// Assign user to team_user@@ -1005,8 +1013,8 @@ impl TeamRepository for TeamRepositoryImpl {sqlx::query(r#"INSERT INTO team_invite- (id, team_id, email, team_role, invited_by, created_at, last_sent_at)- VALUES ($1, $2, $3, $4, $5, $6, $7)+ (id, team_id, email, team_role, invited_by, created_at, last_sent_at, is_agent)+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8)ON CONFLICT DO NOTHING"#,)@@ -1017,6 +1025,7 @@ impl TeamRepository for TeamRepositoryImpl {.bind(accepted_invite.invite.invited_by.as_ref()).bind(accepted_invite.invite.created_at.naive_utc()).bind(accepted_invite.invite.last_sent_at.naive_utc())+ .bind(accepted_invite.invite.is_agent).execute(&mut *transaction).await?;@@ -1282,7 +1291,8 @@ impl TeamRepository for TeamRepositoryImpl {team_role as "team_role!: TeamRole",invited_by,created_at as "created_at!: chrono::DateTime<chrono::Utc>",- last_sent_at as "last_sent_at!: chrono::DateTime<chrono::Utc>"+ last_sent_at as "last_sent_at!: chrono::DateTime<chrono::Utc>",+ is_agentFROM team_inviteWHERE email = $1"#,@@ -1296,6 +1306,7 @@ impl TeamRepository for TeamRepositoryImpl {invited_by: row.invited_by,created_at: row.created_at,last_sent_at: row.last_sent_at,+ is_agent: row.is_agent,}).fetch_all(&self.pool).await?;@@ -1317,7 +1328,8 @@ impl TeamRepository for TeamRepositoryImpl {team_role as "team_role!: TeamRole",invited_by,created_at as "created_at!: chrono::DateTime<chrono::Utc>",- last_sent_at as "last_sent_at!: chrono::DateTime<chrono::Utc>"+ last_sent_at as "last_sent_at!: chrono::DateTime<chrono::Utc>",+ is_agentFROM team_inviteWHERE team_id = $1"#,@@ -1331,6 +1343,7 @@ impl TeamRepository for TeamRepositoryImpl {invited_by: row.invited_by,created_at: row.created_at,last_sent_at: row.last_sent_at,+ is_agent: row.is_agent,}).fetch_all(&self.pool).await?;diff --git a/crates/teams/src/outbound/team_repo/test.rs b/crates/teams/src/outbound/team_repo/test.rsindex 81e79cc8fa..eaefefc7ff 100644--- a/crates/teams/src/outbound/team_repo/test.rs+++ b/crates/teams/src/outbound/team_repo/test.rs@@ -417,7 +417,7 @@ async fn test_invite_users_to_team(pool: Pool<Postgres>) -> anyhow::Result<()> {let invites = non_empty::NonEmpty::new(invites.as_slice())?;let invited = team_repo- .invite_users_to_team(&team_id, &user_id, invites)+ .invite_users_to_team(&team_id, &user_id, invites, false).await?;assert_eq!(invited.len(), 1);@@ -430,7 +430,7 @@ async fn test_invite_users_to_team(pool: Pool<Postgres>) -> anyhow::Result<()> {let invites = non_empty::NonEmpty::new(invites.as_slice())?;let invited = team_repo- .invite_users_to_team(&team_id, &user_id, invites)+ .invite_users_to_team(&team_id, &user_id, invites, false).await?;assert!(invited.is_empty());@@ -533,7 +533,7 @@ async fn test_invite_existing_user_within_rate_limit(pool: Pool<Postgres>) -> anlet invites = non_empty::NonEmpty::new(invites.as_slice())?;let invited = team_repo- .invite_users_to_team(&team_id, &user_id, invites)+ .invite_users_to_team(&team_id, &user_id, invites, false).await?;// Rate limit blocks re-send, no new invite created either@@ -565,7 +565,7 @@ async fn test_invite_existing_user_inside_email_rate_limit(let invites = vec![Email::parse_from_str("[email protected]")?.lowercase()];let invites = non_empty::NonEmpty::new(invites.as_slice())?;let invited = team_repo- .invite_users_to_team(&team_id, &user_id, invites)+ .invite_users_to_team(&team_id, &user_id, invites, false).await?;assert!(invited.is_empty());@@ -596,7 +596,7 @@ async fn test_invite_existing_user_after_rate_limit(pool: Pool<Postgres>) -> anylet invites = non_empty::NonEmpty::new(invites.as_slice())?;let invited = team_repo- .invite_users_to_team(&team_id, &user_id, invites)+ .invite_users_to_team(&team_id, &user_id, invites, false).await?;assert_eq!(invited.len(), 1);@@ -631,7 +631,7 @@ async fn test_invite_mix_new_and_existing(pool: Pool<Postgres>) -> anyhow::Resullet invites = non_empty::NonEmpty::new(invites.as_slice())?;let invited = team_repo- .invite_users_to_team(&team_id, &user_id, invites)+ .invite_users_to_team(&team_id, &user_id, invites, false).await?;assert_eq!(invited.len(), 2);@@ -666,7 +666,7 @@ async fn test_reinvite_updates_last_sent_at(pool: Pool<Postgres>) -> anyhow::Reslet invites = vec![Email::parse_from_str("[email protected]")?.lowercase()];let invites = non_empty::NonEmpty::new(invites.as_slice())?;let invited = team_repo- .invite_users_to_team(&team_id, &user_id, invites)+ .invite_users_to_team(&team_id, &user_id, invites, false).await?;assert_eq!(invited.len(), 1);@@ -678,7 +678,7 @@ async fn test_reinvite_updates_last_sent_at(pool: Pool<Postgres>) -> anyhow::Reslet invites = vec![Email::parse_from_str("[email protected]")?.lowercase()];let invites = non_empty::NonEmpty::new(invites.as_slice())?;let invited = team_repo- .invite_users_to_team(&team_id, &user_id, invites)+ .invite_users_to_team(&team_id, &user_id, invites, false).await?;assert!(invited.is_empty());@@ -708,7 +708,7 @@ async fn test_resend_without_mark_sent_stays_eligible(pool: Pool<Postgres>) -> alet invites = vec![Email::parse_from_str("[email protected]")?.lowercase()];let invites = non_empty::NonEmpty::new(invites.as_slice())?;let invited = team_repo- .invite_users_to_team(&team_id, &user_id, invites)+ .invite_users_to_team(&team_id, &user_id, invites, false).await?;assert_eq!(invited.len(), 1);@@ -718,7 +718,7 @@ async fn test_resend_without_mark_sent_stays_eligible(pool: Pool<Postgres>) -> alet invites = vec![Email::parse_from_str("[email protected]")?.lowercase()];let invites = non_empty::NonEmpty::new(invites.as_slice())?;let invited = team_repo- .invite_users_to_team(&team_id, &user_id, invites)+ .invite_users_to_team(&team_id, &user_id, invites, false).await?;assert_eq!(invited.len(), 1);@@ -768,7 +768,7 @@ async fn test_mark_invites_sent(pool: Pool<Postgres>) -> anyhow::Result<()> {let invites = vec![Email::parse_from_str("[email protected]")?.lowercase()];let invites = non_empty::NonEmpty::new(invites.as_slice())?;let invited = team_repo- .invite_users_to_team(&team_id, &user_id, invites)+ .invite_users_to_team(&team_id, &user_id, invites, false).await?;assert!(invited.is_empty());@@ -1111,6 +1111,14 @@ async fn test_rollback_accept_team_invite(pool: Pool<Postgres>) -> anyhow::Resullet team_invite_id = macro_uuid::string_to_uuid("22222222-2222-2222-2222-222222222222")?;let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")?;+ // A rolled-back agent invite must stay one, or the retry never joins.+ sqlx::query!(+ "UPDATE team_invite SET is_agent = TRUE WHERE id = $1",+ team_invite_id+ )+ .execute(&pool)+ .await?;+let accepted_invite = team_repo.accept_team_invite(&team_invite_id, &user_id).await?;@@ -1134,7 +1142,7 @@ async fn test_rollback_accept_team_invite(pool: Pool<Postgres>) -> anyhow::Resullet invite = sqlx::query(r#"- SELECT email, team_role+ SELECT email, team_role, is_agentFROM team_inviteWHERE id = $1"#,@@ -1142,6 +1150,7 @@ async fn test_rollback_accept_team_invite(pool: Pool<Postgres>) -> anyhow::Resul.bind(team_invite_id).fetch_one(&pool).await?;+ assert!(invite.try_get::<bool, _>("is_agent")?);assert_eq!(invite.try_get::<String, _>("email")?, "[email protected]");assert_eq!(invite.try_get::<TeamRole, _>("team_role")?,@@ -2089,3 +2098,43 @@ async fn invite_reminder_claims_respect_the_limit(pool: Pool<Postgres>) -> anyho);Ok(())}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("teams"))+)]+async fn agent_invites_are_visible_to_the_invitee(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let macro_user_id = uuid::Uuid::new_v4();+ sqlx::query!(+ r#"INSERT INTO "macro_user" (id, username, email, stripe_customer_id)+ VALUES ($1, '[email protected]', '[email protected]', 'cus_owner')"#,+ macro_user_id,+ )+ .execute(&pool)+ .await?;+ sqlx::query!(+ r#"INSERT INTO "User" ("id", "email", "macro_user_id")+ VALUES ('macro|[email protected]', '[email protected]', $1)"#,+ macro_user_id,+ )+ .execute(&pool)+ .await?;++ let team_repo = TeamRepositoryImpl::new(pool);+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")?;+ let team_id = macro_uuid::string_to_uuid("11111111-1111-1111-1111-111111111111")?;+ let invites = vec![Email::parse_from_str("[email protected]")?.lowercase()];+ let invites = non_empty::NonEmpty::new(invites.as_slice())?;++ let invited = team_repo+ .invite_users_to_team(&team_id, &user_id, invites, true)+ .await?;+ assert!(invited[0].is_agent);++ let invitee = MacroUserIdStr::parse_from_str("macro|[email protected]")?;+ let pending = team_repo.get_user_team_invites(&invitee).await?;+ assert_eq!(pending.len(), 1);+ assert!(pending[0].is_agent);++ Ok(())+}diff --git a/crates/user_api_key/AGENTS.md b/crates/user_api_key/AGENTS.mdindex c198d28747..f79ef33394 100644--- a/crates/user_api_key/AGENTS.md+++ b/crates/user_api_key/AGENTS.md@@ -22,7 +22,8 @@ here.## Boundaries- Depends on: `macro_user_id`, `macro_authorization` (feature `inbound`).-- Used by: `services/document_storage_service`.+- Used by: `services/document_storage_service`,+ `services/authentication_service` (agent setup).## Checksdiff --git a/crates/user_api_key/src/domain/ports.rs b/crates/user_api_key/src/domain/ports.rsindex 446dca0c1f..d643260e8d 100644--- a/crates/user_api_key/src/domain/ports.rs+++ b/crates/user_api_key/src/domain/ports.rs@@ -42,6 +42,17 @@ pub trait UserApiKeysRepo: Send + Sync + 'static {id: UserApiKeyId,) -> impl Future<Output = Result<bool, Self::Err>> + Send;+ /// Atomically replace the user's keys with this name by a new key.+ /// Concurrent replacements for a user run one at a time, so exactly one of+ /// the keys they return stays live.+ fn replace_keys_named(+ &self,+ user_id: &MacroUserIdStr<'_>,+ id: UserApiKeyId,+ name: &str,+ hash: &[u8; 32],+ ) -> impl Future<Output = Result<UserApiKeyInfo, Self::Err>> + Send;+/// Owner of a key. Authenticate-by-key is implemented by/// `macro_authorization`'s `PgUserApiKeyAuthorizationRepo`.///@@ -63,6 +74,14 @@ pub trait UserApiKeyService: Send + Sync + 'static {name: &str,) -> impl Future<Output = Result<CreatedUserApiKey, UserApiKeyError>> + Send;+ /// Mint a new key and revoke the user's earlier keys with the same name,+ /// atomically, so repeating or racing this always leaves one live key.+ fn replace_key(+ &self,+ user_id: &MacroUserIdStr<'_>,+ name: &str,+ ) -> impl Future<Output = Result<CreatedUserApiKey, UserApiKeyError>> + Send;+/// List the user's keys as id, name, and created_at.fn list_keys(&self,diff --git a/crates/user_api_key/src/domain/service.rs b/crates/user_api_key/src/domain/service.rsindex 9921ce0524..8229ab6431 100644--- a/crates/user_api_key/src/domain/service.rs+++ b/crates/user_api_key/src/domain/service.rs@@ -62,6 +62,24 @@ whereOk(CreatedUserApiKey::new(info, &key))}+ #[tracing::instrument(err, skip_all)]+ async fn replace_key(+ &self,+ user_id: &MacroUserIdStr<'_>,+ name: &str,+ ) -> Result<CreatedUserApiKey, UserApiKeyError> {+ let name = normalize_key_name(name)?;+ let id = UserApiKeyId::generate();+ let key = UserApiKey::generate();+ let hash = key.hash();+ let info = self+ .repo+ .replace_keys_named(user_id, id, &name, &hash)+ .await+ .map_err(|e| rootcause::Report::new(e).into_dynamic())?;+ Ok(CreatedUserApiKey::new(info, &key))+ }+#[tracing::instrument(err, skip_all)]async fn list_keys(&self,diff --git a/crates/user_api_key/src/domain/service/test.rs b/crates/user_api_key/src/domain/service/test.rsindex af2a193693..a6e03ec90d 100644--- a/crates/user_api_key/src/domain/service/test.rs+++ b/crates/user_api_key/src/domain/service/test.rs@@ -129,6 +129,22 @@ impl UserApiKeysRepo for FakeUserApiKeysRepo {.unwrap_or_default())}+ async fn replace_keys_named(+ &self,+ user_id: &MacroUserIdStr<'_>,+ id: UserApiKeyId,+ name: &str,+ hash: &[u8; 32],+ ) -> Result<UserApiKeyInfo, Self::Err> {+ self.keys+ .lock()+ .expect("keys lock poisoned")+ .entry(user_id.as_ref().to_string())+ .or_default()+ .retain(|stored| stored.name != name);+ self.insert_key(user_id, id, name, hash).await+ }+async fn delete_key(&self,user_id: &MacroUserIdStr<'_>,@@ -370,3 +386,30 @@ fn list_metadata_json_is_id_name_and_created_at() {);assert!(created_json.get("createdAt").is_some());}++#[tokio::test]+async fn replace_key_leaves_one_live_key_with_that_name() {+ let repo = FakeUserApiKeysRepo::default();+ let service = UserApiKeyServiceImpl::new(repo.clone());+ let other = service+ .create_key(&user(USER_A), "other")+ .await+ .expect("create should succeed");+ let first = service+ .replace_key(&user(USER_A), "Agent signup")+ .await+ .expect("replace should succeed");+ let second = service+ .replace_key(&user(USER_A), "Agent signup")+ .await+ .expect("replace should succeed");++ let live = service+ .list_keys(&user(USER_A))+ .await+ .expect("list should succeed");+ assert_eq!(live.len(), 2);+ assert!(live.iter().any(|key| key.id == other.id));+ assert!(live.iter().any(|key| key.id == second.id));+ assert!(!live.iter().any(|key| key.id == first.id));+}diff --git a/crates/user_api_key/src/outbound/pg_user_api_keys_repo.rs b/crates/user_api_key/src/outbound/pg_user_api_keys_repo.rsindex bec185804f..5b530ea9b5 100644--- a/crates/user_api_key/src/outbound/pg_user_api_keys_repo.rs+++ b/crates/user_api_key/src/outbound/pg_user_api_keys_repo.rs@@ -110,6 +110,56 @@ impl UserApiKeysRepo for PgUserApiKeysRepo {Ok(rows.into_iter().map(UserApiKeyInfo::from).collect())}+ #[tracing::instrument(err, skip_all)]+ async fn replace_keys_named(+ &self,+ user_id: &MacroUserIdStr<'_>,+ id: UserApiKeyId,+ name: &str,+ hash: &[u8; 32],+ ) -> Result<UserApiKeyInfo, Self::Err> {+ let mut transaction = self.pool.begin().await?;++ // Serializes replacements for this user: without it, two transactions+ // could each miss the other's uncommitted key and both stay live.+ sqlx::query!(+ r#"SELECT 1 AS "locked!" FROM "User" WHERE id = $1 FOR UPDATE"#,+ user_id.as_ref(),+ )+ .fetch_optional(&mut *transaction)+ .await?;++ sqlx::query!(+ r#"+ DELETE FROM "UserApiKey"+ WHERE user_id = $1 AND name = $2+ "#,+ user_id.as_ref(),+ name,+ )+ .execute(&mut *transaction)+ .await?;++ let row = sqlx::query_as!(+ UserApiKeyInfoRow,+ r#"+ INSERT INTO "UserApiKey" (id, name, user_id, hash)+ VALUES ($1, $2, $3, $4)+ RETURNING id, name, created_at+ "#,+ id.as_uuid(),+ name,+ user_id.as_ref(),+ &hash[..],+ )+ .fetch_one(&mut *transaction)+ .await?;++ transaction.commit().await?;++ Ok(row.into())+ }+#[tracing::instrument(err, skip_all)]async fn delete_key(&self,diff --git a/crates/user_api_key/src/outbound/pg_user_api_keys_repo/tests.rs b/crates/user_api_key/src/outbound/pg_user_api_keys_repo/tests.rsindex a974fe85c7..403ffcef5f 100644--- a/crates/user_api_key/src/outbound/pg_user_api_keys_repo/tests.rs+++ b/crates/user_api_key/src/outbound/pg_user_api_keys_repo/tests.rs@@ -241,3 +241,23 @@ async fn insert_same_hash_for_second_user_is_rejected(pool: PgPool) {.expect_err("duplicate hash should fail");assert!(matches!(err, super::UserApiKeysRepoErr::Db(_)));}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn racing_replacements_leave_exactly_one_live_key(pool: PgPool) {+ insert_user(&pool, USER_A).await;+ let repo = PgUserApiKeysRepo::new(pool.clone());+ let user = user(USER_A);+ let (first_id, second_id) = (UserApiKeyId::generate(), UserApiKeyId::generate());+ let (first_hash, second_hash) = (UserApiKey::generate().hash(), UserApiKey::generate().hash());++ let (first, second) = tokio::join!(+ repo.replace_keys_named(&user, first_id, "Agent signup", &first_hash),+ repo.replace_keys_named(&user, second_id, "Agent signup", &second_hash),+ );+ first.unwrap();+ second.unwrap();++ let live = repo.list_keys(&user).await.unwrap();+ assert_eq!(live.len(), 1);+ assert!(live[0].id == first_id || live[0].id == second_id);+}diff --git a/docs/agent-guide/login.md b/docs/agent-guide/login.mdindex b4c793126d..8242b58ab0 100644--- a/docs/agent-guide/login.md+++ b/docs/agent-guide/login.md@@ -21,6 +21,25 @@failure does not block the remaining content; signup retries repair tagswithout resetting task priorities. The guide waits until its tag IDs resolve.+## Agent accounts++The email step shows an **I'm an agent** toggle when the `enable-agent-signup`+PostHog flag is on (on in dev; in production it targets the Experimental+Features cohort, which matches on email, so signed-out visitors don't match). Turning it on, or redeeming an invite sent with+`team.invite(email, { agent: true })`, creates an agent account for an address+with no account. An existing account keeps its type; the toggle does nothing.++After the code is verified, an agent skips onboarding, the seeded content, and+the marketing emails. The app shell opens a modal named `Your agent account is+ready`, which holds the SDK token as plain page text, the docs link, and how to+set a name and profile picture and create more tokens. An invited agent also+joins the inviting team at this point; if that fails, the modal says so and the invite+stays pending: reloading tries again, and the emailed invite link still works+after confirming. Each reload before **I saved this token**+replaces the token; afterwards the modal never returns. Requesting a code without+the toggle, or signing in with SSO, reverts the account to a person unless it holds+a token, has confirmed setup, or has a pending agent invite.+Production Google/SSO and inbox/calendar connections may return to either`https://macro.com` or `https://www.macro.com`. Verify connections from both hosts;the web inbox link flow returns to `/app/inbox-link-callback` on the originating host.diff --git a/docs/agent-guide/onboarding.md b/docs/agent-guide/onboarding.mdindex 5704382434..5928e1ee3e 100644--- a/docs/agent-guide/onboarding.md+++ b/docs/agent-guide/onboarding.md@@ -13,6 +13,9 @@ localStorage for that user and removed from the URL after it is applied, so areload keeps later progress. The app shell and the inbox connection callbackkeep `step` when they send a first-run user into onboarding.+Agent accounts never see this flow, including through a direct link; see+[login](login.md#agent-accounts).+## Onboarding bypass — `/app/onboarding`All `@macro.com` accounts see a **Bypass** button on every onboarding step. Itdiff --git a/packages/code-mode-sdk/scripts/catalog.ts b/packages/code-mode-sdk/scripts/catalog.tsindex ac86f88805..0d261e7a32 100644--- a/packages/code-mode-sdk/scripts/catalog.ts+++ b/packages/code-mode-sdk/scripts/catalog.ts@@ -35,6 +35,7 @@ export const descriptions: Record<string, string> = {tasks: 'Search, create, and update tasks.',teams:'Manage teams and membership: invite people to the team by email, list and revoke pending invites.',- users: 'Look up users and their profiles.',+ users:+ 'Look up users and their profiles; set your own name and picture (`macro.me.update`).',webhooks: 'Manage API webhook subscriptions.',};diff --git a/packages/code-mode-sdk/scripts/typedoc.ts b/packages/code-mode-sdk/scripts/typedoc.tsindex f202dc57c3..11e98a370a 100644--- a/packages/code-mode-sdk/scripts/typedoc.ts+++ b/packages/code-mode-sdk/scripts/typedoc.ts@@ -91,7 +91,9 @@ export function packageEntityDocs(? ['channels', 'external-chat', 'whatsapp']: directory === 'ai'? ['ai', 'images']- : [directory]+ : directory === 'users'+ ? ['users', 'me']+ : [directory]).map((value) => `src/entities/${value}/`),})),{diff --git a/packages/sdk-docs/pages/home.md b/packages/sdk-docs/pages/home.mdindex b32f72c0ff..c8bc75cbaa 100644--- a/packages/sdk-docs/pages/home.md+++ b/packages/sdk-docs/pages/home.md@@ -26,6 +26,27 @@ for await (const document of macro.documents.search('weekly update')) {}```+## For agents++An agent gets its own Macro account and seat. Have a teammate invite you with+`(await macro.teams.current()).invite('[email protected]', { agent: true })`, or,+where it is enabled, use the "I'm an agent" option on macro.com's email step. Either way, verify the code+sent to your address. Macro then shows your SDK token once. Set it as+`MACRO_API_KEY`, then introduce yourself:++```ts+const macro = new Macro({});++const image = await macro.me.uploadProfilePicture(bytes, {+ fileName: 'avatar.png',+ contentType: 'image/png',+});+await macro.me.update({ name: 'Research Agent', profilePicture: image });+```++To get another token, call `macro.apiKeys.create('my token')` and save the+returned `secret`, or use **Settings → API Keys**.+See {@link src/config!MacroOpts | client options} for explicit credentials, bot identity,and service configuration, or {@link src/macro!Macro | the Macro client} for every entry point.diff --git a/packages/sdk-docs/reference/README.md b/packages/sdk-docs/reference/README.mdindex 5fc926c169..82c89f7f1b 100644--- a/packages/sdk-docs/reference/README.md+++ b/packages/sdk-docs/reference/README.md@@ -26,6 +26,27 @@ for await (const document of macro.documents.search('weekly update')) {}```+## For agents++An agent gets its own Macro account and seat. Have a teammate invite you with+`(await macro.teams.current()).invite('[email protected]', { agent: true })`, or,+where it is enabled, use the "I'm an agent" option on macro.com's email step. Either way, verify the code+sent to your address. Macro then shows your SDK token once. Set it as+`MACRO_API_KEY`, then introduce yourself:++```ts+const macro = new Macro({});++const image = await macro.me.uploadProfilePicture(bytes, {+ fileName: 'avatar.png',+ contentType: 'image/png',+});+await macro.me.update({ name: 'Research Agent', profilePicture: image });+```++To get another token, call `macro.apiKeys.create('my token')` and save the+returned `secret`, or use **Settings → API Keys**.+See [client options](src/config/interfaces/MacroOpts.md) for explicit credentials, bot identity,and service configuration, or [the Macro client](src/macro/classes/Macro.md) for every entry point.diff --git a/packages/sdk-docs/reference/generated/auth/types.gen/README.md b/packages/sdk-docs/reference/generated/auth/types.gen/README.mdindex 57e95fa1a0..0875235465 100644--- a/packages/sdk-docs/reference/generated/auth/types.gen/README.md+++ b/packages/sdk-docs/reference/generated/auth/types.gen/README.md@@ -5,6 +5,12 @@- [AbGroup](type-aliases/AbGroup.md)- [AgentApiKey](type-aliases/AgentApiKey.md)- [AgentApiKeyProvider](type-aliases/AgentApiKeyProvider.md)+- [AgentSetupData](type-aliases/AgentSetupData.md)+- [AgentSetupError](type-aliases/AgentSetupError.md)+- [AgentSetupErrors](type-aliases/AgentSetupErrors.md)+- [AgentSetupResponse](type-aliases/AgentSetupResponse.md)+- [AgentSetupResponse2](type-aliases/AgentSetupResponse2.md)+- [AgentSetupResponses](type-aliases/AgentSetupResponses.md)- [AiBillingErrorBody](type-aliases/AiBillingErrorBody.md)- [AppleLoginData](type-aliases/AppleLoginData.md)- [AppleLoginError](type-aliases/AppleLoginError.md)@@ -84,6 +90,12 @@- [CreatePortalSessionRequest](type-aliases/CreatePortalSessionRequest.md)- [CreatePortalSessionResponse](type-aliases/CreatePortalSessionResponse.md)- [CreatePortalSessionResponses](type-aliases/CreatePortalSessionResponses.md)+- [CreateProfilePictureUploadData](type-aliases/CreateProfilePictureUploadData.md)+- [CreateProfilePictureUploadError](type-aliases/CreateProfilePictureUploadError.md)+- [CreateProfilePictureUploadErrors](type-aliases/CreateProfilePictureUploadErrors.md)+- [CreateProfilePictureUploadRequest](type-aliases/CreateProfilePictureUploadRequest.md)+- [CreateProfilePictureUploadResponse](type-aliases/CreateProfilePictureUploadResponse.md)+- [CreateProfilePictureUploadResponses](type-aliases/CreateProfilePictureUploadResponses.md)- [CreateTeamData](type-aliases/CreateTeamData.md)- [CreateTeamError](type-aliases/CreateTeamError.md)- [CreateTeamErrors](type-aliases/CreateTeamErrors.md)@@ -478,6 +490,7 @@- [PostProfilePicturesResponses](type-aliases/PostProfilePicturesResponses.md)- [ProfilePictureQueryParams](type-aliases/ProfilePictureQueryParams.md)- [ProfilePictures](type-aliases/ProfilePictures.md)+- [ProfilePictureUpload](type-aliases/ProfilePictureUpload.md)- [PublicGtmInviteLink](type-aliases/PublicGtmInviteLink.md)- [PurchaseAiCreditsData](type-aliases/PurchaseAiCreditsData.md)- [PurchaseAiCreditsError](type-aliases/PurchaseAiCreditsError.md)@@ -505,6 +518,12 @@- [PutProfilePictureData](type-aliases/PutProfilePictureData.md)- [PutProfilePictureError](type-aliases/PutProfilePictureError.md)- [PutProfilePictureErrors](type-aliases/PutProfilePictureErrors.md)+- [PutProfilePictureFileData](type-aliases/PutProfilePictureFileData.md)+- [PutProfilePictureFileError](type-aliases/PutProfilePictureFileError.md)+- [PutProfilePictureFileErrors](type-aliases/PutProfilePictureFileErrors.md)+- [PutProfilePictureFileRequest](type-aliases/PutProfilePictureFileRequest.md)+- [PutProfilePictureFileResponse](type-aliases/PutProfilePictureFileResponse.md)+- [PutProfilePictureFileResponses](type-aliases/PutProfilePictureFileResponses.md)- [PutProfilePictureResponse](type-aliases/PutProfilePictureResponse.md)- [PutProfilePictureResponses](type-aliases/PutProfilePictureResponses.md)- [PutUserLanguageData](type-aliases/PutUserLanguageData.md)diff --git a/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/AgentSetupData.md b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/AgentSetupData.mdnew file mode 100644index 0000000000..4fed67fca4--- /dev/null+++ b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/AgentSetupData.md@@ -0,0 +1,12 @@+# Type Alias: AgentSetupData++> **AgentSetupData** = \{ `body?`: `never`; `path?`: `never`; `query?`: `never`; `url`: `"/user/agent_setup"`; \}++## 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` | `"/user/agent_setup"` |diff --git a/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/AgentSetupError.md b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/AgentSetupError.mdnew file mode 100644index 0000000000..c0ff353765--- /dev/null+++ b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/AgentSetupError.md@@ -0,0 +1,3 @@+# Type Alias: AgentSetupError++> **AgentSetupError** = [`AgentSetupErrors`](AgentSetupErrors.md)\[keyof [`AgentSetupErrors`](AgentSetupErrors.md)\]diff --git a/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/AgentSetupErrors.md b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/AgentSetupErrors.mdnew file mode 100644index 0000000000..2a3fba3e94--- /dev/null+++ b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/AgentSetupErrors.md@@ -0,0 +1,12 @@+# Type Alias: AgentSetupErrors++> **AgentSetupErrors** = \{ `401`: `string`; `403`: [`ErrorResponse`](ErrorResponse.md); `409`: [`ErrorResponse`](ErrorResponse.md); `500`: [`ErrorResponse`](ErrorResponse.md); \}++## Properties++| Property | Type | Description |+| ------ | ------ | ------ |+| <a id="property-401"></a> `401` | `string` | - |+| <a id="property-403"></a> `403` | [`ErrorResponse`](ErrorResponse.md) | The account is not an agent |+| <a id="property-409"></a> `409` | [`ErrorResponse`](ErrorResponse.md) | Setup is already confirmed |+| <a id="property-500"></a> `500` | [`ErrorResponse`](ErrorResponse.md) | - |diff --git a/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/AgentSetupResponse.md b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/AgentSetupResponse.mdnew file mode 100644index 0000000000..9d2aef33c0--- /dev/null+++ b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/AgentSetupResponse.md@@ -0,0 +1,12 @@+# Type Alias: AgentSetupResponse++> **AgentSetupResponse** = \{ `api_key`: `string`; `team_join_failed`: `boolean`; \}++What an agent needs to start using the SDK.++## Properties++| Property | Type | Description |+| ------ | ------ | ------ |+| <a id="property-api_key"></a> `api_key` | `string` | The agent's API key. Shown only here; repeating setup revokes it. |+| <a id="property-team_join_failed"></a> `team_join_failed` | `boolean` | Whether joining the inviting team failed. The invite stays pending: repeating setup tries again, and the invite link works after confirming. |diff --git a/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/AgentSetupResponse2.md b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/AgentSetupResponse2.mdnew file mode 100644index 0000000000..2b29ad48e8--- /dev/null+++ b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/AgentSetupResponse2.md@@ -0,0 +1,3 @@+# Type Alias: AgentSetupResponse2++> **AgentSetupResponse2** = [`AgentSetupResponses`](AgentSetupResponses.md)\[keyof [`AgentSetupResponses`](AgentSetupResponses.md)\]diff --git a/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/AgentSetupResponses.md b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/AgentSetupResponses.mdnew file mode 100644index 0000000000..61ff3d3cb1--- /dev/null+++ b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/AgentSetupResponses.md@@ -0,0 +1,9 @@+# Type Alias: AgentSetupResponses++> **AgentSetupResponses** = \{ `200`: [`AgentSetupResponse`](AgentSetupResponse.md); \}++## Properties++| Property | Type |+| ------ | ------ |+| <a id="property-200"></a> `200` | [`AgentSetupResponse`](AgentSetupResponse.md) |diff --git a/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/CreateProfilePictureUploadData.md b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/CreateProfilePictureUploadData.mdnew file mode 100644index 0000000000..93af0192d9--- /dev/null+++ b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/CreateProfilePictureUploadData.md@@ -0,0 +1,12 @@+# Type Alias: CreateProfilePictureUploadData++> **CreateProfilePictureUploadData** = \{ `body`: [`CreateProfilePictureUploadRequest`](CreateProfilePictureUploadRequest.md); `path?`: `never`; `query?`: `never`; `url`: `"/user/profile_picture/file"`; \}++## Properties++| Property | Type |+| ------ | ------ |+| <a id="property-body"></a> `body` | [`CreateProfilePictureUploadRequest`](CreateProfilePictureUploadRequest.md) |+| <a id="property-path"></a> `path?` | `never` |+| <a id="property-query"></a> `query?` | `never` |+| <a id="property-url"></a> `url` | `"/user/profile_picture/file"` |diff --git a/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/CreateProfilePictureUploadError.md b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/CreateProfilePictureUploadError.mdnew file mode 100644index 0000000000..16b8ee657a--- /dev/null+++ b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/CreateProfilePictureUploadError.md@@ -0,0 +1,3 @@+# Type Alias: CreateProfilePictureUploadError++> **CreateProfilePictureUploadError** = [`CreateProfilePictureUploadErrors`](CreateProfilePictureUploadErrors.md)\[keyof [`CreateProfilePictureUploadErrors`](CreateProfilePictureUploadErrors.md)\]diff --git a/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/CreateProfilePictureUploadErrors.md b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/CreateProfilePictureUploadErrors.mdnew file mode 100644index 0000000000..c2303f2d7a--- /dev/null+++ b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/CreateProfilePictureUploadErrors.md@@ -0,0 +1,11 @@+# Type Alias: CreateProfilePictureUploadErrors++> **CreateProfilePictureUploadErrors** = \{ `400`: [`ErrorResponse`](ErrorResponse.md); `401`: `string`; `500`: [`ErrorResponse`](ErrorResponse.md); \}++## Properties++| Property | Type | Description |+| ------ | ------ | ------ |+| <a id="property-400"></a> `400` | [`ErrorResponse`](ErrorResponse.md) | Not a supported image type |+| <a id="property-401"></a> `401` | `string` | - |+| <a id="property-500"></a> `500` | [`ErrorResponse`](ErrorResponse.md) | - |diff --git a/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/CreateProfilePictureUploadRequest.md b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/CreateProfilePictureUploadRequest.mdnew file mode 100644index 0000000000..4a3d94296b--- /dev/null+++ b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/CreateProfilePictureUploadRequest.md@@ -0,0 +1,10 @@+# Type Alias: CreateProfilePictureUploadRequest++> **CreateProfilePictureUploadRequest** = \{ `content_type`: `string`; `file_name`: `string`; \}++## Properties++| Property | Type | Description |+| ------ | ------ | ------ |+| <a id="property-content_type"></a> `content_type` | `string` | Mime type of the image. |+| <a id="property-file_name"></a> `file_name` | `string` | File name, such as `avatar.png`. |diff --git a/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/CreateProfilePictureUploadResponse.md b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/CreateProfilePictureUploadResponse.mdnew file mode 100644index 0000000000..396eb3ec9a--- /dev/null+++ b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/CreateProfilePictureUploadResponse.md@@ -0,0 +1,3 @@+# Type Alias: CreateProfilePictureUploadResponse++> **CreateProfilePictureUploadResponse** = [`CreateProfilePictureUploadResponses`](CreateProfilePictureUploadResponses.md)\[keyof [`CreateProfilePictureUploadResponses`](CreateProfilePictureUploadResponses.md)\]diff --git a/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/CreateProfilePictureUploadResponses.md b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/CreateProfilePictureUploadResponses.mdnew file mode 100644index 0000000000..c1a6ec6b2e--- /dev/null+++ b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/CreateProfilePictureUploadResponses.md@@ -0,0 +1,9 @@+# Type Alias: CreateProfilePictureUploadResponses++> **CreateProfilePictureUploadResponses** = \{ `200`: [`ProfilePictureUpload`](ProfilePictureUpload.md); \}++## Properties++| Property | Type |+| ------ | ------ |+| <a id="property-200"></a> `200` | [`ProfilePictureUpload`](ProfilePictureUpload.md) |diff --git a/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/GetLegacyUserPermissionsResponse.md b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/GetLegacyUserPermissionsResponse.mdindex f600d4033c..19e55cb783 100644--- a/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/GetLegacyUserPermissionsResponse.md+++ b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/GetLegacyUserPermissionsResponse.md@@ -1,6 +1,6 @@# Type Alias: GetLegacyUserPermissionsResponse-> **GetLegacyUserPermissionsResponse** = \{ `aiDataConsent`: `boolean`; `createdAt?`: `string` \| `null`; `email`: `string`; `group?`: `null` \| [`AbGroup`](AbGroup.md); `hasChromeExt`: `boolean`; `hasTrialed`: `boolean`; `licenseStatus`: `string`; `name?`: `string` \| `null`; `permissions`: `string`[]; `referralCode`: `string`; `tutorialComplete`: `boolean`; `userId`: `string`; \}+> **GetLegacyUserPermissionsResponse** = \{ `aiDataConsent`: `boolean`; `createdAt?`: `string` \| `null`; `email`: `string`; `group?`: `null` \| [`AbGroup`](AbGroup.md); `hasChromeExt`: `boolean`; `hasTrialed`: `boolean`; `isAgent`: `boolean`; `licenseStatus`: `string`; `name?`: `string` \| `null`; `permissions`: `string`[]; `referralCode`: `string`; `tutorialComplete`: `boolean`; `userId`: `string`; \}## Properties@@ -12,6 +12,7 @@| <a id="property-group"></a> `group?` | `null` \| [`AbGroup`](AbGroup.md) | - || <a id="property-haschromeext"></a> `hasChromeExt` | `boolean` | Whether the user has the chrome extension || <a id="property-hastrialed"></a> `hasTrialed` | `boolean` | Whether the user has trialed through stripe |+| <a id="property-isagent"></a> `isAgent` | `boolean` | Whether this is an agent account rather than a person || <a id="property-licensestatus"></a> `licenseStatus` | `string` | The user's license status || <a id="property-name"></a> `name?` | `string` \| `null` | The user's name || <a id="property-permissions"></a> `permissions` | `string`[] | The permissions the user has |diff --git a/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/InviteToTeamRequest.md b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/InviteToTeamRequest.mdindex 1a430fa1b7..d6935ababa 100644--- a/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/InviteToTeamRequest.md+++ b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/InviteToTeamRequest.md@@ -1,6 +1,6 @@# Type Alias: InviteToTeamRequest-> **InviteToTeamRequest** = \{ `invites`: [`InviteEntry`](InviteEntry.md)[]; `team_id?`: `string` \| `null`; \}+> **InviteToTeamRequest** = \{ `invites`: [`InviteEntry`](InviteEntry.md)[]; `is_agent?`: `boolean`; `team_id?`: `string` \| `null`; \}The request body to invite a user to a team@@ -9,4 +9,5 @@ The request body to invite a user to a team| Property | Type | Description || ------ | ------ | ------ || <a id="property-invites"></a> `invites` | [`InviteEntry`](InviteEntry.md)[] | The invites to send, each with an email and tier |+| <a id="property-is_agent"></a> `is_agent?` | `boolean` | Invite these addresses as agents: an address with no account signs up as an agent and joins the team when it first signs in. || <a id="property-team_id"></a> `team_id?` | `string` \| `null` | The team the caller means to invite to. Invites always go to the caller's current team; when this names another team, nothing is sent and the request answers 409. |diff --git a/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/PasswordlessRequest.md b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/PasswordlessRequest.mdindex 40e11e8efe..cb715824a6 100644--- a/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/PasswordlessRequest.md+++ b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/PasswordlessRequest.md@@ -1,11 +1,12 @@# Type Alias: PasswordlessRequest-> **PasswordlessRequest** = \{ `email`: `string`; `redirect_uri`: `string`; `referral_code?`: `string` \| `null`; \}+> **PasswordlessRequest** = \{ `email`: `string`; `is_agent?`: `boolean`; `redirect_uri`: `string`; `referral_code?`: `string` \| `null`; \}## Properties| Property | Type | Description || ------ | ------ | ------ || <a id="property-email"></a> `email` | `string` | The email to initiate passwordless authentication for |+| <a id="property-is_agent"></a> `is_agent?` | `boolean` | Create an agent account if this address has no account yet. Otherwise `true` has no effect, and `false` reverts an agent flag nobody has proven: see `revert_unconfirmed_agent`. || <a id="property-redirect_uri"></a> `redirect_uri` | `string` | The redirect uri to redirect to after login || <a id="property-referral_code"></a> `referral_code?` | `string` \| `null` | The referral code |diff --git a/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/ProfilePictureUpload.md b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/ProfilePictureUpload.mdnew file mode 100644index 0000000000..7715c907c3--- /dev/null+++ b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/ProfilePictureUpload.md@@ -0,0 +1,12 @@+# Type Alias: ProfilePictureUpload++> **ProfilePictureUpload** = \{ `file_id`: `string`; `upload_url`: `string`; \}++Where to upload a new profile picture, and the file id to set afterwards.++## Properties++| Property | Type | Description |+| ------ | ------ | ------ |+| <a id="property-file_id"></a> `file_id` | `string` | Id to pass to `PUT /user/profile_picture/file` once uploaded. |+| <a id="property-upload_url"></a> `upload_url` | `string` | Expiring URL to `PUT` the image bytes to. |diff --git a/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/PutProfilePictureFileData.md b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/PutProfilePictureFileData.mdnew file mode 100644index 0000000000..483754c0ca--- /dev/null+++ b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/PutProfilePictureFileData.md@@ -0,0 +1,12 @@+# Type Alias: PutProfilePictureFileData++> **PutProfilePictureFileData** = \{ `body`: [`PutProfilePictureFileRequest`](PutProfilePictureFileRequest.md); `path?`: `never`; `query?`: `never`; `url`: `"/user/profile_picture/file"`; \}++## Properties++| Property | Type |+| ------ | ------ |+| <a id="property-body"></a> `body` | [`PutProfilePictureFileRequest`](PutProfilePictureFileRequest.md) |+| <a id="property-path"></a> `path?` | `never` |+| <a id="property-query"></a> `query?` | `never` |+| <a id="property-url"></a> `url` | `"/user/profile_picture/file"` |diff --git a/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/PutProfilePictureFileError.md b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/PutProfilePictureFileError.mdnew file mode 100644index 0000000000..5966a76999--- /dev/null+++ b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/PutProfilePictureFileError.md@@ -0,0 +1,3 @@+# Type Alias: PutProfilePictureFileError++> **PutProfilePictureFileError** = [`PutProfilePictureFileErrors`](PutProfilePictureFileErrors.md)\[keyof [`PutProfilePictureFileErrors`](PutProfilePictureFileErrors.md)\]diff --git a/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/PutProfilePictureFileErrors.md b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/PutProfilePictureFileErrors.mdnew file mode 100644index 0000000000..8db8247ef2--- /dev/null+++ b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/PutProfilePictureFileErrors.md@@ -0,0 +1,12 @@+# Type Alias: PutProfilePictureFileErrors++> **PutProfilePictureFileErrors** = \{ `400`: [`ErrorResponse`](ErrorResponse.md); `401`: `string`; `404`: [`ErrorResponse`](ErrorResponse.md); `500`: [`ErrorResponse`](ErrorResponse.md); \}++## Properties++| Property | Type | Description |+| ------ | ------ | ------ |+| <a id="property-400"></a> `400` | [`ErrorResponse`](ErrorResponse.md) | The file is not a supported image |+| <a id="property-401"></a> `401` | `string` | - |+| <a id="property-404"></a> `404` | [`ErrorResponse`](ErrorResponse.md) | The caller has no such file |+| <a id="property-500"></a> `500` | [`ErrorResponse`](ErrorResponse.md) | - |diff --git a/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/PutProfilePictureFileRequest.md b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/PutProfilePictureFileRequest.mdnew file mode 100644index 0000000000..58d217018f--- /dev/null+++ b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/PutProfilePictureFileRequest.md@@ -0,0 +1,9 @@+# Type Alias: PutProfilePictureFileRequest++> **PutProfilePictureFileRequest** = \{ `file_id`: `string`; \}++## Properties++| Property | Type | Description |+| ------ | ------ | ------ |+| <a id="property-file_id"></a> `file_id` | `string` | Id of an image the caller uploaded to static file storage. |diff --git a/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/PutProfilePictureFileResponse.md b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/PutProfilePictureFileResponse.mdnew file mode 100644index 0000000000..dfd27468ab--- /dev/null+++ b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/PutProfilePictureFileResponse.md@@ -0,0 +1,3 @@+# Type Alias: PutProfilePictureFileResponse++> **PutProfilePictureFileResponse** = [`PutProfilePictureFileResponses`](PutProfilePictureFileResponses.md)\[keyof [`PutProfilePictureFileResponses`](PutProfilePictureFileResponses.md)\]diff --git a/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/PutProfilePictureFileResponses.md b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/PutProfilePictureFileResponses.mdnew file mode 100644index 0000000000..bb64401808--- /dev/null+++ b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/PutProfilePictureFileResponses.md@@ -0,0 +1,9 @@+# Type Alias: PutProfilePictureFileResponses++> **PutProfilePictureFileResponses** = \{ `200`: [`EmptyResponse`](EmptyResponse.md); \}++## Properties++| Property | Type |+| ------ | ------ |+| <a id="property-200"></a> `200` | [`EmptyResponse`](EmptyResponse.md) |diff --git a/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/TeamInviteDetails.md b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/TeamInviteDetails.mdindex 95c0c9a5a7..38da455a63 100644--- a/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/TeamInviteDetails.md+++ b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/TeamInviteDetails.md@@ -1,6 +1,6 @@# Type Alias: TeamInviteDetails-> **TeamInviteDetails** = \{ `created_at`: `string`; `email`: `string`; `id`: `string`; `invited_by`: `string`; `last_sent_at`: `string`; `team_id`: `string`; `team_role`: [`TeamRole`](TeamRole.md); \}+> **TeamInviteDetails** = \{ `created_at`: `string`; `email`: `string`; `id`: `string`; `invited_by`: `string`; `is_agent`: `boolean`; `last_sent_at`: `string`; `team_id`: `string`; `team_role`: [`TeamRole`](TeamRole.md); \}Detailed information about a team invite@@ -12,6 +12,7 @@ Detailed information about a team invite| <a id="property-email"></a> `email` | `string` | The invited email || <a id="property-id"></a> `id` | `string` | The invite id || <a id="property-invited_by"></a> `invited_by` | `string` | The user who sent the invitation |+| <a id="property-is_agent"></a> `is_agent` | `boolean` | Whether the invite creates an agent account || <a id="property-last_sent_at"></a> `last_sent_at` | `string` | When the invite was last sent || <a id="property-team_id"></a> `team_id` | `string` | The team id || <a id="property-team_role"></a> `team_role` | [`TeamRole`](TeamRole.md) | The role being invited as |diff --git a/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/UserName.md b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/UserName.mdindex a7d3563fb0..321b614999 100644--- a/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/UserName.md+++ b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/UserName.md@@ -1,11 +1,12 @@# Type Alias: UserName-> **UserName** = \{ `first_name?`: `string` \| `null`; `id`: `string`; `last_name?`: `string` \| `null`; \}+> **UserName** = \{ `first_name?`: `string` \| `null`; `id`: `string`; `is_agent?`: `boolean`; `last_name?`: `string` \| `null`; \}## Properties-| Property | Type |-| ------ | ------ |-| <a id="property-first_name"></a> `first_name?` | `string` \| `null` |-| <a id="property-id"></a> `id` | `string` |-| <a id="property-last_name"></a> `last_name?` | `string` \| `null` |+| Property | Type | Description |+| ------ | ------ | ------ |+| <a id="property-first_name"></a> `first_name?` | `string` \| `null` | - |+| <a id="property-id"></a> `id` | `string` | - |+| <a id="property-is_agent"></a> `is_agent?` | `boolean` | Whether this is an agent account rather than a person. |+| <a id="property-last_name"></a> `last_name?` | `string` \| `null` | - |diff --git a/packages/sdk-docs/reference/generated/notification/types.gen/type-aliases/InviteToTeamMetadata.md b/packages/sdk-docs/reference/generated/notification/types.gen/type-aliases/InviteToTeamMetadata.mdindex e7c9655c04..0190a8a580 100644--- a/packages/sdk-docs/reference/generated/notification/types.gen/type-aliases/InviteToTeamMetadata.md+++ b/packages/sdk-docs/reference/generated/notification/types.gen/type-aliases/InviteToTeamMetadata.md@@ -1,6 +1,6 @@# Type Alias: InviteToTeamMetadata-> **InviteToTeamMetadata** = \{ `invitedBy`: `string`; `inviteePlan?`: [`InviteePlan`](InviteePlan.md); `reminder?`: `boolean`; `role?`: `string` \| `null`; `senderProfilePictureUrl?`: `string` \| `null`; `teamId`: `string`; `teamInviteId`: `string`; `teamName`: `string`; \}+> **InviteToTeamMetadata** = \{ `invitedBy`: `string`; `inviteePlan?`: [`InviteePlan`](InviteePlan.md); `isAgent?`: `boolean`; `reminder?`: `boolean`; `role?`: `string` \| `null`; `senderProfilePictureUrl?`: `string` \| `null`; `teamId`: `string`; `teamInviteId`: `string`; `teamName`: `string`; \}Metadata for when a user is invited to a team.@@ -10,6 +10,7 @@ Metadata for when a user is invited to a team.| ------ | ------ | ------ || <a id="property-invitedby"></a> `invitedBy` | `string` | The user who sent the invitation || <a id="property-inviteeplan"></a> `inviteePlan?` | [`InviteePlan`](InviteePlan.md) | What the invitee gets by joining, as the team stood when the invite was sent. |+| <a id="property-isagent"></a> `isAgent?` | `boolean` | Whether the invite creates an agent account. || <a id="property-reminder"></a> `reminder?` | `boolean` | Whether this email reminds the invitee of an invite they have not answered. || <a id="property-role"></a> `role?` | `string` \| `null` | Role/permission level in the team || <a id="property-senderprofilepictureurl"></a> `senderProfilePictureUrl?` | `string` \| `null` | The sender's profile picture URL, if available. |diff --git a/packages/sdk-docs/reference/modules.md b/packages/sdk-docs/reference/modules.mdindex b56d6afa67..6f38bd8351 100644--- a/packages/sdk-docs/reference/modules.md+++ b/packages/sdk-docs/reference/modules.md@@ -104,6 +104,7 @@- [src/entities/images/namespace](src/entities/images/namespace/README.md)- [src/entities/initiatives/initiative](src/entities/initiatives/initiative/README.md)- [src/entities/initiatives/namespace](src/entities/initiatives/namespace/README.md)+- [src/entities/me/namespace](src/entities/me/namespace/README.md)- [src/entities/meetings/meeting](src/entities/meetings/meeting/README.md)- [src/entities/meetings/namespace](src/entities/meetings/namespace/README.md)- [src/entities/messages/thread](src/entities/messages/thread/README.md)diff --git a/packages/sdk-docs/reference/src/entities/me/namespace/README.md b/packages/sdk-docs/reference/src/entities/me/namespace/README.mdnew file mode 100644index 0000000000..4db8d7a91f--- /dev/null+++ b/packages/sdk-docs/reference/src/entities/me/namespace/README.md@@ -0,0 +1,10 @@+# src/entities/me/namespace++## Classes++- [MeNamespace](classes/MeNamespace.md)++## Interfaces++- [UpdateMeOptions](interfaces/UpdateMeOptions.md)+- [UploadProfilePictureOptions](interfaces/UploadProfilePictureOptions.md)diff --git a/packages/sdk-docs/reference/src/entities/me/namespace/classes/MeNamespace.md b/packages/sdk-docs/reference/src/entities/me/namespace/classes/MeNamespace.mdnew file mode 100644index 0000000000..15e0492660--- /dev/null+++ b/packages/sdk-docs/reference/src/entities/me/namespace/classes/MeNamespace.md@@ -0,0 +1,68 @@+# Class: MeNamespace++The authenticated user's own profile.++## Constructors++### Constructor++> **new MeNamespace**(`client`): `MeNamespace`++#### Parameters++| Parameter | Type |+| ------ | ------ |+| `client` | `MacroClient` |++#### Returns++`MeNamespace`++## Methods++### update()++> **update**(`options`): `Promise`\<`void`\>++Set your display name and profile picture. Agents should do this after+signing in, so teammates can tell who they are working with.++#### Parameters++| Parameter | Type |+| ------ | ------ |+| `options` | [`UpdateMeOptions`](../interfaces/UpdateMeOptions.md) |++#### Returns++`Promise`\<`void`\>++#### Example++```ts+const image = await macro.me.uploadProfilePicture(bytes, {+ fileName: 'avatar.png',+ contentType: 'image/png',+});+await macro.me.update({ name: 'Research Agent', profilePicture: image });+```++***++### uploadProfilePicture()++> **uploadProfilePicture**(`data`, `options`): `Promise`\<[`StaticImage`](../../../images/image/classes/StaticImage.md)\>++Upload an image to use as your profile picture. This only stores it; pass+the result to [MeNamespace.update](#update) to start using it.++#### Parameters++| Parameter | Type |+| ------ | ------ |+| `data` | `Blob` \| `Uint8Array`\<`ArrayBuffer`\> |+| `options` | [`UploadProfilePictureOptions`](../interfaces/UploadProfilePictureOptions.md) |++#### Returns++`Promise`\<[`StaticImage`](../../../images/image/classes/StaticImage.md)\>diff --git a/packages/sdk-docs/reference/src/entities/me/namespace/interfaces/UpdateMeOptions.md b/packages/sdk-docs/reference/src/entities/me/namespace/interfaces/UpdateMeOptions.mdnew file mode 100644index 0000000000..f1c3e72a3b--- /dev/null+++ b/packages/sdk-docs/reference/src/entities/me/namespace/interfaces/UpdateMeOptions.md@@ -0,0 +1,10 @@+# Interface: UpdateMeOptions++What to change on the authenticated user's profile.++## Properties++| Property | Type | Description |+| ------ | ------ | ------ |+| <a id="property-name"></a> `name?` | `string` | Display name. The first word becomes the first name. |+| <a id="property-profilepicture"></a> `profilePicture?` | [`StaticImage`](../../../images/image/classes/StaticImage.md) | An image from [MeNamespace.uploadProfilePicture](../classes/MeNamespace.md#uploadprofilepicture). |diff --git a/packages/sdk-docs/reference/src/entities/me/namespace/interfaces/UploadProfilePictureOptions.md b/packages/sdk-docs/reference/src/entities/me/namespace/interfaces/UploadProfilePictureOptions.mdnew file mode 100644index 0000000000..dc2e32f291--- /dev/null+++ b/packages/sdk-docs/reference/src/entities/me/namespace/interfaces/UploadProfilePictureOptions.md@@ -0,0 +1,10 @@+# Interface: UploadProfilePictureOptions++How to store an uploaded profile picture.++## Properties++| Property | Type | Description |+| ------ | ------ | ------ |+| <a id="property-contenttype"></a> `contentType` | `string` | `image/png`, `image/jpeg`, `image/webp` or `image/gif`. |+| <a id="property-filename"></a> `fileName` | `string` | File name, such as `avatar.png`. |diff --git a/packages/sdk-docs/reference/src/entities/teams/team/classes/Team.md b/packages/sdk-docs/reference/src/entities/teams/team/classes/Team.mdindex 6431384161..c52f42756e 100644--- a/packages/sdk-docs/reference/src/entities/teams/team/classes/Team.md+++ b/packages/sdk-docs/reference/src/entities/teams/team/classes/Team.md@@ -21,7 +21,7 @@ field access, resolved from the caller's team memberships.### invite()-> **invite**(`emails`): `Promise`\<`boolean`\>+> **invite**(`emails`, `options?`): `Promise`\<`boolean`\>Invite people to this team by email; only invite addresses the user askedyou to invite. Each new address is emailed an invite in the caller's name.@@ -36,11 +36,19 @@ nothing, when that is no longer the caller's team. A team that limitsinviting to admins rejects other members, and teams without anenterprise plan accept a limited number of invites per day.+Pass `{ agent: true }` to invite the addresses as agents. An agent invite+to an address with no account creates an agent account when that address+signs in: it skips onboarding, gets an SDK token, and joins this team, using+a paid seat when the team has a subscription. An existing account keeps its+type and accepts like any other invite.+#### Parameters| Parameter | Type | Description || ------ | ------ | ------ || `emails` | `string` \| readonly `string`[] | One address or a list of addresses to invite. |+| `options?` | \{ `agent?`: `boolean`; \} | `agent` invites the addresses as agents. |+| `options.agent?` | `boolean` | - |#### Returnsdiff --git a/packages/sdk-docs/reference/src/entities/users/user/classes/User.md b/packages/sdk-docs/reference/src/entities/users/user/classes/User.mdindex 1225abee32..088cafd8cb 100644--- a/packages/sdk-docs/reference/src/entities/users/user/classes/User.md+++ b/packages/sdk-docs/reference/src/entities/users/user/classes/User.md@@ -91,6 +91,20 @@ entity's own detail, so there's nothing cached to invalidate.***+### isAgent()++> **isAgent**(): `Promise`\<`boolean`\>++Whether this user is an agent account rather than a person.++#### Returns++`Promise`\<`boolean`\>++`true` for an agent account.++***+### name()> **name**(): `Promise`\<`string` \| `undefined`\>diff --git a/packages/sdk-docs/reference/src/macro/README.md b/packages/sdk-docs/reference/src/macro/README.mdindex f9afa4df86..759579c310 100644--- a/packages/sdk-docs/reference/src/macro/README.md+++ b/packages/sdk-docs/reference/src/macro/README.md@@ -478,6 +478,12 @@ Re-exports [Meeting](../entities/meetings/meeting/classes/Meeting.md)***+### MeNamespace++Re-exports [MeNamespace](../entities/me/namespace/classes/MeNamespace.md)++***+### MentionableRe-exports [Mentionable](../mentions/interfaces/Mentionable.md)@@ -730,6 +736,18 @@ Re-exports [ToolApproval](../entities/agent-sessions/tool-approval/classes/ToolA***+### UpdateMeOptions++Re-exports [UpdateMeOptions](../entities/me/namespace/interfaces/UpdateMeOptions.md)++***++### UploadProfilePictureOptions++Re-exports [UploadProfilePictureOptions](../entities/me/namespace/interfaces/UploadProfilePictureOptions.md)++***+### UserApiKeyRe-exports [UserApiKey](../entities/api-keys/api-key/classes/UserApiKey.md)diff --git a/packages/sdk-docs/reference/src/macro/classes/Macro.md b/packages/sdk-docs/reference/src/macro/classes/Macro.mdindex 71b4aa6c11..fbf3efc42c 100644--- a/packages/sdk-docs/reference/src/macro/classes/Macro.md+++ b/packages/sdk-docs/reference/src/macro/classes/Macro.md@@ -50,6 +50,7 @@| <a id="property-harnesses"></a> `harnesses` | `readonly` | [`HarnessNamespace`](../../entities/harnesses/namespace/classes/HarnessNamespace.md) | harnesses resources and operations. || <a id="property-images"></a> `images` | `readonly` | [`ImagesNamespace`](../../entities/images/namespace/classes/ImagesNamespace.md) | Generate images with AI and attach them to messages. || <a id="property-initiatives"></a> `initiatives` | `readonly` | [`InitiativeNamespace`](../../entities/initiatives/namespace/classes/InitiativeNamespace.md) | initiatives resources and operations. |+| <a id="property-me"></a> `me` | `readonly` | [`MeNamespace`](../../entities/me/namespace/classes/MeNamespace.md) | Your own profile: set your name and profile picture. || <a id="property-meetings"></a> `meetings` | `readonly` | [`MeetingNamespace`](../../entities/meetings/namespace/classes/MeetingNamespace.md) | meetings resources and operations. || <a id="property-notifications"></a> `notifications` | `readonly` | [`NotificationNamespace`](../../entities/notifications/namespace/classes/NotificationNamespace.md) | - || <a id="property-pins"></a> `pins` | `readonly` | [`PinsNamespace`](../../entities/pins/namespace/classes/PinsNamespace.md) | - |diff --git a/packages/sdk/AGENTS.md b/packages/sdk/AGENTS.mdindex 1fbcafbc05..9b35ef0c23 100644--- a/packages/sdk/AGENTS.md+++ b/packages/sdk/AGENTS.md@@ -25,6 +25,10 @@ enforced by the ordinary backend APIs.`external_chat`) and their message/send/upload/participant handles.- `src/entities/whatsapp/`: the owner's WhatsApp account and chat list; `WhatsAppChat.add()`returns an `ExternalChat`.+- `src/entities/me/`: `macro.me.update()` sets the caller's name and profile+ picture; `macro.me.uploadProfilePicture()` stores the image through the auth+ service, because static file storage does not accept API keys. `team.invite(emails, { agent: true })`+ invites agents; their token only ever appears in the web app's setup modal.- `src/entities/images/`: `macro.images.generate()` (cognition`POST /images/generate`, admitted against the user's AI allowance) returns asized `GeneratedImage`; `StaticImage` handles attach to `channel.send(text,diff --git a/packages/sdk/README.md b/packages/sdk/README.mdindex 5b421ba5f1..44bf452ecc 100644--- a/packages/sdk/README.md+++ b/packages/sdk/README.md@@ -61,6 +61,15 @@ const macro = new Macro({An API key always acts as the user who minted it. `requestedAs` is bot-only.+#### Agent accounts++An agent has its own account and seat. Invite one with+`(await macro.teams.current()).invite('[email protected]', { agent: true })`, or, where it is enabled, sign+up with the "I'm an agent" option. After verifying its email, the agent sees its API key once in the+web app and uses it like any other key. It can set up its profile with+`macro.me.update({ name, profilePicture: await macro.me.uploadProfilePicture(bytes, options) })`+and mint more keys with `macro.apiKeys.create(name)`.+#### Bot token```tsdiff --git a/packages/sdk/generated/auth/index.ts b/packages/sdk/generated/auth/index.tsindex 9311612973..3d9f184749 100644--- a/packages/sdk/generated/auth/index.ts+++ b/packages/sdk/generated/auth/index.ts@@ -1,4 +1,4 @@// This file is auto-generated by @hey-api/openapi-tsexport { type Options, Sdk } from './sdk.gen';-export type { AbGroup, AgentApiKey, AgentApiKeyProvider, AiBillingErrorBody, AppleLoginData, AppleLoginError, AppleLoginErrors, AppleLoginRequest, AppleLoginResponse, AppleLoginResponses, AutoReloadDefaults, AutoReloadMonthlyBudget, AutoReloadSnapshot, CancelCodexLoginData, CancelCodexLoginResponse, CancelCodexLoginResponses, ChangePlanData, ChangePlanError, ChangePlanErrors, ChangePlanRequest, ChangePlanResponse, ChangePlanResponse2, ChangePlanResponses, CheckGithubLinkStatusData, CheckGithubLinkStatusError, CheckGithubLinkStatusErrors, CheckGithubLinkStatusResponse, CheckGithubLinkStatusResponses, CheckGmailLinkStatusData, CheckGmailLinkStatusError, CheckGmailLinkStatusErrors, CheckGmailLinkStatusResponse, CheckGmailLinkStatusResponses, CheckoutSessionMetadata, CheckoutSessionV2Response, ClientOptions, CodexConfigRequest, CodexConnectionStatus, CodexEnvironment, CodexEnvironmentRepository, CodexLoginPoll, CodexLoginStart, CodexLoginState, ConfigureCodexData, ConfigureCodexResponse, ConfigureCodexResponses, CreateAccountMergeRequest, CreateAiCreditCheckoutData, CreateAiCreditCheckoutError, CreateAiCreditCheckoutErrors, CreateAiCreditCheckoutResponse, CreateAiCreditCheckoutResponses, CreateCheckoutSessionV2Data, CreateCheckoutSessionV2Error, CreateCheckoutSessionV2Errors, CreateCheckoutSessionV2Request, CreateCheckoutSessionV2Response, CreateCheckoutSessionV2Responses, CreatedTeamInviteLinkResponse, CreateGtmInviteLinkData, CreateGtmInviteLinkError, CreateGtmInviteLinkErrors, CreateGtmInviteLinkRequest, CreateGtmInviteLinkResponse, CreateGtmInviteLinkResponses, CreateInProgressLinkData, CreateInProgressLinkError, CreateInProgressLinkErrors, CreateInProgressLinkResponse, CreateInProgressLinkResponse2, CreateInProgressLinkResponses, CreateMergeRequestData, CreateMergeRequestError, CreateMergeRequestErrors, CreateMergeRequestResponse, CreateMergeRequestResponses, CreatePortalSessionData, CreatePortalSessionError, CreatePortalSessionErrors, CreatePortalSessionRequest, CreatePortalSessionResponse, CreatePortalSessionResponses, CreateTeamData, CreateTeamError, CreateTeamErrors, CreateTeamInviteLinkData, CreateTeamInviteLinkError, CreateTeamInviteLinkErrors, CreateTeamInviteLinkResponse, CreateTeamInviteLinkResponses, CreateTeamRequest, CreateTeamResponse, CreateTeamResponses, CreditCheckoutRequestBody, CreditCheckoutResponse, CreditPurchaseRequestBody, CreditPurchaseResponse, CreditPurchaseSnapshot, CreditPurchaseStatus, CurrentSystemStatus, CursorApiKeyStatus, CursorModelOption, CursorModelsResponse, DeleteAgentApiKeyData, DeleteAgentApiKeyError, DeleteAgentApiKeyErrors, DeleteAgentApiKeyResponse, DeleteAgentApiKeyResponses, DeleteCursorApiKeyData, DeleteCursorApiKeyError, DeleteCursorApiKeyErrors, DeleteCursorApiKeyResponse, DeleteCursorApiKeyResponses, DeleteGithubLinkData, DeleteGithubLinkError, DeleteGithubLinkErrors, DeleteGithubLinkResponse, DeleteGithubLinkResponses, DeleteTeamData, DeleteTeamError, DeleteTeamErrors, DeleteTeamInviteHandlerData, DeleteTeamInviteHandlerError, DeleteTeamInviteHandlerErrors, DeleteTeamInviteHandlerResponses, DeleteTeamInviteLinkData, DeleteTeamInviteLinkError, DeleteTeamInviteLinkErrors, DeleteTeamInviteLinkResponse, DeleteTeamInviteLinkResponses, DeleteTeamResponses, DeleteUserData, DeleteUserError, DeleteUserErrors, DeleteUserResponse, DeleteUserResponses, DenyReason, DisconnectCodexData, DisconnectCodexResponse, DisconnectCodexResponses, EmailConnectionProviders, EmailConnectionProvidersData, EmailConnectionProvidersError, EmailConnectionProvidersErrors, EmailConnectionProvidersResponse, EmailConnectionProvidersResponses, EmptyResponse, EnrichedGithubPullRequest, EnrichGithubPullRequestsData, EnrichGithubPullRequestsError, EnrichGithubPullRequestsErrors, EnrichGithubPullRequestsProxyRequest, EnrichGithubPullRequestsResponse, EnrichGithubPullRequestsResponse2, EnrichGithubPullRequestsResponses, ErrorResponse, GenerateEmailLinkData, GenerateEmailLinkError, GenerateEmailLinkErrors, GenerateEmailLinkRequest, GenerateEmailLinkResponse, GenerateEmailLinkResponses, GenericSuccessResponse, GetAgentApiKeyData, GetAgentApiKeyError, GetAgentApiKeyErrors, GetAgentApiKeyResponse, GetAgentApiKeyResponses, GetAiBillingPlansData, GetAiBillingPlansResponse, GetAiBillingPlansResponses, GetAiBillingSummaryData, GetAiBillingSummaryError, GetAiBillingSummaryErrors, GetAiBillingSummaryResponse, GetAiBillingSummaryResponses, GetCodexConnectionData, GetCodexConnectionResponse, GetCodexConnectionResponses, GetCursorApiKeyData, GetCursorApiKeyError, GetCursorApiKeyErrors, GetCursorApiKeyResponse, GetCursorApiKeyResponses, GetGithubPullRequestMergeabilityData, GetGithubPullRequestMergeabilityError, GetGithubPullRequestMergeabilityErrors, GetGithubPullRequestMergeabilityResponse, GetGithubPullRequestMergeabilityResponses, GetGtmInviteOfferData, GetGtmInviteOfferError, GetGtmInviteOfferErrors, GetGtmInviteOfferResponse, GetGtmInviteOfferResponses, GetLegacyUserPermissionsData, GetLegacyUserPermissionsError, GetLegacyUserPermissionsErrors, GetLegacyUserPermissionsResponse, GetLegacyUserPermissionsResponse2, GetLegacyUserPermissionsResponses, GetNamesWithEmailRequestBody, GetPermissionsData, GetPermissionsError, GetPermissionsErrors, GetPermissionsResponse, GetPermissionsResponses, GetProfilePicturesRequestBody, GetReferralCodeData, GetReferralCodeError, GetReferralCodeErrors, GetReferralCodeResponse, GetReferralCodeResponses, GetSubscriptionStatusData, GetSubscriptionStatusError, GetSubscriptionStatusErrors, GetSubscriptionStatusResponse, GetSubscriptionStatusResponses, GetSystemStatusData, GetSystemStatusError, GetSystemStatusErrors, GetSystemStatusResponse, GetSystemStatusResponses, GetTeamByInviteLinkData, GetTeamByInviteLinkError, GetTeamByInviteLinkErrors, GetTeamByInviteLinkResponse, GetTeamByInviteLinkResponses, GetTeamData, GetTeamError, GetTeamErrors, GetTeamInviteLinkData, GetTeamInviteLinkError, GetTeamInviteLinkErrors, GetTeamInviteLinkResponse, GetTeamInviteLinkResponses, GetTeamInvitesData, GetTeamInvitesError, GetTeamInvitesErrors, GetTeamInvitesResponse, GetTeamInvitesResponses, GetTeamResponse, GetTeamResponses, GetTrialEligibilityData, GetTrialEligibilityError, GetTrialEligibilityErrors, GetTrialEligibilityResponse, GetTrialEligibilityResponses, GetUserInfo, GetUserInfoData, GetUserInfoError, GetUserInfoErrors, GetUserInfoResponse, GetUserInfoResponses, GetUserInvitesData, GetUserInvitesError, GetUserInvitesErrors, GetUserInvitesResponse, GetUserInvitesResponses, GetUserLanguageData, GetUserLanguageError, GetUserLanguageErrors, GetUserLanguageResponse, GetUserLanguageResponses, GetUserLinkExistsData, GetUserLinkExistsError, GetUserLinkExistsErrors, GetUserLinkExistsResponse, GetUserLinkExistsResponses, GetUserNameData, GetUserNameError, GetUserNameErrors, GetUserNameResponse, GetUserNameResponses, GetUserNamesData, GetUserNamesError, GetUserNamesErrors, GetUserNamesResponse, GetUserNamesResponses, GetUserNamesWithEmailData, GetUserNamesWithEmailError, GetUserNamesWithEmailErrors, GetUserNamesWithEmailResponse, GetUserNamesWithEmailResponses, GetUserOrganizationData, GetUserOrganizationError, GetUserOrganizationErrors, GetUserOrganizationResponse, GetUserOrganizationResponses, GetUserPermissionsData, GetUserPermissionsError, GetUserPermissionsErrors, GetUserPermissionsResponse, GetUserPermissionsResponses, GetUserQuotaData, GetUserQuotaError, GetUserQuotaErrors, GetUserQuotaResponse, GetUserQuotaResponses, GetUserTeamsData, GetUserTeamsError, GetUserTeamsErrors, GetUserTeamsResponse, GetUserTeamsResponses, GithubLinkStatusResponse, GithubMergeMethod, GithubPullRequestCheckRun, GithubPullRequestComment, GithubPullRequestLabel, GithubPullRequestMergeability, GithubPullRequestMergeabilityEntry, GithubPullRequestMergeabilityRequest, GithubPullRequestMergeabilityResponse, GithubPullRequestNumber, GithubPullRequestRef, GithubPullRequestReview, GithubPullRequestReviewState, GithubPullRequestState, GithubPullRequestStatus, GithubPullRequestUser, GmailLinkStatusResponse, GtmInviteLink, GtmInviteLinkList, GtmInviteLinkStatus, GtmInviteOffer, GtmInviteOfferStatus, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, InitGithubLinkData, InitGithubLinkError, InitGithubLinkErrors, InitGithubLinkResponse, InitGithubLinkResponse2, InitGithubLinkResponses, InitGmailLinkData, InitGmailLinkError, InitGmailLinkErrors, InitGmailLinkResponse, InitGmailLinkResponse2, InitGmailLinkResponses, InitOutlookLinkData, InitOutlookLinkError, InitOutlookLinkErrors, InitOutlookLinkResponse, InitOutlookLinkResponse2, InitOutlookLinkResponses, InviteEntry, InviteToTeamData, InviteToTeamError, InviteToTeamErrors, InviteToTeamRequest, InviteToTeamResponses, JoinTeamByInviteLinkData, JoinTeamByInviteLinkError, JoinTeamByInviteLinkErrors, JoinTeamByInviteLinkResponse, JoinTeamByInviteLinkResponse2, JoinTeamByInviteLinkResponses, JoinTeamData, JoinTeamError, JoinTeamErrors, JoinTeamResponses, Language, LinkShare, ListCodexEnvironmentsData, ListCodexEnvironmentsResponse, ListCodexEnvironmentsResponses, ListCursorModelsData, ListCursorModelsError, ListCursorModelsErrors, ListCursorModelsResponse, ListCursorModelsResponses, ListGtmInviteLinksData, ListGtmInviteLinksError, ListGtmInviteLinksErrors, ListGtmInviteLinksResponse, ListGtmInviteLinksResponses, ListSystemStatusHistoryData, ListSystemStatusHistoryError, ListSystemStatusHistoryErrors, ListSystemStatusHistoryResponse, ListSystemStatusHistoryResponses, LogoutData, LogoutResponse, LogoutResponses, MacroApiTokenData, MacroApiTokenError, MacroApiTokenErrors, MacroApiTokenResponse, MacroApiTokenResponse2, MacroApiTokenResponses, MergeGithubPullRequestData, MergeGithubPullRequestError, MergeGithubPullRequestErrors, MergeGithubPullRequestRequest, MergeGithubPullRequestResponse, MergeGithubPullRequestResponse2, MergeGithubPullRequestResponses, Oauth2CallbackData, Oauth2CallbackError, Oauth2CallbackErrors, Oauth2CallbackResponses, OauthRedirectData, OauthRedirectError, OauthRedirectErrors, OauthRedirectResponses, PasswordlessCallbackData, PasswordlessCallbackError, PasswordlessCallbackErrors, PasswordlessCallbackResponse, PasswordlessCallbackResponses, PasswordlessLoginData, PasswordlessLoginError, PasswordlessLoginErrors, PasswordlessLoginResponse, PasswordlessLoginResponses, PasswordlessRequest, PasswordlessStartedResponse, PasswordLoginData, PasswordLoginError, PasswordLoginErrors, PasswordLoginResponse, PasswordLoginResponses, PasswordRequest, PatchTeamCrmSettingsData, PatchTeamCrmSettingsError, PatchTeamCrmSettingsErrors, PatchTeamCrmSettingsRequest, PatchTeamCrmSettingsResponse, PatchTeamCrmSettingsResponse2, PatchTeamCrmSettingsResponses, PatchTeamData, PatchTeamError, PatchTeamErrors, PatchTeamMemberPlanData, PatchTeamMemberPlanError, PatchTeamMemberPlanErrors, PatchTeamMemberPlanRequest, PatchTeamMemberPlanResponse, PatchTeamMemberPlanResponses, PatchTeamRequest, PatchTeamResponses, PatchTeamUserRole, PatchUserGroupData, PatchUserGroupError, PatchUserGroupErrors, PatchUserGroupRequest, PatchUserGroupResponse, PatchUserGroupResponses, PatchUserOnboardingData, PatchUserOnboardingError, PatchUserOnboardingErrors, PatchUserOnboardingRequest, PatchUserOnboardingResponse, PatchUserOnboardingResponses, PatchUserTutorialData, PatchUserTutorialError, PatchUserTutorialErrors, PatchUserTutorialRequest, PatchUserTutorialResponse, PatchUserTutorialResponses, Permission, PlanCatalogEntry, PlanCatalogResponse, PlanTier, PollCodexLoginData, PollCodexLoginResponse, PollCodexLoginResponses, PostGetNamesRequestBody, PostProfilePicturesData, PostProfilePicturesError, PostProfilePicturesErrors, PostProfilePicturesResponse, PostProfilePicturesResponses, ProfilePictureQueryParams, ProfilePictures, PublicGtmInviteLink, PurchaseAiCreditsData, PurchaseAiCreditsError, PurchaseAiCreditsErrors, PurchaseAiCreditsResponse, PurchaseAiCreditsResponses, PutAgentApiKeyData, PutAgentApiKeyError, PutAgentApiKeyErrors, PutAgentApiKeyRequest, PutAgentApiKeyResponse, PutAgentApiKeyResponses, PutCursorApiKeyData, PutCursorApiKeyError, PutCursorApiKeyErrors, PutCursorApiKeyRequest, PutCursorApiKeyResponse, PutCursorApiKeyResponses, PutCursorDefaultModelData, PutCursorDefaultModelError, PutCursorDefaultModelErrors, PutCursorDefaultModelRequest, PutCursorDefaultModelResponse, PutCursorDefaultModelResponses, PutProfilePictureData, PutProfilePictureError, PutProfilePictureErrors, PutProfilePictureResponse, PutProfilePictureResponses, PutUserLanguageData, PutUserLanguageError, PutUserLanguageErrors, PutUserLanguageResponse, PutUserLanguageResponses, PutUserNameData, PutUserNameError, PutUserNameErrors, PutUserNameQueryParams, PutUserNameResponse, PutUserNameResponses, RedeemGtmInviteLinkData, RedeemGtmInviteLinkError, RedeemGtmInviteLinkErrors, RedeemGtmInviteLinkRequest, RedeemGtmInviteLinkResponse, RedeemGtmInviteLinkResponses, RefreshData, RefreshError, RefreshErrors, RefreshResponse, RefreshResponses, RejectInvitationData, RejectInvitationError, RejectInvitationErrors, RejectInvitationResponses, RemoveUserFromTeamData, RemoveUserFromTeamError, RemoveUserFromTeamErrors, RemoveUserFromTeamResponses, ResendFusionauthVerifyUserEmailData, ResendFusionauthVerifyUserEmailError, ResendFusionauthVerifyUserEmailErrors, ResendFusionauthVerifyUserEmailRequest, ResendFusionauthVerifyUserEmailResponse, ResendFusionauthVerifyUserEmailResponses, ResolveGtmInviteLinkData, ResolveGtmInviteLinkError, ResolveGtmInviteLinkErrors, ResolveGtmInviteLinkResponse, ResolveGtmInviteLinkResponses, RevokeGtmInviteLinkData, RevokeGtmInviteLinkError, RevokeGtmInviteLinkErrors, RevokeGtmInviteLinkResponse, RevokeGtmInviteLinkResponses, SavedAgentApiKey, ScheduledSeatPlan, SeatPlan, SendDomainNoticeResponse, SendInviteBody, SendMobileWelcomeEmailData, SendMobileWelcomeEmailError, SendMobileWelcomeEmailErrors, SendMobileWelcomeEmailRequest, SendMobileWelcomeEmailResponse, SendMobileWelcomeEmailResponse2, SendMobileWelcomeEmailResponses, SendReferralCodeData, SendReferralCodeError, SendReferralCodeErrors, SendReferralCodeResponse, SendReferralCodeResponses, SendTeamDomainNoticeData, SendTeamDomainNoticeError, SendTeamDomainNoticeErrors, SendTeamDomainNoticeResponse, SendTeamDomainNoticeResponses, SessionCreationData, SessionCreationError, SessionCreationErrors, SessionCreationResponse, SessionCreationResponses, SessionLoginData, SessionLoginError, SessionLoginErrors, SessionLoginResponse, SessionLoginResponses, SetGithubPullRequestDraftData, SetGithubPullRequestDraftError, SetGithubPullRequestDraftErrors, SetGithubPullRequestDraftRequest, SetGithubPullRequestDraftResponse, SetGithubPullRequestDraftResponse2, SetGithubPullRequestDraftResponses, SetGithubPullRequestStateData, SetGithubPullRequestStateError, SetGithubPullRequestStateErrors, SetGithubPullRequestStateRequest, SetGithubPullRequestStateResponse, SetGithubPullRequestStateResponse2, SetGithubPullRequestStateResponses, SetSystemStatusData, SetSystemStatusError, SetSystemStatusErrors, SetSystemStatusResponse, SetSystemStatusResponses, SsoLoginData, SsoLoginError, SsoLoginErrors, SsoLoginResponses, SsoRequiredResponse, StartCodexLoginData, StartCodexLoginResponse, StartCodexLoginResponses, StatusUpdate, StripeSessionResponse, SubscriptionStatus, SystemStatus, SystemStatusHistory, Team, TeamInviteDetails, TeamInviteLinkResponse, TeamInviteLinkTeam, TeamInviteLinkToken, TeamInviteLinkTokenRequest, TeamInvitesResponse, TeamMember, TeamPlan, TeamRole, TeamWithMembers, ToggleAutoJoinDomainResponse, ToggleNonAdminInvitesResponse, ToggleTeamAutoJoinDomainData, ToggleTeamAutoJoinDomainError, ToggleTeamAutoJoinDomainErrors, ToggleTeamAutoJoinDomainResponse, ToggleTeamAutoJoinDomainResponses, ToggleTeamNonAdminInvitesData, ToggleTeamNonAdminInvitesError, ToggleTeamNonAdminInvitesErrors, ToggleTeamNonAdminInvitesResponse, ToggleTeamNonAdminInvitesResponses, TrialEligibility, UpdateAiBillingAutoReloadData, UpdateAiBillingAutoReloadError, UpdateAiBillingAutoReloadErrors, UpdateAiBillingAutoReloadResponse, UpdateAiBillingAutoReloadResponses, UpdateAiBillingOverageData, UpdateAiBillingOverageError, UpdateAiBillingOverageErrors, UpdateAiBillingOverageResponse, UpdateAiBillingOverageResponses, UpdateAutoReloadRequest, UpdateOverageRequest, UpstreamErrorCode, UpstreamErrorResponse, UsageSnapshot, UserLanguage, UserLinkResponse, UserName, UserNames, UserOrganizationResponse, UserProfilePicture, UserQuota, UserTokensResponse, VerifyEmailLinkData, VerifyEmailLinkError, VerifyEmailLinkErrors, VerifyEmailLinkResponse, VerifyEmailLinkResponses, VerifyFusionauthUserEmailData, VerifyFusionauthUserEmailError, VerifyFusionauthUserEmailErrors, VerifyFusionauthUserEmailResponse, VerifyFusionauthUserEmailResponses, VerifyMergeRequestData, VerifyMergeRequestError, VerifyMergeRequestErrors, VerifyMergeRequestResponse, VerifyMergeRequestResponses } from './types.gen';+export type { AbGroup, AgentApiKey, AgentApiKeyProvider, AgentSetupData, AgentSetupError, AgentSetupErrors, AgentSetupResponse, AgentSetupResponse2, AgentSetupResponses, AiBillingErrorBody, AppleLoginData, AppleLoginError, AppleLoginErrors, AppleLoginRequest, AppleLoginResponse, AppleLoginResponses, AutoReloadDefaults, AutoReloadMonthlyBudget, AutoReloadSnapshot, CancelCodexLoginData, CancelCodexLoginResponse, CancelCodexLoginResponses, ChangePlanData, ChangePlanError, ChangePlanErrors, ChangePlanRequest, ChangePlanResponse, ChangePlanResponse2, ChangePlanResponses, CheckGithubLinkStatusData, CheckGithubLinkStatusError, CheckGithubLinkStatusErrors, CheckGithubLinkStatusResponse, CheckGithubLinkStatusResponses, CheckGmailLinkStatusData, CheckGmailLinkStatusError, CheckGmailLinkStatusErrors, CheckGmailLinkStatusResponse, CheckGmailLinkStatusResponses, CheckoutSessionMetadata, CheckoutSessionV2Response, ClientOptions, CodexConfigRequest, CodexConnectionStatus, CodexEnvironment, CodexEnvironmentRepository, CodexLoginPoll, CodexLoginStart, CodexLoginState, ConfigureCodexData, ConfigureCodexResponse, ConfigureCodexResponses, CreateAccountMergeRequest, CreateAiCreditCheckoutData, CreateAiCreditCheckoutError, CreateAiCreditCheckoutErrors, CreateAiCreditCheckoutResponse, CreateAiCreditCheckoutResponses, CreateCheckoutSessionV2Data, CreateCheckoutSessionV2Error, CreateCheckoutSessionV2Errors, CreateCheckoutSessionV2Request, CreateCheckoutSessionV2Response, CreateCheckoutSessionV2Responses, CreatedTeamInviteLinkResponse, CreateGtmInviteLinkData, CreateGtmInviteLinkError, CreateGtmInviteLinkErrors, CreateGtmInviteLinkRequest, CreateGtmInviteLinkResponse, CreateGtmInviteLinkResponses, CreateInProgressLinkData, CreateInProgressLinkError, CreateInProgressLinkErrors, CreateInProgressLinkResponse, CreateInProgressLinkResponse2, CreateInProgressLinkResponses, CreateMergeRequestData, CreateMergeRequestError, CreateMergeRequestErrors, CreateMergeRequestResponse, CreateMergeRequestResponses, CreatePortalSessionData, CreatePortalSessionError, CreatePortalSessionErrors, CreatePortalSessionRequest, CreatePortalSessionResponse, CreatePortalSessionResponses, CreateProfilePictureUploadData, CreateProfilePictureUploadError, CreateProfilePictureUploadErrors, CreateProfilePictureUploadRequest, CreateProfilePictureUploadResponse, CreateProfilePictureUploadResponses, CreateTeamData, CreateTeamError, CreateTeamErrors, CreateTeamInviteLinkData, CreateTeamInviteLinkError, CreateTeamInviteLinkErrors, CreateTeamInviteLinkResponse, CreateTeamInviteLinkResponses, CreateTeamRequest, CreateTeamResponse, CreateTeamResponses, CreditCheckoutRequestBody, CreditCheckoutResponse, CreditPurchaseRequestBody, CreditPurchaseResponse, CreditPurchaseSnapshot, CreditPurchaseStatus, CurrentSystemStatus, CursorApiKeyStatus, CursorModelOption, CursorModelsResponse, DeleteAgentApiKeyData, DeleteAgentApiKeyError, DeleteAgentApiKeyErrors, DeleteAgentApiKeyResponse, DeleteAgentApiKeyResponses, DeleteCursorApiKeyData, DeleteCursorApiKeyError, DeleteCursorApiKeyErrors, DeleteCursorApiKeyResponse, DeleteCursorApiKeyResponses, DeleteGithubLinkData, DeleteGithubLinkError, DeleteGithubLinkErrors, DeleteGithubLinkResponse, DeleteGithubLinkResponses, DeleteTeamData, DeleteTeamError, DeleteTeamErrors, DeleteTeamInviteHandlerData, DeleteTeamInviteHandlerError, DeleteTeamInviteHandlerErrors, DeleteTeamInviteHandlerResponses, DeleteTeamInviteLinkData, DeleteTeamInviteLinkError, DeleteTeamInviteLinkErrors, DeleteTeamInviteLinkResponse, DeleteTeamInviteLinkResponses, DeleteTeamResponses, DeleteUserData, DeleteUserError, DeleteUserErrors, DeleteUserResponse, DeleteUserResponses, DenyReason, DisconnectCodexData, DisconnectCodexResponse, DisconnectCodexResponses, EmailConnectionProviders, EmailConnectionProvidersData, EmailConnectionProvidersError, EmailConnectionProvidersErrors, EmailConnectionProvidersResponse, EmailConnectionProvidersResponses, EmptyResponse, EnrichedGithubPullRequest, EnrichGithubPullRequestsData, EnrichGithubPullRequestsError, EnrichGithubPullRequestsErrors, EnrichGithubPullRequestsProxyRequest, EnrichGithubPullRequestsResponse, EnrichGithubPullRequestsResponse2, EnrichGithubPullRequestsResponses, ErrorResponse, GenerateEmailLinkData, GenerateEmailLinkError, GenerateEmailLinkErrors, GenerateEmailLinkRequest, GenerateEmailLinkResponse, GenerateEmailLinkResponses, GenericSuccessResponse, GetAgentApiKeyData, GetAgentApiKeyError, GetAgentApiKeyErrors, GetAgentApiKeyResponse, GetAgentApiKeyResponses, GetAiBillingPlansData, GetAiBillingPlansResponse, GetAiBillingPlansResponses, GetAiBillingSummaryData, GetAiBillingSummaryError, GetAiBillingSummaryErrors, GetAiBillingSummaryResponse, GetAiBillingSummaryResponses, GetCodexConnectionData, GetCodexConnectionResponse, GetCodexConnectionResponses, GetCursorApiKeyData, GetCursorApiKeyError, GetCursorApiKeyErrors, GetCursorApiKeyResponse, GetCursorApiKeyResponses, GetGithubPullRequestMergeabilityData, GetGithubPullRequestMergeabilityError, GetGithubPullRequestMergeabilityErrors, GetGithubPullRequestMergeabilityResponse, GetGithubPullRequestMergeabilityResponses, GetGtmInviteOfferData, GetGtmInviteOfferError, GetGtmInviteOfferErrors, GetGtmInviteOfferResponse, GetGtmInviteOfferResponses, GetLegacyUserPermissionsData, GetLegacyUserPermissionsError, GetLegacyUserPermissionsErrors, GetLegacyUserPermissionsResponse, GetLegacyUserPermissionsResponse2, GetLegacyUserPermissionsResponses, GetNamesWithEmailRequestBody, GetPermissionsData, GetPermissionsError, GetPermissionsErrors, GetPermissionsResponse, GetPermissionsResponses, GetProfilePicturesRequestBody, GetReferralCodeData, GetReferralCodeError, GetReferralCodeErrors, GetReferralCodeResponse, GetReferralCodeResponses, GetSubscriptionStatusData, GetSubscriptionStatusError, GetSubscriptionStatusErrors, GetSubscriptionStatusResponse, GetSubscriptionStatusResponses, GetSystemStatusData, GetSystemStatusError, GetSystemStatusErrors, GetSystemStatusResponse, GetSystemStatusResponses, GetTeamByInviteLinkData, GetTeamByInviteLinkError, GetTeamByInviteLinkErrors, GetTeamByInviteLinkResponse, GetTeamByInviteLinkResponses, GetTeamData, GetTeamError, GetTeamErrors, GetTeamInviteLinkData, GetTeamInviteLinkError, GetTeamInviteLinkErrors, GetTeamInviteLinkResponse, GetTeamInviteLinkResponses, GetTeamInvitesData, GetTeamInvitesError, GetTeamInvitesErrors, GetTeamInvitesResponse, GetTeamInvitesResponses, GetTeamResponse, GetTeamResponses, GetTrialEligibilityData, GetTrialEligibilityError, GetTrialEligibilityErrors, GetTrialEligibilityResponse, GetTrialEligibilityResponses, GetUserInfo, GetUserInfoData, GetUserInfoError, GetUserInfoErrors, GetUserInfoResponse, GetUserInfoResponses, GetUserInvitesData, GetUserInvitesError, GetUserInvitesErrors, GetUserInvitesResponse, GetUserInvitesResponses, GetUserLanguageData, GetUserLanguageError, GetUserLanguageErrors, GetUserLanguageResponse, GetUserLanguageResponses, GetUserLinkExistsData, GetUserLinkExistsError, GetUserLinkExistsErrors, GetUserLinkExistsResponse, GetUserLinkExistsResponses, GetUserNameData, GetUserNameError, GetUserNameErrors, GetUserNameResponse, GetUserNameResponses, GetUserNamesData, GetUserNamesError, GetUserNamesErrors, GetUserNamesResponse, GetUserNamesResponses, GetUserNamesWithEmailData, GetUserNamesWithEmailError, GetUserNamesWithEmailErrors, GetUserNamesWithEmailResponse, GetUserNamesWithEmailResponses, GetUserOrganizationData, GetUserOrganizationError, GetUserOrganizationErrors, GetUserOrganizationResponse, GetUserOrganizationResponses, GetUserPermissionsData, GetUserPermissionsError, GetUserPermissionsErrors, GetUserPermissionsResponse, GetUserPermissionsResponses, GetUserQuotaData, GetUserQuotaError, GetUserQuotaErrors, GetUserQuotaResponse, GetUserQuotaResponses, GetUserTeamsData, GetUserTeamsError, GetUserTeamsErrors, GetUserTeamsResponse, GetUserTeamsResponses, GithubLinkStatusResponse, GithubMergeMethod, GithubPullRequestCheckRun, GithubPullRequestComment, GithubPullRequestLabel, GithubPullRequestMergeability, GithubPullRequestMergeabilityEntry, GithubPullRequestMergeabilityRequest, GithubPullRequestMergeabilityResponse, GithubPullRequestNumber, GithubPullRequestRef, GithubPullRequestReview, GithubPullRequestReviewState, GithubPullRequestState, GithubPullRequestStatus, GithubPullRequestUser, GmailLinkStatusResponse, GtmInviteLink, GtmInviteLinkList, GtmInviteLinkStatus, GtmInviteOffer, GtmInviteOfferStatus, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, InitGithubLinkData, InitGithubLinkError, InitGithubLinkErrors, InitGithubLinkResponse, InitGithubLinkResponse2, InitGithubLinkResponses, InitGmailLinkData, InitGmailLinkError, InitGmailLinkErrors, InitGmailLinkResponse, InitGmailLinkResponse2, InitGmailLinkResponses, InitOutlookLinkData, InitOutlookLinkError, InitOutlookLinkErrors, InitOutlookLinkResponse, InitOutlookLinkResponse2, InitOutlookLinkResponses, InviteEntry, InviteToTeamData, InviteToTeamError, InviteToTeamErrors, InviteToTeamRequest, InviteToTeamResponses, JoinTeamByInviteLinkData, JoinTeamByInviteLinkError, JoinTeamByInviteLinkErrors, JoinTeamByInviteLinkResponse, JoinTeamByInviteLinkResponse2, JoinTeamByInviteLinkResponses, JoinTeamData, JoinTeamError, JoinTeamErrors, JoinTeamResponses, Language, LinkShare, ListCodexEnvironmentsData, ListCodexEnvironmentsResponse, ListCodexEnvironmentsResponses, ListCursorModelsData, ListCursorModelsError, ListCursorModelsErrors, ListCursorModelsResponse, ListCursorModelsResponses, ListGtmInviteLinksData, ListGtmInviteLinksError, ListGtmInviteLinksErrors, ListGtmInviteLinksResponse, ListGtmInviteLinksResponses, ListSystemStatusHistoryData, ListSystemStatusHistoryError, ListSystemStatusHistoryErrors, ListSystemStatusHistoryResponse, ListSystemStatusHistoryResponses, LogoutData, LogoutResponse, LogoutResponses, MacroApiTokenData, MacroApiTokenError, MacroApiTokenErrors, MacroApiTokenResponse, MacroApiTokenResponse2, MacroApiTokenResponses, MergeGithubPullRequestData, MergeGithubPullRequestError, MergeGithubPullRequestErrors, MergeGithubPullRequestRequest, MergeGithubPullRequestResponse, MergeGithubPullRequestResponse2, MergeGithubPullRequestResponses, Oauth2CallbackData, Oauth2CallbackError, Oauth2CallbackErrors, Oauth2CallbackResponses, OauthRedirectData, OauthRedirectError, OauthRedirectErrors, OauthRedirectResponses, PasswordlessCallbackData, PasswordlessCallbackError, PasswordlessCallbackErrors, PasswordlessCallbackResponse, PasswordlessCallbackResponses, PasswordlessLoginData, PasswordlessLoginError, PasswordlessLoginErrors, PasswordlessLoginResponse, PasswordlessLoginResponses, PasswordlessRequest, PasswordlessStartedResponse, PasswordLoginData, PasswordLoginError, PasswordLoginErrors, PasswordLoginResponse, PasswordLoginResponses, PasswordRequest, PatchTeamCrmSettingsData, PatchTeamCrmSettingsError, PatchTeamCrmSettingsErrors, PatchTeamCrmSettingsRequest, PatchTeamCrmSettingsResponse, PatchTeamCrmSettingsResponse2, PatchTeamCrmSettingsResponses, PatchTeamData, PatchTeamError, PatchTeamErrors, PatchTeamMemberPlanData, PatchTeamMemberPlanError, PatchTeamMemberPlanErrors, PatchTeamMemberPlanRequest, PatchTeamMemberPlanResponse, PatchTeamMemberPlanResponses, PatchTeamRequest, PatchTeamResponses, PatchTeamUserRole, PatchUserGroupData, PatchUserGroupError, PatchUserGroupErrors, PatchUserGroupRequest, PatchUserGroupResponse, PatchUserGroupResponses, PatchUserOnboardingData, PatchUserOnboardingError, PatchUserOnboardingErrors, PatchUserOnboardingRequest, PatchUserOnboardingResponse, PatchUserOnboardingResponses, PatchUserTutorialData, PatchUserTutorialError, PatchUserTutorialErrors, PatchUserTutorialRequest, PatchUserTutorialResponse, PatchUserTutorialResponses, Permission, PlanCatalogEntry, PlanCatalogResponse, PlanTier, PollCodexLoginData, PollCodexLoginResponse, PollCodexLoginResponses, PostGetNamesRequestBody, PostProfilePicturesData, PostProfilePicturesError, PostProfilePicturesErrors, PostProfilePicturesResponse, PostProfilePicturesResponses, ProfilePictureQueryParams, ProfilePictures, ProfilePictureUpload, PublicGtmInviteLink, PurchaseAiCreditsData, PurchaseAiCreditsError, PurchaseAiCreditsErrors, PurchaseAiCreditsResponse, PurchaseAiCreditsResponses, PutAgentApiKeyData, PutAgentApiKeyError, PutAgentApiKeyErrors, PutAgentApiKeyRequest, PutAgentApiKeyResponse, PutAgentApiKeyResponses, PutCursorApiKeyData, PutCursorApiKeyError, PutCursorApiKeyErrors, PutCursorApiKeyRequest, PutCursorApiKeyResponse, PutCursorApiKeyResponses, PutCursorDefaultModelData, PutCursorDefaultModelError, PutCursorDefaultModelErrors, PutCursorDefaultModelRequest, PutCursorDefaultModelResponse, PutCursorDefaultModelResponses, PutProfilePictureData, PutProfilePictureError, PutProfilePictureErrors, PutProfilePictureFileData, PutProfilePictureFileError, PutProfilePictureFileErrors, PutProfilePictureFileRequest, PutProfilePictureFileResponse, PutProfilePictureFileResponses, PutProfilePictureResponse, PutProfilePictureResponses, PutUserLanguageData, PutUserLanguageError, PutUserLanguageErrors, PutUserLanguageResponse, PutUserLanguageResponses, PutUserNameData, PutUserNameError, PutUserNameErrors, PutUserNameQueryParams, PutUserNameResponse, PutUserNameResponses, RedeemGtmInviteLinkData, RedeemGtmInviteLinkError, RedeemGtmInviteLinkErrors, RedeemGtmInviteLinkRequest, RedeemGtmInviteLinkResponse, RedeemGtmInviteLinkResponses, RefreshData, RefreshError, RefreshErrors, RefreshResponse, RefreshResponses, RejectInvitationData, RejectInvitationError, RejectInvitationErrors, RejectInvitationResponses, RemoveUserFromTeamData, RemoveUserFromTeamError, RemoveUserFromTeamErrors, RemoveUserFromTeamResponses, ResendFusionauthVerifyUserEmailData, ResendFusionauthVerifyUserEmailError, ResendFusionauthVerifyUserEmailErrors, ResendFusionauthVerifyUserEmailRequest, ResendFusionauthVerifyUserEmailResponse, ResendFusionauthVerifyUserEmailResponses, ResolveGtmInviteLinkData, ResolveGtmInviteLinkError, ResolveGtmInviteLinkErrors, ResolveGtmInviteLinkResponse, ResolveGtmInviteLinkResponses, RevokeGtmInviteLinkData, RevokeGtmInviteLinkError, RevokeGtmInviteLinkErrors, RevokeGtmInviteLinkResponse, RevokeGtmInviteLinkResponses, SavedAgentApiKey, ScheduledSeatPlan, SeatPlan, SendDomainNoticeResponse, SendInviteBody, SendMobileWelcomeEmailData, SendMobileWelcomeEmailError, SendMobileWelcomeEmailErrors, SendMobileWelcomeEmailRequest, SendMobileWelcomeEmailResponse, SendMobileWelcomeEmailResponse2, SendMobileWelcomeEmailResponses, SendReferralCodeData, SendReferralCodeError, SendReferralCodeErrors, SendReferralCodeResponse, SendReferralCodeResponses, SendTeamDomainNoticeData, SendTeamDomainNoticeError, SendTeamDomainNoticeErrors, SendTeamDomainNoticeResponse, SendTeamDomainNoticeResponses, SessionCreationData, SessionCreationError, SessionCreationErrors, SessionCreationResponse, SessionCreationResponses, SessionLoginData, SessionLoginError, SessionLoginErrors, SessionLoginResponse, SessionLoginResponses, SetGithubPullRequestDraftData, SetGithubPullRequestDraftError, SetGithubPullRequestDraftErrors, SetGithubPullRequestDraftRequest, SetGithubPullRequestDraftResponse, SetGithubPullRequestDraftResponse2, SetGithubPullRequestDraftResponses, SetGithubPullRequestStateData, SetGithubPullRequestStateError, SetGithubPullRequestStateErrors, SetGithubPullRequestStateRequest, SetGithubPullRequestStateResponse, SetGithubPullRequestStateResponse2, SetGithubPullRequestStateResponses, SetSystemStatusData, SetSystemStatusError, SetSystemStatusErrors, SetSystemStatusResponse, SetSystemStatusResponses, SsoLoginData, SsoLoginError, SsoLoginErrors, SsoLoginResponses, SsoRequiredResponse, StartCodexLoginData, StartCodexLoginResponse, StartCodexLoginResponses, StatusUpdate, StripeSessionResponse, SubscriptionStatus, SystemStatus, SystemStatusHistory, Team, TeamInviteDetails, TeamInviteLinkResponse, TeamInviteLinkTeam, TeamInviteLinkToken, TeamInviteLinkTokenRequest, TeamInvitesResponse, TeamMember, TeamPlan, TeamRole, TeamWithMembers, ToggleAutoJoinDomainResponse, ToggleNonAdminInvitesResponse, ToggleTeamAutoJoinDomainData, ToggleTeamAutoJoinDomainError, ToggleTeamAutoJoinDomainErrors, ToggleTeamAutoJoinDomainResponse, ToggleTeamAutoJoinDomainResponses, ToggleTeamNonAdminInvitesData, ToggleTeamNonAdminInvitesError, ToggleTeamNonAdminInvitesErrors, ToggleTeamNonAdminInvitesResponse, ToggleTeamNonAdminInvitesResponses, TrialEligibility, UpdateAiBillingAutoReloadData, UpdateAiBillingAutoReloadError, UpdateAiBillingAutoReloadErrors, UpdateAiBillingAutoReloadResponse, UpdateAiBillingAutoReloadResponses, UpdateAiBillingOverageData, UpdateAiBillingOverageError, UpdateAiBillingOverageErrors, UpdateAiBillingOverageResponse, UpdateAiBillingOverageResponses, UpdateAutoReloadRequest, UpdateOverageRequest, UpstreamErrorCode, UpstreamErrorResponse, UsageSnapshot, UserLanguage, UserLinkResponse, UserName, UserNames, UserOrganizationResponse, UserProfilePicture, UserQuota, UserTokensResponse, VerifyEmailLinkData, VerifyEmailLinkError, VerifyEmailLinkErrors, VerifyEmailLinkResponse, VerifyEmailLinkResponses, VerifyFusionauthUserEmailData, VerifyFusionauthUserEmailError, VerifyFusionauthUserEmailErrors, VerifyFusionauthUserEmailResponse, VerifyFusionauthUserEmailResponses, VerifyMergeRequestData, VerifyMergeRequestError, VerifyMergeRequestErrors, VerifyMergeRequestResponse, VerifyMergeRequestResponses } from './types.gen';diff --git a/packages/sdk/generated/auth/sdk.gen.ts b/packages/sdk/generated/auth/sdk.gen.tsindex e28112f5e9..1055d02196 100644--- a/packages/sdk/generated/auth/sdk.gen.ts+++ b/packages/sdk/generated/auth/sdk.gen.ts@@ -2,7 +2,7 @@import type { Client, ClientMeta, Options as Options2, RequestResult, TDataShape } from './client';import { client } from './client.gen';-import type { AppleLoginData, AppleLoginErrors, AppleLoginResponses, CancelCodexLoginData, CancelCodexLoginResponses, ChangePlanData, ChangePlanErrors, ChangePlanResponses, CheckGithubLinkStatusData, CheckGithubLinkStatusErrors, CheckGithubLinkStatusResponses, CheckGmailLinkStatusData, CheckGmailLinkStatusErrors, CheckGmailLinkStatusResponses, ConfigureCodexData, ConfigureCodexResponses, CreateAiCreditCheckoutData, CreateAiCreditCheckoutErrors, CreateAiCreditCheckoutResponses, CreateCheckoutSessionV2Data, CreateCheckoutSessionV2Errors, CreateCheckoutSessionV2Responses, CreateGtmInviteLinkData, CreateGtmInviteLinkErrors, CreateGtmInviteLinkResponses, CreateInProgressLinkData, CreateInProgressLinkErrors, CreateInProgressLinkResponses, CreateMergeRequestData, CreateMergeRequestErrors, CreateMergeRequestResponses, CreatePortalSessionData, CreatePortalSessionErrors, CreatePortalSessionResponses, CreateTeamData, CreateTeamErrors, CreateTeamInviteLinkData, CreateTeamInviteLinkErrors, CreateTeamInviteLinkResponses, CreateTeamResponses, DeleteAgentApiKeyData, DeleteAgentApiKeyErrors, DeleteAgentApiKeyResponses, DeleteCursorApiKeyData, DeleteCursorApiKeyErrors, DeleteCursorApiKeyResponses, DeleteGithubLinkData, DeleteGithubLinkErrors, DeleteGithubLinkResponses, DeleteTeamData, DeleteTeamErrors, DeleteTeamInviteHandlerData, DeleteTeamInviteHandlerErrors, DeleteTeamInviteHandlerResponses, DeleteTeamInviteLinkData, DeleteTeamInviteLinkErrors, DeleteTeamInviteLinkResponses, DeleteTeamResponses, DeleteUserData, DeleteUserErrors, DeleteUserResponses, DisconnectCodexData, DisconnectCodexResponses, EmailConnectionProvidersData, EmailConnectionProvidersErrors, EmailConnectionProvidersResponses, EnrichGithubPullRequestsData, EnrichGithubPullRequestsErrors, EnrichGithubPullRequestsResponses, GenerateEmailLinkData, GenerateEmailLinkErrors, GenerateEmailLinkResponses, GetAgentApiKeyData, GetAgentApiKeyErrors, GetAgentApiKeyResponses, GetAiBillingPlansData, GetAiBillingPlansResponses, GetAiBillingSummaryData, GetAiBillingSummaryErrors, GetAiBillingSummaryResponses, GetCodexConnectionData, GetCodexConnectionResponses, GetCursorApiKeyData, GetCursorApiKeyErrors, GetCursorApiKeyResponses, GetGithubPullRequestMergeabilityData, GetGithubPullRequestMergeabilityErrors, GetGithubPullRequestMergeabilityResponses, GetGtmInviteOfferData, GetGtmInviteOfferErrors, GetGtmInviteOfferResponses, GetLegacyUserPermissionsData, GetLegacyUserPermissionsErrors, GetLegacyUserPermissionsResponses, GetPermissionsData, GetPermissionsErrors, GetPermissionsResponses, GetReferralCodeData, GetReferralCodeErrors, GetReferralCodeResponses, GetSubscriptionStatusData, GetSubscriptionStatusErrors, GetSubscriptionStatusResponses, GetSystemStatusData, GetSystemStatusErrors, GetSystemStatusResponses, GetTeamByInviteLinkData, GetTeamByInviteLinkErrors, GetTeamByInviteLinkResponses, GetTeamData, GetTeamErrors, GetTeamInviteLinkData, GetTeamInviteLinkErrors, GetTeamInviteLinkResponses, GetTeamInvitesData, GetTeamInvitesErrors, GetTeamInvitesResponses, GetTeamResponses, GetTrialEligibilityData, GetTrialEligibilityErrors, GetTrialEligibilityResponses, GetUserInfoData, GetUserInfoErrors, GetUserInfoResponses, GetUserInvitesData, GetUserInvitesErrors, GetUserInvitesResponses, GetUserLanguageData, GetUserLanguageErrors, GetUserLanguageResponses, GetUserLinkExistsData, GetUserLinkExistsErrors, GetUserLinkExistsResponses, GetUserNameData, GetUserNameErrors, GetUserNameResponses, GetUserNamesData, GetUserNamesErrors, GetUserNamesResponses, GetUserNamesWithEmailData, GetUserNamesWithEmailErrors, GetUserNamesWithEmailResponses, GetUserOrganizationData, GetUserOrganizationErrors, GetUserOrganizationResponses, GetUserPermissionsData, GetUserPermissionsErrors, GetUserPermissionsResponses, GetUserQuotaData, GetUserQuotaErrors, GetUserQuotaResponses, GetUserTeamsData, GetUserTeamsErrors, GetUserTeamsResponses, HealthHandlerData, HealthHandlerResponses, InitGithubLinkData, InitGithubLinkErrors, InitGithubLinkResponses, InitGmailLinkData, InitGmailLinkErrors, InitGmailLinkResponses, InitOutlookLinkData, InitOutlookLinkErrors, InitOutlookLinkResponses, InviteToTeamData, InviteToTeamErrors, InviteToTeamResponses, JoinTeamByInviteLinkData, JoinTeamByInviteLinkErrors, JoinTeamByInviteLinkResponses, JoinTeamData, JoinTeamErrors, JoinTeamResponses, ListCodexEnvironmentsData, ListCodexEnvironmentsResponses, ListCursorModelsData, ListCursorModelsErrors, ListCursorModelsResponses, ListGtmInviteLinksData, ListGtmInviteLinksErrors, ListGtmInviteLinksResponses, ListSystemStatusHistoryData, ListSystemStatusHistoryErrors, ListSystemStatusHistoryResponses, LogoutData, LogoutResponses, MacroApiTokenData, MacroApiTokenErrors, MacroApiTokenResponses, MergeGithubPullRequestData, MergeGithubPullRequestErrors, MergeGithubPullRequestResponses, Oauth2CallbackData, Oauth2CallbackErrors, Oauth2CallbackResponses, OauthRedirectData, OauthRedirectErrors, OauthRedirectResponses, PasswordlessCallbackData, PasswordlessCallbackErrors, PasswordlessCallbackResponses, PasswordlessLoginData, PasswordlessLoginErrors, PasswordlessLoginResponses, PasswordLoginData, PasswordLoginErrors, PasswordLoginResponses, PatchTeamCrmSettingsData, PatchTeamCrmSettingsErrors, PatchTeamCrmSettingsResponses, PatchTeamData, PatchTeamErrors, PatchTeamMemberPlanData, PatchTeamMemberPlanErrors, PatchTeamMemberPlanResponses, PatchTeamResponses, PatchUserGroupData, PatchUserGroupErrors, PatchUserGroupResponses, PatchUserOnboardingData, PatchUserOnboardingErrors, PatchUserOnboardingResponses, PatchUserTutorialData, PatchUserTutorialErrors, PatchUserTutorialResponses, PollCodexLoginData, PollCodexLoginResponses, PostProfilePicturesData, PostProfilePicturesErrors, PostProfilePicturesResponses, PurchaseAiCreditsData, PurchaseAiCreditsErrors, PurchaseAiCreditsResponses, PutAgentApiKeyData, PutAgentApiKeyErrors, PutAgentApiKeyResponses, PutCursorApiKeyData, PutCursorApiKeyErrors, PutCursorApiKeyResponses, PutCursorDefaultModelData, PutCursorDefaultModelErrors, PutCursorDefaultModelResponses, PutProfilePictureData, PutProfilePictureErrors, PutProfilePictureResponses, PutUserLanguageData, PutUserLanguageErrors, PutUserLanguageResponses, PutUserNameData, PutUserNameErrors, PutUserNameResponses, RedeemGtmInviteLinkData, RedeemGtmInviteLinkErrors, RedeemGtmInviteLinkResponses, RefreshData, RefreshErrors, RefreshResponses, RejectInvitationData, RejectInvitationErrors, RejectInvitationResponses, RemoveUserFromTeamData, RemoveUserFromTeamErrors, RemoveUserFromTeamResponses, ResendFusionauthVerifyUserEmailData, ResendFusionauthVerifyUserEmailErrors, ResendFusionauthVerifyUserEmailResponses, ResolveGtmInviteLinkData, ResolveGtmInviteLinkErrors, ResolveGtmInviteLinkResponses, RevokeGtmInviteLinkData, RevokeGtmInviteLinkErrors, RevokeGtmInviteLinkResponses, SendMobileWelcomeEmailData, SendMobileWelcomeEmailErrors, SendMobileWelcomeEmailResponses, SendReferralCodeData, SendReferralCodeErrors, SendReferralCodeResponses, SendTeamDomainNoticeData, SendTeamDomainNoticeErrors, SendTeamDomainNoticeResponses, SessionCreationData, SessionCreationErrors, SessionCreationResponses, SessionLoginData, SessionLoginErrors, SessionLoginResponses, SetGithubPullRequestDraftData, SetGithubPullRequestDraftErrors, SetGithubPullRequestDraftResponses, SetGithubPullRequestStateData, SetGithubPullRequestStateErrors, SetGithubPullRequestStateResponses, SetSystemStatusData, SetSystemStatusErrors, SetSystemStatusResponses, SsoLoginData, SsoLoginErrors, SsoLoginResponses, StartCodexLoginData, StartCodexLoginResponses, ToggleTeamAutoJoinDomainData, ToggleTeamAutoJoinDomainErrors, ToggleTeamAutoJoinDomainResponses, ToggleTeamNonAdminInvitesData, ToggleTeamNonAdminInvitesErrors, ToggleTeamNonAdminInvitesResponses, UpdateAiBillingAutoReloadData, UpdateAiBillingAutoReloadErrors, UpdateAiBillingAutoReloadResponses, UpdateAiBillingOverageData, UpdateAiBillingOverageErrors, UpdateAiBillingOverageResponses, VerifyEmailLinkData, VerifyEmailLinkErrors, VerifyEmailLinkResponses, VerifyFusionauthUserEmailData, VerifyFusionauthUserEmailErrors, VerifyFusionauthUserEmailResponses, VerifyMergeRequestData, VerifyMergeRequestErrors, VerifyMergeRequestResponses } from './types.gen';+import type { AgentSetupData, AgentSetupErrors, AgentSetupResponses, AppleLoginData, AppleLoginErrors, AppleLoginResponses, CancelCodexLoginData, CancelCodexLoginResponses, ChangePlanData, ChangePlanErrors, ChangePlanResponses, CheckGithubLinkStatusData, CheckGithubLinkStatusErrors, CheckGithubLinkStatusResponses, CheckGmailLinkStatusData, CheckGmailLinkStatusErrors, CheckGmailLinkStatusResponses, ConfigureCodexData, ConfigureCodexResponses, CreateAiCreditCheckoutData, CreateAiCreditCheckoutErrors, CreateAiCreditCheckoutResponses, CreateCheckoutSessionV2Data, CreateCheckoutSessionV2Errors, CreateCheckoutSessionV2Responses, CreateGtmInviteLinkData, CreateGtmInviteLinkErrors, CreateGtmInviteLinkResponses, CreateInProgressLinkData, CreateInProgressLinkErrors, CreateInProgressLinkResponses, CreateMergeRequestData, CreateMergeRequestErrors, CreateMergeRequestResponses, CreatePortalSessionData, CreatePortalSessionErrors, CreatePortalSessionResponses, CreateProfilePictureUploadData, CreateProfilePictureUploadErrors, CreateProfilePictureUploadResponses, CreateTeamData, CreateTeamErrors, CreateTeamInviteLinkData, CreateTeamInviteLinkErrors, CreateTeamInviteLinkResponses, CreateTeamResponses, DeleteAgentApiKeyData, DeleteAgentApiKeyErrors, DeleteAgentApiKeyResponses, DeleteCursorApiKeyData, DeleteCursorApiKeyErrors, DeleteCursorApiKeyResponses, DeleteGithubLinkData, DeleteGithubLinkErrors, DeleteGithubLinkResponses, DeleteTeamData, DeleteTeamErrors, DeleteTeamInviteHandlerData, DeleteTeamInviteHandlerErrors, DeleteTeamInviteHandlerResponses, DeleteTeamInviteLinkData, DeleteTeamInviteLinkErrors, DeleteTeamInviteLinkResponses, DeleteTeamResponses, DeleteUserData, DeleteUserErrors, DeleteUserResponses, DisconnectCodexData, DisconnectCodexResponses, EmailConnectionProvidersData, EmailConnectionProvidersErrors, EmailConnectionProvidersResponses, EnrichGithubPullRequestsData, EnrichGithubPullRequestsErrors, EnrichGithubPullRequestsResponses, GenerateEmailLinkData, GenerateEmailLinkErrors, GenerateEmailLinkResponses, GetAgentApiKeyData, GetAgentApiKeyErrors, GetAgentApiKeyResponses, GetAiBillingPlansData, GetAiBillingPlansResponses, GetAiBillingSummaryData, GetAiBillingSummaryErrors, GetAiBillingSummaryResponses, GetCodexConnectionData, GetCodexConnectionResponses, GetCursorApiKeyData, GetCursorApiKeyErrors, GetCursorApiKeyResponses, GetGithubPullRequestMergeabilityData, GetGithubPullRequestMergeabilityErrors, GetGithubPullRequestMergeabilityResponses, GetGtmInviteOfferData, GetGtmInviteOfferErrors, GetGtmInviteOfferResponses, GetLegacyUserPermissionsData, GetLegacyUserPermissionsErrors, GetLegacyUserPermissionsResponses, GetPermissionsData, GetPermissionsErrors, GetPermissionsResponses, GetReferralCodeData, GetReferralCodeErrors, GetReferralCodeResponses, GetSubscriptionStatusData, GetSubscriptionStatusErrors, GetSubscriptionStatusResponses, GetSystemStatusData, GetSystemStatusErrors, GetSystemStatusResponses, GetTeamByInviteLinkData, GetTeamByInviteLinkErrors, GetTeamByInviteLinkResponses, GetTeamData, GetTeamErrors, GetTeamInviteLinkData, GetTeamInviteLinkErrors, GetTeamInviteLinkResponses, GetTeamInvitesData, GetTeamInvitesErrors, GetTeamInvitesResponses, GetTeamResponses, GetTrialEligibilityData, GetTrialEligibilityErrors, GetTrialEligibilityResponses, GetUserInfoData, GetUserInfoErrors, GetUserInfoResponses, GetUserInvitesData, GetUserInvitesErrors, GetUserInvitesResponses, GetUserLanguageData, GetUserLanguageErrors, GetUserLanguageResponses, GetUserLinkExistsData, GetUserLinkExistsErrors, GetUserLinkExistsResponses, GetUserNameData, GetUserNameErrors, GetUserNameResponses, GetUserNamesData, GetUserNamesErrors, GetUserNamesResponses, GetUserNamesWithEmailData, GetUserNamesWithEmailErrors, GetUserNamesWithEmailResponses, GetUserOrganizationData, GetUserOrganizationErrors, GetUserOrganizationResponses, GetUserPermissionsData, GetUserPermissionsErrors, GetUserPermissionsResponses, GetUserQuotaData, GetUserQuotaErrors, GetUserQuotaResponses, GetUserTeamsData, GetUserTeamsErrors, GetUserTeamsResponses, HealthHandlerData, HealthHandlerResponses, InitGithubLinkData, InitGithubLinkErrors, InitGithubLinkResponses, InitGmailLinkData, InitGmailLinkErrors, InitGmailLinkResponses, InitOutlookLinkData, InitOutlookLinkErrors, InitOutlookLinkResponses, InviteToTeamData, InviteToTeamErrors, InviteToTeamResponses, JoinTeamByInviteLinkData, JoinTeamByInviteLinkErrors, JoinTeamByInviteLinkResponses, JoinTeamData, JoinTeamErrors, JoinTeamResponses, ListCodexEnvironmentsData, ListCodexEnvironmentsResponses, ListCursorModelsData, ListCursorModelsErrors, ListCursorModelsResponses, ListGtmInviteLinksData, ListGtmInviteLinksErrors, ListGtmInviteLinksResponses, ListSystemStatusHistoryData, ListSystemStatusHistoryErrors, ListSystemStatusHistoryResponses, LogoutData, LogoutResponses, MacroApiTokenData, MacroApiTokenErrors, MacroApiTokenResponses, MergeGithubPullRequestData, MergeGithubPullRequestErrors, MergeGithubPullRequestResponses, Oauth2CallbackData, Oauth2CallbackErrors, Oauth2CallbackResponses, OauthRedirectData, OauthRedirectErrors, OauthRedirectResponses, PasswordlessCallbackData, PasswordlessCallbackErrors, PasswordlessCallbackResponses, PasswordlessLoginData, PasswordlessLoginErrors, PasswordlessLoginResponses, PasswordLoginData, PasswordLoginErrors, PasswordLoginResponses, PatchTeamCrmSettingsData, PatchTeamCrmSettingsErrors, PatchTeamCrmSettingsResponses, PatchTeamData, PatchTeamErrors, PatchTeamMemberPlanData, PatchTeamMemberPlanErrors, PatchTeamMemberPlanResponses, PatchTeamResponses, PatchUserGroupData, PatchUserGroupErrors, PatchUserGroupResponses, PatchUserOnboardingData, PatchUserOnboardingErrors, PatchUserOnboardingResponses, PatchUserTutorialData, PatchUserTutorialErrors, PatchUserTutorialResponses, PollCodexLoginData, PollCodexLoginResponses, PostProfilePicturesData, PostProfilePicturesErrors, PostProfilePicturesResponses, PurchaseAiCreditsData, PurchaseAiCreditsErrors, PurchaseAiCreditsResponses, PutAgentApiKeyData, PutAgentApiKeyErrors, PutAgentApiKeyResponses, PutCursorApiKeyData, PutCursorApiKeyErrors, PutCursorApiKeyResponses, PutCursorDefaultModelData, PutCursorDefaultModelErrors, PutCursorDefaultModelResponses, PutProfilePictureData, PutProfilePictureErrors, PutProfilePictureFileData, PutProfilePictureFileErrors, PutProfilePictureFileResponses, PutProfilePictureResponses, PutUserLanguageData, PutUserLanguageErrors, PutUserLanguageResponses, PutUserNameData, PutUserNameErrors, PutUserNameResponses, RedeemGtmInviteLinkData, RedeemGtmInviteLinkErrors, RedeemGtmInviteLinkResponses, RefreshData, RefreshErrors, RefreshResponses, RejectInvitationData, RejectInvitationErrors, RejectInvitationResponses, RemoveUserFromTeamData, RemoveUserFromTeamErrors, RemoveUserFromTeamResponses, ResendFusionauthVerifyUserEmailData, ResendFusionauthVerifyUserEmailErrors, ResendFusionauthVerifyUserEmailResponses, ResolveGtmInviteLinkData, ResolveGtmInviteLinkErrors, ResolveGtmInviteLinkResponses, RevokeGtmInviteLinkData, RevokeGtmInviteLinkErrors, RevokeGtmInviteLinkResponses, SendMobileWelcomeEmailData, SendMobileWelcomeEmailErrors, SendMobileWelcomeEmailResponses, SendReferralCodeData, SendReferralCodeErrors, SendReferralCodeResponses, SendTeamDomainNoticeData, SendTeamDomainNoticeErrors, SendTeamDomainNoticeResponses, SessionCreationData, SessionCreationErrors, SessionCreationResponses, SessionLoginData, SessionLoginErrors, SessionLoginResponses, SetGithubPullRequestDraftData, SetGithubPullRequestDraftErrors, SetGithubPullRequestDraftResponses, SetGithubPullRequestStateData, SetGithubPullRequestStateErrors, SetGithubPullRequestStateResponses, SetSystemStatusData, SetSystemStatusErrors, SetSystemStatusResponses, SsoLoginData, SsoLoginErrors, SsoLoginResponses, StartCodexLoginData, StartCodexLoginResponses, ToggleTeamAutoJoinDomainData, ToggleTeamAutoJoinDomainErrors, ToggleTeamAutoJoinDomainResponses, ToggleTeamNonAdminInvitesData, ToggleTeamNonAdminInvitesErrors, ToggleTeamNonAdminInvitesResponses, UpdateAiBillingAutoReloadData, UpdateAiBillingAutoReloadErrors, UpdateAiBillingAutoReloadResponses, UpdateAiBillingOverageData, UpdateAiBillingOverageErrors, UpdateAiBillingOverageResponses, VerifyEmailLinkData, VerifyEmailLinkErrors, VerifyEmailLinkResponses, VerifyFusionauthUserEmailData, VerifyFusionauthUserEmailErrors, VerifyFusionauthUserEmailResponses, VerifyMergeRequestData, VerifyMergeRequestErrors, VerifyMergeRequestResponses } from './types.gen';export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown> = Options2<TData, ThrowOnError, TResponse> & {/**@@ -980,6 +980,17 @@ export class Sdk extends HeyApiClient {return (options?.client ?? this.client).get<GetUserInvitesResponses, GetUserInvitesErrors, ThrowOnError>({ url: '/team/user/invites', ...options });}+ /**+ * Finishes an agent's signup: joins the team that invited it and mints its+ * SDK token.+ *+ * Safe to repeat until the agent confirms it saved the token: a reload replaces+ * the key, and a failed join stays pending for the next attempt.+ */+ public agentSetup<ThrowOnError extends boolean = false>(options?: Options<AgentSetupData, ThrowOnError>): RequestResult<AgentSetupResponses, AgentSetupErrors, ThrowOnError> {+ return (options?.client ?? this.client).post<AgentSetupResponses, AgentSetupErrors, ThrowOnError>({ url: '/user/agent_setup', ...options });+ }+/*** Retrieves user names in bulk*/@@ -1118,6 +1129,35 @@ export class Sdk extends HeyApiClient {return (options.client ?? this.client).put<PutProfilePictureResponses, PutProfilePictureErrors, ThrowOnError>({ url: '/user/profile_picture', ...options });}+ /**+ * Reserves storage for a new profile picture. Static file storage has no+ * MacroDB, so it cannot check API keys; this route lets key holders upload.+ */+ public createProfilePictureUpload<ThrowOnError extends boolean = false>(options: Options<CreateProfilePictureUploadData, ThrowOnError>): RequestResult<CreateProfilePictureUploadResponses, CreateProfilePictureUploadErrors, ThrowOnError> {+ return (options.client ?? this.client).post<CreateProfilePictureUploadResponses, CreateProfilePictureUploadErrors, ThrowOnError>({+ url: '/user/profile_picture/file',+ ...options,+ headers: {+ 'Content-Type': 'application/json',+ ...options.headers+ }+ });+ }++ /**+ * Sets the caller's profile picture to an image they uploaded.+ */+ public putProfilePictureFile<ThrowOnError extends boolean = false>(options: Options<PutProfilePictureFileData, ThrowOnError>): RequestResult<PutProfilePictureFileResponses, PutProfilePictureFileErrors, ThrowOnError> {+ return (options.client ?? this.client).put<PutProfilePictureFileResponses, PutProfilePictureFileErrors, ThrowOnError>({+ url: '/user/profile_picture/file',+ ...options,+ headers: {+ 'Content-Type': 'application/json',+ ...options.headers+ }+ });+ }+/*** Retrieves profile picture URLs for a list of users*/diff --git a/packages/sdk/generated/auth/types.gen.ts b/packages/sdk/generated/auth/types.gen.tsindex 2286791804..74397c9b49 100644--- a/packages/sdk/generated/auth/types.gen.ts+++ b/packages/sdk/generated/auth/types.gen.ts@@ -23,6 +23,21 @@ export type AgentApiKey = {*/export type AgentApiKeyProvider = 'anthropic' | 'openai';+/**+ * What an agent needs to start using the SDK.+ */+export type AgentSetupResponse = {+ /**+ * The agent's API key. Shown only here; repeating setup revokes it.+ */+ api_key: string;+ /**+ * Whether joining the inviting team failed. The invite stays pending:+ * repeating setup tries again, and the invite link works after confirming.+ */+ team_join_failed: boolean;+};+/*** Error response body.*/@@ -330,6 +345,17 @@ export type CreatePortalSessionRequest = {returnUrl: string;};+export type CreateProfilePictureUploadRequest = {+ /**+ * Mime type of the image.+ */+ content_type: string;+ /**+ * File name, such as `avatar.png`.+ */+ file_name: string;+};+/*** The request body to create a new team*/@@ -688,6 +714,10 @@ export type GetLegacyUserPermissionsResponse = {* Whether the user has trialed through stripe*/hasTrialed: boolean;+ /**+ * Whether this is an agent account rather than a person+ */+ isAgent: boolean;/*** The user's license status*/@@ -1208,6 +1238,11 @@ export type InviteToTeamRequest = {* The invites to send, each with an email and tier*/invites: Array<InviteEntry>;+ /**+ * Invite these addresses as agents: an address with no account signs up+ * as an agent and joins the team when it first signs in.+ */+ is_agent?: boolean;/*** The team the caller means to invite to. Invites always go to the* caller's current team; when this names another team, nothing is sent@@ -1294,6 +1329,12 @@ export type PasswordlessRequest = {* The email to initiate passwordless authentication for*/email: string;+ /**+ * Create an agent account if this address has no account yet. Otherwise+ * `true` has no effect, and `false` reverts an agent flag nobody has proven:+ * see `revert_unconfirmed_agent`.+ */+ is_agent?: boolean;/*** The redirect uri to redirect to after login*/@@ -1515,6 +1556,20 @@ export type ProfilePictureQueryParams = {url: string;};+/**+ * Where to upload a new profile picture, and the file id to set afterwards.+ */+export type ProfilePictureUpload = {+ /**+ * Id to pass to `PUT /user/profile_picture/file` once uploaded.+ */+ file_id: string;+ /**+ * Expiring URL to `PUT` the image bytes to.+ */+ upload_url: string;+};+export type ProfilePictures = {pictures: Array<UserProfilePicture>;};@@ -1569,6 +1624,13 @@ export type PutCursorDefaultModelRequest = {modelId?: string | null;};+export type PutProfilePictureFileRequest = {+ /**+ * Id of an image the caller uploaded to static file storage.+ */+ file_id: string;+};+export type PutUserNameQueryParams = {/*** First Name of user@@ -1861,6 +1923,10 @@ export type TeamInviteDetails = {* The user who sent the invitation*/invited_by: string;+ /**+ * Whether the invite creates an agent account+ */+ is_agent: boolean;/*** When the invite was last sent*/@@ -2182,6 +2248,10 @@ export type UserLinkResponse = {export type UserName = {first_name?: string | null;id: string;+ /**+ * Whether this is an agent account rather than a person.+ */+ is_agent?: boolean;last_name?: string | null;};@@ -4353,6 +4423,34 @@ export type GetUserInvitesResponses = {export type GetUserInvitesResponse = GetUserInvitesResponses[keyof GetUserInvitesResponses];+export type AgentSetupData = {+ body?: never;+ path?: never;+ query?: never;+ url: '/user/agent_setup';+};++export type AgentSetupErrors = {+ 401: string;+ /**+ * The account is not an agent+ */+ 403: ErrorResponse;+ /**+ * Setup is already confirmed+ */+ 409: ErrorResponse;+ 500: ErrorResponse;+};++export type AgentSetupError = AgentSetupErrors[keyof AgentSetupErrors];++export type AgentSetupResponses = {+ 200: AgentSetupResponse;+};++export type AgentSetupResponse2 = AgentSetupResponses[keyof AgentSetupResponses];+export type GetUserNamesData = {body: PostGetNamesRequestBody;path?: never;@@ -4667,6 +4765,58 @@ export type PutProfilePictureResponses = {export type PutProfilePictureResponse = PutProfilePictureResponses[keyof PutProfilePictureResponses];+export type CreateProfilePictureUploadData = {+ body: CreateProfilePictureUploadRequest;+ path?: never;+ query?: never;+ url: '/user/profile_picture/file';+};++export type CreateProfilePictureUploadErrors = {+ /**+ * Not a supported image type+ */+ 400: ErrorResponse;+ 401: string;+ 500: ErrorResponse;+};++export type CreateProfilePictureUploadError = CreateProfilePictureUploadErrors[keyof CreateProfilePictureUploadErrors];++export type CreateProfilePictureUploadResponses = {+ 200: ProfilePictureUpload;+};++export type CreateProfilePictureUploadResponse = CreateProfilePictureUploadResponses[keyof CreateProfilePictureUploadResponses];++export type PutProfilePictureFileData = {+ body: PutProfilePictureFileRequest;+ path?: never;+ query?: never;+ url: '/user/profile_picture/file';+};++export type PutProfilePictureFileErrors = {+ /**+ * The file is not a supported image+ */+ 400: ErrorResponse;+ 401: string;+ /**+ * The caller has no such file+ */+ 404: ErrorResponse;+ 500: ErrorResponse;+};++export type PutProfilePictureFileError = PutProfilePictureFileErrors[keyof PutProfilePictureFileErrors];++export type PutProfilePictureFileResponses = {+ 200: EmptyResponse;+};++export type PutProfilePictureFileResponse = PutProfilePictureFileResponses[keyof PutProfilePictureFileResponses];+export type PostProfilePicturesData = {body: GetProfilePicturesRequestBody;path?: never;diff --git a/packages/sdk/generated/notification/types.gen.ts b/packages/sdk/generated/notification/types.gen.tsindex c0b8b1e64b..39e0408592 100644--- a/packages/sdk/generated/notification/types.gen.ts+++ b/packages/sdk/generated/notification/types.gen.ts@@ -982,6 +982,10 @@ export type InviteToTeamMetadata = {* What the invitee gets by joining, as the team stood when the invite was sent.*/inviteePlan?: InviteePlan;+ /**+ * Whether the invite creates an agent account.+ */+ isAgent?: boolean;/*** Whether this email reminds the invitee of an invite they have not answered.*/diff --git a/packages/sdk/specs/auth.json b/packages/sdk/specs/auth.jsonindex 348566bb13..d6f8b9c67e 100644--- a/packages/sdk/specs/auth.json+++ b/packages/sdk/specs/auth.json@@ -5128,6 +5128,66 @@}}},+ "/user/agent_setup": {+ "post": {+ "tags": ["user::agent_setup"],+ "summary": "Finishes an agent's signup: joins the team that invited it and mints its\nSDK token.",+ "description": "Safe to repeat until the agent confirms it saved the token: a reload replaces\nthe key, and a failed join stays pending for the next attempt.",+ "operationId": "agent_setup",+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/AgentSetupResponse"+ }+ }+ }+ },+ "401": {+ "description": "",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "403": {+ "description": "The account is not an agent",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "409": {+ "description": "Setup is already confirmed",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ }+ },"/user/get_names": {"post": {"tags": ["user::post_get_names"],@@ -5835,6 +5895,132 @@}}},+ "/user/profile_picture/file": {+ "put": {+ "tags": ["user::put_profile_picture_file"],+ "summary": "Sets the caller's profile picture to an image they uploaded.",+ "operationId": "put_profile_picture_file",+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/PutProfilePictureFileRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/EmptyResponse"+ }+ }+ }+ },+ "400": {+ "description": "The file is not a supported image",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "401": {+ "description": "",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "404": {+ "description": "The caller has no such file",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ },+ "post": {+ "tags": ["user::put_profile_picture_file"],+ "summary": "Reserves storage for a new profile picture. Static file storage has no\nMacroDB, so it cannot check API keys; this route lets key holders upload.",+ "operationId": "create_profile_picture_upload",+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CreateProfilePictureUploadRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ProfilePictureUpload"+ }+ }+ }+ },+ "400": {+ "description": "Not a supported image type",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "401": {+ "description": "",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ }+ },"/user/profile_pictures": {"post": {"tags": ["user::post_profile_pictures"],@@ -6322,6 +6508,21 @@"description": "A provider an agent can bring its own key for.","enum": ["anthropic", "openai"]},+ "AgentSetupResponse": {+ "type": "object",+ "description": "What an agent needs to start using the SDK.",+ "required": ["api_key", "team_join_failed"],+ "properties": {+ "api_key": {+ "type": "string",+ "description": "The agent's API key. Shown only here; repeating setup revokes it."+ },+ "team_join_failed": {+ "type": "boolean",+ "description": "Whether joining the inviting team failed. The invite stays pending:\nrepeating setup tries again, and the invite link works after confirming."+ }+ }+ },"AiBillingErrorBody": {"type": "object","description": "Error response body.",@@ -6703,6 +6904,20 @@}}},+ "CreateProfilePictureUploadRequest": {+ "type": "object",+ "required": ["file_name", "content_type"],+ "properties": {+ "content_type": {+ "type": "string",+ "description": "Mime type of the image."+ },+ "file_name": {+ "type": "string",+ "description": "File name, such as `avatar.png`."+ }+ }+ },"CreateTeamRequest": {"type": "object","description": "The request body to create a new team",@@ -7125,6 +7340,7 @@"email","licenseStatus","tutorialComplete",+ "isAgent","hasChromeExt","hasTrialed","aiDataConsent",@@ -7163,6 +7379,10 @@"type": "boolean","description": "Whether the user has trialed through stripe"},+ "isAgent": {+ "type": "boolean",+ "description": "Whether this is an agent account rather than a person"+ },"licenseStatus": {"type": "string","description": "The user's license status"@@ -7821,6 +8041,10 @@},"description": "The invites to send, each with an email and tier"},+ "is_agent": {+ "type": "boolean",+ "description": "Invite these addresses as agents: an address with no account signs up\nas an agent and joins the team when it first signs in."+ },"team_id": {"type": ["string", "null"],"format": "uuid",@@ -7965,6 +8189,10 @@"type": "string","description": "The email to initiate passwordless authentication for"},+ "is_agent": {+ "type": "boolean",+ "description": "Create an agent account if this address has no account yet. Otherwise\n`true` has no effect, and `false` reverts an agent flag nobody has proven:\nsee `revert_unconfirmed_agent`."+ },"redirect_uri": {"type": "string","description": "The redirect uri to redirect to after login"@@ -8264,6 +8492,21 @@}}},+ "ProfilePictureUpload": {+ "type": "object",+ "description": "Where to upload a new profile picture, and the file id to set afterwards.",+ "required": ["file_id", "upload_url"],+ "properties": {+ "file_id": {+ "type": "string",+ "description": "Id to pass to `PUT /user/profile_picture/file` once uploaded."+ },+ "upload_url": {+ "type": "string",+ "description": "Expiring URL to `PUT` the image bytes to."+ }+ }+ },"ProfilePictures": {"type": "object","required": ["pictures"],@@ -8329,6 +8572,16 @@}}},+ "PutProfilePictureFileRequest": {+ "type": "object",+ "required": ["file_id"],+ "properties": {+ "file_id": {+ "type": "string",+ "description": "Id of an image the caller uploaded to static file storage."+ }+ }+ },"PutUserNameQueryParams": {"type": "object","properties": {@@ -8746,7 +8999,8 @@"team_role","invited_by","created_at",- "last_sent_at"+ "last_sent_at",+ "is_agent"],"properties": {"created_at": {@@ -8767,6 +9021,10 @@"type": "string","description": "The user who sent the invitation"},+ "is_agent": {+ "type": "boolean",+ "description": "Whether the invite creates an agent account"+ },"last_sent_at": {"type": "string","format": "date-time",@@ -9183,6 +9441,10 @@"id": {"type": "string"},+ "is_agent": {+ "type": "boolean",+ "description": "Whether this is an agent account rather than a person."+ },"last_name": {"type": ["string", "null"]}diff --git a/packages/sdk/specs/notification.json b/packages/sdk/specs/notification.jsonindex 5536b23ac1..7a55d7e056 100644--- a/packages/sdk/specs/notification.json+++ b/packages/sdk/specs/notification.json@@ -2474,6 +2474,10 @@"$ref": "#/components/schemas/InviteePlan","description": "What the invitee gets by joining, as the team stood when the invite was sent."},+ "isAgent": {+ "type": "boolean",+ "description": "Whether the invite creates an agent account."+ },"reminder": {"type": "boolean","description": "Whether this email reminds the invitee of an invite they have not answered."diff --git a/packages/sdk/src/coverage/skipped.ts b/packages/sdk/src/coverage/skipped.tsindex a749d24b7e..1b4ef19f84 100644--- a/packages/sdk/src/coverage/skipped.ts+++ b/packages/sdk/src/coverage/skipped.ts@@ -121,8 +121,9 @@ export const authExcluded = ['putCursorApiKey','putCursorDefaultModel','putProfilePicture',+ // Internal to the web app's agent signup; the token is shown in its modal.+ 'agentSetup','putUserLanguage',- 'putUserName','redeemGtmInviteLink','refresh','rejectInvitation',diff --git a/packages/sdk/src/entities/me/namespace.ts b/packages/sdk/src/entities/me/namespace.tsnew file mode 100644index 0000000000..da8f20007b--- /dev/null+++ b/packages/sdk/src/entities/me/namespace.ts@@ -0,0 +1,91 @@+import { MacroError, unwrap } from '../../utils';+import type { MacroClient } from '../../utils/client';+import { StaticImage } from '../images/image';++/** The largest profile picture, matching the web app's limit. */+const MAX_PROFILE_PICTURE_BYTES = 16 * 1000 * 1000;++/** How to store an uploaded profile picture. */+export interface UploadProfilePictureOptions {+ /** File name, such as `avatar.png`. */+ fileName: string;+ /** `image/png`, `image/jpeg`, `image/webp` or `image/gif`. */+ contentType: string;+}++/** What to change on the authenticated user's profile. */+export interface UpdateMeOptions {+ /** Display name. The first word becomes the first name. */+ name?: string;+ /** An image from {@link MeNamespace.uploadProfilePicture}. */+ profilePicture?: StaticImage;+}++/** The authenticated user's own profile. */+export class MeNamespace {+ constructor(private readonly client: MacroClient) {}++ /**+ * Upload an image to use as your profile picture. This only stores it; pass+ * the result to {@link MeNamespace.update} to start using it.+ */+ async uploadProfilePicture(+ data: Blob | Uint8Array<ArrayBuffer>,+ options: UploadProfilePictureOptions,+ ): Promise<StaticImage> {+ const size = data instanceof Blob ? data.size : data.byteLength;+ if (size > MAX_PROFILE_PICTURE_BYTES) {+ throw new MacroError('profile picture is larger than 16 MB');+ }++ const { file_id, upload_url } = unwrap(+ await this.client.auth.createProfilePictureUpload({+ body: {+ file_name: options.fileName,+ content_type: options.contentType,+ },+ }),+ );+ const response = await fetch(upload_url, {+ method: 'PUT',+ headers: { 'Content-Type': options.contentType },+ body: data,+ });+ if (!response.ok) {+ throw new MacroError(`image upload failed with ${response.status}`);+ }+ return StaticImage.byId(this.client, file_id);+ }++ /**+ * Set your display name and profile picture. Agents should do this after+ * signing in, so teammates can tell who they are working with.+ *+ * @example+ * const image = await macro.me.uploadProfilePicture(bytes, {+ * fileName: 'avatar.png',+ * contentType: 'image/png',+ * });+ * await macro.me.update({ name: 'Research Agent', profilePicture: image });+ */+ async update(options: UpdateMeOptions): Promise<void> {+ if (options.profilePicture) {+ unwrap(+ await this.client.auth.putProfilePictureFile({+ body: { file_id: options.profilePicture.id },+ }),+ );+ }++ const name = options.name?.trim();+ if (name) {+ const [firstName, ...rest] = name.split(/\s+/);+ unwrap(+ await this.client.auth.putUserName({+ // An empty last name clears the old one; null would keep it.+ query: { first_name: firstName, last_name: rest.join(' ') },+ }),+ );+ }+ }+}diff --git a/packages/sdk/src/entities/teams/team.ts b/packages/sdk/src/entities/teams/team.tsindex 278906bfd7..326978b4f0 100644--- a/packages/sdk/src/entities/teams/team.ts+++ b/packages/sdk/src/entities/teams/team.ts@@ -91,11 +91,21 @@ export class Team extends MacroEntity<TeamRecord> {* inviting to admins rejects other members, and teams without an* enterprise plan accept a limited number of invites per day.*+ * Pass `{ agent: true }` to invite the addresses as agents. An agent invite+ * to an address with no account creates an agent account when that address+ * signs in: it skips onboarding, gets an SDK token, and joins this team, using+ * a paid seat when the team has a subscription. An existing account keeps its+ * type and accepts like any other invite.+ ** @param emails - One address or a list of addresses to invite.+ * @param options - `agent` invites the addresses as agents.* @returns `true` when at least one new invite was sent, `false` when every* address was already a member or already invited.*/- async invite(emails: string | readonly string[]): Promise<boolean> {+ async invite(+ emails: string | readonly string[],+ options?: { agent?: boolean },+ ): Promise<boolean> {const addresses: string[] = [];const seen = new Set<string>();for (const raw of typeof emails === 'string' ? [emails] : emails) {@@ -114,6 +124,7 @@ export class Team extends MacroEntity<TeamRecord> {body: {invites: addresses.map((email) => ({ email })),team_id: this.id,+ ...(options?.agent && { is_agent: true }),},});// The API answers 304 when it created no invite: every address wasdiff --git a/packages/sdk/src/entities/users/user.ts b/packages/sdk/src/entities/users/user.tsindex 5333ff164e..e92c8082b1 100644--- a/packages/sdk/src/entities/users/user.ts+++ b/packages/sdk/src/entities/users/user.ts@@ -56,6 +56,16 @@ export class User extends PropertiedEntity<UserName> implements Mentionable {return full || undefined;}+ /**+ * Whether this user is an agent account rather than a person.+ *+ * @returns `true` for an agent account.+ */+ async isAgent(): Promise<boolean> {+ const entry = await this.detail.get();+ return entry.is_agent === true;+ }+/*** This user's email address. Macro user ids encode it as `macro|<email>`,* so this reads straight off the id — no auth-service endpoint returnsdiff --git a/packages/sdk/src/macro.ts b/packages/sdk/src/macro.tsindex e6e423cfe1..c73f4e3154 100644--- a/packages/sdk/src/macro.ts+++ b/packages/sdk/src/macro.ts@@ -21,6 +21,7 @@ import { GithubPullRequestNamespace } from './entities/github-pull-requests/nameimport { HarnessNamespace } from './entities/harnesses/namespace';import { ImagesNamespace } from './entities/images/namespace';import { InitiativeNamespace } from './entities/initiatives/namespace';+import { MeNamespace } from './entities/me/namespace';import { MeetingNamespace } from './entities/meetings/namespace';import { NotificationNamespace } from './entities/notifications/namespace';import { PinsNamespace } from './entities/pins/namespace';@@ -157,6 +158,8 @@ export class Macro<T extends MacroOpts = MacroOpts> {/** Generate images with AI and attach them to messages. */readonly images: ImagesNamespace;+ /** Your own profile: set your name and profile picture. */+ readonly me: MeNamespace;readonly notifications: NotificationNamespace;@@ -199,6 +202,7 @@ export class Macro<T extends MacroOpts = MacroOpts> {this.agents = new AgentNamespace(client);this.initiatives = new InitiativeNamespace(client);this.apiKeys = new ApiKeyNamespace(client);+ this.me = new MeNamespace(client);this.harnesses = new HarnessNamespace(client);this.meetings = new MeetingNamespace(client);this.githubPullRequests = new GithubPullRequestNamespace(client);@@ -323,6 +327,11 @@ export {type InitiativeOptions,} from './entities/initiatives/initiative';export type { InitiativeSummary } from './entities/initiatives/namespace';+export {+ MeNamespace,+ type UpdateMeOptions,+ type UploadProfilePictureOptions,+} from './entities/me/namespace';export { Meeting } from './entities/meetings/meeting';export type { TimelineOptions } from './entities/messages/thread';export { type MessageParent, MessageThread } from './entities/messages/thread';diff --git a/services/authentication_service/AGENTS.md b/services/authentication_service/AGENTS.mdindex 91673670d4..44df8ccddb 100644--- a/services/authentication_service/AGENTS.md+++ b/services/authentication_service/AGENTS.md@@ -82,6 +82,24 @@ key issuance, and account merge/link flows.API-token exchange preserves verified incoming agent attribution; query/bodyinputs cannot select an agent, and ordinary user credentials remain unattributed.+## Agent accounts++- An agent can do everything a person can, including inviting other agents. Do+ not gate actions on `isAgent`; it only changes signup and labeling.+- `User."isAgent"` is set once, in the FusionAuth `user.create` webhook, from+ `is_agent` on `/login/passwordless` (carried as FusionAuth user data) or a+ pending agent `team_invite`. Agents skip the seeded content, Loops, and Meta.+- The account exists before its email is verified, so the toggle's flag is+ provisional: a code request without the toggle or an SSO sign-in reverts it+ (`revert_unconfirmed_agent`) until a key exists, setup is confirmed, or an+ agent invite is pending.+- `POST /user/agent_setup` joins the inviting team and replaces the+ `Agent signup` API key. It is repeatable until `tutorialComplete` is true.+- `POST /user/profile_picture/file` reserves an SFS upload for API-key callers,+ since `static_file_service` cannot check keys. `PUT` on that path takes the SFS+ id and accepts only the caller's PNG, JPEG, WebP, or GIF; it does not wait for+ the asynchronous upload event.+## Gotchas- `/mobile-welcome-email` copies allowlisted ad parameters from the capturediff --git a/services/authentication_service/Cargo.toml b/services/authentication_service/Cargo.tomlindex f863de450d..1c0d94373d 100644--- a/services/authentication_service/Cargo.toml+++ b/services/authentication_service/Cargo.toml@@ -71,6 +71,9 @@ contacts = { path = "../../crates/contacts", default-features = false, featurescookie = { workspace = true }decode_jwt = { path = "../../crates/decode_jwt" }document_storage_service_client = { path = "../../crates/document_storage_service_client" }+models_sfs = { path = "../../crates/models_sfs" }+static_file_service_client = { path = "../../crates/static_file_service_client" }+user_api_key = { path = "../../crates/user_api_key", features = ["postgres"] }email = { path = "../../crates/email", features = ["http_client", "outbound"] }doppleganger = { workspace = true }email_db_client = { path = "../../crates/email_db_client" }diff --git a/services/authentication_service/src/api/context.rs b/services/authentication_service/src/api/context.rsindex a0de461d1a..b905444530 100644--- a/services/authentication_service/src/api/context.rs+++ b/services/authentication_service/src/api/context.rs@@ -227,6 +227,9 @@ pub(crate) struct ApiContext {>,pub document_storage_service_client:Arc<document_storage_service_client::DocumentStorageServiceClient>,+ pub static_file_service_client: Arc<static_file_service_client::StaticFileServiceClient>,+ /// Browser-facing base URL of static files, which profile pictures use.+ pub static_file_public_url: String,pub user_deletion: Arc<crate::outbound::user_deletion::UserDeletionAdapter<TeamsServiceType,diff --git a/services/authentication_service/src/api/internal/relocate_inbox_grant.rs b/services/authentication_service/src/api/internal/relocate_inbox_grant.rsindex 4feb75a5fd..6dc3b21895 100644--- a/services/authentication_service/src/api/internal/relocate_inbox_grant.rs+++ b/services/authentication_service/src/api/internal/relocate_inbox_grant.rs@@ -85,6 +85,7 @@ pub async fn handler(Ok(id) => id,Err(fusionauth::error::FusionAuthClientError::UserDoesNotExist) => {let user = fusionauth::user::create::User {+ data: None,email: Cow::Borrowed(&email),password: Cow::Owned(uuid::Uuid::new_v4().to_string()),username: Some(Cow::Borrowed(&email)),diff --git a/services/authentication_service/src/api/login/passwordless.rs b/services/authentication_service/src/api/login/passwordless.rsindex 9a62d4aec0..4ce15d8765 100644--- a/services/authentication_service/src/api/login/passwordless.rs+++ b/services/authentication_service/src/api/login/passwordless.rs@@ -9,8 +9,12 @@ use macro_middleware::tracking::ClientIp;use std::borrow::Cow;use crate::{- api::{context::ApiContext, signup_policy::signup_forbidden_response},+ api::{+ context::ApiContext, signup_policy::signup_forbidden_response,+ webhooks::user::create_user_webhook::revert_unconfirmed_agent,+ },generate_password::generate_random_password,+ service::user::agent_signup::AGENT_SIGNUP_DATA_KEY,};use fusionauth::error::FusionAuthClientError;use macro_user_id::user_id::MacroUserId;@@ -97,7 +101,16 @@ pub async fn handler(// We may have a user that has linked an email but they don't have a FusionAuth user to handle// sending the passwordless login.match ctx.auth_client.get_user_id_by_email(&lowercase_email).await {- Ok(_) => (),+ Ok(_) => {+ if !req.is_agent {+ revert_unconfirmed_agent(+ &ctx,+ &format!("macro|{lowercase_email}"),+ &lowercase_email,+ )+ .await;+ }+ }Err(e) => {match e {FusionAuthClientError::UserDoesNotExist => {@@ -116,6 +129,9 @@ pub async fn handler(email: (&lowercase_email).into(),password: generate_random_password().into(),username: None,+ data: req.is_agent.then(|| {+ serde_json::json!({ AGENT_SIGNUP_DATA_KEY: true })+ }),},true,ip_context.origin_ip(),diff --git a/services/authentication_service/src/api/oauth/oauth_redirect.rs b/services/authentication_service/src/api/oauth/oauth_redirect.rsindex 275262edd6..4d4d06f3c6 100644--- a/services/authentication_service/src/api/oauth/oauth_redirect.rs+++ b/services/authentication_service/src/api/oauth/oauth_redirect.rs@@ -1,3 +1,4 @@+use crate::api::webhooks::user::create_user_webhook::revert_unconfirmed_agent;use crate::api::{context::ApiContext,login::sso::{SsoState, is_allowed_original_url, redact_original_url_for_logging},@@ -156,6 +157,11 @@ pub async fn handler(Err(_) => false,};+ // A provider just verified this address, so a person is signing in.+ if !just_signed_up && let Ok(user_id) = decoded_user_id.as_ref() {+ revert_unconfirmed_agent(&ctx, user_id.as_ref(), user_id.email_str()).await;+ }+// Only a brand-new account counts as referred: an existing user who signs// in through a referral link earns the referrer nothing.if just_signed_updiff --git a/services/authentication_service/src/api/swagger.rs b/services/authentication_service/src/api/swagger.rsindex 1aadf916b9..05f7523d55 100644--- a/services/authentication_service/src/api/swagger.rs+++ b/services/authentication_service/src/api/swagger.rs@@ -147,6 +147,9 @@ use model::user::{user::delete_user::handler,user::post_profile_pictures::handler,user::put_profile_picture::handler,+ user::put_profile_picture_file::create_upload_handler,+ user::put_profile_picture_file::handler,+ user::agent_setup::handler,user::put_name::handler,user::get_name::handler,user::patch_user_group::handler,@@ -246,6 +249,10 @@ use model::user::{UserProfilePicture,AppleLoginRequest,ProfilePictureQueryParams,+ crate::api::user::put_profile_picture_file::PutProfilePictureFileRequest,+ crate::api::user::put_profile_picture_file::CreateProfilePictureUploadRequest,+ crate::api::user::put_profile_picture_file::ProfilePictureUpload,+ crate::api::user::agent_setup::AgentSetupResponse,PutUserNameQueryParams,UserName,UserLanguage,diff --git a/services/authentication_service/src/api/user.rs b/services/authentication_service/src/api/user.rsindex 9041f62c4e..513b00cf72 100644--- a/services/authentication_service/src/api/user.rs+++ b/services/authentication_service/src/api/user.rs@@ -7,6 +7,7 @@ use tower_cookies::CookieManagerLayer;use crate::api::{ApiContext, context::EntityAccessServiceType};// needs to be public in api crate for swagger+pub(in crate::api) mod agent_setup;pub(in crate::api) mod delete_user;pub(in crate::api) mod get_legacy_user_permissions;pub(in crate::api) mod get_name;@@ -23,6 +24,7 @@ pub(in crate::api) mod post_get_names_with_email;pub(in crate::api) mod post_profile_pictures;pub(in crate::api) mod put_name;pub(in crate::api) mod put_profile_picture;+pub(in crate::api) mod put_profile_picture_file;pub(in crate::api) mod stripe;pub fn router() -> Router<ApiContext> {@@ -35,6 +37,12 @@ fn router_with_auth() -> Router<ApiContext> {.route("/me", delete(delete_user::handler)).route("/profile_pictures", post(post_profile_pictures::handler)).route("/profile_picture", put(put_profile_picture::handler))+ .route(+ "/profile_picture/file",+ post(put_profile_picture_file::create_upload_handler)+ .put(put_profile_picture_file::handler),+ )+ .route("/agent_setup", post(agent_setup::handler)).route("/name", put(put_name::handler)).route("/name", get(get_name::handler)).route("/get_names", post(post_get_names::handler_external))diff --git a/services/authentication_service/src/api/user/agent_setup.rs b/services/authentication_service/src/api/user/agent_setup.rsnew file mode 100644index 0000000000..54fae755ba--- /dev/null+++ b/services/authentication_service/src/api/user/agent_setup.rs@@ -0,0 +1,123 @@+use axum::{Json, extract::State, http::StatusCode};+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};+use macro_user_id::user_id::MacroUserIdStr;+use model::response::ErrorResponse;+use teams::domain::team_repo::TeamService;+use user_api_key::domain::{ports::UserApiKeyService, service::UserApiKeyServiceImpl};+use user_api_key::outbound::pg_user_api_keys_repo::PgUserApiKeysRepo;++use crate::api::context::{ApiContext, AuthorizationService};+use crate::service::user::agent_signup::AGENT_SIGNUP_KEY_NAME;++/// What an agent needs to start using the SDK.+#[derive(serde::Serialize, serde::Deserialize, utoipa::ToSchema)]+pub struct AgentSetupResponse {+ /// The agent's API key. Shown only here; repeating setup revokes it.+ pub api_key: String,+ /// Whether joining the inviting team failed. The invite stays pending:+ /// repeating setup tries again, and the invite link works after confirming.+ pub team_join_failed: bool,+}++fn error(status: StatusCode, message: &str) -> (StatusCode, Json<ErrorResponse<'static>>) {+ (+ status,+ Json(ErrorResponse {+ message: message.to_string().into(),+ }),+ )+}++/// Finishes an agent's signup: joins the team that invited it and mints its+/// SDK token.+///+/// Safe to repeat until the agent confirms it saved the token: a reload replaces+/// the key, and a failed join stays pending for the next attempt.+#[utoipa::path(+ post,+ path = "/user/agent_setup",+ operation_id = "agent_setup",+ responses(+ (status = 200, body = AgentSetupResponse),+ (status = 401, body = String),+ (status = 403, body = ErrorResponse, description = "The account is not an agent"),+ (status = 409, body = ErrorResponse, description = "Setup is already confirmed"),+ (status = 500, body = ErrorResponse),+ ),+)]+#[tracing::instrument(+ name = "agent.setup",+ skip_all,+ fields(user_id = %authorization.authorization.user.macro_user_id, joined_team_id),+)]+pub async fn handler(+ State(ctx): State<ApiContext>,+ authorization: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,+) -> Result<Json<AgentSetupResponse>, (StatusCode, Json<ErrorResponse<'static>>)> {+ let macro_user_id = &authorization.authorization.user.macro_user_id;+ let user = macro_db_client::user::get::get_legacy_user_info(&ctx.db, macro_user_id)+ .await+ .map_err(|e| {+ tracing::error!(error=?e, "unable to load user");+ error(StatusCode::INTERNAL_SERVER_ERROR, "unable to load user")+ })?;++ if !user.is_agent {+ return Err(error(StatusCode::FORBIDDEN, "account is not an agent"));+ }+ if user.tutorial_complete {+ return Err(error(StatusCode::CONFLICT, "setup is already confirmed"));+ }++ let user_id = MacroUserIdStr::parse_from_str(macro_user_id.as_ref()).map_err(|e| {+ tracing::error!(error=?e, "unable to parse user id");+ error(StatusCode::INTERNAL_SERVER_ERROR, "invalid user id")+ })?;++ let joined = join_inviting_team(&ctx, &user_id).await;++ let created = UserApiKeyServiceImpl::new(PgUserApiKeysRepo::new(ctx.db.clone()))+ .replace_key(&user_id, AGENT_SIGNUP_KEY_NAME)+ .await+ .map_err(|e| {+ tracing::error!(error=?e, "unable to mint agent key");+ error(StatusCode::INTERNAL_SERVER_ERROR, "unable to create token")+ })?;++ Ok(Json(AgentSetupResponse {+ api_key: created.key,+ team_join_failed: !joined,+ }))+}++/// Joins the oldest pending agent invite. A failure leaves the invite pending:+/// the agent still gets its token, and the next attempt tries the join again.+/// Returns `false` when a pending invite could not be joined.+async fn join_inviting_team(ctx: &ApiContext, user_id: &MacroUserIdStr<'_>) -> bool {+ let invites = match ctx.teams_service.get_user_invites(user_id).await {+ Ok(invites) => invites,+ Err(e) => {+ tracing::error!(error=?e, "unable to read agent invites");+ return false;+ }+ };++ let Some(invite) = invites+ .iter()+ .filter(|invite| invite.is_agent)+ .min_by_key(|invite| invite.created_at)+ else {+ return true;+ };++ match ctx.teams_service.join_team(&invite.id, user_id).await {+ Ok(member) => {+ tracing::Span::current().record("joined_team_id", member.team_id.to_string());+ true+ }+ Err(e) => {+ tracing::error!(error=?e, team_id=%invite.team_id, "unable to join inviting team");+ false+ }+ }+}diff --git a/services/authentication_service/src/api/user/get_legacy_user_permissions.rs b/services/authentication_service/src/api/user/get_legacy_user_permissions.rsindex 2391b02b35..c0d77899e7 100644--- a/services/authentication_service/src/api/user/get_legacy_user_permissions.rs+++ b/services/authentication_service/src/api/user/get_legacy_user_permissions.rs@@ -26,6 +26,8 @@ pub struct GetLegacyUserPermissionsResponse {license_status: String,/// Whether the user has completed the tutorialtutorial_complete: bool,+ /// Whether this is an agent account rather than a person+ is_agent: bool,/// The user's groupgroup: Option<ABGroup>,/// Whether the user has the chrome extension@@ -138,6 +140,7 @@ pub async fn handler(name: legacy_user_info.name,license_status: license_status.to_string(),tutorial_complete: legacy_user_info.tutorial_complete,+ is_agent: legacy_user_info.is_agent,group: match legacy_user_info.group.as_deref() {Some("A" | "a") => Some(ABGroup::A),Some("B" | "b") => Some(ABGroup::B),diff --git a/services/authentication_service/src/api/user/put_profile_picture_file.rs b/services/authentication_service/src/api/user/put_profile_picture_file.rsnew file mode 100644index 0000000000..b50026d248--- /dev/null+++ b/services/authentication_service/src/api/user/put_profile_picture_file.rs@@ -0,0 +1,183 @@+use axum::{Json, extract::State, http::StatusCode};+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};+use macro_db_client::user::update_profile_picture::update_profile_picture;+use model::response::{EmptyResponse, ErrorResponse};+use models_sfs::FileMetadata;++use crate::api::context::{ApiContext, AuthorizationService};++#[cfg(test)]+mod test;++/// Image types browsers render as a profile picture. SVG is excluded: it can+/// carry scripts and external references.+const PROFILE_PICTURE_TYPES: [&str; 4] = ["image/png", "image/jpeg", "image/webp", "image/gif"];++#[derive(serde::Serialize, serde::Deserialize, Debug, utoipa::ToSchema)]+pub struct PutProfilePictureFileRequest {+ /// Id of an image the caller uploaded to static file storage.+ pub file_id: String,+}++/// Why a stored file cannot be a caller's profile picture. An upload is marked+/// complete by an asynchronous storage event, so it is not checked here: setting+/// the picture right after uploading must work, as it does in the web app.+#[derive(Debug, PartialEq, Eq)]+enum ProfilePictureFileError {+ NotOwner,+ NotAnImage,+}++fn validate_profile_picture_file(+ metadata: &FileMetadata,+ caller_id: &str,+) -> Result<(), ProfilePictureFileError> {+ if metadata.owner_id != caller_id {+ return Err(ProfilePictureFileError::NotOwner);+ }+ if !PROFILE_PICTURE_TYPES.contains(&metadata.content_type.as_str()) {+ return Err(ProfilePictureFileError::NotAnImage);+ }++ Ok(())+}++fn error(status: StatusCode, message: &str) -> (StatusCode, Json<ErrorResponse<'static>>) {+ (+ status,+ Json(ErrorResponse {+ message: message.to_string().into(),+ }),+ )+}++/// Where to upload a new profile picture, and the file id to set afterwards.+#[derive(serde::Serialize, serde::Deserialize, utoipa::ToSchema)]+pub struct ProfilePictureUpload {+ /// Id to pass to `PUT /user/profile_picture/file` once uploaded.+ pub file_id: String,+ /// Expiring URL to `PUT` the image bytes to.+ pub upload_url: String,+}++#[derive(serde::Serialize, serde::Deserialize, Debug, utoipa::ToSchema)]+pub struct CreateProfilePictureUploadRequest {+ /// File name, such as `avatar.png`.+ pub file_name: String,+ /// Mime type of the image.+ pub content_type: String,+}++/// Reserves storage for a new profile picture. Static file storage has no+/// MacroDB, so it cannot check API keys; this route lets key holders upload.+#[utoipa::path(+ post,+ path = "/user/profile_picture/file",+ operation_id = "create_profile_picture_upload",+ request_body = CreateProfilePictureUploadRequest,+ responses(+ (status = 200, body = ProfilePictureUpload),+ (status = 400, body = ErrorResponse, description = "Not a supported image type"),+ (status = 401, body = String),+ (status = 500, body = ErrorResponse),+ ),+)]+#[tracing::instrument(+ skip_all,+ fields(user_id = %authorization.authorization.user.macro_user_id),+)]+pub async fn create_upload_handler(+ State(ctx): State<ApiContext>,+ authorization: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,+ Json(req): Json<CreateProfilePictureUploadRequest>,+) -> Result<Json<ProfilePictureUpload>, (StatusCode, Json<ErrorResponse<'static>>)> {+ if !PROFILE_PICTURE_TYPES.contains(&req.content_type.as_str()) {+ return Err(error(StatusCode::BAD_REQUEST, "not a supported image type"));+ }++ let reserved = ctx+ .static_file_service_client+ .reserve_for_user(+ authorization.authorization.user.macro_user_id.as_ref(),+ &req.file_name,+ &req.content_type,+ )+ .await+ .map_err(|e| {+ tracing::error!(error=?e, "unable to reserve profile picture upload");+ error(StatusCode::INTERNAL_SERVER_ERROR, "unable to start upload")+ })?;++ Ok(Json(ProfilePictureUpload {+ file_id: reserved.id,+ upload_url: reserved.upload_url,+ }))+}++/// Sets the caller's profile picture to an image they uploaded.+#[utoipa::path(+ put,+ path = "/user/profile_picture/file",+ operation_id = "put_profile_picture_file",+ request_body = PutProfilePictureFileRequest,+ responses(+ (status = 200, body = EmptyResponse),+ (status = 400, body = ErrorResponse, description = "The file is not a supported image"),+ (status = 401, body = String),+ (status = 404, body = ErrorResponse, description = "The caller has no such file"),+ (status = 500, body = ErrorResponse),+ ),+)]+#[tracing::instrument(+ skip_all,+ fields(user_id = %authorization.authorization.user.macro_user_id, file_id = %req.file_id),+)]+pub async fn handler(+ State(ctx): State<ApiContext>,+ authorization: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,+ Json(req): Json<PutProfilePictureFileRequest>,+) -> Result<Json<EmptyResponse>, (StatusCode, Json<ErrorResponse<'static>>)> {+ let file_id = uuid::Uuid::parse_str(&req.file_id)+ .map_err(|_| error(StatusCode::BAD_REQUEST, "invalid file id"))?;++ let metadata = ctx+ .static_file_service_client+ .get_file_metadata(&file_id.to_string())+ .await+ .map_err(|e| {+ tracing::error!(error=?e, "unable to read file metadata");+ error(StatusCode::INTERNAL_SERVER_ERROR, "unable to read file")+ })?+ .ok_or_else(|| error(StatusCode::NOT_FOUND, "file not found"))?;++ let caller_id = authorization.authorization.user.macro_user_id.as_ref();+ validate_profile_picture_file(&metadata, caller_id).map_err(|e| match e {+ // Someone else's file answers like a missing one.+ ProfilePictureFileError::NotOwner => error(StatusCode::NOT_FOUND, "file not found"),+ ProfilePictureFileError::NotAnImage => {+ error(StatusCode::BAD_REQUEST, "file is not a supported image")+ }+ })?;++ let url = format!(+ "{}/file/{}",+ ctx.static_file_public_url.trim_end_matches('/'),+ file_id+ );+ update_profile_picture(+ &ctx.db,+ &authorization.authorization.user.user_context.fusion_user_id,+ &url,+ "000",+ )+ .await+ .map_err(|e| {+ tracing::error!(error=?e, "unable to update profile picture");+ error(+ StatusCode::INTERNAL_SERVER_ERROR,+ "unable to update profile picture",+ )+ })?;++ Ok(Json(EmptyResponse {}))+}diff --git a/services/authentication_service/src/api/user/put_profile_picture_file/test.rs b/services/authentication_service/src/api/user/put_profile_picture_file/test.rsnew file mode 100644index 0000000000..c7eeb4e9a1--- /dev/null+++ b/services/authentication_service/src/api/user/put_profile_picture_file/test.rs@@ -0,0 +1,43 @@+use models_sfs::FileMetadata;++use super::{ProfilePictureFileError, validate_profile_picture_file};++const CALLER: &str = "macro|[email protected]";++fn metadata(owner_id: &str, content_type: &str) -> FileMetadata {+ FileMetadata {+ file_id: "file".to_string(),+ content_type: content_type.to_string(),+ is_uploaded: true,+ extension_data: None,+ file_name: "avatar".to_string(),+ owner_id: owner_id.to_string(),+ s3_key: "key".to_string(),+ }+}++#[test]+fn the_callers_uploaded_image_is_accepted() {+ assert_eq!(+ validate_profile_picture_file(&metadata(CALLER, "image/png"), CALLER),+ Ok(())+ );+}++#[test]+fn another_users_image_is_rejected() {+ assert_eq!(+ validate_profile_picture_file(&metadata("macro|[email protected]", "image/png"), CALLER),+ Err(ProfilePictureFileError::NotOwner)+ );+}++#[test]+fn svg_and_other_files_are_rejected() {+ for content_type in ["image/svg+xml", "application/pdf"] {+ assert_eq!(+ validate_profile_picture_file(&metadata(CALLER, content_type), CALLER),+ Err(ProfilePictureFileError::NotAnImage)+ );+ }+}diff --git a/services/authentication_service/src/api/webhooks/user.rs b/services/authentication_service/src/api/webhooks/user.rsindex 0b098f6d22..073bf0cbff 100644--- a/services/authentication_service/src/api/webhooks/user.rs+++ b/services/authentication_service/src/api/webhooks/user.rs@@ -1,7 +1,7 @@use crate::api::context::ApiContext;use axum::{Router, routing::post};-mod create_user_webhook;+pub(in crate::api) mod create_user_webhook;mod delete_user_webhook;mod populate_jwt;mod stripe_webhook;diff --git a/services/authentication_service/src/api/webhooks/user/create_user_webhook.rs b/services/authentication_service/src/api/webhooks/user/create_user_webhook.rsindex 3125bc19f6..b315e263f2 100644--- a/services/authentication_service/src/api/webhooks/user/create_user_webhook.rs+++ b/services/authentication_service/src/api/webhooks/user/create_user_webhook.rs@@ -14,13 +14,14 @@ use axum::{use macro_authorization::{InternalOnly, MacroAuthorizationExtractor};use rand::Rng;+use crate::service::user::agent_signup::AGENT_SIGNUP_DATA_KEY;use crate::service::user::create_user::create_user;use crate::service::user::support_channel_welcome::{AuthorizedSupportChannelMessages, post_support_channel_welcome,};use crate::{api::{- context::{ApiContext, AuthorizationService},+ context::{ApiContext, AuthorizationService, TeamsServiceType},signup_policy::signup_forbidden_response,},rate_limit_config::RATE_LIMIT_CONFIG,@@ -95,6 +96,26 @@ fn identity_provider_name(user: &FusionAuthWebhookUser) -> (Option<String>, Opti}}+/// Whether the signup request asked for an agent. Only `/login/passwordless`+/// writes this metadata.+fn signup_requested_agent(user: &FusionAuthWebhookUser) -> bool {+ user.data+ .as_ref()+ .and_then(|data| data.get(AGENT_SIGNUP_DATA_KEY))+ .and_then(serde_json::Value::as_bool)+ .unwrap_or(false)+}++async fn has_pending_agent_invite(+ teams_service: &TeamsServiceType,+ email: &str,+) -> anyhow::Result<bool> {+ let user_id = MacroUserIdStr::try_from_email(email)?;+ let invites = teams_service.get_user_invites(&user_id).await?;++ Ok(invites.iter().any(|invite| invite.is_agent))+}+/// FusionAuth create user webhook#[tracing::instrument(skip(ctx, req, _internal_authorization),@@ -255,12 +276,14 @@ async fn create_user_webhook_complete(ip_address = %req.event.info.ip_address,user_id = tracing::field::Empty,organization_id = tracing::field::Empty,+ is_agent = tracing::field::Empty,),err)]async fn create_user_webhook(ctx: &ApiContext, req: FusionAuthUserWebhook) -> anyhow::Result<()> {let ip_address = req.event.info.ip_address;let email = req.event.user.email.to_lowercase();+ let requested_agent = signup_requested_agent(&req.event.user);let (first_name, last_name) = identity_provider_name(&req.event.user);let username = req.event.user.username.unwrap_or(email.clone());let fusionauth_user_id = req.event.user.id;@@ -268,11 +291,9 @@ async fn create_user_webhook(ctx: &ApiContext, req: FusionAuthUserWebhook) -> an// FusionAuth's own email validation is more permissive than ours (e.g. it allows// single quotes). The user.create event is transactional (AbsoluteMajority), so// returning an error here aborts the FusionAuth user creation entirely.- let parsed_email = match Email::parse_from_str(&email) {- Ok(email) => email,- Err(e) => anyhow::bail!("email is not a valid macro email: {e}"),- };- let support_channel_name = support_channel_name(&parsed_email);+ if let Err(e) = Email::parse_from_str(&email) {+ anyhow::bail!("email is not a valid macro email: {e}");+ }// rate limit check for user creationlet rate_limit = ctx@@ -315,6 +336,9 @@ async fn create_user_webhook(ctx: &ApiContext, req: FusionAuthUserWebhook) -> ananyhow::bail!("cannot login through secondary account link");}+ let is_agent = requested_agent || has_pending_agent_invite(&ctx.teams_service, &email).await?;+ tracing::Span::current().record("is_agent", is_agent);+tracing::info!(has_first_name = first_name.is_some(),has_last_name = last_name.is_some(),@@ -328,6 +352,7 @@ async fn create_user_webhook(ctx: &ApiContext, req: FusionAuthUserWebhook) -> anreq.event.user.verified,&ctx.db,&ctx.stripe_client,+ is_agent,).await?;@@ -393,12 +418,18 @@ async fn create_user_webhook(ctx: &ApiContext, req: FusionAuthUserWebhook) -> anserde_json::json!({"verified": verified,"hasOrganization": has_organization,+ "isAgent": is_agent,}),).await.inspect(|_| tracing::info!("tracked PostHog sign_up event")).inspect_err(|e| tracing::warn!(error=?e, "failed to track PostHog sign_up event"));+ // Ad platforms optimize toward people who sign up.+ if is_agent {+ return;+ }+let user_data = MetaUserData {email: Some(email),client_ip_address: Some(ip_address),@@ -433,36 +464,6 @@ async fn create_user_webhook(ctx: &ApiContext, req: FusionAuthUserWebhook) -> an.in_current_span()});- // Tell Loops the account now exists. This upserts the contact into our- // marketing audience, triggers the welcome sequence, and is the exit- // condition for the mobile-lead nurture sequence — so a lead who converts- // stops being asked to sign up. Fire-and-forget: a Loops failure must never- // block user creation.- tokio::spawn({- let loops_client = ctx.loops_client.clone();- let email = loops_client::normalize_email(&email);- let user_id = user_id.clone();- async move {- let _ = loops_client- .send_event(- &email,- "user_registered",- &serde_json::json!({- "signupStage": "registered",- "hasAccount": true,- "source": "macro-signup",- }),- Some(&format!("user-registered-{user_id}")),- )- .await- .inspect(|_| tracing::info!("sent Loops user_registered event"))- .inspect_err(- |e| tracing::error!(error=?e, "failed to send Loops user_registered event"),- );- }- .in_current_span()- });-// add user to all active experimentstokio::spawn({let db = ctx.db.clone();@@ -509,6 +510,64 @@ async fn create_user_webhook(ctx: &ApiContext, req: FusionAuthUserWebhook) -> an.in_current_span()});+ // Agents get an SDK token instead: no marketing sequence, sample content,+ // or support channel.+ if !is_agent {+ spawn_human_signup_content(ctx, &user_id, &email);+ }++ // Allow to fail silently+ let _ = ctx+ .macro_cache_client+ .increment_create_user_hourly_rate_limit(&ip_address)+ .await+ .inspect_err(|e| tracing::error!(error=?e, "unable to increment create user rate limit"));++ Ok(())+}++/// Marketing and sample content for a person's new account. Fire-and-forget:+/// none of it may block signing in.+fn spawn_human_signup_content(ctx: &ApiContext, user_id: &str, email: &str) {+ let support_channel_name = match Email::parse_from_str(email) {+ Ok(email) => support_channel_name(&email),+ Err(e) => {+ tracing::error!(error=?e, "unable to parse email for support channel");+ return;+ }+ };+ let user_id = user_id.to_string();++ // Tell Loops the account now exists. This upserts the contact into our+ // marketing audience, triggers the welcome sequence, and is the exit+ // condition for the mobile-lead nurture sequence — so a lead who converts+ // stops being asked to sign up. Fire-and-forget: a Loops failure must never+ // block user creation.+ tokio::spawn({+ let loops_client = ctx.loops_client.clone();+ let email = loops_client::normalize_email(email);+ let user_id = user_id.clone();+ async move {+ let _ = loops_client+ .send_event(+ &email,+ "user_registered",+ &serde_json::json!({+ "signupStage": "registered",+ "hasAccount": true,+ "source": "macro-signup",+ }),+ Some(&format!("user-registered-{user_id}")),+ )+ .await+ .inspect(|_| tracing::info!("sent Loops user_registered event"))+ .inspect_err(+ |e| tracing::error!(error=?e, "failed to send Loops user_registered event"),+ );+ }+ .in_current_span()+ });+// Seed the starter documents (the "Macro how to guide" and the starter// tasks it links to, with the guide pinned to the new user's sidebar// favorites), then create a private support channel connecting the new@@ -591,15 +650,22 @@ async fn create_user_webhook(ctx: &ApiContext, req: FusionAuthUserWebhook) -> an}.in_current_span()});+}- // Allow to fail silently- let _ = ctx- .macro_cache_client- .increment_create_user_hourly_rate_limit(&ip_address)+/// Someone asked to sign in to this address as a person: undo an agent flag+/// nobody has proven, and give them the content a person's signup skips. A+/// failure here must not block signing in.+pub(in crate::api) async fn revert_unconfirmed_agent(ctx: &ApiContext, user_id: &str, email: &str) {+ match macro_db_client::user::revert_unconfirmed_agent::revert_unconfirmed_agent(&ctx.db, email).await- .inspect_err(|e| tracing::error!(error=?e, "unable to increment create user rate limit"));-- Ok(())+ {+ Ok(true) => {+ tracing::warn!(user_id, "reverted unconfirmed agent account to a person");+ spawn_human_signup_content(ctx, user_id, email);+ }+ Ok(false) => {}+ Err(e) => tracing::error!(error=?e, user_id, "unable to revert unconfirmed agent account"),+ }}/// Seed the starter documents with retries.diff --git a/services/authentication_service/src/api/webhooks/user/create_user_webhook/test.rs b/services/authentication_service/src/api/webhooks/user/create_user_webhook/test.rsindex ce46c91626..ea4d032fcd 100644--- a/services/authentication_service/src/api/webhooks/user/create_user_webhook/test.rs+++ b/services/authentication_service/src/api/webhooks/user/create_user_webhook/test.rs@@ -15,7 +15,8 @@ use macro_user_id::user_id::MacroUserIdStr;use super::{MACRO_SUPPORT_EMAILS, UserCreateWebhookError, dispatch_user_create_webhook,- identity_provider_name, support_channel_name, user_create_webhook_error_response,+ identity_provider_name, signup_requested_agent, support_channel_name,+ user_create_webhook_error_response,};/// A bad entry would skip support channel creation for every signup.@@ -221,3 +222,19 @@ fn identity_provider_name_keeps_partial_name() {(Some("Evan".to_string()), None));}++#[test]+fn only_explicit_signup_metadata_requests_an_agent() {+ let with_data = |data: Option<Value>| FusionAuthWebhookUser {+ data,+ ..webhook_user(None, None, None)+ };++ assert!(signup_requested_agent(&with_data(Some(+ serde_json::json!({ "isAgent": true })+ ))));+ assert!(!signup_requested_agent(&with_data(Some(+ serde_json::json!({ "isAgent": false })+ ))));+ assert!(!signup_requested_agent(&with_data(None)));+}diff --git a/services/authentication_service/src/server.rs b/services/authentication_service/src/server.rsindex 63cdcaa104..abbfd9c31a 100644--- a/services/authentication_service/src/server.rs+++ b/services/authentication_service/src/server.rs@@ -48,6 +48,7 @@ use macro_authorization::{use macro_event_broker::{KafkaEventPublisher, MacroEventBrokerService};use macro_service_urls::{AppServiceUrl, ConnectionGatewayUrl, DocumentStorageServiceUrl, EmailServiceUrl,+ StaticFilePublicUrl, StaticFileServiceUrl,};use native_app_service::{domain::{models::PlatformData, service::NativeAppServiceImpl},@@ -63,6 +64,7 @@ use roles_and_permissions::{};use secretsmanager_client::SecretManager;use sqlx::postgres::PgPoolOptions;+use static_file_service_client::StaticFileServiceClient;use teams::{domain::team_service::TeamServiceImpl,outbound::{@@ -272,6 +274,12 @@ pub async fn run() -> anyhow::Result<()> {) as Arc<dyn MicrosoftAuth>});+ let static_file_service_client = Arc::new(StaticFileServiceClient::with_timeout(+ config.service_internal_auth_key.to_string(),+ StaticFileServiceUrl::new()?.to_string(),+ std::time::Duration::from_secs(10),+ ));+ let static_file_public_url = StaticFilePublicUrl::new()?.to_string();let document_storage_service_client = DocumentStorageServiceClient::new(config.service_internal_auth_key.to_string().clone(),DocumentStorageServiceUrl::new()?.to_string(),@@ -773,6 +781,8 @@ pub async fn run() -> anyhow::Result<()> {subscription_plan,subscription_status,document_storage_service_client,+ static_file_service_client,+ static_file_public_url,user_deletion,email_service_client: Arc::new(email_service_client),ses_client: Arc::new(ses_client),diff --git a/services/authentication_service/src/service/user/agent_signup.rs b/services/authentication_service/src/service/user/agent_signup.rsnew file mode 100644index 0000000000..f93e7fbf27--- /dev/null+++ b/services/authentication_service/src/service/user/agent_signup.rs@@ -0,0 +1,8 @@+//! Agent accounts: an account flagged at signup that gets an SDK token instead+//! of onboarding.++/// FusionAuth user metadata key marking a signup that asked for an agent.+pub(crate) const AGENT_SIGNUP_DATA_KEY: &str = "isAgent";++/// Name of the API key shown during agent setup. Repeating setup replaces it.+pub(crate) const AGENT_SIGNUP_KEY_NAME: &str = "Agent signup";diff --git a/services/authentication_service/src/service/user/create_user.rs b/services/authentication_service/src/service/user/create_user.rsindex 609a23f6ce..acf7f9d01b 100644--- a/services/authentication_service/src/service/user/create_user.rs+++ b/services/authentication_service/src/service/user/create_user.rs@@ -38,6 +38,7 @@ pub async fn create_user(is_verified: bool,db: &sqlx::Pool<sqlx::Postgres>,stripe_client: &stripe::Client,+ is_agent: bool,) -> anyhow::Result<(String, Option<i32>)> {let stripe_customer_id = if is_local_stripe_stub() {// Local mode uses a stub key; don't call Stripe (it would 401 and@@ -84,6 +85,7 @@ pub async fn create_user(stripe_customer_id.as_deref(),organization_id,roles,+ is_agent,).await?;diff --git a/services/authentication_service/src/service/user/mod.rs b/services/authentication_service/src/service/user/mod.rsindex a517a959fd..0d4bd2f562 100644--- a/services/authentication_service/src/service/user/mod.rs+++ b/services/authentication_service/src/service/user/mod.rs@@ -1,3 +1,4 @@+pub mod agent_signup;pub mod create_user;pub mod delete_user;pub mod support_channel_welcome;diff --git a/tooling/seed_cli/src/entity/user.rs b/tooling/seed_cli/src/entity/user.rsindex 717ee31ce4..76601577d6 100644--- a/tooling/seed_cli/src/entity/user.rs+++ b/tooling/seed_cli/src/entity/user.rs@@ -60,6 +60,7 @@ async fn create(args: CreateArgs, ctx: SeedCliContext) -> anyhow::Result<()> {let user_id = ctx.fusionauth_client.create_user(fusionauth::user::create::User {+ data: None,email: Cow::Borrowed(&args.email),username: Some(Cow::Borrowed(&args.email)),// TODO: do we want to bother with random generated passwords?@@ -98,6 +99,7 @@ async fn bulk_create(args: BulkCreateArgs, ctx: SeedCliContext) -> anyhow::Resulmatch ctx.fusionauth_client.create_user(fusionauth::user::create::User {+ data: None,email: Cow::Borrowed(email),username: Some(Cow::Borrowed(email)),password: "hardcodeLocalPassword123!".into(),diff --git a/tooling/seed_cli/src/service/auth.rs b/tooling/seed_cli/src/service/auth.rsindex 8d60c7de76..af263777fb 100644--- a/tooling/seed_cli/src/service/auth.rs+++ b/tooling/seed_cli/src/service/auth.rs@@ -62,6 +62,7 @@ impl SeedAuth {}self.create_user(fusionauth::user::create::User {+ data: None,email: std::borrow::Cow::Owned(email.clone()),username: None,password: "hardcodeLocalPassword123!".into(),