Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(routines): share routines as templates others can activate (#8901)

Eric Hayese57081fe19a2
diff --git a/.sqlx/query-732d1f99ec6e068e2f38277ea773d140dcaf693cd05398f7a3b832de476978c7.json b/.sqlx/query-0cb3f858ff458fda8e8efdc5b81bce0c1dc308a960f66e30a95c6e8a49b11fde.json
similarity index 88%
rename from .sqlx/query-732d1f99ec6e068e2f38277ea773d140dcaf693cd05398f7a3b832de476978c7.json
rename to .sqlx/query-0cb3f858ff458fda8e8efdc5b81bce0c1dc308a960f66e30a95c6e8a49b11fde.json
index 2856753f21..d88558c2da 100644
--- a/.sqlx/query-732d1f99ec6e068e2f38277ea773d140dcaf693cd05398f7a3b832de476978c7.json
+++ b/.sqlx/query-0cb3f858ff458fda8e8efdc5b81bce0c1dc308a960f66e30a95c6e8a49b11fde.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT id, owner, name, schedule, kind, timezone, task, claimed, created_at,\n updated_at, next_run_at, enabled, trigger_type, event_filters,\n configuration_revision, event_activated_at, trigger_config, run_visibility\n FROM scheduled_action\n WHERE owner = $1\n ",
+ "query": "\n SELECT id, owner, name, schedule, kind, timezone, task, claimed, created_at,\n updated_at, next_run_at, enabled, trigger_type, event_filters,\n configuration_revision, event_activated_at, trigger_config, run_visibility, template_id\n FROM scheduled_action\n WHERE owner = $1\n ",
"describe": {
"columns": [
{
@@ -92,6 +92,11 @@
"ordinal": 17,
"name": "run_visibility",
"type_info": "Text"
+ },
+ {
+ "ordinal": 18,
+ "name": "template_id",
+ "type_info": "Uuid"
}
],
"parameters": {
@@ -117,8 +122,9 @@
false,
true,
true,
- false
+ false,
+ true
]
},
- "hash": "732d1f99ec6e068e2f38277ea773d140dcaf693cd05398f7a3b832de476978c7"
+ "hash": "0cb3f858ff458fda8e8efdc5b81bce0c1dc308a960f66e30a95c6e8a49b11fde"
}
diff --git a/.sqlx/query-c148e946377acc6405255402d91bcb1b838ae21eb64bc1b8e9f33c0d5eec0671.json b/.sqlx/query-339fd0e2a1902209e20dae1b5191a8b9ba61686541cc8e4f9dd8b10de39e4aa5.json
similarity index 82%
rename from .sqlx/query-c148e946377acc6405255402d91bcb1b838ae21eb64bc1b8e9f33c0d5eec0671.json
rename to .sqlx/query-339fd0e2a1902209e20dae1b5191a8b9ba61686541cc8e4f9dd8b10de39e4aa5.json
index 2c78a42da2..f634941e82 100644
--- a/.sqlx/query-c148e946377acc6405255402d91bcb1b838ae21eb64bc1b8e9f33c0d5eec0671.json
+++ b/.sqlx/query-339fd0e2a1902209e20dae1b5191a8b9ba61686541cc8e4f9dd8b10de39e4aa5.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT id, owner, name, schedule, kind, timezone, task, claimed, created_at,\n updated_at, next_run_at, enabled, trigger_type, event_filters,\n configuration_revision, event_activated_at, trigger_config, run_visibility\n FROM scheduled_action\n WHERE enabled AND trigger_type IN ('cron', 'multiple') AND next_run_at IS NOT NULL\n AND (claimed IS NULL OR claimed < $1)\n ORDER BY next_run_at ASC, id ASC\n LIMIT $2\n ",
+ "query": "\n SELECT id, owner, name, schedule, kind, timezone, task, claimed, created_at,\n updated_at, next_run_at, enabled, trigger_type, event_filters,\n configuration_revision, event_activated_at, trigger_config, run_visibility, template_id\n FROM scheduled_action\n WHERE enabled AND trigger_type IN ('cron', 'multiple') AND next_run_at IS NOT NULL\n AND (claimed IS NULL OR claimed < $1)\n ORDER BY next_run_at ASC, id ASC\n LIMIT $2\n ",
"describe": {
"columns": [
{
@@ -92,6 +92,11 @@
"ordinal": 17,
"name": "run_visibility",
"type_info": "Text"
+ },
+ {
+ "ordinal": 18,
+ "name": "template_id",
+ "type_info": "Uuid"
}
],
"parameters": {
@@ -118,8 +123,9 @@
false,
true,
true,
- false
+ false,
+ true
]
},
- "hash": "c148e946377acc6405255402d91bcb1b838ae21eb64bc1b8e9f33c0d5eec0671"
+ "hash": "339fd0e2a1902209e20dae1b5191a8b9ba61686541cc8e4f9dd8b10de39e4aa5"
}
diff --git a/.sqlx/query-e1d42468d2b2401c0d05aa3f38e6431d227d5bda371f75d4e5bd1f48c3fb54b4.json b/.sqlx/query-4ea812c6e1eddc69e23c3bf23165283ff94cd1544bc135e89e0dcbbfd21a157c.json
similarity index 79%
rename from .sqlx/query-e1d42468d2b2401c0d05aa3f38e6431d227d5bda371f75d4e5bd1f48c3fb54b4.json
rename to .sqlx/query-4ea812c6e1eddc69e23c3bf23165283ff94cd1544bc135e89e0dcbbfd21a157c.json
index ca070d0569..5cb3f76878 100644
--- a/.sqlx/query-e1d42468d2b2401c0d05aa3f38e6431d227d5bda371f75d4e5bd1f48c3fb54b4.json
+++ b/.sqlx/query-4ea812c6e1eddc69e23c3bf23165283ff94cd1544bc135e89e0dcbbfd21a157c.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n INSERT INTO scheduled_action\n (id, owner, name, schedule, kind, timezone, task, next_run_at, enabled,\n trigger_type, event_filters, configuration_revision, event_activated_at, trigger_config,\n run_visibility)\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15)\n RETURNING id, owner, name, schedule, kind, timezone, task, claimed, created_at,\n updated_at, next_run_at, enabled, trigger_type, event_filters,\n configuration_revision, event_activated_at, trigger_config, run_visibility\n ",
+ "query": "\n INSERT INTO scheduled_action\n (id, owner, name, schedule, kind, timezone, task, next_run_at, enabled,\n trigger_type, event_filters, configuration_revision, event_activated_at, trigger_config,\n run_visibility, template_id)\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16)\n RETURNING id, owner, name, schedule, kind, timezone, task, claimed, created_at,\n updated_at, next_run_at, enabled, trigger_type, event_filters,\n configuration_revision, event_activated_at, trigger_config, run_visibility, template_id\n ",
"describe": {
"columns": [
{
@@ -92,6 +92,11 @@
"ordinal": 17,
"name": "run_visibility",
"type_info": "Text"
+ },
+ {
+ "ordinal": 18,
+ "name": "template_id",
+ "type_info": "Uuid"
}
],
"parameters": {
@@ -110,7 +115,8 @@
"Int8",
"Timestamptz",
"Jsonb",
- "Text"
+ "Text",
+ "Uuid"
]
},
"nullable": [
@@ -131,8 +137,9 @@
false,
true,
true,
- false
+ false,
+ true
]
},
- "hash": "e1d42468d2b2401c0d05aa3f38e6431d227d5bda371f75d4e5bd1f48c3fb54b4"
+ "hash": "4ea812c6e1eddc69e23c3bf23165283ff94cd1544bc135e89e0dcbbfd21a157c"
}
diff --git a/.sqlx/query-25e8d0c6107cbed40084681e520b4efbe35b59a902abe83e021856bf53edc8f2.json b/.sqlx/query-524c351334625b88bdcce2cabd2fc3bb250614590fb4e6b9d29750f0cadfbed0.json
similarity index 88%
rename from .sqlx/query-25e8d0c6107cbed40084681e520b4efbe35b59a902abe83e021856bf53edc8f2.json
rename to .sqlx/query-524c351334625b88bdcce2cabd2fc3bb250614590fb4e6b9d29750f0cadfbed0.json
index 6458987e74..9c4b483633 100644
--- a/.sqlx/query-25e8d0c6107cbed40084681e520b4efbe35b59a902abe83e021856bf53edc8f2.json
+++ b/.sqlx/query-524c351334625b88bdcce2cabd2fc3bb250614590fb4e6b9d29750f0cadfbed0.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT id, owner, name, schedule, kind, timezone, task, claimed, created_at,\n updated_at, next_run_at, enabled, trigger_type, event_filters,\n configuration_revision, event_activated_at, trigger_config, run_visibility\n FROM scheduled_action\n WHERE id = $1\n ",
+ "query": "\n SELECT id, owner, name, schedule, kind, timezone, task, claimed, created_at,\n updated_at, next_run_at, enabled, trigger_type, event_filters,\n configuration_revision, event_activated_at, trigger_config, run_visibility, template_id\n FROM scheduled_action\n WHERE id = $1\n ",
"describe": {
"columns": [
{
@@ -92,6 +92,11 @@
"ordinal": 17,
"name": "run_visibility",
"type_info": "Text"
+ },
+ {
+ "ordinal": 18,
+ "name": "template_id",
+ "type_info": "Uuid"
}
],
"parameters": {
@@ -117,8 +122,9 @@
false,
true,
true,
- false
+ false,
+ true
]
},
- "hash": "25e8d0c6107cbed40084681e520b4efbe35b59a902abe83e021856bf53edc8f2"
+ "hash": "524c351334625b88bdcce2cabd2fc3bb250614590fb4e6b9d29750f0cadfbed0"
}
diff --git a/.sqlx/query-2a7a015e357ab5ac1d83531e3640cbd03881ccff424e1ead55b2603e25b5dd87.json b/.sqlx/query-637babd3f4f561777c40c1cc54afb8d3ded56d4998b89448102ad869fb706e42.json
similarity index 68%
rename from .sqlx/query-2a7a015e357ab5ac1d83531e3640cbd03881ccff424e1ead55b2603e25b5dd87.json
rename to .sqlx/query-637babd3f4f561777c40c1cc54afb8d3ded56d4998b89448102ad869fb706e42.json
index 55d24e17ec..f70d61a926 100644
--- a/.sqlx/query-2a7a015e357ab5ac1d83531e3640cbd03881ccff424e1ead55b2603e25b5dd87.json
+++ b/.sqlx/query-637babd3f4f561777c40c1cc54afb8d3ded56d4998b89448102ad869fb706e42.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT id, owner, name, kind, task, created_at, updated_at, enabled, run_visibility,\n event_filters AS \"event_filters!\", event_activated_at AS \"event_activated_at!\"\n FROM scheduled_action\n WHERE id = $1 AND enabled AND event_filters IS NOT NULL AND configuration_revision = $2\n AND (claimed IS NULL OR claimed < $3)\n AND NOT EXISTS (SELECT 1 FROM scheduled_action_event_run WHERE action_id = $1 AND state = 'started')\n ",
+ "query": "\n SELECT id, owner, name, kind, task, created_at, updated_at, enabled, run_visibility, template_id,\n event_filters AS \"event_filters!\", event_activated_at AS \"event_activated_at!\"\n FROM scheduled_action\n WHERE id = $1 AND enabled AND event_filters IS NOT NULL AND configuration_revision = $2\n AND (claimed IS NULL OR claimed < $3)\n AND NOT EXISTS (SELECT 1 FROM scheduled_action_event_run WHERE action_id = $1 AND state = 'started')\n ",
"describe": {
"columns": [
{
@@ -50,11 +50,16 @@
},
{
"ordinal": 9,
+ "name": "template_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 10,
"name": "event_filters!",
"type_info": "Jsonb"
},
{
- "ordinal": 10,
+ "ordinal": 11,
"name": "event_activated_at!",
"type_info": "Timestamptz"
}
@@ -77,8 +82,9 @@
false,
false,
true,
+ true,
true
]
},
- "hash": "2a7a015e357ab5ac1d83531e3640cbd03881ccff424e1ead55b2603e25b5dd87"
+ "hash": "637babd3f4f561777c40c1cc54afb8d3ded56d4998b89448102ad869fb706e42"
}
diff --git a/.sqlx/query-a1b86eff56bc2db8f6d7f89e4e091e01dfe97116329a1f0021d7a72bd2f18914.json b/.sqlx/query-65781aa8f98a5054cb60b8c4d02c3f79da606d877d9a2dde2ea79fa2035eb748.json
similarity index 93%
rename from .sqlx/query-a1b86eff56bc2db8f6d7f89e4e091e01dfe97116329a1f0021d7a72bd2f18914.json
rename to .sqlx/query-65781aa8f98a5054cb60b8c4d02c3f79da606d877d9a2dde2ea79fa2035eb748.json
index 3bef053523..5dc12ff3d0 100644
--- a/.sqlx/query-a1b86eff56bc2db8f6d7f89e4e091e01dfe97116329a1f0021d7a72bd2f18914.json
+++ b/.sqlx/query-65781aa8f98a5054cb60b8c4d02c3f79da606d877d9a2dde2ea79fa2035eb748.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n UPDATE scheduled_action\n SET name = $1,\n schedule = $2,\n kind = $3,\n timezone = $4,\n task = $5,\n next_run_at = $6,\n enabled = $7,\n trigger_type = $8,\n event_filters = $9,\n configuration_revision = $10,\n event_activated_at = $11,\n trigger_config = $14,\n run_visibility = $15,\n updated_at = now()\n WHERE id = $12\n AND configuration_revision = $10::bigint - 1\n AND (\n claimed IS NULL OR claimed < $13\n OR (\n NOT $7 AND name = $1 AND kind = $3 AND task = $5\n AND trigger_type = $8\n AND schedule IS NOT DISTINCT FROM $2\n AND timezone IS NOT DISTINCT FROM $4\n AND event_filters IS NOT DISTINCT FROM $9\n AND trigger_config IS NOT DISTINCT FROM $14\n AND run_visibility = $15\n )\n )\n RETURNING id, owner, name, schedule, kind, timezone, task, claimed, created_at,\n updated_at, next_run_at, enabled, trigger_type, event_filters,\n configuration_revision, event_activated_at, trigger_config, run_visibility\n ",
+ "query": "\n UPDATE scheduled_action\n SET name = $1,\n schedule = $2,\n kind = $3,\n timezone = $4,\n task = $5,\n next_run_at = $6,\n enabled = $7,\n trigger_type = $8,\n event_filters = $9,\n configuration_revision = $10,\n event_activated_at = $11,\n trigger_config = $14,\n run_visibility = $15,\n updated_at = now()\n WHERE id = $12\n AND configuration_revision = $10::bigint - 1\n AND (\n claimed IS NULL OR claimed < $13\n OR (\n NOT $7 AND name = $1 AND kind = $3 AND task = $5\n AND trigger_type = $8\n AND schedule IS NOT DISTINCT FROM $2\n AND timezone IS NOT DISTINCT FROM $4\n AND event_filters IS NOT DISTINCT FROM $9\n AND trigger_config IS NOT DISTINCT FROM $14\n AND run_visibility = $15\n )\n )\n RETURNING id, owner, name, schedule, kind, timezone, task, claimed, created_at,\n updated_at, next_run_at, enabled, trigger_type, event_filters,\n configuration_revision, event_activated_at, trigger_config, run_visibility, template_id\n ",
"describe": {
"columns": [
{
@@ -92,6 +92,11 @@
"ordinal": 17,
"name": "run_visibility",
"type_info": "Text"
+ },
+ {
+ "ordinal": 18,
+ "name": "template_id",
+ "type_info": "Uuid"
}
],
"parameters": {
@@ -131,8 +136,9 @@
false,
true,
true,
- false
+ false,
+ true
]
},
- "hash": "a1b86eff56bc2db8f6d7f89e4e091e01dfe97116329a1f0021d7a72bd2f18914"
+ "hash": "65781aa8f98a5054cb60b8c4d02c3f79da606d877d9a2dde2ea79fa2035eb748"
}
diff --git a/.sqlx/query-81239baf982bc081d1ca96453a895aef75262b44a6ca7362a8373b1c7477d53c.json b/.sqlx/query-81239baf982bc081d1ca96453a895aef75262b44a6ca7362a8373b1c7477d53c.json
new file mode 100644
index 0000000000..71daf734fd
--- /dev/null
+++ b/.sqlx/query-81239baf982bc081d1ca96453a895aef75262b44a6ca7362a8373b1c7477d53c.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "DELETE FROM scheduled_action_template WHERE action_id = $1",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "81239baf982bc081d1ca96453a895aef75262b44a6ca7362a8373b1c7477d53c"
+}
diff --git a/.sqlx/query-84fa96987eaa5d234bb3e34cc52de29bc2a86e4dc8270a99602eeca1598d4355.json b/.sqlx/query-84fa96987eaa5d234bb3e34cc52de29bc2a86e4dc8270a99602eeca1598d4355.json
new file mode 100644
index 0000000000..b95ea7b5ae
--- /dev/null
+++ b/.sqlx/query-84fa96987eaa5d234bb3e34cc52de29bc2a86e4dc8270a99602eeca1598d4355.json
@@ -0,0 +1,19 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO scheduled_action_template\n (action_id, name, description, trigger_config, task, variables)\n VALUES ($1, $2, $3, $4, $5, $6)\n ON CONFLICT (action_id) DO UPDATE\n SET name = EXCLUDED.name,\n description = EXCLUDED.description,\n trigger_config = EXCLUDED.trigger_config,\n task = EXCLUDED.task,\n variables = EXCLUDED.variables,\n updated_at = now()\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Text",
+ "Jsonb",
+ "Jsonb",
+ "Jsonb"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "84fa96987eaa5d234bb3e34cc52de29bc2a86e4dc8270a99602eeca1598d4355"
+}
diff --git a/.sqlx/query-88adcae2d546e601b07fd5db26a02a7e09048666028a182d45d6ee3374100412.json b/.sqlx/query-9368353b960a8ad7a15486869955277fb4387902f11b8d4efea1f7219cc5e731.json
similarity index 88%
rename from .sqlx/query-88adcae2d546e601b07fd5db26a02a7e09048666028a182d45d6ee3374100412.json
rename to .sqlx/query-9368353b960a8ad7a15486869955277fb4387902f11b8d4efea1f7219cc5e731.json
index a303b7e71b..44f61a4e8e 100644
--- a/.sqlx/query-88adcae2d546e601b07fd5db26a02a7e09048666028a182d45d6ee3374100412.json
+++ b/.sqlx/query-9368353b960a8ad7a15486869955277fb4387902f11b8d4efea1f7219cc5e731.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT id, owner, name, schedule, kind, timezone, task, claimed, created_at,\n updated_at, next_run_at, enabled, trigger_type, event_filters, trigger_config,\n configuration_revision, event_activated_at, run_visibility\n FROM scheduled_action\n WHERE id = ANY($1)\n ",
+ "query": "\n SELECT id, owner, name, schedule, kind, timezone, task, claimed, created_at,\n updated_at, next_run_at, enabled, trigger_type, event_filters, trigger_config,\n configuration_revision, event_activated_at, run_visibility, template_id\n FROM scheduled_action\n WHERE id = ANY($1)\n ",
"describe": {
"columns": [
{
@@ -92,6 +92,11 @@
"ordinal": 17,
"name": "run_visibility",
"type_info": "Text"
+ },
+ {
+ "ordinal": 18,
+ "name": "template_id",
+ "type_info": "Uuid"
}
],
"parameters": {
@@ -117,8 +122,9 @@
true,
false,
true,
- false
+ false,
+ true
]
},
- "hash": "88adcae2d546e601b07fd5db26a02a7e09048666028a182d45d6ee3374100412"
+ "hash": "9368353b960a8ad7a15486869955277fb4387902f11b8d4efea1f7219cc5e731"
}
diff --git a/.sqlx/query-9f59811fb94484b6b712ae397b22c7232a4122ac9fc29b2135b38c16809f6d6f.json b/.sqlx/query-9f59811fb94484b6b712ae397b22c7232a4122ac9fc29b2135b38c16809f6d6f.json
new file mode 100644
index 0000000000..42fea5f00e
--- /dev/null
+++ b/.sqlx/query-9f59811fb94484b6b712ae397b22c7232a4122ac9fc29b2135b38c16809f6d6f.json
@@ -0,0 +1,76 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT t.action_id, a.owner, t.name, t.description, t.trigger_config, t.task,\n t.variables, t.created_at, t.updated_at,\n (SELECT count(*) FROM scheduled_action s WHERE s.template_id = t.action_id)\n AS \"active_count!\"\n FROM scheduled_action_template t\n JOIN scheduled_action a ON a.id = t.action_id\n WHERE t.action_id = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "action_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "owner",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "name",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "description",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 4,
+ "name": "trigger_config",
+ "type_info": "Jsonb"
+ },
+ {
+ "ordinal": 5,
+ "name": "task",
+ "type_info": "Jsonb"
+ },
+ {
+ "ordinal": 6,
+ "name": "variables",
+ "type_info": "Jsonb"
+ },
+ {
+ "ordinal": 7,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 8,
+ "name": "updated_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 9,
+ "name": "active_count!",
+ "type_info": "Int8"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ null
+ ]
+ },
+ "hash": "9f59811fb94484b6b712ae397b22c7232a4122ac9fc29b2135b38c16809f6d6f"
+}
diff --git a/apps/web/src/features/channel/Message/Content.tsx b/apps/web/src/features/channel/Message/Content.tsx
index 7192cf7042..c3c00b1632 100644
--- a/apps/web/src/features/channel/Message/Content.tsx
+++ b/apps/web/src/features/channel/Message/Content.tsx
@@ -20,6 +20,7 @@ import {
} from './context';
import { createSearchHighlightOverlay } from './highlightOverlay';
import { MentionedImages } from './MentionedImages';
+import { MentionedRoutineTemplates } from './MentionedRoutineTemplates';
// Height (px) a long body is cut to while collapsed.
const COLLAPSED_MAX_HEIGHT = 240;
@@ -56,6 +57,7 @@ export function Content(props: ContentProps) {
rootRef={setMarkdownRoot}
/>
<MentionedImages content={content()} />
+ <MentionedRoutineTemplates content={content()} />
</>
);
diff --git a/apps/web/src/features/channel/Message/MentionedRoutineTemplates.tsx b/apps/web/src/features/channel/Message/MentionedRoutineTemplates.tsx
new file mode 100644
index 0000000000..7c7be40e0b
--- /dev/null
+++ b/apps/web/src/features/channel/Message/MentionedRoutineTemplates.tsx
@@ -0,0 +1,32 @@
+import { getDocumentMentions } from '@core/util/documentMentions';
+import { lazyNamed } from '@core/util/lazyNamed';
+import { createMemo, For, Show, Suspense } from 'solid-js';
+
+const RoutineTemplateCard = lazyNamed(
+ () => import('@app/features/routines/routine-template'),
+ 'RoutineTemplateCard'
+);
+
+/**
+ * Routines mentioned in a message that are shared as templates, as cards
+ * beneath its text that people can view or activate for themselves.
+ */
+export function MentionedRoutineTemplates(props: { content: string }) {
+ const routineIds = createMemo(() =>
+ getDocumentMentions(props.content)
+ .filter(
+ (mention) =>
+ mention.blockName === 'routine' || mention.blockName === 'automation'
+ )
+ .map((mention) => mention.documentId)
+ );
+ return (
+ <Show when={routineIds().length > 0}>
+ <Suspense>
+ <For each={routineIds()}>
+ {(routineId) => <RoutineTemplateCard routineId={routineId} />}
+ </For>
+ </Suspense>
+ </Show>
+ );
+}
diff --git a/apps/web/src/features/routines/components/routine-editor.tsx b/apps/web/src/features/routines/components/routine-editor.tsx
index 8bea3aab40..69be158962 100644
--- a/apps/web/src/features/routines/components/routine-editor.tsx
+++ b/apps/web/src/features/routines/components/routine-editor.tsx
@@ -27,6 +27,8 @@ export function RoutineEditor(props: {
showHistory?: boolean;
actions?: JSX.Element;
feedback?: JSX.Element;
+ /** More properties beside the execution target and run visibility. */
+ properties?: JSX.Element;
}) {
return (
<ViewBreadcrumbs.Root
@@ -148,6 +150,7 @@ export function RoutineEditor(props: {
props.onChange((draft) => ({ ...draft, runVisibility }))
}
/>
+ {props.properties}
{props.apps}
</EntityComposer.Properties>
</fieldset>
diff --git a/apps/web/src/features/routines/components/template-card.tsx b/apps/web/src/features/routines/components/template-card.tsx
new file mode 100644
index 0000000000..79ed684e33
--- /dev/null
+++ b/apps/web/src/features/routines/components/template-card.tsx
@@ -0,0 +1,68 @@
+import ClockCounterIcon from '@icon/system/regular/clock-counter-clockwise.svg';
+import LightningIcon from '@icon/system/regular/lightning.svg';
+import { Badge, Button, Card } from '@ui';
+import { For, Show } from 'solid-js';
+
+/** A shared routine template as a card under the message that links it. */
+export function TemplateCard(props: {
+ name: string;
+ description: string;
+ authorName: string;
+ triggers: readonly string[];
+ activeCount: number;
+ /** False for the author, whose own routine this is. */
+ canActivate: boolean;
+ onView(): void;
+ onActivate(): void;
+}) {
+ return (
+ <Card
+ aria-label={`Routine template: ${props.name}`}
+ class="mt-2 max-w-xl"
+ role="article"
+ >
+ <Card.Header>
+ <Card.Metadata class="flex flex-wrap items-center gap-2">
+ <Badge variant="outline" size="xs">
+ <ClockCounterIcon />
+ Routine template
+ </Badge>
+ by {props.authorName}
+ </Card.Metadata>
+ <Card.Title>{props.name}</Card.Title>
+ <Show when={props.description}>
+ <Card.Description>{props.description}</Card.Description>
+ </Show>
+ </Card.Header>
+ <Show when={props.triggers.length > 0}>
+ <Card.Body class="flex flex-col gap-1 pt-0">
+ <For each={props.triggers}>
+ {(trigger) => (
+ <div class="flex items-center gap-2">
+ <LightningIcon class="size-4 shrink-0 text-ink-muted" />
+ {trigger}
+ </div>
+ )}
+ </For>
+ </Card.Body>
+ </Show>
+ <Card.Footer>
+ <span class="text-sm text-ink-muted">
+ {props.activeCount === 1
+ ? 'Active for 1 person'
+ : `Active for ${props.activeCount} people`}
+ </span>
+ <div class="flex gap-2">
+ <Button variant="outline" size="sm" onClick={() => props.onView()}>
+ View template
+ </Button>
+ <Show when={props.canActivate}>
+ <Button variant="cta" size="sm" onClick={() => props.onActivate()}>
+ Activate for me
+ </Button>
+ </Show>
+ </div>
+ </Card.Footer>
+ </Card>
+ );
+}
diff --git a/apps/web/src/features/routines/components/template-reference.tsx b/apps/web/src/features/routines/components/template-reference.tsx
new file mode 100644
index 0000000000..3187299951
--- /dev/null
+++ b/apps/web/src/features/routines/components/template-reference.tsx
@@ -0,0 +1,69 @@
+import ClockIcon from '@icon/system/regular/clock.svg';
+import FileIcon from '@icon/system/regular/file-text.svg';
+import HashIcon from '@icon/system/regular/hash.svg';
+import LockIcon from '@icon/system/regular/lock-simple.svg';
+import UserIcon from '@icon/system/regular/user.svg';
+import type { TemplateVariable } from '@service-scheduled-action/generated/schemas';
+import { Badge, cn } from '@ui';
+import { type JSX, Match, Switch } from 'solid-js';
+import type { ReferenceState } from '../core/template';
+
+/** The name a reference shows: its label, or the time zone it keeps. */
+export function variableLabel(variable: TemplateVariable): string {
+ return variable.kind === 'time_zone' ? variable.timezone : variable.label;
+}
+
+function ReferenceIcon(props: { variable: TemplateVariable; class?: string }) {
+ return (
+ <Switch fallback={<FileIcon class={props.class} />}>
+ <Match when={props.variable.kind === 'user'}>
+ <UserIcon class={props.class} />
+ </Match>
+ <Match when={props.variable.kind === 'time_zone'}>
+ <ClockIcon class={props.class} />
+ </Match>
+ <Match
+ when={
+ props.variable.kind === 'item' &&
+ props.variable.block_name === 'channel'
+ }
+ >
+ <HashIcon class={props.class} />
+ </Match>
+ </Switch>
+ );
+}
+
+/**
+ * A template reference as a badge: dashed when it fills in as the viewer,
+ * amber when they can't open it, plain when it works for them as it is.
+ */
+export function TemplateReferenceChip(props: {
+ variable: TemplateVariable;
+ state: ReferenceState;
+ /** Overrides the reference's own name, e.g. "you" for the author. */
+ children?: JSX.Element;
+}) {
+ return (
+ <Badge
+ variant="outline"
+ size="sm"
+ class={cn(
+ 'max-w-full',
+ props.state === 'fills_in' && 'border-dashed text-accent',
+ props.state === 'works' && 'text-ink',
+ (props.state === 'unavailable' || props.state === 'choose') &&
+ 'text-warning'
+ )}
+ >
+ {props.state === 'unavailable' ? (
+ <LockIcon class="shrink-0" />
+ ) : (
+ <ReferenceIcon variable={props.variable} class="shrink-0" />
+ )}
+ <span class="truncate">
+ {props.children ?? variableLabel(props.variable)}
+ </span>
+ </Badge>
+ );
+}
diff --git a/apps/web/src/features/routines/core/routine-triggers.ts b/apps/web/src/features/routines/core/routine-triggers.ts
index 2f68bc2ea6..7bb44599e6 100644
--- a/apps/web/src/features/routines/core/routine-triggers.ts
+++ b/apps/web/src/features/routines/core/routine-triggers.ts
@@ -1,4 +1,8 @@
-import { getDefaultTimezone } from '@core/util/cron';
+import {
+ describeCron,
+ formatTimeLabel,
+ getDefaultTimezone,
+} from '@core/util/cron';
import { match } from 'ts-pattern';
import { z } from 'zod';
@@ -292,6 +296,26 @@ export function validateTriggers(
}
return null;
}
+/** One trigger as a sentence, such as "Every Monday at 9:00 AM", without its time zone. */
+export function describeTrigger(trigger: RoutineTriggerDraft): string {
+ if (trigger.kind === 'event') return `When: ${eventTriggerLabel(trigger)}`;
+ return match(trigger.frequency)
+ .with('week', 'month', (frequency) => {
+ const text = describeCron({
+ frequency,
+ time: trigger.time,
+ daysOfWeek: trigger.daysOfWeek,
+ dayOfMonth: trigger.dayOfMonth,
+ });
+ return `${text.charAt(0).toUpperCase()}${text.slice(1)}`;
+ })
+ .with('day', () => `Every day at ${formatTimeLabel(trigger.time)}`)
+ .with('hour', () => 'Every hour')
+ .with('once', () => 'Once')
+ .with('custom', () => `Custom schedule (${trigger.cron})`)
+ .exhaustive();
+}
+
export function describeTriggers(triggers: RoutineTriggerDraft[]): string {
return triggers
.map((trigger) =>
diff --git a/apps/web/src/features/routines/core/routine.ts b/apps/web/src/features/routines/core/routine.ts
index 21abc5a5f6..89a7c31d05 100644
--- a/apps/web/src/features/routines/core/routine.ts
+++ b/apps/web/src/features/routines/core/routine.ts
@@ -12,4 +12,6 @@ export type RoutineSnapshot = {
revision: number;
configurationKey: string;
draft?: ScheduleDraft;
+ /** The shared template this routine was activated from. */
+ templateId?: string;
};
diff --git a/apps/web/src/features/routines/core/template.test.ts b/apps/web/src/features/routines/core/template.test.ts
new file mode 100644
index 0000000000..6d4214f832
--- /dev/null
+++ b/apps/web/src/features/routines/core/template.test.ts
@@ -0,0 +1,154 @@
+import { describe, expect, it } from 'vitest';
+import {
+ extractTemplateVariables,
+ fillTemplatePrompt,
+ fillTemplateTrigger,
+} from './template';
+
+const AUTHOR =
+ '<m-user-mention>{"userId":"macro|[email protected]","email":"[email protected]","displayName":"Eric"}</m-user-mention>';
+const TEAMMATE =
+ '<m-user-mention>{"userId":"macro|[email protected]","email":"[email protected]","displayName":"Priya Shah"}</m-user-mention>';
+const CHANNEL =
+ '<m-document-mention>{"documentId":"channel-1","documentName":"customer-success","blockName":"channel"}</m-document-mention>';
+const DOC =
+ '<m-document-mention>{"documentId":"doc-1","documentName":"Acme account","blockName":"md"}</m-document-mention>';
+
+const PROMPT = `Post the digest to ${CHANNEL}. Pull renewal dates from ${DOC}. Assign follow-ups to ${TEAMMATE} and DM ${AUTHOR} a summary. Repeat in ${CHANNEL}.`;
+
+const CRON = {
+ type: 'cron' as const,
+ schedule: '0 0 9 * * 2',
+ timezone: 'America/Los_Angeles',
+};
+
+const ACTIVATOR = {
+ userId: 'macro|[email protected]',
+ email: '[email protected]',
+ displayName: 'Jun',
+ timezone: 'America/New_York',
+};
+
+describe('extractTemplateVariables', () => {
+ it('fills the author and time zone as the activator and keeps other references', () => {
+ expect(
+ extractTemplateVariables({
+ prompt: PROMPT,
+ timezone: CRON.timezone,
+ authorId: 'macro|[email protected]',
+ })
+ ).toEqual([
+ {
+ kind: 'item',
+ id: 'channel-1',
+ block_name: 'channel',
+ label: 'customer-success',
+ fill: 'shared',
+ },
+ {
+ kind: 'item',
+ id: 'doc-1',
+ block_name: 'md',
+ label: 'Acme account',
+ fill: 'shared',
+ },
+ {
+ kind: 'user',
+ id: 'macro|[email protected]',
+ label: 'Priya Shah',
+ fill: 'shared',
+ },
+ {
+ kind: 'user',
+ id: 'macro|[email protected]',
+ label: 'Eric',
+ fill: 'activator',
+ },
+ { kind: 'time_zone', timezone: 'America/Los_Angeles', fill: 'activator' },
+ ]);
+ });
+
+ it('has no time zone for event-only routines', () => {
+ expect(
+ extractTemplateVariables({
+ prompt: 'Summarize it',
+ timezone: undefined,
+ authorId: 'macro|[email protected]',
+ })
+ ).toEqual([]);
+ });
+});
+
+describe('fillTemplatePrompt', () => {
+ const variables = extractTemplateVariables({
+ prompt: PROMPT,
+ timezone: CRON.timezone,
+ authorId: 'macro|[email protected]',
+ });
+
+ it('names the activator in place of the author and leaves out dropped references as text', () => {
+ const filled = fillTemplatePrompt({
+ prompt: PROMPT,
+ variables,
+ activator: ACTIVATOR,
+ choices: new Map([['doc-1', 'leave_out']]),
+ });
+ expect(filled).toBe(
+ `Post the digest to ${CHANNEL}. Pull renewal dates from Acme account. Assign follow-ups to ${TEAMMATE} and DM <m-user-mention>{"userId":"macro|[email protected]","email":"[email protected]","displayName":"Jun"}</m-user-mention> a summary. Repeat in ${CHANNEL}.`
+ );
+ });
+
+ it('leaves out an unchosen per-person reference', () => {
+ const filled = fillTemplatePrompt({
+ prompt: `Read ${DOC}`,
+ variables: [
+ {
+ kind: 'item',
+ id: 'doc-1',
+ block_name: 'md',
+ label: 'Acme account',
+ fill: 'choice',
+ },
+ ],
+ activator: ACTIVATOR,
+ choices: new Map(),
+ });
+ expect(filled).toBe('Read Acme account');
+ });
+});
+
+describe('fillTemplateTrigger', () => {
+ it('moves every schedule to the activator time zone', () => {
+ const trigger = {
+ type: 'multiple' as const,
+ triggers: [CRON, { type: 'events' as const, filters: [] }],
+ };
+ expect(
+ fillTemplateTrigger({
+ trigger,
+ variables: [
+ { kind: 'time_zone', timezone: CRON.timezone, fill: 'activator' },
+ ],
+ activator: ACTIVATOR,
+ })
+ ).toEqual({
+ type: 'multiple',
+ triggers: [
+ { ...CRON, timezone: 'America/New_York' },
+ { type: 'events', filters: [] },
+ ],
+ });
+ });
+
+ it('keeps the author time zone when it is shared', () => {
+ expect(
+ fillTemplateTrigger({
+ trigger: CRON,
+ variables: [
+ { kind: 'time_zone', timezone: CRON.timezone, fill: 'shared' },
+ ],
+ activator: ACTIVATOR,
+ })
+ ).toEqual(CRON);
+ });
+});
diff --git a/apps/web/src/features/routines/core/template.ts b/apps/web/src/features/routines/core/template.ts
new file mode 100644
index 0000000000..9ca73aaf9b
--- /dev/null
+++ b/apps/web/src/features/routines/core/template.ts
@@ -0,0 +1,191 @@
+import type {
+ ActionTrigger,
+ TemplateVariable,
+ VariableFill,
+} from '@service-scheduled-action/generated/schemas';
+import { match } from 'ts-pattern';
+
+const MENTION_PATTERN =
+ /<m-(user|document)-mention>([\s\S]*?)<\/m-\1-mention>/g;
+
+type Mention =
+ | { kind: 'user'; id: string; label: string; email?: string }
+ | { kind: 'item'; id: string; label: string; blockName: string };
+
+function parseMention(kind: string, json: string): Mention | undefined {
+ try {
+ const data: unknown = JSON.parse(json);
+ if (!data || typeof data !== 'object') return undefined;
+ const field = (name: string) => {
+ const value = (data as Record<string, unknown>)[name];
+ return typeof value === 'string' ? value : undefined;
+ };
+ if (kind === 'user') {
+ const id = field('userId');
+ if (!id) return undefined;
+ const email = field('email');
+ return {
+ kind: 'user',
+ id,
+ email,
+ label: field('displayName') || email?.split('@')[0] || id,
+ };
+ }
+ const id = field('documentId');
+ if (!id) return undefined;
+ return {
+ kind: 'item',
+ id,
+ label: field('documentName') || 'Untitled',
+ blockName: field('blockName') ?? 'md',
+ };
+ } catch {
+ return undefined;
+ }
+}
+
+/** `macro|<email>` principals and bare emails name the same person. */
+function isSameUser(mention: { id: string; email?: string }, userId: string) {
+ return (
+ mention.id === userId ||
+ (mention.email !== undefined && `macro|${mention.email}` === userId)
+ );
+}
+
+/** The ID a variable is keyed by within one template. */
+export function variableKey(variable: TemplateVariable): string {
+ return match(variable)
+ .with({ kind: 'user' }, { kind: 'item' }, (reference) => reference.id)
+ .with({ kind: 'time_zone' }, () => 'time_zone')
+ .exhaustive();
+}
+
+/**
+ * The user-specific parts of a routine, as the defaults its owner starts from
+ * when sharing it: the owner's own mentions and the schedule's time zone fill
+ * in as whoever activates it, and every other reference stays the same.
+ */
+export function extractTemplateVariables(args: {
+ prompt: string;
+ /** The time zone its schedules run in; absent for event-only routines. */
+ timezone: string | undefined;
+ authorId: string;
+}): TemplateVariable[] {
+ const variables = new Map<string, TemplateVariable>();
+ for (const [, kind, json] of args.prompt.matchAll(MENTION_PATTERN)) {
+ const mention = parseMention(kind, json);
+ if (!mention || variables.has(mention.id)) continue;
+ variables.set(
+ mention.id,
+ mention.kind === 'user'
+ ? {
+ kind: 'user',
+ id: mention.id,
+ label: mention.label,
+ fill: isSameUser(mention, args.authorId) ? 'activator' : 'shared',
+ }
+ : {
+ kind: 'item',
+ id: mention.id,
+ block_name: mention.blockName,
+ label: mention.label,
+ fill: 'shared',
+ }
+ );
+ }
+ if (args.timezone) {
+ variables.set('time_zone', {
+ kind: 'time_zone',
+ timezone: args.timezone,
+ fill: 'activator',
+ });
+ }
+ return [...variables.values()];
+}
+
+/** Keep the referenced item, or drop it and leave its name as plain text. */
+export type ReferenceChoice = 'keep' | 'leave_out';
+
+export type Activator = {
+ userId: string;
+ email: string;
+ displayName?: string;
+ timezone: string;
+};
+
+/**
+ * The template's instructions as the activator's routine will run them:
+ * mentions that fill in as the activator name them instead, and references
+ * the activator left out become plain text.
+ */
+export function fillTemplatePrompt(args: {
+ prompt: string;
+ variables: readonly TemplateVariable[];
+ activator: Activator;
+ choices: ReadonlyMap<string, ReferenceChoice>;
+}): string {
+ const fills = new Map(
+ args.variables.map((variable) => [variableKey(variable), variable.fill])
+ );
+ return args.prompt.replace(MENTION_PATTERN, (tag, kind, json) => {
+ const mention = parseMention(kind, json);
+ if (!mention) return tag;
+ const fill: VariableFill = fills.get(mention.id) ?? 'shared';
+ if (mention.kind === 'user' && fill === 'activator') {
+ const data = JSON.stringify({
+ userId: args.activator.userId,
+ email: args.activator.email,
+ displayName: args.activator.displayName,
+ });
+ return `<m-user-mention>${data}</m-user-mention>`;
+ }
+ const choice =
+ args.choices.get(mention.id) ??
+ (fill === 'choice' ? 'leave_out' : 'keep');
+ return choice === 'leave_out' ? mention.label : tag;
+ });
+}
+
+/** The template's triggers, on the activator's time zone when it fills in. */
+export function fillTemplateTrigger(args: {
+ trigger: ActionTrigger;
+ variables: readonly TemplateVariable[];
+ activator: Activator;
+}): ActionTrigger {
+ const zone = args.variables.find((variable) => variable.kind === 'time_zone');
+ if (zone?.fill !== 'activator') return args.trigger;
+ const timezone = args.activator.timezone;
+ return match(args.trigger)
+ .returnType<ActionTrigger>()
+ .with({ type: 'cron' }, (cron) => ({ ...cron, timezone }))
+ .with({ type: 'events' }, (events) => events)
+ .with({ type: 'multiple' }, (multiple) => ({
+ ...multiple,
+ triggers: multiple.triggers.map((item) =>
+ item.type === 'cron' ? { ...item, timezone } : item
+ ),
+ }))
+ .exhaustive(() => args.trigger);
+}
+
+/**
+ * How a reference reads to someone activating a template: it fills in as
+ * them, works as it is, or needs their decision because they can't open it or
+ * the author left it for each person to choose.
+ */
+export type ReferenceState = 'fills_in' | 'works' | 'unavailable' | 'choose';
+
+export function referenceState(
+ variable: TemplateVariable,
+ canOpen: boolean | undefined
+): ReferenceState {
+ if (variable.fill === 'activator') return 'fills_in';
+ if (variable.fill === 'choice') return 'choose';
+ return variable.kind === 'item' && canOpen === false
+ ? 'unavailable'
+ : 'works';
+}
+
+export function needsDecision(state: ReferenceState) {
+ return state === 'unavailable' || state === 'choose';
+}
diff --git a/apps/web/src/features/routines/primitives/template-activation.test.ts b/apps/web/src/features/routines/primitives/template-activation.test.ts
new file mode 100644
index 0000000000..899e889e9c
--- /dev/null
+++ b/apps/web/src/features/routines/primitives/template-activation.test.ts
@@ -0,0 +1,76 @@
+import type { RoutineTemplate } from '@service-scheduled-action/generated/schemas';
+import { createRoot, createSignal } from 'solid-js';
+import { describe, expect, it } from 'vitest';
+import { createTemplateActivation } from './template-activation';
+
+const DOC =
+ '<m-document-mention>{"documentId":"doc-1","documentName":"Acme account","blockName":"md"}</m-document-mention>';
+
+const TEMPLATE: RoutineTemplate = {
+ id: 'template-1',
+ author: 'macro|[email protected]',
+ name: 'Weekly digest',
+ description: '',
+ active_count: 0,
+ created_at: '2026-10-20T00:00:00Z',
+ updated_at: '2026-10-20T00:00:00Z',
+ trigger: { type: 'cron', schedule: '0 0 9 * * 2', timezone: 'UTC' },
+ task: { model: 'model', prompt: '', user_prompt: `Read ${DOC}` },
+ variables: [
+ {
+ kind: 'item',
+ id: 'doc-1',
+ block_name: 'md',
+ label: 'Acme account',
+ fill: 'shared',
+ },
+ { kind: 'time_zone', timezone: 'UTC', fill: 'activator' },
+ ],
+};
+
+const ACTIVATOR = {
+ userId: 'macro|[email protected]',
+ email: '[email protected]',
+ timezone: 'America/New_York',
+};
+
+describe('createTemplateActivation', () => {
+ it('waits for a decision on an item the activator cannot open', () => {
+ createRoot((dispose) => {
+ const [access, setAccess] = createSignal<ReadonlyMap<string, boolean>>(
+ new Map([['doc-1', true]])
+ );
+ const activation = createTemplateActivation({
+ template: () => TEMPLATE,
+ activator: () => ACTIVATOR,
+ access,
+ });
+ expect(activation.request()).toEqual({
+ name: 'Weekly digest',
+ trigger: {
+ type: 'cron',
+ schedule: '0 0 9 * * 2',
+ timezone: 'America/New_York',
+ },
+ kind: 'Agent',
+ task: { model: 'model', prompt: '', user_prompt: `Read ${DOC}` },
+ enabled: true,
+ run_visibility: 'unlisted',
+ });
+
+ setAccess(new Map([['doc-1', false]]));
+ expect(activation.undecided().map((reference) => reference.key)).toEqual([
+ 'doc-1',
+ ]);
+ expect(activation.request()).toBeUndefined();
+
+ activation.choose('doc-1', 'leave_out');
+ expect(activation.request()?.task).toEqual({
+ model: 'model',
+ prompt: '',
+ user_prompt: 'Read Acme account',
+ });
+ dispose();
+ });
+ });
+});
diff --git a/apps/web/src/features/routines/primitives/template-activation.ts b/apps/web/src/features/routines/primitives/template-activation.ts
new file mode 100644
index 0000000000..6585f64304
--- /dev/null
+++ b/apps/web/src/features/routines/primitives/template-activation.ts
@@ -0,0 +1,102 @@
+import type {
+ CreateScheduledAction,
+ RoutineTemplate,
+ TemplateVariable,
+} from '@service-scheduled-action/generated/schemas';
+import { type Accessor, createMemo, createSignal } from 'solid-js';
+import { DEFAULT_RUN_VISIBILITY } from '../core/draft';
+import {
+ type Activator,
+ fillTemplatePrompt,
+ fillTemplateTrigger,
+ needsDecision,
+ type ReferenceChoice,
+ type ReferenceState,
+ referenceState,
+ variableKey,
+} from '../core/template';
+
+export type TemplateReference = {
+ key: string;
+ variable: TemplateVariable;
+ state: ReferenceState;
+};
+
+/** The instructions a template's routine runs, from its task. */
+export function templatePrompt(template: RoutineTemplate): string {
+ const prompt = template.task.user_prompt;
+ return typeof prompt === 'string' ? prompt : '';
+}
+
+/**
+ * One person's activation of a template: which references they still have to
+ * decide on, and the routine their decisions produce.
+ */
+export function createTemplateActivation(args: {
+ template: Accessor<RoutineTemplate>;
+ activator: Accessor<Activator | undefined>;
+ /** Whether the activator can open each mentioned item, by item ID. */
+ access: Accessor<ReadonlyMap<string, boolean>>;
+}) {
+ const [choices, setChoices] = createSignal<
+ ReadonlyMap<string, ReferenceChoice>
+ >(new Map());
+
+ const references = createMemo((): TemplateReference[] =>
+ args.template().variables.map((variable) => ({
+ key: variableKey(variable),
+ variable,
+ state: referenceState(
+ variable,
+ variable.kind === 'item' ? args.access().get(variable.id) : undefined
+ ),
+ }))
+ );
+
+ const undecided = () =>
+ references().filter(
+ (reference) =>
+ needsDecision(reference.state) && !choices().has(reference.key)
+ );
+
+ const prompt = () => {
+ const activator = args.activator();
+ if (!activator) return templatePrompt(args.template());
+ return fillTemplatePrompt({
+ prompt: templatePrompt(args.template()),
+ variables: args.template().variables,
+ activator,
+ choices: choices(),
+ });
+ };
+
+ /** The routine to create, once every reference that needs one has a decision. */
+ const request = (): CreateScheduledAction | undefined => {
+ const activator = args.activator();
+ if (!activator || undecided().length > 0) return undefined;
+ const template = args.template();
+ return {
+ name: template.name,
+ trigger: fillTemplateTrigger({
+ trigger: template.trigger,
+ variables: template.variables,
+ activator,
+ }),
+ kind: 'Agent',
+ task: { ...template.task, user_prompt: prompt() },
+ enabled: true,
+ run_visibility: DEFAULT_RUN_VISIBILITY,
+ };
+ };
+
+ return {
+ references,
+ undecided,
+ choices,
+ choose(key: string, choice: ReferenceChoice) {
+ setChoices((current) => new Map(current).set(key, choice));
+ },
+ prompt,
+ request,
+ };
+}
diff --git a/apps/web/src/features/routines/queries/keys.ts b/apps/web/src/features/routines/queries/keys.ts
index 2e72f80d82..a4a491fdba 100644
--- a/apps/web/src/features/routines/queries/keys.ts
+++ b/apps/web/src/features/routines/queries/keys.ts
@@ -9,4 +9,10 @@ export const scheduledActionKeys = createQueryKeys('scheduledAction', {
history: (params: { scheduleId: string }) => ({
queryKey: [params.scheduleId, 'history'],
}),
+ template: (params: { scheduleId: string }) => ({
+ queryKey: [params.scheduleId, 'template'],
+ }),
+ referenceAccess: (params: { itemId: string; itemType: string }) => ({
+ queryKey: [params.itemId, params.itemType],
+ }),
});
diff --git a/apps/web/src/features/routines/queries/routine-sources.ts b/apps/web/src/features/routines/queries/routine-sources.ts
index 8eba495c2d..ae97205a55 100644
--- a/apps/web/src/features/routines/queries/routine-sources.ts
+++ b/apps/web/src/features/routines/queries/routine-sources.ts
@@ -46,6 +46,7 @@ function toRoutine(schedule: ScheduledAction): RoutineSnapshot {
schedule.run_visibility,
]),
draft: draftFromSchedule(schedule),
+ templateId: schedule.template_id ?? undefined,
};
}
diff --git a/apps/web/src/features/routines/queries/templates.ts b/apps/web/src/features/routines/queries/templates.ts
new file mode 100644
index 0000000000..51dbec9f58
--- /dev/null
+++ b/apps/web/src/features/routines/queries/templates.ts
@@ -0,0 +1,160 @@
+import { verifyBlockName } from '@core/constant/allBlocks';
+import { throwOnErr } from '@core/util/result';
+import { queryClient } from '@queries/client';
+import {
+ getItemPreview,
+ type ItemEntity,
+ isAccessiblePreviewItem,
+} from '@queries/preview';
+import { type MutationCallbacks, withCallbacks } from '@queries/utils';
+import { scheduledActionClient } from '@service-scheduled-action/client';
+import type {
+ CreateScheduledAction,
+ RoutineTemplate,
+ ScheduledAction,
+ ShareRoutineTemplate,
+} from '@service-scheduled-action/generated/schemas';
+import { blockNameToItemType } from '@service-storage/itemType';
+import {
+ queryOptions,
+ useMutation,
+ useQueries,
+ useQuery,
+} from '@tanstack/solid-query';
+import type { Accessor } from 'solid-js';
+import { scheduledActionKeys } from './keys';
+import { invalidateSchedules } from './schedules';
+
+/** A routine that isn't shared has no template: `null`, not an error. */
+async function fetchTemplate(
+ scheduleId: string
+): Promise<RoutineTemplate | null> {
+ const result = await scheduledActionClient.getTemplate(scheduleId);
+ if (
+ result.isErr() &&
+ result.error.some((error) => error.code === 'NOT_FOUND')
+ )
+ return null;
+ return throwOnErr(async () => result);
+}
+
+// Cached past unmount; closes over the resolved schedule id only.
+export function routineTemplateQueryOptions(
+ scheduleId: string | undefined,
+ enabled = true
+) {
+ return queryOptions({
+ queryKey: scheduledActionKeys.template({
+ scheduleId: scheduleId ?? '__none__',
+ }).queryKey,
+ enabled: enabled && Boolean(scheduleId),
+ queryFn: () => fetchTemplate(scheduleId!),
+ });
+}
+
+export function useRoutineTemplateQuery(
+ scheduleId: Accessor<string | undefined>,
+ enabled: Accessor<boolean> = () => true
+) {
+ return useQuery(() => routineTemplateQueryOptions(scheduleId(), enabled()));
+}
+
+function setTemplate(scheduleId: string, template: RoutineTemplate | null) {
+ queryClient.setQueryData(
+ scheduledActionKeys.template({ scheduleId }).queryKey,
+ template
+ );
+}
+
+export function useShareTemplateMutation(
+ callbacks?: MutationCallbacks<
+ RoutineTemplate,
+ Error,
+ { scheduleId: string; body: ShareRoutineTemplate }
+ >
+) {
+ return useMutation(() => ({
+ mutationFn: (args: { scheduleId: string; body: ShareRoutineTemplate }) =>
+ throwOnErr(() => scheduledActionClient.shareTemplate(args)),
+ ...withCallbacks(
+ { onSuccess: (template) => setTemplate(template.id, template) },
+ callbacks
+ ),
+ }));
+}
+
+export function useUnshareTemplateMutation(
+ callbacks?: MutationCallbacks<void, Error, { scheduleId: string }>
+) {
+ return useMutation(() => ({
+ mutationFn: (args: { scheduleId: string }) =>
+ throwOnErr(() => scheduledActionClient.unshareTemplate(args)),
+ ...withCallbacks(
+ { onSuccess: (_result, { scheduleId }) => setTemplate(scheduleId, null) },
+ callbacks
+ ),
+ }));
+}
+
+export function useActivateTemplateMutation(
+ callbacks?: MutationCallbacks<
+ ScheduledAction,
+ Error,
+ { templateId: string; body: CreateScheduledAction }
+ >
+) {
+ return useMutation(() => ({
+ mutationFn: (args: { templateId: string; body: CreateScheduledAction }) =>
+ throwOnErr(() => scheduledActionClient.activateTemplate(args)),
+ ...withCallbacks(
+ {
+ onSuccess: async (_routine, { templateId }) => {
+ await Promise.all([
+ invalidateSchedules(),
+ queryClient.invalidateQueries({
+ queryKey: scheduledActionKeys.template({
+ scheduleId: templateId,
+ }).queryKey,
+ }),
+ ]);
+ },
+ },
+ callbacks
+ ),
+ }));
+}
+
+// Cached past unmount; closes over the resolved item only.
+function referenceAccessQueryOptions(item: ItemEntity) {
+ return queryOptions({
+ queryKey: scheduledActionKeys.referenceAccess({
+ itemId: item.id,
+ itemType: item.type ?? 'document',
+ }).queryKey,
+ queryFn: async () => isAccessiblePreviewItem(await getItemPreview(item)),
+ });
+}
+
+/**
+ * Whether the viewer can open each item a template mentions, keyed by item
+ * ID. Items still loading are absent.
+ */
+export function useReferenceAccess(
+ items: Accessor<readonly { id: string; blockName: string }[]>
+): Accessor<ReadonlyMap<string, boolean>> {
+ const queries = useQueries(() => ({
+ queries: items().map((item) =>
+ referenceAccessQueryOptions({
+ id: item.id,
+ type: blockNameToItemType(verifyBlockName(item.blockName)),
+ })
+ ),
+ }));
+ return () =>
+ new Map(
+ items().flatMap((item, index) => {
+ const query = queries[index];
+ return query?.isSuccess ? [[item.id, query.data] as const] : [];
+ })
+ );
+}
diff --git a/apps/web/src/features/routines/routine-detail.test.tsx b/apps/web/src/features/routines/routine-detail.test.tsx
index 5b1e4b51ec..6cd3e28c42 100644
--- a/apps/web/src/features/routines/routine-detail.test.tsx
+++ b/apps/web/src/features/routines/routine-detail.test.tsx
@@ -70,6 +70,12 @@ vi.mock('./queries/routines', () => ({
vi.mock('./routine-triggers', () => ({
RoutineTriggers: () => <div>Triggers</div>,
}));
+vi.mock('./routine-template', () => ({
+ RoutineTemplatePage: (props: { scheduleId: string }) => (
+ <div>Template for {props.scheduleId}</div>
+ ),
+ openShareTemplateDialog: vi.fn(),
+}));
vi.mock('@core/block', () => ({ useBlockId: () => 'routine-id' }));
vi.mock('@core/component/AI/constant', () => ({
defaultModelForPlan: () => 'claude-sonnet-4-6',
@@ -370,13 +376,11 @@ function deferredSave(): {
}
describe('routine execution target autosave', () => {
- it('shows another owner’s routine without edit, run, or history controls', () => {
+ it('shows another owner’s routine as its template, without its controls', () => {
setSchedules([{ ...cron, owner: 'macro|[email protected]' }]);
render(() => <Routine />);
- expect(screen.getByLabelText('Instructions')).toHaveProperty(
- 'disabled',
- true
- );
+ expect(screen.getByText('Template for routine-id')).toBeTruthy();
+ expect(screen.queryByLabelText('Instructions')).toBeNull();
expect(screen.queryByRole('button', { name: 'Run now' })).toBeNull();
expect(
screen.queryByRole('button', { name: 'Routine actions' })
diff --git a/apps/web/src/features/routines/routine-detail.tsx b/apps/web/src/features/routines/routine-detail.tsx
index faf2e9ed15..a47e0da375 100644
--- a/apps/web/src/features/routines/routine-detail.tsx
+++ b/apps/web/src/features/routines/routine-detail.tsx
@@ -8,7 +8,8 @@ import { defaultModelForPlan } from '@core/component/AI/constant';
import { toast } from '@core/component/Toast/Toast';
import { useUserId } from '@core/context/user';
import { writeClipboardData } from '@core/util/dataTransfer';
-import { onMount, Show } from 'solid-js';
+import { getOwner, onMount, Show } from 'solid-js';
+import type { ScheduleDraft } from './core/draft';
import { getErrorMessage } from './core/routine-draft';
import {
createAgentHistoryMetadata,
@@ -18,6 +19,10 @@ import { createRoutineDetailSource } from './queries/routine-sources';
import { createRoutineConnectedApps, RoutineApps } from './routine-apps';
import { RoutineExecutionPicker } from './routine-execution-picker';
import { RoutinePromptEditor } from './routine-prompt-editor';
+import {
+ openShareTemplateDialog,
+ RoutineTemplatePage,
+} from './routine-template';
import { RoutineTriggers } from './routine-triggers';
import { RoutineDetailView } from './views/routine-detail';
@@ -74,37 +79,75 @@ export function RoutineDetail(props: {
onError: () => toast.failure('Failed to delete'),
});
};
+ const owner = getOwner();
+ const shareTemplate = () => {
+ const routine = source.routine();
+ if (!routine) return;
+ openShareTemplateDialog(
+ {
+ routineId: routine.id,
+ name: routine.name,
+ prompt: routine.draft?.prompt ?? '',
+ timezone: scheduleTimezone(routine.draft),
+ ownerId: routine.ownerId,
+ },
+ owner
+ );
+ };
+ // Routines run as their owner, so everyone else sees the shared template.
+ const ownedByViewer = () => {
+ const routine = source.routine();
+ return routine ? routine.ownerId === userId() : true;
+ };
return (
- <RoutineDetailView
- source={source}
- userId={userId}
- defaultModel={defaultModelForPlan(hasPaidAccess())}
- initialTab={props.initialTab}
- onBack={back}
- onDelete={remove}
- onRename={(name) => {
- if (!props.onBack) panel.handle.setDisplayName(name);
- }}
- onOpenRun={(resource, newSplit) =>
- layout.openWithSplit(resource, {
- activate: true,
- preferNewSplit: newSplit,
- })
+ <Show
+ when={ownedByViewer()}
+ fallback={
+ <RoutineTemplatePage scheduleId={props.scheduleId} onBack={back} />
}
- onCopyPrompt={async (prompt) => {
- if (await writeClipboardData({ 'text/plain': prompt }))
- toast.success('Prompt copied');
- else toast.alert('Could not copy prompt');
- }}
- slots={{
- PromptEditor: RoutinePromptEditor,
- ExecutionPicker: RoutineExecutionPicker,
- Triggers: RoutineTriggers,
- Apps: RoutineApps,
- createConnectedApps: createRoutineConnectedApps,
- createChatMetadata: createChatHistoryMetadata,
- createAgentMetadata: createAgentHistoryMetadata,
- }}
- />
+ >
+ <RoutineDetailView
+ source={source}
+ userId={userId}
+ defaultModel={defaultModelForPlan(hasPaidAccess())}
+ initialTab={props.initialTab}
+ onBack={back}
+ onDelete={remove}
+ onRename={(name) => {
+ if (!props.onBack) panel.handle.setDisplayName(name);
+ }}
+ onOpenRun={(resource, newSplit) =>
+ layout.openWithSplit(resource, {
+ activate: true,
+ preferNewSplit: newSplit,
+ })
+ }
+ onCopyPrompt={async (prompt) => {
+ if (await writeClipboardData({ 'text/plain': prompt }))
+ toast.success('Prompt copied');
+ else toast.alert('Could not copy prompt');
+ }}
+ onShareTemplate={shareTemplate}
+ onOpenTemplate={open}
+ slots={{
+ PromptEditor: RoutinePromptEditor,
+ ExecutionPicker: RoutineExecutionPicker,
+ Triggers: RoutineTriggers,
+ Apps: RoutineApps,
+ createConnectedApps: createRoutineConnectedApps,
+ createChatMetadata: createChatHistoryMetadata,
+ createAgentMetadata: createAgentHistoryMetadata,
+ }}
+ />
+ </Show>
+ );
+}
+
+/** The time zone a routine's schedules run in, for sharing it as a template. */
+function scheduleTimezone(draft: ScheduleDraft | undefined) {
+ const schedule = draft?.triggers?.find(
+ (trigger) => trigger.kind === 'schedule'
);
+ if (schedule?.kind === 'schedule') return schedule.timezone;
+ return draft?.triggers ? undefined : draft?.timezone;
}
diff --git a/apps/web/src/features/routines/routine-template.tsx b/apps/web/src/features/routines/routine-template.tsx
new file mode 100644
index 0000000000..9764c6750f
--- /dev/null
+++ b/apps/web/src/features/routines/routine-template.tsx
@@ -0,0 +1,473 @@
+import { openAgentsPage } from '@app/features/agents-view/primitives/open-page';
+import { useSplitLayout } from '@components/app/split-layout/layout';
+import { RecipientSelector } from '@core/component/RecipientSelector';
+import { toast } from '@core/component/Toast/Toast';
+import { useEmail, useUserId } from '@core/context/user';
+import { useCombinedRecipients } from '@core/signal/useCombinedRecipient';
+import type { WithCustomUserInput } from '@core/user';
+import { getDisplayName } from '@core/user/displayName';
+import { tryMacroId } from '@core/user/macroId';
+import { useSendMessageToPeople } from '@core/util/channels';
+import { getDefaultTimezone } from '@core/util/cron';
+import { writeClipboardData } from '@core/util/dataTransfer';
+import { getDestinationFromOptions } from '@core/util/destination';
+import { fireAndForget } from '@core/util/fireAndForget';
+import { buildSimpleEntityUrl } from '@core/util/url';
+import PaperPlaneIcon from '@icon/system/regular/paper-plane-tilt.svg';
+import { Telemetry } from '@macro-inc/observability';
+import type {
+ ActionTrigger,
+ RoutineTemplate,
+ TemplateVariable,
+} from '@service-scheduled-action/generated/schemas';
+import { Button, type ManagedDialogProps, openDialog } from '@ui';
+import {
+ type Accessor,
+ createMemo,
+ createSignal,
+ getOwner,
+ Match,
+ Show,
+ Switch,
+} from 'solid-js';
+import { TemplateCard } from './components/template-card';
+import { describeTrigger } from './core/routine-triggers';
+import {
+ type Activator,
+ extractTemplateVariables,
+ variableKey,
+} from './core/template';
+import {
+ createTemplateActivation,
+ templatePrompt,
+} from './primitives/template-activation';
+import { parseRoutineTriggers } from './queries/routine-trigger-mapping';
+import {
+ useActivateTemplateMutation,
+ useReferenceAccess,
+ useRoutineTemplateQuery,
+ useShareTemplateMutation,
+ useUnshareTemplateMutation,
+} from './queries/templates';
+import { RoutinePromptEditor } from './routine-prompt-editor';
+import { ActivateTemplateDialog } from './views/activate-template-dialog';
+import { RoutineTemplateView } from './views/routine-template-view';
+import { ShareTemplateDialog } from './views/share-template-dialog';
+
+function triggerLines(trigger: ActionTrigger): string[] {
+ return (parseRoutineTriggers(trigger) ?? []).map(describeTrigger);
+}
+
+function ReadOnlyInstructions(props: { prompt: string }) {
+ return (
+ <Show when={{ prompt: props.prompt }} keyed>
+ {(current) => (
+ <RoutinePromptEditor
+ initialValue={current.prompt}
+ disabled
+ onChange={() => {}}
+ />
+ )}
+ </Show>
+ );
+}
+
+function useActivator(): Accessor<Activator | undefined> {
+ const userId = useUserId();
+ const email = useEmail();
+ return () => {
+ const id = userId();
+ const address = email();
+ if (!id || !address) return undefined;
+ return {
+ userId: id,
+ email: address,
+ displayName: getDisplayName(tryMacroId(id)) || undefined,
+ timezone: getDefaultTimezone(),
+ };
+ };
+}
+
+function itemReferences(variables: readonly TemplateVariable[]) {
+ return variables.flatMap((variable) =>
+ variable.kind === 'item'
+ ? [{ id: variable.id, blockName: variable.block_name }]
+ : []
+ );
+}
+
+/** Activating a shared template as the viewer's own routine. */
+function ActivateTemplate(
+ props: ManagedDialogProps & {
+ template: RoutineTemplate;
+ onActivated(routineId: string): void;
+ }
+) {
+ const activator = useActivator();
+ const access = useReferenceAccess(() =>
+ itemReferences(props.template.variables)
+ );
+ const activation = createTemplateActivation({
+ template: () => props.template,
+ activator,
+ access,
+ });
+ const mutation = useActivateTemplateMutation();
+ const [error, setError] = createSignal<string>();
+
+ async function activate() {
+ const body = activation.request();
+ if (!body) return;
+ setError(undefined);
+ await Telemetry.span('routine.template.activate', async (span) => {
+ span.setAttr('routine.template_id', props.template.id);
+ span.setAttr(
+ 'routine.template.variables',
+ props.template.variables.length
+ );
+ try {
+ const routine = await mutation.mutateAsync({
+ templateId: props.template.id,
+ body,
+ });
+ if (!routine.id) throw new Error('Activated routine has no ID');
+ span.setAttr('routine.id', routine.id);
+ props.onOpenChange(false);
+ props.onActivated(routine.id);
+ } catch (cause) {
+ span.error('Template activation failed');
+ setError(
+ cause instanceof Error && cause.message
+ ? cause.message
+ : 'Could not activate the routine. Please try again.'
+ );
+ }
+ });
+ }
+
+ return (
+ <ActivateTemplateDialog
+ open={props.open}
+ onOpenChange={props.onOpenChange}
+ name={props.template.name}
+ authorName={
+ getDisplayName(tryMacroId(props.template.author)) || 'its author'
+ }
+ triggers={triggerLines(props.template.trigger)}
+ instructions={<ReadOnlyInstructions prompt={activation.prompt()} />}
+ references={activation.references()}
+ choices={activation.choices()}
+ onChoose={activation.choose}
+ undecided={activation.undecided().length}
+ pending={mutation.isPending}
+ error={error()}
+ onActivate={() => fireAndForget(activate(), 'routines')}
+ />
+ );
+}
+
+/** Opens activation for a template; `onActivated` gets the new routine. */
+export function openActivateTemplateDialog(
+ template: RoutineTemplate,
+ owner: ReturnType<typeof getOwner>,
+ onActivated: (routineId: string) => void
+) {
+ return openDialog(
+ ActivateTemplate,
+ {
+ template,
+ onActivated: (routineId) => {
+ toast.success('Routine activated');
+ onActivated(routineId);
+ },
+ },
+ { owner, key: `activate-template-${template.id}` }
+ );
+}
+
+/**
+ * A shared routine as people other than its owner see it: its template, with
+ * a way to activate their own copy.
+ */
+export function RoutineTemplatePage(props: {
+ scheduleId: string;
+ onBack(): void;
+}) {
+ const owner = getOwner();
+ const layout = useSplitLayout();
+ const userId = useUserId();
+ const query = useRoutineTemplateQuery(() => props.scheduleId);
+ const template = () => (query.isSuccess ? query.data : undefined);
+ const access = useReferenceAccess(() =>
+ itemReferences(template()?.variables ?? [])
+ );
+ const activator = useActivator();
+
+ const openActivation = (current: RoutineTemplate) =>
+ openActivateTemplateDialog(current, owner, (routineId) =>
+ openAgentsPage(layout, 'routines', { routineId })
+ );
+
+ return (
+ <Switch
+ fallback={
+ <div class="flex size-full items-center justify-center p-3 text-sm text-ink-muted">
+ Loading…
+ </div>
+ }
+ >
+ <Match when={query.isError}>
+ <div class="flex size-full items-center justify-center p-3 text-sm text-ink-muted">
+ Unable to load this routine. Please try again.
+ </div>
+ </Match>
+ <Match when={query.isSuccess && !template()}>
+ <div class="flex size-full items-center justify-center p-3 text-center text-sm text-ink-muted">
+ This routine belongs to someone else and isn't shared as a template.
+ </div>
+ </Match>
+ <Match when={template()}>
+ {(current) => {
+ const activation = createTemplateActivation({
+ template: current,
+ activator,
+ access,
+ });
+ return (
+ <RoutineTemplateView
+ template={current()}
+ authorName={
+ getDisplayName(tryMacroId(current().author)) || 'Someone'
+ }
+ canActivate={current().author !== userId()}
+ triggers={triggerLines(current().trigger)}
+ references={activation.references()}
+ instructions={
+ <ReadOnlyInstructions prompt={templatePrompt(current())} />
+ }
+ onActivate={() => openActivation(current())}
+ onBack={props.onBack}
+ />
+ );
+ }}
+ </Match>
+ </Switch>
+ );
+}
+
+type Recipient = WithCustomUserInput<'user' | 'contact' | 'channel'>;
+
+function mentionMarkup(routineId: string, name: string) {
+ const data = JSON.stringify({
+ documentId: routineId,
+ documentName: name,
+ blockName: 'routine',
+ });
+ return `<m-document-mention>${data}</m-document-mention>`;
+}
+
+/** Posts a template's link to a channel or people. */
+function SendTemplate(props: { routineId: string; name: string }) {
+ const [recipients, setRecipients] = createSignal<Recipient[]>([]);
+ const [sending, setSending] = createSignal(false);
+ const { all } = useCombinedRecipients();
+ const { sendToChannel, sendToUsers } = useSendMessageToPeople();
+
+ async function send() {
+ const destination = getDestinationFromOptions(recipients());
+ if (!destination || sending()) return;
+ setSending(true);
+ const message = {
+ content: `Here's a routine you can activate for yourself: ${mentionMarkup(props.routineId, props.name)}`,
+ mentions: [],
+ };
+ try {
+ const result =
+ destination.type === 'channel'
+ ? await sendToChannel({ ...message, channelId: destination.id })
+ : await sendToUsers({ ...message, users: destination.users });
+ if (result) {
+ toast.success('Template sent');
+ setRecipients([]);
+ } else toast.failure('Message failed to send');
+ } finally {
+ setSending(false);
+ }
+ }
+
+ return (
+ <div class="flex items-start gap-2">
+ <RecipientSelector<'user' | 'contact' | 'channel'>
+ placeholder="Channel or people"
+ options={all}
+ selectedOptions={recipients()}
+ setSelectedOptions={setRecipients}
+ triggerMode="input"
+ portalScope="local"
+ class="min-w-0 flex-1"
+ />
+ <Button
+ variant="outline"
+ disabled={recipients().length === 0 || sending()}
+ onClick={() => fireAndForget(send(), 'routines')}
+ >
+ <PaperPlaneIcon />
+ Send
+ </Button>
+ </div>
+ );
+}
+
+/** The owner's share dialog for one of their routines. */
+function ShareTemplate(
+ props: ManagedDialogProps & {
+ routineId: string;
+ name: string;
+ prompt: string;
+ timezone: string | undefined;
+ ownerId: string;
+ }
+) {
+ const query = useRoutineTemplateQuery(() => props.routineId);
+ const shared = () => (query.isPending ? undefined : (query.data ?? null));
+ const share = useShareTemplateMutation();
+ const unshare = useUnshareTemplateMutation();
+ const [error, setError] = createSignal<string>();
+ const [description, setDescription] = createSignal<string>();
+ const [fills, setFills] = createSignal<
+ ReadonlyMap<string, TemplateVariable['fill']>
+ >(new Map());
+
+ // Start from the shared template's choices for references it still has.
+ const variables = createMemo(() => {
+ const previous = new Map(
+ (shared()?.variables ?? []).map((variable) => [
+ variableKey(variable),
+ variable.fill,
+ ])
+ );
+ return extractTemplateVariables({
+ prompt: props.prompt,
+ timezone: props.timezone,
+ authorId: props.ownerId,
+ }).map((variable) => {
+ const key = variableKey(variable);
+ const fill = fills().get(key) ?? previous.get(key) ?? variable.fill;
+ return { ...variable, fill };
+ });
+ });
+
+ const failed = (cause: unknown) =>
+ setError(
+ cause instanceof Error && cause.message
+ ? cause.message
+ : 'Something went wrong. Please try again.'
+ );
+
+ async function shareTemplate() {
+ setError(undefined);
+ await Telemetry.span('routine.template.share', async (span) => {
+ span.setAttr('routine.id', props.routineId);
+ span.setAttr('routine.template.variables', variables().length);
+ try {
+ await share.mutateAsync({
+ scheduleId: props.routineId,
+ body: {
+ description: description() ?? shared()?.description ?? '',
+ variables: variables(),
+ },
+ });
+ toast.success(shared() ? 'Template updated' : 'Template shared');
+ } catch (cause) {
+ span.error('Sharing the template failed');
+ failed(cause);
+ }
+ });
+ }
+
+ async function stopSharing() {
+ setError(undefined);
+ try {
+ await unshare.mutateAsync({ scheduleId: props.routineId });
+ toast.success('Stopped sharing');
+ } catch (cause) {
+ failed(cause);
+ }
+ }
+
+ async function copyLink() {
+ const url = buildSimpleEntityUrl({ type: 'routine', id: props.routineId });
+ if (await writeClipboardData({ 'text/plain': url }))
+ toast.success('Template link copied');
+ else toast.alert('Could not copy the link');
+ }
+
+ return (
+ <ShareTemplateDialog
+ open={props.open}
+ onOpenChange={props.onOpenChange}
+ name={props.name}
+ template={shared()}
+ description={description() ?? shared()?.description ?? ''}
+ onDescription={setDescription}
+ variables={variables()}
+ onFill={(key, fill) =>
+ setFills((current) => new Map(current).set(key, fill))
+ }
+ pending={share.isPending || unshare.isPending}
+ error={error()}
+ onShare={() => fireAndForget(shareTemplate(), 'routines')}
+ onUnshare={() => fireAndForget(stopSharing(), 'routines')}
+ onCopyLink={() => fireAndForget(copyLink(), 'routines')}
+ send={<SendTemplate routineId={props.routineId} name={props.name} />}
+ />
+ );
+}
+
+/** Opens the share-as-template dialog for a routine the viewer owns. */
+export function openShareTemplateDialog(
+ routine: {
+ routineId: string;
+ name: string;
+ prompt: string;
+ timezone: string | undefined;
+ ownerId: string;
+ },
+ owner: ReturnType<typeof getOwner>
+) {
+ return openDialog(ShareTemplate, routine, {
+ owner,
+ key: `share-template-${routine.routineId}`,
+ });
+}
+
+/**
+ * The card under a message that mentions a shared routine. Nothing renders
+ * for a routine that isn't shared as a template.
+ */
+export function RoutineTemplateCard(props: { routineId: string }) {
+ const owner = getOwner();
+ const layout = useSplitLayout();
+ const userId = useUserId();
+ const query = useRoutineTemplateQuery(() => props.routineId);
+ const open = (routineId: string) =>
+ openAgentsPage(layout, 'routines', { routineId });
+ return (
+ <Show when={query.isSuccess ? query.data : undefined}>
+ {(template) => (
+ <TemplateCard
+ name={template().name}
+ description={template().description}
+ authorName={
+ getDisplayName(tryMacroId(template().author)) || 'Someone'
+ }
+ triggers={triggerLines(template().trigger)}
+ activeCount={template().active_count}
+ canActivate={template().author !== userId()}
+ onView={() => open(template().id)}
+ onActivate={() => openActivateTemplateDialog(template(), owner, open)}
+ />
+ )}
+ </Show>
+ );
+}
diff --git a/apps/web/src/features/routines/views/activate-template-dialog.tsx b/apps/web/src/features/routines/views/activate-template-dialog.tsx
new file mode 100644
index 0000000000..7e8972f1c6
--- /dev/null
+++ b/apps/web/src/features/routines/views/activate-template-dialog.tsx
@@ -0,0 +1,221 @@
+import CheckIcon from '@icon/system/regular/check.svg';
+import LightningIcon from '@icon/system/regular/lightning.svg';
+import UserIcon from '@icon/system/regular/user.svg';
+import WarningIcon from '@icon/system/regular/warning-circle.svg';
+import { ActionDialogShell, Badge, Button, Dialog, Item, Tabs } from '@ui';
+import { For, type JSX, Show } from 'solid-js';
+import {
+ TemplateReferenceChip,
+ variableLabel,
+} from '../components/template-reference';
+import type { ReferenceChoice } from '../core/template';
+import type { TemplateReference } from '../primitives/template-activation';
+
+function decisionReason(reference: TemplateReference) {
+ if (reference.state === 'choose') return 'Each person picks their own.';
+ return reference.variable.kind === 'item' &&
+ reference.variable.block_name === 'channel'
+ ? "A channel you're not in."
+ : "You can't open this.";
+}
+
+function DecisionRow(props: {
+ reference: TemplateReference;
+ choice: ReferenceChoice | undefined;
+ onChoose(choice: ReferenceChoice): void;
+}) {
+ return (
+ <Item variant="outlined" size="sm" class="flex-wrap">
+ <Item.Content>
+ <Item.Title>
+ <TemplateReferenceChip
+ variable={props.reference.variable}
+ state={props.reference.state}
+ />
+ </Item.Title>
+ <Item.Description>{decisionReason(props.reference)}</Item.Description>
+ </Item.Content>
+ <Item.Actions>
+ <Tabs
+ aria-label={`What to do with ${variableLabel(props.reference.variable)}`}
+ size="sm"
+ wrap
+ options={[
+ { value: 'keep' as const, label: 'Keep it' },
+ { value: 'leave_out' as const, label: 'Leave out' },
+ ]}
+ value={props.choice}
+ onChange={props.onChoose}
+ />
+ </Item.Actions>
+ </Item>
+ );
+}
+
+function Section(props: {
+ icon: JSX.Element;
+ title: string;
+ children: JSX.Element;
+}) {
+ return (
+ <section class="flex flex-col gap-2">
+ <h3 class="flex items-center gap-1.5 text-xs font-medium text-ink-muted">
+ {props.icon}
+ {props.title}
+ </h3>
+ {props.children}
+ </section>
+ );
+}
+
+/**
+ * Activating a template: the routine as it will run for the viewer on the
+ * left, and on the right the references they must decide on, what fills in
+ * as them, and what works as it is.
+ */
+export function ActivateTemplateDialog(props: {
+ open: boolean;
+ onOpenChange(open: boolean): void;
+ name: string;
+ authorName: string;
+ triggers: readonly string[];
+ /** The filled-in instructions, read-only. */
+ instructions: JSX.Element;
+ references: readonly TemplateReference[];
+ choices: ReadonlyMap<string, ReferenceChoice>;
+ onChoose(key: string, choice: ReferenceChoice): void;
+ undecided: number;
+ pending: boolean;
+ error?: string;
+ onActivate(): void;
+}) {
+ const byState = (...states: TemplateReference['state'][]) =>
+ props.references.filter((reference) => states.includes(reference.state));
+ return (
+ <Dialog
+ open={props.open}
+ onOpenChange={props.onOpenChange}
+ position="center"
+ class="w-[min(64rem,calc(100vw-2rem))]"
+ visibleScrim
+ >
+ <div class="contents">
+ <ActionDialogShell hideBorder class="max-h-[85dvh] bg-transparent">
+ <ActionDialogShell.Header class="flex flex-wrap items-center gap-2 space-y-0 border-b border-edge-divider px-5 py-3">
+ <ActionDialogShell.Title class="text-base">
+ Activate for me: {props.name}
+ </ActionDialogShell.Title>
+ <Badge variant="outline" size="xs">
+ Template by {props.authorName}
+ </Badge>
+ </ActionDialogShell.Header>
+ <div class="grid min-h-0 flex-1 overflow-y-auto md:grid-cols-[3fr_2fr]">
+ <div class="flex flex-col gap-3 p-5">
+ <h3 class="text-xs font-medium text-ink-muted">Your routine</h3>
+ <For each={props.triggers}>
+ {(trigger) => (
+ <div class="flex items-center gap-2 text-sm">
+ <LightningIcon class="size-4 shrink-0 text-ink-muted" />
+ {trigger}
+ </div>
+ )}
+ </For>
+ {props.instructions}
+ </div>
+ <div class="flex flex-col gap-5 border-edge-divider p-5 md:border-l">
+ <Show when={byState('unavailable', 'choose').length > 0}>
+ <Section
+ icon={<WarningIcon class="size-3.5 text-warning" />}
+ title={`Your call · ${props.undecided} left`}
+ >
+ <For each={byState('unavailable', 'choose')}>
+ {(reference) => (
+ <DecisionRow
+ reference={reference}
+ choice={props.choices.get(reference.key)}
+ onChoose={(choice) =>
+ props.onChoose(reference.key, choice)
+ }
+ />
+ )}
+ </For>
+ </Section>
+ </Show>
+ <Section
+ icon={<UserIcon class="size-3.5" />}
+ title="Filled in as you"
+ >
+ <dl class="grid grid-cols-[auto_1fr] gap-x-3 gap-y-1 text-sm">
+ <dt class="text-ink-muted">Runs as</dt>
+ <dd>You</dd>
+ <For each={byState('fills_in')}>
+ {(reference) => (
+ <>
+ <dt class="text-ink-muted">
+ {reference.variable.kind === 'time_zone'
+ ? 'Time zone'
+ : `Mentions of ${variableLabel(reference.variable)}`}
+ </dt>
+ <dd>
+ {reference.variable.kind === 'time_zone'
+ ? 'Yours'
+ : 'You'}
+ </dd>
+ </>
+ )}
+ </For>
+ </dl>
+ </Section>
+ <Show when={byState('works').length > 0}>
+ <Section
+ icon={<CheckIcon class="size-3.5 text-success" />}
+ title={`Works for you as is · ${byState('works').length}`}
+ >
+ <div class="flex flex-wrap gap-2">
+ <For each={byState('works')}>
+ {(reference) => (
+ <TemplateReferenceChip
+ variable={reference.variable}
+ state={reference.state}
+ />
+ )}
+ </For>
+ </div>
+ </Section>
+ </Show>
+ </div>
+ </div>
+ <ActionDialogShell.Footer class="justify-between">
+ <p class="text-sm text-ink-muted" role="status">
+ <Show
+ when={props.error}
+ fallback={
+ props.undecided > 0
+ ? `Decide on ${props.undecided} ${props.undecided === 1 ? 'reference' : 'references'} to activate.`
+ : 'Your routine runs as you, on its own schedule.'
+ }
+ >
+ {(error) => <span class="text-failure">{error()}</span>}
+ </Show>
+ </p>
+ <div class="flex gap-2">
+ <Button
+ variant="outline"
+ onClick={() => props.onOpenChange(false)}
+ >
+ Cancel
+ </Button>
+ <Button
+ variant="cta"
+ disabled={props.undecided > 0 || props.pending}
+ onClick={() => props.onActivate()}
+ >
+ {props.pending ? 'Activating…' : 'Activate'}
+ </Button>
+ </div>
+ </ActionDialogShell.Footer>
+ </ActionDialogShell>
+ </div>
+ </Dialog>
+ );
+}
diff --git a/apps/web/src/features/routines/views/routine-detail.tsx b/apps/web/src/features/routines/views/routine-detail.tsx
index f46faa4f51..e06f91ef7d 100644
--- a/apps/web/src/features/routines/views/routine-detail.tsx
+++ b/apps/web/src/features/routines/views/routine-detail.tsx
@@ -1,8 +1,10 @@
import { fireAndForget } from '@core/util/fireAndForget';
+import ArrowUpRightIcon from '@icon/system/regular/arrow-up-right.svg';
import CopyIcon from '@icon/system/regular/copy.svg';
import DotsIcon from '@icon/system/regular/dots-three.svg';
+import ShareIcon from '@icon/system/regular/share-network.svg';
import TrashIcon from '@icon/system/regular/trash-simple.svg';
-import { Dropdown } from '@ui';
+import { Button, Dropdown } from '@ui';
import { type Accessor, createSignal, Match, Show, Switch } from 'solid-js';
import { RoutineEditor } from '../components/routine-editor';
import { RoutineRunButton } from '../components/routine-run-button';
@@ -26,6 +28,8 @@ export function RoutineDetailView(props: {
onBack(): void;
onDelete(): void;
onCopyPrompt(prompt: string): Promise<void>;
+ onShareTemplate(): void;
+ onOpenTemplate(templateId: string): void;
onOpenRun(resource: HistoryResource, newSplit: boolean): void;
}) {
const {
@@ -114,6 +118,10 @@ export function RoutineDetailView(props: {
<CopyIcon class="size-4" />
Duplicate
</Dropdown.Item>
+ <Dropdown.Item onSelect={props.onShareTemplate}>
+ <ShareIcon class="size-4" />
+ Share as template
+ </Dropdown.Item>
<Show when={isOwned()}>
<Dropdown.Item onSelect={props.onDelete}>
<TrashIcon class="size-4" />
@@ -124,6 +132,20 @@ export function RoutineDetailView(props: {
</Dropdown>
)
}
+ properties={
+ <Show when={routine().templateId}>
+ {(templateId) => (
+ <Button
+ variant="accent"
+ size="sm"
+ onClick={() => props.onOpenTemplate(templateId())}
+ >
+ Created from template
+ <ArrowUpRightIcon />
+ </Button>
+ )}
+ </Show>
+ }
nextRun={nextRun()}
instructions={
<Show when={state()}>
diff --git a/apps/web/src/features/routines/views/routine-template-view.tsx b/apps/web/src/features/routines/views/routine-template-view.tsx
new file mode 100644
index 0000000000..6b13ce48e6
--- /dev/null
+++ b/apps/web/src/features/routines/views/routine-template-view.tsx
@@ -0,0 +1,164 @@
+import { ViewBreadcrumbs, ViewShell } from '@app/components/view-shell';
+import ClockCounterIcon from '@icon/system/regular/clock-counter-clockwise.svg';
+import LightningIcon from '@icon/system/regular/lightning.svg';
+import PlayIcon from '@icon/system/regular/play.svg';
+import type { RoutineTemplate } from '@service-scheduled-action/generated/schemas';
+import { Badge, Button, Layer } from '@ui';
+import { For, type JSX, Show } from 'solid-js';
+import { TemplateReferenceChip } from '../components/template-reference';
+import { formatDateTime } from '../core/routine-draft';
+import type { TemplateReference } from '../primitives/template-activation';
+
+/**
+ * A routine someone shared as a template, as the people it was shared with
+ * see it. Nothing runs until they activate their own copy.
+ */
+export function RoutineTemplateView(props: {
+ template: RoutineTemplate;
+ authorName: string;
+ /** False for the template's author, who already has the routine. */
+ canActivate: boolean;
+ triggers: readonly string[];
+ references: readonly TemplateReference[];
+ instructions: JSX.Element;
+ onActivate(): void;
+ onBack(): void;
+}) {
+ const decisions = () =>
+ props.references.filter(
+ (reference) =>
+ reference.state === 'unavailable' || reference.state === 'choose'
+ ).length;
+ return (
+ <ViewBreadcrumbs.Root
+ value="template"
+ onChange={(value) => {
+ if (value === 'routines') props.onBack();
+ }}
+ >
+ <ViewBreadcrumbs.Item value="routines" metadata={{}} order={0}>
+ {(item) => (
+ <ViewBreadcrumbs.ReturnButton
+ onClick={item.onSelect}
+ aria-label="Back to routines"
+ tooltip="Routines"
+ >
+ Routines
+ </ViewBreadcrumbs.ReturnButton>
+ )}
+ </ViewBreadcrumbs.Item>
+ <ViewBreadcrumbs.Item value="template" metadata={{}} order={1}>
+ {(item) => (
+ <ViewBreadcrumbs.Button
+ class="gap-1.5"
+ isActive={item.isActive()}
+ onClick={item.onSelect}
+ tooltip={props.template.name}
+ >
+ <ClockCounterIcon class="size-3 shrink-0" />
+ <span class="truncate">{props.template.name}</span>
+ </ViewBreadcrumbs.Button>
+ )}
+ </ViewBreadcrumbs.Item>
+ <div class="flex size-full min-h-0 min-w-0 flex-col text-ink">
+ <ViewShell.TopBar
+ class="touch:flex"
+ aria-label="Routine template toolbar"
+ >
+ <ViewBreadcrumbs.Outlet
+ aria-label="Routine template location"
+ class="min-w-0"
+ />
+ <Show when={props.canActivate}>
+ <Button
+ variant="cta"
+ size="md"
+ class="ml-auto shrink-0"
+ onClick={() => props.onActivate()}
+ >
+ <PlayIcon />
+ Activate for me
+ </Button>
+ </Show>
+ </ViewShell.TopBar>
+ <div class="min-h-0 flex-1 overflow-y-auto px-6 pb-8 pt-12 touch:pt-6">
+ <div class="mx-auto flex max-w-3xl flex-col gap-6">
+ <div>
+ <h1 class="text-2xl font-semibold">{props.template.name}</h1>
+ <Show when={props.template.description}>
+ <p class="mt-1 text-ink-muted">{props.template.description}</p>
+ </Show>
+ <div class="mt-3 flex flex-wrap gap-2">
+ <Badge variant="outline" size="sm">
+ <ClockCounterIcon />
+ Template by {props.authorName}
+ </Badge>
+ <Badge variant="outline" size="sm">
+ {props.template.active_count === 1
+ ? 'Active for 1 person'
+ : `Active for ${props.template.active_count} people`}
+ </Badge>
+ <Badge variant="outline" size="sm">
+ Updated {formatDateTime(props.template.updated_at)}
+ </Badge>
+ </div>
+ </div>
+ <Layer depth={1}>
+ <section
+ aria-label="Template triggers"
+ class="rounded-xl border border-edge-muted bg-surface"
+ >
+ <div class="flex flex-col gap-2 p-4">
+ <For each={props.triggers}>
+ {(trigger) => (
+ <div class="flex items-center gap-2 text-sm">
+ <LightningIcon class="size-4 shrink-0 text-ink-muted" />
+ {trigger}
+ </div>
+ )}
+ </For>
+ </div>
+ <div class="flex items-center gap-2 border-t border-edge-muted px-4 py-3 text-xs text-ink-muted">
+ <span
+ aria-hidden="true"
+ class="size-1.5 rounded-full bg-ink-extra-muted"
+ />
+ Doesn't run until you activate it
+ </div>
+ </section>
+ </Layer>
+ <section aria-label="Template instructions">
+ {props.instructions}
+ </section>
+ <Show when={props.references.length > 0}>
+ <section
+ aria-label="Template references"
+ class="flex flex-col gap-2"
+ >
+ <h2 class="text-sm font-medium text-ink-muted">References</h2>
+ <div class="flex flex-wrap gap-2">
+ <For each={props.references}>
+ {(reference) => (
+ <TemplateReferenceChip
+ variable={reference.variable}
+ state={reference.state}
+ />
+ )}
+ </For>
+ </div>
+ <p class="text-xs text-ink-muted">
+ Dashed references fill in as you.
+ <Show when={decisions() > 0}>
+ {' '}
+ Amber ones you can't open, so you'll decide what to do with
+ them.
+ </Show>
+ </p>
+ </section>
+ </Show>
+ </div>
+ </div>
+ </div>
+ </ViewBreadcrumbs.Root>
+ );
+}
diff --git a/apps/web/src/features/routines/views/share-template-dialog.tsx b/apps/web/src/features/routines/views/share-template-dialog.tsx
new file mode 100644
index 0000000000..a33b87402d
--- /dev/null
+++ b/apps/web/src/features/routines/views/share-template-dialog.tsx
@@ -0,0 +1,212 @@
+import ArrowsClockwiseIcon from '@icon/system/regular/arrows-clockwise.svg';
+import CheckIcon from '@icon/system/regular/check.svg';
+import LinkIcon from '@icon/system/regular/link.svg';
+import LockIcon from '@icon/system/regular/lock-simple.svg';
+import type {
+ RoutineTemplate,
+ TemplateVariable,
+ VariableFill,
+} from '@service-scheduled-action/generated/schemas';
+import {
+ ActionDialogShell,
+ Badge,
+ Button,
+ Card,
+ Dialog,
+ Input,
+ Tabs,
+} from '@ui';
+import { For, type JSX, Show } from 'solid-js';
+import {
+ TemplateReferenceChip,
+ variableLabel,
+} from '../components/template-reference';
+import { variableKey } from '../core/template';
+
+function fillOptions(variable: TemplateVariable) {
+ if (variable.kind === 'time_zone')
+ return [
+ { value: 'activator' as const, label: 'Their time zone' },
+ { value: 'shared' as const, label: `Keep ${variable.timezone}` },
+ ];
+ return [
+ ...(variable.kind === 'user'
+ ? [{ value: 'activator' as const, label: 'The person activating' }]
+ : []),
+ { value: 'shared' as const, label: 'Same for everyone' },
+ { value: 'choice' as const, label: 'They choose' },
+ ];
+}
+
+function VariableRow(props: {
+ variable: TemplateVariable;
+ disabled: boolean;
+ onFill(fill: VariableFill): void;
+}) {
+ return (
+ <div class="flex flex-wrap items-center justify-between gap-2 py-1.5">
+ <TemplateReferenceChip
+ variable={props.variable}
+ state={props.variable.fill === 'activator' ? 'fills_in' : 'works'}
+ />
+ <Tabs
+ aria-label={`How ${variableLabel(props.variable)} fills in`}
+ size="sm"
+ wrap
+ disabled={props.disabled}
+ options={fillOptions(props.variable)}
+ value={props.variable.fill}
+ onChange={props.onFill}
+ />
+ </div>
+ );
+}
+
+function ShareNote(props: { icon: JSX.Element; children: JSX.Element }) {
+ return (
+ <li class="flex gap-2 text-sm text-ink-muted">
+ <span class="mt-0.5 shrink-0">{props.icon}</span>
+ <span>{props.children}</span>
+ </li>
+ );
+}
+
+/**
+ * Sharing a routine as a template: the owner generalizes its references,
+ * publishes the snapshot, and passes the link on. Their routine itself is
+ * never shared.
+ */
+export function ShareTemplateDialog(props: {
+ open: boolean;
+ onOpenChange(open: boolean): void;
+ name: string;
+ /** `undefined` while loading, `null` when not shared yet. */
+ template: RoutineTemplate | null | undefined;
+ description: string;
+ onDescription(description: string): void;
+ variables: readonly TemplateVariable[];
+ onFill(key: string, fill: VariableFill): void;
+ pending: boolean;
+ error?: string;
+ onShare(): void;
+ onUnshare(): void;
+ onCopyLink(): void;
+ /** Posts the template to a channel or person; shown once it's shared. */
+ send: JSX.Element;
+}) {
+ return (
+ <Dialog
+ open={props.open}
+ onOpenChange={props.onOpenChange}
+ position="center"
+ class="w-[min(40rem,calc(100vw-2rem))]"
+ visibleScrim
+ >
+ <div class="contents">
+ <ActionDialogShell hideBorder class="max-h-[85dvh] bg-transparent">
+ <ActionDialogShell.Body class="flex flex-col gap-5 space-y-0">
+ <ActionDialogShell.Header class="flex flex-wrap items-center gap-2 space-y-0">
+ <ActionDialogShell.Title class="text-base">
+ Share: {props.name}
+ </ActionDialogShell.Title>
+ <Badge variant="outline" size="xs">
+ As a template
+ </Badge>
+ </ActionDialogShell.Header>
+ <Card>
+ <Card.Body>
+ <p class="font-medium">
+ People get a template, not your routine
+ </p>
+ <ul class="mt-2 flex flex-col gap-1.5">
+ <ShareNote icon={<CheckIcon class="size-4 text-success" />}>
+ They see your instructions and triggers, and can activate
+ their own copy that runs as them.
+ </ShareNote>
+ <ShareNote icon={<LockIcon class="size-4" />}>
+ Your routine, its runs and its results stay private to you.
+ </ShareNote>
+ <ShareNote icon={<ArrowsClockwiseIcon class="size-4" />}>
+ Sharing again updates the template with your routine's
+ current setup.
+ </ShareNote>
+ </ul>
+ </Card.Body>
+ </Card>
+ <label class="flex flex-col gap-1.5 text-sm">
+ <span class="font-medium">Description</span>
+ <Input
+ value={props.description}
+ placeholder="What does this routine do for someone?"
+ maxLength={1000}
+ disabled={props.pending}
+ onInput={(event) =>
+ props.onDescription(event.currentTarget.value)
+ }
+ />
+ </label>
+ <Show when={props.variables.length > 0}>
+ <section class="flex flex-col gap-1">
+ <h3 class="text-sm font-medium">
+ What changes for each person
+ </h3>
+ <div class="divide-y divide-edge-divider">
+ <For each={props.variables}>
+ {(variable) => (
+ <VariableRow
+ variable={variable}
+ disabled={props.pending}
+ onFill={(fill) =>
+ props.onFill(variableKey(variable), fill)
+ }
+ />
+ )}
+ </For>
+ </div>
+ </section>
+ </Show>
+ <Show when={props.template}>
+ {(template) => (
+ <section class="flex flex-col gap-2">
+ <h3 class="text-sm font-medium">
+ Shared · active for {template().active_count}
+ </h3>
+ {props.send}
+ </section>
+ )}
+ </Show>
+ <Show when={props.error}>
+ <p class="text-sm text-failure" role="alert">
+ {props.error}
+ </p>
+ </Show>
+ </ActionDialogShell.Body>
+ <ActionDialogShell.Footer class="justify-between">
+ <Show when={props.template} fallback={<span />}>
+ <div class="flex flex-wrap gap-2">
+ <Button variant="outline" onClick={() => props.onCopyLink()}>
+ <LinkIcon />
+ Copy template link
+ </Button>
+ <Button
+ variant="danger"
+ disabled={props.pending}
+ onClick={() => props.onUnshare()}
+ >
+ Stop sharing
+ </Button>
+ </div>
+ </Show>
+ <Button
+ variant="cta"
+ disabled={props.pending || props.template === undefined}
+ onClick={() => props.onShare()}
+ >
+ {props.template ? 'Update template' : 'Share template'}
+ </Button>
+ </ActionDialogShell.Footer>
+ </ActionDialogShell>
+ </div>
+ </Dialog>
+ );
+}
diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/client.ts b/apps/web/src/lib/service-clients/service-scheduled-action/client.ts
index 9f80696588..90efbcadb0 100644
--- a/apps/web/src/lib/service-clients/service-scheduled-action/client.ts
+++ b/apps/web/src/lib/service-clients/service-scheduled-action/client.ts
@@ -14,8 +14,10 @@ import type {
ActionExecutionRecord,
CreateScheduledAction,
InProgressExecution,
+ RoutineTemplate,
ScheduledAction,
SetScheduledActionEnabled,
+ ShareRoutineTemplate,
UpdateScheduledAction,
} from './generated/schemas';
@@ -100,4 +102,30 @@ export const scheduledActionClient = {
`/scheduled-actions/${args.scheduleId}/history`,
{ method: 'GET' }
),
+
+ getTemplate: (scheduleId: string) =>
+ scheduledActionFetch<RoutineTemplate>(
+ `/scheduled-actions/${scheduleId}/template`,
+ { method: 'GET' }
+ ),
+
+ shareTemplate: (args: { scheduleId: string; body: ShareRoutineTemplate }) =>
+ scheduledActionFetch<RoutineTemplate>(
+ `/scheduled-actions/${args.scheduleId}/template`,
+ { method: 'PUT', body: JSON.stringify(args.body) }
+ ),
+
+ unshareTemplate: (args: { scheduleId: string }) =>
+ scheduledActionFetch(`/scheduled-actions/${args.scheduleId}/template`, {
+ method: 'DELETE',
+ }),
+
+ activateTemplate: (args: {
+ templateId: string;
+ body: CreateScheduledAction;
+ }) =>
+ scheduledActionFetch<ScheduledAction>(
+ `/scheduled-actions/${args.templateId}/template/activate`,
+ { method: 'POST', body: JSON.stringify(args.body) }
+ ),
};
diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/generated/client.ts b/apps/web/src/lib/service-clients/service-scheduled-action/generated/client.ts
index eebc9295f2..2bdeac878a 100644
--- a/apps/web/src/lib/service-clients/service-scheduled-action/generated/client.ts
+++ b/apps/web/src/lib/service-clients/service-scheduled-action/generated/client.ts
@@ -12,8 +12,10 @@ import type {
EmptyResponse,
InProgressExecution,
ListScheduledActionsParams,
+ RoutineTemplate,
ScheduledActionResponse,
SetScheduledActionEnabled,
+ ShareRoutineTemplate,
UpdateScheduledAction,
} from './schemas';
@@ -615,3 +617,271 @@ export const listScheduledActionHistory = async (
headers: res.headers,
} as listScheduledActionHistoryResponse;
};
+
+export type getScheduledActionTemplateResponse200 = {
+ data: RoutineTemplate;
+ status: 200;
+};
+
+export type getScheduledActionTemplateResponse401 = {
+ data: string;
+ status: 401;
+};
+
+export type getScheduledActionTemplateResponse404 = {
+ data: string;
+ status: 404;
+};
+
+export type getScheduledActionTemplateResponse500 = {
+ data: string;
+ status: 500;
+};
+
+export type getScheduledActionTemplateResponseSuccess =
+ getScheduledActionTemplateResponse200 & {
+ headers: Headers;
+ };
+export type getScheduledActionTemplateResponseError = (
+ | getScheduledActionTemplateResponse401
+ | getScheduledActionTemplateResponse404
+ | getScheduledActionTemplateResponse500
+) & {
+ headers: Headers;
+};
+
+export type getScheduledActionTemplateResponse =
+ | getScheduledActionTemplateResponseSuccess
+ | getScheduledActionTemplateResponseError;
+
+export const getGetScheduledActionTemplateUrl = (id: string) => {
+ return `/scheduled-actions/${id}/template`;
+};
+
+export const getScheduledActionTemplate = async (
+ id: string,
+ options?: RequestInit
+): Promise<getScheduledActionTemplateResponse> => {
+ const res = await fetch(getGetScheduledActionTemplateUrl(id), {
+ ...options,
+ method: 'GET',
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: getScheduledActionTemplateResponse['data'] = body
+ ? JSON.parse(body)
+ : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as getScheduledActionTemplateResponse;
+};
+
+export type shareScheduledActionTemplateResponse200 = {
+ data: RoutineTemplate;
+ status: 200;
+};
+
+export type shareScheduledActionTemplateResponse400 = {
+ data: string;
+ status: 400;
+};
+
+export type shareScheduledActionTemplateResponse401 = {
+ data: string;
+ status: 401;
+};
+
+export type shareScheduledActionTemplateResponse404 = {
+ data: string;
+ status: 404;
+};
+
+export type shareScheduledActionTemplateResponse500 = {
+ data: string;
+ status: 500;
+};
+
+export type shareScheduledActionTemplateResponseSuccess =
+ shareScheduledActionTemplateResponse200 & {
+ headers: Headers;
+ };
+export type shareScheduledActionTemplateResponseError = (
+ | shareScheduledActionTemplateResponse400
+ | shareScheduledActionTemplateResponse401
+ | shareScheduledActionTemplateResponse404
+ | shareScheduledActionTemplateResponse500
+) & {
+ headers: Headers;
+};
+
+export type shareScheduledActionTemplateResponse =
+ | shareScheduledActionTemplateResponseSuccess
+ | shareScheduledActionTemplateResponseError;
+
+export const getShareScheduledActionTemplateUrl = (id: string) => {
+ return `/scheduled-actions/${id}/template`;
+};
+
+export const shareScheduledActionTemplate = async (
+ id: string,
+ shareRoutineTemplate: ShareRoutineTemplate,
+ options?: RequestInit
+): Promise<shareScheduledActionTemplateResponse> => {
+ const res = await fetch(getShareScheduledActionTemplateUrl(id), {
+ ...options,
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(shareRoutineTemplate),
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: shareScheduledActionTemplateResponse['data'] = body
+ ? JSON.parse(body)
+ : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as shareScheduledActionTemplateResponse;
+};
+
+export type unshareScheduledActionTemplateResponse204 = {
+ data: void;
+ status: 204;
+};
+
+export type unshareScheduledActionTemplateResponse401 = {
+ data: string;
+ status: 401;
+};
+
+export type unshareScheduledActionTemplateResponse404 = {
+ data: string;
+ status: 404;
+};
+
+export type unshareScheduledActionTemplateResponse500 = {
+ data: string;
+ status: 500;
+};
+
+export type unshareScheduledActionTemplateResponseSuccess =
+ unshareScheduledActionTemplateResponse204 & {
+ headers: Headers;
+ };
+export type unshareScheduledActionTemplateResponseError = (
+ | unshareScheduledActionTemplateResponse401
+ | unshareScheduledActionTemplateResponse404
+ | unshareScheduledActionTemplateResponse500
+) & {
+ headers: Headers;
+};
+
+export type unshareScheduledActionTemplateResponse =
+ | unshareScheduledActionTemplateResponseSuccess
+ | unshareScheduledActionTemplateResponseError;
+
+export const getUnshareScheduledActionTemplateUrl = (id: string) => {
+ return `/scheduled-actions/${id}/template`;
+};
+
+export const unshareScheduledActionTemplate = async (
+ id: string,
+ options?: RequestInit
+): Promise<unshareScheduledActionTemplateResponse> => {
+ const res = await fetch(getUnshareScheduledActionTemplateUrl(id), {
+ ...options,
+ method: 'DELETE',
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: unshareScheduledActionTemplateResponse['data'] = body
+ ? JSON.parse(body)
+ : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as unshareScheduledActionTemplateResponse;
+};
+
+export type activateScheduledActionTemplateResponse201 = {
+ data: ScheduledActionResponse;
+ status: 201;
+};
+
+export type activateScheduledActionTemplateResponse400 = {
+ data: string;
+ status: 400;
+};
+
+export type activateScheduledActionTemplateResponse401 = {
+ data: string;
+ status: 401;
+};
+
+export type activateScheduledActionTemplateResponse403 = {
+ data: string;
+ status: 403;
+};
+
+export type activateScheduledActionTemplateResponse404 = {
+ data: string;
+ status: 404;
+};
+
+export type activateScheduledActionTemplateResponse500 = {
+ data: string;
+ status: 500;
+};
+
+export type activateScheduledActionTemplateResponseSuccess =
+ activateScheduledActionTemplateResponse201 & {
+ headers: Headers;
+ };
+export type activateScheduledActionTemplateResponseError = (
+ | activateScheduledActionTemplateResponse400
+ | activateScheduledActionTemplateResponse401
+ | activateScheduledActionTemplateResponse403
+ | activateScheduledActionTemplateResponse404
+ | activateScheduledActionTemplateResponse500
+) & {
+ headers: Headers;
+};
+
+export type activateScheduledActionTemplateResponse =
+ | activateScheduledActionTemplateResponseSuccess
+ | activateScheduledActionTemplateResponseError;
+
+export const getActivateScheduledActionTemplateUrl = (id: string) => {
+ return `/scheduled-actions/${id}/template/activate`;
+};
+
+export const activateScheduledActionTemplate = async (
+ id: string,
+ createScheduledAction: CreateScheduledAction,
+ options?: RequestInit
+): Promise<activateScheduledActionTemplateResponse> => {
+ const res = await fetch(getActivateScheduledActionTemplateUrl(id), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(createScheduledAction),
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: activateScheduledActionTemplateResponse['data'] = body
+ ? JSON.parse(body)
+ : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as activateScheduledActionTemplateResponse;
+};
diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/index.ts
index e74f34f303..95e8f53ebb 100644
--- a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/index.ts
+++ b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/index.ts
@@ -55,6 +55,8 @@ export * from './legacyActionConfiguration';
export * from './legacyActionConfigurationTask';
export * from './listScheduledActionsParams';
export * from './routineModelId';
+export * from './routineTemplate';
+export * from './routineTemplateTask';
export * from './routineTrigger';
export * from './routineTriggerOneOf';
export * from './routineTriggerOneOfThree';
@@ -73,6 +75,7 @@ export * from './scheduledActionResponseAllOf';
export * from './scheduledActionResponseAllOfSchedule';
export * from './scheduledActionResponseAllOfTimezone';
export * from './scheduledActionTask';
+export * from './scheduledActionTemplateId';
export * from './scheduledActionUpdate';
export * from './scheduledActionUpdateOneOf';
export * from './scheduledActionUpdateOneOfChatId';
@@ -83,4 +86,13 @@ export * from './scheduledActionUpdateOneOfFiveType';
export * from './scheduledActionUpdateOneOfResource';
export * from './scheduledActionUpdateOneOfType';
export * from './setScheduledActionEnabled';
+export * from './shareRoutineTemplate';
+export * from './templateVariable';
+export * from './templateVariableOneOf';
+export * from './templateVariableOneOfFive';
+export * from './templateVariableOneOfFiveKind';
+export * from './templateVariableOneOfKind';
+export * from './templateVariableOneOfThree';
+export * from './templateVariableOneOfThreeKind';
export * from './updateScheduledAction';
+export * from './variableFill';
diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/routineTemplate.ts b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/routineTemplate.ts
new file mode 100644
index 0000000000..d6ddf07aab
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/routineTemplate.ts
@@ -0,0 +1,33 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * scheduled_action
+ * API for managing scheduled actions
+ * OpenAPI spec version: 0.1.0
+ */
+
+import type { ActionTrigger } from './actionTrigger';
+import type { RoutineTemplateTask } from './routineTemplateTask';
+import type { TemplateVariable } from './templateVariable';
+
+/**
+ * A shared routine's snapshot, readable by any signed-in user with its ID.
+ */
+export interface RoutineTemplate {
+ /**
+ * Routines activated from this template, including stopped ones.
+ * @minimum 0
+ */
+ active_count: number;
+ /** Who shared it: the source routine's owner. */
+ author: string;
+ created_at: string;
+ description: string;
+ /** The routine it was shared from. */
+ id: string;
+ name: string;
+ task: RoutineTemplateTask;
+ trigger: ActionTrigger;
+ updated_at: string;
+ variables: TemplateVariable[];
+}
diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/routineTemplateTask.ts b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/routineTemplateTask.ts
new file mode 100644
index 0000000000..64cd07febb
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/routineTemplateTask.ts
@@ -0,0 +1,9 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * scheduled_action
+ * API for managing scheduled actions
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type RoutineTemplateTask = { [key: string]: unknown };
diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/scheduledAction.ts b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/scheduledAction.ts
index 1494a3af5f..dd130cc5c8 100644
--- a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/scheduledAction.ts
+++ b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/scheduledAction.ts
@@ -14,6 +14,7 @@ import type { ScheduledActionEventActivatedAt } from './scheduledActionEventActi
import type { ScheduledActionId } from './scheduledActionId';
import type { ScheduledActionNextRunAt } from './scheduledActionNextRunAt';
import type { ScheduledActionTask } from './scheduledActionTask';
+import type { ScheduledActionTemplateId } from './scheduledActionTemplateId';
export interface ScheduledAction {
claimed?: ScheduledActionClaimed;
@@ -38,6 +39,8 @@ rather than failing to parse. */
/** Whether the action's runs are listed in Home and the Agents list. */
run_visibility: RunVisibility;
task: ScheduledActionTask;
+ /** The shared template this routine was activated from, if any. */
+ template_id?: ScheduledActionTemplateId;
trigger: ActionTrigger;
updated_at: string;
}
diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/scheduledActionTemplateId.ts b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/scheduledActionTemplateId.ts
new file mode 100644
index 0000000000..391901afd0
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/scheduledActionTemplateId.ts
@@ -0,0 +1,12 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * scheduled_action
+ * API for managing scheduled actions
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * The shared template this routine was activated from, if any.
+ */
+export type ScheduledActionTemplateId = string | null;
diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/shareRoutineTemplate.ts b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/shareRoutineTemplate.ts
new file mode 100644
index 0000000000..57962e314c
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/shareRoutineTemplate.ts
@@ -0,0 +1,16 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * scheduled_action
+ * API for managing scheduled actions
+ * OpenAPI spec version: 0.1.0
+ */
+import type { TemplateVariable } from './templateVariable';
+
+/**
+ * What the owner supplies when sharing; the rest is snapshotted from the routine.
+ */
+export interface ShareRoutineTemplate {
+ description: string;
+ variables: TemplateVariable[];
+}
diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/templateVariable.ts b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/templateVariable.ts
new file mode 100644
index 0000000000..f207ef368c
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/templateVariable.ts
@@ -0,0 +1,18 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * scheduled_action
+ * API for managing scheduled actions
+ * OpenAPI spec version: 0.1.0
+ */
+import type { TemplateVariableOneOf } from './templateVariableOneOf';
+import type { TemplateVariableOneOfFive } from './templateVariableOneOfFive';
+import type { TemplateVariableOneOfThree } from './templateVariableOneOfThree';
+
+/**
+ * A user-specific part of a shared routine.
+ */
+export type TemplateVariable =
+ | TemplateVariableOneOf
+ | TemplateVariableOneOfThree
+ | TemplateVariableOneOfFive;
diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/templateVariableOneOf.ts b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/templateVariableOneOf.ts
new file mode 100644
index 0000000000..9f0ac0cf84
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/templateVariableOneOf.ts
@@ -0,0 +1,20 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * scheduled_action
+ * API for managing scheduled actions
+ * OpenAPI spec version: 0.1.0
+ */
+
+import type { TemplateVariableOneOfKind } from './templateVariableOneOfKind';
+import type { VariableFill } from './variableFill';
+
+/**
+ * A person mentioned in the instructions, by their user ID.
+ */
+export type TemplateVariableOneOf = {
+ fill: VariableFill;
+ id: string;
+ kind: TemplateVariableOneOfKind;
+ label: string;
+};
diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/templateVariableOneOfFive.ts b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/templateVariableOneOfFive.ts
new file mode 100644
index 0000000000..c8090ca44e
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/templateVariableOneOfFive.ts
@@ -0,0 +1,19 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * scheduled_action
+ * API for managing scheduled actions
+ * OpenAPI spec version: 0.1.0
+ */
+
+import type { TemplateVariableOneOfFiveKind } from './templateVariableOneOfFiveKind';
+import type { VariableFill } from './variableFill';
+
+/**
+ * The time zone of the routine's schedules.
+ */
+export type TemplateVariableOneOfFive = {
+ fill: VariableFill;
+ kind: TemplateVariableOneOfFiveKind;
+ timezone: string;
+};
diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/templateVariableOneOfFiveKind.ts b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/templateVariableOneOfFiveKind.ts
new file mode 100644
index 0000000000..6980f68913
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/templateVariableOneOfFiveKind.ts
@@ -0,0 +1,15 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * scheduled_action
+ * API for managing scheduled actions
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type TemplateVariableOneOfFiveKind =
+ (typeof TemplateVariableOneOfFiveKind)[keyof typeof TemplateVariableOneOfFiveKind];
+
+// eslint-disable-next-line @typescript-eslint/no-redeclare
+export const TemplateVariableOneOfFiveKind = {
+ time_zone: 'time_zone',
+} as const;
diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/templateVariableOneOfKind.ts b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/templateVariableOneOfKind.ts
new file mode 100644
index 0000000000..ca53fcca33
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/templateVariableOneOfKind.ts
@@ -0,0 +1,15 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * scheduled_action
+ * API for managing scheduled actions
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type TemplateVariableOneOfKind =
+ (typeof TemplateVariableOneOfKind)[keyof typeof TemplateVariableOneOfKind];
+
+// eslint-disable-next-line @typescript-eslint/no-redeclare
+export const TemplateVariableOneOfKind = {
+ user: 'user',
+} as const;
diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/templateVariableOneOfThree.ts b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/templateVariableOneOfThree.ts
new file mode 100644
index 0000000000..e414fd4dfb
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/templateVariableOneOfThree.ts
@@ -0,0 +1,22 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * scheduled_action
+ * API for managing scheduled actions
+ * OpenAPI spec version: 0.1.0
+ */
+
+import type { TemplateVariableOneOfThreeKind } from './templateVariableOneOfThreeKind';
+import type { VariableFill } from './variableFill';
+
+/**
+ * A document, channel or other item mentioned in the instructions.
+ */
+export type TemplateVariableOneOfThree = {
+ /** The mention's block name, such as `channel` or `md`. */
+ block_name: string;
+ fill: VariableFill;
+ id: string;
+ kind: TemplateVariableOneOfThreeKind;
+ label: string;
+};
diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/templateVariableOneOfThreeKind.ts b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/templateVariableOneOfThreeKind.ts
new file mode 100644
index 0000000000..19ca66b134
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/templateVariableOneOfThreeKind.ts
@@ -0,0 +1,15 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * scheduled_action
+ * API for managing scheduled actions
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type TemplateVariableOneOfThreeKind =
+ (typeof TemplateVariableOneOfThreeKind)[keyof typeof TemplateVariableOneOfThreeKind];
+
+// eslint-disable-next-line @typescript-eslint/no-redeclare
+export const TemplateVariableOneOfThreeKind = {
+ item: 'item',
+} as const;
diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/variableFill.ts b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/variableFill.ts
new file mode 100644
index 0000000000..bce575b978
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/variableFill.ts
@@ -0,0 +1,19 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * scheduled_action
+ * API for managing scheduled actions
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * How a variable is filled when someone activates the template.
+ */
+export type VariableFill = (typeof VariableFill)[keyof typeof VariableFill];
+
+// eslint-disable-next-line @typescript-eslint/no-redeclare
+export const VariableFill = {
+ activator: 'activator',
+ shared: 'shared',
+ choice: 'choice',
+} as const;
diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/openapi.json b/apps/web/src/lib/service-clients/service-scheduled-action/openapi.json
index a1e1bd64f2..afb4d7882b 100644
--- a/apps/web/src/lib/service-clients/service-scheduled-action/openapi.json
+++ b/apps/web/src/lib/service-clients/service-scheduled-action/openapi.json
@@ -602,6 +602,281 @@
}
}
}
+ },
+ "/scheduled-actions/{id}/template": {
+ "get": {
+ "tags": ["scheduled actions"],
+ "operationId": "get_scheduled_action_template",
+ "parameters": [
+ {
+ "name": "id",
+ "in": "path",
+ "description": "ID of the shared routine",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RoutineTemplate"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "The routine is not shared",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ }
+ }
+ },
+ "put": {
+ "tags": ["scheduled actions"],
+ "operationId": "share_scheduled_action_template",
+ "parameters": [
+ {
+ "name": "id",
+ "in": "path",
+ "description": "ID of the routine to share",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ShareRoutineTemplate"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RoutineTemplate"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ }
+ }
+ },
+ "delete": {
+ "tags": ["scheduled actions"],
+ "operationId": "unshare_scheduled_action_template",
+ "parameters": [
+ {
+ "name": "id",
+ "in": "path",
+ "description": "ID of the shared routine",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "204": {
+ "description": ""
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/scheduled-actions/{id}/template/activate": {
+ "post": {
+ "tags": ["scheduled actions"],
+ "operationId": "activate_scheduled_action_template",
+ "parameters": [
+ {
+ "name": "id",
+ "in": "path",
+ "description": "ID of the shared routine",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CreateScheduledAction"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "201": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ScheduledActionResponse"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "403": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "The routine is not shared",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ }
+ }
+ }
}
},
"components": {
@@ -1051,6 +1326,65 @@
"type": "string",
"description": "A nonblank model identifier. Runtime catalogs, not the scheduler, own availability."
},
+ "RoutineTemplate": {
+ "type": "object",
+ "description": "A shared routine's snapshot, readable by any signed-in user with its ID.",
+ "required": [
+ "id",
+ "author",
+ "name",
+ "description",
+ "trigger",
+ "task",
+ "variables",
+ "active_count",
+ "created_at",
+ "updated_at"
+ ],
+ "properties": {
+ "active_count": {
+ "type": "integer",
+ "format": "int32",
+ "description": "Routines activated from this template, including stopped ones.",
+ "minimum": 0
+ },
+ "author": {
+ "type": "string",
+ "description": "Who shared it: the source routine's owner."
+ },
+ "created_at": {
+ "type": "string",
+ "format": "date-time"
+ },
+ "description": {
+ "type": "string"
+ },
+ "id": {
+ "type": "string",
+ "format": "uuid",
+ "description": "The routine it was shared from."
+ },
+ "name": {
+ "type": "string"
+ },
+ "task": {
+ "type": "object"
+ },
+ "trigger": {
+ "$ref": "#/components/schemas/ActionTrigger"
+ },
+ "updated_at": {
+ "type": "string",
+ "format": "date-time"
+ },
+ "variables": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/TemplateVariable"
+ }
+ }
+ }
+ },
"RoutineTrigger": {
"oneOf": [
{
@@ -1163,6 +1497,11 @@
"task": {
"type": "object"
},
+ "template_id": {
+ "type": ["string", "null"],
+ "format": "uuid",
+ "description": "The shared template this routine was activated from, if any."
+ },
"trigger": {
"$ref": "#/components/schemas/ActionTrigger"
},
@@ -1273,6 +1612,89 @@
},
"additionalProperties": false
},
+ "ShareRoutineTemplate": {
+ "type": "object",
+ "description": "What the owner supplies when sharing; the rest is snapshotted from the routine.",
+ "required": ["description", "variables"],
+ "properties": {
+ "description": {
+ "type": "string"
+ },
+ "variables": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/TemplateVariable"
+ }
+ }
+ },
+ "additionalProperties": false
+ },
+ "TemplateVariable": {
+ "oneOf": [
+ {
+ "type": "object",
+ "description": "A person mentioned in the instructions, by their user ID.",
+ "required": ["id", "label", "fill", "kind"],
+ "properties": {
+ "fill": {
+ "$ref": "#/components/schemas/VariableFill"
+ },
+ "id": {
+ "type": "string"
+ },
+ "kind": {
+ "type": "string",
+ "enum": ["user"]
+ },
+ "label": {
+ "type": "string"
+ }
+ }
+ },
+ {
+ "type": "object",
+ "description": "A document, channel or other item mentioned in the instructions.",
+ "required": ["id", "block_name", "label", "fill", "kind"],
+ "properties": {
+ "block_name": {
+ "type": "string",
+ "description": "The mention's block name, such as `channel` or `md`."
+ },
+ "fill": {
+ "$ref": "#/components/schemas/VariableFill"
+ },
+ "id": {
+ "type": "string"
+ },
+ "kind": {
+ "type": "string",
+ "enum": ["item"]
+ },
+ "label": {
+ "type": "string"
+ }
+ }
+ },
+ {
+ "type": "object",
+ "description": "The time zone of the routine's schedules.",
+ "required": ["timezone", "fill", "kind"],
+ "properties": {
+ "fill": {
+ "$ref": "#/components/schemas/VariableFill"
+ },
+ "kind": {
+ "type": "string",
+ "enum": ["time_zone"]
+ },
+ "timezone": {
+ "type": "string"
+ }
+ }
+ }
+ ],
+ "description": "A user-specific part of a shared routine."
+ },
"UpdateScheduledAction": {
"oneOf": [
{
@@ -1283,6 +1705,11 @@
}
],
"description": "Full replacement of client configuration, not of server-owned action state."
+ },
+ "VariableFill": {
+ "type": "string",
+ "description": "How a variable is filled when someone activates the template.",
+ "enum": ["activator", "shared", "choice"]
}
}
},
diff --git a/crates/agent_code_mode/src/domain/documentation.json b/crates/agent_code_mode/src/domain/documentation.json
index 0d2e0bcf6a..91a4d61140 100644
--- a/crates/agent_code_mode/src/domain/documentation.json
+++ b/crates/agent_code_mode/src/domain/documentation.json
@@ -38,7 +38,7 @@
{
"name": "routines",
"description": "Create scheduled and event-triggered agent routines and inspect executions.",
- "index": "## routines\nCreate scheduled and event-triggered agent routines and inspect executions.\nRead any symbol below, or one a reference names, with ReadCodeDocs.\n\n### RoutineNamespace (`macro.routines`)\nScheduled and event-triggered routines.\n- `RoutineNamespace.byId`: byId(id): Routine — Construct a lazy routine handle.\n- `RoutineNamespace.create`: create(options): Promise<Routine> — Create an agent routine.\n- `RoutineNamespace.list`: list(options?): Promise<Routine[]> — List routines, optionally including event triggers.\n\n### Routine\nA scheduled or event-triggered agent task.\nExtends `MacroEntity`.\nFields: enabled, id, name, nextRunAt, owner, revision, runVisibility, trigger\n- `Routine.delete`: delete(): Promise<void> — Delete the routine.\n- `Routine.execute`: execute(): Promise<AgentSession | Chat | undefined> — Start an execution immediately and return its transcript handle if available.\n- `Routine.history`: history(): Promise<RoutineExecution[]> — Completed executions, with their routine scoped identity.\n- `Routine.setEnabled`: setEnabled(enabled): Promise<void> — Enable or disable triggering.\n- `Routine.update`: update(options): Promise<void> — Replace the routine's task and trigger configuration.\n- `Routine.byId`: static byId(client, id): Routine — Construct a lazy routine handle.\n- `Routine.from`: static from(client, record): Routine — Seed a handle from a server record.\n\n### RoutineExecution\nA completed routine execution, as recorded by the service.\nFields: record, routine\n- `RoutineExecution.toJSON`: toJSON(): { action_id: string; created_at: string; end_time: string; id?: string | null; is_success: boolean; resource_id?: string | null; result: {[key: string]: unknown; }; routine: string; start_time: string; } — Serialize without the authenticated client.\n\nFunctions: `routineBody`\n\nTypes: `RoutineOptions`, `RoutineEventFilter`, `RoutineTriggerOptions`, `SingleRoutineTrigger`\n"
+ "index": "## routines\nCreate scheduled and event-triggered agent routines and inspect executions.\nRead any symbol below, or one a reference names, with ReadCodeDocs.\n\n### RoutineNamespace (`macro.routines`)\nScheduled and event-triggered routines.\n- `RoutineNamespace.byId`: byId(id): Routine — Construct a lazy routine handle.\n- `RoutineNamespace.create`: create(options): Promise<Routine> — Create an agent routine.\n- `RoutineNamespace.list`: list(options?): Promise<Routine[]> — List routines, optionally including event triggers.\n\n### Routine\nA scheduled or event-triggered agent task.\nExtends `MacroEntity`.\nFields: enabled, id, name, nextRunAt, owner, revision, runVisibility, sourceTemplate, trigger\n- `Routine.activateTemplate`: activateTemplate(options): Promise<Routine> — Create the caller's own routine from this routine's shared template, with its references already filled in for them.\n- `Routine.delete`: delete(): Promise<void> — Delete the routine.\n- `Routine.execute`: execute(): Promise<AgentSession | Chat | undefined> — Start an execution immediately and return its transcript handle if available.\n- `Routine.history`: history(): Promise<RoutineExecution[]> — Completed executions, with their routine scoped identity.\n- `Routine.setEnabled`: setEnabled(enabled): Promise<void> — Enable or disable triggering.\n- `Routine.shareAsTemplate`: shareAsTemplate(options): Promise<RoutineTemplate> — Share this routine as a template, or update its shared snapshot.\n- `Routine.stopSharingTemplate`: stopSharingTemplate(): Promise<void> — Stop sharing this routine.\n- `Routine.template`: template(): Promise<RoutineTemplate | undefined> — This routine's shared template, or undefined when it isn't shared.\n- `Routine.update`: update(options): Promise<void> — Replace the routine's task and trigger configuration.\n- `Routine.byId`: static byId(client, id): Routine — Construct a lazy routine handle.\n- `Routine.from`: static from(client, record): Routine — Seed a handle from a server record.\n\n### RoutineExecution\nA completed routine execution, as recorded by the service.\nFields: record, routine\n- `RoutineExecution.toJSON`: toJSON(): { action_id: string; created_at: string; end_time: string; id?: string | null; is_success: boolean; resource_id?: string | null; result: {[key: string]: unknown; }; routine: string; start_time: string; } — Serialize without the authenticated client.\n\n### RoutineTemplate\nA routine shared as a template, which people activate as their own routine.\nFields: author, record, routine\n- `RoutineTemplate.activate`: activate(options): Promise<Routine> — Create the caller's own routine from this template, with its references already filled in for them.\n- `RoutineTemplate.toJSON`: toJSON(): scheduled-action.RoutineTemplate — Serialize without the authenticated client.\n\nFunctions: `routineBody`\n\nTypes: `RoutineOptions`, `RoutineEventFilter`, `RoutineTriggerOptions`, `SingleRoutineTrigger`\n"
},
{
"name": "unfurls",
@@ -441,12 +441,15 @@
"EventFilter": "# Type Alias: EventFilter\n\n> **EventFilter** = \\{ `condition?`: `string` \\| `null`; `events`: `EventName`[]; `ids?`: `string`[] \\| `null`; \\}\n\nAn event name AND an entity ID must match within the same filter. A\ncondition further requires the event's content to answer it with yes.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-condition\"></a> `condition?` | `string` \\| `null` | Yes/no question about the triggering content, e.g. \"Is this email an invoice?\". The routine runs only when the answer is yes. |\n| <a id=\"property-events\"></a> `events` | `EventName`[] | - |\n| <a id=\"property-ids\"></a> `ids?` | `string`[] \\| `null` | - |",
"EventFilters": "# Type Alias: EventFilters\n\n> **EventFilters** = `EventFilter`[]\n\nBounded nonempty OR of filters, canonicalized to remove duplicates.",
"EventName": "# Type Alias: EventName\n\n> **EventName** = `\"document.created\"` \\| `\"document.updated\"` \\| `\"document.deleted\"` \\| `\"task.created\"` \\| `\"task.status_changed\"` \\| `\"task.priority_changed\"` \\| `\"task.property_changed\"` \\| `\"email.message_received\"` \\| `\"channel.created\"` \\| `\"channel.message_posted\"` \\| `\"channel.mentioned\"` \\| `\"channel.message_patched\"` \\| `\"channel.message_attachment_created\"` \\| `\"call.started\"` \\| `\"call.ended\"`\n\nClosed allowlist: unknown names, deletions and ambiguous attribution are not\nselectors. Adding a broker variant does not automatically enable routines.",
+ "scheduled-action.RoutineTemplate": "# Type Alias: RoutineTemplate\n\n> **RoutineTemplate** = \\{ `active_count`: `number`; `author`: `string`; `created_at`: `string`; `description`: `string`; `id`: `string`; `name`: `string`; `task`: \\{\\[`key`: `string`\\]: `unknown`; \\}; `trigger`: `ActionTrigger`; `updated_at`: `string`; `variables`: `TemplateVariable`[]; \\}\n\nA shared routine's snapshot, readable by any signed-in user with its ID.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-active_count\"></a> `active_count` | `number` | Routines activated from this template, including stopped ones. |\n| <a id=\"property-author\"></a> `author` | `string` | Who shared it: the source routine's owner. |\n| <a id=\"property-created_at\"></a> `created_at` | `string` | - |\n| <a id=\"property-description\"></a> `description` | `string` | - |\n| <a id=\"property-id\"></a> `id` | `string` | The routine it was shared from. |\n| <a id=\"property-name\"></a> `name` | `string` | - |\n| <a id=\"property-task\"></a> `task` | \\{\\[`key`: `string`\\]: `unknown`; \\} | - |\n| <a id=\"property-trigger\"></a> `trigger` | `ActionTrigger` | - |\n| <a id=\"property-updated_at\"></a> `updated_at` | `string` | - |\n| <a id=\"property-variables\"></a> `variables` | `TemplateVariable`[] | - |",
"RoutineTrigger": "# Type Alias: RoutineTrigger\n\n> **RoutineTrigger** = \\{ `schedule`: `Schedule`; `timezone`: `string`; `type`: `\"cron\"`; \\} \\| \\{ `filters`: `EventFilters`; `type`: `\"events\"`; \\}\n\nAn individual trigger in a routine's trigger list.",
"RoutineTriggers": "# Type Alias: RoutineTriggers\n\n> **RoutineTriggers** = `RoutineTrigger`[]\n\nBounded schedules and one combined set of event filters.",
"RunVisibility": "# Type Alias: RunVisibility\n\n> **RunVisibility** = `\"listed\"` \\| `\"unlisted\"`\n\nWhether a routine's runs are listed in Home and the Agents list. Routines\nthat run often would bury the owner's own work, so runs start unlisted;\neither way they stay in the routine's history. The string form is the\n`scheduled_action.run_visibility` column's.",
"Schedule": "# Type Alias: Schedule\n\n> **Schedule** = `string`",
- "ScheduledAction": "# Type Alias: ScheduledAction\n\n> **ScheduledAction** = \\{ `claimed?`: `string` \\| `null`; `configuration_revision`: `number`; `created_at`: `string`; `enabled`: `boolean`; `event_activated_at?`: `string` \\| `null`; `id?`: `string` \\| `null`; `kind`: `ActionKind`; `name`: `string`; `next_run_at?`: `string` \\| `null`; `owner`: `string`; `run_visibility`: `RunVisibility`; `task`: \\{\\[`key`: `string`\\]: `unknown`; \\}; `trigger`: `ActionTrigger`; `updated_at`: `string`; \\}\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-claimed\"></a> `claimed?` | `string` \\| `null` | - |\n| <a id=\"property-configuration_revision\"></a> `configuration_revision` | `number` | Independent of execution bookkeeping in `updated_at`. |\n| <a id=\"property-created_at\"></a> `created_at` | `string` | - |\n| <a id=\"property-enabled\"></a> `enabled` | `boolean` | When false, automatic dispatch skips this action. `run_now` remains available regardless. |\n| <a id=\"property-event_activated_at\"></a> `event_activated_at?` | `string` \\| `null` | Event publication boundary; absent for cron actions. |\n| <a id=\"property-id\"></a> `id?` | `string` \\| `null` | - |\n| <a id=\"property-kind\"></a> `kind` | `ActionKind` | - |\n| <a id=\"property-name\"></a> `name` | `string` | - |\n| <a id=\"property-next_run_at\"></a> `next_run_at?` | `string` \\| `null` | Next cron firing, absent for event-triggered actions. |\n| <a id=\"property-owner\"></a> `owner` | `string` | Who the action belongs to. Every action is user-owned today, but the type no longer says so: the principal string on the wire and in the `owner` column is the same, and a bot- or team-owned row decodes rather than failing to parse. |\n| <a id=\"property-run_visibility\"></a> `run_visibility` | `RunVisibility` | Whether the action's runs are listed in Home and the Agents list. |\n| <a id=\"property-task\"></a> `task` | \\{\\[`key`: `string`\\]: `unknown`; \\} | - |\n| <a id=\"property-trigger\"></a> `trigger` | `ActionTrigger` | - |\n| <a id=\"property-updated_at\"></a> `updated_at` | `string` | - |",
+ "ScheduledAction": "# Type Alias: ScheduledAction\n\n> **ScheduledAction** = \\{ `claimed?`: `string` \\| `null`; `configuration_revision`: `number`; `created_at`: `string`; `enabled`: `boolean`; `event_activated_at?`: `string` \\| `null`; `id?`: `string` \\| `null`; `kind`: `ActionKind`; `name`: `string`; `next_run_at?`: `string` \\| `null`; `owner`: `string`; `run_visibility`: `RunVisibility`; `task`: \\{\\[`key`: `string`\\]: `unknown`; \\}; `template_id?`: `string` \\| `null`; `trigger`: `ActionTrigger`; `updated_at`: `string`; \\}\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-claimed\"></a> `claimed?` | `string` \\| `null` | - |\n| <a id=\"property-configuration_revision\"></a> `configuration_revision` | `number` | Independent of execution bookkeeping in `updated_at`. |\n| <a id=\"property-created_at\"></a> `created_at` | `string` | - |\n| <a id=\"property-enabled\"></a> `enabled` | `boolean` | When false, automatic dispatch skips this action. `run_now` remains available regardless. |\n| <a id=\"property-event_activated_at\"></a> `event_activated_at?` | `string` \\| `null` | Event publication boundary; absent for cron actions. |\n| <a id=\"property-id\"></a> `id?` | `string` \\| `null` | - |\n| <a id=\"property-kind\"></a> `kind` | `ActionKind` | - |\n| <a id=\"property-name\"></a> `name` | `string` | - |\n| <a id=\"property-next_run_at\"></a> `next_run_at?` | `string` \\| `null` | Next cron firing, absent for event-triggered actions. |\n| <a id=\"property-owner\"></a> `owner` | `string` | Who the action belongs to. Every action is user-owned today, but the type no longer says so: the principal string on the wire and in the `owner` column is the same, and a bot- or team-owned row decodes rather than failing to parse. |\n| <a id=\"property-run_visibility\"></a> `run_visibility` | `RunVisibility` | Whether the action's runs are listed in Home and the Agents list. |\n| <a id=\"property-task\"></a> `task` | \\{\\[`key`: `string`\\]: `unknown`; \\} | - |\n| <a id=\"property-template_id\"></a> `template_id?` | `string` \\| `null` | The shared template this routine was activated from, if any. |\n| <a id=\"property-trigger\"></a> `trigger` | `ActionTrigger` | - |\n| <a id=\"property-updated_at\"></a> `updated_at` | `string` | - |",
"ScheduledActionResponse": "# Type Alias: ScheduledActionResponse\n\n> **ScheduledActionResponse** = `ScheduledAction` & \\{ `schedule?`: `string` \\| `null`; `timezone?`: `string` \\| `null`; \\}\n\nCanonical trigger plus deprecated cron fields for existing clients. Event\nresponses omit legacy fields rather than inventing a schedule or timezone.\n\n## Type Declaration\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `schedule?` | `string` \\| `null` | Deprecated: use `trigger.schedule`. Present only for cron actions. **Deprecated** |\n| `timezone?` | `string` \\| `null` | Deprecated: use `trigger.timezone`. Present only for cron actions. **Deprecated** |",
+ "TemplateVariable": "# Type Alias: TemplateVariable\n\n> **TemplateVariable** = \\{ `fill`: `VariableFill`; `id`: `string`; `kind`: `\"user\"`; `label`: `string`; \\} \\| \\{ `block_name`: `string`; `fill`: `VariableFill`; `id`: `string`; `kind`: `\"item\"`; `label`: `string`; \\} \\| \\{ `fill`: `VariableFill`; `kind`: `\"time_zone\"`; `timezone`: `string`; \\}\n\nA user-specific part of a shared routine.\n\n## Union Members\n\n### Type Literal\n\n\\{ `fill`: `VariableFill`; `id`: `string`; `kind`: `\"user\"`; `label`: `string`; \\}\n\n***\n\n### Type Literal\n\n\\{ `block_name`: `string`; `fill`: `VariableFill`; `id`: `string`; `kind`: `\"item\"`; `label`: `string`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `block_name` | `string` | The mention's block name, such as `channel` or `md`. |\n| `fill` | `VariableFill` | - |\n| `id` | `string` | - |\n| `kind` | `\"item\"` | - |\n| `label` | `string` | - |\n\n***\n\n### Type Literal\n\n\\{ `fill`: `VariableFill`; `kind`: `\"time_zone\"`; `timezone`: `string`; \\}",
+ "VariableFill": "# Type Alias: VariableFill\n\n> **VariableFill** = `\"activator\"` \\| `\"shared\"` \\| `\"choice\"`\n\nHow a variable is filled when someone activates the template.",
"AgentSessionFilters": "# Type Alias: AgentSessionFilters\n\n> **AgentSessionFilters** = \\{ `ids?`: `string`[]; `include?`: `boolean`; `owners?`: `string`[]; \\}\n\nFilters for agent sessions.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-ids\"></a> `ids?` | `string`[] | Agent session ids to filter by. Empty to include all accessible sessions. |\n| <a id=\"property-include\"></a> `include?` | `boolean` | Opt this query into agent sessions at all. Agent sessions are off by default — see [`crate::ast::agent_session::AgentSessionLiteral::Include`]. Asking for specific `ids` or `owners` also opts in. |\n| <a id=\"property-owners\"></a> `owners?` | `string`[] | Filter by session owner principal — a user ('macro\\|[email protected]'), a bot ('bot\\|<uuid>'), or a team (a bare hyphenated uuid). Empty to include every owner. |",
"CalendarEventFilters": "# Type Alias: CalendarEventFilters\n\n> **CalendarEventFilters** = \\{ `attendees?`: `string`[]; `calendar_event_ids?`: `string`[]; `ends_after?`: `string` \\| `null`; `organizers?`: `string`[]; `starts_before?`: `string` \\| `null`; `statuses?`: `string`[]; \\}\n\nFilters for canonical calendar-event entities.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-attendees\"></a> `attendees?` | `string`[] | Attendee email addresses. |\n| <a id=\"property-calendar_event_ids\"></a> `calendar_event_ids?` | `string`[] | Canonical event ids. |\n| <a id=\"property-ends_after\"></a> `ends_after?` | `string` \\| `null` | Include master events ending after this instant. |\n| <a id=\"property-organizers\"></a> `organizers?` | `string`[] | Organizer email addresses. |\n| <a id=\"property-starts_before\"></a> `starts_before?` | `string` \\| `null` | Include master events starting before this instant. |\n| <a id=\"property-statuses\"></a> `statuses?` | `string`[] | Event statuses such as `confirmed`, `tentative`, or `cancelled`. |",
"CallFilters": "# Type Alias: CallFilters\n\n> **CallFilters** = \\{ `attended?`: `boolean` \\| `null`; `call_ids?`: `string`[]; `channel_ids?`: `string`[]; `speaker_ids?`: `string`[]; `status?`: `null` \\| `search.CallStatus`; \\}\n\nFilters for call records.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-attended\"></a> `attended?` | `boolean` \\| `null` | Legacy filter by whether the requesting user attended the call. Prefer [`CallFilters::status`] for new callers. `None` = no filter, `Some(true)` = only calls the user joined, `Some(false)` = only calls the user did not join. |\n| <a id=\"property-call_ids\"></a> `call_ids?` | `string`[] | Call record IDs to filter by. Empty to include all calls. |\n| <a id=\"property-channel_ids\"></a> `channel_ids?` | `string`[] | Channel IDs to filter calls by. Empty to include all calls. |\n| <a id=\"property-speaker_ids\"></a> `speaker_ids?` | `string`[] | Speaker macro user ids. Empty to include all. |\n| <a id=\"property-status\"></a> `status?` | `null` \\| `search.CallStatus` | - |",
@@ -1770,17 +1773,24 @@
"RoutineNamespace.byId": "### byId()\n\n> **byId**(`id`): `Routine`\n\nConstruct a lazy routine handle.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `id` | `string` |\n\n#### Returns\n\n`Routine`",
"RoutineNamespace.create": "### create()\n\n> **create**(`options`): `Promise`\\<`Routine`\\>\n\nCreate an agent routine.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `options` | `RoutineOptions` |\n\n#### Returns\n\n`Promise`\\<`Routine`\\>",
"RoutineNamespace.list": "### list()\n\n> **list**(`options?`): `Promise`\\<`Routine`[]\\>\n\nList routines, optionally including event triggers.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `options?` | \\{ `includeEvents?`: `boolean`; \\} |\n| `options.includeEvents?` | `boolean` |\n\n#### Returns\n\n`Promise`\\<`Routine`[]\\>",
- "Routine": "# Class: Routine\n\nA scheduled or event-triggered agent task.\n\n## Extends\n\n- `MacroEntity`\\<`ScheduledActionResponse`\\>\n\n## Properties\n\n| Property | Modifier | Type | Description | Inherited from |\n| ------ | ------ | ------ | ------ | ------ |\n| <a id=\"property-enabled\"></a> `enabled` | `readonly` | () => `Promise`\\<`boolean`\\> | Whether the routine is enabled. | - |\n| <a id=\"property-id\"></a> `id` | `public readonly` | `string` | - | `MacroEntity.id` |\n| <a id=\"property-name\"></a> `name` | `readonly` | () => `Promise`\\<`string`\\> | Routine name. | - |\n| <a id=\"property-nextrunat\"></a> `nextRunAt` | `readonly` | () => `Promise`\\<`string` \\| `undefined`\\> | Next scheduled execution. | - |\n| <a id=\"property-owner\"></a> `owner` | `readonly` | () => `Promise`\\<`User`\\> | Routine owner. | - |\n| <a id=\"property-revision\"></a> `revision` | `readonly` | () => `Promise`\\<`number`\\> | Configuration revision. | - |\n| <a id=\"property-runvisibility\"></a> `runVisibility` | `readonly` | () => `Promise`\\<`RunVisibility`\\> | Whether the routine's runs appear in Home and the Agents list. | - |\n| <a id=\"property-trigger\"></a> `trigger` | `readonly` | () => `Promise`\\<`ActionTrigger`\\> | Configured triggers. | - |",
+ "Routine": "# Class: Routine\n\nA scheduled or event-triggered agent task.\n\n## Extends\n\n- `MacroEntity`\\<`ScheduledActionResponse`\\>\n\n## Properties\n\n| Property | Modifier | Type | Description | Inherited from |\n| ------ | ------ | ------ | ------ | ------ |\n| <a id=\"property-enabled\"></a> `enabled` | `readonly` | () => `Promise`\\<`boolean`\\> | Whether the routine is enabled. | - |\n| <a id=\"property-id\"></a> `id` | `public readonly` | `string` | - | `MacroEntity.id` |\n| <a id=\"property-name\"></a> `name` | `readonly` | () => `Promise`\\<`string`\\> | Routine name. | - |\n| <a id=\"property-nextrunat\"></a> `nextRunAt` | `readonly` | () => `Promise`\\<`string` \\| `undefined`\\> | Next scheduled execution. | - |\n| <a id=\"property-owner\"></a> `owner` | `readonly` | () => `Promise`\\<`User`\\> | Routine owner. | - |\n| <a id=\"property-revision\"></a> `revision` | `readonly` | () => `Promise`\\<`number`\\> | Configuration revision. | - |\n| <a id=\"property-runvisibility\"></a> `runVisibility` | `readonly` | () => `Promise`\\<`RunVisibility`\\> | Whether the routine's runs appear in Home and the Agents list. | - |\n| <a id=\"property-sourcetemplate\"></a> `sourceTemplate` | `readonly` | () => `Promise`\\<`Routine` \\| `undefined`\\> | The shared routine whose template this routine was activated from. | - |\n| <a id=\"property-trigger\"></a> `trigger` | `readonly` | () => `Promise`\\<`ActionTrigger`\\> | Configured triggers. | - |",
+ "Routine.activateTemplate": "### activateTemplate()\n\n> **activateTemplate**(`options`): `Promise`\\<`Routine`\\>\n\nCreate the caller's own routine from this routine's shared template, with\nits references already filled in for them.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `options` | `RoutineOptions` |\n\n#### Returns\n\n`Promise`\\<`Routine`\\>",
"Routine.delete": "### delete()\n\n> **delete**(): `Promise`\\<`void`\\>\n\nDelete the routine.\n\n#### Returns\n\n`Promise`\\<`void`\\>",
"Routine.execute": "### execute()\n\n> **execute**(): `Promise`\\<`AgentSession` \\| `Chat` \\| `undefined`\\>\n\nStart an execution immediately and return its transcript handle if available.\n\n#### Returns\n\n`Promise`\\<`AgentSession` \\| `Chat` \\| `undefined`\\>",
"Routine.history": "### history()\n\n> **history**(): `Promise`\\<`RoutineExecution`[]\\>\n\nCompleted executions, with their routine scoped identity.\n\n#### Returns\n\n`Promise`\\<`RoutineExecution`[]\\>",
"Routine.setEnabled": "### setEnabled()\n\n> **setEnabled**(`enabled`): `Promise`\\<`void`\\>\n\nEnable or disable triggering.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `enabled` | `boolean` |\n\n#### Returns\n\n`Promise`\\<`void`\\>",
+ "Routine.shareAsTemplate": "### shareAsTemplate()\n\n> **shareAsTemplate**(`options`): `Promise`\\<`RoutineTemplate`\\>\n\nShare this routine as a template, or update its shared snapshot. People\nget the template, never the routine, its runs or its results.\n\n#### Parameters\n\n| Parameter | Type | Description |\n| ------ | ------ | ------ |\n| `options` | \\{ `description`: `string`; `variables`: `TemplateVariable`[]; \\} | - |\n| `options.description` | `string` | What the routine does for someone. |\n| `options.variables` | `TemplateVariable`[] | How each user-specific reference fills in when someone activates it. |\n\n#### Returns\n\n`Promise`\\<`RoutineTemplate`\\>",
+ "Routine.stopSharingTemplate": "### stopSharingTemplate()\n\n> **stopSharingTemplate**(): `Promise`\\<`void`\\>\n\nStop sharing this routine. Routines already activated keep running.\n\n#### Returns\n\n`Promise`\\<`void`\\>",
+ "Routine.template": "### template()\n\n> **template**(): `Promise`\\<`RoutineTemplate` \\| `undefined`\\>\n\nThis routine's shared template, or `undefined` when it isn't shared.\n\n#### Returns\n\n`Promise`\\<`RoutineTemplate` \\| `undefined`\\>",
"Routine.toJSON": "### toJSON()\n\n> **toJSON**(): \\{ `detail?`: `ScheduledActionResponse`; `id`: `string`; \\}\n\n#### Returns\n\n\\{ `detail?`: `ScheduledActionResponse`; `id`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `detail?` | `ScheduledActionResponse` |\n| `id` | `string` |\n\n#### Inherited from\n\n`MacroEntity.toJSON`",
"Routine.update": "### update()\n\n> **update**(`options`): `Promise`\\<`void`\\>\n\nReplace the routine's task and trigger configuration.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `options` | `RoutineOptions` |\n\n#### Returns\n\n`Promise`\\<`void`\\>",
"Routine.byId": "### byId()\n\n> `static` **byId**(`client`, `id`): `Routine`\n\nConstruct a lazy routine handle.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `id` | `string` |\n\n#### Returns\n\n`Routine`",
"Routine.from": "### from()\n\n> `static` **from**(`client`, `record`): `Routine`\n\nSeed a handle from a server record.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `record` | `ScheduledActionResponse` |\n\n#### Returns\n\n`Routine`",
"RoutineExecution": "# Class: RoutineExecution\n\nA completed routine execution, as recorded by the service.\n\n## Properties\n\n| Property | Modifier | Type | Description |\n| ------ | ------ | ------ | ------ |\n| <a id=\"property-record\"></a> `record` | `readonly` | `ActionExecutionRecord` | Execution snapshot. |\n| <a id=\"property-routine\"></a> `routine` | `readonly` | `Routine` | Parent routine. |\n\n## Accessors\n\n### id\n\n#### Get Signature\n\n> **get** **id**(): `string` \\| `undefined`\n\nExecution identity, when assigned.\n\n##### Returns\n\n`string` \\| `undefined`",
"RoutineExecution.toJSON": "### toJSON()\n\n> **toJSON**(): \\{ `action_id`: `string`; `created_at`: `string`; `end_time`: `string`; `id?`: `string` \\| `null`; `is_success`: `boolean`; `resource_id?`: `string` \\| `null`; `result`: \\{\\[`key`: `string`\\]: `unknown`; \\}; `routine`: `string`; `start_time`: `string`; \\}\n\nSerialize without the authenticated client.\n\n#### Returns\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `action_id` | `string` | - |\n| `created_at` | `string` | - |\n| `end_time` | `string` | - |\n| `id?` | `string` \\| `null` | - |\n| `is_success` | `boolean` | - |\n| `resource_id?` | `string` \\| `null` | ID of the primary resource produced by this run. Its type is recorded in `result`, independently of the routine's current configuration. |\n| `result` | \\{\\[`key`: `string`\\]: `unknown`; \\} | - |\n| `routine` | `string` | - |\n| `start_time` | `string` | - |",
+ "RoutineTemplate": "# Class: RoutineTemplate\n\nA routine shared as a template, which people activate as their own routine.\n\n## Properties\n\n| Property | Modifier | Type | Description |\n| ------ | ------ | ------ | ------ |\n| <a id=\"property-author\"></a> `author` | `readonly` | `User` | Who shared it. |\n| <a id=\"property-record\"></a> `record` | `readonly` | `scheduled-action.RoutineTemplate` | Template snapshot. |\n| <a id=\"property-routine\"></a> `routine` | `readonly` | `Routine` | The shared routine. |",
+ "RoutineTemplate.activate": "### activate()\n\n> **activate**(`options`): `Promise`\\<`Routine`\\>\n\nCreate the caller's own routine from this template, with its references\nalready filled in for them.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `options` | `RoutineOptions` |\n\n#### Returns\n\n`Promise`\\<`Routine`\\>",
+ "RoutineTemplate.toJSON": "### toJSON()\n\n> **toJSON**(): `scheduled-action.RoutineTemplate`\n\nSerialize without the authenticated client.\n\n#### Returns\n\n`scheduled-action.RoutineTemplate`",
"routineBody": "# Function: routineBody()\n\n> **routineBody**(`options`): \\{ `enabled`: `boolean` \\| `undefined`; `kind`: `\"Agent\"`; `name`: `string`; `run_visibility`: `RunVisibility` \\| `undefined`; `task`: \\{ `agent?`: `AgentTaskAgent` \\| `null`; `mcp_servers?`: `scheduled-action.AgentMcpServer`[]; `model?`: `string` \\| `null`; `prompt`: `string`; `user_prompt`: `string`; \\}; `trigger`: `ActionTrigger`; \\}\n\nTranslate typed routine options into the generated wire contract.\n\n## Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `options` | `RoutineOptions` |\n\n## Returns\n\n\\{ `enabled`: `boolean` \\| `undefined`; `kind`: `\"Agent\"`; `name`: `string`; `run_visibility`: `RunVisibility` \\| `undefined`; `task`: \\{ `agent?`: `AgentTaskAgent` \\| `null`; `mcp_servers?`: `scheduled-action.AgentMcpServer`[]; `model?`: `string` \\| `null`; `prompt`: `string`; `user_prompt`: `string`; \\}; `trigger`: `ActionTrigger`; \\}\n\n| Name | Type | Default value | Description |\n| ------ | ------ | ------ | ------ |\n| `enabled` | `boolean` \\| `undefined` | `options.enabled` | - |\n| `kind` | `\"Agent\"` | - | - |\n| `name` | `string` | `options.name` | - |\n| `run_visibility` | `RunVisibility` \\| `undefined` | `options.runVisibility` | - |\n| `task` | \\{ `agent?`: `AgentTaskAgent` \\| `null`; `mcp_servers?`: `scheduled-action.AgentMcpServer`[]; `model?`: `string` \\| `null`; `prompt`: `string`; `user_prompt`: `string`; \\} | - | - |\n| `task.agent?` | `AgentTaskAgent` \\| `null` | - | - |\n| `task.mcp_servers?` | `scheduled-action.AgentMcpServer`[] | - | Apps the routine requires on top of the agent's own. The owner must have each one connected to save the routine and for it to run. |\n| `task.model?` | `string` \\| `null` | - | - |\n| `task.prompt` | `string` | - | - |\n| `task.user_prompt` | `string` | - | - |\n| `trigger` | `ActionTrigger` | - | - |",
"RoutineOptions": "# Interface: RoutineOptions\n\nConfiguration of an agent routine.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-agent\"></a> `agent?` | `Agent` | Agent to run the task. |\n| <a id=\"property-enabled\"></a> `enabled?` | `boolean` | Whether triggers can start executions. Defaults to true on creation. |\n| <a id=\"property-model\"></a> `model?` | `string` | Model override. |\n| <a id=\"property-name\"></a> `name` | `string` | Display name. |\n| <a id=\"property-prompt\"></a> `prompt` | `string` | Instructions delivered to the agent. |\n| <a id=\"property-runvisibility\"></a> `runVisibility?` | `RunVisibility` | Whether runs appear in Home and the Agents list. Defaults to `unlisted` on creation; an update that omits it keeps the stored value. |\n| <a id=\"property-trigger\"></a> `trigger` | `RoutineTriggerOptions` | Schedules or Macro events that start the routine. |\n| <a id=\"property-userprompt\"></a> `userPrompt` | `string` | Original user instructions. |",
"RoutineEventFilter": "# Type Alias: RoutineEventFilter\n\n> **RoutineEventFilter** = `Omit`\\<`EventFilter`, `\"ids\"` \\| `\"condition\"`\\> & \\{ `condition?`: `string`; `entities?`: `EntityReference`[]; \\}\n\nAn event selector references resources by typed handles.\n\n## Type Declaration\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `condition?` | `string` | Optional yes/no condition on the triggering content. |\n| `entities?` | `EntityReference`[] | Resource selectors for these events. Omit to match all resources. |",
diff --git a/crates/agent_code_mode/src/domain/operations.json b/crates/agent_code_mode/src/domain/operations.json
index 4b2f69da6d..813c59439e 100644
--- a/crates/agent_code_mode/src/domain/operations.json
+++ b/crates/agent_code_mode/src/domain/operations.json
@@ -335,6 +335,10 @@
"scheduled-action.setScheduledActionEnabled": "Set Scheduled Action Enabled",
"scheduled-action.executeScheduledActionNow": "Execute Scheduled Action Now",
"scheduled-action.listScheduledActionHistory": "List Scheduled Action History",
+ "scheduled-action.unshareScheduledActionTemplate": "Unshare Scheduled Action Template",
+ "scheduled-action.getScheduledActionTemplate": "Get Scheduled Action Template",
+ "scheduled-action.shareScheduledActionTemplate": "Share Scheduled Action Template",
+ "scheduled-action.activateScheduledActionTemplate": "Activate Scheduled Action Template",
"unfurl.proxyRequestHandler": "Proxy Request",
"unfurl.getUnfurl": "Get Unfurl",
"unfurl.getUnfurlBulk": "Get Unfurl Bulk",
diff --git a/crates/code_execution/src/outbound/deno/sdk.mjs b/crates/code_execution/src/outbound/deno/sdk.mjs
index 9e083116a2..4704724c4e 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,G=async()=>{while(S<$.length){let X=S;S+=1,x[X]=await j($[X])}},Z=Array.from({length:Math.min(O,$.length)},G);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)}class f extends Error{constructor($){super($);this.name="MacroError"}}class QO extends f{status;data;constructor($,O){super(`Macro API error ${$}`);this.status=$;this.data=O;this.name="MacroApiError"}}class E extends f{constructor($){super($);this.name="MacroNotFoundError"}}function Y($){if($.error!==void 0)throw new QO($.response?.status??0,$.error);return $.data}class 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 I$ 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 X$ extends I${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 b6={"<":"\\u003c",">":"\\u003e","&":"\\u0026"};function a$($,O){let j=JSON.stringify(O).replace(/[<>&]/g,(x)=>b6[x]??x);return`<${$}>${j}</${$}>`}function k6($){return typeof $==="object"&&$!==null&&typeof $.toMention==="function"}var g6={toMention:()=>({tag:a$("m-group-mention",{groupAlias:"here"}),mention:{entity_type:"group",entity_id:"here"}})};function y6($,...O){let j="",x=[];for(let[S,G]of $.entries()){j+=G;let Z=O[S];if(Z===void 0)continue;if(k6(Z)){let X=Z.toMention();j+=X.tag,x.push(X.mention)}else j+=String(Z)}return{content:j,mentions:v6(x)}}function v6($){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:y0($)}))}}function y0($){let{channels:O,team:j,host:x,autoAcceptPermissions:S,avatarUrl:G,channelScope:Z,defaultModel:X,isCoding:K,...L}=$;return{...L,channel_ids:O?.map((Q)=>Q.id),team_id:j?.id,harness_id:x?.id,auto_accept_permissions:S,avatar_url:G,channel_scope:Z,default_model:X,is_coding:K}}async function Bj($,O,j){let{channelId:x,thread:S}=h6(O);if(await m6($)){let{id:Z}=Y(await $.storage.entityMessageCreate({path:{parent_type:"channel",parent_id:x},body:{content:j.content,mentions:j.mentions,attachments:[],thread_id:S?.rootId??null,nonce:crypto.randomUUID()}}));return Z}if(S)throw new f("a user-owned bot can only post via the channel webhook endpoint, which "+"does not support threads — use a team-owned bot, or requestedAs(user), "+"to reply in a thread");let{message_id:G}=Y(await $.storage.postChannelBotWebhook({path:{channel_id:x},body:{content:j.content},headers:{"x-macro-bot-scope":"user"}}));return G}function h6($){return"rootId"in $?{channelId:$.channelId,thread:$}:{channelId:$.id}}async function m6($){if($.authConfig.type!=="bot"||$.hasActingUser())return!0;let{owner:O}=await $.selfBot();return O?.type==="team"}class h${client;channelId;rootId;constructor($,O,j){this.client=$;this.channelId=O;this.rootId=j}toJSON(){return{channelId:this.channelId,rootId:this.rootId}}channel(){return b.byId(this.client,this.channelId)}root(){return e.byId(this.client,this.channelId,this.rootId)}async replies(){let{replies:$}=Y(await this.client.storage.entityMessageGetThread({path:{parent_type:"channel",parent_id:this.channelId,id:this.rootId}}));return $.map((O)=>e.from(this.client,this.channelId,O))}async reply($){let O=await Bj(this.client,this,O$($));return e.byId(this.client,this.channelId,O)}}class e extends I${channelId;mentions;entityType="channel_message";constructor($,O,j,x=[],S){super($,j,S);this.channelId=O;this.mentions=x}get path(){return{parent_type:"channel",parent_id:this.channelId,id:this.id}}async fetch(){return Y(await this.client.storage.entityMessageGetMessage({path:this.path}))}static byId($,O,j,x=[]){return new e($,O,j,x)}static from($,O,j){return new e($,O,j.id,j.mentions,j)}content=this.field("content");createdAt=this.field("created_at");editedAt=this.field("edited_at");updatedAt=this.field("updated_at");async author(){return P.byId(this.client,(await this.detail.get()).sender_id)}channel(){return b.byId(this.client,this.channelId)}thread(){return new h$(this.client,this.channelId,this.id)}async react($){return await this.mutate((O)=>O.storage.entityMessageReact({path:this.path,body:{add:!0,emoji:$}})),this}async unreact($){return await this.mutate((O)=>O.storage.entityMessageReact({path:this.path,body:{add:!1,emoji:$}})),this}async edit($){let{content:O,mentions:j}=O$($);return await this.mutate((x)=>x.storage.entityMessageEdit({path:this.path,body:{content:O,mentions:j}})),this}async delete(){await this.mutate(($)=>$.storage.entityMessageDeleteMessage({path:this.path}))}async reply($){return this.thread().reply($)}}class Lj{client;channel;record;constructor($,O,j){this.client=$;this.channel=O;this.record=j}agent(){return T$.byId(this.client,this.record.botId)}sessions(){return this.record.sessions.map(($)=>({session:l.byId(this.client,$.sessionId),isCurrent:$.isCurrent,createdAt:$.createdAt}))}turns(){return this.record.turns.map(($)=>new v0(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 v0{client;conversation;record;constructor($,O,j){this.client=$;this.conversation=O;this.record=j}source(){return e.byId(this.client,this.conversation.channel.id,this.record.sourceMessageId)}session(){return l.byId(this.client,this.record.sessionId)}async retry($){Y(await this.client.agentHarness.retryAgentConversationTurn({path:{channel_id:this.conversation.channel.id,bot_id:this.conversation.agent().id,source:this.record.sourceMessageId},body:{actionId:$}}))}toJSON(){return{channelId:this.conversation.channel.id,sourceMessageId:this.record.sourceMessageId}}}class 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 w$($,O,j,x){for(let G of[...x?.messages??[],...x?.around?[x.around]:[]]){let Z="channelId"in G?{type:"channel",id:G.channelId}:("documentId"in G)?{type:"document",id:G.documentId}:("callId"in G)?{type:"call",id:G.callId}:G.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((G)=>G.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((G)=>{if(G.type==="activity")return{type:"activity",activity:{...G.activity,actor:P.byId($,G.activity.actor_id)}};return{type:"message",message:j(G.message)}}),nextCursor:S.next_cursor??void 0,previousCursor:S.previous_cursor??void 0}}var u6=50;function x$($){let{filters:O,type:j,make:x,includeCrm:S}=$;return(G,Z,X)=>{let K=X?.searchOn??"name_content",L=X?.pageSize??u6;return c(async(Q)=>{let{results:J,next_cursor:I}=Y(await G.search.unifiedSearch({body:{query:Z,match_type:"partial",search_on:K,...O?{filters:O}:{},...S?{include_crm:!0}:{}},query:{page_size:L,...Q?{cursor:Q}:{}}}));return{items:J.filter((W)=>W.type===j).map((W)=>x(G,W)),nextCursor:I}})}}class JO{client;channel;record;constructor($,O,j){this.client=$;this.channel=O;this.record=j}get id(){return this.record.id}user(){return P.byId(this.client,this.record.user_id)}createdAt(){return this.record.created_at}async recordInteraction($){return new JO(this.client,this.channel,Y(await this.client.storage.postActivity({body:{activity_type:$,channel_id:this.channel.id}})))}toJSON(){return this.record}}class b extends X${async recordActivity($){return new JO(this.client,this,Y(await this.client.storage.postActivity({body:{activity_type:$,channel_id:this.id}})))}async setPicture($){await this.mutate((O)=>O.storage.setChannelPicture({path:{channel_id:this.id},body:{profile_picture_id:$?.id??null}}))}messageThreadById($){return L$.byId(this.client,{type:"channel",entity:this},$)}timelinePage($){return w$(this.client,{type:"channel",entity:this},(O)=>e.from(this.client,this.id,O),$)}async agentConversations(){return Y(await this.client.agentHarness.listAgentConversations({path:{channel_id:this.id}})).conversations.map(($)=>new Lj(this.client,this,$))}entityType="channel";propertyEntityType="CHANNEL";async fetch(){return Y(await this.client.storage.getChannel({path:{channel_id:this.id}}))}static byId($,O){return new b($,O)}static async dm($,O){let{channel_id:j}=Y(await $.storage.getOrCreateDm({body:{recipient_id:O.id}}));return new b($,j)}static async private($,O){let{channel_id:j}=Y(await $.storage.getOrCreatePrivate({body:{recipients:O.map((x)=>x.id)}}));return new b($,j)}static async create($,O){let{id:j}=Y(await $.storage.createChannel({body:{channel_type:O.type,name:O.name??null,participants:(O.participants??[]).map((x)=>x.id),team_id:O.team?.id??null}}));return new b($,j)}name=this.field("channel_name");type=this.field("channel_type");async send($,O){let j=await Bj(this.client,O?.thread??this,O$($));return e.byId(this.client,this.id,j)}messages($){return this.timeline({limit:$?.pageSize})}messagesAfter($,O){return this.timeline({activity_after:$ instanceof Date?$.toISOString():$,limit:O?.pageSize})}timeline($){return c(async(O)=>{let j=Y(await this.client.storage.messageTimeline({path:{parent_type:"channel",parent_id:this.id},query:{selection:JSON.stringify({...$,cursor:O})}}));return{items:j.items.map((x)=>e.from(this.client,this.id,x)),nextCursor:j.next_cursor}})}message($){return e.byId(this.client,this.id,$)}async rename($){await this.mutate((O)=>O.storage.patchChannel({path:{channel_id:this.id},body:{channel_name:$}}))}async delete(){await this.mutate(($)=>$.storage.deleteChannel({path:{channel_id:this.id}}))}async join(){await this.mutate(($)=>$.storage.joinChannel({path:{channel_id:this.id}}))}async joinCode(){let{join_code:$}=Y(await this.client.storage.getChannelJoinLink({path:{channel_id:this.id}}));return $}async leave(){await this.mutate(($)=>$.storage.leaveChannel({path:{channel_id:this.id}}))}async participants(){return Y(await this.client.storage.getChannelParticipants({path:{channel_id:this.id}}))}async addParticipants($){await this.mutate((O)=>O.storage.addParticipants({path:{channel_id:this.id},body:{participants:$.map((j)=>j.id)}}))}async removeParticipants($){await this.mutate((O)=>O.storage.removeParticipants({path:{channel_id:this.id},body:{participants:$.map((j)=>j.id)}}))}async typing($,O){Y(await this.client.storage.entityMessageTyping({path:{parent_type:"channel",parent_id:this.id},body:{active:$==="start",thread_id:O?.thread?.rootId??null}}))}attachments($){return c(async(O)=>{let j=Y(await this.client.storage.getChannelAttachments({path:{channel_id:this.id},query:{...$?.pageSize?{limit:$.pageSize}:{},...$?.type?{attachment_type:$.type}:{},...O?{cursor:O}:{}}}));return{items:j.items,nextCursor:j.next_cursor}})}webUrl(){return`${this.client.webAppUrl}/app/channel/${this.id}`}static search=x$({type:"channel",make:($,O)=>new b($,O.channel_id)})}class P extends X${entityType="user";propertyEntityType="USER";async fetch(){let{names:$}=Y(await this.client.auth.getUserNamesWithEmail({body:{user_ids:[this.id]}})),O=$.find((j)=>j.id===this.id);if(!O)throw new E(`user ${this.id} not found`);return O}static byId($,O){return new P($,O)}static fromName($,O){return new P($,O.id,O)}static async me($){let{user_id:O}=Y(await $.auth.getUserInfo());return new P($,O)}async name(){let $=await this.detail.get();return[$.first_name,$.last_name].filter(Boolean).join(" ")||void 0}email(){let $=this.id.startsWith("macro|")?this.id.slice(6):void 0;return $?.includes("@")?$:void 0}dm(){return b.dm(this.client,this)}toMention(){return{tag:a$("m-user-mention",{userId:this.id}),mention:{entity_type:"user",entity_id:this.id}}}}class o{client;entityType;entity;constructor($,O,j){this.client=$;this.entityType=O;this.entity=j}get path(){return{entity_type:this.entityType,entity_id:this.entity.id}}async state($){let O=Y(await this.client.storage.accessRequestsState({path:this.path,query:{offset:$}}));return{accessLevel:O.accessLevel??void 0,canReview:O.canReview,owner:O.owner?P.byId(this.client,O.owner):void 0,pendingCount:O.pendingCount,supportedLevels:O.supportedLevels,nextOffset:O.nextOffset??void 0,mine:O.mine?TO.from(this.client,this,O.mine):void 0,requests:O.requests.map((j)=>TO.from(this.client,this,j))}}async submit($,O){return TO.from(this.client,this,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:P.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 TO extends A{access;resolvedRecord;constructor($,O,j){super($,j.id,j);this.access=O}static from($,O,j){return new TO($,O,j)}async fetch(){if(this.resolvedRecord)return this.resolvedRecord;let $;do{let O=await this.access.state($),j=[O.mine,...O.requests].find((x)=>x?.id===this.id);if(j)return j.detail.get();$=O.nextOffset}while($!==void 0);throw new E(`Access request ${this.id} is unavailable`)}revision=this.field("revision");status=this.field("status");requestedLevel=this.field("requestedLevel");requester=this.mappedField("requesterId",($)=>P.byId(this.client,$));async resolve($){this.resolvedRecord=await this.access.resolve(this,{revision:await this.revision(),grantedLevel:$}),this.detail.clear()}}function i$($){return{...$,channelSharePermissions:$.channelSharePermissions===void 0||$.channelSharePermissions===null?$.channelSharePermissions:$.channelSharePermissions.map((O)=>({channelId:O.channel.id,accessLevel:O.accessLevel,operation:O.operation}))}}class N$ extends 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,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(),x))}async fetch(){return Y(await this.client.agentHarness.getSessionReview({path:{session_id:this.parent.id,review_id:this.id}}))}title=this.field("title");kind=this.field("kind");session(){return this.parent}async reference(){return{kind:await this.kind(),id:this.id}}async items(){return(await this.detail.get()).items.map(($)=>new h0($,{edit:(O)=>this.decide({action:"edit",item:$.id,draft:O}),submit:()=>this.decide({action:"submit",items:[$.id]}),dismiss:()=>this.decide({action:"dismiss",items:[$.id]})}))}async refresh(){return this.detail.clear(),await this.detail.get(),this}async submitAll(){await this.decide({action:"submit",items:[]})}async dismissAll(){await this.decide({action:"dismiss",items:[]})}async decide($){let O=(await this.detail.get()).revision;await this.mutate((j)=>j.agentHarness.decideSessionReview({path:{session_id:this.parent.id,review_id:this.id},body:{...$,revision:O}}))}}class h0{snapshot;actions;constructor($,O){this.snapshot=$;this.actions=O}get id(){return this.snapshot.id}get status(){return this.snapshot.status}get draft(){return this.snapshot.draft}get result(){return this.snapshot.result}async edit($){await this.actions.edit($)}async submit(){await this.actions.submit()}async dismiss(){await this.actions.dismiss()}}class dO extends A{parent;constructor($,O,j){super($,O);this.parent=j}static byId($,O,j){return new dO($,j,O)}async fetch(){return Y(await this.client.agentHarness.getCodeExecution({path:{session_id:this.parent.id,execution_id:this.id}}))}reviews={create:($)=>N$.create(this.client,this,$),list:()=>N$.list(this.client,this)};session(){return this.parent}status=this.field("status");source=this.field("source");calls=this.field("calls");error=this.field("error");async result(){return(await this.detail.get()).result}async refresh(){return this.detail.clear(),await this.detail.get(),this}}class Nj{client;sessionId;dto;constructor($,O,j){this.client=$;this.sessionId=O;this.dto=j}static from($,O,j){return new Nj($,O,j)}get actionId(){return this.dto.actionId}get kind(){return this.dto.kind}get prompt(){return this.dto.prompt??void 0}get attachments(){return this.dto.attachments??[]}get actorUserId(){return this.dto.actorUserId??void 0}get createdAt(){return this.dto.createdAt}async edit($){return Y(await this.client.agentHarness.editQueuedAction({path:{session_id:this.sessionId,action_id:this.actionId},body:{prompt:$}})),this.dto={...this.dto,prompt:$},this}async steer(){Y(await this.client.agentHarness.steerQueuedAction({path:{session_id:this.sessionId,action_id:this.actionId}}))}async remove(){Y(await this.client.agentHarness.removeQueuedAction({path:{session_id:this.sessionId,action_id:this.actionId}}))}}class lO{client;session;id;constructor($,O,j){this.client=$;this.session=O;this.id=j}static byId($,O,j){return new lO($,O,j)}async answer($){return Y(await this.client.agentHarness.answerAgentSessionToolApproval({path:{session_id:this.session.id,approval_id:this.id},body:{answer:$}}))}toJSON(){return{id:this.id,sessionId:this.session.id}}}class l extends A{access=new o(this.client,"agent_session",this);toolApprovalById($){return lO.byId(this.client,this,$)}async sharePermissions(){return Y(await this.client.agentHarness.getAgentSessionPermissions({path:{session_id:this.id}}))}async updateSharePermissions($){return this.mutate((O)=>O.agentHarness.updateAgentSessionPermissions({path:{session_id:this.id},body:i$($)}))}static byId($,O){return new l($,O)}static async createManaged($,O){let{session:j}=Y(await $.agentHarness.createAgentSession({body:{prompt:O?.prompt,instructions:O?.instructions,model:O?.model,repoUrl:O?.repoUrl,repoBranch:O?.repoBranch}}));return new l($,j.id,j)}static async repositories($){let{repositories:O}=Y(await $.agentHarness.listAgentRepositories());return O.map((j)=>({url:j.url,defaultBranch:j.defaultBranch??void 0}))}static async repositoryBranches($,O){let{branches:j}=Y(await $.agentHarness.listAgentRepositoryBranches({query:{repoUrl:O}}));return j}static async chooseMode($,O){let{mode:j}=Y(await $.agentHarness.chooseAgentMode({body:{prompt:O}}));return j}async fetch(){return Y(await this.client.agentHarness.getAgentSession({path:{session_id:this.id}}))}name=this.field("name");isArchived=this.field("isArchived");model=this.field("model");harness=this.field("harness");repoUrl=this.field("repoUrl");workspace=this.field("workspace");instructions=this.field("instructions");status=this.field("status");sandboxSize=this.field("sandboxSize");createdAt=this.field("createdAt");modifiedAt=this.field("modifiedAt");static async forPullRequest($,O){let{sessionIds:j}=Y(await $.agentHarness.agentSessionsForPullRequest({body:{url:O}}));return j.map((x)=>l.byId($,x))}async pullRequests(){let{pullRequests:$}=Y(await this.client.agentHarness.listAgentSessionPullRequests({path:{session_id:this.id}}));return $.map((O)=>({githubKey:O.githubKey,url:O.url,source:O.source,linkedBy:O.linkedBy?P.byId(this.client,O.linkedBy):void 0,createdAt:O.createdAt}))}async linkPullRequest($){Y(await this.client.agentHarness.linkAgentSessionPullRequest({path:{session_id:this.id},body:{url:$}}))}async unlinkPullRequest($){Y(await this.client.agentHarness.unlinkAgentSessionPullRequest({path:{session_id:this.id},query:{url:$}}))}async rename($){await this.mutate((O)=>O.agentHarness.renameAgentSession({path:{session_id:this.id},body:{name:$}}))}async archive(){await this.setArchived(!0)}async unarchive(){await this.setArchived(!1)}async setArchived($){await this.mutate((O)=>O.agentHarness.setAgentSessionArchived({path:{session_id:this.id},body:{isArchived:$}}))}async setSandboxSize($){let{size:O}=await this.mutate((j)=>j.agentHarness.putAgentSessionSandboxSize({path:{session_id:this.id},body:{size:$}}));return O}static async defaultSandboxSize($){return Y(await $.agentHarness.getAgentSandboxSize()).size}static async setDefaultSandboxSize($,O){return Y(await $.agentHarness.putAgentSandboxSize({body:{size:O}})).size}static async codingPreferences($){return Y(await $.agentHarness.getAgentCodingPreferences())}static async setCodingPreferences($,O){return Y(await $.agentHarness.putAgentCodingPreferences({body:O}))}async control($){return this.mutate((O)=>O.agentHarness.controlAgentSession({path:{session_id:this.id},body:$}))}prompt($,O){return this.control({type:"prompt",prompt:$,...O&&O.length>0?{attachments:O}:{}})}async queue(){let{entries:$}=Y(await this.client.agentHarness.getAgentSessionQueue({path:{session_id:this.id}}));return $.map((O)=>Nj.from(this.client,this.id,O))}async changes(){return Y(await this.client.agentHarness.getAgentSessionChanges({path:{session_id:this.id}}))}async changesPatch(){return Y(await this.client.agentHarness.getAgentSessionChangesPatch({path:{session_id:this.id}})).patch}async refreshChanges(){return this.mutate(($)=>$.agentHarness.refreshAgentSessionChanges({path:{session_id:this.id}}))}async foldedLog(){let{bot:$,messages:O}=Y(await this.client.agentHarness.getAgentSessionFoldedLog({path:{session_id:this.id}}));return{bot:$,messages:O}}async log(){return Y(await this.client.agentHarness.getAgentSessionLog({path:{session_id:this.id}}))}reviews={create:($)=>N$.createForSession(this.client,this,$),byId:($)=>N$.byId(this.client,this,$)};codeExecutions={byId:($)=>dO.byId(this.client,this,$)};async delete(){await this.mutate(($)=>$.agentHarness.deleteAgentSession({path:{session_id:this.id}}))}}class m0{client;constructor($){this.client=$}byId($){return l.byId(this.client,$)}createManaged($){return l.createManaged(this.client,$)}chooseMode($){return l.chooseMode(this.client,$)}repositories(){return l.repositories(this.client)}repositoryBranches($){return l.repositoryBranches(this.client,$)}forPullRequest($){return l.forPullRequest(this.client,$)}defaultSandboxSize(){return l.defaultSandboxSize(this.client)}setDefaultSandboxSize($){return l.setDefaultSandboxSize(this.client,$)}codingPreferences(){return l.codingPreferences(this.client)}setCodingPreferences($){return l.setCodingPreferences(this.client,$)}}class u0{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:y0($)})))}}class c0{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 n$ extends A{static byId($,O){return new n$($,O)}static from($,O){return new n$($,O.id,{id:O.id,name:O.name,createdAt:O.createdAt})}async fetch(){let $=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 d0{client;constructor($){this.client=$}byId($){return n$.byId(this.client,$)}async list(){return Y(await this.client.storage.listUserApiKeys()).keys.map(($)=>n$.from(this.client,$))}async create($){let O=Y(await this.client.storage.createUserApiKey({body:{name:$}}));return{key:n$.from(this.client,O),secret:O.key}}async tokenForEmail($){return Y(await this.client.auth.macroApiToken({query:{email:$}}))}}class rO{client;constructor($){this.client=$}async me(){if(this.client.authConfig.type!=="bot")throw new f("bots.me() requires bot auth — a user API key has no bot identity");return Y(await this.client.storage.getSelfBot())}async channels(){if(this.client.authConfig.type!=="bot")throw new f("bots.channels() requires bot auth — a user API key has no bot identity");let $=await this.me();return Y(await this.client.storage.listBotChannels({path:{bot_id:$.id}}))}async myPrincipalId(){if(this.client.authConfig.type!=="bot")throw new f("bots.myPrincipalId() requires bot auth — a user API key has no bot identity");return this.client.myPrincipalId()}}class S$ extends 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 S$($,O)}static async current($){let O=Y(await $.auth.getTeam());if(!O)throw new E("caller has no current team");return new S$($,O.team.id,O.team)}static async list($){return Y(await $.auth.getUserTeams()).map((j)=>new S$($,j.id,j))}name=this.field("name");slug=this.field("slug");defaultLinkShare=this.field("default_link_share");owner=this.mappedField("owner_id",($)=>P.byId(this.client,$));async members(){let $=Y(await this.client.auth.getTeam());if(!$||$.team.id!==this.id)throw new f("members are only available for the current team (see Team.current)");return $.members.map((O)=>({user:P.byId(this.client,O.user_id),role:O.role}))}}class H$ 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 H$($,O)}static async list($){let{links:O}=Y(await $.email.listLinks());return O.map((j)=>new H$($,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");isSubscription=this.field("isSubscription");color=this.field("color");syncError=this.field("syncError");emailLink=this.mappedField("emailLinkId",($)=>H$.byId(this.client,$))}class pO{client;id;constructor($,O){this.client=$;this.id=O}async status(){return Y(await this.client.calendar.calendarReplacementStatus({path:{operation_id:this.id}}))}async confirm(){return Y(await this.client.calendar.confirmCalendarReplacement({path:{operation_id:this.id}}))}async discard(){Y(await this.client.calendar.discardCalendarReplacement({path:{operation_id:this.id}}))}}class $$ extends A{async notes($){return this.requireOwnOccurrence($),Y(await this.client.calendar.eventNotes({path:{event_id:this.id},query:{occurrenceKey:$.occurrenceKey}})).map((j)=>q$.fromRecord(this.client,this,$,j))}async linkNote($,O,j={}){return this.requireOwnOccurrence(O),Y(await this.client.calendar.linkEventNote({path:{event_id:this.id,document_id:$.id},query:{occurrenceKey:O.occurrenceKey},body:{teamId:j.team?.id??null}})),q$.forDocument(this.client,this,O,$)}requireOwnOccurrence($){if($.eventId!==this.id)throw new f("The occurrence belongs to a different event")}async fetch(){throw new f(`calendar event ${this.id} has no fetch-by-id endpoint; read the record returned by calendar.createEvent / event.update / event.rsvp instead`)}static byId($,O){return new $$($,O)}static fromRecord($,O){return new $$($,O.id,O)}title=this.field("title");description=this.field("description");location=this.field("location");time=this.field("time");status=this.field("status");attendees=this.field("attendees");transparency=this.field("transparency");isReadOnly=this.field("isReadOnly");recurrenceLines=this.field("recurrenceLines");guestPolicy=this.field("guestPolicy");viewerCan=this.field("viewerCan");calendar=this.mappedField("calendarId",($)=>$?m$.byId(this.client,$):void 0);record(){return this.detail.get()}async update($){let O=await this.mutate((j)=>j.calendar.updateCalendarEvent({path:{event_id:this.id},body:c6($)}));return $$.fromRecord(this.client,O)}async delete($={}){await this.mutate((O)=>O.calendar.deleteCalendarEvent({path:{event_id:this.id},query:{calendarId:$.calendar?.id,scope:$.scope,recurrenceId:$.recurrenceId,inbox:$.inbox}}))}async prepareReplacement($){let O=Y(await this.client.calendar.prepareCalendarReplacement({path:{event_id:this.id},body:{removeConference:$.removeConference,recurrenceId:$.recurrenceId,calendarId:$.calendar?.id}}));return new pO(this.client,O.operationId)}async providerUrl($={}){return Y(await this.client.calendar.calendarEventProviderUrl({path:{event_id:this.id},query:{recurrenceId:$.recurrenceId,calendarId:$.calendar?.id}})).url??void 0}async inviteGuests($){let O=await this.mutate((j)=>j.calendar.inviteCalendarEventGuests({path:{event_id:this.id},body:{guests:$.guests,scope:$.scope,recurrenceId:$.recurrenceId,calendarId:$.calendar?.id,inbox:$.inbox}}));return $$.fromRecord(this.client,O)}async addToCalendar($={}){let O=await this.mutate((j)=>j.calendar.copyCalendarEvent({path:{event_id:this.id},body:{calendarId:$.calendar?.id}}));return $$.fromRecord(this.client,O)}async ics(){return Y(await this.client.storage.eventIcs({path:{event_id:this.id}}))}async rsvp($){let O=await this.mutate((j)=>j.calendar.rsvpCalendarEvent({path:{event_id:this.id},body:{response:$.response,scope:$.scope,recurrenceId:$.recurrenceId,calendarId:$.calendar?.id}}));return $$.fromRecord(this.client,O)}}function c6($){return{title:$.title,description:$.description,location:$.location,time:$.time,attendees:$.attendees,recurrenceLines:$.recurrenceLines,visibility:$.visibility,transparency:$.transparency,reminders:$.reminders,conference:$.conference,outOfOffice:$.outOfOffice,guestPolicy:$.guestPolicy,scope:$.scope,recurrenceId:$.recurrenceId,calendarId:$.calendar?.id,inbox:$.inbox}}class q$ extends A{event;occurrence;fromDocument;constructor($,O,j,x,S,G=!1){super($,x.id,S);this.event=O;this.occurrence=j;this.fromDocument=G;if(j.eventId!==O.id)throw new f("Choose an occurrence belonging to this event")}static fromDocumentLink($,O,j){return new q$($,$$.byId($,j.eventId),j,O,{documentId:O.id,name:j.documentName,team:j.team,canManage:!0},!0)}static forDocument($,O,j,x){return new q$($,O,j,x)}static fromRecord($,O,j,x){return new q$($,O,j,q.byId($,x.documentId),x)}async fetch(){if(this.fromDocument){let x=Y(await this.client.calendar.documentNoteLinks({path:{document_id:this.id}})).find((S)=>S.eventId===this.event.id&&S.occurrenceKey===this.occurrence.occurrenceKey);if(!x)throw new E("This meeting link has been removed");return{documentId:this.id,name:x.documentName,team:x.team,canManage:!0}}let O=Y(await this.client.calendar.eventNotes({path:{event_id:this.event.id},query:{occurrenceKey:this.occurrence.occurrenceKey}})).find((j)=>j.documentId===this.id);if(!O)throw new E("This document is no longer linked to the meeting");return O}document=this.mappedField("documentId",($)=>q.byId(this.client,$));name=this.field("name");team=this.mappedField("team",($)=>$?S$.byId(this.client,$.id):void 0);canManage=this.field("canManage");async setTeam($){await this.mutate((O)=>O.calendar.linkEventNote({path:{event_id:this.event.id,document_id:this.id},query:{occurrenceKey:this.occurrence.occurrenceKey},body:{teamId:$?.id??null}}))}async unlink(){await this.mutate(($)=>$.calendar.unlinkEventNote({path:{event_id:this.event.id,document_id:this.id},query:{occurrenceKey:this.occurrence.occurrenceKey}}))}}class n extends X${async sharePermissions(){return Y(await this.client.storage.getProjectPermissionsV2({path:{id:this.id}}))}async accessLevel(){return Y(await this.client.storage.getProjectUserAccessLevel({path:{id:this.id}}))}access=new o(this.client,"project",this);entityType="project";propertyEntityType="PROJECT";async fetch(){let{data:$}=Y(await this.client.storage.getProjectHandler({path:{id:this.id}}));return $.projectMetadata}static byId($,O){return new n($,O)}static async create($,O){let{data:j}=Y(await $.storage.createProjectHandler({body:{name:O.name,projectParentId:O.parent?.id??null}}));return new n($,j.id,j)}name=this.field("name");parent=this.mappedField("parentId",($)=>$?n.byId(this.client,$):void 0);createdAt=this.field("createdAt");async items(){let{data:$}=Y(await this.client.storage.getProjectContentHandler({path:{id:this.id}}));return $.map((O)=>O.item)}async rename($){await this.mutate((O)=>O.storage.editProjectV2({path:{id:this.id},body:{name:$}}))}async delete($){await this.mutate((O)=>$?.permanent?O.storage.permanentlyDeleteProject({path:{id:this.id}}):O.storage.deleteProjectHandler({path:{id:this.id}}))}async restore(){await this.mutate(($)=>$.storage.revertDeleteProject({path:{id:this.id}}))}static search=x$({filters:{project_filters:{}},type:"project",make:($,O)=>new n($,O.id)})}class VO extends 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 u$ 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 u$($,O,j)}static from($,O,j){return new u$($,O,j.id,j)}text=this.field("content");createdAt=this.field("created_at");updatedAt=this.field("updated_at");async threadId(){return(await this.detail.get()).thread_id??this.id}document(){return q.byId(this.client,this.documentId)}async author(){return P.byId(this.client,(await this.detail.get()).sender_id)}async reply($){return this.document().comment($,{threadId:await this.threadId()})}async edit($){let{content:O,mentions:j}=O$($);return await this.mutate((x)=>x.storage.entityMessageEdit({path:this.path,body:{content:O,mentions:j}})),this}async delete(){await this.mutate(($)=>$.storage.entityMessageDeleteMessage({path:this.path}))}}class aO{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 aO($,O,j)}read(){return this.detail.get()}toJSON(){return{id:this.id,documentId:this.document.id}}}var d6=8;class q extends X${async meetingNotes(){return Y(await this.client.calendar.documentNoteLinks({path:{document_id:this.id}})).map((O)=>({note:q$.fromDocumentLink(this.client,this,O),eventTitle:O.eventTitle}))}async anchors(){return Y(await this.client.storage.getDocumentAnchors({path:{document_id:this.id}})).data.map(($)=>VO.from(this.client,this,$))}async createHighlight($){return VO.from(this.client,this,Y(await this.client.storage.createAnchor({path:{document_id:this.id},body:{...$,fileType:"pdf",anchorType:"highlight"}})))}version($){return aO.byId(this.client,this,$)}async sharePermissions(){return Y(await this.client.storage.getDocumentPermissionsV2({path:{document_id:this.id}})).documentPermissions}async permissionsToken(){return Y(await this.client.storage.getDocumentPermissionsToken({path:{document_id:this.id}})).token}async prepareSave($){return Y(await this.client.storage.presaveDocumentHandler({path:{document_id:this.id},body:{newBom:$}})).data}async save($){return(await this.mutate((O)=>O.storage.saveDocumentHandler({path:{document_id:this.id},body:$}))).data}async simpleSave(){return(await this.mutate(($)=>$.storage.simpleSave({path:{document_id:this.id}}))).data}messageThreadById($){return L$.byId(this.client,{type:"document",entity:this},$)}timelinePage($){return w$(this.client,{type:"document",entity:this},(O)=>u$.from(this.client,this.id,O),$)}access=new o(this.client,"document",this);async fetch(){let{data:$}=Y(await this.client.storage.getDocument({path:{document_id:this.id}}));return $.documentMetadata}static byId($,O){return new q($,O)}static async create($,O){let{documentId:j}=Y(await $.storage.createMarkdownHandler({body:{documentName:O.name,markdown:O.markdown??null,projectId:O.project?.id??null}}));return new q($,j)}static async createSnippet($,O){let{documentId:j}=Y(await $.storage.createSnippetHandler({body:{snippetName:O.name,markdown:O.markdown??null,projectId:O.project?.id??null}}));return new q($,j)}static async createSkill($,O){let{documentId:j}=Y(await $.storage.createSkillHandler({body:{skillName:O.name,markdown:O.markdown??null,projectId:O.project?.id??null}}));return new q($,j)}static recent($,O){let j=O?.pageSize??50;return c(async(x)=>{let S=Y(await $.storage.getUserDocumentsHandler({query:{limit:j,offset:x?Number(x):0,...O?.fileType!==void 0?{file_type:O.fileType}:{}}})),G=S.data?.next_offset;return{items:(S.data?.documents??[]).map((Z)=>new q($,Z.documentId)),nextCursor:G!=null?String(G):null}})}static async recentlyDeleted($){let{data:O}=Y(await $.storage.recentlyDeleted({}));return O.items.filter((j)=>j.type==="document").map((j)=>new q($,j.id))}entityType="document";propertyEntityType="DOCUMENT";name=this.field("documentName");fileType=this.field("fileType");project=this.mappedField("projectId",($)=>$?n.byId(this.client,$):void 0);owner=this.mappedField("owner",($)=>P.byId(this.client,$));branchedFrom=this.mappedField("branchedFromId",($)=>$?q.byId(this.client,$):void 0);createdAt=this.field("createdAt");updatedAt=this.field("updatedAt");deletedAt=this.field("deletedAt");async content(){let{text:$}=Y(await this.client.storage.getDocumentTextContent({path:{document_id:this.id}}));if($!==null)return $;let{presigned_url:O}=Y(await this.client.storage.exportDocument({path:{document_id:this.id}})),j=await fetch(O);if(!j.ok)throw new QO(j.status,{message:"failed to download document content"});return j.text()}async rename($){await this.mutate((O)=>O.storage.editDocument({path:{document_id:this.id},body:{documentName:$}}))}async move($){await this.mutate((O)=>O.storage.editDocument({path:{document_id:this.id},body:{projectId:$?.id??""}}))}async delete($){await this.mutate((O)=>$?.permanent?O.storage.permanentlyDeleteDocument({path:{document_id:this.id}}):O.storage.deleteDocument({path:{document_id:this.id}}))}async restore(){await this.mutate(($)=>$.storage.revertDeleteDocument({path:{document_id:this.id}}))}async copy($){let{data:O}=Y(await this.client.storage.copyDocument({path:{document_id:this.id},query:$.versionId!==void 0?{version_id:$.versionId}:void 0,body:{documentName:$.name}}));return new q(this.client,O.documentMetadata.documentId)}async comments(){let $={parent_type:"document",parent_id:this.id},O=c(async(x)=>{let S=Y(await this.client.storage.messageTimeline({path:$,query:{selection:JSON.stringify({limit:100,cursor:x})}}));return{items:S.items,nextCursor:S.next_cursor}}),j=[];for await(let x of O)j.push(x);return cO(j,d6,async(x)=>{let{state:S,root:G,replies:Z}=Y(await this.client.storage.entityMessageGetThread({path:{...$,id:x.id}}));return{thread:S,comments:[G,...Z].map((X)=>u$.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 u$.from(this.client,this.id,j)}async shortId(){return Y(await this.client.storage.getDocumentShortId({path:{document_id:this.id}}))}async teamShare(){return Y(await this.client.storage.getDocumentTeamShare({path:{document_id:this.id}}))}async setTeamShare($){await this.mutate((O)=>O.storage.setDocumentTeamShare({path:{document_id:this.id},body:{shareWithTeam:$}}))}async githubPullRequests(){let{pullRequests:$}=Y(await this.client.storage.getDocumentGithubPullRequests({path:{document_id:this.id}}));return $}async branchName(){let{branchName:$}=Y(await this.client.storage.getDocumentBranchName({path:{document_id:this.id}}));return $}webUrl(){return`${this.client.webAppUrl}/app/md/${this.id}`}static search=x$({filters:{document_filters:{}},type:"document",make:($,O)=>new q($,O.document_id)});toMention(){let $=this.detail.peek();return{tag:a$("m-document-mention",{documentId:this.id,documentName:$?.documentName??"",blockName:$?.fileType??"md"}),mention:{entity_type:"document",entity_id:this.id}}}}class l0{client;async noteDocuments($=""){let O=Y(await this.client.calendar.noteDocuments({query:{query:$}}));return{documents:O.documents.map((j)=>({document:q.byId(this.client,j.documentId),name:j.name})),teams:O.teams.map((j)=>({team:S$.byId(this.client,j.id),name:j.name}))}}async availabilityCalendars(){return Y(await this.client.calendar.getAvailabilityCalendars()).calendars.map(($)=>({calendar: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??=r6(this.client);let S=await O;return{items:x.items.map((G)=>({event:$$.fromRecord(this.client,G.event),occurrence:G.occurrence,inbox:G.event.calendarId?S.get(G.event.calendarId):void 0,role:p6(G.event)})),nextCursor:x.nextCursor}})}async teamPage($){let O=Y(await this.client.storage.listTeamCalendar({query:$}));return{items:O.items.map(({ownerId:j,...x})=>({...x,owner:P.byId(this.client,j)})),members:O.members.map((j)=>({user:P.byId(this.client,j.userId),sharing:j.sharing,coverage:j.coverage})),nextCursor:O.nextCursor??void 0}}async teamOutOfOffice($){let O=Y(await this.client.storage.listTeamOutOfOffice({query:$}));return{items:O.items.map((j)=>({event:$$.byId(this.client,j.eventId),owner:P.byId(this.client,j.ownerId),occurrenceKey:j.occurrenceKey,time:j.time,title:j.title??void 0})),hasMore:O.hasMore}}constructor($){this.client=$}calendars(){return m$.list(this.client)}calendar($){return m$.byId(this.client,$)}event($){return $$.byId(this.client,$)}replacement($){return new pO(this.client,$)}async createEvent($){let O=Y(await this.client.calendar.createCalendarEvent({body:l6($)}));return $$.fromRecord(this.client,O)}}function l6($){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 r6($){let{calendars:O}=Y(await $.calendar.listCalendars());return new Map(O.map((j)=>[j.id,j.emailAddress]))}function p6($){let O=$.attendees.find((j)=>j.isSelf);if($.viewerCan.organize||O?.isOrganizer)return"organizer";return O?"guest":void 0}class R$ extends A{lookupToken;constructor($,O,j){super($,O,j);this.lookupToken=j?.shareToken}static byId($,O){return new R$($,O)}static from($,O){return new R$($,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",($)=>$?Q$.byId(this.client,$):void 0);async update($){await this.mutate((O)=>O.storage.meetingUpdate({path:{meeting_id:this.id},body:$}))}async cancel(){await this.mutate(($)=>$.storage.meetingCancel({path:{meeting_id:this.id}}))}async invitePermissions(){return 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 c$ 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 c$($,O,j)}static from($,O,j){return new c$($,O,j.id,j)}content=this.field("content");createdAt=this.field("created_at");updatedAt=this.field("updated_at");call(){return Q$.byId(this.client,this.callId)}async author(){return P.byId(this.client,(await this.detail.get()).sender_id)}async reply($){let O=Y(await this.client.storage.entityMessageCreate({path:{parent_type:"call",parent_id:this.callId},body:{...O$($),thread_id:this.callId}}));return c$.from(this.client,this.callId,O)}async edit($){let{content:O,mentions:j}=O$($);return await this.mutate((x)=>x.storage.entityMessageEdit({path:this.path,body:{content:O,mentions:j}})),this}async delete(){await this.mutate(($)=>$.storage.entityMessageDeleteMessage({path:this.path}))}}class Q$ extends I${messageThreadById($){return L$.byId(this.client,{type:"call",entity:this},$)}timelinePage($){return w$(this.client,{type:"call",entity:this},(O)=>c$.from(this.client,this.id,O),$)}access=new o(this.client,"call",this);async meeting(){return R$.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 Q$($,O)}message($){return c$.byId(this.client,this.id,$)}name=this.field("customName");channel=this.mappedField("channelId",($)=>$?b.byId(this.client,$):void 0);channelName=this.field("channelName");creator=this.mappedField("createdBy",($)=>P.byId(this.client,$));isActive=this.field("isActive");status=this.field("status");roomName=this.field("roomName");startedAt=this.field("startedAt");endedAt=this.field("endedAt");durationMs=this.field("durationMs");summary=this.field("summary");transcript=this.field("transcript");participants=this.field("participants");guests=this.field("guests");teamShareAccessLevel=this.field("teamShareAccessLevel");shareWithTeam=this.field("shareWithTeam");recordingUrl=this.field("recordingUrl");recordingPreviewUrl=this.field("recordingPreviewUrl");recordingStartedAt=this.field("recordingStartedAt");async rename($){await this.mutate((O)=>O.storage.editCallRecord({path:{call_id:this.id},body:{customName:$??""}}))}async setTeamShare($){await this.mutate((O)=>O.storage.editCallRecord({path:{call_id:this.id},body:{sharePermission:{teamShareAccessLevel:$?"view":null}}}))}async delete(){await this.mutate(($)=>$.storage.deleteCallRecord({path:{call_id:this.id}}))}static search=x$({filters:{call_filters:{}},type:"call",make:($,O)=>new Q$($,O.call_id)})}class r0{client;constructor($){this.client=$}byId($){return Q$.byId(this.client,$)}search($,O){return Q$.search(this.client,$,O)}}class p0{client;constructor($){this.client=$}async list(){let{labels:$}=Y(await this.client.storage.listChannelLabels());return $}async create($,O=[]){return Y(await this.client.storage.createChannelLabel({body:{name:$,channelIds:O.map((j)=>j.id)}}))}async createSmartTag($,O){return Y(await this.client.storage.createChannelLabel({body:{name:$,rule:O}}))}async previewSmartTag($){return Y(await this.client.storage.previewSmartTag({body:$}))}async updateSmartTag($,O,j){return Y(await this.client.storage.renameChannelLabel({path:{label_id:$.id},body:{name:O,rule:j}}))}async rename($,O){return Y(await this.client.storage.renameChannelLabel({path:{label_id:$.id},body:{name:O}}))}async delete($){Y(await this.client.storage.deleteChannelLabel({path:{label_id:$.id}}))}async setLabel($,O){Y(await this.client.storage.setChannelLabel({path:{channel_id:$.id},body:{labelId:O?.id??null}}))}}class a0{client;async activity(){return Y(await this.client.storage.getActivity()).map(($)=>new JO(this.client,b.byId(this.client,$.channel_id),$))}labels;constructor($){this.client=$;this.labels=new p0($)}byId($){return b.byId(this.client,$)}async dm($){return b.dm(this.client,$)}async private($){return b.private(this.client,$)}async create($){return b.create(this.client,$)}async list(){let{items:$}=Y(await this.client.storage.getChannels());return $.map((O)=>b.byId(this.client,O.id.toString()))}async*search($,O){if(!O?.searchOn||O.searchOn==="name"){let{items:j}=Y(await this.client.storage.getChannels()),x=$.toLowerCase();for(let S of j)if(S.name?.toLowerCase().includes(x))yield b.byId(this.client,S.id.toString())}else yield*b.search(this.client,$,O)}}class iO{client;chat;id;message;constructor($,O,j,x){this.client=$;this.chat=O;this.id=j;this.message=x}static byId($,O,j,x){return new iO($,O,j,x)}async stop(){Y(await this.client.cognition.stopChatStream({body:{chat_id:this.chat.id,stream_id:this.id}}))}toJSON(){return{id:this.id,chatId:this.chat.id,messageId:this.message.id}}}class nO extends A{chat;constructor($,O,j){super($,j);this.chat=O}static byId($,O,j){return new nO($,O,j)}async fetch(){let $=Y(await this.client.cognition.getChat({path:{chat_id:this.chat.id}})).chat.messages.find((O)=>O.id===this.id);if(!$)throw new E(`Chat message ${this.id} is not yet available`);return $}content=this.field("content");role=this.field("role");async refresh(){this.detail.clear(),await this.detail.get()}toJSON(){return{...super.toJSON(),chatId:this.chat.id}}}class G$ extends X${async send($){let{attachments:O,additionalInstructions:j,...x}=$,S=await this.mutate((Z)=>Z.cognition.sendChatMessage({body:{...x,chat_id:this.id,additional_instructions:j,attachments:O?.map((X)=>({entity_id:X.entity.id,entity_type:X.type}))}})),G=G$.byId(this.client,S.chat_id);return iO.byId(this.client,G,S.stream_id,nO.byId(this.client,G,S.message_id))}access=new o(this.client,"chat",this);entityType="chat";propertyEntityType="CHAT";async fetch(){let{chat:$}=Y(await this.client.cognition.getChat({path:{chat_id:this.id}}));return $}static byId($,O){return new G$($,O)}static async create($,O){let{id:j}=Y(await $.cognition.createChat({body:{name:O?.name??null,projectId:O?.project?.id??null}}));return new G$($,j)}name=this.field("name");model=this.field("model");project=this.mappedField("projectId",($)=>$?n.byId(this.client,$):void 0);createdAt=this.field("createdAt");updatedAt=this.field("updatedAt");messages=this.field("messages");async rename($){await this.mutate((O)=>O.cognition.patchChat({path:{chat_id:this.id},body:{name:$}}))}async delete($){await this.mutate((O)=>$?.permanent?O.cognition.permanentlyDeleteChat({path:{chat_id:this.id}}):O.cognition.deleteChat({path:{chat_id:this.id}}))}async copy(){let{id:$}=await this.mutate((O)=>O.cognition.copyChat({path:{chat_id:this.id}}));return new G$(this.client,$)}async restore(){await this.mutate(($)=>$.cognition.revertDeleteChat({path:{chat_id:this.id}}))}async history(){let{conversation:$}=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 G$($,O.chat_id)});toMention(){return{tag:a$("m-document-mention",{documentId:this.id,documentName:this.detail.peek()?.name??"",blockName:"chat",blockParams:{}}),mention:{entity_type:"chat",entity_id:this.id}}}}class i0{client;constructor($){this.client=$}byId($){return G$.byId(this.client,$)}create($){return G$.create(this.client,$)}search($,O){return G$.search(this.client,$,O)}}var a6=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 P.byId(this.client,(await this.detail.get()).sender_id)}async reply($){return sO(this.client,this.parent,$,{threadId:await this.threadId()})}async edit($){let{content:O,mentions:j}=O$($);return await this.mutate((x)=>x.storage.entityMessageEdit({path:this.path,body:{content:O,mentions:j}})),this}async delete(){await this.mutate(($)=>$.storage.entityMessageDeleteMessage({path:this.path}))}}async function Uj($,O){let j={parent_type:O.type,parent_id:O.id},x=c(async(G)=>{let Z=Y(await $.storage.messageTimeline({path:j,query:{selection:JSON.stringify({limit:100,cursor:G})}}));return{items:Z.items,nextCursor:Z.next_cursor}}),S=[];for await(let G of x)S.push(G);return cO(S,a6,async(G)=>{let{state:Z,root:X,replies:K}=Y(await $.storage.entityMessageGetThread({path:{...j,id:G.id}}));return{thread:Z,comments:[X,...K].map((L)=>A$.from($,O,L))}})}async function sO($,O,j,x){let S=Y(await $.storage.entityMessageCreate({path:{parent_type:O.type,parent_id:O.id},body:{...O$(j),thread_id:x?.threadId??null}}));return A$.from($,O,S)}class f$ extends I${messageThreadById($){return L$.byId(this.client,{type:"crm_contact",entity:this},$)}timelinePage($){return w$(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 f$($,O)}static from($,O){return new f$($,O.id,O)}name=this.field("name");email=this.field("email");company=this.mappedField("companyId",($)=>b$.byId(this.client,$));hidden=this.field("hidden");createdAt=this.field("createdAt");updatedAt=this.field("updatedAt");firstInteraction=this.field("firstInteraction");lastInteraction=this.field("lastInteraction");async hide(){await this.setHidden(!0)}async unhide(){await this.setHidden(!1)}async setHidden($){await this.mutate((O)=>O.storage.setContactHidden({path:{contact_id:this.id},body:{hidden:$}}))}async rename($){await this.mutate((O)=>O.storage.setCrmContactName({path:{contact_id:this.id},body:{name:$}}))}get commentParent(){return{type:"crm_contact",id:this.id}}async comments(){return Uj(this.client,this.commentParent)}async comment($,O){return sO(this.client,this.commentParent,$,O)}commentById($){return A$.byId(this.client,this.commentParent,$)}}class b$ extends X${messageThreadById($){return L$.byId(this.client,{type:"crm_company",entity:this},$)}timelinePage($){return w$(this.client,{type:"crm_company",entity:this},(O)=>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 b$($,O)}static from($,O){return new b$($,O.id,O)}name=this.field("name");description=this.field("description");hidden=this.field("hidden");emailSync=this.field("emailSync");team=this.mappedField("teamId",($)=>S$.byId(this.client,$));createdAt=this.field("createdAt");updatedAt=this.field("updatedAt");async domain(){let{domains:$}=await this.detail.get();return $[0]?.domain}async domains(){let{domains:$}=await this.detail.get();return $.map((O)=>O.domain)}async contacts(){return Y(await this.client.storage.listCompanyContacts({path:{company_id:this.id}})).map((O)=>f$.from(this.client,O))}static search=x$({filters:{crm_company_filters:{}},type:"company",includeCrm:!0,make:($,O)=>new b$($,O.id)});async hide(){await this.setHidden(!0)}async unhide(){await this.setHidden(!1)}async setHidden($){await this.mutate((O)=>O.storage.setCompanyHidden({path:{company_id:this.id},body:{hidden:$}}))}async setEmailSync($){await this.mutate((O)=>O.storage.setEmailSync({path:{company_id:this.id},body:{email_sync:$}}))}async rename($){await this.mutate((O)=>O.storage.setCrmCompanyName({path:{company_id:this.id},body:{name:$}}))}async createContact($){let O=await this.mutate((j)=>j.storage.createCrmContact({path:{company_id:this.id},body:$}));return f$.from(this.client,O)}get commentParent(){return{type:"crm_company",id:this.id}}async comments(){return Uj(this.client,this.commentParent)}async comment($,O){return sO(this.client,this.commentParent,$,O)}commentById($){return A$.byId(this.client,this.commentParent,$)}}class s$ extends A{tableDetail=new W$(async()=>Y(await this.client.storage.getCrmPipelineTable({path:{id:this.id}})));static byId($,O){return new s$($,O)}static from($,O){return new s$($,O.id,O)}async fetch(){return 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",($)=>P.byId(this.client,$));team=this.mappedField("teamId",($)=>S$.byId(this.client,$));async rename($){await this.mutate((O)=>O.storage.renameCrmPipeline({path:{id:this.id},body:{name:$}}))}async setSharing($){if($===void 0)throw Error("Sharing is required");await this.mutate((O)=>O.storage.shareCrmPipeline({path:{id:this.id},body:{sharing:$}}))}async setTrashed($){await this.mutate((O)=>O.storage.trashCrmPipeline({path:{id:this.id},body:{trashed:$}}))}async sharePermissions(){return Y(await this.client.storage.getCrmPipelinePermissions({path:{id:this.id}}))}async updateSharePermissions($){return this.mutate((O)=>O.storage.updateCrmPipelinePermissions({path:{id:this.id},body:i$($)}))}async table(){return zj.from(this.client,this,await this.tableRecord())}tableRecord(){return this.tableDetail.get()}rows(){return c(async($)=>{let O=Y(await this.client.storage.getCrmPipelineRows({path:{id:this.id},query:{after:$}}));return{items:O.rows.map((j)=>WO.from(this.client,this,j)),nextCursor:O.next}})}queryRows($={}){if($.rows?.some((O)=>O.pipeline.id!==this.id))throw Error("Rows belong to another pipeline");return c(async(O)=>{let j=Y(await this.client.storage.queryCrmPipelineRows({path:{id:this.id},body:{after:O,query:$.query,rowIds:$.rows?.map((x)=>x.id)}}));return{items:j.rows.map((x)=>WO.from(this.client,this,x)),nextCursor:j.next}})}async applyOps($,O){if(O?.baseVersions?.some((S)=>S.table.pipeline.id!==this.id))throw Error("Table belongs to another pipeline");let j={ops:$,baseVersions:O?.baseVersions?Object.fromEntries(O.baseVersions.map((S)=>[S.table.id,S.version])):void 0},x=await this.mutate((S)=>S.storage.applyCrmPipelineOps({path:{id:this.id},body:j}));return this.tableDetail.clear(),x}}class zj extends 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 zj($,O,j)}fetch(){return this.pipeline.tableRecord()}async columns(){return(await this.pipeline.tableRecord()).columns.map(($)=>Ij.from(this.client,this,$))}async version(){return(await this.pipeline.tableRecord()).table.version}rowById($){return WO.byId(this.client,this.pipeline,$)}rows(){return this.pipeline.rows()}}class WO extends 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 WO($,O,j)}static from($,O,j){return new WO($,O,j.rowId,j)}async fetch(){for await(let $ of this.pipeline.queryRows({rows:[this]}))if($.id===this.id)return $.detail.get();throw new E(`Pipeline row ${this.id} is unavailable`)}cells=this.field("cells");async refresh(){this.detail.clear(),await this.detail.get()}}class Ij extends 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 Ij($,O,j)}async fetch(){let $=(await this.table.pipeline.tableRecord()).columns.find((O)=>O.column.id===this.id);if(!$)throw new E(`Pipeline column ${this.id} is unavailable`);return $}async writable(){return(await this.fetch()).writable}async name(){return(await this.fetch()).column.display_name??(await this.fetch()).definition.definition.display_name}}class n0{client;constructor($){this.client=$}byId($){return s$.byId(this.client,$)}async list(){return Y(await this.client.storage.listCrmPipelines()).map(($)=>s$.from(this.client,$))}async create($){return s$.from(this.client,Y(await this.client.storage.createCrmPipeline({body:$})))}}class s0{client;pipelines;constructor($){this.client=$;this.pipelines=new n0($)}companyById($){return b$.byId(this.client,$)}contactById($){return f$.byId(this.client,$)}async contactByEmail($){let{contact:O}=Y(await this.client.storage.getContactByEmail({query:{email:$}}));return O?f$.from(this.client,O):void 0}async searchContacts($,O={}){let{contacts:j}=Y(await this.client.storage.searchContacts({query:{query:$,limit:O.limit}}));return j.map((x)=>f$.from(this.client,x))}async createCompany($){return b$.from(this.client,Y(await this.client.storage.createCrmCompany({body:$})))}async settings(){return Y(await this.client.storage.getCrmTeamSettings())}async updateSettings($){return Y(await this.client.storage.putCrmTeamSettings({body:$}))}async setStages($){return Y(await this.client.storage.putCrmTeamStages({body:$}))}async resetStages(){Y(await this.client.storage.resetCrmTeamStages())}searchCompanies($){return b$.search(this.client,$)}}var Y$=Symbol.for("@ts-pattern/matcher"),u1=Symbol.for("@ts-pattern/isVariadic");var t0=($)=>Boolean($&&typeof $=="object"),Tj=($)=>$&&!!$[Y$],s=($,O,j)=>{if(Tj($)){let x=$[Y$](),{matched:S,selections:G}=x.match(O);return S&&G&&Object.keys(G).forEach((Z)=>j(Z,G[Z])),S}if(t0($)){if(!t0(O))return!1;if(Array.isArray($)){if(!Array.isArray(O))return!1;let x=[],S=[],G=[];for(let Z of $.keys()){let X=$[Z];Tj(X)&&X[u1]?G.push(X):G.length?S.push(X):x.push(X)}if(G.length){if(G.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),K=O.slice(x.length,S.length===0?1/0:-S.length);return x.every((L,Q)=>s(L,Z[Q],j))&&S.every((L,Q)=>s(L,X[Q],j))&&(G.length===0||s(G[0],K,j))}return $.length===O.length&&$.every((Z,X)=>s(Z,O[X],j))}return Reflect.ownKeys($).every((x)=>{let S=$[x];return((x in O)||Tj(G=S)&&G[Y$]().matcherType==="optional")&&s(S,O[x],j);var G})}return Object.is(O,$)},K$=($)=>{var O,j,x;return t0($)?Tj($)?(O=(j=(x=$[Y$]()).getSelectionKeys)==null?void 0:j.call(x))!=null?O:[]:Array.isArray($)?tO($,K$):tO(Object.values($),K$):[]},tO=($,O)=>$.reduce((j,x)=>j.concat(O(x)),[]);function i6(...$){if($.length===1){let[O]=$;return(j)=>s(O,j,()=>{})}if($.length===2){let[O,j]=$;return s(O,j,()=>{})}throw Error(`isMatching wasn't given the right number of arguments: expected 1 or 2, received ${$.length}.`)}function t($){return Object.assign($,{optional:()=>$x($),and:(O)=>d($,O),or:(O)=>c1($,O),select:(O)=>O===void 0?eO($):eO(O,$)})}function e0($){return Object.assign(((O)=>Object.assign(O,{[Symbol.iterator](){let j=0,x=[{value:Object.assign(O,{[u1]:!0}),done:!1},{done:!0,value:void 0}];return{next:()=>{var S;return(S=x[j++])!=null?S:x.at(-1)}}}}))($),{optional:()=>e0($x($)),select:(O)=>e0(O===void 0?eO($):eO(O,$))})}function $x($){return t({[Y$]:()=>({match:(O)=>{let j={},x=(S,G)=>{j[S]=G};return O===void 0?(K$($).forEach((S)=>x(S,void 0)),{matched:!0,selections:j}):{matched:s($,O,x),selections:j}},getSelectionKeys:()=>K$($),matcherType:"optional"})})}var n6=($,O)=>{for(let j of $)if(!O(j))return!1;return!0},s6=($,O)=>{for(let[j,x]of $.entries())if(!O(x,j))return!1;return!0},t6=($,O)=>{let j=Reflect.ownKeys($);for(let x of j)if(!O(x,$[x]))return!1;return!0};function d(...$){return t({[Y$]:()=>({match:(O)=>{let j={},x=(S,G)=>{j[S]=G};return{matched:$.every((S)=>s(S,O,x)),selections:j}},getSelectionKeys:()=>tO($,K$),matcherType:"and"})})}function c1(...$){return t({[Y$]:()=>({match:(O)=>{let j={},x=(S,G)=>{j[S]=G};return tO($,K$).forEach((S)=>x(S,void 0)),{matched:$.some((S)=>s(S,O,x)),selections:j}},getSelectionKeys:()=>tO($,K$),matcherType:"or"})})}function u($){return{[Y$]:()=>({match:(O)=>({matched:Boolean($(O))})})}}function eO(...$){let O=typeof $[0]=="string"?$[0]:void 0,j=$.length===2?$[1]:typeof $[0]=="string"?void 0:$[0];return t({[Y$]:()=>({match:(x)=>{let S={[O!=null?O:"@ts-pattern/anonymous-select-key"]:x};return{matched:j===void 0||s(j,x,(G,Z)=>{S[G]=Z}),selections:S}},getSelectionKeys:()=>[O!=null?O:"@ts-pattern/anonymous-select-key"].concat(j===void 0?[]:K$(j))})})}function d1($){return!0}function k$($){return typeof $=="number"}function t$($){return typeof $=="string"}function e$($){return typeof $=="bigint"}var l1=t(u(d1)),e6=t(u(d1)),o6=l1,o$=($)=>Object.assign(t($),{startsWith:(O)=>{return o$(d($,(j=O,u((x)=>t$(x)&&x.startsWith(j)))));var j},endsWith:(O)=>{return o$(d($,(j=O,u((x)=>t$(x)&&x.endsWith(j)))));var j},minLength:(O)=>o$(d($,((j)=>u((x)=>t$(x)&&x.length>=j))(O))),length:(O)=>o$(d($,((j)=>u((x)=>t$(x)&&x.length===j))(O))),maxLength:(O)=>o$(d($,((j)=>u((x)=>t$(x)&&x.length<=j))(O))),includes:(O)=>{return o$(d($,(j=O,u((x)=>t$(x)&&x.includes(j)))));var j},regex:(O)=>{return o$(d($,(j=O,u((x)=>t$(x)&&Boolean(x.match(j))))));var j}}),m1=o$(u(t$)),g$=($)=>Object.assign(t($),{between:(O,j)=>g$(d($,((x,S)=>u((G)=>k$(G)&&x<=G&&S>=G))(O,j))),lt:(O)=>g$(d($,((j)=>u((x)=>k$(x)&&x<j))(O))),gt:(O)=>g$(d($,((j)=>u((x)=>k$(x)&&x>j))(O))),lte:(O)=>g$(d($,((j)=>u((x)=>k$(x)&&x<=j))(O))),gte:(O)=>g$(d($,((j)=>u((x)=>k$(x)&&x>=j))(O))),int:()=>g$(d($,u((O)=>k$(O)&&Number.isInteger(O)))),finite:()=>g$(d($,u((O)=>k$(O)&&Number.isFinite(O)))),positive:()=>g$(d($,u((O)=>k$(O)&&O>0))),negative:()=>g$(d($,u((O)=>k$(O)&&O<0)))}),$7=g$(u(k$)),$O=($)=>Object.assign(t($),{between:(O,j)=>$O(d($,((x,S)=>u((G)=>e$(G)&&x<=G&&S>=G))(O,j))),lt:(O)=>$O(d($,((j)=>u((x)=>e$(x)&&x<j))(O))),gt:(O)=>$O(d($,((j)=>u((x)=>e$(x)&&x>j))(O))),lte:(O)=>$O(d($,((j)=>u((x)=>e$(x)&&x<=j))(O))),gte:(O)=>$O(d($,((j)=>u((x)=>e$(x)&&x>=j))(O))),positive:()=>$O(d($,u((O)=>e$(O)&&O>0))),negative:()=>$O(d($,u((O)=>e$(O)&&O<0)))}),O7=$O(u(e$)),j7=t(u(function($){return typeof $=="boolean"})),x7=t(u(function($){return typeof $=="symbol"})),S7=t(u(function($){return $==null})),Z7=t(u(function($){return $!=null})),Z$={__proto__:null,matcher:Y$,optional:$x,array:function(...$){return e0({[Y$]:()=>({match:(O)=>{if(!Array.isArray(O))return{matched:!1};if($.length===0)return{matched:!0};let j=$[0],x={};if(O.length===0)return K$(j).forEach((G)=>{x[G]=[]}),{matched:!0,selections:x};let S=(G,Z)=>{x[G]=(x[G]||[]).concat([Z])};return{matched:O.every((G)=>s(j,G,S)),selections:x}},getSelectionKeys:()=>$.length===0?[]:K$($[0])})})},set:function(...$){return t({[Y$]:()=>({match:(O)=>{if(!(O instanceof Set))return{matched:!1};let j={};if(O.size===0)return{matched:!0,selections:j};if($.length===0)return{matched:!0};let x=(G,Z)=>{j[G]=(j[G]||[]).concat([Z])},S=$[0];return{matched:n6(O,(G)=>s(S,G,x)),selections:j}},getSelectionKeys:()=>$.length===0?[]:K$($[0])})})},map:function(...$){return t({[Y$]:()=>({match:(O)=>{if(!(O instanceof Map))return{matched:!1};let j={};if(O.size===0)return{matched:!0,selections:j};let x=(X,K)=>{j[X]=(j[X]||[]).concat([K])};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[G,Z]=$;return{matched:s6(O,(X,K)=>{let L=s(G,K,x),Q=s(Z,X,x);return L&&Q}),selections:j}},getSelectionKeys:()=>$.length===0?[]:[...K$($[0]),...K$($[1])]})})},record:function(...$){return t({[Y$]:()=>({match:(O)=>{if(O===null||typeof O!="object"||Array.isArray(O))return{matched:!1};var j;if($.length===0)throw Error(`\`P.record\` wasn't given enough arguments. Expected (value) or (key, value), received ${(j=$[0])==null?void 0:j.toString()}`);let x={},S=(X,K)=>{x[X]=(x[X]||[]).concat([K])},[G,Z]=$.length===1?[m1,$[0]]:$;return{matched:t6(O,(X,K)=>{let L=typeof X!="string"||Number.isNaN(Number(X))?null:Number(X),Q=L!==null&&s(G,L,S),J=s(G,X,S),I=s(Z,K,S);return(J||Q)&&I}),selections:x}},getSelectionKeys:()=>$.length===0?[]:[...K$($[0]),...K$($[1])]})})},intersection:d,union:c1,not:function($){return t({[Y$]:()=>({match:(O)=>({matched:!s($,O,()=>{})}),getSelectionKeys:()=>[],matcherType:"not"})})},when:u,select:eO,any:l1,unknown:e6,_:o6,string:m1,number:$7,bigint:O7,boolean:j7,symbol:x7,nullish:S7,nonNullable:Z7,instanceOf:function($){return t(u(function(O){return(j)=>j instanceof O}($)))},shape:function($){return t(u(i6($)))}};class r1 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 o0={matched:!1,value:void 0};function k($){return new Hj($,o0)}class Hj{constructor($,O){this.input=void 0,this.state=void 0,this.input=$,this.state=O}with(...$){if(this.state.matched)return this;let O=$[$.length-1],j=[$[0]],x;$.length===3&&typeof $[1]=="function"?x=$[1]:$.length>2&&j.push(...$.slice(1,$.length-1));let S=!1,G={},Z=(K,L)=>{S=!0,G[K]=L},X=!j.some((K)=>s(K,this.input,Z))||x&&!Boolean(x(this.input))?o0:{matched:!0,value:O(S?"@ts-pattern/anonymous-select-key"in G?G["@ts-pattern/anonymous-select-key"]:G:this.input,this.input)};return new Hj(this.input,X)}when($,O){if(this.state.matched)return this;let j=Boolean($(this.input));return new Hj(this.input,j?{matched:!0,value:O(this.input,this.input)}:o0)}otherwise($){return this.state.matched?this.state.value:$(this.input)}exhaustive($=X7){return this.state.matched?this.state.value:$(this.input)}run(){return this.exhaustive()}returnType(){return this}narrow(){return this}}function X7($){throw new r1($)}var Ox,G7=new Uint8Array(16);function Rj(){if(!Ox){if(typeof crypto>"u"||!crypto.getRandomValues)throw Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Ox=crypto.getRandomValues.bind(crypto)}return Ox(G7)}var j$=[];for(let $=0;$<256;++$)j$.push(($+256).toString(16).slice(1));function p1($,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 jx={};function K7($,O,j){let x;if($)x=a1($.random??$.rng?.()??Rj(),$.msecs,$.seq,O,j);else{let S=Date.now(),G=Rj();Y7(jx,S,G),x=a1(G,jx.msecs,jx.seq,O,j)}return O??p1(x)}function Y7($,O,j){if($.msecs??=-1/0,$.seq??=0,O>$.msecs)$.seq=j[6]<<23|j[7]<<16|j[8]<<8|j[9],$.msecs=O;else if($.seq=$.seq+1|0,$.seq===0)$.msecs++;return $}function a1($,O,j,x,S=0){if($.length<16)throw Error("Random bytes length must be >= 16");if(!x)x=new Uint8Array(16),S=0;else if(S<0||S+16>x.length)throw RangeError(`UUID byte range ${S}:${S+15} is out of buffer bounds`);return O??=Date.now(),j??=$[6]*127<<24|$[7]<<16|$[8]<<8|$[9],x[S++]=O/1099511627776&255,x[S++]=O/4294967296&255,x[S++]=O/16777216&255,x[S++]=O/65536&255,x[S++]=O/256&255,x[S++]=O&255,x[S++]=112|j>>>28&15,x[S++]=j>>>20&255,x[S++]=128|j>>>14&63,x[S++]=j>>>6&255,x[S++]=j<<2&255|$[10]&3,x[S++]=$[11],x[S++]=$[12],x[S++]=$[13],x[S++]=$[14],x[S++]=$[15],x}var d$=K7;class C${table;id;constructor($,O){this.table=$;this.id=O}static byId($,O){return new C$($,O)}async detail(){let{columns:$}=await this.table.detail(),O=$.find((j)=>j.column.id===this.id);if(!O)throw new E(`column ${this.id} is not on table ${this.table.id}`);return O}async name(){let $=await this.detail();return $.column.display_name??$.definition.definition.display_name}async rename($){return await this.table.database.renameColumn(this,$),this}async inferType($){return await this.table.database.inferColumnType(this,$),this}changeType($){return this.table.database.changeColumnType(this,$)}convertIntoNewColumn($){return this.table.database.convertColumnIntoNewColumn(this,$)}casts(){return this.table.database.columnCasts(this)}async delete(){await this.table.database.deleteColumn(this)}async dataType(){return(await this.detail()).definition.definition.data_type}async isMultiSelect(){return(await this.detail()).definition.definition.is_multi_select}async position(){return(await this.detail()).column.position}async definition(){return(await this.detail()).definition}async config(){return(await this.detail()).column.config??void 0}async addOptions($){return await this.table.database.addColumnOptions(this,$),this}toJSON(){return{id:this.id,tableId:this.table.id}}}class F${table;id;constructor($,O){this.table=$;this.id=O}static byId($,O){return new F$($,O)}history(){return this.table.database.rowHistory(this)}toJSON(){return{id:this.id,tableId:this.table.id}}}class Dj{table;id;constructor($,O){this.table=$;this.id=O}static byId($,O){return new Dj($,O)}async detail(){let{views:$}=await this.table.detail(),O=$.find((j)=>j.id===this.id);if(!O)throw new E(`view ${this.id} is not on table ${this.table.id}`);return O}async name(){return(await this.detail()).name}async position(){return(await this.detail()).position}async layout(){return(await this.detail()).layout}async query(){return(await this.detail()).query}positions(){return this.table.database.viewPositions(this)}toJSON(){return{id:this.id,tableId:this.table.id}}}class J${database;id;constructor($,O){this.database=$;this.id=O}static byId($,O){return new J$($,O)}async detail(){let{tables:$}=await this.database.schema(),O=$.find((j)=>j.table.id===this.id);if(!O)throw new E(`table ${this.id} is not in database ${this.database.id}`);return O}async name(){return(await this.detail()).table.name}async rename($){return await this.database.renameTable(this,$),this}async version(){return(await this.detail()).table.version}async position(){return(await this.detail()).table.position}async columns(){let{columns:$}=await this.detail();return $.map((O)=>C$.byId(this,O.column.id))}addColumn($){return this.database.addColumn(this,$)}async reorderColumns($){return await this.database.reorderColumns(this,$),this}row($){return F$.byId(this,$)}async views(){let{views:$}=await this.detail();return $.map((O)=>Dj.byId(this,O.id))}createWebhook(){return this.database.createWebhook(this)}async delete(){await this.database.deleteTable(this)}toJSON(){return{id:this.id,databaseId:this.database.id}}}async function _j($,O,j,x={}){let S=Y(await $.storage.queryDatabases({body:{sql:j,databaseId:x.database?.id,baseVersions:Object.fromEntries((x.baseVersions??[]).map(({table:Q,version:J})=>[Q.id,J]))}})),G=new Map;for(let Q of[x.database,...(x.baseVersions??[]).map(({table:J})=>J.database)]){if(!Q)continue;let J=G.get(Q.id);if(J)J.add(Q);else G.set(Q.id,new Set([Q]))}let Z=(Q)=>{let J=G.get(Q)?.values().next().value;if(J)return J;let I=O($,Q);return G.set(Q,new Set([I])),I},X=(Q)=>{let J=S.tableDatabases[Q];if(!J)throw Error(`SQL response is missing the owner of table ${Q}`);return J$.byId(Z(J),Q)},K=new Set(Object.keys(S.newVersions).map((Q)=>X(Q).database.id));if(S.statement.kind==="schema")K.add(S.statement.databaseId);for(let Q of K)for(let J of G.get(Q)??[])J.invalidateSchema();let L=k(S.statement).with({kind:"select"},(Q)=>Q).with({kind:"schema"},({databaseId:Q,summary:J})=>({kind:"schema",database:Z(Q),summary:J})).with({kind:"insert"},{kind:"update"},{kind:"delete"},({kind:Q,tableId:J,tableName:I})=>({kind:Q,table:X(J),tableName:I})).with({kind:"alterColumnType"},({tableId:Q,tableName:J,columnId:I,columnName:z,to:W})=>{let V=X(Q);return{kind:"alterColumnType",table:V,tableName:J,column:C$.byId(V,I),columnName:z,to:W}}).exhaustive();return{result:S.result?Q7(S.result,X,S.tableDatabases):void 0,changesApplied:S.changesApplied,insertedRows:L.kind==="insert"?S.insertedRowIds.map((Q)=>F$.byId(L.table,Q)):[],newVersions:Object.entries(S.newVersions).map(([Q,J])=>({table:X(Q),version:J})),readVersions:Object.entries(S.readVersions).map(([Q,J])=>({table:X(Q),version:J})),truncatedTables:S.truncatedTables,statement:L}}function Q7($,O,j){let x=$.sourceTable&&j[$.sourceTable]?O($.sourceTable):void 0;return{columns:$.columns.map(({relatedTable:S,...G})=>({...G,relatedTable:S&&j[S]?O(S):void 0})),rows:$.rows,sourceTable:x,rowHandles:x?$.rowIds.map((S)=>F$.byId(x,S)):[]}}class Mj{table;id;createdBy;record;constructor($,O,j,x){this.table=$;this.id=O;this.createdBy=j;this.record=x}static fromRecord($,O,j){return new Mj($,j.id,O,j)}get tokenPrefix(){return this.record.tokenPrefix}get createdAt(){return this.record.createdAt}delete(){return this.table.database.deleteWebhook(this)}toJSON(){return{id:this.id,tableId:this.table.id,tokenPrefix:this.tokenPrefix}}}class Zx extends QO{op;row;column;taken;constructor($,O){super($,O);this.name="MacroOpRefusedError",this.message=O.message,this.op=O.op,this.row=O.row,this.column=O.column,this.taken=O.taken}}function Pj($){return k($).with({type:"relation"},({table:O})=>({type:"relation",database:O.database.id,table:O.id})).with({type:Z$.not("relation")},(O)=>O).exhaustive()}var J7={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 V7($){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})=>J7[O]).with({type:"relation"},()=>"Relation").exhaustive(()=>"Column")}function xx($){return $.map((O)=>({id:d$(),label:O}))}function i1($,O,j){return $?.kind===O&&"change"in $&&$.change.kind===j}function Sx($){return k($).with({kind:"reorder_tables"},({kind:O})=>O).with({kind:Z$.union("table","column","rows","view")},({kind:O,change:j})=>`${O}.${j.kind}`).exhaustive(()=>"unknown")}function l$($,O,j){let[x]=$;if($.length!==1||!i1(x,O,j))throw new f(`expected one ${O}.${j} result, got ${$.map(Sx).join(", ")||"none"}`);return x}class V$ extends A{access=new o(this.client,"database",this);async fetch(){return Y(await this.client.storage.getDatabase({path:{id:this.id}}))}assertOwns($,O){if(O.id!==this.id)throw new f(`${$} does not belong to database ${this.id}`)}static byId($,O){return new V$($,O)}static async create($,O){let j=Y(await $.storage.createDatabase({body:{name:O.name}}));return new V$($,j.id)}static async list($){return Y(await $.storage.listDatabases()).map((j)=>new V$($,j.database.id))}query($,O){return _j(this.client,V$.byId,$,{...O,database:this})}invalidateSchema(){this.detail.clear()}schema(){return this.detail.get()}name=this.mappedField("database",($)=>$.name);owner=this.mappedField("database",($)=>P.byId(this.client,$.owner_id));createdAt=this.mappedField("database",($)=>$.created_at);trashedAt=this.mappedField("database",($)=>$.trashed_at??void 0);grant=this.field("grant");tables=this.mappedField("tables",($)=>$.map((O)=>J$.byId(this,O.table.id)));async table($){let{tables:O}=await this.schema(),j=O.find((x)=>x.table.name===$);return j?J$.byId(this,j.table.id):void 0}async createTable($){let{table:O}=l$(await this.applyOps([{kind:"table",table:d$(),change:{kind:"create",name:$.name}}]),"table","created");return J$.byId(this,O)}async applyOps($,O={}){let j={ops:$};if(O.baseVersions!==void 0){for(let{table:S}of O.baseVersions)this.assertOwns(`table ${S.id}`,S.database);j.baseVersions=Object.fromEntries(O.baseVersions.map(({table:S,version:G})=>[S.id,G]))}let{results:x}=await this.mutate(async(S)=>{let G=await S.storage.applyDatabaseOps({path:{id:this.id},body:j});if(G.error!==void 0&&"op"in G.error)throw new Zx(G.response?.status??0,G.error);return G});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(Sx).join(", ")||"none"}`);return j.tables.map(({table:x})=>J$.byId(this,x))}async deleteTable($){this.assertOwns(`table ${$.id}`,$.database),l$(await this.applyOps([{kind:"table",table:$.id,change:{kind:"delete"}}]),"table","deleted")}async columnCasts($){return this.assertOwns(`column ${$.id}`,$.table.database),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 J$.byId(this,O.id)}webhookOf($){return Mj.fromRecord(J$.byId(this,$.tableId),P.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 l$(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),Y(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()} (${V7(O.to)})`,S=d$(),G=[{kind:"column",table:$.table.id,column:S,change:{kind:"create",definition:{source:"new",name:x,type:Pj(O.to),options:xx(j.options)},after:$.id}}];if(j.cells.length>0)G.push({kind:"rows",table:$.table.id,change:{kind:"update",changes:{kind:"per_row",rows:j.cells.map(({row:X,value:K})=>({row:X,cells:[{column:S,value:K}]}))}}});let[Z]=await this.applyOps(G,{baseVersions:[{table:$.table,version:j.tableVersion}]});if(!i1(Z,"column","created"))throw new f(`expected a column.created result, got ${Z?Sx(Z):"none"}`);return C$.byId($.table,Z.column)}async deleteColumn($){this.assertOwns(`column ${$.id}`,$.table.database);let O=await $.table.version(),{tableVersion:j}=l$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"delete"}}],{baseVersions:[{table:$.table,version:O}]}),"column","deleted");return j}async reorderColumns($,O){this.assertOwns(`table ${$.id}`,$.database);for(let S of O)if(S.table.id!==$.id)throw new f(`column ${S.id} does not belong to table ${$.id}`);let j=await $.version(),{tableVersion:x}=l$(await this.applyOps([{kind:"table",table:$.id,change:{kind:"reorder_columns",order:O.map((S)=>S.id)}}],{baseVersions:[{table:$,version:j}]}),"table","columns_reordered");if(x===void 0)throw new f(`table ${$.id} reordered its columns without a version`);return x}async renameTable($,O){this.assertOwns(`table ${$.id}`,$.database);let j=await $.name(),{tableVersion:x}=l$(await this.applyOps([{kind:"table",table:$.id,change:{kind:"rename",name:O,previousName:j}}]),"table","renamed");if(x===void 0)throw new f(`table ${$.id} was renamed without a version`);return x}async renameColumn($,O){this.assertOwns(`column ${$.id}`,$.table.database);let j=await $.name(),{tableVersion:x}=l$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"rename",name:O,previousName:j}}]),"column","renamed");return x}async inferColumnType($,O){return this.assertOwns(`column ${$.id}`,$.table.database),this.mutate((j)=>j.storage.inferDatabaseColumnType({path:{id:this.id,table_id:$.table.id,column_id:$.id},body:{dataType:O.dataType,baseVersion:O.baseVersion,...O.specificEntityType!==void 0?{specificEntityType:O.specificEntityType}:{}}}))}async addColumn($,O){if(this.assertOwns(`table ${$.id}`,$.database),O.after!==void 0&&O.after.table.id!==$.id)throw new f(`column ${O.after.id} does not belong to table ${$.id}`);let j="property"in O?{source:"existing",property:O.property.id}:{source:"new",name:O.name,type:Pj(O.type),...O.options!==void 0?{options:xx(O.options)}:{},...O.inferType!==void 0?{inferType:O.inferType}:{}},{column:x}=l$(await this.applyOps([{kind:"column",table:$.id,column:d$(),change:{kind:"create",definition:j,...O.after!==void 0?{after:O.after.id}:{}}}]),"column","created");return C$.byId($,x)}async addColumnOptions($,O){return this.assertOwns(`column ${$.id}`,$.table.database),l$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"add_options",options:xx(O)}}]),"column","options_added")}}class Xx{client;constructor($){this.client=$}query($,O){return _j(this.client,V$.byId,$,O)}byId($){return V$.byId(this.client,$)}create($){return V$.create(this.client,$)}list(){return V$.list(this.client)}}class Aj{id;name;constructor($,O){this.id=$;this.name=O}static async list($){let{skills:O}=Y(await $.storage.getSystemSkillsHandler());return O.map((j)=>new Aj(j.id,j.name))}}class Gx{client;async byTeamSlug($){let O=Y(await this.client.storage.getDocumentByTeamSlug({path:{slug:$}}));if(typeof O!=="object"||O===null||!("data"in O)||typeof O.data!=="object"||O.data===null||!("documentMetadata"in O.data)||typeof O.data.documentMetadata!=="object"||O.data.documentMetadata===null||!("documentId"in O.data.documentMetadata)||typeof O.data.documentMetadata.documentId!=="string")throw Error("Invalid team task document response");return q.byId(this.client,O.data.documentMetadata.documentId)}async validatePermissionsToken($){let O=Y(await this.client.storage.validateDocumentPermissionsToken({body:{token:$}}));return{document:q.byId(this.client,O.document_id),user:O.user_id?P.byId(this.client,O.user_id):void 0,accessLevel:O.access_level,expiresAt:O.exp,issuer:O.iss}}async createUpload($){let O={documentName:$.name,sha:$.sha,fileType:$.fileType,mimeType:$.mimeType,projectId:$.project?.id,teamId:$.team?.id,branchedFromId:$.branchedFrom?.id,emailAttachmentId:$.attachment?.id,isTask:$.isTask},j=Y(await this.client.storage.createDocument({body:O})).data;return{document:q.byId(this.client,j.documentMetadata.documentId),uploadUrl:j.presignedUrl??void 0,contentType:j.contentType,content:j.documentMetadata.content}}constructor($){this.client=$}byId($){return q.byId(this.client,$)}create($){return q.create(this.client,$)}async createCanvas($){let O=Y(await this.client.storage.createCanvasHandler({body:{documentName:$.name,projectId:$.project?.id}}));return q.byId(this.client,O.documentId)}createSnippet($){return q.createSnippet(this.client,$)}createSkill($){return q.createSkill(this.client,$)}systemSkills(){return Aj.list(this.client)}search($,O){return q.search(this.client,$,O)}recent($){return q.recent(this.client,$)}recentlyDeleted(){return q.recentlyDeleted(this.client)}}class BO extends A{async fetch(){let{attachment:$}=Y(await this.client.email.getAttachment({path:{id:this.id}}));return $}static byId($,O){return new BO($,O)}static from($,O){return new BO($,O.db_id,O)}filename=this.field("filename");mimeType=this.field("mime_type");size=this.field("size_bytes");dataUrl=this.field("data_url");sfsId=this.field("sfs_id");contentId=this.field("content_id");async toDocument(){let{document_id:$}=Y(await this.client.email.getAttachmentDocumentId({path:{id:this.id}}));return q.byId(this.client,$)}}class U$ extends X${access=new o(this.client,"email_thread",this);async followup(){return Y(await this.client.storage.getEmailFollowup({path:{thread_id:this.id}}))}async setFollowup($){return Y(await this.client.storage.setEmailFollowup({path:{thread_id:this.id},body:$}))}async calendarInvitations(){return Y(await this.client.email.getThreadCalendarInvitations({path:{thread_id:this.id}}))}async addEventToCalendar($,O,j={}){let x=Y(await this.client.email.copyThreadCalendarInvitation({path:{thread_id:this.id,message_id:$.id,invitation_id:O.id},body:{calendarId:j.calendar?.id}}));return $$.fromRecord(this.client,x)}async update($){await this.mutate((O)=>O.storage.editThreadV2({path:{thread_id:this.id},body:{projectId:$.project===void 0?void 0:$.project?.id??null,sharePermission:$.sharePermission?i$($.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 U$($,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",($)=>H$.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)=>D$.from(this.client,j))}async attachments(){let{messages:$}=await this.detail.get();return $.flatMap((O)=>O.attachments.map((j)=>BO.from(this.client,j)))}async reply($){let O=$.subject??await this.subject()??"",{message:j}=await this.mutate((x)=>x.email.sendMessage({body:{message:{thread_db_id:this.id,replying_to_id:$.replyingTo?.id??null,to:$.to,cc:$.cc??null,bcc:$.bcc??null,subject:O,body_text:$.bodyText}}}));return j.db_id?D$.byId(this.client,j.db_id):void 0}async archive($=!0){await this.mutate((O)=>O.email.archiveThread({path:{id:this.id},body:{value:$}}))}static async archiveMany($,O,j=!0){let x=[];for(let S=0;S<O.length;S+=100){let G=O.slice(S,S+100),Z=Y(await $.email.archiveThreads({body:{thread_ids:G.map((K)=>K.id),value:j}})),X=new Set(Z.failed_thread_ids);for(let K of G)if(K.detail.clear(),X.has(K.id))x.push(K)}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 U$($,O.thread_id)})}class D$ extends A{async fetch(){return Y(await this.client.email.getMessage({path:{id:this.id}}))}static byId($,O){return new D$($,O)}static from($,O){return new D$($,O.db_id,O)}static async send($,O){let{message:j}=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?D$.byId($,j.db_id):void 0}subject=this.field("subject");from=this.field("from");to=this.field("to");cc=this.field("cc");bcc=this.field("bcc");body=this.field("body_parsed");sentAt=this.field("internal_date_ts");labels=this.field("labels");link=this.mappedField("link_id",($)=>H$.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 U$.byId(this.client,(await this.detail.get()).thread_db_id)}}class LO extends D${async draftContext(){let $=await this.detail.get();return{headers:{"X-Email-Link-Id":$.link_id},query:{draft_generation:$.draft_generation??0}}}static byId($,O){return new LO($,O)}draftGeneration=this.field("draft_generation");async update($){let{headers:O,query:j}=await this.draftContext();await this.mutate((x)=>x.email.createDraft({headers:O,body:{draft:{...Kx($),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((G)=>G.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 Kx($){let{bodyText:O,bodyHtml:j,bodyMacro:x,headers:S,includeSignature:G,draftGeneration:Z,thread:X,replyingTo:K,...L}=$;return{...L,body_text:O,body_html:j===void 0?void 0:btoa(Array.from(new TextEncoder().encode(j),(Q)=>String.fromCharCode(Q)).join("")).replaceAll("+","-").replaceAll("/","_").replaceAll("=",""),body_macro:x,headers_json:S,include_signature:G,draft_generation:Z,thread_db_id:X?.id,replying_to_id:K?.id}}class NO 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 NO($,O,void 0,j)}static from($,O,j){return new NO($,O.id,O,j)}async fetch(){let $=Y(await this.client.email.listEmailFilters({headers:this.headers})).filters.find((O)=>O.id===this.id);if(!$)throw new E(`Email filter ${this.id} is unavailable`);return $}emailAddress=this.field("email_address");emailDomain=this.field("email_domain");isImportant=this.field("is_important");async setImportant($){let O=await this.detail.get();await this.mutate((j)=>j.email.upsertEmailFilter({headers:this.headers,body:{email_address:O.email_address,email_domain:O.email_domain,is_important:$}}))}async delete(){await this.mutate(($)=>$.email.deleteEmailFilter({path:{id:this.id},headers:this.headers}))}}class OO 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 OO($,O)}static async list($){let{labels:O}=Y(await $.email.listLabels());return O.map((j)=>new OO($,j.id,j))}static async create($,O){let{label:j}=Y(await $.email.createLabel({body:{label_name:O}}));if(!j.id)throw new f("created label has no id");return new OO($,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 Yx{client;async createDraft($,O){let j=Y(await this.client.email.createDraft({body:{draft:Kx($)},headers:O?{"X-Email-Link-Id":O.id}:void 0}));if(!j.draft.db_id)throw Error("Draft response has no message id");return LO.byId(this.client,j.draft.db_id)}draftById($){return LO.byId(this.client,$)}async*scheduled($){let O=$?.pageSize??100;if(!Number.isInteger(O)||O<1)throw Error("pageSize must be positive");let j=Math.min(O,1000);for(let x=0;;x+=j){let S=Y(await this.client.email.getScheduledMessages({query:{offset:x,limit:j},headers:$?.inbox?{"X-Email-Link-Id":$.inbox.id}:void 0}));for(let G of S.messages)yield LO.byId(this.client,G.db_id);if(S.messages.length<j)return}}async filters($){return Y(await this.client.email.listEmailFilters({headers:$?{"X-Email-Link-Id":$.id}:void 0})).filters.map((O)=>NO.from(this.client,O,$))}async upsertFilter($,O){return NO.from(this.client,Y(await this.client.email.upsertEmailFilter({headers:O?{"X-Email-Link-Id":O.id}:void 0,body:{email_address:$.emailAddress,email_domain:$.emailDomain,is_important:$.isImportant}})).filter,O)}async contacts(){return Y(await this.client.email.listContacts()).contacts}reminders($){let{inboxes:O,...j}=$??{};return c(async(x)=>{let S=Y(await this.client.storage.listEmailReminders({query:{...j,inboxIds:O?.map((G)=>G.id),cursor:x}}));return{items:S.items.map(({threadId:G,...Z})=>({...Z,thread:U$.byId(this.client,G)})),nextCursor:S.nextCursor}})}constructor($){this.client=$}byId($){return U$.byId(this.client,$)}message($){return D$.byId(this.client,$)}attachment($){return BO.byId(this.client,$)}link($){return H$.byId(this.client,$)}links(){return H$.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 D$.send(this.client,$)}search($,O){return U$.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)=>U$.byId(this.client,x.id)),nextCursor:j.next_cursor}})}label($){return OO.byId(this.client,$)}labels(){return OO.list(this.client)}createLabel($){return OO.create(this.client,$)}archive($,O=!0){return U$.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 HO{client;id;constructor($,O){this.client=$;this.id=O}static byId($,O){return new HO($,O)}async delete(){Y(await this.client.storage.deleteEntityMention({path:{mention_id:this.id}}))}toJSON(){return{id:this.id}}}class Qx{client;constructor($){this.client=$}byId($){return HO.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 HO.byId(this.client,j.id)}}function Jx($,O){return{chat:UO.byId($,O.id),name:O.name,announcements:O.announcements}}class UO extends A{static byId($,O){return new UO($,O)}static from($,O){return new UO($,O.jid,O)}async fetch(){let{chats:$}=Y(await this.client.storage.whatsappChats()),O=$.find((j)=>j.jid===this.id);if(!O)throw new E("WhatsApp chat is not available");return O}kind=this.field("kind");name=this.field("name");lastActivityAt=this.field("lastActivityAt");archived=this.field("archived");pinned=this.field("pinned");canAdd=this.field("canAdd");cannotAddReason=this.field("cannotAddReason");community=this.mappedField("community",($)=>$?Jx(this.client,$):void 0);added=this.mappedField("added",($)=>$?y$.byId(this.client,$.id):void 0);shared=this.mappedField("shared",($)=>$?y$.byId(this.client,$.id):void 0);async add(){let $=await this.kind(),O=await this.mutate((j)=>j.storage.externalChatAdd({body:{provider:"whatsapp",remoteId:this.id,kind:$}}));return y$.byId(this.client,O.chatId)}async refresh(){return this.detail.clear(),await this.detail.get(),this}}class _$ extends A{chat;constructor($,O,j,x){super($,j,x);this.chat=O}static byId($,O,j){return new _$($,O,j)}static from($,O,j){return new _$($,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",($)=>$?_$.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 jO{chat;id;record;constructor($,O,j){this.chat=$;this.id=O;this.record=j}static byId($,O){return new jO($,O)}static from($,O){return new jO($,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 xO{id;chat;filename;kind;constructor($,O,j,x){this.id=$;this.chat=O;this.filename=j;this.kind=x}static byId($,O){return new xO(O,$)}static from($,O){return new xO(O.uploadId,$,O.filename,O.kind)}toJSON(){return{id:this.id,chat:this.chat.id,filename:this.filename,kind:this.kind}}}class SO extends A{chat;constructor($,O,j,x){super($,j,x);this.chat=O}static byId($,O,j){return new SO($,O,j)}static from($,O,j){return new SO($,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",($)=>$?_$.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:xO.byId(this.chat,x.uploadId),caption:x.caption??void 0})).with({type:"mutation"},(x)=>({type:"mutation",message:_$.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)=>jO.byId(this.chat,S))})).exhaustive();return{idempotencyKey:$.idempotencyKey,message:j,replyTo:$.replyTo?_$.byId(this.client,this.chat,$.replyTo):void 0}}async refresh(){return this.detail.clear(),await this.detail.get(),this}}class y$ extends I${entityType="external_chat";static byId($,O){return new y$($,O)}async fetch(){return Y(await this.client.storage.externalChat({path:{chat_id:this.id}}))}provider=this.field("provider");name=this.field("name");kind=this.field("kind");canSend=this.field("canSend");sendReason=this.field("sendReason");sendingIdentity=this.field("sendingIdentity");unreadCount=this.field("unreadCount");backfill=this.field("backfill");limits=this.field("limits");members=this.field("members");participants=this.mappedField("members",($)=>($?.participants??[]).map((O)=>jO.from(this,O)));disappearingSeconds=this.field("disappearingSeconds");owner=this.mappedField("userId",($)=>P.byId(this.client,$));async community(){let{provider:$,community:O}=await this.detail.get();if(!O)return;return k($).with("whatsapp",()=>Jx(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)=>_$.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 xO.from(this,O)}async send($,O){if(O.replyTo)this.assertChat(O.replyTo.chat);let j=k($).returnType().with({type:"text"},(S)=>{let G=S.mentions??[];for(let Z of G)this.assertChat(Z.chat);return{type:"text",text:S.text,mentions:G.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 SO.from(this.client,this,x)}async sends(){return Y(await this.client.storage.externalChatSends({path:{chat_id:this.id}})).map(($)=>SO.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)=>SO.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:_$.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 Vx{client;constructor($){this.client=$}async list(){return Y(await this.client.storage.externalChats()).map(($)=>y$.byId(this.client,$.id))}byId($){return y$.byId(this.client,$)}}class Wx{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 ZO extends I${entityType="foreign_entity";async fetch(){return Y(await this.client.storage.getForeignEntity({path:{id:this.id}}))}static byId($,O){return new ZO($,O)}static fromRecord($,O){return new ZO($,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 n1({login:$,...O}){return{...O,login:$??void 0}}class Bx{client;constructor($){this.client=$}byId($){return ZO.byId(this.client,$)}async bySource($,O){return ZO.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(n1),assignees:j.map(n1),labels:x.map(({color:S,...G})=>({...G,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 C$.byId(await this.form.table(),(await this.detail()).column)}async options(){return(await this.detail()).options.map(($)=>zO.byId(this,$.id))}}class zO{question;id;constructor($,O){this.question=$;this.id=O}static byId($,O){return new zO($,O)}async detail(){let $=(await this.question.detail()).options.find((O)=>O.id===this.id);if(!$)throw new E(`option ${this.id} is not on question ${this.question.id}`);return $}async label(){return(await this.detail()).label}async color(){return(await this.detail()).color??void 0}}class RO{form;id;detail;constructor($,O,j){this.form=$;this.id=O;this.detail=new W$(()=>this.load(),j)}async load(){let $=await this.form.myResponse();if($.response.id!==this.id)throw new E(`response ${this.id} is not your current response`);return $}static byId($,O,j){return new 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 Cj{entityType;id;constructor($,O){this.entityType=$;this.id=O}static byId($,O){return new Cj($,O)}}class v$ extends A{async fetch(){return Y(await this.client.storage.getForm({path:{id:this.id}}))}static byId($,O){return new v$($,O)}static async create($,O){let j=Y(await $.storage.createForm({body:{name:O.name,source:O.table?{kind:"table",databaseId:O.table.database.id,tableId:O.table.id}:{kind:"new"}}}));return new v$($,j.form.id,j)}static async list($,O){if(!O)return Y(await $.storage.listAccessibleForms()).map(({form:S})=>new v$($,S.id));return Y(await $.storage.listForms({query:{databaseId:O.id}})).map((x)=>new v$($,x.id))}schema(){return this.detail.get()}name=this.mappedField("form",($)=>$.name);description=this.mappedField("form",($)=>$.description);owner=this.mappedField("form",($)=>P.byId(this.client,$.ownerId));database=this.mappedField("form",($)=>V$.byId(this.client,$.databaseId));table=this.mappedField("form",($)=>J$.byId(V$.byId(this.client,$.databaseId),$.tableId));audience=this.mappedField("form",($)=>$.audience);status=this.mappedField("form",($)=>$.status);closesAt=this.mappedField("form",($)=>$.closesAt??void 0);access=this.field("access");async sections(){return(await this.detail.get()).sections.map(($)=>p$.byId(this,$.id))}async questions(){return(await this.detail.get()).sections.flatMap(($)=>$.kind==="questions"?$.questions.map((O)=>r$.byId(this,O.id)):[])}async update($){return await this.mutate((O)=>O.storage.updateForm({path:{id:this.id},body:$})),this}assertOwns($){if($.form.id!==this.id)throw new f(`question or section does not belong to form ${this.id}`)}async replaceLayout($){let O=await this.table(),j=(Z)=>{if(Z.table.id!==O.id||Z.table.database.id!==O.database.id)throw new f(`column does not belong to form ${this.id}'s table`);return Z.id},x=(Z)=>({conjunction:Z.conjunction,conditions:Z.conditions.map((X)=>k(X).with({kind:"group"},(K)=>({kind:"group",...x(K)})).with({kind:"condition"},(K)=>({kind:"condition",column:j(K.column),test:k(K.test).with({kind:"options"},(L)=>({...L,options:L.options.map((Q)=>Q.id)})).with({kind:"entities"},(L)=>({...L,entities:L.entities.map((Q)=>Q.id)})).with({kind:Z$.union("presence","text","number","date","dateRange","checkbox")},(L)=>L).exhaustive()})).exhaustive())}),S={sections:$.map((Z)=>{if(Z.section)this.assertOwns(Z.section);let X={id:Z.section?.id??d$(),title:Z.title,description:Z.description??""};return k(Z).with({kind:"booking"},(K)=>({...X,kind:"booking",target:K.target})).with({kind:"gate"},(K)=>({...X,kind:"gate",rules:x(K.rules),message:K.message})).with({kind:"questions"},(K)=>({...X,kind:"questions",questions:K.questions.map((L)=>{if(L.question)this.assertOwns(L.question);return{id:L.question?.id??d$(),column:j(L.column),helpText:L.helpText??"",required:L.required??!1,widget:L.widget??null}})})).exhaustive()})},G=await this.mutate((Z)=>Z.storage.putFormLayout({path:{id:this.id},body:S}));return{form:this,publicationError:G.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((G)=>G.id)})).with({type:"options"},(S)=>({type:"options",value:S.value.map((G)=>{if(G.question.id!==O.id||G.question.form.id!==this.id)throw new f("option does not belong to the answered question");return{id:G.id}})})).with({type:"entities"},(S)=>({type:"entities",value:S.value.map(({entityType:G,entity:Z})=>({entityType:G,entityId:Z.id}))})).with({type:Z$.union("text","number","boolean","date","date_range","link","clear")},(S)=>S).exhaustive();return{question:O.id,value:x}})}unlockedBooking($){return $?{...$,section: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=F$.byId(await this.table(),j.row),S=this.unlockedBooking(j.booking);return{outcome:"submitted",response:RO.byId(this,j.response,{status:"submitted",row:x,answers:O,booking:S}),row:x,...S?{booking:S}:{}}}).exhaustive()}async submit($){let O={answers:this.wireAnswers($)};return this.outcome(Y(await this.client.storage.submitFormResponse({path:{id:this.id},body:O})),$)}async editResponse($){let O={answers:this.wireAnswers($)};return this.outcome(Y(await this.client.storage.editMyFormResponse({path:{id:this.id},body:O})),$)}async myResponse(){let $=Y(await this.client.storage.getMyFormResponse({path:{id:this.id}})),O=await this.table(),j=await Promise.all($.answers.map(async(G)=>{let Z=r$.byId(this,G.question),X=await k(G.value).with({type:"options"},(K)=>({type:"options",value:K.value.map((L)=>{if(!("id"in L))throw new f("stored form answers must reference options by id");return zO.byId(Z,L.id)})})).with({type:"entities"},(K)=>({type:"entities",value:K.value.map((L)=>({entityType:L.entityType,entity:Cj.byId(L.entityType,L.entityId)}))})).with({type:"rows"},async(K)=>{let L=await Z.detail();if(L.kind.type!=="relation")throw new f("row answer requires a relation question");let Q=J$.byId(V$.byId(this.client,L.kind.database),L.kind.table);return{type:"rows",value:K.value.map((J)=>F$.byId(Q,J))}}).with({type:Z$.union("text","number","boolean","date","date_range","link","clear")},(K)=>K).exhaustive(()=>{throw new f(`answer to question ${Z.id} has a type this SDK doesn't know`)});return{question:Z,value:X}})),x=$.response.row?F$.byId(O,$.response.row):void 0,S=this.unlockedBooking($.booking);return{...S?{booking:S}:{},response:RO.byId(this,$.response.id,{status:$.response.status,row:x,answers:j,booking:S}),status:$.response.status,stoppedAtSection:$.response.stoppedAtSection?p$.byId(this,$.response.stoppedAtSection):void 0,row:x,submittedAt:$.response.submittedAt,updatedAt:$.response.updatedAt,answers:j}}async responseSummary(){let $=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:zO.byId(j,S.option)}}]).with({kind:"checkbox"},(S)=>[{count:x.count,value:S}]).exhaustive((S)=>{return console.warn("macro sdk: unknown form tally bucket",S),[]}))}})}async sharePermissions(){return Y(await this.client.storage.getFormPermissions({path:{id:this.id}}))}updateSharePermissions($){return this.mutate((O)=>O.storage.updateFormPermissions({path:{id:this.id},body:$}))}webUrl(){return`${this.client.webAppUrl}/app/form/${this.id}`}respondUrl(){return`${this.client.webAppUrl}/app/form/${this.id}/respond`}}class Lx{client;constructor($){this.client=$}byId($){return v$.byId(this.client,$)}create($){return v$.create(this.client,$)}list($){return v$.list(this.client,$)}}class DO extends 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 Nx(this.client,this,$.changeset):void 0,error:$.error??void 0}}}class Nx{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 Ux{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 $j{client;id;constructor($,O){this.client=$;this.id=O}static byId($,O){return new $j($,O)}async claim($){let O=Y(await this.client.storage.claimHarnessPairing({path:{pairing_id:this.id},body:{device_secret:$}}));return"harness"in O?{harness:B$.from(this.client,O.harness),token:O.token}:void 0}toJSON(){return{id:this.id}}}class zx{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(($)=>l.byId(this.client,$.session_id))}pairing($){return _O.byId(this.client,$)}async createPairing($){let O=Y(await this.client.storage.createHarnessPairing({body:$}));return{pairing:_O.byId(this.client,O.code),device:$j.byId(this.client,O.pairing_id),deviceSecret:O.device_secret,expiresAt:O.expires_at,pollIntervalSeconds:O.poll_interval_seconds}}}var W7="00000001-0000-0000-0000-000000000002",B7="00000001-0000-0000-0002-000000000004";function L7($){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 M$ extends q{static byId($,O){return new M$($,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}}));return new M$($,j)}static async forPullRequest($,O){let j=L7(O),{pullRequests:x}=Y(await $.storage.getGithubPullRequestTasks({body:{githubKeys:[j]}}));return(x[0]?.taskIds??[]).map((S)=>new M$($,S))}async completed(){let{subType:$}=await this.detail.get();if($!=="task")return;let j=(await this.properties()).find((x)=>x.definition.id===W7)?.value;return j?.type==="SelectOption"&&j.value.includes(B7)}webUrl(){return`${this.client.webAppUrl}/app/task/${this.id}`}static search=x$({filters:{document_filters:{sub_types:["task"],task_filters:{}}},type:"document",make:($,O)=>new M$($,O.document_id)})}class XO extends A{access=new o(this.client,"initiative",this);static byId($,O){return new XO($,O)}static from($,O){return new XO($,O.id,O)}async fetch(){return Y(await this.client.storage.getInitiative({path:{initiative_id:this.id}}))}name=this.field("name");owner=this.mappedField("ownerId",($)=>P.byId(this.client,$));members=this.mappedField("memberIds",($)=>$.map((O)=>P.byId(this.client,O)));tasks=this.mappedField("taskIds",($)=>$.map((O)=>M$.byId(this.client,O)));accessLevel=this.field("userAccessLevel");sharePermissions=this.field("sharePermission");async update($){await this.mutate((O)=>O.storage.updateInitiative({path:{initiative_id:this.id},body:{name:$.name,memberIds:$.members?.map((j)=>j.id),sharePermission:$.sharePermission?i$($.sharePermission):void 0}}))}async delete(){await this.mutate(($)=>$.storage.deleteInitiative({path:{initiative_id:this.id}}))}}class Ix{client;constructor($){this.client=$}byId($){return XO.byId(this.client,$)}async list(){return Y(await this.client.storage.listInitiatives()).initiatives.map(($)=>XO.byId(this.client,$.id))}async create($){return XO.from(this.client,Y(await this.client.storage.createInitiative({body:{name:$.name,description:$.description,memberIds:$.members?.map((O)=>O.id),shareWithTeam:$.shareWithTeam,propertyValues:$.propertyValues}})))}}class Tx{client;constructor($){this.client=$}byId($){return R$.byId(this.client,$)}async create($){return R$.from(this.client,Y(await this.client.storage.meetingCreate({body:$})))}async list(){return Y(await this.client.storage.meetingList()).meetings.map(($)=>R$.from(this.client,$))}async active(){return Y(await this.client.storage.meetingListActive()).meetings.map(($)=>R$.from(this.client,$))}async lookup($){return R$.from(this.client,Y(await this.client.storage.meetingLookup({path:{token:$}})))}}class IO extends A{async fetch(){return Y(await this.client.notification.getTypedNotificationById({path:{notification_id:this.id}}))}static byId($,O){return new IO($,O)}static from($,O){return new IO($,O.id,O)}static list($,O){return c(async(j)=>{let x=Y(await $.notification.listTypedNotifications({query:{...O?.pageSize?{limit:O.pageSize}:{},...O?.states!==void 0?{states:O.states.join(",")}:{},...j?{cursor:j}:{}}}));return{items:x.items.map((S)=>IO.from($,S)),nextCursor:x.next_cursor}})}type=this.field("notification_event_type");createdAt=this.field("created_at");updatedAt=this.field("updated_at");state=this.field("state");done=this.mappedField("state",($)=>$==="done");sent=this.field("sent");viewedAt=this.field("viewed_at");deletedAt=this.field("deleted_at");owner=this.mappedField("owner_id",($)=>P.byId(this.client,$));sender=this.mappedField("sender_id",($)=>$?P.byId(this.client,$):void 0);metadata=this.field("notification_metadata");async seen(){return await this.state()!=="unseen"}async markSeen(){await this.mutate(($)=>$.notification.bulkMarkNotificationsSeen({body:{notificationIds:[this.id]}}))}async markDone(){await this.mutate(($)=>$.notification.bulkMarkNotificationsDone({body:{notificationIds:[this.id]}}))}async markUndone(){await this.mutate(($)=>$.notification.bulkMarkNotificationsUndone({body:{notificationIds:[this.id]}}))}async delete(){await this.mutate(($)=>$.notification.deleteUserNotificationV2({path:{notification_id:this.id}}))}}class Hx{client;constructor($){this.client=$}byId($){return IO.byId(this.client,$)}list($){return IO.list(this.client,$)}async markSeen($){Y(await this.client.notification.bulkMarkNotificationsSeen({body:{notificationIds:$}}))}async markDone($){Y(await this.client.notification.bulkMarkNotificationsDone({body:{notificationIds:$}}))}async delete($){Y(await this.client.notification.bulkDeleteUserNotificationsV2({body:{notificationIds:$}}))}async preferences(){return Y(await this.client.notification.getNotificationTypePreferences())}async enableType($){Y(await this.client.notification.enableNotificationType({path:{notification_event_type:$}}))}async disableType($){Y(await this.client.notification.disableNotificationType({path:{notification_event_type:$}}))}}class Rx{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 Dx{client;constructor($){this.client=$}byId($){return n.byId(this.client,$)}create($){return n.create(this.client,$)}search($,O){return n.search(this.client,$,O)}}class MO{client;definitionId;id;record;constructor($,O,j,x){this.client=$;this.definitionId=O;this.id=j;this.record=x}static from($,O,j){return new MO($,O,j.id,j)}get value(){return this.record.value}get color(){return this.record.color??void 0}get displayOrder(){return this.record.display_order}get createdAt(){return this.record.created_at}get updatedAt(){return this.record.updated_at}async update($){return this.record=Y(await this.client.properties.updatePropertyOption({path:{definition_id:this.definitionId,option_id:this.id},body:$})),this}async delete(){Y(await this.client.properties.deletePropertyOption({path:{definition_id:this.definitionId,option_id:this.id}}))}}class GO{client;id;detail;constructor($,O,j){this.client=$;this.id=O;this.detail=new 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 GO($,j.id,j)}static byId($,O){return new GO($,O)}static fromRecord($,O){return new GO($,O.id,O)}get displayName(){return this.detail.get().then(($)=>$.display_name)}get dataType(){return this.detail.get().then(($)=>$.data_type)}get owner(){return this.detail.get().then(($)=>$.owner)}get isSystem(){return this.detail.get().then(($)=>$.is_system)}get isMultiSelect(){return this.detail.get().then(($)=>$.is_multi_select)}get createdAt(){return this.detail.get().then(($)=>$.created_at)}get updatedAt(){return this.detail.get().then(($)=>$.updated_at)}async delete(){return Y(await this.client.properties.deletePropertyDefinition({path:{definition_id:this.id}}))}async options(){return Y(await this.client.properties.getPropertyOptions({path:{definition_id:this.id}})).map((O)=>MO.from(this.client,this.id,O))}async addOption($){let O=Y(await this.client.properties.addPropertyOption({path:{definition_id:this.id},body:$}));return MO.from(this.client,this.id,O)}async updateOption($,O){let j=Y(await this.client.properties.updatePropertyOption({path:{definition_id:this.id,option_id:$.id},body:O}));return MO.from(this.client,this.id,j)}async deleteOption($){return Y(await this.client.properties.deletePropertyOption({path:{definition_id:this.id,option_id:$.id}}))}}class _x{client;constructor($){this.client=$}async list($){return Y(await this.client.properties.listProperties({query:{scope:$?.scope??"all",...$?.forEntityType!==void 0?{for_entity_type:$.forEntityType}:{}}})).map((j)=>{let x="definition"in j?j.definition:j;return GO.fromRecord(this.client,x)})}create($){return GO.create(this.client,$)}definition($){return GO.byId(this.client,$)}async bulkEntityProperties($){return Y(await this.client.properties.getBulkEntityProperties({body:$}))}async updateEntityPropertyOptions($,O){return Y(await this.client.properties.bulkUpdateEntitiesPropertyOptions({body:{entities:$.map((x)=>x.propertyReference()),property_id:O.property.id,...O.add?{add_option_ids:O.add.map((x)=>x.id)}:{},...O.remove?{remove_option_ids:O.remove.map((x)=>x.id)}:{}}})).results}async addEntityPropertyOption($){return Y(await this.client.properties.addEntityPropertyOption({path:{...$.entity.propertyReference(),property_id:$.property.id,option_id:$.option.id}}))}async removeEntityPropertyOption($){return Y(await this.client.properties.removeEntityPropertyOption({path:{...$.entity.propertyReference(),property_id:$.property.id,option_id:$.option.id}}))}async tags(){return Y(await this.client.properties.listTags({}))}}function Mx($){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 N7($){return k($).with({type:"multiple"},(O)=>({type:"multiple",triggers:O.triggers.map(Mx)})).with({type:"cron"},Mx).with({type:"events"},Mx).exhaustive()}class KO extends A{static byId($,O){return new KO($,O)}static from($,O){if(!O.id)throw Error("Routine response has no id");return new KO($,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",($)=>P.byId(this.client,$));async update($){await this.mutate((O)=>O.scheduledAction.updateScheduledAction({path:{id:this.id},body:Ax($)}))}async setEnabled($){await this.mutate((O)=>O.scheduledAction.setScheduledActionEnabled({path:{id:this.id},body:{enabled:$}}))}async execute(){let $=Y(await this.client.scheduledAction.executeScheduledActionNow({path:{id:this.id}}));if($.resource)return k($.resource).with({type:"agent"},(O)=>l.byId(this.client,O.id)).with({type:"chat"},(O)=>G$.byId(this.client,O.id)).exhaustive();return $.chat_id?G$.byId(this.client,$.chat_id):void 0}async history(){return Y(await this.client.scheduledAction.listScheduledActionHistory({path:{id:this.id}})).map(($)=>new Px(this,$))}async delete(){await this.mutate(($)=>$.scheduledAction.deleteScheduledAction({path:{id:this.id}}))}}class Px{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 Ax($){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:N7($.trigger),task:{...O}}}class Cx{client;constructor($){this.client=$}byId($){return KO.byId(this.client,$)}async create($){return KO.from(this.client,Y(await this.client.scheduledAction.createScheduledAction({body:{...Ax($),enabled:$.enabled??!0}})))}async list($){return Y(await this.client.scheduledAction.listScheduledActions({query:{include_events:$?.includeEvents}})).map((O)=>KO.from(this.client,O))}}class Fx{client;constructor($){this.client=$}byId($){return M$.byId(this.client,$)}create($){return M$.create(this.client,$)}forPullRequest($){return M$.forPullRequest(this.client,$)}search($,O){return M$.search(this.client,$,O)}}class Ex{client;constructor($){this.client=$}byId($){return S$.byId(this.client,$)}current(){return S$.current(this.client)}list(){return S$.list(this.client)}}class wx{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 qx{client;constructor($){this.client=$}byId($){return P.byId(this.client,$)}me(){return P.me(this.client)}async search($){let O=$.trim().toLocaleLowerCase();if(!O)throw Error("A person search needs a name or email.");let j=await this.client.contacts.getContacts();if(j.response?.status===404)return[];let{contacts:x}=Y(j),S=[...new Set(x)],G=[];for(let Z=0;Z<S.length;Z+=100){let X=S.slice(Z,Z+100),{names:K}=Y(await this.client.auth.getUserNamesWithEmail({body:{user_ids:X}})),L=new Map(K.map((Q)=>[Q.id,Q]));for(let Q of X){let J=L.get(Q)??{id:Q};if(`${[J.first_name,J.last_name].filter(Boolean).join(" ")} ${Q}`.toLocaleLowerCase().includes(O))G.push(P.fromName(this.client,J))}}return G}}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",($)=>P.byId(this.client,$));async scope(){let $=await this.detail.get();return $.workspace_id===$.created_by_user_id?"user":"team"}async update($){await this.mutate((O)=>O.storage.patchWebhook({path:{webhook_id:this.id},body:$}))}async rename($){await this.update({name:$})}async setUrl($){await this.update({endpoint_url:$})}async setFilters($){await this.update({filters:$})}async pause(){await this.update({status:"paused"})}async resume(){await this.update({status:"active"})}async delete(){await this.mutate(($)=>$.storage.deleteWebhook({path:{webhook_id:this.id}}))}async validate(){return this.mutate(($)=>$.storage.validateWebhook({path:{webhook_id:this.id}}))}}class fx{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 PO extends A{static byId($,O){return new PO($,O)}static from($,O){return new PO($,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",($)=>P.byId(this.client,$));async refresh(){return this.detail.clear(),await this.detail.get(),this}}class bx{client;constructor($){this.client=$}async account(){let{account:$}=Y(await this.client.storage.whatsappAccount());return $?PO.from(this.client,$):void 0}async chats(){return Y(await this.client.storage.whatsappChats()).chats.map(($)=>UO.from(this.client,$))}}function kx($){if("properties"in $.data)return $.data.properties;if($.tag==="calendarEvent")return $.data.extra.properties;return[]}function s1($,O,j){let x=[];for(let S of kx(O)){if(S.definition.data_type!=="TAG"||S.value?.type!=="SelectOption")continue;for(let G of S.value.value){let Z=j.get(G);if(Z&&!x.some((X)=>X.label===Z.label&&X.scope===Z.scope))x.push(Z)}}switch(O.tag){case"document":return{type:"document",id:O.data.id,entity:q.byId($,O.data.id),snapshot:O,tags:x,name:O.data.name,fileType:O.data.fileType,subType:O.data.subType?.type};case"chat":return{type:"ai_chat",id:O.data.id,entity:G$.byId($,O.data.id),snapshot:O,tags:x,name:O.data.name};case"project":return{type:"project",id:O.data.id,entity:n.byId($,O.data.id),snapshot:O,tags:x,name:O.data.name};case"emailThread":return{type:"email",id:O.data.id,entity:U$.byId($,O.data.id),snapshot:O,tags:x,subject:O.data.name,snippet:O.data.snippet,senderName:O.data.senderName,senderEmail:O.data.senderEmail,inboxVisible:O.data.inboxVisible,isRead:O.data.isRead,isDraft:O.data.isDraft};case"channel":return{type:"channel",id:O.data.channel.id,entity:b.byId($,O.data.channel.id),snapshot:O,tags:x,name:O.data.channel.name};case"channelThread":return{type:"channel_thread",id:O.data.id,entity:new h$($,O.data.channel_id,O.data.id),snapshot:O,tags:x,channelId:O.data.channel_id};case"call":return{type:"call",id:O.data.callId,entity:Q$.byId($,O.data.callId),snapshot:O,tags:x,createdBy:O.data.createdBy};case"calendarEvent":return{type:"calendar_event",id:O.data.id,entity:$$.byId($,O.data.id),snapshot:O,tags:x,title:O.data.title,status:O.data.status,location:O.data.location,conferenceUrl:O.data.conferenceUrl,conferenceProvider:O.data.conferenceProvider,time:O.data.time};case"foreignEntity":return{type:"foreign_entity",id:O.data.id,entity:ZO.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 t1="00000000-0000-0000-0000-000000000000",gx={document:["df","id"],project:["pf","pid"],ai_chat:["cf","cid"],email:["ef","ThreadId"],channel:["chanf","ChannelId"],channel_thread:["cthf","ThreadId"],call:["callf","CallId"],calendar_event:["calf","id"],foreign_entity:["fef","id"]},Fj=($)=>$.replace(/[A-Z]/g,(O)=>O.toLowerCase()),e1=($,O)=>$==null?O:{"&":[$,O]};function yx($,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,G]=x;if(S==="l")return;if(S==="!"){yx(G,`${O}.!`);return}if(S!=="&"&&S!=="|")throw Error(`Invalid workspace ${O}: use l, &, | or !.`);if(!Array.isArray(G)||G.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.`);G.forEach((Z,X)=>{yx(Z,`${O}.${S}[${X}]`)})}class Ej{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,G,Z]of[["sortBy",$.sortBy,["recently_viewed","recently_updated","recently_created"]],["emailPreset",$.emailPreset,["signal"]],["tagsMatch",$.tagsMatch,["any","all"]]])if(G!==void 0&&!Z.includes(G))throw Error(`Invalid workspace ${S}: ${G}`);if($.includeTypes!==void 0&&(!Array.isArray($.includeTypes)||$.includeTypes.some((S)=>!Object.hasOwn(gx,S))))throw Error(`Invalid workspace includeTypes. Supported values: ${Object.keys(gx).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)yx($[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:t1}},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()),G=S.filter((X)=>Fj(X.email_address)===Fj(j)),Z=G[0];if(!Z)throw Error(`No connected inbox matches "${j}". Connected inboxes: ${S.map((X)=>X.email_address).join(", ")}.`);if(G.length>1)throw Error(`Multiple connected inboxes match "${j}"; cannot pick one.`);O.ef=e1(O.ef,{l:{Owner:Z.id}})}let x=$.includeTypes??($.emailPreset==="signal"?["email"]:void 0);if(x?.length){for(let[S,[G,Z]]of Object.entries(gx))if(!x.includes(S))O[G]={l:{[Z]:t1}}}if($.tags?.length){let S=(await this.sets()).flatMap((K)=>{let L=K.definition;if(!L)return[];return K.options.flatMap((Q)=>Q.value.type==="string"?[{id:Q.id,definitionId:L.id,label:Q.value.value,scope:K.scope==="user"?"personal":"team"}]:[])}),G=new Map;for(let K of $.tags){let L=S.filter((Q)=>Fj(Q.label)===Fj(K.label.trim())&&(!K.scope||Q.scope===K.scope));if(!L.length)throw Error(`Unknown tag "${K.label}". Available tags: ${S.map((Q)=>`${Q.label} (${Q.scope})`).join(", ")}.`);if($.tagsMatch==="all"&&L.length>1)throw Error(`Tag "${K.label}" is ambiguous; specify personal or team scope.`);for(let Q of L)G.set(Q.id,Q)}let X=[...G.values()].map((K)=>({l:{pd:K.definitionId,v:{so:K.id}}})).reduce((K,L)=>K===void 0?L:{[$.tagsMatch==="all"?"&":"|"]:[K,L]},void 0);O.propf=e1(O.propf,X)}return O}}class vx{client;constructor($){this.client=$}async page($={}){let O=new Ej(this.client);return this.fetch(O,await O.body($),$.cursor)}async*list($={}){let O=new Ej(this.client),j=await O.body($);yield*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})),G=x.items.some((Z)=>kx(Z).some((X)=>X.definition.data_type==="TAG"))?await $.tagMap():new Map;return{items:x.items.map((Z)=>s1(this.client,Z,G)),nextCursor:x.next_cursor,hasMore:x.next_cursor!=null}}}function o1({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:G,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:K,url:L,...Q}){let J,I=K??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=G??3000,B=0,T=Q.signal??new AbortController().signal;while(!0){if(T.aborted)break;B++;let C=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)C.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:C,signal:T},_=new Request(L,D);if($)_=await $(L,D);let N=await(Q.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{H.cancel()}catch{}};T.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await H.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
+async function 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,G=async()=>{while(S<$.length){let X=S;S+=1,x[X]=await j($[X])}},Z=Array.from({length:Math.min(O,$.length)},G);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)}class f extends Error{constructor($){super($);this.name="MacroError"}}class QO extends f{status;data;constructor($,O){super(`Macro API error ${$}`);this.status=$;this.data=O;this.name="MacroApiError"}}class E extends f{constructor($){super($);this.name="MacroNotFoundError"}}function Y($){if($.error!==void 0)throw new QO($.response?.status??0,$.error);return $.data}class 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 I$ 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 X$ extends I${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 k6={"<":"\\u003c",">":"\\u003e","&":"\\u0026"};function i$($,O){let j=JSON.stringify(O).replace(/[<>&]/g,(x)=>k6[x]??x);return`<${$}>${j}</${$}>`}function g6($){return typeof $==="object"&&$!==null&&typeof $.toMention==="function"}var y6={toMention:()=>({tag:i$("m-group-mention",{groupAlias:"here"}),mention:{entity_type:"group",entity_id:"here"}})};function v6($,...O){let j="",x=[];for(let[S,G]of $.entries()){j+=G;let Z=O[S];if(Z===void 0)continue;if(g6(Z)){let X=Z.toMention();j+=X.tag,x.push(X.mention)}else j+=String(Z)}return{content:j,mentions:h6(x)}}function h6($){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:v0($)}))}}function v0($){let{channels:O,team:j,host:x,autoAcceptPermissions:S,avatarUrl:G,channelScope:Z,defaultModel:X,isCoding:K,...L}=$;return{...L,channel_ids:O?.map((Q)=>Q.id),team_id:j?.id,harness_id:x?.id,auto_accept_permissions:S,avatar_url:G,channel_scope:Z,default_model:X,is_coding:K}}async function Bj($,O,j){let{channelId:x,thread:S}=m6(O);if(await u6($)){let{id:Z}=Y(await $.storage.entityMessageCreate({path:{parent_type:"channel",parent_id:x},body:{content:j.content,mentions:j.mentions,attachments:[],thread_id:S?.rootId??null,nonce:crypto.randomUUID()}}));return Z}if(S)throw new f("a user-owned bot can only post via the channel webhook endpoint, which "+"does not support threads — use a team-owned bot, or requestedAs(user), "+"to reply in a thread");let{message_id:G}=Y(await $.storage.postChannelBotWebhook({path:{channel_id:x},body:{content:j.content},headers:{"x-macro-bot-scope":"user"}}));return G}function m6($){return"rootId"in $?{channelId:$.channelId,thread:$}:{channelId:$.id}}async function u6($){if($.authConfig.type!=="bot"||$.hasActingUser())return!0;let{owner:O}=await $.selfBot();return O?.type==="team"}class m${client;channelId;rootId;constructor($,O,j){this.client=$;this.channelId=O;this.rootId=j}toJSON(){return{channelId:this.channelId,rootId:this.rootId}}channel(){return b.byId(this.client,this.channelId)}root(){return e.byId(this.client,this.channelId,this.rootId)}async replies(){let{replies:$}=Y(await this.client.storage.entityMessageGetThread({path:{parent_type:"channel",parent_id:this.channelId,id:this.rootId}}));return $.map((O)=>e.from(this.client,this.channelId,O))}async reply($){let O=await Bj(this.client,this,O$($));return e.byId(this.client,this.channelId,O)}}class e extends I${channelId;mentions;entityType="channel_message";constructor($,O,j,x=[],S){super($,j,S);this.channelId=O;this.mentions=x}get path(){return{parent_type:"channel",parent_id:this.channelId,id:this.id}}async fetch(){return Y(await this.client.storage.entityMessageGetMessage({path:this.path}))}static byId($,O,j,x=[]){return new e($,O,j,x)}static from($,O,j){return new e($,O,j.id,j.mentions,j)}content=this.field("content");createdAt=this.field("created_at");editedAt=this.field("edited_at");updatedAt=this.field("updated_at");async author(){return P.byId(this.client,(await this.detail.get()).sender_id)}channel(){return b.byId(this.client,this.channelId)}thread(){return new m$(this.client,this.channelId,this.id)}async react($){return await this.mutate((O)=>O.storage.entityMessageReact({path:this.path,body:{add:!0,emoji:$}})),this}async unreact($){return await this.mutate((O)=>O.storage.entityMessageReact({path:this.path,body:{add:!1,emoji:$}})),this}async edit($){let{content:O,mentions:j}=O$($);return await this.mutate((x)=>x.storage.entityMessageEdit({path:this.path,body:{content:O,mentions:j}})),this}async delete(){await this.mutate(($)=>$.storage.entityMessageDeleteMessage({path:this.path}))}async reply($){return this.thread().reply($)}}class Lj{client;channel;record;constructor($,O,j){this.client=$;this.channel=O;this.record=j}agent(){return T$.byId(this.client,this.record.botId)}sessions(){return this.record.sessions.map(($)=>({session:l.byId(this.client,$.sessionId),isCurrent:$.isCurrent,createdAt:$.createdAt}))}turns(){return this.record.turns.map(($)=>new h0(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 h0{client;conversation;record;constructor($,O,j){this.client=$;this.conversation=O;this.record=j}source(){return e.byId(this.client,this.conversation.channel.id,this.record.sourceMessageId)}session(){return l.byId(this.client,this.record.sessionId)}async retry($){Y(await this.client.agentHarness.retryAgentConversationTurn({path:{channel_id:this.conversation.channel.id,bot_id:this.conversation.agent().id,source:this.record.sourceMessageId},body:{actionId:$}}))}toJSON(){return{channelId:this.conversation.channel.id,sourceMessageId:this.record.sourceMessageId}}}class 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 w$($,O,j,x){for(let G of[...x?.messages??[],...x?.around?[x.around]:[]]){let Z="channelId"in G?{type:"channel",id:G.channelId}:("documentId"in G)?{type:"document",id:G.documentId}:("callId"in G)?{type:"call",id:G.callId}:G.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((G)=>G.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((G)=>{if(G.type==="activity")return{type:"activity",activity:{...G.activity,actor:P.byId($,G.activity.actor_id)}};return{type:"message",message:j(G.message)}}),nextCursor:S.next_cursor??void 0,previousCursor:S.previous_cursor??void 0}}var c6=50;function x$($){let{filters:O,type:j,make:x,includeCrm:S}=$;return(G,Z,X)=>{let K=X?.searchOn??"name_content",L=X?.pageSize??c6;return c(async(Q)=>{let{results:J,next_cursor:I}=Y(await G.search.unifiedSearch({body:{query:Z,match_type:"partial",search_on:K,...O?{filters:O}:{},...S?{include_crm:!0}:{}},query:{page_size:L,...Q?{cursor:Q}:{}}}));return{items:J.filter((W)=>W.type===j).map((W)=>x(G,W)),nextCursor:I}})}}class JO{client;channel;record;constructor($,O,j){this.client=$;this.channel=O;this.record=j}get id(){return this.record.id}user(){return P.byId(this.client,this.record.user_id)}createdAt(){return this.record.created_at}async recordInteraction($){return new JO(this.client,this.channel,Y(await this.client.storage.postActivity({body:{activity_type:$,channel_id:this.channel.id}})))}toJSON(){return this.record}}class b extends X${async recordActivity($){return new JO(this.client,this,Y(await this.client.storage.postActivity({body:{activity_type:$,channel_id:this.id}})))}async setPicture($){await this.mutate((O)=>O.storage.setChannelPicture({path:{channel_id:this.id},body:{profile_picture_id:$?.id??null}}))}messageThreadById($){return L$.byId(this.client,{type:"channel",entity:this},$)}timelinePage($){return w$(this.client,{type:"channel",entity:this},(O)=>e.from(this.client,this.id,O),$)}async agentConversations(){return Y(await this.client.agentHarness.listAgentConversations({path:{channel_id:this.id}})).conversations.map(($)=>new Lj(this.client,this,$))}entityType="channel";propertyEntityType="CHANNEL";async fetch(){return Y(await this.client.storage.getChannel({path:{channel_id:this.id}}))}static byId($,O){return new b($,O)}static async dm($,O){let{channel_id:j}=Y(await $.storage.getOrCreateDm({body:{recipient_id:O.id}}));return new b($,j)}static async private($,O){let{channel_id:j}=Y(await $.storage.getOrCreatePrivate({body:{recipients:O.map((x)=>x.id)}}));return new b($,j)}static async create($,O){let{id:j}=Y(await $.storage.createChannel({body:{channel_type:O.type,name:O.name??null,participants:(O.participants??[]).map((x)=>x.id),team_id:O.team?.id??null}}));return new b($,j)}name=this.field("channel_name");type=this.field("channel_type");async send($,O){let j=await Bj(this.client,O?.thread??this,O$($));return e.byId(this.client,this.id,j)}messages($){return this.timeline({limit:$?.pageSize})}messagesAfter($,O){return this.timeline({activity_after:$ instanceof Date?$.toISOString():$,limit:O?.pageSize})}timeline($){return c(async(O)=>{let j=Y(await this.client.storage.messageTimeline({path:{parent_type:"channel",parent_id:this.id},query:{selection:JSON.stringify({...$,cursor:O})}}));return{items:j.items.map((x)=>e.from(this.client,this.id,x)),nextCursor:j.next_cursor}})}message($){return e.byId(this.client,this.id,$)}async rename($){await this.mutate((O)=>O.storage.patchChannel({path:{channel_id:this.id},body:{channel_name:$}}))}async delete(){await this.mutate(($)=>$.storage.deleteChannel({path:{channel_id:this.id}}))}async join(){await this.mutate(($)=>$.storage.joinChannel({path:{channel_id:this.id}}))}async joinCode(){let{join_code:$}=Y(await this.client.storage.getChannelJoinLink({path:{channel_id:this.id}}));return $}async leave(){await this.mutate(($)=>$.storage.leaveChannel({path:{channel_id:this.id}}))}async participants(){return Y(await this.client.storage.getChannelParticipants({path:{channel_id:this.id}}))}async addParticipants($){await this.mutate((O)=>O.storage.addParticipants({path:{channel_id:this.id},body:{participants:$.map((j)=>j.id)}}))}async removeParticipants($){await this.mutate((O)=>O.storage.removeParticipants({path:{channel_id:this.id},body:{participants:$.map((j)=>j.id)}}))}async typing($,O){Y(await this.client.storage.entityMessageTyping({path:{parent_type:"channel",parent_id:this.id},body:{active:$==="start",thread_id:O?.thread?.rootId??null}}))}attachments($){return c(async(O)=>{let j=Y(await this.client.storage.getChannelAttachments({path:{channel_id:this.id},query:{...$?.pageSize?{limit:$.pageSize}:{},...$?.type?{attachment_type:$.type}:{},...O?{cursor:O}:{}}}));return{items:j.items,nextCursor:j.next_cursor}})}webUrl(){return`${this.client.webAppUrl}/app/channel/${this.id}`}static search=x$({type:"channel",make:($,O)=>new b($,O.channel_id)})}class P extends X${entityType="user";propertyEntityType="USER";async fetch(){let{names:$}=Y(await this.client.auth.getUserNamesWithEmail({body:{user_ids:[this.id]}})),O=$.find((j)=>j.id===this.id);if(!O)throw new E(`user ${this.id} not found`);return O}static byId($,O){return new P($,O)}static fromName($,O){return new P($,O.id,O)}static async me($){let{user_id:O}=Y(await $.auth.getUserInfo());return new P($,O)}async name(){let $=await this.detail.get();return[$.first_name,$.last_name].filter(Boolean).join(" ")||void 0}email(){let $=this.id.startsWith("macro|")?this.id.slice(6):void 0;return $?.includes("@")?$:void 0}dm(){return b.dm(this.client,this)}toMention(){return{tag:i$("m-user-mention",{userId:this.id}),mention:{entity_type:"user",entity_id:this.id}}}}class o{client;entityType;entity;constructor($,O,j){this.client=$;this.entityType=O;this.entity=j}get path(){return{entity_type:this.entityType,entity_id:this.entity.id}}async state($){let O=Y(await this.client.storage.accessRequestsState({path:this.path,query:{offset:$}}));return{accessLevel:O.accessLevel??void 0,canReview:O.canReview,owner:O.owner?P.byId(this.client,O.owner):void 0,pendingCount:O.pendingCount,supportedLevels:O.supportedLevels,nextOffset:O.nextOffset??void 0,mine:O.mine?TO.from(this.client,this,O.mine):void 0,requests:O.requests.map((j)=>TO.from(this.client,this,j))}}async submit($,O){return TO.from(this.client,this,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:P.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 TO extends A{access;resolvedRecord;constructor($,O,j){super($,j.id,j);this.access=O}static from($,O,j){return new TO($,O,j)}async fetch(){if(this.resolvedRecord)return this.resolvedRecord;let $;do{let O=await this.access.state($),j=[O.mine,...O.requests].find((x)=>x?.id===this.id);if(j)return j.detail.get();$=O.nextOffset}while($!==void 0);throw new E(`Access request ${this.id} is unavailable`)}revision=this.field("revision");status=this.field("status");requestedLevel=this.field("requestedLevel");requester=this.mappedField("requesterId",($)=>P.byId(this.client,$));async resolve($){this.resolvedRecord=await this.access.resolve(this,{revision:await this.revision(),grantedLevel:$}),this.detail.clear()}}function n$($){return{...$,channelSharePermissions:$.channelSharePermissions===void 0||$.channelSharePermissions===null?$.channelSharePermissions:$.channelSharePermissions.map((O)=>({channelId:O.channel.id,accessLevel:O.accessLevel,operation:O.operation}))}}class N$ extends 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,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(),x))}async fetch(){return Y(await this.client.agentHarness.getSessionReview({path:{session_id:this.parent.id,review_id:this.id}}))}title=this.field("title");kind=this.field("kind");session(){return this.parent}async reference(){return{kind:await this.kind(),id:this.id}}async items(){return(await this.detail.get()).items.map(($)=>new m0($,{edit:(O)=>this.decide({action:"edit",item:$.id,draft:O}),submit:()=>this.decide({action:"submit",items:[$.id]}),dismiss:()=>this.decide({action:"dismiss",items:[$.id]})}))}async refresh(){return this.detail.clear(),await this.detail.get(),this}async submitAll(){await this.decide({action:"submit",items:[]})}async dismissAll(){await this.decide({action:"dismiss",items:[]})}async decide($){let O=(await this.detail.get()).revision;await this.mutate((j)=>j.agentHarness.decideSessionReview({path:{session_id:this.parent.id,review_id:this.id},body:{...$,revision:O}}))}}class m0{snapshot;actions;constructor($,O){this.snapshot=$;this.actions=O}get id(){return this.snapshot.id}get status(){return this.snapshot.status}get draft(){return this.snapshot.draft}get result(){return this.snapshot.result}async edit($){await this.actions.edit($)}async submit(){await this.actions.submit()}async dismiss(){await this.actions.dismiss()}}class dO extends A{parent;constructor($,O,j){super($,O);this.parent=j}static byId($,O,j){return new dO($,j,O)}async fetch(){return Y(await this.client.agentHarness.getCodeExecution({path:{session_id:this.parent.id,execution_id:this.id}}))}reviews={create:($)=>N$.create(this.client,this,$),list:()=>N$.list(this.client,this)};session(){return this.parent}status=this.field("status");source=this.field("source");calls=this.field("calls");error=this.field("error");async result(){return(await this.detail.get()).result}async refresh(){return this.detail.clear(),await this.detail.get(),this}}class Nj{client;sessionId;dto;constructor($,O,j){this.client=$;this.sessionId=O;this.dto=j}static from($,O,j){return new Nj($,O,j)}get actionId(){return this.dto.actionId}get kind(){return this.dto.kind}get prompt(){return this.dto.prompt??void 0}get attachments(){return this.dto.attachments??[]}get actorUserId(){return this.dto.actorUserId??void 0}get createdAt(){return this.dto.createdAt}async edit($){return Y(await this.client.agentHarness.editQueuedAction({path:{session_id:this.sessionId,action_id:this.actionId},body:{prompt:$}})),this.dto={...this.dto,prompt:$},this}async steer(){Y(await this.client.agentHarness.steerQueuedAction({path:{session_id:this.sessionId,action_id:this.actionId}}))}async remove(){Y(await this.client.agentHarness.removeQueuedAction({path:{session_id:this.sessionId,action_id:this.actionId}}))}}class lO{client;session;id;constructor($,O,j){this.client=$;this.session=O;this.id=j}static byId($,O,j){return new lO($,O,j)}async answer($){return Y(await this.client.agentHarness.answerAgentSessionToolApproval({path:{session_id:this.session.id,approval_id:this.id},body:{answer:$}}))}toJSON(){return{id:this.id,sessionId:this.session.id}}}class l extends A{access=new o(this.client,"agent_session",this);toolApprovalById($){return lO.byId(this.client,this,$)}async sharePermissions(){return Y(await this.client.agentHarness.getAgentSessionPermissions({path:{session_id:this.id}}))}async updateSharePermissions($){return this.mutate((O)=>O.agentHarness.updateAgentSessionPermissions({path:{session_id:this.id},body:n$($)}))}static byId($,O){return new l($,O)}static async createManaged($,O){let{session:j}=Y(await $.agentHarness.createAgentSession({body:{prompt:O?.prompt,instructions:O?.instructions,model:O?.model,repoUrl:O?.repoUrl,repoBranch:O?.repoBranch}}));return new l($,j.id,j)}static async repositories($){let{repositories:O}=Y(await $.agentHarness.listAgentRepositories());return O.map((j)=>({url:j.url,defaultBranch:j.defaultBranch??void 0}))}static async repositoryBranches($,O){let{branches:j}=Y(await $.agentHarness.listAgentRepositoryBranches({query:{repoUrl:O}}));return j}static async chooseMode($,O){let{mode:j}=Y(await $.agentHarness.chooseAgentMode({body:{prompt:O}}));return j}async fetch(){return Y(await this.client.agentHarness.getAgentSession({path:{session_id:this.id}}))}name=this.field("name");isArchived=this.field("isArchived");model=this.field("model");harness=this.field("harness");repoUrl=this.field("repoUrl");workspace=this.field("workspace");instructions=this.field("instructions");status=this.field("status");sandboxSize=this.field("sandboxSize");createdAt=this.field("createdAt");modifiedAt=this.field("modifiedAt");static async forPullRequest($,O){let{sessionIds:j}=Y(await $.agentHarness.agentSessionsForPullRequest({body:{url:O}}));return j.map((x)=>l.byId($,x))}async pullRequests(){let{pullRequests:$}=Y(await this.client.agentHarness.listAgentSessionPullRequests({path:{session_id:this.id}}));return $.map((O)=>({githubKey:O.githubKey,url:O.url,source:O.source,linkedBy:O.linkedBy?P.byId(this.client,O.linkedBy):void 0,createdAt:O.createdAt}))}async linkPullRequest($){Y(await this.client.agentHarness.linkAgentSessionPullRequest({path:{session_id:this.id},body:{url:$}}))}async unlinkPullRequest($){Y(await this.client.agentHarness.unlinkAgentSessionPullRequest({path:{session_id:this.id},query:{url:$}}))}async rename($){await this.mutate((O)=>O.agentHarness.renameAgentSession({path:{session_id:this.id},body:{name:$}}))}async archive(){await this.setArchived(!0)}async unarchive(){await this.setArchived(!1)}async setArchived($){await this.mutate((O)=>O.agentHarness.setAgentSessionArchived({path:{session_id:this.id},body:{isArchived:$}}))}async setSandboxSize($){let{size:O}=await this.mutate((j)=>j.agentHarness.putAgentSessionSandboxSize({path:{session_id:this.id},body:{size:$}}));return O}static async defaultSandboxSize($){return Y(await $.agentHarness.getAgentSandboxSize()).size}static async setDefaultSandboxSize($,O){return Y(await $.agentHarness.putAgentSandboxSize({body:{size:O}})).size}static async codingPreferences($){return Y(await $.agentHarness.getAgentCodingPreferences())}static async setCodingPreferences($,O){return Y(await $.agentHarness.putAgentCodingPreferences({body:O}))}async control($){return this.mutate((O)=>O.agentHarness.controlAgentSession({path:{session_id:this.id},body:$}))}prompt($,O){return this.control({type:"prompt",prompt:$,...O&&O.length>0?{attachments:O}:{}})}async queue(){let{entries:$}=Y(await this.client.agentHarness.getAgentSessionQueue({path:{session_id:this.id}}));return $.map((O)=>Nj.from(this.client,this.id,O))}async changes(){return Y(await this.client.agentHarness.getAgentSessionChanges({path:{session_id:this.id}}))}async changesPatch(){return Y(await this.client.agentHarness.getAgentSessionChangesPatch({path:{session_id:this.id}})).patch}async refreshChanges(){return this.mutate(($)=>$.agentHarness.refreshAgentSessionChanges({path:{session_id:this.id}}))}async foldedLog(){let{bot:$,messages:O}=Y(await this.client.agentHarness.getAgentSessionFoldedLog({path:{session_id:this.id}}));return{bot:$,messages:O}}async log(){return Y(await this.client.agentHarness.getAgentSessionLog({path:{session_id:this.id}}))}reviews={create:($)=>N$.createForSession(this.client,this,$),byId:($)=>N$.byId(this.client,this,$)};codeExecutions={byId:($)=>dO.byId(this.client,this,$)};async delete(){await this.mutate(($)=>$.agentHarness.deleteAgentSession({path:{session_id:this.id}}))}}class u0{client;constructor($){this.client=$}byId($){return l.byId(this.client,$)}createManaged($){return l.createManaged(this.client,$)}chooseMode($){return l.chooseMode(this.client,$)}repositories(){return l.repositories(this.client)}repositoryBranches($){return l.repositoryBranches(this.client,$)}forPullRequest($){return l.forPullRequest(this.client,$)}defaultSandboxSize(){return l.defaultSandboxSize(this.client)}setDefaultSandboxSize($){return l.setDefaultSandboxSize(this.client,$)}codingPreferences(){return l.codingPreferences(this.client)}setCodingPreferences($){return l.setCodingPreferences(this.client,$)}}class c0{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:v0($)})))}}class d0{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 s$ extends A{static byId($,O){return new s$($,O)}static from($,O){return new s$($,O.id,{id:O.id,name:O.name,createdAt:O.createdAt})}async fetch(){let $=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 l0{client;constructor($){this.client=$}byId($){return s$.byId(this.client,$)}async list(){return Y(await this.client.storage.listUserApiKeys()).keys.map(($)=>s$.from(this.client,$))}async create($){let O=Y(await this.client.storage.createUserApiKey({body:{name:$}}));return{key:s$.from(this.client,O),secret:O.key}}async tokenForEmail($){return Y(await this.client.auth.macroApiToken({query:{email:$}}))}}class rO{client;constructor($){this.client=$}async me(){if(this.client.authConfig.type!=="bot")throw new f("bots.me() requires bot auth — a user API key has no bot identity");return Y(await this.client.storage.getSelfBot())}async channels(){if(this.client.authConfig.type!=="bot")throw new f("bots.channels() requires bot auth — a user API key has no bot identity");let $=await this.me();return Y(await this.client.storage.listBotChannels({path:{bot_id:$.id}}))}async myPrincipalId(){if(this.client.authConfig.type!=="bot")throw new f("bots.myPrincipalId() requires bot auth — a user API key has no bot identity");return this.client.myPrincipalId()}}class S$ extends 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 S$($,O)}static async current($){let O=Y(await $.auth.getTeam());if(!O)throw new E("caller has no current team");return new S$($,O.team.id,O.team)}static async list($){return Y(await $.auth.getUserTeams()).map((j)=>new S$($,j.id,j))}name=this.field("name");slug=this.field("slug");defaultLinkShare=this.field("default_link_share");owner=this.mappedField("owner_id",($)=>P.byId(this.client,$));async members(){let $=Y(await this.client.auth.getTeam());if(!$||$.team.id!==this.id)throw new f("members are only available for the current team (see Team.current)");return $.members.map((O)=>({user:P.byId(this.client,O.user_id),role:O.role}))}}class H$ 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 H$($,O)}static async list($){let{links:O}=Y(await $.email.listLinks());return O.map((j)=>new H$($,j.id,j))}emailAddress=this.field("email_address");provider=this.field("provider");isPrimary=this.field("is_primary");isSyncActive=this.field("is_sync_active");syncStatus=this.field("sync_status");needsReauth=this.field("needs_reauth");photoUrl=this.field("photo_url");async settingsOperations(){return Y(await this.client.email.mailboxSettingsOperations({headers:{"X-Email-Link-Id":this.id}}))}}class u$ extends 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 u$($,O)}static async list($){let{calendars:O}=Y(await $.calendar.listCalendars());return O.map((j)=>new u$($,j.id,j))}name=this.field("name");emailAddress=this.field("emailAddress");isPrimary=this.field("isPrimary");isWritable=this.field("isWritable");isSubscription=this.field("isSubscription");color=this.field("color");syncError=this.field("syncError");emailLink=this.mappedField("emailLinkId",($)=>H$.byId(this.client,$))}class pO{client;id;constructor($,O){this.client=$;this.id=O}async status(){return Y(await this.client.calendar.calendarReplacementStatus({path:{operation_id:this.id}}))}async confirm(){return Y(await this.client.calendar.confirmCalendarReplacement({path:{operation_id:this.id}}))}async discard(){Y(await this.client.calendar.discardCalendarReplacement({path:{operation_id:this.id}}))}}class $$ extends A{async notes($){return this.requireOwnOccurrence($),Y(await this.client.calendar.eventNotes({path:{event_id:this.id},query:{occurrenceKey:$.occurrenceKey}})).map((j)=>q$.fromRecord(this.client,this,$,j))}async linkNote($,O,j={}){return this.requireOwnOccurrence(O),Y(await this.client.calendar.linkEventNote({path:{event_id:this.id,document_id:$.id},query:{occurrenceKey:O.occurrenceKey},body:{teamId:j.team?.id??null}})),q$.forDocument(this.client,this,O,$)}requireOwnOccurrence($){if($.eventId!==this.id)throw new f("The occurrence belongs to a different event")}async fetch(){throw new f(`calendar event ${this.id} has no fetch-by-id endpoint; read the record returned by calendar.createEvent / event.update / event.rsvp instead`)}static byId($,O){return new $$($,O)}static fromRecord($,O){return new $$($,O.id,O)}title=this.field("title");description=this.field("description");location=this.field("location");time=this.field("time");status=this.field("status");attendees=this.field("attendees");transparency=this.field("transparency");isReadOnly=this.field("isReadOnly");recurrenceLines=this.field("recurrenceLines");guestPolicy=this.field("guestPolicy");viewerCan=this.field("viewerCan");calendar=this.mappedField("calendarId",($)=>$?u$.byId(this.client,$):void 0);record(){return this.detail.get()}async update($){let O=await this.mutate((j)=>j.calendar.updateCalendarEvent({path:{event_id:this.id},body:d6($)}));return $$.fromRecord(this.client,O)}async delete($={}){await this.mutate((O)=>O.calendar.deleteCalendarEvent({path:{event_id:this.id},query:{calendarId:$.calendar?.id,scope:$.scope,recurrenceId:$.recurrenceId,inbox:$.inbox}}))}async prepareReplacement($){let O=Y(await this.client.calendar.prepareCalendarReplacement({path:{event_id:this.id},body:{removeConference:$.removeConference,recurrenceId:$.recurrenceId,calendarId:$.calendar?.id}}));return new pO(this.client,O.operationId)}async providerUrl($={}){return Y(await this.client.calendar.calendarEventProviderUrl({path:{event_id:this.id},query:{recurrenceId:$.recurrenceId,calendarId:$.calendar?.id}})).url??void 0}async inviteGuests($){let O=await this.mutate((j)=>j.calendar.inviteCalendarEventGuests({path:{event_id:this.id},body:{guests:$.guests,scope:$.scope,recurrenceId:$.recurrenceId,calendarId:$.calendar?.id,inbox:$.inbox}}));return $$.fromRecord(this.client,O)}async addToCalendar($={}){let O=await this.mutate((j)=>j.calendar.copyCalendarEvent({path:{event_id:this.id},body:{calendarId:$.calendar?.id}}));return $$.fromRecord(this.client,O)}async ics(){return Y(await this.client.storage.eventIcs({path:{event_id:this.id}}))}async rsvp($){let O=await this.mutate((j)=>j.calendar.rsvpCalendarEvent({path:{event_id:this.id},body:{response:$.response,scope:$.scope,recurrenceId:$.recurrenceId,calendarId:$.calendar?.id}}));return $$.fromRecord(this.client,O)}}function d6($){return{title:$.title,description:$.description,location:$.location,time:$.time,attendees:$.attendees,recurrenceLines:$.recurrenceLines,visibility:$.visibility,transparency:$.transparency,reminders:$.reminders,conference:$.conference,outOfOffice:$.outOfOffice,guestPolicy:$.guestPolicy,scope:$.scope,recurrenceId:$.recurrenceId,calendarId:$.calendar?.id,inbox:$.inbox}}class q$ extends A{event;occurrence;fromDocument;constructor($,O,j,x,S,G=!1){super($,x.id,S);this.event=O;this.occurrence=j;this.fromDocument=G;if(j.eventId!==O.id)throw new f("Choose an occurrence belonging to this event")}static fromDocumentLink($,O,j){return new q$($,$$.byId($,j.eventId),j,O,{documentId:O.id,name:j.documentName,team:j.team,canManage:!0},!0)}static forDocument($,O,j,x){return new q$($,O,j,x)}static fromRecord($,O,j,x){return new q$($,O,j,q.byId($,x.documentId),x)}async fetch(){if(this.fromDocument){let x=Y(await this.client.calendar.documentNoteLinks({path:{document_id:this.id}})).find((S)=>S.eventId===this.event.id&&S.occurrenceKey===this.occurrence.occurrenceKey);if(!x)throw new E("This meeting link has been removed");return{documentId:this.id,name:x.documentName,team:x.team,canManage:!0}}let O=Y(await this.client.calendar.eventNotes({path:{event_id:this.event.id},query:{occurrenceKey:this.occurrence.occurrenceKey}})).find((j)=>j.documentId===this.id);if(!O)throw new E("This document is no longer linked to the meeting");return O}document=this.mappedField("documentId",($)=>q.byId(this.client,$));name=this.field("name");team=this.mappedField("team",($)=>$?S$.byId(this.client,$.id):void 0);canManage=this.field("canManage");async setTeam($){await this.mutate((O)=>O.calendar.linkEventNote({path:{event_id:this.event.id,document_id:this.id},query:{occurrenceKey:this.occurrence.occurrenceKey},body:{teamId:$?.id??null}}))}async unlink(){await this.mutate(($)=>$.calendar.unlinkEventNote({path:{event_id:this.event.id,document_id:this.id},query:{occurrenceKey:this.occurrence.occurrenceKey}}))}}class n extends X${async sharePermissions(){return Y(await this.client.storage.getProjectPermissionsV2({path:{id:this.id}}))}async accessLevel(){return Y(await this.client.storage.getProjectUserAccessLevel({path:{id:this.id}}))}access=new o(this.client,"project",this);entityType="project";propertyEntityType="PROJECT";async fetch(){let{data:$}=Y(await this.client.storage.getProjectHandler({path:{id:this.id}}));return $.projectMetadata}static byId($,O){return new n($,O)}static async create($,O){let{data:j}=Y(await $.storage.createProjectHandler({body:{name:O.name,projectParentId:O.parent?.id??null}}));return new n($,j.id,j)}name=this.field("name");parent=this.mappedField("parentId",($)=>$?n.byId(this.client,$):void 0);createdAt=this.field("createdAt");async items(){let{data:$}=Y(await this.client.storage.getProjectContentHandler({path:{id:this.id}}));return $.map((O)=>O.item)}async rename($){await this.mutate((O)=>O.storage.editProjectV2({path:{id:this.id},body:{name:$}}))}async delete($){await this.mutate((O)=>$?.permanent?O.storage.permanentlyDeleteProject({path:{id:this.id}}):O.storage.deleteProjectHandler({path:{id:this.id}}))}async restore(){await this.mutate(($)=>$.storage.revertDeleteProject({path:{id:this.id}}))}static search=x$({filters:{project_filters:{}},type:"project",make:($,O)=>new n($,O.id)})}class VO extends 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 c$ extends A{documentId;constructor($,O,j,x){super($,j,x);this.documentId=O}get path(){return{parent_type:"document",parent_id:this.documentId,id:this.id}}async fetch(){return Y(await this.client.storage.entityMessageGetMessage({path:this.path}))}static byId($,O,j){return new c$($,O,j)}static from($,O,j){return new c$($,O,j.id,j)}text=this.field("content");createdAt=this.field("created_at");updatedAt=this.field("updated_at");async threadId(){return(await this.detail.get()).thread_id??this.id}document(){return q.byId(this.client,this.documentId)}async author(){return P.byId(this.client,(await this.detail.get()).sender_id)}async reply($){return this.document().comment($,{threadId:await this.threadId()})}async edit($){let{content:O,mentions:j}=O$($);return await this.mutate((x)=>x.storage.entityMessageEdit({path:this.path,body:{content:O,mentions:j}})),this}async delete(){await this.mutate(($)=>$.storage.entityMessageDeleteMessage({path:this.path}))}}class aO{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 aO($,O,j)}read(){return this.detail.get()}toJSON(){return{id:this.id,documentId:this.document.id}}}var l6=8;class q extends X${async meetingNotes(){return Y(await this.client.calendar.documentNoteLinks({path:{document_id:this.id}})).map((O)=>({note:q$.fromDocumentLink(this.client,this,O),eventTitle:O.eventTitle}))}async anchors(){return Y(await this.client.storage.getDocumentAnchors({path:{document_id:this.id}})).data.map(($)=>VO.from(this.client,this,$))}async createHighlight($){return VO.from(this.client,this,Y(await this.client.storage.createAnchor({path:{document_id:this.id},body:{...$,fileType:"pdf",anchorType:"highlight"}})))}version($){return aO.byId(this.client,this,$)}async sharePermissions(){return Y(await this.client.storage.getDocumentPermissionsV2({path:{document_id:this.id}})).documentPermissions}async permissionsToken(){return Y(await this.client.storage.getDocumentPermissionsToken({path:{document_id:this.id}})).token}async prepareSave($){return Y(await this.client.storage.presaveDocumentHandler({path:{document_id:this.id},body:{newBom:$}})).data}async save($){return(await this.mutate((O)=>O.storage.saveDocumentHandler({path:{document_id:this.id},body:$}))).data}async simpleSave(){return(await this.mutate(($)=>$.storage.simpleSave({path:{document_id:this.id}}))).data}messageThreadById($){return L$.byId(this.client,{type:"document",entity:this},$)}timelinePage($){return w$(this.client,{type:"document",entity:this},(O)=>c$.from(this.client,this.id,O),$)}access=new o(this.client,"document",this);async fetch(){let{data:$}=Y(await this.client.storage.getDocument({path:{document_id:this.id}}));return $.documentMetadata}static byId($,O){return new q($,O)}static async create($,O){let{documentId:j}=Y(await $.storage.createMarkdownHandler({body:{documentName:O.name,markdown:O.markdown??null,projectId:O.project?.id??null}}));return new q($,j)}static async createSnippet($,O){let{documentId:j}=Y(await $.storage.createSnippetHandler({body:{snippetName:O.name,markdown:O.markdown??null,projectId:O.project?.id??null}}));return new q($,j)}static async createSkill($,O){let{documentId:j}=Y(await $.storage.createSkillHandler({body:{skillName:O.name,markdown:O.markdown??null,projectId:O.project?.id??null}}));return new q($,j)}static recent($,O){let j=O?.pageSize??50;return c(async(x)=>{let S=Y(await $.storage.getUserDocumentsHandler({query:{limit:j,offset:x?Number(x):0,...O?.fileType!==void 0?{file_type:O.fileType}:{}}})),G=S.data?.next_offset;return{items:(S.data?.documents??[]).map((Z)=>new q($,Z.documentId)),nextCursor:G!=null?String(G):null}})}static async recentlyDeleted($){let{data:O}=Y(await $.storage.recentlyDeleted({}));return O.items.filter((j)=>j.type==="document").map((j)=>new q($,j.id))}entityType="document";propertyEntityType="DOCUMENT";name=this.field("documentName");fileType=this.field("fileType");project=this.mappedField("projectId",($)=>$?n.byId(this.client,$):void 0);owner=this.mappedField("owner",($)=>P.byId(this.client,$));branchedFrom=this.mappedField("branchedFromId",($)=>$?q.byId(this.client,$):void 0);createdAt=this.field("createdAt");updatedAt=this.field("updatedAt");deletedAt=this.field("deletedAt");async content(){let{text:$}=Y(await this.client.storage.getDocumentTextContent({path:{document_id:this.id}}));if($!==null)return $;let{presigned_url:O}=Y(await this.client.storage.exportDocument({path:{document_id:this.id}})),j=await fetch(O);if(!j.ok)throw new QO(j.status,{message:"failed to download document content"});return j.text()}async rename($){await this.mutate((O)=>O.storage.editDocument({path:{document_id:this.id},body:{documentName:$}}))}async move($){await this.mutate((O)=>O.storage.editDocument({path:{document_id:this.id},body:{projectId:$?.id??""}}))}async delete($){await this.mutate((O)=>$?.permanent?O.storage.permanentlyDeleteDocument({path:{document_id:this.id}}):O.storage.deleteDocument({path:{document_id:this.id}}))}async restore(){await this.mutate(($)=>$.storage.revertDeleteDocument({path:{document_id:this.id}}))}async copy($){let{data:O}=Y(await this.client.storage.copyDocument({path:{document_id:this.id},query:$.versionId!==void 0?{version_id:$.versionId}:void 0,body:{documentName:$.name}}));return new q(this.client,O.documentMetadata.documentId)}async comments(){let $={parent_type:"document",parent_id:this.id},O=c(async(x)=>{let S=Y(await this.client.storage.messageTimeline({path:$,query:{selection:JSON.stringify({limit:100,cursor:x})}}));return{items:S.items,nextCursor:S.next_cursor}}),j=[];for await(let x of O)j.push(x);return cO(j,l6,async(x)=>{let{state:S,root:G,replies:Z}=Y(await this.client.storage.entityMessageGetThread({path:{...$,id:x.id}}));return{thread:S,comments:[G,...Z].map((X)=>c$.from(this.client,this.id,X))}})}async comment($,O){let j=await this.mutate((x)=>x.storage.entityMessageCreate({path:{parent_type:"document",parent_id:this.id},body:{...O$($),thread_id:O?.threadId??null}}));return c$.from(this.client,this.id,j)}async shortId(){return Y(await this.client.storage.getDocumentShortId({path:{document_id:this.id}}))}async teamShare(){return Y(await this.client.storage.getDocumentTeamShare({path:{document_id:this.id}}))}async setTeamShare($){await this.mutate((O)=>O.storage.setDocumentTeamShare({path:{document_id:this.id},body:{shareWithTeam:$}}))}async githubPullRequests(){let{pullRequests:$}=Y(await this.client.storage.getDocumentGithubPullRequests({path:{document_id:this.id}}));return $}async branchName(){let{branchName:$}=Y(await this.client.storage.getDocumentBranchName({path:{document_id:this.id}}));return $}webUrl(){return`${this.client.webAppUrl}/app/md/${this.id}`}static search=x$({filters:{document_filters:{}},type:"document",make:($,O)=>new q($,O.document_id)});toMention(){let $=this.detail.peek();return{tag:i$("m-document-mention",{documentId:this.id,documentName:$?.documentName??"",blockName:$?.fileType??"md"}),mention:{entity_type:"document",entity_id:this.id}}}}class r0{client;async noteDocuments($=""){let O=Y(await this.client.calendar.noteDocuments({query:{query:$}}));return{documents:O.documents.map((j)=>({document:q.byId(this.client,j.documentId),name:j.name})),teams:O.teams.map((j)=>({team:S$.byId(this.client,j.id),name:j.name}))}}async availabilityCalendars(){return Y(await this.client.calendar.getAvailabilityCalendars()).calendars.map(($)=>({calendar:u$.byId(this.client,$.calendarId),name:$.name,isPrimary:$.isPrimary,contributesToAvailability:$.contributesToAvailability}))}async teamSharing(){return Y(await this.client.calendar.getTeamSharing()).sharing}async setTeamSharing($){return Y(await this.client.calendar.setTeamSharing({body:{sharing:$}})).sharing}occurrences($){let O;return c(async(j)=>{let x=Y(await this.client.storage.listOccurrences({query:{...$,cursor:j}}));O??=p6(this.client);let S=await O;return{items:x.items.map((G)=>({event:$$.fromRecord(this.client,G.event),occurrence:G.occurrence,inbox:G.event.calendarId?S.get(G.event.calendarId):void 0,role:a6(G.event)})),nextCursor:x.nextCursor}})}async teamPage($){let O=Y(await this.client.storage.listTeamCalendar({query:$}));return{items:O.items.map(({ownerId:j,...x})=>({...x,owner:P.byId(this.client,j)})),members:O.members.map((j)=>({user:P.byId(this.client,j.userId),sharing:j.sharing,coverage:j.coverage})),nextCursor:O.nextCursor??void 0}}async teamOutOfOffice($){let O=Y(await this.client.storage.listTeamOutOfOffice({query:$}));return{items:O.items.map((j)=>({event:$$.byId(this.client,j.eventId),owner:P.byId(this.client,j.ownerId),occurrenceKey:j.occurrenceKey,time:j.time,title:j.title??void 0})),hasMore:O.hasMore}}constructor($){this.client=$}calendars(){return u$.list(this.client)}calendar($){return u$.byId(this.client,$)}event($){return $$.byId(this.client,$)}replacement($){return new pO(this.client,$)}async createEvent($){let O=Y(await this.client.calendar.createCalendarEvent({body:r6($)}));return $$.fromRecord(this.client,O)}}function r6($){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 p6($){let{calendars:O}=Y(await $.calendar.listCalendars());return new Map(O.map((j)=>[j.id,j.emailAddress]))}function a6($){let O=$.attendees.find((j)=>j.isSelf);if($.viewerCan.organize||O?.isOrganizer)return"organizer";return O?"guest":void 0}class R$ extends A{lookupToken;constructor($,O,j){super($,O,j);this.lookupToken=j?.shareToken}static byId($,O){return new R$($,O)}static from($,O){return new R$($,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",($)=>$?Q$.byId(this.client,$):void 0);async update($){await this.mutate((O)=>O.storage.meetingUpdate({path:{meeting_id:this.id},body:$}))}async cancel(){await this.mutate(($)=>$.storage.meetingCancel({path:{meeting_id:this.id}}))}async invitePermissions(){return Y(await this.client.storage.meetingInvitePermissions({path:{token:(await this.detail.get()).shareToken}}))}async invite($){Y(await this.client.storage.meetingInvite({path:{token:(await this.detail.get()).shareToken},body:{email:$}}))}async inviteUsers($){Y(await this.client.storage.meetingInviteUsers({path:{token:(await this.detail.get()).shareToken},body:{userIds:$.map((O)=>O.id)}}))}async webUrl(){return`${this.client.webAppUrl}/app/meet/join/${encodeURIComponent((await this.detail.get()).shareToken)}`}}class d$ extends 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 d$($,O,j)}static from($,O,j){return new d$($,O,j.id,j)}content=this.field("content");createdAt=this.field("created_at");updatedAt=this.field("updated_at");call(){return Q$.byId(this.client,this.callId)}async author(){return P.byId(this.client,(await this.detail.get()).sender_id)}async reply($){let O=Y(await this.client.storage.entityMessageCreate({path:{parent_type:"call",parent_id:this.callId},body:{...O$($),thread_id:this.callId}}));return d$.from(this.client,this.callId,O)}async edit($){let{content:O,mentions:j}=O$($);return await this.mutate((x)=>x.storage.entityMessageEdit({path:this.path,body:{content:O,mentions:j}})),this}async delete(){await this.mutate(($)=>$.storage.entityMessageDeleteMessage({path:this.path}))}}class Q$ extends I${messageThreadById($){return L$.byId(this.client,{type:"call",entity:this},$)}timelinePage($){return w$(this.client,{type:"call",entity:this},(O)=>d$.from(this.client,this.id,O),$)}access=new o(this.client,"call",this);async meeting(){return R$.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 Q$($,O)}message($){return d$.byId(this.client,this.id,$)}name=this.field("customName");channel=this.mappedField("channelId",($)=>$?b.byId(this.client,$):void 0);channelName=this.field("channelName");creator=this.mappedField("createdBy",($)=>P.byId(this.client,$));isActive=this.field("isActive");status=this.field("status");roomName=this.field("roomName");startedAt=this.field("startedAt");endedAt=this.field("endedAt");durationMs=this.field("durationMs");summary=this.field("summary");transcript=this.field("transcript");participants=this.field("participants");guests=this.field("guests");teamShareAccessLevel=this.field("teamShareAccessLevel");shareWithTeam=this.field("shareWithTeam");recordingUrl=this.field("recordingUrl");recordingPreviewUrl=this.field("recordingPreviewUrl");recordingStartedAt=this.field("recordingStartedAt");async rename($){await this.mutate((O)=>O.storage.editCallRecord({path:{call_id:this.id},body:{customName:$??""}}))}async setTeamShare($){await this.mutate((O)=>O.storage.editCallRecord({path:{call_id:this.id},body:{sharePermission:{teamShareAccessLevel:$?"view":null}}}))}async delete(){await this.mutate(($)=>$.storage.deleteCallRecord({path:{call_id:this.id}}))}static search=x$({filters:{call_filters:{}},type:"call",make:($,O)=>new Q$($,O.call_id)})}class p0{client;constructor($){this.client=$}byId($){return Q$.byId(this.client,$)}search($,O){return Q$.search(this.client,$,O)}}class a0{client;constructor($){this.client=$}async list(){let{labels:$}=Y(await this.client.storage.listChannelLabels());return $}async create($,O=[]){return Y(await this.client.storage.createChannelLabel({body:{name:$,channelIds:O.map((j)=>j.id)}}))}async createSmartTag($,O){return Y(await this.client.storage.createChannelLabel({body:{name:$,rule:O}}))}async previewSmartTag($){return Y(await this.client.storage.previewSmartTag({body:$}))}async updateSmartTag($,O,j){return Y(await this.client.storage.renameChannelLabel({path:{label_id:$.id},body:{name:O,rule:j}}))}async rename($,O){return Y(await this.client.storage.renameChannelLabel({path:{label_id:$.id},body:{name:O}}))}async delete($){Y(await this.client.storage.deleteChannelLabel({path:{label_id:$.id}}))}async setLabel($,O){Y(await this.client.storage.setChannelLabel({path:{channel_id:$.id},body:{labelId:O?.id??null}}))}}class i0{client;async activity(){return Y(await this.client.storage.getActivity()).map(($)=>new JO(this.client,b.byId(this.client,$.channel_id),$))}labels;constructor($){this.client=$;this.labels=new a0($)}byId($){return b.byId(this.client,$)}async dm($){return b.dm(this.client,$)}async private($){return b.private(this.client,$)}async create($){return b.create(this.client,$)}async list(){let{items:$}=Y(await this.client.storage.getChannels());return $.map((O)=>b.byId(this.client,O.id.toString()))}async*search($,O){if(!O?.searchOn||O.searchOn==="name"){let{items:j}=Y(await this.client.storage.getChannels()),x=$.toLowerCase();for(let S of j)if(S.name?.toLowerCase().includes(x))yield b.byId(this.client,S.id.toString())}else yield*b.search(this.client,$,O)}}class iO{client;chat;id;message;constructor($,O,j,x){this.client=$;this.chat=O;this.id=j;this.message=x}static byId($,O,j,x){return new iO($,O,j,x)}async stop(){Y(await this.client.cognition.stopChatStream({body:{chat_id:this.chat.id,stream_id:this.id}}))}toJSON(){return{id:this.id,chatId:this.chat.id,messageId:this.message.id}}}class nO extends A{chat;constructor($,O,j){super($,j);this.chat=O}static byId($,O,j){return new nO($,O,j)}async fetch(){let $=Y(await this.client.cognition.getChat({path:{chat_id:this.chat.id}})).chat.messages.find((O)=>O.id===this.id);if(!$)throw new E(`Chat message ${this.id} is not yet available`);return $}content=this.field("content");role=this.field("role");async refresh(){this.detail.clear(),await this.detail.get()}toJSON(){return{...super.toJSON(),chatId:this.chat.id}}}class G$ extends X${async send($){let{attachments:O,additionalInstructions:j,...x}=$,S=await this.mutate((Z)=>Z.cognition.sendChatMessage({body:{...x,chat_id:this.id,additional_instructions:j,attachments:O?.map((X)=>({entity_id:X.entity.id,entity_type:X.type}))}})),G=G$.byId(this.client,S.chat_id);return iO.byId(this.client,G,S.stream_id,nO.byId(this.client,G,S.message_id))}access=new o(this.client,"chat",this);entityType="chat";propertyEntityType="CHAT";async fetch(){let{chat:$}=Y(await this.client.cognition.getChat({path:{chat_id:this.id}}));return $}static byId($,O){return new G$($,O)}static async create($,O){let{id:j}=Y(await $.cognition.createChat({body:{name:O?.name??null,projectId:O?.project?.id??null}}));return new G$($,j)}name=this.field("name");model=this.field("model");project=this.mappedField("projectId",($)=>$?n.byId(this.client,$):void 0);createdAt=this.field("createdAt");updatedAt=this.field("updatedAt");messages=this.field("messages");async rename($){await this.mutate((O)=>O.cognition.patchChat({path:{chat_id:this.id},body:{name:$}}))}async delete($){await this.mutate((O)=>$?.permanent?O.cognition.permanentlyDeleteChat({path:{chat_id:this.id}}):O.cognition.deleteChat({path:{chat_id:this.id}}))}async copy(){let{id:$}=await this.mutate((O)=>O.cognition.copyChat({path:{chat_id:this.id}}));return new G$(this.client,$)}async restore(){await this.mutate(($)=>$.cognition.revertDeleteChat({path:{chat_id:this.id}}))}async history(){let{conversation:$}=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 G$($,O.chat_id)});toMention(){return{tag:i$("m-document-mention",{documentId:this.id,documentName:this.detail.peek()?.name??"",blockName:"chat",blockParams:{}}),mention:{entity_type:"chat",entity_id:this.id}}}}class n0{client;constructor($){this.client=$}byId($){return G$.byId(this.client,$)}create($){return G$.create(this.client,$)}search($,O){return G$.search(this.client,$,O)}}var i6=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 P.byId(this.client,(await this.detail.get()).sender_id)}async reply($){return sO(this.client,this.parent,$,{threadId:await this.threadId()})}async edit($){let{content:O,mentions:j}=O$($);return await this.mutate((x)=>x.storage.entityMessageEdit({path:this.path,body:{content:O,mentions:j}})),this}async delete(){await this.mutate(($)=>$.storage.entityMessageDeleteMessage({path:this.path}))}}async function Uj($,O){let j={parent_type:O.type,parent_id:O.id},x=c(async(G)=>{let Z=Y(await $.storage.messageTimeline({path:j,query:{selection:JSON.stringify({limit:100,cursor:G})}}));return{items:Z.items,nextCursor:Z.next_cursor}}),S=[];for await(let G of x)S.push(G);return cO(S,i6,async(G)=>{let{state:Z,root:X,replies:K}=Y(await $.storage.entityMessageGetThread({path:{...j,id:G.id}}));return{thread:Z,comments:[X,...K].map((L)=>A$.from($,O,L))}})}async function sO($,O,j,x){let S=Y(await $.storage.entityMessageCreate({path:{parent_type:O.type,parent_id:O.id},body:{...O$(j),thread_id:x?.threadId??null}}));return A$.from($,O,S)}class f$ extends I${messageThreadById($){return L$.byId(this.client,{type:"crm_contact",entity:this},$)}timelinePage($){return w$(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 f$($,O)}static from($,O){return new f$($,O.id,O)}name=this.field("name");email=this.field("email");company=this.mappedField("companyId",($)=>b$.byId(this.client,$));hidden=this.field("hidden");createdAt=this.field("createdAt");updatedAt=this.field("updatedAt");firstInteraction=this.field("firstInteraction");lastInteraction=this.field("lastInteraction");async hide(){await this.setHidden(!0)}async unhide(){await this.setHidden(!1)}async setHidden($){await this.mutate((O)=>O.storage.setContactHidden({path:{contact_id:this.id},body:{hidden:$}}))}async rename($){await this.mutate((O)=>O.storage.setCrmContactName({path:{contact_id:this.id},body:{name:$}}))}get commentParent(){return{type:"crm_contact",id:this.id}}async comments(){return Uj(this.client,this.commentParent)}async comment($,O){return sO(this.client,this.commentParent,$,O)}commentById($){return A$.byId(this.client,this.commentParent,$)}}class b$ extends X${messageThreadById($){return L$.byId(this.client,{type:"crm_company",entity:this},$)}timelinePage($){return w$(this.client,{type:"crm_company",entity:this},(O)=>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 b$($,O)}static from($,O){return new b$($,O.id,O)}name=this.field("name");description=this.field("description");hidden=this.field("hidden");emailSync=this.field("emailSync");team=this.mappedField("teamId",($)=>S$.byId(this.client,$));createdAt=this.field("createdAt");updatedAt=this.field("updatedAt");async domain(){let{domains:$}=await this.detail.get();return $[0]?.domain}async domains(){let{domains:$}=await this.detail.get();return $.map((O)=>O.domain)}async contacts(){return Y(await this.client.storage.listCompanyContacts({path:{company_id:this.id}})).map((O)=>f$.from(this.client,O))}static search=x$({filters:{crm_company_filters:{}},type:"company",includeCrm:!0,make:($,O)=>new b$($,O.id)});async hide(){await this.setHidden(!0)}async unhide(){await this.setHidden(!1)}async setHidden($){await this.mutate((O)=>O.storage.setCompanyHidden({path:{company_id:this.id},body:{hidden:$}}))}async setEmailSync($){await this.mutate((O)=>O.storage.setEmailSync({path:{company_id:this.id},body:{email_sync:$}}))}async rename($){await this.mutate((O)=>O.storage.setCrmCompanyName({path:{company_id:this.id},body:{name:$}}))}async createContact($){let O=await this.mutate((j)=>j.storage.createCrmContact({path:{company_id:this.id},body:$}));return f$.from(this.client,O)}get commentParent(){return{type:"crm_company",id:this.id}}async comments(){return Uj(this.client,this.commentParent)}async comment($,O){return sO(this.client,this.commentParent,$,O)}commentById($){return A$.byId(this.client,this.commentParent,$)}}class t$ extends A{tableDetail=new W$(async()=>Y(await this.client.storage.getCrmPipelineTable({path:{id:this.id}})));static byId($,O){return new t$($,O)}static from($,O){return new t$($,O.id,O)}async fetch(){return 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",($)=>P.byId(this.client,$));team=this.mappedField("teamId",($)=>S$.byId(this.client,$));async rename($){await this.mutate((O)=>O.storage.renameCrmPipeline({path:{id:this.id},body:{name:$}}))}async setSharing($){if($===void 0)throw Error("Sharing is required");await this.mutate((O)=>O.storage.shareCrmPipeline({path:{id:this.id},body:{sharing:$}}))}async setTrashed($){await this.mutate((O)=>O.storage.trashCrmPipeline({path:{id:this.id},body:{trashed:$}}))}async sharePermissions(){return Y(await this.client.storage.getCrmPipelinePermissions({path:{id:this.id}}))}async updateSharePermissions($){return this.mutate((O)=>O.storage.updateCrmPipelinePermissions({path:{id:this.id},body:n$($)}))}async table(){return zj.from(this.client,this,await this.tableRecord())}tableRecord(){return this.tableDetail.get()}rows(){return c(async($)=>{let O=Y(await this.client.storage.getCrmPipelineRows({path:{id:this.id},query:{after:$}}));return{items:O.rows.map((j)=>WO.from(this.client,this,j)),nextCursor:O.next}})}queryRows($={}){if($.rows?.some((O)=>O.pipeline.id!==this.id))throw Error("Rows belong to another pipeline");return c(async(O)=>{let j=Y(await this.client.storage.queryCrmPipelineRows({path:{id:this.id},body:{after:O,query:$.query,rowIds:$.rows?.map((x)=>x.id)}}));return{items:j.rows.map((x)=>WO.from(this.client,this,x)),nextCursor:j.next}})}async applyOps($,O){if(O?.baseVersions?.some((S)=>S.table.pipeline.id!==this.id))throw Error("Table belongs to another pipeline");let j={ops:$,baseVersions:O?.baseVersions?Object.fromEntries(O.baseVersions.map((S)=>[S.table.id,S.version])):void 0},x=await this.mutate((S)=>S.storage.applyCrmPipelineOps({path:{id:this.id},body:j}));return this.tableDetail.clear(),x}}class zj extends 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 zj($,O,j)}fetch(){return this.pipeline.tableRecord()}async columns(){return(await this.pipeline.tableRecord()).columns.map(($)=>Ij.from(this.client,this,$))}async version(){return(await this.pipeline.tableRecord()).table.version}rowById($){return WO.byId(this.client,this.pipeline,$)}rows(){return this.pipeline.rows()}}class WO extends 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 WO($,O,j)}static from($,O,j){return new WO($,O,j.rowId,j)}async fetch(){for await(let $ of this.pipeline.queryRows({rows:[this]}))if($.id===this.id)return $.detail.get();throw new E(`Pipeline row ${this.id} is unavailable`)}cells=this.field("cells");async refresh(){this.detail.clear(),await this.detail.get()}}class Ij extends 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 Ij($,O,j)}async fetch(){let $=(await this.table.pipeline.tableRecord()).columns.find((O)=>O.column.id===this.id);if(!$)throw new E(`Pipeline column ${this.id} is unavailable`);return $}async writable(){return(await this.fetch()).writable}async name(){return(await this.fetch()).column.display_name??(await this.fetch()).definition.definition.display_name}}class s0{client;constructor($){this.client=$}byId($){return t$.byId(this.client,$)}async list(){return Y(await this.client.storage.listCrmPipelines()).map(($)=>t$.from(this.client,$))}async create($){return t$.from(this.client,Y(await this.client.storage.createCrmPipeline({body:$})))}}class t0{client;pipelines;constructor($){this.client=$;this.pipelines=new s0($)}companyById($){return b$.byId(this.client,$)}contactById($){return f$.byId(this.client,$)}async contactByEmail($){let{contact:O}=Y(await this.client.storage.getContactByEmail({query:{email:$}}));return O?f$.from(this.client,O):void 0}async searchContacts($,O={}){let{contacts:j}=Y(await this.client.storage.searchContacts({query:{query:$,limit:O.limit}}));return j.map((x)=>f$.from(this.client,x))}async createCompany($){return b$.from(this.client,Y(await this.client.storage.createCrmCompany({body:$})))}async settings(){return Y(await this.client.storage.getCrmTeamSettings())}async updateSettings($){return Y(await this.client.storage.putCrmTeamSettings({body:$}))}async setStages($){return Y(await this.client.storage.putCrmTeamStages({body:$}))}async resetStages(){Y(await this.client.storage.resetCrmTeamStages())}searchCompanies($){return b$.search(this.client,$)}}var Y$=Symbol.for("@ts-pattern/matcher"),u1=Symbol.for("@ts-pattern/isVariadic");var e0=($)=>Boolean($&&typeof $=="object"),Tj=($)=>$&&!!$[Y$],s=($,O,j)=>{if(Tj($)){let x=$[Y$](),{matched:S,selections:G}=x.match(O);return S&&G&&Object.keys(G).forEach((Z)=>j(Z,G[Z])),S}if(e0($)){if(!e0(O))return!1;if(Array.isArray($)){if(!Array.isArray(O))return!1;let x=[],S=[],G=[];for(let Z of $.keys()){let X=$[Z];Tj(X)&&X[u1]?G.push(X):G.length?S.push(X):x.push(X)}if(G.length){if(G.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),K=O.slice(x.length,S.length===0?1/0:-S.length);return x.every((L,Q)=>s(L,Z[Q],j))&&S.every((L,Q)=>s(L,X[Q],j))&&(G.length===0||s(G[0],K,j))}return $.length===O.length&&$.every((Z,X)=>s(Z,O[X],j))}return Reflect.ownKeys($).every((x)=>{let S=$[x];return((x in O)||Tj(G=S)&&G[Y$]().matcherType==="optional")&&s(S,O[x],j);var G})}return Object.is(O,$)},K$=($)=>{var O,j,x;return e0($)?Tj($)?(O=(j=(x=$[Y$]()).getSelectionKeys)==null?void 0:j.call(x))!=null?O:[]:Array.isArray($)?tO($,K$):tO(Object.values($),K$):[]},tO=($,O)=>$.reduce((j,x)=>j.concat(O(x)),[]);function n6(...$){if($.length===1){let[O]=$;return(j)=>s(O,j,()=>{})}if($.length===2){let[O,j]=$;return s(O,j,()=>{})}throw Error(`isMatching wasn't given the right number of arguments: expected 1 or 2, received ${$.length}.`)}function t($){return Object.assign($,{optional:()=>Ox($),and:(O)=>d($,O),or:(O)=>c1($,O),select:(O)=>O===void 0?eO($):eO(O,$)})}function o0($){return Object.assign(((O)=>Object.assign(O,{[Symbol.iterator](){let j=0,x=[{value:Object.assign(O,{[u1]:!0}),done:!1},{done:!0,value:void 0}];return{next:()=>{var S;return(S=x[j++])!=null?S:x.at(-1)}}}}))($),{optional:()=>o0(Ox($)),select:(O)=>o0(O===void 0?eO($):eO(O,$))})}function Ox($){return t({[Y$]:()=>({match:(O)=>{let j={},x=(S,G)=>{j[S]=G};return O===void 0?(K$($).forEach((S)=>x(S,void 0)),{matched:!0,selections:j}):{matched:s($,O,x),selections:j}},getSelectionKeys:()=>K$($),matcherType:"optional"})})}var s6=($,O)=>{for(let j of $)if(!O(j))return!1;return!0},t6=($,O)=>{for(let[j,x]of $.entries())if(!O(x,j))return!1;return!0},e6=($,O)=>{let j=Reflect.ownKeys($);for(let x of j)if(!O(x,$[x]))return!1;return!0};function d(...$){return t({[Y$]:()=>({match:(O)=>{let j={},x=(S,G)=>{j[S]=G};return{matched:$.every((S)=>s(S,O,x)),selections:j}},getSelectionKeys:()=>tO($,K$),matcherType:"and"})})}function c1(...$){return t({[Y$]:()=>({match:(O)=>{let j={},x=(S,G)=>{j[S]=G};return tO($,K$).forEach((S)=>x(S,void 0)),{matched:$.some((S)=>s(S,O,x)),selections:j}},getSelectionKeys:()=>tO($,K$),matcherType:"or"})})}function u($){return{[Y$]:()=>({match:(O)=>({matched:Boolean($(O))})})}}function eO(...$){let O=typeof $[0]=="string"?$[0]:void 0,j=$.length===2?$[1]:typeof $[0]=="string"?void 0:$[0];return t({[Y$]:()=>({match:(x)=>{let S={[O!=null?O:"@ts-pattern/anonymous-select-key"]:x};return{matched:j===void 0||s(j,x,(G,Z)=>{S[G]=Z}),selections:S}},getSelectionKeys:()=>[O!=null?O:"@ts-pattern/anonymous-select-key"].concat(j===void 0?[]:K$(j))})})}function d1($){return!0}function k$($){return typeof $=="number"}function e$($){return typeof $=="string"}function o$($){return typeof $=="bigint"}var l1=t(u(d1)),o6=t(u(d1)),$7=l1,$O=($)=>Object.assign(t($),{startsWith:(O)=>{return $O(d($,(j=O,u((x)=>e$(x)&&x.startsWith(j)))));var j},endsWith:(O)=>{return $O(d($,(j=O,u((x)=>e$(x)&&x.endsWith(j)))));var j},minLength:(O)=>$O(d($,((j)=>u((x)=>e$(x)&&x.length>=j))(O))),length:(O)=>$O(d($,((j)=>u((x)=>e$(x)&&x.length===j))(O))),maxLength:(O)=>$O(d($,((j)=>u((x)=>e$(x)&&x.length<=j))(O))),includes:(O)=>{return $O(d($,(j=O,u((x)=>e$(x)&&x.includes(j)))));var j},regex:(O)=>{return $O(d($,(j=O,u((x)=>e$(x)&&Boolean(x.match(j))))));var j}}),m1=$O(u(e$)),g$=($)=>Object.assign(t($),{between:(O,j)=>g$(d($,((x,S)=>u((G)=>k$(G)&&x<=G&&S>=G))(O,j))),lt:(O)=>g$(d($,((j)=>u((x)=>k$(x)&&x<j))(O))),gt:(O)=>g$(d($,((j)=>u((x)=>k$(x)&&x>j))(O))),lte:(O)=>g$(d($,((j)=>u((x)=>k$(x)&&x<=j))(O))),gte:(O)=>g$(d($,((j)=>u((x)=>k$(x)&&x>=j))(O))),int:()=>g$(d($,u((O)=>k$(O)&&Number.isInteger(O)))),finite:()=>g$(d($,u((O)=>k$(O)&&Number.isFinite(O)))),positive:()=>g$(d($,u((O)=>k$(O)&&O>0))),negative:()=>g$(d($,u((O)=>k$(O)&&O<0)))}),O7=g$(u(k$)),OO=($)=>Object.assign(t($),{between:(O,j)=>OO(d($,((x,S)=>u((G)=>o$(G)&&x<=G&&S>=G))(O,j))),lt:(O)=>OO(d($,((j)=>u((x)=>o$(x)&&x<j))(O))),gt:(O)=>OO(d($,((j)=>u((x)=>o$(x)&&x>j))(O))),lte:(O)=>OO(d($,((j)=>u((x)=>o$(x)&&x<=j))(O))),gte:(O)=>OO(d($,((j)=>u((x)=>o$(x)&&x>=j))(O))),positive:()=>OO(d($,u((O)=>o$(O)&&O>0))),negative:()=>OO(d($,u((O)=>o$(O)&&O<0)))}),j7=OO(u(o$)),x7=t(u(function($){return typeof $=="boolean"})),S7=t(u(function($){return typeof $=="symbol"})),Z7=t(u(function($){return $==null})),X7=t(u(function($){return $!=null})),Z$={__proto__:null,matcher:Y$,optional:Ox,array:function(...$){return o0({[Y$]:()=>({match:(O)=>{if(!Array.isArray(O))return{matched:!1};if($.length===0)return{matched:!0};let j=$[0],x={};if(O.length===0)return K$(j).forEach((G)=>{x[G]=[]}),{matched:!0,selections:x};let S=(G,Z)=>{x[G]=(x[G]||[]).concat([Z])};return{matched:O.every((G)=>s(j,G,S)),selections:x}},getSelectionKeys:()=>$.length===0?[]:K$($[0])})})},set:function(...$){return t({[Y$]:()=>({match:(O)=>{if(!(O instanceof Set))return{matched:!1};let j={};if(O.size===0)return{matched:!0,selections:j};if($.length===0)return{matched:!0};let x=(G,Z)=>{j[G]=(j[G]||[]).concat([Z])},S=$[0];return{matched:s6(O,(G)=>s(S,G,x)),selections:j}},getSelectionKeys:()=>$.length===0?[]:K$($[0])})})},map:function(...$){return t({[Y$]:()=>({match:(O)=>{if(!(O instanceof Map))return{matched:!1};let j={};if(O.size===0)return{matched:!0,selections:j};let x=(X,K)=>{j[X]=(j[X]||[]).concat([K])};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[G,Z]=$;return{matched:t6(O,(X,K)=>{let L=s(G,K,x),Q=s(Z,X,x);return L&&Q}),selections:j}},getSelectionKeys:()=>$.length===0?[]:[...K$($[0]),...K$($[1])]})})},record:function(...$){return t({[Y$]:()=>({match:(O)=>{if(O===null||typeof O!="object"||Array.isArray(O))return{matched:!1};var j;if($.length===0)throw Error(`\`P.record\` wasn't given enough arguments. Expected (value) or (key, value), received ${(j=$[0])==null?void 0:j.toString()}`);let x={},S=(X,K)=>{x[X]=(x[X]||[]).concat([K])},[G,Z]=$.length===1?[m1,$[0]]:$;return{matched:e6(O,(X,K)=>{let L=typeof X!="string"||Number.isNaN(Number(X))?null:Number(X),Q=L!==null&&s(G,L,S),J=s(G,X,S),I=s(Z,K,S);return(J||Q)&&I}),selections:x}},getSelectionKeys:()=>$.length===0?[]:[...K$($[0]),...K$($[1])]})})},intersection:d,union:c1,not:function($){return t({[Y$]:()=>({match:(O)=>({matched:!s($,O,()=>{})}),getSelectionKeys:()=>[],matcherType:"not"})})},when:u,select:eO,any:l1,unknown:o6,_:$7,string:m1,number:O7,bigint:j7,boolean:x7,symbol:S7,nullish:Z7,nonNullable:X7,instanceOf:function($){return t(u(function(O){return(j)=>j instanceof O}($)))},shape:function($){return t(u(n6($)))}};class r1 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 $x={matched:!1,value:void 0};function k($){return new Hj($,$x)}class Hj{constructor($,O){this.input=void 0,this.state=void 0,this.input=$,this.state=O}with(...$){if(this.state.matched)return this;let O=$[$.length-1],j=[$[0]],x;$.length===3&&typeof $[1]=="function"?x=$[1]:$.length>2&&j.push(...$.slice(1,$.length-1));let S=!1,G={},Z=(K,L)=>{S=!0,G[K]=L},X=!j.some((K)=>s(K,this.input,Z))||x&&!Boolean(x(this.input))?$x:{matched:!0,value:O(S?"@ts-pattern/anonymous-select-key"in G?G["@ts-pattern/anonymous-select-key"]:G:this.input,this.input)};return new Hj(this.input,X)}when($,O){if(this.state.matched)return this;let j=Boolean($(this.input));return new Hj(this.input,j?{matched:!0,value:O(this.input,this.input)}:$x)}otherwise($){return this.state.matched?this.state.value:$(this.input)}exhaustive($=G7){return this.state.matched?this.state.value:$(this.input)}run(){return this.exhaustive()}returnType(){return this}narrow(){return this}}function G7($){throw new r1($)}var jx,K7=new Uint8Array(16);function Rj(){if(!jx){if(typeof crypto>"u"||!crypto.getRandomValues)throw Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");jx=crypto.getRandomValues.bind(crypto)}return jx(K7)}var j$=[];for(let $=0;$<256;++$)j$.push(($+256).toString(16).slice(1));function p1($,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 xx={};function Y7($,O,j){let x;if($)x=a1($.random??$.rng?.()??Rj(),$.msecs,$.seq,O,j);else{let S=Date.now(),G=Rj();Q7(xx,S,G),x=a1(G,xx.msecs,xx.seq,O,j)}return O??p1(x)}function Q7($,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 a1($,O,j,x,S=0){if($.length<16)throw Error("Random bytes length must be >= 16");if(!x)x=new Uint8Array(16),S=0;else if(S<0||S+16>x.length)throw RangeError(`UUID byte range ${S}:${S+15} is out of buffer bounds`);return O??=Date.now(),j??=$[6]*127<<24|$[7]<<16|$[8]<<8|$[9],x[S++]=O/1099511627776&255,x[S++]=O/4294967296&255,x[S++]=O/16777216&255,x[S++]=O/65536&255,x[S++]=O/256&255,x[S++]=O&255,x[S++]=112|j>>>28&15,x[S++]=j>>>20&255,x[S++]=128|j>>>14&63,x[S++]=j>>>6&255,x[S++]=j<<2&255|$[10]&3,x[S++]=$[11],x[S++]=$[12],x[S++]=$[13],x[S++]=$[14],x[S++]=$[15],x}var l$=Y7;class C${table;id;constructor($,O){this.table=$;this.id=O}static byId($,O){return new C$($,O)}async detail(){let{columns:$}=await this.table.detail(),O=$.find((j)=>j.column.id===this.id);if(!O)throw new E(`column ${this.id} is not on table ${this.table.id}`);return O}async name(){let $=await this.detail();return $.column.display_name??$.definition.definition.display_name}async rename($){return await this.table.database.renameColumn(this,$),this}async inferType($){return await this.table.database.inferColumnType(this,$),this}changeType($){return this.table.database.changeColumnType(this,$)}convertIntoNewColumn($){return this.table.database.convertColumnIntoNewColumn(this,$)}casts(){return this.table.database.columnCasts(this)}async delete(){await this.table.database.deleteColumn(this)}async dataType(){return(await this.detail()).definition.definition.data_type}async isMultiSelect(){return(await this.detail()).definition.definition.is_multi_select}async position(){return(await this.detail()).column.position}async definition(){return(await this.detail()).definition}async config(){return(await this.detail()).column.config??void 0}async addOptions($){return await this.table.database.addColumnOptions(this,$),this}toJSON(){return{id:this.id,tableId:this.table.id}}}class F${table;id;constructor($,O){this.table=$;this.id=O}static byId($,O){return new F$($,O)}history(){return this.table.database.rowHistory(this)}toJSON(){return{id:this.id,tableId:this.table.id}}}class Dj{table;id;constructor($,O){this.table=$;this.id=O}static byId($,O){return new Dj($,O)}async detail(){let{views:$}=await this.table.detail(),O=$.find((j)=>j.id===this.id);if(!O)throw new E(`view ${this.id} is not on table ${this.table.id}`);return O}async name(){return(await this.detail()).name}async position(){return(await this.detail()).position}async layout(){return(await this.detail()).layout}async query(){return(await this.detail()).query}positions(){return this.table.database.viewPositions(this)}toJSON(){return{id:this.id,tableId:this.table.id}}}class J${database;id;constructor($,O){this.database=$;this.id=O}static byId($,O){return new J$($,O)}async detail(){let{tables:$}=await this.database.schema(),O=$.find((j)=>j.table.id===this.id);if(!O)throw new E(`table ${this.id} is not in database ${this.database.id}`);return O}async name(){return(await this.detail()).table.name}async rename($){return await this.database.renameTable(this,$),this}async version(){return(await this.detail()).table.version}async position(){return(await this.detail()).table.position}async columns(){let{columns:$}=await this.detail();return $.map((O)=>C$.byId(this,O.column.id))}addColumn($){return this.database.addColumn(this,$)}async reorderColumns($){return await this.database.reorderColumns(this,$),this}row($){return F$.byId(this,$)}async views(){let{views:$}=await this.detail();return $.map((O)=>Dj.byId(this,O.id))}createWebhook(){return this.database.createWebhook(this)}async delete(){await this.database.deleteTable(this)}toJSON(){return{id:this.id,databaseId:this.database.id}}}async function _j($,O,j,x={}){let S=Y(await $.storage.queryDatabases({body:{sql:j,databaseId:x.database?.id,baseVersions:Object.fromEntries((x.baseVersions??[]).map(({table:Q,version:J})=>[Q.id,J]))}})),G=new Map;for(let Q of[x.database,...(x.baseVersions??[]).map(({table:J})=>J.database)]){if(!Q)continue;let J=G.get(Q.id);if(J)J.add(Q);else G.set(Q.id,new Set([Q]))}let Z=(Q)=>{let J=G.get(Q)?.values().next().value;if(J)return J;let I=O($,Q);return G.set(Q,new Set([I])),I},X=(Q)=>{let J=S.tableDatabases[Q];if(!J)throw Error(`SQL response is missing the owner of table ${Q}`);return J$.byId(Z(J),Q)},K=new Set(Object.keys(S.newVersions).map((Q)=>X(Q).database.id));if(S.statement.kind==="schema")K.add(S.statement.databaseId);for(let Q of K)for(let J of G.get(Q)??[])J.invalidateSchema();let L=k(S.statement).with({kind:"select"},(Q)=>Q).with({kind:"schema"},({databaseId:Q,summary:J})=>({kind:"schema",database:Z(Q),summary:J})).with({kind:"insert"},{kind:"update"},{kind:"delete"},({kind:Q,tableId:J,tableName:I})=>({kind:Q,table:X(J),tableName:I})).with({kind:"alterColumnType"},({tableId:Q,tableName:J,columnId:I,columnName:z,to:W})=>{let V=X(Q);return{kind:"alterColumnType",table:V,tableName:J,column:C$.byId(V,I),columnName:z,to:W}}).exhaustive();return{result:S.result?J7(S.result,X,S.tableDatabases):void 0,changesApplied:S.changesApplied,insertedRows:L.kind==="insert"?S.insertedRowIds.map((Q)=>F$.byId(L.table,Q)):[],newVersions:Object.entries(S.newVersions).map(([Q,J])=>({table:X(Q),version:J})),readVersions:Object.entries(S.readVersions).map(([Q,J])=>({table:X(Q),version:J})),truncatedTables:S.truncatedTables,statement:L}}function J7($,O,j){let x=$.sourceTable&&j[$.sourceTable]?O($.sourceTable):void 0;return{columns:$.columns.map(({relatedTable:S,...G})=>({...G,relatedTable:S&&j[S]?O(S):void 0})),rows:$.rows,sourceTable:x,rowHandles:x?$.rowIds.map((S)=>F$.byId(x,S)):[]}}class Mj{table;id;createdBy;record;constructor($,O,j,x){this.table=$;this.id=O;this.createdBy=j;this.record=x}static fromRecord($,O,j){return new Mj($,j.id,O,j)}get tokenPrefix(){return this.record.tokenPrefix}get createdAt(){return this.record.createdAt}delete(){return this.table.database.deleteWebhook(this)}toJSON(){return{id:this.id,tableId:this.table.id,tokenPrefix:this.tokenPrefix}}}class Xx extends QO{op;row;column;taken;constructor($,O){super($,O);this.name="MacroOpRefusedError",this.message=O.message,this.op=O.op,this.row=O.row,this.column=O.column,this.taken=O.taken}}function Pj($){return k($).with({type:"relation"},({table:O})=>({type:"relation",database:O.database.id,table:O.id})).with({type:Z$.not("relation")},(O)=>O).exhaustive()}var V7={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 W7($){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})=>V7[O]).with({type:"relation"},()=>"Relation").exhaustive(()=>"Column")}function Sx($){return $.map((O)=>({id:l$(),label:O}))}function i1($,O,j){return $?.kind===O&&"change"in $&&$.change.kind===j}function Zx($){return k($).with({kind:"reorder_tables"},({kind:O})=>O).with({kind:Z$.union("table","column","rows","view")},({kind:O,change:j})=>`${O}.${j.kind}`).exhaustive(()=>"unknown")}function r$($,O,j){let[x]=$;if($.length!==1||!i1(x,O,j))throw new f(`expected one ${O}.${j} result, got ${$.map(Zx).join(", ")||"none"}`);return x}class V$ extends A{access=new o(this.client,"database",this);async fetch(){return Y(await this.client.storage.getDatabase({path:{id:this.id}}))}assertOwns($,O){if(O.id!==this.id)throw new f(`${$} does not belong to database ${this.id}`)}static byId($,O){return new V$($,O)}static async create($,O){let j=Y(await $.storage.createDatabase({body:{name:O.name}}));return new V$($,j.id)}static async list($){return Y(await $.storage.listDatabases()).map((j)=>new V$($,j.database.id))}query($,O){return _j(this.client,V$.byId,$,{...O,database:this})}invalidateSchema(){this.detail.clear()}schema(){return this.detail.get()}name=this.mappedField("database",($)=>$.name);owner=this.mappedField("database",($)=>P.byId(this.client,$.owner_id));createdAt=this.mappedField("database",($)=>$.created_at);trashedAt=this.mappedField("database",($)=>$.trashed_at??void 0);grant=this.field("grant");tables=this.mappedField("tables",($)=>$.map((O)=>J$.byId(this,O.table.id)));async table($){let{tables:O}=await this.schema(),j=O.find((x)=>x.table.name===$);return j?J$.byId(this,j.table.id):void 0}async createTable($){let{table:O}=r$(await this.applyOps([{kind:"table",table:l$(),change:{kind:"create",name:$.name}}]),"table","created");return J$.byId(this,O)}async applyOps($,O={}){let j={ops:$};if(O.baseVersions!==void 0){for(let{table:S}of O.baseVersions)this.assertOwns(`table ${S.id}`,S.database);j.baseVersions=Object.fromEntries(O.baseVersions.map(({table:S,version:G})=>[S.id,G]))}let{results:x}=await this.mutate(async(S)=>{let G=await S.storage.applyDatabaseOps({path:{id:this.id},body:j});if(G.error!==void 0&&"op"in G.error)throw new Xx(G.response?.status??0,G.error);return G});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(Zx).join(", ")||"none"}`);return j.tables.map(({table:x})=>J$.byId(this,x))}async deleteTable($){this.assertOwns(`table ${$.id}`,$.database),r$(await this.applyOps([{kind:"table",table:$.id,change:{kind:"delete"}}]),"table","deleted")}async columnCasts($){return this.assertOwns(`column ${$.id}`,$.table.database),Y(await this.client.storage.listDatabaseColumnCasts({path:{id:this.id,table_id:$.table.id,column_id:$.id}}))}async viewPositions($){this.assertOwns(`view ${$.id}`,$.table.database);let{positions:O}=Y(await this.client.storage.getDatabaseViewPositions({path:{id:this.id,view_id:$.id}}));return O}async rowHistory($){this.assertOwns(`row ${$.id}`,$.table.database);let{changes:O}=Y(await this.client.storage.getDatabaseRowHistory({path:{id:this.id,table_id:$.table.id,row_id:$.id}}));return O}async importTable($){let O=await this.mutate((j)=>j.storage.importDatabaseTable({path:{id:this.id},body:$}));return J$.byId(this,O.id)}webhookOf($){return Mj.fromRecord(J$.byId(this,$.tableId),P.byId(this.client,$.createdBy),$)}async webhooks(){let{webhooks:$}=Y(await this.client.storage.listDatabaseWebhooks({path:{id:this.id}}));return $.map((O)=>this.webhookOf(O))}async createWebhook($){this.assertOwns("table",$.database);let O=Y(await this.client.storage.createDatabaseWebhook({path:{id:this.id},body:{tableId:$.id}}));return{webhook:this.webhookOf(O.webhook),token:O.token}}async deleteWebhook($){this.assertOwns("webhook",$.table.database),Y(await this.client.storage.deleteDatabaseWebhook({path:{id:this.id,webhook_id:$.id}}))}async sharePermissions(){return Y(await this.client.storage.getDatabasePermissions({path:{id:this.id}}))}updateSharePermissions($){return this.mutate((O)=>O.storage.updateDatabasePermissions({path:{id:this.id},body:$}))}async changeColumnType($,O){this.assertOwns(`column ${$.id}`,$.table.database);let j=await $.table.version();return r$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"change_type",to:Pj(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:Pj(O)}}))}async convertColumnIntoNewColumn($,O){let j=await this.columnConversion($,O.to),x=O.name??`${await $.name()} (${W7(O.to)})`,S=l$(),G=[{kind:"column",table:$.table.id,column:S,change:{kind:"create",definition:{source:"new",name:x,type:Pj(O.to),options:Sx(j.options)},after:$.id}}];if(j.cells.length>0)G.push({kind:"rows",table:$.table.id,change:{kind:"update",changes:{kind:"per_row",rows:j.cells.map(({row:X,value:K})=>({row:X,cells:[{column:S,value:K}]}))}}});let[Z]=await this.applyOps(G,{baseVersions:[{table:$.table,version:j.tableVersion}]});if(!i1(Z,"column","created"))throw new f(`expected a column.created result, got ${Z?Zx(Z):"none"}`);return C$.byId($.table,Z.column)}async deleteColumn($){this.assertOwns(`column ${$.id}`,$.table.database);let O=await $.table.version(),{tableVersion:j}=r$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"delete"}}],{baseVersions:[{table:$.table,version:O}]}),"column","deleted");return j}async reorderColumns($,O){this.assertOwns(`table ${$.id}`,$.database);for(let S of O)if(S.table.id!==$.id)throw new f(`column ${S.id} does not belong to table ${$.id}`);let j=await $.version(),{tableVersion:x}=r$(await this.applyOps([{kind:"table",table:$.id,change:{kind:"reorder_columns",order:O.map((S)=>S.id)}}],{baseVersions:[{table:$,version:j}]}),"table","columns_reordered");if(x===void 0)throw new f(`table ${$.id} reordered its columns without a version`);return x}async renameTable($,O){this.assertOwns(`table ${$.id}`,$.database);let j=await $.name(),{tableVersion:x}=r$(await this.applyOps([{kind:"table",table:$.id,change:{kind:"rename",name:O,previousName:j}}]),"table","renamed");if(x===void 0)throw new f(`table ${$.id} was renamed without a version`);return x}async renameColumn($,O){this.assertOwns(`column ${$.id}`,$.table.database);let j=await $.name(),{tableVersion:x}=r$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"rename",name:O,previousName:j}}]),"column","renamed");return x}async inferColumnType($,O){return this.assertOwns(`column ${$.id}`,$.table.database),this.mutate((j)=>j.storage.inferDatabaseColumnType({path:{id:this.id,table_id:$.table.id,column_id:$.id},body:{dataType:O.dataType,baseVersion:O.baseVersion,...O.specificEntityType!==void 0?{specificEntityType:O.specificEntityType}:{}}}))}async addColumn($,O){if(this.assertOwns(`table ${$.id}`,$.database),O.after!==void 0&&O.after.table.id!==$.id)throw new f(`column ${O.after.id} does not belong to table ${$.id}`);let j="property"in O?{source:"existing",property:O.property.id}:{source:"new",name:O.name,type:Pj(O.type),...O.options!==void 0?{options:Sx(O.options)}:{},...O.inferType!==void 0?{inferType:O.inferType}:{}},{column:x}=r$(await this.applyOps([{kind:"column",table:$.id,column:l$(),change:{kind:"create",definition:j,...O.after!==void 0?{after:O.after.id}:{}}}]),"column","created");return C$.byId($,x)}async addColumnOptions($,O){return this.assertOwns(`column ${$.id}`,$.table.database),r$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"add_options",options:Sx(O)}}]),"column","options_added")}}class Gx{client;constructor($){this.client=$}query($,O){return _j(this.client,V$.byId,$,O)}byId($){return V$.byId(this.client,$)}create($){return V$.create(this.client,$)}list(){return V$.list(this.client)}}class Aj{id;name;constructor($,O){this.id=$;this.name=O}static async list($){let{skills:O}=Y(await $.storage.getSystemSkillsHandler());return O.map((j)=>new Aj(j.id,j.name))}}class Kx{client;async byTeamSlug($){let O=Y(await this.client.storage.getDocumentByTeamSlug({path:{slug:$}}));if(typeof O!=="object"||O===null||!("data"in O)||typeof O.data!=="object"||O.data===null||!("documentMetadata"in O.data)||typeof O.data.documentMetadata!=="object"||O.data.documentMetadata===null||!("documentId"in O.data.documentMetadata)||typeof O.data.documentMetadata.documentId!=="string")throw Error("Invalid team task document response");return q.byId(this.client,O.data.documentMetadata.documentId)}async validatePermissionsToken($){let O=Y(await this.client.storage.validateDocumentPermissionsToken({body:{token:$}}));return{document:q.byId(this.client,O.document_id),user:O.user_id?P.byId(this.client,O.user_id):void 0,accessLevel:O.access_level,expiresAt:O.exp,issuer:O.iss}}async createUpload($){let O={documentName:$.name,sha:$.sha,fileType:$.fileType,mimeType:$.mimeType,projectId:$.project?.id,teamId:$.team?.id,branchedFromId:$.branchedFrom?.id,emailAttachmentId:$.attachment?.id,isTask:$.isTask},j=Y(await this.client.storage.createDocument({body:O})).data;return{document:q.byId(this.client,j.documentMetadata.documentId),uploadUrl:j.presignedUrl??void 0,contentType:j.contentType,content:j.documentMetadata.content}}constructor($){this.client=$}byId($){return q.byId(this.client,$)}create($){return q.create(this.client,$)}async createCanvas($){let O=Y(await this.client.storage.createCanvasHandler({body:{documentName:$.name,projectId:$.project?.id}}));return q.byId(this.client,O.documentId)}createSnippet($){return q.createSnippet(this.client,$)}createSkill($){return q.createSkill(this.client,$)}systemSkills(){return Aj.list(this.client)}search($,O){return q.search(this.client,$,O)}recent($){return q.recent(this.client,$)}recentlyDeleted(){return q.recentlyDeleted(this.client)}}class BO extends A{async fetch(){let{attachment:$}=Y(await this.client.email.getAttachment({path:{id:this.id}}));return $}static byId($,O){return new BO($,O)}static from($,O){return new BO($,O.db_id,O)}filename=this.field("filename");mimeType=this.field("mime_type");size=this.field("size_bytes");dataUrl=this.field("data_url");sfsId=this.field("sfs_id");contentId=this.field("content_id");async toDocument(){let{document_id:$}=Y(await this.client.email.getAttachmentDocumentId({path:{id:this.id}}));return q.byId(this.client,$)}}class U$ extends X${access=new o(this.client,"email_thread",this);async followup(){return Y(await this.client.storage.getEmailFollowup({path:{thread_id:this.id}}))}async setFollowup($){return Y(await this.client.storage.setEmailFollowup({path:{thread_id:this.id},body:$}))}async calendarInvitations(){return Y(await this.client.email.getThreadCalendarInvitations({path:{thread_id:this.id}}))}async addEventToCalendar($,O,j={}){let x=Y(await this.client.email.copyThreadCalendarInvitation({path:{thread_id:this.id,message_id:$.id,invitation_id:O.id},body:{calendarId:j.calendar?.id}}));return $$.fromRecord(this.client,x)}async update($){await this.mutate((O)=>O.storage.editThreadV2({path:{thread_id:this.id},body:{projectId:$.project===void 0?void 0:$.project?.id??null,sharePermission:$.sharePermission?n$($.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 U$($,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",($)=>H$.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)=>D$.from(this.client,j))}async attachments(){let{messages:$}=await this.detail.get();return $.flatMap((O)=>O.attachments.map((j)=>BO.from(this.client,j)))}async reply($){let O=$.subject??await this.subject()??"",{message:j}=await this.mutate((x)=>x.email.sendMessage({body:{message:{thread_db_id:this.id,replying_to_id:$.replyingTo?.id??null,to:$.to,cc:$.cc??null,bcc:$.bcc??null,subject:O,body_text:$.bodyText}}}));return j.db_id?D$.byId(this.client,j.db_id):void 0}async archive($=!0){await this.mutate((O)=>O.email.archiveThread({path:{id:this.id},body:{value:$}}))}static async archiveMany($,O,j=!0){let x=[];for(let S=0;S<O.length;S+=100){let G=O.slice(S,S+100),Z=Y(await $.email.archiveThreads({body:{thread_ids:G.map((K)=>K.id),value:j}})),X=new Set(Z.failed_thread_ids);for(let K of G)if(K.detail.clear(),X.has(K.id))x.push(K)}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 U$($,O.thread_id)})}class D$ extends A{async fetch(){return Y(await this.client.email.getMessage({path:{id:this.id}}))}static byId($,O){return new D$($,O)}static from($,O){return new D$($,O.db_id,O)}static async send($,O){let{message:j}=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?D$.byId($,j.db_id):void 0}subject=this.field("subject");from=this.field("from");to=this.field("to");cc=this.field("cc");bcc=this.field("bcc");body=this.field("body_parsed");sentAt=this.field("internal_date_ts");labels=this.field("labels");link=this.mappedField("link_id",($)=>H$.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 U$.byId(this.client,(await this.detail.get()).thread_db_id)}}class LO extends D${async draftContext(){let $=await this.detail.get();return{headers:{"X-Email-Link-Id":$.link_id},query:{draft_generation:$.draft_generation??0}}}static byId($,O){return new LO($,O)}draftGeneration=this.field("draft_generation");async update($){let{headers:O,query:j}=await this.draftContext();await this.mutate((x)=>x.email.createDraft({headers:O,body:{draft:{...Yx($),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((G)=>G.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 Yx($){let{bodyText:O,bodyHtml:j,bodyMacro:x,headers:S,includeSignature:G,draftGeneration:Z,thread:X,replyingTo:K,...L}=$;return{...L,body_text:O,body_html:j===void 0?void 0:btoa(Array.from(new TextEncoder().encode(j),(Q)=>String.fromCharCode(Q)).join("")).replaceAll("+","-").replaceAll("/","_").replaceAll("=",""),body_macro:x,headers_json:S,include_signature:G,draft_generation:Z,thread_db_id:X?.id,replying_to_id:K?.id}}class NO 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 NO($,O,void 0,j)}static from($,O,j){return new NO($,O.id,O,j)}async fetch(){let $=Y(await this.client.email.listEmailFilters({headers:this.headers})).filters.find((O)=>O.id===this.id);if(!$)throw new E(`Email filter ${this.id} is unavailable`);return $}emailAddress=this.field("email_address");emailDomain=this.field("email_domain");isImportant=this.field("is_important");async setImportant($){let O=await this.detail.get();await this.mutate((j)=>j.email.upsertEmailFilter({headers:this.headers,body:{email_address:O.email_address,email_domain:O.email_domain,is_important:$}}))}async delete(){await this.mutate(($)=>$.email.deleteEmailFilter({path:{id:this.id},headers:this.headers}))}}class jO 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 jO($,O)}static async list($){let{labels:O}=Y(await $.email.listLabels());return O.map((j)=>new jO($,j.id,j))}static async create($,O){let{label:j}=Y(await $.email.createLabel({body:{label_name:O}}));if(!j.id)throw new f("created label has no id");return new jO($,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 Qx{client;async createDraft($,O){let j=Y(await this.client.email.createDraft({body:{draft:Yx($)},headers:O?{"X-Email-Link-Id":O.id}:void 0}));if(!j.draft.db_id)throw Error("Draft response has no message id");return LO.byId(this.client,j.draft.db_id)}draftById($){return LO.byId(this.client,$)}async*scheduled($){let O=$?.pageSize??100;if(!Number.isInteger(O)||O<1)throw Error("pageSize must be positive");let j=Math.min(O,1000);for(let x=0;;x+=j){let S=Y(await this.client.email.getScheduledMessages({query:{offset:x,limit:j},headers:$?.inbox?{"X-Email-Link-Id":$.inbox.id}:void 0}));for(let G of S.messages)yield LO.byId(this.client,G.db_id);if(S.messages.length<j)return}}async filters($){return Y(await this.client.email.listEmailFilters({headers:$?{"X-Email-Link-Id":$.id}:void 0})).filters.map((O)=>NO.from(this.client,O,$))}async upsertFilter($,O){return NO.from(this.client,Y(await this.client.email.upsertEmailFilter({headers:O?{"X-Email-Link-Id":O.id}:void 0,body:{email_address:$.emailAddress,email_domain:$.emailDomain,is_important:$.isImportant}})).filter,O)}async contacts(){return Y(await this.client.email.listContacts()).contacts}reminders($){let{inboxes:O,...j}=$??{};return c(async(x)=>{let S=Y(await this.client.storage.listEmailReminders({query:{...j,inboxIds:O?.map((G)=>G.id),cursor:x}}));return{items:S.items.map(({threadId:G,...Z})=>({...Z,thread:U$.byId(this.client,G)})),nextCursor:S.nextCursor}})}constructor($){this.client=$}byId($){return U$.byId(this.client,$)}message($){return D$.byId(this.client,$)}attachment($){return BO.byId(this.client,$)}link($){return H$.byId(this.client,$)}links(){return H$.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 D$.send(this.client,$)}search($,O){return U$.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)=>U$.byId(this.client,x.id)),nextCursor:j.next_cursor}})}label($){return jO.byId(this.client,$)}labels(){return jO.list(this.client)}createLabel($){return jO.create(this.client,$)}archive($,O=!0){return U$.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 HO{client;id;constructor($,O){this.client=$;this.id=O}static byId($,O){return new HO($,O)}async delete(){Y(await this.client.storage.deleteEntityMention({path:{mention_id:this.id}}))}toJSON(){return{id:this.id}}}class Jx{client;constructor($){this.client=$}byId($){return HO.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 HO.byId(this.client,j.id)}}function Vx($,O){return{chat:UO.byId($,O.id),name:O.name,announcements:O.announcements}}class UO extends A{static byId($,O){return new UO($,O)}static from($,O){return new UO($,O.jid,O)}async fetch(){let{chats:$}=Y(await this.client.storage.whatsappChats()),O=$.find((j)=>j.jid===this.id);if(!O)throw new E("WhatsApp chat is not available");return O}kind=this.field("kind");name=this.field("name");lastActivityAt=this.field("lastActivityAt");archived=this.field("archived");pinned=this.field("pinned");canAdd=this.field("canAdd");cannotAddReason=this.field("cannotAddReason");community=this.mappedField("community",($)=>$?Vx(this.client,$):void 0);added=this.mappedField("added",($)=>$?y$.byId(this.client,$.id):void 0);shared=this.mappedField("shared",($)=>$?y$.byId(this.client,$.id):void 0);async add(){let $=await this.kind(),O=await this.mutate((j)=>j.storage.externalChatAdd({body:{provider:"whatsapp",remoteId:this.id,kind:$}}));return y$.byId(this.client,O.chatId)}async refresh(){return this.detail.clear(),await this.detail.get(),this}}class _$ extends A{chat;constructor($,O,j,x){super($,j,x);this.chat=O}static byId($,O,j){return new _$($,O,j)}static from($,O,j){return new _$($,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",($)=>$?_$.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 xO{chat;id;record;constructor($,O,j){this.chat=$;this.id=O;this.record=j}static byId($,O){return new xO($,O)}static from($,O){return new xO($,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 SO{id;chat;filename;kind;constructor($,O,j,x){this.id=$;this.chat=O;this.filename=j;this.kind=x}static byId($,O){return new SO(O,$)}static from($,O){return new SO(O.uploadId,$,O.filename,O.kind)}toJSON(){return{id:this.id,chat:this.chat.id,filename:this.filename,kind:this.kind}}}class ZO extends A{chat;constructor($,O,j,x){super($,j,x);this.chat=O}static byId($,O,j){return new ZO($,O,j)}static from($,O,j){return new ZO($,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",($)=>$?_$.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:SO.byId(this.chat,x.uploadId),caption:x.caption??void 0})).with({type:"mutation"},(x)=>({type:"mutation",message:_$.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)=>xO.byId(this.chat,S))})).exhaustive();return{idempotencyKey:$.idempotencyKey,message:j,replyTo:$.replyTo?_$.byId(this.client,this.chat,$.replyTo):void 0}}async refresh(){return this.detail.clear(),await this.detail.get(),this}}class y$ extends I${entityType="external_chat";static byId($,O){return new y$($,O)}async fetch(){return Y(await this.client.storage.externalChat({path:{chat_id:this.id}}))}provider=this.field("provider");name=this.field("name");kind=this.field("kind");canSend=this.field("canSend");sendReason=this.field("sendReason");sendingIdentity=this.field("sendingIdentity");unreadCount=this.field("unreadCount");backfill=this.field("backfill");limits=this.field("limits");members=this.field("members");participants=this.mappedField("members",($)=>($?.participants??[]).map((O)=>xO.from(this,O)));disappearingSeconds=this.field("disappearingSeconds");owner=this.mappedField("userId",($)=>P.byId(this.client,$));async community(){let{provider:$,community:O}=await this.detail.get();if(!O)return;return k($).with("whatsapp",()=>Vx(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)=>_$.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 SO.from(this,O)}async send($,O){if(O.replyTo)this.assertChat(O.replyTo.chat);let j=k($).returnType().with({type:"text"},(S)=>{let G=S.mentions??[];for(let Z of G)this.assertChat(Z.chat);return{type:"text",text:S.text,mentions:G.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 ZO.from(this.client,this,x)}async sends(){return Y(await this.client.storage.externalChatSends({path:{chat_id:this.id}})).map(($)=>ZO.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)=>ZO.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:_$.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 Wx{client;constructor($){this.client=$}async list(){return Y(await this.client.storage.externalChats()).map(($)=>y$.byId(this.client,$.id))}byId($){return y$.byId(this.client,$)}}class Bx{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 XO extends I${entityType="foreign_entity";async fetch(){return Y(await this.client.storage.getForeignEntity({path:{id:this.id}}))}static byId($,O){return new XO($,O)}static fromRecord($,O){return new XO($,O.id,O)}foreignEntityId=this.field("foreignEntityId");source=this.field("foreignEntitySource");storedForId=this.field("storedForId");storedForAuthEntity=this.field("storedForAuthEntity");createdAt=this.field("createdAt");updatedAt=this.field("updatedAt");async metadata(){return(await this.detail.get()).metadata}}function n1({login:$,...O}){return{...O,login:$??void 0}}class Lx{client;constructor($){this.client=$}byId($){return XO.byId(this.client,$)}async bySource($,O){return XO.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(n1),assignees:j.map(n1),labels:x.map(({color:S,...G})=>({...G,color:S??void 0}))}}}class p${form;id;constructor($,O){this.form=$;this.id=O}static byId($,O){return new p$($,O)}async detail(){let O=(await this.form.schema()).sections.flatMap((j)=>j.kind==="questions"?j.questions:[]).find((j)=>j.id===this.id);if(!O)throw new E(`question ${this.id} is not on form ${this.form.id}`);return O}async title(){return(await this.detail()).title}async column(){return C$.byId(await this.form.table(),(await this.detail()).column)}async options(){return(await this.detail()).options.map(($)=>zO.byId(this,$.id))}}class zO{question;id;constructor($,O){this.question=$;this.id=O}static byId($,O){return new zO($,O)}async detail(){let $=(await this.question.detail()).options.find((O)=>O.id===this.id);if(!$)throw new E(`option ${this.id} is not on question ${this.question.id}`);return $}async label(){return(await this.detail()).label}async color(){return(await this.detail()).color??void 0}}class RO{form;id;detail;constructor($,O,j){this.form=$;this.id=O;this.detail=new W$(()=>this.load(),j)}async load(){let $=await this.form.myResponse();if($.response.id!==this.id)throw new E(`response ${this.id} is not your current response`);return $}static byId($,O,j){return new 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 a${form;id;constructor($,O){this.form=$;this.id=O}static byId($,O){return new a$($,O)}async detail(){let $=(await this.form.schema()).sections.find((O)=>O.id===this.id);if(!$)throw new E(`section ${this.id} is not on form ${this.form.id}`);return $}async title(){return(await this.detail()).title}async questions(){let $=await this.detail();return $.kind==="questions"?$.questions.map((O)=>p$.byId(this.form,O.id)):[]}}class Cj{entityType;id;constructor($,O){this.entityType=$;this.id=O}static byId($,O){return new Cj($,O)}}class v$ extends A{async fetch(){return Y(await this.client.storage.getForm({path:{id:this.id}}))}static byId($,O){return new v$($,O)}static async create($,O){let j=Y(await $.storage.createForm({body:{name:O.name,source:O.table?{kind:"table",databaseId:O.table.database.id,tableId:O.table.id}:{kind:"new"}}}));return new v$($,j.form.id,j)}static async list($,O){if(!O)return Y(await $.storage.listAccessibleForms()).map(({form:S})=>new v$($,S.id));return Y(await $.storage.listForms({query:{databaseId:O.id}})).map((x)=>new v$($,x.id))}schema(){return this.detail.get()}name=this.mappedField("form",($)=>$.name);description=this.mappedField("form",($)=>$.description);owner=this.mappedField("form",($)=>P.byId(this.client,$.ownerId));database=this.mappedField("form",($)=>V$.byId(this.client,$.databaseId));table=this.mappedField("form",($)=>J$.byId(V$.byId(this.client,$.databaseId),$.tableId));audience=this.mappedField("form",($)=>$.audience);status=this.mappedField("form",($)=>$.status);closesAt=this.mappedField("form",($)=>$.closesAt??void 0);access=this.field("access");async sections(){return(await this.detail.get()).sections.map(($)=>a$.byId(this,$.id))}async questions(){return(await this.detail.get()).sections.flatMap(($)=>$.kind==="questions"?$.questions.map((O)=>p$.byId(this,O.id)):[])}async update($){return await this.mutate((O)=>O.storage.updateForm({path:{id:this.id},body:$})),this}assertOwns($){if($.form.id!==this.id)throw new f(`question or section does not belong to form ${this.id}`)}async replaceLayout($){let O=await this.table(),j=(Z)=>{if(Z.table.id!==O.id||Z.table.database.id!==O.database.id)throw new f(`column does not belong to form ${this.id}'s table`);return Z.id},x=(Z)=>({conjunction:Z.conjunction,conditions:Z.conditions.map((X)=>k(X).with({kind:"group"},(K)=>({kind:"group",...x(K)})).with({kind:"condition"},(K)=>({kind:"condition",column:j(K.column),test:k(K.test).with({kind:"options"},(L)=>({...L,options:L.options.map((Q)=>Q.id)})).with({kind:"entities"},(L)=>({...L,entities:L.entities.map((Q)=>Q.id)})).with({kind:Z$.union("presence","text","number","date","dateRange","checkbox")},(L)=>L).exhaustive()})).exhaustive())}),S={sections:$.map((Z)=>{if(Z.section)this.assertOwns(Z.section);let X={id:Z.section?.id??l$(),title:Z.title,description:Z.description??""};return k(Z).with({kind:"booking"},(K)=>({...X,kind:"booking",target:K.target})).with({kind:"gate"},(K)=>({...X,kind:"gate",rules:x(K.rules),message:K.message})).with({kind:"questions"},(K)=>({...X,kind:"questions",questions:K.questions.map((L)=>{if(L.question)this.assertOwns(L.question);return{id:L.question?.id??l$(),column:j(L.column),helpText:L.helpText??"",required:L.required??!1,widget:L.widget??null}})})).exhaustive()})},G=await this.mutate((Z)=>Z.storage.putFormLayout({path:{id:this.id},body:S}));return{form:this,publicationError:G.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((G)=>G.id)})).with({type:"options"},(S)=>({type:"options",value:S.value.map((G)=>{if(G.question.id!==O.id||G.question.form.id!==this.id)throw new f("option does not belong to the answered question");return{id:G.id}})})).with({type:"entities"},(S)=>({type:"entities",value:S.value.map(({entityType:G,entity:Z})=>({entityType:G,entityId:Z.id}))})).with({type:Z$.union("text","number","boolean","date","date_range","link","clear")},(S)=>S).exhaustive();return{question:O.id,value:x}})}unlockedBooking($){return $?{...$,section:a$.byId(this,$.section)}:void 0}async outcome($,O){return k($).with({outcome:"stopped"},(j)=>({...j,section:a$.byId(this,j.section)})).with({outcome:"submitted"},async(j)=>{let x=F$.byId(await this.table(),j.row),S=this.unlockedBooking(j.booking);return{outcome:"submitted",response:RO.byId(this,j.response,{status:"submitted",row:x,answers:O,booking:S}),row:x,...S?{booking:S}:{}}}).exhaustive()}async submit($){let O={answers:this.wireAnswers($)};return this.outcome(Y(await this.client.storage.submitFormResponse({path:{id:this.id},body:O})),$)}async editResponse($){let O={answers:this.wireAnswers($)};return this.outcome(Y(await this.client.storage.editMyFormResponse({path:{id:this.id},body:O})),$)}async myResponse(){let $=Y(await this.client.storage.getMyFormResponse({path:{id:this.id}})),O=await this.table(),j=await Promise.all($.answers.map(async(G)=>{let Z=p$.byId(this,G.question),X=await k(G.value).with({type:"options"},(K)=>({type:"options",value:K.value.map((L)=>{if(!("id"in L))throw new f("stored form answers must reference options by id");return zO.byId(Z,L.id)})})).with({type:"entities"},(K)=>({type:"entities",value:K.value.map((L)=>({entityType:L.entityType,entity:Cj.byId(L.entityType,L.entityId)}))})).with({type:"rows"},async(K)=>{let L=await Z.detail();if(L.kind.type!=="relation")throw new f("row answer requires a relation question");let Q=J$.byId(V$.byId(this.client,L.kind.database),L.kind.table);return{type:"rows",value:K.value.map((J)=>F$.byId(Q,J))}}).with({type:Z$.union("text","number","boolean","date","date_range","link","clear")},(K)=>K).exhaustive(()=>{throw new f(`answer to question ${Z.id} has a type this SDK doesn't know`)});return{question:Z,value:X}})),x=$.response.row?F$.byId(O,$.response.row):void 0,S=this.unlockedBooking($.booking);return{...S?{booking:S}:{},response:RO.byId(this,$.response.id,{status:$.response.status,row:x,answers:j,booking:S}),status:$.response.status,stoppedAtSection:$.response.stoppedAtSection?a$.byId(this,$.response.stoppedAtSection):void 0,row:x,submittedAt:$.response.submittedAt,updatedAt:$.response.updatedAt,answers:j}}async responseSummary(){let $=Y(await this.client.storage.getFormResponseSummary({path:{id:this.id}}));return{...$,stoppedBySection:$.stoppedBySection.map((O)=>({section:a$.byId(this,O.section),count:O.count}))}}async tally(){return Y(await this.client.storage.getFormTally({path:{id:this.id}})).questions.map((O)=>{let j=p$.byId(this,O.question);return{question:j,responses:O.responses,buckets:O.buckets.flatMap((x)=>k(x.value).with({kind:"option"},(S)=>[{count:x.count,value:{kind:"option",option:zO.byId(j,S.option)}}]).with({kind:"checkbox"},(S)=>[{count:x.count,value:S}]).exhaustive((S)=>{return console.warn("macro sdk: unknown form tally bucket",S),[]}))}})}async sharePermissions(){return Y(await this.client.storage.getFormPermissions({path:{id:this.id}}))}updateSharePermissions($){return this.mutate((O)=>O.storage.updateFormPermissions({path:{id:this.id},body:$}))}webUrl(){return`${this.client.webAppUrl}/app/form/${this.id}`}respondUrl(){return`${this.client.webAppUrl}/app/form/${this.id}/respond`}}class Nx{client;constructor($){this.client=$}byId($){return v$.byId(this.client,$)}create($){return v$.create(this.client,$)}list($){return v$.list(this.client,$)}}class DO extends 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 Ux(this.client,this,$.changeset):void 0,error:$.error??void 0}}}class Ux{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 zx{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 $j{client;id;constructor($,O){this.client=$;this.id=O}static byId($,O){return new $j($,O)}async claim($){let O=Y(await this.client.storage.claimHarnessPairing({path:{pairing_id:this.id},body:{device_secret:$}}));return"harness"in O?{harness:B$.from(this.client,O.harness),token:O.token}:void 0}toJSON(){return{id:this.id}}}class Ix{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(($)=>l.byId(this.client,$.session_id))}pairing($){return _O.byId(this.client,$)}async createPairing($){let O=Y(await this.client.storage.createHarnessPairing({body:$}));return{pairing:_O.byId(this.client,O.code),device:$j.byId(this.client,O.pairing_id),deviceSecret:O.device_secret,expiresAt:O.expires_at,pollIntervalSeconds:O.poll_interval_seconds}}}var B7="00000001-0000-0000-0000-000000000002",L7="00000001-0000-0000-0002-000000000004";function N7($){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 M$ extends q{static byId($,O){return new M$($,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}}));return new M$($,j)}static async forPullRequest($,O){let j=N7(O),{pullRequests:x}=Y(await $.storage.getGithubPullRequestTasks({body:{githubKeys:[j]}}));return(x[0]?.taskIds??[]).map((S)=>new M$($,S))}async completed(){let{subType:$}=await this.detail.get();if($!=="task")return;let j=(await this.properties()).find((x)=>x.definition.id===B7)?.value;return j?.type==="SelectOption"&&j.value.includes(L7)}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 M$($,O.document_id)})}class GO extends A{access=new o(this.client,"initiative",this);static byId($,O){return new GO($,O)}static from($,O){return new GO($,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",($)=>P.byId(this.client,$));members=this.mappedField("memberIds",($)=>$.map((O)=>P.byId(this.client,O)));tasks=this.mappedField("taskIds",($)=>$.map((O)=>M$.byId(this.client,O)));accessLevel=this.field("userAccessLevel");sharePermissions=this.field("sharePermission");async update($){await this.mutate((O)=>O.storage.updateInitiative({path:{initiative_id:this.id},body:{name:$.name,memberIds:$.members?.map((j)=>j.id),sharePermission:$.sharePermission?n$($.sharePermission):void 0}}))}async delete(){await this.mutate(($)=>$.storage.deleteInitiative({path:{initiative_id:this.id}}))}}class Tx{client;constructor($){this.client=$}byId($){return GO.byId(this.client,$)}async list(){return Y(await this.client.storage.listInitiatives()).initiatives.map(($)=>GO.byId(this.client,$.id))}async create($){return GO.from(this.client,Y(await this.client.storage.createInitiative({body:{name:$.name,description:$.description,memberIds:$.members?.map((O)=>O.id),shareWithTeam:$.shareWithTeam,propertyValues:$.propertyValues}})))}}class Hx{client;constructor($){this.client=$}byId($){return R$.byId(this.client,$)}async create($){return R$.from(this.client,Y(await this.client.storage.meetingCreate({body:$})))}async list(){return Y(await this.client.storage.meetingList()).meetings.map(($)=>R$.from(this.client,$))}async active(){return Y(await this.client.storage.meetingListActive()).meetings.map(($)=>R$.from(this.client,$))}async lookup($){return R$.from(this.client,Y(await this.client.storage.meetingLookup({path:{token:$}})))}}class IO extends A{async fetch(){return Y(await this.client.notification.getTypedNotificationById({path:{notification_id:this.id}}))}static byId($,O){return new IO($,O)}static from($,O){return new IO($,O.id,O)}static list($,O){return c(async(j)=>{let x=Y(await $.notification.listTypedNotifications({query:{...O?.pageSize?{limit:O.pageSize}:{},...O?.states!==void 0?{states:O.states.join(",")}:{},...j?{cursor:j}:{}}}));return{items:x.items.map((S)=>IO.from($,S)),nextCursor:x.next_cursor}})}type=this.field("notification_event_type");createdAt=this.field("created_at");updatedAt=this.field("updated_at");state=this.field("state");done=this.mappedField("state",($)=>$==="done");sent=this.field("sent");viewedAt=this.field("viewed_at");deletedAt=this.field("deleted_at");owner=this.mappedField("owner_id",($)=>P.byId(this.client,$));sender=this.mappedField("sender_id",($)=>$?P.byId(this.client,$):void 0);metadata=this.field("notification_metadata");async seen(){return await this.state()!=="unseen"}async markSeen(){await this.mutate(($)=>$.notification.bulkMarkNotificationsSeen({body:{notificationIds:[this.id]}}))}async markDone(){await this.mutate(($)=>$.notification.bulkMarkNotificationsDone({body:{notificationIds:[this.id]}}))}async markUndone(){await this.mutate(($)=>$.notification.bulkMarkNotificationsUndone({body:{notificationIds:[this.id]}}))}async delete(){await this.mutate(($)=>$.notification.deleteUserNotificationV2({path:{notification_id:this.id}}))}}class Rx{client;constructor($){this.client=$}byId($){return IO.byId(this.client,$)}list($){return IO.list(this.client,$)}async markSeen($){Y(await this.client.notification.bulkMarkNotificationsSeen({body:{notificationIds:$}}))}async markDone($){Y(await this.client.notification.bulkMarkNotificationsDone({body:{notificationIds:$}}))}async delete($){Y(await this.client.notification.bulkDeleteUserNotificationsV2({body:{notificationIds:$}}))}async preferences(){return Y(await this.client.notification.getNotificationTypePreferences())}async enableType($){Y(await this.client.notification.enableNotificationType({path:{notification_event_type:$}}))}async disableType($){Y(await this.client.notification.disableNotificationType({path:{notification_event_type:$}}))}}class Dx{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 _x{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 KO{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 KO($,j.id,j)}static byId($,O){return new KO($,O)}static fromRecord($,O){return new KO($,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 Mx{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 KO.fromRecord(this.client,x)})}create($){return KO.create(this.client,$)}definition($){return KO.byId(this.client,$)}async bulkEntityProperties($){return Y(await this.client.properties.getBulkEntityProperties({body:$}))}async updateEntityPropertyOptions($,O){return Y(await this.client.properties.bulkUpdateEntitiesPropertyOptions({body:{entities:$.map((x)=>x.propertyReference()),property_id:O.property.id,...O.add?{add_option_ids:O.add.map((x)=>x.id)}:{},...O.remove?{remove_option_ids:O.remove.map((x)=>x.id)}:{}}})).results}async addEntityPropertyOption($){return Y(await this.client.properties.addEntityPropertyOption({path:{...$.entity.propertyReference(),property_id:$.property.id,option_id:$.option.id}}))}async removeEntityPropertyOption($){return Y(await this.client.properties.removeEntityPropertyOption({path:{...$.entity.propertyReference(),property_id:$.property.id,option_id:$.option.id}}))}async tags(){return Y(await this.client.properties.listTags({}))}}function Px($){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 U7($){return k($).with({type:"multiple"},(O)=>({type:"multiple",triggers:O.triggers.map(Px)})).with({type:"cron"},Px).with({type:"events"},Px).exhaustive()}class h$ extends A{static byId($,O){return new h$($,O)}static from($,O){if(!O.id)throw Error("Routine response has no id");return new h$($,O.id,O)}async fetch(){return Y(await this.client.scheduledAction.getScheduledAction({path:{id:this.id}}))}name=this.field("name");trigger=this.field("trigger");enabled=this.field("enabled");runVisibility=this.field("run_visibility");nextRunAt=this.field("next_run_at");revision=this.field("configuration_revision");owner=this.mappedField("owner",($)=>P.byId(this.client,$));sourceTemplate=this.mappedField("template_id",($)=>$?h$.byId(this.client,$):void 0);async template(){let $=await this.client.scheduledAction.getScheduledActionTemplate({path:{id:this.id}});if($.response?.status===404)return;return this.toTemplate(Y($))}async shareAsTemplate($){return this.toTemplate(Y(await this.client.scheduledAction.shareScheduledActionTemplate({path:{id:this.id},body:$})))}async activateTemplate($){return h$.from(this.client,Y(await this.client.scheduledAction.activateScheduledActionTemplate({path:{id:this.id},body:{...Fj($),enabled:$.enabled??!0}})))}toTemplate($){return new s1(this,P.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:Fj($)}))}async setEnabled($){await this.mutate((O)=>O.scheduledAction.setScheduledActionEnabled({path:{id:this.id},body:{enabled:$}}))}async execute(){let $=Y(await this.client.scheduledAction.executeScheduledActionNow({path:{id:this.id}}));if($.resource)return k($.resource).with({type:"agent"},(O)=>l.byId(this.client,O.id)).with({type:"chat"},(O)=>G$.byId(this.client,O.id)).exhaustive();return $.chat_id?G$.byId(this.client,$.chat_id):void 0}async history(){return Y(await this.client.scheduledAction.listScheduledActionHistory({path:{id:this.id}})).map(($)=>new Ax(this,$))}async delete(){await this.mutate(($)=>$.scheduledAction.deleteScheduledAction({path:{id:this.id}}))}}class s1{routine;author;record;constructor($,O,j){this.routine=$;this.author=O;this.record=j}activate($){return this.routine.activateTemplate($)}toJSON(){return this.record}}class Ax{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:U7($.trigger),task:{...O}}}class Cx{client;constructor($){this.client=$}byId($){return h$.byId(this.client,$)}async create($){return h$.from(this.client,Y(await this.client.scheduledAction.createScheduledAction({body:{...Fj($),enabled:$.enabled??!0}})))}async list($){return Y(await this.client.scheduledAction.listScheduledActions({query:{include_events:$?.includeEvents}})).map((O)=>h$.from(this.client,O))}}class Fx{client;constructor($){this.client=$}byId($){return M$.byId(this.client,$)}create($){return M$.create(this.client,$)}forPullRequest($){return M$.forPullRequest(this.client,$)}search($,O){return M$.search(this.client,$,O)}}class Ex{client;constructor($){this.client=$}byId($){return S$.byId(this.client,$)}current(){return S$.current(this.client)}list(){return S$.list(this.client)}}class wx{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 qx{client;constructor($){this.client=$}byId($){return P.byId(this.client,$)}me(){return P.me(this.client)}async search($){let O=$.trim().toLocaleLowerCase();if(!O)throw Error("A person search needs a name or email.");let j=await this.client.contacts.getContacts();if(j.response?.status===404)return[];let{contacts:x}=Y(j),S=[...new Set(x)],G=[];for(let Z=0;Z<S.length;Z+=100){let X=S.slice(Z,Z+100),{names:K}=Y(await this.client.auth.getUserNamesWithEmail({body:{user_ids:X}})),L=new Map(K.map((Q)=>[Q.id,Q]));for(let Q of X){let J=L.get(Q)??{id:Q};if(`${[J.first_name,J.last_name].filter(Boolean).join(" ")} ${Q}`.toLocaleLowerCase().includes(O))G.push(P.fromName(this.client,J))}}return G}}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",($)=>P.byId(this.client,$));async scope(){let $=await this.detail.get();return $.workspace_id===$.created_by_user_id?"user":"team"}async update($){await this.mutate((O)=>O.storage.patchWebhook({path:{webhook_id:this.id},body:$}))}async rename($){await this.update({name:$})}async setUrl($){await this.update({endpoint_url:$})}async setFilters($){await this.update({filters:$})}async pause(){await this.update({status:"paused"})}async resume(){await this.update({status:"active"})}async delete(){await this.mutate(($)=>$.storage.deleteWebhook({path:{webhook_id:this.id}}))}async validate(){return this.mutate(($)=>$.storage.validateWebhook({path:{webhook_id:this.id}}))}}class fx{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 PO extends A{static byId($,O){return new PO($,O)}static from($,O){return new PO($,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",($)=>P.byId(this.client,$));async refresh(){return this.detail.clear(),await this.detail.get(),this}}class bx{client;constructor($){this.client=$}async account(){let{account:$}=Y(await this.client.storage.whatsappAccount());return $?PO.from(this.client,$):void 0}async chats(){return Y(await this.client.storage.whatsappChats()).chats.map(($)=>UO.from(this.client,$))}}function kx($){if("properties"in $.data)return $.data.properties;if($.tag==="calendarEvent")return $.data.extra.properties;return[]}function t1($,O,j){let x=[];for(let S of kx(O)){if(S.definition.data_type!=="TAG"||S.value?.type!=="SelectOption")continue;for(let G of S.value.value){let Z=j.get(G);if(Z&&!x.some((X)=>X.label===Z.label&&X.scope===Z.scope))x.push(Z)}}switch(O.tag){case"document":return{type:"document",id:O.data.id,entity:q.byId($,O.data.id),snapshot:O,tags:x,name:O.data.name,fileType:O.data.fileType,subType:O.data.subType?.type};case"chat":return{type:"ai_chat",id:O.data.id,entity:G$.byId($,O.data.id),snapshot:O,tags:x,name:O.data.name};case"project":return{type:"project",id:O.data.id,entity:n.byId($,O.data.id),snapshot:O,tags:x,name:O.data.name};case"emailThread":return{type:"email",id:O.data.id,entity:U$.byId($,O.data.id),snapshot:O,tags:x,subject:O.data.name,snippet:O.data.snippet,senderName:O.data.senderName,senderEmail:O.data.senderEmail,inboxVisible:O.data.inboxVisible,isRead:O.data.isRead,isDraft:O.data.isDraft};case"channel":return{type:"channel",id:O.data.channel.id,entity:b.byId($,O.data.channel.id),snapshot:O,tags:x,name:O.data.channel.name};case"channelThread":return{type:"channel_thread",id:O.data.id,entity:new m$($,O.data.channel_id,O.data.id),snapshot:O,tags:x,channelId:O.data.channel_id};case"call":return{type:"call",id:O.data.callId,entity:Q$.byId($,O.data.callId),snapshot:O,tags:x,createdBy:O.data.createdBy};case"calendarEvent":return{type:"calendar_event",id:O.data.id,entity:$$.byId($,O.data.id),snapshot:O,tags:x,title:O.data.title,status:O.data.status,location:O.data.location,conferenceUrl:O.data.conferenceUrl,conferenceProvider:O.data.conferenceProvider,time:O.data.time};case"foreignEntity":return{type:"foreign_entity",id:O.data.id,entity:XO.byId($,O.data.id),snapshot:O,tags:x,foreignEntityId:O.data.foreignEntityId,foreignEntitySource:O.data.foreignEntitySource,metadata:O.data.metadata};default:throw Error(`Unexpected workspace entity type: ${O.tag}`)}}var e1="00000000-0000-0000-0000-000000000000",gx={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"]},Ej=($)=>$.replace(/[A-Z]/g,(O)=>O.toLowerCase()),o1=($,O)=>$==null?O:{"&":[$,O]};function yx($,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,G]=x;if(S==="l")return;if(S==="!"){yx(G,`${O}.!`);return}if(S!=="&"&&S!=="|")throw Error(`Invalid workspace ${O}: use l, &, | or !.`);if(!Array.isArray(G)||G.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.`);G.forEach((Z,X)=>{yx(Z,`${O}.${S}[${X}]`)})}class wj{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,G,Z]of[["sortBy",$.sortBy,["recently_viewed","recently_updated","recently_created"]],["emailPreset",$.emailPreset,["signal"]],["tagsMatch",$.tagsMatch,["any","all"]]])if(G!==void 0&&!Z.includes(G))throw Error(`Invalid workspace ${S}: ${G}`);if($.includeTypes!==void 0&&(!Array.isArray($.includeTypes)||$.includeTypes.some((S)=>!Object.hasOwn(gx,S))))throw Error(`Invalid workspace includeTypes. Supported values: ${Object.keys(gx).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)yx($[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:e1}},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()),G=S.filter((X)=>Ej(X.email_address)===Ej(j)),Z=G[0];if(!Z)throw Error(`No connected inbox matches "${j}". Connected inboxes: ${S.map((X)=>X.email_address).join(", ")}.`);if(G.length>1)throw Error(`Multiple connected inboxes match "${j}"; cannot pick one.`);O.ef=o1(O.ef,{l:{Owner:Z.id}})}let x=$.includeTypes??($.emailPreset==="signal"?["email"]:void 0);if(x?.length){for(let[S,[G,Z]]of Object.entries(gx))if(!x.includes(S))O[G]={l:{[Z]:e1}}}if($.tags?.length){let S=(await this.sets()).flatMap((K)=>{let L=K.definition;if(!L)return[];return K.options.flatMap((Q)=>Q.value.type==="string"?[{id:Q.id,definitionId:L.id,label:Q.value.value,scope:K.scope==="user"?"personal":"team"}]:[])}),G=new Map;for(let K of $.tags){let L=S.filter((Q)=>Ej(Q.label)===Ej(K.label.trim())&&(!K.scope||Q.scope===K.scope));if(!L.length)throw Error(`Unknown tag "${K.label}". Available tags: ${S.map((Q)=>`${Q.label} (${Q.scope})`).join(", ")}.`);if($.tagsMatch==="all"&&L.length>1)throw Error(`Tag "${K.label}" is ambiguous; specify personal or team scope.`);for(let Q of L)G.set(Q.id,Q)}let X=[...G.values()].map((K)=>({l:{pd:K.definitionId,v:{so:K.id}}})).reduce((K,L)=>K===void 0?L:{[$.tagsMatch==="all"?"&":"|"]:[K,L]},void 0);O.propf=o1(O.propf,X)}return O}}class vx{client;constructor($){this.client=$}async page($={}){let O=new wj(this.client);return this.fetch(O,await O.body($),$.cursor)}async*list($={}){let O=new wj(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})),G=x.items.some((Z)=>kx(Z).some((X)=>X.definition.data_type==="TAG"))?await $.tagMap():new Map;return{items:x.items.map((Z)=>t1(this.client,Z,G)),nextCursor:x.next_cursor,hasMore:x.next_cursor!=null}}}function $2({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:G,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:K,url:L,...Q}){let J,I=K??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=G??3000,B=0,T=Q.signal??new AbortController().signal;while(!0){if(T.aborted)break;B++;let C=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)C.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:C,signal:T},_=new Request(L,D);if($)_=await $(L,D);let N=await(Q.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{H.cancel()}catch{}};T.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await H.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
`);let 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{T.removeEventListener("abort",g),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var U7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},z7=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},I7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},wj=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((K)=>encodeURIComponent(K))).join(z7(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let G=U7(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return AO({allowReserved:$,name:j,value:X})}).join(G);return x==="label"||x==="matrix"?G+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)}`},qj=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:G})=>{if(S instanceof Date)return G?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let K=[];Object.entries(S).forEach(([Q,J])=>{K=[...K,Q,$?J:encodeURIComponent(J)]});let L=K.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=I7(x),X=Object.entries(S).map(([K,L])=>AO({allowReserved:$,name:x==="deepObject"?`${j}[${K}]`:K,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var T7=/\{[^{}]+\}/g,H7=({path:$,url:O})=>{let j=O,x=O.match(T7);if(x)for(let S of x){let G=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))G=!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 K=$[Z];if(K===void 0||K===null)continue;if(Array.isArray(K)){j=j.replace(S,wj({explode:G,name:Z,style:X,value:K}));continue}if(typeof K==="object"){j=j.replace(S,qj({explode:G,name:Z,style:X,value:K,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${AO({name:Z,value:K})}`);continue}let L=encodeURIComponent(X==="label"?`.${K}`:K);j=j.replace(S,L)}return j},$2=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let G=S.startsWith("/")?S:`/${S}`,Z=($??"")+G;if(O)Z=H7({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function hx($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var O2=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var j2={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var x2=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let G in x){let Z=x[G];if(Z===void 0||Z===null)continue;let X=$[G]||O;if(Array.isArray(Z)){let K=wj({allowReserved:X.allowReserved,explode:!0,name:G,style:"form",value:Z,...X.array});if(K)S.push(K)}else if(typeof Z==="object"){let K=qj({allowReserved:X.allowReserved,explode:!0,name:G,style:"deepObject",value:Z,...X.object});if(K)S.push(K)}else{let K=AO({allowReserved:X.allowReserved,name:G,value:Z});if(K)S.push(K)}}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},R7=($,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(R7($,O.name))continue;let j=await O2(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var mx=($)=>$2({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:x2($.querySerializer),url:$.url}),ux=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=bj($.headers,O.headers),j},D7=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},bj=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?D7(j):Object.entries(j);for(let[S,G]of x)if(G===null)O.delete(S);else if(Array.isArray(G))for(let Z of G)O.append(S,Z);else if(G!==void 0)O.set(S,typeof G==="object"?JSON.stringify(G):G)}return O};class fj{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var X2=()=>({error:new fj,request:new fj,response:new fj}),_7=x2({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),M7={"Content-Type":"application/json"},Oj=($={})=>({...j2,headers:M7,parseAs:"auto",querySerializer:_7,...$});var cx=($={})=>{let O=ux(Oj(),$),j=()=>({...O}),x=(Q)=>{return O=ux(O,Q),j()},S=X2(),G=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:bj(O.headers,Q.headers),serializedBody:void 0};if(J.security)await 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=mx(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await G(Q),T={redirect:"follow",...V,body:hx(V)};z=new Request(B,T);for(let N of S.request.fns)if(N)z=await N(z,V);let C=V.fetch;W=await C(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?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 H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await W[N]();break;case"json":{let U=await W.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let _=await W.text(),w;try{w=JSON.parse(_)}catch{}throw w??_}catch(V){let B=V;for(let T of S.error.fns)if(T)B=await T(B,W,z,Q);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(Q)=>(J)=>Z({...J,method:Q}),K=(Q)=>async(J)=>{let{opts:I,url:z}=await G(J);return o1({...I,body:I.body,method:Q,onRequest:async(W,V)=>{let B=new Request(W,V);for(let T of S.request.fns)if(T)B=await T(B,I);return B},serializedBody:hx(I),url:z})};return{buildUrl:(Q)=>mx({...O,...Q}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:K("CONNECT"),delete:K("DELETE"),get:K("GET"),head:K("HEAD"),options:K("OPTIONS"),patch:K("PATCH"),post:K("POST"),put:K("PUT"),trace:K("TRACE")},trace:X("TRACE")}};var G2=cx(Oj());class K2{client;constructor($){this.client=$?.client??G2}}class Y2{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class kj extends K2{static __registry=new Y2;constructor($){super($);kj.__registry.set(this,$?.key)}discoverAgentCapabilitiesHandler($){return($.client??this.client).post({security:[{scheme:"bearer",type:"http"}],url:"/agent-capabilities/discover",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAgentCodingPreferences($){return($?.client??this.client).get({url:"/agent-coding-preferences",...$})}putAgentCodingPreferences($){return($.client??this.client).put({url:"/agent-coding-preferences",...$,headers:{"Content-Type":"application/json",...$.headers}})}listAgentConversations($){return($.client??this.client).get({security:[{scheme:"bearer",type:"http"}],url:"/agent-conversations/{channel_id}",...$})}startFreshAgentConversation($){return($.client??this.client).post({security:[{scheme:"bearer",type:"http"}],url:"/agent-conversations/{channel_id}/{bot_id}/start-fresh",...$,headers:{"Content-Type":"application/json",...$.headers}})}retryAgentConversationTurn($){return($.client??this.client).post({security:[{scheme:"bearer",type:"http"}],url:"/agent-conversations/{channel_id}/{bot_id}/turns/{source}/retry",...$,headers:{"Content-Type":"application/json",...$.headers}})}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}})}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}})}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 Q2({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:G,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:K,url:L,...Q}){let J,I=K??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=G??3000,B=0,T=Q.signal??new AbortController().signal;while(!0){if(T.aborted)break;B++;let C=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)C.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:C,signal:T},_=new Request(L,D);if($)_=await $(L,D);let N=await(Q.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{H.cancel()}catch{}};T.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await H.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
+`);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{T.removeEventListener("abort",g),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var z7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},I7=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},T7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},qj=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((K)=>encodeURIComponent(K))).join(I7(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let G=z7(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return AO({allowReserved:$,name:j,value:X})}).join(G);return x==="label"||x==="matrix"?G+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)}`},fj=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:G})=>{if(S instanceof Date)return G?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let K=[];Object.entries(S).forEach(([Q,J])=>{K=[...K,Q,$?J:encodeURIComponent(J)]});let L=K.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=T7(x),X=Object.entries(S).map(([K,L])=>AO({allowReserved:$,name:x==="deepObject"?`${j}[${K}]`:K,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var H7=/\{[^{}]+\}/g,R7=({path:$,url:O})=>{let j=O,x=O.match(H7);if(x)for(let S of x){let G=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))G=!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 K=$[Z];if(K===void 0||K===null)continue;if(Array.isArray(K)){j=j.replace(S,qj({explode:G,name:Z,style:X,value:K}));continue}if(typeof K==="object"){j=j.replace(S,fj({explode:G,name:Z,style:X,value:K,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${AO({name:Z,value:K})}`);continue}let L=encodeURIComponent(X==="label"?`.${K}`:K);j=j.replace(S,L)}return j},O2=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let G=S.startsWith("/")?S:`/${S}`,Z=($??"")+G;if(O)Z=R7({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function hx($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var j2=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var x2={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var S2=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let G in x){let Z=x[G];if(Z===void 0||Z===null)continue;let X=$[G]||O;if(Array.isArray(Z)){let K=qj({allowReserved:X.allowReserved,explode:!0,name:G,style:"form",value:Z,...X.array});if(K)S.push(K)}else if(typeof Z==="object"){let K=fj({allowReserved:X.allowReserved,explode:!0,name:G,style:"deepObject",value:Z,...X.object});if(K)S.push(K)}else{let K=AO({allowReserved:X.allowReserved,name:G,value:Z});if(K)S.push(K)}}return S.join("&")}},Z2=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},D7=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function X2($){for(let O of $.security??[]){if(D7($,O.name))continue;let j=await j2(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var mx=($)=>O2({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:S2($.querySerializer),url:$.url}),ux=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=kj($.headers,O.headers),j},_7=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},kj=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?_7(j):Object.entries(j);for(let[S,G]of x)if(G===null)O.delete(S);else if(Array.isArray(G))for(let Z of G)O.append(S,Z);else if(G!==void 0)O.set(S,typeof G==="object"?JSON.stringify(G):G)}return O};class bj{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var G2=()=>({error:new bj,request:new bj,response:new bj}),M7=S2({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),P7={"Content-Type":"application/json"},Oj=($={})=>({...x2,headers:P7,parseAs:"auto",querySerializer:M7,...$});var cx=($={})=>{let O=ux(Oj(),$),j=()=>({...O}),x=(Q)=>{return O=ux(O,Q),j()},S=G2(),G=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:kj(O.headers,Q.headers),serializedBody:void 0};if(J.security)await X2(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=mx(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await G(Q),T={redirect:"follow",...V,body:hx(V)};z=new Request(B,T);for(let N of S.request.fns)if(N)z=await N(z,V);let C=V.fetch;W=await C(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?Z2(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await W[N]();break;case"json":{let U=await W.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let _=await W.text(),w;try{w=JSON.parse(_)}catch{}throw w??_}catch(V){let B=V;for(let T of S.error.fns)if(T)B=await T(B,W,z,Q);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(Q)=>(J)=>Z({...J,method:Q}),K=(Q)=>async(J)=>{let{opts:I,url:z}=await G(J);return $2({...I,body:I.body,method:Q,onRequest:async(W,V)=>{let B=new Request(W,V);for(let T of S.request.fns)if(T)B=await T(B,I);return B},serializedBody:hx(I),url:z})};return{buildUrl:(Q)=>mx({...O,...Q}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:K("CONNECT"),delete:K("DELETE"),get:K("GET"),head:K("HEAD"),options:K("OPTIONS"),patch:K("PATCH"),post:K("POST"),put:K("PUT"),trace:K("TRACE")},trace:X("TRACE")}};var K2=cx(Oj());class Y2{client;constructor($){this.client=$?.client??K2}}class Q2{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 gj extends Y2{static __registry=new Q2;constructor($){super($);gj.__registry.set(this,$?.key)}discoverAgentCapabilitiesHandler($){return($.client??this.client).post({security:[{scheme:"bearer",type:"http"}],url:"/agent-capabilities/discover",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAgentCodingPreferences($){return($?.client??this.client).get({url:"/agent-coding-preferences",...$})}putAgentCodingPreferences($){return($.client??this.client).put({url:"/agent-coding-preferences",...$,headers:{"Content-Type":"application/json",...$.headers}})}listAgentConversations($){return($.client??this.client).get({security:[{scheme:"bearer",type:"http"}],url:"/agent-conversations/{channel_id}",...$})}startFreshAgentConversation($){return($.client??this.client).post({security:[{scheme:"bearer",type:"http"}],url:"/agent-conversations/{channel_id}/{bot_id}/start-fresh",...$,headers:{"Content-Type":"application/json",...$.headers}})}retryAgentConversationTurn($){return($.client??this.client).post({security:[{scheme:"bearer",type:"http"}],url:"/agent-conversations/{channel_id}/{bot_id}/turns/{source}/retry",...$,headers:{"Content-Type":"application/json",...$.headers}})}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}})}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}})}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 J2({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:G,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:K,url:L,...Q}){let J,I=K??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=G??3000,B=0,T=Q.signal??new AbortController().signal;while(!0){if(T.aborted)break;B++;let C=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)C.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:C,signal:T},_=new Request(L,D);if($)_=await $(L,D);let N=await(Q.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{H.cancel()}catch{}};T.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await H.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
`);let 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{T.removeEventListener("abort",g),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var P7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},A7=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},C7=($)=>{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((K)=>encodeURIComponent(K))).join(A7(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let G=P7(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return CO({allowReserved:$,name:j,value:X})}).join(G);return x==="label"||x==="matrix"?G+Z:Z},CO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},yj=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:G})=>{if(S instanceof Date)return G?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let K=[];Object.entries(S).forEach(([Q,J])=>{K=[...K,Q,$?J:encodeURIComponent(J)]});let L=K.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=C7(x),X=Object.entries(S).map(([K,L])=>CO({allowReserved:$,name:x==="deepObject"?`${j}[${K}]`:K,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var F7=/\{[^{}]+\}/g,E7=({path:$,url:O})=>{let j=O,x=O.match(F7);if(x)for(let S of x){let G=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))G=!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 K=$[Z];if(K===void 0||K===null)continue;if(Array.isArray(K)){j=j.replace(S,gj({explode:G,name:Z,style:X,value:K}));continue}if(typeof K==="object"){j=j.replace(S,yj({explode:G,name:Z,style:X,value:K,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${CO({name:Z,value:K})}`);continue}let L=encodeURIComponent(X==="label"?`.${K}`:K);j=j.replace(S,L)}return j},J2=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let G=S.startsWith("/")?S:`/${S}`,Z=($??"")+G;if(O)Z=E7({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function dx($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var V2=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var W2={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var B2=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let G in x){let Z=x[G];if(Z===void 0||Z===null)continue;let X=$[G]||O;if(Array.isArray(Z)){let K=gj({allowReserved:X.allowReserved,explode:!0,name:G,style:"form",value:Z,...X.array});if(K)S.push(K)}else if(typeof Z==="object"){let K=yj({allowReserved:X.allowReserved,explode:!0,name:G,style:"deepObject",value:Z,...X.object});if(K)S.push(K)}else{let K=CO({allowReserved:X.allowReserved,name:G,value:Z});if(K)S.push(K)}}return S.join("&")}},L2=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},w7=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function N2($){for(let O of $.security??[]){if(w7($,O.name))continue;let j=await V2(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var lx=($)=>J2({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:B2($.querySerializer),url:$.url}),rx=($,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},q7=($)=>{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?q7(j):Object.entries(j);for(let[S,G]of x)if(G===null)O.delete(S);else if(Array.isArray(G))for(let Z of G)O.append(S,Z);else if(G!==void 0)O.set(S,typeof G==="object"?JSON.stringify(G):G)}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 U2=()=>({error:new vj,request:new vj,response:new vj}),f7=B2({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),b7={"Content-Type":"application/json"},jj=($={})=>({...W2,headers:b7,parseAs:"auto",querySerializer:f7,...$});var px=($={})=>{let O=rx(jj(),$),j=()=>({...O}),x=(Q)=>{return O=rx(O,Q),j()},S=U2(),G=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:hj(O.headers,Q.headers),serializedBody:void 0};if(J.security)await N2(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let I=J,z=lx(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await G(Q),T={redirect:"follow",...V,body:dx(V)};z=new Request(B,T);for(let N of S.request.fns)if(N)z=await N(z,V);let C=V.fetch;W=await C(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?L2(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await W[N]();break;case"json":{let U=await W.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let _=await W.text(),w;try{w=JSON.parse(_)}catch{}throw w??_}catch(V){let B=V;for(let T of S.error.fns)if(T)B=await T(B,W,z,Q);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(Q)=>(J)=>Z({...J,method:Q}),K=(Q)=>async(J)=>{let{opts:I,url:z}=await G(J);return Q2({...I,body:I.body,method:Q,onRequest:async(W,V)=>{let B=new Request(W,V);for(let T of S.request.fns)if(T)B=await T(B,I);return B},serializedBody:dx(I),url:z})};return{buildUrl:(Q)=>lx({...O,...Q}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:K("CONNECT"),delete:K("DELETE"),get:K("GET"),head:K("HEAD"),options:K("OPTIONS"),patch:K("PATCH"),post:K("POST"),put:K("PUT"),trace:K("TRACE")},trace:X("TRACE")}};var z2=px(jj());class I2{client;constructor($){this.client=$?.client??z2}}class T2{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class mj extends I2{static __registry=new T2;constructor($){super($);mj.__registry.set(this,$?.key)}deleteAgentApiKey($){return($.client??this.client).delete({url:"/agents/{agent_id}/api-key",...$})}getAgentApiKey($){return($.client??this.client).get({url:"/agents/{agent_id}/api-key",...$})}putAgentApiKey($){return($.client??this.client).put({url:"/agents/{agent_id}/api-key",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateAiBillingAutoReload($){return($.client??this.client).patch({url:"/ai-billing/auto-reload",...$,headers:{"Content-Type":"application/json",...$.headers}})}createAiCreditCheckout($){return($.client??this.client).post({url:"/ai-billing/credits/checkout",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateAiBillingOverage($){return($.client??this.client).patch({url:"/ai-billing/overage",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAiBillingPlans($){return($?.client??this.client).get({url:"/ai-billing/plans",...$})}getAiBillingSummary($){return($?.client??this.client).get({url:"/ai-billing/summary",...$})}disconnectCodex($){return($?.client??this.client).delete({url:"/codex",...$})}getCodexConnection($){return($?.client??this.client).get({url:"/codex",...$})}configureCodex($){return($.client??this.client).put({url:"/codex/config",...$,headers:{"Content-Type":"application/json",...$.headers}})}listCodexEnvironments($){return($?.client??this.client).get({url:"/codex/environments",...$})}startCodexLogin($){return($?.client??this.client).post({url:"/codex/login",...$})}cancelCodexLogin($){return($.client??this.client).delete({url:"/codex/login/{attempt_id}",...$})}pollCodexLogin($){return($.client??this.client).get({url:"/codex/login/{attempt_id}",...$})}deleteCursorApiKey($){return($?.client??this.client).delete({url:"/cursor-api-key",...$})}getCursorApiKey($){return($?.client??this.client).get({url:"/cursor-api-key",...$})}putCursorApiKey($){return($.client??this.client).put({url:"/cursor-api-key",...$,headers:{"Content-Type":"application/json",...$.headers}})}putCursorDefaultModel($){return($.client??this.client).put({url:"/cursor-api-key/default-model",...$,headers:{"Content-Type":"application/json",...$.headers}})}listCursorModels($){return($?.client??this.client).get({url:"/cursor-api-key/models",...$})}verifyFusionauthUserEmail($){return($.client??this.client).get({url:"/email/fusionauth/verify/{verification_id}",...$})}resendFusionauthVerifyUserEmail($){return($.client??this.client).post({url:"/email/fusionauth_resend",...$,headers:{"Content-Type":"application/json",...$.headers}})}generateEmailLink($){return($.client??this.client).post({url:"/email/generate/link",...$,headers:{"Content-Type":"application/json",...$.headers}})}verifyEmailLink($){return($.client??this.client).get({url:"/email/verify/{verification_id}",...$})}setGithubPullRequestDraft($){return($.client??this.client).post({url:"/github_pull_requests/draft",...$,headers:{"Content-Type":"application/json",...$.headers}})}enrichGithubPullRequests($){return($.client??this.client).post({url:"/github_pull_requests/enrich",...$,headers:{"Content-Type":"application/json",...$.headers}})}mergeGithubPullRequest($){return($.client??this.client).post({url:"/github_pull_requests/merge",...$,headers:{"Content-Type":"application/json",...$.headers}})}getGithubPullRequestMergeability($){return($.client??this.client).post({url:"/github_pull_requests/mergeability",...$,headers:{"Content-Type":"application/json",...$.headers}})}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}",...$})}deleteTeam($){return($?.client??this.client).delete({url:"/team",...$})}getTeam($){return($?.client??this.client).get({url:"/team",...$})}patchTeam($){return($.client??this.client).patch({url:"/team",...$,headers:{"Content-Type":"application/json",...$.headers}})}createTeam($){return($.client??this.client).post({url:"/team",...$,headers:{"Content-Type":"application/json",...$.headers}})}toggleTeamAutoJoinDomain($){return($?.client??this.client).post({url:"/team/auto-join-domain/toggle",...$})}patchTeamCrmSettings($){return($.client??this.client).patch({url:"/team/crm",...$,headers:{"Content-Type":"application/json",...$.headers}})}inviteToTeam($){return($.client??this.client).post({url:"/team/invite",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteTeamInviteLink($){return($?.client??this.client).delete({url:"/team/invite-link",...$})}getTeamInviteLink($){return($?.client??this.client).get({url:"/team/invite-link",...$})}createTeamInviteLink($){return($?.client??this.client).post({url:"/team/invite-link",...$})}joinTeamByInviteLink($){return($.client??this.client).post({url:"/team/invite-link/join",...$,headers:{"Content-Type":"application/json",...$.headers}})}getTeamByInviteLink($){return($.client??this.client).post({url:"/team/invite-link/team",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteTeamInviteHandler($){return($.client??this.client).delete({url:"/team/invite/{team_invite_id}",...$})}getTeamInvites($){return($?.client??this.client).get({url:"/team/invites",...$})}rejectInvitation($){return($.client??this.client).delete({url:"/team/join/{team_invite_id}",...$})}joinTeam($){return($.client??this.client).get({url:"/team/join/{team_invite_id}",...$})}patchTeamMemberPlan($){return($.client??this.client).patch({url:"/team/members/{member_user_id}/plan",...$,headers:{"Content-Type":"application/json",...$.headers}})}toggleTeamNonAdminInvites($){return($?.client??this.client).post({url:"/team/non-admin-invites/toggle",...$})}removeUserFromTeam($){return($.client??this.client).delete({url:"/team/remove/{remove_user_id}",...$})}getUserTeams($){return($?.client??this.client).get({url:"/team/user",...$})}getUserInvites($){return($?.client??this.client).get({url:"/team/user/invites",...$})}getUserNames($){return($.client??this.client).post({url:"/user/get_names",...$,headers:{"Content-Type":"application/json",...$.headers}})}getUserNamesWithEmail($){return($.client??this.client).post({url:"/user/get_names_with_email",...$,headers:{"Content-Type":"application/json",...$.headers}})}patchUserGroup($){return($.client??this.client).patch({url:"/user/group",...$,headers:{"Content-Type":"application/json",...$.headers}})}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 H2({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:G,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:K,url:L,...Q}){let J,I=K??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=G??3000,B=0,T=Q.signal??new AbortController().signal;while(!0){if(T.aborted)break;B++;let C=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)C.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:C,signal:T},_=new Request(L,D);if($)_=await $(L,D);let N=await(Q.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{H.cancel()}catch{}};T.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await H.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
+`);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{T.removeEventListener("abort",g),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var A7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},C7=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},F7=($)=>{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((K)=>encodeURIComponent(K))).join(C7(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let G=A7(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return CO({allowReserved:$,name:j,value:X})}).join(G);return x==="label"||x==="matrix"?G+Z:Z},CO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},vj=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:G})=>{if(S instanceof Date)return G?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let K=[];Object.entries(S).forEach(([Q,J])=>{K=[...K,Q,$?J:encodeURIComponent(J)]});let L=K.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=F7(x),X=Object.entries(S).map(([K,L])=>CO({allowReserved:$,name:x==="deepObject"?`${j}[${K}]`:K,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var E7=/\{[^{}]+\}/g,w7=({path:$,url:O})=>{let j=O,x=O.match(E7);if(x)for(let S of x){let G=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))G=!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 K=$[Z];if(K===void 0||K===null)continue;if(Array.isArray(K)){j=j.replace(S,yj({explode:G,name:Z,style:X,value:K}));continue}if(typeof K==="object"){j=j.replace(S,vj({explode:G,name:Z,style:X,value:K,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${CO({name:Z,value:K})}`);continue}let L=encodeURIComponent(X==="label"?`.${K}`:K);j=j.replace(S,L)}return j},V2=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let G=S.startsWith("/")?S:`/${S}`,Z=($??"")+G;if(O)Z=w7({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function dx($){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 G in x){let Z=x[G];if(Z===void 0||Z===null)continue;let X=$[G]||O;if(Array.isArray(Z)){let K=yj({allowReserved:X.allowReserved,explode:!0,name:G,style:"form",value:Z,...X.array});if(K)S.push(K)}else if(typeof Z==="object"){let K=vj({allowReserved:X.allowReserved,explode:!0,name:G,style:"deepObject",value:Z,...X.object});if(K)S.push(K)}else{let K=CO({allowReserved:X.allowReserved,name:G,value:Z});if(K)S.push(K)}}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},q7=($,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(q7($,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 lx=($)=>V2({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:L2($.querySerializer),url:$.url}),rx=($,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},f7=($)=>{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?f7(j):Object.entries(j);for(let[S,G]of x)if(G===null)O.delete(S);else if(Array.isArray(G))for(let Z of G)O.append(S,Z);else if(G!==void 0)O.set(S,typeof G==="object"?JSON.stringify(G):G)}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 z2=()=>({error:new hj,request:new hj,response:new hj}),b7=L2({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),k7={"Content-Type":"application/json"},jj=($={})=>({...B2,headers:k7,parseAs:"auto",querySerializer:b7,...$});var px=($={})=>{let O=rx(jj(),$),j=()=>({...O}),x=(Q)=>{return O=rx(O,Q),j()},S=z2(),G=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:mj(O.headers,Q.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=lx(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await G(Q),T={redirect:"follow",...V,body:dx(V)};z=new Request(B,T);for(let N of S.request.fns)if(N)z=await N(z,V);let C=V.fetch;W=await C(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?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 H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await W[N]();break;case"json":{let U=await W.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let _=await W.text(),w;try{w=JSON.parse(_)}catch{}throw w??_}catch(V){let B=V;for(let T of S.error.fns)if(T)B=await T(B,W,z,Q);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(Q)=>(J)=>Z({...J,method:Q}),K=(Q)=>async(J)=>{let{opts:I,url:z}=await G(J);return J2({...I,body:I.body,method:Q,onRequest:async(W,V)=>{let B=new Request(W,V);for(let T of S.request.fns)if(T)B=await T(B,I);return B},serializedBody:dx(I),url:z})};return{buildUrl:(Q)=>lx({...O,...Q}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:K("CONNECT"),delete:K("DELETE"),get:K("GET"),head:K("HEAD"),options:K("OPTIONS"),patch:K("PATCH"),post:K("POST"),put:K("PUT"),trace:K("TRACE")},trace:X("TRACE")}};var I2=px(jj());class T2{client;constructor($){this.client=$?.client??I2}}class H2{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class uj extends T2{static __registry=new H2;constructor($){super($);uj.__registry.set(this,$?.key)}deleteAgentApiKey($){return($.client??this.client).delete({url:"/agents/{agent_id}/api-key",...$})}getAgentApiKey($){return($.client??this.client).get({url:"/agents/{agent_id}/api-key",...$})}putAgentApiKey($){return($.client??this.client).put({url:"/agents/{agent_id}/api-key",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateAiBillingAutoReload($){return($.client??this.client).patch({url:"/ai-billing/auto-reload",...$,headers:{"Content-Type":"application/json",...$.headers}})}createAiCreditCheckout($){return($.client??this.client).post({url:"/ai-billing/credits/checkout",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateAiBillingOverage($){return($.client??this.client).patch({url:"/ai-billing/overage",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAiBillingPlans($){return($?.client??this.client).get({url:"/ai-billing/plans",...$})}getAiBillingSummary($){return($?.client??this.client).get({url:"/ai-billing/summary",...$})}disconnectCodex($){return($?.client??this.client).delete({url:"/codex",...$})}getCodexConnection($){return($?.client??this.client).get({url:"/codex",...$})}configureCodex($){return($.client??this.client).put({url:"/codex/config",...$,headers:{"Content-Type":"application/json",...$.headers}})}listCodexEnvironments($){return($?.client??this.client).get({url:"/codex/environments",...$})}startCodexLogin($){return($?.client??this.client).post({url:"/codex/login",...$})}cancelCodexLogin($){return($.client??this.client).delete({url:"/codex/login/{attempt_id}",...$})}pollCodexLogin($){return($.client??this.client).get({url:"/codex/login/{attempt_id}",...$})}deleteCursorApiKey($){return($?.client??this.client).delete({url:"/cursor-api-key",...$})}getCursorApiKey($){return($?.client??this.client).get({url:"/cursor-api-key",...$})}putCursorApiKey($){return($.client??this.client).put({url:"/cursor-api-key",...$,headers:{"Content-Type":"application/json",...$.headers}})}putCursorDefaultModel($){return($.client??this.client).put({url:"/cursor-api-key/default-model",...$,headers:{"Content-Type":"application/json",...$.headers}})}listCursorModels($){return($?.client??this.client).get({url:"/cursor-api-key/models",...$})}verifyFusionauthUserEmail($){return($.client??this.client).get({url:"/email/fusionauth/verify/{verification_id}",...$})}resendFusionauthVerifyUserEmail($){return($.client??this.client).post({url:"/email/fusionauth_resend",...$,headers:{"Content-Type":"application/json",...$.headers}})}generateEmailLink($){return($.client??this.client).post({url:"/email/generate/link",...$,headers:{"Content-Type":"application/json",...$.headers}})}verifyEmailLink($){return($.client??this.client).get({url:"/email/verify/{verification_id}",...$})}setGithubPullRequestDraft($){return($.client??this.client).post({url:"/github_pull_requests/draft",...$,headers:{"Content-Type":"application/json",...$.headers}})}enrichGithubPullRequests($){return($.client??this.client).post({url:"/github_pull_requests/enrich",...$,headers:{"Content-Type":"application/json",...$.headers}})}mergeGithubPullRequest($){return($.client??this.client).post({url:"/github_pull_requests/merge",...$,headers:{"Content-Type":"application/json",...$.headers}})}getGithubPullRequestMergeability($){return($.client??this.client).post({url:"/github_pull_requests/mergeability",...$,headers:{"Content-Type":"application/json",...$.headers}})}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}",...$})}deleteTeam($){return($?.client??this.client).delete({url:"/team",...$})}getTeam($){return($?.client??this.client).get({url:"/team",...$})}patchTeam($){return($.client??this.client).patch({url:"/team",...$,headers:{"Content-Type":"application/json",...$.headers}})}createTeam($){return($.client??this.client).post({url:"/team",...$,headers:{"Content-Type":"application/json",...$.headers}})}toggleTeamAutoJoinDomain($){return($?.client??this.client).post({url:"/team/auto-join-domain/toggle",...$})}patchTeamCrmSettings($){return($.client??this.client).patch({url:"/team/crm",...$,headers:{"Content-Type":"application/json",...$.headers}})}inviteToTeam($){return($.client??this.client).post({url:"/team/invite",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteTeamInviteLink($){return($?.client??this.client).delete({url:"/team/invite-link",...$})}getTeamInviteLink($){return($?.client??this.client).get({url:"/team/invite-link",...$})}createTeamInviteLink($){return($?.client??this.client).post({url:"/team/invite-link",...$})}joinTeamByInviteLink($){return($.client??this.client).post({url:"/team/invite-link/join",...$,headers:{"Content-Type":"application/json",...$.headers}})}getTeamByInviteLink($){return($.client??this.client).post({url:"/team/invite-link/team",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteTeamInviteHandler($){return($.client??this.client).delete({url:"/team/invite/{team_invite_id}",...$})}getTeamInvites($){return($?.client??this.client).get({url:"/team/invites",...$})}rejectInvitation($){return($.client??this.client).delete({url:"/team/join/{team_invite_id}",...$})}joinTeam($){return($.client??this.client).get({url:"/team/join/{team_invite_id}",...$})}patchTeamMemberPlan($){return($.client??this.client).patch({url:"/team/members/{member_user_id}/plan",...$,headers:{"Content-Type":"application/json",...$.headers}})}toggleTeamNonAdminInvites($){return($?.client??this.client).post({url:"/team/non-admin-invites/toggle",...$})}removeUserFromTeam($){return($.client??this.client).delete({url:"/team/remove/{remove_user_id}",...$})}getUserTeams($){return($?.client??this.client).get({url:"/team/user",...$})}getUserInvites($){return($?.client??this.client).get({url:"/team/user/invites",...$})}getUserNames($){return($.client??this.client).post({url:"/user/get_names",...$,headers:{"Content-Type":"application/json",...$.headers}})}getUserNamesWithEmail($){return($.client??this.client).post({url:"/user/get_names_with_email",...$,headers:{"Content-Type":"application/json",...$.headers}})}patchUserGroup($){return($.client??this.client).patch({url:"/user/group",...$,headers:{"Content-Type":"application/json",...$.headers}})}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 R2({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:G,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:K,url:L,...Q}){let J,I=K??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=G??3000,B=0,T=Q.signal??new AbortController().signal;while(!0){if(T.aborted)break;B++;let C=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)C.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:C,signal:T},_=new Request(L,D);if($)_=await $(L,D);let N=await(Q.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{H.cancel()}catch{}};T.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await H.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
`);let 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{T.removeEventListener("abort",g),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var k7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},g7=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},y7=($)=>{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((K)=>encodeURIComponent(K))).join(g7(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let G=k7(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return FO({allowReserved:$,name:j,value:X})}).join(G);return x==="label"||x==="matrix"?G+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)}`},cj=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:G})=>{if(S instanceof Date)return G?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let K=[];Object.entries(S).forEach(([Q,J])=>{K=[...K,Q,$?J:encodeURIComponent(J)]});let L=K.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=y7(x),X=Object.entries(S).map(([K,L])=>FO({allowReserved:$,name:x==="deepObject"?`${j}[${K}]`:K,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var v7=/\{[^{}]+\}/g,h7=({path:$,url:O})=>{let j=O,x=O.match(v7);if(x)for(let S of x){let G=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))G=!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 K=$[Z];if(K===void 0||K===null)continue;if(Array.isArray(K)){j=j.replace(S,uj({explode:G,name:Z,style:X,value:K}));continue}if(typeof K==="object"){j=j.replace(S,cj({explode:G,name:Z,style:X,value:K,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${FO({name:Z,value:K})}`);continue}let L=encodeURIComponent(X==="label"?`.${K}`:K);j=j.replace(S,L)}return j},R2=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let G=S.startsWith("/")?S:`/${S}`,Z=($??"")+G;if(O)Z=h7({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 D2=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var _2={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var M2=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let G in x){let Z=x[G];if(Z===void 0||Z===null)continue;let X=$[G]||O;if(Array.isArray(Z)){let K=uj({allowReserved:X.allowReserved,explode:!0,name:G,style:"form",value:Z,...X.array});if(K)S.push(K)}else if(typeof Z==="object"){let K=cj({allowReserved:X.allowReserved,explode:!0,name:G,style:"deepObject",value:Z,...X.object});if(K)S.push(K)}else{let K=FO({allowReserved:X.allowReserved,name:G,value:Z});if(K)S.push(K)}}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},m7=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function A2($){for(let O of $.security??[]){if(m7($,O.name))continue;let j=await D2(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var ix=($)=>R2({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:M2($.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=lj($.headers,O.headers),j},u7=($)=>{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?u7(j):Object.entries(j);for(let[S,G]of x)if(G===null)O.delete(S);else if(Array.isArray(G))for(let Z of G)O.append(S,Z);else if(G!==void 0)O.set(S,typeof G==="object"?JSON.stringify(G):G)}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 C2=()=>({error:new dj,request:new dj,response:new dj}),c7=M2({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),d7={"Content-Type":"application/json"},xj=($={})=>({..._2,headers:d7,parseAs:"auto",querySerializer:c7,...$});var sx=($={})=>{let O=nx(xj(),$),j=()=>({...O}),x=(Q)=>{return O=nx(O,Q),j()},S=C2(),G=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:lj(O.headers,Q.headers),serializedBody:void 0};if(J.security)await A2(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(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await G(Q),T={redirect:"follow",...V,body:ax(V)};z=new Request(B,T);for(let N of S.request.fns)if(N)z=await N(z,V);let C=V.fetch;W=await C(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?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 H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await W[N]();break;case"json":{let U=await W.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let _=await W.text(),w;try{w=JSON.parse(_)}catch{}throw w??_}catch(V){let B=V;for(let T of S.error.fns)if(T)B=await T(B,W,z,Q);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(Q)=>(J)=>Z({...J,method:Q}),K=(Q)=>async(J)=>{let{opts:I,url:z}=await G(J);return H2({...I,body:I.body,method:Q,onRequest:async(W,V)=>{let B=new Request(W,V);for(let T of S.request.fns)if(T)B=await T(B,I);return B},serializedBody:ax(I),url:z})};return{buildUrl:(Q)=>ix({...O,...Q}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:K("CONNECT"),delete:K("DELETE"),get:K("GET"),head:K("HEAD"),options:K("OPTIONS"),patch:K("PATCH"),post:K("POST"),put:K("PUT"),trace:K("TRACE")},trace:X("TRACE")}};var F2=sx(xj());class E2{client;constructor($){this.client=$?.client??F2}}class w2{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class rj extends E2{static __registry=new w2;constructor($){super($);rj.__registry.set(this,$?.key)}getAvailabilityCalendars($){return($?.client??this.client).get({url:"/availability-calendars",...$})}setAvailabilityCalendar($){return($.client??this.client).put({url:"/availability-calendars/{calendar_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}listCalendars($){return($?.client??this.client).get({url:"/calendars",...$})}createCalendarEvent($){return($.client??this.client).post({url:"/events",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteCalendarEvent($){return($.client??this.client).delete({url:"/events/{event_id}",...$})}updateCalendarEvent($){return($.client??this.client).patch({url:"/events/{event_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}copyCalendarEvent($){return($.client??this.client).post({url:"/events/{event_id}/copy",...$,headers:{"Content-Type":"application/json",...$.headers}})}inviteCalendarEventGuests($){return($.client??this.client).post({url:"/events/{event_id}/guests",...$,headers:{"Content-Type":"application/json",...$.headers}})}eventNotes($){return($.client??this.client).get({url:"/events/{event_id}/notes",...$})}unlinkEventNote($){return($.client??this.client).delete({url:"/events/{event_id}/notes/{document_id}",...$})}linkEventNote($){return($.client??this.client).put({url:"/events/{event_id}/notes/{document_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}calendarEventProviderUrl($){return($.client??this.client).get({url:"/events/{event_id}/provider-url",...$})}prepareCalendarReplacement($){return($.client??this.client).post({url:"/events/{event_id}/replacement",...$,headers:{"Content-Type":"application/json",...$.headers}})}rsvpCalendarEvent($){return($.client??this.client).put({url:"/events/{event_id}/rsvp",...$,headers:{"Content-Type":"application/json",...$.headers}})}healthHandler($){return($?.client??this.client).get({url:"/health",...$})}respondToJoinRequest($){return($.client??this.client).put({url:"/join-requests/{request_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}noteDocuments($){return($?.client??this.client).get({url:"/meeting-notes/documents",...$})}documentNoteLinks($){return($.client??this.client).get({url:"/meeting-notes/documents/{document_id}/links",...$})}discardCalendarReplacement($){return($.client??this.client).delete({url:"/replacements/{operation_id}",...$})}calendarReplacementStatus($){return($.client??this.client).get({url:"/replacements/{operation_id}",...$})}confirmCalendarReplacement($){return($.client??this.client).post({url:"/replacements/{operation_id}/confirm",...$})}getTeamSharing($){return($?.client??this.client).get({url:"/team-sharing",...$})}setTeamSharing($){return($.client??this.client).put({url:"/team-sharing",...$,headers:{"Content-Type":"application/json",...$.headers}})}}function q2({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:G,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:K,url:L,...Q}){let J,I=K??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=G??3000,B=0,T=Q.signal??new AbortController().signal;while(!0){if(T.aborted)break;B++;let C=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)C.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:C,signal:T},_=new Request(L,D);if($)_=await $(L,D);let N=await(Q.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{H.cancel()}catch{}};T.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await H.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
+`);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{T.removeEventListener("abort",g),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var g7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},y7=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},v7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},cj=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((K)=>encodeURIComponent(K))).join(y7(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let G=g7(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return FO({allowReserved:$,name:j,value:X})}).join(G);return x==="label"||x==="matrix"?G+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:G})=>{if(S instanceof Date)return G?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let K=[];Object.entries(S).forEach(([Q,J])=>{K=[...K,Q,$?J:encodeURIComponent(J)]});let L=K.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=v7(x),X=Object.entries(S).map(([K,L])=>FO({allowReserved:$,name:x==="deepObject"?`${j}[${K}]`:K,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var h7=/\{[^{}]+\}/g,m7=({path:$,url:O})=>{let j=O,x=O.match(h7);if(x)for(let S of x){let G=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))G=!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 K=$[Z];if(K===void 0||K===null)continue;if(Array.isArray(K)){j=j.replace(S,cj({explode:G,name:Z,style:X,value:K}));continue}if(typeof K==="object"){j=j.replace(S,dj({explode:G,name:Z,style:X,value:K,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${FO({name:Z,value:K})}`);continue}let L=encodeURIComponent(X==="label"?`.${K}`:K);j=j.replace(S,L)}return j},D2=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let G=S.startsWith("/")?S:`/${S}`,Z=($??"")+G;if(O)Z=m7({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function 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 _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 P2=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let G in x){let Z=x[G];if(Z===void 0||Z===null)continue;let X=$[G]||O;if(Array.isArray(Z)){let K=cj({allowReserved:X.allowReserved,explode:!0,name:G,style:"form",value:Z,...X.array});if(K)S.push(K)}else if(typeof Z==="object"){let K=dj({allowReserved:X.allowReserved,explode:!0,name:G,style:"deepObject",value:Z,...X.object});if(K)S.push(K)}else{let K=FO({allowReserved:X.allowReserved,name:G,value:Z});if(K)S.push(K)}}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},u7=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function C2($){for(let O of $.security??[]){if(u7($,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 ix=($)=>D2({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:P2($.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=rj($.headers,O.headers),j},c7=($)=>{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?c7(j):Object.entries(j);for(let[S,G]of x)if(G===null)O.delete(S);else if(Array.isArray(G))for(let Z of G)O.append(S,Z);else if(G!==void 0)O.set(S,typeof G==="object"?JSON.stringify(G):G)}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 F2=()=>({error:new lj,request:new lj,response:new lj}),d7=P2({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),l7={"Content-Type":"application/json"},xj=($={})=>({...M2,headers:l7,parseAs:"auto",querySerializer:d7,...$});var sx=($={})=>{let O=nx(xj(),$),j=()=>({...O}),x=(Q)=>{return O=nx(O,Q),j()},S=F2(),G=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:rj(O.headers,Q.headers),serializedBody:void 0};if(J.security)await C2(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(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await G(Q),T={redirect:"follow",...V,body:ax(V)};z=new Request(B,T);for(let N of S.request.fns)if(N)z=await N(z,V);let C=V.fetch;W=await C(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?A2(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await W[N]();break;case"json":{let U=await W.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let _=await W.text(),w;try{w=JSON.parse(_)}catch{}throw w??_}catch(V){let B=V;for(let T of S.error.fns)if(T)B=await T(B,W,z,Q);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(Q)=>(J)=>Z({...J,method:Q}),K=(Q)=>async(J)=>{let{opts:I,url:z}=await G(J);return R2({...I,body:I.body,method:Q,onRequest:async(W,V)=>{let B=new Request(W,V);for(let T of S.request.fns)if(T)B=await T(B,I);return B},serializedBody:ax(I),url:z})};return{buildUrl:(Q)=>ix({...O,...Q}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:K("CONNECT"),delete:K("DELETE"),get:K("GET"),head:K("HEAD"),options:K("OPTIONS"),patch:K("PATCH"),post:K("POST"),put:K("PUT"),trace:K("TRACE")},trace:X("TRACE")}};var E2=sx(xj());class w2{client;constructor($){this.client=$?.client??E2}}class q2{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 q2;constructor($){super($);pj.__registry.set(this,$?.key)}getAvailabilityCalendars($){return($?.client??this.client).get({url:"/availability-calendars",...$})}setAvailabilityCalendar($){return($.client??this.client).put({url:"/availability-calendars/{calendar_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}listCalendars($){return($?.client??this.client).get({url:"/calendars",...$})}createCalendarEvent($){return($.client??this.client).post({url:"/events",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteCalendarEvent($){return($.client??this.client).delete({url:"/events/{event_id}",...$})}updateCalendarEvent($){return($.client??this.client).patch({url:"/events/{event_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}copyCalendarEvent($){return($.client??this.client).post({url:"/events/{event_id}/copy",...$,headers:{"Content-Type":"application/json",...$.headers}})}inviteCalendarEventGuests($){return($.client??this.client).post({url:"/events/{event_id}/guests",...$,headers:{"Content-Type":"application/json",...$.headers}})}eventNotes($){return($.client??this.client).get({url:"/events/{event_id}/notes",...$})}unlinkEventNote($){return($.client??this.client).delete({url:"/events/{event_id}/notes/{document_id}",...$})}linkEventNote($){return($.client??this.client).put({url:"/events/{event_id}/notes/{document_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}calendarEventProviderUrl($){return($.client??this.client).get({url:"/events/{event_id}/provider-url",...$})}prepareCalendarReplacement($){return($.client??this.client).post({url:"/events/{event_id}/replacement",...$,headers:{"Content-Type":"application/json",...$.headers}})}rsvpCalendarEvent($){return($.client??this.client).put({url:"/events/{event_id}/rsvp",...$,headers:{"Content-Type":"application/json",...$.headers}})}healthHandler($){return($?.client??this.client).get({url:"/health",...$})}respondToJoinRequest($){return($.client??this.client).put({url:"/join-requests/{request_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}noteDocuments($){return($?.client??this.client).get({url:"/meeting-notes/documents",...$})}documentNoteLinks($){return($.client??this.client).get({url:"/meeting-notes/documents/{document_id}/links",...$})}discardCalendarReplacement($){return($.client??this.client).delete({url:"/replacements/{operation_id}",...$})}calendarReplacementStatus($){return($.client??this.client).get({url:"/replacements/{operation_id}",...$})}confirmCalendarReplacement($){return($.client??this.client).post({url:"/replacements/{operation_id}/confirm",...$})}getTeamSharing($){return($?.client??this.client).get({url:"/team-sharing",...$})}setTeamSharing($){return($.client??this.client).put({url:"/team-sharing",...$,headers:{"Content-Type":"application/json",...$.headers}})}}function f2({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:G,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:K,url:L,...Q}){let J,I=K??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=G??3000,B=0,T=Q.signal??new AbortController().signal;while(!0){if(T.aborted)break;B++;let C=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)C.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:C,signal:T},_=new Request(L,D);if($)_=await $(L,D);let N=await(Q.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{H.cancel()}catch{}};T.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await H.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
`);let 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{T.removeEventListener("abort",g),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var l7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},r7=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},p7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},pj=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((K)=>encodeURIComponent(K))).join(r7(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let G=l7(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return EO({allowReserved:$,name:j,value:X})}).join(G);return x==="label"||x==="matrix"?G+Z:Z},EO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},aj=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:G})=>{if(S instanceof Date)return G?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let K=[];Object.entries(S).forEach(([Q,J])=>{K=[...K,Q,$?J:encodeURIComponent(J)]});let L=K.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=p7(x),X=Object.entries(S).map(([K,L])=>EO({allowReserved:$,name:x==="deepObject"?`${j}[${K}]`:K,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var a7=/\{[^{}]+\}/g,i7=({path:$,url:O})=>{let j=O,x=O.match(a7);if(x)for(let S of x){let G=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))G=!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 K=$[Z];if(K===void 0||K===null)continue;if(Array.isArray(K)){j=j.replace(S,pj({explode:G,name:Z,style:X,value:K}));continue}if(typeof K==="object"){j=j.replace(S,aj({explode:G,name:Z,style:X,value:K,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${EO({name:Z,value:K})}`);continue}let L=encodeURIComponent(X==="label"?`.${K}`:K);j=j.replace(S,L)}return j},f2=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let G=S.startsWith("/")?S:`/${S}`,Z=($??"")+G;if(O)Z=i7({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 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 k2={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var g2=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let G in x){let Z=x[G];if(Z===void 0||Z===null)continue;let X=$[G]||O;if(Array.isArray(Z)){let K=pj({allowReserved:X.allowReserved,explode:!0,name:G,style:"form",value:Z,...X.array});if(K)S.push(K)}else if(typeof Z==="object"){let K=aj({allowReserved:X.allowReserved,explode:!0,name:G,style:"deepObject",value:Z,...X.object});if(K)S.push(K)}else{let K=EO({allowReserved:X.allowReserved,name:G,value:Z});if(K)S.push(K)}}return S.join("&")}},y2=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},n7=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function v2($){for(let O of $.security??[]){if(n7($,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 ex=($)=>f2({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:g2($.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=nj($.headers,O.headers),j},s7=($)=>{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?s7(j):Object.entries(j);for(let[S,G]of x)if(G===null)O.delete(S);else if(Array.isArray(G))for(let Z of G)O.append(S,Z);else if(G!==void 0)O.set(S,typeof G==="object"?JSON.stringify(G):G)}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 h2=()=>({error:new ij,request:new ij,response:new ij}),t7=g2({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),e7={"Content-Type":"application/json"},Sj=($={})=>({...k2,headers:e7,parseAs:"auto",querySerializer:t7,...$});var $1=($={})=>{let O=ox(Sj(),$),j=()=>({...O}),x=(Q)=>{return O=ox(O,Q),j()},S=h2(),G=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:nj(O.headers,Q.headers),serializedBody:void 0};if(J.security)await v2(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let I=J,z=ex(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await G(Q),T={redirect:"follow",...V,body:tx(V)};z=new Request(B,T);for(let N of S.request.fns)if(N)z=await N(z,V);let C=V.fetch;W=await C(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?y2(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await W[N]();break;case"json":{let U=await W.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let _=await W.text(),w;try{w=JSON.parse(_)}catch{}throw w??_}catch(V){let B=V;for(let T of S.error.fns)if(T)B=await T(B,W,z,Q);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(Q)=>(J)=>Z({...J,method:Q}),K=(Q)=>async(J)=>{let{opts:I,url:z}=await G(J);return q2({...I,body:I.body,method:Q,onRequest:async(W,V)=>{let B=new Request(W,V);for(let T of S.request.fns)if(T)B=await T(B,I);return B},serializedBody:tx(I),url:z})};return{buildUrl:(Q)=>ex({...O,...Q}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:K("CONNECT"),delete:K("DELETE"),get:K("GET"),head:K("HEAD"),options:K("OPTIONS"),patch:K("PATCH"),post:K("POST"),put:K("PUT"),trace:K("TRACE")},trace:X("TRACE")}};var m2=$1(Sj());class u2{client;constructor($){this.client=$?.client??m2}}class c2{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class sj extends u2{static __registry=new c2;constructor($){super($);sj.__registry.set(this,$?.key)}setPricingHandler($){return($.client??this.client).post({url:"/ai-cost/pricing",...$,headers:{"Content-Type":"application/json",...$.headers}})}getUsageHandler($){return($.client??this.client).post({url:"/ai-cost/usage",...$,headers:{"Content-Type":"application/json",...$.headers}})}upsertAiProjection($){return($.client??this.client).post({url:"/ai-projections",...$,headers:{"Content-Type":"application/json",...$.headers}})}getChatsForAttachmentHandler($){return($.client??this.client).get({url:"/attachments/{attachment_id}/chats",...$})}deleteChat($){return($.client??this.client).delete({url:"/chat/{chat_id}",...$})}patchChat($){return($.client??this.client).patch({url:"/chat/{chat_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}permanentlyDeleteChat($){return($.client??this.client).delete({url:"/chat/{chat_id}/permanent",...$})}createChat($){return($.client??this.client).post({url:"/chats",...$,headers:{"Content-Type":"application/json",...$.headers}})}getChatHistoryHandler($){return($.client??this.client).get({url:"/chats/history/{chat_id}",...$})}getChatHistoryBatchMessagesHandler($){return($.client??this.client).post({url:"/chats/history_batch_messages",...$,headers:{"Content-Type":"application/json",...$.headers}})}getChat($){return($.client??this.client).get({url:"/chats/{chat_id}",...$})}copyChat($){return($.client??this.client).post({url:"/chats/{chat_id}/copy",...$})}getChatPermissions($){return($.client??this.client).get({url:"/chats/{chat_id}/permissions",...$})}revertDeleteChat($){return($.client??this.client).put({url:"/chats/{chat_id}/revert_delete",...$})}callTool($){return($.client??this.client).post({url:"/chats/{chat_id}/tool/call",...$,headers:{"Content-Type":"application/json",...$.headers}})}rejectToolCall($){return($.client??this.client).post({url:"/chats/{chat_id}/tool/reject",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateToolResponse($){return($.client??this.client).post({url:"/chats/{chat_id}/tool/response/update",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateToolCall($){return($.client??this.client).post({url:"/chats/{chat_id}/tool/update",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCitationHandler($){return($.client??this.client).get({url:"/citations/{id}",...$})}decisions($){return($.client??this.client).post({url:"/decisions",...$,headers:{"Content-Type":"application/json",...$.headers}})}healthHandler($){return($?.client??this.client).get({url:"/health",...$})}notionReportHandler($){return($?.client??this.client).get({url:"/import/notion",...$})}cancelNotionHandler($){return($?.client??this.client).post({url:"/import/notion/cancel",...$})}runImportHandler($){return($.client??this.client).post({url:"/import/run",...$,headers:{"Content-Type":"application/json",...$.headers}})}discoverHandler($){return($.client??this.client).post({url:"/import/runs/{source}/discover",...$})}getStateHandler($){return($?.client??this.client).get({url:"/import/state",...$})}workspaceReportHandler($){return($.client??this.client).get({url:"/import/workspaces/{source}",...$})}cancelWorkspaceHandler($){return($.client??this.client).post({url:"/import/workspaces/{source}/cancel",...$})}deleteMcpServer($){return($.client??this.client).delete({url:"/mcp/servers",...$})}listMcpServers($){return($?.client??this.client).get({url:"/mcp/servers",...$})}addMcpServer($){return($.client??this.client).post({url:"/mcp/servers",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateMcpServer($){return($.client??this.client).put({url:"/mcp/servers",...$,headers:{"Content-Type":"application/json",...$.headers}})}mcpAuthCallback($){return($?.client??this.client).get({url:"/mcp/servers/auth/callback",...$})}mcpOauthClientMetadata($){return($?.client??this.client).get({url:"/mcp/servers/auth/client-metadata",...$})}startMcpAuth($){return($.client??this.client).post({url:"/mcp/servers/auth/start",...$,headers:{"Content-Type":"application/json",...$.headers}})}getMemoryHandler($){return($?.client??this.client).get({url:"/memory",...$})}getStateHandler2($){return($?.client??this.client).get({url:"/onboarding",...$})}completeHandler($){return($.client??this.client).post({url:"/onboarding/complete",...$,headers:{"Content-Type":"application/json",...$.headers}})}dismissedPromptsHandler($){return($?.client??this.client).get({url:"/onboarding/prompts",...$})}dismissPromptHandler($){return($.client??this.client).post({url:"/onboarding/prompts/{prompt_id}/dismiss",...$})}browsePipedreamMcpCatalog($){return($?.client??this.client).get({url:"/pipedream/mcp/catalog",...$})}completePipedreamMcpConnection($){return($.client??this.client).post({url:"/pipedream/mcp/complete",...$,headers:{"Content-Type":"application/json",...$.headers}})}deletePipedreamMcpConnection($){return($.client??this.client).delete({url:"/pipedream/mcp/connections",...$})}listPipedreamMcpConnections($){return($?.client??this.client).get({url:"/pipedream/mcp/connections",...$})}updatePipedreamMcpConnection($){return($.client??this.client).put({url:"/pipedream/mcp/connections",...$,headers:{"Content-Type":"application/json",...$.headers}})}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",...$})}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 d2({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:G,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:K,url:L,...Q}){let J,I=K??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=G??3000,B=0,T=Q.signal??new AbortController().signal;while(!0){if(T.aborted)break;B++;let C=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)C.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:C,signal:T},_=new Request(L,D);if($)_=await $(L,D);let N=await(Q.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{H.cancel()}catch{}};T.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await H.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
+`);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{T.removeEventListener("abort",g),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var r7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},p7=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},a7=($)=>{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((K)=>encodeURIComponent(K))).join(p7(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let G=r7(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return EO({allowReserved:$,name:j,value:X})}).join(G);return x==="label"||x==="matrix"?G+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:G})=>{if(S instanceof Date)return G?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let K=[];Object.entries(S).forEach(([Q,J])=>{K=[...K,Q,$?J:encodeURIComponent(J)]});let L=K.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=a7(x),X=Object.entries(S).map(([K,L])=>EO({allowReserved:$,name:x==="deepObject"?`${j}[${K}]`:K,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var i7=/\{[^{}]+\}/g,n7=({path:$,url:O})=>{let j=O,x=O.match(i7);if(x)for(let S of x){let G=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))G=!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 K=$[Z];if(K===void 0||K===null)continue;if(Array.isArray(K)){j=j.replace(S,aj({explode:G,name:Z,style:X,value:K}));continue}if(typeof K==="object"){j=j.replace(S,ij({explode:G,name:Z,style:X,value:K,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${EO({name:Z,value:K})}`);continue}let L=encodeURIComponent(X==="label"?`.${K}`:K);j=j.replace(S,L)}return j},b2=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let G=S.startsWith("/")?S:`/${S}`,Z=($??"")+G;if(O)Z=n7({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 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 G in x){let Z=x[G];if(Z===void 0||Z===null)continue;let X=$[G]||O;if(Array.isArray(Z)){let K=aj({allowReserved:X.allowReserved,explode:!0,name:G,style:"form",value:Z,...X.array});if(K)S.push(K)}else if(typeof Z==="object"){let K=ij({allowReserved:X.allowReserved,explode:!0,name:G,style:"deepObject",value:Z,...X.object});if(K)S.push(K)}else{let K=EO({allowReserved:X.allowReserved,name:G,value:Z});if(K)S.push(K)}}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},s7=($,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(s7($,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 ex=($)=>b2({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:y2($.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=sj($.headers,O.headers),j},t7=($)=>{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?t7(j):Object.entries(j);for(let[S,G]of x)if(G===null)O.delete(S);else if(Array.isArray(G))for(let Z of G)O.append(S,Z);else if(G!==void 0)O.set(S,typeof G==="object"?JSON.stringify(G):G)}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 m2=()=>({error:new nj,request:new nj,response:new nj}),e7=y2({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),o7={"Content-Type":"application/json"},Sj=($={})=>({...g2,headers:o7,parseAs:"auto",querySerializer:e7,...$});var $1=($={})=>{let O=ox(Sj(),$),j=()=>({...O}),x=(Q)=>{return O=ox(O,Q),j()},S=m2(),G=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:sj(O.headers,Q.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=ex(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await G(Q),T={redirect:"follow",...V,body:tx(V)};z=new Request(B,T);for(let N of S.request.fns)if(N)z=await N(z,V);let C=V.fetch;W=await C(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?v2(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await W[N]();break;case"json":{let U=await W.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let _=await W.text(),w;try{w=JSON.parse(_)}catch{}throw w??_}catch(V){let B=V;for(let T of S.error.fns)if(T)B=await T(B,W,z,Q);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(Q)=>(J)=>Z({...J,method:Q}),K=(Q)=>async(J)=>{let{opts:I,url:z}=await G(J);return f2({...I,body:I.body,method:Q,onRequest:async(W,V)=>{let B=new Request(W,V);for(let T of S.request.fns)if(T)B=await T(B,I);return B},serializedBody:tx(I),url:z})};return{buildUrl:(Q)=>ex({...O,...Q}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:K("CONNECT"),delete:K("DELETE"),get:K("GET"),head:K("HEAD"),options:K("OPTIONS"),patch:K("PATCH"),post:K("POST"),put:K("PUT"),trace:K("TRACE")},trace:X("TRACE")}};var u2=$1(Sj());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 tj extends c2{static __registry=new d2;constructor($){super($);tj.__registry.set(this,$?.key)}setPricingHandler($){return($.client??this.client).post({url:"/ai-cost/pricing",...$,headers:{"Content-Type":"application/json",...$.headers}})}getUsageHandler($){return($.client??this.client).post({url:"/ai-cost/usage",...$,headers:{"Content-Type":"application/json",...$.headers}})}upsertAiProjection($){return($.client??this.client).post({url:"/ai-projections",...$,headers:{"Content-Type":"application/json",...$.headers}})}getChatsForAttachmentHandler($){return($.client??this.client).get({url:"/attachments/{attachment_id}/chats",...$})}deleteChat($){return($.client??this.client).delete({url:"/chat/{chat_id}",...$})}patchChat($){return($.client??this.client).patch({url:"/chat/{chat_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}permanentlyDeleteChat($){return($.client??this.client).delete({url:"/chat/{chat_id}/permanent",...$})}createChat($){return($.client??this.client).post({url:"/chats",...$,headers:{"Content-Type":"application/json",...$.headers}})}getChatHistoryHandler($){return($.client??this.client).get({url:"/chats/history/{chat_id}",...$})}getChatHistoryBatchMessagesHandler($){return($.client??this.client).post({url:"/chats/history_batch_messages",...$,headers:{"Content-Type":"application/json",...$.headers}})}getChat($){return($.client??this.client).get({url:"/chats/{chat_id}",...$})}copyChat($){return($.client??this.client).post({url:"/chats/{chat_id}/copy",...$})}getChatPermissions($){return($.client??this.client).get({url:"/chats/{chat_id}/permissions",...$})}revertDeleteChat($){return($.client??this.client).put({url:"/chats/{chat_id}/revert_delete",...$})}callTool($){return($.client??this.client).post({url:"/chats/{chat_id}/tool/call",...$,headers:{"Content-Type":"application/json",...$.headers}})}rejectToolCall($){return($.client??this.client).post({url:"/chats/{chat_id}/tool/reject",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateToolResponse($){return($.client??this.client).post({url:"/chats/{chat_id}/tool/response/update",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateToolCall($){return($.client??this.client).post({url:"/chats/{chat_id}/tool/update",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCitationHandler($){return($.client??this.client).get({url:"/citations/{id}",...$})}decisions($){return($.client??this.client).post({url:"/decisions",...$,headers:{"Content-Type":"application/json",...$.headers}})}healthHandler($){return($?.client??this.client).get({url:"/health",...$})}notionReportHandler($){return($?.client??this.client).get({url:"/import/notion",...$})}cancelNotionHandler($){return($?.client??this.client).post({url:"/import/notion/cancel",...$})}runImportHandler($){return($.client??this.client).post({url:"/import/run",...$,headers:{"Content-Type":"application/json",...$.headers}})}discoverHandler($){return($.client??this.client).post({url:"/import/runs/{source}/discover",...$})}getStateHandler($){return($?.client??this.client).get({url:"/import/state",...$})}workspaceReportHandler($){return($.client??this.client).get({url:"/import/workspaces/{source}",...$})}cancelWorkspaceHandler($){return($.client??this.client).post({url:"/import/workspaces/{source}/cancel",...$})}deleteMcpServer($){return($.client??this.client).delete({url:"/mcp/servers",...$})}listMcpServers($){return($?.client??this.client).get({url:"/mcp/servers",...$})}addMcpServer($){return($.client??this.client).post({url:"/mcp/servers",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateMcpServer($){return($.client??this.client).put({url:"/mcp/servers",...$,headers:{"Content-Type":"application/json",...$.headers}})}mcpAuthCallback($){return($?.client??this.client).get({url:"/mcp/servers/auth/callback",...$})}mcpOauthClientMetadata($){return($?.client??this.client).get({url:"/mcp/servers/auth/client-metadata",...$})}startMcpAuth($){return($.client??this.client).post({url:"/mcp/servers/auth/start",...$,headers:{"Content-Type":"application/json",...$.headers}})}getMemoryHandler($){return($?.client??this.client).get({url:"/memory",...$})}getStateHandler2($){return($?.client??this.client).get({url:"/onboarding",...$})}completeHandler($){return($.client??this.client).post({url:"/onboarding/complete",...$,headers:{"Content-Type":"application/json",...$.headers}})}dismissedPromptsHandler($){return($?.client??this.client).get({url:"/onboarding/prompts",...$})}dismissPromptHandler($){return($.client??this.client).post({url:"/onboarding/prompts/{prompt_id}/dismiss",...$})}browsePipedreamMcpCatalog($){return($?.client??this.client).get({url:"/pipedream/mcp/catalog",...$})}completePipedreamMcpConnection($){return($.client??this.client).post({url:"/pipedream/mcp/complete",...$,headers:{"Content-Type":"application/json",...$.headers}})}deletePipedreamMcpConnection($){return($.client??this.client).delete({url:"/pipedream/mcp/connections",...$})}listPipedreamMcpConnections($){return($?.client??this.client).get({url:"/pipedream/mcp/connections",...$})}updatePipedreamMcpConnection($){return($.client??this.client).put({url:"/pipedream/mcp/connections",...$,headers:{"Content-Type":"application/json",...$.headers}})}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",...$})}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 l2({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:G,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:K,url:L,...Q}){let J,I=K??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=G??3000,B=0,T=Q.signal??new AbortController().signal;while(!0){if(T.aborted)break;B++;let C=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)C.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:C,signal:T},_=new Request(L,D);if($)_=await $(L,D);let N=await(Q.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{H.cancel()}catch{}};T.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await H.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
`);let 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{T.removeEventListener("abort",g),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var o7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},$5=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},O5=($)=>{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((K)=>encodeURIComponent(K))).join($5(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let G=o7(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return wO({allowReserved:$,name:j,value:X})}).join(G);return x==="label"||x==="matrix"?G+Z:Z},wO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},ej=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:G})=>{if(S instanceof Date)return G?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let K=[];Object.entries(S).forEach(([Q,J])=>{K=[...K,Q,$?J:encodeURIComponent(J)]});let L=K.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=O5(x),X=Object.entries(S).map(([K,L])=>wO({allowReserved:$,name:x==="deepObject"?`${j}[${K}]`:K,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var j5=/\{[^{}]+\}/g,x5=({path:$,url:O})=>{let j=O,x=O.match(j5);if(x)for(let S of x){let G=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))G=!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 K=$[Z];if(K===void 0||K===null)continue;if(Array.isArray(K)){j=j.replace(S,tj({explode:G,name:Z,style:X,value:K}));continue}if(typeof K==="object"){j=j.replace(S,ej({explode:G,name:Z,style:X,value:K,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${wO({name:Z,value:K})}`);continue}let L=encodeURIComponent(X==="label"?`.${K}`:K);j=j.replace(S,L)}return j},l2=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let G=S.startsWith("/")?S:`/${S}`,Z=($??"")+G;if(O)Z=x5({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function 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 r2=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var p2={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var a2=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let G in x){let Z=x[G];if(Z===void 0||Z===null)continue;let X=$[G]||O;if(Array.isArray(Z)){let K=tj({allowReserved:X.allowReserved,explode:!0,name:G,style:"form",value:Z,...X.array});if(K)S.push(K)}else if(typeof Z==="object"){let K=ej({allowReserved:X.allowReserved,explode:!0,name:G,style:"deepObject",value:Z,...X.object});if(K)S.push(K)}else{let K=wO({allowReserved:X.allowReserved,name:G,value:Z});if(K)S.push(K)}}return S.join("&")}},i2=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},S5=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function n2($){for(let O of $.security??[]){if(S5($,O.name))continue;let j=await r2(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var j1=($)=>l2({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:a2($.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=$0($.headers,O.headers),j},Z5=($)=>{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?Z5(j):Object.entries(j);for(let[S,G]of x)if(G===null)O.delete(S);else if(Array.isArray(G))for(let Z of G)O.append(S,Z);else if(G!==void 0)O.set(S,typeof G==="object"?JSON.stringify(G):G)}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 s2=()=>({error:new oj,request:new oj,response:new oj}),X5=a2({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),G5={"Content-Type":"application/json"},Zj=($={})=>({...p2,headers:G5,parseAs:"auto",querySerializer:X5,...$});var S1=($={})=>{let O=x1(Zj(),$),j=()=>({...O}),x=(Q)=>{return O=x1(O,Q),j()},S=s2(),G=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:$0(O.headers,Q.headers),serializedBody:void 0};if(J.security)await n2(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let I=J,z=j1(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await G(Q),T={redirect:"follow",...V,body:O1(V)};z=new Request(B,T);for(let N of S.request.fns)if(N)z=await N(z,V);let C=V.fetch;W=await C(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?i2(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await W[N]();break;case"json":{let U=await W.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let _=await W.text(),w;try{w=JSON.parse(_)}catch{}throw w??_}catch(V){let B=V;for(let T of S.error.fns)if(T)B=await T(B,W,z,Q);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(Q)=>(J)=>Z({...J,method:Q}),K=(Q)=>async(J)=>{let{opts:I,url:z}=await G(J);return d2({...I,body:I.body,method:Q,onRequest:async(W,V)=>{let B=new Request(W,V);for(let T of S.request.fns)if(T)B=await T(B,I);return B},serializedBody:O1(I),url:z})};return{buildUrl:(Q)=>j1({...O,...Q}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:K("CONNECT"),delete:K("DELETE"),get:K("GET"),head:K("HEAD"),options:K("OPTIONS"),patch:K("PATCH"),post:K("POST"),put:K("PUT"),trace:K("TRACE")},trace:X("TRACE")}};var t2=S1(Zj());class e2{client;constructor($){this.client=$?.client??t2}}class o2{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class O0 extends e2{static __registry=new o2;constructor($){super($);O0.__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 $S({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:G,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:K,url:L,...Q}){let J,I=K??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=G??3000,B=0,T=Q.signal??new AbortController().signal;while(!0){if(T.aborted)break;B++;let C=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)C.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:C,signal:T},_=new Request(L,D);if($)_=await $(L,D);let N=await(Q.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{H.cancel()}catch{}};T.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await H.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
+`);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{T.removeEventListener("abort",g),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var $5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},O5=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},j5=($)=>{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((K)=>encodeURIComponent(K))).join(O5(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let G=$5(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return wO({allowReserved:$,name:j,value:X})}).join(G);return x==="label"||x==="matrix"?G+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)}`},oj=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:G})=>{if(S instanceof Date)return G?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let K=[];Object.entries(S).forEach(([Q,J])=>{K=[...K,Q,$?J:encodeURIComponent(J)]});let L=K.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=j5(x),X=Object.entries(S).map(([K,L])=>wO({allowReserved:$,name:x==="deepObject"?`${j}[${K}]`:K,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var x5=/\{[^{}]+\}/g,S5=({path:$,url:O})=>{let j=O,x=O.match(x5);if(x)for(let S of x){let G=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))G=!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 K=$[Z];if(K===void 0||K===null)continue;if(Array.isArray(K)){j=j.replace(S,ej({explode:G,name:Z,style:X,value:K}));continue}if(typeof K==="object"){j=j.replace(S,oj({explode:G,name:Z,style:X,value:K,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${wO({name:Z,value:K})}`);continue}let L=encodeURIComponent(X==="label"?`.${K}`:K);j=j.replace(S,L)}return j},r2=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let G=S.startsWith("/")?S:`/${S}`,Z=($??"")+G;if(O)Z=S5({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function 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 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 G in x){let Z=x[G];if(Z===void 0||Z===null)continue;let X=$[G]||O;if(Array.isArray(Z)){let K=ej({allowReserved:X.allowReserved,explode:!0,name:G,style:"form",value:Z,...X.array});if(K)S.push(K)}else if(typeof Z==="object"){let K=oj({allowReserved:X.allowReserved,explode:!0,name:G,style:"deepObject",value:Z,...X.object});if(K)S.push(K)}else{let K=wO({allowReserved:X.allowReserved,name:G,value:Z});if(K)S.push(K)}}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},Z5=($,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(Z5($,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 j1=($)=>r2({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:i2($.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=O0($.headers,O.headers),j},X5=($)=>{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?X5(j):Object.entries(j);for(let[S,G]of x)if(G===null)O.delete(S);else if(Array.isArray(G))for(let Z of G)O.append(S,Z);else if(G!==void 0)O.set(S,typeof G==="object"?JSON.stringify(G):G)}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 t2=()=>({error:new $0,request:new $0,response:new $0}),G5=i2({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),K5={"Content-Type":"application/json"},Zj=($={})=>({...a2,headers:K5,parseAs:"auto",querySerializer:G5,...$});var S1=($={})=>{let O=x1(Zj(),$),j=()=>({...O}),x=(Q)=>{return O=x1(O,Q),j()},S=t2(),G=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:O0(O.headers,Q.headers),serializedBody:void 0};if(J.security)await s2(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let I=J,z=j1(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await G(Q),T={redirect:"follow",...V,body:O1(V)};z=new Request(B,T);for(let N of S.request.fns)if(N)z=await N(z,V);let C=V.fetch;W=await C(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?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 H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await W[N]();break;case"json":{let U=await W.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let _=await W.text(),w;try{w=JSON.parse(_)}catch{}throw w??_}catch(V){let B=V;for(let T of S.error.fns)if(T)B=await T(B,W,z,Q);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(Q)=>(J)=>Z({...J,method:Q}),K=(Q)=>async(J)=>{let{opts:I,url:z}=await G(J);return l2({...I,body:I.body,method:Q,onRequest:async(W,V)=>{let B=new Request(W,V);for(let T of S.request.fns)if(T)B=await T(B,I);return B},serializedBody:O1(I),url:z})};return{buildUrl:(Q)=>j1({...O,...Q}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:K("CONNECT"),delete:K("DELETE"),get:K("GET"),head:K("HEAD"),options:K("OPTIONS"),patch:K("PATCH"),post:K("POST"),put:K("PUT"),trace:K("TRACE")},trace:X("TRACE")}};var e2=S1(Zj());class o2{client;constructor($){this.client=$?.client??e2}}class $S{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 o2{static __registry=new $S;constructor($){super($);j0.__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 OS({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:G,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:K,url:L,...Q}){let J,I=K??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=G??3000,B=0,T=Q.signal??new AbortController().signal;while(!0){if(T.aborted)break;B++;let C=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)C.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:C,signal:T},_=new Request(L,D);if($)_=await $(L,D);let N=await(Q.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{H.cancel()}catch{}};T.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await H.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
`);let 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{T.removeEventListener("abort",g),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var K5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},Y5=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},Q5=($)=>{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((K)=>encodeURIComponent(K))).join(Y5(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let G=K5(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return qO({allowReserved:$,name:j,value:X})}).join(G);return x==="label"||x==="matrix"?G+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:G})=>{if(S instanceof Date)return G?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let K=[];Object.entries(S).forEach(([Q,J])=>{K=[...K,Q,$?J:encodeURIComponent(J)]});let L=K.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=Q5(x),X=Object.entries(S).map(([K,L])=>qO({allowReserved:$,name:x==="deepObject"?`${j}[${K}]`:K,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var J5=/\{[^{}]+\}/g,V5=({path:$,url:O})=>{let j=O,x=O.match(J5);if(x)for(let S of x){let G=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))G=!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 K=$[Z];if(K===void 0||K===null)continue;if(Array.isArray(K)){j=j.replace(S,j0({explode:G,name:Z,style:X,value:K}));continue}if(typeof K==="object"){j=j.replace(S,x0({explode:G,name:Z,style:X,value:K,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${qO({name:Z,value:K})}`);continue}let L=encodeURIComponent(X==="label"?`.${K}`:K);j=j.replace(S,L)}return j},OS=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let G=S.startsWith("/")?S:`/${S}`,Z=($??"")+G;if(O)Z=V5({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function 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 jS=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var xS={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var SS=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let G in x){let Z=x[G];if(Z===void 0||Z===null)continue;let X=$[G]||O;if(Array.isArray(Z)){let K=j0({allowReserved:X.allowReserved,explode:!0,name:G,style:"form",value:Z,...X.array});if(K)S.push(K)}else if(typeof Z==="object"){let K=x0({allowReserved:X.allowReserved,explode:!0,name:G,style:"deepObject",value:Z,...X.object});if(K)S.push(K)}else{let K=qO({allowReserved:X.allowReserved,name:G,value:Z});if(K)S.push(K)}}return S.join("&")}},ZS=($)=>{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},W5=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function XS($){for(let O of $.security??[]){if(W5($,O.name))continue;let j=await jS(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var X1=($)=>OS({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:SS($.querySerializer),url:$.url}),G1=($,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},B5=($)=>{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?B5(j):Object.entries(j);for(let[S,G]of x)if(G===null)O.delete(S);else if(Array.isArray(G))for(let Z of G)O.append(S,Z);else if(G!==void 0)O.set(S,typeof G==="object"?JSON.stringify(G):G)}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 GS=()=>({error:new S0,request:new S0,response:new S0}),L5=SS({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),N5={"Content-Type":"application/json"},Xj=($={})=>({...xS,headers:N5,parseAs:"auto",querySerializer:L5,...$});var K1=($={})=>{let O=G1(Xj(),$),j=()=>({...O}),x=(Q)=>{return O=G1(O,Q),j()},S=GS(),G=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:Z0(O.headers,Q.headers),serializedBody:void 0};if(J.security)await XS(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let I=J,z=X1(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await G(Q),T={redirect:"follow",...V,body:Z1(V)};z=new Request(B,T);for(let N of S.request.fns)if(N)z=await N(z,V);let C=V.fetch;W=await C(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?ZS(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await W[N]();break;case"json":{let U=await W.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let _=await W.text(),w;try{w=JSON.parse(_)}catch{}throw w??_}catch(V){let B=V;for(let T of S.error.fns)if(T)B=await T(B,W,z,Q);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(Q)=>(J)=>Z({...J,method:Q}),K=(Q)=>async(J)=>{let{opts:I,url:z}=await G(J);return $S({...I,body:I.body,method:Q,onRequest:async(W,V)=>{let B=new Request(W,V);for(let T of S.request.fns)if(T)B=await T(B,I);return B},serializedBody:Z1(I),url:z})};return{buildUrl:(Q)=>X1({...O,...Q}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:K("CONNECT"),delete:K("DELETE"),get:K("GET"),head:K("HEAD"),options:K("OPTIONS"),patch:K("PATCH"),post:K("POST"),put:K("PUT"),trace:K("TRACE")},trace:X("TRACE")}};var KS=K1(Xj());class YS{client;constructor($){this.client=$?.client??KS}}class QS{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 YS{static __registry=new QS;constructor($){super($);X0.__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}",...$})}patchSettings($){return($.client??this.client).patch({url:"/email/settings",...$,headers:{"Content-Type":"application/json",...$.headers}})}mailboxSettingsOperations($){return($?.client??this.client).get({url:"/email/settings/operations",...$})}disableSync($){return($?.client??this.client).delete({url:"/email/sync",...$})}archiveThreads($){return($.client??this.client).patch({url:"/email/threads/archived",...$,headers:{"Content-Type":"application/json",...$.headers}})}previewsInboxCursor($){return($.client??this.client).get({url:"/email/threads/previews/cursor/{view}",...$})}archiveThread($){return($.client??this.client).patch({url:"/email/threads/{id}/archived",...$,headers:{"Content-Type":"application/json",...$.headers}})}addRemoveThreadLabel($){return($.client??this.client).patch({url:"/email/threads/{id}/labels",...$,headers:{"Content-Type":"application/json",...$.headers}})}getThreadMessagesHandler($){return($.client??this.client).get({url:"/email/threads/{id}/messages",...$})}threadOperations($){return($.client??this.client).get({url:"/email/threads/{id}/operations",...$})}threadSeen($){return($.client??this.client).post({url:"/email/threads/{id}/seen",...$})}updateThreadState($){return($.client??this.client).patch({url:"/email/threads/{id}/state",...$,headers:{"Content-Type":"application/json",...$.headers}})}getThread($){return($.client??this.client).get({url:"/email/threads/{thread_id}",...$})}getThreadCalendarInvitations($){return($.client??this.client).get({url:"/email/threads/{thread_id}/calendar-invitations",...$})}copyThreadCalendarInvitation($){return($.client??this.client).post({url:"/email/threads/{thread_id}/messages/{message_id}/calendar-invitations/{invitation_id}/copy",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateThreadProject($){return($.client??this.client).patch({url:"/email/threads/{thread_id}/project",...$,headers:{"Content-Type":"application/json",...$.headers}})}healthHandler($){return($?.client??this.client).get({url:"/health",...$})}}function JS({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:G,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:K,url:L,...Q}){let J,I=K??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=G??3000,B=0,T=Q.signal??new AbortController().signal;while(!0){if(T.aborted)break;B++;let C=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)C.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:C,signal:T},_=new Request(L,D);if($)_=await $(L,D);let N=await(Q.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{H.cancel()}catch{}};T.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await H.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
+`);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{T.removeEventListener("abort",g),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var Y5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},Q5=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},J5=($)=>{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((K)=>encodeURIComponent(K))).join(Q5(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let G=Y5(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return qO({allowReserved:$,name:j,value:X})}).join(G);return x==="label"||x==="matrix"?G+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)}`},S0=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:G})=>{if(S instanceof Date)return G?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let K=[];Object.entries(S).forEach(([Q,J])=>{K=[...K,Q,$?J:encodeURIComponent(J)]});let L=K.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=J5(x),X=Object.entries(S).map(([K,L])=>qO({allowReserved:$,name:x==="deepObject"?`${j}[${K}]`:K,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var V5=/\{[^{}]+\}/g,W5=({path:$,url:O})=>{let j=O,x=O.match(V5);if(x)for(let S of x){let G=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))G=!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 K=$[Z];if(K===void 0||K===null)continue;if(Array.isArray(K)){j=j.replace(S,x0({explode:G,name:Z,style:X,value:K}));continue}if(typeof K==="object"){j=j.replace(S,S0({explode:G,name:Z,style:X,value:K,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${qO({name:Z,value:K})}`);continue}let L=encodeURIComponent(X==="label"?`.${K}`:K);j=j.replace(S,L)}return j},jS=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let G=S.startsWith("/")?S:`/${S}`,Z=($??"")+G;if(O)Z=W5({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 xS=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 SS={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var ZS=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let G in x){let Z=x[G];if(Z===void 0||Z===null)continue;let X=$[G]||O;if(Array.isArray(Z)){let K=x0({allowReserved:X.allowReserved,explode:!0,name:G,style:"form",value:Z,...X.array});if(K)S.push(K)}else if(typeof Z==="object"){let K=S0({allowReserved:X.allowReserved,explode:!0,name:G,style:"deepObject",value:Z,...X.object});if(K)S.push(K)}else{let K=qO({allowReserved:X.allowReserved,name:G,value:Z});if(K)S.push(K)}}return S.join("&")}},XS=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},B5=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function GS($){for(let O of $.security??[]){if(B5($,O.name))continue;let j=await xS(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=($)=>jS({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:ZS($.querySerializer),url:$.url}),G1=($,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},L5=($)=>{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?L5(j):Object.entries(j);for(let[S,G]of x)if(G===null)O.delete(S);else if(Array.isArray(G))for(let Z of G)O.append(S,Z);else if(G!==void 0)O.set(S,typeof G==="object"?JSON.stringify(G):G)}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 KS=()=>({error:new Z0,request:new Z0,response:new Z0}),N5=ZS({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),U5={"Content-Type":"application/json"},Xj=($={})=>({...SS,headers:U5,parseAs:"auto",querySerializer:N5,...$});var K1=($={})=>{let O=G1(Xj(),$),j=()=>({...O}),x=(Q)=>{return O=G1(O,Q),j()},S=KS(),G=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:X0(O.headers,Q.headers),serializedBody:void 0};if(J.security)await GS(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let I=J,z=X1(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await G(Q),T={redirect:"follow",...V,body:Z1(V)};z=new Request(B,T);for(let N of S.request.fns)if(N)z=await N(z,V);let C=V.fetch;W=await C(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?XS(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await W[N]();break;case"json":{let U=await W.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let _=await W.text(),w;try{w=JSON.parse(_)}catch{}throw w??_}catch(V){let B=V;for(let T of S.error.fns)if(T)B=await T(B,W,z,Q);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(Q)=>(J)=>Z({...J,method:Q}),K=(Q)=>async(J)=>{let{opts:I,url:z}=await G(J);return OS({...I,body:I.body,method:Q,onRequest:async(W,V)=>{let B=new Request(W,V);for(let T of S.request.fns)if(T)B=await T(B,I);return B},serializedBody:Z1(I),url:z})};return{buildUrl:(Q)=>X1({...O,...Q}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:K("CONNECT"),delete:K("DELETE"),get:K("GET"),head:K("HEAD"),options:K("OPTIONS"),patch:K("PATCH"),post:K("POST"),put:K("PUT"),trace:K("TRACE")},trace:X("TRACE")}};var YS=K1(Xj());class QS{client;constructor($){this.client=$?.client??YS}}class JS{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 QS{static __registry=new JS;constructor($){super($);G0.__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}",...$})}patchSettings($){return($.client??this.client).patch({url:"/email/settings",...$,headers:{"Content-Type":"application/json",...$.headers}})}mailboxSettingsOperations($){return($?.client??this.client).get({url:"/email/settings/operations",...$})}disableSync($){return($?.client??this.client).delete({url:"/email/sync",...$})}archiveThreads($){return($.client??this.client).patch({url:"/email/threads/archived",...$,headers:{"Content-Type":"application/json",...$.headers}})}previewsInboxCursor($){return($.client??this.client).get({url:"/email/threads/previews/cursor/{view}",...$})}archiveThread($){return($.client??this.client).patch({url:"/email/threads/{id}/archived",...$,headers:{"Content-Type":"application/json",...$.headers}})}addRemoveThreadLabel($){return($.client??this.client).patch({url:"/email/threads/{id}/labels",...$,headers:{"Content-Type":"application/json",...$.headers}})}getThreadMessagesHandler($){return($.client??this.client).get({url:"/email/threads/{id}/messages",...$})}threadOperations($){return($.client??this.client).get({url:"/email/threads/{id}/operations",...$})}threadSeen($){return($.client??this.client).post({url:"/email/threads/{id}/seen",...$})}updateThreadState($){return($.client??this.client).patch({url:"/email/threads/{id}/state",...$,headers:{"Content-Type":"application/json",...$.headers}})}getThread($){return($.client??this.client).get({url:"/email/threads/{thread_id}",...$})}getThreadCalendarInvitations($){return($.client??this.client).get({url:"/email/threads/{thread_id}/calendar-invitations",...$})}copyThreadCalendarInvitation($){return($.client??this.client).post({url:"/email/threads/{thread_id}/messages/{message_id}/calendar-invitations/{invitation_id}/copy",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateThreadProject($){return($.client??this.client).patch({url:"/email/threads/{thread_id}/project",...$,headers:{"Content-Type":"application/json",...$.headers}})}healthHandler($){return($?.client??this.client).get({url:"/health",...$})}}function VS({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:G,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:K,url:L,...Q}){let J,I=K??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=G??3000,B=0,T=Q.signal??new AbortController().signal;while(!0){if(T.aborted)break;B++;let C=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)C.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:C,signal:T},_=new Request(L,D);if($)_=await $(L,D);let N=await(Q.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{H.cancel()}catch{}};T.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await H.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
`);let 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{T.removeEventListener("abort",g),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var U5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},z5=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},I5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},G0=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((K)=>encodeURIComponent(K))).join(z5(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let G=U5(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return fO({allowReserved:$,name:j,value:X})}).join(G);return x==="label"||x==="matrix"?G+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)}`},K0=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:G})=>{if(S instanceof Date)return G?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let K=[];Object.entries(S).forEach(([Q,J])=>{K=[...K,Q,$?J:encodeURIComponent(J)]});let L=K.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=I5(x),X=Object.entries(S).map(([K,L])=>fO({allowReserved:$,name:x==="deepObject"?`${j}[${K}]`:K,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var T5=/\{[^{}]+\}/g,H5=({path:$,url:O})=>{let j=O,x=O.match(T5);if(x)for(let S of x){let G=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))G=!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 K=$[Z];if(K===void 0||K===null)continue;if(Array.isArray(K)){j=j.replace(S,G0({explode:G,name:Z,style:X,value:K}));continue}if(typeof K==="object"){j=j.replace(S,K0({explode:G,name:Z,style:X,value:K,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${fO({name:Z,value:K})}`);continue}let L=encodeURIComponent(X==="label"?`.${K}`:K);j=j.replace(S,L)}return j},VS=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let G=S.startsWith("/")?S:`/${S}`,Z=($??"")+G;if(O)Z=H5({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function Y1($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var WS=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var BS={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var LS=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let G in x){let Z=x[G];if(Z===void 0||Z===null)continue;let X=$[G]||O;if(Array.isArray(Z)){let K=G0({allowReserved:X.allowReserved,explode:!0,name:G,style:"form",value:Z,...X.array});if(K)S.push(K)}else if(typeof Z==="object"){let K=K0({allowReserved:X.allowReserved,explode:!0,name:G,style:"deepObject",value:Z,...X.object});if(K)S.push(K)}else{let K=fO({allowReserved:X.allowReserved,name:G,value:Z});if(K)S.push(K)}}return S.join("&")}},NS=($)=>{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 US($){for(let O of $.security??[]){if(R5($,O.name))continue;let j=await WS(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=($)=>VS({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:LS($.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=Q0($.headers,O.headers),j},D5=($)=>{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?D5(j):Object.entries(j);for(let[S,G]of x)if(G===null)O.delete(S);else if(Array.isArray(G))for(let Z of G)O.append(S,Z);else if(G!==void 0)O.set(S,typeof G==="object"?JSON.stringify(G):G)}return O};class Y0{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var zS=()=>({error:new Y0,request:new Y0,response:new Y0}),_5=LS({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),M5={"Content-Type":"application/json"},Gj=($={})=>({...BS,headers:M5,parseAs:"auto",querySerializer:_5,...$});var V1=($={})=>{let O=J1(Gj(),$),j=()=>({...O}),x=(Q)=>{return O=J1(O,Q),j()},S=zS(),G=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:Q0(O.headers,Q.headers),serializedBody:void 0};if(J.security)await US(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(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await G(Q),T={redirect:"follow",...V,body:Y1(V)};z=new Request(B,T);for(let N of S.request.fns)if(N)z=await N(z,V);let C=V.fetch;W=await C(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?NS(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await W[N]();break;case"json":{let U=await W.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let _=await W.text(),w;try{w=JSON.parse(_)}catch{}throw w??_}catch(V){let B=V;for(let T of S.error.fns)if(T)B=await T(B,W,z,Q);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(Q)=>(J)=>Z({...J,method:Q}),K=(Q)=>async(J)=>{let{opts:I,url:z}=await G(J);return JS({...I,body:I.body,method:Q,onRequest:async(W,V)=>{let B=new Request(W,V);for(let T of S.request.fns)if(T)B=await T(B,I);return B},serializedBody:Y1(I),url:z})};return{buildUrl:(Q)=>Q1({...O,...Q}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:K("CONNECT"),delete:K("DELETE"),get:K("GET"),head:K("HEAD"),options:K("OPTIONS"),patch:K("PATCH"),post:K("POST"),put:K("PUT"),trace:K("TRACE")},trace:X("TRACE")}};var IS=V1(Gj());class TS{client;constructor($){this.client=$?.client??IS}}class HS{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 TS{static __registry=new HS;constructor($){super($);J0.__registry.set(this,$?.key)}healthHandler($){return($?.client??this.client).get({url:"/health",...$})}getUnsubscribes($){return($?.client??this.client).get({url:"/unsubscribe",...$})}unsubscribeEmail($){return($?.client??this.client).post({url:"/unsubscribe/email",...$})}removeUnsubscribeItem($){return($.client??this.client).delete({url:"/unsubscribe/item/{item_type}/{item_id}",...$})}unsubscribeItem($){return($.client??this.client).post({url:"/unsubscribe/item/{item_type}/{item_id}",...$})}removeUnsubscribeAll($){return($?.client??this.client).delete({url:"/unsubscribe/mute",...$})}unsubscribeAll($){return($?.client??this.client).post({url:"/unsubscribe/mute",...$})}listTypedNotifications($){return($?.client??this.client).get({url:"/v1/user_notifications",...$})}bulkGetTypedNotificationsByEventItemIds($){return($.client??this.client).post({url:"/v1/user_notifications/item/bulk",...$,headers:{"Content-Type":"application/json",...$.headers}})}getTypedNotificationsByEventItemId($){return($.client??this.client).get({url:"/v1/user_notifications/item/{event_item_id}",...$})}getNotificationTypePreferences($){return($?.client??this.client).get({url:"/v1/user_notifications/preferences",...$})}disableNotificationType($){return($.client??this.client).put({url:"/v1/user_notifications/preferences/{notification_event_type}/disable",...$})}enableNotificationType($){return($.client??this.client).put({url:"/v1/user_notifications/preferences/{notification_event_type}/enable",...$})}getTypedNotificationById($){return($.client??this.client).get({url:"/v1/user_notifications/{notification_id}",...$})}bulkDeleteUserNotificationsV2($){return($.client??this.client).delete({url:"/v2/user_notifications/bulk",...$,headers:{"Content-Type":"application/json",...$.headers}})}bulkMarkNotificationsDone($){return($.client??this.client).patch({url:"/v2/user_notifications/bulk/done",...$,headers:{"Content-Type":"application/json",...$.headers}})}bulkMarkNotificationsSeen($){return($.client??this.client).patch({url:"/v2/user_notifications/bulk/seen",...$,headers:{"Content-Type":"application/json",...$.headers}})}bulkMarkNotificationsUndone($){return($.client??this.client).patch({url:"/v2/user_notifications/bulk/undone",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteUserNotificationV2($){return($.client??this.client).delete({url:"/v2/user_notifications/{notification_id}",...$})}}function RS({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:G,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:K,url:L,...Q}){let J,I=K??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=G??3000,B=0,T=Q.signal??new AbortController().signal;while(!0){if(T.aborted)break;B++;let C=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)C.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:C,signal:T},_=new Request(L,D);if($)_=await $(L,D);let N=await(Q.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{H.cancel()}catch{}};T.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await H.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
+`);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{T.removeEventListener("abort",g),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var z5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},I5=($)=>{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"&"}},K0=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((K)=>encodeURIComponent(K))).join(I5(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let G=z5(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return fO({allowReserved:$,name:j,value:X})}).join(G);return x==="label"||x==="matrix"?G+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:G})=>{if(S instanceof Date)return G?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let K=[];Object.entries(S).forEach(([Q,J])=>{K=[...K,Q,$?J:encodeURIComponent(J)]});let L=K.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(([K,L])=>fO({allowReserved:$,name:x==="deepObject"?`${j}[${K}]`:K,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var H5=/\{[^{}]+\}/g,R5=({path:$,url:O})=>{let j=O,x=O.match(H5);if(x)for(let S of x){let G=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))G=!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 K=$[Z];if(K===void 0||K===null)continue;if(Array.isArray(K)){j=j.replace(S,K0({explode:G,name:Z,style:X,value:K}));continue}if(typeof K==="object"){j=j.replace(S,Y0({explode:G,name:Z,style:X,value:K,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${fO({name:Z,value:K})}`);continue}let L=encodeURIComponent(X==="label"?`.${K}`:K);j=j.replace(S,L)}return j},WS=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let G=S.startsWith("/")?S:`/${S}`,Z=($??"")+G;if(O)Z=R5({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function Y1($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var BS=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var LS={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var NS=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let G in x){let Z=x[G];if(Z===void 0||Z===null)continue;let X=$[G]||O;if(Array.isArray(Z)){let K=K0({allowReserved:X.allowReserved,explode:!0,name:G,style:"form",value:Z,...X.array});if(K)S.push(K)}else if(typeof Z==="object"){let K=Y0({allowReserved:X.allowReserved,explode:!0,name:G,style:"deepObject",value:Z,...X.object});if(K)S.push(K)}else{let K=fO({allowReserved:X.allowReserved,name:G,value:Z});if(K)S.push(K)}}return S.join("&")}},US=($)=>{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 zS($){for(let O of $.security??[]){if(D5($,O.name))continue;let j=await BS(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var Q1=($)=>WS({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:NS($.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=J0($.headers,O.headers),j},_5=($)=>{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?_5(j):Object.entries(j);for(let[S,G]of x)if(G===null)O.delete(S);else if(Array.isArray(G))for(let Z of G)O.append(S,Z);else if(G!==void 0)O.set(S,typeof G==="object"?JSON.stringify(G):G)}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 IS=()=>({error:new Q0,request:new Q0,response:new Q0}),M5=NS({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),P5={"Content-Type":"application/json"},Gj=($={})=>({...LS,headers:P5,parseAs:"auto",querySerializer:M5,...$});var V1=($={})=>{let O=J1(Gj(),$),j=()=>({...O}),x=(Q)=>{return O=J1(O,Q),j()},S=IS(),G=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:J0(O.headers,Q.headers),serializedBody:void 0};if(J.security)await zS(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let I=J,z=Q1(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await G(Q),T={redirect:"follow",...V,body:Y1(V)};z=new Request(B,T);for(let N of S.request.fns)if(N)z=await N(z,V);let C=V.fetch;W=await C(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?US(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await W[N]();break;case"json":{let U=await W.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let _=await W.text(),w;try{w=JSON.parse(_)}catch{}throw w??_}catch(V){let B=V;for(let T of S.error.fns)if(T)B=await T(B,W,z,Q);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(Q)=>(J)=>Z({...J,method:Q}),K=(Q)=>async(J)=>{let{opts:I,url:z}=await G(J);return VS({...I,body:I.body,method:Q,onRequest:async(W,V)=>{let B=new Request(W,V);for(let T of S.request.fns)if(T)B=await T(B,I);return B},serializedBody:Y1(I),url:z})};return{buildUrl:(Q)=>Q1({...O,...Q}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:K("CONNECT"),delete:K("DELETE"),get:K("GET"),head:K("HEAD"),options:K("OPTIONS"),patch:K("PATCH"),post:K("POST"),put:K("PUT"),trace:K("TRACE")},trace:X("TRACE")}};var TS=V1(Gj());class HS{client;constructor($){this.client=$?.client??TS}}class RS{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 HS{static __registry=new RS;constructor($){super($);V0.__registry.set(this,$?.key)}healthHandler($){return($?.client??this.client).get({url:"/health",...$})}getUnsubscribes($){return($?.client??this.client).get({url:"/unsubscribe",...$})}unsubscribeEmail($){return($?.client??this.client).post({url:"/unsubscribe/email",...$})}removeUnsubscribeItem($){return($.client??this.client).delete({url:"/unsubscribe/item/{item_type}/{item_id}",...$})}unsubscribeItem($){return($.client??this.client).post({url:"/unsubscribe/item/{item_type}/{item_id}",...$})}removeUnsubscribeAll($){return($?.client??this.client).delete({url:"/unsubscribe/mute",...$})}unsubscribeAll($){return($?.client??this.client).post({url:"/unsubscribe/mute",...$})}listTypedNotifications($){return($?.client??this.client).get({url:"/v1/user_notifications",...$})}bulkGetTypedNotificationsByEventItemIds($){return($.client??this.client).post({url:"/v1/user_notifications/item/bulk",...$,headers:{"Content-Type":"application/json",...$.headers}})}getTypedNotificationsByEventItemId($){return($.client??this.client).get({url:"/v1/user_notifications/item/{event_item_id}",...$})}getNotificationTypePreferences($){return($?.client??this.client).get({url:"/v1/user_notifications/preferences",...$})}disableNotificationType($){return($.client??this.client).put({url:"/v1/user_notifications/preferences/{notification_event_type}/disable",...$})}enableNotificationType($){return($.client??this.client).put({url:"/v1/user_notifications/preferences/{notification_event_type}/enable",...$})}getTypedNotificationById($){return($.client??this.client).get({url:"/v1/user_notifications/{notification_id}",...$})}bulkDeleteUserNotificationsV2($){return($.client??this.client).delete({url:"/v2/user_notifications/bulk",...$,headers:{"Content-Type":"application/json",...$.headers}})}bulkMarkNotificationsDone($){return($.client??this.client).patch({url:"/v2/user_notifications/bulk/done",...$,headers:{"Content-Type":"application/json",...$.headers}})}bulkMarkNotificationsSeen($){return($.client??this.client).patch({url:"/v2/user_notifications/bulk/seen",...$,headers:{"Content-Type":"application/json",...$.headers}})}bulkMarkNotificationsUndone($){return($.client??this.client).patch({url:"/v2/user_notifications/bulk/undone",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteUserNotificationV2($){return($.client??this.client).delete({url:"/v2/user_notifications/{notification_id}",...$})}}function DS({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:G,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:K,url:L,...Q}){let J,I=K??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=G??3000,B=0,T=Q.signal??new AbortController().signal;while(!0){if(T.aborted)break;B++;let C=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)C.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:C,signal:T},_=new Request(L,D);if($)_=await $(L,D);let N=await(Q.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{H.cancel()}catch{}};T.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await H.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
`);let 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{T.removeEventListener("abort",g),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var P5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},A5=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},C5=($)=>{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((K)=>encodeURIComponent(K))).join(A5(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let G=P5(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return bO({allowReserved:$,name:j,value:X})}).join(G);return x==="label"||x==="matrix"?G+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)}`},W0=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:G})=>{if(S instanceof Date)return G?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let K=[];Object.entries(S).forEach(([Q,J])=>{K=[...K,Q,$?J:encodeURIComponent(J)]});let L=K.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(([K,L])=>bO({allowReserved:$,name:x==="deepObject"?`${j}[${K}]`:K,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var F5=/\{[^{}]+\}/g,E5=({path:$,url:O})=>{let j=O,x=O.match(F5);if(x)for(let S of x){let G=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))G=!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 K=$[Z];if(K===void 0||K===null)continue;if(Array.isArray(K)){j=j.replace(S,V0({explode:G,name:Z,style:X,value:K}));continue}if(typeof K==="object"){j=j.replace(S,W0({explode:G,name:Z,style:X,value:K,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${bO({name:Z,value:K})}`);continue}let L=encodeURIComponent(X==="label"?`.${K}`:K);j=j.replace(S,L)}return j},DS=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let G=S.startsWith("/")?S:`/${S}`,Z=($??"")+G;if(O)Z=E5({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 _S=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var MS={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var PS=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let G in x){let Z=x[G];if(Z===void 0||Z===null)continue;let X=$[G]||O;if(Array.isArray(Z)){let K=V0({allowReserved:X.allowReserved,explode:!0,name:G,style:"form",value:Z,...X.array});if(K)S.push(K)}else if(typeof Z==="object"){let K=W0({allowReserved:X.allowReserved,explode:!0,name:G,style:"deepObject",value:Z,...X.object});if(K)S.push(K)}else{let K=bO({allowReserved:X.allowReserved,name:G,value:Z});if(K)S.push(K)}}return S.join("&")}},AS=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},w5=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function CS($){for(let O of $.security??[]){if(w5($,O.name))continue;let j=await _S(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var B1=($)=>DS({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:PS($.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=L0($.headers,O.headers),j},q5=($)=>{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?q5(j):Object.entries(j);for(let[S,G]of x)if(G===null)O.delete(S);else if(Array.isArray(G))for(let Z of G)O.append(S,Z);else if(G!==void 0)O.set(S,typeof G==="object"?JSON.stringify(G):G)}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 FS=()=>({error:new B0,request:new B0,response:new B0}),f5=PS({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),b5={"Content-Type":"application/json"},Kj=($={})=>({...MS,headers:b5,parseAs:"auto",querySerializer:f5,...$});var N1=($={})=>{let O=L1(Kj(),$),j=()=>({...O}),x=(Q)=>{return O=L1(O,Q),j()},S=FS(),G=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:L0(O.headers,Q.headers),serializedBody:void 0};if(J.security)await CS(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let I=J,z=B1(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await G(Q),T={redirect:"follow",...V,body:W1(V)};z=new Request(B,T);for(let N of S.request.fns)if(N)z=await N(z,V);let C=V.fetch;W=await C(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?AS(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await W[N]();break;case"json":{let U=await W.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let _=await W.text(),w;try{w=JSON.parse(_)}catch{}throw w??_}catch(V){let B=V;for(let T of S.error.fns)if(T)B=await T(B,W,z,Q);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(Q)=>(J)=>Z({...J,method:Q}),K=(Q)=>async(J)=>{let{opts:I,url:z}=await G(J);return RS({...I,body:I.body,method:Q,onRequest:async(W,V)=>{let B=new Request(W,V);for(let T of S.request.fns)if(T)B=await T(B,I);return B},serializedBody:W1(I),url:z})};return{buildUrl:(Q)=>B1({...O,...Q}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:K("CONNECT"),delete:K("DELETE"),get:K("GET"),head:K("HEAD"),options:K("OPTIONS"),patch:K("PATCH"),post:K("POST"),put:K("PUT"),trace:K("TRACE")},trace:X("TRACE")}};var ES=N1(Kj());class wS{client;constructor($){this.client=$?.client??ES}}class qS{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 wS{static __registry=new qS;constructor($){super($);N0.__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 fS({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:G,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:K,url:L,...Q}){let J,I=K??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=G??3000,B=0,T=Q.signal??new AbortController().signal;while(!0){if(T.aborted)break;B++;let C=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)C.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:C,signal:T},_=new Request(L,D);if($)_=await $(L,D);let N=await(Q.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{H.cancel()}catch{}};T.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await H.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
+`);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{T.removeEventListener("abort",g),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var A5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},C5=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},F5=($)=>{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((K)=>encodeURIComponent(K))).join(C5(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let G=A5(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return bO({allowReserved:$,name:j,value:X})}).join(G);return x==="label"||x==="matrix"?G+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:G})=>{if(S instanceof Date)return G?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let K=[];Object.entries(S).forEach(([Q,J])=>{K=[...K,Q,$?J:encodeURIComponent(J)]});let L=K.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=F5(x),X=Object.entries(S).map(([K,L])=>bO({allowReserved:$,name:x==="deepObject"?`${j}[${K}]`:K,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var E5=/\{[^{}]+\}/g,w5=({path:$,url:O})=>{let j=O,x=O.match(E5);if(x)for(let S of x){let G=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))G=!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 K=$[Z];if(K===void 0||K===null)continue;if(Array.isArray(K)){j=j.replace(S,W0({explode:G,name:Z,style:X,value:K}));continue}if(typeof K==="object"){j=j.replace(S,B0({explode:G,name:Z,style:X,value:K,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${bO({name:Z,value:K})}`);continue}let L=encodeURIComponent(X==="label"?`.${K}`:K);j=j.replace(S,L)}return j},_S=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let G=S.startsWith("/")?S:`/${S}`,Z=($??"")+G;if(O)Z=w5({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 MS=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var PS={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var AS=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let G in x){let Z=x[G];if(Z===void 0||Z===null)continue;let X=$[G]||O;if(Array.isArray(Z)){let K=W0({allowReserved:X.allowReserved,explode:!0,name:G,style:"form",value:Z,...X.array});if(K)S.push(K)}else if(typeof Z==="object"){let K=B0({allowReserved:X.allowReserved,explode:!0,name:G,style:"deepObject",value:Z,...X.object});if(K)S.push(K)}else{let K=bO({allowReserved:X.allowReserved,name:G,value:Z});if(K)S.push(K)}}return S.join("&")}},CS=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},q5=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function FS($){for(let O of $.security??[]){if(q5($,O.name))continue;let j=await MS(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=($)=>_S({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:AS($.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=N0($.headers,O.headers),j},f5=($)=>{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?f5(j):Object.entries(j);for(let[S,G]of x)if(G===null)O.delete(S);else if(Array.isArray(G))for(let Z of G)O.append(S,Z);else if(G!==void 0)O.set(S,typeof G==="object"?JSON.stringify(G):G)}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 ES=()=>({error:new L0,request:new L0,response:new L0}),b5=AS({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),k5={"Content-Type":"application/json"},Kj=($={})=>({...PS,headers:k5,parseAs:"auto",querySerializer:b5,...$});var N1=($={})=>{let O=L1(Kj(),$),j=()=>({...O}),x=(Q)=>{return O=L1(O,Q),j()},S=ES(),G=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:N0(O.headers,Q.headers),serializedBody:void 0};if(J.security)await FS(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let I=J,z=B1(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await G(Q),T={redirect:"follow",...V,body:W1(V)};z=new Request(B,T);for(let N of S.request.fns)if(N)z=await N(z,V);let C=V.fetch;W=await C(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?CS(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await W[N]();break;case"json":{let U=await W.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let _=await W.text(),w;try{w=JSON.parse(_)}catch{}throw w??_}catch(V){let B=V;for(let T of S.error.fns)if(T)B=await T(B,W,z,Q);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(Q)=>(J)=>Z({...J,method:Q}),K=(Q)=>async(J)=>{let{opts:I,url:z}=await G(J);return DS({...I,body:I.body,method:Q,onRequest:async(W,V)=>{let B=new Request(W,V);for(let T of S.request.fns)if(T)B=await T(B,I);return B},serializedBody:W1(I),url:z})};return{buildUrl:(Q)=>B1({...O,...Q}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:K("CONNECT"),delete:K("DELETE"),get:K("GET"),head:K("HEAD"),options:K("OPTIONS"),patch:K("PATCH"),post:K("POST"),put:K("PUT"),trace:K("TRACE")},trace:X("TRACE")}};var wS=N1(Kj());class qS{client;constructor($){this.client=$?.client??wS}}class fS{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class U0 extends qS{static __registry=new fS;constructor($){super($);U0.__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 bS({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:G,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:K,url:L,...Q}){let J,I=K??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=G??3000,B=0,T=Q.signal??new AbortController().signal;while(!0){if(T.aborted)break;B++;let C=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)C.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:C,signal:T},_=new Request(L,D);if($)_=await $(L,D);let N=await(Q.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{H.cancel()}catch{}};T.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await H.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
`);let 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{T.removeEventListener("abort",g),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var k5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},g5=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},y5=($)=>{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((K)=>encodeURIComponent(K))).join(g5(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let G=k5(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return kO({allowReserved:$,name:j,value:X})}).join(G);return x==="label"||x==="matrix"?G+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)}`},z0=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:G})=>{if(S instanceof Date)return G?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let K=[];Object.entries(S).forEach(([Q,J])=>{K=[...K,Q,$?J:encodeURIComponent(J)]});let L=K.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=y5(x),X=Object.entries(S).map(([K,L])=>kO({allowReserved:$,name:x==="deepObject"?`${j}[${K}]`:K,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var v5=/\{[^{}]+\}/g,h5=({path:$,url:O})=>{let j=O,x=O.match(v5);if(x)for(let S of x){let G=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))G=!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 K=$[Z];if(K===void 0||K===null)continue;if(Array.isArray(K)){j=j.replace(S,U0({explode:G,name:Z,style:X,value:K}));continue}if(typeof K==="object"){j=j.replace(S,z0({explode:G,name:Z,style:X,value:K,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${kO({name:Z,value:K})}`);continue}let L=encodeURIComponent(X==="label"?`.${K}`:K);j=j.replace(S,L)}return j},bS=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let G=S.startsWith("/")?S:`/${S}`,Z=($??"")+G;if(O)Z=h5({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 kS=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 gS={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var yS=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let G in x){let Z=x[G];if(Z===void 0||Z===null)continue;let X=$[G]||O;if(Array.isArray(Z)){let K=U0({allowReserved:X.allowReserved,explode:!0,name:G,style:"form",value:Z,...X.array});if(K)S.push(K)}else if(typeof Z==="object"){let K=z0({allowReserved:X.allowReserved,explode:!0,name:G,style:"deepObject",value:Z,...X.object});if(K)S.push(K)}else{let K=kO({allowReserved:X.allowReserved,name:G,value:Z});if(K)S.push(K)}}return S.join("&")}},vS=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},m5=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function hS($){for(let O of $.security??[]){if(m5($,O.name))continue;let j=await kS(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=($)=>bS({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:yS($.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=T0($.headers,O.headers),j},u5=($)=>{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?u5(j):Object.entries(j);for(let[S,G]of x)if(G===null)O.delete(S);else if(Array.isArray(G))for(let Z of G)O.append(S,Z);else if(G!==void 0)O.set(S,typeof G==="object"?JSON.stringify(G):G)}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 mS=()=>({error:new I0,request:new I0,response:new I0}),c5=yS({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),d5={"Content-Type":"application/json"},Yj=($={})=>({...gS,headers:d5,parseAs:"auto",querySerializer:c5,...$});var T1=($={})=>{let O=I1(Yj(),$),j=()=>({...O}),x=(Q)=>{return O=I1(O,Q),j()},S=mS(),G=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:T0(O.headers,Q.headers),serializedBody:void 0};if(J.security)await hS(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let I=J,z=z1(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await G(Q),T={redirect:"follow",...V,body:U1(V)};z=new Request(B,T);for(let N of S.request.fns)if(N)z=await N(z,V);let C=V.fetch;W=await C(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?vS(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await W[N]();break;case"json":{let U=await W.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let _=await W.text(),w;try{w=JSON.parse(_)}catch{}throw w??_}catch(V){let B=V;for(let T of S.error.fns)if(T)B=await T(B,W,z,Q);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(Q)=>(J)=>Z({...J,method:Q}),K=(Q)=>async(J)=>{let{opts:I,url:z}=await G(J);return fS({...I,body:I.body,method:Q,onRequest:async(W,V)=>{let B=new Request(W,V);for(let T of S.request.fns)if(T)B=await T(B,I);return B},serializedBody:U1(I),url:z})};return{buildUrl:(Q)=>z1({...O,...Q}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:K("CONNECT"),delete:K("DELETE"),get:K("GET"),head:K("HEAD"),options:K("OPTIONS"),patch:K("PATCH"),post:K("POST"),put:K("PUT"),trace:K("TRACE")},trace:X("TRACE")}};var uS=T1(Yj());class cS{client;constructor($){this.client=$?.client??uS}}class dS{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class H0 extends cS{static __registry=new dS;constructor($){super($);H0.__registry.set(this,$?.key)}scheduledActionHealth($){return($?.client??this.client).get({url:"/health",...$})}listScheduledActions($){return($?.client??this.client).get({url:"/scheduled-actions",...$})}createScheduledAction($){return($.client??this.client).post({url:"/scheduled-actions",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteScheduledAction($){return($.client??this.client).delete({url:"/scheduled-actions/{id}",...$})}getScheduledAction($){return($.client??this.client).get({url:"/scheduled-actions/{id}",...$})}updateScheduledAction($){return($.client??this.client).put({url:"/scheduled-actions/{id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}setScheduledActionEnabled($){return($.client??this.client).put({url:"/scheduled-actions/{id}/enabled",...$,headers:{"Content-Type":"application/json",...$.headers}})}executeScheduledActionNow($){return($.client??this.client).post({url:"/scheduled-actions/{id}/execute",...$})}listScheduledActionHistory($){return($.client??this.client).get({url:"/scheduled-actions/{id}/history",...$})}}function lS({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:G,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:K,url:L,...Q}){let J,I=K??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=G??3000,B=0,T=Q.signal??new AbortController().signal;while(!0){if(T.aborted)break;B++;let C=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)C.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:C,signal:T},_=new Request(L,D);if($)_=await $(L,D);let N=await(Q.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{H.cancel()}catch{}};T.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await H.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
+`);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{T.removeEventListener("abort",g),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var g5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},y5=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},v5=($)=>{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((K)=>encodeURIComponent(K))).join(y5(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let G=g5(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return kO({allowReserved:$,name:j,value:X})}).join(G);return x==="label"||x==="matrix"?G+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:G})=>{if(S instanceof Date)return G?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let K=[];Object.entries(S).forEach(([Q,J])=>{K=[...K,Q,$?J:encodeURIComponent(J)]});let L=K.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=v5(x),X=Object.entries(S).map(([K,L])=>kO({allowReserved:$,name:x==="deepObject"?`${j}[${K}]`:K,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var h5=/\{[^{}]+\}/g,m5=({path:$,url:O})=>{let j=O,x=O.match(h5);if(x)for(let S of x){let G=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))G=!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 K=$[Z];if(K===void 0||K===null)continue;if(Array.isArray(K)){j=j.replace(S,z0({explode:G,name:Z,style:X,value:K}));continue}if(typeof K==="object"){j=j.replace(S,I0({explode:G,name:Z,style:X,value:K,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${kO({name:Z,value:K})}`);continue}let L=encodeURIComponent(X==="label"?`.${K}`:K);j=j.replace(S,L)}return j},kS=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let G=S.startsWith("/")?S:`/${S}`,Z=($??"")+G;if(O)Z=m5({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function 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 gS=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 yS={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var vS=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let G in x){let Z=x[G];if(Z===void 0||Z===null)continue;let X=$[G]||O;if(Array.isArray(Z)){let K=z0({allowReserved:X.allowReserved,explode:!0,name:G,style:"form",value:Z,...X.array});if(K)S.push(K)}else if(typeof Z==="object"){let K=I0({allowReserved:X.allowReserved,explode:!0,name:G,style:"deepObject",value:Z,...X.object});if(K)S.push(K)}else{let K=kO({allowReserved:X.allowReserved,name:G,value:Z});if(K)S.push(K)}}return S.join("&")}},hS=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},u5=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function mS($){for(let O of $.security??[]){if(u5($,O.name))continue;let j=await gS(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=($)=>kS({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:vS($.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=H0($.headers,O.headers),j},c5=($)=>{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?c5(j):Object.entries(j);for(let[S,G]of x)if(G===null)O.delete(S);else if(Array.isArray(G))for(let Z of G)O.append(S,Z);else if(G!==void 0)O.set(S,typeof G==="object"?JSON.stringify(G):G)}return O};class T0{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var uS=()=>({error:new T0,request:new T0,response:new T0}),d5=vS({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),l5={"Content-Type":"application/json"},Yj=($={})=>({...yS,headers:l5,parseAs:"auto",querySerializer:d5,...$});var T1=($={})=>{let O=I1(Yj(),$),j=()=>({...O}),x=(Q)=>{return O=I1(O,Q),j()},S=uS(),G=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:H0(O.headers,Q.headers),serializedBody:void 0};if(J.security)await mS(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let I=J,z=z1(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await G(Q),T={redirect:"follow",...V,body:U1(V)};z=new Request(B,T);for(let N of S.request.fns)if(N)z=await N(z,V);let C=V.fetch;W=await C(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?hS(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await W[N]();break;case"json":{let U=await W.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let _=await W.text(),w;try{w=JSON.parse(_)}catch{}throw w??_}catch(V){let B=V;for(let T of S.error.fns)if(T)B=await T(B,W,z,Q);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(Q)=>(J)=>Z({...J,method:Q}),K=(Q)=>async(J)=>{let{opts:I,url:z}=await G(J);return bS({...I,body:I.body,method:Q,onRequest:async(W,V)=>{let B=new Request(W,V);for(let T of S.request.fns)if(T)B=await T(B,I);return B},serializedBody:U1(I),url:z})};return{buildUrl:(Q)=>z1({...O,...Q}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:K("CONNECT"),delete:K("DELETE"),get:K("GET"),head:K("HEAD"),options:K("OPTIONS"),patch:K("PATCH"),post:K("POST"),put:K("PUT"),trace:K("TRACE")},trace:X("TRACE")}};var cS=T1(Yj());class dS{client;constructor($){this.client=$?.client??cS}}class lS{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 dS{static __registry=new lS;constructor($){super($);R0.__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 rS({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:G,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:K,url:L,...Q}){let J,I=K??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=G??3000,B=0,T=Q.signal??new AbortController().signal;while(!0){if(T.aborted)break;B++;let C=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)C.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:C,signal:T},_=new Request(L,D);if($)_=await $(L,D);let N=await(Q.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{H.cancel()}catch{}};T.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await H.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
`);let 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{T.removeEventListener("abort",g),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var l5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},r5=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},p5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},R0=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((K)=>encodeURIComponent(K))).join(r5(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let G=l5(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return gO({allowReserved:$,name:j,value:X})}).join(G);return x==="label"||x==="matrix"?G+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)}`},D0=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:G})=>{if(S instanceof Date)return G?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let K=[];Object.entries(S).forEach(([Q,J])=>{K=[...K,Q,$?J:encodeURIComponent(J)]});let L=K.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=p5(x),X=Object.entries(S).map(([K,L])=>gO({allowReserved:$,name:x==="deepObject"?`${j}[${K}]`:K,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var a5=/\{[^{}]+\}/g,i5=({path:$,url:O})=>{let j=O,x=O.match(a5);if(x)for(let S of x){let G=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))G=!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 K=$[Z];if(K===void 0||K===null)continue;if(Array.isArray(K)){j=j.replace(S,R0({explode:G,name:Z,style:X,value:K}));continue}if(typeof K==="object"){j=j.replace(S,D0({explode:G,name:Z,style:X,value:K,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${gO({name:Z,value:K})}`);continue}let L=encodeURIComponent(X==="label"?`.${K}`:K);j=j.replace(S,L)}return j},rS=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let G=S.startsWith("/")?S:`/${S}`,Z=($??"")+G;if(O)Z=i5({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 pS=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 aS={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var iS=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let G in x){let Z=x[G];if(Z===void 0||Z===null)continue;let X=$[G]||O;if(Array.isArray(Z)){let K=R0({allowReserved:X.allowReserved,explode:!0,name:G,style:"form",value:Z,...X.array});if(K)S.push(K)}else if(typeof Z==="object"){let K=D0({allowReserved:X.allowReserved,explode:!0,name:G,style:"deepObject",value:Z,...X.object});if(K)S.push(K)}else{let K=gO({allowReserved:X.allowReserved,name:G,value:Z});if(K)S.push(K)}}return S.join("&")}},nS=($)=>{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},n5=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function sS($){for(let O of $.security??[]){if(n5($,O.name))continue;let j=await pS(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=($)=>rS({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:iS($.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=M0($.headers,O.headers),j},s5=($)=>{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?s5(j):Object.entries(j);for(let[S,G]of x)if(G===null)O.delete(S);else if(Array.isArray(G))for(let Z of G)O.append(S,Z);else if(G!==void 0)O.set(S,typeof G==="object"?JSON.stringify(G):G)}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 tS=()=>({error:new _0,request:new _0,response:new _0}),t5=iS({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),e5={"Content-Type":"application/json"},Qj=($={})=>({...aS,headers:e5,parseAs:"auto",querySerializer:t5,...$});var _1=($={})=>{let O=D1(Qj(),$),j=()=>({...O}),x=(Q)=>{return O=D1(O,Q),j()},S=tS(),G=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:M0(O.headers,Q.headers),serializedBody:void 0};if(J.security)await sS(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let I=J,z=R1(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await G(Q),T={redirect:"follow",...V,body:H1(V)};z=new Request(B,T);for(let N of S.request.fns)if(N)z=await N(z,V);let C=V.fetch;W=await C(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?nS(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await W[N]();break;case"json":{let U=await W.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let _=await W.text(),w;try{w=JSON.parse(_)}catch{}throw w??_}catch(V){let B=V;for(let T of S.error.fns)if(T)B=await T(B,W,z,Q);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(Q)=>(J)=>Z({...J,method:Q}),K=(Q)=>async(J)=>{let{opts:I,url:z}=await G(J);return lS({...I,body:I.body,method:Q,onRequest:async(W,V)=>{let B=new Request(W,V);for(let T of S.request.fns)if(T)B=await T(B,I);return B},serializedBody:H1(I),url:z})};return{buildUrl:(Q)=>R1({...O,...Q}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:K("CONNECT"),delete:K("DELETE"),get:K("GET"),head:K("HEAD"),options:K("OPTIONS"),patch:K("PATCH"),post:K("POST"),put:K("PUT"),trace:K("TRACE")},trace:X("TRACE")}};var eS=_1(Qj());class oS{client;constructor($){this.client=$?.client??eS}}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 P0 extends oS{static __registry=new $6;constructor($){super($);P0.__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 O6=($,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 M1={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)=>O6(O,j,S));else O6(O,j,x)}),O}},P1={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};function j6({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:G,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:K,url:L,...Q}){let J,I=K??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=G??3000,B=0,T=Q.signal??new AbortController().signal;while(!0){if(T.aborted)break;B++;let C=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)C.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:C,signal:T},_=new Request(L,D);if($)_=await $(L,D);let N=await(Q.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{H.cancel()}catch{}};T.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await H.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
+`);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{T.removeEventListener("abort",g),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var r5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},p5=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},a5=($)=>{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((K)=>encodeURIComponent(K))).join(p5(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let G=r5(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return gO({allowReserved:$,name:j,value:X})}).join(G);return x==="label"||x==="matrix"?G+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:G})=>{if(S instanceof Date)return G?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let K=[];Object.entries(S).forEach(([Q,J])=>{K=[...K,Q,$?J:encodeURIComponent(J)]});let L=K.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=a5(x),X=Object.entries(S).map(([K,L])=>gO({allowReserved:$,name:x==="deepObject"?`${j}[${K}]`:K,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var i5=/\{[^{}]+\}/g,n5=({path:$,url:O})=>{let j=O,x=O.match(i5);if(x)for(let S of x){let G=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))G=!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 K=$[Z];if(K===void 0||K===null)continue;if(Array.isArray(K)){j=j.replace(S,D0({explode:G,name:Z,style:X,value:K}));continue}if(typeof K==="object"){j=j.replace(S,_0({explode:G,name:Z,style:X,value:K,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${gO({name:Z,value:K})}`);continue}let L=encodeURIComponent(X==="label"?`.${K}`:K);j=j.replace(S,L)}return j},pS=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let G=S.startsWith("/")?S:`/${S}`,Z=($??"")+G;if(O)Z=n5({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 aS=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 iS={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var nS=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let G in x){let Z=x[G];if(Z===void 0||Z===null)continue;let X=$[G]||O;if(Array.isArray(Z)){let K=D0({allowReserved:X.allowReserved,explode:!0,name:G,style:"form",value:Z,...X.array});if(K)S.push(K)}else if(typeof Z==="object"){let K=_0({allowReserved:X.allowReserved,explode:!0,name:G,style:"deepObject",value:Z,...X.object});if(K)S.push(K)}else{let K=gO({allowReserved:X.allowReserved,name:G,value:Z});if(K)S.push(K)}}return S.join("&")}},sS=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},s5=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function tS($){for(let O of $.security??[]){if(s5($,O.name))continue;let j=await aS(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=($)=>pS({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:nS($.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=P0($.headers,O.headers),j},t5=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},P0=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?t5(j):Object.entries(j);for(let[S,G]of x)if(G===null)O.delete(S);else if(Array.isArray(G))for(let Z of G)O.append(S,Z);else if(G!==void 0)O.set(S,typeof G==="object"?JSON.stringify(G):G)}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 eS=()=>({error:new M0,request:new M0,response:new M0}),e5=nS({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),o5={"Content-Type":"application/json"},Qj=($={})=>({...iS,headers:o5,parseAs:"auto",querySerializer:e5,...$});var _1=($={})=>{let O=D1(Qj(),$),j=()=>({...O}),x=(Q)=>{return O=D1(O,Q),j()},S=eS(),G=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:P0(O.headers,Q.headers),serializedBody:void 0};if(J.security)await tS(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(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await G(Q),T={redirect:"follow",...V,body:H1(V)};z=new Request(B,T);for(let N of S.request.fns)if(N)z=await N(z,V);let C=V.fetch;W=await C(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?sS(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await W[N]();break;case"json":{let U=await W.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let _=await W.text(),w;try{w=JSON.parse(_)}catch{}throw w??_}catch(V){let B=V;for(let T of S.error.fns)if(T)B=await T(B,W,z,Q);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(Q)=>(J)=>Z({...J,method:Q}),K=(Q)=>async(J)=>{let{opts:I,url:z}=await G(J);return rS({...I,body:I.body,method:Q,onRequest:async(W,V)=>{let B=new Request(W,V);for(let T of S.request.fns)if(T)B=await T(B,I);return B},serializedBody:H1(I),url:z})};return{buildUrl:(Q)=>R1({...O,...Q}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:K("CONNECT"),delete:K("DELETE"),get:K("GET"),head:K("HEAD"),options:K("OPTIONS"),patch:K("PATCH"),post:K("POST"),put:K("PUT"),trace:K("TRACE")},trace:X("TRACE")}};var oS=_1(Qj());class $6{client;constructor($){this.client=$?.client??oS}}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 A0 extends $6{static __registry=new O6;constructor($){super($);A0.__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 j6=($,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 M1={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)=>j6(O,j,S));else j6(O,j,x)}),O}},P1={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};function x6({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:G,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:K,url:L,...Q}){let J,I=K??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=G??3000,B=0,T=Q.signal??new AbortController().signal;while(!0){if(T.aborted)break;B++;let C=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)C.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:C,signal:T},_=new Request(L,D);if($)_=await $(L,D);let N=await(Q.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{H.cancel()}catch{}};T.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await H.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
`);let 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{T.removeEventListener("abort",g),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var o5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},$4=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},O4=($)=>{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((K)=>encodeURIComponent(K))).join($4(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let G=o5(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return yO({allowReserved:$,name:j,value:X})}).join(G);return x==="label"||x==="matrix"?G+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)}`},C0=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:G})=>{if(S instanceof Date)return G?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let K=[];Object.entries(S).forEach(([Q,J])=>{K=[...K,Q,$?J:encodeURIComponent(J)]});let L=K.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=O4(x),X=Object.entries(S).map(([K,L])=>yO({allowReserved:$,name:x==="deepObject"?`${j}[${K}]`:K,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var j4=/\{[^{}]+\}/g,x4=({path:$,url:O})=>{let j=O,x=O.match(j4);if(x)for(let S of x){let G=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))G=!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 K=$[Z];if(K===void 0||K===null)continue;if(Array.isArray(K)){j=j.replace(S,A0({explode:G,name:Z,style:X,value:K}));continue}if(typeof K==="object"){j=j.replace(S,C0({explode:G,name:Z,style:X,value:K,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${yO({name:Z,value:K})}`);continue}let L=encodeURIComponent(X==="label"?`.${K}`:K);j=j.replace(S,L)}return j},x6=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let G=S.startsWith("/")?S:`/${S}`,Z=($??"")+G;if(O)Z=x4({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function A1($){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=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let G in x){let Z=x[G];if(Z===void 0||Z===null)continue;let X=$[G]||O;if(Array.isArray(Z)){let K=A0({allowReserved:X.allowReserved,explode:!0,name:G,style:"form",value:Z,...X.array});if(K)S.push(K)}else if(typeof Z==="object"){let K=C0({allowReserved:X.allowReserved,explode:!0,name:G,style:"deepObject",value:Z,...X.object});if(K)S.push(K)}else{let K=yO({allowReserved:X.allowReserved,name:G,value:Z});if(K)S.push(K)}}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},S4=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function G6($){for(let O of $.security??[]){if(S4($,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 C1=($)=>x6({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:Z6($.querySerializer),url:$.url}),F1=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=E0($.headers,O.headers),j},Z4=($)=>{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?Z4(j):Object.entries(j);for(let[S,G]of x)if(G===null)O.delete(S);else if(Array.isArray(G))for(let Z of G)O.append(S,Z);else if(G!==void 0)O.set(S,typeof G==="object"?JSON.stringify(G):G)}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 K6=()=>({error:new F0,request:new F0,response:new F0}),X4=Z6({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),G4={"Content-Type":"application/json"},Jj=($={})=>({...P1,headers:G4,parseAs:"auto",querySerializer:X4,...$});var Vj=($={})=>{let O=F1(Jj(),$),j=()=>({...O}),x=(Q)=>{return O=F1(O,Q),j()},S=K6(),G=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:E0(O.headers,Q.headers),serializedBody:void 0};if(J.security)await G6(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let I=J,z=C1(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await G(Q),T={redirect:"follow",...V,body:A1(V)};z=new Request(B,T);for(let N of S.request.fns)if(N)z=await N(z,V);let C=V.fetch;W=await C(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?X6(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await W[N]();break;case"json":{let U=await W.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let _=await W.text(),w;try{w=JSON.parse(_)}catch{}throw w??_}catch(V){let B=V;for(let T of S.error.fns)if(T)B=await T(B,W,z,Q);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(Q)=>(J)=>Z({...J,method:Q}),K=(Q)=>async(J)=>{let{opts:I,url:z}=await G(J);return j6({...I,body:I.body,method:Q,onRequest:async(W,V)=>{let B=new Request(W,V);for(let T of S.request.fns)if(T)B=await T(B,I);return B},serializedBody:A1(I),url:z})};return{buildUrl:(Q)=>C1({...O,...Q}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:K("CONNECT"),delete:K("DELETE"),get:K("GET"),head:K("HEAD"),options:K("OPTIONS"),patch:K("PATCH"),post:K("POST"),put:K("PUT"),trace:K("TRACE")},trace:X("TRACE")}};var Y6=Vj(Jj());class Q6{client;constructor($){this.client=$?.client??Y6}}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 w0 extends Q6{static __registry=new J6;constructor($){super($);w0.__registry.set(this,$?.key)}listAgents($){return($?.client??this.client).get({url:"/agents",...$})}createAgent($){return($.client??this.client).post({url:"/agents",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateAgent($){return($.client??this.client).put({url:"/agents/{agent_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteAnchor($){return($.client??this.client).delete({url:"/annotations/anchors",...$,headers:{"Content-Type":"application/json",...$.headers}})}editAnchor($){return($.client??this.client).patch({url:"/annotations/anchors",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDocumentAnchors($){return($.client??this.client).get({url:"/annotations/anchors/document/{document_id}",...$})}createAnchor($){return($.client??this.client).post({url:"/annotations/anchors/document/{document_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getSelfBot($){return($?.client??this.client).get({url:"/bots/me",...$})}getBotOwnerProfiles($){return($?.client??this.client).get({url:"/bots/profiles",...$})}listBotChannels($){return($.client??this.client).get({url:"/bots/{bot_id}/channels",...$})}removeBotFromChannelByBot($){return($.client??this.client).delete({url:"/bots/{bot_id}/channels/{channel_id}",...$})}listOccurrences($){return($.client??this.client).get({url:"/calendar-events",...$})}mentionPreviews($){return($.client??this.client).post({url:"/calendar-events/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}listTeamCalendar($){return($.client??this.client).get({url:"/calendar-events/team",...$})}listTeamOutOfOffice($){return($.client??this.client).get({url:"/calendar-events/team-out-of-office",...$})}eventIcs($){return($.client??this.client).get({url:"/calendar-events/{event_id}/ics",...$})}listJoinRequests($){return($.client??this.client).get({url:"/calendar-events/{event_id}/join-requests",...$})}requestToJoin($){return($.client??this.client).post({url:"/calendar-events/{event_id}/join-requests",...$})}getActiveCalls($){return($?.client??this.client).get({url:"/call/active",...$})}guestCallChatRead($){return($.client??this.client).get({url:"/call/guest-chat/{call_id}",...$})}guestCallChatPost($){return($.client??this.client).post({url:"/call/guest-chat/{call_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}meetingLookup($){return($.client??this.client).get({url:"/call/join/{token}",...$})}meetingGuestJoin($){return($.client??this.client).post({url:"/call/join/{token}",...$,headers:{"Content-Type":"application/json",...$.headers}})}meetingLeave($){return($.client??this.client).post({url:"/call/join/{token}/leave",...$})}meetingGuestParticipants($){return($.client??this.client).get({url:"/call/join/{token}/participants",...$})}meetingList($){return($?.client??this.client).get({url:"/call/meetings",...$})}meetingCreate($){return($.client??this.client).post({url:"/call/meetings",...$,headers:{"Content-Type":"application/json",...$.headers}})}meetingListActive($){return($?.client??this.client).get({url:"/call/meetings/active",...$})}meetingInvitePermissions($){return($.client??this.client).get({url:"/call/meetings/invite/{token}",...$})}meetingInvite($){return($.client??this.client).post({url:"/call/meetings/invite/{token}",...$,headers:{"Content-Type":"application/json",...$.headers}})}meetingInviteUsers($){return($.client??this.client).post({url:"/call/meetings/invite/{token}/users",...$,headers:{"Content-Type":"application/json",...$.headers}})}meetingJoin($){return($.client??this.client).post({url:"/call/meetings/join/{token}",...$})}meetingParticipants($){return($.client??this.client).get({url:"/call/meetings/join/{token}/participants",...$})}meetingPrepare($){return($?.client??this.client).post({url:"/call/meetings/prepare",...$})}meetingCancelPreparation($){return($.client??this.client).delete({url:"/call/meetings/prepare/{preparation_id}",...$})}meetingCancel($){return($.client??this.client).delete({url:"/call/meetings/{meeting_id}",...$})}meetingUpdate($){return($.client??this.client).patch({url:"/call/meetings/{meeting_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getBatchCallRecordPreview($){return($.client??this.client).post({url:"/call/record/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteCallRecord($){return($.client??this.client).delete({url:"/call/record/{call_id}",...$})}getCallRecord($){return($.client??this.client).get({url:"/call/record/{call_id}",...$})}editCallRecord($){return($.client??this.client).patch({url:"/call/record/{call_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}declineCall($){return($.client??this.client).post({url:"/call/record/{call_id}/decline",...$})}meetingShare($){return($.client??this.client).post({url:"/call/record/{call_id}/link",...$})}toggleShareWithTeam($){return($.client??this.client).post({url:"/call/record/{call_id}/share-with-team/toggle",...$})}editCallTranscript($){return($.client??this.client).patch({url:"/call/record/{call_id}/transcript",...$,headers:{"Content-Type":"application/json",...$.headers}})}getRingStatus($){return($.client??this.client).get({url:"/call/ring-status/{call_id}",...$})}declineRing($){return($.client??this.client).post({url:"/call/ring-status/{call_id}/decline",...$})}callWebhook($){return($?.client??this.client).post({url:"/call/webhook",...$})}leaveOrEndCall($){return($.client??this.client).delete({url:"/call/{channel_id}",...$})}getOrCreateCall($){return($.client??this.client).get({url:"/call/{channel_id}",...$})}checkActiveCall($){return($.client??this.client).get({url:"/call/{channel_id}/active",...$})}ingestTranscript($){return($.client??this.client).post({url:"/call/{room_name}/transcript",...$,headers:{"Content-Type":"application/json",...$.headers}})}listChannelLabels($){return($?.client??this.client).get({url:"/channel-labels",...$})}createChannelLabel($){return($.client??this.client).post({url:"/channel-labels",...$,headers:{"Content-Type":"application/json",...$.headers}})}setChannelLabel($){return($.client??this.client).put({url:"/channel-labels/channels/{channel_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}previewSmartTag($){return($.client??this.client).post({url:"/channel-labels/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteChannelLabel($){return($.client??this.client).delete({url:"/channel-labels/{label_id}",...$})}renameChannelLabel($){return($.client??this.client).patch({url:"/channel-labels/{label_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}createChannel($){return($.client??this.client).post({url:"/channels",...$,headers:{"Content-Type":"application/json",...$.headers}})}getActivity($){return($?.client??this.client).get({url:"/channels/activity",...$})}postActivity($){return($.client??this.client).post({url:"/channels/activity",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAttachmentReferences($){return($.client??this.client).get({url:"/channels/attachments/{entity_type}/{entity_id}/references",...$})}getOrCreateDm($){return($.client??this.client).post({url:"/channels/get_or_create_dm",...$,headers:{"Content-Type":"application/json",...$.headers}})}getOrCreatePrivate($){return($.client??this.client).post({url:"/channels/get_or_create_private",...$,headers:{"Content-Type":"application/json",...$.headers}})}joinChannelByCode($){return($.client??this.client).post({url:"/channels/join/{join_code}",...$})}createEntityMention($){return($.client??this.client).post({url:"/channels/mentions",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteEntityMention($){return($.client??this.client).delete({url:"/channels/mentions/{mention_id}",...$})}getBatchChannelPreview($){return($.client??this.client).post({url:"/channels/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteChannel($){return($.client??this.client).delete({url:"/channels/{channel_id}",...$})}getChannel($){return($.client??this.client).get({url:"/channels/{channel_id}",...$})}patchChannel($){return($.client??this.client).patch({url:"/channels/{channel_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getChannelAttachments($){return($.client??this.client).get({url:"/channels/{channel_id}/attachments",...$})}createChannelScopedBot($){return($.client??this.client).post({url:"/channels/{channel_id}/bots/scoped",...$,headers:{"Content-Type":"application/json",...$.headers}})}joinChannel($){return($.client??this.client).post({url:"/channels/{channel_id}/join",...$})}getChannelJoinLink($){return($.client??this.client).get({url:"/channels/{channel_id}/join-link",...$})}leaveChannel($){return($.client??this.client).post({url:"/channels/{channel_id}/leave",...$})}removeParticipants($){return($.client??this.client).delete({url:"/channels/{channel_id}/participants",...$,headers:{"Content-Type":"application/json",...$.headers}})}getChannelParticipants($){return($.client??this.client).get({url:"/channels/{channel_id}/participants",...$})}addParticipants($){return($.client??this.client).post({url:"/channels/{channel_id}/participants",...$,headers:{"Content-Type":"application/json",...$.headers}})}setChannelPicture($){return($.client??this.client).put({url:"/channels/{channel_id}/profile_picture",...$,headers:{"Content-Type":"application/json",...$.headers}})}postChannelBotWebhook($){return($.client??this.client).post({url:"/channels/{channel_id}/webhook",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteCollabSurface($){return($.client??this.client).delete({url:"/collab_surfaces/{id}",...$})}getCollabSurface($){return($.client??this.client).get({url:"/collab_surfaces/{id}",...$})}ensureCollabSurface($){return($.client??this.client).put({url:"/collab_surfaces/{id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}createCollabSurfaceToken($){return($.client??this.client).post({url:"/collab_surfaces/{id}/token",...$})}getChannels($){return($?.client??this.client).get({url:"/comms/channels",...$})}createCrmCompany($){return($.client??this.client).post({url:"/crm/companies",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCompany($){return($.client??this.client).get({url:"/crm/companies/{company_id}",...$})}listCompanyContacts($){return($.client??this.client).get({url:"/crm/companies/{company_id}/contacts",...$})}createCrmContact($){return($.client??this.client).post({url:"/crm/companies/{company_id}/contacts",...$,headers:{"Content-Type":"application/json",...$.headers}})}setEmailSync($){return($.client??this.client).put({url:"/crm/companies/{company_id}/email-sync",...$,headers:{"Content-Type":"application/json",...$.headers}})}setCompanyHidden($){return($.client??this.client).put({url:"/crm/companies/{company_id}/hidden",...$,headers:{"Content-Type":"application/json",...$.headers}})}setCrmCompanyName($){return($.client??this.client).put({url:"/crm/companies/{company_id}/name",...$,headers:{"Content-Type":"application/json",...$.headers}})}searchContacts($){return($?.client??this.client).get({url:"/crm/contacts",...$})}getContactByEmail($){return($.client??this.client).get({url:"/crm/contacts/by-email",...$})}getContact($){return($.client??this.client).get({url:"/crm/contacts/{contact_id}",...$})}setContactHidden($){return($.client??this.client).put({url:"/crm/contacts/{contact_id}/hidden",...$,headers:{"Content-Type":"application/json",...$.headers}})}setCrmContactName($){return($.client??this.client).put({url:"/crm/contacts/{contact_id}/name",...$,headers:{"Content-Type":"application/json",...$.headers}})}listCrmPipelines($){return($?.client??this.client).get({url:"/crm/pipelines",...$})}createCrmPipeline($){return($.client??this.client).post({url:"/crm/pipelines",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCrmPipeline($){return($.client??this.client).get({url:"/crm/pipelines/{id}",...$})}renameCrmPipeline($){return($.client??this.client).put({url:"/crm/pipelines/{id}/name",...$,headers:{"Content-Type":"application/json",...$.headers}})}applyCrmPipelineOps($){return($.client??this.client).post({url:"/crm/pipelines/{id}/ops",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCrmPipelinePermissions($){return($.client??this.client).get({url:"/crm/pipelines/{id}/permissions",...$})}updateCrmPipelinePermissions($){return($.client??this.client).patch({url:"/crm/pipelines/{id}/permissions",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCrmPipelineRows($){return($.client??this.client).get({url:"/crm/pipelines/{id}/rows",...$})}queryCrmPipelineRows($){return($.client??this.client).post({url:"/crm/pipelines/{id}/rows",...$,headers:{"Content-Type":"application/json",...$.headers}})}shareCrmPipeline($){return($.client??this.client).put({url:"/crm/pipelines/{id}/sharing",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCrmPipelineTable($){return($.client??this.client).get({url:"/crm/pipelines/{id}/table",...$})}trashCrmPipeline($){return($.client??this.client).put({url:"/crm/pipelines/{id}/trash",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCrmTeamSettings($){return($?.client??this.client).get({url:"/crm/settings",...$})}putCrmTeamSettings($){return($.client??this.client).put({url:"/crm/settings",...$,headers:{"Content-Type":"application/json",...$.headers}})}resetCrmTeamStages($){return($?.client??this.client).delete({url:"/crm/stages",...$})}putCrmTeamStages($){return($.client??this.client).put({url:"/crm/stages",...$,headers:{"Content-Type":"application/json",...$.headers}})}listDatabases($){return($?.client??this.client).get({url:"/databases",...$})}createDatabase($){return($.client??this.client).post({url:"/databases",...$,headers:{"Content-Type":"application/json",...$.headers}})}saveDatabaseQuery($){return($.client??this.client).post({url:"/databases/queries",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDatabaseQuery($){return($.client??this.client).get({url:"/databases/queries/{query_id}",...$})}queryDatabases($){return($.client??this.client).post({url:"/databases/query",...$,headers:{"Content-Type":"application/json",...$.headers}})}ensureStarterHandler($){return($?.client??this.client).post({url:"/databases/starter",...$})}deliverDatabaseWebhook($){return($.client??this.client).post({url:"/databases/webhooks/{token}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDatabase($){return($.client??this.client).get({url:"/databases/{id}",...$})}shareDatabaseAwareness($){return($.client??this.client).put({url:"/databases/{id}/awareness",...$,headers:{"Content-Type":"application/json",...$.headers}})}undoDatabaseChange($){return($.client??this.client).post({url:"/databases/{id}/changes/{change}/undo",...$})}importDatabaseTable($){return($.client??this.client).post({url:"/databases/{id}/import",...$,headers:{"Content-Type":"application/json",...$.headers}})}applyDatabaseOps($){return($.client??this.client).post({url:"/databases/{id}/ops",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDatabasePermissions($){return($.client??this.client).get({url:"/databases/{id}/permissions",...$})}updateDatabasePermissions($){return($.client??this.client).patch({url:"/databases/{id}/permissions",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDatabaseTableChanges($){return($.client??this.client).get({url:"/databases/{id}/tables/{table_id}/changes",...$})}listDatabaseColumnCasts($){return($.client??this.client).get({url:"/databases/{id}/tables/{table_id}/columns/{column_id}/casts",...$})}convertDatabaseColumn($){return($.client??this.client).post({url:"/databases/{id}/tables/{table_id}/columns/{column_id}/conversion",...$,headers:{"Content-Type":"application/json",...$.headers}})}inferDatabaseColumnType($){return($.client??this.client).post({url:"/databases/{id}/tables/{table_id}/columns/{column_id}/infer-type",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDatabaseRowHistory($){return($.client??this.client).get({url:"/databases/{id}/tables/{table_id}/rows/{row_id}/history",...$})}getDatabaseViewPositions($){return($.client??this.client).get({url:"/databases/{id}/views/{view_id}/positions",...$})}listDatabaseWebhooks($){return($.client??this.client).get({url:"/databases/{id}/webhooks",...$})}createDatabaseWebhook($){return($.client??this.client).post({url:"/databases/{id}/webhooks",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteDatabaseWebhook($){return($.client??this.client).delete({url:"/databases/{id}/webhooks/{webhook_id}",...$})}transcribeDictation($){return($.client??this.client).post({bodySerializer:null,url:"/dictation/transcribe",...$,headers:{"Content-Type":"audio/webm",...$.headers}})}getUserDocumentsHandler($){return($.client??this.client).get({url:"/documents",...$})}createDocument($){return($.client??this.client).post({url:"/documents",...$,headers:{"Content-Type":"application/json",...$.headers}})}createCanvasHandler($){return($.client??this.client).post({url:"/documents/create_canvas",...$,headers:{"Content-Type":"application/json",...$.headers}})}createMarkdownHandler($){return($.client??this.client).post({url:"/documents/create_markdown",...$,headers:{"Content-Type":"application/json",...$.headers}})}createSkillHandler($){return($.client??this.client).post({url:"/documents/create_skill",...$,headers:{"Content-Type":"application/json",...$.headers}})}createSnippetHandler($){return($.client??this.client).post({url:"/documents/create_snippet",...$,headers:{"Content-Type":"application/json",...$.headers}})}createTaskHandler($){return($.client??this.client).post({url:"/documents/create_task",...$,headers:{"Content-Type":"application/json",...$.headers}})}getGithubPullRequestTasks($){return($.client??this.client).post({url:"/documents/github_prs/tasks",...$,headers:{"Content-Type":"application/json",...$.headers}})}initializeUserDocuments($){return($?.client??this.client).post({url:"/documents/initialize_user_documents",...$})}getDocumentListHandler($){return($?.client??this.client).get({url:"/documents/list",...$})}validateDocumentPermissionsToken($){return($.client??this.client).post({url:"/documents/permissions_token/validate",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDocumentPermissionsToken($){return($.client??this.client).post({url:"/documents/permissions_token/{document_id}",...$})}presaveDocumentHandler($){return($.client??this.client).put({url:"/documents/presave/{document_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getBatchPreviewHandler($){return($.client??this.client).post({url:"/documents/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDocumentByTeamSlug($){return($.client??this.client).get({url:"/documents/slug/{slug}",...$})}handler($){return($?.client??this.client).get({url:"/documents/starter_docs",...$})}getSystemSkillsHandler($){return($?.client??this.client).get({url:"/documents/system_skills",...$})}deleteDocument($){return($.client??this.client).delete({url:"/documents/{document_id}",...$})}getDocument($){return($.client??this.client).get({url:"/documents/{document_id}",...$})}editDocument($){return($.client??this.client).patch({url:"/documents/{document_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}saveDocumentHandler($){return($.client??this.client).put({url:"/documents/{document_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDocumentBranchName($){return($.client??this.client).get({url:"/documents/{document_id}/branch_name",...$})}copyDocument($){return($.client??this.client).post({url:"/documents/{document_id}/copy",...$,headers:{"Content-Type":"application/json",...$.headers}})}exportDocument($){return($.client??this.client).get({url:"/documents/{document_id}/export",...$})}getDocumentGithubPullRequests($){return($.client??this.client).get({url:"/documents/{document_id}/github_prs",...$})}getLocationHandler($){return($.client??this.client).get({url:"/documents/{document_id}/location",...$})}getDocumentLocationV3($){return($.client??this.client).get({url:"/documents/{document_id}/location_v3",...$})}permanentlyDeleteDocument($){return($.client??this.client).delete({url:"/documents/{document_id}/permanent",...$})}getDocumentProcessingResult($){return($.client??this.client).get({url:"/documents/{document_id}/processing",...$})}jobProcessingResultHandler($){return($.client??this.client).get({url:"/documents/{document_id}/processing/{job_id}",...$})}revertDeleteDocument($){return($.client??this.client).put({url:"/documents/{document_id}/revert_delete",...$})}getDocumentShortId($){return($.client??this.client).get({url:"/documents/{document_id}/short_id",...$})}simpleSave($){return($.client??this.client).put({url:"/documents/{document_id}/simple_save",...$})}getDocumentTeamShare($){return($.client??this.client).get({url:"/documents/{document_id}/team_share",...$})}setDocumentTeamShare($){return($.client??this.client).put({url:"/documents/{document_id}/team_share",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDocumentTextContent($){return($.client??this.client).get({url:"/documents/{document_id}/text-content",...$})}getDocumentViewsHandler($){return($.client??this.client).get({url:"/documents/{document_id}/views",...$})}getDocumentVersion($){return($.client??this.client).get({url:"/documents/{document_id}/{document_version_id}",...$})}accessRequestsState($){return($.client??this.client).get({url:"/entities/{entity_type}/{entity_id}/access-requests",...$})}accessRequestsCancel($){return($.client??this.client).delete({url:"/entities/{entity_type}/{entity_id}/access-requests/mine",...$})}accessRequestsSubmit($){return($.client??this.client).put({url:"/entities/{entity_type}/{entity_id}/access-requests/mine",...$,headers:{"Content-Type":"application/json",...$.headers}})}accessRequestsResolve($){return($.client??this.client).post({url:"/entities/{entity_type}/{entity_id}/access-requests/{request_id}/resolve",...$,headers:{"Content-Type":"application/json",...$.headers}})}accessRequestsDirect($){return($.client??this.client).get({url:"/entities/{entity_type}/{entity_id}/direct-access",...$})}accessRequestsRemoveDirect($){return($.client??this.client).delete({url:"/entities/{entity_type}/{entity_id}/direct-access/{user_id}",...$})}accessRequestsSetDirect($){return($.client??this.client).put({url:"/entities/{entity_type}/{entity_id}/direct-access/{user_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getEntityPermission($){return($.client??this.client).get({url:"/entity/{entity_type}/{entity_id}/permissions",...$})}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({...M1,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}})}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 V6({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:G,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:K,url:L,...Q}){let J,I=K??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=G??3000,B=0,T=Q.signal??new AbortController().signal;while(!0){if(T.aborted)break;B++;let C=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)C.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:C,signal:T},_=new Request(L,D);if($)_=await $(L,D);let N=await(Q.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{H.cancel()}catch{}};T.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await H.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
+`);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{T.removeEventListener("abort",g),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var $4=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},O4=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},j4=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},C0=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((K)=>encodeURIComponent(K))).join(O4(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let G=$4(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return yO({allowReserved:$,name:j,value:X})}).join(G);return x==="label"||x==="matrix"?G+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:G})=>{if(S instanceof Date)return G?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let K=[];Object.entries(S).forEach(([Q,J])=>{K=[...K,Q,$?J:encodeURIComponent(J)]});let L=K.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=j4(x),X=Object.entries(S).map(([K,L])=>yO({allowReserved:$,name:x==="deepObject"?`${j}[${K}]`:K,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var x4=/\{[^{}]+\}/g,S4=({path:$,url:O})=>{let j=O,x=O.match(x4);if(x)for(let S of x){let G=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))G=!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 K=$[Z];if(K===void 0||K===null)continue;if(Array.isArray(K)){j=j.replace(S,C0({explode:G,name:Z,style:X,value:K}));continue}if(typeof K==="object"){j=j.replace(S,F0({explode:G,name:Z,style:X,value:K,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${yO({name:Z,value:K})}`);continue}let L=encodeURIComponent(X==="label"?`.${K}`:K);j=j.replace(S,L)}return j},S6=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let G=S.startsWith("/")?S:`/${S}`,Z=($??"")+G;if(O)Z=S4({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function A1($){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 Z6=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var X6=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let G in x){let Z=x[G];if(Z===void 0||Z===null)continue;let X=$[G]||O;if(Array.isArray(Z)){let K=C0({allowReserved:X.allowReserved,explode:!0,name:G,style:"form",value:Z,...X.array});if(K)S.push(K)}else if(typeof Z==="object"){let K=F0({allowReserved:X.allowReserved,explode:!0,name:G,style:"deepObject",value:Z,...X.object});if(K)S.push(K)}else{let K=yO({allowReserved:X.allowReserved,name:G,value:Z});if(K)S.push(K)}}return S.join("&")}},G6=($)=>{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},Z4=($,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(Z4($,O.name))continue;let j=await Z6(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=($)=>S6({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:X6($.querySerializer),url:$.url}),F1=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=w0($.headers,O.headers),j},X4=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},w0=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?X4(j):Object.entries(j);for(let[S,G]of x)if(G===null)O.delete(S);else if(Array.isArray(G))for(let Z of G)O.append(S,Z);else if(G!==void 0)O.set(S,typeof G==="object"?JSON.stringify(G):G)}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 Y6=()=>({error:new E0,request:new E0,response:new E0}),G4=X6({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),K4={"Content-Type":"application/json"},Jj=($={})=>({...P1,headers:K4,parseAs:"auto",querySerializer:G4,...$});var Vj=($={})=>{let O=F1(Jj(),$),j=()=>({...O}),x=(Q)=>{return O=F1(O,Q),j()},S=Y6(),G=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:w0(O.headers,Q.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=C1(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await G(Q),T={redirect:"follow",...V,body:A1(V)};z=new Request(B,T);for(let N of S.request.fns)if(N)z=await N(z,V);let C=V.fetch;W=await C(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?G6(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await W[N]();break;case"json":{let U=await W.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let _=await W.text(),w;try{w=JSON.parse(_)}catch{}throw w??_}catch(V){let B=V;for(let T of S.error.fns)if(T)B=await T(B,W,z,Q);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(Q)=>(J)=>Z({...J,method:Q}),K=(Q)=>async(J)=>{let{opts:I,url:z}=await G(J);return x6({...I,body:I.body,method:Q,onRequest:async(W,V)=>{let B=new Request(W,V);for(let T of S.request.fns)if(T)B=await T(B,I);return B},serializedBody:A1(I),url:z})};return{buildUrl:(Q)=>C1({...O,...Q}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:K("CONNECT"),delete:K("DELETE"),get:K("GET"),head:K("HEAD"),options:K("OPTIONS"),patch:K("PATCH"),post:K("POST"),put:K("PUT"),trace:K("TRACE")},trace:X("TRACE")}};var Q6=Vj(Jj());class J6{client;constructor($){this.client=$?.client??Q6}}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 q0 extends J6{static __registry=new V6;constructor($){super($);q0.__registry.set(this,$?.key)}listAgents($){return($?.client??this.client).get({url:"/agents",...$})}createAgent($){return($.client??this.client).post({url:"/agents",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateAgent($){return($.client??this.client).put({url:"/agents/{agent_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteAnchor($){return($.client??this.client).delete({url:"/annotations/anchors",...$,headers:{"Content-Type":"application/json",...$.headers}})}editAnchor($){return($.client??this.client).patch({url:"/annotations/anchors",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDocumentAnchors($){return($.client??this.client).get({url:"/annotations/anchors/document/{document_id}",...$})}createAnchor($){return($.client??this.client).post({url:"/annotations/anchors/document/{document_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getSelfBot($){return($?.client??this.client).get({url:"/bots/me",...$})}getBotOwnerProfiles($){return($?.client??this.client).get({url:"/bots/profiles",...$})}listBotChannels($){return($.client??this.client).get({url:"/bots/{bot_id}/channels",...$})}removeBotFromChannelByBot($){return($.client??this.client).delete({url:"/bots/{bot_id}/channels/{channel_id}",...$})}listOccurrences($){return($.client??this.client).get({url:"/calendar-events",...$})}mentionPreviews($){return($.client??this.client).post({url:"/calendar-events/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}listTeamCalendar($){return($.client??this.client).get({url:"/calendar-events/team",...$})}listTeamOutOfOffice($){return($.client??this.client).get({url:"/calendar-events/team-out-of-office",...$})}eventIcs($){return($.client??this.client).get({url:"/calendar-events/{event_id}/ics",...$})}listJoinRequests($){return($.client??this.client).get({url:"/calendar-events/{event_id}/join-requests",...$})}requestToJoin($){return($.client??this.client).post({url:"/calendar-events/{event_id}/join-requests",...$})}getActiveCalls($){return($?.client??this.client).get({url:"/call/active",...$})}guestCallChatRead($){return($.client??this.client).get({url:"/call/guest-chat/{call_id}",...$})}guestCallChatPost($){return($.client??this.client).post({url:"/call/guest-chat/{call_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}meetingLookup($){return($.client??this.client).get({url:"/call/join/{token}",...$})}meetingGuestJoin($){return($.client??this.client).post({url:"/call/join/{token}",...$,headers:{"Content-Type":"application/json",...$.headers}})}meetingLeave($){return($.client??this.client).post({url:"/call/join/{token}/leave",...$})}meetingGuestParticipants($){return($.client??this.client).get({url:"/call/join/{token}/participants",...$})}meetingList($){return($?.client??this.client).get({url:"/call/meetings",...$})}meetingCreate($){return($.client??this.client).post({url:"/call/meetings",...$,headers:{"Content-Type":"application/json",...$.headers}})}meetingListActive($){return($?.client??this.client).get({url:"/call/meetings/active",...$})}meetingInvitePermissions($){return($.client??this.client).get({url:"/call/meetings/invite/{token}",...$})}meetingInvite($){return($.client??this.client).post({url:"/call/meetings/invite/{token}",...$,headers:{"Content-Type":"application/json",...$.headers}})}meetingInviteUsers($){return($.client??this.client).post({url:"/call/meetings/invite/{token}/users",...$,headers:{"Content-Type":"application/json",...$.headers}})}meetingJoin($){return($.client??this.client).post({url:"/call/meetings/join/{token}",...$})}meetingParticipants($){return($.client??this.client).get({url:"/call/meetings/join/{token}/participants",...$})}meetingPrepare($){return($?.client??this.client).post({url:"/call/meetings/prepare",...$})}meetingCancelPreparation($){return($.client??this.client).delete({url:"/call/meetings/prepare/{preparation_id}",...$})}meetingCancel($){return($.client??this.client).delete({url:"/call/meetings/{meeting_id}",...$})}meetingUpdate($){return($.client??this.client).patch({url:"/call/meetings/{meeting_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getBatchCallRecordPreview($){return($.client??this.client).post({url:"/call/record/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteCallRecord($){return($.client??this.client).delete({url:"/call/record/{call_id}",...$})}getCallRecord($){return($.client??this.client).get({url:"/call/record/{call_id}",...$})}editCallRecord($){return($.client??this.client).patch({url:"/call/record/{call_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}declineCall($){return($.client??this.client).post({url:"/call/record/{call_id}/decline",...$})}meetingShare($){return($.client??this.client).post({url:"/call/record/{call_id}/link",...$})}toggleShareWithTeam($){return($.client??this.client).post({url:"/call/record/{call_id}/share-with-team/toggle",...$})}editCallTranscript($){return($.client??this.client).patch({url:"/call/record/{call_id}/transcript",...$,headers:{"Content-Type":"application/json",...$.headers}})}getRingStatus($){return($.client??this.client).get({url:"/call/ring-status/{call_id}",...$})}declineRing($){return($.client??this.client).post({url:"/call/ring-status/{call_id}/decline",...$})}callWebhook($){return($?.client??this.client).post({url:"/call/webhook",...$})}leaveOrEndCall($){return($.client??this.client).delete({url:"/call/{channel_id}",...$})}getOrCreateCall($){return($.client??this.client).get({url:"/call/{channel_id}",...$})}checkActiveCall($){return($.client??this.client).get({url:"/call/{channel_id}/active",...$})}ingestTranscript($){return($.client??this.client).post({url:"/call/{room_name}/transcript",...$,headers:{"Content-Type":"application/json",...$.headers}})}listChannelLabels($){return($?.client??this.client).get({url:"/channel-labels",...$})}createChannelLabel($){return($.client??this.client).post({url:"/channel-labels",...$,headers:{"Content-Type":"application/json",...$.headers}})}setChannelLabel($){return($.client??this.client).put({url:"/channel-labels/channels/{channel_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}previewSmartTag($){return($.client??this.client).post({url:"/channel-labels/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteChannelLabel($){return($.client??this.client).delete({url:"/channel-labels/{label_id}",...$})}renameChannelLabel($){return($.client??this.client).patch({url:"/channel-labels/{label_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}createChannel($){return($.client??this.client).post({url:"/channels",...$,headers:{"Content-Type":"application/json",...$.headers}})}getActivity($){return($?.client??this.client).get({url:"/channels/activity",...$})}postActivity($){return($.client??this.client).post({url:"/channels/activity",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAttachmentReferences($){return($.client??this.client).get({url:"/channels/attachments/{entity_type}/{entity_id}/references",...$})}getOrCreateDm($){return($.client??this.client).post({url:"/channels/get_or_create_dm",...$,headers:{"Content-Type":"application/json",...$.headers}})}getOrCreatePrivate($){return($.client??this.client).post({url:"/channels/get_or_create_private",...$,headers:{"Content-Type":"application/json",...$.headers}})}joinChannelByCode($){return($.client??this.client).post({url:"/channels/join/{join_code}",...$})}createEntityMention($){return($.client??this.client).post({url:"/channels/mentions",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteEntityMention($){return($.client??this.client).delete({url:"/channels/mentions/{mention_id}",...$})}getBatchChannelPreview($){return($.client??this.client).post({url:"/channels/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteChannel($){return($.client??this.client).delete({url:"/channels/{channel_id}",...$})}getChannel($){return($.client??this.client).get({url:"/channels/{channel_id}",...$})}patchChannel($){return($.client??this.client).patch({url:"/channels/{channel_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getChannelAttachments($){return($.client??this.client).get({url:"/channels/{channel_id}/attachments",...$})}createChannelScopedBot($){return($.client??this.client).post({url:"/channels/{channel_id}/bots/scoped",...$,headers:{"Content-Type":"application/json",...$.headers}})}joinChannel($){return($.client??this.client).post({url:"/channels/{channel_id}/join",...$})}getChannelJoinLink($){return($.client??this.client).get({url:"/channels/{channel_id}/join-link",...$})}leaveChannel($){return($.client??this.client).post({url:"/channels/{channel_id}/leave",...$})}removeParticipants($){return($.client??this.client).delete({url:"/channels/{channel_id}/participants",...$,headers:{"Content-Type":"application/json",...$.headers}})}getChannelParticipants($){return($.client??this.client).get({url:"/channels/{channel_id}/participants",...$})}addParticipants($){return($.client??this.client).post({url:"/channels/{channel_id}/participants",...$,headers:{"Content-Type":"application/json",...$.headers}})}setChannelPicture($){return($.client??this.client).put({url:"/channels/{channel_id}/profile_picture",...$,headers:{"Content-Type":"application/json",...$.headers}})}postChannelBotWebhook($){return($.client??this.client).post({url:"/channels/{channel_id}/webhook",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteCollabSurface($){return($.client??this.client).delete({url:"/collab_surfaces/{id}",...$})}getCollabSurface($){return($.client??this.client).get({url:"/collab_surfaces/{id}",...$})}ensureCollabSurface($){return($.client??this.client).put({url:"/collab_surfaces/{id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}createCollabSurfaceToken($){return($.client??this.client).post({url:"/collab_surfaces/{id}/token",...$})}getChannels($){return($?.client??this.client).get({url:"/comms/channels",...$})}createCrmCompany($){return($.client??this.client).post({url:"/crm/companies",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCompany($){return($.client??this.client).get({url:"/crm/companies/{company_id}",...$})}listCompanyContacts($){return($.client??this.client).get({url:"/crm/companies/{company_id}/contacts",...$})}createCrmContact($){return($.client??this.client).post({url:"/crm/companies/{company_id}/contacts",...$,headers:{"Content-Type":"application/json",...$.headers}})}setEmailSync($){return($.client??this.client).put({url:"/crm/companies/{company_id}/email-sync",...$,headers:{"Content-Type":"application/json",...$.headers}})}setCompanyHidden($){return($.client??this.client).put({url:"/crm/companies/{company_id}/hidden",...$,headers:{"Content-Type":"application/json",...$.headers}})}setCrmCompanyName($){return($.client??this.client).put({url:"/crm/companies/{company_id}/name",...$,headers:{"Content-Type":"application/json",...$.headers}})}searchContacts($){return($?.client??this.client).get({url:"/crm/contacts",...$})}getContactByEmail($){return($.client??this.client).get({url:"/crm/contacts/by-email",...$})}getContact($){return($.client??this.client).get({url:"/crm/contacts/{contact_id}",...$})}setContactHidden($){return($.client??this.client).put({url:"/crm/contacts/{contact_id}/hidden",...$,headers:{"Content-Type":"application/json",...$.headers}})}setCrmContactName($){return($.client??this.client).put({url:"/crm/contacts/{contact_id}/name",...$,headers:{"Content-Type":"application/json",...$.headers}})}listCrmPipelines($){return($?.client??this.client).get({url:"/crm/pipelines",...$})}createCrmPipeline($){return($.client??this.client).post({url:"/crm/pipelines",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCrmPipeline($){return($.client??this.client).get({url:"/crm/pipelines/{id}",...$})}renameCrmPipeline($){return($.client??this.client).put({url:"/crm/pipelines/{id}/name",...$,headers:{"Content-Type":"application/json",...$.headers}})}applyCrmPipelineOps($){return($.client??this.client).post({url:"/crm/pipelines/{id}/ops",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCrmPipelinePermissions($){return($.client??this.client).get({url:"/crm/pipelines/{id}/permissions",...$})}updateCrmPipelinePermissions($){return($.client??this.client).patch({url:"/crm/pipelines/{id}/permissions",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCrmPipelineRows($){return($.client??this.client).get({url:"/crm/pipelines/{id}/rows",...$})}queryCrmPipelineRows($){return($.client??this.client).post({url:"/crm/pipelines/{id}/rows",...$,headers:{"Content-Type":"application/json",...$.headers}})}shareCrmPipeline($){return($.client??this.client).put({url:"/crm/pipelines/{id}/sharing",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCrmPipelineTable($){return($.client??this.client).get({url:"/crm/pipelines/{id}/table",...$})}trashCrmPipeline($){return($.client??this.client).put({url:"/crm/pipelines/{id}/trash",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCrmTeamSettings($){return($?.client??this.client).get({url:"/crm/settings",...$})}putCrmTeamSettings($){return($.client??this.client).put({url:"/crm/settings",...$,headers:{"Content-Type":"application/json",...$.headers}})}resetCrmTeamStages($){return($?.client??this.client).delete({url:"/crm/stages",...$})}putCrmTeamStages($){return($.client??this.client).put({url:"/crm/stages",...$,headers:{"Content-Type":"application/json",...$.headers}})}listDatabases($){return($?.client??this.client).get({url:"/databases",...$})}createDatabase($){return($.client??this.client).post({url:"/databases",...$,headers:{"Content-Type":"application/json",...$.headers}})}saveDatabaseQuery($){return($.client??this.client).post({url:"/databases/queries",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDatabaseQuery($){return($.client??this.client).get({url:"/databases/queries/{query_id}",...$})}queryDatabases($){return($.client??this.client).post({url:"/databases/query",...$,headers:{"Content-Type":"application/json",...$.headers}})}ensureStarterHandler($){return($?.client??this.client).post({url:"/databases/starter",...$})}deliverDatabaseWebhook($){return($.client??this.client).post({url:"/databases/webhooks/{token}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDatabase($){return($.client??this.client).get({url:"/databases/{id}",...$})}shareDatabaseAwareness($){return($.client??this.client).put({url:"/databases/{id}/awareness",...$,headers:{"Content-Type":"application/json",...$.headers}})}undoDatabaseChange($){return($.client??this.client).post({url:"/databases/{id}/changes/{change}/undo",...$})}importDatabaseTable($){return($.client??this.client).post({url:"/databases/{id}/import",...$,headers:{"Content-Type":"application/json",...$.headers}})}applyDatabaseOps($){return($.client??this.client).post({url:"/databases/{id}/ops",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDatabasePermissions($){return($.client??this.client).get({url:"/databases/{id}/permissions",...$})}updateDatabasePermissions($){return($.client??this.client).patch({url:"/databases/{id}/permissions",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDatabaseTableChanges($){return($.client??this.client).get({url:"/databases/{id}/tables/{table_id}/changes",...$})}listDatabaseColumnCasts($){return($.client??this.client).get({url:"/databases/{id}/tables/{table_id}/columns/{column_id}/casts",...$})}convertDatabaseColumn($){return($.client??this.client).post({url:"/databases/{id}/tables/{table_id}/columns/{column_id}/conversion",...$,headers:{"Content-Type":"application/json",...$.headers}})}inferDatabaseColumnType($){return($.client??this.client).post({url:"/databases/{id}/tables/{table_id}/columns/{column_id}/infer-type",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDatabaseRowHistory($){return($.client??this.client).get({url:"/databases/{id}/tables/{table_id}/rows/{row_id}/history",...$})}getDatabaseViewPositions($){return($.client??this.client).get({url:"/databases/{id}/views/{view_id}/positions",...$})}listDatabaseWebhooks($){return($.client??this.client).get({url:"/databases/{id}/webhooks",...$})}createDatabaseWebhook($){return($.client??this.client).post({url:"/databases/{id}/webhooks",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteDatabaseWebhook($){return($.client??this.client).delete({url:"/databases/{id}/webhooks/{webhook_id}",...$})}transcribeDictation($){return($.client??this.client).post({bodySerializer:null,url:"/dictation/transcribe",...$,headers:{"Content-Type":"audio/webm",...$.headers}})}getUserDocumentsHandler($){return($.client??this.client).get({url:"/documents",...$})}createDocument($){return($.client??this.client).post({url:"/documents",...$,headers:{"Content-Type":"application/json",...$.headers}})}createCanvasHandler($){return($.client??this.client).post({url:"/documents/create_canvas",...$,headers:{"Content-Type":"application/json",...$.headers}})}createMarkdownHandler($){return($.client??this.client).post({url:"/documents/create_markdown",...$,headers:{"Content-Type":"application/json",...$.headers}})}createSkillHandler($){return($.client??this.client).post({url:"/documents/create_skill",...$,headers:{"Content-Type":"application/json",...$.headers}})}createSnippetHandler($){return($.client??this.client).post({url:"/documents/create_snippet",...$,headers:{"Content-Type":"application/json",...$.headers}})}createTaskHandler($){return($.client??this.client).post({url:"/documents/create_task",...$,headers:{"Content-Type":"application/json",...$.headers}})}getGithubPullRequestTasks($){return($.client??this.client).post({url:"/documents/github_prs/tasks",...$,headers:{"Content-Type":"application/json",...$.headers}})}initializeUserDocuments($){return($?.client??this.client).post({url:"/documents/initialize_user_documents",...$})}getDocumentListHandler($){return($?.client??this.client).get({url:"/documents/list",...$})}validateDocumentPermissionsToken($){return($.client??this.client).post({url:"/documents/permissions_token/validate",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDocumentPermissionsToken($){return($.client??this.client).post({url:"/documents/permissions_token/{document_id}",...$})}presaveDocumentHandler($){return($.client??this.client).put({url:"/documents/presave/{document_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getBatchPreviewHandler($){return($.client??this.client).post({url:"/documents/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDocumentByTeamSlug($){return($.client??this.client).get({url:"/documents/slug/{slug}",...$})}handler($){return($?.client??this.client).get({url:"/documents/starter_docs",...$})}getSystemSkillsHandler($){return($?.client??this.client).get({url:"/documents/system_skills",...$})}deleteDocument($){return($.client??this.client).delete({url:"/documents/{document_id}",...$})}getDocument($){return($.client??this.client).get({url:"/documents/{document_id}",...$})}editDocument($){return($.client??this.client).patch({url:"/documents/{document_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}saveDocumentHandler($){return($.client??this.client).put({url:"/documents/{document_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDocumentBranchName($){return($.client??this.client).get({url:"/documents/{document_id}/branch_name",...$})}copyDocument($){return($.client??this.client).post({url:"/documents/{document_id}/copy",...$,headers:{"Content-Type":"application/json",...$.headers}})}exportDocument($){return($.client??this.client).get({url:"/documents/{document_id}/export",...$})}getDocumentGithubPullRequests($){return($.client??this.client).get({url:"/documents/{document_id}/github_prs",...$})}getLocationHandler($){return($.client??this.client).get({url:"/documents/{document_id}/location",...$})}getDocumentLocationV3($){return($.client??this.client).get({url:"/documents/{document_id}/location_v3",...$})}permanentlyDeleteDocument($){return($.client??this.client).delete({url:"/documents/{document_id}/permanent",...$})}getDocumentProcessingResult($){return($.client??this.client).get({url:"/documents/{document_id}/processing",...$})}jobProcessingResultHandler($){return($.client??this.client).get({url:"/documents/{document_id}/processing/{job_id}",...$})}revertDeleteDocument($){return($.client??this.client).put({url:"/documents/{document_id}/revert_delete",...$})}getDocumentShortId($){return($.client??this.client).get({url:"/documents/{document_id}/short_id",...$})}simpleSave($){return($.client??this.client).put({url:"/documents/{document_id}/simple_save",...$})}getDocumentTeamShare($){return($.client??this.client).get({url:"/documents/{document_id}/team_share",...$})}setDocumentTeamShare($){return($.client??this.client).put({url:"/documents/{document_id}/team_share",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDocumentTextContent($){return($.client??this.client).get({url:"/documents/{document_id}/text-content",...$})}getDocumentViewsHandler($){return($.client??this.client).get({url:"/documents/{document_id}/views",...$})}getDocumentVersion($){return($.client??this.client).get({url:"/documents/{document_id}/{document_version_id}",...$})}accessRequestsState($){return($.client??this.client).get({url:"/entities/{entity_type}/{entity_id}/access-requests",...$})}accessRequestsCancel($){return($.client??this.client).delete({url:"/entities/{entity_type}/{entity_id}/access-requests/mine",...$})}accessRequestsSubmit($){return($.client??this.client).put({url:"/entities/{entity_type}/{entity_id}/access-requests/mine",...$,headers:{"Content-Type":"application/json",...$.headers}})}accessRequestsResolve($){return($.client??this.client).post({url:"/entities/{entity_type}/{entity_id}/access-requests/{request_id}/resolve",...$,headers:{"Content-Type":"application/json",...$.headers}})}accessRequestsDirect($){return($.client??this.client).get({url:"/entities/{entity_type}/{entity_id}/direct-access",...$})}accessRequestsRemoveDirect($){return($.client??this.client).delete({url:"/entities/{entity_type}/{entity_id}/direct-access/{user_id}",...$})}accessRequestsSetDirect($){return($.client??this.client).put({url:"/entities/{entity_type}/{entity_id}/direct-access/{user_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getEntityPermission($){return($.client??this.client).get({url:"/entity/{entity_type}/{entity_id}/permissions",...$})}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({...M1,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}})}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 W6({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:G,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:K,url:L,...Q}){let J,I=K??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=G??3000,B=0,T=Q.signal??new AbortController().signal;while(!0){if(T.aborted)break;B++;let C=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)C.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:C,signal:T},_=new Request(L,D);if($)_=await $(L,D);let N=await(Q.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{H.cancel()}catch{}};T.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await H.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
`);let 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{T.removeEventListener("abort",g),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var K4=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},Y4=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},Q4=($)=>{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((K)=>encodeURIComponent(K))).join(Y4(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let G=K4(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return vO({allowReserved:$,name:j,value:X})}).join(G);return x==="label"||x==="matrix"?G+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)}`},f0=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:G})=>{if(S instanceof Date)return G?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let K=[];Object.entries(S).forEach(([Q,J])=>{K=[...K,Q,$?J:encodeURIComponent(J)]});let L=K.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=Q4(x),X=Object.entries(S).map(([K,L])=>vO({allowReserved:$,name:x==="deepObject"?`${j}[${K}]`:K,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var J4=/\{[^{}]+\}/g,V4=({path:$,url:O})=>{let j=O,x=O.match(J4);if(x)for(let S of x){let G=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))G=!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 K=$[Z];if(K===void 0||K===null)continue;if(Array.isArray(K)){j=j.replace(S,q0({explode:G,name:Z,style:X,value:K}));continue}if(typeof K==="object"){j=j.replace(S,f0({explode:G,name:Z,style:X,value:K,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${vO({name:Z,value:K})}`);continue}let L=encodeURIComponent(X==="label"?`.${K}`:K);j=j.replace(S,L)}return j},W6=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let G=S.startsWith("/")?S:`/${S}`,Z=($??"")+G;if(O)Z=V4({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 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 G in x){let Z=x[G];if(Z===void 0||Z===null)continue;let X=$[G]||O;if(Array.isArray(Z)){let K=q0({allowReserved:X.allowReserved,explode:!0,name:G,style:"form",value:Z,...X.array});if(K)S.push(K)}else if(typeof Z==="object"){let K=f0({allowReserved:X.allowReserved,explode:!0,name:G,style:"deepObject",value:Z,...X.object});if(K)S.push(K)}else{let K=vO({allowReserved:X.allowReserved,name:G,value:Z});if(K)S.push(K)}}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},W4=($,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(W4($,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 w1=($)=>W6({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:N6($.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=k0($.headers,O.headers),j},B4=($)=>{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?B4(j):Object.entries(j);for(let[S,G]of x)if(G===null)O.delete(S);else if(Array.isArray(G))for(let Z of G)O.append(S,Z);else if(G!==void 0)O.set(S,typeof G==="object"?JSON.stringify(G):G)}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 I6=()=>({error:new b0,request:new b0,response:new b0}),L4=N6({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),N4={"Content-Type":"application/json"},Wj=($={})=>({...L6,headers:N4,parseAs:"auto",querySerializer:L4,...$});var f1=($={})=>{let O=q1(Wj(),$),j=()=>({...O}),x=(Q)=>{return O=q1(O,Q),j()},S=I6(),G=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:k0(O.headers,Q.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=w1(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await G(Q),T={redirect:"follow",...V,body:E1(V)};z=new Request(B,T);for(let N of S.request.fns)if(N)z=await N(z,V);let C=V.fetch;W=await C(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?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 H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await W[N]();break;case"json":{let U=await W.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let _=await W.text(),w;try{w=JSON.parse(_)}catch{}throw w??_}catch(V){let B=V;for(let T of S.error.fns)if(T)B=await T(B,W,z,Q);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(Q)=>(J)=>Z({...J,method:Q}),K=(Q)=>async(J)=>{let{opts:I,url:z}=await G(J);return V6({...I,body:I.body,method:Q,onRequest:async(W,V)=>{let B=new Request(W,V);for(let T of S.request.fns)if(T)B=await T(B,I);return B},serializedBody:E1(I),url:z})};return{buildUrl:(Q)=>w1({...O,...Q}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:K("CONNECT"),delete:K("DELETE"),get:K("GET"),head:K("HEAD"),options:K("OPTIONS"),patch:K("PATCH"),post:K("POST"),put:K("PUT"),trace:K("TRACE")},trace:X("TRACE")}};var T6=f1(Wj());class H6{client;constructor($){this.client=$?.client??T6}}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 g0 extends H6{static __registry=new R6;constructor($){super($);g0.__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 D6={dev:"https://dev.macro.com",prod:"https://macro.com",local:"http://localhost:3000"},b1={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 U4($,O){let j=O?.channel_id;return O&&j?{channel:b.byId($,j),thread:new h$($,j,O.thread_id)}:{channel:void 0,thread:void 0}}function E$($,O){return{session:l.byId($,O.session_id),owner:P.byId($,O.owner_id),...U4($,O.origin)}}function hO($,O,j){let x=O.origin?.channel_id;return x&&j?e.byId($,x,j):void 0}function mO($,O){return O?P.byId($,O):void 0}function _6($,O){return k(O).with({event_type:"agent_session.opened"},({metadata:j})=>({event_type:"agent_session.opened",metadata:j,...E$($,j.identity)})).with({event_type:"agent_session.turn_started"},({metadata:j})=>({event_type:"agent_session.turn_started",metadata:j,...E$($,j.identity),actor:mO($,j.actor),announcement:hO($,j.identity,j.announcement_message_id)})).with({event_type:"agent_session.turn_ended"},({metadata:j})=>({event_type:"agent_session.turn_ended",metadata:j,...E$($,j.identity),actor:mO($,j.actor),announcement:hO($,j.identity,j.announcement_message_id)})).with({event_type:"agent_session.command_rejected"},({metadata:j})=>({event_type:"agent_session.command_rejected",metadata:j,...E$($,j.identity),actor:mO($,j.actor),announcement:hO($,j.identity,j.announcement_message_id)})).with({event_type:"agent_session.settled"},({metadata:j})=>({event_type:"agent_session.settled",metadata:j,...E$($,j.identity),actor:mO($,j.last_turn?.actor),announcement:hO($,j.identity,j.last_turn?.announcement_message_id)})).with({event_type:"agent_session.waiting_for_input"},({metadata:j})=>({event_type:"agent_session.waiting_for_input",metadata:j,...E$($,j.identity),announcement:hO($,j.identity,j.announcement_message_id)})).with({event_type:"agent_session.input_received"},({metadata:j})=>({event_type:"agent_session.input_received",metadata:j,...E$($,j.identity)})).with({event_type:"agent_session.mentioned"},({metadata:j})=>({event_type:"agent_session.mentioned",metadata:j,...E$($,j.identity),mentionedBy:mO($,j.mentioned_by),mentioned:j.mentioned.map((x)=>P.byId($,x))})).with({event_type:"agent_session.stopped"},({metadata:j})=>({event_type:"agent_session.stopped",metadata:j,...E$($,j.identity),actor:mO($,j.turn_in_flight?.actor),announcement:hO($,j.identity,j.turn_in_flight?.announcement_message_id)})).with({event_type:"agent_session.renamed"},({metadata:j})=>({event_type:"agent_session.renamed",metadata:j,...E$($,j.identity)})).with({event_type:"agent_session.deleted"},({metadata:j})=>({event_type:"agent_session.deleted",metadata:j,...E$($,j.identity)})).exhaustive((j)=>{console.warn("macro sdk: unknown agent session event",j);return})}var M6="macro|";function P$($,O){return O.startsWith(M6)&&O.length>M6.length?P.byId($,O.toLowerCase()):void 0}function P6($,O){return k(O).with({event_type:"channel.created"},({metadata:j})=>({event_type:"channel.created",metadata:j,channel:b.byId($,j.channel_id),actor:P$($,j.actor),participants:j.participant_user_ids.map((x)=>P.byId($,x))})).with({event_type:"channel.updated"},({metadata:j})=>({event_type:"channel.updated",metadata:j,channel:b.byId($,j.channel_id),actor:P$($,j.actor)})).with({event_type:"channel.deleted"},({metadata:j})=>({event_type:"channel.deleted",metadata:j,channel:b.byId($,j.channel_id),actor:P$($,j.actor)})).with({event_type:"channel.picture_changed"},({metadata:j})=>({event_type:"channel.picture_changed",metadata:j,channel:b.byId($,j.channel_id),actor:P$($,j.actor)})).with({event_type:"channel.participant_added"},({metadata:j})=>({event_type:"channel.participant_added",metadata:j,channel:b.byId($,j.channel_id),addedBy:P$($,j.added_by),addedUsers:j.added_user_ids.map((x)=>P.byId($,x))})).with({event_type:"channel.participant_removed"},({metadata:j})=>({event_type:"channel.participant_removed",metadata:j,channel:b.byId($,j.channel_id),removedBy:P.byId($,j.removed_by),removedUsers:j.removed_user_ids.map((x)=>P.byId($,x))})).exhaustive((j)=>{console.warn("macro sdk: unknown channel event",j);return})}function A6($,O){return k(O).with({event_type:"document.created"},({metadata:j})=>({event_type:"document.created",metadata:j,document:q.byId($,j.document_id),owner:P.byId($,j.owner),project:j.project_id?n.byId($,j.project_id):void 0})).with({event_type:"document.updated"},({metadata:j})=>({event_type:"document.updated",metadata:j,document:q.byId($,j.document_id),owner:P.byId($,j.owner),actor:j.actor_user_id?P.byId($,j.actor_user_id):void 0,project:j.project_id?n.byId($,j.project_id):void 0,previousProject:j.previous_project_id?n.byId($,j.previous_project_id):void 0})).with({event_type:"document.deleted"},({metadata:j})=>({event_type:"document.deleted",metadata:j,document:q.byId($,j.document_id),actor:j.actor_user_id?P.byId($,j.actor_user_id):void 0,project:j.project_id?n.byId($,j.project_id):void 0})).with({event_type:"document.content_uploaded"},({metadata:j})=>({event_type:"document.content_uploaded",metadata:j,document:q.byId($,j.document_id),owner:P.byId($,j.owner)})).with({event_type:"document.sync_content_updated"},({metadata:j})=>({event_type:"document.sync_content_updated",metadata:j,document:q.byId($,j.document_id)})).with({event_type:"document.purged"},({metadata:j})=>({event_type:"document.purged",metadata:j,document:q.byId($,j.document_id)})).with({event_type:"document.copied"},({metadata:j})=>({event_type:"document.copied",metadata:j,document:q.byId($,j.document_id),sourceDocument:q.byId($,j.source_document_id),owner:P.byId($,j.owner),project:j.project_id?n.byId($,j.project_id):void 0})).with({event_type:"document.interaction"},({metadata:j})=>({event_type:"document.interaction",metadata:j,document:q.byId($,j.document_id)})).exhaustive((j)=>{console.warn("macro sdk: unknown document event",j);return})}function uO($,O,j=[]){let x=O.parent;if(x.type==="call")return{type:"call",call:Q$.byId($,x.id),message:c$.byId($,x.id,O.message_id),threadId:x.id};if(x.type==="channel")return{type:"channel",channel:b.byId($,x.id),message:e.byId($,x.id,O.message_id,j),thread:O.thread_id?new h$($,x.id,O.thread_id):void 0};return{type:"document",document:q.byId($,x.id),comment:u$.byId($,x.id,O.message_id),threadId:O.root_id}}function C6($,O){return k(O).with({event_type:"message.posted"},({metadata:j})=>({event_type:"message.posted",metadata:j,target:uO($,j,j.mentions),sender:P$($,j.sender)})).with({event_type:"message.mentioned"},({metadata:j})=>({event_type:"message.mentioned",metadata:j,target:uO($,j),sender:P$($,j.sender)})).with({event_type:"message.patched"},({metadata:j})=>({event_type:"message.patched",metadata:j,target:uO($,j),actor:P$($,j.actor)})).with({event_type:"message.deleted"},({metadata:j})=>({event_type:"message.deleted",metadata:j,target:uO($,j),actor:P$($,j.actor)})).with({event_type:"message.attachment_created"},({metadata:j})=>({event_type:"message.attachment_created",metadata:j,target:uO($,j),actor:P$($,j.actor)})).with({event_type:"message.attachment_removed"},({metadata:j})=>({event_type:"message.attachment_removed",metadata:j,target:uO($,j),actor:P$($,j.actor)})).exhaustive((j)=>{console.warn("macro sdk: unknown message event",j);return})}async function F6($){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 z4="webhook.validation.test";function I4($,O){return k(O).with({event_type:Z$.string.startsWith("document.")},(j)=>A6($,j)).with({event_type:Z$.string.startsWith("channel.")},(j)=>P6($,j)).with({event_type:Z$.string.startsWith("message.")},(j)=>C6($,j)).with({event_type:Z$.string.startsWith("agent_session.")},(j)=>_6($,j)).otherwise(()=>{return})}class k1{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((G)=>G.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 G of x)await this.dispatchEvent(G)}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 F6({secret:this.secret,timestamp:O.timestamp??"",rawBody:$,signature:O.signature??""}))throw new f("invalid webhook signature");if(O.event===z4)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=I4(this.client,j);if(!S)return;await Promise.all([...x].map((G)=>G(S)))}}function E6(){return}var T4=0,g1;function H4($){g1=$}function z$($,O,j){if(!j&&!g1)return $;let x=(S)=>{for(let G of[g1,j])try{Promise.resolve(G?.(S)).catch(()=>{})}catch{}};return new Proxy($,{get(S,G,Z){let X=Reflect.get(S,G,Z);if(typeof G!=="string"||typeof X!=="function")return X;return async(...K)=>{let L={id:++T4,service:O,operation:G};x({...L,status:"started"});try{let Q=await Reflect.apply(X,S,K),J=Q!==null&&typeof Q==="object"&&"error"in Q&&Q.error!=null;return x({...L,status:J?"failed":"completed"}),Q}catch(Q){throw x({...L,status:"failed"}),Q}}}})}var q6="x-macro-user-api-key",R4="mak_",y1="mbot_";function D4($){return k($).with(Z$.string.startsWith(y1),()=>{throw Error("bot token passed as a user credential. Use auth: { type: 'bot', token } or MACRO_BOT_TOKEN.")}).with(Z$.string.startsWith(R4),(O)=>[q6,O]).otherwise((O)=>["Authorization",`Bearer ${O}`])}async function w6($){return typeof $==="function"?await $():$}async function _4($,O,j){return k($).with({type:"bot"},async(x)=>{let S=await w6(x.token);if(!S.startsWith(y1))throw Error("user API key passed as a bot token. Use auth: { type: 'user', apiKey } or MACRO_API_KEY.");let G=[["x-macro-bot-token",S]];if(!j?.hasBotScope)G.push(["x-macro-bot-scope",x.scope??(O?"user":"team")]);if(O)G.push(["x-macro-bot-for-macro-user-id",O]);return G}).with({type:"user",apiKey:Z$.string},({apiKey:x})=>{if(x.startsWith(y1))throw Error("bot token passed as a user credential. Use auth: { type: 'bot', token } or MACRO_BOT_TOKEN.");return[[q6,x]]}).with({type:"user"},async({token:x})=>{return[D4(await w6(x))]}).exhaustive()}class v1{scheduledAction;unfurl;agentHarness;auth;calendar;cognition;contacts;email;notification;properties;search;storage;webAppUrl;wsVerify;events;authConfig;hosts;localPortmap;requestedAs;selfBotRecord;selfPrincipal;constructor($){let O=M4($),j=O==="local"?E6():void 0,x={...b1[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??D6[O],this.authConfig=P4($),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=z$(new H0({client:this.makeClient(x["scheduled-action"])}),"scheduled-action",$.onRequest),this.unfurl=z$(new g0({client:this.makeClient(x.unfurl)}),"unfurl",$.onRequest),this.agentHarness=z$(new kj({client:this.makeClient(x["agent-harness"])}),"agent-harness",$.onRequest),this.auth=z$(new mj({client:this.makeClient(x.auth)}),"auth",$.onRequest),this.calendar=z$(new rj({client:this.makeClient(x.calendar)}),"calendar",$.onRequest),this.cognition=z$(new sj({client:this.makeClient(x.cognition)}),"cognition",$.onRequest),this.contacts=z$(new O0({client:this.makeClient(x.contacts)}),"contacts",$.onRequest),this.email=z$(new X0({client:this.makeClient(x.email)}),"email",$.onRequest),this.notification=z$(new J0({client:this.makeClient(x.notification)}),"notification",$.onRequest),this.properties=z$(new N0({client:this.makeClient(x.properties)}),"properties",$.onRequest),this.search=z$(new P0({client:this.makeClient(x.search)}),"search",$.onRequest),this.storage=z$(new w0({client:this.makeClient(x.storage)}),"storage",$.onRequest);let G=typeof process<"u"?{}.MACRO_WEBHOOK_SECRET:void 0,Z=$.webhookSecret??G;this.events=new k1(this,Z)}hasActingUser(){return this.authConfig.type==="user"||this.requestedAs!==void 0}selfBot(){return this.selfBotRecord??=new rO(this).me().catch(($)=>{throw this.selfBotRecord=void 0,$}),this.selfBotRecord}myPrincipalId(){return this.selfPrincipal??=(this.authConfig.type==="bot"?this.selfBot().then(($)=>`bot|${$.id}`):P.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 _4(this.authConfig,this.requestedAs,{hasBotScope:j.headers.has("x-macro-bot-scope")});for(let[S,G]of x)j.headers.set(S,G);return j}),O}}function M4($){if($.env)return $.env;let O=typeof process<"u"?{}.MACRO_ENV:void 0;if(!O)return"prod";if(!(O in b1))throw Error(`invalid MACRO_ENV "${O}" — expected local, dev, or prod`);return O}function P4($){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 h1{id;constructor($){this.id=$}static byId($){return new h1($)}toJSON(){return{id:this.id}}}class f6{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;notifications;pins;projects;properties;tasks;teams;users;webhooks;workspace;events;webAppUrl;_client;opts;constructor($){this.opts=$;let O=new v1($);this._client=O,this.routines=new Cx(O),this.unfurls=new wx(O),this.agents=new u0(O),this.initiatives=new Ix(O),this.apiKeys=new d0(O),this.harnesses=new zx(O),this.meetings=new Tx(O),this.githubPullRequests=new Ux(O),this.entityMentions=new Qx(O),this.agentSessions=new m0(O),this.ai=new c0(O),this.bots=new rO(O),this.calendar=new l0(O),this.calls=new r0(O),this.channels=new a0(O),this.externalChats=new Vx(O),this.whatsapp=new bx(O),this.chats=new i0(O),this.crm=new s0(O),this.databases=new Xx(O),this.documents=new Gx(O),this.email=new Yx(O),this.favorites=new Wx(O),this.foreignEntities=new Bx(O),this.forms=new Lx(O),this.notifications=new Hx(O),this.pins=new Rx(O),this.projects=new Dx(O),this.properties=new _x(O),this.tasks=new Fx(O),this.teams=new Ex(O),this.users=new qx(O),this.webhooks=new fx(O),this.workspace=new vx(O),this.events=O.events,this.webAppUrl=O.webAppUrl}myPrincipalId(){return this._client.myPrincipalId()}requestedAs($){return new f6({...this.opts,requestedAs:$.id})}}export{a$ as wrapXml,O$ as toBody,H4 as observeRequests,y6 as msg,g6 as here,UO as WhatsAppChat,PO as WhatsAppAccount,n$ as UserApiKey,lO as ToolApproval,N$ as SessionReview,Px as RoutineExecution,KO as Routine,h0 as ReviewItem,Nx as PullRequestChangeset,zj as PipelineTable,WO as PipelineRow,Ij as PipelineColumn,L$ as MessageThread,R$ as Meeting,Zx as MacroOpRefusedError,f6 as Macro,XO as Initiative,_O as HarnessPairing,B$ as Harness,DO as GithubPullRequest,p$ as FormSection,RO as FormResponse,Cj as FormReference,r$ as FormQuestion,zO as FormOption,v$ as Form,xO as ExternalChatUpload,SO as ExternalChatSend,jO as ExternalChatParticipant,_$ as ExternalChatMessage,y$ as ExternalChat,HO as EntityMention,o as EntityAccess,NO as EmailFilter,LO as EmailDraft,oO as DraftAttachment,aO as DocumentVersion,VO as DocumentAnchor,$j as DevicePairing,s$ as CrmPipeline,v0 as ConversationTurn,dO as CodeExecution,nO as ChatMessage,iO as ChatGeneration,h1 as ChannelPicture,JO as ChannelActivity,q$ as CalendarNote,Lj as AgentConversation,T$ as Agent,TO as AccessRequest};
+`);try{M=JSON.parse(R),h=!0}catch{M=R}}if(h){if(S)await S(M);if(x)M=await x(M)}if(j?.({data:M,event:v,id:J,retry:V}),F.length)yield M}}}finally{T.removeEventListener("abort",g),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var Y4=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},Q4=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},J4=($)=>{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((K)=>encodeURIComponent(K))).join(Q4(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let G=Y4(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return vO({allowReserved:$,name:j,value:X})}).join(G);return x==="label"||x==="matrix"?G+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:G})=>{if(S instanceof Date)return G?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let K=[];Object.entries(S).forEach(([Q,J])=>{K=[...K,Q,$?J:encodeURIComponent(J)]});let L=K.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=J4(x),X=Object.entries(S).map(([K,L])=>vO({allowReserved:$,name:x==="deepObject"?`${j}[${K}]`:K,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var V4=/\{[^{}]+\}/g,W4=({path:$,url:O})=>{let j=O,x=O.match(V4);if(x)for(let S of x){let G=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))G=!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 K=$[Z];if(K===void 0||K===null)continue;if(Array.isArray(K)){j=j.replace(S,f0({explode:G,name:Z,style:X,value:K}));continue}if(typeof K==="object"){j=j.replace(S,b0({explode:G,name:Z,style:X,value:K,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${vO({name:Z,value:K})}`);continue}let L=encodeURIComponent(X==="label"?`.${K}`:K);j=j.replace(S,L)}return j},B6=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let G=S.startsWith("/")?S:`/${S}`,Z=($??"")+G;if(O)Z=W4({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 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 G in x){let Z=x[G];if(Z===void 0||Z===null)continue;let X=$[G]||O;if(Array.isArray(Z)){let K=f0({allowReserved:X.allowReserved,explode:!0,name:G,style:"form",value:Z,...X.array});if(K)S.push(K)}else if(typeof Z==="object"){let K=b0({allowReserved:X.allowReserved,explode:!0,name:G,style:"deepObject",value:Z,...X.object});if(K)S.push(K)}else{let K=vO({allowReserved:X.allowReserved,name:G,value:Z});if(K)S.push(K)}}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},B4=($,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(B4($,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 w1=($)=>B6({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:U6($.querySerializer),url:$.url}),q1=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=g0($.headers,O.headers),j},L4=($)=>{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?L4(j):Object.entries(j);for(let[S,G]of x)if(G===null)O.delete(S);else if(Array.isArray(G))for(let Z of G)O.append(S,Z);else if(G!==void 0)O.set(S,typeof G==="object"?JSON.stringify(G):G)}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 T6=()=>({error:new k0,request:new k0,response:new k0}),N4=U6({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),U4={"Content-Type":"application/json"},Wj=($={})=>({...N6,headers:U4,parseAs:"auto",querySerializer:N4,...$});var f1=($={})=>{let O=q1(Wj(),$),j=()=>({...O}),x=(Q)=>{return O=q1(O,Q),j()},S=T6(),G=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:g0(O.headers,Q.headers),serializedBody:void 0};if(J.security)await 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=w1(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await G(Q),T={redirect:"follow",...V,body:E1(V)};z=new Request(B,T);for(let N of S.request.fns)if(N)z=await N(z,V);let C=V.fetch;W=await C(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?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 H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await W[N]();break;case"json":{let U=await W.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let _=await W.text(),w;try{w=JSON.parse(_)}catch{}throw w??_}catch(V){let B=V;for(let T of S.error.fns)if(T)B=await T(B,W,z,Q);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(Q)=>(J)=>Z({...J,method:Q}),K=(Q)=>async(J)=>{let{opts:I,url:z}=await G(J);return W6({...I,body:I.body,method:Q,onRequest:async(W,V)=>{let B=new Request(W,V);for(let T of S.request.fns)if(T)B=await T(B,I);return B},serializedBody:E1(I),url:z})};return{buildUrl:(Q)=>w1({...O,...Q}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:K("CONNECT"),delete:K("DELETE"),get:K("GET"),head:K("HEAD"),options:K("OPTIONS"),patch:K("PATCH"),post:K("POST"),put:K("PUT"),trace:K("TRACE")},trace:X("TRACE")}};var H6=f1(Wj());class R6{client;constructor($){this.client=$?.client??H6}}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 y0 extends R6{static __registry=new D6;constructor($){super($);y0.__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 _6={dev:"https://dev.macro.com",prod:"https://macro.com",local:"http://localhost:3000"},b1={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 z4($,O){let j=O?.channel_id;return O&&j?{channel:b.byId($,j),thread:new m$($,j,O.thread_id)}:{channel:void 0,thread:void 0}}function E$($,O){return{session:l.byId($,O.session_id),owner:P.byId($,O.owner_id),...z4($,O.origin)}}function hO($,O,j){let x=O.origin?.channel_id;return x&&j?e.byId($,x,j):void 0}function mO($,O){return O?P.byId($,O):void 0}function M6($,O){return k(O).with({event_type:"agent_session.opened"},({metadata:j})=>({event_type:"agent_session.opened",metadata:j,...E$($,j.identity)})).with({event_type:"agent_session.turn_started"},({metadata:j})=>({event_type:"agent_session.turn_started",metadata:j,...E$($,j.identity),actor:mO($,j.actor),announcement:hO($,j.identity,j.announcement_message_id)})).with({event_type:"agent_session.turn_ended"},({metadata:j})=>({event_type:"agent_session.turn_ended",metadata:j,...E$($,j.identity),actor:mO($,j.actor),announcement:hO($,j.identity,j.announcement_message_id)})).with({event_type:"agent_session.command_rejected"},({metadata:j})=>({event_type:"agent_session.command_rejected",metadata:j,...E$($,j.identity),actor:mO($,j.actor),announcement:hO($,j.identity,j.announcement_message_id)})).with({event_type:"agent_session.settled"},({metadata:j})=>({event_type:"agent_session.settled",metadata:j,...E$($,j.identity),actor:mO($,j.last_turn?.actor),announcement:hO($,j.identity,j.last_turn?.announcement_message_id)})).with({event_type:"agent_session.waiting_for_input"},({metadata:j})=>({event_type:"agent_session.waiting_for_input",metadata:j,...E$($,j.identity),announcement:hO($,j.identity,j.announcement_message_id)})).with({event_type:"agent_session.input_received"},({metadata:j})=>({event_type:"agent_session.input_received",metadata:j,...E$($,j.identity)})).with({event_type:"agent_session.mentioned"},({metadata:j})=>({event_type:"agent_session.mentioned",metadata:j,...E$($,j.identity),mentionedBy:mO($,j.mentioned_by),mentioned:j.mentioned.map((x)=>P.byId($,x))})).with({event_type:"agent_session.stopped"},({metadata:j})=>({event_type:"agent_session.stopped",metadata:j,...E$($,j.identity),actor:mO($,j.turn_in_flight?.actor),announcement:hO($,j.identity,j.turn_in_flight?.announcement_message_id)})).with({event_type:"agent_session.renamed"},({metadata:j})=>({event_type:"agent_session.renamed",metadata:j,...E$($,j.identity)})).with({event_type:"agent_session.deleted"},({metadata:j})=>({event_type:"agent_session.deleted",metadata:j,...E$($,j.identity)})).exhaustive((j)=>{console.warn("macro sdk: unknown agent session event",j);return})}var P6="macro|";function P$($,O){return O.startsWith(P6)&&O.length>P6.length?P.byId($,O.toLowerCase()):void 0}function A6($,O){return k(O).with({event_type:"channel.created"},({metadata:j})=>({event_type:"channel.created",metadata:j,channel:b.byId($,j.channel_id),actor:P$($,j.actor),participants:j.participant_user_ids.map((x)=>P.byId($,x))})).with({event_type:"channel.updated"},({metadata:j})=>({event_type:"channel.updated",metadata:j,channel:b.byId($,j.channel_id),actor:P$($,j.actor)})).with({event_type:"channel.deleted"},({metadata:j})=>({event_type:"channel.deleted",metadata:j,channel:b.byId($,j.channel_id),actor:P$($,j.actor)})).with({event_type:"channel.picture_changed"},({metadata:j})=>({event_type:"channel.picture_changed",metadata:j,channel:b.byId($,j.channel_id),actor:P$($,j.actor)})).with({event_type:"channel.participant_added"},({metadata:j})=>({event_type:"channel.participant_added",metadata:j,channel:b.byId($,j.channel_id),addedBy:P$($,j.added_by),addedUsers:j.added_user_ids.map((x)=>P.byId($,x))})).with({event_type:"channel.participant_removed"},({metadata:j})=>({event_type:"channel.participant_removed",metadata:j,channel:b.byId($,j.channel_id),removedBy:P.byId($,j.removed_by),removedUsers:j.removed_user_ids.map((x)=>P.byId($,x))})).exhaustive((j)=>{console.warn("macro sdk: unknown channel event",j);return})}function C6($,O){return k(O).with({event_type:"document.created"},({metadata:j})=>({event_type:"document.created",metadata:j,document:q.byId($,j.document_id),owner:P.byId($,j.owner),project:j.project_id?n.byId($,j.project_id):void 0})).with({event_type:"document.updated"},({metadata:j})=>({event_type:"document.updated",metadata:j,document:q.byId($,j.document_id),owner:P.byId($,j.owner),actor:j.actor_user_id?P.byId($,j.actor_user_id):void 0,project:j.project_id?n.byId($,j.project_id):void 0,previousProject:j.previous_project_id?n.byId($,j.previous_project_id):void 0})).with({event_type:"document.deleted"},({metadata:j})=>({event_type:"document.deleted",metadata:j,document:q.byId($,j.document_id),actor:j.actor_user_id?P.byId($,j.actor_user_id):void 0,project:j.project_id?n.byId($,j.project_id):void 0})).with({event_type:"document.content_uploaded"},({metadata:j})=>({event_type:"document.content_uploaded",metadata:j,document:q.byId($,j.document_id),owner:P.byId($,j.owner)})).with({event_type:"document.sync_content_updated"},({metadata:j})=>({event_type:"document.sync_content_updated",metadata:j,document:q.byId($,j.document_id)})).with({event_type:"document.purged"},({metadata:j})=>({event_type:"document.purged",metadata:j,document:q.byId($,j.document_id)})).with({event_type:"document.copied"},({metadata:j})=>({event_type:"document.copied",metadata:j,document:q.byId($,j.document_id),sourceDocument:q.byId($,j.source_document_id),owner:P.byId($,j.owner),project:j.project_id?n.byId($,j.project_id):void 0})).with({event_type:"document.interaction"},({metadata:j})=>({event_type:"document.interaction",metadata:j,document:q.byId($,j.document_id)})).exhaustive((j)=>{console.warn("macro sdk: unknown document event",j);return})}function uO($,O,j=[]){let x=O.parent;if(x.type==="call")return{type:"call",call:Q$.byId($,x.id),message:d$.byId($,x.id,O.message_id),threadId:x.id};if(x.type==="channel")return{type:"channel",channel:b.byId($,x.id),message:e.byId($,x.id,O.message_id,j),thread:O.thread_id?new m$($,x.id,O.thread_id):void 0};return{type:"document",document:q.byId($,x.id),comment:c$.byId($,x.id,O.message_id),threadId:O.root_id}}function F6($,O){return k(O).with({event_type:"message.posted"},({metadata:j})=>({event_type:"message.posted",metadata:j,target:uO($,j,j.mentions),sender:P$($,j.sender)})).with({event_type:"message.mentioned"},({metadata:j})=>({event_type:"message.mentioned",metadata:j,target:uO($,j),sender:P$($,j.sender)})).with({event_type:"message.patched"},({metadata:j})=>({event_type:"message.patched",metadata:j,target:uO($,j),actor:P$($,j.actor)})).with({event_type:"message.deleted"},({metadata:j})=>({event_type:"message.deleted",metadata:j,target:uO($,j),actor:P$($,j.actor)})).with({event_type:"message.attachment_created"},({metadata:j})=>({event_type:"message.attachment_created",metadata:j,target:uO($,j),actor:P$($,j.actor)})).with({event_type:"message.attachment_removed"},({metadata:j})=>({event_type:"message.attachment_removed",metadata:j,target:uO($,j),actor:P$($,j.actor)})).exhaustive((j)=>{console.warn("macro sdk: unknown message event",j);return})}async function E6($){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 I4="webhook.validation.test";function T4($,O){return k(O).with({event_type:Z$.string.startsWith("document.")},(j)=>C6($,j)).with({event_type:Z$.string.startsWith("channel.")},(j)=>A6($,j)).with({event_type:Z$.string.startsWith("message.")},(j)=>F6($,j)).with({event_type:Z$.string.startsWith("agent_session.")},(j)=>M6($,j)).otherwise(()=>{return})}class k1{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((G)=>G.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 G of x)await this.dispatchEvent(G)}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 E6({secret:this.secret,timestamp:O.timestamp??"",rawBody:$,signature:O.signature??""}))throw new f("invalid webhook signature");if(O.event===I4)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=T4(this.client,j);if(!S)return;await Promise.all([...x].map((G)=>G(S)))}}function w6(){return}var H4=0,g1;function R4($){g1=$}function z$($,O,j){if(!j&&!g1)return $;let x=(S)=>{for(let G of[g1,j])try{Promise.resolve(G?.(S)).catch(()=>{})}catch{}};return new Proxy($,{get(S,G,Z){let X=Reflect.get(S,G,Z);if(typeof G!=="string"||typeof X!=="function")return X;return async(...K)=>{let L={id:++H4,service:O,operation:G};x({...L,status:"started"});try{let Q=await Reflect.apply(X,S,K),J=Q!==null&&typeof Q==="object"&&"error"in Q&&Q.error!=null;return x({...L,status:J?"failed":"completed"}),Q}catch(Q){throw x({...L,status:"failed"}),Q}}}})}var f6="x-macro-user-api-key",D4="mak_",y1="mbot_";function _4($){return k($).with(Z$.string.startsWith(y1),()=>{throw Error("bot token passed as a user credential. Use auth: { type: 'bot', token } or MACRO_BOT_TOKEN.")}).with(Z$.string.startsWith(D4),(O)=>[f6,O]).otherwise((O)=>["Authorization",`Bearer ${O}`])}async function q6($){return typeof $==="function"?await $():$}async function M4($,O,j){return k($).with({type:"bot"},async(x)=>{let S=await q6(x.token);if(!S.startsWith(y1))throw Error("user API key passed as a bot token. Use auth: { type: 'user', apiKey } or MACRO_API_KEY.");let G=[["x-macro-bot-token",S]];if(!j?.hasBotScope)G.push(["x-macro-bot-scope",x.scope??(O?"user":"team")]);if(O)G.push(["x-macro-bot-for-macro-user-id",O]);return G}).with({type:"user",apiKey:Z$.string},({apiKey:x})=>{if(x.startsWith(y1))throw Error("bot token passed as a user credential. Use auth: { type: 'bot', token } or MACRO_BOT_TOKEN.");return[[f6,x]]}).with({type:"user"},async({token:x})=>{return[_4(await q6(x))]}).exhaustive()}class v1{scheduledAction;unfurl;agentHarness;auth;calendar;cognition;contacts;email;notification;properties;search;storage;webAppUrl;wsVerify;events;authConfig;hosts;localPortmap;requestedAs;selfBotRecord;selfPrincipal;constructor($){let O=P4($),j=O==="local"?w6():void 0,x={...b1[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??_6[O],this.authConfig=A4($),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=z$(new R0({client:this.makeClient(x["scheduled-action"])}),"scheduled-action",$.onRequest),this.unfurl=z$(new y0({client:this.makeClient(x.unfurl)}),"unfurl",$.onRequest),this.agentHarness=z$(new gj({client:this.makeClient(x["agent-harness"])}),"agent-harness",$.onRequest),this.auth=z$(new uj({client:this.makeClient(x.auth)}),"auth",$.onRequest),this.calendar=z$(new pj({client:this.makeClient(x.calendar)}),"calendar",$.onRequest),this.cognition=z$(new tj({client:this.makeClient(x.cognition)}),"cognition",$.onRequest),this.contacts=z$(new j0({client:this.makeClient(x.contacts)}),"contacts",$.onRequest),this.email=z$(new G0({client:this.makeClient(x.email)}),"email",$.onRequest),this.notification=z$(new V0({client:this.makeClient(x.notification)}),"notification",$.onRequest),this.properties=z$(new U0({client:this.makeClient(x.properties)}),"properties",$.onRequest),this.search=z$(new A0({client:this.makeClient(x.search)}),"search",$.onRequest),this.storage=z$(new q0({client:this.makeClient(x.storage)}),"storage",$.onRequest);let G=typeof process<"u"?{}.MACRO_WEBHOOK_SECRET:void 0,Z=$.webhookSecret??G;this.events=new k1(this,Z)}hasActingUser(){return this.authConfig.type==="user"||this.requestedAs!==void 0}selfBot(){return this.selfBotRecord??=new rO(this).me().catch(($)=>{throw this.selfBotRecord=void 0,$}),this.selfBotRecord}myPrincipalId(){return this.selfPrincipal??=(this.authConfig.type==="bot"?this.selfBot().then(($)=>`bot|${$.id}`):P.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 M4(this.authConfig,this.requestedAs,{hasBotScope:j.headers.has("x-macro-bot-scope")});for(let[S,G]of x)j.headers.set(S,G);return j}),O}}function P4($){if($.env)return $.env;let O=typeof process<"u"?{}.MACRO_ENV:void 0;if(!O)return"prod";if(!(O in b1))throw Error(`invalid MACRO_ENV "${O}" — expected local, dev, or prod`);return O}function A4($){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 h1{id;constructor($){this.id=$}static byId($){return new h1($)}toJSON(){return{id:this.id}}}class b6{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;notifications;pins;projects;properties;tasks;teams;users;webhooks;workspace;events;webAppUrl;_client;opts;constructor($){this.opts=$;let O=new v1($);this._client=O,this.routines=new Cx(O),this.unfurls=new wx(O),this.agents=new c0(O),this.initiatives=new Tx(O),this.apiKeys=new l0(O),this.harnesses=new Ix(O),this.meetings=new Hx(O),this.githubPullRequests=new zx(O),this.entityMentions=new Jx(O),this.agentSessions=new u0(O),this.ai=new d0(O),this.bots=new rO(O),this.calendar=new r0(O),this.calls=new p0(O),this.channels=new i0(O),this.externalChats=new Wx(O),this.whatsapp=new bx(O),this.chats=new n0(O),this.crm=new t0(O),this.databases=new Gx(O),this.documents=new Kx(O),this.email=new Qx(O),this.favorites=new Bx(O),this.foreignEntities=new Lx(O),this.forms=new Nx(O),this.notifications=new Rx(O),this.pins=new Dx(O),this.projects=new _x(O),this.properties=new Mx(O),this.tasks=new Fx(O),this.teams=new Ex(O),this.users=new qx(O),this.webhooks=new fx(O),this.workspace=new vx(O),this.events=O.events,this.webAppUrl=O.webAppUrl}myPrincipalId(){return this._client.myPrincipalId()}requestedAs($){return new b6({...this.opts,requestedAs:$.id})}}export{i$ as wrapXml,O$ as toBody,R4 as observeRequests,v6 as msg,y6 as here,UO as WhatsAppChat,PO as WhatsAppAccount,s$ as UserApiKey,lO as ToolApproval,N$ as SessionReview,Ax as RoutineExecution,h$ as Routine,m0 as ReviewItem,Ux as PullRequestChangeset,zj as PipelineTable,WO as PipelineRow,Ij as PipelineColumn,L$ as MessageThread,R$ as Meeting,Xx as MacroOpRefusedError,b6 as Macro,GO as Initiative,_O as HarnessPairing,B$ as Harness,DO as GithubPullRequest,a$ as FormSection,RO as FormResponse,Cj as FormReference,p$ as FormQuestion,zO as FormOption,v$ as Form,SO as ExternalChatUpload,ZO as ExternalChatSend,xO as ExternalChatParticipant,_$ as ExternalChatMessage,y$ as ExternalChat,HO as EntityMention,o as EntityAccess,NO as EmailFilter,LO as EmailDraft,oO as DraftAttachment,aO as DocumentVersion,VO as DocumentAnchor,$j as DevicePairing,t$ as CrmPipeline,h0 as ConversationTurn,dO as CodeExecution,nO as ChatMessage,iO as ChatGeneration,h1 as ChannelPicture,JO as ChannelActivity,q$ as CalendarNote,Lj as AgentConversation,T$ as Agent,TO as AccessRequest};
diff --git a/crates/graphql_scheduled_action/src/query/test.rs b/crates/graphql_scheduled_action/src/query/test.rs
index 5504da33be..2fd24a8a40 100644
--- a/crates/graphql_scheduled_action/src/query/test.rs
+++ b/crates/graphql_scheduled_action/src/query/test.rs
@@ -134,6 +134,7 @@ fn routine(
next_run_at,
enabled,
run_visibility: RunVisibility::Unlisted,
+ template_id: None,
}
}
diff --git a/crates/macro_db_client/migrations/20261028210000_routine_templates.sql b/crates/macro_db_client/migrations/20261028210000_routine_templates.sql
new file mode 100644
index 0000000000..482df3897e
--- /dev/null
+++ b/crates/macro_db_client/migrations/20261028210000_routine_templates.sql
@@ -0,0 +1,19 @@
+-- A routine shared as a template: a snapshot of the source routine that other
+-- people activate as their own routine. Keyed by the source routine, so a link
+-- to a shared routine is a link to its template.
+SET LOCAL lock_timeout = '5s';
+CREATE TABLE IF NOT EXISTS scheduled_action_template (
+ action_id UUID PRIMARY KEY REFERENCES scheduled_action (id) ON DELETE CASCADE,
+ name TEXT NOT NULL,
+ description TEXT NOT NULL,
+ trigger_config JSONB NOT NULL,
+ task JSONB NOT NULL,
+ variables JSONB NOT NULL,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
+
+-- The template a routine was activated from. A plain pointer, not a foreign
+-- key: activated routines keep running after their template stops being shared.
+ALTER TABLE scheduled_action
+ ADD COLUMN IF NOT EXISTS template_id UUID;
diff --git a/crates/macro_db_client/migrations/20261028210001_scheduled_action_template_id_idx.sql b/crates/macro_db_client/migrations/20261028210001_scheduled_action_template_id_idx.sql
new file mode 100644
index 0000000000..207b9799bd
--- /dev/null
+++ b/crates/macro_db_client/migrations/20261028210001_scheduled_action_template_id_idx.sql
@@ -0,0 +1,7 @@
+-- no-transaction
+-- Counts the routines activated from a template. Partial: most routines were
+-- not activated from one. Built CONCURRENTLY so routine writes continue; an
+-- INVALID leftover from an interrupted build must be dropped by hand first.
+CREATE INDEX CONCURRENTLY IF NOT EXISTS scheduled_action_template_id_idx
+ ON scheduled_action (template_id)
+ WHERE template_id IS NOT NULL;
diff --git a/crates/scheduled_action/AGENTS.md b/crates/scheduled_action/AGENTS.md
index fd616c7ee5..7203778fb6 100644
--- a/crates/scheduled_action/AGENTS.md
+++ b/crates/scheduled_action/AGENTS.md
@@ -16,6 +16,8 @@ each run.
(Kafka or polled) turns into a dispatched run.
- `src/inbound/axum_router.rs`, `src/inbound/kafka_consumer.rs`,
`src/inbound/event_run_worker.rs`: the three inbound adapters.
+- `src/domain/templates.rs` + `src/inbound/template_router.rs`: sharing a
+ routine as a template and activating it as someone else's routine.
- `services/agent_harness_service/src/scheduling.rs`: the sole runtime host;
this crate has no deployed binary.
@@ -26,6 +28,10 @@ each run.
gateway.
- An authenticated caller with a routine ID can read its detail; listing,
run history, and mutations stay owner-scoped.
+- Templates: the owner shares a snapshot of a routine (keyed by the routine's
+ ID) with its references marked as variables; any authenticated caller reads
+ it, and activating creates the caller's own routine with `template_id`
+ pointing back. Filling variables happens in the client.
- Not here: the target being run (an agent turn, a routine's tool logic) →
`crates/agent_session`, `ai_tools`; Jev condition evaluation → `crates/jev`.
@@ -74,6 +80,8 @@ that listener is ready. Cancellation can stop the gate before startup finishes.
(both reject unknown fields, and older clients omit it), plus every query in
`pg_scheduled_action_repo.rs` and the event-run claim in `pg_event_run_repo.rs`,
which builds its own `ScheduledAction`.
+- `template_id` is a plain pointer, not a foreign key: activated routines keep
+ it after the template is unshared or its source routine is deleted.
- `run_visibility` is copied onto each run's agent session when the run is
prepared, so changing it affects later runs only.
diff --git a/crates/scheduled_action/TODO.md b/crates/scheduled_action/TODO.md
index ba279aaa66..4f026da22a 100644
--- a/crates/scheduled_action/TODO.md
+++ b/crates/scheduled_action/TODO.md
@@ -27,7 +27,9 @@
[] Fix noops in `ai_tools`
[] Make an infra file for tools that configures tools the same everywhere they're needed
[] Real unified list for history
-[] Sharing / permissions
+[~] Sharing / permissions
+ [x] Share a routine as a template; activate it as your own routine
+ [] AI-suggested variable fills, template versions, detach
[] Mention menu
[] Delete schedules
[] right click menu on unified list
diff --git a/crates/scheduled_action/src/domain.rs b/crates/scheduled_action/src/domain.rs
index 9c2304ba27..3c389827b4 100644
--- a/crates/scheduled_action/src/domain.rs
+++ b/crates/scheduled_action/src/domain.rs
@@ -7,3 +7,4 @@ pub mod read_service;
pub mod service;
pub mod target_runner;
pub mod target_validation;
+pub mod templates;
diff --git a/crates/scheduled_action/src/domain/event_runs/test_support.rs b/crates/scheduled_action/src/domain/event_runs/test_support.rs
index b139f2da79..c9951aea7d 100644
--- a/crates/scheduled_action/src/domain/event_runs/test_support.rs
+++ b/crates/scheduled_action/src/domain/event_runs/test_support.rs
@@ -309,6 +309,7 @@ impl EventRunRepository for Repo {
next_run_at: None,
claimed: Some(started_at),
run_visibility: RunVisibility::Unlisted,
+ template_id: None,
},
}))
}
diff --git a/crates/scheduled_action/src/domain/execution/test.rs b/crates/scheduled_action/src/domain/execution/test.rs
index 201379e43c..0b3b9a2326 100644
--- a/crates/scheduled_action/src/domain/execution/test.rs
+++ b/crates/scheduled_action/src/domain/execution/test.rs
@@ -331,6 +331,7 @@ fn action() -> ScheduledAction {
created_at: Utc::now(),
updated_at: Utc::now(),
run_visibility: RunVisibility::Unlisted,
+ template_id: None,
}
}
fn executor(repo: Repo, runner: Runner) -> InProcessExecutor<Repo, Live, Runner> {
diff --git a/crates/scheduled_action/src/domain/models.rs b/crates/scheduled_action/src/domain/models.rs
index 6c0f4f2d54..cc842a8674 100644
--- a/crates/scheduled_action/src/domain/models.rs
+++ b/crates/scheduled_action/src/domain/models.rs
@@ -347,6 +347,10 @@ pub struct ScheduledAction {
pub enabled: bool,
/// Whether the action's runs are listed in Home and the Agents list.
pub run_visibility: RunVisibility,
+ /// The shared template this routine was activated from, if any.
+ #[serde(default)]
+ #[schema(value_type = Option<String>, format = Uuid)]
+ pub template_id: Option<Uuid>,
}
impl ScheduledAction {
diff --git a/crates/scheduled_action/src/domain/models/test.rs b/crates/scheduled_action/src/domain/models/test.rs
index 30e8cc8624..b59d7ce516 100644
--- a/crates/scheduled_action/src/domain/models/test.rs
+++ b/crates/scheduled_action/src/domain/models/test.rs
@@ -235,6 +235,7 @@ fn action_owned_by(owner: Owner) -> ScheduledAction {
next_run_at: Some(next_run_at),
enabled: true,
run_visibility: RunVisibility::Unlisted,
+ template_id: None,
}
}
diff --git a/crates/scheduled_action/src/domain/ports.rs b/crates/scheduled_action/src/domain/ports.rs
index 0bc098dbe9..75386279de 100644
--- a/crates/scheduled_action/src/domain/ports.rs
+++ b/crates/scheduled_action/src/domain/ports.rs
@@ -5,6 +5,7 @@ use super::models::{
ActionExecutionRecord, CreateScheduledAction, DispatchEvent, InProgressExecution,
ScheduledAction, ScheduledActionUpdate, UpdateScheduledAction,
};
+use super::templates::{RoutineTemplate, ShareRoutineTemplate, TemplateSnapshot};
use anyhow::Result;
use chrono::{DateTime, Utc};
use entity_access::domain::models::{
@@ -148,6 +149,15 @@ pub trait ScheduledActionService: Send + Sync + 'static {
input: CreateScheduledAction,
) -> impl Future<Output = Result<ScheduledAction>> + Send;
+ /// `create_action` for a routine activated from `template_id`, recorded
+ /// as given: callers check that the template exists.
+ fn create_action_from_template(
+ &self,
+ principal: &CreationPrincipal,
+ input: CreateScheduledAction,
+ template_id: Uuid,
+ ) -> impl Future<Output = Result<ScheduledAction>> + Send;
+
/// Actions `user_id` can access. Legacy clients see cron actions only;
/// backend clients opt into events. ID-based operations and workers must
/// never authorize through this list.
@@ -187,6 +197,52 @@ pub trait ScheduledActionService: Send + Sync + 'static {
) -> impl Future<Output = Result<Vec<ActionExecutionRecord>>> + Send;
}
+/// Templates shared from routines, keyed by their source routine's ID.
+pub trait RoutineTemplateRepo: Send + Sync + 'static {
+ /// Create the template or replace its snapshot, keeping its creation time.
+ fn upsert_template(
+ &self,
+ snapshot: TemplateSnapshot,
+ ) -> impl Future<Output = Result<RoutineTemplate>> + Send;
+
+ /// A missing template is `Ok(())`.
+ fn delete_template(&self, id: &Uuid) -> impl Future<Output = Result<()>> + Send;
+
+ fn get_template(
+ &self,
+ id: &Uuid,
+ ) -> impl Future<Output = Result<Option<RoutineTemplate>>> + Send;
+}
+
+/// Sharing routines as templates and activating them.
+pub trait RoutineTemplateService: Send + Sync + 'static {
+ /// Share the receipt's routine, or replace its shared snapshot with the
+ /// routine's current configuration.
+ fn share_template(
+ &self,
+ receipt: EntityAccessReceipt<OwnerAccessLevel>,
+ input: ShareRoutineTemplate,
+ ) -> impl Future<Output = Result<RoutineTemplate>> + Send;
+
+ /// Stop sharing. Routines already activated from it keep running.
+ fn unshare_template(
+ &self,
+ receipt: EntityAccessReceipt<OwnerAccessLevel>,
+ ) -> impl Future<Output = Result<()>> + Send;
+
+ /// Read a template by its unguessable ID for any authenticated viewer.
+ fn get_template(&self, id: Uuid) -> impl Future<Output = Result<RoutineTemplate>> + Send;
+
+ /// Create the principal's own routine from a shared template. The input
+ /// is the activator's filled-in configuration, validated like any create.
+ fn activate_template(
+ &self,
+ principal: &CreationPrincipal,
+ template_id: Uuid,
+ input: CreateScheduledAction,
+ ) -> impl Future<Output = Result<ScheduledAction>> + Send;
+}
+
pub trait ScheduledActionDispatcher {
fn begin_dispatch_loop(self) -> (Sender<DispatchEvent>, Receiver<InProgressExecution>);
}
diff --git a/crates/scheduled_action/src/domain/service.rs b/crates/scheduled_action/src/domain/service.rs
index 999c573dfb..20b409878e 100644
--- a/crates/scheduled_action/src/domain/service.rs
+++ b/crates/scheduled_action/src/domain/service.rs
@@ -138,6 +138,53 @@ impl<Rpo: ScheduledActionRepo, Exe, Grants, Targets>
Ok(())
}
+ async fn create(
+ &self,
+ principal: &CreationPrincipal,
+ input: CreateScheduledAction,
+ template_id: Option<Uuid>,
+ ) -> Result<ScheduledAction>
+ where
+ Targets: TaskTargetValidator,
+ {
+ let owner = principal.owner();
+ let owner_user = owner.as_user().ok_or(OwnerNotUserError {
+ owner_type: owner.owner_type(),
+ })?;
+ let input = ActionConfiguration::from(input);
+ self.check_event_management(&input.trigger)?;
+ self.check_conditions(&input.trigger)?;
+ self.targets.validate_task(&input.task, owner_user).await?;
+ let now = Utc::now();
+ let next_run_at = next_run(&input.trigger)?;
+ let event_activated_at = input.trigger.event_filters().is_some().then_some(now);
+ let created = self
+ .repo
+ .create_action(ScheduledAction {
+ id: None,
+ owner,
+ name: input.name,
+ trigger: input.trigger,
+ kind: input.kind,
+ task: input.task,
+ enabled: input.enabled,
+ run_visibility: input.run_visibility,
+ created_at: now,
+ updated_at: now,
+ configuration_revision: ConfigurationRevision::INITIAL,
+ event_activated_at,
+ next_run_at,
+ claimed: None,
+ template_id,
+ })
+ .await?;
+ self.dispatcher_tx
+ .send(DispatchEvent::Create(created.clone()))
+ .await
+ .map_err(|e| anyhow::anyhow!("failed to dispatch create event: {e}"))?;
+ Ok(created)
+ }
+
async fn replace_configuration(
&self,
mut action: ScheduledAction,
@@ -299,41 +346,16 @@ where
principal: &CreationPrincipal,
input: CreateScheduledAction,
) -> Result<ScheduledAction> {
- let owner = principal.owner();
- let owner_user = owner.as_user().ok_or(OwnerNotUserError {
- owner_type: owner.owner_type(),
- })?;
- let input = ActionConfiguration::from(input);
- self.check_event_management(&input.trigger)?;
- self.check_conditions(&input.trigger)?;
- self.targets.validate_task(&input.task, owner_user).await?;
- let now = Utc::now();
- let next_run_at = next_run(&input.trigger)?;
- let event_activated_at = input.trigger.event_filters().is_some().then_some(now);
- let created = self
- .repo
- .create_action(ScheduledAction {
- id: None,
- owner,
- name: input.name,
- trigger: input.trigger,
- kind: input.kind,
- task: input.task,
- enabled: input.enabled,
- run_visibility: input.run_visibility,
- created_at: now,
- updated_at: now,
- configuration_revision: ConfigurationRevision::INITIAL,
- event_activated_at,
- next_run_at,
- claimed: None,
- })
- .await?;
- self.dispatcher_tx
- .send(DispatchEvent::Create(created.clone()))
- .await
- .map_err(|e| anyhow::anyhow!("failed to dispatch create event: {e}"))?;
- Ok(created)
+ self.create(principal, input, None).await
+ }
+
+ async fn create_action_from_template(
+ &self,
+ principal: &CreationPrincipal,
+ input: CreateScheduledAction,
+ template_id: Uuid,
+ ) -> Result<ScheduledAction> {
+ self.create(principal, input, Some(template_id)).await
}
async fn get_actions(
diff --git a/crates/scheduled_action/src/domain/service/test.rs b/crates/scheduled_action/src/domain/service/test.rs
index 1b6a6ea3e8..34327ebefa 100644
--- a/crates/scheduled_action/src/domain/service/test.rs
+++ b/crates/scheduled_action/src/domain/service/test.rs
@@ -931,6 +931,7 @@ fn claim_expiry_instant_still_blocks_replacement() {
next_run_at: None,
enabled: true,
run_visibility: RunVisibility::Unlisted,
+ template_id: None,
};
let expires_at = action
.claim_expires_at()
@@ -1000,6 +1001,7 @@ fn seeded(
next_run_at: None,
enabled: true,
run_visibility: RunVisibility::Unlisted,
+ template_id: None,
}
}
diff --git a/crates/scheduled_action/src/domain/service/test/user_cleanup.rs b/crates/scheduled_action/src/domain/service/test/user_cleanup.rs
index fe17bbd755..42df9a6d63 100644
--- a/crates/scheduled_action/src/domain/service/test/user_cleanup.rs
+++ b/crates/scheduled_action/src/domain/service/test/user_cleanup.rs
@@ -109,6 +109,7 @@ pub(super) fn action(owner: Owner, events: bool) -> ScheduledAction {
claimed: None,
enabled: true,
run_visibility: config.run_visibility,
+ template_id: None,
}
}
diff --git a/crates/scheduled_action/src/domain/target_runner/test.rs b/crates/scheduled_action/src/domain/target_runner/test.rs
index 7685ff1142..bd1f912547 100644
--- a/crates/scheduled_action/src/domain/target_runner/test.rs
+++ b/crates/scheduled_action/src/domain/target_runner/test.rs
@@ -217,6 +217,7 @@ fn action() -> ScheduledAction {
created_at: Utc::now(),
updated_at: Utc::now(),
run_visibility: RunVisibility::Unlisted,
+ template_id: None,
}
}
@@ -882,6 +883,7 @@ async fn a_scheduled_run_tells_the_agent_which_routine_fired_and_on_what_schedul
created_at: scheduled_for,
updated_at: scheduled_for,
run_visibility: RunVisibility::Unlisted,
+ template_id: None,
};
let mut handle = ExecutionHandle::default();
runner.prepare(&action, &mut handle).await.unwrap();
@@ -989,6 +991,7 @@ async fn a_task_status_change_hands_the_agent_the_task_instead_of_its_ids() {
created_at: at,
updated_at: at,
run_visibility: RunVisibility::Unlisted,
+ template_id: None,
};
let event: EventReference = serde_json::from_value(json!({
"event_id": "01928f3e-6a2b-7c3d-8e4f-0123456789cd",
@@ -1097,6 +1100,7 @@ async fn a_manual_run_tells_the_agent_its_owner_started_it() {
created_at: requested_at,
updated_at: requested_at,
run_visibility: RunVisibility::Unlisted,
+ template_id: None,
};
let mut handle = ExecutionHandle::default();
runner.prepare(&action, &mut handle).await.unwrap();
diff --git a/crates/scheduled_action/src/domain/templates.rs b/crates/scheduled_action/src/domain/templates.rs
new file mode 100644
index 0000000000..420521e1e1
--- /dev/null
+++ b/crates/scheduled_action/src/domain/templates.rs
@@ -0,0 +1,218 @@
+//! Sharing a routine as a template that other people activate as their own
+//! routine. A routine runs as its owner, so it is never shared itself: its
+//! owner publishes a snapshot whose references are marked as variables, and
+//! each person who activates it gets an ordinary routine of their own that
+//! points back at the template.
+
+use std::sync::Arc;
+
+use anyhow::Result;
+use chrono::{DateTime, Utc};
+use chrono_tz::Tz;
+use entity_access::domain::models::{EntityAccessReceipt, EntityType, OwnerAccessLevel};
+use macro_uuid::Uuid;
+use model_owner::{CreationPrincipal, Owner};
+use serde::{Deserialize, Serialize};
+use serde_json::Value;
+use utoipa::ToSchema;
+
+use super::event_trigger::ActionTrigger;
+use super::models::{ActionPolicyError, CreateScheduledAction, ScheduledAction};
+use super::ports::{RoutineTemplateRepo, RoutineTemplateService, ScheduledActionService};
+
+#[cfg(test)]
+mod test;
+
+/// Longest description a template can carry.
+pub const MAX_DESCRIPTION_CHARS: usize = 1_000;
+/// Most variables a template can mark.
+pub const MAX_VARIABLES: usize = 100;
+
+/// How a variable is filled when someone activates the template.
+#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, ToSchema)]
+#[serde(rename_all = "snake_case")]
+pub enum VariableFill {
+ /// Replaced by the person activating it, such as the author's own
+ /// mention or the schedule's time zone.
+ Activator,
+ /// The same item for everyone. Kept when the activator can open it.
+ Shared,
+ /// Each person chooses their own. Left out unless they replace it.
+ Choice,
+}
+
+/// A user-specific part of a shared routine.
+#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, ToSchema)]
+#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
+pub enum TemplateVariable {
+ /// A person mentioned in the instructions, by their user ID.
+ User {
+ id: String,
+ label: String,
+ fill: VariableFill,
+ },
+ /// A document, channel or other item mentioned in the instructions.
+ Item {
+ id: String,
+ /// The mention's block name, such as `channel` or `md`.
+ block_name: String,
+ label: String,
+ fill: VariableFill,
+ },
+ /// The time zone of the routine's schedules.
+ TimeZone {
+ #[schema(value_type = String)]
+ timezone: Tz,
+ fill: VariableFill,
+ },
+}
+
+/// What the owner supplies when sharing; the rest is snapshotted from the routine.
+#[derive(Serialize, Deserialize, Debug, Clone, ToSchema)]
+#[serde(deny_unknown_fields)]
+pub struct ShareRoutineTemplate {
+ pub description: String,
+ pub variables: Vec<TemplateVariable>,
+}
+
+/// A shared routine's snapshot, readable by any signed-in user with its ID.
+#[derive(Serialize, Deserialize, Debug, Clone, ToSchema)]
+pub struct RoutineTemplate {
+ /// The routine it was shared from.
+ #[schema(value_type = String, format = Uuid)]
+ pub id: Uuid,
+ /// Who shared it: the source routine's owner.
+ #[schema(value_type = String)]
+ pub author: Owner,
+ pub name: String,
+ pub description: String,
+ pub trigger: ActionTrigger,
+ #[schema(value_type = Object)]
+ pub task: Value,
+ pub variables: Vec<TemplateVariable>,
+ /// Routines activated from this template, including stopped ones.
+ pub active_count: u32,
+ pub created_at: DateTime<Utc>,
+ pub updated_at: DateTime<Utc>,
+}
+
+/// The snapshot written when an owner shares or re-shares a routine.
+#[derive(Debug, Clone)]
+pub struct TemplateSnapshot {
+ pub action_id: Uuid,
+ pub name: String,
+ pub description: String,
+ pub trigger: ActionTrigger,
+ pub task: Value,
+ pub variables: Vec<TemplateVariable>,
+}
+
+/// Rejected template input.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
+pub enum TemplateInputError {
+ #[error("a template description can be at most 1000 characters")]
+ DescriptionTooLong,
+ #[error("a template can have at most 100 variables")]
+ TooManyVariables,
+}
+
+impl ShareRoutineTemplate {
+ fn into_snapshot(self, action: &ScheduledAction, action_id: Uuid) -> Result<TemplateSnapshot> {
+ if self.description.chars().count() > MAX_DESCRIPTION_CHARS {
+ return Err(TemplateInputError::DescriptionTooLong.into());
+ }
+ if self.variables.len() > MAX_VARIABLES {
+ return Err(TemplateInputError::TooManyVariables.into());
+ }
+ Ok(TemplateSnapshot {
+ action_id,
+ name: action.name.clone(),
+ description: self.description.trim().to_owned(),
+ trigger: action.trigger.clone(),
+ task: action.task.clone(),
+ variables: self.variables,
+ })
+ }
+}
+
+pub struct RoutineTemplateServiceImpl<Actions, Templates> {
+ actions: Arc<Actions>,
+ templates: Arc<Templates>,
+}
+
+impl<Actions, Templates> RoutineTemplateServiceImpl<Actions, Templates> {
+ pub fn new(actions: Arc<Actions>, templates: Arc<Templates>) -> Self {
+ Self { actions, templates }
+ }
+}
+
+impl<Actions: ScheduledActionService, Templates> RoutineTemplateServiceImpl<Actions, Templates> {
+ /// The routine behind an owner receipt, while the receipt's user still owns it.
+ async fn owned_action(
+ &self,
+ receipt: &EntityAccessReceipt<OwnerAccessLevel>,
+ ) -> Result<(Uuid, ScheduledAction)> {
+ if receipt.entity().entity_type != EntityType::ScheduledAction {
+ anyhow::bail!("scheduled action receipt has the wrong entity type");
+ }
+ let id = receipt
+ .entity()
+ .entity_id
+ .parse::<Uuid>()
+ .map_err(|_| ActionPolicyError::NotFound)?;
+ let action = self.actions.get_action(id).await?;
+ let owned = receipt
+ .acting_user_id()
+ .is_some_and(|user| action.owner.is_user(user));
+ if !owned {
+ return Err(ActionPolicyError::NotFound.into());
+ }
+ Ok((id, action))
+ }
+}
+
+impl<Actions, Templates> RoutineTemplateService for RoutineTemplateServiceImpl<Actions, Templates>
+where
+ Actions: ScheduledActionService,
+ Templates: RoutineTemplateRepo,
+{
+ #[tracing::instrument(err, skip_all, fields(action_id = %receipt.entity().entity_id, variables = input.variables.len()))]
+ async fn share_template(
+ &self,
+ receipt: EntityAccessReceipt<OwnerAccessLevel>,
+ input: ShareRoutineTemplate,
+ ) -> Result<RoutineTemplate> {
+ let (id, action) = self.owned_action(&receipt).await?;
+ action.owner_user()?;
+ let snapshot = input.into_snapshot(&action, id)?;
+ self.templates.upsert_template(snapshot).await
+ }
+
+ #[tracing::instrument(err, skip_all, fields(action_id = %receipt.entity().entity_id))]
+ async fn unshare_template(&self, receipt: EntityAccessReceipt<OwnerAccessLevel>) -> Result<()> {
+ let (id, _) = self.owned_action(&receipt).await?;
+ self.templates.delete_template(&id).await
+ }
+
+ async fn get_template(&self, id: Uuid) -> Result<RoutineTemplate> {
+ self.templates
+ .get_template(&id)
+ .await?
+ .ok_or_else(|| ActionPolicyError::NotFound.into())
+ }
+
+ #[tracing::instrument(err, skip_all, fields(template_id = %template_id))]
+ async fn activate_template(
+ &self,
+ principal: &CreationPrincipal,
+ template_id: Uuid,
+ input: CreateScheduledAction,
+ ) -> Result<ScheduledAction> {
+ if self.templates.get_template(&template_id).await?.is_none() {
+ return Err(ActionPolicyError::NotFound.into());
+ }
+ self.actions
+ .create_action_from_template(principal, input, template_id)
+ .await
+ }
+}
diff --git a/crates/scheduled_action/src/domain/templates/test.rs b/crates/scheduled_action/src/domain/templates/test.rs
new file mode 100644
index 0000000000..0926ed327c
--- /dev/null
+++ b/crates/scheduled_action/src/domain/templates/test.rs
@@ -0,0 +1,191 @@
+use super::*;
+use crate::domain::service::test::{TestService, USER, configuration, service, user};
+use macro_user_id::user_id::MacroUserIdStr;
+use std::collections::HashMap;
+use std::sync::Mutex;
+
+#[derive(Default)]
+struct FakeTemplates {
+ templates: Mutex<HashMap<Uuid, RoutineTemplate>>,
+}
+
+impl RoutineTemplateRepo for FakeTemplates {
+ async fn upsert_template(&self, snapshot: TemplateSnapshot) -> Result<RoutineTemplate> {
+ let now = Utc::now();
+ let template = RoutineTemplate {
+ id: snapshot.action_id,
+ author: Owner::User(user()),
+ name: snapshot.name,
+ description: snapshot.description,
+ trigger: snapshot.trigger,
+ task: snapshot.task,
+ variables: snapshot.variables,
+ active_count: 0,
+ created_at: now,
+ updated_at: now,
+ };
+ self.templates
+ .lock()
+ .unwrap()
+ .insert(template.id, template.clone());
+ Ok(template)
+ }
+
+ async fn delete_template(&self, id: &Uuid) -> Result<()> {
+ self.templates.lock().unwrap().remove(id);
+ Ok(())
+ }
+
+ async fn get_template(&self, id: &Uuid) -> Result<Option<RoutineTemplate>> {
+ Ok(self.templates.lock().unwrap().get(id).cloned())
+ }
+}
+
+type Templates = RoutineTemplateServiceImpl<TestService, FakeTemplates>;
+
+fn templates(actions: &Arc<TestService>) -> Templates {
+ RoutineTemplateServiceImpl::new(Arc::clone(actions), Arc::new(FakeTemplates::default()))
+}
+
+fn owner_receipt(user: MacroUserIdStr<'static>, id: Uuid) -> EntityAccessReceipt<OwnerAccessLevel> {
+ EntityAccessReceipt::dangerously_assert_authenticated_user(
+ user,
+ &id.to_string(),
+ EntityType::ScheduledAction,
+ )
+}
+
+fn other_user() -> MacroUserIdStr<'static> {
+ MacroUserIdStr::try_from("macro|[email protected]".to_owned()).unwrap()
+}
+
+async fn create_routine(actions: &TestService) -> Uuid {
+ actions
+ .create_action(
+ &CreationPrincipal::User(user()),
+ CreateScheduledAction::Canonical(configuration(false)),
+ )
+ .await
+ .unwrap()
+ .id
+ .unwrap()
+}
+
+fn share_input() -> ShareRoutineTemplate {
+ ShareRoutineTemplate {
+ description: " Summarizes the week ".into(),
+ variables: vec![TemplateVariable::User {
+ id: USER.into(),
+ label: "Eric".into(),
+ fill: VariableFill::Activator,
+ }],
+ }
+}
+
+#[tokio::test]
+async fn sharing_snapshots_the_routine_and_activation_points_back_at_it() {
+ let actions = service(false);
+ let templates = templates(&actions);
+ let id = create_routine(&actions).await;
+
+ let shared = templates
+ .share_template(owner_receipt(user(), id), share_input())
+ .await
+ .unwrap();
+ assert_eq!(shared.id, id);
+ assert_eq!(shared.name, "routine");
+ assert_eq!(shared.description, "Summarizes the week");
+ assert_eq!(shared.task, configuration(false).task);
+
+ let activated = templates
+ .activate_template(
+ &CreationPrincipal::User(other_user()),
+ id,
+ CreateScheduledAction::Canonical(configuration(false)),
+ )
+ .await
+ .unwrap();
+ assert_eq!(activated.template_id, Some(id));
+ assert!(activated.owner.is_user(&other_user()));
+}
+
+#[tokio::test]
+async fn only_the_owner_can_share_or_stop_sharing() {
+ let actions = service(false);
+ let templates = templates(&actions);
+ let id = create_routine(&actions).await;
+
+ let error = templates
+ .share_template(owner_receipt(other_user(), id), share_input())
+ .await
+ .unwrap_err();
+ assert!(matches!(
+ error.downcast_ref::<ActionPolicyError>(),
+ Some(ActionPolicyError::NotFound)
+ ));
+
+ templates
+ .share_template(owner_receipt(user(), id), share_input())
+ .await
+ .unwrap();
+ let error = templates
+ .unshare_template(owner_receipt(other_user(), id))
+ .await
+ .unwrap_err();
+ assert!(matches!(
+ error.downcast_ref::<ActionPolicyError>(),
+ Some(ActionPolicyError::NotFound)
+ ));
+ assert!(templates.get_template(id).await.is_ok());
+}
+
+#[tokio::test]
+async fn activating_an_unshared_routine_creates_nothing() {
+ let actions = service(false);
+ let templates = templates(&actions);
+ let id = create_routine(&actions).await;
+ templates
+ .share_template(owner_receipt(user(), id), share_input())
+ .await
+ .unwrap();
+ templates
+ .unshare_template(owner_receipt(user(), id))
+ .await
+ .unwrap();
+
+ let error = templates
+ .activate_template(
+ &CreationPrincipal::User(other_user()),
+ id,
+ CreateScheduledAction::Canonical(configuration(false)),
+ )
+ .await
+ .unwrap_err();
+ assert!(matches!(
+ error.downcast_ref::<ActionPolicyError>(),
+ Some(ActionPolicyError::NotFound)
+ ));
+}
+
+#[tokio::test]
+async fn rejects_an_oversized_description() {
+ let actions = service(false);
+ let templates = templates(&actions);
+ let id = create_routine(&actions).await;
+
+ let error = templates
+ .share_template(
+ owner_receipt(user(), id),
+ ShareRoutineTemplate {
+ description: "a".repeat(MAX_DESCRIPTION_CHARS + 1),
+ variables: vec![],
+ },
+ )
+ .await
+ .unwrap_err();
+ assert_eq!(
+ error.downcast_ref::<TemplateInputError>(),
+ Some(&TemplateInputError::DescriptionTooLong)
+ );
+ assert!(templates.get_template(id).await.is_err());
+}
diff --git a/crates/scheduled_action/src/inbound.rs b/crates/scheduled_action/src/inbound.rs
index 548b1282da..3744da3ee0 100644
--- a/crates/scheduled_action/src/inbound.rs
+++ b/crates/scheduled_action/src/inbound.rs
@@ -1,3 +1,4 @@
pub mod axum_router;
pub mod event_run_worker;
pub mod kafka_consumer;
+pub mod template_router;
diff --git a/crates/scheduled_action/src/inbound/axum_router.rs b/crates/scheduled_action/src/inbound/axum_router.rs
index 3745cd9f91..dd6fc1c45a 100644
--- a/crates/scheduled_action/src/inbound/axum_router.rs
+++ b/crates/scheduled_action/src/inbound/axum_router.rs
@@ -7,6 +7,7 @@ use crate::domain::models::{
};
use crate::domain::ports::ScheduledActionService;
use crate::domain::target_validation::TargetValidationError;
+use crate::domain::templates::TemplateInputError;
use agent_session::domain::routines::RoutineSessionError;
use ai_billing::{AiAdmissionError, inbound::admission::AiAdmissionErrorBody};
use axum::extract::{FromRef, Path, Query, State, rejection::JsonRejection};
@@ -522,6 +523,9 @@ impl IntoResponse for ScheduledActionApiError {
};
return (status, policy.to_string()).into_response();
}
+ if let Some(input) = error.downcast_ref::<TemplateInputError>() {
+ return (StatusCode::BAD_REQUEST, input.to_string()).into_response();
+ }
if let Some(validation) = error.downcast_ref::<TargetValidationError>() {
let status = match validation {
TargetValidationError::InvalidTask | TargetValidationError::AgentsDisabled => {
diff --git a/crates/scheduled_action/src/inbound/template_router.rs b/crates/scheduled_action/src/inbound/template_router.rs
new file mode 100644
index 0000000000..05ed91dd97
--- /dev/null
+++ b/crates/scheduled_action/src/inbound/template_router.rs
@@ -0,0 +1,209 @@
+use std::sync::Arc;
+
+use axum::extract::{FromRef, Path, State, rejection::JsonRejection};
+use axum::http::StatusCode;
+use axum::response::IntoResponse;
+use axum::routing::{post, put};
+use axum::{Json, Router};
+use entity_access::domain::models::OwnerAccessLevel;
+use entity_access::domain::ports::EntityAccessService;
+use entity_access::inbound::axum_extractors::ScheduledActionAccessExtractor;
+use entity_registry::{CreationPrincipalExtractor, NonUserOwners};
+use macro_authorization::{
+ MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState, UserOrInternal,
+};
+use macro_uuid::Uuid;
+
+use crate::domain::models::CreateScheduledAction;
+use crate::domain::ports::RoutineTemplateService;
+use crate::domain::templates::{RoutineTemplate, ShareRoutineTemplate};
+use crate::inbound::axum_router::{ScheduledActionApiError, ScheduledActionResponse};
+
+pub struct RoutineTemplateRouterState<T, Svc, Auth> {
+ pub service: Arc<T>,
+ pub access_service: Arc<Svc>,
+ pub authorization_state: MacroAuthorizationState<Auth>,
+}
+
+impl<T, Svc, Auth> Clone for RoutineTemplateRouterState<T, Svc, Auth> {
+ fn clone(&self) -> Self {
+ Self {
+ service: Arc::clone(&self.service),
+ access_service: Arc::clone(&self.access_service),
+ authorization_state: self.authorization_state.clone(),
+ }
+ }
+}
+
+impl<T, Svc, Auth> FromRef<RoutineTemplateRouterState<T, Svc, Auth>> for Arc<Svc> {
+ fn from_ref(state: &RoutineTemplateRouterState<T, Svc, Auth>) -> Self {
+ Arc::clone(&state.access_service)
+ }
+}
+
+impl<T, Svc, Auth> FromRef<RoutineTemplateRouterState<T, Svc, Auth>>
+ for MacroAuthorizationState<Auth>
+{
+ fn from_ref(state: &RoutineTemplateRouterState<T, Svc, Auth>) -> Self {
+ state.authorization_state.clone()
+ }
+}
+
+/// Like routine creation, a team bot reaches the domain so its non-user owner
+/// gets the explicit `OwnerNotUserError` instead of a generic 403.
+impl<T, Svc, Auth> FromRef<RoutineTemplateRouterState<T, Svc, Auth>> for NonUserOwners {
+ fn from_ref(_state: &RoutineTemplateRouterState<T, Svc, Auth>) -> Self {
+ NonUserOwners::Enabled
+ }
+}
+
+pub fn routine_template_router<T, Svc, Auth, St>(
+ state: RoutineTemplateRouterState<T, Svc, Auth>,
+) -> Router<St>
+where
+ T: RoutineTemplateService,
+ Svc: EntityAccessService,
+ Auth: MacroAuthorizationService,
+ St: Send + Sync,
+{
+ Router::new()
+ .route(
+ "/scheduled-actions/{id}/template",
+ put(share_template::<T, Svc, Auth>)
+ .get(get_template::<T, Svc, Auth>)
+ .delete(unshare_template::<T, Svc, Auth>),
+ )
+ .route(
+ "/scheduled-actions/{id}/template/activate",
+ post(activate_template::<T, Svc, Auth>),
+ )
+ .with_state(state)
+}
+
+#[utoipa::path(
+ put,
+ path = "/scheduled-actions/{id}/template",
+ tag = "scheduled actions",
+ operation_id = "share_scheduled_action_template",
+ params(("id" = String, Path, description = "ID of the routine to share")),
+ request_body = ShareRoutineTemplate,
+ responses(
+ (status = 200, body = RoutineTemplate),
+ (status = 400, body = String),
+ (status = 401, body = String),
+ (status = 404, body = String),
+ (status = 500, body = String),
+ )
+)]
+pub async fn share_template<T, Svc, Auth>(
+ State(state): State<RoutineTemplateRouterState<T, Svc, Auth>>,
+ ScheduledActionAccessExtractor {
+ entity_access_receipt,
+ ..
+ }: ScheduledActionAccessExtractor<OwnerAccessLevel, Svc, Auth>,
+ body: Result<Json<ShareRoutineTemplate>, JsonRejection>,
+) -> Result<Json<RoutineTemplate>, ScheduledActionApiError>
+where
+ T: RoutineTemplateService,
+ Svc: EntityAccessService,
+ Auth: MacroAuthorizationService,
+{
+ let Json(req) = body.map_err(ScheduledActionApiError::InvalidRequest)?;
+ let template = state
+ .service
+ .share_template(entity_access_receipt, req)
+ .await?;
+ Ok(Json(template))
+}
+
+#[utoipa::path(
+ delete,
+ path = "/scheduled-actions/{id}/template",
+ tag = "scheduled actions",
+ operation_id = "unshare_scheduled_action_template",
+ params(("id" = String, Path, description = "ID of the shared routine")),
+ responses(
+ (status = 204),
+ (status = 401, body = String),
+ (status = 404, body = String),
+ (status = 500, body = String),
+ )
+)]
+pub async fn unshare_template<T, Svc, Auth>(
+ State(state): State<RoutineTemplateRouterState<T, Svc, Auth>>,
+ ScheduledActionAccessExtractor {
+ entity_access_receipt,
+ ..
+ }: ScheduledActionAccessExtractor<OwnerAccessLevel, Svc, Auth>,
+) -> Result<StatusCode, ScheduledActionApiError>
+where
+ T: RoutineTemplateService,
+ Svc: EntityAccessService,
+ Auth: MacroAuthorizationService,
+{
+ state
+ .service
+ .unshare_template(entity_access_receipt)
+ .await?;
+ Ok(StatusCode::NO_CONTENT)
+}
+
+#[utoipa::path(
+ get,
+ path = "/scheduled-actions/{id}/template",
+ tag = "scheduled actions",
+ operation_id = "get_scheduled_action_template",
+ params(("id" = String, Path, description = "ID of the shared routine")),
+ responses(
+ (status = 200, body = RoutineTemplate),
+ (status = 401, body = String),
+ (status = 404, body = String, description = "The routine is not shared"),
+ (status = 500, body = String),
+ )
+)]
+pub async fn get_template<T, Svc, Auth>(
+ State(state): State<RoutineTemplateRouterState<T, Svc, Auth>>,
+ _user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
+ Path(id): Path<Uuid>,
+) -> Result<Json<RoutineTemplate>, ScheduledActionApiError>
+where
+ T: RoutineTemplateService,
+ Auth: MacroAuthorizationService,
+{
+ Ok(Json(state.service.get_template(id).await?))
+}
+
+#[utoipa::path(
+ post,
+ path = "/scheduled-actions/{id}/template/activate",
+ tag = "scheduled actions",
+ operation_id = "activate_scheduled_action_template",
+ params(("id" = String, Path, description = "ID of the shared routine")),
+ request_body = CreateScheduledAction,
+ responses(
+ (status = 201, body = ScheduledActionResponse),
+ (status = 400, body = String),
+ (status = 401, body = String),
+ (status = 403, body = String),
+ (status = 404, body = String, description = "The routine is not shared"),
+ (status = 500, body = String),
+ )
+)]
+pub async fn activate_template<T, Svc, Auth>(
+ State(state): State<RoutineTemplateRouterState<T, Svc, Auth>>,
+ Path(id): Path<Uuid>,
+ CreationPrincipalExtractor { principal, .. }: CreationPrincipalExtractor<Auth>,
+ body: Result<Json<CreateScheduledAction>, JsonRejection>,
+) -> Result<impl IntoResponse, ScheduledActionApiError>
+where
+ T: RoutineTemplateService,
+ Svc: EntityAccessService,
+ Auth: MacroAuthorizationService,
+{
+ let Json(req) = body.map_err(ScheduledActionApiError::InvalidRequest)?;
+ let created = state.service.activate_template(&principal, id, req).await?;
+ Ok((
+ StatusCode::CREATED,
+ Json(ScheduledActionResponse::from(created)),
+ ))
+}
diff --git a/crates/scheduled_action/src/outbound.rs b/crates/scheduled_action/src/outbound.rs
index e520ac6f0d..4fa4558171 100644
--- a/crates/scheduled_action/src/outbound.rs
+++ b/crates/scheduled_action/src/outbound.rs
@@ -5,5 +5,6 @@ pub mod event_content;
pub mod inprocess_executor;
pub mod pg_event_run_repo;
pub mod pg_polling_dispatcher;
+pub mod pg_routine_template_repo;
pub mod pg_scheduled_action_repo;
pub mod tokio_dispatcher;
diff --git a/crates/scheduled_action/src/outbound/pg_event_run_repo.rs b/crates/scheduled_action/src/outbound/pg_event_run_repo.rs
index 76111641fd..bb338dd2d7 100644
--- a/crates/scheduled_action/src/outbound/pg_event_run_repo.rs
+++ b/crates/scheduled_action/src/outbound/pg_event_run_repo.rs
@@ -287,7 +287,7 @@ impl EventRunRepository for PgEventRunRepo {
}
let action = sqlx::query!(
r#"
- SELECT id, owner, name, kind, task, created_at, updated_at, enabled, run_visibility,
+ SELECT id, owner, name, kind, task, created_at, updated_at, enabled, run_visibility, template_id,
event_filters AS "event_filters!", event_activated_at AS "event_activated_at!"
FROM scheduled_action
WHERE id = $1 AND enabled AND event_filters IS NOT NULL AND configuration_revision = $2
@@ -354,6 +354,7 @@ impl EventRunRepository for PgEventRunRepo {
event_activated_at: Some(action.event_activated_at),
next_run_at: None,
claimed: Some(started_at),
+ template_id: action.template_id,
};
sqlx::query!(
"UPDATE scheduled_action SET claimed = $2, claim_token = $3, updated_at = now() WHERE id = $1",
diff --git a/crates/scheduled_action/src/outbound/pg_polling_dispatcher/test.rs b/crates/scheduled_action/src/outbound/pg_polling_dispatcher/test.rs
index 421dc70d14..8358fa6ccb 100644
--- a/crates/scheduled_action/src/outbound/pg_polling_dispatcher/test.rs
+++ b/crates/scheduled_action/src/outbound/pg_polling_dispatcher/test.rs
@@ -193,6 +193,7 @@ fn due_action() -> ScheduledAction {
next_run_at: Some(now - ChronoDuration::seconds(1)),
enabled: true,
run_visibility: RunVisibility::Unlisted,
+ template_id: None,
}
}
diff --git a/crates/scheduled_action/src/outbound/pg_routine_template_repo.rs b/crates/scheduled_action/src/outbound/pg_routine_template_repo.rs
new file mode 100644
index 0000000000..f2d1c652a8
--- /dev/null
+++ b/crates/scheduled_action/src/outbound/pg_routine_template_repo.rs
@@ -0,0 +1,116 @@
+use anyhow::Result;
+use chrono::{DateTime, Utc};
+use macro_uuid::Uuid;
+use model_owner::Owner;
+use serde_json::Value;
+use sqlx::PgPool;
+
+use crate::domain::ports::RoutineTemplateRepo;
+use crate::domain::templates::{RoutineTemplate, TemplateSnapshot};
+
+#[cfg(test)]
+mod test;
+
+/// PostgreSQL store for templates shared from routines. A template is deleted
+/// with its source routine.
+pub struct PgRoutineTemplateRepo {
+ pool: PgPool,
+}
+
+impl PgRoutineTemplateRepo {
+ pub fn new(pool: PgPool) -> Self {
+ Self { pool }
+ }
+}
+
+struct TemplateRow {
+ action_id: Uuid,
+ owner: String,
+ name: String,
+ description: String,
+ trigger_config: Value,
+ task: Value,
+ variables: Value,
+ active_count: i64,
+ created_at: DateTime<Utc>,
+ updated_at: DateTime<Utc>,
+}
+
+impl TryFrom<TemplateRow> for RoutineTemplate {
+ type Error = anyhow::Error;
+
+ fn try_from(row: TemplateRow) -> Result<Self> {
+ Ok(Self {
+ id: row.action_id,
+ author: Owner::from_principal_str(&row.owner)?,
+ name: row.name,
+ description: row.description,
+ trigger: serde_json::from_value(row.trigger_config)?,
+ task: row.task,
+ variables: serde_json::from_value(row.variables)?,
+ active_count: u32::try_from(row.active_count)?,
+ created_at: row.created_at,
+ updated_at: row.updated_at,
+ })
+ }
+}
+
+impl RoutineTemplateRepo for PgRoutineTemplateRepo {
+ async fn upsert_template(&self, snapshot: TemplateSnapshot) -> Result<RoutineTemplate> {
+ sqlx::query!(
+ r#"
+ INSERT INTO scheduled_action_template
+ (action_id, name, description, trigger_config, task, variables)
+ VALUES ($1, $2, $3, $4, $5, $6)
+ ON CONFLICT (action_id) DO UPDATE
+ SET name = EXCLUDED.name,
+ description = EXCLUDED.description,
+ trigger_config = EXCLUDED.trigger_config,
+ task = EXCLUDED.task,
+ variables = EXCLUDED.variables,
+ updated_at = now()
+ "#,
+ snapshot.action_id,
+ snapshot.name,
+ snapshot.description,
+ serde_json::to_value(&snapshot.trigger)?,
+ snapshot.task,
+ serde_json::to_value(&snapshot.variables)?,
+ )
+ .execute(&self.pool)
+ .await?;
+ self.get_template(&snapshot.action_id)
+ .await?
+ .ok_or_else(|| anyhow::anyhow!("template disappeared after it was shared"))
+ }
+
+ async fn delete_template(&self, id: &Uuid) -> Result<()> {
+ sqlx::query!(
+ "DELETE FROM scheduled_action_template WHERE action_id = $1",
+ *id,
+ )
+ .execute(&self.pool)
+ .await?;
+ Ok(())
+ }
+
+ async fn get_template(&self, id: &Uuid) -> Result<Option<RoutineTemplate>> {
+ sqlx::query_as!(
+ TemplateRow,
+ r#"
+ SELECT t.action_id, a.owner, t.name, t.description, t.trigger_config, t.task,
+ t.variables, t.created_at, t.updated_at,
+ (SELECT count(*) FROM scheduled_action s WHERE s.template_id = t.action_id)
+ AS "active_count!"
+ FROM scheduled_action_template t
+ JOIN scheduled_action a ON a.id = t.action_id
+ WHERE t.action_id = $1
+ "#,
+ *id,
+ )
+ .fetch_optional(&self.pool)
+ .await?
+ .map(RoutineTemplate::try_from)
+ .transpose()
+ }
+}
diff --git a/crates/scheduled_action/src/outbound/pg_routine_template_repo/test.rs b/crates/scheduled_action/src/outbound/pg_routine_template_repo/test.rs
new file mode 100644
index 0000000000..08c5c78f7c
--- /dev/null
+++ b/crates/scheduled_action/src/outbound/pg_routine_template_repo/test.rs
@@ -0,0 +1,105 @@
+use macro_db_migrator::MACRO_DB_MIGRATIONS;
+use serde_json::json;
+
+use super::*;
+use crate::domain::ports::ScheduledActionRepo;
+use crate::domain::templates::{TemplateVariable, VariableFill};
+use crate::outbound::pg_scheduled_action_repo::test::{
+ USER_A, USER_B, insert_user, sample_action, test_repo, user_owner,
+};
+
+fn snapshot(
+ action: &crate::domain::models::ScheduledAction,
+ description: &str,
+) -> TemplateSnapshot {
+ TemplateSnapshot {
+ action_id: action.id.expect("created action has an id"),
+ name: action.name.clone(),
+ description: description.into(),
+ trigger: action.trigger.clone(),
+ task: json!({"model": "model", "prompt": "summarize", "user_prompt": "summarize"}),
+ variables: vec![TemplateVariable::Item {
+ id: "channel-1".into(),
+ block_name: "channel".into(),
+ label: "customer-success".into(),
+ fill: VariableFill::Shared,
+ }],
+ }
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn resharing_replaces_the_snapshot_and_counts_activations(pool: PgPool) {
+ insert_user(&pool, USER_A).await;
+ insert_user(&pool, USER_B).await;
+ let actions = test_repo(pool.clone());
+ let templates = PgRoutineTemplateRepo::new(pool);
+ let source = actions
+ .create_action(sample_action(user_owner(USER_A), "digest"))
+ .await
+ .unwrap();
+ let id = source.id.unwrap();
+
+ let first = templates
+ .upsert_template(snapshot(&source, "first"))
+ .await
+ .unwrap();
+ assert_eq!(first.author, user_owner(USER_A));
+ assert_eq!(first.active_count, 0);
+
+ let mut activated = sample_action(user_owner(USER_B), "my digest");
+ activated.template_id = Some(id);
+ let activated = actions.create_action(activated).await.unwrap();
+ assert_eq!(activated.template_id, Some(id));
+ let reread = actions
+ .get_action(&activated.id.unwrap())
+ .await
+ .unwrap()
+ .unwrap();
+ assert_eq!(reread.template_id, Some(id));
+
+ let second = templates
+ .upsert_template(snapshot(&source, "second"))
+ .await
+ .unwrap();
+ assert_eq!(second.description, "second");
+ assert_eq!(second.created_at, first.created_at);
+ assert_eq!(second.active_count, 1);
+ assert_eq!(second.variables, first.variables);
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn stopping_or_deleting_the_source_removes_the_template_only(pool: PgPool) {
+ insert_user(&pool, USER_A).await;
+ insert_user(&pool, USER_B).await;
+ let actions = test_repo(pool.clone());
+ let templates = PgRoutineTemplateRepo::new(pool);
+ let source = actions
+ .create_action(sample_action(user_owner(USER_A), "digest"))
+ .await
+ .unwrap();
+ let id = source.id.unwrap();
+ templates
+ .upsert_template(snapshot(&source, "shared"))
+ .await
+ .unwrap();
+ let mut activated = sample_action(user_owner(USER_B), "my digest");
+ activated.template_id = Some(id);
+ let activated = actions.create_action(activated).await.unwrap();
+
+ templates.delete_template(&id).await.unwrap();
+ templates.delete_template(&id).await.unwrap();
+ assert!(templates.get_template(&id).await.unwrap().is_none());
+
+ templates
+ .upsert_template(snapshot(&source, "shared again"))
+ .await
+ .unwrap();
+ actions.delete_action(&id).await.unwrap();
+ assert!(templates.get_template(&id).await.unwrap().is_none());
+ let kept = actions
+ .get_action(&activated.id.unwrap())
+ .await
+ .unwrap()
+ .expect("activated routines outlive their template");
+ assert_eq!(kept.template_id, Some(id));
+}
diff --git a/crates/scheduled_action/src/outbound/pg_scheduled_action_repo.rs b/crates/scheduled_action/src/outbound/pg_scheduled_action_repo.rs
index 21eb9255d0..73e7fcc160 100644
--- a/crates/scheduled_action/src/outbound/pg_scheduled_action_repo.rs
+++ b/crates/scheduled_action/src/outbound/pg_scheduled_action_repo.rs
@@ -23,7 +23,7 @@ use crate::domain::models::{
use crate::domain::ports::ScheduledActionRepo;
#[cfg(test)]
-mod test;
+pub(crate) mod test;
/// PostgreSQL scheduled-action store.
///
@@ -79,6 +79,7 @@ struct ActionRow {
configuration_revision: i64,
event_activated_at: Option<DateTime<Utc>>,
run_visibility: String,
+ template_id: Option<Uuid>,
}
impl TryFrom<ActionRow> for ScheduledAction {
@@ -120,6 +121,7 @@ impl TryFrom<ActionRow> for ScheduledAction {
})?,
configuration_revision: ConfigurationRevision::try_from(row.configuration_revision)?,
event_activated_at: row.event_activated_at,
+ template_id: row.template_id,
})
}
}
@@ -179,11 +181,11 @@ impl<B: BotFacts + 'static> ScheduledActionRepo for PgScheduledActionRepo<B> {
INSERT INTO scheduled_action
(id, owner, name, schedule, kind, timezone, task, next_run_at, enabled,
trigger_type, event_filters, configuration_revision, event_activated_at, trigger_config,
- run_visibility)
- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15)
+ run_visibility, template_id)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16)
RETURNING id, owner, name, schedule, kind, timezone, task, claimed, created_at,
updated_at, next_run_at, enabled, trigger_type, event_filters,
- configuration_revision, event_activated_at, trigger_config, run_visibility
+ configuration_revision, event_activated_at, trigger_config, run_visibility, template_id
"#,
id,
owner,
@@ -200,6 +202,7 @@ impl<B: BotFacts + 'static> ScheduledActionRepo for PgScheduledActionRepo<B> {
action.event_activated_at,
trigger.trigger_config,
<&str>::from(action.run_visibility),
+ action.template_id,
)
.fetch_one(&mut *tx)
.await?;
@@ -235,7 +238,7 @@ impl<B: BotFacts + 'static> ScheduledActionRepo for PgScheduledActionRepo<B> {
r#"
SELECT id, owner, name, schedule, kind, timezone, task, claimed, created_at,
updated_at, next_run_at, enabled, trigger_type, event_filters,
- configuration_revision, event_activated_at, trigger_config, run_visibility
+ configuration_revision, event_activated_at, trigger_config, run_visibility, template_id
FROM scheduled_action
WHERE owner = $1
"#,
@@ -252,7 +255,7 @@ impl<B: BotFacts + 'static> ScheduledActionRepo for PgScheduledActionRepo<B> {
r#"
SELECT id, owner, name, schedule, kind, timezone, task, claimed, created_at,
updated_at, next_run_at, enabled, trigger_type, event_filters, trigger_config,
- configuration_revision, event_activated_at, run_visibility
+ configuration_revision, event_activated_at, run_visibility, template_id
FROM scheduled_action
WHERE id = ANY($1)
"#,
@@ -269,7 +272,7 @@ impl<B: BotFacts + 'static> ScheduledActionRepo for PgScheduledActionRepo<B> {
r#"
SELECT id, owner, name, schedule, kind, timezone, task, claimed, created_at,
updated_at, next_run_at, enabled, trigger_type, event_filters,
- configuration_revision, event_activated_at, trigger_config, run_visibility
+ configuration_revision, event_activated_at, trigger_config, run_visibility, template_id
FROM scheduled_action
WHERE id = $1
"#,
@@ -288,7 +291,7 @@ impl<B: BotFacts + 'static> ScheduledActionRepo for PgScheduledActionRepo<B> {
r#"
SELECT id, owner, name, schedule, kind, timezone, task, claimed, created_at,
updated_at, next_run_at, enabled, trigger_type, event_filters,
- configuration_revision, event_activated_at, trigger_config, run_visibility
+ configuration_revision, event_activated_at, trigger_config, run_visibility, template_id
FROM scheduled_action
WHERE enabled AND trigger_type IN ('cron', 'multiple') AND next_run_at IS NOT NULL
AND (claimed IS NULL OR claimed < $1)
@@ -343,7 +346,7 @@ impl<B: BotFacts + 'static> ScheduledActionRepo for PgScheduledActionRepo<B> {
)
RETURNING id, owner, name, schedule, kind, timezone, task, claimed, created_at,
updated_at, next_run_at, enabled, trigger_type, event_filters,
- configuration_revision, event_activated_at, trigger_config, run_visibility
+ configuration_revision, event_activated_at, trigger_config, run_visibility, template_id
"#,
action.name,
trigger.schedule,
diff --git a/crates/scheduled_action/src/outbound/pg_scheduled_action_repo/test.rs b/crates/scheduled_action/src/outbound/pg_scheduled_action_repo/test.rs
index 7431c282f8..e86b32f2cf 100644
--- a/crates/scheduled_action/src/outbound/pg_scheduled_action_repo/test.rs
+++ b/crates/scheduled_action/src/outbound/pg_scheduled_action_repo/test.rs
@@ -18,20 +18,20 @@ use crate::domain::models::{
};
use crate::domain::ports::ScheduledActionRepo;
-const USER_A: &str = "macro|[email protected]";
-const USER_B: &str = "macro|[email protected]";
+pub(crate) const USER_A: &str = "macro|[email protected]";
+pub(crate) const USER_B: &str = "macro|[email protected]";
const DAILY_9AM: &str = "0 0 9 * * *";
fn user(id: &'static str) -> MacroUserIdStr<'static> {
MacroUserIdStr::parse_from_str(id).expect("valid user id")
}
-fn user_owner(id: &'static str) -> Owner {
+pub(crate) fn user_owner(id: &'static str) -> Owner {
Owner::User(user(id))
}
#[derive(Clone)]
-struct NoBots;
+pub(crate) struct NoBots;
impl BotFacts for NoBots {
async fn sponsor(&self, _bot: bot_id::BotId) -> EntityRegistryResult<Option<Owner>> {
@@ -48,7 +48,7 @@ impl BotFacts for SponsoredBy {
}
}
-fn test_repo(pool: PgPool) -> PgScheduledActionRepo<NoBots> {
+pub(crate) fn test_repo(pool: PgPool) -> PgScheduledActionRepo<NoBots> {
PgScheduledActionRepo::new(
pool,
OwnedEntityRegistrar::new(OwnerGrantPolicy::new(NoBots)),
@@ -74,7 +74,7 @@ async fn direct_grants(pool: &PgPool, id: Uuid) -> Vec<(String, String, String)>
.collect()
}
-async fn insert_user(pool: &PgPool, id: &str) {
+pub(crate) async fn insert_user(pool: &PgPool, id: &str) {
let macro_user_id = macro_uuid::generate_uuid_v7();
sqlx::query!(
r#"INSERT INTO macro_user (id, username, email, stripe_customer_id) VALUES ($1, $2, $2, $2)"#,
@@ -94,7 +94,7 @@ async fn insert_user(pool: &PgPool, id: &str) {
.expect("user should insert");
}
-fn sample_action(owner: Owner, name: &str) -> ScheduledAction {
+pub(crate) fn sample_action(owner: Owner, name: &str) -> ScheduledAction {
let now = Utc::now();
let schedule = Schedule::from_cron(DAILY_9AM.to_string()).expect("valid cron");
let timezone = chrono_tz::UTC;
@@ -116,6 +116,7 @@ fn sample_action(owner: Owner, name: &str) -> ScheduledAction {
next_run_at: Some(next_run_at),
enabled: true,
run_visibility: RunVisibility::Unlisted,
+ template_id: None,
}
}
diff --git a/crates/scheduled_action/src/outbound/tokio_dispatcher/test.rs b/crates/scheduled_action/src/outbound/tokio_dispatcher/test.rs
index 2e5bf366e2..3e074cb046 100644
--- a/crates/scheduled_action/src/outbound/tokio_dispatcher/test.rs
+++ b/crates/scheduled_action/src/outbound/tokio_dispatcher/test.rs
@@ -27,6 +27,7 @@ fn only_enabled_cron_actions_get_a_timer() {
next_run_at: Some(now),
enabled: true,
run_visibility: RunVisibility::Unlisted,
+ template_id: None,
};
assert!(action_sleep(id, &action, 0).is_some());
action.trigger = serde_json::from_value(json!({"type":"multiple", "triggers":[
diff --git a/crates/scheduled_action/src/swagger.rs b/crates/scheduled_action/src/swagger.rs
index c0b4af7937..49b2c7acac 100644
--- a/crates/scheduled_action/src/swagger.rs
+++ b/crates/scheduled_action/src/swagger.rs
@@ -9,6 +9,13 @@ use crate::inbound::axum_router::{
__path_health, __path_list_actions, __path_list_history, __path_set_action_enabled,
__path_update_action, ScheduledActionResponse, SetScheduledActionEnabled,
};
+#[expect(
+ unused_imports,
+ reason = "utoipa path macros require these generated symbols in scope"
+)]
+use crate::inbound::template_router::{
+ __path_activate_template, __path_get_template, __path_share_template, __path_unshare_template,
+};
use crate::domain::event_trigger::{ActionTrigger, EventFilter, EventFilters, EventName};
use crate::domain::models::{
@@ -37,6 +44,10 @@ use model::response::EmptyResponse;
crate::inbound::axum_router::delete_action,
crate::inbound::axum_router::execute_action,
crate::inbound::axum_router::list_history,
+ crate::inbound::template_router::share_template,
+ crate::inbound::template_router::get_template,
+ crate::inbound::template_router::unshare_template,
+ crate::inbound::template_router::activate_template,
),
components(
schemas(
@@ -67,6 +78,10 @@ use model::response::EmptyResponse;
ActionExecutionRecord,
ScheduledActionUpdate,
EmptyResponse,
+ crate::domain::templates::RoutineTemplate,
+ crate::domain::templates::ShareRoutineTemplate,
+ crate::domain::templates::TemplateVariable,
+ crate::domain::templates::VariableFill,
),
),
tags(
diff --git a/docs/agent-guide/navigation.md b/docs/agent-guide/navigation.md
index 5f35b3fbff..0b33bc2942 100644
--- a/docs/agent-guide/navigation.md
+++ b/docs/agent-guide/navigation.md
@@ -1106,11 +1106,46 @@ An `m-document-mention` with `blockName: "routine"`, the returned routine ID,
and the saved name renders as a clickable mention in an agent reply. Once the
routine is deleted the mention reads `Deleted` and clicking it shows a card
instead of opening the routine. Routines do not appear in the mention menu.
-Anyone signed in with the link can view its settings, instructions, and
-triggers. Only the owner can edit, enable, run,
-duplicate, delete, or view run history; other users do not see those controls.
+Only the owner sees a routine's editor and can edit, enable, run, duplicate,
+delete, or view run history. Anyone else who opens a routine link sees its
+template when the owner shared one, and otherwise "isn't shared as a template".
Run conversations keep their own permissions.
+### Routine templates
+
+A routine runs as its owner, so it is shared as a template, never directly.
+The three-dot menu's **Share as template** opens **Share: name**. It explains
+what people get, takes a **Description**, and lists **What changes for each
+person**: every mention in the instructions plus the schedules' time zone, each
+with tabs. People can be **The person activating** (the owner's own mention
+starts here), **Same for everyone**, or **They choose**; items are **Same for
+everyone** or **They choose**; the time zone is **Their time zone** or **Keep** the owner's
+zone. **Share template** publishes a snapshot of the saved routine;
+**Update template** re-snapshots it. Once shared, the dialog shows how many
+routines were activated from it, a channel-or-people picker with **Send** that
+posts the routine mention, **Copy template link** (the routine's own URL), and
+**Stop sharing**, which hides the template while activated routines keep
+running.
+
+Opening a shared routine someone else owns shows the template laid out like a
+routine's Overview: **Activate for me** at the right of the top bar, then the
+name, description, **Template by author**, activation count, triggers (marked
+"Doesn't run until you activate it"), read-only instructions, and
+**References**: dashed chips fill in as the viewer, amber ones they can't open. **Activate for me** opens **Activate for me: name**: the routine
+as it will run on the left, and on the right **Your call · N left** for each
+reference they can't open or must choose (**Keep it** / **Leave out**),
+**Filled in as you**, and **Works for you as is**. **Activate** stays disabled
+until every reference is decided, then creates the viewer's own enabled
+routine and opens it. A left-out reference becomes plain text. That routine
+behaves like any other, with a **Created from template ↗** chip beside its
+model chip that opens the template.
+
+A channel message that mentions a shared routine shows a template card under
+its text: name, author, description, triggers, activation count, **View
+template**, and **Activate for me** (hidden for the author). Mentions of
+routines that aren't shared show no card. On phones both dialogs open as
+bottom sheets.
+
**Run History** shows outcome, duration, and firing time. History loads fifty
rows at a time; **Load more runs** reveals older records. Accessible run rows
open the agent session created by that run. Selecting a model uses the same
diff --git a/packages/sdk-docs/reference/generated/scheduled-action/types.gen/README.md b/packages/sdk-docs/reference/generated/scheduled-action/types.gen/README.md
index 76089e12e6..8d16caa64b 100644
--- a/packages/sdk-docs/reference/generated/scheduled-action/types.gen/README.md
+++ b/packages/sdk-docs/reference/generated/scheduled-action/types.gen/README.md
@@ -7,6 +7,11 @@
- [ActionExecutionRecord](type-aliases/ActionExecutionRecord.md)
- [ActionKind](type-aliases/ActionKind.md)
- [ActionTrigger](type-aliases/ActionTrigger.md)
+- [ActivateScheduledActionTemplateData](type-aliases/ActivateScheduledActionTemplateData.md)
+- [ActivateScheduledActionTemplateError](type-aliases/ActivateScheduledActionTemplateError.md)
+- [ActivateScheduledActionTemplateErrors](type-aliases/ActivateScheduledActionTemplateErrors.md)
+- [ActivateScheduledActionTemplateResponse](type-aliases/ActivateScheduledActionTemplateResponse.md)
+- [ActivateScheduledActionTemplateResponses](type-aliases/ActivateScheduledActionTemplateResponses.md)
- [AgentMcpServer](type-aliases/AgentMcpServer.md)
- [AgentTask](type-aliases/AgentTask.md)
- [AgentTaskAgent](type-aliases/AgentTaskAgent.md)
@@ -41,6 +46,11 @@
- [GetScheduledActionErrors](type-aliases/GetScheduledActionErrors.md)
- [GetScheduledActionResponse](type-aliases/GetScheduledActionResponse.md)
- [GetScheduledActionResponses](type-aliases/GetScheduledActionResponses.md)
+- [GetScheduledActionTemplateData](type-aliases/GetScheduledActionTemplateData.md)
+- [GetScheduledActionTemplateError](type-aliases/GetScheduledActionTemplateError.md)
+- [GetScheduledActionTemplateErrors](type-aliases/GetScheduledActionTemplateErrors.md)
+- [GetScheduledActionTemplateResponse](type-aliases/GetScheduledActionTemplateResponse.md)
+- [GetScheduledActionTemplateResponses](type-aliases/GetScheduledActionTemplateResponses.md)
- [InProgressExecution](type-aliases/InProgressExecution.md)
- [LegacyActionConfiguration](type-aliases/LegacyActionConfiguration.md)
- [ListScheduledActionHistoryData](type-aliases/ListScheduledActionHistoryData.md)
@@ -54,6 +64,7 @@
- [ListScheduledActionsResponse](type-aliases/ListScheduledActionsResponse.md)
- [ListScheduledActionsResponses](type-aliases/ListScheduledActionsResponses.md)
- [RoutineModelId](type-aliases/RoutineModelId.md)
+- [RoutineTemplate](type-aliases/RoutineTemplate.md)
- [RoutineTrigger](type-aliases/RoutineTrigger.md)
- [RoutineTriggers](type-aliases/RoutineTriggers.md)
- [RunVisibility](type-aliases/RunVisibility.md)
@@ -70,9 +81,22 @@
- [SetScheduledActionEnabledErrors](type-aliases/SetScheduledActionEnabledErrors.md)
- [SetScheduledActionEnabledResponse](type-aliases/SetScheduledActionEnabledResponse.md)
- [SetScheduledActionEnabledResponses](type-aliases/SetScheduledActionEnabledResponses.md)
+- [ShareRoutineTemplate](type-aliases/ShareRoutineTemplate.md)
+- [ShareScheduledActionTemplateData](type-aliases/ShareScheduledActionTemplateData.md)
+- [ShareScheduledActionTemplateError](type-aliases/ShareScheduledActionTemplateError.md)
+- [ShareScheduledActionTemplateErrors](type-aliases/ShareScheduledActionTemplateErrors.md)
+- [ShareScheduledActionTemplateResponse](type-aliases/ShareScheduledActionTemplateResponse.md)
+- [ShareScheduledActionTemplateResponses](type-aliases/ShareScheduledActionTemplateResponses.md)
+- [TemplateVariable](type-aliases/TemplateVariable.md)
+- [UnshareScheduledActionTemplateData](type-aliases/UnshareScheduledActionTemplateData.md)
+- [UnshareScheduledActionTemplateError](type-aliases/UnshareScheduledActionTemplateError.md)
+- [UnshareScheduledActionTemplateErrors](type-aliases/UnshareScheduledActionTemplateErrors.md)
+- [UnshareScheduledActionTemplateResponse](type-aliases/UnshareScheduledActionTemplateResponse.md)
+- [UnshareScheduledActionTemplateResponses](type-aliases/UnshareScheduledActionTemplateResponses.md)
- [UpdateScheduledAction](type-aliases/UpdateScheduledAction.md)
- [UpdateScheduledActionData](type-aliases/UpdateScheduledActionData.md)
- [UpdateScheduledActionError](type-aliases/UpdateScheduledActionError.md)
- [UpdateScheduledActionErrors](type-aliases/UpdateScheduledActionErrors.md)
- [UpdateScheduledActionResponse](type-aliases/UpdateScheduledActionResponse.md)
- [UpdateScheduledActionResponses](type-aliases/UpdateScheduledActionResponses.md)
+- [VariableFill](type-aliases/VariableFill.md)
diff --git a/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/ActivateScheduledActionTemplateData.md b/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/ActivateScheduledActionTemplateData.md
new file mode 100644
index 0000000000..7058ffdb15
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/ActivateScheduledActionTemplateData.md
@@ -0,0 +1,13 @@
+# Type Alias: ActivateScheduledActionTemplateData
+
+> **ActivateScheduledActionTemplateData** = \{ `body`: [`CreateScheduledAction`](CreateScheduledAction.md); `path`: \{ `id`: `string`; \}; `query?`: `never`; `url`: `"/scheduled-actions/{id}/template/activate"`; \}
+
+## Properties
+
+| Property | Type | Description |
+| ------ | ------ | ------ |
+| <a id="property-body"></a> `body` | [`CreateScheduledAction`](CreateScheduledAction.md) | - |
+| <a id="property-path"></a> `path` | \{ `id`: `string`; \} | - |
+| `path.id` | `string` | ID of the shared routine |
+| <a id="property-query"></a> `query?` | `never` | - |
+| <a id="property-url"></a> `url` | `"/scheduled-actions/{id}/template/activate"` | - |
diff --git a/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/ActivateScheduledActionTemplateError.md b/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/ActivateScheduledActionTemplateError.md
new file mode 100644
index 0000000000..d5ceace5aa
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/ActivateScheduledActionTemplateError.md
@@ -0,0 +1,3 @@
+# Type Alias: ActivateScheduledActionTemplateError
+
+> **ActivateScheduledActionTemplateError** = [`ActivateScheduledActionTemplateErrors`](ActivateScheduledActionTemplateErrors.md)\[keyof [`ActivateScheduledActionTemplateErrors`](ActivateScheduledActionTemplateErrors.md)\]
diff --git a/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/ActivateScheduledActionTemplateErrors.md b/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/ActivateScheduledActionTemplateErrors.md
new file mode 100644
index 0000000000..4f94d2316a
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/ActivateScheduledActionTemplateErrors.md
@@ -0,0 +1,13 @@
+# Type Alias: ActivateScheduledActionTemplateErrors
+
+> **ActivateScheduledActionTemplateErrors** = \{ `400`: `string`; `401`: `string`; `403`: `string`; `404`: `string`; `500`: `string`; \}
+
+## Properties
+
+| Property | Type | Description |
+| ------ | ------ | ------ |
+| <a id="property-400"></a> `400` | `string` | - |
+| <a id="property-401"></a> `401` | `string` | - |
+| <a id="property-403"></a> `403` | `string` | - |
+| <a id="property-404"></a> `404` | `string` | The routine is not shared |
+| <a id="property-500"></a> `500` | `string` | - |
diff --git a/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/ActivateScheduledActionTemplateResponse.md b/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/ActivateScheduledActionTemplateResponse.md
new file mode 100644
index 0000000000..5d7910ced1
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/ActivateScheduledActionTemplateResponse.md
@@ -0,0 +1,3 @@
+# Type Alias: ActivateScheduledActionTemplateResponse
+
+> **ActivateScheduledActionTemplateResponse** = [`ActivateScheduledActionTemplateResponses`](ActivateScheduledActionTemplateResponses.md)\[keyof [`ActivateScheduledActionTemplateResponses`](ActivateScheduledActionTemplateResponses.md)\]
diff --git a/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/ActivateScheduledActionTemplateResponses.md b/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/ActivateScheduledActionTemplateResponses.md
new file mode 100644
index 0000000000..f9383a14d2
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/ActivateScheduledActionTemplateResponses.md
@@ -0,0 +1,9 @@
+# Type Alias: ActivateScheduledActionTemplateResponses
+
+> **ActivateScheduledActionTemplateResponses** = \{ `201`: [`ScheduledActionResponse`](ScheduledActionResponse.md); \}
+
+## Properties
+
+| Property | Type |
+| ------ | ------ |
+| <a id="property-201"></a> `201` | [`ScheduledActionResponse`](ScheduledActionResponse.md) |
diff --git a/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/GetScheduledActionTemplateData.md b/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/GetScheduledActionTemplateData.md
new file mode 100644
index 0000000000..a7ec19377f
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/GetScheduledActionTemplateData.md
@@ -0,0 +1,13 @@
+# Type Alias: GetScheduledActionTemplateData
+
+> **GetScheduledActionTemplateData** = \{ `body?`: `never`; `path`: \{ `id`: `string`; \}; `query?`: `never`; `url`: `"/scheduled-actions/{id}/template"`; \}
+
+## Properties
+
+| Property | Type | Description |
+| ------ | ------ | ------ |
+| <a id="property-body"></a> `body?` | `never` | - |
+| <a id="property-path"></a> `path` | \{ `id`: `string`; \} | - |
+| `path.id` | `string` | ID of the shared routine |
+| <a id="property-query"></a> `query?` | `never` | - |
+| <a id="property-url"></a> `url` | `"/scheduled-actions/{id}/template"` | - |
diff --git a/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/GetScheduledActionTemplateError.md b/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/GetScheduledActionTemplateError.md
new file mode 100644
index 0000000000..e81b82f7aa
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/GetScheduledActionTemplateError.md
@@ -0,0 +1,3 @@
+# Type Alias: GetScheduledActionTemplateError
+
+> **GetScheduledActionTemplateError** = [`GetScheduledActionTemplateErrors`](GetScheduledActionTemplateErrors.md)\[keyof [`GetScheduledActionTemplateErrors`](GetScheduledActionTemplateErrors.md)\]
diff --git a/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/GetScheduledActionTemplateErrors.md b/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/GetScheduledActionTemplateErrors.md
new file mode 100644
index 0000000000..f2f25d7219
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/GetScheduledActionTemplateErrors.md
@@ -0,0 +1,11 @@
+# Type Alias: GetScheduledActionTemplateErrors
+
+> **GetScheduledActionTemplateErrors** = \{ `401`: `string`; `404`: `string`; `500`: `string`; \}
+
+## Properties
+
+| Property | Type | Description |
+| ------ | ------ | ------ |
+| <a id="property-401"></a> `401` | `string` | - |
+| <a id="property-404"></a> `404` | `string` | The routine is not shared |
+| <a id="property-500"></a> `500` | `string` | - |
diff --git a/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/GetScheduledActionTemplateResponse.md b/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/GetScheduledActionTemplateResponse.md
new file mode 100644
index 0000000000..b3f44be2f1
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/GetScheduledActionTemplateResponse.md
@@ -0,0 +1,3 @@
+# Type Alias: GetScheduledActionTemplateResponse
+
+> **GetScheduledActionTemplateResponse** = [`GetScheduledActionTemplateResponses`](GetScheduledActionTemplateResponses.md)\[keyof [`GetScheduledActionTemplateResponses`](GetScheduledActionTemplateResponses.md)\]
diff --git a/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/GetScheduledActionTemplateResponses.md b/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/GetScheduledActionTemplateResponses.md
new file mode 100644
index 0000000000..8bbe9e6aa2
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/GetScheduledActionTemplateResponses.md
@@ -0,0 +1,9 @@
+# Type Alias: GetScheduledActionTemplateResponses
+
+> **GetScheduledActionTemplateResponses** = \{ `200`: [`RoutineTemplate`](RoutineTemplate.md); \}
+
+## Properties
+
+| Property | Type |
+| ------ | ------ |
+| <a id="property-200"></a> `200` | [`RoutineTemplate`](RoutineTemplate.md) |
diff --git a/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/RoutineTemplate.md b/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/RoutineTemplate.md
new file mode 100644
index 0000000000..b7cfe535d5
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/RoutineTemplate.md
@@ -0,0 +1,20 @@
+# Type Alias: RoutineTemplate
+
+> **RoutineTemplate** = \{ `active_count`: `number`; `author`: `string`; `created_at`: `string`; `description`: `string`; `id`: `string`; `name`: `string`; `task`: \{\[`key`: `string`\]: `unknown`; \}; `trigger`: [`ActionTrigger`](ActionTrigger.md); `updated_at`: `string`; `variables`: [`TemplateVariable`](TemplateVariable.md)[]; \}
+
+A shared routine's snapshot, readable by any signed-in user with its ID.
+
+## Properties
+
+| Property | Type | Description |
+| ------ | ------ | ------ |
+| <a id="property-active_count"></a> `active_count` | `number` | Routines activated from this template, including stopped ones. |
+| <a id="property-author"></a> `author` | `string` | Who shared it: the source routine's owner. |
+| <a id="property-created_at"></a> `created_at` | `string` | - |
+| <a id="property-description"></a> `description` | `string` | - |
+| <a id="property-id"></a> `id` | `string` | The routine it was shared from. |
+| <a id="property-name"></a> `name` | `string` | - |
+| <a id="property-task"></a> `task` | \{\[`key`: `string`\]: `unknown`; \} | - |
+| <a id="property-trigger"></a> `trigger` | [`ActionTrigger`](ActionTrigger.md) | - |
+| <a id="property-updated_at"></a> `updated_at` | `string` | - |
+| <a id="property-variables"></a> `variables` | [`TemplateVariable`](TemplateVariable.md)[] | - |
diff --git a/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/ScheduledAction.md b/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/ScheduledAction.md
index 887c726269..e9fb2c4bc4 100644
--- a/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/ScheduledAction.md
+++ b/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/ScheduledAction.md
@@ -1,6 +1,6 @@
# Type Alias: ScheduledAction
-> **ScheduledAction** = \{ `claimed?`: `string` \| `null`; `configuration_revision`: `number`; `created_at`: `string`; `enabled`: `boolean`; `event_activated_at?`: `string` \| `null`; `id?`: `string` \| `null`; `kind`: [`ActionKind`](ActionKind.md); `name`: `string`; `next_run_at?`: `string` \| `null`; `owner`: `string`; `run_visibility`: [`RunVisibility`](RunVisibility.md); `task`: \{\[`key`: `string`\]: `unknown`; \}; `trigger`: [`ActionTrigger`](ActionTrigger.md); `updated_at`: `string`; \}
+> **ScheduledAction** = \{ `claimed?`: `string` \| `null`; `configuration_revision`: `number`; `created_at`: `string`; `enabled`: `boolean`; `event_activated_at?`: `string` \| `null`; `id?`: `string` \| `null`; `kind`: [`ActionKind`](ActionKind.md); `name`: `string`; `next_run_at?`: `string` \| `null`; `owner`: `string`; `run_visibility`: [`RunVisibility`](RunVisibility.md); `task`: \{\[`key`: `string`\]: `unknown`; \}; `template_id?`: `string` \| `null`; `trigger`: [`ActionTrigger`](ActionTrigger.md); `updated_at`: `string`; \}
## Properties
@@ -18,5 +18,6 @@
| <a id="property-owner"></a> `owner` | `string` | Who the action belongs to. Every action is user-owned today, but the type no longer says so: the principal string on the wire and in the `owner` column is the same, and a bot- or team-owned row decodes rather than failing to parse. |
| <a id="property-run_visibility"></a> `run_visibility` | [`RunVisibility`](RunVisibility.md) | Whether the action's runs are listed in Home and the Agents list. |
| <a id="property-task"></a> `task` | \{\[`key`: `string`\]: `unknown`; \} | - |
+| <a id="property-template_id"></a> `template_id?` | `string` \| `null` | The shared template this routine was activated from, if any. |
| <a id="property-trigger"></a> `trigger` | [`ActionTrigger`](ActionTrigger.md) | - |
| <a id="property-updated_at"></a> `updated_at` | `string` | - |
diff --git a/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/ShareRoutineTemplate.md b/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/ShareRoutineTemplate.md
new file mode 100644
index 0000000000..636ba5e647
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/ShareRoutineTemplate.md
@@ -0,0 +1,12 @@
+# Type Alias: ShareRoutineTemplate
+
+> **ShareRoutineTemplate** = \{ `description`: `string`; `variables`: [`TemplateVariable`](TemplateVariable.md)[]; \}
+
+What the owner supplies when sharing; the rest is snapshotted from the routine.
+
+## Properties
+
+| Property | Type |
+| ------ | ------ |
+| <a id="property-description"></a> `description` | `string` |
+| <a id="property-variables"></a> `variables` | [`TemplateVariable`](TemplateVariable.md)[] |
diff --git a/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/ShareScheduledActionTemplateData.md b/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/ShareScheduledActionTemplateData.md
new file mode 100644
index 0000000000..33deaa704b
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/ShareScheduledActionTemplateData.md
@@ -0,0 +1,13 @@
+# Type Alias: ShareScheduledActionTemplateData
+
+> **ShareScheduledActionTemplateData** = \{ `body`: [`ShareRoutineTemplate`](ShareRoutineTemplate.md); `path`: \{ `id`: `string`; \}; `query?`: `never`; `url`: `"/scheduled-actions/{id}/template"`; \}
+
+## Properties
+
+| Property | Type | Description |
+| ------ | ------ | ------ |
+| <a id="property-body"></a> `body` | [`ShareRoutineTemplate`](ShareRoutineTemplate.md) | - |
+| <a id="property-path"></a> `path` | \{ `id`: `string`; \} | - |
+| `path.id` | `string` | ID of the routine to share |
+| <a id="property-query"></a> `query?` | `never` | - |
+| <a id="property-url"></a> `url` | `"/scheduled-actions/{id}/template"` | - |
diff --git a/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/ShareScheduledActionTemplateError.md b/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/ShareScheduledActionTemplateError.md
new file mode 100644
index 0000000000..aa3f8d719d
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/ShareScheduledActionTemplateError.md
@@ -0,0 +1,3 @@
+# Type Alias: ShareScheduledActionTemplateError
+
+> **ShareScheduledActionTemplateError** = [`ShareScheduledActionTemplateErrors`](ShareScheduledActionTemplateErrors.md)\[keyof [`ShareScheduledActionTemplateErrors`](ShareScheduledActionTemplateErrors.md)\]
diff --git a/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/ShareScheduledActionTemplateErrors.md b/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/ShareScheduledActionTemplateErrors.md
new file mode 100644
index 0000000000..0fe0963fad
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/ShareScheduledActionTemplateErrors.md
@@ -0,0 +1,12 @@
+# Type Alias: ShareScheduledActionTemplateErrors
+
+> **ShareScheduledActionTemplateErrors** = \{ `400`: `string`; `401`: `string`; `404`: `string`; `500`: `string`; \}
+
+## Properties
+
+| Property | Type |
+| ------ | ------ |
+| <a id="property-400"></a> `400` | `string` |
+| <a id="property-401"></a> `401` | `string` |
+| <a id="property-404"></a> `404` | `string` |
+| <a id="property-500"></a> `500` | `string` |
diff --git a/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/ShareScheduledActionTemplateResponse.md b/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/ShareScheduledActionTemplateResponse.md
new file mode 100644
index 0000000000..4bd11e032b
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/ShareScheduledActionTemplateResponse.md
@@ -0,0 +1,3 @@
+# Type Alias: ShareScheduledActionTemplateResponse
+
+> **ShareScheduledActionTemplateResponse** = [`ShareScheduledActionTemplateResponses`](ShareScheduledActionTemplateResponses.md)\[keyof [`ShareScheduledActionTemplateResponses`](ShareScheduledActionTemplateResponses.md)\]
diff --git a/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/ShareScheduledActionTemplateResponses.md b/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/ShareScheduledActionTemplateResponses.md
new file mode 100644
index 0000000000..f252f3749a
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/ShareScheduledActionTemplateResponses.md
@@ -0,0 +1,9 @@
+# Type Alias: ShareScheduledActionTemplateResponses
+
+> **ShareScheduledActionTemplateResponses** = \{ `200`: [`RoutineTemplate`](RoutineTemplate.md); \}
+
+## Properties
+
+| Property | Type |
+| ------ | ------ |
+| <a id="property-200"></a> `200` | [`RoutineTemplate`](RoutineTemplate.md) |
diff --git a/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/TemplateVariable.md b/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/TemplateVariable.md
new file mode 100644
index 0000000000..7c0d68575f
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/TemplateVariable.md
@@ -0,0 +1,31 @@
+# Type Alias: TemplateVariable
+
+> **TemplateVariable** = \{ `fill`: [`VariableFill`](VariableFill.md); `id`: `string`; `kind`: `"user"`; `label`: `string`; \} \| \{ `block_name`: `string`; `fill`: [`VariableFill`](VariableFill.md); `id`: `string`; `kind`: `"item"`; `label`: `string`; \} \| \{ `fill`: [`VariableFill`](VariableFill.md); `kind`: `"time_zone"`; `timezone`: `string`; \}
+
+A user-specific part of a shared routine.
+
+## Union Members
+
+### Type Literal
+
+\{ `fill`: [`VariableFill`](VariableFill.md); `id`: `string`; `kind`: `"user"`; `label`: `string`; \}
+
+***
+
+### Type Literal
+
+\{ `block_name`: `string`; `fill`: [`VariableFill`](VariableFill.md); `id`: `string`; `kind`: `"item"`; `label`: `string`; \}
+
+| Name | Type | Description |
+| ------ | ------ | ------ |
+| `block_name` | `string` | The mention's block name, such as `channel` or `md`. |
+| `fill` | [`VariableFill`](VariableFill.md) | - |
+| `id` | `string` | - |
+| `kind` | `"item"` | - |
+| `label` | `string` | - |
+
+***
+
+### Type Literal
+
+\{ `fill`: [`VariableFill`](VariableFill.md); `kind`: `"time_zone"`; `timezone`: `string`; \}
diff --git a/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/UnshareScheduledActionTemplateData.md b/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/UnshareScheduledActionTemplateData.md
new file mode 100644
index 0000000000..cb822a4dfd
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/UnshareScheduledActionTemplateData.md
@@ -0,0 +1,13 @@
+# Type Alias: UnshareScheduledActionTemplateData
+
+> **UnshareScheduledActionTemplateData** = \{ `body?`: `never`; `path`: \{ `id`: `string`; \}; `query?`: `never`; `url`: `"/scheduled-actions/{id}/template"`; \}
+
+## Properties
+
+| Property | Type | Description |
+| ------ | ------ | ------ |
+| <a id="property-body"></a> `body?` | `never` | - |
+| <a id="property-path"></a> `path` | \{ `id`: `string`; \} | - |
+| `path.id` | `string` | ID of the shared routine |
+| <a id="property-query"></a> `query?` | `never` | - |
+| <a id="property-url"></a> `url` | `"/scheduled-actions/{id}/template"` | - |
diff --git a/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/UnshareScheduledActionTemplateError.md b/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/UnshareScheduledActionTemplateError.md
new file mode 100644
index 0000000000..6026977e05
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/UnshareScheduledActionTemplateError.md
@@ -0,0 +1,3 @@
+# Type Alias: UnshareScheduledActionTemplateError
+
+> **UnshareScheduledActionTemplateError** = [`UnshareScheduledActionTemplateErrors`](UnshareScheduledActionTemplateErrors.md)\[keyof [`UnshareScheduledActionTemplateErrors`](UnshareScheduledActionTemplateErrors.md)\]
diff --git a/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/UnshareScheduledActionTemplateErrors.md b/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/UnshareScheduledActionTemplateErrors.md
new file mode 100644
index 0000000000..93c34bdad6
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/UnshareScheduledActionTemplateErrors.md
@@ -0,0 +1,11 @@
+# Type Alias: UnshareScheduledActionTemplateErrors
+
+> **UnshareScheduledActionTemplateErrors** = \{ `401`: `string`; `404`: `string`; `500`: `string`; \}
+
+## Properties
+
+| Property | Type |
+| ------ | ------ |
+| <a id="property-401"></a> `401` | `string` |
+| <a id="property-404"></a> `404` | `string` |
+| <a id="property-500"></a> `500` | `string` |
diff --git a/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/UnshareScheduledActionTemplateResponse.md b/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/UnshareScheduledActionTemplateResponse.md
new file mode 100644
index 0000000000..2706aa122e
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/UnshareScheduledActionTemplateResponse.md
@@ -0,0 +1,3 @@
+# Type Alias: UnshareScheduledActionTemplateResponse
+
+> **UnshareScheduledActionTemplateResponse** = [`UnshareScheduledActionTemplateResponses`](UnshareScheduledActionTemplateResponses.md)\[keyof [`UnshareScheduledActionTemplateResponses`](UnshareScheduledActionTemplateResponses.md)\]
diff --git a/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/UnshareScheduledActionTemplateResponses.md b/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/UnshareScheduledActionTemplateResponses.md
new file mode 100644
index 0000000000..5a567755a9
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/UnshareScheduledActionTemplateResponses.md
@@ -0,0 +1,9 @@
+# Type Alias: UnshareScheduledActionTemplateResponses
+
+> **UnshareScheduledActionTemplateResponses** = \{ `204`: `void`; \}
+
+## Properties
+
+| Property | Type |
+| ------ | ------ |
+| <a id="property-204"></a> `204` | `void` |
diff --git a/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/VariableFill.md b/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/VariableFill.md
new file mode 100644
index 0000000000..20eaf3ca31
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/VariableFill.md
@@ -0,0 +1,5 @@
+# Type Alias: VariableFill
+
+> **VariableFill** = `"activator"` \| `"shared"` \| `"choice"`
+
+How a variable is filled when someone activates the template.
diff --git a/packages/sdk-docs/reference/src/entities/routines/routine/README.md b/packages/sdk-docs/reference/src/entities/routines/routine/README.md
index 21c2a9af3c..9716dee3cf 100644
--- a/packages/sdk-docs/reference/src/entities/routines/routine/README.md
+++ b/packages/sdk-docs/reference/src/entities/routines/routine/README.md
@@ -4,6 +4,7 @@
- [Routine](classes/Routine.md)
- [RoutineExecution](classes/RoutineExecution.md)
+- [RoutineTemplate](classes/RoutineTemplate.md)
## Interfaces
diff --git a/packages/sdk-docs/reference/src/entities/routines/routine/classes/Routine.md b/packages/sdk-docs/reference/src/entities/routines/routine/classes/Routine.md
index e92dba010b..82253b905d 100644
--- a/packages/sdk-docs/reference/src/entities/routines/routine/classes/Routine.md
+++ b/packages/sdk-docs/reference/src/entities/routines/routine/classes/Routine.md
@@ -17,10 +17,30 @@ A scheduled or event-triggered agent task.
| <a id="property-owner"></a> `owner` | `readonly` | () => `Promise`\<[`User`](../../../users/user/classes/User.md)\> | Routine owner. | - |
| <a id="property-revision"></a> `revision` | `readonly` | () => `Promise`\<`number`\> | Configuration revision. | - |
| <a id="property-runvisibility"></a> `runVisibility` | `readonly` | () => `Promise`\<[`RunVisibility`](../../../../../generated/scheduled-action/types.gen/type-aliases/RunVisibility.md)\> | Whether the routine's runs appear in Home and the Agents list. | - |
+| <a id="property-sourcetemplate"></a> `sourceTemplate` | `readonly` | () => `Promise`\<`Routine` \| `undefined`\> | The shared routine whose template this routine was activated from. | - |
| <a id="property-trigger"></a> `trigger` | `readonly` | () => `Promise`\<[`ActionTrigger`](../../../../../generated/scheduled-action/types.gen/type-aliases/ActionTrigger.md)\> | Configured triggers. | - |
## Methods
+### activateTemplate()
+
+> **activateTemplate**(`options`): `Promise`\<`Routine`\>
+
+Create the caller's own routine from this routine's shared template, with
+its references already filled in for them.
+
+#### Parameters
+
+| Parameter | Type |
+| ------ | ------ |
+| `options` | [`RoutineOptions`](../interfaces/RoutineOptions.md) |
+
+#### Returns
+
+`Promise`\<`Routine`\>
+
+***
+
### delete()
> **delete**(): `Promise`\<`void`\>
@@ -75,6 +95,51 @@ Enable or disable triggering.
***
+### shareAsTemplate()
+
+> **shareAsTemplate**(`options`): `Promise`\<[`RoutineTemplate`](RoutineTemplate.md)\>
+
+Share this routine as a template, or update its shared snapshot. People
+get the template, never the routine, its runs or its results.
+
+#### Parameters
+
+| Parameter | Type | Description |
+| ------ | ------ | ------ |
+| `options` | \{ `description`: `string`; `variables`: [`TemplateVariable`](../../../../../generated/scheduled-action/types.gen/type-aliases/TemplateVariable.md)[]; \} | - |
+| `options.description` | `string` | What the routine does for someone. |
+| `options.variables` | [`TemplateVariable`](../../../../../generated/scheduled-action/types.gen/type-aliases/TemplateVariable.md)[] | How each user-specific reference fills in when someone activates it. |
+
+#### Returns
+
+`Promise`\<[`RoutineTemplate`](RoutineTemplate.md)\>
+
+***
+
+### stopSharingTemplate()
+
+> **stopSharingTemplate**(): `Promise`\<`void`\>
+
+Stop sharing this routine. Routines already activated keep running.
+
+#### Returns
+
+`Promise`\<`void`\>
+
+***
+
+### template()
+
+> **template**(): `Promise`\<[`RoutineTemplate`](RoutineTemplate.md) \| `undefined`\>
+
+This routine's shared template, or `undefined` when it isn't shared.
+
+#### Returns
+
+`Promise`\<[`RoutineTemplate`](RoutineTemplate.md) \| `undefined`\>
+
+***
+
### toJSON()
> **toJSON**(): \{ `detail?`: [`ScheduledActionResponse`](../../../../../generated/scheduled-action/types.gen/type-aliases/ScheduledActionResponse.md); `id`: `string`; \}
diff --git a/packages/sdk-docs/reference/src/entities/routines/routine/classes/RoutineTemplate.md b/packages/sdk-docs/reference/src/entities/routines/routine/classes/RoutineTemplate.md
new file mode 100644
index 0000000000..7b54d3d40f
--- /dev/null
+++ b/packages/sdk-docs/reference/src/entities/routines/routine/classes/RoutineTemplate.md
@@ -0,0 +1,60 @@
+# Class: RoutineTemplate
+
+A routine shared as a template, which people activate as their own routine.
+
+## Constructors
+
+### Constructor
+
+> **new RoutineTemplate**(`routine`, `author`, `record`): `RoutineTemplate`
+
+#### Parameters
+
+| Parameter | Type | Description |
+| ------ | ------ | ------ |
+| `routine` | [`Routine`](Routine.md) | The shared routine. |
+| `author` | [`User`](../../../users/user/classes/User.md) | Who shared it. |
+| `record` | [`RoutineTemplate`](../../../../../generated/scheduled-action/types.gen/type-aliases/RoutineTemplate.md) | Template snapshot. |
+
+#### Returns
+
+`RoutineTemplate`
+
+## Properties
+
+| Property | Modifier | Type | Description |
+| ------ | ------ | ------ | ------ |
+| <a id="property-author"></a> `author` | `readonly` | [`User`](../../../users/user/classes/User.md) | Who shared it. |
+| <a id="property-record"></a> `record` | `readonly` | [`RoutineTemplate`](../../../../../generated/scheduled-action/types.gen/type-aliases/RoutineTemplate.md) | Template snapshot. |
+| <a id="property-routine"></a> `routine` | `readonly` | [`Routine`](Routine.md) | The shared routine. |
+
+## Methods
+
+### activate()
+
+> **activate**(`options`): `Promise`\<[`Routine`](Routine.md)\>
+
+Create the caller's own routine from this template, with its references
+already filled in for them.
+
+#### Parameters
+
+| Parameter | Type |
+| ------ | ------ |
+| `options` | [`RoutineOptions`](../interfaces/RoutineOptions.md) |
+
+#### Returns
+
+`Promise`\<[`Routine`](Routine.md)\>
+
+***
+
+### toJSON()
+
+> **toJSON**(): [`RoutineTemplate`](../../../../../generated/scheduled-action/types.gen/type-aliases/RoutineTemplate.md)
+
+Serialize without the authenticated client.
+
+#### Returns
+
+[`RoutineTemplate`](../../../../../generated/scheduled-action/types.gen/type-aliases/RoutineTemplate.md)
diff --git a/packages/sdk/README.md b/packages/sdk/README.md
index ddb3a7d67a..b1800292b7 100644
--- a/packages/sdk/README.md
+++ b/packages/sdk/README.md
@@ -375,6 +375,11 @@ Event triggers use `{ type: 'events', filters: [{ events, entities, condition }]
`entities` takes typed references such as `{ type: 'document', entity: doc }`.
Use `{ type: 'multiple', triggers: [...] }` to combine schedules and events.
`routine.update(options)` replaces task and trigger settings; `delete()` removes it.
+Routines run as their owner, so share one as a template instead:
+`routine.shareAsTemplate({ description, variables })` publishes a snapshot,
+`routine.template()` reads it (undefined when not shared), and
+`routine.activateTemplate(options)` creates the caller's own routine from it.
+`routine.sourceTemplate()` returns the routine a template came from.
### Agents, conversations and hosts
diff --git a/packages/sdk/generated/scheduled-action/index.ts b/packages/sdk/generated/scheduled-action/index.ts
index bb63816cee..fe4045f79a 100644
--- a/packages/sdk/generated/scheduled-action/index.ts
+++ b/packages/sdk/generated/scheduled-action/index.ts
@@ -1,4 +1,4 @@
// This file is auto-generated by @hey-api/openapi-ts
export { type Options, Sdk } from './sdk.gen';
-export type { ActionConfiguration, ActionConfigurationUpdate, ActionExecutionRecord, ActionKind, ActionTrigger, AgentMcpServer, AgentTask, AgentTaskAgent, AiAdmissionErrorBody, ClientOptions, ConditionResult, CreateScheduledAction, CreateScheduledActionData, CreateScheduledActionError, CreateScheduledActionErrors, CreateScheduledActionResponse, CreateScheduledActionResponses, DeleteScheduledActionData, DeleteScheduledActionError, DeleteScheduledActionErrors, DeleteScheduledActionResponse, DeleteScheduledActionResponses, EmptyResponse, EventFilter, EventFilters, EventName, ExecuteScheduledActionNowData, ExecuteScheduledActionNowError, ExecuteScheduledActionNowErrors, ExecuteScheduledActionNowResponse, ExecuteScheduledActionNowResponses, ExecutionResource, ExecutionResourceType, ExecutionResult, GetScheduledActionData, GetScheduledActionError, GetScheduledActionErrors, GetScheduledActionResponse, GetScheduledActionResponses, InProgressExecution, LegacyActionConfiguration, ListScheduledActionHistoryData, ListScheduledActionHistoryError, ListScheduledActionHistoryErrors, ListScheduledActionHistoryResponse, ListScheduledActionHistoryResponses, ListScheduledActionsData, ListScheduledActionsError, ListScheduledActionsErrors, ListScheduledActionsResponse, ListScheduledActionsResponses, RoutineModelId, RoutineTrigger, RoutineTriggers, RunVisibility, Schedule, ScheduledAction, ScheduledActionHealthData, ScheduledActionHealthResponse, ScheduledActionHealthResponses, ScheduledActionResponse, ScheduledActionUpdate, SetScheduledActionEnabled, SetScheduledActionEnabledData, SetScheduledActionEnabledError, SetScheduledActionEnabledErrors, SetScheduledActionEnabledResponse, SetScheduledActionEnabledResponses, UpdateScheduledAction, UpdateScheduledActionData, UpdateScheduledActionError, UpdateScheduledActionErrors, UpdateScheduledActionResponse, UpdateScheduledActionResponses } from './types.gen';
+export type { ActionConfiguration, ActionConfigurationUpdate, ActionExecutionRecord, ActionKind, ActionTrigger, ActivateScheduledActionTemplateData, ActivateScheduledActionTemplateError, ActivateScheduledActionTemplateErrors, ActivateScheduledActionTemplateResponse, ActivateScheduledActionTemplateResponses, AgentMcpServer, AgentTask, AgentTaskAgent, AiAdmissionErrorBody, ClientOptions, ConditionResult, CreateScheduledAction, CreateScheduledActionData, CreateScheduledActionError, CreateScheduledActionErrors, CreateScheduledActionResponse, CreateScheduledActionResponses, DeleteScheduledActionData, DeleteScheduledActionError, DeleteScheduledActionErrors, DeleteScheduledActionResponse, DeleteScheduledActionResponses, EmptyResponse, EventFilter, EventFilters, EventName, ExecuteScheduledActionNowData, ExecuteScheduledActionNowError, ExecuteScheduledActionNowErrors, ExecuteScheduledActionNowResponse, ExecuteScheduledActionNowResponses, ExecutionResource, ExecutionResourceType, ExecutionResult, GetScheduledActionData, GetScheduledActionError, GetScheduledActionErrors, GetScheduledActionResponse, GetScheduledActionResponses, GetScheduledActionTemplateData, GetScheduledActionTemplateError, GetScheduledActionTemplateErrors, GetScheduledActionTemplateResponse, GetScheduledActionTemplateResponses, InProgressExecution, LegacyActionConfiguration, ListScheduledActionHistoryData, ListScheduledActionHistoryError, ListScheduledActionHistoryErrors, ListScheduledActionHistoryResponse, ListScheduledActionHistoryResponses, ListScheduledActionsData, ListScheduledActionsError, ListScheduledActionsErrors, ListScheduledActionsResponse, ListScheduledActionsResponses, RoutineModelId, RoutineTemplate, RoutineTrigger, RoutineTriggers, RunVisibility, Schedule, ScheduledAction, ScheduledActionHealthData, ScheduledActionHealthResponse, ScheduledActionHealthResponses, ScheduledActionResponse, ScheduledActionUpdate, SetScheduledActionEnabled, SetScheduledActionEnabledData, SetScheduledActionEnabledError, SetScheduledActionEnabledErrors, SetScheduledActionEnabledResponse, SetScheduledActionEnabledResponses, ShareRoutineTemplate, ShareScheduledActionTemplateData, ShareScheduledActionTemplateError, ShareScheduledActionTemplateErrors, ShareScheduledActionTemplateResponse, ShareScheduledActionTemplateResponses, TemplateVariable, UnshareScheduledActionTemplateData, UnshareScheduledActionTemplateError, UnshareScheduledActionTemplateErrors, UnshareScheduledActionTemplateResponse, UnshareScheduledActionTemplateResponses, UpdateScheduledAction, UpdateScheduledActionData, UpdateScheduledActionError, UpdateScheduledActionErrors, UpdateScheduledActionResponse, UpdateScheduledActionResponses, VariableFill } from './types.gen';
diff --git a/packages/sdk/generated/scheduled-action/sdk.gen.ts b/packages/sdk/generated/scheduled-action/sdk.gen.ts
index e63d5ba2ac..547583af02 100644
--- a/packages/sdk/generated/scheduled-action/sdk.gen.ts
+++ b/packages/sdk/generated/scheduled-action/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 { CreateScheduledActionData, CreateScheduledActionErrors, CreateScheduledActionResponses, DeleteScheduledActionData, DeleteScheduledActionErrors, DeleteScheduledActionResponses, ExecuteScheduledActionNowData, ExecuteScheduledActionNowErrors, ExecuteScheduledActionNowResponses, GetScheduledActionData, GetScheduledActionErrors, GetScheduledActionResponses, ListScheduledActionHistoryData, ListScheduledActionHistoryErrors, ListScheduledActionHistoryResponses, ListScheduledActionsData, ListScheduledActionsErrors, ListScheduledActionsResponses, ScheduledActionHealthData, ScheduledActionHealthResponses, SetScheduledActionEnabledData, SetScheduledActionEnabledErrors, SetScheduledActionEnabledResponses, UpdateScheduledActionData, UpdateScheduledActionErrors, UpdateScheduledActionResponses } from './types.gen';
+import type { ActivateScheduledActionTemplateData, ActivateScheduledActionTemplateErrors, ActivateScheduledActionTemplateResponses, CreateScheduledActionData, CreateScheduledActionErrors, CreateScheduledActionResponses, DeleteScheduledActionData, DeleteScheduledActionErrors, DeleteScheduledActionResponses, ExecuteScheduledActionNowData, ExecuteScheduledActionNowErrors, ExecuteScheduledActionNowResponses, GetScheduledActionData, GetScheduledActionErrors, GetScheduledActionResponses, GetScheduledActionTemplateData, GetScheduledActionTemplateErrors, GetScheduledActionTemplateResponses, ListScheduledActionHistoryData, ListScheduledActionHistoryErrors, ListScheduledActionHistoryResponses, ListScheduledActionsData, ListScheduledActionsErrors, ListScheduledActionsResponses, ScheduledActionHealthData, ScheduledActionHealthResponses, SetScheduledActionEnabledData, SetScheduledActionEnabledErrors, SetScheduledActionEnabledResponses, ShareScheduledActionTemplateData, ShareScheduledActionTemplateErrors, ShareScheduledActionTemplateResponses, UnshareScheduledActionTemplateData, UnshareScheduledActionTemplateErrors, UnshareScheduledActionTemplateResponses, UpdateScheduledActionData, UpdateScheduledActionErrors, UpdateScheduledActionResponses } from './types.gen';
export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown> = Options2<TData, ThrowOnError, TResponse> & {
/**
@@ -113,4 +113,34 @@ export class Sdk extends HeyApiClient {
public listScheduledActionHistory<ThrowOnError extends boolean = false>(options: Options<ListScheduledActionHistoryData, ThrowOnError>): RequestResult<ListScheduledActionHistoryResponses, ListScheduledActionHistoryErrors, ThrowOnError> {
return (options.client ?? this.client).get<ListScheduledActionHistoryResponses, ListScheduledActionHistoryErrors, ThrowOnError>({ url: '/scheduled-actions/{id}/history', ...options });
}
+
+ public unshareScheduledActionTemplate<ThrowOnError extends boolean = false>(options: Options<UnshareScheduledActionTemplateData, ThrowOnError>): RequestResult<UnshareScheduledActionTemplateResponses, UnshareScheduledActionTemplateErrors, ThrowOnError> {
+ return (options.client ?? this.client).delete<UnshareScheduledActionTemplateResponses, UnshareScheduledActionTemplateErrors, ThrowOnError>({ url: '/scheduled-actions/{id}/template', ...options });
+ }
+
+ public getScheduledActionTemplate<ThrowOnError extends boolean = false>(options: Options<GetScheduledActionTemplateData, ThrowOnError>): RequestResult<GetScheduledActionTemplateResponses, GetScheduledActionTemplateErrors, ThrowOnError> {
+ return (options.client ?? this.client).get<GetScheduledActionTemplateResponses, GetScheduledActionTemplateErrors, ThrowOnError>({ url: '/scheduled-actions/{id}/template', ...options });
+ }
+
+ public shareScheduledActionTemplate<ThrowOnError extends boolean = false>(options: Options<ShareScheduledActionTemplateData, ThrowOnError>): RequestResult<ShareScheduledActionTemplateResponses, ShareScheduledActionTemplateErrors, ThrowOnError> {
+ return (options.client ?? this.client).put<ShareScheduledActionTemplateResponses, ShareScheduledActionTemplateErrors, ThrowOnError>({
+ url: '/scheduled-actions/{id}/template',
+ ...options,
+ headers: {
+ 'Content-Type': 'application/json',
+ ...options.headers
+ }
+ });
+ }
+
+ public activateScheduledActionTemplate<ThrowOnError extends boolean = false>(options: Options<ActivateScheduledActionTemplateData, ThrowOnError>): RequestResult<ActivateScheduledActionTemplateResponses, ActivateScheduledActionTemplateErrors, ThrowOnError> {
+ return (options.client ?? this.client).post<ActivateScheduledActionTemplateResponses, ActivateScheduledActionTemplateErrors, ThrowOnError>({
+ url: '/scheduled-actions/{id}/template/activate',
+ ...options,
+ headers: {
+ 'Content-Type': 'application/json',
+ ...options.headers
+ }
+ });
+ }
}
diff --git a/packages/sdk/generated/scheduled-action/types.gen.ts b/packages/sdk/generated/scheduled-action/types.gen.ts
index b6510ac8d5..37cbd1caf1 100644
--- a/packages/sdk/generated/scheduled-action/types.gen.ts
+++ b/packages/sdk/generated/scheduled-action/types.gen.ts
@@ -226,6 +226,33 @@ export type LegacyActionConfiguration = {
*/
export type RoutineModelId = string;
+/**
+ * A shared routine's snapshot, readable by any signed-in user with its ID.
+ */
+export type RoutineTemplate = {
+ /**
+ * Routines activated from this template, including stopped ones.
+ */
+ active_count: number;
+ /**
+ * Who shared it: the source routine's owner.
+ */
+ author: string;
+ created_at: string;
+ description: string;
+ /**
+ * The routine it was shared from.
+ */
+ id: string;
+ name: string;
+ task: {
+ [key: string]: unknown;
+ };
+ trigger: ActionTrigger;
+ updated_at: string;
+ variables: Array<TemplateVariable>;
+};
+
/**
* An individual trigger in a routine's trigger list.
*/
@@ -290,6 +317,10 @@ export type ScheduledAction = {
task: {
[key: string]: unknown;
};
+ /**
+ * The shared template this routine was activated from, if any.
+ */
+ template_id?: string | null;
trigger: ActionTrigger;
updated_at: string;
};
@@ -341,11 +372,47 @@ export type SetScheduledActionEnabled = {
enabled: boolean;
};
+/**
+ * What the owner supplies when sharing; the rest is snapshotted from the routine.
+ */
+export type ShareRoutineTemplate = {
+ description: string;
+ variables: Array<TemplateVariable>;
+};
+
+/**
+ * A user-specific part of a shared routine.
+ */
+export type TemplateVariable = {
+ fill: VariableFill;
+ id: string;
+ kind: 'user';
+ label: string;
+} | {
+ /**
+ * The mention's block name, such as `channel` or `md`.
+ */
+ block_name: string;
+ fill: VariableFill;
+ id: string;
+ kind: 'item';
+ label: string;
+} | {
+ fill: VariableFill;
+ kind: 'time_zone';
+ timezone: string;
+};
+
/**
* Full replacement of client configuration, not of server-owned action state.
*/
export type UpdateScheduledAction = ActionConfigurationUpdate | LegacyActionConfiguration;
+/**
+ * How a variable is filled when someone activates the template.
+ */
+export type VariableFill = 'activator' | 'shared' | 'choice';
+
export type ScheduledActionHealthData = {
body?: never;
path?: never;
@@ -588,3 +655,116 @@ export type ListScheduledActionHistoryResponses = {
};
export type ListScheduledActionHistoryResponse = ListScheduledActionHistoryResponses[keyof ListScheduledActionHistoryResponses];
+
+export type UnshareScheduledActionTemplateData = {
+ body?: never;
+ path: {
+ /**
+ * ID of the shared routine
+ */
+ id: string;
+ };
+ query?: never;
+ url: '/scheduled-actions/{id}/template';
+};
+
+export type UnshareScheduledActionTemplateErrors = {
+ 401: string;
+ 404: string;
+ 500: string;
+};
+
+export type UnshareScheduledActionTemplateError = UnshareScheduledActionTemplateErrors[keyof UnshareScheduledActionTemplateErrors];
+
+export type UnshareScheduledActionTemplateResponses = {
+ 204: void;
+};
+
+export type UnshareScheduledActionTemplateResponse = UnshareScheduledActionTemplateResponses[keyof UnshareScheduledActionTemplateResponses];
+
+export type GetScheduledActionTemplateData = {
+ body?: never;
+ path: {
+ /**
+ * ID of the shared routine
+ */
+ id: string;
+ };
+ query?: never;
+ url: '/scheduled-actions/{id}/template';
+};
+
+export type GetScheduledActionTemplateErrors = {
+ 401: string;
+ /**
+ * The routine is not shared
+ */
+ 404: string;
+ 500: string;
+};
+
+export type GetScheduledActionTemplateError = GetScheduledActionTemplateErrors[keyof GetScheduledActionTemplateErrors];
+
+export type GetScheduledActionTemplateResponses = {
+ 200: RoutineTemplate;
+};
+
+export type GetScheduledActionTemplateResponse = GetScheduledActionTemplateResponses[keyof GetScheduledActionTemplateResponses];
+
+export type ShareScheduledActionTemplateData = {
+ body: ShareRoutineTemplate;
+ path: {
+ /**
+ * ID of the routine to share
+ */
+ id: string;
+ };
+ query?: never;
+ url: '/scheduled-actions/{id}/template';
+};
+
+export type ShareScheduledActionTemplateErrors = {
+ 400: string;
+ 401: string;
+ 404: string;
+ 500: string;
+};
+
+export type ShareScheduledActionTemplateError = ShareScheduledActionTemplateErrors[keyof ShareScheduledActionTemplateErrors];
+
+export type ShareScheduledActionTemplateResponses = {
+ 200: RoutineTemplate;
+};
+
+export type ShareScheduledActionTemplateResponse = ShareScheduledActionTemplateResponses[keyof ShareScheduledActionTemplateResponses];
+
+export type ActivateScheduledActionTemplateData = {
+ body: CreateScheduledAction;
+ path: {
+ /**
+ * ID of the shared routine
+ */
+ id: string;
+ };
+ query?: never;
+ url: '/scheduled-actions/{id}/template/activate';
+};
+
+export type ActivateScheduledActionTemplateErrors = {
+ 400: string;
+ 401: string;
+ 403: string;
+ /**
+ * The routine is not shared
+ */
+ 404: string;
+ 500: string;
+};
+
+export type ActivateScheduledActionTemplateError = ActivateScheduledActionTemplateErrors[keyof ActivateScheduledActionTemplateErrors];
+
+export type ActivateScheduledActionTemplateResponses = {
+ 201: ScheduledActionResponse;
+};
+
+export type ActivateScheduledActionTemplateResponse = ActivateScheduledActionTemplateResponses[keyof ActivateScheduledActionTemplateResponses];
diff --git a/packages/sdk/specs/scheduled-action.json b/packages/sdk/specs/scheduled-action.json
index a1e1bd64f2..afb4d7882b 100644
--- a/packages/sdk/specs/scheduled-action.json
+++ b/packages/sdk/specs/scheduled-action.json
@@ -602,6 +602,281 @@
}
}
}
+ },
+ "/scheduled-actions/{id}/template": {
+ "get": {
+ "tags": ["scheduled actions"],
+ "operationId": "get_scheduled_action_template",
+ "parameters": [
+ {
+ "name": "id",
+ "in": "path",
+ "description": "ID of the shared routine",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RoutineTemplate"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "The routine is not shared",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ }
+ }
+ },
+ "put": {
+ "tags": ["scheduled actions"],
+ "operationId": "share_scheduled_action_template",
+ "parameters": [
+ {
+ "name": "id",
+ "in": "path",
+ "description": "ID of the routine to share",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ShareRoutineTemplate"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RoutineTemplate"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ }
+ }
+ },
+ "delete": {
+ "tags": ["scheduled actions"],
+ "operationId": "unshare_scheduled_action_template",
+ "parameters": [
+ {
+ "name": "id",
+ "in": "path",
+ "description": "ID of the shared routine",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "204": {
+ "description": ""
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/scheduled-actions/{id}/template/activate": {
+ "post": {
+ "tags": ["scheduled actions"],
+ "operationId": "activate_scheduled_action_template",
+ "parameters": [
+ {
+ "name": "id",
+ "in": "path",
+ "description": "ID of the shared routine",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CreateScheduledAction"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "201": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ScheduledActionResponse"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "403": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "The routine is not shared",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ }
+ }
+ }
}
},
"components": {
@@ -1051,6 +1326,65 @@
"type": "string",
"description": "A nonblank model identifier. Runtime catalogs, not the scheduler, own availability."
},
+ "RoutineTemplate": {
+ "type": "object",
+ "description": "A shared routine's snapshot, readable by any signed-in user with its ID.",
+ "required": [
+ "id",
+ "author",
+ "name",
+ "description",
+ "trigger",
+ "task",
+ "variables",
+ "active_count",
+ "created_at",
+ "updated_at"
+ ],
+ "properties": {
+ "active_count": {
+ "type": "integer",
+ "format": "int32",
+ "description": "Routines activated from this template, including stopped ones.",
+ "minimum": 0
+ },
+ "author": {
+ "type": "string",
+ "description": "Who shared it: the source routine's owner."
+ },
+ "created_at": {
+ "type": "string",
+ "format": "date-time"
+ },
+ "description": {
+ "type": "string"
+ },
+ "id": {
+ "type": "string",
+ "format": "uuid",
+ "description": "The routine it was shared from."
+ },
+ "name": {
+ "type": "string"
+ },
+ "task": {
+ "type": "object"
+ },
+ "trigger": {
+ "$ref": "#/components/schemas/ActionTrigger"
+ },
+ "updated_at": {
+ "type": "string",
+ "format": "date-time"
+ },
+ "variables": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/TemplateVariable"
+ }
+ }
+ }
+ },
"RoutineTrigger": {
"oneOf": [
{
@@ -1163,6 +1497,11 @@
"task": {
"type": "object"
},
+ "template_id": {
+ "type": ["string", "null"],
+ "format": "uuid",
+ "description": "The shared template this routine was activated from, if any."
+ },
"trigger": {
"$ref": "#/components/schemas/ActionTrigger"
},
@@ -1273,6 +1612,89 @@
},
"additionalProperties": false
},
+ "ShareRoutineTemplate": {
+ "type": "object",
+ "description": "What the owner supplies when sharing; the rest is snapshotted from the routine.",
+ "required": ["description", "variables"],
+ "properties": {
+ "description": {
+ "type": "string"
+ },
+ "variables": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/TemplateVariable"
+ }
+ }
+ },
+ "additionalProperties": false
+ },
+ "TemplateVariable": {
+ "oneOf": [
+ {
+ "type": "object",
+ "description": "A person mentioned in the instructions, by their user ID.",
+ "required": ["id", "label", "fill", "kind"],
+ "properties": {
+ "fill": {
+ "$ref": "#/components/schemas/VariableFill"
+ },
+ "id": {
+ "type": "string"
+ },
+ "kind": {
+ "type": "string",
+ "enum": ["user"]
+ },
+ "label": {
+ "type": "string"
+ }
+ }
+ },
+ {
+ "type": "object",
+ "description": "A document, channel or other item mentioned in the instructions.",
+ "required": ["id", "block_name", "label", "fill", "kind"],
+ "properties": {
+ "block_name": {
+ "type": "string",
+ "description": "The mention's block name, such as `channel` or `md`."
+ },
+ "fill": {
+ "$ref": "#/components/schemas/VariableFill"
+ },
+ "id": {
+ "type": "string"
+ },
+ "kind": {
+ "type": "string",
+ "enum": ["item"]
+ },
+ "label": {
+ "type": "string"
+ }
+ }
+ },
+ {
+ "type": "object",
+ "description": "The time zone of the routine's schedules.",
+ "required": ["timezone", "fill", "kind"],
+ "properties": {
+ "fill": {
+ "$ref": "#/components/schemas/VariableFill"
+ },
+ "kind": {
+ "type": "string",
+ "enum": ["time_zone"]
+ },
+ "timezone": {
+ "type": "string"
+ }
+ }
+ }
+ ],
+ "description": "A user-specific part of a shared routine."
+ },
"UpdateScheduledAction": {
"oneOf": [
{
@@ -1283,6 +1705,11 @@
}
],
"description": "Full replacement of client configuration, not of server-owned action state."
+ },
+ "VariableFill": {
+ "type": "string",
+ "description": "How a variable is filled when someone activates the template.",
+ "enum": ["activator", "shared", "choice"]
}
}
},
diff --git a/packages/sdk/src/entities/routines/routine.ts b/packages/sdk/src/entities/routines/routine.ts
index 39511d8f57..4e5374575a 100644
--- a/packages/sdk/src/entities/routines/routine.ts
+++ b/packages/sdk/src/entities/routines/routine.ts
@@ -4,9 +4,11 @@ import type {
AgentTask,
EventFilter,
RoutineModelId,
+ RoutineTemplate as RoutineTemplateRecord,
RoutineTrigger,
RunVisibility,
ScheduledActionResponse,
+ TemplateVariable,
} from '../../../generated/scheduled-action/types.gen';
import { unwrap } from '../../utils';
import type { MacroClient } from '../../utils/client';
@@ -126,6 +128,74 @@ export class Routine extends MacroEntity<ScheduledActionResponse> {
User.byId(this.client, id),
);
+ /** The shared routine whose template this routine was activated from. */
+ readonly sourceTemplate: () => Promise<Routine | undefined> =
+ this.mappedField('template_id', (id): Routine | undefined =>
+ id ? Routine.byId(this.client, id) : undefined,
+ );
+
+ /** This routine's shared template, or `undefined` when it isn't shared. */
+ async template(): Promise<RoutineTemplate | undefined> {
+ const result = await this.client.scheduledAction.getScheduledActionTemplate(
+ { path: { id: this.id } },
+ );
+ if (result.response?.status === 404) return undefined;
+ return this.toTemplate(unwrap(result));
+ }
+
+ /**
+ * Share this routine as a template, or update its shared snapshot. People
+ * get the template, never the routine, its runs or its results.
+ */
+ async shareAsTemplate(options: {
+ /** What the routine does for someone. */
+ description: string;
+ /** How each user-specific reference fills in when someone activates it. */
+ variables: TemplateVariable[];
+ }): Promise<RoutineTemplate> {
+ return this.toTemplate(
+ unwrap(
+ await this.client.scheduledAction.shareScheduledActionTemplate({
+ path: { id: this.id },
+ body: options,
+ }),
+ ),
+ );
+ }
+
+ /**
+ * Create the caller's own routine from this routine's shared template, with
+ * its references already filled in for them.
+ */
+ async activateTemplate(options: RoutineOptions): Promise<Routine> {
+ return Routine.from(
+ this.client,
+ unwrap(
+ await this.client.scheduledAction.activateScheduledActionTemplate({
+ path: { id: this.id },
+ body: { ...routineBody(options), enabled: options.enabled ?? true },
+ }),
+ ),
+ );
+ }
+
+ private toTemplate(record: RoutineTemplateRecord): RoutineTemplate {
+ return new RoutineTemplate(
+ this,
+ User.byId(this.client, record.author),
+ record,
+ );
+ }
+
+ /** Stop sharing this routine. Routines already activated keep running. */
+ async stopSharingTemplate(): Promise<void> {
+ unwrap(
+ await this.client.scheduledAction.unshareScheduledActionTemplate({
+ path: { id: this.id },
+ }),
+ );
+ }
+
/** Replace the routine's task and trigger configuration. */
async update(options: RoutineOptions): Promise<void> {
await this.mutate((c) =>
@@ -182,6 +252,31 @@ export class Routine extends MacroEntity<ScheduledActionResponse> {
}
}
+/** A routine shared as a template, which people activate as their own routine. */
+export class RoutineTemplate {
+ constructor(
+ /** The shared routine. */
+ readonly routine: Routine,
+ /** Who shared it. */
+ readonly author: User,
+ /** Template snapshot. */
+ readonly record: RoutineTemplateRecord,
+ ) {}
+
+ /**
+ * Create the caller's own routine from this template, with its references
+ * already filled in for them.
+ */
+ activate(options: RoutineOptions): Promise<Routine> {
+ return this.routine.activateTemplate(options);
+ }
+
+ /** Serialize without the authenticated client. */
+ toJSON() {
+ return this.record;
+ }
+}
+
/** A completed routine execution, as recorded by the service. */
export class RoutineExecution {
constructor(
diff --git a/services/agent_harness_service/src/scheduling.rs b/services/agent_harness_service/src/scheduling.rs
index 36baa5e6a7..d3e70450ae 100644
--- a/services/agent_harness_service/src/scheduling.rs
+++ b/services/agent_harness_service/src/scheduling.rs
@@ -25,9 +25,13 @@ use scheduled_action::domain::ports::ScheduledActionDispatcher;
use scheduled_action::domain::service::ScheduledActionServiceImpl;
use scheduled_action::domain::target_runner::TargetRunner;
use scheduled_action::domain::target_validation::TargetValidation;
+use scheduled_action::domain::templates::RoutineTemplateServiceImpl;
use scheduled_action::inbound::axum_router::{ScheduledActionRouterState, scheduled_action_router};
use scheduled_action::inbound::event_run_worker::run_event_worker;
use scheduled_action::inbound::kafka_consumer::run_scheduled_action_event_consumer;
+use scheduled_action::inbound::template_router::{
+ RoutineTemplateRouterState, routine_template_router,
+};
use scheduled_action::outbound::agent_session_client::AgentSessionClient;
use scheduled_action::outbound::conn_gateway_live_updates::ConnGatewayLiveUpdates;
use scheduled_action::outbound::event_access::EventAccessAdapter;
@@ -37,6 +41,7 @@ use scheduled_action::outbound::pg_event_run_repo::PgEventRunRepo;
use scheduled_action::outbound::pg_polling_dispatcher::{
PgPollingDispatcher, PgPollingDispatcherLifecycle,
};
+use scheduled_action::outbound::pg_routine_template_repo::PgRoutineTemplateRepo;
use scheduled_action::outbound::pg_scheduled_action_repo::PgScheduledActionRepo;
use scheduled_action::swagger::ApiDoc;
use tokio_util::{sync::CancellationToken, task::TaskTracker};
@@ -260,12 +265,21 @@ pub async fn build(
config.routine_agents_enabled,
)),
);
+ let template_state = RoutineTemplateRouterState {
+ service: Arc::new(RoutineTemplateServiceImpl::new(
+ Arc::clone(&service),
+ Arc::new(PgRoutineTemplateRepo::new(db.clone())),
+ )),
+ access_service: Arc::clone(&access),
+ authorization_state: authorization_state.clone(),
+ };
let state = ScheduledActionRouterState {
service,
access_service: access,
authorization_state,
};
- let authed_routes = scheduled_action_router::<_, _, _, ()>(state);
+ let authed_routes = scheduled_action_router::<_, _, _, ()>(state)
+ .merge(routine_template_router::<_, _, _, ()>(template_state));
let router = mount_router(authed_routes)
.layer(macro_cors::cors_layer())