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(agent-reviews): make typed review drafts and results the source of truth (#9433)

Wolf Mermelstein78cb07918f0c
diff --git a/.github/workflows/web-app-check-main.yml b/.github/workflows/web-app-check-main.yml
index 4ba9f3529f..fd7044123a 100644
--- a/.github/workflows/web-app-check-main.yml
+++ b/.github/workflows/web-app-check-main.yml
@@ -344,8 +344,9 @@ jobs:
just gen-agent-fold-types
just gen-database-sql-types
just gen-dynamic-ui-types
- if ! git diff --exit-code -- src/lib/service-clients/service-agent-fold/generated src/lib/core/database-sql/generated src/features/dynamic-ui/generated ../../packages/lexical-core/generated; then
- echo "Generated specta types are stale. Run 'just gen-agent-fold-types', 'just gen-database-sql-types' and 'just gen-dynamic-ui-types' in apps/web and commit the result."
+ just gen-agent-review-types
+ if ! git diff --exit-code -- src/lib/service-clients/service-agent-fold/generated src/lib/core/database-sql/generated src/features/dynamic-ui/generated ../../packages/lexical-core/generated src/lib/service-clients/service-agent-reviews/generated ../../packages/sdk/generated/agent-reviews; then
+ echo "Generated specta types are stale. Run 'just gen-agent-fold-types', 'just gen-database-sql-types', 'just gen-dynamic-ui-types' and 'just gen-agent-review-types' in apps/web and commit the result."
exit 1
fi
working-directory: apps/web
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.json
index c1292cb5d9..8320fa47dd 100644
--- a/.github/workspace-dep-closures.json
+++ b/.github/workspace-dep-closures.json
@@ -117,6 +117,7 @@
"crates/email_api_client",
"crates/email_db_client",
"crates/email_utils",
+ "crates/email_validator",
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
@@ -223,6 +224,7 @@
"crates/email_api_client",
"crates/email_db_client",
"crates/email_utils",
+ "crates/email_validator",
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
@@ -322,6 +324,7 @@
"crates/channels",
"crates/code_execution",
"crates/cognition",
+ "crates/connect_client",
"crates/connection",
"crates/connection_gateway_client",
"crates/connection_gateway_models",
@@ -337,6 +340,7 @@
"crates/email_api_client",
"crates/email_db_client",
"crates/email_utils",
+ "crates/email_validator",
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
@@ -353,6 +357,9 @@
"crates/google_token",
"crates/harness_id",
"crates/harness_token",
+ "crates/import",
+ "crates/import_notion",
+ "crates/import_tracker",
"crates/initiative",
"crates/invite_email",
"crates/ip_extractor",
@@ -374,6 +381,9 @@
"crates/macro_user_id",
"crates/macro_uuid",
"crates/maybe_send",
+ "crates/mcp_client",
+ "crates/mcp_select",
+ "crates/mcp_toolset",
"crates/mention_utils",
"crates/messages",
"crates/model",
@@ -395,6 +405,7 @@
"crates/non_empty",
"crates/notification",
"crates/notification_state",
+ "crates/pipedream_mcp",
"crates/prompt",
"crates/properties",
"crates/rate_limit",
@@ -451,6 +462,7 @@
"crates/email_api_client",
"crates/email_db_client",
"crates/email_utils",
+ "crates/email_validator",
"crates/embedding",
"crates/entity_access",
"crates/entity_access_db_utils",
@@ -607,6 +619,7 @@
"crates/email_api_client",
"crates/email_db_client",
"crates/email_utils",
+ "crates/email_validator",
"crates/embedding",
"crates/entity_access",
"crates/entity_access_db_utils",
@@ -1180,6 +1193,7 @@
"crates/email_api_client",
"crates/email_db_client",
"crates/email_utils",
+ "crates/email_validator",
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
@@ -1289,6 +1303,7 @@
"crates/email_api_client",
"crates/email_db_client",
"crates/email_utils",
+ "crates/email_validator",
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
@@ -1399,6 +1414,7 @@
"crates/email_api_client",
"crates/email_db_client",
"crates/email_utils",
+ "crates/email_validator",
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
@@ -1510,6 +1526,7 @@
"crates/email_api_client",
"crates/email_db_client",
"crates/email_utils",
+ "crates/email_validator",
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
@@ -1620,6 +1637,7 @@
"crates/email_api_client",
"crates/email_db_client",
"crates/email_utils",
+ "crates/email_validator",
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
@@ -1723,6 +1741,7 @@
"crates/email_api_client",
"crates/email_db_client",
"crates/email_utils",
+ "crates/email_validator",
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
@@ -2228,6 +2247,7 @@
"crates/email_api_client",
"crates/email_db_client",
"crates/email_utils",
+ "crates/email_validator",
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
@@ -2642,6 +2662,7 @@
"crates/email_api_client",
"crates/email_db_client",
"crates/email_utils",
+ "crates/email_validator",
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
@@ -2759,6 +2780,7 @@
"crates/database_env_vars",
"crates/document_sub_type",
"crates/email_utils",
+ "crates/email_validator",
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_mutation",
@@ -3506,6 +3528,7 @@
"crates/email_api_client",
"crates/email_db_client",
"crates/email_utils",
+ "crates/email_validator",
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
@@ -3616,6 +3639,7 @@
"crates/email_api_client",
"crates/email_db_client",
"crates/email_utils",
+ "crates/email_validator",
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
@@ -3742,6 +3766,7 @@
"crates/email_api_client",
"crates/email_db_client",
"crates/email_utils",
+ "crates/email_validator",
"crates/embedding",
"crates/entity_access",
"crates/entity_access_db_utils",
@@ -3874,6 +3899,7 @@
"crates/email_api_client",
"crates/email_db_client",
"crates/email_utils",
+ "crates/email_validator",
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
@@ -4142,6 +4168,7 @@
"crates/email_api_client",
"crates/email_db_client",
"crates/email_utils",
+ "crates/email_validator",
"crates/embedding",
"crates/entity_access",
"crates/entity_access_db_utils",
@@ -4476,6 +4503,7 @@
"crates/email_api_client",
"crates/email_db_client",
"crates/email_utils",
+ "crates/email_validator",
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
@@ -4681,6 +4709,7 @@
"crates/email_api_client",
"crates/email_db_client",
"crates/email_utils",
+ "crates/email_validator",
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
@@ -4943,6 +4972,7 @@
"crates/email_api_client",
"crates/email_db_client",
"crates/email_utils",
+ "crates/email_validator",
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
@@ -5113,6 +5143,7 @@
"crates/email_api_client",
"crates/email_db_client",
"crates/email_utils",
+ "crates/email_validator",
"crates/embedding",
"crates/entity_access",
"crates/entity_access_db_utils",
@@ -5570,6 +5601,7 @@
"crates/email_api_client",
"crates/email_db_client",
"crates/email_utils",
+ "crates/email_validator",
"crates/embedding",
"crates/entity_access",
"crates/entity_access_db_utils",
@@ -5700,6 +5732,7 @@
"crates/email_api_client",
"crates/email_db_client",
"crates/email_utils",
+ "crates/email_validator",
"crates/embedding",
"crates/entity_access",
"crates/entity_access_db_utils",
@@ -5826,6 +5859,7 @@
"crates/email_api_client",
"crates/email_db_client",
"crates/email_utils",
+ "crates/email_validator",
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
@@ -5951,6 +5985,7 @@
"crates/email_api_client",
"crates/email_db_client",
"crates/email_utils",
+ "crates/email_validator",
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
@@ -6037,6 +6072,7 @@
"crates/document_sub_type",
"crates/email_api_client",
"crates/email_utils",
+ "crates/email_validator",
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_mutation",
@@ -6142,6 +6178,7 @@
"crates/email_api_client",
"crates/email_db_client",
"crates/email_utils",
+ "crates/email_validator",
"crates/embedding",
"crates/entity_access",
"crates/entity_access_db_utils",
@@ -6311,6 +6348,7 @@
"crates/email_api_client",
"crates/email_db_client",
"crates/email_utils",
+ "crates/email_validator",
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
@@ -6410,6 +6448,7 @@
"crates/email_api_client",
"crates/email_db_client",
"crates/email_utils",
+ "crates/email_validator",
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
@@ -6510,6 +6549,7 @@
"crates/email_api_client",
"crates/email_db_client",
"crates/email_utils",
+ "crates/email_validator",
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
@@ -6625,6 +6665,7 @@
"crates/email_db_client",
"crates/email_service_client",
"crates/email_utils",
+ "crates/email_validator",
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
@@ -6719,6 +6760,7 @@
"crates/email_api_client",
"crates/email_db_client",
"crates/email_utils",
+ "crates/email_validator",
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
@@ -7336,6 +7378,7 @@
"crates/email_api_client",
"crates/email_db_client",
"crates/email_utils",
+ "crates/email_validator",
"crates/embedding",
"crates/entity_access",
"crates/entity_access_db_utils",
@@ -7667,6 +7710,7 @@
"crates/database_env_vars",
"crates/document_sub_type",
"crates/email_utils",
+ "crates/email_validator",
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_mutation",
@@ -7946,6 +7990,7 @@
"crates/email_api_client",
"crates/email_db_client",
"crates/email_utils",
+ "crates/email_validator",
"crates/embedding",
"crates/entity_access",
"crates/entity_access_db_utils",
@@ -8085,6 +8130,7 @@
"crates/email_api_client",
"crates/email_db_client",
"crates/email_utils",
+ "crates/email_validator",
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
@@ -8192,6 +8238,7 @@
"crates/email_api_client",
"crates/email_db_client",
"crates/email_utils",
+ "crates/email_validator",
"crates/embedding",
"crates/entity_access",
"crates/entity_access_db_utils",
@@ -8342,6 +8389,7 @@
"crates/email_api_client",
"crates/email_db_client",
"crates/email_utils",
+ "crates/email_validator",
"crates/embedding",
"crates/entity_access",
"crates/entity_access_db_utils",
@@ -8493,6 +8541,7 @@
"crates/email_api_client",
"crates/email_db_client",
"crates/email_utils",
+ "crates/email_validator",
"crates/embedding",
"crates/entity_access",
"crates/entity_access_db_utils",
@@ -8779,6 +8828,7 @@
"crates/email_api_client",
"crates/email_db_client",
"crates/email_utils",
+ "crates/email_validator",
"crates/embedding",
"crates/entity_access",
"crates/entity_access_db_utils",
@@ -8920,6 +8970,7 @@
"crates/email_api_client",
"crates/email_db_client",
"crates/email_utils",
+ "crates/email_validator",
"crates/embedding",
"crates/entity_access",
"crates/entity_access_db_utils",
@@ -9096,6 +9147,7 @@
"crates/email_api_client",
"crates/email_db_client",
"crates/email_utils",
+ "crates/email_validator",
"crates/embedding",
"crates/entity_access",
"crates/entity_access_db_utils",
@@ -9284,6 +9336,7 @@
"crates/email_api_client",
"crates/email_db_client",
"crates/email_utils",
+ "crates/email_validator",
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
@@ -9478,6 +9531,7 @@
"crates/email_api_client",
"crates/email_db_client",
"crates/email_utils",
+ "crates/email_validator",
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
@@ -9885,6 +9939,7 @@
"crates/email_api_client",
"crates/email_db_client",
"crates/email_utils",
+ "crates/email_validator",
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
@@ -10566,6 +10621,7 @@
"crates/email_api_client",
"crates/email_db_client",
"crates/email_utils",
+ "crates/email_validator",
"crates/embedding",
"crates/entity_access",
"crates/entity_access_db_utils",
@@ -10937,6 +10993,7 @@
"crates/email_api_client",
"crates/email_db_client",
"crates/email_utils",
+ "crates/email_validator",
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
@@ -11045,6 +11102,7 @@
"crates/email_api_client",
"crates/email_db_client",
"crates/email_utils",
+ "crates/email_validator",
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
@@ -11500,6 +11558,7 @@
"crates/email_api_client",
"crates/email_db_client",
"crates/email_utils",
+ "crates/email_validator",
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
@@ -11599,6 +11658,7 @@
"crates/email_api_client",
"crates/email_db_client",
"crates/email_utils",
+ "crates/email_validator",
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
@@ -11733,6 +11793,7 @@
"crates/email_api_client",
"crates/email_db_client",
"crates/email_utils",
+ "crates/email_validator",
"crates/embedding",
"crates/entity_access",
"crates/entity_access_db_utils",
@@ -12018,6 +12079,7 @@
"crates/email_api_client",
"crates/email_db_client",
"crates/email_utils",
+ "crates/email_validator",
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
@@ -12171,6 +12233,7 @@
"crates/email_api_client",
"crates/email_db_client",
"crates/email_utils",
+ "crates/email_validator",
"crates/embedding",
"crates/entity_access",
"crates/entity_access_db_utils",
@@ -12310,6 +12373,7 @@
"crates/email_api_client",
"crates/email_db_client",
"crates/email_utils",
+ "crates/email_validator",
"crates/embedding",
"crates/ensure_exists",
"crates/entity_access",
@@ -12452,6 +12516,7 @@
"crates/email_api_client",
"crates/email_db_client",
"crates/email_utils",
+ "crates/email_validator",
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
@@ -12570,6 +12635,7 @@
"crates/email_api_client",
"crates/email_db_client",
"crates/email_utils",
+ "crates/email_validator",
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
@@ -12889,6 +12955,7 @@
"crates/email_api_client",
"crates/email_db_client",
"crates/email_utils",
+ "crates/email_validator",
"crates/embedding",
"crates/entity_access",
"crates/entity_access_db_utils",
@@ -13028,6 +13095,7 @@
"crates/email_api_client",
"crates/email_db_client",
"crates/email_utils",
+ "crates/email_validator",
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
@@ -13149,6 +13217,7 @@
"crates/email_api_client",
"crates/email_db_client",
"crates/email_utils",
+ "crates/email_validator",
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
@@ -13271,6 +13340,7 @@
"crates/email_api_client",
"crates/email_db_client",
"crates/email_utils",
+ "crates/email_validator",
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
@@ -13389,6 +13459,7 @@
"crates/email_api_client",
"crates/email_db_client",
"crates/email_utils",
+ "crates/email_validator",
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
@@ -13512,6 +13583,7 @@
"crates/email_api_client",
"crates/email_db_client",
"crates/email_utils",
+ "crates/email_validator",
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
@@ -13637,6 +13709,7 @@
"crates/email_api_client",
"crates/email_db_client",
"crates/email_utils",
+ "crates/email_validator",
"crates/embedding",
"crates/entity_access",
"crates/entity_access_db_utils",
@@ -13762,6 +13835,7 @@
"crates/email_api_client",
"crates/email_db_client",
"crates/email_utils",
+ "crates/email_validator",
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
@@ -14104,6 +14178,7 @@
"crates/email_api_client",
"crates/email_db_client",
"crates/email_utils",
+ "crates/email_validator",
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
@@ -14232,6 +14307,7 @@
"crates/email_api_client",
"crates/email_db_client",
"crates/email_utils",
+ "crates/email_validator",
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
@@ -14337,6 +14413,7 @@
"crates/email_api_client",
"crates/email_db_client",
"crates/email_utils",
+ "crates/email_validator",
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
@@ -14437,6 +14514,7 @@
"crates/email_api_client",
"crates/email_db_client",
"crates/email_utils",
+ "crates/email_validator",
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
@@ -14660,6 +14738,7 @@
"crates/email_api_client",
"crates/email_db_client",
"crates/email_utils",
+ "crates/email_validator",
"crates/embedding",
"crates/entity_access",
"crates/entity_access_db_utils",
@@ -14978,6 +15057,7 @@
"crates/email_api_client",
"crates/email_db_client",
"crates/email_utils",
+ "crates/email_validator",
"crates/embedding",
"crates/entity_access",
"crates/entity_access_db_utils",
diff --git a/Cargo.lock b/Cargo.lock
index 2dd92dfbef..758a67047a 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -314,19 +314,27 @@ dependencies = [
"async-trait",
"axum",
"bot_id",
+ "calendar_events",
"chrono",
"code_execution",
"cognition",
"dynamic_ui",
+ "email",
"entity_access",
+ "import",
"macro_authorization",
"macro_db_migrator",
"macro_user_id",
"macro_uuid",
+ "nutype",
"rootcause",
"schemars 1.2.1",
"serde",
"serde_json",
+ "serde_path_to_error",
+ "specta",
+ "specta-serde",
+ "specta-typescript",
"sqlx",
"tempfile",
"thiserror 2.0.18",
@@ -3819,6 +3827,7 @@ dependencies = [
"chrono",
"chrono-tz",
"email_utils",
+ "email_validator",
"futures",
"macro_authorization",
"macro_db_migrator",
@@ -3834,6 +3843,7 @@ dependencies = [
"schemars 1.2.1",
"serde",
"serde_json",
+ "specta",
"sqlx",
"thiserror 2.0.18",
"tokio",
@@ -7268,6 +7278,7 @@ dependencies = [
"email_api_client",
"email_db_client",
"email_utils",
+ "email_validator",
"entity_access",
"entity_access_management",
"entity_mutation",
@@ -7302,6 +7313,7 @@ dependencies = [
"serde_json",
"serde_with",
"sha2 0.10.9",
+ "specta",
"sqlx",
"strum 0.27.2",
"subtle",
@@ -7675,7 +7687,12 @@ name = "email_validator"
version = "0.1.0"
dependencies = [
"lazy_static",
+ "nutype",
"regex",
+ "schemars 1.2.1",
+ "serde",
+ "serde_json",
+ "specta",
"workspace-hack",
]
@@ -10726,6 +10743,7 @@ dependencies = [
"schemars 1.2.1",
"serde",
"serde_json",
+ "specta",
"sqlx",
"strum 0.27.2",
"thiserror 2.0.18",
@@ -23116,6 +23134,8 @@ dependencies = [
"simd-adler32",
"slab",
"smallvec",
+ "specta",
+ "specta-macros",
"spin 0.9.9",
"sqlx-core",
"sqlx-postgres",
diff --git a/Cargo.toml b/Cargo.toml
index fb6322bea4..9e8d7054a6 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -398,8 +398,8 @@ ruzstd = { version = "0.9.1", default-features = false, features = ["std"] }
serde = { version = "1.0.214", features = ["derive"] }
serde-wasm-bindgen = "0.6"
serde_dynamo = { version = "4", features = ["aws-sdk-dynamodb+1"] }
-serde_json = { version = "1.0.132" }
serde_path_to_error = "0.1.20"
+serde_json = { version = "1.0.132" }
serde_repr = "0.1"
serde_with = { version = "3.12.0", features = ["base64"] }
serde_yaml = "0.9"
diff --git a/apps/web/justfile b/apps/web/justfile
index 2306ffc50c..2e26c2a03c 100644
--- a/apps/web/justfile
+++ b/apps/web/justfile
@@ -471,6 +471,16 @@ gen-agent-fold-types:
cargo run -p agent_fold --bin export_types
bunx biome format --write {{justfile_directory()}}/src/lib/service-clients/service-agent-fold/generated/types.ts
+# Regenerate src/lib/service-clients/service-agent-reviews/generated/types.ts
+# (and the SDK's packages/sdk/generated/agent-reviews/index.ts) from
+# agent_code_mode's review types with specta. Run after changing a review type
+# or a type a review draft or result reuses (SendEmail, CreateCalendarEvent,
+# their responses, the import report); biome reformats specta's output for the
+# same reason as gen-agent-fold-types.
+gen-agent-review-types:
+ SQLX_OFFLINE=true cargo run -p agent_code_mode --bin export_review_types
+ bunx biome format --write {{justfile_directory()}}/src/lib/service-clients/service-agent-reviews/generated/types.ts
+
# Regenerate the dynamic-UI view types (src/features/dynamic-ui/generated/types.ts
# and lexical-core's copy) from `crates/dynamic_ui` with specta. Run after
# changing a widget; biome reformats specta's output as in gen-agent-fold-types.
diff --git a/apps/web/package.json b/apps/web/package.json
index 69eb148a5d..167e9f17fa 100644
--- a/apps/web/package.json
+++ b/apps/web/package.json
@@ -43,6 +43,7 @@
"ui-audit": "bun scripts/ui-audit.ts",
"gen-agent-fold-types": "just gen-agent-fold-types",
"gen-database-sql-types": "just gen-database-sql-types",
+ "gen-agent-review-types": "just gen-agent-review-types",
"type-check": "bun ../../node_modules/typescript-native/bin/tsc --noEmit --skipLibCheck --project tsconfig.json",
"check": "bun check-graphql-cache-schema && bun type-check && bun biome check",
"preview": "vite preview -c vite.config.ts --outDir dist --base /app",
diff --git a/apps/web/src/features/agent-reviews/core/import-plan.test.ts b/apps/web/src/features/agent-reviews/core/import-plan.test.ts
index c92a347f61..79080981cc 100644
--- a/apps/web/src/features/agent-reviews/core/import-plan.test.ts
+++ b/apps/web/src/features/agent-reviews/core/import-plan.test.ts
@@ -312,22 +312,33 @@ describe('importReviewPhase', () => {
importReviewPhase({ presentedAt: null }, undefined, undefined)
).toEqual({ kind: 'preparing' });
expect(
- importReviewPhase({ presentedAt: 1 }, { status: 'pending' }, progress)
+ importReviewPhase(
+ { presentedAt: 1 },
+ { status: 'pending', error: null },
+ progress
+ )
).toEqual({ kind: 'plan' });
expect(
importReviewPhase(
{ presentedAt: 1 },
- { status: 'pending' },
+ { status: 'pending', error: null },
{ ...progress, status: 'running' }
)
).toEqual({ kind: 'planning' });
expect(
- importReviewPhase({ presentedAt: 1 }, { status: 'dismissed' }, undefined)
+ importReviewPhase(
+ { presentedAt: 1 },
+ { status: 'dismissed', error: null },
+ undefined
+ )
).toEqual({ kind: 'dismissed' });
});
it('follows the run once the plan is approved', () => {
- const completed = { status: 'completed' as const };
+ const completed: { status: 'completed'; error: null } = {
+ status: 'completed',
+ error: null,
+ };
expect(importReviewPhase({ presentedAt: 1 }, completed, progress)).toEqual({
kind: 'importing',
});
diff --git a/apps/web/src/features/agent-reviews/core/import-plan.ts b/apps/web/src/features/agent-reviews/core/import-plan.ts
index d4df9726af..e3e48cea2e 100644
--- a/apps/web/src/features/agent-reviews/core/import-plan.ts
+++ b/apps/web/src/features/agent-reviews/core/import-plan.ts
@@ -1,3 +1,4 @@
+import type { ImportDraft as SavedImportDraft } from '@service-agent-reviews/generated/types';
import { match } from 'ts-pattern';
import type { Review, ReviewItem } from './review';
@@ -106,12 +107,17 @@ export type ImportReviewPhase =
* The saved draft of an import review. `shared` and `personal` hold the rows
* the owner switched to or from team sharing, against the plan's choice.
*/
-export type ImportDraft = {
- source: 'notion' | 'linear' | 'jira';
- excluded: string[];
- shared: string[];
- personal: string[];
-};
+export type ImportDraft = Required<SavedImportDraft>;
+
+/** A saved import draft with its omitted row lists filled in. */
+export function withRowLists(draft: SavedImportDraft): ImportDraft {
+ return {
+ source: draft.source,
+ excluded: draft.excluded ?? [],
+ shared: draft.shared ?? [],
+ personal: draft.personal ?? [],
+ };
+}
export const EMPTY_IMPORT_DRAFT: ImportDraft = {
source: 'notion',
diff --git a/apps/web/src/features/agent-reviews/core/review.ts b/apps/web/src/features/agent-reviews/core/review.ts
index 89bee4e765..da642a54a6 100644
--- a/apps/web/src/features/agent-reviews/core/review.ts
+++ b/apps/web/src/features/agent-reviews/core/review.ts
@@ -1,28 +1,15 @@
+import type {
+ ReviewDecision_Deserialize,
+ ReviewDraft_Deserialize,
+ ReviewRecord_Serialize,
+} from '@service-agent-reviews/generated/types';
+
/** A saved interaction is independent from the code run that prepared it. */
-export type Review = {
- id: string;
- sessionId: string;
- actingUser?: string | null;
- executionId?: string | null;
- kind: 'email' | 'calendar' | 'import';
- title: string;
- revision: number;
- updatedAt: number;
- presentedAt?: number | null;
- /** The most recent decision; `chat` when the agent acted on the account holder's word. */
- decision?: { via: 'card' | 'chat' | 'inbox' } | null;
- items: ReviewItem[];
-};
-export type ReviewItem = {
- id: string;
- draft: unknown;
- status: 'pending' | 'submitting' | 'completed' | 'dismissed' | 'unknown';
- result?: unknown;
- error?: string | null;
-};
-export type ReviewDecision =
- | { action: 'edit'; revision: number; item: string; draft: unknown }
- | { action: 'submit' | 'dismiss'; revision: number; items: string[] };
+export type Review = ReviewRecord_Serialize;
+export type ReviewItem = Review['items'][number];
+/** A replacement draft, keyed by its review's kind. */
+export type ReviewDraft = ReviewDraft_Deserialize;
+export type ReviewDecision = ReviewDecision_Deserialize;
export type ReviewActions = {
reload: () => Promise<Review>;
decide: (decision: ReviewDecision) => Promise<Review>;
diff --git a/apps/web/src/features/agent-reviews/primitives/import-review.ts b/apps/web/src/features/agent-reviews/primitives/import-review.ts
index 569a3ec0ec..28b9a114f4 100644
--- a/apps/web/src/features/agent-reviews/primitives/import-review.ts
+++ b/apps/web/src/features/agent-reviews/primitives/import-review.ts
@@ -22,11 +22,10 @@ import {
setShared,
sharingSummary,
visiblePlanNodes,
+ withRowLists,
} from '../core/import-plan';
import type { Review, ReviewActions } from '../core/review';
-import { decodeImportDraft } from '../queries/import-plan';
import { createReviewController } from './review-controller';
-import { validateReviewDraft } from './review-draft-validation';
export type ImportReviewSources = {
review: Accessor<Review>;
@@ -45,17 +44,20 @@ export type ImportReviewSources = {
* progress. Edits go through the review controller, which serializes saves.
*/
export function createImportReview(sources: ImportReviewSources) {
- const controller = createReviewController(
- sources.review,
- sources.actions,
- validateReviewDraft
- );
+ const controller = createReviewController(sources.review, sources.actions);
const record = controller.record;
- const item = () => record().items[0];
+ const item = () => {
+ const review = record();
+ return review.kind === 'import' ? review.items[0] : undefined;
+ };
// Shown until the review is reloaded; the controller saves it in order.
const [editedDraft, setEditedDraft] = createSignal<ImportDraft>();
- const draft = (): ImportDraft =>
- editedDraft() ?? decodeImportDraft(item()?.draft) ?? EMPTY_IMPORT_DRAFT;
+ const draft = (): ImportDraft => {
+ const saved = item();
+ return (
+ editedDraft() ?? (saved ? withRowLists(saved.draft) : EMPTY_IMPORT_DRAFT)
+ );
+ };
const nodes = createMemo(() =>
buildPlanTree(planTreeEntries(sources.entries()))
);
@@ -97,14 +99,14 @@ export function createImportReview(sources: ImportReviewSources) {
if (!current || !editable()) return;
const next = setExcluded(draft(), nodes(), id, !included);
setEditedDraft(next);
- controller.edit(current.id, next);
+ controller.edit(current.id, { kind: 'import', draft: next });
}
function setSharedWithTeam(id: string, shared: boolean) {
const current = item();
if (!current || !editable()) return;
const next = setShared(draft(), nodes(), id, shared);
setEditedDraft(next);
- controller.edit(current.id, next);
+ controller.edit(current.id, { kind: 'import', draft: next });
}
function toggleRows(id: string) {
const next = new Set(showingRows());
@@ -181,7 +183,7 @@ export function createImportReview(sources: ImportReviewSources) {
stopping,
stopFailed,
error: controller.error,
- validation: () => controller.validation()?.message,
+ validation: controller.validation,
stale: controller.stale,
setIncluded,
setShared: setSharedWithTeam,
diff --git a/apps/web/src/features/agent-reviews/primitives/review-controller.test.ts b/apps/web/src/features/agent-reviews/primitives/review-controller.test.ts
index 4ad3bb7f3f..4320eafe9f 100644
--- a/apps/web/src/features/agent-reviews/primitives/review-controller.test.ts
+++ b/apps/web/src/features/agent-reviews/primitives/review-controller.test.ts
@@ -1,20 +1,39 @@
/** @vitest-environment jsdom */
+import { ThrownResultError } from '@core/util/result';
+import { INVALID_REVIEW_DECISION } from '@service-agent-harness/reviews';
import { createRoot, createSignal } from 'solid-js';
import { afterEach, describe, expect, it, vi } from 'vitest';
import type { Review, ReviewDecision } from '../core/review';
import { createReviewController } from './review-controller';
-const initial: Review = {
+type EmailReview = Review & { kind: 'email' };
+
+const initial: EmailReview = {
id: 'review',
sessionId: 'session',
+ actingUser: 'macro|[email protected]',
executionId: 'execution',
+ presentedAt: null,
+ decision: null,
kind: 'email',
title: 'Emails',
revision: 0,
updatedAt: 0,
items: [
- { id: 'one', draft: { subject: 'Ready?' }, status: 'pending' },
- { id: 'two', draft: { subject: 'When?' }, status: 'pending' },
+ {
+ id: 'one',
+ draft: { subject: 'Ready?', body: '', to: [{ email: '[email protected]' }] },
+ status: 'pending',
+ error: null,
+ result: null,
+ },
+ {
+ id: 'two',
+ draft: { subject: 'When?', body: '', to: [{ email: '[email protected]' }] },
+ status: 'pending',
+ error: null,
+ result: null,
+ },
],
};
const cleanups: Array<() => void> = [];
@@ -23,49 +42,52 @@ afterEach(() => {
});
function setup(
fail = false,
- validate?: (
- item: Review['items'][number],
- kind: Review['kind']
- ) => string | undefined
+ refuseSubmit?: (record: EmailReview) => string | undefined
) {
let saved = structuredClone(initial);
const actions = {
- reload: async () => structuredClone(saved),
- decide: vi.fn(async (decision: ReviewDecision) => {
+ reload: async (): Promise<Review> => structuredClone(saved),
+ decide: vi.fn(async (decision: ReviewDecision): Promise<Review> => {
if (fail || decision.revision !== saved.revision)
throw new Error('conflict');
+ const refusal =
+ decision.action === 'submit' ? refuseSubmit?.(saved) : undefined;
+ if (refusal)
+ throw new ThrownResultError([
+ { code: INVALID_REVIEW_DECISION, message: refusal },
+ ]);
saved = {
...saved,
revision: saved.revision + 1,
- items: saved.items.map((item) =>
- decision.action === 'edit'
- ? item.id === decision.item
- ? { ...item, draft: decision.draft }
- : item
- : decision.items.length === 0 || decision.items.includes(item.id)
- ? {
- ...item,
- status:
- decision.action === 'submit' ? 'submitting' : 'dismissed',
- }
- : item
- ),
+ items: saved.items.map((item) => {
+ if (decision.action === 'edit')
+ return item.id === decision.item && decision.draft.kind === 'email'
+ ? { ...item, draft: decision.draft.draft }
+ : item;
+ return decision.items.length === 0 || decision.items.includes(item.id)
+ ? {
+ ...item,
+ status:
+ decision.action === 'submit' ? 'submitting' : 'dismissed',
+ }
+ : item;
+ }),
};
return structuredClone(saved);
}),
};
const controller = createRoot((dispose) => {
cleanups.push(dispose);
- return createReviewController(() => initial, actions, validate);
+ return createReviewController(() => initial, actions);
});
return { controller, actions };
}
describe('persisted review decisions', () => {
it('adopts presentation acknowledgments but preserves conflicting editor data', async () => {
- const [source, update] = createSignal(initial);
+ const [source, update] = createSignal<EmailReview>(initial);
const actions = {
- reload: async () => source(),
- decide: vi.fn(async () => source()),
+ reload: async (): Promise<Review> => source(),
+ decide: vi.fn(async (): Promise<Review> => source()),
};
const controller = createRoot((dispose) => {
cleanups.push(dispose);
@@ -80,7 +102,7 @@ describe('persisted review decisions', () => {
revision: 2,
items: initial.items.map((item) => ({
...item,
- draft: { subject: 'Changed elsewhere' },
+ draft: { ...item.draft, subject: 'Changed elsewhere' },
})),
});
await Promise.resolve();
@@ -88,8 +110,22 @@ describe('persisted review decisions', () => {
});
it('saves the latest edits before sending all, using the acknowledged revision', async () => {
const { controller, actions } = setup();
- controller.edit('one', { subject: 'Ready?', body: 'Yes' });
- controller.edit('two', { subject: 'When?', body: 'Tomorrow' });
+ controller.edit('one', {
+ kind: 'email',
+ draft: {
+ subject: 'Ready?',
+ body: 'Yes',
+ to: [{ email: '[email protected]' }],
+ },
+ });
+ controller.edit('two', {
+ kind: 'email',
+ draft: {
+ subject: 'When?',
+ body: 'Tomorrow',
+ to: [{ email: '[email protected]' }],
+ },
+ });
expect(await controller.decide('submit', [])).toBe(true);
expect(
actions.decide.mock.calls.map(([call]) => [call.action, call.revision])
@@ -102,39 +138,32 @@ describe('persisted review decisions', () => {
controller.record().items.every((item) => item.status === 'submitting')
).toBe(true);
});
- it('preflights every selected item before starting any batch action', async () => {
- const { controller, actions } = setup(false, (item) =>
- item.id === 'two' && !JSON.stringify(item.draft).includes('Fixed')
- ? 'Fix the second draft.'
+ it('shows a refused submission as validation without blocking the review', async () => {
+ const { controller, actions } = setup(false, (record) =>
+ record.items[1].draft.to.length === 0
+ ? 'Add at least one recipient.'
: undefined
);
- expect(await controller.decide('submit', [])).toBe(false);
- expect(actions.decide).not.toHaveBeenCalled();
- expect(controller.validation()).toEqual({
- item: 'two',
- message: 'Fix the second draft.',
+ controller.edit('two', {
+ kind: 'email',
+ draft: { subject: 'When?', body: '', to: [] },
});
+ expect(await controller.decide('submit', [])).toBe(false);
+ expect(controller.validation()).toBe('Add at least one recipient.');
expect(controller.error()).toBeUndefined();
- controller.edit('two', { subject: 'Fixed' });
+ controller.edit('two', {
+ kind: 'email',
+ draft: { subject: 'When?', body: '', to: [{ email: '[email protected]' }] },
+ });
expect(controller.validation()).toBeUndefined();
expect(await controller.decide('submit', [])).toBe(true);
expect(actions.decide.mock.calls.map(([call]) => call.action)).toEqual([
'edit',
'submit',
+ 'edit',
+ 'submit',
]);
});
- it('does not let an unrelated invalid draft block an individual submission', async () => {
- const { controller, actions } = setup(false, (item) =>
- item.id === 'two' ? 'Fix the second draft.' : undefined
- );
- expect(await controller.decide('submit', ['one'])).toBe(true);
- expect(actions.decide).toHaveBeenCalledExactlyOnceWith({
- action: 'submit',
- revision: 0,
- items: ['one'],
- });
- expect(controller.record().items[1].status).toBe('pending');
- });
it('a simultaneous second click cannot submit twice', async () => {
const { controller, actions } = setup();
const first = controller.decide('submit', ['one']);
@@ -144,7 +173,14 @@ describe('persisted review decisions', () => {
});
it('a failed save stops submission and requires explicit reload', async () => {
const { controller, actions } = setup(true);
- controller.edit('one', { subject: 'Ready?', body: 'Changed' });
+ controller.edit('one', {
+ kind: 'email',
+ draft: {
+ subject: 'Ready?',
+ body: 'Changed',
+ to: [{ email: '[email protected]' }],
+ },
+ });
expect(await controller.decide('submit', [])).toBe(false);
expect(actions.decide.mock.calls.map(([call]) => call.action)).toEqual([
'edit',
@@ -155,7 +191,14 @@ describe('persisted review decisions', () => {
});
it('serialized flushes cannot reuse a revision', async () => {
const { controller, actions } = setup();
- controller.edit('one', { subject: 'Ready?', body: 'Yes' });
+ controller.edit('one', {
+ kind: 'email',
+ draft: {
+ subject: 'Ready?',
+ body: 'Yes',
+ to: [{ email: '[email protected]' }],
+ },
+ });
expect(await Promise.all([controller.flush(), controller.flush()])).toEqual(
[true, true]
);
diff --git a/apps/web/src/features/agent-reviews/primitives/review-controller.ts b/apps/web/src/features/agent-reviews/primitives/review-controller.ts
index b7212f1f8d..3e854484bf 100644
--- a/apps/web/src/features/agent-reviews/primitives/review-controller.ts
+++ b/apps/web/src/features/agent-reviews/primitives/review-controller.ts
@@ -1,23 +1,25 @@
import { fireAndForget } from '@core/util/fireAndForget';
+import { ThrownResultError, thrownResultErrorHasCode } from '@core/util/result';
+import { INVALID_REVIEW_DECISION } from '@service-agent-harness/reviews';
import { debounce } from '@solid-primitives/scheduled';
import { type Accessor, createEffect, createSignal, onCleanup } from 'solid-js';
-import type { Review, ReviewActions, ReviewItem } from '../core/review';
+import type { Review, ReviewActions, ReviewDraft } from '../core/review';
-/** Serial saves share an acknowledged revision; conflicts never retry a send. */
+/**
+ * Serial saves share an acknowledged revision; conflicts never retry a send.
+ * The server checks that each selected draft is complete before it claims a
+ * batch, and its refusal is shown as the validation message.
+ */
export function createReviewController(
source: Accessor<Review>,
- actions: ReviewActions,
- validateDraft?: (item: ReviewItem, kind: Review['kind']) => string | undefined
+ actions: ReviewActions
) {
const [saved, setSaved] = createSignal(source());
const [busy, setBusy] = createSignal(false);
const [error, setError] = createSignal<string>();
const [saving, setSaving] = createSignal(false);
- const [validation, setValidation] = createSignal<{
- item: string;
- message: string;
- }>();
- const drafts = new Map<string, unknown>();
+ const [validation, setValidation] = createSignal<string>();
+ const drafts = new Map<string, ReviewDraft>();
let tail: Promise<void> = Promise.resolve();
const record = () =>
source().revision > saved().revision ? source() : saved();
@@ -81,11 +83,11 @@ export function createReviewController(
const saveLater = debounce(() => {
fireAndForget(flush(), 'agent-reviews');
}, 300);
- function edit(item: string, draft: unknown) {
+ function edit(item: string, draft: ReviewDraft) {
if (busy() || error()) return;
setValidation(undefined);
const existing = saved().items.find((entry) => entry.id === item);
- if (JSON.stringify(existing?.draft) === JSON.stringify(draft)) return;
+ if (JSON.stringify(existing?.draft) === JSON.stringify(draft.draft)) return;
drafts.set(item, draft);
saveLater();
}
@@ -98,26 +100,19 @@ export function createReviewController(
saveLater.clear();
try {
if (!(await flush())) return false;
- if (action === 'submit' && validateDraft) {
- for (const item of record().items) {
- if (
- item.status !== 'pending' ||
- (items.length > 0 && !items.includes(item.id))
- )
- continue;
- const message = validateDraft(item, record().kind);
- if (message) {
- setValidation({ item: item.id, message });
- return false;
- }
- }
- }
setValidation(undefined);
setSaved(
await actions.decide({ action, revision: saved().revision, items })
);
return true;
- } catch {
+ } catch (failure) {
+ if (
+ failure instanceof ThrownResultError &&
+ thrownResultErrorHasCode(failure, INVALID_REVIEW_DECISION)
+ ) {
+ setValidation(failure.message);
+ return false;
+ }
setError(
'The review changed or the request could not be confirmed. Reload its saved status before taking another action.'
);
diff --git a/apps/web/src/features/agent-reviews/primitives/review-draft-validation.test.ts b/apps/web/src/features/agent-reviews/primitives/review-draft-validation.test.ts
deleted file mode 100644
index a4242e3258..0000000000
--- a/apps/web/src/features/agent-reviews/primitives/review-draft-validation.test.ts
+++ /dev/null
@@ -1,71 +0,0 @@
-/** @vitest-environment jsdom */
-import { describe, expect, it } from 'vitest';
-import type { ReviewItem } from '../core/review';
-import { validateReviewDraft } from './review-draft-validation';
-
-const email = {
- subject: 'Update',
- to: [{ email: '[email protected]' }],
- body: '**Hello**',
-};
-const event = {
- title: 'Planning',
- time: {
- kind: 'timed',
- startsAt: '2026-10-20T10:00:00Z',
- endsAt: '2026-10-20T11:00:00Z',
- },
-};
-function item(draft: unknown): ReviewItem {
- return { id: 'draft', draft, status: 'pending' };
-}
-describe('review submission preflight', () => {
- it('accepts unvisited Markdown and composer HTML without rewriting either', () => {
- for (const body of ['**Hello**', btoa('<body><p>Hello</p></body>')]) {
- const draft = { ...email, body };
- expect(validateReviewDraft(item(draft), 'email')).toBeUndefined();
- expect(draft.body).toBe(body);
- }
- });
- it('rejects empty messages, missing recipients and invalid addresses', () => {
- for (const draft of [
- { ...email, body: ' ' },
- { ...email, body: btoa('<body><p><br></p></body>') },
- { ...email, to: [] },
- { ...email, cc: [{ email: 'bad-address' }] },
- { subject: 'Missing fields' },
- ])
- expect(validateReviewDraft(item(draft), 'email')).toBeTruthy();
- });
- it('accepts timed and all-day events and rejects impossible ranges', () => {
- expect(validateReviewDraft(item(event), 'calendar')).toBeUndefined();
- expect(
- validateReviewDraft(
- item({
- ...event,
- time: {
- kind: 'allDay',
- startDate: '2026-10-20',
- endDate: '2026-10-21',
- },
- }),
- 'calendar'
- )
- ).toBeUndefined();
- for (const draft of [
- { ...event, title: '' },
- { ...event, time: { ...event.time, endsAt: event.time.startsAt } },
- {
- ...event,
- time: {
- kind: 'allDay',
- startDate: '2026-10-21',
- endDate: '2026-10-20',
- },
- },
- { ...event, attendees: [{ email: 'invalid' }] },
- { ...event, addConference: true, addMacroCall: true },
- ])
- expect(validateReviewDraft(item(draft), 'calendar')).toBeTruthy();
- });
-});
diff --git a/apps/web/src/features/agent-reviews/primitives/review-draft-validation.ts b/apps/web/src/features/agent-reviews/primitives/review-draft-validation.ts
deleted file mode 100644
index 7bdb11d119..0000000000
--- a/apps/web/src/features/agent-reviews/primitives/review-draft-validation.ts
+++ /dev/null
@@ -1,69 +0,0 @@
-import { decodeBase64Utf8 } from '@app/features/email-compose/core/decode-base64';
-import {
- CreateCalendarEvent,
- SendEmail,
-} from '@service-cognition/generated/tools/schemas';
-import * as EmailValidator from 'email-validator';
-import { match } from 'ts-pattern';
-import type { Review, ReviewItem } from '../core/review';
-import { decodeImportDraft } from '../queries/import-plan';
-
-/** Preflight every selected draft before a batch can start external actions. */
-export function validateReviewDraft(
- item: ReviewItem,
- kind: Review['kind']
-): string | undefined {
- return match(kind)
- .with('email', () => validateEmailDraft(item.draft))
- .with('calendar', () => validateCalendarDraft(item.draft))
- .with('import', () =>
- decodeImportDraft(item.draft)
- ? undefined
- : 'This import plan cannot be read. Reload it before importing.'
- )
- .exhaustive();
-}
-
-function validateEmailDraft(value: unknown): string | undefined {
- const parsed = SendEmail.safeParse(value);
- if (!parsed.success)
- return 'This email has invalid fields. Review it before sending.';
- const draft = parsed.data;
- if (draft.to.length === 0) return 'Add at least one recipient.';
- if (
- [...draft.to, ...(draft.cc ?? []), ...(draft.bcc ?? [])].some(
- (recipient) => !EmailValidator.validate(recipient.email)
- )
- )
- return 'Correct the email addresses before sending.';
- const decoded = decodeBase64Utf8(draft.body);
- const content =
- decoded !== draft.body && /^\s*</.test(decoded)
- ? new DOMParser().parseFromString(decoded, 'text/html').body.textContent
- : draft.body;
- if (!content?.trim()) return 'Write a message before sending.';
-}
-
-function validateCalendarDraft(value: unknown): string | undefined {
- const parsed = CreateCalendarEvent.safeParse(value);
- if (!parsed.success)
- return 'This event has invalid fields. Review it before creating.';
- const draft = parsed.data;
- if (!draft.title.trim()) return 'Give this event a title.';
- const time = draft.time;
- if (!time) return 'Choose the event start and end.';
- const start = Date.parse(
- time.kind === 'timed' ? time.startsAt : time.startDate
- );
- const end = Date.parse(time.kind === 'timed' ? time.endsAt : time.endDate);
- if (!Number.isFinite(start) || !Number.isFinite(end) || end <= start)
- return 'The event must end after it starts.';
- if (draft.addMacroCall && draft.addConference)
- return 'Choose either a Macro call or a video meeting.';
- if (
- (draft.attendees ?? []).some(
- (guest) => !EmailValidator.validate(guest.email)
- )
- )
- return 'Correct the guest email addresses before creating.';
-}
diff --git a/apps/web/src/features/agent-reviews/queries/import-plan.test.ts b/apps/web/src/features/agent-reviews/queries/import-plan.test.ts
index b928761892..701d34771f 100644
--- a/apps/web/src/features/agent-reviews/queries/import-plan.test.ts
+++ b/apps/web/src/features/agent-reviews/queries/import-plan.test.ts
@@ -1,6 +1,6 @@
import type { ImportEntity } from '@queries/import';
import { describe, expect, it } from 'vitest';
-import { decodeImportDraft, decodePlanEntries } from './import-plan';
+import { decodePlanEntries } from './import-plan';
const row: ImportEntity = {
id: 'roadmap',
@@ -128,34 +128,7 @@ describe('decodePlanEntries while planning', () => {
});
});
-describe('decodeImportDraft', () => {
- it('reads the excluded and re-shared rows and rejects other drafts', () => {
- expect(decodeImportDraft({ source: 'notion' })).toEqual({
- source: 'notion',
- excluded: [],
- shared: [],
- personal: [],
- });
- expect(
- decodeImportDraft({
- source: 'notion',
- excluded: ['roadmap'],
- shared: ['wiki'],
- personal: ['q3'],
- })
- ).toEqual({
- source: 'notion',
- excluded: ['roadmap'],
- shared: ['wiki'],
- personal: ['q3'],
- });
- expect(decodeImportDraft({ subject: 'Hi' })).toBeUndefined();
- });
-});
-
it('decodes tracker tasks and projects while isolating review ids', () => {
- expect(decodeImportDraft({ source: 'linear' })?.source).toBe('linear');
- expect(decodeImportDraft({ source: 'jira' })?.source).toBe('jira');
const decoded = decodePlanEntries(
[
{ ...row, id: 'l', source: 'linear', kind: 'issue' },
diff --git a/apps/web/src/features/agent-reviews/queries/import-plan.ts b/apps/web/src/features/agent-reviews/queries/import-plan.ts
index 4c5dfc05df..8409ef7a12 100644
--- a/apps/web/src/features/agent-reviews/queries/import-plan.ts
+++ b/apps/web/src/features/agent-reviews/queries/import-plan.ts
@@ -7,25 +7,6 @@ import type {
ImportProgress,
} from '../core/import-plan';
-const importDraftSchema = z.object({
- source: z.enum(['notion', 'linear', 'jira']),
- excluded: z.array(z.string()).optional(),
- shared: z.array(z.string()).optional(),
- personal: z.array(z.string()).optional(),
-});
-
-/** The saved draft of an import review; `undefined` when it is not one. */
-export function decodeImportDraft(draft: unknown): ImportDraft | undefined {
- const parsed = importDraftSchema.safeParse(draft);
- if (!parsed.success) return undefined;
- return {
- source: parsed.data.source,
- excluded: parsed.data.excluded ?? [],
- shared: parsed.data.shared ?? [],
- personal: parsed.data.personal ?? [],
- };
-}
-
const planMetadataSchema = z.object({
title: z.string(),
plan: z.object({
diff --git a/apps/web/src/features/agent-reviews/views/import-review.test.tsx b/apps/web/src/features/agent-reviews/views/import-review.test.tsx
index c9a062e0c4..cd05860391 100644
--- a/apps/web/src/features/agent-reviews/views/import-review.test.tsx
+++ b/apps/web/src/features/agent-reviews/views/import-review.test.tsx
@@ -8,16 +8,29 @@ import {
waitFor,
within,
} from '@solidjs/testing-library';
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import type { Review, ReviewDecision, ReviewItem } from '../core/review';
+import {
+ afterEach,
+ beforeEach,
+ describe,
+ expect,
+ it,
+ type Mock,
+ vi,
+} from 'vitest';
+import type { Review, ReviewDecision } from '../core/review';
import { ImportReview } from './import-review';
-const imports = vi.hoisted(() => ({
- entities: [] as ImportEntity[],
- report: undefined as NotionImportReport | undefined,
- cancel: vi.fn(),
- open: vi.fn(),
-}));
+type ImportReviewRecord = Review & { kind: 'import' };
+
+const imports = vi.hoisted(() => {
+ const state: {
+ entities: ImportEntity[];
+ report: NotionImportReport | undefined;
+ cancel: Mock;
+ open: Mock;
+ } = { entities: [], report: undefined, cancel: vi.fn(), open: vi.fn() };
+ return state;
+});
vi.mock('@components/app/split-layout/layout', () => ({
useSplitLayout: () => ({ openWithSplit: imports.open }),
}));
@@ -129,42 +142,50 @@ afterEach(() => {
function setup(
options: {
- item?: Partial<ReviewItem>;
+ item?: Partial<ImportReviewRecord['items'][0]>;
canAct?: boolean;
- review?: Partial<Review>;
+ review?: Partial<Omit<ImportReviewRecord, 'kind' | 'items'>>;
} = {}
) {
- let record: Review = {
+ let record: ImportReviewRecord = {
id: 'review',
sessionId: 'session',
+ actingUser: 'macro|[email protected]',
+ executionId: null,
kind: 'import',
title: 'Import from Notion',
revision: 0,
updatedAt: 0,
presentedAt: 1,
+ decision: null,
items: [
{
id: 'plan',
status: 'pending',
+ error: null,
draft: { source: 'notion' },
+ result: null,
...options.item,
},
],
...options.review,
};
- const decide = vi.fn(async (decision: ReviewDecision) => {
+ const decide = vi.fn(async (decision: ReviewDecision): Promise<Review> => {
if (decision.revision !== record.revision) throw new Error('conflict');
+ const [item] = record.items;
record = {
...record,
revision: record.revision + 1,
- items: record.items.map((item) =>
+ items: [
decision.action === 'edit'
- ? { ...item, draft: decision.draft }
+ ? decision.draft.kind === 'import'
+ ? { ...item, draft: decision.draft.draft }
+ : item
: {
...item,
status: decision.action === 'submit' ? 'submitting' : 'dismissed',
- }
- ),
+ },
+ ],
};
return record;
});
@@ -201,10 +222,13 @@ describe('import review', () => {
revision: 0,
item: 'plan',
draft: {
- source: 'notion',
- excluded: ['roadmap'],
- shared: [],
- personal: [],
+ kind: 'import',
+ draft: {
+ source: 'notion',
+ excluded: ['roadmap'],
+ shared: [],
+ personal: [],
+ },
},
})
);
@@ -291,7 +315,9 @@ describe('import review', () => {
it("says when the agent started the import at the owner's request", () => {
setup({
item: { status: 'submitting' },
- review: { decision: { via: 'chat' } },
+ review: {
+ decision: { by: 'owner', via: 'chat', revision: 0, items: [] },
+ },
});
expect(
screen.getByText('Started by the agent at your request')
@@ -376,10 +402,13 @@ describe('import review', () => {
revision: 0,
item: 'plan',
draft: {
- source: 'notion',
- excluded: [],
- shared: [],
- personal: ['wiki', 'guide'],
+ kind: 'import',
+ draft: {
+ source: 'notion',
+ excluded: [],
+ shared: [],
+ personal: ['wiki', 'guide'],
+ },
},
})
);
@@ -399,10 +428,13 @@ describe('import review', () => {
revision: 1,
item: 'plan',
draft: {
- source: 'notion',
- excluded: [],
- shared: [],
- personal: ['wiki'],
+ kind: 'import',
+ draft: {
+ source: 'notion',
+ excluded: [],
+ shared: [],
+ personal: ['wiki'],
+ },
},
})
);
@@ -415,7 +447,10 @@ describe('import review', () => {
action: 'edit',
revision: 2,
item: 'plan',
- draft: { source: 'notion', excluded: [], shared: [], personal: [] },
+ draft: {
+ kind: 'import',
+ draft: { source: 'notion', excluded: [], shared: [], personal: [] },
+ },
})
);
diff --git a/apps/web/src/features/agent-reviews/views/import-review.tsx b/apps/web/src/features/agent-reviews/views/import-review.tsx
index 98887358cb..63e5304606 100644
--- a/apps/web/src/features/agent-reviews/views/import-review.tsx
+++ b/apps/web/src/features/agent-reviews/views/import-review.tsx
@@ -15,7 +15,6 @@ import type { ImportedCopy } from '../core/import-plan';
import type { Review, ReviewActions } from '../core/review';
import { createImportReview } from '../primitives/import-review';
import {
- decodeImportDraft,
decodeImportProgress,
decodePlanEntries,
} from '../queries/import-plan';
@@ -28,13 +27,12 @@ function copyBlock(copy: ImportedCopy) {
/** An import review shows its plan, then the run it started. */
export function ImportReview(props: {
- review: Review;
+ review: Extract<Review, { kind: 'import' }>;
canAct: boolean;
actions: ReviewActions;
}) {
const state = useImportQuery();
- const source = () =>
- decodeImportDraft(props.review.items[0]?.draft)?.source ?? 'notion';
+ const source = () => props.review.items[0].draft.source;
const report = useWorkspaceImportReportQuery(source);
const cancel = useCancelWorkspaceImportMutation(source);
const layout = useSplitLayout();
diff --git a/apps/web/src/features/agent-reviews/views/persisted-review.test.tsx b/apps/web/src/features/agent-reviews/views/persisted-review.test.tsx
index a599afb645..44ed6c93fc 100644
--- a/apps/web/src/features/agent-reviews/views/persisted-review.test.tsx
+++ b/apps/web/src/features/agent-reviews/views/persisted-review.test.tsx
@@ -1,13 +1,16 @@
/** @vitest-environment jsdom */
import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';
-import { afterEach, describe, expect, it, vi } from 'vitest';
+import { afterEach, describe, expect, it, type Mock, vi } from 'vitest';
import type { Review, ReviewActions } from '../core/review';
import { PersistedReview } from './persisted-review';
-const reviews = vi.hoisted(() => ({
- record: undefined as Review | undefined,
- decide: vi.fn(),
-}));
+const reviews = vi.hoisted(() => {
+ const state: {
+ record: Review | undefined;
+ decide: Mock<ReviewActions['decide']>;
+ } = { record: undefined, decide: vi.fn() };
+ return state;
+});
vi.mock('../queries/reviews', () => ({
useReview: () => ({
isError: false,
@@ -59,18 +62,48 @@ vi.mock('./review-stack', () => ({
Card(props),
}));
-function review(kind: Review['kind']): Review {
- return {
- id: 'review',
- sessionId: 'session',
- kind,
- title: 'Review',
- revision: 1,
- updatedAt: 1,
- presentedAt: 1,
- items: [{ id: 'item', draft: {}, status: 'pending' }],
- };
-}
+const importReview: Review = {
+ id: 'review',
+ sessionId: 'session',
+ actingUser: 'macro|[email protected]',
+ executionId: null,
+ kind: 'import',
+ title: 'Review',
+ revision: 1,
+ updatedAt: 1,
+ presentedAt: 1,
+ decision: null,
+ items: [
+ {
+ id: 'item',
+ draft: { source: 'notion' },
+ status: 'pending',
+ error: null,
+ result: null,
+ },
+ ],
+};
+const emailReview: Review = {
+ id: 'review',
+ sessionId: 'session',
+ actingUser: 'macro|[email protected]',
+ executionId: null,
+ kind: 'email',
+ title: 'Review',
+ revision: 1,
+ updatedAt: 1,
+ presentedAt: 1,
+ decision: null,
+ items: [
+ {
+ id: 'item',
+ draft: { subject: 'Hello', body: '', to: [{ email: '[email protected]' }] },
+ status: 'pending',
+ error: null,
+ result: null,
+ },
+ ],
+};
afterEach(() => {
cleanup();
@@ -79,15 +112,14 @@ afterEach(() => {
describe('PersistedReview', () => {
it('expects no answer until an approved import settles', () => {
- reviews.record = review('import');
- reviews.decide.mockResolvedValue(review('import'));
+ reviews.record = importReview;
+ reviews.decide.mockResolvedValue(importReview);
const onDecision = vi.fn();
render(() => (
<PersistedReview
sessionId="session"
reviewId="review"
canAct
- ownerId="macro|[email protected]"
onDecision={onDecision}
/>
));
@@ -101,15 +133,14 @@ describe('PersistedReview', () => {
});
it('expects the agent to answer an approved email stack at once', () => {
- reviews.record = review('email');
- reviews.decide.mockResolvedValue(review('email'));
+ reviews.record = emailReview;
+ reviews.decide.mockResolvedValue(emailReview);
const onDecision = vi.fn();
render(() => (
<PersistedReview
sessionId="session"
reviewId="review"
canAct
- ownerId="macro|[email protected]"
onDecision={onDecision}
/>
));
diff --git a/apps/web/src/features/agent-reviews/views/persisted-review.tsx b/apps/web/src/features/agent-reviews/views/persisted-review.tsx
index 00e5acfada..875a59dc2c 100644
--- a/apps/web/src/features/agent-reviews/views/persisted-review.tsx
+++ b/apps/web/src/features/agent-reviews/views/persisted-review.tsx
@@ -12,7 +12,6 @@ export function PersistedReview(props: {
sessionId: string;
reviewId: string;
canAct: boolean;
- ownerId?: string;
eventId?: string;
onDecision?: () => void;
onDecisionFailed?: () => void;
@@ -63,22 +62,21 @@ export function PersistedReview(props: {
</Show>
<Show when={query.isSuccess ? query.data : undefined}>
{(record) => {
- const canAct = () =>
- props.canAct && userId() === (record().actingUser ?? props.ownerId);
+ const canAct = () => props.canAct && userId() === record().actingUser;
// A review's kind is fixed when it is saved.
- return match(record().kind)
- .with('import', () => (
+ return match(record())
+ .with({ kind: 'import' }, (review) => (
<ImportReview
- review={record()}
+ review={review}
canAct={canAct()}
actions={decisions('import')}
/>
))
- .with('email', 'calendar', (kind) => (
+ .with({ kind: 'email' }, { kind: 'calendar' }, (review) => (
<ReviewStack
- review={record()}
+ review={review}
canAct={canAct()}
- actions={decisions(kind)}
+ actions={decisions(review.kind)}
/>
))
.exhaustive();
diff --git a/apps/web/src/features/agent-reviews/views/review-stack.test.tsx b/apps/web/src/features/agent-reviews/views/review-stack.test.tsx
index bf0f08f6c3..17adf44016 100644
--- a/apps/web/src/features/agent-reviews/views/review-stack.test.tsx
+++ b/apps/web/src/features/agent-reviews/views/review-stack.test.tsx
@@ -1,4 +1,11 @@
/** @vitest-environment jsdom */
+
+import { ThrownResultError } from '@core/util/result';
+import { INVALID_REVIEW_DECISION } from '@service-agent-harness/reviews';
+import type {
+ ReviewItem,
+ ReviewItems_Serialize,
+} from '@service-agent-reviews/generated/types';
import {
cleanup,
fireEvent,
@@ -8,16 +15,27 @@ import {
within,
} from '@solidjs/testing-library';
import { createSignal } from 'solid-js';
+import { match } from 'ts-pattern';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import type { Review, ReviewDecision, ReviewItem } from '../core/review';
+import type { Review, ReviewDecision } from '../core/review';
import { ReviewStack } from './review-stack';
-const editor = vi.hoisted(() => ({
- ready: true,
- valid: true,
- submitReady: undefined as Promise<void> | undefined,
- executed: undefined as Promise<boolean> | undefined,
-}));
+type EmailReview = Review & { kind: 'email' };
+
+const editor = vi.hoisted(() => {
+ const state: {
+ ready: boolean;
+ valid: boolean;
+ submitReady: Promise<void> | undefined;
+ executed: Promise<boolean> | undefined;
+ } = {
+ ready: true,
+ valid: true,
+ submitReady: undefined,
+ executed: undefined,
+ };
+ return state;
+});
const mobile = vi.hoisted(() => ({ value: false }));
vi.mock('@core/mobile/isMobile', () => ({ isMobile: () => mobile.value }));
vi.mock('@core/mobile/virtualKeyboard', () => ({
@@ -103,74 +121,127 @@ afterEach(() => {
vi.unstubAllGlobals();
});
+/** The fake server's answer to a decision for one saved item. */
+function decided<Draft, Outcome>(
+ item: ReviewItem<Draft, Outcome>,
+ decision: ReviewDecision,
+ draft: Draft | undefined,
+ failedItem: string | undefined
+): ReviewItem<Draft, Outcome> {
+ if (decision.action === 'edit')
+ return item.id === decision.item && draft !== undefined
+ ? { ...item, draft }
+ : item;
+ if (
+ item.status !== 'pending' ||
+ (decision.items.length > 0 && !decision.items.includes(item.id))
+ )
+ return item;
+ if (decision.action === 'submit' && item.id === failedItem)
+ return { ...item, error: 'The destination rejected this draft.' };
+ return {
+ ...item,
+ status: decision.action === 'submit' ? 'completed' : 'dismissed',
+ };
+}
+
function setup(
options: {
canAct?: boolean;
presentedAt?: number | null;
- items?: ReviewItem[];
- kind?: Review['kind'];
+ content?: ReviewItems_Serialize;
failSave?: boolean;
failedItem?: string;
+ refuseSubmit?: (record: Review) => string | undefined;
} = {}
) {
let record: Review = {
id: 'review',
sessionId: 'session',
+ actingUser: 'macro|[email protected]',
executionId: 'execution',
- kind: options.kind ?? 'email',
title: 'Drafts to review',
revision: 0,
updatedAt: 0,
presentedAt: options.presentedAt === undefined ? 1 : options.presentedAt,
- items: options.items ?? [
- {
- id: 'first',
- status: 'pending',
- draft: {
- subject: 'First email',
- body: 'Hello',
- to: [{ email: '[email protected]' }],
+ decision: null,
+ ...(options.content ?? {
+ kind: 'email',
+ items: [
+ {
+ id: 'first',
+ status: 'pending',
+ error: null,
+ result: null,
+ draft: {
+ subject: 'First email',
+ body: 'Hello',
+ to: [{ email: '[email protected]' }],
+ },
},
- },
- {
- id: 'second',
- status: 'pending',
- draft: {
- subject: 'Second email',
- body: 'World',
- to: [{ email: '[email protected]' }],
+ {
+ id: 'second',
+ status: 'pending',
+ error: null,
+ result: null,
+ draft: {
+ subject: 'Second email',
+ body: 'World',
+ to: [{ email: '[email protected]' }],
+ },
},
- },
- ],
+ ],
+ }),
};
- const decide = vi.fn(async (decision: ReviewDecision) => {
+ const decide = vi.fn(async (decision: ReviewDecision): Promise<Review> => {
if (
decision.revision !== record.revision ||
(options.failSave && decision.action === 'edit')
)
throw new Error('conflict');
- record = {
- ...record,
- revision: record.revision + 1,
- items: record.items.map((item) => {
- if (decision.action === 'edit')
- return item.id === decision.item
- ? { ...item, draft: decision.draft }
- : item;
- if (
- item.status !== 'pending' ||
- (decision.items.length > 0 && !decision.items.includes(item.id))
- )
- return item;
- if (decision.action === 'submit' && item.id === options.failedItem) {
- return { ...item, error: 'The destination rejected this draft.' };
- }
+ const refusal =
+ decision.action === 'submit' ? options.refuseSubmit?.(record) : undefined;
+ if (refusal)
+ throw new ThrownResultError([
+ { code: INVALID_REVIEW_DECISION, message: refusal },
+ ]);
+ const revision = record.revision + 1;
+ record = match(record)
+ .with({ kind: 'email' }, (review): Review => {
+ const draft =
+ decision.action === 'edit' && decision.draft.kind === 'email'
+ ? decision.draft.draft
+ : undefined;
return {
- ...item,
- status: decision.action === 'submit' ? 'completed' : 'dismissed',
+ ...review,
+ revision,
+ items: review.items.map((item) =>
+ decided(item, decision, draft, options.failedItem)
+ ),
};
- }),
- };
+ })
+ // Calendar composers in these tests never change their drafts.
+ .with(
+ { kind: 'calendar' },
+ (review): Review => ({
+ ...review,
+ revision,
+ items: review.items.map((item) =>
+ decided(item, decision, undefined, options.failedItem)
+ ),
+ })
+ )
+ .with(
+ { kind: 'import' },
+ (review): Review => ({
+ ...review,
+ revision,
+ items: [
+ decided(review.items[0], decision, undefined, options.failedItem),
+ ],
+ })
+ )
+ .exhaustive();
return record;
});
render(() => (
@@ -214,17 +285,22 @@ describe('review deck', () => {
);
it('shows a single draft in its composer without navigation or batch actions', () => {
setup({
- items: [
- {
- id: 'one',
- status: 'pending',
- draft: {
- subject: 'One email',
- body: 'Hello',
- to: [{ email: '[email protected]' }],
+ content: {
+ kind: 'email',
+ items: [
+ {
+ id: 'one',
+ status: 'pending',
+ error: null,
+ result: null,
+ draft: {
+ subject: 'One email',
+ body: 'Hello',
+ to: [{ email: '[email protected]' }],
+ },
},
- },
- ],
+ ],
+ },
});
expect(screen.getByLabelText('Draft body')).toBeTruthy();
expect(screen.queryByRole('navigation')).toBeNull();
@@ -254,7 +330,7 @@ describe('review deck', () => {
expect(decide.mock.calls[0][0]).toMatchObject({
action: 'edit',
item: 'first',
- draft: { body: 'Edited first' },
+ draft: { kind: 'email', draft: { body: 'Edited first' } },
});
fireEvent.click(screen.getByRole('button', { name: 'Previous draft' }));
await waitFor(() =>
@@ -332,9 +408,12 @@ describe('review deck', () => {
expect(screen.getByText(/1 sent · 1 needs attention/)).toBeTruthy();
});
it('opens an uncertain draft once when a locally submitted batch finishes through polling', async () => {
- let server: Review = {
+ let server: EmailReview = {
id: 'review',
sessionId: 'session',
+ actingUser: 'macro|[email protected]',
+ executionId: null,
+ decision: null,
kind: 'email',
title: 'Polled drafts',
revision: 0,
@@ -344,6 +423,8 @@ describe('review deck', () => {
{
id: 'first',
status: 'pending',
+ error: null,
+ result: null,
draft: {
subject: 'First email',
body: 'Hello',
@@ -353,6 +434,8 @@ describe('review deck', () => {
{
id: 'second',
status: 'pending',
+ error: null,
+ result: null,
draft: {
subject: 'Second email',
body: 'World',
@@ -421,9 +504,12 @@ describe('review deck', () => {
expect(decide).toHaveBeenCalledOnce();
});
it('does not change the selected card for outcomes from a batch started elsewhere', async () => {
- const initial: Review = {
+ const initial: EmailReview = {
id: 'review',
sessionId: 'session',
+ actingUser: 'macro|[email protected]',
+ executionId: null,
+ decision: null,
kind: 'email',
title: 'Polled drafts',
revision: 0,
@@ -433,6 +519,8 @@ describe('review deck', () => {
{
id: 'first',
status: 'submitting',
+ error: null,
+ result: null,
draft: {
subject: 'First email',
body: 'Hello',
@@ -442,6 +530,8 @@ describe('review deck', () => {
{
id: 'second',
status: 'submitting',
+ error: null,
+ result: null,
draft: {
subject: 'Second email',
body: 'World',
@@ -478,16 +568,20 @@ describe('review deck', () => {
review={{
id: 'review',
sessionId: 'session',
+ actingUser: 'macro|[email protected]',
+ executionId: null,
kind: 'email',
title: 'Follow-ups',
revision: 2,
updatedAt: 1,
presentedAt: 1,
- decision: { via: 'chat' },
+ decision: { by: 'owner', via: 'chat', revision: 1, items: ['first'] },
items: [
{
id: 'first',
status: 'completed',
+ error: null,
+ result: null,
draft: {
subject: 'First email',
body: 'Hello',
@@ -508,31 +602,53 @@ describe('review deck', () => {
screen.getByText('Started by the agent at your request')
).toBeTruthy();
});
- it('opens an invalid unvisited draft without dispatching any email', async () => {
+ it('shows the server refusing an incomplete draft without blocking the review', async () => {
const decide = setup({
- items: [
- {
- id: 'first',
- status: 'pending',
- draft: {
- subject: 'Ready email',
- body: 'Ready',
- to: [{ email: '[email protected]' }],
+ content: {
+ kind: 'email',
+ items: [
+ {
+ id: 'first',
+ status: 'pending',
+ error: null,
+ result: null,
+ draft: {
+ subject: 'Ready email',
+ body: 'Ready',
+ to: [{ email: '[email protected]' }],
+ },
},
- },
- {
- id: 'second',
- status: 'pending',
- draft: { subject: 'Needs a recipient', body: 'Hello', to: [] },
- },
- ],
+ {
+ id: 'second',
+ status: 'pending',
+ error: null,
+ result: null,
+ draft: { subject: 'Needs a recipient', body: 'Hello', to: [] },
+ },
+ ],
+ },
+ refuseSubmit: (record) =>
+ record.kind === 'email' &&
+ record.items.some((item) => item.draft.to.length === 0)
+ ? 'Add at least one recipient.'
+ : undefined,
});
await confirmBatch();
- await screen.findByText('Needs a recipient');
- expect(screen.getByRole('alert').textContent).toBe(
+ expect((await screen.findByRole('alert')).textContent).toBe(
'Add at least one recipient.'
);
- expect(decide).not.toHaveBeenCalled();
+ expect(decide).toHaveBeenCalledExactlyOnceWith({
+ action: 'submit',
+ revision: 0,
+ items: ['first', 'second'],
+ });
+ expect(
+ screen.queryByRole('button', { name: 'Reload saved review' })
+ ).toBeNull();
+ expect(
+ screen.getByRole<HTMLButtonElement>('button', { name: 'Send all (2)' })
+ .disabled
+ ).toBe(false);
});
it('keeps an unprepared draft editable without a generic instruction banner', async () => {
const decide = setup();
@@ -587,15 +703,20 @@ describe('review deck', () => {
async (isMobile) => {
mobile.value = isMobile;
setup({
- items: Array.from({ length: 12 }, (_, index) => ({
- id: `draft-${index}`,
- status: 'pending',
- draft: {
- subject: `Email ${index + 1}`,
- body: `Body ${index + 1}`,
- to: [{ email: `person${index + 1}@example.com` }],
- },
- })),
+ content: {
+ kind: 'email',
+ items: Array.from({ length: 12 }, (_, index) => ({
+ id: `draft-${index}`,
+ status: 'pending',
+ error: null,
+ result: null,
+ draft: {
+ subject: `Email ${index + 1}`,
+ body: `Body ${index + 1}`,
+ to: [{ email: `person${index + 1}@example.com` }],
+ },
+ })),
+ },
});
const picker = screen.getByRole('button', {
name: 'Choose draft, 1 of 12',
@@ -623,34 +744,62 @@ describe('review deck', () => {
);
it('creates every remaining calendar event with the same batch control', async () => {
const decide = setup({
- kind: 'calendar',
- items: [
- {
- id: 'first',
- status: 'pending',
- draft: {
- title: 'First event',
- time: {
- kind: 'timed',
- startsAt: '2026-10-16T09:00:00Z',
- endsAt: '2026-10-16T10:00:00Z',
- timeZone: 'UTC',
+ content: {
+ kind: 'calendar',
+ items: [
+ {
+ id: 'first',
+ status: 'pending',
+ error: null,
+ result: null,
+ draft: {
+ title: 'First event',
+ time: {
+ kind: 'timed',
+ startsAt: '2026-10-16T09:00:00Z',
+ endsAt: '2026-10-16T10:00:00Z',
+ timeZone: 'UTC',
+ },
+ description: null,
+ location: null,
+ attendees: [],
+ recurrenceLines: [],
+ calendarId: null,
+ reminders: null,
+ addMacroCall: false,
+ addConference: false,
+ eventType: 'default',
+ outOfOffice: null,
+ guestPolicy: null,
},
},
- },
- {
- id: 'second',
- status: 'pending',
- draft: {
- title: 'Second event',
- time: {
- kind: 'allDay',
- startDate: '2026-10-17',
- endDate: '2026-10-18',
+ {
+ id: 'second',
+ status: 'pending',
+ error: null,
+ result: null,
+ draft: {
+ title: 'Second event',
+ time: {
+ kind: 'allDay',
+ startDate: '2026-10-17',
+ endDate: '2026-10-18',
+ },
+ description: null,
+ location: null,
+ attendees: [],
+ recurrenceLines: [],
+ calendarId: null,
+ reminders: null,
+ addMacroCall: false,
+ addConference: false,
+ eventType: 'default',
+ outOfOffice: null,
+ guestPolicy: null,
},
},
- },
- ],
+ ],
+ },
});
await confirmBatch('Create all (2)', 'Create 2 events');
await waitFor(() => expect(decide).toHaveBeenCalledOnce());
diff --git a/apps/web/src/features/agent-reviews/views/review-stack.tsx b/apps/web/src/features/agent-reviews/views/review-stack.tsx
index e0d2190c07..05720aefd2 100644
--- a/apps/web/src/features/agent-reviews/views/review-stack.tsx
+++ b/apps/web/src/features/agent-reviews/views/review-stack.tsx
@@ -2,22 +2,29 @@ import { CalendarDraftComposer } from '@core/component/AI/component/tool/calenda
import { EmailDraftComposer } from '@core/component/AI/component/tool/email/DraftComposer';
import type { UserToolReviewSink } from '@core/component/AI/component/tool/user-tool-review';
import { fireAndForget } from '@core/util/fireAndForget';
-import {
- CreateCalendarEvent,
+import type {
+ CreateCalendarEvent_Deserialize,
SendEmail,
-} from '@service-cognition/generated/tools/schemas';
+} from '@service-agent-reviews/generated/types';
import { Button } from '@ui/components/Button';
import { ConfirmDialog } from '@ui/components/ConfirmDialog';
-import { createEffect, createSignal, Match, on, Show, Switch } from 'solid-js';
+import { createEffect, createSignal, on, Show } from 'solid-js';
import { match } from 'ts-pattern';
import { ReviewDeck } from '../components/review-deck';
import {
ReviewNavigation,
type ReviewSummary,
} from '../components/review-navigation';
-import type { Review, ReviewActions, ReviewItem } from '../core/review';
+import type {
+ Review,
+ ReviewActions,
+ ReviewDraft,
+ ReviewItem,
+} from '../core/review';
import { createReviewController } from '../primitives/review-controller';
-import { validateReviewDraft } from '../primitives/review-draft-validation';
+
+type EmailDraft = SendEmail;
+type CalendarDraft = CreateCalendarEvent_Deserialize;
/** Saved drafts reuse the same composers as chat, with a deck only for batches. */
export function ReviewStack(props: {
@@ -25,11 +32,7 @@ export function ReviewStack(props: {
canAct: boolean;
actions: ReviewActions;
}) {
- const controller = createReviewController(
- () => props.review,
- props.actions,
- validateReviewDraft
- );
+ const controller = createReviewController(() => props.review, props.actions);
const [index, setIndex] = createSignal(0);
const [generation, setGeneration] = createSignal(0);
const [preparing, setPreparing] = createSignal(false);
@@ -40,8 +43,8 @@ export function ReviewStack(props: {
const record = controller.record;
const current = () => record().items[index()];
const isBatch = () => record().items.length > 1;
- let readDraft: (() => unknown) | undefined;
- let readSubmit: (() => Promise<unknown | undefined>) | undefined;
+ let readDraft: (() => ReviewDraft | undefined) | undefined;
+ let readSubmit: (() => Promise<ReviewDraft | undefined>) | undefined;
let section: HTMLElement | undefined;
const working = () => controller.busy() || preparing() || navigating();
const locked = () =>
@@ -108,12 +111,6 @@ export function ReviewStack(props: {
setIndex(Math.min(index(), Math.max(0, record().items.length - 1)));
setGeneration((value) => value + 1);
}
- function showInvalidDraft() {
- const invalid = controller.validation();
- if (!invalid) return;
- const next = record().items.findIndex((item) => item.id === invalid.item);
- if (next >= 0) select(next);
- }
async function submitAll(items: string[]) {
if (locked() || pending() === 0) return;
setPreparing(true);
@@ -124,11 +121,7 @@ export function ReviewStack(props: {
if (draft === undefined) return;
controller.edit(current().id, draft);
}
- if (!(await controller.decide('submit', items))) {
- showInvalidDraft();
- } else {
- setSubmittedBatch(items);
- }
+ if (await controller.decide('submit', items)) setSubmittedBatch(items);
} finally {
setPreparing(false);
}
@@ -152,7 +145,10 @@ export function ReviewStack(props: {
}
return true;
}
- const sink = <T,>(id: string): UserToolReviewSink<T> => ({
+ const sink = <T,>(
+ id: string,
+ toDraft: (draft: T) => ReviewDraft
+ ): UserToolReviewSink<T> => ({
canAct: () =>
!locked() &&
record().items.find((item) => item.id === id)?.status === 'pending',
@@ -161,10 +157,10 @@ export function ReviewStack(props: {
? 'Only the person whose account this review uses can submit it.'
: undefined,
onEdit: (draft) => {
- controller.edit(id, draft);
+ controller.edit(id, toDraft(draft));
},
onExecute: async (draft) => {
- controller.edit(id, draft);
+ controller.edit(id, toDraft(draft));
return decideItem('submit', id);
},
onReject: () => decideItem('dismiss', id),
@@ -205,8 +201,8 @@ export function ReviewStack(props: {
<Show when={isBatch()}>
<ReviewNavigation
title={record().title}
- items={record().items.map((item) =>
- reviewSummary(item, record().kind)
+ items={record().items.map((item, position) =>
+ reviewSummary(item, record(), position)
)}
index={index()}
disabled={working()}
@@ -241,9 +237,9 @@ export function ReviewStack(props: {
</span>
</div>
</Show>
- <Show when={controller.validation()?.message}>
+ <Show when={controller.validation()}>
<p role="alert" class="mb-2 text-sm text-failure">
- {controller.validation()?.message}
+ {controller.validation()}
</p>
</Show>
<Show when={current()?.error}>
@@ -267,54 +263,56 @@ export function ReviewStack(props: {
>
<Show when={mountKey()} keyed>
{(_key) => {
- const item = current();
- if (!item) return null;
- const email = SendEmail.safeParse(item.draft);
- const calendar = CreateCalendarEvent.safeParse(item.draft);
- return (
- <Switch>
- <Match when={record().kind === 'email' && email.success}>
+ const readOnly = current()?.status !== 'pending';
+ // A review's kind is fixed when it is saved.
+ return match(record())
+ .with({ kind: 'email' }, (review) => {
+ const item = review.items[index()];
+ if (!item) return null;
+ const toDraft = (draft: EmailDraft): ReviewDraft => ({
+ kind: 'email',
+ draft,
+ });
+ return (
<EmailDraftComposer
- initialData={email.success ? email.data : neverDraft()}
- sink={sink(item.id)}
+ initialData={item.draft}
+ sink={sink(item.id, toDraft)}
debugName={`review-${item.id}`}
- readOnly={current()?.status !== 'pending'}
+ readOnly={readOnly}
registerDraftReader={(reader) => {
- readDraft = reader;
+ readDraft = () => mapDraft(reader(), toDraft);
}}
registerSubmitReader={(reader) => {
- readSubmit = reader;
+ readSubmit = async () =>
+ mapDraft(await reader(), toDraft);
}}
/>
- </Match>
- <Match
- when={
- record().kind === 'calendar' &&
- calendar.success &&
- calendar.data.time !== undefined
- }
- >
+ );
+ })
+ .with({ kind: 'calendar' }, (review) => {
+ const item = review.items[index()];
+ if (!item) return null;
+ const toDraft = (draft: CalendarDraft): ReviewDraft => ({
+ kind: 'calendar',
+ draft,
+ });
+ return (
<CalendarDraftComposer
- initialData={
- calendar.success
- ? { ...calendar.data, time: calendar.data.time }
- : neverDraft()
- }
- sink={sink(item.id)}
+ initialData={item.draft}
+ sink={sink(item.id, toDraft)}
previewKey={item.id}
registerDraftReader={(reader) => {
- readDraft = reader;
+ readDraft = () => mapDraft(reader(), toDraft);
}}
registerSubmitReader={(reader) => {
- readSubmit = reader;
+ readSubmit = async () =>
+ mapDraft(await reader(), toDraft);
}}
/>
- </Match>
- <Match when={!email.success && !calendar.success}>
- <p role="alert">This draft cannot be displayed.</p>
- </Match>
- </Switch>
- );
+ );
+ })
+ .with({ kind: 'import' }, () => null)
+ .exhaustive();
}}
</Show>
</ReviewDeck>
@@ -363,8 +361,11 @@ function startedByAgent(review: Review, item: ReviewItem | undefined) {
(item?.status === 'submitting' || item?.status === 'completed')
);
}
-function neverDraft(): never {
- throw new Error('Invalid review draft');
+function mapDraft<T>(
+ draft: T | undefined,
+ toDraft: (draft: T) => ReviewDraft
+): ReviewDraft | undefined {
+ return draft === undefined ? undefined : toDraft(draft);
}
function reviewWording(kind: Review['kind']) {
return match(kind)
@@ -412,60 +413,59 @@ function statusLabel(
.with('pending', undefined, () => 'Draft')
.exhaustive();
}
-function reviewSummary(item: ReviewItem, kind: Review['kind']): ReviewSummary {
+function reviewSummary(
+ item: ReviewItem,
+ review: Review,
+ index: number
+): ReviewSummary {
const summary = {
id: item.id,
- title: 'Draft unavailable',
+ title: 'Import plan',
description: '',
status: item.error
? 'Needs attention'
: item.status === 'unknown'
? 'Check status'
- : statusLabel(item.status, kind),
+ : statusLabel(item.status, review.kind),
needsAttention: Boolean(item.error) || item.status === 'unknown',
};
- return match(kind)
- .with('email', () => emailSummary(item, summary))
- .with('calendar', () => calendarSummary(item, summary))
- .with('import', () => ({ ...summary, title: 'Import plan' }))
+ return match(review)
+ .with({ kind: 'email' }, (review) => {
+ const email = review.items[index]?.draft;
+ if (!email) return summary;
+ return {
+ ...summary,
+ title: email.subject || '(No subject)',
+ description:
+ email.to
+ .map((recipient) =>
+ recipient.name
+ ? `${recipient.name} <${recipient.email}>`
+ : recipient.email
+ )
+ .join(', ') || 'No recipients',
+ };
+ })
+ .with({ kind: 'calendar' }, (review) => {
+ const event = review.items[index]?.draft;
+ if (!event) return summary;
+ const time = event.time;
+ const description =
+ time.kind === 'allDay'
+ ? `${time.startDate} · All day`
+ : new Date(time.startsAt).toLocaleString(undefined, {
+ month: 'short',
+ day: 'numeric',
+ hour: 'numeric',
+ minute: '2-digit',
+ timeZoneName: 'short',
+ });
+ return {
+ ...summary,
+ title: event.title || '(Untitled event)',
+ description,
+ };
+ })
+ .with({ kind: 'import' }, () => summary)
.exhaustive();
}
-function emailSummary(item: ReviewItem, summary: ReviewSummary): ReviewSummary {
- const email = SendEmail.safeParse(item.draft);
- if (!email.success) return summary;
- return {
- ...summary,
- title: email.data.subject || '(No subject)',
- description:
- email.data.to
- ?.map((recipient) =>
- recipient.name
- ? `${recipient.name} <${recipient.email}>`
- : recipient.email
- )
- .join(', ') || 'No recipients',
- };
-}
-function calendarSummary(
- item: ReviewItem,
- summary: ReviewSummary
-): ReviewSummary {
- const calendar = CreateCalendarEvent.safeParse(item.draft);
- if (!calendar.success) return summary;
- const time = calendar.data.time;
- const description =
- time.kind === 'allDay'
- ? `${time.startDate} · All day`
- : new Date(time.startsAt).toLocaleString(undefined, {
- month: 'short',
- day: 'numeric',
- hour: 'numeric',
- minute: '2-digit',
- timeZoneName: 'short',
- });
- return {
- ...summary,
- title: calendar.data.title || '(Untitled event)',
- description,
- };
-}
diff --git a/apps/web/src/features/block-agent/views/PresentedReviewPart.tsx b/apps/web/src/features/block-agent/views/PresentedReviewPart.tsx
index 9fef7edbe0..b7e10f84a0 100644
--- a/apps/web/src/features/block-agent/views/PresentedReviewPart.tsx
+++ b/apps/web/src/features/block-agent/views/PresentedReviewPart.tsx
@@ -66,7 +66,6 @@ export function PresentedReviewPart(props: {
sessionId={props.sessionId}
reviewId={props.reviewId}
canAct={canAct()}
- ownerId={session?.session()?.ownerId}
eventId={latestNotification()?.id}
onDecision={() =>
setPendingDecision({ previousEvent: latestNotification()?.id })
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createReview.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createReview.ts
index d122f02b0f..e78c8bebdd 100644
--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createReview.ts
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createReview.ts
@@ -4,26 +4,11 @@
* agent_harness_service
* OpenAPI spec version: 0.1.0
*/
-import type { CreateReviewExecutionId } from './createReviewExecutionId';
-import type { ReviewKind } from './reviewKind';
+import type { CreateReviewAllOf } from './createReviewAllOf';
+import type { CreateReviewAllOfTwo } from './createReviewAllOfTwo';
/**
- * Review creation. Drafts are validated by the action's owning adapter.
+ * Review creation. Decoding it validates every draft; creating a review only
+presents the drafts, and the account holder acts separately.
*/
-export interface CreateReview {
- /** One to one hundred independent drafts. Email: {subject, body: Markdown,
-to: [{email, name?}], cc?: [{email, name?}], bcc?: [{email, name?}],
-replyingToId?, attachments?: [{documentId}]}. Calendar: {title,
-time: {kind: "timed", startsAt: ISO datetime, endsAt: ISO datetime,
-timeZone?: IANA zone} or {kind: "allDay", startDate: ISO date,
-endDate: exclusive ISO date}, description?, location?, attendees?:
-[{email, isOptional?}]}. Import: exactly one draft {source: "notion" | "linear" | "jira"},
-presenting the plan ImportFromNotion, ImportFromLinear or ImportFromJira staged.
-Creating any review only presents these drafts; the user acts separately. */
- drafts: unknown[];
- executionId?: CreateReviewExecutionId;
- /** Existing UI and action to use. */
- kind: ReviewKind;
- /** Stack label. */
- title: string;
-}
+export type CreateReview = CreateReviewAllOf & CreateReviewAllOfTwo;
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createReviewAllOf.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createReviewAllOf.ts
new file mode 100644
index 0000000000..b16f6bf50c
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createReviewAllOf.ts
@@ -0,0 +1,13 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * The review's kind (email, calendar, import) and its drafts: 1–100
+SendEmail or CreateCalendarEvent arguments, or exactly one import
+plan selection.
+ */
+export type CreateReviewAllOf = { [key: string]: unknown };
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createReviewAllOfTwo.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createReviewAllOfTwo.ts
new file mode 100644
index 0000000000..e8c613ab0f
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createReviewAllOfTwo.ts
@@ -0,0 +1,13 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { CreateReviewAllOfTwoExecutionId } from './createReviewAllOfTwoExecutionId';
+
+export type CreateReviewAllOfTwo = {
+ executionId?: CreateReviewAllOfTwoExecutionId;
+ /** Stack label. */
+ title: string;
+};
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/reviewRecordExecutionId.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createReviewAllOfTwoExecutionId.ts
similarity index 72%
rename from apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/reviewRecordExecutionId.ts
rename to apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createReviewAllOfTwoExecutionId.ts
index a893e0fcc3..7cd639c76f 100644
--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/reviewRecordExecutionId.ts
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createReviewAllOfTwoExecutionId.ts
@@ -6,4 +6,4 @@
*/
import type { ExecutionId } from './executionId';
-export type ReviewRecordExecutionId = null | ExecutionId;
+export type CreateReviewAllOfTwoExecutionId = null | ExecutionId;
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/index.ts
index 96d1b6f565..df17a98710 100644
--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/index.ts
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/index.ts
@@ -161,7 +161,9 @@ export * from './createAgentSessionRequestThread';
export * from './createAgentSessionRequestWorkspace';
export * from './createAgentSessionResponse';
export * from './createReview';
-export * from './createReviewExecutionId';
+export * from './createReviewAllOf';
+export * from './createReviewAllOfTwo';
+export * from './createReviewAllOfTwoExecutionId';
export * from './createSessionThread';
export * from './createSessionThreadChannelId';
export * from './createSessionThreadParent';
@@ -302,20 +304,18 @@ export * from './reviewDecision';
export * from './reviewDecisionContext';
export * from './reviewDecisionOneOf';
export * from './reviewDecisionOneOfAction';
-export * from './reviewDecisionOneOfFive';
-export * from './reviewDecisionOneOfFiveAction';
-export * from './reviewDecisionOneOfThree';
-export * from './reviewDecisionOneOfThreeAction';
+export * from './reviewDecisionOneOfDraft';
+export * from './reviewDecisionOneOfFour';
+export * from './reviewDecisionOneOfFourAction';
+export * from './reviewDecisionOneOfSix';
+export * from './reviewDecisionOneOfSixAction';
export * from './reviewId';
-export * from './reviewItem';
-export * from './reviewItemError';
-export * from './reviewItemStatus';
-export * from './reviewKind';
export * from './reviewRecord';
-export * from './reviewRecordActingUser';
-export * from './reviewRecordDecision';
-export * from './reviewRecordExecutionId';
-export * from './reviewRecordPresentedAt';
+export * from './reviewRecordAllOf';
+export * from './reviewRecordAllOfTwo';
+export * from './reviewRecordAllOfTwoDecision';
+export * from './reviewRecordAllOfTwoExecutionId';
+export * from './reviewRecordAllOfTwoPresentedAt';
export * from './sandboxSize';
export * from './sandboxSizeBody';
export * from './searchSuggestions';
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/reviewDecision.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/reviewDecision.ts
index 16f7a32a30..74ed1d187b 100644
--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/reviewDecision.ts
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/reviewDecision.ts
@@ -5,13 +5,13 @@
* OpenAPI spec version: 0.1.0
*/
import type { ReviewDecisionOneOf } from './reviewDecisionOneOf';
-import type { ReviewDecisionOneOfFive } from './reviewDecisionOneOfFive';
-import type { ReviewDecisionOneOfThree } from './reviewDecisionOneOfThree';
+import type { ReviewDecisionOneOfFour } from './reviewDecisionOneOfFour';
+import type { ReviewDecisionOneOfSix } from './reviewDecisionOneOfSix';
/**
* One atomic user decision against the displayed revision.
*/
export type ReviewDecision =
| ReviewDecisionOneOf
- | ReviewDecisionOneOfThree
- | ReviewDecisionOneOfFive;
+ | ReviewDecisionOneOfFour
+ | ReviewDecisionOneOfSix;
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/reviewDecisionOneOf.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/reviewDecisionOneOf.ts
index 89a6605711..bdb2964173 100644
--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/reviewDecisionOneOf.ts
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/reviewDecisionOneOf.ts
@@ -5,14 +5,15 @@
* OpenAPI spec version: 0.1.0
*/
import type { ReviewDecisionOneOfAction } from './reviewDecisionOneOfAction';
+import type { ReviewDecisionOneOfDraft } from './reviewDecisionOneOfDraft';
/**
* Save one edited draft.
*/
export type ReviewDecisionOneOf = {
action: ReviewDecisionOneOfAction;
- /** Replacement action arguments. */
- draft: unknown;
+ /** Replacement action arguments, keyed by the review's kind. */
+ draft: ReviewDecisionOneOfDraft;
/** Pending item to update. */
item: string;
/** Revision displayed by the caller. */
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/reviewDecisionOneOfDraft.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/reviewDecisionOneOfDraft.ts
new file mode 100644
index 0000000000..1e73300059
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/reviewDecisionOneOfDraft.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Replacement action arguments, keyed by the review's kind.
+ */
+export type ReviewDecisionOneOfDraft = { [key: string]: unknown };
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/reviewDecisionOneOfThree.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/reviewDecisionOneOfFour.ts
similarity index 67%
rename from apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/reviewDecisionOneOfThree.ts
rename to apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/reviewDecisionOneOfFour.ts
index e6cc874012..dab6a2afd4 100644
--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/reviewDecisionOneOfThree.ts
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/reviewDecisionOneOfFour.ts
@@ -4,13 +4,13 @@
* agent_harness_service
* OpenAPI spec version: 0.1.0
*/
-import type { ReviewDecisionOneOfThreeAction } from './reviewDecisionOneOfThreeAction';
+import type { ReviewDecisionOneOfFourAction } from './reviewDecisionOneOfFourAction';
/**
* Send/create selected items, or all pending items when empty.
*/
-export type ReviewDecisionOneOfThree = {
- action: ReviewDecisionOneOfThreeAction;
+export type ReviewDecisionOneOfFour = {
+ action: ReviewDecisionOneOfFourAction;
/** Pending items, or an empty list to select all pending items. */
items: string[];
/** Revision displayed by the caller. */
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/reviewDecisionOneOfThreeAction.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/reviewDecisionOneOfFourAction.ts
similarity index 54%
rename from apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/reviewDecisionOneOfThreeAction.ts
rename to apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/reviewDecisionOneOfFourAction.ts
index 19cf7f4006..eda99d2a74 100644
--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/reviewDecisionOneOfThreeAction.ts
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/reviewDecisionOneOfFourAction.ts
@@ -5,10 +5,10 @@
* OpenAPI spec version: 0.1.0
*/
-export type ReviewDecisionOneOfThreeAction =
- (typeof ReviewDecisionOneOfThreeAction)[keyof typeof ReviewDecisionOneOfThreeAction];
+export type ReviewDecisionOneOfFourAction =
+ (typeof ReviewDecisionOneOfFourAction)[keyof typeof ReviewDecisionOneOfFourAction];
// eslint-disable-next-line @typescript-eslint/no-redeclare
-export const ReviewDecisionOneOfThreeAction = {
+export const ReviewDecisionOneOfFourAction = {
submit: 'submit',
} as const;
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/reviewDecisionOneOfFive.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/reviewDecisionOneOfSix.ts
similarity index 68%
rename from apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/reviewDecisionOneOfFive.ts
rename to apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/reviewDecisionOneOfSix.ts
index 7be96d963b..3c74115f77 100644
--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/reviewDecisionOneOfFive.ts
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/reviewDecisionOneOfSix.ts
@@ -4,13 +4,13 @@
* agent_harness_service
* OpenAPI spec version: 0.1.0
*/
-import type { ReviewDecisionOneOfFiveAction } from './reviewDecisionOneOfFiveAction';
+import type { ReviewDecisionOneOfSixAction } from './reviewDecisionOneOfSixAction';
/**
* Dismiss selected pending items, or all pending items when empty.
*/
-export type ReviewDecisionOneOfFive = {
- action: ReviewDecisionOneOfFiveAction;
+export type ReviewDecisionOneOfSix = {
+ action: ReviewDecisionOneOfSixAction;
/** Pending items, or an empty list to select all pending items. */
items: string[];
/** Revision displayed by the caller. */
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/reviewDecisionOneOfFiveAction.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/reviewDecisionOneOfSixAction.ts
similarity index 55%
rename from apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/reviewDecisionOneOfFiveAction.ts
rename to apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/reviewDecisionOneOfSixAction.ts
index a75527c015..678e9a73da 100644
--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/reviewDecisionOneOfFiveAction.ts
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/reviewDecisionOneOfSixAction.ts
@@ -5,10 +5,10 @@
* OpenAPI spec version: 0.1.0
*/
-export type ReviewDecisionOneOfFiveAction =
- (typeof ReviewDecisionOneOfFiveAction)[keyof typeof ReviewDecisionOneOfFiveAction];
+export type ReviewDecisionOneOfSixAction =
+ (typeof ReviewDecisionOneOfSixAction)[keyof typeof ReviewDecisionOneOfSixAction];
// eslint-disable-next-line @typescript-eslint/no-redeclare
-export const ReviewDecisionOneOfFiveAction = {
+export const ReviewDecisionOneOfSixAction = {
dismiss: 'dismiss',
} as const;
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/reviewItem.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/reviewItem.ts
deleted file mode 100644
index ba6dbe0d67..0000000000
--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/reviewItem.ts
+++ /dev/null
@@ -1,26 +0,0 @@
-/**
- * Generated by orval v7.21.0 🍺
- * Do not edit manually.
- * agent_harness_service
- * OpenAPI spec version: 0.1.0
- */
-import type { ReviewItemError } from './reviewItemError';
-import type { ReviewItemStatus } from './reviewItemStatus';
-
-/**
- * One editable item and its durable outcome.
- */
-export interface ReviewItem {
- /** Validated arguments for the existing composer/action. */
- draft: unknown;
- /** Whether the account holder edited this draft before deciding. */
- edited?: boolean;
- /** Failure or uncertainty description. */
- error?: ReviewItemError;
- /** Stable item identity across stack navigation and edits. */
- id: string;
- /** Actual backend response, never a model assertion. */
- result?: unknown;
- /** Current outcome. */
- status: ReviewItemStatus;
-}
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/reviewItemStatus.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/reviewItemStatus.ts
deleted file mode 100644
index 8c9fc72618..0000000000
--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/reviewItemStatus.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-/**
- * Generated by orval v7.21.0 🍺
- * Do not edit manually.
- * agent_harness_service
- * OpenAPI spec version: 0.1.0
- */
-
-/**
- * Review item state, shared with notification consumers.
- */
-export type ReviewItemStatus =
- (typeof ReviewItemStatus)[keyof typeof ReviewItemStatus];
-
-// eslint-disable-next-line @typescript-eslint/no-redeclare
-export const ReviewItemStatus = {
- pending: 'pending',
- submitting: 'submitting',
- completed: 'completed',
- dismissed: 'dismissed',
- unknown: 'unknown',
-} as const;
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/reviewKind.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/reviewKind.ts
deleted file mode 100644
index 4d1cc935ea..0000000000
--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/reviewKind.ts
+++ /dev/null
@@ -1,18 +0,0 @@
-/**
- * Generated by orval v7.21.0 🍺
- * Do not edit manually.
- * agent_harness_service
- * OpenAPI spec version: 0.1.0
- */
-
-/**
- * The component and action used to finish a review.
- */
-export type ReviewKind = (typeof ReviewKind)[keyof typeof ReviewKind];
-
-// eslint-disable-next-line @typescript-eslint/no-redeclare
-export const ReviewKind = {
- email: 'email',
- calendar: 'calendar',
- import: 'import',
-} as const;
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/reviewRecord.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/reviewRecord.ts
index 0eb7e403a0..af5b374169 100644
--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/reviewRecord.ts
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/reviewRecord.ts
@@ -4,37 +4,10 @@
* agent_harness_service
* OpenAPI spec version: 0.1.0
*/
-
-import type { ReviewId } from './reviewId';
-import type { ReviewItem } from './reviewItem';
-import type { ReviewKind } from './reviewKind';
-import type { ReviewRecordActingUser } from './reviewRecordActingUser';
-import type { ReviewRecordDecision } from './reviewRecordDecision';
-import type { ReviewRecordExecutionId } from './reviewRecordExecutionId';
-import type { ReviewRecordPresentedAt } from './reviewRecordPresentedAt';
+import type { ReviewRecordAllOf } from './reviewRecordAllOf';
+import type { ReviewRecordAllOfTwo } from './reviewRecordAllOfTwo';
/**
* Full UI record, fetched outside the model context.
*/
-export interface ReviewRecord {
- /** Account whose email/calendar the drafts use; historical records use the session owner. */
- actingUser?: ReviewRecordActingUser;
- decision?: ReviewRecordDecision;
- executionId?: ReviewRecordExecutionId;
- /** Review identity. */
- id: ReviewId;
- /** Drafts and per-item outcomes. */
- items: ReviewItem[];
- /** Component kind. */
- kind: ReviewKind;
- /** Durable presentation acknowledgment, separate from user decisions. */
- presentedAt?: ReviewRecordPresentedAt;
- /** Compare-and-swap revision for edits and submissions. */
- revision: number;
- /** Owning session. */
- sessionId: string;
- /** Stack label. */
- title: string;
- /** Milliseconds since epoch of the last state change. */
- updatedAt: number;
-}
+export type ReviewRecord = ReviewRecordAllOf & ReviewRecordAllOfTwo;
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/reviewRecordActingUser.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/reviewRecordActingUser.ts
deleted file mode 100644
index 0b17c76165..0000000000
--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/reviewRecordActingUser.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-/**
- * Generated by orval v7.21.0 🍺
- * Do not edit manually.
- * agent_harness_service
- * OpenAPI spec version: 0.1.0
- */
-
-/**
- * Account whose email/calendar the drafts use; historical records use the session owner.
- */
-export type ReviewRecordActingUser = string | null;
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/reviewItemError.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/reviewRecordAllOf.ts
similarity index 54%
rename from apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/reviewItemError.ts
rename to apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/reviewRecordAllOf.ts
index edf650f418..4e5a316653 100644
--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/reviewItemError.ts
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/reviewRecordAllOf.ts
@@ -6,6 +6,6 @@
*/
/**
- * Failure or uncertainty description.
+ * Component kind, drafts and per-item outcomes.
*/
-export type ReviewItemError = string | null;
+export type ReviewRecordAllOf = { [key: string]: unknown };
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/reviewRecordAllOfTwo.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/reviewRecordAllOfTwo.ts
new file mode 100644
index 0000000000..146b5aa973
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/reviewRecordAllOfTwo.ts
@@ -0,0 +1,30 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+import type { ReviewId } from './reviewId';
+import type { ReviewRecordAllOfTwoDecision } from './reviewRecordAllOfTwoDecision';
+import type { ReviewRecordAllOfTwoExecutionId } from './reviewRecordAllOfTwoExecutionId';
+import type { ReviewRecordAllOfTwoPresentedAt } from './reviewRecordAllOfTwoPresentedAt';
+
+export type ReviewRecordAllOfTwo = {
+ /** Account whose email/calendar the drafts use. */
+ actingUser: string;
+ decision?: ReviewRecordAllOfTwoDecision;
+ executionId?: ReviewRecordAllOfTwoExecutionId;
+ /** Review identity. */
+ id: ReviewId;
+ /** Durable presentation acknowledgment, separate from user decisions. */
+ presentedAt?: ReviewRecordAllOfTwoPresentedAt;
+ /** Compare-and-swap revision for edits and submissions. */
+ revision: number;
+ /** Owning session. */
+ sessionId: string;
+ /** Stack label. */
+ title: string;
+ /** Milliseconds since epoch of the last state change. */
+ updatedAt: number;
+};
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/reviewRecordDecision.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/reviewRecordAllOfTwoDecision.ts
similarity index 72%
rename from apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/reviewRecordDecision.ts
rename to apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/reviewRecordAllOfTwoDecision.ts
index e0d48c4a4b..ecb6580e99 100644
--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/reviewRecordDecision.ts
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/reviewRecordAllOfTwoDecision.ts
@@ -6,4 +6,4 @@
*/
import type { ReviewDecisionContext } from './reviewDecisionContext';
-export type ReviewRecordDecision = null | ReviewDecisionContext;
+export type ReviewRecordAllOfTwoDecision = null | ReviewDecisionContext;
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createReviewExecutionId.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/reviewRecordAllOfTwoExecutionId.ts
similarity index 72%
rename from apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createReviewExecutionId.ts
rename to apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/reviewRecordAllOfTwoExecutionId.ts
index 47a30cfaf9..b819e47571 100644
--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createReviewExecutionId.ts
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/reviewRecordAllOfTwoExecutionId.ts
@@ -6,4 +6,4 @@
*/
import type { ExecutionId } from './executionId';
-export type CreateReviewExecutionId = null | ExecutionId;
+export type ReviewRecordAllOfTwoExecutionId = null | ExecutionId;
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/reviewRecordPresentedAt.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/reviewRecordAllOfTwoPresentedAt.ts
similarity index 76%
rename from apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/reviewRecordPresentedAt.ts
rename to apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/reviewRecordAllOfTwoPresentedAt.ts
index 3a87b0d333..4ee4a82097 100644
--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/reviewRecordPresentedAt.ts
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/reviewRecordAllOfTwoPresentedAt.ts
@@ -8,4 +8,4 @@
/**
* Durable presentation acknowledgment, separate from user decisions.
*/
-export type ReviewRecordPresentedAt = number | null;
+export type ReviewRecordAllOfTwoPresentedAt = number | null;
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/openapi.json b/apps/web/src/lib/service-clients/service-agent-harness/openapi.json
index 949ddf6100..3ef8436dce 100644
--- a/apps/web/src/lib/service-clients/service-agent-harness/openapi.json
+++ b/apps/web/src/lib/service-clients/service-agent-harness/openapi.json
@@ -4588,36 +4588,34 @@
}
},
"CreateReview": {
- "type": "object",
- "description": "Review creation. Drafts are validated by the action's owning adapter.",
- "required": ["kind", "title", "drafts"],
- "properties": {
- "drafts": {
- "type": "array",
- "items": {},
- "description": "One to one hundred independent drafts. Email: {subject, body: Markdown,\nto: [{email, name?}], cc?: [{email, name?}], bcc?: [{email, name?}],\nreplyingToId?, attachments?: [{documentId}]}. Calendar: {title,\ntime: {kind: \"timed\", startsAt: ISO datetime, endsAt: ISO datetime,\ntimeZone?: IANA zone} or {kind: \"allDay\", startDate: ISO date,\nendDate: exclusive ISO date}, description?, location?, attendees?:\n[{email, isOptional?}]}. Import: exactly one draft {source: \"notion\" | \"linear\" | \"jira\"},\npresenting the plan ImportFromNotion, ImportFromLinear or ImportFromJira staged.\nCreating any review only presents these drafts; the user acts separately."
+ "allOf": [
+ {
+ "type": "object",
+ "description": "The review's kind (email, calendar, import) and its drafts: 1–100\nSendEmail or CreateCalendarEvent arguments, or exactly one import\nplan selection."
},
- "executionId": {
- "oneOf": [
- {
- "type": "null"
+ {
+ "type": "object",
+ "required": ["title"],
+ "properties": {
+ "executionId": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/ExecutionId",
+ "description": "Optional code execution that prepared these drafts."
+ }
+ ]
},
- {
- "$ref": "#/components/schemas/ExecutionId",
- "description": "Optional code execution that prepared these drafts."
+ "title": {
+ "type": "string",
+ "description": "Stack label."
}
- ]
- },
- "kind": {
- "$ref": "#/components/schemas/ReviewKind",
- "description": "Existing UI and action to use."
- },
- "title": {
- "type": "string",
- "description": "Stack label."
+ }
}
- },
- "additionalProperties": false
+ ],
+ "description": "Review creation. Decoding it validates every draft; creating a review only\npresents the drafts, and the account holder acts separately."
},
"CreateSessionThread": {
"type": "object",
@@ -5887,7 +5885,8 @@
"enum": ["edit"]
},
"draft": {
- "description": "Replacement action arguments."
+ "type": "object",
+ "description": "Replacement action arguments, keyed by the review's kind."
},
"item": {
"type": "string",
@@ -5985,125 +5984,81 @@
"format": "uuid",
"description": "Persisted review identity."
},
- "ReviewItem": {
- "type": "object",
- "description": "One editable item and its durable outcome.",
- "required": ["id", "draft", "status"],
- "properties": {
- "draft": {
- "description": "Validated arguments for the existing composer/action."
- },
- "edited": {
- "type": "boolean",
- "description": "Whether the account holder edited this draft before deciding."
- },
- "error": {
- "type": ["string", "null"],
- "description": "Failure or uncertainty description."
- },
- "id": {
- "type": "string",
- "format": "uuid",
- "description": "Stable item identity across stack navigation and edits."
- },
- "result": {
- "description": "Actual backend response, never a model assertion."
- },
- "status": {
- "$ref": "#/components/schemas/ReviewItemStatus",
- "description": "Current outcome."
- }
- }
- },
- "ReviewItemStatus": {
- "type": "string",
- "description": "Review item state, shared with notification consumers.",
- "enum": ["pending", "submitting", "completed", "dismissed", "unknown"]
- },
- "ReviewKind": {
- "type": "string",
- "description": "The component and action used to finish a review.",
- "enum": ["email", "calendar", "import"]
- },
"ReviewRecord": {
- "type": "object",
- "description": "Full UI record, fetched outside the model context.",
- "required": [
- "id",
- "sessionId",
- "kind",
- "title",
- "revision",
- "updatedAt",
- "items"
- ],
- "properties": {
- "actingUser": {
- "type": ["string", "null"],
- "description": "Account whose email/calendar the drafts use; historical records use the session owner."
+ "allOf": [
+ {
+ "type": "object",
+ "description": "Component kind, drafts and per-item outcomes."
},
- "decision": {
- "oneOf": [
- {
- "type": "null"
+ {
+ "type": "object",
+ "required": [
+ "id",
+ "sessionId",
+ "actingUser",
+ "title",
+ "revision",
+ "updatedAt"
+ ],
+ "properties": {
+ "actingUser": {
+ "type": "string",
+ "description": "Account whose email/calendar the drafts use."
},
- {
- "$ref": "#/components/schemas/ReviewDecisionContext",
- "description": "Current batch's authenticated decision, preserved for interrupted work."
- }
- ]
- },
- "executionId": {
- "oneOf": [
- {
- "type": "null"
+ "decision": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/ReviewDecisionContext",
+ "description": "Current batch's authenticated decision, preserved for interrupted work."
+ }
+ ]
},
- {
- "$ref": "#/components/schemas/ExecutionId",
- "description": "Originating code execution, absent for directly presented reviews."
+ "executionId": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/ExecutionId",
+ "description": "Originating code execution, absent for directly presented reviews."
+ }
+ ]
+ },
+ "id": {
+ "$ref": "#/components/schemas/ReviewId",
+ "description": "Review identity."
+ },
+ "presentedAt": {
+ "type": ["integer", "null"],
+ "format": "int64",
+ "description": "Durable presentation acknowledgment, separate from user decisions."
+ },
+ "revision": {
+ "type": "integer",
+ "format": "int64",
+ "description": "Compare-and-swap revision for edits and submissions."
+ },
+ "sessionId": {
+ "type": "string",
+ "format": "uuid",
+ "description": "Owning session."
+ },
+ "title": {
+ "type": "string",
+ "description": "Stack label."
+ },
+ "updatedAt": {
+ "type": "integer",
+ "format": "int64",
+ "description": "Milliseconds since epoch of the last state change."
}
- ]
- },
- "id": {
- "$ref": "#/components/schemas/ReviewId",
- "description": "Review identity."
- },
- "items": {
- "type": "array",
- "items": {
- "$ref": "#/components/schemas/ReviewItem"
- },
- "description": "Drafts and per-item outcomes."
- },
- "kind": {
- "$ref": "#/components/schemas/ReviewKind",
- "description": "Component kind."
- },
- "presentedAt": {
- "type": ["integer", "null"],
- "format": "int64",
- "description": "Durable presentation acknowledgment, separate from user decisions."
- },
- "revision": {
- "type": "integer",
- "format": "int64",
- "description": "Compare-and-swap revision for edits and submissions."
- },
- "sessionId": {
- "type": "string",
- "format": "uuid",
- "description": "Owning session."
- },
- "title": {
- "type": "string",
- "description": "Stack label."
- },
- "updatedAt": {
- "type": "integer",
- "format": "int64",
- "description": "Milliseconds since epoch of the last state change."
+ }
}
- }
+ ],
+ "description": "Full UI record, fetched outside the model context."
},
"SandboxSize": {
"type": "string",
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/reviews.ts b/apps/web/src/lib/service-clients/service-agent-harness/reviews.ts
index 9b62a0ec4e..b33aca6c05 100644
--- a/apps/web/src/lib/service-clients/service-agent-harness/reviews.ts
+++ b/apps/web/src/lib/service-clients/service-agent-harness/reviews.ts
@@ -1,19 +1,30 @@
import { SERVER_HOSTS } from '@core/constant/servers';
import { fetchWithToken } from '@core/util/fetchWithToken';
+import { statusError } from '@core/util/safeFetch';
import { Telemetry } from '@macro-inc/observability';
-import type { ReviewDecision, ReviewRecord } from './generated/schemas';
+import type {
+ ReviewDecision_Deserialize,
+ ReviewRecord_Serialize,
+} from '@service-agent-reviews/generated/types';
const host = SERVER_HOSTS['agent-harness'];
+/** A decision the server refused, with its reason for the account holder. */
+export const INVALID_REVIEW_DECISION = 'INVALID_REVIEW_DECISION';
+
/** Persisted reviews use the ordinary authenticated session API. */
export const agentReviewClient = {
get(session: string, review: string) {
- return fetchWithToken<ReviewRecord>(
+ return fetchWithToken<ReviewRecord_Serialize>(
`${host}/agent-sessions/${session}/reviews/${review}`,
{ method: 'GET' }
);
},
- async decide(session: string, review: string, decision: ReviewDecision) {
+ async decide(
+ session: string,
+ review: string,
+ decision: ReviewDecision_Deserialize
+ ) {
const span = Telemetry.span('agent.review.decide', { kind: 'client' });
span.setAttr('agent.session.id', session);
span.setAttr('agent.review.id', review);
@@ -23,15 +34,19 @@ export const agentReviewClient = {
};
span.injectTraceHeaders(headers);
try {
- const result = await fetchWithToken<ReviewRecord>(
- `${host}/agent-sessions/${session}/reviews/${review}`,
- {
- method: 'POST',
- headers,
- body: JSON.stringify(decision),
- trace: { parentSpan: span },
- }
- );
+ const result = await fetchWithToken<
+ ReviewRecord_Serialize,
+ typeof INVALID_REVIEW_DECISION
+ >(`${host}/agent-sessions/${session}/reviews/${review}`, {
+ method: 'POST',
+ headers,
+ body: JSON.stringify(decision),
+ errorResponseHandler: async (response) =>
+ response.status === 400
+ ? { code: INVALID_REVIEW_DECISION, message: await response.text() }
+ : statusError(response.status),
+ trace: { parentSpan: span },
+ });
if (result.isErr()) span.error('Review decision failed');
return result;
} finally {
diff --git a/apps/web/src/lib/service-clients/service-agent-reviews/generated/types.ts b/apps/web/src/lib/service-clients/service-agent-reviews/generated/types.ts
new file mode 100644
index 0000000000..984292d649
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-reviews/generated/types.ts
@@ -0,0 +1,902 @@
+// This file has been generated by Specta. Do not edit this file manually.
+/** An attendee supplied to a calendar tool. */
+export type AttendeeInput = {
+ /** Attendee email address. */
+ email: EmailAddress;
+ /** Whether attendance is optional. */
+ isOptional?: boolean;
+};
+
+/** How an out-of-office event handles conflicting invitations. */
+export type AutoDeclineModeInput =
+ /** Leave conflicting invitations alone. */
+ | 'decline_none'
+ /** Decline every conflicting invitation, existing and new. */
+ | 'decline_all'
+ /** Decline only invitations that arrive after the event is created. */
+ | 'decline_new_only';
+
+/** The kind of event a create tool call makes. */
+export type CalendarEventTypeInput =
+ /** A regular calendar event. */
+ | 'default'
+ /**
+ * A Google out-of-office status event: primary calendar only, timed, no
+ * attendees, and Google shows the user as away and can auto-decline
+ * conflicting invitations.
+ */
+ | 'out_of_office';
+
+/** Create a calendar event. */
+export type CreateCalendarEvent =
+ | CreateCalendarEvent_Serialize
+ | CreateCalendarEvent_Deserialize;
+
+/** Create a calendar event. */
+export type CreateCalendarEvent_Deserialize =
+ | ({
+ /** Display title. */
+ title: string;
+ /** Timed or all-day span. */
+ time: EventTimeInput;
+ /** Optional event body. */
+ description?: string | null;
+ /** Optional location label. */
+ location?: string | null;
+ /** Attendees to invite. */
+ attendees?: AttendeeInput[];
+ /** Recurrence properties. */
+ recurrenceLines?: string[];
+ /** Calendar to create the event on. */
+ calendarId?: string | null;
+ /** Reminder configuration. */
+ reminders?: EventRemindersInput | null;
+ /** Whether to attach a Macro meeting link. */
+ addMacroCall?: boolean;
+ /** Kind of event to create. */
+ eventType?: CalendarEventTypeInput;
+ /** Out-of-office decline behavior. */
+ outOfOffice?: OutOfOfficeInput | null;
+ /** What guests may do with the event. */
+ guestPolicy?: GuestPolicy | null;
+ } & {
+ /** Whether to attach the calendar provider's meeting conference. */
+ addConference?: boolean;
+ })
+ | {
+ /** Whether to attach the calendar provider's meeting conference. */
+ addGoogleMeet?: boolean;
+ };
+
+/** Create a calendar event. */
+export type CreateCalendarEvent_Serialize = {
+ /** Display title. */
+ title: string;
+ /** Timed or all-day span. */
+ time: EventTimeInput;
+ /** Optional event body. */
+ description: string | null;
+ /** Optional location label. */
+ location: string | null;
+ /** Attendees to invite. */
+ attendees: AttendeeInput[];
+ /** Recurrence properties. */
+ recurrenceLines: string[];
+ /** Calendar to create the event on. */
+ calendarId: string | null;
+ /** Reminder configuration. */
+ reminders: EventRemindersInput | null;
+ /** Whether to attach a Macro meeting link. */
+ addMacroCall: boolean;
+ /** Whether to attach the calendar provider's meeting conference. */
+ addConference: boolean;
+ /** Kind of event to create. */
+ eventType: CalendarEventTypeInput;
+ /** Out-of-office decline behavior. */
+ outOfOffice: OutOfOfficeInput | null;
+ /** What guests may do with the event. */
+ guestPolicy: GuestPolicy | null;
+};
+
+/**
+ * Review creation. Decoding it validates every draft; creating a review only
+ * presents the drafts, and the account holder acts separately.
+ */
+export type CreateReview = CreateReview_Serialize | CreateReview_Deserialize;
+
+/**
+ * Review creation. Decoding it validates every draft; creating a review only
+ * presents the drafts, and the account holder acts separately.
+ */
+export type CreateReview_Deserialize = {
+ /** Optional code execution that prepared these drafts. */
+ executionId?: ExecutionId | null;
+ /** Stack label. */
+ title: ReviewTitle;
+} & ReviewDrafts_Deserialize;
+
+/**
+ * Review creation. Decoding it validates every draft; creating a review only
+ * presents the drafts, and the account holder acts separately.
+ */
+export type CreateReview_Serialize = {
+ /** Optional code execution that prepared these drafts. */
+ executionId: ExecutionId | null;
+ /** Stack label. */
+ title: ReviewTitle;
+} & ReviewDrafts_Serialize;
+
+/** Surface of a review decision. */
+export type DecisionVia =
+ /** Review card. */
+ | 'card'
+ /** Owner request in chat. */
+ | 'chat'
+ /** Inbox action. */
+ | 'inbox';
+
+/** One to [`MAX_DRAFTS`] drafts of one kind. */
+export type DraftList<Draft> = Draft[];
+
+/** An address that passes [`is_valid_email`]; decoding rejects any other string. */
+export type EmailAddress = string;
+
+/** A Macro document attached to an outgoing email as a file. */
+export type EmailAttachment = {
+ /**
+ * The id of the Macro document to attach. It must be a stored file -
+ * an uploaded PDF, image, spreadsheet, Word document, or other upload -
+ * that the user can view. A Macro-native document (one written in the
+ * editor) has no file to attach; link to it in the body instead.
+ */
+ documentId: string;
+};
+
+/** A recipient for an email. */
+export type EmailRecipient = {
+ /** The recipient's email address. */
+ email: EmailAddress;
+ /** The recipient's display name (optional). */
+ name?: string | null;
+};
+
+/** One reminder override supplied to a calendar tool. */
+export type EventReminderOverrideInput = {
+ /** Provider reminder method. `popup` creates a Macro notification. */
+ method: string;
+ /** Minutes before the event start. */
+ minutes: number;
+};
+
+/** Reminder configuration supplied when creating a calendar event. */
+export type EventRemindersInput = {
+ /** Whether the selected calendar's default reminders should apply. */
+ useDefault: boolean;
+ /** Overrides used when calendar defaults are disabled. */
+ overrides?: EventReminderOverrideInput[];
+};
+
+/** The mutually exclusive time shape supplied to calendar tools. */
+export type EventTimeInput =
+ /** A clock-time event with absolute instants. */
+ | {
+ kind: 'timed';
+ /** Inclusive start instant, RFC 3339 UTC (e.g. 2026-08-20T17:00:00Z). */
+ startsAt: string;
+ /** Exclusive end instant, RFC 3339 UTC. Must be after the start. */
+ endsAt: string;
+ /**
+ * IANA time zone the event was scheduled in (e.g.
+ * America/New_York). Recurring events expand in this zone.
+ */
+ timeZone?: string | null;
+ }
+ /** An all-day event spanning whole local dates. */
+ | {
+ kind: 'allDay';
+ /** Inclusive local start date (YYYY-MM-DD). */
+ startDate: string;
+ /**
+ * Exclusive local end date (YYYY-MM-DD); the day after the last
+ * covered day, so a one-day event ends the next date.
+ */
+ endDate: string;
+ };
+
+/** Caller-selected UUID persisted in tool input before execution begins. */
+export type ExecutionId = string;
+
+/**
+ * The switches an organizer sets on an event to bound what its guests may
+ * do. Google omits a switch from the payload while it holds its default.
+ */
+export type GuestPolicy = {
+ /** Whether guests may change the event, including its guest list. */
+ canModify: boolean;
+ /** Whether guests may invite others. */
+ canInviteOthers: boolean;
+ /** Whether guests may see the guest list. */
+ canSeeOtherGuests: boolean;
+};
+
+/**
+ * The one draft an import review carries: which source's staged plan it
+ * presents, the plan rows the user took out of it, and the rows whose
+ * sharing they changed: `shared` to share with their team, `personal` to
+ * keep to themselves.
+ */
+export type ImportDraft = {
+ /** The staged plan's source; fixed once the review is presented. */
+ source: ImportReviewSource;
+ /** Plan rows left out of the import. */
+ excluded?: string[];
+ /** Plan rows shared with the team although the plan keeps them private. */
+ shared?: string[];
+ /** Plan rows kept private although the plan shares them. */
+ personal?: string[];
+};
+
+/**
+ * What an imported item is in its source system. Each source has its own
+ * kinds; a Notion database and a Notion page, or a Linear project and a
+ * Linear issue, are tracked and deduplicated separately.
+ */
+export type ImportKind =
+ /** A Linear issue. */
+ | 'issue'
+ /** A Linear project. */
+ | 'project'
+ /** A Linear document. */
+ | 'document'
+ /** A Notion page. */
+ | 'page'
+ /** A Notion database. */
+ | 'database'
+ /** One data source (table) of a Notion database. */
+ | 'data_source'
+ /** One row of a Notion data source. */
+ | 'row'
+ /** A Jira issue. */
+ | 'jira_issue'
+ /** A Jira project. */
+ | 'jira_project'
+ /** A Jira epic grouping. */
+ | 'jira_epic'
+ /** A Slack channel. */
+ | 'channel';
+
+/** Which source's staged plan an import review presents. */
+export type ImportReviewSource =
+ /** A Notion workspace plan, staged by ImportFromNotion. */
+ | 'notion'
+ /** A Linear plan, staged by ImportFromLinear. */
+ | 'linear'
+ /** A Jira plan, staged by ImportFromJira. */
+ | 'jira';
+
+/** Review item state, shared with notification consumers. */
+export type ItemStatus =
+ /** Still awaiting a decision. */
+ | 'pending'
+ /** Claimed for execution. */
+ | 'submitting'
+ /** Confirmed complete. */
+ | 'completed'
+ /** Dismissed by the owner. */
+ | 'dismissed'
+ /** Outcome requires reconciliation. */
+ | 'unknown';
+
+/** Where a Notion workspace import stands. */
+export type NotionImportReport =
+ | NotionImportReport_Serialize
+ | NotionImportReport_Deserialize;
+
+/** Where a Notion workspace import stands. */
+export type NotionImportReport_Deserialize = {
+ /** Provider items skipped because they were unreadable, or optional features unavailable. */
+ warnings?: string[];
+ /** Tracker issues in the plan. */
+ issues?: number;
+ /** Tracker groups written as Macro projects. */
+ projects?: number;
+ /**
+ * The run's state: `running` while planning, `ready` once a plan is
+ * staged, `importing` while writing, `completed`, `failed`, or
+ * `dismissed` when cancelled. Absent before the first run.
+ */
+ status?: RunStatus | null;
+ /** Why the run failed, when it did. */
+ error?: string | null;
+ /** What planning has found in Notion so far, while it is `running`. */
+ scanned?: ScanCounts | null;
+ /** Pages in the plan. */
+ pages: number;
+ /** Data sources (database tables) in the plan. */
+ dataSources: number;
+ /**
+ * Plan objects the decision model has not answered for yet, while
+ * planning is still `running`.
+ */
+ deciding?: number;
+ /**
+ * Whether the user is on a team. Without one, everything the import
+ * writes stays visible only to them.
+ */
+ onTeam?: boolean;
+ /** Objects to copy as they are. */
+ copy: number;
+ /** Data sources whose rows become tasks. */
+ tasks: number;
+ /** Objects left in Notion. */
+ skip: number;
+ /** Objects that need handling by hand. */
+ hand: number;
+ /** Pages written as documents. */
+ documents: number;
+ /** Data sources written as databases. */
+ databases: number;
+ /** Rows those databases hold, every one counted while planning. */
+ databaseRows: number;
+ /** Tasks the task lists become, one per row. */
+ taskRows: number;
+ /** Plan objects already imported. */
+ imported: number;
+ /** Plan objects still waiting to be written. */
+ waiting: number;
+ /** Plan objects being written now. */
+ writing: number;
+ /**
+ * Plan objects waiting for a teammate who is writing the same object
+ * for the team; they link to the teammate's copy once it is written.
+ */
+ waitingOnTeammates?: number;
+ /** Written plan objects shared with the user's team. */
+ sharedWithTeam?: number;
+ /**
+ * Plan objects a teammate already imported and shared with the team;
+ * they link to that copy and are not counted as copies.
+ */
+ alreadyInMacro?: number;
+ /** Who imported the objects already in Macro, most first. */
+ alreadyImportedBy?: NotionImporter[];
+ /** The review the plan is tied to, once presented. */
+ reviewId?: string | null;
+ /** Objects that need handling by hand, with reasons. */
+ handItems?: NotionReportItem_Deserialize[];
+ /** Objects that failed to import, with the failure. */
+ failures?: NotionReportItem_Deserialize[];
+};
+
+/** Where a Notion workspace import stands. */
+export type NotionImportReport_Serialize = {
+ /** Provider items skipped because they were unreadable, or optional features unavailable. */
+ warnings?: string[];
+ /** Tracker issues in the plan. */
+ issues: number;
+ /** Tracker groups written as Macro projects. */
+ projects: number;
+ /**
+ * The run's state: `running` while planning, `ready` once a plan is
+ * staged, `importing` while writing, `completed`, `failed`, or
+ * `dismissed` when cancelled. Absent before the first run.
+ */
+ status?: RunStatus | null;
+ /** Why the run failed, when it did. */
+ error?: string | null;
+ /** What planning has found in Notion so far, while it is `running`. */
+ scanned?: ScanCounts | null;
+ /** Pages in the plan. */
+ pages: number;
+ /** Data sources (database tables) in the plan. */
+ dataSources: number;
+ /**
+ * Plan objects the decision model has not answered for yet, while
+ * planning is still `running`.
+ */
+ deciding: number;
+ /**
+ * Whether the user is on a team. Without one, everything the import
+ * writes stays visible only to them.
+ */
+ onTeam: boolean;
+ /** Objects to copy as they are. */
+ copy: number;
+ /** Data sources whose rows become tasks. */
+ tasks: number;
+ /** Objects left in Notion. */
+ skip: number;
+ /** Objects that need handling by hand. */
+ hand: number;
+ /** Pages written as documents. */
+ documents: number;
+ /** Data sources written as databases. */
+ databases: number;
+ /** Rows those databases hold, every one counted while planning. */
+ databaseRows: number;
+ /** Tasks the task lists become, one per row. */
+ taskRows: number;
+ /** Plan objects already imported. */
+ imported: number;
+ /** Plan objects still waiting to be written. */
+ waiting: number;
+ /** Plan objects being written now. */
+ writing: number;
+ /**
+ * Plan objects waiting for a teammate who is writing the same object
+ * for the team; they link to the teammate's copy once it is written.
+ */
+ waitingOnTeammates: number;
+ /** Written plan objects shared with the user's team. */
+ sharedWithTeam: number;
+ /**
+ * Plan objects a teammate already imported and shared with the team;
+ * they link to that copy and are not counted as copies.
+ */
+ alreadyInMacro: number;
+ /** Who imported the objects already in Macro, most first. */
+ alreadyImportedBy: NotionImporter[];
+ /** The review the plan is tied to, once presented. */
+ reviewId?: string | null;
+ /** Objects that need handling by hand, with reasons. */
+ handItems: NotionReportItem_Serialize[];
+ /** Objects that failed to import, with the failure. */
+ failures: NotionReportItem_Serialize[];
+};
+
+/** A teammate who already imported some of a plan's objects. */
+export type NotionImporter = {
+ /** The teammate, by email. */
+ by: string;
+ /** How many of the plan's objects they imported. */
+ count: number;
+};
+
+/** One object a workspace import report calls out. */
+export type NotionReportItem =
+ | NotionReportItem_Serialize
+ | NotionReportItem_Deserialize;
+
+/** One object a workspace import report calls out. */
+export type NotionReportItem_Deserialize = {
+ /** The ledger row. */
+ importId: string;
+ /** The object's title. */
+ title: string;
+ /** What the object is. */
+ kind: ImportKind;
+ /** Its Notion URL. */
+ url?: string | null;
+ /** Why it is called out: the decision model's reason, or the failure. */
+ reason?: string | null;
+};
+
+/** One object a workspace import report calls out. */
+export type NotionReportItem_Serialize = {
+ /** The ledger row. */
+ importId: string;
+ /** The object's title. */
+ title: string;
+ /** What the object is. */
+ kind: ImportKind;
+ /** Its Notion URL. */
+ url?: string | null;
+ /** Why it is called out: the decision model's reason, or the failure. */
+ reason?: string | null;
+};
+
+/** Out-of-office decline behavior supplied to the calendar tools. */
+export type OutOfOfficeInput = {
+ /**
+ * How conflicting invitations are handled. Defaults to declining nothing,
+ * so the event only blocks time and shows the away status.
+ */
+ autoDeclineMode?: AutoDeclineModeInput | null;
+ /** Message returned to organizers whose invitations are auto-declined. */
+ declineMessage?: string | null;
+};
+
+/** One atomic user decision against the displayed revision. */
+export type ReviewDecision =
+ | ReviewDecision_Serialize
+ | ReviewDecision_Deserialize;
+
+/** Facts about the most recent account-holder decision. */
+export type ReviewDecisionContext = {
+ /** Authenticated account holder. */
+ by: string;
+ /** Entry surface. */
+ via: DecisionVia;
+ /** Revision claimed by this batch, used in notification deduplication. */
+ revision: number;
+ /** Items selected by this decision. */
+ items: string[];
+};
+
+/** One atomic user decision against the displayed revision. */
+export type ReviewDecision_Deserialize =
+ /** Save one edited draft. */
+ | ({
+ action: 'edit';
+ /** Revision displayed by the caller. */
+ revision: number;
+ /** Pending item to update. */
+ item: string;
+ /** Replacement action arguments, keyed by the review's kind. */
+ draft: ReviewDraft_Deserialize;
+ } & { items?: never })
+ /** Send/create selected items, or all pending items when empty. */
+ | ({
+ action: 'submit';
+ /** Revision displayed by the caller. */
+ revision: number;
+ /** Pending items, or an empty list to select all pending items. */
+ items: string[];
+ } & { draft?: never; item?: never })
+ /** Dismiss selected pending items, or all pending items when empty. */
+ | ({
+ action: 'dismiss';
+ /** Revision displayed by the caller. */
+ revision: number;
+ /** Pending items, or an empty list to select all pending items. */
+ items: string[];
+ } & { draft?: never; item?: never });
+
+/** One atomic user decision against the displayed revision. */
+export type ReviewDecision_Serialize =
+ /** Save one edited draft. */
+ | ({
+ action: 'edit';
+ /** Revision displayed by the caller. */
+ revision: number;
+ /** Pending item to update. */
+ item: string;
+ /** Replacement action arguments, keyed by the review's kind. */
+ draft: ReviewDraft_Serialize;
+ } & { items?: never })
+ /** Send/create selected items, or all pending items when empty. */
+ | ({
+ action: 'submit';
+ /** Revision displayed by the caller. */
+ revision: number;
+ /** Pending items, or an empty list to select all pending items. */
+ items: string[];
+ } & { draft?: never; item?: never })
+ /** Dismiss selected pending items, or all pending items when empty. */
+ | ({
+ action: 'dismiss';
+ /** Revision displayed by the caller. */
+ revision: number;
+ /** Pending items, or an empty list to select all pending items. */
+ items: string[];
+ } & { draft?: never; item?: never });
+
+/** One replacement draft, keyed by the kind of the review it edits. */
+export type ReviewDraft = ReviewDraft_Serialize | ReviewDraft_Deserialize;
+
+/** One replacement draft, keyed by the kind of the review it edits. */
+export type ReviewDraft_Deserialize =
+ /** An edited email. */
+ | { kind: 'email'; draft: SendEmail }
+ /** An edited calendar event. */
+ | { kind: 'calendar'; draft: CreateCalendarEvent_Deserialize }
+ /** An edited import plan selection. */
+ | { kind: 'import'; draft: ImportDraft };
+
+/** One replacement draft, keyed by the kind of the review it edits. */
+export type ReviewDraft_Serialize =
+ /** An edited email. */
+ | { kind: 'email'; draft: SendEmail }
+ /** An edited calendar event. */
+ | { kind: 'calendar'; draft: CreateCalendarEvent_Serialize }
+ /** An edited import plan selection. */
+ | { kind: 'import'; draft: ImportDraft };
+
+/** The drafts a new review presents, keyed by the review's kind. */
+export type ReviewDrafts = ReviewDrafts_Serialize | ReviewDrafts_Deserialize;
+
+/** The drafts a new review presents, keyed by the review's kind. */
+export type ReviewDrafts_Deserialize =
+ /** Emails, each sent with the SendEmail action (Markdown body). */
+ | { kind: 'email'; drafts: DraftList<SendEmail> }
+ /** Calendar events, each created with the CreateCalendarEvent action. */
+ | { kind: 'calendar'; drafts: DraftList<CreateCalendarEvent_Deserialize> }
+ /** Exactly one staged import plan, approved as one item. */
+ | { kind: 'import'; drafts: [ImportDraft] };
+
+/** The drafts a new review presents, keyed by the review's kind. */
+export type ReviewDrafts_Serialize =
+ /** Emails, each sent with the SendEmail action (Markdown body). */
+ | { kind: 'email'; drafts: DraftList<SendEmail> }
+ /** Calendar events, each created with the CreateCalendarEvent action. */
+ | { kind: 'calendar'; drafts: DraftList<CreateCalendarEvent_Serialize> }
+ /** Exactly one staged import plan, approved as one item. */
+ | { kind: 'import'; drafts: [ImportDraft] };
+
+/** Persisted review identity. */
+export type ReviewId = string;
+
+/** One editable item and its durable outcome. */
+export type ReviewItem<Draft, Outcome> = {
+ /** Arguments for the existing composer and action. */
+ draft: Draft;
+ /** The action's confirmed response, never a model assertion. */
+ result: Outcome | null;
+} & ReviewItemState;
+
+/** Item facts every kind shares. */
+export type ReviewItemState = {
+ /** Stable item identity across stack navigation and edits. */
+ id: string;
+ /** Whether the account holder edited this draft before deciding. */
+ edited?: boolean;
+ /** Current outcome. */
+ status: ItemStatus;
+ /** Failure or uncertainty description. */
+ error: string | null;
+};
+
+/** Saved items keyed by the review's kind. */
+export type ReviewItems = ReviewItems_Serialize | ReviewItems_Deserialize;
+
+/** Saved items keyed by the review's kind. */
+export type ReviewItems_Deserialize =
+ /** Email drafts and their send responses. */
+ | { kind: 'email'; items: ReviewItem<SendEmail, SendEmailResponse>[] }
+ /** Calendar drafts and their created events. */
+ | {
+ kind: 'calendar';
+ items: ReviewItem<CreateCalendarEvent_Deserialize, ToolCalendarEvent>[];
+ }
+ /** The import plan selection and the started write's report. */
+ | {
+ kind: 'import';
+ items: [ReviewItem<ImportDraft, NotionImportReport_Deserialize>];
+ };
+
+/** Saved items keyed by the review's kind. */
+export type ReviewItems_Serialize =
+ /** Email drafts and their send responses. */
+ | { kind: 'email'; items: ReviewItem<SendEmail, SendEmailResponse>[] }
+ /** Calendar drafts and their created events. */
+ | {
+ kind: 'calendar';
+ items: ReviewItem<CreateCalendarEvent_Serialize, ToolCalendarEvent>[];
+ }
+ /** The import plan selection and the started write's report. */
+ | {
+ kind: 'import';
+ items: [ReviewItem<ImportDraft, NotionImportReport_Serialize>];
+ };
+
+/** Full UI record, fetched outside the model context. */
+export type ReviewRecord = ReviewRecord_Serialize | ReviewRecord_Deserialize;
+
+/** Full UI record, fetched outside the model context. */
+export type ReviewRecord_Deserialize = {
+ /** Review identity. */
+ id: ReviewId;
+ /** Owning session. */
+ sessionId: string;
+ /** Account whose email/calendar the drafts use. */
+ actingUser: string;
+ /** Originating code execution, absent for directly presented reviews. */
+ executionId: ExecutionId | null;
+ /** Durable presentation acknowledgment, separate from user decisions. */
+ presentedAt?: number | null;
+ /** Stack label. */
+ title: ReviewTitle;
+ /** Compare-and-swap revision for edits and submissions. */
+ revision: number;
+ /** Milliseconds since epoch of the last state change. */
+ updatedAt: number;
+ /** Current batch's authenticated decision, preserved for interrupted work. */
+ decision?: ReviewDecisionContext | null;
+} & ReviewItems_Deserialize;
+
+/** Full UI record, fetched outside the model context. */
+export type ReviewRecord_Serialize = {
+ /** Review identity. */
+ id: ReviewId;
+ /** Owning session. */
+ sessionId: string;
+ /** Account whose email/calendar the drafts use. */
+ actingUser: string;
+ /** Originating code execution, absent for directly presented reviews. */
+ executionId: ExecutionId | null;
+ /** Durable presentation acknowledgment, separate from user decisions. */
+ presentedAt: number | null;
+ /** Stack label. */
+ title: ReviewTitle;
+ /** Compare-and-swap revision for edits and submissions. */
+ revision: number;
+ /** Milliseconds since epoch of the last state change. */
+ updatedAt: number;
+ /** Current batch's authenticated decision, preserved for interrupted work. */
+ decision: ReviewDecisionContext | null;
+} & ReviewItems_Serialize;
+
+/** A review stack label: not blank, at most 256 characters. */
+export type ReviewTitle = string;
+
+/** Lifecycle of a discovery run (one per user × source). */
+export type RunStatus =
+ /**
+ * Slack discovery is staging candidates, or a Notion workspace import is
+ * being planned.
+ */
+ | 'running'
+ /** Discovery or planning finished; staged rows (if any) are ready. */
+ | 'ready'
+ /** An approved Notion workspace import plan is being written. */
+ | 'importing'
+ /**
+ * A Notion workspace import finished writing; `error` notes objects
+ * that could not be imported.
+ */
+ | 'completed'
+ /** Discovery, planning or writing failed; `error` has details. Retryable. */
+ | 'failed'
+ /**
+ * A Notion workspace import was cancelled. Older rows may hold it from
+ * the removed onboarding import, where it meant a dismissed section.
+ */
+ | 'dismissed';
+
+/** What a planning run has found in the source so far. */
+export type ScanCounts = {
+ /** Pages found. */
+ pages: number;
+ /** Data sources (database tables) found. */
+ dataSources: number;
+};
+
+/** Compose and send an email. Creates a draft and immediately queues it for delivery. */
+export type SendEmail = {
+ /** The subject line of the email. */
+ subject: string;
+ /**
+ * The address of the inbox to send from, when the user has more than one
+ * connected and this email belongs to a particular one. Use the exact
+ * `emailAddress` of a connected inbox — `ListInboxes` lists them, and
+ * `GetThread` reports the `inbox` a thread belongs to. Omit it unless
+ * you know which inbox is right: a reply then goes out from the inbox
+ * that received the message it answers, and a new email from the user's
+ * primary inbox. The user can change it in the composer either way.
+ */
+ from?: string | null;
+ /**
+ * The body of the email, written as Markdown. A host with a composer
+ * (chat) replaces this with the base64url-encoded HTML the composer
+ * exported before the tool runs; a host without one (an agent session)
+ * leaves the Markdown, and this tool renders it the same way.
+ */
+ body: string;
+ /** The primary recipients (To field). */
+ to: EmailRecipient[];
+ /** Carbon copy recipients (optional). */
+ cc?: EmailRecipient[];
+ /** Blind carbon copy recipients (optional). */
+ bcc?: EmailRecipient[];
+ /**
+ * The ID of a message to reply to (optional). When set, the email is
+ * sent as a reply within the same thread.
+ */
+ replyingToId?: string | null;
+ /**
+ * Per-message signature override, set by the composer's signature preview —
+ * not normally by you. Omit to use the inbox's default policy (always on a
+ * new email; on replies/forwards only when the user enabled it). `false`
+ * excludes the signature for this one email.
+ */
+ includeSignature?: boolean | null;
+ /**
+ * Macro documents to attach as files (optional). Each must be an
+ * uploaded file the user can view; together they may total 18 MB.
+ */
+ attachments?: EmailAttachment[];
+};
+
+/** Response from the SendEmail tool. */
+export type SendEmailResponse =
+ | ({
+ sent: {
+ /** The database ID of the sent message. */
+ message_id: string;
+ /** The thread ID the message belongs to. */
+ thread_id: string;
+ };
+ } & { convertedToDraft?: never })
+ | ({
+ convertedToDraft: {
+ draft_id: string;
+ };
+ } & { sent?: never })
+ | 'userEdited';
+
+/** A calendar event as returned by the create and update tools. */
+export type ToolCalendarEvent = {
+ /**
+ * Macro calendar event id, used by UpdateCalendarEvent and
+ * DeleteCalendarEvent.
+ */
+ eventId: string;
+ /** Display title. */
+ title: string;
+ /** Event start: RFC 3339 UTC instant, or YYYY-MM-DD for all-day events. */
+ start: string;
+ /**
+ * Exclusive event end: RFC 3339 UTC instant, or YYYY-MM-DD for all-day
+ * events.
+ */
+ end: string;
+ /** Whether the event covers whole days. */
+ isAllDay: boolean;
+ /** IANA time zone the event was scheduled in, when known. */
+ timeZone: string | null;
+ /** Location label, when set. */
+ location: string | null;
+ /** Event body, truncated for brevity. */
+ description: string | null;
+ /** Event status: confirmed, tentative, or cancelled. */
+ status: string;
+ /** Whether the event recurs. */
+ isRecurring: boolean;
+ /** Raw RFC 5545 recurrence properties, when the event recurs. */
+ recurrenceLines: string[];
+ /** Attendees, capped at 20; `attendee_count` has the full number. */
+ attendees: ToolEventAttendee[];
+ /** Total number of attendees. */
+ attendeeCount: number;
+ /** Organizer email address, when known. */
+ organizerEmail: string | null;
+ /** Conference join URL, when a conference is attached. */
+ conferenceUrl: string | null;
+ /**
+ * Join URL of the Macro call created with the event, when
+ * CreateCalendarEvent was asked for one.
+ */
+ macroCallUrl: string | null;
+ /** Whether the user's calendar prohibits modifying this event. */
+ isReadOnly: boolean;
+ /** Calendar the event belongs to, when known. */
+ calendarId: string | null;
+ /** Display name of that calendar, when known. */
+ calendarName: string | null;
+ /**
+ * Connected inbox address syncing the calendar, when known. It stays the
+ * user's own address on a colleague's calendar, so it never says whose
+ * calendar it is.
+ */
+ inbox: string | null;
+ /**
+ * Whether the user organizes this event or is a guest on it, through
+ * that inbox; absent when they are neither, can only write that
+ * calendar, or a read-only calendar names them organizer.
+ */
+ myRole: ToolEventRole | null;
+};
+
+/** An attendee of a calendar event, as returned by calendar tools. */
+export type ToolEventAttendee = {
+ /** Attendee email address. */
+ email: string;
+ /** RSVP state: needs_action, accepted, declined, or tentative. */
+ responseStatus: string;
+ /** Whether this attendee organized the event. */
+ isOrganizer: boolean;
+ /** Whether attendance is optional. */
+ isOptional: boolean;
+};
+
+/** What the user is on one copy of an event, through the inbox holding it. */
+export type ToolEventRole =
+ /**
+ * The inbox organizes the event, or the event has no guests and is the
+ * user's own. Being able to write someone else's calendar is not this,
+ * nor is a read-only calendar naming them organizer; `viewerCan` says
+ * what the user may do there.
+ */
+ | 'organizer'
+ /** The inbox is invited to the event. */
+ | 'guest';
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts
index 132551946b..34841e715d 100644
--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts
+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts
@@ -2342,25 +2342,27 @@ export const CreateCalendarEvent = z.object({
addMacroCall: z.boolean().optional(),
addConference: z.boolean().optional(),
eventType: z
- .any()
- .superRefine((x, ctx) => {
- const schemas = [z.literal('default'), z.literal('out_of_office')];
- const errors = schemas.reduce<z.ZodError[]>(
- (errors, schema) =>
- ((result) => (result.error ? [...errors, result.error] : errors))(
- schema.safeParse(x)
- ),
- []
- );
- if (schemas.length - errors.length !== 1) {
- ctx.addIssue({
- path: ctx.path,
- code: 'invalid_union',
- unionErrors: errors,
- message: 'Invalid input: Should pass single schema',
- });
- }
- })
+ .intersection(
+ z.any().superRefine((x, ctx) => {
+ const schemas = [z.literal('default'), z.literal('out_of_office')];
+ const errors = schemas.reduce<z.ZodError[]>(
+ (errors, schema) =>
+ ((result) => (result.error ? [...errors, result.error] : errors))(
+ schema.safeParse(x)
+ ),
+ []
+ );
+ if (schemas.length - errors.length !== 1) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message: 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ z.any().default('default')
+ )
.optional(),
outOfOffice: z
.union([
@@ -2605,25 +2607,27 @@ export const CreateConfirmedCalendarEvent = z.object({
addMacroCall: z.boolean().optional(),
addConference: z.boolean().optional(),
eventType: z
- .any()
- .superRefine((x, ctx) => {
- const schemas = [z.literal('default'), z.literal('out_of_office')];
- const errors = schemas.reduce<z.ZodError[]>(
- (errors, schema) =>
- ((result) => (result.error ? [...errors, result.error] : errors))(
- schema.safeParse(x)
- ),
- []
- );
- if (schemas.length - errors.length !== 1) {
- ctx.addIssue({
- path: ctx.path,
- code: 'invalid_union',
- unionErrors: errors,
- message: 'Invalid input: Should pass single schema',
- });
- }
- })
+ .intersection(
+ z.any().superRefine((x, ctx) => {
+ const schemas = [z.literal('default'), z.literal('out_of_office')];
+ const errors = schemas.reduce<z.ZodError[]>(
+ (errors, schema) =>
+ ((result) => (result.error ? [...errors, result.error] : errors))(
+ schema.safeParse(x)
+ ),
+ []
+ );
+ if (schemas.length - errors.length !== 1) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message: 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ z.any().default('default')
+ )
.optional(),
outOfOffice: z
.union([
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts
index 49d35fea9e..ebdbdd03ab 100644
--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts
+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts
@@ -419,6 +419,10 @@ export type EventTimeInput =
endDate: string;
kind: 'allDay';
};
+/**
+ * An address that passes [`is_valid_email`]; decoding rejects any other string.
+ */
+export type EmailAddress = string;
/**
* The kind of event a create tool call makes.
*/
@@ -7393,7 +7397,7 @@ export interface CreateCalendarEvent {
* Attach a conference supported by this calendar: Google Meet or Microsoft Teams. Check ListCalendars capabilities first.
*/
addConference?: boolean;
- eventType?: CalendarEventTypeInput;
+ eventType?: CalendarEventTypeInput & string;
/**
* Out-of-office decline behavior, used only when eventType is "out_of_office". Omit to just block the time; set `autoDeclineMode` to "decline_all" or "decline_new_only" to have the calendar integration decline conflicting meetings, optionally with a `declineMessage`.
*/
@@ -7407,10 +7411,7 @@ export interface CreateCalendarEvent {
* An attendee supplied to a calendar tool.
*/
export interface AttendeeInput {
- /**
- * The attendee's email address.
- */
- email: string;
+ email: EmailAddress;
/**
* Whether attendance is optional for this attendee. Defaults to required.
*/
@@ -7582,7 +7583,7 @@ export interface CreateConfirmedCalendarEvent {
* Attach a conference supported by this calendar: Google Meet or Microsoft Teams. Check ListCalendars capabilities first.
*/
addConference?: boolean;
- eventType?: CalendarEventTypeInput;
+ eventType?: CalendarEventTypeInput & string;
/**
* Out-of-office decline behavior, used only when eventType is "out_of_office". Omit to just block the time; set `autoDeclineMode` to "decline_all" or "decline_new_only" to have the calendar integration decline conflicting meetings, optionally with a `declineMessage`.
*/
@@ -15419,10 +15420,7 @@ export interface SendConfirmedEmail {
* A recipient for an email.
*/
export interface EmailRecipient {
- /**
- * The recipient's email address.
- */
- email: string;
+ email: EmailAddress;
/**
* The recipient's display name (optional).
*/
diff --git a/apps/web/tsconfig.json b/apps/web/tsconfig.json
index e501053f68..14d8f353fa 100644
--- a/apps/web/tsconfig.json
+++ b/apps/web/tsconfig.json
@@ -137,6 +137,9 @@
"@service-agent-fold/*": [
"./src/lib/service-clients/service-agent-fold/*"
],
+ "@service-agent-reviews/*": [
+ "./src/lib/service-clients/service-agent-reviews/*"
+ ],
"@block-chat/*": [
"./src/features/block-chat/*"
],
diff --git a/crates/agent_code_mode/AGENTS.md b/crates/agent_code_mode/AGENTS.md
index e660cc459d..f784c6c875 100644
--- a/crates/agent_code_mode/AGENTS.md
+++ b/crates/agent_code_mode/AGENTS.md
@@ -22,7 +22,13 @@ stacks. Process isolation belongs to
receipts include observed SDK activity for inline conversation snapshots.
- `src/domain/user.rs`: `UserCodeMode`, runs as an authenticated user with no
session, journal or reviews; shares outcome validation with the session path.
-- `src/domain/reviews.rs`: review validation, revisions, claims and outcomes.
+- `src/domain/reviews.rs`: review revisions, claims and outcomes.
+ `src/domain/reviews/drafts.rs` holds the typed drafts and results: items
+ keyed by kind, reusing `SendEmail`, `CreateCalendarEvent` and their
+ responses, and the import plan selection. Decoding is the only validation
+ (`decode`, location-only errors); value constraints are nutype newtypes.
+ Submit refuses incomplete drafts (no recipients, no title, ends before it
+ starts) before claiming the batch.
`decide_for_session` (the `DecideReview` tool, `inbound/reviews.rs`) is the
agent deciding on the account holder's word in chat: a turn they prompted,
never a System turn (per `ReviewSession::prompter`), and a Submit only once
@@ -58,7 +64,7 @@ session presentation. Never replay an uncertain submitted action.
Reviews write `review.decided` and `review.settled` through the injected
transaction-aware notification writer in the same revision-checked transaction.
Reviews persist the immutable acting account. Only that account may edit or
-submit; historical reviews without an acting account use the session owner.
+submit.
ACP presentation uses the session owner's transcript capability, independently
of the account that later sends the email or creates the event. Cards require
direct user authentication; `DecideReview` requires a real turn prompted by the
@@ -78,3 +84,8 @@ longer delivery state.
Import reviews contain exactly one draft, with source `notion`, `linear`, or
`jira`. Source selection stays on that draft through presentation and approval.
+
+The web and SDK review types are generated from these Rust types with specta
+(`src/bin/export_review_types.rs`, `just gen-agent-review-types` in `apps/web`).
+Regenerate after changing a review type or a type a draft or result reuses; CI
+fails on stale output.
diff --git a/crates/agent_code_mode/Cargo.toml b/crates/agent_code_mode/Cargo.toml
index ecacc7d42f..c87b56a206 100644
--- a/crates/agent_code_mode/Cargo.toml
+++ b/crates/agent_code_mode/Cargo.toml
@@ -15,15 +15,23 @@ async-trait = { workspace = true }
anyhow = { workspace = true }
axum = { workspace = true }
bot_id = { path = "../bot_id" }
+calendar_events = { path = "../calendar_events", features = ["ai_tools"] }
code_execution = { path = "../code_execution" }
+email = { path = "../email", features = ["ai_tools", "inbound"] }
entity_access = { path = "../entity_access", default-features = false, features = ["ports", "inbound"] }
+import = { path = "../import" }
macro_authorization = { path = "../macro_authorization", default-features = false, features = ["axum"] }
macro_user_id = { path = "../macro_user_id" }
macro_uuid = { path = "../macro_uuid" }
+nutype = { workspace = true }
rootcause = { workspace = true }
schemars = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
+serde_path_to_error = { workspace = true }
+specta = { workspace = true }
+specta-serde = { workspace = true }
+specta-typescript = { workspace = true }
sqlx = { workspace = true, features = ["json"] }
thiserror = { workspace = true }
tokio = { workspace = true, features = ["rt", "sync"] }
diff --git a/crates/agent_code_mode/src/bin/export_review_types.rs b/crates/agent_code_mode/src/bin/export_review_types.rs
new file mode 100644
index 0000000000..6207d05e15
--- /dev/null
+++ b/crates/agent_code_mode/src/bin/export_review_types.rs
@@ -0,0 +1,43 @@
+//! Export the review wire contract as TypeScript.
+//!
+//! Run with:
+//!
+//! ```text
+//! cargo run -p agent_code_mode --bin export_review_types
+//! ```
+
+use agent_code_mode::domain::reviews::{CreateReview, ReviewDecision, ReviewRecord};
+use specta::Types;
+use specta_typescript::Typescript;
+use std::fs;
+use std::path::Path;
+
+fn main() -> Result<(), rootcause::Report> {
+ let types = Types::default()
+ .register::<CreateReview>()
+ .register::<ReviewDecision>()
+ .register::<ReviewRecord>();
+ // Defaulted fields are optional on input and always present on output.
+ let generated = Typescript::default()
+ .export(&types, specta_serde::PhasesFormat)
+ .map_err(|error| rootcause::report!("could not export the review types: {error}"))?;
+ let generated = generated
+ .lines()
+ .map(str::trim_end)
+ .collect::<Vec<_>>()
+ .join("\n");
+
+ // The web review card and the SDK's review handles read the same records.
+ let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
+ for output in [
+ "apps/web/src/lib/service-clients/service-agent-reviews/generated/types.ts",
+ "packages/sdk/generated/agent-reviews/index.ts",
+ ] {
+ let output = root.join(output);
+ if let Some(parent) = output.parent() {
+ fs::create_dir_all(parent)?;
+ }
+ fs::write(output, format!("{generated}\n"))?;
+ }
+ Ok(())
+}
diff --git a/crates/agent_code_mode/src/domain/documentation.json b/crates/agent_code_mode/src/domain/documentation.json
index 63d21aa585..b0607b60ae 100644
--- a/crates/agent_code_mode/src/domain/documentation.json
+++ b/crates/agent_code_mode/src/domain/documentation.json
@@ -3,7 +3,7 @@
{
"name": "agentSessions",
"description": "Create and inspect agent sessions, read any viewable session's history as folded messages (`session.foldedLog()`), saved code executions, and editable email or calendar review stacks.",
- "index": "## agentSessions\nCreate and inspect agent sessions, read any viewable session's history as folded messages (`session.foldedLog()`), saved code executions, and editable email or calendar review stacks.\nRead any symbol below, or one a reference names, with ReadCodeDocs.\n\n### AgentSession\nA managed or externally hosted coding-agent session.\nExtends `MacroEntity`.\nFields: access, archivedAt, archivedBy, codeExecutions, createdAt, harness, id, instructions, model, modifiedAt, name, repoUrl, reviews, sandboxSize, status, views, workspace\n- `AgentSession.archive`: archive(): Promise<void> — Archive this session, making it read-only until unarchived.\n- `AgentSession.autoArchive`: autoArchive(): Promise<SessionAutoArchive> — This session's auto-archive settings, and when a trigger archived it.\n- `AgentSession.changes`: changes(): Promise<AgentSessionChangesResponse> — Read the latest captured GitHub pull request changes and capture status.\n- `AgentSession.changesPatch`: changesPatch(): Promise<string> — Read the unified diff of the latest captured changeset.\n- `AgentSession.control`: control(action): Promise<ControlResponse> — Send a prompt or lifecycle operation to the live agent session.\n- `AgentSession.delete`: delete(): Promise<void> — Delete this session and any live resources it owns.\n- `AgentSession.foldedLog`: foldedLog(): Promise<FoldedAgentSessionLog> — Read this session's whole history as the conversation the app renders: each user prompt and agent reply, oldest first, with tool calls and their results, pla...\n- `AgentSession.linkPullRequest`: linkPullRequest(url): Promise<void> — Link the GitHub pull request at url to this session.\n- `AgentSession.log`: log(): Promise<AgentSessionLogResponse> — Read the complete raw protocol log for this session.\n- `AgentSession.prompt`: prompt(text, attachments?): Promise<ControlResponse> — Send a prompt to the session — sugar over [control](#control).\n- `AgentSession.pullRequests`: pullRequests(): Promise<SessionPullRequest[]> — The GitHub pull requests linked to this session: the one its agent opened and any a person linked, oldest first.\n- `AgentSession.queue`: queue(): Promise<QueuedAction[]> — The actions waiting to dispatch in this session, oldest first.\n- `AgentSession.refreshChanges`: refreshChanges(): Promise<AgentSessionChangesResponse> — Request a fresh capture and return the current state while it runs.\n- `AgentSession.rename`: rename(name): Promise<void> — Rename this session.\n- `AgentSession.setAutoArchive`: setAutoArchive(overrides): Promise<void> — Replace this session's auto-archive choices.\n- `AgentSession.setSandboxSize`: setSandboxSize(size): Promise<SandboxSize> — Resize this session's sandbox and remember the size as the owner's default.\n- `AgentSession.sharePermissions`: sharePermissions(): Promise<agent-harness.SharePermissionV2> — Sharing configuration.\n- `AgentSession.toolApprovalById`: toolApprovalById(id): ToolApproval — Construct an approval handle scoped to this session.\n- `AgentSession.unarchive`: unarchive(): Promise<void> — Restore an archived session so it can be edited and prompted again.\n- `AgentSession.unlinkPullRequest`: unlinkPullRequest(url): Promise<void> — Unlink a GitHub pull request a person linked to this session.\n- `AgentSession.updateSharePermissions`: updateSharePermissions(options): Promise<agent-harness.SharePermissionV2> — Replace sharing grants.\n- `AgentSession.autoArchivePreferences`: static autoArchivePreferences(client): Promise<AutoArchivePreferencesBody> — Which triggers archive the caller's sessions by default; each is off unless chosen.\n- `AgentSession.byId`: static byId(client, id): AgentSession — A handle to an agent session by id.\n- `AgentSession.chooseMode`: static chooseMode(client, prompt): Promise<AgentMode> — Whether prompt needs a chat agent or a coding agent, as the app's Auto mode decides before starting a session.\n- `AgentSession.codingPreferences`: static codingPreferences(client): Promise<CodingPreferencesBody> — What the caller's new coding sessions are told to do beyond their assignment.\n- `AgentSession.createManaged`: static createManaged(client, opts?): Promise<AgentSession> — Create a managed session as agent when one is named, otherwise the deployment's default coding persona.\n- `AgentSession.defaultSandboxSize`: static defaultSandboxSize(client): Promise<SandboxSize> — The caller's default sandbox size for new @coder sessions.\n- `AgentSession.forPullRequest`: static forPullRequest(client, url): Promise<AgentSession[]> — The sessions linked to the GitHub pull request at url that the caller can view, oldest link first.\n- `AgentSession.repositories`: static repositories(client): Promise<SelectableRepository[]> — The GitHub repositories the caller can hand a managed session: every repository under an installation of Macro's GitHub App they or their teams made, sorted ...\n- `AgentSession.repositoryBranches`: static repositoryBranches(client, repoUrl): Promise<string[]> — Branch names on one repository the caller can start a managed session from, in the order GitHub listed them.\n- `AgentSession.setAutoArchivePreferences`: static setAutoArchivePreferences(client, preferences): Promise<AutoArchivePreferencesBody> — Replace which triggers archive the caller's sessions by default.\n- `AgentSession.setCodingPreferences`: static setCodingPreferences(client, preferences): Promise<CodingPreferencesBody> — Replace the caller's coding preferences.\n- `AgentSession.setDefaultSandboxSize`: static setDefaultSandboxSize(client, size): Promise<SandboxSize> — Set the caller's default sandbox size for the next @coder mention.\n\n### CodeExecution\nA saved code execution belonging to one agent session.\nExtends `MacroEntity`.\nFields: calls, error, id, reviews, source, status, views\n- `CodeExecution.refresh`: refresh(): Promise<CodeExecution> — Reload the saved state, for example after a running execution completes.\n- `CodeExecution.result`: result(): Promise<unknown> — The program's returned JSON; preserves an explicit null result.\n- `CodeExecution.session`: session(): AgentSession — The session this execution belongs to.\n- `CodeExecution.byId`: static byId(client, session, id): CodeExecution — Construct a lazy execution handle within its owning session.\n\n### AgentConversation\nAn agent's conversation in one channel.\nFields: channel\n- `AgentConversation.agent`: agent(): Agent — The agent taking part.\n- `AgentConversation.sessions`: sessions(): { createdAt: string; isCurrent: boolean; session: AgentSession; }[] — Conversation sessions with their current flag.\n- `AgentConversation.startFresh`: startFresh(session): Promise<void> — Start a fresh conversation from one of its sessions.\n- `AgentConversation.toJSON`: toJSON(): { agentId: string; channelId: string; } — Serialize scoped identity.\n- `AgentConversation.turns`: turns(): ConversationTurn[] — Recorded conversation turns.\n\n### ConversationTurn\nOne agent conversation turn, identified by its source message.\nFields: conversation\n- `ConversationTurn.retry`: retry(actionId): Promise<void> — Retry with a caller persisted action nonce.\n- `ConversationTurn.session`: session(): AgentSession — Session that handled this turn.\n- `ConversationTurn.source`: source(): Message — Originating message.\n- `ConversationTurn.toJSON`: toJSON(): { channelId: string; sourceMessageId: string; } — Serialize scoped identity.\n\n### AgentSessionNamespace (`macro.agentSessions`)\nEntry point for coding-agent sessions.\n- `AgentSessionNamespace.autoArchivePreferences`: autoArchivePreferences(): Promise<AutoArchivePreferencesBody> — Which triggers archive the caller's sessions by default; each is off unless chosen.\n- `AgentSessionNamespace.byId`: byId(id): AgentSession — A handle to an agent session by id.\n- `AgentSessionNamespace.chooseMode`: chooseMode(prompt): Promise<AgentMode> — Whether prompt needs a chat agent ('chat') or a coding agent ('code'), as the app's Auto mode decides before starting a session.\n- `AgentSessionNamespace.codingPreferences`: codingPreferences(): Promise<CodingPreferencesBody> — What the caller's new coding sessions are told to do beyond their assignment.\n- `AgentSessionNamespace.createManaged`: createManaged(opts?): Promise<AgentSession> — Create a managed session as agent when one is named, otherwise the deployment's default coding persona.\n- `AgentSessionNamespace.defaultSandboxSize`: defaultSandboxSize(): Promise<SandboxSize> — The caller's default sandbox size for new @coder sessions.\n- `AgentSessionNamespace.forPullRequest`: forPullRequest(url): Promise<AgentSession[]> — The sessions linked to the GitHub pull request at url that the caller can view.\n- `AgentSessionNamespace.repositories`: repositories(): Promise<SelectableRepository[]> — The GitHub repositories the caller can hand a managed session, with the branch each one's sessions start on by default.\n- `AgentSessionNamespace.repositoryBranches`: repositoryBranches(repoUrl): Promise<string[]> — Branch names on one repository the caller can start a managed session from.\n- `AgentSessionNamespace.setAutoArchivePreferences`: setAutoArchivePreferences(preferences): Promise<AutoArchivePreferencesBody> — Replace which triggers archive the caller's sessions by default.\n- `AgentSessionNamespace.setCodingPreferences`: setCodingPreferences(preferences): Promise<CodingPreferencesBody> — Replace the caller's coding preferences.\n- `AgentSessionNamespace.setDefaultSandboxSize`: setDefaultSandboxSize(size): Promise<SandboxSize> — Set the caller's default sandbox size for the next @coder mention.\n\n### QueuedAction\nOne action waiting in an agent session's server-side queue: a prompt or a compact accepted while a turn was running, dispatching when that turn ends.\n- `QueuedAction.edit`: edit(prompt): Promise<QueuedAction> — Replace this queued prompt's text before it dispatches.\n- `QueuedAction.remove`: remove(): Promise<void> — Remove this action from the queue before it dispatches.\n- `QueuedAction.steer`: steer(): Promise<void> — Move this action to the front and interrupt the current turn to run it next.\n- `QueuedAction.from`: static from(client, sessionId, dto): QueuedAction — Wrap a queue entry already in hand (e.g.\n\n### ReviewItem\nAn item handle scopes edits and decisions to its persisted review.\n- `ReviewItem.dismiss`: dismiss(): Promise<void> — Promise<void>\n- `ReviewItem.edit`: edit(draft): Promise<void> — Promise<void>\n- `ReviewItem.submit`: submit(): Promise<void> — Promise<void>\n\n### SessionReview\nA persistent review remains actionable after the code execution ends.\nExtends `MacroEntity`.\nFields: id, kind, title\n- `SessionReview.dismissAll`: dismissAll(): Promise<void> — Promise<void>\n- `SessionReview.items`: items(): Promise<ReviewItem[]> — Promise<ReviewItem[]>\n- `SessionReview.reference`: reference(): Promise<{ id: string; kind: ReviewKind; }> — Compact reference for main()'s returned reviews array.\n- `SessionReview.refresh`: refresh(): Promise<SessionReview> — Promise<SessionReview>\n- `SessionReview.session`: session(): AgentSession — AgentSession\n- `SessionReview.submitAll`: submitAll(): Promise<void> — Submit the saved pending drafts.\n- `SessionReview.byId`: static byId(client, session, id): SessionReview — SessionReview\n- `SessionReview.create`: static create(client, execution, input): Promise<SessionReview> — Promise<SessionReview>\n- `SessionReview.createForSession`: static createForSession(client, session, input, execution?): Promise<SessionReview> — Present a review in a session without requiring a code execution.\n- `SessionReview.fromRecord`: static fromRecord(client, session, record): SessionReview — SessionReview\n- `SessionReview.list`: static list(client, execution): Promise<SessionReview[]> — Promise<SessionReview[]>\n\n### ToolApproval\nA permission request scoped to its originating agent session.\nFields: id, session\n- `ToolApproval.answer`: answer(answer): Promise<AnswerToolApprovalResponse> — Answer the approval using the generated discriminated answer contract.\n- `ToolApproval.toJSON`: toJSON(): { id: string; sessionId: string; } — Serialize scoped identity only.\n- `ToolApproval.byId`: static byId(client, session, id): ToolApproval — Construct a scoped approval handle.\n\nFunctions: `presentView`\n\nTypes: `AutoArchiveOverrides`, `CreateManagedSessionOptions`, `FoldedAgentSessionLog`, `SelectableRepository`, `SessionAutoArchive`, `SessionPullRequest`, `CodeResult`, `JsonValue`, `CreateReviewOptions`, `ReviewCalendarDraft`, `ReviewEmailDraft`, `SessionView`\n"
+ "index": "## agentSessions\nCreate and inspect agent sessions, read any viewable session's history as folded messages (`session.foldedLog()`), saved code executions, and editable email or calendar review stacks.\nRead any symbol below, or one a reference names, with ReadCodeDocs.\n\n### AgentSession\nA managed or externally hosted coding-agent session.\nExtends `MacroEntity`.\nFields: access, archivedAt, archivedBy, codeExecutions, createdAt, harness, id, instructions, model, modifiedAt, name, repoUrl, reviews, sandboxSize, status, views, workspace\n- `AgentSession.archive`: archive(): Promise<void> — Archive this session, making it read-only until unarchived.\n- `AgentSession.autoArchive`: autoArchive(): Promise<SessionAutoArchive> — This session's auto-archive settings, and when a trigger archived it.\n- `AgentSession.changes`: changes(): Promise<AgentSessionChangesResponse> — Read the latest captured GitHub pull request changes and capture status.\n- `AgentSession.changesPatch`: changesPatch(): Promise<string> — Read the unified diff of the latest captured changeset.\n- `AgentSession.control`: control(action): Promise<ControlResponse> — Send a prompt or lifecycle operation to the live agent session.\n- `AgentSession.delete`: delete(): Promise<void> — Delete this session and any live resources it owns.\n- `AgentSession.foldedLog`: foldedLog(): Promise<FoldedAgentSessionLog> — Read this session's whole history as the conversation the app renders: each user prompt and agent reply, oldest first, with tool calls and their results, pla...\n- `AgentSession.linkPullRequest`: linkPullRequest(url): Promise<void> — Link the GitHub pull request at url to this session.\n- `AgentSession.log`: log(): Promise<AgentSessionLogResponse> — Read the complete raw protocol log for this session.\n- `AgentSession.prompt`: prompt(text, attachments?): Promise<ControlResponse> — Send a prompt to the session — sugar over [control](#control).\n- `AgentSession.pullRequests`: pullRequests(): Promise<SessionPullRequest[]> — The GitHub pull requests linked to this session: the one its agent opened and any a person linked, oldest first.\n- `AgentSession.queue`: queue(): Promise<QueuedAction[]> — The actions waiting to dispatch in this session, oldest first.\n- `AgentSession.refreshChanges`: refreshChanges(): Promise<AgentSessionChangesResponse> — Request a fresh capture and return the current state while it runs.\n- `AgentSession.rename`: rename(name): Promise<void> — Rename this session.\n- `AgentSession.setAutoArchive`: setAutoArchive(overrides): Promise<void> — Replace this session's auto-archive choices.\n- `AgentSession.setSandboxSize`: setSandboxSize(size): Promise<SandboxSize> — Resize this session's sandbox and remember the size as the owner's default.\n- `AgentSession.sharePermissions`: sharePermissions(): Promise<agent-harness.SharePermissionV2> — Sharing configuration.\n- `AgentSession.toolApprovalById`: toolApprovalById(id): ToolApproval — Construct an approval handle scoped to this session.\n- `AgentSession.unarchive`: unarchive(): Promise<void> — Restore an archived session so it can be edited and prompted again.\n- `AgentSession.unlinkPullRequest`: unlinkPullRequest(url): Promise<void> — Unlink a GitHub pull request a person linked to this session.\n- `AgentSession.updateSharePermissions`: updateSharePermissions(options): Promise<agent-harness.SharePermissionV2> — Replace sharing grants.\n- `AgentSession.autoArchivePreferences`: static autoArchivePreferences(client): Promise<AutoArchivePreferencesBody> — Which triggers archive the caller's sessions by default; each is off unless chosen.\n- `AgentSession.byId`: static byId(client, id): AgentSession — A handle to an agent session by id.\n- `AgentSession.chooseMode`: static chooseMode(client, prompt): Promise<AgentMode> — Whether prompt needs a chat agent or a coding agent, as the app's Auto mode decides before starting a session.\n- `AgentSession.codingPreferences`: static codingPreferences(client): Promise<CodingPreferencesBody> — What the caller's new coding sessions are told to do beyond their assignment.\n- `AgentSession.createManaged`: static createManaged(client, opts?): Promise<AgentSession> — Create a managed session as agent when one is named, otherwise the deployment's default coding persona.\n- `AgentSession.defaultSandboxSize`: static defaultSandboxSize(client): Promise<SandboxSize> — The caller's default sandbox size for new @coder sessions.\n- `AgentSession.forPullRequest`: static forPullRequest(client, url): Promise<AgentSession[]> — The sessions linked to the GitHub pull request at url that the caller can view, oldest link first.\n- `AgentSession.repositories`: static repositories(client): Promise<SelectableRepository[]> — The GitHub repositories the caller can hand a managed session: every repository under an installation of Macro's GitHub App they or their teams made, sorted ...\n- `AgentSession.repositoryBranches`: static repositoryBranches(client, repoUrl): Promise<string[]> — Branch names on one repository the caller can start a managed session from, in the order GitHub listed them.\n- `AgentSession.setAutoArchivePreferences`: static setAutoArchivePreferences(client, preferences): Promise<AutoArchivePreferencesBody> — Replace which triggers archive the caller's sessions by default.\n- `AgentSession.setCodingPreferences`: static setCodingPreferences(client, preferences): Promise<CodingPreferencesBody> — Replace the caller's coding preferences.\n- `AgentSession.setDefaultSandboxSize`: static setDefaultSandboxSize(client, size): Promise<SandboxSize> — Set the caller's default sandbox size for the next @coder mention.\n\n### CodeExecution\nA saved code execution belonging to one agent session.\nExtends `MacroEntity`.\nFields: calls, error, id, reviews, source, status, views\n- `CodeExecution.refresh`: refresh(): Promise<CodeExecution> — Reload the saved state, for example after a running execution completes.\n- `CodeExecution.result`: result(): Promise<unknown> — The program's returned JSON; preserves an explicit null result.\n- `CodeExecution.session`: session(): AgentSession — The session this execution belongs to.\n- `CodeExecution.byId`: static byId(client, session, id): CodeExecution — Construct a lazy execution handle within its owning session.\n\n### AgentConversation\nAn agent's conversation in one channel.\nFields: channel\n- `AgentConversation.agent`: agent(): Agent — The agent taking part.\n- `AgentConversation.sessions`: sessions(): { createdAt: string; isCurrent: boolean; session: AgentSession; }[] — Conversation sessions with their current flag.\n- `AgentConversation.startFresh`: startFresh(session): Promise<void> — Start a fresh conversation from one of its sessions.\n- `AgentConversation.toJSON`: toJSON(): { agentId: string; channelId: string; } — Serialize scoped identity.\n- `AgentConversation.turns`: turns(): ConversationTurn[] — Recorded conversation turns.\n\n### ConversationTurn\nOne agent conversation turn, identified by its source message.\nFields: conversation\n- `ConversationTurn.retry`: retry(actionId): Promise<void> — Retry with a caller persisted action nonce.\n- `ConversationTurn.session`: session(): AgentSession — Session that handled this turn.\n- `ConversationTurn.source`: source(): Message — Originating message.\n- `ConversationTurn.toJSON`: toJSON(): { channelId: string; sourceMessageId: string; } — Serialize scoped identity.\n\n### AgentSessionNamespace (`macro.agentSessions`)\nEntry point for coding-agent sessions.\n- `AgentSessionNamespace.autoArchivePreferences`: autoArchivePreferences(): Promise<AutoArchivePreferencesBody> — Which triggers archive the caller's sessions by default; each is off unless chosen.\n- `AgentSessionNamespace.byId`: byId(id): AgentSession — A handle to an agent session by id.\n- `AgentSessionNamespace.chooseMode`: chooseMode(prompt): Promise<AgentMode> — Whether prompt needs a chat agent ('chat') or a coding agent ('code'), as the app's Auto mode decides before starting a session.\n- `AgentSessionNamespace.codingPreferences`: codingPreferences(): Promise<CodingPreferencesBody> — What the caller's new coding sessions are told to do beyond their assignment.\n- `AgentSessionNamespace.createManaged`: createManaged(opts?): Promise<AgentSession> — Create a managed session as agent when one is named, otherwise the deployment's default coding persona.\n- `AgentSessionNamespace.defaultSandboxSize`: defaultSandboxSize(): Promise<SandboxSize> — The caller's default sandbox size for new @coder sessions.\n- `AgentSessionNamespace.forPullRequest`: forPullRequest(url): Promise<AgentSession[]> — The sessions linked to the GitHub pull request at url that the caller can view.\n- `AgentSessionNamespace.repositories`: repositories(): Promise<SelectableRepository[]> — The GitHub repositories the caller can hand a managed session, with the branch each one's sessions start on by default.\n- `AgentSessionNamespace.repositoryBranches`: repositoryBranches(repoUrl): Promise<string[]> — Branch names on one repository the caller can start a managed session from.\n- `AgentSessionNamespace.setAutoArchivePreferences`: setAutoArchivePreferences(preferences): Promise<AutoArchivePreferencesBody> — Replace which triggers archive the caller's sessions by default.\n- `AgentSessionNamespace.setCodingPreferences`: setCodingPreferences(preferences): Promise<CodingPreferencesBody> — Replace the caller's coding preferences.\n- `AgentSessionNamespace.setDefaultSandboxSize`: setDefaultSandboxSize(size): Promise<SandboxSize> — Set the caller's default sandbox size for the next @coder mention.\n\n### QueuedAction\nOne action waiting in an agent session's server-side queue: a prompt or a compact accepted while a turn was running, dispatching when that turn ends.\n- `QueuedAction.edit`: edit(prompt): Promise<QueuedAction> — Replace this queued prompt's text before it dispatches.\n- `QueuedAction.remove`: remove(): Promise<void> — Remove this action from the queue before it dispatches.\n- `QueuedAction.steer`: steer(): Promise<void> — Move this action to the front and interrupt the current turn to run it next.\n- `QueuedAction.from`: static from(client, sessionId, dto): QueuedAction — Wrap a queue entry already in hand (e.g.\n\n### ReviewItem\nAn item handle scopes edits and decisions to its persisted review.\n- `ReviewItem.dismiss`: dismiss(): Promise<void> — Promise<void>\n- `ReviewItem.edit`: edit(draft): Promise<void> — Replace this pending draft; kind must match the review's.\n- `ReviewItem.submit`: submit(): Promise<void> — Promise<void>\n\n### SessionReview\nA persistent review remains actionable after the code execution ends.\nExtends `MacroEntity`.\nFields: id, kind, title\n- `SessionReview.dismissAll`: dismissAll(): Promise<void> — Promise<void>\n- `SessionReview.items`: items(): Promise<ReviewItem[]> — Promise<ReviewItem[]>\n- `SessionReview.reference`: reference(): Promise<{ id: string; kind: \"calendar\" | \"email\" | \"import\"; }> — Compact reference for main()'s returned reviews array.\n- `SessionReview.refresh`: refresh(): Promise<SessionReview> — Promise<SessionReview>\n- `SessionReview.session`: session(): AgentSession — AgentSession\n- `SessionReview.submitAll`: submitAll(): Promise<void> — Submit the saved pending drafts.\n- `SessionReview.byId`: static byId(client, session, id): SessionReview — SessionReview\n- `SessionReview.create`: static create(client, execution, input): Promise<SessionReview> — Promise<SessionReview>\n- `SessionReview.createForSession`: static createForSession(client, session, input, execution?): Promise<SessionReview> — Present a review in a session without requiring a code execution.\n- `SessionReview.fromRecord`: static fromRecord(client, session, record): SessionReview — SessionReview\n- `SessionReview.list`: static list(client, execution): Promise<SessionReview[]> — Promise<SessionReview[]>\n\n### ToolApproval\nA permission request scoped to its originating agent session.\nFields: id, session\n- `ToolApproval.answer`: answer(answer): Promise<AnswerToolApprovalResponse> — Answer the approval using the generated discriminated answer contract.\n- `ToolApproval.toJSON`: toJSON(): { id: string; sessionId: string; } — Serialize scoped identity only.\n- `ToolApproval.byId`: static byId(client, session, id): ToolApproval — Construct a scoped approval handle.\n\nFunctions: `presentView`\n\nTypes: `AutoArchiveOverrides`, `CreateManagedSessionOptions`, `FoldedAgentSessionLog`, `SelectableRepository`, `SessionAutoArchive`, `SessionPullRequest`, `CodeResult`, `JsonValue`, `CreateReviewOptions`, `ReviewCalendarDraft`, `ReviewDraft`, `ReviewEmailDraft`, `SessionView`\n"
},
{
"name": "agents",
@@ -187,14 +187,13 @@
"ControlResponse": "# Type Alias: ControlResponse\n\n> **ControlResponse** = \\{ `actionId`: `AgentActionId`; `status`: `ControlStatusDto`; \\}\n\nResponse body for a control operation.\n\nClients deserialize this, so both derives are used.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-actionid\"></a> `actionId` | `AgentActionId` | Matches `requestId` on the folded message this action derives once it dispatches, and names the queue entry until then. The caller's own `actionId` when it supplied one; a freshly minted id otherwise. |\n| <a id=\"property-status\"></a> `status` | `ControlStatusDto` | Whether the action went out or waits in the queue. |",
"ControlStatusDto": "# Type Alias: ControlStatusDto\n\n> **ControlStatusDto** = `\"sent\"` \\| `\"queued\"`\n\nWhat accepting a control operation did with it, on the wire.",
"ConversationTurnState": "# Type Alias: ConversationTurnState\n\n> **ConversationTurnState** = `\"queued\"` \\| `\"running\"` \\| `\"succeeded\"` \\| `\"failed\"` \\| `\"stopped\"` \\| `\"interrupted\"`\n\nThe state of one source message, retained after completion for deduplication.",
- "DecisionVia": "# Type Alias: DecisionVia\n\n> **DecisionVia** = `\"card\"` \\| `\"chat\"` \\| `\"inbox\"`\n\nSurface of a review decision.",
"agent-harness.DocumentId": "# Type Alias: DocumentId\n\n> **DocumentId** = `string`\n\nA validated document identifier. Historical document ids need not be UUIDs.",
"ElicitationAnswer": "# Type Alias: ElicitationAnswer\n\n> **ElicitationAnswer** = \\{ `action`: `\"accept\"`; `content?`: \\{\\[`key`: `string`\\]: `ElicitationContentValue`; \\} \\| `null`; \\} \\| \\{ `action`: `\"decline\"`; \\} \\| \\{ `action`: `\"cancel\"`; \\}\n\nWhat the user decided about an elicitation. Mirrors ACP's three actions;\nthere is no `Other` because we never originate an action we do not know.\n\n## Union Members\n\n### Type Literal\n\n\\{ `action`: `\"accept\"`; `content?`: \\{\\[`key`: `string`\\]: `ElicitationContentValue`; \\} \\| `null`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `action` | `\"accept\"` | - |\n| `content?` | \\{\\[`key`: `string`\\]: `ElicitationContentValue`; \\} \\| `null` | Form: the submitted values keyed by property. URL: omitted. |\n\n***\n\n### Type Literal\n\n\\{ `action`: `\"decline\"`; \\}\n\n***\n\n### Type Literal\n\n\\{ `action`: `\"cancel\"`; \\}",
"ElicitationContentValue": "# Type Alias: ElicitationContentValue\n\n> **ElicitationContentValue** = `string` \\| `boolean` \\| `number` \\| `number` \\| `string`[]\n\nA value ACP accepts in an elicitation answer.\n\nMirrors ACP's `ElicitationContentValue` so that the contract a caller\nanswers against is the closed union ACP will accept, rather than arbitrary\nJSON narrowed on the way out. An object, a null, or a mixed array is\nrefused when the request is deserialized - where the caller learns of it -\ninstead of at send time, when the elicitation slot has already been\nreleased.",
"ElicitationRequestId": "# Type Alias: ElicitationRequestId\n\n> **ElicitationRequestId** = `number` \\| `string`\n\nThe JSON-RPC id of an agent's `elicitation/create` request, carried whole\nso the answer echoes exactly what the agent sent.\n\nAgents pick these, not us: Claude Code counts from `0`, others use\nstrings. `null` is not a legal id for a request that expects a response,\nso it is not representable here.",
"ExecutionActivity": "# Type Alias: ExecutionActivity\n\n> **ExecutionActivity** = \\{ `id`: `number`; `label`: `string`; `status`: `RecordedCallStatus`; \\}\n\nA bounded SDK operation observed during execution; not an authorization or write receipt.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-id\"></a> `id` | `number` | Request identity within the execution. |\n| <a id=\"property-label\"></a> `label` | `string` | Server-selected label from the generated operation catalog. |\n| <a id=\"property-status\"></a> `status` | `RecordedCallStatus` | Observed request state; unfinished operations have unknown outcomes. |",
- "ExecutionId": "# Type Alias: ExecutionId\n\n> **ExecutionId** = `string`\n\nCaller-selected UUID persisted in tool input before execution begins.",
- "ExecutionRecord": "# Type Alias: ExecutionRecord\n\n> **ExecutionRecord** = \\{ `actingAs?`: `null` \\| `ToolActor`; `activity?`: `ExecutionActivity`[]; `activityTruncated?`: `boolean`; `calls`: `RecordedToolCall`[]; `error?`: `string` \\| `null`; `executionId`: `ExecutionId`; `result?`: `unknown`; `source`: `string`; `status`: `ExecutionStatus`; `turnId?`: `string` \\| `null`; \\}\n\nDurable source and final outcome, with historical bridge calls when present.\nThe full journal is not included in the model's tool result.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-actingas\"></a> `actingAs?` | `null` \\| `ToolActor` | - |\n| <a id=\"property-activity\"></a> `activity?` | `ExecutionActivity`[] | Advisory SDK operation activity, without arguments or response contents. |\n| <a id=\"property-activitytruncated\"></a> `activityTruncated?` | `boolean` | Additional request activity was omitted at the bounded observation limit. |\n| <a id=\"property-calls\"></a> `calls` | `RecordedToolCall`[] | Historical bridge calls. Direct HTTP executions leave this empty. |\n| <a id=\"property-error\"></a> `error?` | `string` \\| `null` | Safe execution failure text. |\n| <a id=\"property-executionid\"></a> `executionId` | `ExecutionId` | Execution identity. |\n| <a id=\"property-result\"></a> `result?` | `unknown` | JSON returned by the program, if successful. |\n| <a id=\"property-source\"></a> `source` | `string` | The submitted JavaScript module. |\n| <a id=\"property-status\"></a> `status` | `ExecutionStatus` | Overall execution state. |\n| <a id=\"property-turnid\"></a> `turnId?` | `string` \\| `null` | Original turn, preventing another requester from replaying a saved result. |",
+ "agent-harness.ExecutionId": "# Type Alias: ExecutionId\n\n> **ExecutionId** = `string`\n\nCaller-selected UUID persisted in tool input before execution begins.",
+ "ExecutionRecord": "# Type Alias: ExecutionRecord\n\n> **ExecutionRecord** = \\{ `actingAs?`: `null` \\| `ToolActor`; `activity?`: `ExecutionActivity`[]; `activityTruncated?`: `boolean`; `calls`: `RecordedToolCall`[]; `error?`: `string` \\| `null`; `executionId`: `agent-harness.ExecutionId`; `result?`: `unknown`; `source`: `string`; `status`: `ExecutionStatus`; `turnId?`: `string` \\| `null`; \\}\n\nDurable source and final outcome, with historical bridge calls when present.\nThe full journal is not included in the model's tool result.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-actingas\"></a> `actingAs?` | `null` \\| `ToolActor` | - |\n| <a id=\"property-activity\"></a> `activity?` | `ExecutionActivity`[] | Advisory SDK operation activity, without arguments or response contents. |\n| <a id=\"property-activitytruncated\"></a> `activityTruncated?` | `boolean` | Additional request activity was omitted at the bounded observation limit. |\n| <a id=\"property-calls\"></a> `calls` | `RecordedToolCall`[] | Historical bridge calls. Direct HTTP executions leave this empty. |\n| <a id=\"property-error\"></a> `error?` | `string` \\| `null` | Safe execution failure text. |\n| <a id=\"property-executionid\"></a> `executionId` | `agent-harness.ExecutionId` | Execution identity. |\n| <a id=\"property-result\"></a> `result?` | `unknown` | JSON returned by the program, if successful. |\n| <a id=\"property-source\"></a> `source` | `string` | The submitted JavaScript module. |\n| <a id=\"property-status\"></a> `status` | `ExecutionStatus` | Overall execution state. |\n| <a id=\"property-turnid\"></a> `turnId?` | `string` \\| `null` | Original turn, preventing another requester from replaying a saved result. |",
"ExecutionStatus": "# Type Alias: ExecutionStatus\n\n> **ExecutionStatus** = `\"running\"` \\| `\"succeeded\"` \\| `\"failed\"` \\| `\"cancelled\"` \\| `\"timed_out\"`\n\nThe recorded outcome of a program.",
"ExternalSessionResponse": "# Type Alias: ExternalSessionResponse\n\n> **ExternalSessionResponse** = \\{ `name?`: `string` \\| `null`; `provider`: `string`; `url?`: `string` \\| `null`; \\}\n\nThe provider-side identity of an externally-served session.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-name\"></a> `name?` | `string` \\| `null` | The provider's display name for the agent, when it reported one. |\n| <a id=\"property-provider\"></a> `provider` | `string` | Which provider serves the session, e.g. `cursor`. |\n| <a id=\"property-url\"></a> `url?` | `string` \\| `null` | The agent's page on the provider's site, for a client to link out to. |",
"agent-harness.FileChangeKindDto": "# Type Alias: FileChangeKindDto\n\n> **FileChangeKindDto** = `\"added\"` \\| `\"modified\"` \\| `\"deleted\"` \\| `\"renamed\"`\n\nWhat happened to a file, on the wire.",
@@ -204,18 +203,12 @@
"LogFrameDto": "# Type Alias: LogFrameDto\n\n> **LogFrameDto** = \\{ `content`: \\{\\[`key`: `string`\\]: `unknown`; \\}; `direction`: `LogDirectionDto`; \\}\n\nThe two fields [`AgentSessionLogEntryDto`] flattens in.\n\nSchema only. Nothing constructs one: the entry serializes through\n[`Message`], and this exists so the generated clients see `direction` and\n`content` as named fields instead of an open map. A hand-built copy could\ndrift from the fold's wire format, and the point of the endpoint is that it\ncannot - so this describes that format without being able to produce it.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-content\"></a> `content` | \\{\\[`key`: `string`\\]: `unknown`; \\} | The protocol envelope, verbatim. Opaque here: it is Agent Runtime Protocol, whose shape belongs to the fold rather than this endpoint. |\n| <a id=\"property-direction\"></a> `direction` | `LogDirectionDto` | Which way the frame travelled. |",
"agent-harness.MessageParent": "# Type Alias: MessageParent\n\n> **MessageParent** = \\{ `id`: `string`; `type`: `\"channel\"`; \\} \\| \\{ `id`: `agent-harness.DocumentId`; `type`: `\"document\"`; \\} \\| \\{ `id`: `string`; `type`: `\"initiative\"`; \\} \\| \\{ `id`: `string`; `type`: `\"crm_company\"`; \\} \\| \\{ `id`: `string`; `type`: `\"crm_contact\"`; \\} \\| \\{ `id`: `string`; `type`: `\"call\"`; \\}\n\nThe entity whose permissions and lifecycle govern a message.\n\n## Union Members\n\n### Type Literal\n\n\\{ `id`: `string`; `type`: `\"channel\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `id` | `string` | A channel, including direct messages. |\n| `type` | `\"channel\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `id`: `agent-harness.DocumentId`; `type`: `\"document\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `id` | `agent-harness.DocumentId` | A document, including tasks and PDFs. |\n| `type` | `\"document\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `id`: `string`; `type`: `\"initiative\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `id` | `string` | An initiative, presented as a project in the application. |\n| `type` | `\"initiative\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `id`: `string`; `type`: `\"crm_company\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `id` | `string` | A CRM company. |\n| `type` | `\"crm_company\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `id`: `string`; `type`: `\"crm_contact\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `id` | `string` | A CRM contact. |\n| `type` | `\"crm_contact\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `id`: `string`; `type`: `\"call\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `id` | `string` | A video call and its persistent chat thread. |\n| `type` | `\"call\"` | - |",
"PermissionAnswer": "# Type Alias: PermissionAnswer\n\n> **PermissionAnswer** = \\{ `kind`: `\"selected\"`; `optionId`: `string`; \\} \\| \\{ `kind`: `\"cancelled\"`; \\}\n\nThe decision carried by an [`AgentPermissionAction`].\n\n## Union Members\n\n### Type Literal\n\n\\{ `kind`: `\"selected\"`; `optionId`: `string`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `kind` | `\"selected\"` | - |\n| `optionId` | `string` | The chosen option's id, as the agent listed it. |\n\n***\n\n### Type Literal\n\n\\{ `kind`: `\"cancelled\"`; \\}",
- "PresentView": "# Type Alias: PresentView\n\n> **PresentView** = \\{ `executionId?`: `null` \\| `ExecutionId`; `view`: \\{\\[`key`: `string`\\]: `unknown`; \\}; \\}\n\nA view to present.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-executionid\"></a> `executionId?` | `null` \\| `ExecutionId` | - |\n| <a id=\"property-view\"></a> `view` | \\{\\[`key`: `string`\\]: `unknown`; \\} | A dynamic-UI view, in the format of the PresentView schema in ExecuteCode's description. |",
+ "PresentView": "# Type Alias: PresentView\n\n> **PresentView** = \\{ `executionId?`: `null` \\| `agent-harness.ExecutionId`; `view`: \\{\\[`key`: `string`\\]: `unknown`; \\}; \\}\n\nA view to present.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-executionid\"></a> `executionId?` | `null` \\| `agent-harness.ExecutionId` | - |\n| <a id=\"property-view\"></a> `view` | \\{\\[`key`: `string`\\]: `unknown`; \\} | A dynamic-UI view, in the format of the PresentView schema in ExecuteCode's description. |",
"PromptAttachment": "# Type Alias: PromptAttachment\n\n> **PromptAttachment** = \\{ `mimeType?`: `string` \\| `null`; `name`: `string`; `size?`: `number` \\| `null`; `uri`: `string`; \\}\n\nA file the prompt refers to, by where the agent can fetch it.\n\nMirrors ACP's `resource_link` content block, which every agent must\naccept: bytes never ride the prompt, only a URI (a static file service URL\nin practice) with enough metadata for a client to render a chip and for\nthe agent to decide whether to fetch it. Keeping the wire shape ACP-native\nmeans the harness translates without resolving anything, and the fold\nreads the same fields back off the logged frame.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-mimetype\"></a> `mimeType?` | `string` \\| `null` | The file's media type, when known. |\n| <a id=\"property-name\"></a> `name` | `string` | Display name, typically the original file name. |\n| <a id=\"property-size\"></a> `size?` | `number` \\| `null` | Size in bytes, when known. |\n| <a id=\"property-uri\"></a> `uri` | `string` | Where the agent can fetch the file. |",
"PullRequestLinkSource": "# Type Alias: PullRequestLinkSource\n\n> **PullRequestLinkSource** = `\"agent\"` \\| `\"user\"`\n\nWho associated a pull request with a session.",
"QueuedActionDto": "# Type Alias: QueuedActionDto\n\n> **QueuedActionDto** = \\{ `actionId`: `AgentActionId`; `actorUserId?`: `string` \\| `null`; `attachments?`: `PromptAttachment`[]; `createdAt`: `string`; `kind`: `string`; `prompt?`: `string` \\| `null`; \\}\n\nOne action waiting in a session's queue.\n\nClients deserialize this, so both derives are used.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-actionid\"></a> `actionId` | `AgentActionId` | The id the action was accepted under. |\n| <a id=\"property-actoruserid\"></a> `actorUserId?` | `string` \\| `null` | The user who queued it, absent when a bot acted on nobody's behalf. |\n| <a id=\"property-attachments\"></a> `attachments?` | `PromptAttachment`[] | Files the prompt refers to, for prompts only. Kept through an edit, which replaces the text alone. |\n| <a id=\"property-createdat\"></a> `createdAt` | `string` | When it was accepted. |\n| <a id=\"property-kind\"></a> `kind` | `string` | What kind of action waits - `prompt` or `compact`; only turn-occupying actions are ever queued. |\n| <a id=\"property-prompt\"></a> `prompt?` | `string` \\| `null` | The prompt's raw text, present for prompts only. What an edit replaces. |",
"RecordedCallStatus": "# Type Alias: RecordedCallStatus\n\n> **RecordedCallStatus** = `\"running\"` \\| `\"completed\"` \\| `\"failed\"` \\| `\"unknown\"`\n\nA dispatch result; unfinished work is never reported as success.",
"RecordedToolCall": "# Type Alias: RecordedToolCall\n\n> **RecordedToolCall** = \\{ `error?`: `string` \\| `null`; `id`: `string`; `input`: `unknown`; `name`: `string`; `output?`: `unknown`; `outputOmitted`: `boolean`; `status`: `RecordedCallStatus`; \\}\n\nA real inner call, recorded by trusted dispatch for the existing renderers.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-error\"></a> `error?` | `string` \\| `null` | Safe tool failure, if one was returned. |\n| <a id=\"property-id\"></a> `id` | `string` | Stable, execution-scoped component identity. |\n| <a id=\"property-input\"></a> `input` | `unknown` | Arguments passed to the actual tool. |\n| <a id=\"property-name\"></a> `name` | `string` | Canonical Macro tool name from the allowlisted registry. |\n| <a id=\"property-output\"></a> `output?` | `unknown` | Original tool output, retained independently of the program's return value. |\n| <a id=\"property-outputomitted\"></a> `outputOmitted` | `boolean` | Whether the response was omitted to keep the durable journal bounded. |\n| <a id=\"property-status\"></a> `status` | `RecordedCallStatus` | A started call that never replied has an unknown side-effect outcome. |",
- "ReviewDecisionContext": "# Type Alias: ReviewDecisionContext\n\n> **ReviewDecisionContext** = \\{ `by`: `string`; `items`: `string`[]; `revision`: `number`; `via`: `DecisionVia`; \\}\n\nFacts about the most recent account-holder decision.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-by\"></a> `by` | `string` | Authenticated account holder. |\n| <a id=\"property-items\"></a> `items` | `string`[] | Items selected by this decision. |\n| <a id=\"property-revision\"></a> `revision` | `number` | Revision claimed by this batch, used in notification deduplication. |\n| <a id=\"property-via\"></a> `via` | `DecisionVia` | Entry surface. |",
- "ReviewId": "# Type Alias: ReviewId\n\n> **ReviewId** = `string`\n\nPersisted review identity.",
- "agent-harness.ReviewItem": "# Type Alias: ReviewItem\n\n> **ReviewItem** = \\{ `draft`: `unknown`; `edited?`: `boolean`; `error?`: `string` \\| `null`; `id`: `string`; `result?`: `unknown`; `status`: `ReviewItemStatus`; \\}\n\nOne editable item and its durable outcome.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-draft\"></a> `draft` | `unknown` | Validated arguments for the existing composer/action. |\n| <a id=\"property-edited\"></a> `edited?` | `boolean` | Whether the account holder edited this draft before deciding. |\n| <a id=\"property-error\"></a> `error?` | `string` \\| `null` | Failure or uncertainty description. |\n| <a id=\"property-id\"></a> `id` | `string` | Stable item identity across stack navigation and edits. |\n| <a id=\"property-result\"></a> `result?` | `unknown` | Actual backend response, never a model assertion. |\n| <a id=\"property-status\"></a> `status` | `ReviewItemStatus` | Current outcome. |",
- "ReviewItemStatus": "# Type Alias: ReviewItemStatus\n\n> **ReviewItemStatus** = `\"pending\"` \\| `\"submitting\"` \\| `\"completed\"` \\| `\"dismissed\"` \\| `\"unknown\"`\n\nReview item state, shared with notification consumers.",
- "ReviewKind": "# Type Alias: ReviewKind\n\n> **ReviewKind** = `\"email\"` \\| `\"calendar\"` \\| `\"import\"`\n\nThe component and action used to finish a review.",
- "ReviewRecord": "# Type Alias: ReviewRecord\n\n> **ReviewRecord** = \\{ `actingUser?`: `string` \\| `null`; `decision?`: `null` \\| `ReviewDecisionContext`; `executionId?`: `null` \\| `ExecutionId`; `id`: `ReviewId`; `items`: `agent-harness.ReviewItem`[]; `kind`: `ReviewKind`; `presentedAt?`: `number` \\| `null`; `revision`: `number`; `sessionId`: `string`; `title`: `string`; `updatedAt`: `number`; \\}\n\nFull UI record, fetched outside the model context.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-actinguser\"></a> `actingUser?` | `string` \\| `null` | Account whose email/calendar the drafts use; historical records use the session owner. |\n| <a id=\"property-decision\"></a> `decision?` | `null` \\| `ReviewDecisionContext` | - |\n| <a id=\"property-executionid\"></a> `executionId?` | `null` \\| `ExecutionId` | - |\n| <a id=\"property-id\"></a> `id` | `ReviewId` | Review identity. |\n| <a id=\"property-items\"></a> `items` | `agent-harness.ReviewItem`[] | Drafts and per-item outcomes. |\n| <a id=\"property-kind\"></a> `kind` | `ReviewKind` | Component kind. |\n| <a id=\"property-presentedat\"></a> `presentedAt?` | `number` \\| `null` | Durable presentation acknowledgment, separate from user decisions. |\n| <a id=\"property-revision\"></a> `revision` | `number` | Compare-and-swap revision for edits and submissions. |\n| <a id=\"property-sessionid\"></a> `sessionId` | `string` | Owning session. |\n| <a id=\"property-title\"></a> `title` | `string` | Stack label. |\n| <a id=\"property-updatedat\"></a> `updatedAt` | `number` | Milliseconds since epoch of the last state change. |",
"SandboxSize": "# Type Alias: SandboxSize\n\n> **SandboxSize** = `\"small\"` \\| `\"default\"` \\| `\"large\"`\n\nNamed compute tier for a managed sandbox.\n\nThe API and database store the name. CPU, RAM, and disk live in\n`crates/agent_harness/sandbox_sizes.json`.",
"SessionBot": "# Type Alias: SessionBot\n\n> **SessionBot** = \\{ `avatarUrl?`: `string` \\| `null`; `handle`: `string`; `id`: `agent-harness.BotId`; `name`: `string`; \\}\n\nThe agent behind a session, as much of it as rendering a message needs.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-avatarurl\"></a> `avatarUrl?` | `string` \\| `null` | Avatar, when it has one. |\n| <a id=\"property-handle\"></a> `handle` | `string` | Stable `@` handle, without a leading `@`. |\n| <a id=\"property-id\"></a> `id` | `agent-harness.BotId` | The bot's id. A message it sent has `\"bot\\|{id}\"` as its sender. |\n| <a id=\"property-name\"></a> `name` | `string` | Display name. |",
"SessionStatusDto": "# Type Alias: SessionStatusDto\n\n> **SessionStatusDto** = \\{ `kind`: `\"no_messages\"`; \\} \\| \\{ `event`: `string`; `kind`: `\"event\"`; \\} \\| \\{ `kind`: `\"disconnected\"`; \\}\n\nTransport representation of a session's status, mirroring\n[`SessionStatus`].\n\n## Union Members\n\n### Type Literal\n\n\\{ `kind`: `\"no_messages\"`; \\}\n\n***\n\n### Type Literal\n\n\\{ `event`: `string`; `kind`: `\"event\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `event` | `string` | The wire name of the system event, e.g. `acp_ready`. |\n| `kind` | `\"event\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `kind`: `\"disconnected\"`; \\}",
@@ -223,6 +216,45 @@
"ToolActor": "# Type Alias: ToolActor\n\n> **ToolActor** = `\"requester\"` \\| `\"owner\"`\n\nWhich authenticated participant's access a tool call requests.",
"ToolApprovalAnswerDto": "# Type Alias: ToolApprovalAnswerDto\n\n> **ToolApprovalAnswerDto** = `\"approve\"` \\| `\"approve_and_remember\"` \\| `\"deny\"` \\| `\"cancel\"`\n\nHow a person answers a held tool call.",
"ToolApprovalStatusDto": "# Type Alias: ToolApprovalStatusDto\n\n> **ToolApprovalStatusDto** = `\"pending\"` \\| `\"approved\"` \\| `\"denied\"` \\| `\"cancelled\"` \\| `\"expired\"`\n\nWhere a held tool call stands once answered.",
+ "AttendeeInput": "# Type Alias: AttendeeInput\n\n> **AttendeeInput** = \\{ `email`: `EmailAddress`; `isOptional?`: `boolean`; \\}\n\nAn attendee supplied to a calendar tool.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-email\"></a> `email` | `EmailAddress` | Attendee email address. |\n| <a id=\"property-isoptional\"></a> `isOptional?` | `boolean` | Whether attendance is optional. |",
+ "AutoDeclineModeInput": "# Type Alias: AutoDeclineModeInput\n\n> **AutoDeclineModeInput** = `\"decline_none\"` \\| `\"decline_all\"` \\| `\"decline_new_only\"`\n\nHow an out-of-office event handles conflicting invitations.",
+ "CalendarEventTypeInput": "# Type Alias: CalendarEventTypeInput\n\n> **CalendarEventTypeInput** = `\"default\"` \\| `\"out_of_office\"`\n\nThe kind of event a create tool call makes.",
+ "CreateCalendarEvent_Deserialize": "# Type Alias: CreateCalendarEvent\\_Deserialize\n\n> **CreateCalendarEvent\\_Deserialize** = \\{ `addMacroCall?`: `boolean`; `attendees?`: `AttendeeInput`[]; `calendarId?`: `string` \\| `null`; `description?`: `string` \\| `null`; `eventType?`: `CalendarEventTypeInput`; `guestPolicy?`: `agent-reviews.GuestPolicy` \\| `null`; `location?`: `string` \\| `null`; `outOfOffice?`: `OutOfOfficeInput` \\| `null`; `recurrenceLines?`: `string`[]; `reminders?`: `EventRemindersInput` \\| `null`; `time`: `EventTimeInput`; `title`: `string`; \\} & \\{ `addConference?`: `boolean`; \\} \\| \\{ `addGoogleMeet?`: `boolean`; \\}\n\nCreate a calendar event.\n\n## Union Members\n\n\\{ `addMacroCall?`: `boolean`; `attendees?`: `AttendeeInput`[]; `calendarId?`: `string` \\| `null`; `description?`: `string` \\| `null`; `eventType?`: `CalendarEventTypeInput`; `guestPolicy?`: `agent-reviews.GuestPolicy` \\| `null`; `location?`: `string` \\| `null`; `outOfOffice?`: `OutOfOfficeInput` \\| `null`; `recurrenceLines?`: `string`[]; `reminders?`: `EventRemindersInput` \\| `null`; `time`: `EventTimeInput`; `title`: `string`; \\} & \\{ `addConference?`: `boolean`; \\}\n\n***\n\n### Type Literal\n\n\\{ `addGoogleMeet?`: `boolean`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `addGoogleMeet?` | `boolean` | Whether to attach the calendar provider's meeting conference. |",
+ "CreateCalendarEvent_Serialize": "# Type Alias: CreateCalendarEvent\\_Serialize\n\n> **CreateCalendarEvent\\_Serialize** = \\{ `addConference`: `boolean`; `addMacroCall`: `boolean`; `attendees`: `AttendeeInput`[]; `calendarId`: `string` \\| `null`; `description`: `string` \\| `null`; `eventType`: `CalendarEventTypeInput`; `guestPolicy`: `agent-reviews.GuestPolicy` \\| `null`; `location`: `string` \\| `null`; `outOfOffice`: `OutOfOfficeInput` \\| `null`; `recurrenceLines`: `string`[]; `reminders`: `EventRemindersInput` \\| `null`; `time`: `EventTimeInput`; `title`: `string`; \\}\n\nCreate a calendar event.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-addconference\"></a> `addConference` | `boolean` | Whether to attach the calendar provider's meeting conference. |\n| <a id=\"property-addmacrocall\"></a> `addMacroCall` | `boolean` | Whether to attach a Macro meeting link. |\n| <a id=\"property-attendees\"></a> `attendees` | `AttendeeInput`[] | Attendees to invite. |\n| <a id=\"property-calendarid\"></a> `calendarId` | `string` \\| `null` | Calendar to create the event on. |\n| <a id=\"property-description\"></a> `description` | `string` \\| `null` | Optional event body. |\n| <a id=\"property-eventtype\"></a> `eventType` | `CalendarEventTypeInput` | Kind of event to create. |\n| <a id=\"property-guestpolicy\"></a> `guestPolicy` | `agent-reviews.GuestPolicy` \\| `null` | What guests may do with the event. |\n| <a id=\"property-location\"></a> `location` | `string` \\| `null` | Optional location label. |\n| <a id=\"property-outofoffice\"></a> `outOfOffice` | `OutOfOfficeInput` \\| `null` | Out-of-office decline behavior. |\n| <a id=\"property-recurrencelines\"></a> `recurrenceLines` | `string`[] | Recurrence properties. |\n| <a id=\"property-reminders\"></a> `reminders` | `EventRemindersInput` \\| `null` | Reminder configuration. |\n| <a id=\"property-time\"></a> `time` | `EventTimeInput` | Timed or all-day span. |\n| <a id=\"property-title\"></a> `title` | `string` | Display title. |",
+ "DecisionVia": "# Type Alias: DecisionVia\n\n> **DecisionVia** = `\"card\"` \\| `\"chat\"` \\| `\"inbox\"`\n\nSurface of a review decision.",
+ "DraftList": "# Type Alias: DraftList\\<Draft\\>\n\n> **DraftList**\\<`Draft`\\> = `Draft`[]\n\nOne to [`MAX_DRAFTS`] drafts of one kind.\n\n## Type Parameters\n\n| Type Parameter |\n| ------ |\n| <a id=\"type-parameter-draft\"></a> `Draft` |",
+ "EmailAddress": "# Type Alias: EmailAddress\n\n> **EmailAddress** = `string`\n\nAn address that passes [`is_valid_email`]; decoding rejects any other string.",
+ "agent-reviews.EmailAttachment": "# Type Alias: EmailAttachment\n\n> **EmailAttachment** = \\{ `documentId`: `string`; \\}\n\nA Macro document attached to an outgoing email as a file.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-documentid\"></a> `documentId` | `string` | The id of the Macro document to attach. It must be a stored file - an uploaded PDF, image, spreadsheet, Word document, or other upload - that the user can view. A Macro-native document (one written in the editor) has no file to attach; link to it in the body instead. |",
+ "EmailRecipient": "# Type Alias: EmailRecipient\n\n> **EmailRecipient** = \\{ `email`: `EmailAddress`; `name?`: `string` \\| `null`; \\}\n\nA recipient for an email.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-email\"></a> `email` | `EmailAddress` | The recipient's email address. |\n| <a id=\"property-name\"></a> `name?` | `string` \\| `null` | The recipient's display name (optional). |",
+ "EventReminderOverrideInput": "# Type Alias: EventReminderOverrideInput\n\n> **EventReminderOverrideInput** = \\{ `method`: `string`; `minutes`: `number`; \\}\n\nOne reminder override supplied to a calendar tool.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-method\"></a> `method` | `string` | Provider reminder method. `popup` creates a Macro notification. |\n| <a id=\"property-minutes\"></a> `minutes` | `number` | Minutes before the event start. |",
+ "EventRemindersInput": "# Type Alias: EventRemindersInput\n\n> **EventRemindersInput** = \\{ `overrides?`: `EventReminderOverrideInput`[]; `useDefault`: `boolean`; \\}\n\nReminder configuration supplied when creating a calendar event.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-overrides\"></a> `overrides?` | `EventReminderOverrideInput`[] | Overrides used when calendar defaults are disabled. |\n| <a id=\"property-usedefault\"></a> `useDefault` | `boolean` | Whether the selected calendar's default reminders should apply. |",
+ "EventTimeInput": "# Type Alias: EventTimeInput\n\n> **EventTimeInput** = \\{ `endsAt`: `string`; `kind`: `\"timed\"`; `startsAt`: `string`; `timeZone?`: `string` \\| `null`; \\} \\| \\{ `endDate`: `string`; `kind`: `\"allDay\"`; `startDate`: `string`; \\}\n\nThe mutually exclusive time shape supplied to calendar tools.\n\n## Union Members\n\n### Type Literal\n\n\\{ `endsAt`: `string`; `kind`: `\"timed\"`; `startsAt`: `string`; `timeZone?`: `string` \\| `null`; \\}\n\nA clock-time event with absolute instants.\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `endsAt` | `string` | Exclusive end instant, RFC 3339 UTC. Must be after the start. |\n| `kind` | `\"timed\"` | - |\n| `startsAt` | `string` | Inclusive start instant, RFC 3339 UTC (e.g. 2026-08-20T17:00:00Z). |\n| `timeZone?` | `string` \\| `null` | IANA time zone the event was scheduled in (e.g. America/New_York). Recurring events expand in this zone. |\n\n***\n\n### Type Literal\n\n\\{ `endDate`: `string`; `kind`: `\"allDay\"`; `startDate`: `string`; \\}\n\nAn all-day event spanning whole local dates.\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `endDate` | `string` | Exclusive local end date (YYYY-MM-DD); the day after the last covered day, so a one-day event ends the next date. |\n| `kind` | `\"allDay\"` | - |\n| `startDate` | `string` | Inclusive local start date (YYYY-MM-DD). |",
+ "agent-reviews.ExecutionId": "# Type Alias: ExecutionId\n\n> **ExecutionId** = `string`\n\nCaller-selected UUID persisted in tool input before execution begins.",
+ "agent-reviews.GuestPolicy": "# Type Alias: GuestPolicy\n\n> **GuestPolicy** = \\{ `canInviteOthers`: `boolean`; `canModify`: `boolean`; `canSeeOtherGuests`: `boolean`; \\}\n\nThe switches an organizer sets on an event to bound what its guests may\n do. Google omits a switch from the payload while it holds its default.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-caninviteothers\"></a> `canInviteOthers` | `boolean` | Whether guests may invite others. |\n| <a id=\"property-canmodify\"></a> `canModify` | `boolean` | Whether guests may change the event, including its guest list. |\n| <a id=\"property-canseeotherguests\"></a> `canSeeOtherGuests` | `boolean` | Whether guests may see the guest list. |",
+ "ImportDraft": "# Type Alias: ImportDraft\n\n> **ImportDraft** = \\{ `excluded?`: `string`[]; `personal?`: `string`[]; `shared?`: `string`[]; `source`: `ImportReviewSource`; \\}\n\nThe one draft an import review carries: which source's staged plan it\n presents, the plan rows the user took out of it, and the rows whose\n sharing they changed: `shared` to share with their team, `personal` to\n keep to themselves.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-excluded\"></a> `excluded?` | `string`[] | Plan rows left out of the import. |\n| <a id=\"property-personal\"></a> `personal?` | `string`[] | Plan rows kept private although the plan shares them. |\n| <a id=\"property-shared\"></a> `shared?` | `string`[] | Plan rows shared with the team although the plan keeps them private. |\n| <a id=\"property-source\"></a> `source` | `ImportReviewSource` | The staged plan's source; fixed once the review is presented. |",
+ "ImportKind": "# Type Alias: ImportKind\n\n> **ImportKind** = `\"issue\"` \\| `\"project\"` \\| `\"document\"` \\| `\"page\"` \\| `\"database\"` \\| `\"data_source\"` \\| `\"row\"` \\| `\"jira_issue\"` \\| `\"jira_project\"` \\| `\"jira_epic\"` \\| `\"channel\"`\n\nWhat an imported item is in its source system. Each source has its own\n kinds; a Notion database and a Notion page, or a Linear project and a\n Linear issue, are tracked and deduplicated separately.",
+ "ImportReviewSource": "# Type Alias: ImportReviewSource\n\n> **ImportReviewSource** = `\"notion\"` \\| `\"linear\"` \\| `\"jira\"`\n\nWhich source's staged plan an import review presents.",
+ "ItemStatus": "# Type Alias: ItemStatus\n\n> **ItemStatus** = `\"pending\"` \\| `\"submitting\"` \\| `\"completed\"` \\| `\"dismissed\"` \\| `\"unknown\"`\n\nReview item state, shared with notification consumers.",
+ "NotionImportReport_Serialize": "# Type Alias: NotionImportReport\\_Serialize\n\n> **NotionImportReport\\_Serialize** = \\{ `alreadyImportedBy`: `NotionImporter`[]; `alreadyInMacro`: `number`; `copy`: `number`; `databaseRows`: `number`; `databases`: `number`; `dataSources`: `number`; `deciding`: `number`; `documents`: `number`; `error?`: `string` \\| `null`; `failures`: `NotionReportItem_Serialize`[]; `hand`: `number`; `handItems`: `NotionReportItem_Serialize`[]; `imported`: `number`; `issues`: `number`; `onTeam`: `boolean`; `pages`: `number`; `projects`: `number`; `reviewId?`: `string` \\| `null`; `scanned?`: `ScanCounts` \\| `null`; `sharedWithTeam`: `number`; `skip`: `number`; `status?`: `RunStatus` \\| `null`; `taskRows`: `number`; `tasks`: `number`; `waiting`: `number`; `waitingOnTeammates`: `number`; `warnings?`: `string`[]; `writing`: `number`; \\}\n\nWhere a Notion workspace import stands.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-alreadyimportedby\"></a> `alreadyImportedBy` | `NotionImporter`[] | Who imported the objects already in Macro, most first. |\n| <a id=\"property-alreadyinmacro\"></a> `alreadyInMacro` | `number` | Plan objects a teammate already imported and shared with the team; they link to that copy and are not counted as copies. |\n| <a id=\"property-copy\"></a> `copy` | `number` | Objects to copy as they are. |\n| <a id=\"property-databaserows\"></a> `databaseRows` | `number` | Rows those databases hold, every one counted while planning. |\n| <a id=\"property-databases\"></a> `databases` | `number` | Data sources written as databases. |\n| <a id=\"property-datasources\"></a> `dataSources` | `number` | Data sources (database tables) in the plan. |\n| <a id=\"property-deciding\"></a> `deciding` | `number` | Plan objects the decision model has not answered for yet, while planning is still `running`. |\n| <a id=\"property-documents\"></a> `documents` | `number` | Pages written as documents. |\n| <a id=\"property-error\"></a> `error?` | `string` \\| `null` | Why the run failed, when it did. |\n| <a id=\"property-failures\"></a> `failures` | `NotionReportItem_Serialize`[] | Objects that failed to import, with the failure. |\n| <a id=\"property-hand\"></a> `hand` | `number` | Objects that need handling by hand. |\n| <a id=\"property-handitems\"></a> `handItems` | `NotionReportItem_Serialize`[] | Objects that need handling by hand, with reasons. |\n| <a id=\"property-imported\"></a> `imported` | `number` | Plan objects already imported. |\n| <a id=\"property-issues\"></a> `issues` | `number` | Tracker issues in the plan. |\n| <a id=\"property-onteam\"></a> `onTeam` | `boolean` | Whether the user is on a team. Without one, everything the import writes stays visible only to them. |\n| <a id=\"property-pages\"></a> `pages` | `number` | Pages in the plan. |\n| <a id=\"property-projects\"></a> `projects` | `number` | Tracker groups written as Macro projects. |\n| <a id=\"property-reviewid\"></a> `reviewId?` | `string` \\| `null` | The review the plan is tied to, once presented. |\n| <a id=\"property-scanned\"></a> `scanned?` | `ScanCounts` \\| `null` | What planning has found in Notion so far, while it is `running`. |\n| <a id=\"property-sharedwithteam\"></a> `sharedWithTeam` | `number` | Written plan objects shared with the user's team. |\n| <a id=\"property-skip\"></a> `skip` | `number` | Objects left in Notion. |\n| <a id=\"property-status\"></a> `status?` | `RunStatus` \\| `null` | The run's state: `running` while planning, `ready` once a plan is staged, `importing` while writing, `completed`, `failed`, or `dismissed` when cancelled. Absent before the first run. |\n| <a id=\"property-taskrows\"></a> `taskRows` | `number` | Tasks the task lists become, one per row. |\n| <a id=\"property-tasks\"></a> `tasks` | `number` | Data sources whose rows become tasks. |\n| <a id=\"property-waiting\"></a> `waiting` | `number` | Plan objects still waiting to be written. |\n| <a id=\"property-waitingonteammates\"></a> `waitingOnTeammates` | `number` | Plan objects waiting for a teammate who is writing the same object for the team; they link to the teammate's copy once it is written. |\n| <a id=\"property-warnings\"></a> `warnings?` | `string`[] | Provider items skipped because they were unreadable, or optional features unavailable. |\n| <a id=\"property-writing\"></a> `writing` | `number` | Plan objects being written now. |",
+ "NotionImporter": "# Type Alias: NotionImporter\n\n> **NotionImporter** = \\{ `by`: `string`; `count`: `number`; \\}\n\nA teammate who already imported some of a plan's objects.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-by\"></a> `by` | `string` | The teammate, by email. |\n| <a id=\"property-count\"></a> `count` | `number` | How many of the plan's objects they imported. |",
+ "NotionReportItem_Serialize": "# Type Alias: NotionReportItem\\_Serialize\n\n> **NotionReportItem\\_Serialize** = \\{ `importId`: `string`; `kind`: `ImportKind`; `reason?`: `string` \\| `null`; `title`: `string`; `url?`: `string` \\| `null`; \\}\n\nOne object a workspace import report calls out.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-importid\"></a> `importId` | `string` | The ledger row. |\n| <a id=\"property-kind\"></a> `kind` | `ImportKind` | What the object is. |\n| <a id=\"property-reason\"></a> `reason?` | `string` \\| `null` | Why it is called out: the decision model's reason, or the failure. |\n| <a id=\"property-title\"></a> `title` | `string` | The object's title. |\n| <a id=\"property-url\"></a> `url?` | `string` \\| `null` | Its Notion URL. |",
+ "OutOfOfficeInput": "# Type Alias: OutOfOfficeInput\n\n> **OutOfOfficeInput** = \\{ `autoDeclineMode?`: `AutoDeclineModeInput` \\| `null`; `declineMessage?`: `string` \\| `null`; \\}\n\nOut-of-office decline behavior supplied to the calendar tools.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-autodeclinemode\"></a> `autoDeclineMode?` | `AutoDeclineModeInput` \\| `null` | How conflicting invitations are handled. Defaults to declining nothing, so the event only blocks time and shows the away status. |\n| <a id=\"property-declinemessage\"></a> `declineMessage?` | `string` \\| `null` | Message returned to organizers whose invitations are auto-declined. |",
+ "ReviewDecisionContext": "# Type Alias: ReviewDecisionContext\n\n> **ReviewDecisionContext** = \\{ `by`: `string`; `items`: `string`[]; `revision`: `number`; `via`: `DecisionVia`; \\}\n\nFacts about the most recent account-holder decision.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-by\"></a> `by` | `string` | Authenticated account holder. |\n| <a id=\"property-items\"></a> `items` | `string`[] | Items selected by this decision. |\n| <a id=\"property-revision\"></a> `revision` | `number` | Revision claimed by this batch, used in notification deduplication. |\n| <a id=\"property-via\"></a> `via` | `DecisionVia` | Entry surface. |",
+ "ReviewDraft_Deserialize": "# Type Alias: ReviewDraft\\_Deserialize\n\n> **ReviewDraft\\_Deserialize** = \\{ `draft`: `SendEmail`; `kind`: `\"email\"`; \\} \\| \\{ `draft`: `CreateCalendarEvent_Deserialize`; `kind`: `\"calendar\"`; \\} \\| \\{ `draft`: `ImportDraft`; `kind`: `\"import\"`; \\}\n\nOne replacement draft, keyed by the kind of the review it edits.\n\n## Union Members\n\n### Type Literal\n\n\\{ `draft`: `SendEmail`; `kind`: `\"email\"`; \\}\n\nAn edited email.\n\n***\n\n### Type Literal\n\n\\{ `draft`: `CreateCalendarEvent_Deserialize`; `kind`: `\"calendar\"`; \\}\n\nAn edited calendar event.\n\n***\n\n### Type Literal\n\n\\{ `draft`: `ImportDraft`; `kind`: `\"import\"`; \\}\n\nAn edited import plan selection.",
+ "ReviewDrafts_Deserialize": "# Type Alias: ReviewDrafts\\_Deserialize\n\n> **ReviewDrafts\\_Deserialize** = \\{ `drafts`: `DraftList`\\<`SendEmail`\\>; `kind`: `\"email\"`; \\} \\| \\{ `drafts`: `DraftList`\\<`CreateCalendarEvent_Deserialize`\\>; `kind`: `\"calendar\"`; \\} \\| \\{ `drafts`: \\`ImportDraft`\\]; `kind`: `\"import\"`; \\}\n\nThe drafts a new review presents, keyed by the review's kind.\n\n## Union Members\n\n### Type Literal\n\n\\{ `drafts`: `DraftList`\\<`SendEmail`\\>; `kind`: `\"email\"`; \\}\n\nEmails, each sent with the SendEmail action (Markdown body).\n\n***\n\n### Type Literal\n\n\\{ `drafts`: `DraftList`\\<`CreateCalendarEvent_Deserialize`\\>; `kind`: `\"calendar\"`; \\}\n\nCalendar events, each created with the CreateCalendarEvent action.\n\n***\n\n### Type Literal\n\n\\{ `drafts`: \\`ImportDraft`\\]; `kind`: `\"import\"`; \\}\n\nExactly one staged import plan, approved as one item.",
+ "ReviewId": "# Type Alias: ReviewId\n\n> **ReviewId** = `string`\n\nPersisted review identity.",
+ "agent-reviews.ReviewItem": "# Type Alias: ReviewItem\\<Draft, Outcome\\>\n\n> **ReviewItem**\\<`Draft`, `Outcome`\\> = \\{ `draft`: `Draft`; `result`: `Outcome` \\| `null`; \\} & `ReviewItemState`\n\nOne editable item and its durable outcome.\n\n## Type Parameters\n\n| Type Parameter |\n| ------ |\n| <a id=\"type-parameter-draft\"></a> `Draft` |\n| <a id=\"type-parameter-outcome\"></a> `Outcome` |\n\n## Type Declaration\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `draft` | `Draft` | Arguments for the existing composer and action. |\n| `result` | `Outcome` \\| `null` | The action's confirmed response, never a model assertion. |",
+ "ReviewItemState": "# Type Alias: ReviewItemState\n\n> **ReviewItemState** = \\{ `edited?`: `boolean`; `error`: `string` \\| `null`; `id`: `string`; `status`: `ItemStatus`; \\}\n\nItem facts every kind shares.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-edited\"></a> `edited?` | `boolean` | Whether the account holder edited this draft before deciding. |\n| <a id=\"property-error\"></a> `error` | `string` \\| `null` | Failure or uncertainty description. |\n| <a id=\"property-id\"></a> `id` | `string` | Stable item identity across stack navigation and edits. |\n| <a id=\"property-status\"></a> `status` | `ItemStatus` | Current outcome. |",
+ "ReviewItems_Serialize": "# Type Alias: ReviewItems\\_Serialize\n\n> **ReviewItems\\_Serialize** = \\{ `items`: `agent-reviews.ReviewItem`\\<`SendEmail`, `SendEmailResponse`\\>[]; `kind`: `\"email\"`; \\} \\| \\{ `items`: `agent-reviews.ReviewItem`\\<`CreateCalendarEvent_Serialize`, `ToolCalendarEvent`\\>[]; `kind`: `\"calendar\"`; \\} \\| \\{ `items`: \\`agent-reviews.ReviewItem`\\<`ImportDraft`, `NotionImportReport_Serialize`\\>\\]; `kind`: `\"import\"`; \\}\n\nSaved items keyed by the review's kind.\n\n## Union Members\n\n### Type Literal\n\n\\{ `items`: `agent-reviews.ReviewItem`\\<`SendEmail`, `SendEmailResponse`\\>[]; `kind`: `\"email\"`; \\}\n\nEmail drafts and their send responses.\n\n***\n\n### Type Literal\n\n\\{ `items`: `agent-reviews.ReviewItem`\\<`CreateCalendarEvent_Serialize`, `ToolCalendarEvent`\\>[]; `kind`: `\"calendar\"`; \\}\n\nCalendar drafts and their created events.\n\n***\n\n### Type Literal\n\n\\{ `items`: \\`agent-reviews.ReviewItem`\\<`ImportDraft`, `NotionImportReport_Serialize`\\>\\]; `kind`: `\"import\"`; \\}\n\nThe import plan selection and the started write's report.",
+ "ReviewRecord_Serialize": "# Type Alias: ReviewRecord\\_Serialize\n\n> **ReviewRecord\\_Serialize** = \\{ `actingUser`: `string`; `decision`: `ReviewDecisionContext` \\| `null`; `executionId`: `agent-reviews.ExecutionId` \\| `null`; `id`: `ReviewId`; `presentedAt`: `number` \\| `null`; `revision`: `number`; `sessionId`: `string`; `title`: `ReviewTitle`; `updatedAt`: `number`; \\} & `ReviewItems_Serialize`\n\nFull UI record, fetched outside the model context.\n\n## Type Declaration\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `actingUser` | `string` | Account whose email/calendar the drafts use. |\n| `decision` | `ReviewDecisionContext` \\| `null` | Current batch's authenticated decision, preserved for interrupted work. |\n| `executionId` | `agent-reviews.ExecutionId` \\| `null` | Originating code execution, absent for directly presented reviews. |\n| `id` | `ReviewId` | Review identity. |\n| `presentedAt` | `number` \\| `null` | Durable presentation acknowledgment, separate from user decisions. |\n| `revision` | `number` | Compare-and-swap revision for edits and submissions. |\n| `sessionId` | `string` | Owning session. |\n| `title` | `ReviewTitle` | Stack label. |\n| `updatedAt` | `number` | Milliseconds since epoch of the last state change. |",
+ "ReviewTitle": "# Type Alias: ReviewTitle\n\n> **ReviewTitle** = `string`\n\nA review stack label: not blank, at most 256 characters.",
+ "RunStatus": "# Type Alias: RunStatus\n\n> **RunStatus** = `\"running\"` \\| `\"ready\"` \\| `\"importing\"` \\| `\"completed\"` \\| `\"failed\"` \\| `\"dismissed\"`\n\nLifecycle of a discovery run (one per user × source).",
+ "ScanCounts": "# Type Alias: ScanCounts\n\n> **ScanCounts** = \\{ `dataSources`: `number`; `pages`: `number`; \\}\n\nWhat a planning run has found in the source so far.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-datasources\"></a> `dataSources` | `number` | Data sources (database tables) found. |\n| <a id=\"property-pages\"></a> `pages` | `number` | Pages found. |",
+ "SendEmail": "# Type Alias: SendEmail\n\n> **SendEmail** = \\{ `attachments?`: `agent-reviews.EmailAttachment`[]; `bcc?`: `EmailRecipient`[]; `body`: `string`; `cc?`: `EmailRecipient`[]; `from?`: `string` \\| `null`; `includeSignature?`: `boolean` \\| `null`; `replyingToId?`: `string` \\| `null`; `subject`: `string`; `to`: `EmailRecipient`[]; \\}\n\nCompose and send an email. Creates a draft and immediately queues it for delivery.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-attachments\"></a> `attachments?` | `agent-reviews.EmailAttachment`[] | Macro documents to attach as files (optional). Each must be an uploaded file the user can view; together they may total 18 MB. |\n| <a id=\"property-bcc\"></a> `bcc?` | `EmailRecipient`[] | Blind carbon copy recipients (optional). |\n| <a id=\"property-body\"></a> `body` | `string` | The body of the email, written as Markdown. A host with a composer (chat) replaces this with the base64url-encoded HTML the composer exported before the tool runs; a host without one (an agent session) leaves the Markdown, and this tool renders it the same way. |\n| <a id=\"property-cc\"></a> `cc?` | `EmailRecipient`[] | Carbon copy recipients (optional). |\n| <a id=\"property-from\"></a> `from?` | `string` \\| `null` | The address of the inbox to send from, when the user has more than one connected and this email belongs to a particular one. Use the exact `emailAddress` of a connected inbox — `ListInboxes` lists them, and `GetThread` reports the `inbox` a thread belongs to. Omit it unless you know which inbox is right: a reply then goes out from the inbox that received the message it answers, and a new email from the user's primary inbox. The user can change it in the composer either way. |\n| <a id=\"property-includesignature\"></a> `includeSignature?` | `boolean` \\| `null` | Per-message signature override, set by the composer's signature preview — not normally by you. Omit to use the inbox's default policy (always on a new email; on replies/forwards only when the user enabled it). `false` excludes the signature for this one email. |\n| <a id=\"property-replyingtoid\"></a> `replyingToId?` | `string` \\| `null` | The ID of a message to reply to (optional). When set, the email is sent as a reply within the same thread. |\n| <a id=\"property-subject\"></a> `subject` | `string` | The subject line of the email. |\n| <a id=\"property-to\"></a> `to` | `EmailRecipient`[] | The primary recipients (To field). |",
+ "SendEmailResponse": "# Type Alias: SendEmailResponse\n\n> **SendEmailResponse** = \\{ `sent`: \\{ `message_id`: `string`; `thread_id`: `string`; \\}; \\} & \\{ `convertedToDraft?`: `never`; \\} \\| \\{ `convertedToDraft`: \\{ `draft_id`: `string`; \\}; \\} & \\{ `sent?`: `never`; \\} \\| `\"userEdited\"`\n\nResponse from the SendEmail tool.",
+ "ToolCalendarEvent": "# Type Alias: ToolCalendarEvent\n\n> **ToolCalendarEvent** = \\{ `attendeeCount`: `number`; `attendees`: `ToolEventAttendee`[]; `calendarId`: `string` \\| `null`; `calendarName`: `string` \\| `null`; `conferenceUrl`: `string` \\| `null`; `description`: `string` \\| `null`; `end`: `string`; `eventId`: `string`; `inbox`: `string` \\| `null`; `isAllDay`: `boolean`; `isReadOnly`: `boolean`; `isRecurring`: `boolean`; `location`: `string` \\| `null`; `macroCallUrl`: `string` \\| `null`; `myRole`: `ToolEventRole` \\| `null`; `organizerEmail`: `string` \\| `null`; `recurrenceLines`: `string`[]; `start`: `string`; `status`: `string`; `timeZone`: `string` \\| `null`; `title`: `string`; \\}\n\nA calendar event as returned by the create and update tools.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-attendeecount\"></a> `attendeeCount` | `number` | Total number of attendees. |\n| <a id=\"property-attendees\"></a> `attendees` | `ToolEventAttendee`[] | Attendees, capped at 20; `attendee_count` has the full number. |\n| <a id=\"property-calendarid\"></a> `calendarId` | `string` \\| `null` | Calendar the event belongs to, when known. |\n| <a id=\"property-calendarname\"></a> `calendarName` | `string` \\| `null` | Display name of that calendar, when known. |\n| <a id=\"property-conferenceurl\"></a> `conferenceUrl` | `string` \\| `null` | Conference join URL, when a conference is attached. |\n| <a id=\"property-description\"></a> `description` | `string` \\| `null` | Event body, truncated for brevity. |\n| <a id=\"property-end\"></a> `end` | `string` | Exclusive event end: RFC 3339 UTC instant, or YYYY-MM-DD for all-day events. |\n| <a id=\"property-eventid\"></a> `eventId` | `string` | Macro calendar event id, used by UpdateCalendarEvent and DeleteCalendarEvent. |\n| <a id=\"property-inbox\"></a> `inbox` | `string` \\| `null` | Connected inbox address syncing the calendar, when known. It stays the user's own address on a colleague's calendar, so it never says whose calendar it is. |\n| <a id=\"property-isallday\"></a> `isAllDay` | `boolean` | Whether the event covers whole days. |\n| <a id=\"property-isreadonly\"></a> `isReadOnly` | `boolean` | Whether the user's calendar prohibits modifying this event. |\n| <a id=\"property-isrecurring\"></a> `isRecurring` | `boolean` | Whether the event recurs. |\n| <a id=\"property-location\"></a> `location` | `string` \\| `null` | Location label, when set. |\n| <a id=\"property-macrocallurl\"></a> `macroCallUrl` | `string` \\| `null` | Join URL of the Macro call created with the event, when CreateCalendarEvent was asked for one. |\n| <a id=\"property-myrole\"></a> `myRole` | `ToolEventRole` \\| `null` | Whether the user organizes this event or is a guest on it, through that inbox; absent when they are neither, can only write that calendar, or a read-only calendar names them organizer. |\n| <a id=\"property-organizeremail\"></a> `organizerEmail` | `string` \\| `null` | Organizer email address, when known. |\n| <a id=\"property-recurrencelines\"></a> `recurrenceLines` | `string`[] | Raw RFC 5545 recurrence properties, when the event recurs. |\n| <a id=\"property-start\"></a> `start` | `string` | Event start: RFC 3339 UTC instant, or YYYY-MM-DD for all-day events. |\n| <a id=\"property-status\"></a> `status` | `string` | Event status: confirmed, tentative, or cancelled. |\n| <a id=\"property-timezone\"></a> `timeZone` | `string` \\| `null` | IANA time zone the event was scheduled in, when known. |\n| <a id=\"property-title\"></a> `title` | `string` | Display title. |",
+ "ToolEventAttendee": "# Type Alias: ToolEventAttendee\n\n> **ToolEventAttendee** = \\{ `email`: `string`; `isOptional`: `boolean`; `isOrganizer`: `boolean`; `responseStatus`: `string`; \\}\n\nAn attendee of a calendar event, as returned by calendar tools.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-email\"></a> `email` | `string` | Attendee email address. |\n| <a id=\"property-isoptional\"></a> `isOptional` | `boolean` | Whether attendance is optional. |\n| <a id=\"property-isorganizer\"></a> `isOrganizer` | `boolean` | Whether this attendee organized the event. |\n| <a id=\"property-responsestatus\"></a> `responseStatus` | `string` | RSVP state: needs_action, accepted, declined, or tentative. |",
+ "ToolEventRole": "# Type Alias: ToolEventRole\n\n> **ToolEventRole** = `\"organizer\"` \\| `\"guest\"`\n\nWhat the user is on one copy of an event, through the inbox holding it.",
"EmailConnectionProviders": "# Type Alias: EmailConnectionProviders\n\n> **EmailConnectionProviders** = \\{ `gmail`: `boolean`; `outlook`: `boolean`; `outlook_admin_consent_url?`: `string` \\| `null`; \\}\n\nWhat the provider selector offers the requesting user.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-gmail\"></a> `gmail` | `boolean` | - |\n| <a id=\"property-outlook\"></a> `outlook` | `boolean` | Whether this user may start a new Outlook connection: the deployment switch and their `enable-outlook` flag. |\n| <a id=\"property-outlook_admin_consent_url\"></a> `outlook_admin_consent_url?` | `string` \\| `null` | Where a Microsoft 365 administrator approves Macro for their whole directory. Present when Outlook is configured and the request named an `original_url` for the administrator's browser to return to. |",
"Language": "# Type Alias: Language\n\n> **Language** = `\"en\"` \\| `\"de\"` \\| `\"fr\"` \\| `\"es\"` \\| `\"it\"` \\| `\"nl\"` \\| `\"pt-PT\"` \\| `\"sv\"` \\| `\"da\"` \\| `\"nb\"` \\| `\"fi\"` \\| `\"pl\"` \\| `\"ru\"` \\| `\"ja\"` \\| `\"ko\"` \\| `\"zh-Hans\"` \\| `\"zh-Hant\"` \\| `\"hi\"` \\| `\"id\"` \\| `\"vi\"` \\| `\"th\"`\n\nA language the app's interface is available in, as a BCP 47 tag.",
"auth.LinkShare": "# Type Alias: LinkShare\n\n> **LinkShare** = `\"PUBLIC\"` \\| `\"TEAM\"`\n\nDefines who can access an item through its share link.",
@@ -888,26 +920,27 @@
"QueuedAction.remove": "### remove()\n\n> **remove**(): `Promise`\\<`void`\\>\n\nRemove this action from the queue before it dispatches.\n\n#### Returns\n\n`Promise`\\<`void`\\>",
"QueuedAction.steer": "### steer()\n\n> **steer**(): `Promise`\\<`void`\\>\n\nMove this action to the front and interrupt the current turn to run it next.\n\n#### Returns\n\n`Promise`\\<`void`\\>",
"QueuedAction.from": "### from()\n\n> `static` **from**(`client`, `sessionId`, `dto`): `QueuedAction`\n\nWrap a queue entry already in hand (e.g. from `AgentSession.queue()`).\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `sessionId` | `string` |\n| `dto` | `QueuedActionDto` |\n\n#### Returns\n\n`QueuedAction`",
- "ReviewItem": "# Class: ReviewItem\n\nAn item handle scopes edits and decisions to its persisted review.\n\n## Accessors\n\n### draft\n\n#### Get Signature\n\n> **get** **draft**(): `unknown`\n\n##### Returns\n\n`unknown`\n\n***\n\n### id\n\n#### Get Signature\n\n> **get** **id**(): `string`\n\n##### Returns\n\n`string`\n\n***\n\n### result\n\n#### Get Signature\n\n> **get** **result**(): `unknown`\n\n##### Returns\n\n`unknown`\n\n***\n\n### status\n\n#### Get Signature\n\n> **get** **status**(): `ReviewItemStatus`\n\n##### Returns\n\n`ReviewItemStatus`",
+ "ReviewItem": "# Class: ReviewItem\n\nAn item handle scopes edits and decisions to its persisted review.\n\n## Accessors\n\n### draft\n\n#### Get Signature\n\n> **get** **draft**(): `CreateCalendarEvent_Serialize` \\| `ImportDraft` \\| `SendEmail`\n\n##### Returns\n\n`CreateCalendarEvent_Serialize` \\| `ImportDraft` \\| `SendEmail`\n\n***\n\n### id\n\n#### Get Signature\n\n> **get** **id**(): `string`\n\n##### Returns\n\n`string`\n\n***\n\n### result\n\n#### Get Signature\n\n> **get** **result**(): `NotionImportReport_Serialize` \\| `SendEmailResponse` \\| `ToolCalendarEvent` \\| `null`\n\nThe action's confirmed response, `null` until it completes.\n\n##### Returns\n\n`NotionImportReport_Serialize` \\| `SendEmailResponse` \\| `ToolCalendarEvent` \\| `null`\n\n***\n\n### status\n\n#### Get Signature\n\n> **get** **status**(): `ItemStatus`\n\n##### Returns\n\n`ItemStatus`",
"ReviewItem.dismiss": "### dismiss()\n\n> **dismiss**(): `Promise`\\<`void`\\>\n\n#### Returns\n\n`Promise`\\<`void`\\>",
- "ReviewItem.edit": "### edit()\n\n> **edit**(`draft`): `Promise`\\<`void`\\>\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `draft` | `unknown` |\n\n#### Returns\n\n`Promise`\\<`void`\\>",
+ "ReviewItem.edit": "### edit()\n\n> **edit**(`draft`): `Promise`\\<`void`\\>\n\nReplace this pending draft; `kind` must match the review's.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `draft` | `ReviewDraft_Deserialize` |\n\n#### Returns\n\n`Promise`\\<`void`\\>",
"ReviewItem.submit": "### submit()\n\n> **submit**(): `Promise`\\<`void`\\>\n\n#### Returns\n\n`Promise`\\<`void`\\>",
- "SessionReview": "# Class: SessionReview\n\nA persistent review remains actionable after the code execution ends.\n\n## Extends\n\n- `MacroEntity`\\<`ReviewRecord`\\>\n\n## Properties\n\n| Property | Modifier | Type | Inherited from |\n| ------ | ------ | ------ | ------ |\n| <a id=\"property-id\"></a> `id` | `public readonly` | `string` | `MacroEntity.id` |\n| <a id=\"property-kind\"></a> `kind` | `readonly` | () => `Promise`\\<`ReviewKind`\\> | - |\n| <a id=\"property-title\"></a> `title` | `readonly` | () => `Promise`\\<`string`\\> | - |",
+ "SessionReview": "# Class: SessionReview\n\nA persistent review remains actionable after the code execution ends.\n\n## Extends\n\n- `MacroEntity`\\<`ReviewRecord`\\>\n\n## Properties\n\n| Property | Modifier | Type | Inherited from |\n| ------ | ------ | ------ | ------ |\n| <a id=\"property-id\"></a> `id` | `public readonly` | `string` | `MacroEntity.id` |\n| <a id=\"property-kind\"></a> `kind` | `readonly` | () => `Promise`\\<`\"calendar\"` \\| `\"email\"` \\| `\"import\"`\\> | - |\n| <a id=\"property-title\"></a> `title` | `readonly` | () => `Promise`\\<`string`\\> | - |",
"SessionReview.dismissAll": "### dismissAll()\n\n> **dismissAll**(): `Promise`\\<`void`\\>\n\n#### Returns\n\n`Promise`\\<`void`\\>",
"SessionReview.items": "### items()\n\n> **items**(): `Promise`\\<`ReviewItem`[]\\>\n\n#### Returns\n\n`Promise`\\<`ReviewItem`[]\\>",
- "SessionReview.reference": "### reference()\n\n> **reference**(): `Promise`\\<\\{ `id`: `string`; `kind`: `ReviewKind`; \\}\\>\n\nCompact reference for main()'s returned reviews array.\n\n#### Returns\n\n`Promise`\\<\\{ `id`: `string`; `kind`: `ReviewKind`; \\}\\>",
+ "SessionReview.reference": "### reference()\n\n> **reference**(): `Promise`\\<\\{ `id`: `string`; `kind`: `\"calendar\"` \\| `\"email\"` \\| `\"import\"`; \\}\\>\n\nCompact reference for main()'s returned reviews array.\n\n#### Returns\n\n`Promise`\\<\\{ `id`: `string`; `kind`: `\"calendar\"` \\| `\"email\"` \\| `\"import\"`; \\}\\>",
"SessionReview.refresh": "### refresh()\n\n> **refresh**(): `Promise`\\<`SessionReview`\\>\n\n#### Returns\n\n`Promise`\\<`SessionReview`\\>",
"SessionReview.session": "### session()\n\n> **session**(): `AgentSession`\n\n#### Returns\n\n`AgentSession`",
"SessionReview.submitAll": "### submitAll()\n\n> **submitAll**(): `Promise`\\<`void`\\>\n\nSubmit the saved pending drafts. Never retries a conflict or ambiguous send.\n\n#### Returns\n\n`Promise`\\<`void`\\>",
- "SessionReview.toJSON": "### toJSON()\n\n> **toJSON**(): \\{ `detail?`: `ReviewRecord`; `id`: `string`; \\}\n\n#### Returns\n\n\\{ `detail?`: `ReviewRecord`; `id`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `detail?` | `ReviewRecord` |\n| `id` | `string` |\n\n#### Inherited from\n\n`MacroEntity.toJSON`",
+ "SessionReview.toJSON": "### toJSON()\n\n> **toJSON**(): \\{ `detail?`: `ReviewRecord_Serialize`; `id`: `string`; \\}\n\n#### Returns\n\n\\{ `detail?`: `ReviewRecord_Serialize`; `id`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `detail?` | `ReviewRecord_Serialize` |\n| `id` | `string` |\n\n#### Inherited from\n\n`MacroEntity.toJSON`",
"SessionReview.byId": "### byId()\n\n> `static` **byId**(`client`, `session`, `id`): `SessionReview`\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `session` | `AgentSession` |\n| `id` | `string` |\n\n#### Returns\n\n`SessionReview`",
"SessionReview.create": "### create()\n\n> `static` **create**(`client`, `execution`, `input`): `Promise`\\<`SessionReview`\\>\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `execution` | `CodeExecution` |\n| `input` | `CreateReviewOptions` |\n\n#### Returns\n\n`Promise`\\<`SessionReview`\\>",
"SessionReview.createForSession": "### createForSession()\n\n> `static` **createForSession**(`client`, `session`, `input`, `execution?`): `Promise`\\<`SessionReview`\\>\n\nPresent a review in a session without requiring a code execution.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `session` | `AgentSession` |\n| `input` | `CreateReviewOptions` |\n| `execution?` | `CodeExecution` |\n\n#### Returns\n\n`Promise`\\<`SessionReview`\\>",
- "SessionReview.fromRecord": "### fromRecord()\n\n> `static` **fromRecord**(`client`, `session`, `record`): `SessionReview`\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `session` | `AgentSession` |\n| `record` | `ReviewRecord` |\n\n#### Returns\n\n`SessionReview`",
+ "SessionReview.fromRecord": "### fromRecord()\n\n> `static` **fromRecord**(`client`, `session`, `record`): `SessionReview`\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `session` | `AgentSession` |\n| `record` | `ReviewRecord_Serialize` |\n\n#### Returns\n\n`SessionReview`",
"SessionReview.list": "### list()\n\n> `static` **list**(`client`, `execution`): `Promise`\\<`SessionReview`[]\\>\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `execution` | `CodeExecution` |\n\n#### Returns\n\n`Promise`\\<`SessionReview`[]\\>",
- "CreateReviewOptions": "# Type Alias: CreateReviewOptions\n\n> **CreateReviewOptions** = \\{ `drafts`: `ReviewEmailDraft`[]; `kind`: `\"email\"`; `title`: `string`; \\} \\| \\{ `drafts`: `ReviewCalendarDraft`[]; `kind`: `\"calendar\"`; `title`: `string`; \\}",
- "ReviewCalendarDraft": "# Type Alias: ReviewCalendarDraft\n\n> **ReviewCalendarDraft** = \\{ `addGoogleMeet?`: `boolean`; `addMacroCall?`: `boolean`; `attendees?`: \\{ `email`: `string`; `isOptional?`: `boolean`; \\}[]; `calendarId?`: `string` \\| `null`; `description?`: `string` \\| `null`; `eventType?`: `\"default\"` \\| `\"out_of_office\"`; `location?`: `string` \\| `null`; `outOfOffice?`: \\{ `autoDeclineMode?`: `\"decline_none\"` \\| `\"decline_all\"` \\| `\"decline_new_only\"`; `declineMessage?`: `string` \\| `null`; \\} \\| `null`; `recurrenceLines?`: `string`[]; `reminders?`: \\{ `overrides?`: \\{ `method`: `string`; `minutes`: `number`; \\}[]; `useDefault`: `boolean`; \\} \\| `null`; `time`: `calendar.EventTime`; `title`: `string`; \\}\n\nCalendar drafts use the existing calendar composer and creation action.\n\n## Properties\n\n| Property | Type |\n| ------ | ------ |\n| <a id=\"property-addgooglemeet\"></a> `addGoogleMeet?` | `boolean` |\n| <a id=\"property-addmacrocall\"></a> `addMacroCall?` | `boolean` |\n| <a id=\"property-attendees\"></a> `attendees?` | \\{ `email`: `string`; `isOptional?`: `boolean`; \\}[] |\n| <a id=\"property-calendarid\"></a> `calendarId?` | `string` \\| `null` |\n| <a id=\"property-description\"></a> `description?` | `string` \\| `null` |\n| <a id=\"property-eventtype\"></a> `eventType?` | `\"default\"` \\| `\"out_of_office\"` |\n| <a id=\"property-location\"></a> `location?` | `string` \\| `null` |\n| <a id=\"property-outofoffice\"></a> `outOfOffice?` | \\{ `autoDeclineMode?`: `\"decline_none\"` \\| `\"decline_all\"` \\| `\"decline_new_only\"`; `declineMessage?`: `string` \\| `null`; \\} \\| `null` |\n| <a id=\"property-recurrencelines\"></a> `recurrenceLines?` | `string`[] |\n| <a id=\"property-reminders\"></a> `reminders?` | \\{ `overrides?`: \\{ `method`: `string`; `minutes`: `number`; \\}[]; `useDefault`: `boolean`; \\} \\| `null` |\n| <a id=\"property-time\"></a> `time` | `calendar.EventTime` |\n| <a id=\"property-title\"></a> `title` | `string` |",
- "ReviewEmailDraft": "# Type Alias: ReviewEmailDraft\n\n> **ReviewEmailDraft** = \\{ `attachments?`: \\{ `documentId`: `string`; \\}[]; `bcc?`: \\{ `email`: `string`; `name?`: `string` \\| `null`; \\}[]; `body`: `string`; `cc?`: \\{ `email`: `string`; `name?`: `string` \\| `null`; \\}[]; `includeSignature?`: `boolean` \\| `null`; `replyingToId?`: `string` \\| `null`; `subject`: `string`; `to`: \\{ `email`: `string`; `name?`: `string` \\| `null`; \\}[]; \\}\n\nMarkdown is rendered by the ordinary email action; the UI can edit each draft.\n\n## Properties\n\n| Property | Type |\n| ------ | ------ |\n| <a id=\"property-attachments\"></a> `attachments?` | \\{ `documentId`: `string`; \\}[] |\n| <a id=\"property-bcc\"></a> `bcc?` | \\{ `email`: `string`; `name?`: `string` \\| `null`; \\}[] |\n| <a id=\"property-body\"></a> `body` | `string` |\n| <a id=\"property-cc\"></a> `cc?` | \\{ `email`: `string`; `name?`: `string` \\| `null`; \\}[] |\n| <a id=\"property-includesignature\"></a> `includeSignature?` | `boolean` \\| `null` |\n| <a id=\"property-replyingtoid\"></a> `replyingToId?` | `string` \\| `null` |\n| <a id=\"property-subject\"></a> `subject` | `string` |\n| <a id=\"property-to\"></a> `to` | \\{ `email`: `string`; `name?`: `string` \\| `null`; \\}[] |",
+ "CreateReviewOptions": "# Type Alias: CreateReviewOptions\n\n> **CreateReviewOptions** = \\{ `title`: `ReviewTitle`; \\} & `ReviewDrafts_Deserialize`\n\nA review's kind and its drafts; the execution is attached by the handle.\n\n## Type Declaration\n\n| Name | Type |\n| ------ | ------ |\n| `title` | `ReviewTitle` |",
+ "ReviewCalendarDraft": "# Type Alias: ReviewCalendarDraft\n\n> **ReviewCalendarDraft** = `CreateCalendarEvent_Deserialize`\n\nCalendar drafts use the existing calendar composer and creation action.",
+ "ReviewDraft": "# Type Alias: ReviewDraft\n\n> **ReviewDraft** = `ReviewDraft_Deserialize`\n\nA replacement draft keyed by its review's kind.",
+ "ReviewEmailDraft": "# Type Alias: ReviewEmailDraft\n\n> **ReviewEmailDraft** = `SendEmail`\n\nMarkdown is rendered by the ordinary email action; the UI can edit each draft.",
"ToolApproval": "# Class: ToolApproval\n\nA permission request scoped to its originating agent session.\n\n## Properties\n\n| Property | Modifier | Type | Description |\n| ------ | ------ | ------ | ------ |\n| <a id=\"property-id\"></a> `id` | `readonly` | `string` | Approval identity. |\n| <a id=\"property-session\"></a> `session` | `readonly` | `AgentSession` | Owning session. |",
"ToolApproval.answer": "### answer()\n\n> **answer**(`answer`): `Promise`\\<`AnswerToolApprovalResponse`\\>\n\nAnswer the approval using the generated discriminated answer contract.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `answer` | `ToolApprovalAnswerDto` |\n\n#### Returns\n\n`Promise`\\<`AnswerToolApprovalResponse`\\>",
"ToolApproval.toJSON": "### toJSON()\n\n> **toJSON**(): \\{ `id`: `string`; `sessionId`: `string`; \\}\n\nSerialize scoped identity only.\n\n#### Returns\n\n\\{ `id`: `string`; `sessionId`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `id` | `string` |\n| `sessionId` | `string` |",
diff --git a/crates/agent_code_mode/src/domain/models.rs b/crates/agent_code_mode/src/domain/models.rs
index 47bf77fe5f..ca2b3f07ba 100644
--- a/crates/agent_code_mode/src/domain/models.rs
+++ b/crates/agent_code_mode/src/domain/models.rs
@@ -7,9 +7,15 @@ use serde_json::Value;
use utoipa::ToSchema;
/// Caller-selected UUID persisted in tool input before execution begins.
-#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema, ToSchema)]
+#[derive(
+ Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema, ToSchema, specta::Type,
+)]
#[serde(transparent)]
-pub struct ExecutionId(#[schemars(with = "String")] Uuid);
+pub struct ExecutionId(
+ #[schemars(with = "String")]
+ #[specta(type = String)]
+ Uuid,
+);
impl ExecutionId {
/// Mint an execution identity.
diff --git a/crates/agent_code_mode/src/domain/reviews.rs b/crates/agent_code_mode/src/domain/reviews.rs
index daac36c721..0827e8378e 100644
--- a/crates/agent_code_mode/src/domain/reviews.rs
+++ b/crates/agent_code_mode/src/domain/reviews.rs
@@ -14,35 +14,58 @@ use entity_access::domain::models::{
use macro_user_id::user_id::MacroUserIdStr;
use macro_uuid::Uuid;
use serde::{Deserialize, Serialize};
-use serde_json::Value;
use std::sync::Arc;
use tracing::Instrument as _;
use utoipa::ToSchema;
+mod drafts;
mod views;
pub use views::{PresentView, PresentedView};
#[cfg(test)]
mod test;
+pub use drafts::*;
+
const MAX_REVIEWS_PER_SESSION: u16 = 100;
const MAX_DRAFT_BYTES: usize = 128 * 1024;
const MAX_RECORD_BYTES: usize = 2 * 1024 * 1024;
const MAX_INPUT_BYTES: usize = 1024 * 1024;
const STALE_SUBMISSION_MS: i64 = 300_000;
const ACTION_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(60);
-const MAX_RESULT_BYTES: usize = 8192;
/// Persisted review identity.
#[derive(
- Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, ToSchema, schemars::JsonSchema,
+ Clone,
+ Copy,
+ Debug,
+ PartialEq,
+ Eq,
+ Serialize,
+ Deserialize,
+ ToSchema,
+ schemars::JsonSchema,
+ specta::Type,
)]
#[serde(transparent)]
-pub struct ReviewId(#[schemars(with = "String")] pub Uuid);
+pub struct ReviewId(
+ #[schemars(with = "String")]
+ #[specta(type = String)]
+ pub Uuid,
+);
/// The component and action used to finish a review.
#[derive(
- Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, ToSchema, schemars::JsonSchema,
+ Clone,
+ Copy,
+ Debug,
+ PartialEq,
+ Eq,
+ Serialize,
+ Deserialize,
+ ToSchema,
+ schemars::JsonSchema,
+ specta::Type,
)]
#[serde(rename_all = "snake_case")]
pub enum ReviewKind {
@@ -63,86 +86,75 @@ pub struct ReviewReference {
pub id: ReviewId,
}
-/// Review creation. Drafts are validated by the action's owning adapter.
-#[derive(Clone, Deserialize, Serialize, ToSchema, schemars::JsonSchema)]
-#[serde(rename_all = "camelCase", deny_unknown_fields)]
+/// Review creation. Decoding it validates every draft; creating a review only
+/// presents the drafts, and the account holder acts separately.
+#[derive(Clone, Deserialize, Serialize, ToSchema, schemars::JsonSchema, specta::Type)]
+#[serde(rename_all = "camelCase")]
pub struct CreateReview {
/// Optional code execution that prepared these drafts.
#[serde(default)]
pub execution_id: Option<ExecutionId>,
- /// Existing UI and action to use.
- pub kind: ReviewKind,
/// Stack label.
- pub title: String,
- /// One to one hundred independent drafts. Email: {subject, body: Markdown,
- /// to: [{email, name?}], cc?: [{email, name?}], bcc?: [{email, name?}],
- /// replyingToId?, attachments?: [{documentId}]}. Calendar: {title,
- /// time: {kind: "timed", startsAt: ISO datetime, endsAt: ISO datetime,
- /// timeZone?: IANA zone} or {kind: "allDay", startDate: ISO date,
- /// endDate: exclusive ISO date}, description?, location?, attendees?:
- /// [{email, isOptional?}]}. Import: exactly one draft {source: "notion" | "linear" | "jira"},
- /// presenting the plan ImportFromNotion, ImportFromLinear or ImportFromJira staged.
- /// Creating any review only presents these drafts; the user acts separately.
- pub drafts: Vec<Value>,
+ #[schema(value_type = String)]
+ pub title: ReviewTitle,
+ /// The review's kind (email, calendar, import) and its drafts: 1–100
+ /// SendEmail or CreateCalendarEvent arguments, or exactly one import
+ /// plan selection.
+ #[serde(flatten)]
+ #[schema(value_type = Object)]
+ pub drafts: ReviewDrafts,
}
/// Persisted review item state shared with typed system notifications.
pub use agent_runtime_protocol::domain::notification::ItemStatus as ReviewItemStatus;
-/// One editable item and its durable outcome.
-#[derive(Clone, Serialize, Deserialize, ToSchema)]
-#[serde(rename_all = "camelCase")]
-pub struct ReviewItem {
- /// Stable item identity across stack navigation and edits.
- pub id: Uuid,
- /// Validated arguments for the existing composer/action.
- pub draft: Value,
- /// Whether the account holder edited this draft before deciding.
- #[serde(default)]
- pub edited: bool,
- /// Current outcome.
- pub status: ReviewItemStatus,
- /// Actual backend response, never a model assertion.
- pub result: Option<Value>,
- /// Failure or uncertainty description.
- pub error: Option<String>,
-}
-
/// Full UI record, fetched outside the model context.
-#[derive(Clone, Serialize, Deserialize, ToSchema)]
+#[derive(Clone, Serialize, Deserialize, ToSchema, specta::Type)]
#[serde(rename_all = "camelCase")]
pub struct ReviewRecord {
/// Review identity.
pub id: ReviewId,
/// Owning session.
#[schema(value_type = Uuid)]
+ #[specta(type = String)]
pub session_id: AgentSessionId,
- /// Account whose email/calendar the drafts use; historical records use the session owner.
- #[serde(default)]
- #[schema(value_type = Option<String>)]
- pub acting_user: Option<MacroUserIdStr<'static>>,
+ /// Account whose email/calendar the drafts use.
+ #[schema(value_type = String)]
+ #[specta(type = String)]
+ pub acting_user: MacroUserIdStr<'static>,
/// Originating code execution, absent for directly presented reviews.
pub execution_id: Option<ExecutionId>,
/// Durable presentation acknowledgment, separate from user decisions.
#[serde(default)]
+ #[specta(type = Option<i32>)]
pub presented_at: Option<i64>,
- /// Component kind.
- pub kind: ReviewKind,
/// Stack label.
- pub title: String,
+ #[schema(value_type = String)]
+ pub title: ReviewTitle,
/// Compare-and-swap revision for edits and submissions.
+ #[specta(type = i32)]
pub revision: i64,
/// Milliseconds since epoch of the last state change.
+ #[specta(type = i32)]
pub updated_at: i64,
- /// Drafts and per-item outcomes.
- pub items: Vec<ReviewItem>,
+ /// Component kind, drafts and per-item outcomes.
+ #[serde(flatten)]
+ #[schema(value_type = Object)]
+ pub items: ReviewItems,
/// Current batch's authenticated decision, preserved for interrupted work.
#[serde(default)]
pub decision: Option<ReviewDecisionContext>,
}
+impl ReviewRecord {
+ /// The component and action used to finish this review.
+ pub fn kind(&self) -> ReviewKind {
+ self.items.kind()
+ }
+}
+
/// Facts about the most recent account-holder decision.
-#[derive(Clone, Serialize, Deserialize, ToSchema)]
+#[derive(Clone, Serialize, Deserialize, ToSchema, specta::Type)]
#[serde(rename_all = "camelCase")]
pub struct ReviewDecisionContext {
/// Authenticated account holder.
@@ -150,36 +162,45 @@ pub struct ReviewDecisionContext {
/// Entry surface.
pub via: DecisionVia,
/// Revision claimed by this batch, used in notification deduplication.
+ #[specta(type = i32)]
pub revision: i64,
/// Items selected by this decision.
+ #[specta(type = Vec<String>)]
pub items: Vec<Uuid>,
}
/// One atomic user decision against the displayed revision.
-#[derive(Clone, Deserialize, Serialize, ToSchema, schemars::JsonSchema)]
-#[serde(tag = "action", rename_all = "snake_case", deny_unknown_fields)]
+#[derive(Clone, Deserialize, Serialize, ToSchema, schemars::JsonSchema, specta::Type)]
+#[serde(tag = "action", rename_all = "snake_case")]
pub enum ReviewDecision {
/// Save one edited draft.
Edit {
/// Revision displayed by the caller.
+ #[specta(type = i32)]
revision: i64,
/// Pending item to update.
+ #[specta(type = String)]
item: Uuid,
- /// Replacement action arguments.
- draft: Value,
+ /// Replacement action arguments, keyed by the review's kind.
+ #[schema(value_type = Object)]
+ draft: Box<ReviewDraft>,
},
/// Send/create selected items, or all pending items when empty.
Submit {
/// Revision displayed by the caller.
+ #[specta(type = i32)]
revision: i64,
/// Pending items, or an empty list to select all pending items.
+ #[specta(type = Vec<String>)]
items: Vec<Uuid>,
},
/// Dismiss selected pending items, or all pending items when empty.
Dismiss {
/// Revision displayed by the caller.
+ #[specta(type = i32)]
revision: i64,
/// Pending items, or an empty list to select all pending items.
+ #[specta(type = Vec<String>)]
items: Vec<Uuid>,
},
}
@@ -229,8 +250,6 @@ pub struct ReviewSession {
pub trait ReviewActions: Send + Sync + 'static {
/// Read current ownership and lifecycle facts without applying review policy.
async fn session(&self, session: AgentSessionId) -> Result<ReviewSession, CodeModeError>;
- /// Validate draft structure without performing the action.
- fn validate(&self, kind: ReviewKind, draft: &Value) -> Result<(), CodeModeError>;
/// Whether `record`'s action can start now. A kind whose action depends on
/// work still in progress refuses until it is ready.
async fn approvable(
@@ -240,15 +259,26 @@ pub trait ReviewActions: Send + Sync + 'static {
) -> Result<bool, CodeModeError> {
Ok(true)
}
- /// Execute the reviewed draft of `record` as its saved, authenticated
- /// account holder. An import only starts here: its background write
+ /// Send a reviewed email as the record's saved, authenticated account holder.
+ async fn send_email(
+ &self,
+ account_holder: &MacroUserIdStr<'static>,
+ draft: &EmailDraft,
+ ) -> Result<EmailResult, CodeModeError>;
+ /// Create a reviewed calendar event as the record's account holder.
+ async fn create_calendar_event(
+ &self,
+ account_holder: &MacroUserIdStr<'static>,
+ draft: &CalendarDraft,
+ ) -> Result<CalendarResult, CodeModeError>;
+ /// Start writing `record`'s approved import plan. Its background write
/// reports its own end as a `review.settled` event once it stops.
- async fn execute(
+ async fn start_import(
&self,
- owner: &MacroUserIdStr<'static>,
+ account_holder: &MacroUserIdStr<'static>,
record: &ReviewRecord,
- draft: Value,
- ) -> Result<Value, CodeModeError>;
+ draft: &ImportDraft,
+ ) -> Result<ImportResult, CodeModeError>;
/// Persist and stream a completed presentation without waiting for user action.
/// Repeated calls with the same review ID must not duplicate its ACP frames.
async fn present(
@@ -301,8 +331,8 @@ impl ReviewService {
&self,
record: &ReviewRecord,
) -> Result<MacroUserIdStr<'static>, CodeModeError> {
- let owner = self.owner(record.session_id).await?;
- Ok(record.acting_user.clone().unwrap_or(owner))
+ self.owner(record.session_id).await?;
+ Ok(record.acting_user.clone())
}
async fn authorize(
&self,
@@ -364,40 +394,22 @@ impl ReviewService {
if let Some(execution) = input.execution_id {
self.executions.get(session, execution).await?;
}
- if input.title.trim().is_empty()
- || input.title.len() > 256
- || !(1..=100).contains(&input.drafts.len())
- || (input.kind == ReviewKind::Import && input.drafts.len() != 1)
- || serde_json::to_vec(&input).map_err(|_| invalid())?.len() > MAX_INPUT_BYTES
+ if serde_json::to_vec(&input).map_err(|_| invalid())?.len() > MAX_INPUT_BYTES
+ || !input.drafts.each_within(MAX_DRAFT_BYTES)
{
return Err(invalid());
}
- for draft in &input.drafts {
- self.validate_draft(input.kind, draft)?;
- }
let record = ReviewRecord {
id: ReviewId(macro_uuid::generate_uuid_v7()),
session_id: session,
- acting_user: Some(actor.clone()),
+ acting_user: actor.clone(),
execution_id: input.execution_id,
presented_at: None,
- kind: input.kind,
title: input.title,
revision: 0,
updated_at: chrono::Utc::now().timestamp_millis(),
decision: None,
- items: input
- .drafts
- .into_iter()
- .map(|draft| ReviewItem {
- id: macro_uuid::generate_uuid_v7(),
- draft,
- edited: false,
- status: ReviewItemStatus::Pending,
- result: None,
- error: None,
- })
- .collect(),
+ items: input.drafts.into(),
};
self.store.create(&record, MAX_REVIEWS_PER_SESSION).await?;
self.present(record).await
@@ -449,25 +461,11 @@ impl ReviewService {
if chrono::Utc::now().timestamp_millis() - record.updated_at > STALE_SUBMISSION_MS
&& record
.items
+ .states()
.iter()
.any(|item| item.status == ReviewItemStatus::Submitting)
{
- // Old review records predate typed decision context. Preserve their
- // interrupted batch when replacing the former mini-outbox.
- if record.decision.is_none() {
- record.decision = Some(ReviewDecisionContext {
- by: self.record_actor(&record).await?.to_string(),
- via: DecisionVia::Card,
- revision: record.revision,
- items: record
- .items
- .iter()
- .filter(|item| item.status == ReviewItemStatus::Submitting)
- .map(|item| item.id)
- .collect(),
- });
- }
- for item in &mut record.items {
+ for item in record.items.states_mut() {
if item.status == ReviewItemStatus::Submitting {
item.status = ReviewItemStatus::Unknown;
item.error = Some(
@@ -488,12 +486,6 @@ impl ReviewService {
}
Ok(record)
}
- fn validate_draft(&self, kind: ReviewKind, draft: &Value) -> Result<(), CodeModeError> {
- if serde_json::to_vec(draft).map_err(|_| invalid())?.len() > MAX_DRAFT_BYTES {
- return Err(invalid());
- }
- self.actions.validate(kind, draft)
- }
async fn save(
&self,
record: &mut ReviewRecord,
@@ -509,7 +501,7 @@ impl ReviewService {
.map(|event| {
// An approved import only started: its write settles later, and
// that wakes the session instead.
- let wake = !(record.kind == ReviewKind::Import
+ let wake = !(record.kind() == ReviewKind::Import
&& matches!(&event, NotificationEvent::ReviewDecided(outcome) if outcome.outcome != DecisionOutcome::Dismissed));
PendingNotification::new(ProduceNotification {
session_id: record.session_id,
@@ -616,77 +608,77 @@ impl ReviewService {
|| record.presented_at.is_none()
|| record
.items
+ .states()
.iter()
.any(|item| item.status == ReviewItemStatus::Submitting)
{
return Err(CodeModeError::Conflict);
}
- if let ReviewDecision::Edit { item, draft, .. } = decision {
- self.validate_draft(record.kind, &draft)?;
- let target = record
- .items
- .iter_mut()
- .find(|entry| entry.id == item && entry.status == ReviewItemStatus::Pending)
- .ok_or(CodeModeError::Conflict)?;
- target.draft = draft;
- target.edited = true;
- if record
- .items
- .iter()
- .map(|item| {
- serde_json::to_vec(&item.draft)
- .map(|bytes| bytes.len())
- .unwrap_or(MAX_INPUT_BYTES + 1)
- })
- .sum::<usize>()
- > MAX_INPUT_BYTES
- {
- return Err(invalid());
- }
- self.save(&mut record, None).await?;
- return Ok(record);
- }
let (ids, submit) = match decision {
+ ReviewDecision::Edit { item, draft, .. } => {
+ if serde_json::to_vec(&draft).map_err(|_| invalid())?.len() > MAX_DRAFT_BYTES {
+ return Err(invalid());
+ }
+ record.items.edit(item, *draft)?;
+ if serde_json::to_vec(&record.items)
+ .map_err(|_| invalid())?
+ .len()
+ > MAX_INPUT_BYTES
+ {
+ return Err(invalid());
+ }
+ self.save(&mut record, None).await?;
+ return Ok(record);
+ }
ReviewDecision::Submit { items, .. } => (items, true),
ReviewDecision::Dismiss { items, .. } => (items, false),
- ReviewDecision::Edit { .. } => unreachable!(),
};
+ let states = record.items.states();
if ids.iter().any(|id| {
- !record
- .items
+ !states
.iter()
.any(|item| item.id == *id && item.status == ReviewItemStatus::Pending)
}) {
return Err(CodeModeError::Conflict);
}
- let selected: Vec<usize> = record
- .items
+ let selected: Vec<(usize, Uuid)> = states
.iter()
.enumerate()
.filter(|(_, item)| {
item.status == ReviewItemStatus::Pending
&& (ids.is_empty() || ids.contains(&item.id))
})
- .map(|(index, _)| index)
+ .map(|(index, item)| (index, item.id))
.collect();
if selected.is_empty() {
return Ok(record);
}
- for index in &selected {
- record.items[*index].status = if submit {
- ReviewItemStatus::Submitting
- } else {
- ReviewItemStatus::Dismissed
- };
+ if submit {
+ for (position, (index, _)) in selected.iter().enumerate() {
+ if let Some(problem) = record.items.submission_problem(*index) {
+ return Err(CodeModeError::Invalid(if selected.len() == 1 {
+ problem.to_string()
+ } else {
+ format!("Draft {} of {}: {problem}", position + 1, selected.len())
+ }));
+ }
+ }
+ }
+ let mut states = record.items.states_mut();
+ for (index, _) in &selected {
+ if let Some(item) = states.get_mut(*index) {
+ item.status = if submit {
+ ReviewItemStatus::Submitting
+ } else {
+ ReviewItemStatus::Dismissed
+ };
+ }
}
record.decision = Some(ReviewDecisionContext {
by: actor.to_string(),
via,
revision,
- items: selected
- .iter()
- .map(|index| record.items[*index].id)
- .collect(),
+ items: selected.iter().map(|(_, id)| *id).collect(),
});
let event = NotificationEvent::ReviewDecided(review_outcome(&record));
self.save(&mut record, Some(event)).await?;
@@ -695,42 +687,29 @@ impl ReviewService {
let actor = actor.clone();
tokio::spawn(async move {
if submit {
- let last = selected.last().copied();
- for index in selected {
+ let last = selected.last().map(|(index, _)| *index);
+ for (index, _) in selected {
let outcome = tokio::time::timeout(ACTION_TIMEOUT, async {
if service.record_actor(&record).await? != actor {
return Err(CodeModeError::Forbidden);
}
- service
- .actions
- .execute(&actor, &record, record.items[index].draft.clone())
- .await
+ service.perform(&actor, &record, index).await
})
.await;
- let item = &mut record.items[index];
- match outcome {
- Ok(Ok(result)) => {
- item.status = ReviewItemStatus::Completed;
- item.result = Some(
- if serde_json::to_vec(&result)
- .is_ok_and(|bytes| bytes.len() <= MAX_RESULT_BYTES)
- {
- result
- } else {
- serde_json::json!({"outputOmitted": true, "reason": "Review action succeeded; result exceeded the saved detail limit."})
- },
- );
- }
- _ => {
- item.status = ReviewItemStatus::Unknown;
- item.error = Some("The submission outcome could not be confirmed. Check the destination before retrying.".into());
- }
+ let completed = match outcome {
+ Ok(Ok(result)) => record.items.complete(index, result).is_ok(),
+ _ => false,
+ };
+ if !completed
+ && let Some(item) = record.items.states_mut().get_mut(index)
+ {
+ item.status = ReviewItemStatus::Unknown;
+ item.error = Some("The submission outcome could not be confirmed. Check the destination before retrying.".into());
}
// A started import settles when its write ends; only one that
// could not start settles here.
let event = (Some(index) == last
- && !(record.kind == ReviewKind::Import
- && record.items[index].status == ReviewItemStatus::Completed))
+ && !(record.kind() == ReviewKind::Import && completed))
.then(|| {
NotificationEvent::ReviewSettled(ReviewSettlement::Actions(
review_outcome(&record),
@@ -744,6 +723,38 @@ impl ReviewService {
}.in_current_span());
Ok(response)
}
+
+ /// Run the existing action for the item at `index` with its typed draft.
+ async fn perform(
+ &self,
+ account_holder: &MacroUserIdStr<'static>,
+ record: &ReviewRecord,
+ index: usize,
+ ) -> Result<ReviewResult, CodeModeError> {
+ match &record.items {
+ ReviewItems::Email(items) => {
+ let item = items.get(index).ok_or(CodeModeError::Conflict)?;
+ let result = self.actions.send_email(account_holder, &item.draft).await?;
+ Ok(ReviewResult::Email(result))
+ }
+ ReviewItems::Calendar(items) => {
+ let item = items.get(index).ok_or(CodeModeError::Conflict)?;
+ let result = self
+ .actions
+ .create_calendar_event(account_holder, &item.draft)
+ .await?;
+ Ok(ReviewResult::Calendar(result))
+ }
+ ReviewItems::Import(items) => {
+ let item = items.get(index).ok_or(CodeModeError::Conflict)?;
+ let result = self
+ .actions
+ .start_import(account_holder, record, &item.draft)
+ .await?;
+ Ok(ReviewResult::Import(result))
+ }
+ }
+ }
}
fn session_id(kind: EntityType, id: &str) -> Result<AgentSessionId, CodeModeError> {
if kind != EntityType::AgentSession {
@@ -754,7 +765,9 @@ fn session_id(kind: EntityType, id: &str) -> Result<AgentSessionId, CodeModeErro
.map_err(|_| CodeModeError::Forbidden)
}
fn invalid() -> CodeModeError {
- CodeModeError::Invalid("Provide a title and 1–100 valid drafts within 1 MiB.".into())
+ CodeModeError::Invalid(
+ "Keep a review's drafts within 1 MiB, and each draft within 128 KiB.".into(),
+ )
}
/// Bounded outcome facts; final drafts and provider results stay on the review.
@@ -762,7 +775,8 @@ pub fn review_outcome(record: &ReviewRecord) -> ReviewOutcome {
let decision = record.decision.as_ref();
let items: Vec<_> = record
.items
- .iter()
+ .states()
+ .into_iter()
.filter(|item| decision.is_some_and(|decision| decision.items.contains(&item.id)))
.map(|item| ReviewItemOutcome {
id: item.id,
diff --git a/crates/agent_code_mode/src/domain/reviews/drafts.rs b/crates/agent_code_mode/src/domain/reviews/drafts.rs
new file mode 100644
index 0000000000..a2d8a89f8b
--- /dev/null
+++ b/crates/agent_code_mode/src/domain/reviews/drafts.rs
@@ -0,0 +1,358 @@
+//! Typed review drafts and outcomes. Decoding a draft is its validation.
+use super::{ReviewItemStatus, ReviewKind};
+use crate::domain::CodeModeError;
+use macro_uuid::Uuid;
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize, de::DeserializeOwned};
+
+pub use calendar_events::inbound::toolset::{
+ CreateCalendarEvent as CalendarDraft, EventTimeInput, ToolCalendarEvent as CalendarResult,
+};
+pub use email::inbound::toolset::{SendEmail as EmailDraft, SendEmailResponse as EmailResult};
+pub use import::domain::models::NotionImportReport as ImportResult;
+
+/// Most independent drafts one review may stack.
+pub const MAX_DRAFTS: usize = 100;
+
+/// A review stack label: not blank, at most 256 characters.
+#[nutype::nutype(
+ sanitize(trim),
+ validate(not_empty, len_char_max = 256),
+ derive(Debug, Clone, PartialEq, Eq, AsRef, Display, Serialize, Deserialize),
+ derive_unchecked(JsonSchema, specta::Type)
+)]
+pub struct ReviewTitle(String);
+
+/// One to [`MAX_DRAFTS`] drafts of one kind.
+#[nutype::nutype(
+ validate(predicate = |drafts| (1..=MAX_DRAFTS).contains(&drafts.len())),
+ derive(Debug, Clone, AsRef, Serialize, Deserialize),
+ derive_unchecked(JsonSchema, specta::Type)
+)]
+pub struct DraftList<Draft>(Vec<Draft>);
+
+/// Which source's staged plan an import review presents.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema, specta::Type)]
+#[serde(rename_all = "snake_case")]
+pub enum ImportReviewSource {
+ /// A Notion workspace plan, staged by ImportFromNotion.
+ Notion,
+ /// A Linear plan, staged by ImportFromLinear.
+ Linear,
+ /// A Jira plan, staged by ImportFromJira.
+ Jira,
+}
+
+impl From<ImportReviewSource> for import::domain::models::ImportSource {
+ fn from(source: ImportReviewSource) -> Self {
+ match source {
+ ImportReviewSource::Notion => Self::Notion,
+ ImportReviewSource::Linear => Self::Linear,
+ ImportReviewSource::Jira => Self::Jira,
+ }
+ }
+}
+
+/// The one draft an import review carries: which source's staged plan it
+/// presents, the plan rows the user took out of it, and the rows whose
+/// sharing they changed: `shared` to share with their team, `personal` to
+/// keep to themselves.
+#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, specta::Type)]
+#[serde(rename_all = "camelCase", deny_unknown_fields)]
+pub struct ImportDraft {
+ /// The staged plan's source; fixed once the review is presented.
+ pub source: ImportReviewSource,
+ /// Plan rows left out of the import.
+ #[serde(default)]
+ pub excluded: Vec<Uuid>,
+ /// Plan rows shared with the team although the plan keeps them private.
+ #[serde(default)]
+ pub shared: Vec<Uuid>,
+ /// Plan rows kept private although the plan shares them.
+ #[serde(default)]
+ pub personal: Vec<Uuid>,
+}
+
+/// The drafts a new review presents, keyed by the review's kind.
+#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, specta::Type)]
+#[serde(tag = "kind", content = "drafts", rename_all = "snake_case")]
+pub enum ReviewDrafts {
+ /// Emails, each sent with the SendEmail action (Markdown body).
+ Email(DraftList<EmailDraft>),
+ /// Calendar events, each created with the CreateCalendarEvent action.
+ Calendar(DraftList<CalendarDraft>),
+ /// Exactly one staged import plan, approved as one item.
+ Import([ImportDraft; 1]),
+}
+
+/// One replacement draft, keyed by the kind of the review it edits.
+#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, specta::Type)]
+#[serde(tag = "kind", content = "draft", rename_all = "snake_case")]
+pub enum ReviewDraft {
+ /// An edited email.
+ Email(EmailDraft),
+ /// An edited calendar event.
+ Calendar(CalendarDraft),
+ /// An edited import plan selection.
+ Import(ImportDraft),
+}
+
+/// Item facts every kind shares.
+#[derive(Clone, Debug, Serialize, Deserialize, specta::Type)]
+#[serde(rename_all = "camelCase")]
+pub struct ReviewItemState {
+ /// Stable item identity across stack navigation and edits.
+ #[specta(type = String)]
+ pub id: Uuid,
+ /// Whether the account holder edited this draft before deciding.
+ #[serde(default)]
+ pub edited: bool,
+ /// Current outcome.
+ pub status: ReviewItemStatus,
+ /// Failure or uncertainty description.
+ pub error: Option<String>,
+}
+
+/// One editable item and its durable outcome.
+#[derive(Clone, Debug, Serialize, Deserialize, specta::Type)]
+#[serde(rename_all = "camelCase")]
+pub struct ReviewItem<Draft, Outcome> {
+ /// Identity and status.
+ #[serde(flatten)]
+ pub state: ReviewItemState,
+ /// Arguments for the existing composer and action.
+ pub draft: Draft,
+ /// The action's confirmed response, never a model assertion.
+ pub result: Option<Outcome>,
+}
+
+impl<Draft, Outcome> ReviewItem<Draft, Outcome> {
+ /// A new pending item.
+ pub fn pending(draft: Draft) -> Self {
+ Self {
+ state: ReviewItemState {
+ id: macro_uuid::generate_uuid_v7(),
+ edited: false,
+ status: ReviewItemStatus::Pending,
+ error: None,
+ },
+ draft,
+ result: None,
+ }
+ }
+}
+
+/// Saved items keyed by the review's kind.
+#[derive(Clone, Debug, Serialize, Deserialize, specta::Type)]
+#[serde(tag = "kind", content = "items", rename_all = "snake_case")]
+pub enum ReviewItems {
+ /// Email drafts and their send responses.
+ Email(Vec<ReviewItem<EmailDraft, EmailResult>>),
+ /// Calendar drafts and their created events.
+ Calendar(Vec<ReviewItem<CalendarDraft, CalendarResult>>),
+ /// The import plan selection and the started write's report.
+ Import(Box<[ReviewItem<ImportDraft, ImportResult>; 1]>),
+}
+
+/// A confirmed action response, keyed by kind.
+pub enum ReviewResult {
+ /// The email was sent.
+ Email(EmailResult),
+ /// The event was created.
+ Calendar(CalendarResult),
+ /// The import write started.
+ Import(ImportResult),
+}
+
+impl From<ReviewDrafts> for ReviewItems {
+ fn from(drafts: ReviewDrafts) -> Self {
+ match drafts {
+ ReviewDrafts::Email(drafts) => Self::Email(
+ drafts
+ .into_inner()
+ .into_iter()
+ .map(ReviewItem::pending)
+ .collect(),
+ ),
+ ReviewDrafts::Calendar(drafts) => Self::Calendar(
+ drafts
+ .into_inner()
+ .into_iter()
+ .map(ReviewItem::pending)
+ .collect(),
+ ),
+ ReviewDrafts::Import([draft]) => Self::Import(Box::new([ReviewItem::pending(draft)])),
+ }
+ }
+}
+
+impl ReviewDrafts {
+ /// Whether every draft serializes within `limit` bytes.
+ pub fn each_within(&self, limit: usize) -> bool {
+ fn fits<Draft: Serialize>(drafts: &[Draft], limit: usize) -> bool {
+ drafts
+ .iter()
+ .all(|draft| serde_json::to_vec(draft).is_ok_and(|bytes| bytes.len() <= limit))
+ }
+ match self {
+ Self::Email(drafts) => fits(drafts.as_ref(), limit),
+ Self::Calendar(drafts) => fits(drafts.as_ref(), limit),
+ Self::Import(drafts) => fits(drafts, limit),
+ }
+ }
+
+ /// The kind of review these drafts present.
+ pub fn kind(&self) -> ReviewKind {
+ match self {
+ Self::Email(_) => ReviewKind::Email,
+ Self::Calendar(_) => ReviewKind::Calendar,
+ Self::Import(_) => ReviewKind::Import,
+ }
+ }
+}
+
+impl ReviewItems {
+ /// The component and action used to finish these items.
+ pub fn kind(&self) -> ReviewKind {
+ match self {
+ Self::Email(_) => ReviewKind::Email,
+ Self::Calendar(_) => ReviewKind::Calendar,
+ Self::Import(_) => ReviewKind::Import,
+ }
+ }
+
+ /// Every item's shared facts, in stack order.
+ pub fn states(&self) -> Vec<&ReviewItemState> {
+ match self {
+ Self::Email(items) => items.iter().map(|item| &item.state).collect(),
+ Self::Calendar(items) => items.iter().map(|item| &item.state).collect(),
+ Self::Import(items) => items.iter().map(|item| &item.state).collect(),
+ }
+ }
+
+ /// Every item's shared facts, mutably, in stack order.
+ pub fn states_mut(&mut self) -> Vec<&mut ReviewItemState> {
+ match self {
+ Self::Email(items) => items.iter_mut().map(|item| &mut item.state).collect(),
+ Self::Calendar(items) => items.iter_mut().map(|item| &mut item.state).collect(),
+ Self::Import(items) => items.iter_mut().map(|item| &mut item.state).collect(),
+ }
+ }
+
+ /// Replace a pending item's draft with one of the same kind.
+ pub fn edit(&mut self, item: Uuid, draft: ReviewDraft) -> Result<(), CodeModeError> {
+ fn replace<Draft, Outcome>(
+ items: &mut [ReviewItem<Draft, Outcome>],
+ item: Uuid,
+ draft: Draft,
+ ) -> Result<(), CodeModeError> {
+ let target = items
+ .iter_mut()
+ .find(|entry| {
+ entry.state.id == item && entry.state.status == ReviewItemStatus::Pending
+ })
+ .ok_or(CodeModeError::Conflict)?;
+ target.draft = draft;
+ target.state.edited = true;
+ Ok(())
+ }
+ match (self, draft) {
+ (Self::Email(items), ReviewDraft::Email(draft)) => replace(items, item, draft),
+ (Self::Calendar(items), ReviewDraft::Calendar(draft)) => replace(items, item, draft),
+ (Self::Import(items), ReviewDraft::Import(draft)) => {
+ let [saved] = &**items;
+ if saved.draft.source != draft.source {
+ return Err(CodeModeError::Invalid(
+ "An import review's source cannot change after presentation.".into(),
+ ));
+ }
+ replace(&mut items[..], item, draft)
+ }
+ _ => Err(CodeModeError::Invalid(
+ "The draft's kind does not match the review's kind.".into(),
+ )),
+ }
+ }
+
+ /// Why the item at `index` cannot be acted on yet, if it cannot.
+ pub fn submission_problem(&self, index: usize) -> Option<&'static str> {
+ match self {
+ Self::Email(items) => items.get(index).and_then(|item| email_problem(&item.draft)),
+ Self::Calendar(items) => items
+ .get(index)
+ .and_then(|item| calendar_problem(&item.draft)),
+ Self::Import(_) => None,
+ }
+ }
+
+ /// Record a confirmed response on the item at `index`.
+ pub fn complete(&mut self, index: usize, result: ReviewResult) -> Result<(), CodeModeError> {
+ fn store<Draft, Outcome>(
+ items: &mut [ReviewItem<Draft, Outcome>],
+ index: usize,
+ result: Outcome,
+ ) -> Result<(), CodeModeError> {
+ let item = items.get_mut(index).ok_or(CodeModeError::Conflict)?;
+ item.state.status = ReviewItemStatus::Completed;
+ item.result = Some(result);
+ Ok(())
+ }
+ match (self, result) {
+ (Self::Email(items), ReviewResult::Email(result)) => store(items, index, result),
+ (Self::Calendar(items), ReviewResult::Calendar(result)) => store(items, index, result),
+ (Self::Import(items), ReviewResult::Import(result)) => {
+ store(&mut items[..], index, result)
+ }
+ _ => Err(CodeModeError::Invalid(
+ "The action's response does not match the review's kind.".into(),
+ )),
+ }
+ }
+}
+
+/// Whether an email draft can be sent. Incomplete drafts still save, so the
+/// account holder can finish them in the card.
+fn email_problem(draft: &EmailDraft) -> Option<&'static str> {
+ if draft.to.is_empty() {
+ return Some("Add at least one recipient.");
+ }
+ if draft.body.trim().is_empty() {
+ return Some("Write a message before sending.");
+ }
+ None
+}
+
+/// Whether a calendar draft can be created. Incomplete drafts still save.
+fn calendar_problem(draft: &CalendarDraft) -> Option<&'static str> {
+ if draft.title.trim().is_empty() {
+ return Some("Give this event a title.");
+ }
+ let ends_after_start = match &draft.time {
+ EventTimeInput::Timed {
+ starts_at, ends_at, ..
+ } => ends_at > starts_at,
+ EventTimeInput::AllDay {
+ start_date,
+ end_date,
+ } => end_date > start_date,
+ };
+ if !ends_after_start {
+ return Some("The event must end after it starts.");
+ }
+ if draft.add_macro_call && draft.add_conference {
+ return Some("Choose either a Macro call or a video meeting.");
+ }
+ None
+}
+
+/// Decode JSON into a review type. Errors name only the failing location,
+/// never the submitted content.
+pub fn decode<Input: DeserializeOwned>(json: &[u8]) -> Result<Input, CodeModeError> {
+ let mut deserializer = serde_json::Deserializer::from_slice(json);
+ let input = serde_path_to_error::deserialize(&mut deserializer)
+ .map_err(|error| CodeModeError::Invalid(format!("Invalid value at `{}`.", error.path())))?;
+ deserializer
+ .end()
+ .map_err(|_| CodeModeError::Invalid("Unexpected content after the JSON value.".into()))?;
+ Ok(input)
+}
diff --git a/crates/agent_code_mode/src/domain/reviews/test.rs b/crates/agent_code_mode/src/domain/reviews/test.rs
index 56b837f99e..ca89111ee1 100644
--- a/crates/agent_code_mode/src/domain/reviews/test.rs
+++ b/crates/agent_code_mode/src/domain/reviews/test.rs
@@ -1,7 +1,7 @@
use super::*;
use crate::domain::{ExecutionRecord, ExecutionStatus};
use macro_user_id::cowlike::CowLike;
-use serde_json::json;
+use serde_json::{Value, json};
use std::{
collections::HashMap,
sync::{
@@ -120,7 +120,7 @@ struct Actions {
owner: MacroUserIdStr<'static>,
archived: AtomicBool,
prompter: Mutex<Option<TurnPrompter>>,
- calls: Mutex<Vec<Value>>,
+ calls: Mutex<Vec<String>>,
actors: Mutex<Vec<String>>,
presentations: Mutex<Vec<ReviewId>>,
views: Mutex<Vec<(AgentSessionId, PresentedView)>>,
@@ -129,6 +129,17 @@ struct Actions {
action_gate: tokio::sync::Notify,
action_started: tokio::sync::Notify,
approvable: AtomicBool,
+ fail_import: AtomicBool,
+}
+impl Actions {
+ async fn act(&self, account_holder: &MacroUserIdStr<'static>, call: String) {
+ self.actors.lock().unwrap().push(account_holder.to_string());
+ self.calls.lock().unwrap().push(call);
+ self.action_started.notify_one();
+ if self.block_actions.load(Ordering::SeqCst) {
+ self.action_gate.notified().await;
+ }
+ }
}
#[async_trait]
impl ReviewActions for Actions {
@@ -144,34 +155,41 @@ impl ReviewActions for Actions {
account_holder: &MacroUserIdStr<'static>,
record: &ReviewRecord,
) -> Result<bool, CodeModeError> {
- assert_eq!(
- Some(account_holder),
- record.acting_user.as_ref().or(Some(&self.owner))
- );
+ assert_eq!(account_holder, &record.acting_user);
Ok(self.approvable.load(Ordering::SeqCst))
}
- fn validate(&self, _: ReviewKind, draft: &Value) -> Result<(), CodeModeError> {
- if draft.get("subject").and_then(Value::as_str).is_none() {
+ async fn send_email(
+ &self,
+ account_holder: &MacroUserIdStr<'static>,
+ draft: &EmailDraft,
+ ) -> Result<EmailResult, CodeModeError> {
+ self.act(account_holder, draft.subject.clone()).await;
+ if draft.subject == "fail" {
return Err(invalid());
}
- Ok(())
+ Ok(EmailResult::Sent {
+ message_id: macro_uuid::generate_uuid_v7(),
+ thread_id: macro_uuid::generate_uuid_v7(),
+ })
}
- async fn execute(
+ async fn create_calendar_event(
&self,
- owner: &MacroUserIdStr<'static>,
+ _: &MacroUserIdStr<'static>,
+ _: &CalendarDraft,
+ ) -> Result<CalendarResult, CodeModeError> {
+ unreachable!("these tests present email and import reviews")
+ }
+ async fn start_import(
+ &self,
+ account_holder: &MacroUserIdStr<'static>,
_: &ReviewRecord,
- draft: Value,
- ) -> Result<Value, CodeModeError> {
- self.actors.lock().unwrap().push(owner.to_string());
- self.calls.lock().unwrap().push(draft.clone());
- self.action_started.notify_one();
- if self.block_actions.load(Ordering::SeqCst) {
- self.action_gate.notified().await;
- }
- if draft.get("fail").is_some() {
+ _: &ImportDraft,
+ ) -> Result<ImportResult, CodeModeError> {
+ self.act(account_holder, "import".into()).await;
+ if self.fail_import.load(Ordering::SeqCst) {
return Err(invalid());
}
- Ok(draft)
+ Ok(ImportResult::default())
}
async fn present(
&self,
@@ -224,6 +242,7 @@ impl Fixture {
action_gate: tokio::sync::Notify::new(),
action_started: tokio::sync::Notify::new(),
approvable: AtomicBool::new(true),
+ fail_import: AtomicBool::new(false),
});
let service = ReviewService::new(
store.clone(),
@@ -252,17 +271,22 @@ impl Fixture {
EntityType::AgentSession,
)
}
- fn input(&self, drafts: Vec<Value>) -> CreateReview {
- CreateReview {
- execution_id: Some(self.execution),
- kind: ReviewKind::Email,
- title: "Emails".into(),
- drafts,
- }
+ fn input(&self, kind: &str, drafts: Vec<Value>) -> CreateReview {
+ let input = json!({
+ "executionId": self.execution,
+ "title": "Drafts",
+ "kind": kind,
+ "drafts": drafts,
+ });
+ decode(&serde_json::to_vec(&input).unwrap()).unwrap()
}
async fn create(&self, drafts: Vec<Value>) -> ReviewRecord {
self.service
- .create(&self.edit(), &self.actions.owner, self.input(drafts))
+ .create(
+ &self.edit(),
+ &self.actions.owner,
+ self.input("email", drafts),
+ )
.await
.unwrap()
}
@@ -275,6 +299,7 @@ impl Fixture {
let row = self.store.get(self.session, id).await.unwrap();
if row
.items
+ .states()
.iter()
.all(|item| item.status != ReviewItemStatus::Submitting)
{
@@ -295,11 +320,23 @@ async fn owner_receipt_execution_and_archive_are_enforced_before_creation() {
.into_owned();
assert!(matches!(
f.service
- .create(&f.edit(), &stranger, f.input(vec![json!({"subject":"x"})]))
+ .create(
+ &f.edit(),
+ &stranger,
+ f.input(
+ "email",
+ vec![
+ json!({"subject":"x", "body":"Hello", "to":[{"email":"[email protected]"}]})
+ ]
+ )
+ )
.await,
Err(CodeModeError::Forbidden)
));
- let mut input = f.input(vec![json!({"subject":"x"})]);
+ let mut input = f.input(
+ "email",
+ vec![json!({"subject":"x", "body":"Hello", "to":[{"email":"[email protected]"}]})],
+ );
input.execution_id = Some(ExecutionId::mint());
assert!(matches!(
f.service.create(&f.edit(), &f.actions.owner, input).await,
@@ -315,7 +352,12 @@ async fn owner_receipt_execution_and_archive_are_enforced_before_creation() {
.create(
&wrong_receipt,
&f.actions.owner,
- f.input(vec![json!({"subject":"x"})])
+ f.input(
+ "email",
+ vec![
+ json!({"subject":"x", "body":"Hello", "to":[{"email":"[email protected]"}]})
+ ]
+ )
)
.await,
Err(CodeModeError::Forbidden)
@@ -326,7 +368,12 @@ async fn owner_receipt_execution_and_archive_are_enforced_before_creation() {
.create(
&f.edit(),
&f.actions.owner,
- f.input(vec![json!({"subject":"x"})])
+ f.input(
+ "email",
+ vec![
+ json!({"subject":"x", "body":"Hello", "to":[{"email":"[email protected]"}]})
+ ]
+ )
)
.await,
Err(CodeModeError::Forbidden)
@@ -337,7 +384,11 @@ async fn owner_receipt_execution_and_archive_are_enforced_before_creation() {
async fn double_submit_claims_before_work_and_never_repeats_an_action() {
let f = Fixture::new();
f.actions.block_actions.store(true, Ordering::SeqCst);
- let row = f.create(vec![json!({"subject":"x"})]).await;
+ let row = f
+ .create(vec![
+ json!({"subject":"x", "body":"Hello", "to":[{"email":"[email protected]"}]}),
+ ])
+ .await;
let decision = ReviewDecision::Submit {
revision: row.revision,
items: vec![],
@@ -353,12 +404,15 @@ async fn double_submit_claims_before_work_and_never_repeats_an_action() {
assert!(matches!(a.err().or(b.err()), Some(CodeModeError::Conflict)));
f.actions.action_started.notified().await;
assert_eq!(
- f.store.get(f.session, row.id).await.unwrap().items[0].status,
+ f.store.get(f.session, row.id).await.unwrap().items.states()[0].status,
ReviewItemStatus::Submitting
);
f.actions.action_gate.notify_one();
let final_row = f.settled(row.id).await;
- assert_eq!(final_row.items[0].status, ReviewItemStatus::Completed);
+ assert_eq!(
+ final_row.items.states()[0].status,
+ ReviewItemStatus::Completed
+ );
assert_eq!(f.actions.calls.lock().unwrap().len(), 1);
assert!(matches!(
f.service
@@ -368,7 +422,7 @@ async fn double_submit_claims_before_work_and_never_repeats_an_action() {
row.id,
ReviewDecision::Submit {
revision: final_row.revision,
- items: vec![row.items[0].id]
+ items: vec![row.items.states()[0].id]
}
)
.await,
@@ -380,9 +434,9 @@ async fn send_all_preserves_successes_and_ambiguous_failure_without_retries() {
let f = Fixture::new();
let row = f
.create(vec![
- json!({"subject":"one"}),
- json!({"subject":"two", "fail":true}),
- json!({"subject":"three"}),
+ json!({"subject":"one", "body":"Hello", "to":[{"email":"[email protected]"}]}),
+ json!({"subject":"fail", "body":"Hello", "to":[{"email":"[email protected]"}]}),
+ json!({"subject":"three", "body":"Hello", "to":[{"email":"[email protected]"}]}),
])
.await;
f.service
@@ -401,8 +455,9 @@ async fn send_all_preserves_successes_and_ambiguous_failure_without_retries() {
assert_eq!(
completed
.items
+ .states()
.iter()
- .map(|i| i.status.clone())
+ .map(|i| i.status)
.collect::<Vec<_>>(),
vec![
ReviewItemStatus::Completed,
@@ -416,11 +471,15 @@ async fn send_all_preserves_successes_and_ambiguous_failure_without_retries() {
#[tokio::test]
async fn edit_checks_saved_revision_and_draft_bounds_and_dismiss_does_not_execute() {
let f = Fixture::new();
- let row = f.create(vec![json!({"subject":"x"})]).await;
- let edit = |revision, draft| ReviewDecision::Edit {
+ let row = f
+ .create(vec![
+ json!({"subject":"x", "body":"Hello", "to":[{"email":"[email protected]"}]}),
+ ])
+ .await;
+ let edit = |revision, draft: Value| ReviewDecision::Edit {
revision,
- item: row.items[0].id,
- draft,
+ item: row.items.states()[0].id,
+ draft: Box::new(serde_json::from_value(json!({"kind":"email", "draft": draft})).unwrap()),
};
let changed = f
.service
@@ -428,7 +487,10 @@ async fn edit_checks_saved_revision_and_draft_bounds_and_dismiss_does_not_execut
&f.edit(),
&f.actions.owner,
row.id,
- edit(row.revision, json!({"subject":"edited"})),
+ edit(
+ row.revision,
+ json!({"subject":"edited", "body":"Hello", "to":[{"email":"[email protected]"}]}),
+ ),
)
.await
.unwrap();
@@ -438,7 +500,10 @@ async fn edit_checks_saved_revision_and_draft_bounds_and_dismiss_does_not_execut
&f.edit(),
&f.actions.owner,
row.id,
- edit(row.revision, json!({"subject":"stale"}))
+ edit(
+ row.revision,
+ json!({"subject":"stale", "body":"Hello", "to":[{"email":"[email protected]"}]})
+ )
)
.await,
Err(CodeModeError::Conflict)
@@ -451,7 +516,7 @@ async fn edit_checks_saved_revision_and_draft_bounds_and_dismiss_does_not_execut
row.id,
edit(
changed.revision,
- json!({"subject":"x".repeat(MAX_DRAFT_BYTES)})
+ json!({"subject":"x".repeat(MAX_DRAFT_BYTES), "body":"Hello", "to":[{"email":"[email protected]"}]})
)
)
.await
@@ -470,19 +535,26 @@ async fn edit_checks_saved_revision_and_draft_bounds_and_dismiss_does_not_execut
.await
.unwrap();
let final_row = f.settled(row.id).await;
- assert_eq!(final_row.items[0].status, ReviewItemStatus::Dismissed);
+ assert_eq!(
+ final_row.items.states()[0].status,
+ ReviewItemStatus::Dismissed
+ );
assert!(f.actions.calls.lock().unwrap().is_empty());
}
#[tokio::test]
async fn list_recovers_stale_claim_without_repeating_external_work() {
let f = Fixture::new();
- let mut row = f.create(vec![json!({"subject":"x"})]).await;
- row.items[0].status = ReviewItemStatus::Submitting;
+ let mut row = f
+ .create(vec![
+ json!({"subject":"x", "body":"Hello", "to":[{"email":"[email protected]"}]}),
+ ])
+ .await;
+ row.items.states_mut()[0].status = ReviewItemStatus::Submitting;
row.decision = Some(ReviewDecisionContext {
by: f.actions.owner.to_string(),
via: DecisionVia::Card,
revision: row.revision,
- items: vec![row.items[0].id],
+ items: vec![row.items.states()[0].id],
});
row.updated_at -= STALE_SUBMISSION_MS + 1;
f.store
@@ -491,7 +563,10 @@ async fn list_recovers_stale_claim_without_repeating_external_work() {
.unwrap()
.insert((f.session, row.id.0), row.clone());
let listed = f.service.list(&f.view(), f.execution).await.unwrap();
- assert_eq!(listed[0].items[0].status, ReviewItemStatus::Unknown);
+ assert_eq!(
+ listed[0].items.states()[0].status,
+ ReviewItemStatus::Unknown
+ );
assert!(f.actions.calls.lock().unwrap().is_empty());
let events = f.store.2.lock().unwrap();
assert_eq!(events.len(), 1);
@@ -503,7 +578,11 @@ async fn list_recovers_stale_claim_without_repeating_external_work() {
#[tokio::test]
async fn read_and_list_never_cross_session_scope_and_creation_is_bounded() {
let f = Fixture::new();
- let row = f.create(vec![json!({"subject":"x"})]).await;
+ let row = f
+ .create(vec![
+ json!({"subject":"x", "body":"Hello", "to":[{"email":"[email protected]"}]}),
+ ])
+ .await;
let other = EntityAccessReceipt::dangerously_assert_authenticated_user(
f.actions.owner.clone(),
&macro_uuid::generate_uuid_v7().to_string(),
@@ -520,25 +599,188 @@ async fn read_and_list_never_cross_session_scope_and_creation_is_bounded() {
.unwrap()
.is_empty()
);
- for drafts in [
- vec![],
- vec![json!({"subject":"x"}); 101],
- vec![json!({"subject":"x".repeat(MAX_DRAFT_BYTES)})],
- vec![json!({"wrong":"shape"})],
+ let oversized = f.input(
+ "email",
+ vec![json!({"subject":"x".repeat(MAX_DRAFT_BYTES), "body":"Hello", "to":[{"email":"[email protected]"}]}); 9],
+ );
+ assert!(
+ f.service
+ .create(&f.edit(), &f.actions.owner, oversized)
+ .await
+ .is_err()
+ );
+ let one_oversized_draft = f.input(
+ "email",
+ vec![json!({"subject":"x".repeat(MAX_DRAFT_BYTES), "body":"Hello", "to":[{"email":"[email protected]"}]})],
+ );
+ assert!(
+ f.service
+ .create(&f.edit(), &f.actions.owner, one_oversized_draft)
+ .await
+ .is_err()
+ );
+}
+
+#[tokio::test]
+async fn an_import_review_keeps_the_source_it_was_presented_with() {
+ let f = Fixture::new();
+ let row = f
+ .service
+ .create(
+ &f.edit(),
+ &f.actions.owner,
+ f.input("import", vec![json!({"source":"notion"})]),
+ )
+ .await
+ .unwrap();
+ let item = row.items.states()[0].id;
+ let edit = |source| ReviewDecision::Edit {
+ revision: row.revision,
+ item,
+ draft: Box::new(ReviewDraft::Import(ImportDraft {
+ source,
+ excluded: vec![],
+ shared: vec![],
+ personal: vec![],
+ })),
+ };
+
+ assert!(matches!(
+ f.service
+ .decide(
+ &f.edit(),
+ &f.actions.owner,
+ row.id,
+ edit(ImportReviewSource::Jira)
+ )
+ .await,
+ Err(CodeModeError::Invalid(_))
+ ));
+ f.service
+ .decide(
+ &f.edit(),
+ &f.actions.owner,
+ row.id,
+ edit(ImportReviewSource::Notion),
+ )
+ .await
+ .unwrap();
+}
+
+#[test]
+fn decoding_a_review_is_its_validation_and_errors_name_only_the_location() {
+ let email = json!({"subject":"Hi", "body":"Hello", "to":[{"email":"[email protected]"}]});
+ let decoded = decode::<CreateReview>(
+ &serde_json::to_vec(&json!({"title":"Emails", "kind":"email", "drafts":[email]})).unwrap(),
+ )
+ .unwrap();
+ assert_eq!(decoded.drafts.kind(), ReviewKind::Email);
+
+ for input in [
+ json!({"title":"Emails", "kind":"email", "drafts":[]}),
+ json!({"title":"Emails", "kind":"email", "drafts":vec![email.clone(); 101]}),
+ json!({"title":" ", "kind":"email", "drafts":[email]}),
+ json!({"title":"Emails", "kind":"email", "drafts":[{"subject":"missing body"}]}),
+ json!({"title":"Events", "kind":"calendar", "drafts":[{"title":"missing time"}]}),
+ json!({"title":"Import", "kind":"import", "drafts":[{"source":"notion"}, {"source":"jira"}]}),
+ json!({"title":"Import", "kind":"import", "drafts":[{"source":"slack"}]}),
+ json!({"title":"Import", "kind":"import", "drafts":[{"source":"notion", "write":"everything"}]}),
] {
assert!(
- f.service
- .create(&f.edit(), &f.actions.owner, f.input(drafts))
- .await
- .is_err()
+ decode::<CreateReview>(&serde_json::to_vec(&input).unwrap()).is_err(),
+ "{input}"
);
}
+
+ let secret = "not-an-address-secret";
+ let Err(CodeModeError::Invalid(message)) = decode::<CreateReview>(
+ &serde_json::to_vec(&json!({
+ "title":"Emails",
+ "kind":"email",
+ "drafts":[{"subject":"Hi", "body":"Hello", "to":[{"email":secret}]}]
+ }))
+ .unwrap(),
+ ) else {
+ panic!("an invalid address must not decode");
+ };
+ assert!(!message.contains(secret), "{message}");
+}
+
+#[test]
+fn an_import_review_keeps_its_source_and_owner_choices() {
+ for source in ["notion", "linear", "jira"] {
+ let input = json!({
+ "title":"Import",
+ "kind":"import",
+ "drafts":[{
+ "source": source,
+ "excluded": ["01a15623-f76d-7ea0-955d-a9ecb91a520e"],
+ "shared": ["01a15623-f76d-7ea0-955d-a9ecb91a520f"],
+ "personal": ["01a15623-f76d-7ea0-955d-a9ecb91a5210"]
+ }]
+ });
+ let decoded = decode::<CreateReview>(&serde_json::to_vec(&input).unwrap()).unwrap();
+ assert_eq!(
+ serde_json::to_value(&decoded).unwrap()["drafts"],
+ input["drafts"]
+ );
+ }
+}
+
+#[tokio::test]
+async fn an_edit_must_match_the_review_kind_and_a_submit_needs_a_complete_draft() {
+ let f = Fixture::new();
+ let row = f
+ .create(vec![json!({"subject":"Hi", "body":"Hello", "to":[]})])
+ .await;
+ let item = row.items.states()[0].id;
+ assert!(matches!(
+ f.service
+ .decide(
+ &f.edit(),
+ &f.actions.owner,
+ row.id,
+ ReviewDecision::Edit {
+ revision: row.revision,
+ item,
+ draft: Box::new(ReviewDraft::Import(ImportDraft {
+ source: ImportReviewSource::Notion,
+ excluded: vec![],
+ shared: vec![],
+ personal: vec![],
+ })),
+ },
+ )
+ .await,
+ Err(CodeModeError::Invalid(_))
+ ));
+
+ let Err(CodeModeError::Invalid(message)) = f
+ .service
+ .decide(
+ &f.edit(),
+ &f.actions.owner,
+ row.id,
+ ReviewDecision::Submit {
+ revision: row.revision,
+ items: vec![],
+ },
+ )
+ .await
+ else {
+ panic!("a draft without recipients cannot be sent");
+ };
+ assert_eq!(message, "Add at least one recipient.");
+ let unsaved = f.store.get(f.session, row.id).await.unwrap();
+ assert_eq!(unsaved.revision, row.revision);
+ assert_eq!(unsaved.items.states()[0].status, ReviewItemStatus::Pending);
+ assert!(f.actions.calls.lock().unwrap().is_empty());
}
#[tokio::test]
async fn standalone_presentation_completes_without_approval_or_external_dispatch() {
let f = Fixture::new();
- let mut input = f.input(vec![json!({"subject":"Approve this proposal?"})]);
+ let mut input = f.input("email", vec![json!({"subject":"Approve this proposal?", "body":"Hello", "to":[{"email":"[email protected]"}]})]);
input.execution_id = None;
f.actions.block_actions.store(true, Ordering::SeqCst);
let row = tokio::time::timeout(
@@ -550,7 +792,7 @@ async fn standalone_presentation_completes_without_approval_or_external_dispatch
.unwrap();
assert!(row.execution_id.is_none());
assert!(row.presented_at.is_some());
- assert_eq!(row.items[0].status, ReviewItemStatus::Pending);
+ assert_eq!(row.items.states()[0].status, ReviewItemStatus::Pending);
assert!(f.actions.calls.lock().unwrap().is_empty());
assert!(f.store.2.lock().unwrap().is_empty());
assert_eq!(*f.actions.presentations.lock().unwrap(), vec![row.id]);
@@ -567,7 +809,7 @@ async fn interrupted_presentation_preserves_review_and_retries_same_identity() {
.create(
&f.edit(),
&f.actions.owner,
- f.input(vec![json!({"subject":"Which?"})])
+ f.input("email", vec![json!({"subject":"Which?", "body":"Hello", "to":[{"email":"[email protected]"}]})])
)
.await
.is_err()
@@ -605,7 +847,10 @@ async fn native_presentation_checks_authenticated_and_current_owner() {
let f = Fixture::new();
let mut session = agent_session::testing::test_agent_session(f.session);
// The test session's owner differs from the authoritative review owner.
- let mut input = f.input(vec![json!({"subject":"Which?"})]);
+ let mut input = f.input(
+ "email",
+ vec![json!({"subject":"Which?", "body":"Hello", "to":[{"email":"[email protected]"}]})],
+ );
input.execution_id = None;
assert!(matches!(
f.service
@@ -642,7 +887,11 @@ fn questions_use_acp_instead_of_the_saved_review_contract() {
#[tokio::test]
async fn a_system_turn_cannot_approve_even_with_owner_credentials() {
let f = Fixture::new();
- let row = f.create(vec![json!({"subject":"x"})]).await;
+ let row = f
+ .create(vec![
+ json!({"subject":"x", "body":"Hello", "to":[{"email":"[email protected]"}]}),
+ ])
+ .await;
*f.actions.prompter.lock().unwrap() = Some(TurnPrompter {
action_id: agent_runtime_protocol::domain::action::AgentActionId::mint(),
user: Some(f.actions.owner.clone()),
@@ -666,7 +915,10 @@ async fn a_system_turn_cannot_approve_even_with_owner_credentials() {
.await
.unwrap();
let settled = f.settled(row.id).await;
- assert_eq!(settled.items[0].status, ReviewItemStatus::Completed);
+ assert_eq!(
+ settled.items.states()[0].status,
+ ReviewItemStatus::Completed
+ );
let events = f.store.2.lock().unwrap();
assert_eq!(events.len(), 2);
assert!(events.iter().all(|event| event.wake));
@@ -678,8 +930,7 @@ async fn a_system_turn_cannot_approve_even_with_owner_credentials() {
#[tokio::test]
async fn a_started_import_waits_quietly_for_its_write_to_settle() {
let f = Fixture::new();
- let mut input = f.input(vec![json!({"subject":"plan"})]);
- input.kind = ReviewKind::Import;
+ let input = f.input("import", vec![json!({"source":"notion"})]);
let row = f
.service
.create(&f.edit(), &f.actions.owner, input)
@@ -700,7 +951,10 @@ async fn a_started_import_waits_quietly_for_its_write_to_settle() {
.unwrap();
let started = f.settled(row.id).await;
- assert_eq!(started.items[0].status, ReviewItemStatus::Completed);
+ assert_eq!(
+ started.items.states()[0].status,
+ ReviewItemStatus::Completed
+ );
let events = f.store.2.lock().unwrap();
assert_eq!(events.len(), 1);
assert!(matches!(
@@ -713,8 +967,8 @@ async fn a_started_import_waits_quietly_for_its_write_to_settle() {
#[tokio::test]
async fn an_import_that_could_not_start_settles_and_wakes() {
let f = Fixture::new();
- let mut input = f.input(vec![json!({"subject":"plan", "fail": true})]);
- input.kind = ReviewKind::Import;
+ f.actions.fail_import.store(true, Ordering::SeqCst);
+ let input = f.input("import", vec![json!({"source":"notion"})]);
let row = f
.service
.create(&f.edit(), &f.actions.owner, input)
@@ -735,7 +989,7 @@ async fn an_import_that_could_not_start_settles_and_wakes() {
.unwrap();
let ended = f.settled(row.id).await;
- assert_eq!(ended.items[0].status, ReviewItemStatus::Unknown);
+ assert_eq!(ended.items.states()[0].status, ReviewItemStatus::Unknown);
let events = f.store.2.lock().unwrap();
assert_eq!(events.len(), 2);
assert!(!events[0].wake);
@@ -749,8 +1003,7 @@ async fn an_import_that_could_not_start_settles_and_wakes() {
#[tokio::test]
async fn dismissing_an_import_wakes_the_session() {
let f = Fixture::new();
- let mut input = f.input(vec![json!({"subject":"plan"})]);
- input.kind = ReviewKind::Import;
+ let input = f.input("import", vec![json!({"source":"notion"})]);
let row = f
.service
.create(&f.edit(), &f.actions.owner, input)
@@ -790,11 +1043,11 @@ async fn requester_reviews_are_decided_and_executed_only_with_their_account() {
.create(
&access,
&requester,
- f.input(vec![json!({"subject":"requester draft"})]),
+ f.input("email", vec![json!({"subject":"requester draft", "body":"Hello", "to":[{"email":"[email protected]"}]})]),
)
.await
.unwrap();
- assert_eq!(row.acting_user.as_ref(), Some(&requester));
+ assert_eq!(row.acting_user, requester);
let decision = ReviewDecision::Submit {
revision: row.revision,
items: vec![],
@@ -810,7 +1063,10 @@ async fn requester_reviews_are_decided_and_executed_only_with_their_account() {
.await
.unwrap();
let settled = f.settled(row.id).await;
- assert_eq!(settled.items[0].status, ReviewItemStatus::Completed);
+ assert_eq!(
+ settled.items.states()[0].status,
+ ReviewItemStatus::Completed
+ );
assert_eq!(
*f.actions.actors.lock().unwrap(),
vec![requester.to_string()]
@@ -820,7 +1076,11 @@ async fn requester_reviews_are_decided_and_executed_only_with_their_account() {
#[tokio::test]
async fn a_chat_submit_waits_until_the_review_is_approvable() {
let f = Fixture::new();
- let row = f.create(vec![json!({"subject":"x"})]).await;
+ let row = f
+ .create(vec![
+ json!({"subject":"x", "body":"Hello", "to":[{"email":"[email protected]"}]}),
+ ])
+ .await;
*f.actions.prompter.lock().unwrap() = Some(TurnPrompter {
action_id: agent_runtime_protocol::domain::action::AgentActionId::mint(),
user: Some(f.actions.owner.clone()),
@@ -840,7 +1100,7 @@ async fn a_chat_submit_waits_until_the_review_is_approvable() {
));
let unsaved = f.store.get(f.session, row.id).await.unwrap();
assert_eq!(unsaved.revision, row.revision);
- assert_eq!(unsaved.items[0].status, ReviewItemStatus::Pending);
+ assert_eq!(unsaved.items.states()[0].status, ReviewItemStatus::Pending);
assert!(f.actions.calls.lock().unwrap().is_empty());
f.actions.approvable.store(true, Ordering::SeqCst);
@@ -851,7 +1111,10 @@ async fn a_chat_submit_waits_until_the_review_is_approvable() {
.unwrap();
assert_eq!(approved.decision.unwrap().via, DecisionVia::Chat);
let settled = f.settled(row.id).await;
- assert_eq!(settled.items[0].status, ReviewItemStatus::Completed);
+ assert_eq!(
+ settled.items.states()[0].status,
+ ReviewItemStatus::Completed
+ );
}
fn a_view() -> Value {
diff --git a/crates/agent_code_mode/src/inbound/axum_router.rs b/crates/agent_code_mode/src/inbound/axum_router.rs
index b2a5cad582..c594039523 100644
--- a/crates/agent_code_mode/src/inbound/axum_router.rs
+++ b/crates/agent_code_mode/src/inbound/axum_router.rs
@@ -2,6 +2,7 @@
use crate::domain::{CodeModeError, ExecutionId, ExecutionRecord, SessionCodeMode, reviews::*};
use axum::{
Json, Router,
+ body::Bytes,
extract::{FromRef, Path, State},
http::StatusCode,
response::{IntoResponse, Response},
@@ -147,8 +148,9 @@ pub async fn create_review<Access: EntityAccessService, Auth: MacroAuthorization
access: AgentSessionAccessLevelExtractor<EditAccessLevel, Access, Auth>,
caller: MacroAuthorizationExtractor<Auth, ActingUser>,
State(state): State<CodeExecutionRouterState<Access, Auth>>,
- Json(input): Json<CreateReview>,
+ body: Bytes,
) -> Result<Json<ReviewRecord>, CodeExecutionApiError> {
+ let input: CreateReview = decode(&body).map_err(CodeExecutionApiError)?;
state
.reviews
.create(
@@ -214,8 +216,9 @@ pub async fn decide_review<Access: EntityAccessService, Auth: MacroAuthorization
caller: MacroAuthorizationExtractor<Auth, UserOnly>,
State(state): State<CodeExecutionRouterState<Access, Auth>>,
Path((_session, id)): Path<(Uuid, Uuid)>,
- Json(decision): Json<ReviewDecision>,
+ body: Bytes,
) -> Result<Json<ReviewRecord>, CodeExecutionApiError> {
+ let decision: ReviewDecision = decode(&body).map_err(CodeExecutionApiError)?;
state
.reviews
.decide(
diff --git a/crates/agent_code_mode/src/inbound/reviews.rs b/crates/agent_code_mode/src/inbound/reviews.rs
index a35396296d..15385bc7d6 100644
--- a/crates/agent_code_mode/src/inbound/reviews.rs
+++ b/crates/agent_code_mode/src/inbound/reviews.rs
@@ -58,7 +58,9 @@ impl AsyncTool<ReviewToolContext> for PresentReview {
description: error.to_string(),
internal_error: anyhow::anyhow!(error.to_string()),
})?;
- Ok(json!({"reviewId": record.id, "kind": record.kind, "message": "Presented to the user"}))
+ Ok(
+ json!({"reviewId": record.id, "kind": record.kind(), "message": "Presented to the user"}),
+ )
}
}
diff --git a/crates/agent_code_mode/src/outbound/reviews/test.rs b/crates/agent_code_mode/src/outbound/reviews/test.rs
index 399e65eb4a..3b3d36a8ec 100644
--- a/crates/agent_code_mode/src/outbound/reviews/test.rs
+++ b/crates/agent_code_mode/src/outbound/reviews/test.rs
@@ -38,26 +38,27 @@ async fn review_revision_claim_is_atomic_and_session_deletion_removes_reviews(po
pool.clone(),
)),
);
- let mut record = ReviewRecord {
- id: ReviewId(macro_uuid::generate_uuid_v7()),
- session_id: session,
- acting_user: None,
- execution_id: Some(execution),
- presented_at: None,
- kind: ReviewKind::Email,
- title: "Pick one".into(),
- revision: 0,
- updated_at: 0,
- decision: None,
- items: vec![ReviewItem {
- id: macro_uuid::generate_uuid_v7(),
- draft: json!({"subject":"Which?"}),
- edited: false,
- status: ReviewItemStatus::Pending,
- result: None,
- error: None,
- }],
- };
+ let mut record: ReviewRecord = serde_json::from_value(json!({
+ "id": macro_uuid::generate_uuid_v7(),
+ "sessionId": session.as_uuid(),
+ "actingUser": "macro|[email protected]",
+ "executionId": execution,
+ "presentedAt": null,
+ "title": "Pick one",
+ "revision": 0,
+ "updatedAt": 0,
+ "decision": null,
+ "kind": "email",
+ "items": [{
+ "id": macro_uuid::generate_uuid_v7(),
+ "draft": {"subject":"Which?", "body":"Hello", "to":[{"email":"[email protected]"}]},
+ "edited": false,
+ "status": "pending",
+ "result": null,
+ "error": null
+ }]
+ }))
+ .unwrap();
store.create(&record, 100).await.unwrap();
let mut second = record.clone();
second.id = ReviewId(macro_uuid::generate_uuid_v7());
@@ -96,7 +97,7 @@ async fn review_revision_claim_is_atomic_and_session_deletion_removes_reviews(po
.is_none()
);
record.revision = 1;
- record.items[0].status = ReviewItemStatus::Submitting;
+ record.items.states_mut()[0].status = ReviewItemStatus::Submitting;
let notification = agent_session::domain::notifications::PendingNotification::new(
agent_session::domain::notifications::ProduceNotification {
session_id: session,
@@ -144,7 +145,10 @@ async fn review_revision_claim_is_atomic_and_session_deletion_removes_reviews(po
.await
.unwrap();
assert_eq!(persisted.revision, 1);
- assert_eq!(persisted.items[0].status, ReviewItemStatus::Submitting);
+ assert_eq!(
+ persisted.items.states()[0].status,
+ ReviewItemStatus::Submitting
+ );
sqlx::raw_sql("DELETE FROM agent_session WHERE id = '00000000-0000-0000-0000-000000000001'")
.execute(&pool)
.await
diff --git a/crates/calendar_events/Cargo.toml b/crates/calendar_events/Cargo.toml
index 16178e5bde..3e3e84fe03 100644
--- a/crates/calendar_events/Cargo.toml
+++ b/crates/calendar_events/Cargo.toml
@@ -8,7 +8,14 @@ version = "0.1.0"
default = []
outlook = ["dep:tokio"]
# The AI toolset adapter exposing calendar CRUD to agents.
-ai_tools = ["dep:ai_toolset", "dep:anyhow", "dep:async-trait", "dep:schemars"]
+ai_tools = [
+ "dep:ai_toolset",
+ "dep:anyhow",
+ "dep:async-trait",
+ "dep:email_validator",
+ "dep:schemars",
+ "dep:specta",
+]
# The meeting-link adapter that mints Macro calls through the call domain
# service, for hosts that compose both calendars and calls.
call-meetings = ["dep:call", "dep:macro_user_id"]
@@ -39,6 +46,7 @@ anyhow = { workspace = true, optional = true }
async-trait = { workspace = true, optional = true }
aws-sdk-sqs = { workspace = true, optional = true }
axum = { workspace = true, optional = true }
+email_validator = { path = "../email_validator", optional = true }
call = { path = "../call", default-features = false, features = [
"ports",
], optional = true }
@@ -59,6 +67,7 @@ macro_event_broker = { path = "../macro_event_broker", default-features = false
macro_event_topics = { path = "../macro_event_topics" }
rootcause = { workspace = true }
schemars = { workspace = true, optional = true }
+specta = { workspace = true, optional = true, features = ["chrono", "uuid"] }
serde = { workspace = true }
serde_json = { workspace = true }
sqlx = { workspace = true, optional = true }
diff --git a/crates/calendar_events/src/domain/capabilities.rs b/crates/calendar_events/src/domain/capabilities.rs
index 577d106762..bcf8b15176 100644
--- a/crates/calendar_events/src/domain/capabilities.rs
+++ b/crates/calendar_events/src/domain/capabilities.rs
@@ -10,7 +10,7 @@ use super::models::{CalendarAttendee, CalendarEvent, CalendarProvider, EventStat
/// do. Google omits a switch from the payload while it holds its default.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
-#[cfg_attr(feature = "ai_tools", derive(schemars::JsonSchema))]
+#[cfg_attr(feature = "ai_tools", derive(schemars::JsonSchema, specta::Type))]
#[serde(rename_all = "camelCase")]
pub struct GuestPolicy {
/// Whether guests may change the event, including its guest list.
diff --git a/crates/calendar_events/src/inbound/toolset.rs b/crates/calendar_events/src/inbound/toolset.rs
index ac14b56df1..dabba5a1dd 100644
--- a/crates/calendar_events/src/inbound/toolset.rs
+++ b/crates/calendar_events/src/inbound/toolset.rs
@@ -22,6 +22,7 @@ use std::sync::Arc;
use ai_toolset::{AsyncToolCollection, ToolCallError};
use chrono::NaiveDate;
use chrono::{DateTime, Utc};
+use email_validator::EmailAddress;
use rootcause::compat::boxed_error::IntoBoxedError;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
@@ -167,7 +168,7 @@ where
}
/// The mutually exclusive time shape supplied to calendar tools.
-#[derive(Debug, Clone, PartialEq, Deserialize, JsonSchema)]
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema, specta::Type)]
#[serde(rename_all = "camelCase", tag = "kind")]
pub enum EventTimeInput {
/// A clock-time event with absolute instants.
@@ -179,6 +180,7 @@ pub enum EventTimeInput {
ends_at: DateTime<Utc>,
/// IANA time zone the event was scheduled in (e.g.
/// America/New_York). Recurring events expand in this zone.
+ #[serde(default)]
time_zone: Option<String>,
},
/// An all-day event spanning whole local dates.
@@ -216,12 +218,12 @@ impl From<EventTimeInput> for EventTime {
}
/// An attendee supplied to a calendar tool.
-#[derive(Debug, Clone, PartialEq, Eq, Deserialize, JsonSchema)]
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, specta::Type)]
#[serde(rename_all = "camelCase")]
pub struct AttendeeInput {
/// Attendee email address.
#[schemars(description = "The attendee's email address.")]
- pub email: String,
+ pub email: EmailAddress,
/// Whether attendance is optional.
#[schemars(
description = "Whether attendance is optional for this attendee. Defaults to required."
@@ -233,7 +235,7 @@ pub struct AttendeeInput {
impl From<AttendeeInput> for CalendarAttendeeInput {
fn from(input: AttendeeInput) -> Self {
Self {
- email: input.email,
+ email: input.email.into_inner(),
is_optional: input.is_optional,
response_status: None,
}
@@ -241,7 +243,7 @@ impl From<AttendeeInput> for CalendarAttendeeInput {
}
/// One reminder override supplied to a calendar tool.
-#[derive(Debug, Clone, PartialEq, Eq, Deserialize, JsonSchema)]
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, specta::Type)]
#[serde(rename_all = "camelCase")]
pub struct EventReminderOverrideInput {
/// Provider reminder method. `popup` creates a Macro notification.
@@ -260,7 +262,7 @@ impl From<EventReminderOverrideInput> for EventReminderOverride {
}
/// Reminder configuration supplied when creating a calendar event.
-#[derive(Debug, Clone, PartialEq, Eq, Deserialize, JsonSchema)]
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, specta::Type)]
#[serde(rename_all = "camelCase")]
pub struct EventRemindersInput {
/// Whether the selected calendar's default reminders should apply.
@@ -280,7 +282,9 @@ impl From<EventRemindersInput> for EventReminders {
}
/// The kind of event a create tool call makes.
-#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize, JsonSchema)]
+#[derive(
+ Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize, JsonSchema, specta::Type,
+)]
#[serde(rename_all = "snake_case")]
pub enum CalendarEventTypeInput {
/// A regular calendar event.
@@ -293,7 +297,7 @@ pub enum CalendarEventTypeInput {
}
/// How an out-of-office event handles conflicting invitations.
-#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, JsonSchema)]
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema, specta::Type)]
#[serde(rename_all = "snake_case")]
pub enum AutoDeclineModeInput {
/// Leave conflicting invitations alone.
@@ -315,7 +319,9 @@ impl From<AutoDeclineModeInput> for OutOfOfficeAutoDeclineMode {
}
/// Out-of-office decline behavior supplied to the calendar tools.
-#[derive(Debug, Clone, PartialEq, Eq, Default, Deserialize, JsonSchema)]
+#[derive(
+ Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize, JsonSchema, specta::Type,
+)]
#[serde(rename_all = "camelCase")]
pub struct OutOfOfficeInput {
/// How conflicting invitations are handled. Defaults to declining nothing,
@@ -337,7 +343,7 @@ impl From<OutOfOfficeInput> for OutOfOfficeProperties {
}
/// An attendee of a calendar event, as returned by calendar tools.
-#[derive(Debug, Serialize, JsonSchema)]
+#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, specta::Type)]
#[serde(rename_all = "camelCase")]
pub struct ToolEventAttendee {
/// Attendee email address.
@@ -351,7 +357,7 @@ pub struct ToolEventAttendee {
}
/// A calendar event as returned by the create and update tools.
-#[derive(Debug, Serialize, JsonSchema)]
+#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, specta::Type)]
#[serde(rename_all = "camelCase")]
pub struct ToolCalendarEvent {
/// Macro calendar event id, used by UpdateCalendarEvent and
@@ -381,6 +387,7 @@ pub struct ToolCalendarEvent {
/// Attendees, capped at 20; `attendee_count` has the full number.
pub attendees: Vec<ToolEventAttendee>,
/// Total number of attendees.
+ #[specta(type = u32)]
pub attendee_count: usize,
/// Organizer email address, when known.
pub organizer_email: Option<String>,
@@ -406,7 +413,7 @@ pub struct ToolCalendarEvent {
}
/// What the user is on one copy of an event, through the inbox holding it.
-#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, JsonSchema)]
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema, specta::Type)]
#[serde(rename_all = "snake_case")]
pub enum ToolEventRole {
/// The inbox organizes the event, or the event has no guests and is the
diff --git a/crates/calendar_events/src/inbound/toolset/create_calendar_event.rs b/crates/calendar_events/src/inbound/toolset/create_calendar_event.rs
index 8f6e8f6224..fc644058bf 100644
--- a/crates/calendar_events/src/inbound/toolset/create_calendar_event.rs
+++ b/crates/calendar_events/src/inbound/toolset/create_calendar_event.rs
@@ -7,7 +7,7 @@ use ai_toolset::{
use async_trait::async_trait;
use rootcause::compat::boxed_error::IntoBoxedError;
use schemars::JsonSchema;
-use serde::Deserialize;
+use serde::{Deserialize, Serialize};
use super::{
AttendeeInput, CalendarEventTypeInput, CalendarLabels, CalendarToolContext,
@@ -21,7 +21,7 @@ use crate::domain::{
};
/// Create a calendar event.
-#[derive(Debug, Deserialize, JsonSchema, Clone)]
+#[derive(Debug, Serialize, Deserialize, JsonSchema, specta::Type, Clone)]
#[serde(rename_all = "camelCase")]
#[schemars(
title = "CreateCalendarEvent",
diff --git a/crates/calendar_events/src/inbound/toolset/test.rs b/crates/calendar_events/src/inbound/toolset/test.rs
index cf9c893617..a6ea640ee7 100644
--- a/crates/calendar_events/src/inbound/toolset/test.rs
+++ b/crates/calendar_events/src/inbound/toolset/test.rs
@@ -615,7 +615,7 @@ async fn create_converts_input_into_a_domain_draft() {
description: Some("Quarterly".to_string()),
location: None,
attendees: vec![AttendeeInput {
- email: "[email protected]".to_string(),
+ email: EmailAddress::try_new("[email protected]".to_string()).unwrap(),
is_optional: true,
}],
recurrence_lines: vec!["RRULE:FREQ=WEEKLY".to_string()],
@@ -775,7 +775,7 @@ fn macro_call_tool() -> CreateCalendarEvent {
description: Some("<p>Agenda</p>".to_string()),
location: None,
attendees: vec![AttendeeInput {
- email: "[email protected]".to_string(),
+ email: EmailAddress::try_new("[email protected]".to_string()).unwrap(),
is_optional: false,
}],
recurrence_lines: Vec::new(),
@@ -949,7 +949,7 @@ async fn update_converts_input_into_a_domain_patch() {
location: None,
time: None,
attendees: Some(vec![AttendeeInput {
- email: "[email protected]".to_string(),
+ email: EmailAddress::try_new("[email protected]".to_string()).unwrap(),
is_optional: false,
}]),
recurrence_lines: None,
@@ -1247,7 +1247,7 @@ async fn update_answers_after_applying_the_patch() {
location: None,
time: None,
attendees: Some(vec![AttendeeInput {
- email: "[email protected]".to_string(),
+ email: EmailAddress::try_new("[email protected]".to_string()).unwrap(),
is_optional: false,
}]),
recurrence_lines: None,
diff --git a/crates/code_execution/src/outbound/deno/sdk.mjs b/crates/code_execution/src/outbound/deno/sdk.mjs
index 4e582733f4..d150f3060e 100644
--- a/crates/code_execution/src/outbound/deno/sdk.mjs
+++ b/crates/code_execution/src/outbound/deno/sdk.mjs
@@ -1,62 +1,62 @@
// Generated by packages/code-mode-sdk/scripts/generate.ts.
-async function cO($,O,j){if(!Number.isInteger(O)||O<1)throw RangeError(`concurrency limit must be a positive integer, got ${O}`);let x=Array($.length),S=0,K=async()=>{while(S<$.length){let X=S;S+=1,x[X]=await j($[X])}},Z=Array.from({length:Math.min(O,$.length)},K);return await Promise.all(Z),x}class W${loader;value;inflight;constructor($,O){this.loader=$;this.value=O}get(){if(this.value!==void 0)return Promise.resolve(this.value);return this.inflight??=this.loader().then(($)=>{return this.value=$,$}),this.inflight}peek(){return this.value}clear(){this.value=void 0,this.inflight=void 0}}async function*c($){let O;do{let j=await $(O),x=j.nextCursor??void 0;if(O!==void 0&&x!==void 0&&JSON.stringify(x)===JSON.stringify(O))throw Error("Pagination cursor did not advance");yield*j.items,O=x}while(O!==void 0)}var X$=Symbol.for("@ts-pattern/matcher"),a1=Symbol.for("@ts-pattern/isVariadic");var u0=($)=>Boolean($&&typeof $=="object"),Bj=($)=>$&&!!$[X$],s=($,O,j)=>{if(Bj($)){let x=$[X$](),{matched:S,selections:K}=x.match(O);return S&&K&&Object.keys(K).forEach((Z)=>j(Z,K[Z])),S}if(u0($)){if(!u0(O))return!1;if(Array.isArray($)){if(!Array.isArray(O))return!1;let x=[],S=[],K=[];for(let Z of $.keys()){let X=$[Z];Bj(X)&&X[a1]?K.push(X):K.length?S.push(X):x.push(X)}if(K.length){if(K.length>1)throw Error("Pattern error: Using `...P.array(...)` several times in a single pattern is not allowed.");if(O.length<x.length+S.length)return!1;let Z=O.slice(0,x.length),X=S.length===0?[]:O.slice(-S.length),Y=O.slice(x.length,S.length===0?1/0:-S.length);return x.every((L,G)=>s(L,Z[G],j))&&S.every((L,G)=>s(L,X[G],j))&&(K.length===0||s(K[0],Y,j))}return $.length===O.length&&$.every((Z,X)=>s(Z,O[X],j))}return Reflect.ownKeys($).every((x)=>{let S=$[x];return((x in O)||Bj(K=S)&&K[X$]().matcherType==="optional")&&s(S,O[x],j);var K})}return Object.is(O,$)},Z$=($)=>{var O,j,x;return u0($)?Bj($)?(O=(j=(x=$[X$]()).getSelectionKeys)==null?void 0:j.call(x))!=null?O:[]:Array.isArray($)?dO($,Z$):dO(Object.values($),Z$):[]},dO=($,O)=>$.reduce((j,x)=>j.concat(O(x)),[]);function l7(...$){if($.length===1){let[O]=$;return(j)=>s(O,j,()=>{})}if($.length===2){let[O,j]=$;return s(O,j,()=>{})}throw Error(`isMatching wasn't given the right number of arguments: expected 1 or 2, received ${$.length}.`)}function e($){return Object.assign($,{optional:()=>l0($),and:(O)=>l($,O),or:(O)=>i1($,O),select:(O)=>O===void 0?lO($):lO(O,$)})}function c0($){return Object.assign(((O)=>Object.assign(O,{[Symbol.iterator](){let j=0,x=[{value:Object.assign(O,{[a1]:!0}),done:!1},{done:!0,value:void 0}];return{next:()=>{var S;return(S=x[j++])!=null?S:x.at(-1)}}}}))($),{optional:()=>c0(l0($)),select:(O)=>c0(O===void 0?lO($):lO(O,$))})}function l0($){return e({[X$]:()=>({match:(O)=>{let j={},x=(S,K)=>{j[S]=K};return O===void 0?(Z$($).forEach((S)=>x(S,void 0)),{matched:!0,selections:j}):{matched:s($,O,x),selections:j}},getSelectionKeys:()=>Z$($),matcherType:"optional"})})}var r7=($,O)=>{for(let j of $)if(!O(j))return!1;return!0},p7=($,O)=>{for(let[j,x]of $.entries())if(!O(x,j))return!1;return!0},a7=($,O)=>{let j=Reflect.ownKeys($);for(let x of j)if(!O(x,$[x]))return!1;return!0};function l(...$){return e({[X$]:()=>({match:(O)=>{let j={},x=(S,K)=>{j[S]=K};return{matched:$.every((S)=>s(S,O,x)),selections:j}},getSelectionKeys:()=>dO($,Z$),matcherType:"and"})})}function i1(...$){return e({[X$]:()=>({match:(O)=>{let j={},x=(S,K)=>{j[S]=K};return dO($,Z$).forEach((S)=>x(S,void 0)),{matched:$.some((S)=>s(S,O,x)),selections:j}},getSelectionKeys:()=>dO($,Z$),matcherType:"or"})})}function u($){return{[X$]:()=>({match:(O)=>({matched:Boolean($(O))})})}}function lO(...$){let O=typeof $[0]=="string"?$[0]:void 0,j=$.length===2?$[1]:typeof $[0]=="string"?void 0:$[0];return e({[X$]:()=>({match:(x)=>{let S={[O!=null?O:"@ts-pattern/anonymous-select-key"]:x};return{matched:j===void 0||s(j,x,(K,Z)=>{S[K]=Z}),selections:S}},getSelectionKeys:()=>[O!=null?O:"@ts-pattern/anonymous-select-key"].concat(j===void 0?[]:Z$(j))})})}function n1($){return!0}function w$($){return typeof $=="number"}function i$($){return typeof $=="string"}function n$($){return typeof $=="bigint"}var s1=e(u(n1)),i7=e(u(n1)),n7=s1,s$=($)=>Object.assign(e($),{startsWith:(O)=>{return s$(l($,(j=O,u((x)=>i$(x)&&x.startsWith(j)))));var j},endsWith:(O)=>{return s$(l($,(j=O,u((x)=>i$(x)&&x.endsWith(j)))));var j},minLength:(O)=>s$(l($,((j)=>u((x)=>i$(x)&&x.length>=j))(O))),length:(O)=>s$(l($,((j)=>u((x)=>i$(x)&&x.length===j))(O))),maxLength:(O)=>s$(l($,((j)=>u((x)=>i$(x)&&x.length<=j))(O))),includes:(O)=>{return s$(l($,(j=O,u((x)=>i$(x)&&x.includes(j)))));var j},regex:(O)=>{return s$(l($,(j=O,u((x)=>i$(x)&&Boolean(x.match(j))))));var j}}),p1=s$(u(i$)),f$=($)=>Object.assign(e($),{between:(O,j)=>f$(l($,((x,S)=>u((K)=>w$(K)&&x<=K&&S>=K))(O,j))),lt:(O)=>f$(l($,((j)=>u((x)=>w$(x)&&x<j))(O))),gt:(O)=>f$(l($,((j)=>u((x)=>w$(x)&&x>j))(O))),lte:(O)=>f$(l($,((j)=>u((x)=>w$(x)&&x<=j))(O))),gte:(O)=>f$(l($,((j)=>u((x)=>w$(x)&&x>=j))(O))),int:()=>f$(l($,u((O)=>w$(O)&&Number.isInteger(O)))),finite:()=>f$(l($,u((O)=>w$(O)&&Number.isFinite(O)))),positive:()=>f$(l($,u((O)=>w$(O)&&O>0))),negative:()=>f$(l($,u((O)=>w$(O)&&O<0)))}),s7=f$(u(w$)),t$=($)=>Object.assign(e($),{between:(O,j)=>t$(l($,((x,S)=>u((K)=>n$(K)&&x<=K&&S>=K))(O,j))),lt:(O)=>t$(l($,((j)=>u((x)=>n$(x)&&x<j))(O))),gt:(O)=>t$(l($,((j)=>u((x)=>n$(x)&&x>j))(O))),lte:(O)=>t$(l($,((j)=>u((x)=>n$(x)&&x<=j))(O))),gte:(O)=>t$(l($,((j)=>u((x)=>n$(x)&&x>=j))(O))),positive:()=>t$(l($,u((O)=>n$(O)&&O>0))),negative:()=>t$(l($,u((O)=>n$(O)&&O<0)))}),t7=t$(u(n$)),e7=e(u(function($){return typeof $=="boolean"})),o7=e(u(function($){return typeof $=="symbol"})),$5=e(u(function($){return $==null})),O5=e(u(function($){return $!=null})),t={__proto__:null,matcher:X$,optional:l0,array:function(...$){return c0({[X$]:()=>({match:(O)=>{if(!Array.isArray(O))return{matched:!1};if($.length===0)return{matched:!0};let j=$[0],x={};if(O.length===0)return Z$(j).forEach((K)=>{x[K]=[]}),{matched:!0,selections:x};let S=(K,Z)=>{x[K]=(x[K]||[]).concat([Z])};return{matched:O.every((K)=>s(j,K,S)),selections:x}},getSelectionKeys:()=>$.length===0?[]:Z$($[0])})})},set:function(...$){return e({[X$]:()=>({match:(O)=>{if(!(O instanceof Set))return{matched:!1};let j={};if(O.size===0)return{matched:!0,selections:j};if($.length===0)return{matched:!0};let x=(K,Z)=>{j[K]=(j[K]||[]).concat([Z])},S=$[0];return{matched:r7(O,(K)=>s(S,K,x)),selections:j}},getSelectionKeys:()=>$.length===0?[]:Z$($[0])})})},map:function(...$){return e({[X$]:()=>({match:(O)=>{if(!(O instanceof Map))return{matched:!1};let j={};if(O.size===0)return{matched:!0,selections:j};let x=(X,Y)=>{j[X]=(j[X]||[]).concat([Y])};if($.length===0)return{matched:!0};var S;if($.length===1)throw Error(`\`P.map\` wasn't given enough arguments. Expected (key, value), received ${(S=$[0])==null?void 0:S.toString()}`);let[K,Z]=$;return{matched:p7(O,(X,Y)=>{let L=s(K,Y,x),G=s(Z,X,x);return L&&G}),selections:j}},getSelectionKeys:()=>$.length===0?[]:[...Z$($[0]),...Z$($[1])]})})},record:function(...$){return e({[X$]:()=>({match:(O)=>{if(O===null||typeof O!="object"||Array.isArray(O))return{matched:!1};var j;if($.length===0)throw Error(`\`P.record\` wasn't given enough arguments. Expected (value) or (key, value), received ${(j=$[0])==null?void 0:j.toString()}`);let x={},S=(X,Y)=>{x[X]=(x[X]||[]).concat([Y])},[K,Z]=$.length===1?[p1,$[0]]:$;return{matched:a7(O,(X,Y)=>{let L=typeof X!="string"||Number.isNaN(Number(X))?null:Number(X),G=L!==null&&s(K,L,S),J=s(K,X,S),I=s(Z,Y,S);return(J||G)&&I}),selections:x}},getSelectionKeys:()=>$.length===0?[]:[...Z$($[0]),...Z$($[1])]})})},intersection:l,union:i1,not:function($){return e({[X$]:()=>({match:(O)=>({matched:!s($,O,()=>{})}),getSelectionKeys:()=>[],matcherType:"not"})})},when:u,select:lO,any:s1,unknown:i7,_:n7,string:p1,number:s7,bigint:t7,boolean:e7,symbol:o7,nullish:$5,nonNullable:O5,instanceOf:function($){return e(u(function(O){return(j)=>j instanceof O}($)))},shape:function($){return e(u(l7($)))}};class t1 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 d0={matched:!1,value:void 0};function k($){return new Lj($,d0)}class Lj{constructor($,O){this.input=void 0,this.state=void 0,this.input=$,this.state=O}with(...$){if(this.state.matched)return this;let O=$[$.length-1],j=[$[0]],x;$.length===3&&typeof $[1]=="function"?x=$[1]:$.length>2&&j.push(...$.slice(1,$.length-1));let S=!1,K={},Z=(Y,L)=>{S=!0,K[Y]=L},X=!j.some((Y)=>s(Y,this.input,Z))||x&&!Boolean(x(this.input))?d0:{matched:!0,value:O(S?"@ts-pattern/anonymous-select-key"in K?K["@ts-pattern/anonymous-select-key"]:K:this.input,this.input)};return new Lj(this.input,X)}when($,O){if(this.state.matched)return this;let j=Boolean($(this.input));return new Lj(this.input,j?{matched:!0,value:O(this.input,this.input)}:d0)}otherwise($){return this.state.matched?this.state.value:$(this.input)}exhaustive($=j5){return this.state.matched?this.state.value:$(this.input)}run(){return this.exhaustive()}returnType(){return this}narrow(){return this}}function j5($){throw new t1($)}class f extends Error{constructor($){super($);this.name="MacroError"}}var e1=500;function x5($){let O=k($).with(t.string,(j)=>j).with({message:t.string},({message:j})=>j).with({error:t.string},({error:j})=>j).otherwise(()=>"").trim();return O.length>e1?`${O.slice(0,e1)}…`:O}class e$ extends f{status;data;constructor($,O){let j=x5(O);super(j?`Macro API error ${$}: ${j}`:`Macro API error ${$}`);this.status=$;this.data=O;this.name="MacroApiError"}}class r0 extends e${constructor($){super(403,$);this.name="MacroForbiddenError"}}function S5($,O){return $===403?new r0(O):new e$($,O)}class E extends f{constructor($){super($);this.name="MacroNotFoundError"}}function Q($){if($.error!==void 0)throw S5($.response?.status??0,$.error);return $.data}class P{client;id;detail;constructor($,O,j){this.client=$;this.id=O;this.detail=new W$(()=>this.fetch(),j)}field($){return async()=>(await this.detail.get())[$]??void 0}mappedField($,O){return async()=>O((await this.detail.get())[$]??void 0)}toJSON(){let $=this.detail.peek();return $===void 0?{id:this.id}:{id:this.id,detail:$}}async mutate($){let O=Q(await $(this.client));return this.detail.clear(),O}}class H$ extends P{async permission(){return Q(await this.client.storage.getEntityPermission({path:{entity_type:this.entityType,entity_id:this.id}}))}async favorite(){return Q(await this.client.storage.addFavorite({body:{entityId:this.id,entityType:this.entityType}})),this}async unfavorite(){return Q(await this.client.storage.removeFavoriteByEntity({path:{entity_type:this.entityType,entity_id:this.id}})),this}}class K$ extends H${propertyReference(){return{entity_type:this.propertyEntityType,entity_id:this.id}}async properties($){let{properties:O}=Q(await this.client.properties.getEntityProperties({path:{entity_type:this.propertyEntityType,entity_id:this.id},query:$?.includeMetadata!==void 0?{include_metadata:$.includeMetadata}:void 0}));return O}async setProperty($,O){Q(await this.client.properties.setEntityProperty({path:{...this.propertyReference(),property_id:$.id},body:{value:O??null}}))}async updatePropertyOptions($){return Q(await this.client.properties.bulkUpdateEntityPropertyOptions({path:this.propertyReference(),body:{properties:$.map((O)=>({property_id:O.property.id,...O.add?{add_option_ids:O.add.map((j)=>j.id)}:{},...O.remove?{remove_option_ids:O.remove.map((j)=>j.id)}:{}}))}}))}async deleteProperty($){Q(await this.client.properties.deleteEntityProperty({path:{entity_property_id:$.property.id}}))}}var Z5={"<":"\\u003c",">":"\\u003e","&":"\\u0026"};function o$($,O){let j=JSON.stringify(O).replace(/[<>&]/g,(x)=>Z5[x]??x);return`<${$}>${j}</${$}>`}function X5($){return typeof $==="object"&&$!==null&&typeof $.toMention==="function"}var K5={toMention:()=>({tag:o$("m-group-mention",{groupAlias:"here"}),mention:{entity_type:"group",entity_id:"here"}})};function Y5($,...O){let j="",x=[];for(let[S,K]of $.entries()){j+=K;let Z=O[S];if(Z===void 0)continue;if(X5(Z)){let X=Z.toMention();j+=X.tag,x.push(X.mention)}else j+=String(Z)}return{content:j,mentions:Q5(x)}}function Q5($){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 P{static byId($,O){return new B$($,O)}static from($,O){return new B$($,O.id,O)}async fetch(){let $=Q(await this.client.storage.listHarnesses()).find((O)=>O.id===this.id);if(!$)throw new E(`Harness ${this.id} is unavailable`);return $}name=this.field("name");connected=this.field("connected");kind=this.field("kind");async delete(){await this.mutate(($)=>$.storage.deleteHarness({path:{harness_id:this.id}}))}}class T$ extends P{static byId($,O){return new T$($,O)}static from($,O){return new T$($,O.bot.id,O)}async fetch(){let $=Q(await this.client.storage.listAgents()).find((O)=>O.bot.id===this.id);if(!$)throw new E(`Agent ${this.id} is unavailable`);return $}name=this.mappedField("bot",($)=>$.name);instructions=this.field("instructions");defaultModel=this.field("default_model");channels=this.mappedField("channel_ids",($)=>$.map((O)=>b.byId(this.client,O)));host=this.mappedField("harness_id",($)=>$?B$.byId(this.client,$):void 0);async update($){await this.mutate((O)=>O.storage.updateAgent({path:{agent_id:this.id},body:p0($)}))}}function p0($){let{channels:O,team:j,host:x,autoAcceptPermissions:S,avatarUrl:K,channelScope:Z,defaultModel:X,isCoding:Y,...L}=$;return{...L,channel_ids:O?.map((G)=>G.id),team_id:j?.id,harness_id:x?.id,auto_accept_permissions:S,avatar_url:K,channel_scope:Z,default_model:X,is_coding:Y}}async function Nj($,O,j,x=[]){let{channelId:S,thread:K}=J5(O);if(await V5($)){let{id:X}=Q(await $.storage.entityMessageCreate({path:{parent_type:"channel",parent_id:S},body:{content:j.content,mentions:j.mentions,attachments:x.map((Y)=>({entity_type:G5,entity_id:Y.id,width:Y.width??null,height:Y.height??null})),thread_id:K?.rootId??null,nonce:crypto.randomUUID()}}));return X}if(x.length>0)throw new f("a user-owned bot can only post via the channel webhook endpoint, which "+"does not support images — use a team-owned bot, or requestedAs(user), "+"to attach images");if(K)throw new f("a user-owned bot can only post via the channel webhook endpoint, which "+"does not support threads — use a team-owned bot, or requestedAs(user), "+"to reply in a thread");let{message_id:Z}=Q(await $.storage.postChannelBotWebhook({path:{channel_id:S},body:{content:j.content},headers:{"x-macro-bot-scope":"user"}}));return Z}var G5="static/image";function J5($){return"rootId"in $?{channelId:$.channelId,thread:$}:{channelId:$.id}}async function V5($){if($.authConfig.type!=="bot"||$.hasActingUser())return!0;let{owner:O}=await $.selfBot();return O?.type==="team"}class h${client;channelId;rootId;constructor($,O,j){this.client=$;this.channelId=O;this.rootId=j}toJSON(){return{channelId:this.channelId,rootId:this.rootId}}channel(){return b.byId(this.client,this.channelId)}root(){return o.byId(this.client,this.channelId,this.rootId)}async replies(){let{replies:$}=Q(await this.client.storage.entityMessageGetThread({path:{parent_type:"channel",parent_id:this.channelId,id:this.rootId}}));return $.map((O)=>o.from(this.client,this.channelId,O))}async reply($,O){let j=await Nj(this.client,this,O$($),O?.images);return o.byId(this.client,this.channelId,j)}}class o extends H${channelId;mentions;entityType="channel_message";constructor($,O,j,x=[],S){super($,j,S);this.channelId=O;this.mentions=x}get path(){return{parent_type:"channel",parent_id:this.channelId,id:this.id}}async fetch(){return Q(await this.client.storage.entityMessageGetMessage({path:this.path}))}static byId($,O,j,x=[]){return new o($,O,j,x)}static from($,O,j){return new o($,O,j.id,j.mentions,j)}content=this.field("content");createdAt=this.field("created_at");editedAt=this.field("edited_at");updatedAt=this.field("updated_at");async author(){return C.byId(this.client,(await this.detail.get()).sender_id)}channel(){return b.byId(this.client,this.channelId)}thread(){return new h$(this.client,this.channelId,this.id)}async react($){return await this.mutate((O)=>O.storage.entityMessageReact({path:this.path,body:{add:!0,emoji:$}})),this}async unreact($){return await this.mutate((O)=>O.storage.entityMessageReact({path:this.path,body:{add:!1,emoji:$}})),this}async edit($){let{content:O,mentions:j}=O$($);return await this.mutate((x)=>x.storage.entityMessageEdit({path:this.path,body:{content:O,mentions:j}})),this}async delete(){await this.mutate(($)=>$.storage.entityMessageDeleteMessage({path:this.path}))}async reply($){return this.thread().reply($)}}class Uj{client;channel;record;constructor($,O,j){this.client=$;this.channel=O;this.record=j}agent(){return T$.byId(this.client,this.record.botId)}sessions(){return this.record.sessions.map(($)=>({session:d.byId(this.client,$.sessionId),isCurrent:$.isCurrent,createdAt:$.createdAt}))}turns(){return this.record.turns.map(($)=>new a0(this.client,this,$))}async startFresh($){Q(await this.client.agentHarness.startFreshAgentConversation({path:{channel_id:this.channel.id,bot_id:this.record.botId},body:{sessionId:$.id}}))}toJSON(){return{channelId:this.channel.id,agentId:this.record.botId}}}class a0{client;conversation;record;constructor($,O,j){this.client=$;this.conversation=O;this.record=j}source(){return o.byId(this.client,this.conversation.channel.id,this.record.sourceMessageId)}session(){return d.byId(this.client,this.record.sessionId)}async retry($){Q(await this.client.agentHarness.retryAgentConversationTurn({path:{channel_id:this.conversation.channel.id,bot_id:this.conversation.agent().id,source:this.record.sourceMessageId},body:{actionId:$}}))}toJSON(){return{channelId:this.conversation.channel.id,sourceMessageId:this.record.sourceMessageId}}}class L$ extends P{parent;toJSON(){return{...super.toJSON(),parentType:this.parent.type,parentId:this.parent.entity.id}}constructor($,O,j){super($,j);this.parent=O}static byId($,O,j){return new L$($,O,j)}get path(){return{parent_type:this.parent.type,parent_id:this.parent.entity.id,id:this.id}}async fetch(){return Q(await this.client.storage.entityMessageGetThread({path:this.path})).state}resolved=this.field("resolved");async update($){let O={resolved:$.resolved,detach_anchor:$.detachAnchor,nonce:$.nonce};await this.mutate((j)=>j.storage.entityMessagePatchThread({path:this.path,body:O}))}async delete($){await this.mutate((O)=>O.storage.entityMessageDeleteThread({path:this.path,query:{nonce:$}}))}}async function b$($,O,j,x){for(let K of[...x?.messages??[],...x?.around?[x.around]:[]]){let Z="channelId"in K?{type:"channel",id:K.channelId}:("documentId"in K)?{type:"document",id:K.documentId}:("callId"in K)?{type:"call",id:K.callId}:K.parent;if(Z.type!==O.type||Z.id!==O.entity.id)throw Error("Timeline message belongs to another resource")}let S=Q(await $.storage.messageTimelineEntries({path:{parent_type:O.type,parent_id:O.entity.id},query:{selection:x?JSON.stringify({cursor:x.cursor,around:x.around?.id,ids:x.messages?.map((K)=>K.id),activity_after:x.activityAfter,activity_before:x.activityBefore,anchored:x.anchored,direction:x.direction,include_deleted_threads:x.includeDeletedThreads,limit:x.limit}):void 0}}));return{entries:S.entries.map((K)=>{if(K.type==="activity")return{type:"activity",activity:{...K.activity,actor:C.byId($,K.activity.actor_id)}};return{type:"message",message:j(K.message)}}),nextCursor:S.next_cursor??void 0,previousCursor:S.previous_cursor??void 0}}var W5=50;function x$($){let{filters:O,type:j,make:x,includeCrm:S}=$;return(K,Z,X)=>{let Y=X?.searchOn??"name_content",L=X?.pageSize??W5;return c(async(G)=>{let{results:J,next_cursor:I}=Q(await K.search.unifiedSearch({body:{query:Z,match_type:"partial",search_on:Y,...O?{filters:O}:{},...S?{include_crm:!0}:{}},query:{page_size:L,...G?{cursor:G}:{}}}));return{items:J.filter((W)=>W.type===j).map((W)=>x(K,W)),nextCursor:I}})}}class GO{client;channel;record;constructor($,O,j){this.client=$;this.channel=O;this.record=j}get id(){return this.record.id}user(){return C.byId(this.client,this.record.user_id)}createdAt(){return this.record.created_at}async recordInteraction($){return new GO(this.client,this.channel,Q(await this.client.storage.postActivity({body:{activity_type:$,channel_id:this.channel.id}})))}toJSON(){return this.record}}class b extends K${async recordActivity($){return new GO(this.client,this,Q(await this.client.storage.postActivity({body:{activity_type:$,channel_id:this.id}})))}async setPicture($){await this.mutate((O)=>O.storage.setChannelPicture({path:{channel_id:this.id},body:{profile_picture_id:$?.id??null}}))}messageThreadById($){return L$.byId(this.client,{type:"channel",entity:this},$)}timelinePage($){return b$(this.client,{type:"channel",entity:this},(O)=>o.from(this.client,this.id,O),$)}async agentConversations(){return Q(await this.client.agentHarness.listAgentConversations({path:{channel_id:this.id}})).conversations.map(($)=>new Uj(this.client,this,$))}entityType="channel";propertyEntityType="CHANNEL";async fetch(){return Q(await this.client.storage.getChannel({path:{channel_id:this.id}}))}static byId($,O){return new b($,O)}static async dm($,O){let{channel_id:j}=Q(await $.storage.getOrCreateDm({body:{recipient_id:O.id}}));return new b($,j)}static async private($,O){let{channel_id:j}=Q(await $.storage.getOrCreatePrivate({body:{recipients:O.map((x)=>x.id)}}));return new b($,j)}static async create($,O){let{id:j}=Q(await $.storage.createChannel({body:{channel_type:O.type,name:O.name??null,participants:(O.participants??[]).map((x)=>x.id),team_id:O.team?.id??null}}));return new b($,j)}name=this.field("channel_name");type=this.field("channel_type");async send($,O){let j=await Nj(this.client,O?.thread??this,O$($),O?.images);return o.byId(this.client,this.id,j)}messages($){return this.timeline({limit:$?.pageSize})}messagesAfter($,O){return this.timeline({activity_after:$ instanceof Date?$.toISOString():$,limit:O?.pageSize})}timeline($){return c(async(O)=>{let j=Q(await this.client.storage.messageTimeline({path:{parent_type:"channel",parent_id:this.id},query:{selection:JSON.stringify({...$,cursor:O})}}));return{items:j.items.map((x)=>o.from(this.client,this.id,x)),nextCursor:j.next_cursor}})}message($){return o.byId(this.client,this.id,$)}async rename($){await this.mutate((O)=>O.storage.patchChannel({path:{channel_id:this.id},body:{channel_name:$}}))}async delete(){await this.mutate(($)=>$.storage.deleteChannel({path:{channel_id:this.id}}))}async join(){await this.mutate(($)=>$.storage.joinChannel({path:{channel_id:this.id}}))}async joinCode(){let{join_code:$}=Q(await this.client.storage.getChannelJoinLink({path:{channel_id:this.id}}));return $}async leave(){await this.mutate(($)=>$.storage.leaveChannel({path:{channel_id:this.id}}))}async participants(){return Q(await this.client.storage.getChannelParticipants({path:{channel_id:this.id}}))}async addParticipants($){await this.mutate((O)=>O.storage.addParticipants({path:{channel_id:this.id},body:{participants:$.map((j)=>j.id)}}))}async removeParticipants($){await this.mutate((O)=>O.storage.removeParticipants({path:{channel_id:this.id},body:{participants:$.map((j)=>j.id)}}))}async typing($,O){Q(await this.client.storage.entityMessageTyping({path:{parent_type:"channel",parent_id:this.id},body:{active:$==="start",thread_id:O?.thread?.rootId??null}}))}attachments($){return c(async(O)=>{let j=Q(await this.client.storage.getChannelAttachments({path:{channel_id:this.id},query:{...$?.pageSize?{limit:$.pageSize}:{},...$?.type?{attachment_type:$.type}:{},...O?{cursor:O}:{}}}));return{items:j.items,nextCursor:j.next_cursor}})}webUrl(){return`${this.client.webAppUrl}/app/channel/${this.id}`}static search=x$({type:"channel",make:($,O)=>new b($,O.channel_id)})}class C extends K${entityType="user";propertyEntityType="USER";async fetch(){let{names:$}=Q(await this.client.auth.getUserNamesWithEmail({body:{user_ids:[this.id]}})),O=$.find((j)=>j.id===this.id);if(!O)throw new E(`user ${this.id} not found`);return O}static byId($,O){return new C($,O)}static fromName($,O){return new C($,O.id,O)}static async me($){let{user_id:O}=Q(await $.auth.getUserInfo());return new C($,O)}async name(){let $=await this.detail.get();return[$.first_name,$.last_name].filter(Boolean).join(" ")||void 0}email(){let $=this.id.startsWith("macro|")?this.id.slice(6):void 0;return $?.includes("@")?$:void 0}dm(){return b.dm(this.client,this)}toMention(){return{tag:o$("m-user-mention",{userId:this.id}),mention:{entity_type:"user",entity_id:this.id}}}}class $${client;entityType;entity;constructor($,O,j){this.client=$;this.entityType=O;this.entity=j}get path(){return{entity_type:this.entityType,entity_id:this.entity.id}}async state($){let O=Q(await this.client.storage.accessRequestsState({path:this.path,query:{offset:$}}));return{accessLevel:O.accessLevel??void 0,canReview:O.canReview,owner:O.owner?C.byId(this.client,O.owner):void 0,pendingCount:O.pendingCount,supportedLevels:O.supportedLevels,nextOffset:O.nextOffset??void 0,mine:O.mine?IO.from(this.client,this,O.mine):void 0,requests:O.requests.map((j)=>IO.from(this.client,this,j))}}async request($){let{mine:O}=await this.state();return this.submit($,O?await O.revision():void 0)}async submit($,O){return IO.from(this.client,this,Q(await this.client.storage.accessRequestsSubmit({path:this.path,body:{requestedLevel:$,revision:O}})))}async cancel($){Q(await this.client.storage.accessRequestsCancel({path:this.path,query:{revision:$}}))}async direct(){return Q(await this.client.storage.accessRequestsDirect({path:this.path})).map(($)=>({user:C.byId(this.client,$.userId),accessLevel:$.accessLevel}))}async grant($,O){Q(await this.client.storage.accessRequestsSetDirect({path:{...this.path,user_id:$.id},body:{accessLevel:O}}))}async remove($){Q(await this.client.storage.accessRequestsRemoveDirect({path:{...this.path,user_id:$.id}}))}async resolve($,O){let j=$.access.toJSON();if(j.entity_type!==this.entityType||j.entity_id!==this.entity.id)throw Error("Access request belongs to another entity");return Q(await this.client.storage.accessRequestsResolve({path:{...this.path,request_id:$.id},body:O}))}toJSON(){return this.path}}class IO extends P{access;resolvedRecord;constructor($,O,j){super($,j.id,j);this.access=O}static from($,O,j){return new IO($,O,j)}async fetch(){if(this.resolvedRecord)return this.resolvedRecord;let $;do{let O=await this.access.state($),j=[O.mine,...O.requests].find((x)=>x?.id===this.id);if(j)return j.detail.get();$=O.nextOffset}while($!==void 0);throw new E(`Access request ${this.id} is unavailable`)}revision=this.field("revision");status=this.field("status");requestedLevel=this.field("requestedLevel");requester=this.mappedField("requesterId",($)=>C.byId(this.client,$));async resolve($){this.resolvedRecord=await this.access.resolve(this,{revision:await this.revision(),grantedLevel:$}),this.detail.clear()}}function $O($){return{...$,channelSharePermissions:$.channelSharePermissions===void 0||$.channelSharePermissions===null?$.channelSharePermissions:$.channelSharePermissions.map((O)=>({channelId:O.channel.id,accessLevel:O.accessLevel,operation:O.operation}))}}class N$ extends P{parent;constructor($,O,j,x){super($,j,x);this.parent=O}static byId($,O,j){return new N$($,O,j)}static fromRecord($,O,j){return new N$($,O,j.id,j)}static async create($,O,j){return N$.createForSession($,O.session(),j,O)}static async createForSession($,O,j,x){let S=Q(await $.agentHarness.createSessionReview({path:{session_id:O.id},body:{...j,executionId:x?.id??null}}));return N$.fromRecord($,O,S)}static async list($,O){return Q(await $.agentHarness.listExecutionReviews({path:{session_id:O.session().id,execution_id:O.id}})).map((x)=>N$.fromRecord($,O.session(),x))}async fetch(){return Q(await this.client.agentHarness.getSessionReview({path:{session_id:this.parent.id,review_id:this.id}}))}title=this.field("title");kind=this.field("kind");session(){return this.parent}async reference(){return{kind:await this.kind(),id:this.id}}async items(){return(await this.detail.get()).items.map(($)=>new i0($,{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 i0{snapshot;actions;constructor($,O){this.snapshot=$;this.actions=O}get id(){return this.snapshot.id}get status(){return this.snapshot.status}get draft(){return this.snapshot.draft}get result(){return this.snapshot.result}async edit($){await this.actions.edit($)}async submit(){await this.actions.submit()}async dismiss(){await this.actions.dismiss()}}async function zj($,O,j,x){Q(await $.agentHarness.presentSessionView({path:{session_id:O.id},body:{view:j,executionId:x?.id??null}}))}class rO extends P{parent;constructor($,O,j){super($,O);this.parent=j}static byId($,O,j){return new rO($,j,O)}async fetch(){return Q(await this.client.agentHarness.getCodeExecution({path:{session_id:this.parent.id,execution_id:this.id}}))}reviews={create:($)=>N$.create(this.client,this,$),list:()=>N$.list(this.client,this)};views={present:($)=>zj(this.client,this.parent,$,this)};session(){return this.parent}status=this.field("status");source=this.field("source");calls=this.field("calls");error=this.field("error");async result(){return(await this.detail.get()).result}async refresh(){return this.detail.clear(),await this.detail.get(),this}}class Ij{client;sessionId;dto;constructor($,O,j){this.client=$;this.sessionId=O;this.dto=j}static from($,O,j){return new Ij($,O,j)}get actionId(){return this.dto.actionId}get kind(){return this.dto.kind}get prompt(){return this.dto.prompt??void 0}get attachments(){return this.dto.attachments??[]}get actorUserId(){return this.dto.actorUserId??void 0}get createdAt(){return this.dto.createdAt}async edit($){return Q(await this.client.agentHarness.editQueuedAction({path:{session_id:this.sessionId,action_id:this.actionId},body:{prompt:$}})),this.dto={...this.dto,prompt:$},this}async steer(){Q(await this.client.agentHarness.steerQueuedAction({path:{session_id:this.sessionId,action_id:this.actionId}}))}async remove(){Q(await this.client.agentHarness.removeQueuedAction({path:{session_id:this.sessionId,action_id:this.actionId}}))}}class pO{client;session;id;constructor($,O,j){this.client=$;this.session=O;this.id=j}static byId($,O,j){return new pO($,O,j)}async answer($){return Q(await this.client.agentHarness.answerAgentSessionToolApproval({path:{session_id:this.session.id,approval_id:this.id},body:{answer:$}}))}toJSON(){return{id:this.id,sessionId:this.session.id}}}class d extends P{access=new $$(this.client,"agent_session",this);toolApprovalById($){return pO.byId(this.client,this,$)}async sharePermissions(){return Q(await this.client.agentHarness.getAgentSessionPermissions({path:{session_id:this.id}}))}async updateSharePermissions($){return this.mutate((O)=>O.agentHarness.updateAgentSessionPermissions({path:{session_id:this.id},body:$O($)}))}static byId($,O){return new d($,O)}static async createManaged($,O){let{session:j}=Q(await $.agentHarness.createAgentSession({body:{botId:O?.agent?.id,prompt:O?.prompt,instructions:O?.instructions,model:O?.model,repoUrl:O?.repoUrl,repoBranch:O?.repoBranch}}));return new d($,j.id,j)}static async repositories($){let{repositories:O}=Q(await $.agentHarness.listAgentRepositories());return O.map((j)=>({url:j.url,defaultBranch:j.defaultBranch??void 0}))}static async repositoryBranches($,O){let{branches:j}=Q(await $.agentHarness.listAgentRepositoryBranches({query:{repoUrl:O}}));return j}static async chooseMode($,O){let{mode:j}=Q(await $.agentHarness.chooseAgentMode({body:{prompt:O}}));return j}async fetch(){return Q(await this.client.agentHarness.getAgentSession({path:{session_id:this.id}}))}name=this.field("name");archivedBy=this.field("archivedBy");archivedAt=this.field("archivedAt");model=this.field("model");harness=this.field("harness");repoUrl=this.field("repoUrl");workspace=this.field("workspace");instructions=this.field("instructions");status=this.field("status");sandboxSize=this.field("sandboxSize");createdAt=this.field("createdAt");modifiedAt=this.field("modifiedAt");static async forPullRequest($,O){let{sessionIds:j}=Q(await $.agentHarness.agentSessionsForPullRequest({body:{url:O}}));return j.map((x)=>d.byId($,x))}async pullRequests(){let{pullRequests:$}=Q(await this.client.agentHarness.listAgentSessionPullRequests({path:{session_id:this.id}}));return $.map((O)=>({githubKey:O.githubKey,url:O.url,source:O.source,linkedBy:O.linkedBy?C.byId(this.client,O.linkedBy):void 0,createdAt:O.createdAt}))}async linkPullRequest($){Q(await this.client.agentHarness.linkAgentSessionPullRequest({path:{session_id:this.id},body:{url:$}}))}async unlinkPullRequest($){Q(await this.client.agentHarness.unlinkAgentSessionPullRequest({path:{session_id:this.id},query:{url:$}}))}async autoArchive(){let{overrides:$,defaults:O,autoArchivedAt:j}=Q(await this.client.agentHarness.getAgentSessionAutoArchive({path:{session_id:this.id}}));return{overrides:{onPullRequestMerged:$.onPullRequestMerged??void 0,onRuntimeClosed:$.onRuntimeClosed??void 0},defaults:O,autoArchivedAt:j??void 0}}async setAutoArchive($){Q(await this.client.agentHarness.putAgentSessionAutoArchive({path:{session_id:this.id},body:{onPullRequestMerged:$.onPullRequestMerged??null,onRuntimeClosed:$.onRuntimeClosed??null}}))}async rename($){await this.mutate((O)=>O.agentHarness.renameAgentSession({path:{session_id:this.id},body:{name:$}}))}async archive(){await this.setArchived(!0)}async unarchive(){await this.setArchived(!1)}async setArchived($){await this.mutate((O)=>O.agentHarness.setAgentSessionArchived({path:{session_id:this.id},body:{archived:$}}))}async setSandboxSize($){let{size:O}=await this.mutate((j)=>j.agentHarness.putAgentSessionSandboxSize({path:{session_id:this.id},body:{size:$}}));return O}static async defaultSandboxSize($){return Q(await $.agentHarness.getAgentSandboxSize()).size}static async setDefaultSandboxSize($,O){return Q(await $.agentHarness.putAgentSandboxSize({body:{size:O}})).size}static async codingPreferences($){return Q(await $.agentHarness.getAgentCodingPreferences())}static async autoArchivePreferences($){return Q(await $.agentHarness.getAgentAutoArchivePreferences())}static async setAutoArchivePreferences($,O){return Q(await $.agentHarness.putAgentAutoArchivePreferences({body:O}))}static async setCodingPreferences($,O){return Q(await $.agentHarness.putAgentCodingPreferences({body:O}))}async control($){return this.mutate((O)=>O.agentHarness.controlAgentSession({path:{session_id:this.id},body:$}))}prompt($,O){return this.control({type:"prompt",prompt:$,...O&&O.length>0?{attachments:O}:{}})}async queue(){let{entries:$}=Q(await this.client.agentHarness.getAgentSessionQueue({path:{session_id:this.id}}));return $.map((O)=>Ij.from(this.client,this.id,O))}async changes(){return Q(await this.client.agentHarness.getAgentSessionChanges({path:{session_id:this.id}}))}async changesPatch(){return Q(await this.client.agentHarness.getAgentSessionChangesPatch({path:{session_id:this.id}})).patch}async refreshChanges(){return this.mutate(($)=>$.agentHarness.refreshAgentSessionChanges({path:{session_id:this.id}}))}async foldedLog(){let{bot:$,messages:O}=Q(await this.client.agentHarness.getAgentSessionFoldedLog({path:{session_id:this.id}}));return{bot:$,messages:O}}async log(){return Q(await this.client.agentHarness.getAgentSessionLog({path:{session_id:this.id}}))}reviews={create:($)=>N$.createForSession(this.client,this,$),byId:($)=>N$.byId(this.client,this,$)};views={present:($)=>zj(this.client,this,$)};codeExecutions={byId:($)=>rO.byId(this.client,this,$)};async delete(){await this.mutate(($)=>$.agentHarness.deleteAgentSession({path:{session_id:this.id}}))}}class n0{client;constructor($){this.client=$}byId($){return d.byId(this.client,$)}createManaged($){return d.createManaged(this.client,$)}chooseMode($){return d.chooseMode(this.client,$)}repositories(){return d.repositories(this.client)}repositoryBranches($){return d.repositoryBranches(this.client,$)}forPullRequest($){return d.forPullRequest(this.client,$)}defaultSandboxSize(){return d.defaultSandboxSize(this.client)}setDefaultSandboxSize($){return d.setDefaultSandboxSize(this.client,$)}codingPreferences(){return d.codingPreferences(this.client)}autoArchivePreferences(){return d.autoArchivePreferences(this.client)}setAutoArchivePreferences($){return d.setAutoArchivePreferences(this.client,$)}setCodingPreferences($){return d.setCodingPreferences(this.client,$)}}class s0{client;constructor($){this.client=$}byId($){return T$.byId(this.client,$)}async list(){return Q(await this.client.storage.listAgents()).map(($)=>T$.from(this.client,$))}async create($){return T$.from(this.client,Q(await this.client.storage.createAgent({body:p0($)})))}}class t0{client;async usage($={}){let{users:O,...j}=$;return Q(await this.client.cognition.getUsageHandler({body:{...j,include_users:O?.map((x)=>x.id)}}))}constructor($){this.client=$}async structuredCompletion($){return Q(await this.client.cognition.structuredCompletion({body:$}))}async decide($){return Q(await this.client.cognition.decisions({body:$}))}}class OO extends P{static byId($,O){return new OO($,O)}static from($,O){return new OO($,O.id,{id:O.id,name:O.name,createdAt:O.createdAt})}async fetch(){let $=Q(await this.client.storage.listUserApiKeys()).keys.find((O)=>O.id===this.id);if(!$)throw new E(`API key ${this.id} is unavailable`);return $}name=this.field("name");createdAt=this.field("createdAt");async delete(){await this.mutate(($)=>$.storage.deleteUserApiKey({path:{id:this.id}}))}}class e0{client;constructor($){this.client=$}byId($){return OO.byId(this.client,$)}async list(){return Q(await this.client.storage.listUserApiKeys()).keys.map(($)=>OO.from(this.client,$))}async create($){let O=Q(await this.client.storage.createUserApiKey({body:{name:$}}));return{key:OO.from(this.client,O),secret:O.key}}async tokenForEmail($){return Q(await this.client.auth.macroApiToken({query:{email:$}}))}}class aO{client;constructor($){this.client=$}async me(){if(this.client.authConfig.type!=="bot")throw new f("bots.me() requires bot auth — a user API key has no bot identity");return Q(await this.client.storage.getSelfBot())}async channels(){if(this.client.authConfig.type!=="bot")throw new f("bots.channels() requires bot auth — a user API key has no bot identity");let $=await this.me();return Q(await this.client.storage.listBotChannels({path:{bot_id:$.id}}))}async myPrincipalId(){if(this.client.authConfig.type!=="bot")throw new f("bots.myPrincipalId() requires bot auth — a user API key has no bot identity");return this.client.myPrincipalId()}}class R$ extends P{async fetch(){let{links:$}=Q(await this.client.email.listLinks()),O=$.find((j)=>j.id===this.id);if(!O)throw new E(`email link ${this.id} not found`);return O}static byId($,O){return new R$($,O)}static async list($){let{links:O}=Q(await $.email.listLinks());return O.map((j)=>new R$($,j.id,j))}emailAddress=this.field("email_address");provider=this.field("provider");isPrimary=this.field("is_primary");isSyncActive=this.field("is_sync_active");syncStatus=this.field("sync_status");needsReauth=this.field("needs_reauth");photoUrl=this.field("photo_url");async settingsOperations(){return Q(await this.client.email.mailboxSettingsOperations({headers:{"X-Email-Link-Id":this.id}}))}}class m$ extends P{async setContributesToAvailability($){await this.mutate((O)=>O.calendar.setAvailabilityCalendar({path:{calendar_id:this.id},body:{contributesToAvailability:$}}))}async fetch(){let{calendars:$}=Q(await this.client.calendar.listCalendars()),O=$.find((j)=>j.id===this.id);if(!O)throw new E(`calendar ${this.id} not found`);return O}static byId($,O){return new m$($,O)}static async list($){let{calendars:O}=Q(await $.calendar.listCalendars());return O.map((j)=>new m$($,j.id,j))}name=this.field("name");emailAddress=this.field("emailAddress");isPrimary=this.field("isPrimary");isWritable=this.field("isWritable");contributesToAvailability=this.field("contributesToAvailability");isSubscription=this.field("isSubscription");color=this.field("color");syncError=this.field("syncError");emailLink=this.mappedField("emailLinkId",($)=>R$.byId(this.client,$))}class iO{client;id;constructor($,O){this.client=$;this.id=O}async status(){return Q(await this.client.calendar.calendarReplacementStatus({path:{operation_id:this.id}}))}async confirm(){return Q(await this.client.calendar.confirmCalendarReplacement({path:{operation_id:this.id}}))}async discard(){Q(await this.client.calendar.discardCalendarReplacement({path:{operation_id:this.id}}))}}class S$ extends P{async fetch(){throw new f(`calendar event ${this.id} has no fetch-by-id endpoint; read the record returned by calendar.createEvent / event.update / event.rsvp instead`)}static byId($,O){return new S$($,O)}static fromRecord($,O){return new S$($,O.id,O)}title=this.field("title");description=this.field("description");location=this.field("location");time=this.field("time");status=this.field("status");attendees=this.field("attendees");transparency=this.field("transparency");isReadOnly=this.field("isReadOnly");recurrenceLines=this.field("recurrenceLines");guestPolicy=this.field("guestPolicy");viewerCan=this.field("viewerCan");calendar=this.mappedField("calendarId",($)=>$?m$.byId(this.client,$):void 0);record(){return this.detail.get()}async update($){let O=await this.mutate((j)=>j.calendar.updateCalendarEvent({path:{event_id:this.id},body:B5($)}));return S$.fromRecord(this.client,O)}async delete($={}){await this.mutate((O)=>O.calendar.deleteCalendarEvent({path:{event_id:this.id},query:{calendarId:$.calendar?.id,scope:$.scope,recurrenceId:$.recurrenceId,inbox:$.inbox}}))}async prepareReplacement($){let O=Q(await this.client.calendar.prepareCalendarReplacement({path:{event_id:this.id},body:{removeConference:$.removeConference,recurrenceId:$.recurrenceId,calendarId:$.calendar?.id}}));return new iO(this.client,O.operationId)}async providerUrl($={}){return Q(await this.client.calendar.calendarEventProviderUrl({path:{event_id:this.id},query:{recurrenceId:$.recurrenceId,calendarId:$.calendar?.id}})).url??void 0}async inviteGuests($){let O=await this.mutate((j)=>j.calendar.inviteCalendarEventGuests({path:{event_id:this.id},body:{guests:$.guests,scope:$.scope,recurrenceId:$.recurrenceId,calendarId:$.calendar?.id,inbox:$.inbox}}));return S$.fromRecord(this.client,O)}async addToCalendar($={}){let O=await this.mutate((j)=>j.calendar.copyCalendarEvent({path:{event_id:this.id},body:{calendarId:$.calendar?.id}}));return S$.fromRecord(this.client,O)}async ics(){return Q(await this.client.storage.eventIcs({path:{event_id:this.id}}))}async rsvp($){let O=await this.mutate((j)=>j.calendar.rsvpCalendarEvent({path:{event_id:this.id},body:{response:$.response,scope:$.scope,recurrenceId:$.recurrenceId,calendarId:$.calendar?.id}}));return S$.fromRecord(this.client,O)}}function B5($){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 o0{client;async availabilityCalendars(){return Q(await this.client.calendar.getAvailabilityCalendars()).calendars.map(($)=>({calendar:m$.byId(this.client,$.calendarId),name:$.name,isPrimary:$.isPrimary,contributesToAvailability:$.contributesToAvailability}))}async teamSharing(){return Q(await this.client.calendar.getTeamSharing()).sharing}async setTeamSharing($){return Q(await this.client.calendar.setTeamSharing({body:{sharing:$}})).sharing}occurrences($){let O;return c(async(j)=>{let x=Q(await this.client.storage.listOccurrences({query:{...$,cursor:j}}));O??=N5(this.client);let S=await O;return{items:x.items.map((K)=>{let Z=K.event.calendarId?S.get(K.event.calendarId):void 0;return{event:S$.fromRecord(this.client,K.event),occurrence:K.occurrence,calendarName:Z?.name,contributesToAvailability:o1(K.event,S),inbox:Z?.emailAddress,role:U5(K.event,S)}}),nextCursor:x.nextCursor}})}async teamPage($){let O=Q(await this.client.storage.listTeamCalendar({query:$}));return{items:O.items.map(({ownerId:j,...x})=>({...x,owner:C.byId(this.client,j)})),members:O.members.map((j)=>({user:C.byId(this.client,j.userId),sharing:j.sharing,coverage:j.coverage})),nextCursor:O.nextCursor??void 0}}async teamOutOfOffice($){let O=Q(await this.client.storage.listTeamOutOfOffice({query:$}));return{items:O.items.map((j)=>({event:S$.byId(this.client,j.eventId),owner:C.byId(this.client,j.ownerId),occurrenceKey:j.occurrenceKey,time:j.time,title:j.title??void 0})),hasMore:O.hasMore}}constructor($){this.client=$}calendars(){return m$.list(this.client)}calendar($){return m$.byId(this.client,$)}event($){return S$.byId(this.client,$)}replacement($){return new iO(this.client,$)}async createEvent($){let O=Q(await this.client.calendar.createCalendarEvent({body:L5($)}));return S$.fromRecord(this.client,O)}}function L5($){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 N5($){let{calendars:O}=Q(await $.calendar.listCalendars());return new Map(O.map((j)=>[j.id,j]))}function o1($,O){let j=[$.calendarId,...($.sources??[]).map((x)=>x.calendarId)].flatMap((x)=>{let S=x?O.get(x):void 0;return S?[S.contributesToAvailability]:[]});if(j.some(Boolean))return!0;return j.length>0&&j.every((x)=>x===!1)?!1:void 0}function U5($,O){let j=$.attendees.find((S)=>S.isSelf);if(j?.isOrganizer)return $.isReadOnly?void 0:"organizer";let x=$.attendees.some((S)=>S.isOrganizer);if($.viewerCan.organize&&o1($,O)&&!x)return"organizer";return j?"guest":void 0}class D$ extends P{lookupToken;constructor($,O,j){super($,O,j);this.lookupToken=j?.shareToken}static byId($,O){return new D$($,O)}static from($,O){return new D$($,O.id,O)}async fetch(){if(this.lookupToken)return Q(await this.client.storage.meetingLookup({path:{token:this.lookupToken}}));let $=Q(await this.client.storage.meetingList()).meetings.find((O)=>O.id===this.id);if(!$)throw new E(`Meeting ${this.id} is unavailable`);return this.lookupToken=$.shareToken,$}title=this.field("title");scheduledStart=this.field("scheduledStart");scheduledEnd=this.field("scheduledEnd");channel=this.mappedField("channelId",($)=>$?b.byId(this.client,$):void 0);call=this.mappedField("callId",($)=>$?J$.byId(this.client,$):void 0);async update($){await this.mutate((O)=>O.storage.meetingUpdate({path:{meeting_id:this.id},body:$}))}async cancel(){await this.mutate(($)=>$.storage.meetingCancel({path:{meeting_id:this.id}}))}async invitePermissions(){return Q(await this.client.storage.meetingInvitePermissions({path:{token:(await this.detail.get()).shareToken}}))}async invite($){Q(await this.client.storage.meetingInvite({path:{token:(await this.detail.get()).shareToken},body:{email:$}}))}async inviteUsers($){Q(await this.client.storage.meetingInviteUsers({path:{token:(await this.detail.get()).shareToken},body:{userIds:$.map((O)=>O.id)}}))}async webUrl(){return`${this.client.webAppUrl}/app/meet/join/${encodeURIComponent((await this.detail.get()).shareToken)}`}}class u$ extends P{callId;constructor($,O,j,x){super($,j,x);this.callId=O}get path(){return{parent_type:"call",parent_id:this.callId,id:this.id}}async fetch(){return Q(await this.client.storage.entityMessageGetMessage({path:this.path}))}static byId($,O,j){return new u$($,O,j)}static from($,O,j){return new u$($,O,j.id,j)}content=this.field("content");createdAt=this.field("created_at");updatedAt=this.field("updated_at");call(){return J$.byId(this.client,this.callId)}async author(){return C.byId(this.client,(await this.detail.get()).sender_id)}async reply($){let O=Q(await this.client.storage.entityMessageCreate({path:{parent_type:"call",parent_id:this.callId},body:{...O$($),thread_id:this.callId}}));return u$.from(this.client,this.callId,O)}async edit($){let{content:O,mentions:j}=O$($);return await this.mutate((x)=>x.storage.entityMessageEdit({path:this.path,body:{content:O,mentions:j}})),this}async delete(){await this.mutate(($)=>$.storage.entityMessageDeleteMessage({path:this.path}))}}class J$ extends H${messageThreadById($){return L$.byId(this.client,{type:"call",entity:this},$)}timelinePage($){return b$(this.client,{type:"call",entity:this},(O)=>u$.from(this.client,this.id,O),$)}access=new $$(this.client,"call",this);async meeting(){return D$.from(this.client,Q(await this.client.storage.meetingShare({path:{call_id:this.id}})))}async editTranscript($){await this.mutate((O)=>O.storage.editCallTranscript({path:{call_id:this.id},body:{assignments:$}}))}async toggleTeamShare(){return this.mutate(($)=>$.storage.toggleShareWithTeam({path:{call_id:this.id}}))}entityType="call";async fetch(){return Q(await this.client.storage.getCallRecord({path:{call_id:this.id}}))}static byId($,O){return new J$($,O)}message($){return u$.byId(this.client,this.id,$)}name=this.field("customName");channel=this.mappedField("channelId",($)=>$?b.byId(this.client,$):void 0);channelName=this.field("channelName");creator=this.mappedField("createdBy",($)=>C.byId(this.client,$));isActive=this.field("isActive");status=this.field("status");roomName=this.field("roomName");startedAt=this.field("startedAt");endedAt=this.field("endedAt");durationMs=this.field("durationMs");summary=this.field("summary");transcript=this.field("transcript");participants=this.field("participants");guests=this.field("guests");teamShareAccessLevel=this.field("teamShareAccessLevel");shareWithTeam=this.field("shareWithTeam");recordingUrl=this.field("recordingUrl");recordingPreviewUrl=this.field("recordingPreviewUrl");recordingStartedAt=this.field("recordingStartedAt");async rename($){await this.mutate((O)=>O.storage.editCallRecord({path:{call_id:this.id},body:{customName:$??""}}))}async setTeamShare($){await this.mutate((O)=>O.storage.editCallRecord({path:{call_id:this.id},body:{sharePermission:{teamShareAccessLevel:$?"view":null}}}))}async delete(){await this.mutate(($)=>$.storage.deleteCallRecord({path:{call_id:this.id}}))}static search=x$({filters:{call_filters:{}},type:"call",make:($,O)=>new J$($,O.call_id)})}class $x{client;constructor($){this.client=$}byId($){return J$.byId(this.client,$)}search($,O){return J$.search(this.client,$,O)}}class Ox{client;constructor($){this.client=$}async list(){let{labels:$}=Q(await this.client.storage.listChannelLabels());return $}async create($,O=[]){return Q(await this.client.storage.createChannelLabel({body:{name:$,channelIds:O.map((j)=>j.id)}}))}async createSmartTag($,O){return Q(await this.client.storage.createChannelLabel({body:{name:$,rule:O}}))}async previewSmartTag($){return Q(await this.client.storage.previewSmartTag({body:$}))}async updateSmartTag($,O,j){return Q(await this.client.storage.renameChannelLabel({path:{label_id:$.id},body:{name:O,rule:j}}))}async rename($,O){return Q(await this.client.storage.renameChannelLabel({path:{label_id:$.id},body:{name:O}}))}async delete($){Q(await this.client.storage.deleteChannelLabel({path:{label_id:$.id}}))}async setLabel($,O){Q(await this.client.storage.setChannelLabel({path:{channel_id:$.id},body:{labelId:O?.id??null}}))}}var z5=100;class jx{client;async activity(){return Q(await this.client.storage.getActivity()).map(($)=>new GO(this.client,b.byId(this.client,$.channel_id),$))}labels;constructor($){this.client=$;this.labels=new Ox($)}byId($){return b.byId(this.client,$)}async dm($){return b.dm(this.client,$)}async private($){return b.private(this.client,$)}async create($){return b.create(this.client,$)}async*list(){for await(let $ of this.records())yield b.byId(this.client,$.id)}async*search($,O){if(!O?.searchOn||O.searchOn==="name"){let j=$.toLowerCase();for await(let x of this.records())if(x.name?.toLowerCase().includes(j))yield b.byId(this.client,x.id)}else yield*b.search(this.client,$,O)}records(){return c(async($)=>{let O=Q(await this.client.storage.getChannels({query:{limit:z5,...$?{cursor:$}:{}}}));return{items:O.items,nextCursor:O.next_cursor}})}}class n extends K${async sharePermissions(){return Q(await this.client.storage.getProjectPermissionsV2({path:{id:this.id}}))}async accessLevel(){return Q(await this.client.storage.getProjectUserAccessLevel({path:{id:this.id}}))}access=new $$(this.client,"project",this);entityType="project";propertyEntityType="PROJECT";async fetch(){let{data:$}=Q(await this.client.storage.getProjectHandler({path:{id:this.id}}));return $.projectMetadata}static byId($,O){return new n($,O)}static async create($,O){let{data:j}=Q(await $.storage.createProjectHandler({body:{name:O.name,projectParentId:O.parent?.id??null}}));return new n($,j.id,j)}name=this.field("name");parent=this.mappedField("parentId",($)=>$?n.byId(this.client,$):void 0);createdAt=this.field("createdAt");async items(){let{data:$}=Q(await this.client.storage.getProjectContentHandler({path:{id:this.id}}));return $.map((O)=>O.item)}async rename($){await this.mutate((O)=>O.storage.editProjectV2({path:{id:this.id},body:{name:$}}))}async delete($){await this.mutate((O)=>$?.permanent?O.storage.permanentlyDeleteProject({path:{id:this.id}}):O.storage.deleteProjectHandler({path:{id:this.id}}))}async restore(){await this.mutate(($)=>$.storage.revertDeleteProject({path:{id:this.id}}))}static search=x$({filters:{project_filters:{}},type:"project",make:($,O)=>new n($,O.id)})}class nO{client;chat;id;message;constructor($,O,j,x){this.client=$;this.chat=O;this.id=j;this.message=x}static byId($,O,j,x){return new nO($,O,j,x)}async stop(){Q(await this.client.cognition.stopChatStream({body:{chat_id:this.chat.id,stream_id:this.id}}))}toJSON(){return{id:this.id,chatId:this.chat.id,messageId:this.message.id}}}class sO extends P{chat;constructor($,O,j){super($,j);this.chat=O}static byId($,O,j){return new sO($,O,j)}async fetch(){let $=Q(await this.client.cognition.getChat({path:{chat_id:this.chat.id}})).chat.messages.find((O)=>O.id===this.id);if(!$)throw new E(`Chat message ${this.id} is not yet available`);return $}content=this.field("content");role=this.field("role");async refresh(){this.detail.clear(),await this.detail.get()}toJSON(){return{...super.toJSON(),chatId:this.chat.id}}}class Y$ extends K${async send($){let{attachments:O,additionalInstructions:j,...x}=$,S=await this.mutate((Z)=>Z.cognition.sendChatMessage({body:{...x,chat_id:this.id,additional_instructions:j,attachments:O?.map((X)=>({entity_id:X.entity.id,entity_type:X.type}))}})),K=Y$.byId(this.client,S.chat_id);return nO.byId(this.client,K,S.stream_id,sO.byId(this.client,K,S.message_id))}access=new $$(this.client,"chat",this);entityType="chat";propertyEntityType="CHAT";async fetch(){let{chat:$}=Q(await this.client.cognition.getChat({path:{chat_id:this.id}}));return $}static byId($,O){return new Y$($,O)}static async create($,O){let{id:j}=Q(await $.cognition.createChat({body:{name:O?.name??null,projectId:O?.project?.id??null}}));return new Y$($,j)}name=this.field("name");model=this.field("model");project=this.mappedField("projectId",($)=>$?n.byId(this.client,$):void 0);createdAt=this.field("createdAt");updatedAt=this.field("updatedAt");messages=this.field("messages");async rename($){await this.mutate((O)=>O.cognition.patchChat({path:{chat_id:this.id},body:{name:$}}))}async delete($){await this.mutate((O)=>$?.permanent?O.cognition.permanentlyDeleteChat({path:{chat_id:this.id}}):O.cognition.deleteChat({path:{chat_id:this.id}}))}async copy(){let{id:$}=await this.mutate((O)=>O.cognition.copyChat({path:{chat_id:this.id}}));return new Y$(this.client,$)}async restore(){await this.mutate(($)=>$.cognition.revertDeleteChat({path:{chat_id:this.id}}))}async history(){let{conversation:$}=Q(await this.client.cognition.getChatHistoryHandler({path:{chat_id:this.id}}));return $}webUrl(){return`${this.client.webAppUrl}/app/chat/${this.id}`}static search=x$({filters:{chat_filters:{}},type:"chat",make:($,O)=>new Y$($,O.chat_id)});toMention(){return{tag:o$("m-document-mention",{documentId:this.id,documentName:this.detail.peek()?.name??"",blockName:"chat",blockParams:{}}),mention:{entity_type:"chat",entity_id:this.id}}}}class xx{client;constructor($){this.client=$}byId($){return Y$.byId(this.client,$)}create($){return Y$.create(this.client,$)}search($,O){return Y$.search(this.client,$,O)}}class HO extends P{static byId($,O){return new HO($,O)}static from($,O){return new HO($,O.id,O)}async fetch(){let $=Q(await this.client.auth.getTeamInvites()).invites.find((O)=>O.id===this.id);if(!$)throw new E(`team invite ${this.id} not found`);return $}email=this.field("email");role=this.field("team_role");invitedBy=this.mappedField("invited_by",($)=>C.byId(this.client,$));createdAt=this.field("created_at");lastSentAt=this.field("last_sent_at");async revoke(){await this.mutate(($)=>$.auth.deleteTeamInviteHandler({path:{team_invite_id:this.id}}))}}class _$ extends P{async fetch(){let O=Q(await this.client.auth.getUserTeams()).find((j)=>j.id===this.id);if(!O)throw new E(`team ${this.id} not found`);return O}static byId($,O){return new _$($,O)}static async current($){let O=Q(await $.auth.getTeam());if(!O?.team)throw new E("caller has no current team");return new _$($,O.team.id,O.team)}static async list($){return Q(await $.auth.getUserTeams()).map((j)=>new _$($,j.id,j))}name=this.field("name");slug=this.field("slug");defaultLinkShare=this.field("default_link_share");owner=this.mappedField("owner_id",($)=>C.byId(this.client,$));async members(){return(await this.requireCurrent("members")).members.map((O)=>({user:C.byId(this.client,O.user_id),role:O.role}))}async invite($){let O=[],j=new Set;for(let S of typeof $==="string"?[$]:$){let K=S.trim(),Z=K.toLowerCase();if(K&&!j.has(Z))j.add(Z),O.push(K)}if(O.length===0)throw new f("invite needs at least one email address");let x=await this.client.auth.inviteToTeam({body:{invites:O.map((S)=>({email:S})),team_id:this.id}});if(x.response?.status===304)return!1;return Q(x),!0}async invites(){return Q(await this.client.auth.getTeamInvites({query:{team_id:this.id}})).invites.map(($)=>HO.from(this.client,$))}async requireCurrent($){let O=Q(await this.client.auth.getTeam());if(!O?.team||O.team.id!==this.id)throw new f(`${$} are only available for the current team (see Team.current)`);return O}}var I5=8;class P$ extends P{parent;constructor($,O,j,x){super($,j,x);this.parent=O}get path(){return{parent_type:this.parent.type,parent_id:this.parent.id,id:this.id}}async fetch(){return Q(await this.client.storage.entityMessageGetMessage({path:this.path}))}static byId($,O,j){return new P$($,O,j)}static from($,O,j){return new P$($,O,j.id,j)}text=this.field("content");createdAt=this.field("created_at");updatedAt=this.field("updated_at");deletedAt=this.field("deleted_at");async threadId(){return(await this.detail.get()).thread_id??this.id}async author(){return C.byId(this.client,(await this.detail.get()).sender_id)}async reply($){return tO(this.client,this.parent,$,{threadId:await this.threadId()})}async edit($){let{content:O,mentions:j}=O$($);return await this.mutate((x)=>x.storage.entityMessageEdit({path:this.path,body:{content:O,mentions:j}})),this}async delete(){await this.mutate(($)=>$.storage.entityMessageDeleteMessage({path:this.path}))}}async function Hj($,O){let j={parent_type:O.type,parent_id:O.id},x=c(async(K)=>{let Z=Q(await $.storage.messageTimeline({path:j,query:{selection:JSON.stringify({limit:100,cursor:K})}}));return{items:Z.items,nextCursor:Z.next_cursor}}),S=[];for await(let K of x)S.push(K);return cO(S,I5,async(K)=>{let{state:Z,root:X,replies:Y}=Q(await $.storage.entityMessageGetThread({path:{...j,id:K.id}}));return{thread:Z,comments:[X,...Y].map((L)=>P$.from($,O,L))}})}async function tO($,O,j,x){let S=Q(await $.storage.entityMessageCreate({path:{parent_type:O.type,parent_id:O.id},body:{...O$(j),thread_id:x?.threadId??null}}));return P$.from($,O,S)}class A$ extends H${messageThreadById($){return L$.byId(this.client,{type:"crm_contact",entity:this},$)}timelinePage($){return b$(this.client,{type:"crm_contact",entity:this},(O)=>P$.from(this.client,{type:"crm_contact",id:this.id},O),$)}entityType="crm_contact";async fetch(){return Q(await this.client.storage.getContact({path:{contact_id:this.id}}))}static byId($,O){return new A$($,O)}static from($,O){return new A$($,O.id,O)}name=this.field("name");email=this.field("email");company=this.mappedField("companyId",($)=>$?k$.byId(this.client,$):void 0);hidden=this.field("hidden");createdAt=this.field("createdAt");updatedAt=this.field("updatedAt");firstInteraction=this.field("firstInteraction");lastInteraction=this.field("lastInteraction");async hide(){await this.setHidden(!0)}async unhide(){await this.setHidden(!1)}async setHidden($){await this.mutate((O)=>O.storage.setContactHidden({path:{contact_id:this.id},body:{hidden:$}}))}async rename($){await this.mutate((O)=>O.storage.setCrmContactName({path:{contact_id:this.id},body:{name:$}}))}get commentParent(){return{type:"crm_contact",id:this.id}}async comments(){return Hj(this.client,this.commentParent)}async comment($,O){return tO(this.client,this.commentParent,$,O)}commentById($){return P$.byId(this.client,this.commentParent,$)}}class k$ extends K${messageThreadById($){return L$.byId(this.client,{type:"crm_company",entity:this},$)}timelinePage($){return b$(this.client,{type:"crm_company",entity:this},(O)=>P$.from(this.client,{type:"crm_company",id:this.id},O),$)}entityType="crm_company";propertyEntityType="COMPANY";async fetch(){return Q(await this.client.storage.getCompany({path:{company_id:this.id}}))}static byId($,O){return new k$($,O)}static from($,O){return new k$($,O.id,O)}name=this.field("name");description=this.field("description");hidden=this.field("hidden");emailSync=this.field("emailSync");team=this.mappedField("teamId",($)=>_$.byId(this.client,$));createdAt=this.field("createdAt");updatedAt=this.field("updatedAt");async domain(){let{domains:$}=await this.detail.get();return $[0]?.domain}async domains(){let{domains:$}=await this.detail.get();return $.map((O)=>O.domain)}async contacts(){return Q(await this.client.storage.listCompanyContacts({path:{company_id:this.id}})).map((O)=>A$.from(this.client,O))}static search=x$({filters:{crm_company_filters:{}},type:"company",includeCrm:!0,make:($,O)=>new k$($,O.id)});async hide(){await this.setHidden(!0)}async unhide(){await this.setHidden(!1)}async setHidden($){await this.mutate((O)=>O.storage.setCompanyHidden({path:{company_id:this.id},body:{hidden:$}}))}async setEmailSync($){await this.mutate((O)=>O.storage.setEmailSync({path:{company_id:this.id},body:{email_sync:$}}))}async rename($){await this.mutate((O)=>O.storage.setCrmCompanyName({path:{company_id:this.id},body:{name:$}}))}async createContact($){let O=await this.mutate((j)=>j.storage.createCrmContact({path:{company_id:this.id},body:$}));return A$.from(this.client,O)}get commentParent(){return{type:"crm_company",id:this.id}}async comments(){return Hj(this.client,this.commentParent)}async comment($,O){return tO(this.client,this.commentParent,$,O)}commentById($){return P$.byId(this.client,this.commentParent,$)}}class jO extends P{tableDetail=new W$(async()=>Q(await this.client.storage.getCrmPipelineTable({path:{id:this.id}})));static byId($,O){return new jO($,O)}static from($,O){return new jO($,O.id,O)}async fetch(){return Q(await this.client.storage.getCrmPipeline({path:{id:this.id}}))}name=this.field("name");recordType=this.field("recordType");accessLevel=this.field("grant");sharing=this.field("sharing");owner=this.mappedField("userId",($)=>C.byId(this.client,$));team=this.mappedField("teamId",($)=>_$.byId(this.client,$));async rename($){await this.mutate((O)=>O.storage.renameCrmPipeline({path:{id:this.id},body:{name:$}}))}async setSharing($){if($===void 0)throw Error("Sharing is required");await this.mutate((O)=>O.storage.shareCrmPipeline({path:{id:this.id},body:{sharing:$}}))}async setTrashed($){await this.mutate((O)=>O.storage.trashCrmPipeline({path:{id:this.id},body:{trashed:$}}))}async sharePermissions(){return Q(await this.client.storage.getCrmPipelinePermissions({path:{id:this.id}}))}async updateSharePermissions($){return this.mutate((O)=>O.storage.updateCrmPipelinePermissions({path:{id:this.id},body:$O($)}))}async table(){return Tj.from(this.client,this,await this.tableRecord())}tableRecord(){return this.tableDetail.get()}rows(){return c(async($)=>{let O=Q(await this.client.storage.getCrmPipelineRows({path:{id:this.id},query:{after:$}}));return{items:O.rows.map((j)=>JO.from(this.client,this,j)),nextCursor:O.next}})}queryRows($={}){if($.rows?.some((O)=>O.pipeline.id!==this.id))throw Error("Rows belong to another pipeline");return c(async(O)=>{let j=Q(await this.client.storage.queryCrmPipelineRows({path:{id:this.id},body:{after:O,query:$.query,rowIds:$.rows?.map((x)=>x.id)}}));return{items:j.rows.map((x)=>JO.from(this.client,this,x)),nextCursor:j.next}})}async applyOps($,O){if(O?.baseVersions?.some((S)=>S.table.pipeline.id!==this.id))throw Error("Table belongs to another pipeline");let j={ops:$,baseVersions:O?.baseVersions?Object.fromEntries(O.baseVersions.map((S)=>[S.table.id,S.version])):void 0},x=await this.mutate((S)=>S.storage.applyCrmPipelineOps({path:{id:this.id},body:j}));return this.tableDetail.clear(),x}}class Tj extends P{pipeline;toJSON(){return{...super.toJSON(),pipelineId:this.pipeline.id}}constructor($,O,j){super($,j.table.id,j);this.pipeline=O}static from($,O,j){return new Tj($,O,j)}fetch(){return this.pipeline.tableRecord()}async columns(){return(await this.pipeline.tableRecord()).columns.map(($)=>Rj.from(this.client,this,$))}async version(){return(await this.pipeline.tableRecord()).table.version}rowById($){return JO.byId(this.client,this.pipeline,$)}rows(){return this.pipeline.rows()}}class JO extends P{pipeline;toJSON(){return{...super.toJSON(),pipelineId:this.pipeline.id}}constructor($,O,j,x){super($,j,x);this.pipeline=O}static byId($,O,j){return new JO($,O,j)}static from($,O,j){return new JO($,O,j.rowId,j)}async fetch(){for await(let $ of this.pipeline.queryRows({rows:[this]}))if($.id===this.id)return $.detail.get();throw new E(`Pipeline row ${this.id} is unavailable`)}cells=this.field("cells");async refresh(){this.detail.clear(),await this.detail.get()}}class Rj extends P{table;toJSON(){return{...super.toJSON(),pipelineId:this.table.pipeline.id,tableId:this.table.id}}constructor($,O,j){super($,j.column.id,j);this.table=O}static from($,O,j){return new Rj($,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 Sx{client;constructor($){this.client=$}byId($){return jO.byId(this.client,$)}async list(){return Q(await this.client.storage.listCrmPipelines()).map(($)=>jO.from(this.client,$))}async create($){return jO.from(this.client,Q(await this.client.storage.createCrmPipeline({body:$})))}}class Zx{client;pipelines;constructor($){this.client=$;this.pipelines=new Sx($)}companyById($){return k$.byId(this.client,$)}contactById($){return A$.byId(this.client,$)}async contactByEmail($){let{contact:O}=Q(await this.client.storage.getContactByEmail({query:{email:$}}));return O?A$.from(this.client,O):void 0}async searchContacts($,O={}){let{contacts:j}=Q(await this.client.storage.searchContacts({query:{query:$,limit:O.limit}}));return j.map((x)=>A$.from(this.client,x))}async createCompany($){return k$.from(this.client,Q(await this.client.storage.createCrmCompany({body:$})))}async createContact($){return A$.from(this.client,Q(await this.client.storage.createCrmTeamContact({body:$})))}async blockedDomains(){return Q(await this.client.storage.listCrmBlockedDomains()).map(($)=>$.domain)}async blockDomain($){Q(await this.client.storage.blockCrmDomain({path:{domain:$}}))}async unblockDomain($){Q(await this.client.storage.unblockCrmDomain({path:{domain:$}}))}async settings(){return Q(await this.client.storage.getCrmTeamSettings())}async updateSettings($){return Q(await this.client.storage.putCrmTeamSettings({body:$}))}async setStages($){return Q(await this.client.storage.putCrmTeamStages({body:$}))}async resetStages(){Q(await this.client.storage.resetCrmTeamStages())}searchCompanies($){return k$.search(this.client,$)}}var Xx,H5=new Uint8Array(16);function Dj(){if(!Xx){if(typeof crypto>"u"||!crypto.getRandomValues)throw Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Xx=crypto.getRandomValues.bind(crypto)}return Xx(H5)}var j$=[];for(let $=0;$<256;++$)j$.push(($+256).toString(16).slice(1));function $2($,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 Kx={};function T5($,O,j){let x;if($)x=O2($.random??$.rng?.()??Dj(),$.msecs,$.seq,O,j);else{let S=Date.now(),K=Dj();R5(Kx,S,K),x=O2(K,Kx.msecs,Kx.seq,O,j)}return O??$2(x)}function R5($,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 O2($,O,j,x,S=0){if($.length<16)throw Error("Random bytes length must be >= 16");if(!x)x=new Uint8Array(16),S=0;else if(S<0||S+16>x.length)throw RangeError(`UUID byte range ${S}:${S+15} is out of buffer bounds`);return O??=Date.now(),j??=$[6]*127<<24|$[7]<<16|$[8]<<8|$[9],x[S++]=O/1099511627776&255,x[S++]=O/4294967296&255,x[S++]=O/16777216&255,x[S++]=O/65536&255,x[S++]=O/256&255,x[S++]=O&255,x[S++]=112|j>>>28&15,x[S++]=j>>>20&255,x[S++]=128|j>>>14&63,x[S++]=j>>>6&255,x[S++]=j<<2&255|$[10]&3,x[S++]=$[11],x[S++]=$[12],x[S++]=$[13],x[S++]=$[14],x[S++]=$[15],x}var c$=T5;class F${table;id;constructor($,O){this.table=$;this.id=O}static byId($,O){return new F$($,O)}async detail(){let{columns:$}=await this.table.detail(),O=$.find((j)=>j.column.id===this.id);if(!O)throw new E(`column ${this.id} is not on table ${this.table.id}`);return O}async name(){let $=await this.detail();return $.column.display_name??$.definition.definition.display_name}async rename($){return await this.table.database.renameColumn(this,$),this}async inferType($){return await this.table.database.inferColumnType(this,$),this}changeType($){return this.table.database.changeColumnType(this,$)}convertIntoNewColumn($){return this.table.database.convertColumnIntoNewColumn(this,$)}casts(){return this.table.database.columnCasts(this)}async delete(){await this.table.database.deleteColumn(this)}async dataType(){return(await this.detail()).definition.definition.data_type}async isMultiSelect(){return(await this.detail()).definition.definition.is_multi_select}async position(){return(await this.detail()).column.position}async definition(){return(await this.detail()).definition}async config(){return(await this.detail()).column.config??void 0}async addOptions($){return await this.table.database.addColumnOptions(this,$),this}toJSON(){return{id:this.id,tableId:this.table.id}}}class E${table;id;constructor($,O){this.table=$;this.id=O}static byId($,O){return new E$($,O)}history(){return this.table.database.rowHistory(this)}toJSON(){return{id:this.id,tableId:this.table.id}}}class _j{table;id;constructor($,O){this.table=$;this.id=O}static byId($,O){return new _j($,O)}async detail(){let{views:$}=await this.table.detail(),O=$.find((j)=>j.id===this.id);if(!O)throw new E(`view ${this.id} is not on table ${this.table.id}`);return O}async name(){return(await this.detail()).name}async position(){return(await this.detail()).position}async layout(){return(await this.detail()).layout}async query(){return(await this.detail()).query}positions(){return this.table.database.viewPositions(this)}toJSON(){return{id:this.id,tableId:this.table.id}}}class V${database;id;constructor($,O){this.database=$;this.id=O}static byId($,O){return new V$($,O)}async detail(){let{tables:$}=await this.database.schema(),O=$.find((j)=>j.table.id===this.id);if(!O)throw new E(`table ${this.id} is not in database ${this.database.id}`);return O}async name(){return(await this.detail()).table.name}async rename($){return await this.database.renameTable(this,$),this}async version(){return(await this.detail()).table.version}async position(){return(await this.detail()).table.position}async columns(){let{columns:$}=await this.detail();return $.map((O)=>F$.byId(this,O.column.id))}addColumn($){return this.database.addColumn(this,$)}async reorderColumns($){return await this.database.reorderColumns(this,$),this}row($){return E$.byId(this,$)}async views(){let{views:$}=await this.detail();return $.map((O)=>_j.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 Mj($,O,j,x={}){let S=Q(await $.storage.queryDatabases({body:{sql:j,databaseId:x.database?.id,baseVersions:Object.fromEntries((x.baseVersions??[]).map(({table:G,version:J})=>[G.id,J]))}})),K=new Map;for(let G of[x.database,...(x.baseVersions??[]).map(({table:J})=>J.database)]){if(!G)continue;let J=K.get(G.id);if(J)J.add(G);else K.set(G.id,new Set([G]))}let Z=(G)=>{let J=K.get(G)?.values().next().value;if(J)return J;let I=O($,G);return K.set(G,new Set([I])),I},X=(G)=>{let J=S.tableDatabases[G];if(!J)throw Error(`SQL response is missing the owner of table ${G}`);return V$.byId(Z(J),G)},Y=new Set(Object.keys(S.newVersions).map((G)=>X(G).database.id));if(S.statement.kind==="schema")Y.add(S.statement.databaseId);for(let G of Y)for(let J of K.get(G)??[])J.invalidateSchema();let L=k(S.statement).with({kind:"select"},(G)=>G).with({kind:"schema"},({databaseId:G,summary:J})=>({kind:"schema",database:Z(G),summary:J})).with({kind:"insert"},{kind:"update"},{kind:"delete"},({kind:G,tableId:J,tableName:I})=>({kind:G,table:X(J),tableName:I})).with({kind:"alterColumnType"},({tableId:G,tableName:J,columnId:I,columnName:z,to:W})=>{let V=X(G);return{kind:"alterColumnType",table:V,tableName:J,column:F$.byId(V,I),columnName:z,to:W}}).exhaustive();return{result:S.result?D5(S.result,X,S.tableDatabases):void 0,changesApplied:S.changesApplied,insertedRows:L.kind==="insert"?S.insertedRowIds.map((G)=>E$.byId(L.table,G)):[],newVersions:Object.entries(S.newVersions).map(([G,J])=>({table:X(G),version:J})),readVersions:Object.entries(S.readVersions).map(([G,J])=>({table:X(G),version:J})),truncatedTables:S.truncatedTables,statement:L}}function D5($,O,j){let x=$.sourceTable&&j[$.sourceTable]?O($.sourceTable):void 0;return{columns:$.columns.map(({relatedTable:S,...K})=>({...K,relatedTable:S&&j[S]?O(S):void 0})),rows:$.rows,sourceTable:x,rowHandles:x?$.rowIds.map((S)=>E$.byId(x,S)):[]}}class Cj{table;id;createdBy;record;constructor($,O,j,x){this.table=$;this.id=O;this.createdBy=j;this.record=x}static fromRecord($,O,j){return new Cj($,j.id,O,j)}get tokenPrefix(){return this.record.tokenPrefix}get createdAt(){return this.record.createdAt}delete(){return this.table.database.deleteWebhook(this)}toJSON(){return{id:this.id,tableId:this.table.id,tokenPrefix:this.tokenPrefix}}}class Gx extends e${op;row;column;taken;constructor($,O){super($,O);this.name="MacroOpRefusedError",this.message=O.message,this.op=O.op,this.row=O.row,this.column=O.column,this.taken=O.taken}}function Pj($){return k($).with({type:"relation"},({table:O})=>({type:"relation",database:O.database.id,table:O.id})).with({type:t.not("relation")},(O)=>O).exhaustive()}var _5={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 M5($){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})=>_5[O]).with({type:"relation"},()=>"Relation").exhaustive(()=>"Column")}function Yx($){return $.map((O)=>({id:c$(),label:O}))}function j2($,O,j){return $?.kind===O&&"change"in $&&$.change.kind===j}function Qx($){return k($).with({kind:"reorder_tables"},({kind:O})=>O).with({kind:t.union("table","column","rows","view")},({kind:O,change:j})=>`${O}.${j.kind}`).exhaustive(()=>"unknown")}function d$($,O,j){let[x]=$;if($.length!==1||!j2(x,O,j))throw new f(`expected one ${O}.${j} result, got ${$.map(Qx).join(", ")||"none"}`);return x}class Q$ extends P{access=new $$(this.client,"database",this);async fetch(){return Q(await this.client.storage.getDatabase({path:{id:this.id}}))}assertOwns($,O){if(O.id!==this.id)throw new f(`${$} does not belong to database ${this.id}`)}static byId($,O){return new Q$($,O)}static async create($,O){let j=Q(await $.storage.createDatabase({body:{name:O.name}}));return new Q$($,j.id)}async duplicate($){let O=Q(await this.client.storage.duplicateDatabase({path:{id:this.id},body:{name:$?.name}}));return new Q$(this.client,O.id)}static async list($){return Q(await $.storage.listDatabases()).map((j)=>new Q$($,j.database.id))}query($,O){return Mj(this.client,Q$.byId,$,{...O,database:this})}invalidateSchema(){this.detail.clear()}schema(){return this.detail.get()}name=this.mappedField("database",($)=>$.name);owner=this.mappedField("database",($)=>C.byId(this.client,$.owner_id));createdAt=this.mappedField("database",($)=>$.created_at);trashedAt=this.mappedField("database",($)=>$.trashed_at??void 0);grant=this.field("grant");tables=this.mappedField("tables",($)=>$.map((O)=>V$.byId(this,O.table.id)));async table($){let{tables:O}=await this.schema(),j=O.find((x)=>x.table.name===$);return j?V$.byId(this,j.table.id):void 0}async createTable($){let{table:O}=d$(await this.applyOps([{kind:"table",table:c$(),change:{kind:"create",name:$.name}}]),"table","created");return V$.byId(this,O)}async applyOps($,O={}){let j={ops:$};if(O.baseVersions!==void 0){for(let{table:S}of O.baseVersions)this.assertOwns(`table ${S.id}`,S.database);j.baseVersions=Object.fromEntries(O.baseVersions.map(({table:S,version:K})=>[S.id,K]))}let{results:x}=await this.mutate(async(S)=>{let K=await S.storage.applyDatabaseOps({path:{id:this.id},body:j});if(K.error!==void 0&&"op"in K.error)throw new Gx(K.response?.status??0,K.error);return K});return x}async reorderTables($){for(let x of $)this.assertOwns(`table ${x.id}`,x.database);let O=await this.applyOps([{kind:"reorder_tables",order:$.map((x)=>x.id)}]),[j]=O;if(O.length!==1||j?.kind!=="reorder_tables")throw new f(`expected one reorder_tables result, got ${O.map(Qx).join(", ")||"none"}`);return j.tables.map(({table:x})=>V$.byId(this,x))}async deleteTable($){this.assertOwns(`table ${$.id}`,$.database),d$(await this.applyOps([{kind:"table",table:$.id,change:{kind:"delete"}}]),"table","deleted")}async columnCasts($){return this.assertOwns(`column ${$.id}`,$.table.database),Q(await this.client.storage.listDatabaseColumnCasts({path:{id:this.id,table_id:$.table.id,column_id:$.id}}))}async viewPositions($){this.assertOwns(`view ${$.id}`,$.table.database);let{positions:O}=Q(await this.client.storage.getDatabaseViewPositions({path:{id:this.id,view_id:$.id}}));return O}async rowHistory($){this.assertOwns(`row ${$.id}`,$.table.database);let{changes:O}=Q(await this.client.storage.getDatabaseRowHistory({path:{id:this.id,table_id:$.table.id,row_id:$.id}}));return O}async importTable($){let O=await this.mutate((j)=>j.storage.importDatabaseTable({path:{id:this.id},body:$}));return V$.byId(this,O.id)}webhookOf($){return Cj.fromRecord(V$.byId(this,$.tableId),C.byId(this.client,$.createdBy),$)}async webhooks(){let{webhooks:$}=Q(await this.client.storage.listDatabaseWebhooks({path:{id:this.id}}));return $.map((O)=>this.webhookOf(O))}async createWebhook($){this.assertOwns("table",$.database);let O=Q(await this.client.storage.createDatabaseWebhook({path:{id:this.id},body:{tableId:$.id}}));return{webhook:this.webhookOf(O.webhook),token:O.token}}async deleteWebhook($){this.assertOwns("webhook",$.table.database),Q(await this.client.storage.deleteDatabaseWebhook({path:{id:this.id,webhook_id:$.id}}))}async sharePermissions(){return Q(await this.client.storage.getDatabasePermissions({path:{id:this.id}}))}updateSharePermissions($){return this.mutate((O)=>O.storage.updateDatabasePermissions({path:{id:this.id},body:$}))}async changeColumnType($,O){this.assertOwns(`column ${$.id}`,$.table.database);let j=await $.table.version();return d$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"change_type",to:Pj(O.to)}}],{baseVersions:[{table:$.table,version:j}]}),"column","type_changed")}async columnConversion($,O){return this.assertOwns(`column ${$.id}`,$.table.database),Q(await this.client.storage.convertDatabaseColumn({path:{id:this.id,table_id:$.table.id,column_id:$.id},body:{to:Pj(O)}}))}async convertColumnIntoNewColumn($,O){let j=await this.columnConversion($,O.to),x=O.name??`${await $.name()} (${M5(O.to)})`,S=c$(),K=[{kind:"column",table:$.table.id,column:S,change:{kind:"create",definition:{source:"new",name:x,type:Pj(O.to),options:Yx(j.options)},after:$.id}}];if(j.cells.length>0)K.push({kind:"rows",table:$.table.id,change:{kind:"update",changes:{kind:"per_row",rows:j.cells.map(({row:X,value:Y})=>({row:X,cells:[{column:S,value:Y}]}))}}});let[Z]=await this.applyOps(K,{baseVersions:[{table:$.table,version:j.tableVersion}]});if(!j2(Z,"column","created"))throw new f(`expected a column.created result, got ${Z?Qx(Z):"none"}`);return F$.byId($.table,Z.column)}async deleteColumn($){this.assertOwns(`column ${$.id}`,$.table.database);let O=await $.table.version(),{tableVersion:j}=d$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"delete"}}],{baseVersions:[{table:$.table,version:O}]}),"column","deleted");return j}async reorderColumns($,O){this.assertOwns(`table ${$.id}`,$.database);for(let S of O)if(S.table.id!==$.id)throw new f(`column ${S.id} does not belong to table ${$.id}`);let j=await $.version(),{tableVersion:x}=d$(await this.applyOps([{kind:"table",table:$.id,change:{kind:"reorder_columns",order:O.map((S)=>S.id)}}],{baseVersions:[{table:$,version:j}]}),"table","columns_reordered");if(x===void 0)throw new f(`table ${$.id} reordered its columns without a version`);return x}async renameTable($,O){this.assertOwns(`table ${$.id}`,$.database);let j=await $.name(),{tableVersion:x}=d$(await this.applyOps([{kind:"table",table:$.id,change:{kind:"rename",name:O,previousName:j}}]),"table","renamed");if(x===void 0)throw new f(`table ${$.id} was renamed without a version`);return x}async renameColumn($,O){this.assertOwns(`column ${$.id}`,$.table.database);let j=await $.name(),{tableVersion:x}=d$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"rename",name:O,previousName:j}}]),"column","renamed");return x}async inferColumnType($,O){return this.assertOwns(`column ${$.id}`,$.table.database),this.mutate((j)=>j.storage.inferDatabaseColumnType({path:{id:this.id,table_id:$.table.id,column_id:$.id},body:{dataType:O.dataType,baseVersion:O.baseVersion,...O.specificEntityType!==void 0?{specificEntityType:O.specificEntityType}:{}}}))}async addColumn($,O){if(this.assertOwns(`table ${$.id}`,$.database),O.after!==void 0&&O.after.table.id!==$.id)throw new f(`column ${O.after.id} does not belong to table ${$.id}`);let j="property"in O?{source:"existing",property:O.property.id}:{source:"new",name:O.name,type:Pj(O.type),...O.options!==void 0?{options:Yx(O.options)}:{},...O.inferType!==void 0?{inferType:O.inferType}:{}},{column:x}=d$(await this.applyOps([{kind:"column",table:$.id,column:c$(),change:{kind:"create",definition:j,...O.after!==void 0?{after:O.after.id}:{}}}]),"column","created");return F$.byId($,x)}async addColumnOptions($,O){return this.assertOwns(`column ${$.id}`,$.table.database),d$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"add_options",options:Yx(O)}}]),"column","options_added")}}class Jx{client;constructor($){this.client=$}query($,O){return Mj(this.client,Q$.byId,$,O)}byId($){return Q$.byId(this.client,$)}create($){return Q$.create(this.client,$)}list(){return Q$.list(this.client)}}class VO extends P{document;toJSON(){return{...super.toJSON(),documentId:this.document.id}}constructor($,O,j,x){super($,j,x);this.document=O}static byId($,O,j){return new VO($,O,j)}static from($,O,j){return new VO($,O,j.uuid,j)}async fetch(){let $=Q(await this.client.storage.getDocumentAnchors({path:{document_id:this.document.id}})).data.find((O)=>O.uuid===this.id);if(!$)throw new E(`Annotation ${this.id} is unavailable`);return $}kind=this.field("anchorType");page=this.field("page");async edit($){if(await this.kind()!=="placeable")throw Error("Only placeable comment annotations can be edited");await this.mutate((O)=>O.storage.editAnchor({body:{...$,uuid:this.id,anchorType:"free-comment",fileType:"pdf"}}))}async delete(){if(await this.kind()!=="highlight")throw Error("Only standalone highlights can be deleted with this endpoint");await this.mutate(($)=>$.storage.deleteAnchor({body:{uuid:this.id,anchorType:"highlight",fileType:"pdf"}}))}}class l$ extends P{documentId;constructor($,O,j,x){super($,j,x);this.documentId=O}get path(){return{parent_type:"document",parent_id:this.documentId,id:this.id}}async fetch(){return Q(await this.client.storage.entityMessageGetMessage({path:this.path}))}static byId($,O,j){return new l$($,O,j)}static from($,O,j){return new l$($,O,j.id,j)}text=this.field("content");createdAt=this.field("created_at");updatedAt=this.field("updated_at");async threadId(){return(await this.detail.get()).thread_id??this.id}document(){return w.byId(this.client,this.documentId)}async author(){return C.byId(this.client,(await this.detail.get()).sender_id)}async reply($){return this.document().comment($,{threadId:await this.threadId()})}async edit($){let{content:O,mentions:j}=O$($);return await this.mutate((x)=>x.storage.entityMessageEdit({path:this.path,body:{content:O,mentions:j}})),this}async delete(){await this.mutate(($)=>$.storage.entityMessageDeleteMessage({path:this.path}))}}class eO{client;document;id;detail;constructor($,O,j){this.client=$;this.document=O;this.id=j;this.detail=new W$(async()=>Q(await this.client.storage.getDocumentVersion({path:{document_id:O.id,document_version_id:j}})).data)}static byId($,O,j){return new eO($,O,j)}read(){return this.detail.get()}toJSON(){return{id:this.id,documentId:this.document.id}}}var C5=8;class w extends K${async anchors(){return Q(await this.client.storage.getDocumentAnchors({path:{document_id:this.id}})).data.map(($)=>VO.from(this.client,this,$))}async createHighlight($){return VO.from(this.client,this,Q(await this.client.storage.createAnchor({path:{document_id:this.id},body:{...$,fileType:"pdf",anchorType:"highlight"}})))}version($){return eO.byId(this.client,this,$)}async sharePermissions(){return Q(await this.client.storage.getDocumentPermissionsV2({path:{document_id:this.id}})).documentPermissions}async permissionsToken(){return Q(await this.client.storage.getDocumentPermissionsToken({path:{document_id:this.id}})).token}async prepareSave($){return Q(await this.client.storage.presaveDocumentHandler({path:{document_id:this.id},body:{newBom:$}})).data}async save($){return(await this.mutate((O)=>O.storage.saveDocumentHandler({path:{document_id:this.id},body:$}))).data}async simpleSave(){return(await this.mutate(($)=>$.storage.simpleSave({path:{document_id:this.id}}))).data}messageThreadById($){return L$.byId(this.client,{type:"document",entity:this},$)}timelinePage($){return b$(this.client,{type:"document",entity:this},(O)=>l$.from(this.client,this.id,O),$)}access=new $$(this.client,"document",this);async fetch(){let{data:$}=Q(await this.client.storage.getDocument({path:{document_id:this.id}}));return $.documentMetadata}static byId($,O){return new w($,O)}static async create($,O){let{documentId:j}=Q(await $.storage.createMarkdownHandler({body:{documentName:O.name,markdown:O.markdown??null,projectId:O.project?.id??null}}));return new w($,j)}static async createSnippet($,O){let{documentId:j}=Q(await $.storage.createSnippetHandler({body:{snippetName:O.name,markdown:O.markdown??null,projectId:O.project?.id??null}}));return new w($,j)}static async createSkill($,O){let{documentId:j}=Q(await $.storage.createSkillHandler({body:{skillName:O.name,markdown:O.markdown??null,projectId:O.project?.id??null}}));return new w($,j)}static recent($,O){let j=O?.pageSize??50;return c(async(x)=>{let S=Q(await $.storage.getUserDocumentsHandler({query:{limit:j,offset:x?Number(x):0,...O?.fileType!==void 0?{file_type:O.fileType}:{}}})),K=S.data?.next_offset;return{items:(S.data?.documents??[]).map((Z)=>new w($,Z.documentId)),nextCursor:K!=null?String(K):null}})}static async recentlyDeleted($){let{data:O}=Q(await $.storage.recentlyDeleted({}));return O.items.filter((j)=>j.type==="document").map((j)=>new w($,j.id))}entityType="document";propertyEntityType="DOCUMENT";name=this.field("documentName");fileType=this.field("fileType");project=this.mappedField("projectId",($)=>$?n.byId(this.client,$):void 0);owner=this.mappedField("owner",($)=>C.byId(this.client,$));branchedFrom=this.mappedField("branchedFromId",($)=>$?w.byId(this.client,$):void 0);createdAt=this.field("createdAt");updatedAt=this.field("updatedAt");deletedAt=this.field("deletedAt");async content(){let{text:$}=Q(await this.client.storage.getDocumentTextContent({path:{document_id:this.id}}));if($!==null)return $;let{presigned_url:O}=Q(await this.client.storage.exportDocument({path:{document_id:this.id}})),j=await fetch(O);if(!j.ok)throw new e$(j.status,{message:"failed to download document content"});return j.text()}async rename($){await this.mutate((O)=>O.storage.editDocument({path:{document_id:this.id},body:{documentName:$}}))}async move($){await this.mutate((O)=>O.storage.editDocument({path:{document_id:this.id},body:{projectId:$?.id??""}}))}async delete($){await this.mutate((O)=>$?.permanent?O.storage.permanentlyDeleteDocument({path:{document_id:this.id}}):O.storage.deleteDocument({path:{document_id:this.id}}))}async restore(){await this.mutate(($)=>$.storage.revertDeleteDocument({path:{document_id:this.id}}))}async copy($){let{data:O}=Q(await this.client.storage.copyDocument({path:{document_id:this.id},query:$.versionId!==void 0?{version_id:$.versionId}:void 0,body:{documentName:$.name}}));return new w(this.client,O.documentMetadata.documentId)}async comments(){let $={parent_type:"document",parent_id:this.id},O=c(async(x)=>{let S=Q(await this.client.storage.messageTimeline({path:$,query:{selection:JSON.stringify({limit:100,cursor:x})}}));return{items:S.items,nextCursor:S.next_cursor}}),j=[];for await(let x of O)j.push(x);return cO(j,C5,async(x)=>{let{state:S,root:K,replies:Z}=Q(await this.client.storage.entityMessageGetThread({path:{...$,id:x.id}}));return{thread:S,comments:[K,...Z].map((X)=>l$.from(this.client,this.id,X))}})}async comment($,O){let j=await this.mutate((x)=>x.storage.entityMessageCreate({path:{parent_type:"document",parent_id:this.id},body:{...O$($),thread_id:O?.threadId??null}}));return l$.from(this.client,this.id,j)}async shortId(){return Q(await this.client.storage.getDocumentShortId({path:{document_id:this.id}}))}async teamShare(){return Q(await this.client.storage.getDocumentTeamShare({path:{document_id:this.id}}))}async setTeamShare($){await this.mutate((O)=>O.storage.setDocumentTeamShare({path:{document_id:this.id},body:{shareWithTeam:$}}))}async githubPullRequests(){let{pullRequests:$}=Q(await this.client.storage.getDocumentGithubPullRequests({path:{document_id:this.id}}));return $}async branchName(){let{branchName:$}=Q(await this.client.storage.getDocumentBranchName({path:{document_id:this.id}}));return $}webUrl(){return`${this.client.webAppUrl}/app/md/${this.id}`}static search=x$({filters:{document_filters:{}},type:"document",make:($,O)=>new w($,O.document_id)});toMention(){let $=this.detail.peek();return{tag:o$("m-document-mention",{documentId:this.id,documentName:$?.documentName??"",blockName:$?.fileType??"md"}),mention:{entity_type:"document",entity_id:this.id}}}}class Aj{id;name;constructor($,O){this.id=$;this.name=O}static async list($){let{skills:O}=Q(await $.storage.getSystemSkillsHandler());return O.map((j)=>new Aj(j.id,j.name))}}class Vx{client;async byTeamSlug($){let O=Q(await this.client.storage.getDocumentByTeamSlug({path:{slug:$}}));if(typeof O!=="object"||O===null||!("data"in O)||typeof O.data!=="object"||O.data===null||!("documentMetadata"in O.data)||typeof O.data.documentMetadata!=="object"||O.data.documentMetadata===null||!("documentId"in O.data.documentMetadata)||typeof O.data.documentMetadata.documentId!=="string")throw Error("Invalid team task document response");return w.byId(this.client,O.data.documentMetadata.documentId)}async validatePermissionsToken($){let O=Q(await this.client.storage.validateDocumentPermissionsToken({body:{token:$}}));return{document:w.byId(this.client,O.document_id),user:O.user_id?C.byId(this.client,O.user_id):void 0,accessLevel:O.access_level,expiresAt:O.exp,issuer:O.iss}}async createUpload($){let O={documentName:$.name,sha:$.sha,fileType:$.fileType,mimeType:$.mimeType,projectId:$.project?.id,teamId:$.team?.id,branchedFromId:$.branchedFrom?.id,emailAttachmentId:$.attachment?.id,isTask:$.isTask},j=Q(await this.client.storage.createDocument({body:O})).data;return{document:w.byId(this.client,j.documentMetadata.documentId),uploadUrl:j.presignedUrl??void 0,contentType:j.contentType,content:j.documentMetadata.content}}constructor($){this.client=$}byId($){return w.byId(this.client,$)}create($){return w.create(this.client,$)}async createCanvas($){let O=Q(await this.client.storage.createCanvasHandler({body:{documentName:$.name,projectId:$.project?.id}}));return w.byId(this.client,O.documentId)}createSnippet($){return w.createSnippet(this.client,$)}createSkill($){return w.createSkill(this.client,$)}systemSkills(){return Aj.list(this.client)}search($,O){return w.search(this.client,$,O)}recent($){return w.recent(this.client,$)}recentlyDeleted(){return w.recentlyDeleted(this.client)}}class WO extends P{async fetch(){let{attachment:$}=Q(await this.client.email.getAttachment({path:{id:this.id}}));return $}static byId($,O){return new WO($,O)}static from($,O){return new WO($,O.db_id,O)}filename=this.field("filename");mimeType=this.field("mime_type");size=this.field("size_bytes");dataUrl=this.field("data_url");sfsId=this.field("sfs_id");contentId=this.field("content_id");async toDocument(){let{document_id:$}=Q(await this.client.email.getAttachmentDocumentId({path:{id:this.id}}));return w.byId(this.client,$)}}class z$ extends K${access=new $$(this.client,"email_thread",this);async followup(){return Q(await this.client.storage.getEmailFollowup({path:{thread_id:this.id}}))}async setFollowup($){return Q(await this.client.storage.setEmailFollowup({path:{thread_id:this.id},body:$}))}async calendarInvitations(){return Q(await this.client.email.getThreadCalendarInvitations({path:{thread_id:this.id}}))}async addEventToCalendar($,O,j={}){let x=Q(await this.client.email.copyThreadCalendarInvitation({path:{thread_id:this.id,message_id:$.id,invitation_id:O.id},body:{calendarId:j.calendar?.id}}));return S$.fromRecord(this.client,x)}async readReceipts(){let{receipts:$}=Q(await this.client.email.getThreadReadReceipts({path:{thread_id:this.id}}));return $.map((O)=>({message:U$.byId(this.client,O.message_id),openCount:O.open_count,firstOpenedAt:O.first_opened_at??void 0,lastOpenedAt:O.last_opened_at??void 0}))}async update($){await this.mutate((O)=>O.storage.editThreadV2({path:{thread_id:this.id},body:{projectId:$.project===void 0?void 0:$.project?.id??null,sharePermission:$.sharePermission?$O($.sharePermission):void 0}}))}entityType="email_thread";propertyEntityType="THREAD";async fetch(){let{thread:$}=Q(await this.client.email.getThread({path:{thread_id:this.id},query:{limit:100}}));return $}static byId($,O){return new z$($,O)}createdAt=this.field("created_at");updatedAt=this.field("updated_at");isRead=this.field("is_read");inboxVisible=this.field("inbox_visible");accessLevel=this.field("access_level");providerId=this.field("provider_id");link=this.mappedField("link_id",($)=>R$.byId(this.client,$));project=this.mappedField("project_id",($)=>$?n.byId(this.client,$):void 0);latestInboundAt=this.field("latest_inbound_message_ts");latestOutboundAt=this.field("latest_outbound_message_ts");latestNonSpamAt=this.field("latest_non_spam_message_ts");async subject(){let{messages:$}=await this.detail.get();for(let O of $)if(O.subject)return O.subject;return}async participants(){let{messages:$}=await this.detail.get(),O=new Map;for(let j of $)for(let x of[j.from,...j.to,...j.cc,...j.bcc])if(x&&!O.has(x.email))O.set(x.email,x);return[...O.values()]}async messages($){return Q(await this.client.email.getThreadMessagesHandler({path:{id:this.id},query:{...$?.since?{since:$.since}:{},...$?.limit?{limit:$.limit}:{}}})).map((j)=>U$.from(this.client,j))}async attachments(){let{messages:$}=await this.detail.get();return $.flatMap((O)=>O.attachments.map((j)=>WO.from(this.client,j)))}async reply($){let O=$.subject??await this.subject()??"",{message:j}=await this.mutate((x)=>x.email.sendMessage({body:{message:{thread_db_id:this.id,replying_to_id:$.replyingTo?.id??null,to:$.to,cc:$.cc??null,bcc:$.bcc??null,subject:O,body_text:$.bodyText}}}));return j.db_id?U$.byId(this.client,j.db_id):void 0}async archive($=!0){await this.mutate((O)=>O.email.archiveThread({path:{id:this.id},body:{value:$}}))}static async archiveMany($,O,j=!0){let x=[];for(let S=0;S<O.length;S+=100){let K=O.slice(S,S+100),Z=Q(await $.email.archiveThreads({body:{thread_ids:K.map((Y)=>Y.id),value:j}})),X=new Set(Z.failed_thread_ids);for(let Y of K)if(Y.detail.clear(),X.has(Y.id))x.push(Y)}return x}async updateState($){await this.mutate((O)=>O.email.updateThreadState({path:{id:this.id},body:$}))}async operations(){return Q(await this.client.email.threadOperations({path:{id:this.id}}))}async markSeen(){await this.mutate(($)=>$.email.threadSeen({path:{id:this.id}}))}async addLabel($){await this.mutate((O)=>O.email.addRemoveThreadLabel({path:{id:this.id},body:{label_id:$.id,value:!0}}))}async removeLabel($){await this.mutate((O)=>O.email.addRemoveThreadLabel({path:{id:this.id},body:{label_id:$.id,value:!1}}))}async moveToProject($){await this.mutate((O)=>O.email.updateThreadProject({path:{thread_id:this.id},body:{projectId:$?.id??null}}))}static search=x$({filters:{email_filters:{}},type:"email",make:($,O)=>new z$($,O.thread_id)})}class U$ extends P{async fetch(){return Q(await this.client.email.getMessage({path:{id:this.id}}))}static byId($,O){return new U$($,O)}static from($,O){return new U$($,O.db_id,O)}static async send($,O){let{message:j}=Q(await $.email.sendMessage({body:{message:{to:O.to,cc:O.cc??null,bcc:O.bcc??null,subject:O.subject,body_text:O.bodyText}}}));return j.db_id?U$.byId($,j.db_id):void 0}subject=this.field("subject");from=this.field("from");to=this.field("to");cc=this.field("cc");bcc=this.field("bcc");body=this.field("body_parsed");sentAt=this.field("internal_date_ts");labels=this.field("labels");link=this.mappedField("link_id",($)=>R$.byId(this.client,$));async operationStatus(){return Q(await this.client.email.messageOperationStatus({path:{id:this.id}}))}async resolveOperation($){await this.mutate((O)=>O.email.resolveMessageOperation({path:{id:this.id},body:$}))}async completeDraftAttachment($,O=0){let j=await this.link();await this.mutate((x)=>x.email.completeDraftAttachment({path:{id:this.id,attachment_id:$},query:{draft_generation:O},headers:{"X-Email-Link-Id":j.id}}))}async transferDraft($){let O=await this.detail.get();return this.mutate((j)=>j.email.transferDraft({path:{id:this.id},body:{...$,draft_generation:$.draft_generation??O.draft_generation??0},headers:{"X-Email-Link-Id":O.link_id}}))}async addLabel($){await this.mutate((O)=>O.email.addRemoveLabel({body:{label_id:$.id,message_ids:[this.id],value:!0}}))}async removeLabel($){await this.mutate((O)=>O.email.addRemoveLabel({body:{label_id:$.id,message_ids:[this.id],value:!1}}))}async thread(){return z$.byId(this.client,(await this.detail.get()).thread_db_id)}async downloadEml(){return Q(await this.client.email.getMessageEml({path:{id:this.id},parseAs:"blob"}))}}class BO extends U${async draftContext(){let $=await this.detail.get();return{headers:{"X-Email-Link-Id":$.link_id},query:{draft_generation:$.draft_generation??0}}}static byId($,O){return new BO($,O)}draftGeneration=this.field("draft_generation");async update($){let{headers:O,query:j}=await this.draftContext();await this.mutate((x)=>x.email.createDraft({headers:O,body:{draft:{...Wx($),db_id:this.id,draft_generation:$.draftGeneration??j.draft_generation}}}))}async delete(){let{headers:$,query:O}=await this.draftContext();await this.mutate((j)=>j.email.deleteDraft({path:{id:this.id},headers:$,query:O}))}async schedule($,O){let{headers:j,query:x}=await this.draftContext();await this.mutate((S)=>S.email.upsertScheduledMessage({path:{id:this.id},headers:j,query:x,body:{send_time:$,include_signature:O?.includeSignature}}))}async unschedule(){let{headers:$,query:O}=await this.draftContext();await this.mutate((j)=>j.email.deleteScheduledDraft({path:{message_id:this.id},headers:$,query:O}))}async addAttachment($){let O={file_name:$.fileName,sha:$.sha,size:$.size,upload_id:$.uploadId},{headers:j,query:x}=await this.draftContext(),S=await this.mutate((K)=>K.email.addDraftAttachment({path:{id:this.id},headers:j,query:x,body:O}));return{attachment:oO.byId(this.client,this,S.attachment_id,!1,x.draft_generation),uploadUrl:S.upload_url,contentType:S.content_type}}async forwardAttachment($){let{headers:O,query:j}=await this.draftContext(),x=await this.mutate((S)=>S.email.addForwardedAttachment({path:{id:this.id},headers:O,query:j,body:{attachment_id:$.id}}));return oO.byId(this.client,this,x.attachment_id,!0,j.draft_generation)}async removeAttachment($){if($.draft.id!==this.id)throw Error("Attachment belongs to another draft");let{headers:O}=await this.draftContext(),j={draft_generation:$.draftGeneration};if($.forwarded)await this.mutate((x)=>x.email.removeForwardedAttachment({path:{id:this.id,attachment_id:$.id},headers:O,query:j}));else await this.mutate((x)=>x.email.removeDraftAttachment({path:{id:this.id,attachment_id:$.id},headers:O,query:j}))}async verifyAttachment($){if($.draft.id!==this.id||$.forwarded)throw Error("Expected an uploaded attachment on this draft");await this.completeDraftAttachment($.id,$.draftGeneration)}}class oO{draft;id;forwarded;draftGeneration;constructor($,O,j,x){this.draft=$;this.id=O;this.forwarded=j;this.draftGeneration=x}static byId($,O,j,x=!1,S=0){return new oO(O,j,x,S)}complete(){return this.draft.verifyAttachment(this)}remove(){return this.draft.removeAttachment(this)}toJSON(){return{id:this.id,draftId:this.draft.id,forwarded:this.forwarded,draftGeneration:this.draftGeneration}}}function Wx($){let{bodyText:O,bodyHtml:j,bodyMacro:x,headers:S,includeSignature:K,draftGeneration:Z,thread:X,replyingTo:Y,...L}=$;return{...L,body_text:O,body_html:j===void 0?void 0:btoa(Array.from(new TextEncoder().encode(j),(G)=>String.fromCharCode(G)).join("")).replaceAll("+","-").replaceAll("/","_").replaceAll("=",""),body_macro:x,headers_json:S,include_signature:K,draft_generation:Z,thread_db_id:X?.id,replying_to_id:Y?.id}}class LO extends P{inbox;constructor($,O,j,x){super($,O,j);this.inbox=x}get headers(){return this.inbox?{"X-Email-Link-Id":this.inbox.id}:void 0}static byId($,O,j){return new LO($,O,void 0,j)}static from($,O,j){return new LO($,O.id,O,j)}async fetch(){let $=Q(await this.client.email.listEmailFilters({headers:this.headers})).filters.find((O)=>O.id===this.id);if(!$)throw new E(`Email filter ${this.id} is unavailable`);return $}emailAddress=this.field("email_address");emailDomain=this.field("email_domain");isImportant=this.field("is_important");async setImportant($){let O=await this.detail.get();await this.mutate((j)=>j.email.upsertEmailFilter({headers:this.headers,body:{email_address:O.email_address,email_domain:O.email_domain,is_important:$}}))}async delete(){await this.mutate(($)=>$.email.deleteEmailFilter({path:{id:this.id},headers:this.headers}))}}class xO extends P{async fetch(){let{labels:$}=Q(await this.client.email.listLabels()),O=$.find((j)=>j.id===this.id);if(!O)throw new E(`label ${this.id} not found`);return O}static byId($,O){return new xO($,O)}static async list($){let{labels:O}=Q(await $.email.listLabels());return O.map((j)=>new xO($,j.id,j))}static async create($,O){let{label:j}=Q(await $.email.createLabel({body:{label_name:O}}));if(!j.id)throw new f("created label has no id");return new xO($,j.id)}async delete(){Q(await this.client.email.deleteLabel({path:{id:this.id}}))}name=this.field("name");linkId=this.field("linkId");type=this.field("type");createdAt=this.field("createdAt");labelListVisibility=this.field("labelListVisibility");messageListVisibility=this.field("messageListVisibility")}class Bx{client;async createDraft($,O){let j=Q(await this.client.email.createDraft({body:{draft:Wx($)},headers:O?{"X-Email-Link-Id":O.id}:void 0}));if(!j.draft.db_id)throw Error("Draft response has no message id");return BO.byId(this.client,j.draft.db_id)}draftById($){return BO.byId(this.client,$)}async*scheduled($){let O=$?.pageSize??100;if(!Number.isInteger(O)||O<1)throw Error("pageSize must be positive");let j=Math.min(O,1000);for(let x=0;;x+=j){let S=Q(await this.client.email.getScheduledMessages({query:{offset:x,limit:j},headers:$?.inbox?{"X-Email-Link-Id":$.inbox.id}:void 0}));for(let K of S.messages)yield BO.byId(this.client,K.db_id);if(S.messages.length<j)return}}async filters($){return Q(await this.client.email.listEmailFilters({headers:$?{"X-Email-Link-Id":$.id}:void 0})).filters.map((O)=>LO.from(this.client,O,$))}async upsertFilter($,O){return LO.from(this.client,Q(await this.client.email.upsertEmailFilter({headers:O?{"X-Email-Link-Id":O.id}:void 0,body:{email_address:$.emailAddress,email_domain:$.emailDomain,is_important:$.isImportant}})).filter,O)}async contacts(){return Q(await this.client.email.listContacts()).contacts}reminders($){let{inboxes:O,...j}=$??{};return c(async(x)=>{let S=Q(await this.client.storage.listEmailReminders({query:{...j,inboxIds:O?.map((K)=>K.id),cursor:x}}));return{items:S.items.map(({threadId:K,...Z})=>({...Z,thread:z$.byId(this.client,K)})),nextCursor:S.nextCursor}})}constructor($){this.client=$}byId($){return z$.byId(this.client,$)}message($){return U$.byId(this.client,$)}attachment($){return WO.byId(this.client,$)}link($){return R$.byId(this.client,$)}links(){return R$.list(this.client)}async connectionProviders(){return Q(await this.client.auth.emailConnectionProviders())}async recoverDraftTransfer($){return Q(await this.client.email.recoverDraftTransfer({path:{id:$}}))}send($){return U$.send(this.client,$)}search($,O){return z$.search(this.client,$,O)}inbox($){return c(async(O)=>{let j=Q(await this.client.email.previewsInboxCursor({path:{view:"inbox"},query:{...$?.pageSize?{limit:$.pageSize}:{},...$?.sort?{sort_method:$.sort}:{},...O?{cursor:O}:{}}}));return{items:j.items.map((x)=>z$.byId(this.client,x.id)),nextCursor:j.next_cursor}})}label($){return xO.byId(this.client,$)}labels(){return xO.list(this.client)}createLabel($){return xO.create(this.client,$)}archive($,O=!0){return z$.archiveMany(this.client,$,O)}async deleteLabel($){Q(await this.client.email.deleteLabel({path:{id:$.id}}))}async blockSender($){Q(await this.client.email.blockSender({body:{email_address:$}}))}async unblockSender($){Q(await this.client.email.unblockSender({body:{email_address:$}}))}async blockedSenders(){return Q(await this.client.email.listBlockedSenders()).blocked_emails}}class TO{client;id;constructor($,O){this.client=$;this.id=O}static byId($,O){return new TO($,O)}async delete(){Q(await this.client.storage.deleteEntityMention({path:{mention_id:this.id}}))}toJSON(){return{id:this.id}}}class Lx{client;constructor($){this.client=$}byId($){return TO.byId(this.client,$)}async create($,O){let j=Q(await this.client.storage.createEntityMention({body:{source_entity_id:$.entity.id,source_entity_type:$.type,entity_id:O.entity.id,entity_type:O.type}}));return TO.byId(this.client,j.id)}}function Nx($,O){return{chat:NO.byId($,O.id),name:O.name,announcements:O.announcements}}class NO extends P{static byId($,O){return new NO($,O)}static from($,O){return new NO($,O.jid,O)}async fetch(){let{chats:$}=Q(await this.client.storage.whatsappChats()),O=$.find((j)=>j.jid===this.id);if(!O)throw new E("WhatsApp chat is not available");return O}kind=this.field("kind");name=this.field("name");phoneNumber=this.field("phoneNumber");lastActivityAt=this.field("lastActivityAt");archived=this.field("archived");pinned=this.field("pinned");canAdd=this.field("canAdd");cannotAddReason=this.field("cannotAddReason");community=this.mappedField("community",($)=>$?Nx(this.client,$):void 0);added=this.mappedField("added",($)=>$?g$.byId(this.client,$.id):void 0);shared=this.mappedField("shared",($)=>$?g$.byId(this.client,$.id):void 0);async add(){let $=await this.kind(),O=await this.mutate((j)=>j.storage.externalChatAdd({body:{provider:"whatsapp",remoteId:this.id,kind:$}}));return g$.byId(this.client,O.chatId)}async refresh(){return this.detail.clear(),await this.detail.get(),this}}class M$ extends P{chat;constructor($,O,j,x){super($,j,x);this.chat=O}static byId($,O,j){return new M$($,O,j)}static from($,O,j){return new M$($,O,j.id,j)}async fetch(){return Q(await this.client.storage.externalChatMessage({path:{chat_id:this.chat.id,message_id:this.id}}))}body=this.field("body");sender=this.field("sender");sentAt=this.field("sentAt");editedAt=this.field("editedAt");deleted=this.field("deleted");reactions=this.field("reactions");deliveryState=this.field("deliveryState");kind=this.field("kind");forwarded=this.field("forwarded");viewOnce=this.field("viewOnce");mentions=this.field("mentions");rich=this.field("rich");replyTo=this.mappedField("replyTo",($)=>$?M$.byId(this.client,this.chat,$):void 0);attachments=this.mappedField("attachments",($)=>$.map((O)=>({ordinal:O.ordinal,state:O.state,fileName:O.fileName,mime:O.mime,size:O.size,width:O.width??void 0,height:O.height??void 0,durationSeconds:O.durationSeconds??void 0,presentation:O.presentation??void 0,url:O.fileId?`${this.client.hosts["static-files"]}/file/${O.fileId}`:void 0})))}class SO{chat;id;record;constructor($,O,j){this.chat=$;this.id=O;this.record=j}static byId($,O){return new SO($,O)}static from($,O){return new SO($,O.jid,O)}get displayName(){return this.record?.displayName??void 0}get mentionToken(){return this.id.split("@")[0]??this.id}get admin(){return this.record?.admin}toJSON(){return{id:this.id,chat:this.chat.id,displayName:this.displayName,admin:this.admin}}}class ZO{id;chat;filename;kind;constructor($,O,j,x){this.id=$;this.chat=O;this.filename=j;this.kind=x}static byId($,O){return new ZO(O,$)}static from($,O){return new ZO(O.uploadId,$,O.filename,O.kind)}toJSON(){return{id:this.id,chat:this.chat.id,filename:this.filename,kind:this.kind}}}class XO extends P{chat;constructor($,O,j,x){super($,j,x);this.chat=O}static byId($,O,j){return new XO($,O,j)}static from($,O,j){return new XO($,O,j.id,j)}async fetch(){let O=Q(await this.client.storage.externalChatDelivery({path:{chat_id:this.chat.id},body:[this.id]})).find((j)=>j.id===this.id);if(!O)throw new E("External chat send is not available");return O}state=this.field("state");errorCode=this.field("errorCode");createdAt=this.field("createdAt");message=this.mappedField("messageId",($)=>$?M$.byId(this.client,this.chat,$):void 0);async request(){let{payload:$}=await this.detail.get(),O=$.message,j=k(O).returnType().with({type:"media"},(x)=>({type:"media",upload:ZO.byId(this.chat,x.uploadId),caption:x.caption??void 0})).with({type:"mutation"},(x)=>({type:"mutation",message:M$.byId(this.client,this.chat,x.messageId),operation:x.operation,text:x.text??void 0})).with({type:"text"},(x)=>({type:"text",text:x.text,mentions:(x.mentions??[]).map((S)=>SO.byId(this.chat,S))})).exhaustive();return{idempotencyKey:$.idempotencyKey,message:j,replyTo:$.replyTo?M$.byId(this.client,this.chat,$.replyTo):void 0}}async refresh(){return this.detail.clear(),await this.detail.get(),this}}class g$ extends H${entityType="external_chat";static byId($,O){return new g$($,O)}async fetch(){return Q(await this.client.storage.externalChat({path:{chat_id:this.id}}))}provider=this.field("provider");name=this.field("name");kind=this.field("kind");canSend=this.field("canSend");sendReason=this.field("sendReason");sendingIdentity=this.field("sendingIdentity");unreadCount=this.field("unreadCount");backfill=this.field("backfill");limits=this.field("limits");members=this.field("members");participants=this.mappedField("members",($)=>($?.participants??[]).map((O)=>SO.from(this,O)));disappearingSeconds=this.field("disappearingSeconds");owner=this.mappedField("userId",($)=>C.byId(this.client,$));async community(){let{provider:$,community:O}=await this.detail.get();if(!O)return;return k($).with("whatsapp",()=>Nx(this.client,O)).exhaustive()}async*messages($={}){yield*c(async(O)=>{let j=Q(await this.client.storage.externalChatMessages({path:{chat_id:this.id},query:{before:O,limit:$.limit}}));return{items:j.messages.map((x)=>M$.from(this.client,this,x)),nextCursor:j.nextCursor}})}async markRead($){this.assertChat($.chat),await this.mutate((O)=>O.storage.externalChatRead({path:{chat_id:this.id},body:{messageId:$.id}}))}async permissions(){return Q(await this.client.storage.externalChatPermissions({path:{chat_id:this.id}}))}async updatePermissions($){await this.mutate((O)=>O.storage.externalChatUpdatePermissions({path:{chat_id:this.id},body:$}))}async remove(){await this.mutate(($)=>$.storage.externalChatRemove({path:{chat_id:this.id}}))}async upload($){let O=Q(await this.client.storage.externalChatUpload({path:{chat_id:this.id},body:{file:$}}));return ZO.from(this,O)}async send($,O){if(O.replyTo)this.assertChat(O.replyTo.chat);let j=k($).returnType().with({type:"text"},(S)=>{let K=S.mentions??[];for(let Z of K)this.assertChat(Z.chat);return{type:"text",text:S.text,mentions:K.map((Z)=>Z.id)}}).with({type:"media"},(S)=>{return this.assertChat(S.upload.chat),{type:"media",uploadId:S.upload.id,caption:S.caption}}).with({type:"mutation"},(S)=>{return this.assertChat(S.message.chat),{type:"mutation",messageId:S.message.id,operation:S.operation,text:S.text}}).exhaustive(),x=await this.mutate((S)=>S.storage.externalChatSend({path:{chat_id:this.id},body:{idempotencyKey:O.idempotencyKey,message:j,replyTo:O.replyTo?.id}}));return XO.from(this.client,this,x)}async sends(){return Q(await this.client.storage.externalChatSends({path:{chat_id:this.id}})).map(($)=>XO.from(this.client,this,$))}async delivery($){for(let O of $)this.assertChat(O.chat);return Q(await this.client.storage.externalChatDelivery({path:{chat_id:this.id},body:$.map((O)=>O.id)})).map((O)=>XO.from(this.client,this,O))}async messageAttachments($){for(let O of $)this.assertChat(O.chat);return Q(await this.client.storage.externalChatMessageAttachments({path:{chat_id:this.id},body:$.map((O)=>O.id)})).map((O)=>({message:M$.byId(this.client,this,O.messageId),attachments:O.attachments.map((j)=>({ordinal:j.ordinal,state:j.state,fileName:j.fileName,mime:j.mime,size:j.size,url:j.fileId?`${this.client.hosts["static-files"]}/file/${j.fileId}`:void 0}))}))}async refresh(){return this.detail.clear(),await this.detail.get(),this}assertChat($){if($.id!==this.id)throw Error("External chat reference belongs to another chat")}}class Ux{client;constructor($){this.client=$}async list(){return Q(await this.client.storage.externalChats()).map(($)=>g$.byId(this.client,$.id))}byId($){return g$.byId(this.client,$)}}class zx{client;constructor($){this.client=$}async list($={}){let{favorites:O}=Q(await this.client.storage.listFavorites({query:{entityType:$.entityTypes,entityId:$.entityIds}}));return O}async add($){return Q(await this.client.storage.addFavorite({body:{entityId:$.id,entityType:$.entityType}}))}async remove($){Q(await this.client.storage.removeFavoriteByEntity({path:{entity_type:$.entityType,entity_id:$.id}}))}async reorder($){Q(await this.client.storage.reorderFavorites({body:{favorites:$}}))}}class KO extends H${entityType="foreign_entity";async fetch(){return Q(await this.client.storage.getForeignEntity({path:{id:this.id}}))}static byId($,O){return new KO($,O)}static fromRecord($,O){return new KO($,O.id,O)}foreignEntityId=this.field("foreignEntityId");source=this.field("foreignEntitySource");storedForId=this.field("storedForId");storedForAuthEntity=this.field("storedForAuthEntity");createdAt=this.field("createdAt");updatedAt=this.field("updatedAt");async metadata(){return(await this.detail.get()).metadata}}function x2({login:$,...O}){return{...O,login:$??void 0}}class Ix{client;constructor($){this.client=$}byId($){return KO.byId(this.client,$)}async bySource($,O){return KO.fromRecord(this.client,Q(await this.client.storage.getForeignEntityBySource({path:{source:$,foreign_entity_id:O}})))}async githubPullRequestFacets(){let{repositories:$,authors:O,assignees:j,labels:x}=Q(await this.client.storage.getGithubPullRequestFacets());return{repositories:$,authors:O.map(x2),assignees:j.map(x2),labels:x.map(({color:S,...K})=>({...K,color:S??void 0}))}}}class r${form;id;constructor($,O){this.form=$;this.id=O}static byId($,O){return new r$($,O)}async detail(){let O=(await this.form.schema()).sections.flatMap((j)=>j.kind==="questions"?j.questions:[]).find((j)=>j.id===this.id);if(!O)throw new E(`question ${this.id} is not on form ${this.form.id}`);return O}async title(){return(await this.detail()).title}async column(){return F$.byId(await this.form.table(),(await this.detail()).column)}async options(){return(await this.detail()).options.map(($)=>UO.byId(this,$.id))}}class UO{question;id;constructor($,O){this.question=$;this.id=O}static byId($,O){return new UO($,O)}async detail(){let $=(await this.question.detail()).options.find((O)=>O.id===this.id);if(!$)throw new E(`option ${this.id} is not on question ${this.question.id}`);return $}async label(){return(await this.detail()).label}async color(){return(await this.detail()).color??void 0}}class RO{form;id;detail;constructor($,O,j){this.form=$;this.id=O;this.detail=new W$(()=>this.load(),j)}async load(){let $=await this.form.myResponse();if($.kind==="anonymous"||$.response.id!==this.id)throw new E(`response ${this.id} is not your current response`);return $}static byId($,O,j){return new RO($,O,j)}async status(){return(await this.detail.get()).status}async row(){return(await this.detail.get()).row}async answers(){return(await this.detail.get()).answers}async booking(){return(await this.detail.get()).booking}async refresh(){let $=await this.load();return this.detail=new W$(()=>this.load(),$),this}}class p${form;id;constructor($,O){this.form=$;this.id=O}static byId($,O){return new p$($,O)}async detail(){let $=(await this.form.schema()).sections.find((O)=>O.id===this.id);if(!$)throw new E(`section ${this.id} is not on form ${this.form.id}`);return $}async title(){return(await this.detail()).title}async questions(){let $=await this.detail();return $.kind==="questions"?$.questions.map((O)=>r$.byId(this.form,O.id)):[]}}class Fj{entityType;id;constructor($,O){this.entityType=$;this.id=O}static byId($,O){return new Fj($,O)}}class y$ extends P{async fetch(){return Q(await this.client.storage.getForm({path:{id:this.id}}))}static byId($,O){return new y$($,O)}static async create($,O){let j=Q(await $.storage.createForm({body:{name:O.name,source:O.table?{kind:"table",databaseId:O.table.database.id,tableId:O.table.id}:{kind:"new"}}}));return new y$($,j.form.id,j)}static async list($,O){if(!O)return Q(await $.storage.listAccessibleForms()).map(({form:S})=>new y$($,S.id));return Q(await $.storage.listForms({query:{databaseId:O.id}})).map((x)=>new y$($,x.id))}schema(){return this.detail.get()}name=this.mappedField("form",($)=>$.name);description=this.mappedField("form",($)=>$.description);owner=this.mappedField("form",($)=>C.byId(this.client,$.ownerId));database=this.mappedField("form",($)=>Q$.byId(this.client,$.databaseId));table=this.mappedField("form",($)=>V$.byId(Q$.byId(this.client,$.databaseId),$.tableId));audience=this.mappedField("form",($)=>$.audience);status=this.mappedField("form",($)=>$.status);closesAt=this.mappedField("form",($)=>$.closesAt??void 0);access=this.field("access");async sections(){return(await this.detail.get()).sections.map(($)=>p$.byId(this,$.id))}async questions(){return(await this.detail.get()).sections.flatMap(($)=>$.kind==="questions"?$.questions.map((O)=>r$.byId(this,O.id)):[])}async update($){return await this.mutate((O)=>O.storage.updateForm({path:{id:this.id},body:$})),this}assertOwns($){if($.form.id!==this.id)throw new f(`question or section does not belong to form ${this.id}`)}async replaceLayout($){let O=await this.table(),j=(Z)=>{if(Z.table.id!==O.id||Z.table.database.id!==O.database.id)throw new f(`column does not belong to form ${this.id}'s table`);return Z.id},x=(Z)=>({conjunction:Z.conjunction,conditions:Z.conditions.map((X)=>k(X).with({kind:"group"},(Y)=>({kind:"group",...x(Y)})).with({kind:"condition"},(Y)=>({kind:"condition",column:j(Y.column),test:k(Y.test).with({kind:"options"},(L)=>({...L,options:L.options.map((G)=>G.id)})).with({kind:"entities"},(L)=>({...L,entities:L.entities.map((G)=>G.id)})).with({kind:t.union("presence","text","number","date","dateRange","checkbox")},(L)=>L).exhaustive()})).exhaustive())}),S={sections:$.map((Z)=>{if(Z.section)this.assertOwns(Z.section);let X={id:Z.section?.id??c$(),title:Z.title,description:Z.description??""};return k(Z).with({kind:"booking"},(Y)=>({...X,kind:"booking",target:Y.target})).with({kind:"gate"},(Y)=>({...X,kind:"gate",rules:x(Y.rules),message:Y.message})).with({kind:"questions"},(Y)=>({...X,kind:"questions",questions:Y.questions.map((L)=>{if(L.question)this.assertOwns(L.question);return{id:L.question?.id??c$(),column:j(L.column),helpText:L.helpText??"",required:L.required??!1,widget:L.widget??null}})})).exhaustive()})},K=await this.mutate((Z)=>Z.storage.putFormLayout({path:{id:this.id},body:S}));return{form:this,publicationError:K.publicationError}}wireAnswers($){return $.map(({question:O,value:j})=>{this.assertOwns(O);let x=k(j).with({type:"rows"},(S)=>({type:"rows",value:S.value.map((K)=>K.id)})).with({type:"options"},(S)=>({type:"options",value:S.value.map((K)=>{if(K.question.id!==O.id||K.question.form.id!==this.id)throw new f("option does not belong to the answered question");return{id:K.id}})})).with({type:"entities"},(S)=>({type:"entities",value:S.value.map(({entityType:K,entity:Z})=>({entityType:K,entityId:Z.id}))})).with({type:t.union("text","number","boolean","date","date_range","link","clear")},(S)=>S).exhaustive();return{question:O.id,value:x}})}unlockedBooking($){return $?{...$,section:p$.byId(this,$.section)}:void 0}async outcome($,O){return k($).with({outcome:"stopped"},(j)=>({...j,section:p$.byId(this,j.section)})).with({outcome:"submitted"},async(j)=>{let x=E$.byId(await this.table(),j.row),S=this.unlockedBooking(j.booking);return{outcome:"submitted",response:RO.byId(this,j.response,{status:"submitted",row:x,answers:O,booking:S}),row:x,...S?{booking:S}:{}}}).exhaustive()}async submit($){let O={answers:this.wireAnswers($)};return this.outcome(Q(await this.client.storage.submitFormResponse({path:{id:this.id},body:O})),$)}async editResponse($){let O={answers:this.wireAnswers($)};return this.outcome(Q(await this.client.storage.editMyFormResponse({path:{id:this.id},body:O})),$)}async myResponse(){let $=Q(await this.client.storage.getMyFormResponse({path:{id:this.id}}));if($.kind==="anonymous")return{kind:"anonymous"};let O=await this.table(),j=await Promise.all($.answers.map(async(K)=>{let Z=r$.byId(this,K.question),X=await k(K.value).with({type:"options"},(Y)=>({type:"options",value:Y.value.map((L)=>{if(!("id"in L))throw new f("stored form answers must reference options by id");return UO.byId(Z,L.id)})})).with({type:"entities"},(Y)=>({type:"entities",value:Y.value.map((L)=>({entityType:L.entityType,entity:Fj.byId(L.entityType,L.entityId)}))})).with({type:"rows"},async(Y)=>{let L=await Z.detail();if(L.kind.type!=="relation")throw new f("row answer requires a relation question");let G=V$.byId(Q$.byId(this.client,L.kind.database),L.kind.table);return{type:"rows",value:Y.value.map((J)=>E$.byId(G,J))}}).with({type:t.union("text","number","boolean","date","date_range","link","clear")},(Y)=>Y).exhaustive(()=>{throw new f(`answer to question ${Z.id} has a type this SDK doesn't know`)});return{question:Z,value:X}})),x=$.response.row?E$.byId(O,$.response.row):void 0,S=this.unlockedBooking($.booking);return{kind:"saved",...S?{booking:S}:{},response:RO.byId(this,$.response.id,{status:$.response.status,row:x,answers:j,booking:S}),status:$.response.status,stoppedAtSection:$.response.stoppedAtSection?p$.byId(this,$.response.stoppedAtSection):void 0,row:x,submittedAt:$.response.submittedAt,updatedAt:$.response.updatedAt,answers:j}}async responseSummary(){let $=Q(await this.client.storage.getFormResponseSummary({path:{id:this.id}}));return{...$,stoppedBySection:$.stoppedBySection.map((O)=>({section:p$.byId(this,O.section),count:O.count}))}}async tally(){return Q(await this.client.storage.getFormTally({path:{id:this.id}})).questions.map((O)=>{let j=r$.byId(this,O.question);return{question:j,responses:O.responses,buckets:O.buckets.flatMap((x)=>k(x.value).with({kind:"option"},(S)=>[{count:x.count,value:{kind:"option",option:UO.byId(j,S.option)}}]).with({kind:"checkbox"},(S)=>[{count:x.count,value:S}]).exhaustive((S)=>{return console.warn("macro sdk: unknown form tally bucket",S),[]}))}})}async sharePermissions(){return Q(await this.client.storage.getFormPermissions({path:{id:this.id}}))}updateSharePermissions($){return this.mutate((O)=>O.storage.updateFormPermissions({path:{id:this.id},body:$}))}webUrl(){return`${this.client.webAppUrl}/app/form/${this.id}`}respondUrl(){return`${this.client.webAppUrl}/app/form/${this.id}/respond`}}class Hx{client;constructor($){this.client=$}byId($){return y$.byId(this.client,$)}create($){return y$.create(this.client,$)}list($){return y$.list(this.client,$)}}class DO extends P{static byId($,O){return new DO($,O)}async fetch(){return Q(await this.client.storage.getGithubPullRequest({path:{id:this.id}}))}title=this.field("title");url=this.field("url");status=this.field("status");async changes(){let $=Q(await this.client.storage.getGithubPullRequestChanges({path:{id:this.id}}));return{changeset:$.changeset?new Tx(this.client,this,$.changeset):void 0,error:$.error??void 0}}}class Tx{client;pullRequest;record;constructor($,O,j){this.client=$;this.pullRequest=O;this.record=j}get id(){return this.record.id}async patch(){return Q(await this.client.storage.getGithubPullRequestChangesPatch({path:{id:this.pullRequest.id},query:{changeset:this.id}})).patch}toJSON(){return{pullRequestId:this.pullRequest.id,...this.record}}}class Rx{client;constructor($){this.client=$}byId($){return DO.byId(this.client,$)}forEntity($){return DO.byId(this.client,$.id)}}class _O extends P{static byId($,O){return new _O($,O)}async fetch(){return Q(await this.client.storage.getHarnessPairing({path:{code:this.id}}))}name=this.field("requested_name");expiresAt=this.field("expires_at");async approve($){let O={name:$?.name,team_id:$?.team?.id,allow_permission_bypass:$?.allowPermissionBypass};return B$.from(this.client,await this.mutate((j)=>j.storage.approveHarnessPairing({path:{code:this.id},body:O})))}}class $j{client;id;constructor($,O){this.client=$;this.id=O}static byId($,O){return new $j($,O)}async claim($){let O=Q(await this.client.storage.claimHarnessPairing({path:{pairing_id:this.id},body:{device_secret:$}}));return"harness"in O?{harness:B$.from(this.client,O.harness),token:O.token}:void 0}toJSON(){return{id:this.id}}}class Dx{client;constructor($){this.client=$}byId($){return B$.byId(this.client,$)}async list(){return Q(await this.client.storage.listHarnesses()).map(($)=>B$.from(this.client,$))}async me(){return B$.from(this.client,Q(await this.client.storage.getSelfHarness()))}async deleteSelf(){Q(await this.client.storage.deleteSelfHarness())}async agents(){return Q(await this.client.storage.listHarnessAgents()).map(($)=>T$.byId(this.client,$.bot_id))}async sessions(){return Q(await this.client.storage.listHarnessSessions()).map(($)=>d.byId(this.client,$.session_id))}pairing($){return _O.byId(this.client,$)}async createPairing($){let O=Q(await this.client.storage.createHarnessPairing({body:$}));return{pairing:_O.byId(this.client,O.code),device:$j.byId(this.client,O.pairing_id),deviceSecret:O.device_secret,expiresAt:O.expires_at,pollIntervalSeconds:O.poll_interval_seconds}}}class Ej{id;url;width;height;constructor($,O,j,x){this.id=$;this.url=O;this.width=j;this.height=x}static byId($,O,j){return new Ej(O,`${$.hosts["static-files"]}/file/${O}`,j?.width,j?.height)}toJSON(){return{id:this.id,url:this.url,width:this.width,height:this.height}}}class qj extends Ej{width;height;mimeType;sizeBytes;note;constructor($,O,j,x,S,K,Z){super($,O,j,x);this.width=j;this.height=x;this.mimeType=S;this.sizeBytes=K;this.note=Z}toJSON(){return{...super.toJSON(),mimeType:this.mimeType,sizeBytes:this.sizeBytes,note:this.note}}}class _x{client;constructor($){this.client=$}async generate($){let O=Q(await this.client.cognition.generateImage({body:{prompt:$.prompt,aspectRatio:$.aspectRatio??null,referenceImages:($.referenceImages??[]).map(P5)}}));return new qj(O.staticFileId,O.url,O.width,O.height,O.mimeType,O.sizeBytes,O.note??void 0)}}function P5($){return $ instanceof w?{type:"document",id:$.id}:{type:"staticFile",id:$.id}}var A5="00000001-0000-0000-0000-000000000001",S2="00000001-0000-0000-0000-000000000002",F5="00000001-0000-0000-0000-000000000004",E5="00000001-0000-0000-0000-000000000014",q5="00000001-0000-0000-0002-000000000001",w5="00000001-0000-0000-0002-000000000004";function f5($){let O=$.match(/^https:\/\/github\.com\/([^/]+)\/([^/]+)\/pull\/([1-9][0-9]*)\/?(?:[?#].*)?$/i);if(!O)throw Error(`Expected a GitHub pull request URL like https://github.com/owner/repo/pull/1, got ${$}`);return`${O[1]}/${O[2]}/pull/${O[3]}`}class G$ extends w{static byId($,O){return new G$($,O)}static async create($,O){let{documentId:j}=Q(await $.storage.createTaskHandler({body:{taskName:O.name,markdown:O.markdown??null,projectId:O.project?.id??null,teamId:O.team?.id??null,shareWithTeam:O.shareWithTeam??!0,propertyValues:await b5($,O)}}));return new G$($,j)}static async summaries($,O){if(O.length===0)return[];let{previews:j}=Q(await $.storage.getBatchPreviewHandler({body:{document_ids:O.map((S)=>S.id)}})),x=new Map(j.flatMap((S)=>S.type==="access"?[[S.document_id,S]]:[]));return O.flatMap((S)=>{let K=x.get(S.id);if(!K)return[];return[{task:S,name:K.document_name,owner:C.byId($,K.owner),updatedAt:K.updated_at??void 0,completed:K.sub_type?.type==="task"&&K.sub_type.is_completed}]})}static async findSimilar($,O){let{results:j}=Q(await $.storage.taskSimilaritySearchHandler({body:{taskName:O.title,markdown:O.body??null}}));return j.map((x)=>({task:new G$($,x.taskId),name:x.taskName,similarity:x.vectorScore}))}static async forPullRequest($,O){let j=f5(O),{pullRequests:x}=Q(await $.storage.getGithubPullRequestTasks({body:{githubKeys:[j]}}));return(x[0]?.taskIds??[]).map((S)=>new G$($,S))}async completed(){let{subType:$}=await this.detail.get();if($!=="task")return;let j=(await this.properties()).find((x)=>x.definition.id===S2)?.value;return j?.type==="SelectOption"&&j.value.includes(w5)}webUrl(){return`${this.client.webAppUrl}/app/task/${this.id}`}static search=x$({filters:{document_filters:{sub_types:["task"],task_filters:{}}},type:"document",make:($,O)=>new G$($,O.document_id)})}async function b5($,O){if(!O.initiative&&!O.assignees&&!O.dueDate)return null;let j=O.assignees??[await C.me($)],x=[{propertyId:S2,value:{type:"select_option",option_id:q5}}];if(j.length>0)x.push({propertyId:A5,value:{type:"multi_entity_reference",references:j.map((S)=>({entity_id:S.id,entity_type:"USER"}))}});if(O.initiative)x.push({propertyId:E5,value:{type:"entity_reference",reference:{entity_id:O.initiative.id,entity_type:"INITIATIVE"}}});if(O.dueDate)x.push({propertyId:F5,value:{type:"date",value:O.dueDate.toISOString()}});return x}class a$ extends P{access=new $$(this.client,"initiative",this);static byId($,O){return new a$($,O)}static from($,O){return new a$($,O.id,O)}async fetch(){return Q(await this.client.storage.getInitiative({path:{initiative_id:this.id}}))}name=this.field("name");owner=this.mappedField("ownerId",($)=>C.byId(this.client,$));members=this.mappedField("memberIds",($)=>$.map((O)=>C.byId(this.client,O)));tasks=this.mappedField("taskIds",($)=>$.map((O)=>G$.byId(this.client,O)));accessLevel=this.field("userAccessLevel");sharePermissions=this.field("sharePermission");async update($){await this.mutate((O)=>O.storage.updateInitiative({path:{initiative_id:this.id},body:{name:$.name,memberIds:$.members?.map((j)=>j.id),sharePermission:$.sharePermission?$O($.sharePermission):void 0}}))}async delete(){await this.mutate(($)=>$.storage.deleteInitiative({path:{initiative_id:this.id}}))}}class Mx{client;constructor($){this.client=$}byId($){return a$.byId(this.client,$)}async list(){return Q(await this.client.storage.listInitiatives()).initiatives.map(($)=>a$.byId(this.client,$.id))}async summaries(){return Q(await this.client.storage.listInitiatives()).initiatives.map(($)=>({initiative:a$.byId(this.client,$.id),name:$.name,updatedAt:$.updatedAt}))}async create($){return a$.from(this.client,Q(await this.client.storage.createInitiative({body:{name:$.name,description:$.description,memberIds:$.members?.map((O)=>O.id),shareWithTeam:$.shareWithTeam,propertyValues:$.propertyValues}})))}}class Cx{client;constructor($){this.client=$}byId($){return D$.byId(this.client,$)}async create($){return D$.from(this.client,Q(await this.client.storage.meetingCreate({body:$})))}async list(){return Q(await this.client.storage.meetingList()).meetings.map(($)=>D$.from(this.client,$))}async active(){return Q(await this.client.storage.meetingListActive()).meetings.map(($)=>D$.from(this.client,$))}async lookup($){return D$.from(this.client,Q(await this.client.storage.meetingLookup({path:{token:$}})))}}class zO extends P{async fetch(){return Q(await this.client.notification.getTypedNotificationById({path:{notification_id:this.id}}))}static byId($,O){return new zO($,O)}static from($,O){return new zO($,O.id,O)}static list($,O){return c(async(j)=>{let x=Q(await $.notification.listTypedNotifications({query:{...O?.pageSize?{limit:O.pageSize}:{},...O?.states!==void 0?{states:O.states.join(",")}:{},...j?{cursor:j}:{}}}));return{items:x.items.map((S)=>zO.from($,S)),nextCursor:x.next_cursor}})}type=this.field("notification_event_type");createdAt=this.field("created_at");updatedAt=this.field("updated_at");state=this.field("state");done=this.mappedField("state",($)=>$==="done");sent=this.field("sent");viewedAt=this.field("viewed_at");deletedAt=this.field("deleted_at");owner=this.mappedField("owner_id",($)=>C.byId(this.client,$));sender=this.mappedField("sender_id",($)=>$?C.byId(this.client,$):void 0);metadata=this.field("notification_metadata");async seen(){return await this.state()!=="unseen"}async markSeen(){await this.mutate(($)=>$.notification.bulkMarkNotificationsSeen({body:{notificationIds:[this.id]}}))}async markDone(){await this.mutate(($)=>$.notification.bulkMarkNotificationsDone({body:{notificationIds:[this.id]}}))}async markUndone(){await this.mutate(($)=>$.notification.bulkMarkNotificationsUndone({body:{notificationIds:[this.id]}}))}async delete(){await this.mutate(($)=>$.notification.deleteUserNotificationV2({path:{notification_id:this.id}}))}}class Px{client;constructor($){this.client=$}byId($){return zO.byId(this.client,$)}list($){return zO.list(this.client,$)}async markSeen($){Q(await this.client.notification.bulkMarkNotificationsSeen({body:{notificationIds:$}}))}async markDone($){Q(await this.client.notification.bulkMarkNotificationsDone({body:{notificationIds:$}}))}async delete($){Q(await this.client.notification.bulkDeleteUserNotificationsV2({body:{notificationIds:$}}))}async preferences(){return Q(await this.client.notification.getNotificationTypePreferences())}async enableType($){Q(await this.client.notification.enableNotificationType({path:{notification_event_type:$}}))}async disableType($){Q(await this.client.notification.disableNotificationType({path:{notification_event_type:$}}))}}class Ax{client;constructor($){this.client=$}async list(){let{data:$}=Q(await this.client.storage.getPinsHandler({}));return $?.recent??[]}async add($,O){Q(await this.client.storage.addPinHandler({path:{pinned_item_id:$.id},body:{pinType:$.entityType,pinIndex:O.index}}))}async remove($){Q(await this.client.storage.removePinHandler({path:{pinned_item_id:$.id},body:{pinType:$.entityType}}))}async reorder($){Q(await this.client.storage.reorderPinsHandler({body:$}))}}class Fx{client;constructor($){this.client=$}byId($){return n.byId(this.client,$)}create($){return n.create(this.client,$)}search($,O){return n.search(this.client,$,O)}}class MO{client;definitionId;id;record;constructor($,O,j,x){this.client=$;this.definitionId=O;this.id=j;this.record=x}static from($,O,j){return new MO($,O,j.id,j)}get value(){return this.record.value}get color(){return this.record.color??void 0}get displayOrder(){return this.record.display_order}get createdAt(){return this.record.created_at}get updatedAt(){return this.record.updated_at}async update($){return this.record=Q(await this.client.properties.updatePropertyOption({path:{definition_id:this.definitionId,option_id:this.id},body:$})),this}async delete(){Q(await this.client.properties.deletePropertyOption({path:{definition_id:this.definitionId,option_id:this.id}}))}}class YO{client;id;detail;constructor($,O,j){this.client=$;this.id=O;this.detail=new W$(()=>this.fetch(),j)}async fetch(){return Q(await this.client.properties.getPropertyDefinition({path:{definition_id:this.id}}))}static async create($,O){let j=Q(await $.properties.createPropertyDefinition({body:{display_name:O.displayName,scope:O.scope,data_type:O.dataType}}));return new YO($,j.id,j)}static byId($,O){return new YO($,O)}static fromRecord($,O){return new YO($,O.id,O)}get displayName(){return this.detail.get().then(($)=>$.display_name)}get dataType(){return this.detail.get().then(($)=>$.data_type)}get owner(){return this.detail.get().then(($)=>$.owner)}get isSystem(){return this.detail.get().then(($)=>$.is_system)}get isMultiSelect(){return this.detail.get().then(($)=>$.is_multi_select)}get createdAt(){return this.detail.get().then(($)=>$.created_at)}get updatedAt(){return this.detail.get().then(($)=>$.updated_at)}async delete(){return Q(await this.client.properties.deletePropertyDefinition({path:{definition_id:this.id}}))}async options(){return Q(await this.client.properties.getPropertyOptions({path:{definition_id:this.id}})).map((O)=>MO.from(this.client,this.id,O))}async addOption($){let O=Q(await this.client.properties.addPropertyOption({path:{definition_id:this.id},body:$}));return MO.from(this.client,this.id,O)}async updateOption($,O){let j=Q(await this.client.properties.updatePropertyOption({path:{definition_id:this.id,option_id:$.id},body:O}));return MO.from(this.client,this.id,j)}async deleteOption($){return Q(await this.client.properties.deletePropertyOption({path:{definition_id:this.id,option_id:$.id}}))}}class Ex{client;constructor($){this.client=$}async list($){return Q(await this.client.properties.listProperties({query:{scope:$?.scope??"all",...$?.forEntityType!==void 0?{for_entity_type:$.forEntityType}:{}}})).map((j)=>{let x="definition"in j?j.definition:j;return YO.fromRecord(this.client,x)})}create($){return YO.create(this.client,$)}definition($){return YO.byId(this.client,$)}async bulkEntityProperties($){return Q(await this.client.properties.getBulkEntityProperties({body:$}))}async updateEntityPropertyOptions($,O){return Q(await this.client.properties.bulkUpdateEntitiesPropertyOptions({body:{entities:$.map((x)=>x.propertyReference()),property_id:O.property.id,...O.add?{add_option_ids:O.add.map((x)=>x.id)}:{},...O.remove?{remove_option_ids:O.remove.map((x)=>x.id)}:{}}})).results}async addEntityPropertyOption($){return Q(await this.client.properties.addEntityPropertyOption({path:{...$.entity.propertyReference(),property_id:$.property.id,option_id:$.option.id}}))}async removeEntityPropertyOption($){return Q(await this.client.properties.removeEntityPropertyOption({path:{...$.entity.propertyReference(),property_id:$.property.id,option_id:$.option.id}}))}async tags(){return Q(await this.client.properties.listTags({}))}}class qx{client;constructor($){this.client=$}async link(){let $=Q(await this.client.auth.getReferralCode()),O=new URL("/app/signup",this.client.webAppUrl);return O.searchParams.set("referral_code",$),{code:$,url:O.toString()}}async invite($){let O=$.trim();if(!O)throw new f("invite needs an email address");Q(await this.client.auth.sendReferralCode({body:{recipient:O}}))}}function wx($){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 k5($){return k($).with({type:"multiple"},(O)=>({type:"multiple",triggers:O.triggers.map(wx)})).with({type:"cron"},wx).with({type:"events"},wx).exhaustive()}class v$ extends P{static byId($,O){return new v$($,O)}static from($,O){if(!O.id)throw Error("Routine response has no id");return new v$($,O.id,O)}async fetch(){return Q(await this.client.scheduledAction.getScheduledAction({path:{id:this.id}}))}name=this.field("name");trigger=this.field("trigger");enabled=this.field("enabled");runVisibility=this.field("run_visibility");nextRunAt=this.field("next_run_at");revision=this.field("configuration_revision");owner=this.mappedField("owner",($)=>C.byId(this.client,$));sourceTemplate=this.mappedField("template_id",($)=>$?v$.byId(this.client,$):void 0);async template(){let $=await this.client.scheduledAction.getScheduledActionTemplate({path:{id:this.id}});if($.response?.status===404)return;return this.toTemplate(Q($))}async shareAsTemplate($){return this.toTemplate(Q(await this.client.scheduledAction.shareScheduledActionTemplate({path:{id:this.id},body:$})))}async activateTemplate($){return v$.from(this.client,Q(await this.client.scheduledAction.activateScheduledActionTemplate({path:{id:this.id},body:{...wj($),enabled:$.enabled??!0}})))}toTemplate($){return new Z2(this,C.byId(this.client,$.author),$)}async stopSharingTemplate(){Q(await this.client.scheduledAction.unshareScheduledActionTemplate({path:{id:this.id}}))}async update($){await this.mutate((O)=>O.scheduledAction.updateScheduledAction({path:{id:this.id},body:wj($)}))}async setEnabled($){await this.mutate((O)=>O.scheduledAction.setScheduledActionEnabled({path:{id:this.id},body:{enabled:$}}))}async execute(){let $=Q(await this.client.scheduledAction.executeScheduledActionNow({path:{id:this.id}}));if($.resource)return k($.resource).with({type:"agent"},(O)=>d.byId(this.client,O.id)).with({type:"chat"},(O)=>Y$.byId(this.client,O.id)).exhaustive();return $.chat_id?Y$.byId(this.client,$.chat_id):void 0}async history(){return Q(await this.client.scheduledAction.listScheduledActionHistory({path:{id:this.id}})).map(($)=>new fx(this,$))}async delete(){await this.mutate(($)=>$.scheduledAction.deleteScheduledAction({path:{id:this.id}}))}}class Z2{routine;author;record;constructor($,O,j){this.routine=$;this.author=O;this.record=j}activate($){return this.routine.activateTemplate($)}toJSON(){return this.record}}class fx{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 wj($){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:k5($.trigger),task:{...O}}}class bx{client;constructor($){this.client=$}byId($){return v$.byId(this.client,$)}async create($){return v$.from(this.client,Q(await this.client.scheduledAction.createScheduledAction({body:{...wj($),enabled:$.enabled??!0}})))}async list($){return Q(await this.client.scheduledAction.listScheduledActions({query:{include_events:$?.includeEvents}})).map((O)=>v$.from(this.client,O))}}class kx{client;constructor($){this.client=$}byId($){return G$.byId(this.client,$)}create($){return G$.create(this.client,$)}summaries($){return G$.summaries(this.client,$)}findSimilar($){return G$.findSimilar(this.client,$)}forPullRequest($){return G$.forPullRequest(this.client,$)}search($,O){return G$.search(this.client,$,O)}}class gx{client;constructor($){this.client=$}byId($){return _$.byId(this.client,$)}current(){return _$.current(this.client)}list(){return _$.list(this.client)}}class yx{client;constructor($){this.client=$}async get($){return Q(await this.client.unfurl.getUnfurl({query:{url:$}}))}async bulk($){return Q(await this.client.unfurl.getUnfurlBulk({body:{url_list:$}}))}}class vx{client;constructor($){this.client=$}byId($){return C.byId(this.client,$)}me(){return C.me(this.client)}async search($){let O=$.trim().toLocaleLowerCase();if(!O)throw Error("A person search needs a name or email.");let j=await this.client.contacts.getContacts();if(j.response?.status===404)return[];let{contacts:x}=Q(j),S=[...new Set(x)],K=[];for(let Z=0;Z<S.length;Z+=100){let X=S.slice(Z,Z+100),{names:Y}=Q(await this.client.auth.getUserNamesWithEmail({body:{user_ids:X}})),L=new Map(Y.map((G)=>[G.id,G]));for(let G of X){let J=L.get(G)??{id:G};if(`${[J.first_name,J.last_name].filter(Boolean).join(" ")} ${G}`.toLocaleLowerCase().includes(O))K.push(C.fromName(this.client,J))}}return K}}class QO extends P{signingSecret;constructor($,O,j,x){super($,O,j);this.signingSecret=x}async fetch(){return Q(await this.client.storage.getWebhook({path:{webhook_id:this.id}}))}static async create($,O){let j=Q(await $.storage.createWebhook({body:{endpoint_url:O.url,namespace:O.namespace,name:O.name,filters:O.filters,scope:O.scope??"user",...O.headers!==void 0?{headers:O.headers}:{}}}));return new QO($,j.id,j,j.signing_secret)}static byId($,O){return new QO($,O)}static fromRecord($,O){return new QO($,O.id,O)}name=this.field("name");namespace=this.field("namespace");endpointUrl=this.field("endpoint_url");status=this.field("status");isValid=this.field("is_valid");filters=this.field("filters");createdAt=this.field("created_at");workspaceId=this.field("workspace_id");createdBy=this.mappedField("created_by_user_id",($)=>C.byId(this.client,$));async scope(){let $=await this.detail.get();return $.workspace_id===$.created_by_user_id?"user":"team"}async update($){await this.mutate((O)=>O.storage.patchWebhook({path:{webhook_id:this.id},body:$}))}async rename($){await this.update({name:$})}async setUrl($){await this.update({endpoint_url:$})}async setFilters($){await this.update({filters:$})}async pause(){await this.update({status:"paused"})}async resume(){await this.update({status:"active"})}async delete(){await this.mutate(($)=>$.storage.deleteWebhook({path:{webhook_id:this.id}}))}async validate(){return this.mutate(($)=>$.storage.validateWebhook({path:{webhook_id:this.id}}))}}class hx{client;constructor($){this.client=$}create($){return QO.create(this.client,$)}byId($){return QO.byId(this.client,$)}async list(){let{webhooks:$}=Q(await this.client.storage.listWebhooks());return $.map((O)=>QO.fromRecord(this.client,O))}}class CO extends P{static byId($,O){return new CO($,O)}static from($,O){return new CO($,O.id,O)}async fetch(){let{account:$}=Q(await this.client.storage.whatsappAccount());if($?.id!==this.id)throw new E("WhatsApp account is not available");return $}state=this.field("state");identity=this.field("identityJid");owner=this.mappedField("userId",($)=>C.byId(this.client,$));async refresh(){return this.detail.clear(),await this.detail.get(),this}}class mx{client;constructor($){this.client=$}async account(){let{account:$}=Q(await this.client.storage.whatsappAccount());return $?CO.from(this.client,$):void 0}async chats(){return Q(await this.client.storage.whatsappChats()).chats.map(($)=>NO.from(this.client,$))}}function ux($){if("properties"in $.data)return $.data.properties;if($.tag==="calendarEvent")return $.data.extra.properties;return[]}function X2($,O,j){let x=[];for(let S of ux(O)){if(S.definition.data_type!=="TAG"||S.value?.type!=="SelectOption")continue;for(let K of S.value.value){let Z=j.get(K);if(Z&&!x.some((X)=>X.label===Z.label&&X.scope===Z.scope))x.push(Z)}}switch(O.tag){case"document":return{type:"document",id:O.data.id,entity:w.byId($,O.data.id),snapshot:O,tags:x,name:O.data.name,fileType:O.data.fileType,subType:O.data.subType?.type};case"chat":return{type:"ai_chat",id:O.data.id,entity:Y$.byId($,O.data.id),snapshot:O,tags:x,name:O.data.name};case"project":return{type:"project",id:O.data.id,entity:n.byId($,O.data.id),snapshot:O,tags:x,name:O.data.name};case"emailThread":return{type:"email",id:O.data.id,entity:z$.byId($,O.data.id),snapshot:O,tags:x,subject:O.data.name,snippet:O.data.snippet,senderName:O.data.senderName,senderEmail:O.data.senderEmail,inboxVisible:O.data.inboxVisible,isRead:O.data.isRead,isDraft:O.data.isDraft};case"channel":return{type:"channel",id:O.data.channel.id,entity:b.byId($,O.data.channel.id),snapshot:O,tags:x,name:O.data.channel.name};case"channelThread":return{type:"channel_thread",id:O.data.id,entity:new h$($,O.data.channel_id,O.data.id),snapshot:O,tags:x,channelId:O.data.channel_id};case"call":return{type:"call",id:O.data.callId,entity:J$.byId($,O.data.callId),snapshot:O,tags:x,createdBy:O.data.createdBy};case"calendarEvent":return{type:"calendar_event",id:O.data.id,entity:S$.byId($,O.data.id),snapshot:O,tags:x,title:O.data.title,status:O.data.status,location:O.data.location,conferenceUrl:O.data.conferenceUrl,conferenceProvider:O.data.conferenceProvider,time:O.data.time};case"foreignEntity":return{type:"foreign_entity",id:O.data.id,entity:KO.byId($,O.data.id),snapshot:O,tags:x,foreignEntityId:O.data.foreignEntityId,foreignEntitySource:O.data.foreignEntitySource,metadata:O.data.metadata};default:throw Error(`Unexpected workspace entity type: ${O.tag}`)}}var K2="00000000-0000-0000-0000-000000000000",cx={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()),Y2=($,O)=>$==null?O:{"&":[$,O]};function dx($,O){if(!$||typeof $!=="object"||Array.isArray($))throw Error(`Invalid workspace ${O}: expected a filter expression.`);let j=Object.entries($),x=j[0];if(j.length!==1||x===void 0)throw Error(`Invalid workspace ${O}: use exactly one of l, &, |, !.`);let[S,K]=x;if(S==="l")return;if(S==="!"){dx(K,`${O}.!`);return}if(S!=="&"&&S!=="|")throw Error(`Invalid workspace ${O}: use l, &, | or !.`);if(!Array.isArray(K)||K.length!==2)throw Error(`Invalid workspace ${O}.${S}: expected exactly two expressions. Use {l: {...}} for a single condition; nest binary operators for three or more.`);K.forEach((Z,X)=>{dx(Z,`${O}.${S}[${X}]`)})}class bj{client;tagSets;constructor($){this.client=$}sets(){return this.tagSets??=this.client.properties.listTags({}).then(Q),this.tagSets}async tagMap(){let $=new Map;for(let O of await this.sets())for(let j of O.options)if(j.value.type==="string")$.set(j.id,{label:j.value.value,scope:O.scope==="user"?"personal":"team"});return $}async body($){for(let[S,K,Z]of[["sortBy",$.sortBy,["recently_viewed","recently_updated","recently_created"]],["emailPreset",$.emailPreset,["signal"]],["tagsMatch",$.tagsMatch,["any","all"]]])if(K!==void 0&&!Z.includes(K))throw Error(`Invalid workspace ${S}: ${K}`);if($.includeTypes!==void 0&&(!Array.isArray($.includeTypes)||$.includeTypes.some((S)=>!Object.hasOwn(cx,S))))throw Error(`Invalid workspace includeTypes. Supported values: ${Object.keys(cx).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)dx($[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:K2}},favorites_only:$.favoritesOnly,expand:!0,limit:Math.max(1,Math.min(500,Math.trunc($.limit??50))),sort_method:$.sortBy==="recently_viewed"?"viewed_at":$.sortBy==="recently_created"?"created_at":"updated_at",sort_direction:"desc",emailView:$.emailView??"inbox"};if($.emailPreset==="signal")O.ef={"&":[{l:{Importance:!0}},{l:{Shared:"exclude"}}]};let j=$.inbox?.trim();if(j){let{links:S}=Q(await this.client.email.listLinks()),K=S.filter((X)=>fj(X.email_address)===fj(j)),Z=K[0];if(!Z)throw Error(`No connected inbox matches "${j}". Connected inboxes: ${S.map((X)=>X.email_address).join(", ")}.`);if(K.length>1)throw Error(`Multiple connected inboxes match "${j}"; cannot pick one.`);O.ef=Y2(O.ef,{l:{Owner:Z.id}})}let x=$.includeTypes??($.emailPreset==="signal"?["email"]:void 0);if(x?.length){for(let[S,[K,Z]]of Object.entries(cx))if(!x.includes(S))O[K]={l:{[Z]:K2}}}if($.tags?.length){let S=(await this.sets()).flatMap((Y)=>{let L=Y.definition;if(!L)return[];return Y.options.flatMap((G)=>G.value.type==="string"?[{id:G.id,definitionId:L.id,label:G.value.value,scope:Y.scope==="user"?"personal":"team"}]:[])}),K=new Map;for(let Y of $.tags){let L=S.filter((G)=>fj(G.label)===fj(Y.label.trim())&&(!Y.scope||G.scope===Y.scope));if(!L.length)throw Error(`Unknown tag "${Y.label}". Available tags: ${S.map((G)=>`${G.label} (${G.scope})`).join(", ")}.`);if($.tagsMatch==="all"&&L.length>1)throw Error(`Tag "${Y.label}" is ambiguous; specify personal or team scope.`);for(let G of L)K.set(G.id,G)}let X=[...K.values()].map((Y)=>({l:{pd:Y.definitionId,v:{so:Y.id}}})).reduce((Y,L)=>Y===void 0?L:{[$.tagsMatch==="all"?"&":"|"]:[Y,L]},void 0);O.propf=Y2(O.propf,X)}return O}}class lx{client;constructor($){this.client=$}async page($={}){let O=new bj(this.client);return this.fetch(O,await O.body($),$.cursor)}async*list($={}){let O=new bj(this.client),j=await O.body($);yield*c((x)=>this.fetch(O,j,x))}async fetch($,O,j){let x=Q(await this.client.storage.postItemsSoupAst({body:O,query:j?{cursor:j}:void 0})),K=x.items.some((Z)=>ux(Z).some((X)=>X.definition.data_type==="TAG"))?await $.tagMap():new Map;return{items:x.items.map((Z)=>X2(this.client,Z,K)),nextCursor:x.next_cursor,hasMore:x.next_cursor!=null}}}function Q2({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...G}){let J,I=Y??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,H=G.signal??new AbortController().signal;while(!0){if(H.aborted)break;B++;let A=G.headers instanceof Headers?G.headers:new Headers(G.headers);if(J!==void 0)A.set("Last-Event-ID",J);try{let D={redirect:"follow",...G,body:G.serializedBody,headers:A,signal:H},_=new Request(L,D);if($)_=await $(L,D);let N=await(G.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let T=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{T.cancel()}catch{}};H.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await T.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
+async function cO($,O,j){if(!Number.isInteger(O)||O<1)throw RangeError(`concurrency limit must be a positive integer, got ${O}`);let x=Array($.length),S=0,K=async()=>{while(S<$.length){let X=S;S+=1,x[X]=await j($[X])}},Z=Array.from({length:Math.min(O,$.length)},K);return await Promise.all(Z),x}class W${loader;value;inflight;constructor($,O){this.loader=$;this.value=O}get(){if(this.value!==void 0)return Promise.resolve(this.value);return this.inflight??=this.loader().then(($)=>{return this.value=$,$}),this.inflight}peek(){return this.value}clear(){this.value=void 0,this.inflight=void 0}}async function*c($){let O;do{let j=await $(O),x=j.nextCursor??void 0;if(O!==void 0&&x!==void 0&&JSON.stringify(x)===JSON.stringify(O))throw Error("Pagination cursor did not advance");yield*j.items,O=x}while(O!==void 0)}var X$=Symbol.for("@ts-pattern/matcher"),i1=Symbol.for("@ts-pattern/isVariadic");var u0=($)=>Boolean($&&typeof $=="object"),Bj=($)=>$&&!!$[X$],s=($,O,j)=>{if(Bj($)){let x=$[X$](),{matched:S,selections:K}=x.match(O);return S&&K&&Object.keys(K).forEach((Z)=>j(Z,K[Z])),S}if(u0($)){if(!u0(O))return!1;if(Array.isArray($)){if(!Array.isArray(O))return!1;let x=[],S=[],K=[];for(let Z of $.keys()){let X=$[Z];Bj(X)&&X[i1]?K.push(X):K.length?S.push(X):x.push(X)}if(K.length){if(K.length>1)throw Error("Pattern error: Using `...P.array(...)` several times in a single pattern is not allowed.");if(O.length<x.length+S.length)return!1;let Z=O.slice(0,x.length),X=S.length===0?[]:O.slice(-S.length),Y=O.slice(x.length,S.length===0?1/0:-S.length);return x.every((L,G)=>s(L,Z[G],j))&&S.every((L,G)=>s(L,X[G],j))&&(K.length===0||s(K[0],Y,j))}return $.length===O.length&&$.every((Z,X)=>s(Z,O[X],j))}return Reflect.ownKeys($).every((x)=>{let S=$[x];return((x in O)||Bj(K=S)&&K[X$]().matcherType==="optional")&&s(S,O[x],j);var K})}return Object.is(O,$)},Z$=($)=>{var O,j,x;return u0($)?Bj($)?(O=(j=(x=$[X$]()).getSelectionKeys)==null?void 0:j.call(x))!=null?O:[]:Array.isArray($)?dO($,Z$):dO(Object.values($),Z$):[]},dO=($,O)=>$.reduce((j,x)=>j.concat(O(x)),[]);function r7(...$){if($.length===1){let[O]=$;return(j)=>s(O,j,()=>{})}if($.length===2){let[O,j]=$;return s(O,j,()=>{})}throw Error(`isMatching wasn't given the right number of arguments: expected 1 or 2, received ${$.length}.`)}function e($){return Object.assign($,{optional:()=>l0($),and:(O)=>l($,O),or:(O)=>n1($,O),select:(O)=>O===void 0?lO($):lO(O,$)})}function c0($){return Object.assign(((O)=>Object.assign(O,{[Symbol.iterator](){let j=0,x=[{value:Object.assign(O,{[i1]:!0}),done:!1},{done:!0,value:void 0}];return{next:()=>{var S;return(S=x[j++])!=null?S:x.at(-1)}}}}))($),{optional:()=>c0(l0($)),select:(O)=>c0(O===void 0?lO($):lO(O,$))})}function l0($){return e({[X$]:()=>({match:(O)=>{let j={},x=(S,K)=>{j[S]=K};return O===void 0?(Z$($).forEach((S)=>x(S,void 0)),{matched:!0,selections:j}):{matched:s($,O,x),selections:j}},getSelectionKeys:()=>Z$($),matcherType:"optional"})})}var p7=($,O)=>{for(let j of $)if(!O(j))return!1;return!0},a7=($,O)=>{for(let[j,x]of $.entries())if(!O(x,j))return!1;return!0},i7=($,O)=>{let j=Reflect.ownKeys($);for(let x of j)if(!O(x,$[x]))return!1;return!0};function l(...$){return e({[X$]:()=>({match:(O)=>{let j={},x=(S,K)=>{j[S]=K};return{matched:$.every((S)=>s(S,O,x)),selections:j}},getSelectionKeys:()=>dO($,Z$),matcherType:"and"})})}function n1(...$){return e({[X$]:()=>({match:(O)=>{let j={},x=(S,K)=>{j[S]=K};return dO($,Z$).forEach((S)=>x(S,void 0)),{matched:$.some((S)=>s(S,O,x)),selections:j}},getSelectionKeys:()=>dO($,Z$),matcherType:"or"})})}function u($){return{[X$]:()=>({match:(O)=>({matched:Boolean($(O))})})}}function lO(...$){let O=typeof $[0]=="string"?$[0]:void 0,j=$.length===2?$[1]:typeof $[0]=="string"?void 0:$[0];return e({[X$]:()=>({match:(x)=>{let S={[O!=null?O:"@ts-pattern/anonymous-select-key"]:x};return{matched:j===void 0||s(j,x,(K,Z)=>{S[K]=Z}),selections:S}},getSelectionKeys:()=>[O!=null?O:"@ts-pattern/anonymous-select-key"].concat(j===void 0?[]:Z$(j))})})}function s1($){return!0}function w$($){return typeof $=="number"}function i$($){return typeof $=="string"}function n$($){return typeof $=="bigint"}var t1=e(u(s1)),n7=e(u(s1)),s7=t1,s$=($)=>Object.assign(e($),{startsWith:(O)=>{return s$(l($,(j=O,u((x)=>i$(x)&&x.startsWith(j)))));var j},endsWith:(O)=>{return s$(l($,(j=O,u((x)=>i$(x)&&x.endsWith(j)))));var j},minLength:(O)=>s$(l($,((j)=>u((x)=>i$(x)&&x.length>=j))(O))),length:(O)=>s$(l($,((j)=>u((x)=>i$(x)&&x.length===j))(O))),maxLength:(O)=>s$(l($,((j)=>u((x)=>i$(x)&&x.length<=j))(O))),includes:(O)=>{return s$(l($,(j=O,u((x)=>i$(x)&&x.includes(j)))));var j},regex:(O)=>{return s$(l($,(j=O,u((x)=>i$(x)&&Boolean(x.match(j))))));var j}}),a1=s$(u(i$)),f$=($)=>Object.assign(e($),{between:(O,j)=>f$(l($,((x,S)=>u((K)=>w$(K)&&x<=K&&S>=K))(O,j))),lt:(O)=>f$(l($,((j)=>u((x)=>w$(x)&&x<j))(O))),gt:(O)=>f$(l($,((j)=>u((x)=>w$(x)&&x>j))(O))),lte:(O)=>f$(l($,((j)=>u((x)=>w$(x)&&x<=j))(O))),gte:(O)=>f$(l($,((j)=>u((x)=>w$(x)&&x>=j))(O))),int:()=>f$(l($,u((O)=>w$(O)&&Number.isInteger(O)))),finite:()=>f$(l($,u((O)=>w$(O)&&Number.isFinite(O)))),positive:()=>f$(l($,u((O)=>w$(O)&&O>0))),negative:()=>f$(l($,u((O)=>w$(O)&&O<0)))}),t7=f$(u(w$)),t$=($)=>Object.assign(e($),{between:(O,j)=>t$(l($,((x,S)=>u((K)=>n$(K)&&x<=K&&S>=K))(O,j))),lt:(O)=>t$(l($,((j)=>u((x)=>n$(x)&&x<j))(O))),gt:(O)=>t$(l($,((j)=>u((x)=>n$(x)&&x>j))(O))),lte:(O)=>t$(l($,((j)=>u((x)=>n$(x)&&x<=j))(O))),gte:(O)=>t$(l($,((j)=>u((x)=>n$(x)&&x>=j))(O))),positive:()=>t$(l($,u((O)=>n$(O)&&O>0))),negative:()=>t$(l($,u((O)=>n$(O)&&O<0)))}),e7=t$(u(n$)),o7=e(u(function($){return typeof $=="boolean"})),$5=e(u(function($){return typeof $=="symbol"})),O5=e(u(function($){return $==null})),j5=e(u(function($){return $!=null})),t={__proto__:null,matcher:X$,optional:l0,array:function(...$){return c0({[X$]:()=>({match:(O)=>{if(!Array.isArray(O))return{matched:!1};if($.length===0)return{matched:!0};let j=$[0],x={};if(O.length===0)return Z$(j).forEach((K)=>{x[K]=[]}),{matched:!0,selections:x};let S=(K,Z)=>{x[K]=(x[K]||[]).concat([Z])};return{matched:O.every((K)=>s(j,K,S)),selections:x}},getSelectionKeys:()=>$.length===0?[]:Z$($[0])})})},set:function(...$){return e({[X$]:()=>({match:(O)=>{if(!(O instanceof Set))return{matched:!1};let j={};if(O.size===0)return{matched:!0,selections:j};if($.length===0)return{matched:!0};let x=(K,Z)=>{j[K]=(j[K]||[]).concat([Z])},S=$[0];return{matched:p7(O,(K)=>s(S,K,x)),selections:j}},getSelectionKeys:()=>$.length===0?[]:Z$($[0])})})},map:function(...$){return e({[X$]:()=>({match:(O)=>{if(!(O instanceof Map))return{matched:!1};let j={};if(O.size===0)return{matched:!0,selections:j};let x=(X,Y)=>{j[X]=(j[X]||[]).concat([Y])};if($.length===0)return{matched:!0};var S;if($.length===1)throw Error(`\`P.map\` wasn't given enough arguments. Expected (key, value), received ${(S=$[0])==null?void 0:S.toString()}`);let[K,Z]=$;return{matched:a7(O,(X,Y)=>{let L=s(K,Y,x),G=s(Z,X,x);return L&&G}),selections:j}},getSelectionKeys:()=>$.length===0?[]:[...Z$($[0]),...Z$($[1])]})})},record:function(...$){return e({[X$]:()=>({match:(O)=>{if(O===null||typeof O!="object"||Array.isArray(O))return{matched:!1};var j;if($.length===0)throw Error(`\`P.record\` wasn't given enough arguments. Expected (value) or (key, value), received ${(j=$[0])==null?void 0:j.toString()}`);let x={},S=(X,Y)=>{x[X]=(x[X]||[]).concat([Y])},[K,Z]=$.length===1?[a1,$[0]]:$;return{matched:i7(O,(X,Y)=>{let L=typeof X!="string"||Number.isNaN(Number(X))?null:Number(X),G=L!==null&&s(K,L,S),J=s(K,X,S),I=s(Z,Y,S);return(J||G)&&I}),selections:x}},getSelectionKeys:()=>$.length===0?[]:[...Z$($[0]),...Z$($[1])]})})},intersection:l,union:n1,not:function($){return e({[X$]:()=>({match:(O)=>({matched:!s($,O,()=>{})}),getSelectionKeys:()=>[],matcherType:"not"})})},when:u,select:lO,any:t1,unknown:n7,_:s7,string:a1,number:t7,bigint:e7,boolean:o7,symbol:$5,nullish:O5,nonNullable:j5,instanceOf:function($){return e(u(function(O){return(j)=>j instanceof O}($)))},shape:function($){return e(u(r7($)))}};class e1 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 d0={matched:!1,value:void 0};function k($){return new Lj($,d0)}class Lj{constructor($,O){this.input=void 0,this.state=void 0,this.input=$,this.state=O}with(...$){if(this.state.matched)return this;let O=$[$.length-1],j=[$[0]],x;$.length===3&&typeof $[1]=="function"?x=$[1]:$.length>2&&j.push(...$.slice(1,$.length-1));let S=!1,K={},Z=(Y,L)=>{S=!0,K[Y]=L},X=!j.some((Y)=>s(Y,this.input,Z))||x&&!Boolean(x(this.input))?d0:{matched:!0,value:O(S?"@ts-pattern/anonymous-select-key"in K?K["@ts-pattern/anonymous-select-key"]:K:this.input,this.input)};return new Lj(this.input,X)}when($,O){if(this.state.matched)return this;let j=Boolean($(this.input));return new Lj(this.input,j?{matched:!0,value:O(this.input,this.input)}:d0)}otherwise($){return this.state.matched?this.state.value:$(this.input)}exhaustive($=x5){return this.state.matched?this.state.value:$(this.input)}run(){return this.exhaustive()}returnType(){return this}narrow(){return this}}function x5($){throw new e1($)}class f extends Error{constructor($){super($);this.name="MacroError"}}var o1=500;function S5($){let O=k($).with(t.string,(j)=>j).with({message:t.string},({message:j})=>j).with({error:t.string},({error:j})=>j).otherwise(()=>"").trim();return O.length>o1?`${O.slice(0,o1)}…`:O}class e$ extends f{status;data;constructor($,O){let j=S5(O);super(j?`Macro API error ${$}: ${j}`:`Macro API error ${$}`);this.status=$;this.data=O;this.name="MacroApiError"}}class r0 extends e${constructor($){super(403,$);this.name="MacroForbiddenError"}}function Z5($,O){return $===403?new r0(O):new e$($,O)}class E extends f{constructor($){super($);this.name="MacroNotFoundError"}}function Q($){if($.error!==void 0)throw Z5($.response?.status??0,$.error);return $.data}class P{client;id;detail;constructor($,O,j){this.client=$;this.id=O;this.detail=new W$(()=>this.fetch(),j)}field($){return async()=>(await this.detail.get())[$]??void 0}mappedField($,O){return async()=>O((await this.detail.get())[$]??void 0)}toJSON(){let $=this.detail.peek();return $===void 0?{id:this.id}:{id:this.id,detail:$}}async mutate($){let O=Q(await $(this.client));return this.detail.clear(),O}}class H$ extends P{async permission(){return Q(await this.client.storage.getEntityPermission({path:{entity_type:this.entityType,entity_id:this.id}}))}async favorite(){return Q(await this.client.storage.addFavorite({body:{entityId:this.id,entityType:this.entityType}})),this}async unfavorite(){return Q(await this.client.storage.removeFavoriteByEntity({path:{entity_type:this.entityType,entity_id:this.id}})),this}}class K$ extends H${propertyReference(){return{entity_type:this.propertyEntityType,entity_id:this.id}}async properties($){let{properties:O}=Q(await this.client.properties.getEntityProperties({path:{entity_type:this.propertyEntityType,entity_id:this.id},query:$?.includeMetadata!==void 0?{include_metadata:$.includeMetadata}:void 0}));return O}async setProperty($,O){Q(await this.client.properties.setEntityProperty({path:{...this.propertyReference(),property_id:$.id},body:{value:O??null}}))}async updatePropertyOptions($){return Q(await this.client.properties.bulkUpdateEntityPropertyOptions({path:this.propertyReference(),body:{properties:$.map((O)=>({property_id:O.property.id,...O.add?{add_option_ids:O.add.map((j)=>j.id)}:{},...O.remove?{remove_option_ids:O.remove.map((j)=>j.id)}:{}}))}}))}async deleteProperty($){Q(await this.client.properties.deleteEntityProperty({path:{entity_property_id:$.property.id}}))}}var X5={"<":"\\u003c",">":"\\u003e","&":"\\u0026"};function o$($,O){let j=JSON.stringify(O).replace(/[<>&]/g,(x)=>X5[x]??x);return`<${$}>${j}</${$}>`}function K5($){return typeof $==="object"&&$!==null&&typeof $.toMention==="function"}var Y5={toMention:()=>({tag:o$("m-group-mention",{groupAlias:"here"}),mention:{entity_type:"group",entity_id:"here"}})};function Q5($,...O){let j="",x=[];for(let[S,K]of $.entries()){j+=K;let Z=O[S];if(Z===void 0)continue;if(K5(Z)){let X=Z.toMention();j+=X.tag,x.push(X.mention)}else j+=String(Z)}return{content:j,mentions:G5(x)}}function G5($){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 P{static byId($,O){return new B$($,O)}static from($,O){return new B$($,O.id,O)}async fetch(){let $=Q(await this.client.storage.listHarnesses()).find((O)=>O.id===this.id);if(!$)throw new E(`Harness ${this.id} is unavailable`);return $}name=this.field("name");connected=this.field("connected");kind=this.field("kind");async delete(){await this.mutate(($)=>$.storage.deleteHarness({path:{harness_id:this.id}}))}}class T$ extends P{static byId($,O){return new T$($,O)}static from($,O){return new T$($,O.bot.id,O)}async fetch(){let $=Q(await this.client.storage.listAgents()).find((O)=>O.bot.id===this.id);if(!$)throw new E(`Agent ${this.id} is unavailable`);return $}name=this.mappedField("bot",($)=>$.name);instructions=this.field("instructions");defaultModel=this.field("default_model");channels=this.mappedField("channel_ids",($)=>$.map((O)=>b.byId(this.client,O)));host=this.mappedField("harness_id",($)=>$?B$.byId(this.client,$):void 0);async update($){await this.mutate((O)=>O.storage.updateAgent({path:{agent_id:this.id},body:p0($)}))}}function p0($){let{channels:O,team:j,host:x,autoAcceptPermissions:S,avatarUrl:K,channelScope:Z,defaultModel:X,isCoding:Y,...L}=$;return{...L,channel_ids:O?.map((G)=>G.id),team_id:j?.id,harness_id:x?.id,auto_accept_permissions:S,avatar_url:K,channel_scope:Z,default_model:X,is_coding:Y}}async function Nj($,O,j,x=[]){let{channelId:S,thread:K}=V5(O);if(await W5($)){let{id:X}=Q(await $.storage.entityMessageCreate({path:{parent_type:"channel",parent_id:S},body:{content:j.content,mentions:j.mentions,attachments:x.map((Y)=>({entity_type:J5,entity_id:Y.id,width:Y.width??null,height:Y.height??null})),thread_id:K?.rootId??null,nonce:crypto.randomUUID()}}));return X}if(x.length>0)throw new f("a user-owned bot can only post via the channel webhook endpoint, which "+"does not support images — use a team-owned bot, or requestedAs(user), "+"to attach images");if(K)throw new f("a user-owned bot can only post via the channel webhook endpoint, which "+"does not support threads — use a team-owned bot, or requestedAs(user), "+"to reply in a thread");let{message_id:Z}=Q(await $.storage.postChannelBotWebhook({path:{channel_id:S},body:{content:j.content},headers:{"x-macro-bot-scope":"user"}}));return Z}var J5="static/image";function V5($){return"rootId"in $?{channelId:$.channelId,thread:$}:{channelId:$.id}}async function W5($){if($.authConfig.type!=="bot"||$.hasActingUser())return!0;let{owner:O}=await $.selfBot();return O?.type==="team"}class h${client;channelId;rootId;constructor($,O,j){this.client=$;this.channelId=O;this.rootId=j}toJSON(){return{channelId:this.channelId,rootId:this.rootId}}channel(){return b.byId(this.client,this.channelId)}root(){return o.byId(this.client,this.channelId,this.rootId)}async replies(){let{replies:$}=Q(await this.client.storage.entityMessageGetThread({path:{parent_type:"channel",parent_id:this.channelId,id:this.rootId}}));return $.map((O)=>o.from(this.client,this.channelId,O))}async reply($,O){let j=await Nj(this.client,this,O$($),O?.images);return o.byId(this.client,this.channelId,j)}}class o extends H${channelId;mentions;entityType="channel_message";constructor($,O,j,x=[],S){super($,j,S);this.channelId=O;this.mentions=x}get path(){return{parent_type:"channel",parent_id:this.channelId,id:this.id}}async fetch(){return Q(await this.client.storage.entityMessageGetMessage({path:this.path}))}static byId($,O,j,x=[]){return new o($,O,j,x)}static from($,O,j){return new o($,O,j.id,j.mentions,j)}content=this.field("content");createdAt=this.field("created_at");editedAt=this.field("edited_at");updatedAt=this.field("updated_at");async author(){return C.byId(this.client,(await this.detail.get()).sender_id)}channel(){return b.byId(this.client,this.channelId)}thread(){return new h$(this.client,this.channelId,this.id)}async react($){return await this.mutate((O)=>O.storage.entityMessageReact({path:this.path,body:{add:!0,emoji:$}})),this}async unreact($){return await this.mutate((O)=>O.storage.entityMessageReact({path:this.path,body:{add:!1,emoji:$}})),this}async edit($){let{content:O,mentions:j}=O$($);return await this.mutate((x)=>x.storage.entityMessageEdit({path:this.path,body:{content:O,mentions:j}})),this}async delete(){await this.mutate(($)=>$.storage.entityMessageDeleteMessage({path:this.path}))}async reply($){return this.thread().reply($)}}class Uj{client;channel;record;constructor($,O,j){this.client=$;this.channel=O;this.record=j}agent(){return T$.byId(this.client,this.record.botId)}sessions(){return this.record.sessions.map(($)=>({session:d.byId(this.client,$.sessionId),isCurrent:$.isCurrent,createdAt:$.createdAt}))}turns(){return this.record.turns.map(($)=>new a0(this.client,this,$))}async startFresh($){Q(await this.client.agentHarness.startFreshAgentConversation({path:{channel_id:this.channel.id,bot_id:this.record.botId},body:{sessionId:$.id}}))}toJSON(){return{channelId:this.channel.id,agentId:this.record.botId}}}class a0{client;conversation;record;constructor($,O,j){this.client=$;this.conversation=O;this.record=j}source(){return o.byId(this.client,this.conversation.channel.id,this.record.sourceMessageId)}session(){return d.byId(this.client,this.record.sessionId)}async retry($){Q(await this.client.agentHarness.retryAgentConversationTurn({path:{channel_id:this.conversation.channel.id,bot_id:this.conversation.agent().id,source:this.record.sourceMessageId},body:{actionId:$}}))}toJSON(){return{channelId:this.conversation.channel.id,sourceMessageId:this.record.sourceMessageId}}}class L$ extends P{parent;toJSON(){return{...super.toJSON(),parentType:this.parent.type,parentId:this.parent.entity.id}}constructor($,O,j){super($,j);this.parent=O}static byId($,O,j){return new L$($,O,j)}get path(){return{parent_type:this.parent.type,parent_id:this.parent.entity.id,id:this.id}}async fetch(){return Q(await this.client.storage.entityMessageGetThread({path:this.path})).state}resolved=this.field("resolved");async update($){let O={resolved:$.resolved,detach_anchor:$.detachAnchor,nonce:$.nonce};await this.mutate((j)=>j.storage.entityMessagePatchThread({path:this.path,body:O}))}async delete($){await this.mutate((O)=>O.storage.entityMessageDeleteThread({path:this.path,query:{nonce:$}}))}}async function b$($,O,j,x){for(let K of[...x?.messages??[],...x?.around?[x.around]:[]]){let Z="channelId"in K?{type:"channel",id:K.channelId}:("documentId"in K)?{type:"document",id:K.documentId}:("callId"in K)?{type:"call",id:K.callId}:K.parent;if(Z.type!==O.type||Z.id!==O.entity.id)throw Error("Timeline message belongs to another resource")}let S=Q(await $.storage.messageTimelineEntries({path:{parent_type:O.type,parent_id:O.entity.id},query:{selection:x?JSON.stringify({cursor:x.cursor,around:x.around?.id,ids:x.messages?.map((K)=>K.id),activity_after:x.activityAfter,activity_before:x.activityBefore,anchored:x.anchored,direction:x.direction,include_deleted_threads:x.includeDeletedThreads,limit:x.limit}):void 0}}));return{entries:S.entries.map((K)=>{if(K.type==="activity")return{type:"activity",activity:{...K.activity,actor:C.byId($,K.activity.actor_id)}};return{type:"message",message:j(K.message)}}),nextCursor:S.next_cursor??void 0,previousCursor:S.previous_cursor??void 0}}var B5=50;function x$($){let{filters:O,type:j,make:x,includeCrm:S}=$;return(K,Z,X)=>{let Y=X?.searchOn??"name_content",L=X?.pageSize??B5;return c(async(G)=>{let{results:J,next_cursor:I}=Q(await K.search.unifiedSearch({body:{query:Z,match_type:"partial",search_on:Y,...O?{filters:O}:{},...S?{include_crm:!0}:{}},query:{page_size:L,...G?{cursor:G}:{}}}));return{items:J.filter((W)=>W.type===j).map((W)=>x(K,W)),nextCursor:I}})}}class GO{client;channel;record;constructor($,O,j){this.client=$;this.channel=O;this.record=j}get id(){return this.record.id}user(){return C.byId(this.client,this.record.user_id)}createdAt(){return this.record.created_at}async recordInteraction($){return new GO(this.client,this.channel,Q(await this.client.storage.postActivity({body:{activity_type:$,channel_id:this.channel.id}})))}toJSON(){return this.record}}class b extends K${async recordActivity($){return new GO(this.client,this,Q(await this.client.storage.postActivity({body:{activity_type:$,channel_id:this.id}})))}async setPicture($){await this.mutate((O)=>O.storage.setChannelPicture({path:{channel_id:this.id},body:{profile_picture_id:$?.id??null}}))}messageThreadById($){return L$.byId(this.client,{type:"channel",entity:this},$)}timelinePage($){return b$(this.client,{type:"channel",entity:this},(O)=>o.from(this.client,this.id,O),$)}async agentConversations(){return Q(await this.client.agentHarness.listAgentConversations({path:{channel_id:this.id}})).conversations.map(($)=>new Uj(this.client,this,$))}entityType="channel";propertyEntityType="CHANNEL";async fetch(){return Q(await this.client.storage.getChannel({path:{channel_id:this.id}}))}static byId($,O){return new b($,O)}static async dm($,O){let{channel_id:j}=Q(await $.storage.getOrCreateDm({body:{recipient_id:O.id}}));return new b($,j)}static async private($,O){let{channel_id:j}=Q(await $.storage.getOrCreatePrivate({body:{recipients:O.map((x)=>x.id)}}));return new b($,j)}static async create($,O){let{id:j}=Q(await $.storage.createChannel({body:{channel_type:O.type,name:O.name??null,participants:(O.participants??[]).map((x)=>x.id),team_id:O.team?.id??null}}));return new b($,j)}name=this.field("channel_name");type=this.field("channel_type");async send($,O){let j=await Nj(this.client,O?.thread??this,O$($),O?.images);return o.byId(this.client,this.id,j)}messages($){return this.timeline({limit:$?.pageSize})}messagesAfter($,O){return this.timeline({activity_after:$ instanceof Date?$.toISOString():$,limit:O?.pageSize})}timeline($){return c(async(O)=>{let j=Q(await this.client.storage.messageTimeline({path:{parent_type:"channel",parent_id:this.id},query:{selection:JSON.stringify({...$,cursor:O})}}));return{items:j.items.map((x)=>o.from(this.client,this.id,x)),nextCursor:j.next_cursor}})}message($){return o.byId(this.client,this.id,$)}async rename($){await this.mutate((O)=>O.storage.patchChannel({path:{channel_id:this.id},body:{channel_name:$}}))}async delete(){await this.mutate(($)=>$.storage.deleteChannel({path:{channel_id:this.id}}))}async join(){await this.mutate(($)=>$.storage.joinChannel({path:{channel_id:this.id}}))}async joinCode(){let{join_code:$}=Q(await this.client.storage.getChannelJoinLink({path:{channel_id:this.id}}));return $}async leave(){await this.mutate(($)=>$.storage.leaveChannel({path:{channel_id:this.id}}))}async participants(){return Q(await this.client.storage.getChannelParticipants({path:{channel_id:this.id}}))}async addParticipants($){await this.mutate((O)=>O.storage.addParticipants({path:{channel_id:this.id},body:{participants:$.map((j)=>j.id)}}))}async removeParticipants($){await this.mutate((O)=>O.storage.removeParticipants({path:{channel_id:this.id},body:{participants:$.map((j)=>j.id)}}))}async typing($,O){Q(await this.client.storage.entityMessageTyping({path:{parent_type:"channel",parent_id:this.id},body:{active:$==="start",thread_id:O?.thread?.rootId??null}}))}attachments($){return c(async(O)=>{let j=Q(await this.client.storage.getChannelAttachments({path:{channel_id:this.id},query:{...$?.pageSize?{limit:$.pageSize}:{},...$?.type?{attachment_type:$.type}:{},...O?{cursor:O}:{}}}));return{items:j.items,nextCursor:j.next_cursor}})}webUrl(){return`${this.client.webAppUrl}/app/channel/${this.id}`}static search=x$({type:"channel",make:($,O)=>new b($,O.channel_id)})}class C extends K${entityType="user";propertyEntityType="USER";async fetch(){let{names:$}=Q(await this.client.auth.getUserNamesWithEmail({body:{user_ids:[this.id]}})),O=$.find((j)=>j.id===this.id);if(!O)throw new E(`user ${this.id} not found`);return O}static byId($,O){return new C($,O)}static fromName($,O){return new C($,O.id,O)}static async me($){let{user_id:O}=Q(await $.auth.getUserInfo());return new C($,O)}async name(){let $=await this.detail.get();return[$.first_name,$.last_name].filter(Boolean).join(" ")||void 0}email(){let $=this.id.startsWith("macro|")?this.id.slice(6):void 0;return $?.includes("@")?$:void 0}dm(){return b.dm(this.client,this)}toMention(){return{tag:o$("m-user-mention",{userId:this.id}),mention:{entity_type:"user",entity_id:this.id}}}}class $${client;entityType;entity;constructor($,O,j){this.client=$;this.entityType=O;this.entity=j}get path(){return{entity_type:this.entityType,entity_id:this.entity.id}}async state($){let O=Q(await this.client.storage.accessRequestsState({path:this.path,query:{offset:$}}));return{accessLevel:O.accessLevel??void 0,canReview:O.canReview,owner:O.owner?C.byId(this.client,O.owner):void 0,pendingCount:O.pendingCount,supportedLevels:O.supportedLevels,nextOffset:O.nextOffset??void 0,mine:O.mine?IO.from(this.client,this,O.mine):void 0,requests:O.requests.map((j)=>IO.from(this.client,this,j))}}async request($){let{mine:O}=await this.state();return this.submit($,O?await O.revision():void 0)}async submit($,O){return IO.from(this.client,this,Q(await this.client.storage.accessRequestsSubmit({path:this.path,body:{requestedLevel:$,revision:O}})))}async cancel($){Q(await this.client.storage.accessRequestsCancel({path:this.path,query:{revision:$}}))}async direct(){return Q(await this.client.storage.accessRequestsDirect({path:this.path})).map(($)=>({user:C.byId(this.client,$.userId),accessLevel:$.accessLevel}))}async grant($,O){Q(await this.client.storage.accessRequestsSetDirect({path:{...this.path,user_id:$.id},body:{accessLevel:O}}))}async remove($){Q(await this.client.storage.accessRequestsRemoveDirect({path:{...this.path,user_id:$.id}}))}async resolve($,O){let j=$.access.toJSON();if(j.entity_type!==this.entityType||j.entity_id!==this.entity.id)throw Error("Access request belongs to another entity");return Q(await this.client.storage.accessRequestsResolve({path:{...this.path,request_id:$.id},body:O}))}toJSON(){return this.path}}class IO extends P{access;resolvedRecord;constructor($,O,j){super($,j.id,j);this.access=O}static from($,O,j){return new IO($,O,j)}async fetch(){if(this.resolvedRecord)return this.resolvedRecord;let $;do{let O=await this.access.state($),j=[O.mine,...O.requests].find((x)=>x?.id===this.id);if(j)return j.detail.get();$=O.nextOffset}while($!==void 0);throw new E(`Access request ${this.id} is unavailable`)}revision=this.field("revision");status=this.field("status");requestedLevel=this.field("requestedLevel");requester=this.mappedField("requesterId",($)=>C.byId(this.client,$));async resolve($){this.resolvedRecord=await this.access.resolve(this,{revision:await this.revision(),grantedLevel:$}),this.detail.clear()}}function $O($){return{...$,channelSharePermissions:$.channelSharePermissions===void 0||$.channelSharePermissions===null?$.channelSharePermissions:$.channelSharePermissions.map((O)=>({channelId:O.channel.id,accessLevel:O.accessLevel,operation:O.operation}))}}function i0($){return $}class N$ extends P{parent;constructor($,O,j,x){super($,j,x);this.parent=O}static byId($,O,j){return new N$($,O,j)}static fromRecord($,O,j){return new N$($,O,j.id,j)}static async create($,O,j){return N$.createForSession($,O.session(),j,O)}static async createForSession($,O,j,x){let S=Q(await $.agentHarness.createSessionReview({path:{session_id:O.id},body:{...j,executionId:x?.id??null}}));return N$.fromRecord($,O,i0(S))}static async list($,O){return Q(await $.agentHarness.listExecutionReviews({path:{session_id:O.session().id,execution_id:O.id}})).map((x)=>N$.fromRecord($,O.session(),i0(x)))}async fetch(){return i0(Q(await this.client.agentHarness.getSessionReview({path:{session_id:this.parent.id,review_id:this.id}})))}title=this.field("title");kind=this.field("kind");session(){return this.parent}async reference(){return{kind:await this.kind(),id:this.id}}async items(){return(await this.detail.get()).items.map((j)=>new n0(j,{edit:(x)=>this.decide({action:"edit",item:j.id,draft:x}),submit:()=>this.decide({action:"submit",items:[j.id]}),dismiss:()=>this.decide({action:"dismiss",items:[j.id]})}))}async refresh(){return this.detail.clear(),await this.detail.get(),this}async submitAll(){await this.decide({action:"submit",items:[]})}async dismissAll(){await this.decide({action:"dismiss",items:[]})}async decide($){let O=(await this.detail.get()).revision;await this.mutate((j)=>j.agentHarness.decideSessionReview({path:{session_id:this.parent.id,review_id:this.id},body:{...$,revision:O}}))}}class n0{snapshot;actions;constructor($,O){this.snapshot=$;this.actions=O}get id(){return this.snapshot.id}get status(){return this.snapshot.status}get draft(){return this.snapshot.draft}get result(){return this.snapshot.result}async edit($){await this.actions.edit($)}async submit(){await this.actions.submit()}async dismiss(){await this.actions.dismiss()}}async function zj($,O,j,x){Q(await $.agentHarness.presentSessionView({path:{session_id:O.id},body:{view:j,executionId:x?.id??null}}))}class rO extends P{parent;constructor($,O,j){super($,O);this.parent=j}static byId($,O,j){return new rO($,j,O)}async fetch(){return Q(await this.client.agentHarness.getCodeExecution({path:{session_id:this.parent.id,execution_id:this.id}}))}reviews={create:($)=>N$.create(this.client,this,$),list:()=>N$.list(this.client,this)};views={present:($)=>zj(this.client,this.parent,$,this)};session(){return this.parent}status=this.field("status");source=this.field("source");calls=this.field("calls");error=this.field("error");async result(){return(await this.detail.get()).result}async refresh(){return this.detail.clear(),await this.detail.get(),this}}class Ij{client;sessionId;dto;constructor($,O,j){this.client=$;this.sessionId=O;this.dto=j}static from($,O,j){return new Ij($,O,j)}get actionId(){return this.dto.actionId}get kind(){return this.dto.kind}get prompt(){return this.dto.prompt??void 0}get attachments(){return this.dto.attachments??[]}get actorUserId(){return this.dto.actorUserId??void 0}get createdAt(){return this.dto.createdAt}async edit($){return Q(await this.client.agentHarness.editQueuedAction({path:{session_id:this.sessionId,action_id:this.actionId},body:{prompt:$}})),this.dto={...this.dto,prompt:$},this}async steer(){Q(await this.client.agentHarness.steerQueuedAction({path:{session_id:this.sessionId,action_id:this.actionId}}))}async remove(){Q(await this.client.agentHarness.removeQueuedAction({path:{session_id:this.sessionId,action_id:this.actionId}}))}}class pO{client;session;id;constructor($,O,j){this.client=$;this.session=O;this.id=j}static byId($,O,j){return new pO($,O,j)}async answer($){return Q(await this.client.agentHarness.answerAgentSessionToolApproval({path:{session_id:this.session.id,approval_id:this.id},body:{answer:$}}))}toJSON(){return{id:this.id,sessionId:this.session.id}}}class d extends P{access=new $$(this.client,"agent_session",this);toolApprovalById($){return pO.byId(this.client,this,$)}async sharePermissions(){return Q(await this.client.agentHarness.getAgentSessionPermissions({path:{session_id:this.id}}))}async updateSharePermissions($){return this.mutate((O)=>O.agentHarness.updateAgentSessionPermissions({path:{session_id:this.id},body:$O($)}))}static byId($,O){return new d($,O)}static async createManaged($,O){let{session:j}=Q(await $.agentHarness.createAgentSession({body:{botId:O?.agent?.id,prompt:O?.prompt,instructions:O?.instructions,model:O?.model,repoUrl:O?.repoUrl,repoBranch:O?.repoBranch}}));return new d($,j.id,j)}static async repositories($){let{repositories:O}=Q(await $.agentHarness.listAgentRepositories());return O.map((j)=>({url:j.url,defaultBranch:j.defaultBranch??void 0}))}static async repositoryBranches($,O){let{branches:j}=Q(await $.agentHarness.listAgentRepositoryBranches({query:{repoUrl:O}}));return j}static async chooseMode($,O){let{mode:j}=Q(await $.agentHarness.chooseAgentMode({body:{prompt:O}}));return j}async fetch(){return Q(await this.client.agentHarness.getAgentSession({path:{session_id:this.id}}))}name=this.field("name");archivedBy=this.field("archivedBy");archivedAt=this.field("archivedAt");model=this.field("model");harness=this.field("harness");repoUrl=this.field("repoUrl");workspace=this.field("workspace");instructions=this.field("instructions");status=this.field("status");sandboxSize=this.field("sandboxSize");createdAt=this.field("createdAt");modifiedAt=this.field("modifiedAt");static async forPullRequest($,O){let{sessionIds:j}=Q(await $.agentHarness.agentSessionsForPullRequest({body:{url:O}}));return j.map((x)=>d.byId($,x))}async pullRequests(){let{pullRequests:$}=Q(await this.client.agentHarness.listAgentSessionPullRequests({path:{session_id:this.id}}));return $.map((O)=>({githubKey:O.githubKey,url:O.url,source:O.source,linkedBy:O.linkedBy?C.byId(this.client,O.linkedBy):void 0,createdAt:O.createdAt}))}async linkPullRequest($){Q(await this.client.agentHarness.linkAgentSessionPullRequest({path:{session_id:this.id},body:{url:$}}))}async unlinkPullRequest($){Q(await this.client.agentHarness.unlinkAgentSessionPullRequest({path:{session_id:this.id},query:{url:$}}))}async autoArchive(){let{overrides:$,defaults:O,autoArchivedAt:j}=Q(await this.client.agentHarness.getAgentSessionAutoArchive({path:{session_id:this.id}}));return{overrides:{onPullRequestMerged:$.onPullRequestMerged??void 0,onRuntimeClosed:$.onRuntimeClosed??void 0},defaults:O,autoArchivedAt:j??void 0}}async setAutoArchive($){Q(await this.client.agentHarness.putAgentSessionAutoArchive({path:{session_id:this.id},body:{onPullRequestMerged:$.onPullRequestMerged??null,onRuntimeClosed:$.onRuntimeClosed??null}}))}async rename($){await this.mutate((O)=>O.agentHarness.renameAgentSession({path:{session_id:this.id},body:{name:$}}))}async archive(){await this.setArchived(!0)}async unarchive(){await this.setArchived(!1)}async setArchived($){await this.mutate((O)=>O.agentHarness.setAgentSessionArchived({path:{session_id:this.id},body:{archived:$}}))}async setSandboxSize($){let{size:O}=await this.mutate((j)=>j.agentHarness.putAgentSessionSandboxSize({path:{session_id:this.id},body:{size:$}}));return O}static async defaultSandboxSize($){return Q(await $.agentHarness.getAgentSandboxSize()).size}static async setDefaultSandboxSize($,O){return Q(await $.agentHarness.putAgentSandboxSize({body:{size:O}})).size}static async codingPreferences($){return Q(await $.agentHarness.getAgentCodingPreferences())}static async autoArchivePreferences($){return Q(await $.agentHarness.getAgentAutoArchivePreferences())}static async setAutoArchivePreferences($,O){return Q(await $.agentHarness.putAgentAutoArchivePreferences({body:O}))}static async setCodingPreferences($,O){return Q(await $.agentHarness.putAgentCodingPreferences({body:O}))}async control($){return this.mutate((O)=>O.agentHarness.controlAgentSession({path:{session_id:this.id},body:$}))}prompt($,O){return this.control({type:"prompt",prompt:$,...O&&O.length>0?{attachments:O}:{}})}async queue(){let{entries:$}=Q(await this.client.agentHarness.getAgentSessionQueue({path:{session_id:this.id}}));return $.map((O)=>Ij.from(this.client,this.id,O))}async changes(){return Q(await this.client.agentHarness.getAgentSessionChanges({path:{session_id:this.id}}))}async changesPatch(){return Q(await this.client.agentHarness.getAgentSessionChangesPatch({path:{session_id:this.id}})).patch}async refreshChanges(){return this.mutate(($)=>$.agentHarness.refreshAgentSessionChanges({path:{session_id:this.id}}))}async foldedLog(){let{bot:$,messages:O}=Q(await this.client.agentHarness.getAgentSessionFoldedLog({path:{session_id:this.id}}));return{bot:$,messages:O}}async log(){return Q(await this.client.agentHarness.getAgentSessionLog({path:{session_id:this.id}}))}reviews={create:($)=>N$.createForSession(this.client,this,$),byId:($)=>N$.byId(this.client,this,$)};views={present:($)=>zj(this.client,this,$)};codeExecutions={byId:($)=>rO.byId(this.client,this,$)};async delete(){await this.mutate(($)=>$.agentHarness.deleteAgentSession({path:{session_id:this.id}}))}}class s0{client;constructor($){this.client=$}byId($){return d.byId(this.client,$)}createManaged($){return d.createManaged(this.client,$)}chooseMode($){return d.chooseMode(this.client,$)}repositories(){return d.repositories(this.client)}repositoryBranches($){return d.repositoryBranches(this.client,$)}forPullRequest($){return d.forPullRequest(this.client,$)}defaultSandboxSize(){return d.defaultSandboxSize(this.client)}setDefaultSandboxSize($){return d.setDefaultSandboxSize(this.client,$)}codingPreferences(){return d.codingPreferences(this.client)}autoArchivePreferences(){return d.autoArchivePreferences(this.client)}setAutoArchivePreferences($){return d.setAutoArchivePreferences(this.client,$)}setCodingPreferences($){return d.setCodingPreferences(this.client,$)}}class t0{client;constructor($){this.client=$}byId($){return T$.byId(this.client,$)}async list(){return Q(await this.client.storage.listAgents()).map(($)=>T$.from(this.client,$))}async create($){return T$.from(this.client,Q(await this.client.storage.createAgent({body:p0($)})))}}class e0{client;async usage($={}){let{users:O,...j}=$;return Q(await this.client.cognition.getUsageHandler({body:{...j,include_users:O?.map((x)=>x.id)}}))}constructor($){this.client=$}async structuredCompletion($){return Q(await this.client.cognition.structuredCompletion({body:$}))}async decide($){return Q(await this.client.cognition.decisions({body:$}))}}class OO extends P{static byId($,O){return new OO($,O)}static from($,O){return new OO($,O.id,{id:O.id,name:O.name,createdAt:O.createdAt})}async fetch(){let $=Q(await this.client.storage.listUserApiKeys()).keys.find((O)=>O.id===this.id);if(!$)throw new E(`API key ${this.id} is unavailable`);return $}name=this.field("name");createdAt=this.field("createdAt");async delete(){await this.mutate(($)=>$.storage.deleteUserApiKey({path:{id:this.id}}))}}class o0{client;constructor($){this.client=$}byId($){return OO.byId(this.client,$)}async list(){return Q(await this.client.storage.listUserApiKeys()).keys.map(($)=>OO.from(this.client,$))}async create($){let O=Q(await this.client.storage.createUserApiKey({body:{name:$}}));return{key:OO.from(this.client,O),secret:O.key}}async tokenForEmail($){return Q(await this.client.auth.macroApiToken({query:{email:$}}))}}class aO{client;constructor($){this.client=$}async me(){if(this.client.authConfig.type!=="bot")throw new f("bots.me() requires bot auth — a user API key has no bot identity");return Q(await this.client.storage.getSelfBot())}async channels(){if(this.client.authConfig.type!=="bot")throw new f("bots.channels() requires bot auth — a user API key has no bot identity");let $=await this.me();return Q(await this.client.storage.listBotChannels({path:{bot_id:$.id}}))}async myPrincipalId(){if(this.client.authConfig.type!=="bot")throw new f("bots.myPrincipalId() requires bot auth — a user API key has no bot identity");return this.client.myPrincipalId()}}class R$ extends P{async fetch(){let{links:$}=Q(await this.client.email.listLinks()),O=$.find((j)=>j.id===this.id);if(!O)throw new E(`email link ${this.id} not found`);return O}static byId($,O){return new R$($,O)}static async list($){let{links:O}=Q(await $.email.listLinks());return O.map((j)=>new R$($,j.id,j))}emailAddress=this.field("email_address");provider=this.field("provider");isPrimary=this.field("is_primary");isSyncActive=this.field("is_sync_active");syncStatus=this.field("sync_status");needsReauth=this.field("needs_reauth");photoUrl=this.field("photo_url");async settingsOperations(){return Q(await this.client.email.mailboxSettingsOperations({headers:{"X-Email-Link-Id":this.id}}))}}class m$ extends P{async setContributesToAvailability($){await this.mutate((O)=>O.calendar.setAvailabilityCalendar({path:{calendar_id:this.id},body:{contributesToAvailability:$}}))}async fetch(){let{calendars:$}=Q(await this.client.calendar.listCalendars()),O=$.find((j)=>j.id===this.id);if(!O)throw new E(`calendar ${this.id} not found`);return O}static byId($,O){return new m$($,O)}static async list($){let{calendars:O}=Q(await $.calendar.listCalendars());return O.map((j)=>new m$($,j.id,j))}name=this.field("name");emailAddress=this.field("emailAddress");isPrimary=this.field("isPrimary");isWritable=this.field("isWritable");contributesToAvailability=this.field("contributesToAvailability");isSubscription=this.field("isSubscription");color=this.field("color");syncError=this.field("syncError");emailLink=this.mappedField("emailLinkId",($)=>R$.byId(this.client,$))}class iO{client;id;constructor($,O){this.client=$;this.id=O}async status(){return Q(await this.client.calendar.calendarReplacementStatus({path:{operation_id:this.id}}))}async confirm(){return Q(await this.client.calendar.confirmCalendarReplacement({path:{operation_id:this.id}}))}async discard(){Q(await this.client.calendar.discardCalendarReplacement({path:{operation_id:this.id}}))}}class S$ extends P{async fetch(){throw new f(`calendar event ${this.id} has no fetch-by-id endpoint; read the record returned by calendar.createEvent / event.update / event.rsvp instead`)}static byId($,O){return new S$($,O)}static fromRecord($,O){return new S$($,O.id,O)}title=this.field("title");description=this.field("description");location=this.field("location");time=this.field("time");status=this.field("status");attendees=this.field("attendees");transparency=this.field("transparency");isReadOnly=this.field("isReadOnly");recurrenceLines=this.field("recurrenceLines");guestPolicy=this.field("guestPolicy");viewerCan=this.field("viewerCan");calendar=this.mappedField("calendarId",($)=>$?m$.byId(this.client,$):void 0);record(){return this.detail.get()}async update($){let O=await this.mutate((j)=>j.calendar.updateCalendarEvent({path:{event_id:this.id},body:L5($)}));return S$.fromRecord(this.client,O)}async delete($={}){await this.mutate((O)=>O.calendar.deleteCalendarEvent({path:{event_id:this.id},query:{calendarId:$.calendar?.id,scope:$.scope,recurrenceId:$.recurrenceId,inbox:$.inbox}}))}async prepareReplacement($){let O=Q(await this.client.calendar.prepareCalendarReplacement({path:{event_id:this.id},body:{removeConference:$.removeConference,recurrenceId:$.recurrenceId,calendarId:$.calendar?.id}}));return new iO(this.client,O.operationId)}async providerUrl($={}){return Q(await this.client.calendar.calendarEventProviderUrl({path:{event_id:this.id},query:{recurrenceId:$.recurrenceId,calendarId:$.calendar?.id}})).url??void 0}async inviteGuests($){let O=await this.mutate((j)=>j.calendar.inviteCalendarEventGuests({path:{event_id:this.id},body:{guests:$.guests,scope:$.scope,recurrenceId:$.recurrenceId,calendarId:$.calendar?.id,inbox:$.inbox}}));return S$.fromRecord(this.client,O)}async addToCalendar($={}){let O=await this.mutate((j)=>j.calendar.copyCalendarEvent({path:{event_id:this.id},body:{calendarId:$.calendar?.id}}));return S$.fromRecord(this.client,O)}async ics(){return Q(await this.client.storage.eventIcs({path:{event_id:this.id}}))}async rsvp($){let O=await this.mutate((j)=>j.calendar.rsvpCalendarEvent({path:{event_id:this.id},body:{response:$.response,scope:$.scope,recurrenceId:$.recurrenceId,calendarId:$.calendar?.id}}));return S$.fromRecord(this.client,O)}}function L5($){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 $x{client;async availabilityCalendars(){return Q(await this.client.calendar.getAvailabilityCalendars()).calendars.map(($)=>({calendar:m$.byId(this.client,$.calendarId),name:$.name,isPrimary:$.isPrimary,contributesToAvailability:$.contributesToAvailability}))}async teamSharing(){return Q(await this.client.calendar.getTeamSharing()).sharing}async setTeamSharing($){return Q(await this.client.calendar.setTeamSharing({body:{sharing:$}})).sharing}occurrences($){let O;return c(async(j)=>{let x=Q(await this.client.storage.listOccurrences({query:{...$,cursor:j}}));O??=U5(this.client);let S=await O;return{items:x.items.map((K)=>{let Z=K.event.calendarId?S.get(K.event.calendarId):void 0;return{event:S$.fromRecord(this.client,K.event),occurrence:K.occurrence,calendarName:Z?.name,contributesToAvailability:$2(K.event,S),inbox:Z?.emailAddress,role:z5(K.event,S)}}),nextCursor:x.nextCursor}})}async teamPage($){let O=Q(await this.client.storage.listTeamCalendar({query:$}));return{items:O.items.map(({ownerId:j,...x})=>({...x,owner:C.byId(this.client,j)})),members:O.members.map((j)=>({user:C.byId(this.client,j.userId),sharing:j.sharing,coverage:j.coverage})),nextCursor:O.nextCursor??void 0}}async teamOutOfOffice($){let O=Q(await this.client.storage.listTeamOutOfOffice({query:$}));return{items:O.items.map((j)=>({event:S$.byId(this.client,j.eventId),owner:C.byId(this.client,j.ownerId),occurrenceKey:j.occurrenceKey,time:j.time,title:j.title??void 0})),hasMore:O.hasMore}}constructor($){this.client=$}calendars(){return m$.list(this.client)}calendar($){return m$.byId(this.client,$)}event($){return S$.byId(this.client,$)}replacement($){return new iO(this.client,$)}async createEvent($){let O=Q(await this.client.calendar.createCalendarEvent({body:N5($)}));return S$.fromRecord(this.client,O)}}function N5($){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 U5($){let{calendars:O}=Q(await $.calendar.listCalendars());return new Map(O.map((j)=>[j.id,j]))}function $2($,O){let j=[$.calendarId,...($.sources??[]).map((x)=>x.calendarId)].flatMap((x)=>{let S=x?O.get(x):void 0;return S?[S.contributesToAvailability]:[]});if(j.some(Boolean))return!0;return j.length>0&&j.every((x)=>x===!1)?!1:void 0}function z5($,O){let j=$.attendees.find((S)=>S.isSelf);if(j?.isOrganizer)return $.isReadOnly?void 0:"organizer";let x=$.attendees.some((S)=>S.isOrganizer);if($.viewerCan.organize&&$2($,O)&&!x)return"organizer";return j?"guest":void 0}class D$ extends P{lookupToken;constructor($,O,j){super($,O,j);this.lookupToken=j?.shareToken}static byId($,O){return new D$($,O)}static from($,O){return new D$($,O.id,O)}async fetch(){if(this.lookupToken)return Q(await this.client.storage.meetingLookup({path:{token:this.lookupToken}}));let $=Q(await this.client.storage.meetingList()).meetings.find((O)=>O.id===this.id);if(!$)throw new E(`Meeting ${this.id} is unavailable`);return this.lookupToken=$.shareToken,$}title=this.field("title");scheduledStart=this.field("scheduledStart");scheduledEnd=this.field("scheduledEnd");channel=this.mappedField("channelId",($)=>$?b.byId(this.client,$):void 0);call=this.mappedField("callId",($)=>$?J$.byId(this.client,$):void 0);async update($){await this.mutate((O)=>O.storage.meetingUpdate({path:{meeting_id:this.id},body:$}))}async cancel(){await this.mutate(($)=>$.storage.meetingCancel({path:{meeting_id:this.id}}))}async invitePermissions(){return Q(await this.client.storage.meetingInvitePermissions({path:{token:(await this.detail.get()).shareToken}}))}async invite($){Q(await this.client.storage.meetingInvite({path:{token:(await this.detail.get()).shareToken},body:{email:$}}))}async inviteUsers($){Q(await this.client.storage.meetingInviteUsers({path:{token:(await this.detail.get()).shareToken},body:{userIds:$.map((O)=>O.id)}}))}async webUrl(){return`${this.client.webAppUrl}/app/meet/join/${encodeURIComponent((await this.detail.get()).shareToken)}`}}class u$ extends P{callId;constructor($,O,j,x){super($,j,x);this.callId=O}get path(){return{parent_type:"call",parent_id:this.callId,id:this.id}}async fetch(){return Q(await this.client.storage.entityMessageGetMessage({path:this.path}))}static byId($,O,j){return new u$($,O,j)}static from($,O,j){return new u$($,O,j.id,j)}content=this.field("content");createdAt=this.field("created_at");updatedAt=this.field("updated_at");call(){return J$.byId(this.client,this.callId)}async author(){return C.byId(this.client,(await this.detail.get()).sender_id)}async reply($){let O=Q(await this.client.storage.entityMessageCreate({path:{parent_type:"call",parent_id:this.callId},body:{...O$($),thread_id:this.callId}}));return u$.from(this.client,this.callId,O)}async edit($){let{content:O,mentions:j}=O$($);return await this.mutate((x)=>x.storage.entityMessageEdit({path:this.path,body:{content:O,mentions:j}})),this}async delete(){await this.mutate(($)=>$.storage.entityMessageDeleteMessage({path:this.path}))}}class J$ extends H${messageThreadById($){return L$.byId(this.client,{type:"call",entity:this},$)}timelinePage($){return b$(this.client,{type:"call",entity:this},(O)=>u$.from(this.client,this.id,O),$)}access=new $$(this.client,"call",this);async meeting(){return D$.from(this.client,Q(await this.client.storage.meetingShare({path:{call_id:this.id}})))}async editTranscript($){await this.mutate((O)=>O.storage.editCallTranscript({path:{call_id:this.id},body:{assignments:$}}))}async toggleTeamShare(){return this.mutate(($)=>$.storage.toggleShareWithTeam({path:{call_id:this.id}}))}entityType="call";async fetch(){return Q(await this.client.storage.getCallRecord({path:{call_id:this.id}}))}static byId($,O){return new J$($,O)}message($){return u$.byId(this.client,this.id,$)}name=this.field("customName");channel=this.mappedField("channelId",($)=>$?b.byId(this.client,$):void 0);channelName=this.field("channelName");creator=this.mappedField("createdBy",($)=>C.byId(this.client,$));isActive=this.field("isActive");status=this.field("status");roomName=this.field("roomName");startedAt=this.field("startedAt");endedAt=this.field("endedAt");durationMs=this.field("durationMs");summary=this.field("summary");transcript=this.field("transcript");participants=this.field("participants");guests=this.field("guests");teamShareAccessLevel=this.field("teamShareAccessLevel");shareWithTeam=this.field("shareWithTeam");recordingUrl=this.field("recordingUrl");recordingPreviewUrl=this.field("recordingPreviewUrl");recordingStartedAt=this.field("recordingStartedAt");async rename($){await this.mutate((O)=>O.storage.editCallRecord({path:{call_id:this.id},body:{customName:$??""}}))}async setTeamShare($){await this.mutate((O)=>O.storage.editCallRecord({path:{call_id:this.id},body:{sharePermission:{teamShareAccessLevel:$?"view":null}}}))}async delete(){await this.mutate(($)=>$.storage.deleteCallRecord({path:{call_id:this.id}}))}static search=x$({filters:{call_filters:{}},type:"call",make:($,O)=>new J$($,O.call_id)})}class Ox{client;constructor($){this.client=$}byId($){return J$.byId(this.client,$)}search($,O){return J$.search(this.client,$,O)}}class jx{client;constructor($){this.client=$}async list(){let{labels:$}=Q(await this.client.storage.listChannelLabels());return $}async create($,O=[]){return Q(await this.client.storage.createChannelLabel({body:{name:$,channelIds:O.map((j)=>j.id)}}))}async createSmartTag($,O){return Q(await this.client.storage.createChannelLabel({body:{name:$,rule:O}}))}async previewSmartTag($){return Q(await this.client.storage.previewSmartTag({body:$}))}async updateSmartTag($,O,j){return Q(await this.client.storage.renameChannelLabel({path:{label_id:$.id},body:{name:O,rule:j}}))}async rename($,O){return Q(await this.client.storage.renameChannelLabel({path:{label_id:$.id},body:{name:O}}))}async delete($){Q(await this.client.storage.deleteChannelLabel({path:{label_id:$.id}}))}async setLabel($,O){Q(await this.client.storage.setChannelLabel({path:{channel_id:$.id},body:{labelId:O?.id??null}}))}}var I5=100;class xx{client;async activity(){return Q(await this.client.storage.getActivity()).map(($)=>new GO(this.client,b.byId(this.client,$.channel_id),$))}labels;constructor($){this.client=$;this.labels=new jx($)}byId($){return b.byId(this.client,$)}async dm($){return b.dm(this.client,$)}async private($){return b.private(this.client,$)}async create($){return b.create(this.client,$)}async*list(){for await(let $ of this.records())yield b.byId(this.client,$.id)}async*search($,O){if(!O?.searchOn||O.searchOn==="name"){let j=$.toLowerCase();for await(let x of this.records())if(x.name?.toLowerCase().includes(j))yield b.byId(this.client,x.id)}else yield*b.search(this.client,$,O)}records(){return c(async($)=>{let O=Q(await this.client.storage.getChannels({query:{limit:I5,...$?{cursor:$}:{}}}));return{items:O.items,nextCursor:O.next_cursor}})}}class n extends K${async sharePermissions(){return Q(await this.client.storage.getProjectPermissionsV2({path:{id:this.id}}))}async accessLevel(){return Q(await this.client.storage.getProjectUserAccessLevel({path:{id:this.id}}))}access=new $$(this.client,"project",this);entityType="project";propertyEntityType="PROJECT";async fetch(){let{data:$}=Q(await this.client.storage.getProjectHandler({path:{id:this.id}}));return $.projectMetadata}static byId($,O){return new n($,O)}static async create($,O){let{data:j}=Q(await $.storage.createProjectHandler({body:{name:O.name,projectParentId:O.parent?.id??null}}));return new n($,j.id,j)}name=this.field("name");parent=this.mappedField("parentId",($)=>$?n.byId(this.client,$):void 0);createdAt=this.field("createdAt");async items(){let{data:$}=Q(await this.client.storage.getProjectContentHandler({path:{id:this.id}}));return $.map((O)=>O.item)}async rename($){await this.mutate((O)=>O.storage.editProjectV2({path:{id:this.id},body:{name:$}}))}async delete($){await this.mutate((O)=>$?.permanent?O.storage.permanentlyDeleteProject({path:{id:this.id}}):O.storage.deleteProjectHandler({path:{id:this.id}}))}async restore(){await this.mutate(($)=>$.storage.revertDeleteProject({path:{id:this.id}}))}static search=x$({filters:{project_filters:{}},type:"project",make:($,O)=>new n($,O.id)})}class nO{client;chat;id;message;constructor($,O,j,x){this.client=$;this.chat=O;this.id=j;this.message=x}static byId($,O,j,x){return new nO($,O,j,x)}async stop(){Q(await this.client.cognition.stopChatStream({body:{chat_id:this.chat.id,stream_id:this.id}}))}toJSON(){return{id:this.id,chatId:this.chat.id,messageId:this.message.id}}}class sO extends P{chat;constructor($,O,j){super($,j);this.chat=O}static byId($,O,j){return new sO($,O,j)}async fetch(){let $=Q(await this.client.cognition.getChat({path:{chat_id:this.chat.id}})).chat.messages.find((O)=>O.id===this.id);if(!$)throw new E(`Chat message ${this.id} is not yet available`);return $}content=this.field("content");role=this.field("role");async refresh(){this.detail.clear(),await this.detail.get()}toJSON(){return{...super.toJSON(),chatId:this.chat.id}}}class Y$ extends K${async send($){let{attachments:O,additionalInstructions:j,...x}=$,S=await this.mutate((Z)=>Z.cognition.sendChatMessage({body:{...x,chat_id:this.id,additional_instructions:j,attachments:O?.map((X)=>({entity_id:X.entity.id,entity_type:X.type}))}})),K=Y$.byId(this.client,S.chat_id);return nO.byId(this.client,K,S.stream_id,sO.byId(this.client,K,S.message_id))}access=new $$(this.client,"chat",this);entityType="chat";propertyEntityType="CHAT";async fetch(){let{chat:$}=Q(await this.client.cognition.getChat({path:{chat_id:this.id}}));return $}static byId($,O){return new Y$($,O)}static async create($,O){let{id:j}=Q(await $.cognition.createChat({body:{name:O?.name??null,projectId:O?.project?.id??null}}));return new Y$($,j)}name=this.field("name");model=this.field("model");project=this.mappedField("projectId",($)=>$?n.byId(this.client,$):void 0);createdAt=this.field("createdAt");updatedAt=this.field("updatedAt");messages=this.field("messages");async rename($){await this.mutate((O)=>O.cognition.patchChat({path:{chat_id:this.id},body:{name:$}}))}async delete($){await this.mutate((O)=>$?.permanent?O.cognition.permanentlyDeleteChat({path:{chat_id:this.id}}):O.cognition.deleteChat({path:{chat_id:this.id}}))}async copy(){let{id:$}=await this.mutate((O)=>O.cognition.copyChat({path:{chat_id:this.id}}));return new Y$(this.client,$)}async restore(){await this.mutate(($)=>$.cognition.revertDeleteChat({path:{chat_id:this.id}}))}async history(){let{conversation:$}=Q(await this.client.cognition.getChatHistoryHandler({path:{chat_id:this.id}}));return $}webUrl(){return`${this.client.webAppUrl}/app/chat/${this.id}`}static search=x$({filters:{chat_filters:{}},type:"chat",make:($,O)=>new Y$($,O.chat_id)});toMention(){return{tag:o$("m-document-mention",{documentId:this.id,documentName:this.detail.peek()?.name??"",blockName:"chat",blockParams:{}}),mention:{entity_type:"chat",entity_id:this.id}}}}class Sx{client;constructor($){this.client=$}byId($){return Y$.byId(this.client,$)}create($){return Y$.create(this.client,$)}search($,O){return Y$.search(this.client,$,O)}}class HO extends P{static byId($,O){return new HO($,O)}static from($,O){return new HO($,O.id,O)}async fetch(){let $=Q(await this.client.auth.getTeamInvites()).invites.find((O)=>O.id===this.id);if(!$)throw new E(`team invite ${this.id} not found`);return $}email=this.field("email");role=this.field("team_role");invitedBy=this.mappedField("invited_by",($)=>C.byId(this.client,$));createdAt=this.field("created_at");lastSentAt=this.field("last_sent_at");async revoke(){await this.mutate(($)=>$.auth.deleteTeamInviteHandler({path:{team_invite_id:this.id}}))}}class _$ extends P{async fetch(){let O=Q(await this.client.auth.getUserTeams()).find((j)=>j.id===this.id);if(!O)throw new E(`team ${this.id} not found`);return O}static byId($,O){return new _$($,O)}static async current($){let O=Q(await $.auth.getTeam());if(!O?.team)throw new E("caller has no current team");return new _$($,O.team.id,O.team)}static async list($){return Q(await $.auth.getUserTeams()).map((j)=>new _$($,j.id,j))}name=this.field("name");slug=this.field("slug");defaultLinkShare=this.field("default_link_share");owner=this.mappedField("owner_id",($)=>C.byId(this.client,$));async members(){return(await this.requireCurrent("members")).members.map((O)=>({user:C.byId(this.client,O.user_id),role:O.role}))}async invite($){let O=[],j=new Set;for(let S of typeof $==="string"?[$]:$){let K=S.trim(),Z=K.toLowerCase();if(K&&!j.has(Z))j.add(Z),O.push(K)}if(O.length===0)throw new f("invite needs at least one email address");let x=await this.client.auth.inviteToTeam({body:{invites:O.map((S)=>({email:S})),team_id:this.id}});if(x.response?.status===304)return!1;return Q(x),!0}async invites(){return Q(await this.client.auth.getTeamInvites({query:{team_id:this.id}})).invites.map(($)=>HO.from(this.client,$))}async requireCurrent($){let O=Q(await this.client.auth.getTeam());if(!O?.team||O.team.id!==this.id)throw new f(`${$} are only available for the current team (see Team.current)`);return O}}var H5=8;class P$ extends P{parent;constructor($,O,j,x){super($,j,x);this.parent=O}get path(){return{parent_type:this.parent.type,parent_id:this.parent.id,id:this.id}}async fetch(){return Q(await this.client.storage.entityMessageGetMessage({path:this.path}))}static byId($,O,j){return new P$($,O,j)}static from($,O,j){return new P$($,O,j.id,j)}text=this.field("content");createdAt=this.field("created_at");updatedAt=this.field("updated_at");deletedAt=this.field("deleted_at");async threadId(){return(await this.detail.get()).thread_id??this.id}async author(){return C.byId(this.client,(await this.detail.get()).sender_id)}async reply($){return tO(this.client,this.parent,$,{threadId:await this.threadId()})}async edit($){let{content:O,mentions:j}=O$($);return await this.mutate((x)=>x.storage.entityMessageEdit({path:this.path,body:{content:O,mentions:j}})),this}async delete(){await this.mutate(($)=>$.storage.entityMessageDeleteMessage({path:this.path}))}}async function Hj($,O){let j={parent_type:O.type,parent_id:O.id},x=c(async(K)=>{let Z=Q(await $.storage.messageTimeline({path:j,query:{selection:JSON.stringify({limit:100,cursor:K})}}));return{items:Z.items,nextCursor:Z.next_cursor}}),S=[];for await(let K of x)S.push(K);return cO(S,H5,async(K)=>{let{state:Z,root:X,replies:Y}=Q(await $.storage.entityMessageGetThread({path:{...j,id:K.id}}));return{thread:Z,comments:[X,...Y].map((L)=>P$.from($,O,L))}})}async function tO($,O,j,x){let S=Q(await $.storage.entityMessageCreate({path:{parent_type:O.type,parent_id:O.id},body:{...O$(j),thread_id:x?.threadId??null}}));return P$.from($,O,S)}class A$ extends H${messageThreadById($){return L$.byId(this.client,{type:"crm_contact",entity:this},$)}timelinePage($){return b$(this.client,{type:"crm_contact",entity:this},(O)=>P$.from(this.client,{type:"crm_contact",id:this.id},O),$)}entityType="crm_contact";async fetch(){return Q(await this.client.storage.getContact({path:{contact_id:this.id}}))}static byId($,O){return new A$($,O)}static from($,O){return new A$($,O.id,O)}name=this.field("name");email=this.field("email");company=this.mappedField("companyId",($)=>$?k$.byId(this.client,$):void 0);hidden=this.field("hidden");createdAt=this.field("createdAt");updatedAt=this.field("updatedAt");firstInteraction=this.field("firstInteraction");lastInteraction=this.field("lastInteraction");async hide(){await this.setHidden(!0)}async unhide(){await this.setHidden(!1)}async setHidden($){await this.mutate((O)=>O.storage.setContactHidden({path:{contact_id:this.id},body:{hidden:$}}))}async rename($){await this.mutate((O)=>O.storage.setCrmContactName({path:{contact_id:this.id},body:{name:$}}))}get commentParent(){return{type:"crm_contact",id:this.id}}async comments(){return Hj(this.client,this.commentParent)}async comment($,O){return tO(this.client,this.commentParent,$,O)}commentById($){return P$.byId(this.client,this.commentParent,$)}}class k$ extends K${messageThreadById($){return L$.byId(this.client,{type:"crm_company",entity:this},$)}timelinePage($){return b$(this.client,{type:"crm_company",entity:this},(O)=>P$.from(this.client,{type:"crm_company",id:this.id},O),$)}entityType="crm_company";propertyEntityType="COMPANY";async fetch(){return Q(await this.client.storage.getCompany({path:{company_id:this.id}}))}static byId($,O){return new k$($,O)}static from($,O){return new k$($,O.id,O)}name=this.field("name");description=this.field("description");hidden=this.field("hidden");emailSync=this.field("emailSync");team=this.mappedField("teamId",($)=>_$.byId(this.client,$));createdAt=this.field("createdAt");updatedAt=this.field("updatedAt");async domain(){let{domains:$}=await this.detail.get();return $[0]?.domain}async domains(){let{domains:$}=await this.detail.get();return $.map((O)=>O.domain)}async contacts(){return Q(await this.client.storage.listCompanyContacts({path:{company_id:this.id}})).map((O)=>A$.from(this.client,O))}static search=x$({filters:{crm_company_filters:{}},type:"company",includeCrm:!0,make:($,O)=>new k$($,O.id)});async hide(){await this.setHidden(!0)}async unhide(){await this.setHidden(!1)}async setHidden($){await this.mutate((O)=>O.storage.setCompanyHidden({path:{company_id:this.id},body:{hidden:$}}))}async setEmailSync($){await this.mutate((O)=>O.storage.setEmailSync({path:{company_id:this.id},body:{email_sync:$}}))}async rename($){await this.mutate((O)=>O.storage.setCrmCompanyName({path:{company_id:this.id},body:{name:$}}))}async createContact($){let O=await this.mutate((j)=>j.storage.createCrmContact({path:{company_id:this.id},body:$}));return A$.from(this.client,O)}get commentParent(){return{type:"crm_company",id:this.id}}async comments(){return Hj(this.client,this.commentParent)}async comment($,O){return tO(this.client,this.commentParent,$,O)}commentById($){return P$.byId(this.client,this.commentParent,$)}}class jO extends P{tableDetail=new W$(async()=>Q(await this.client.storage.getCrmPipelineTable({path:{id:this.id}})));static byId($,O){return new jO($,O)}static from($,O){return new jO($,O.id,O)}async fetch(){return Q(await this.client.storage.getCrmPipeline({path:{id:this.id}}))}name=this.field("name");recordType=this.field("recordType");accessLevel=this.field("grant");sharing=this.field("sharing");owner=this.mappedField("userId",($)=>C.byId(this.client,$));team=this.mappedField("teamId",($)=>_$.byId(this.client,$));async rename($){await this.mutate((O)=>O.storage.renameCrmPipeline({path:{id:this.id},body:{name:$}}))}async setSharing($){if($===void 0)throw Error("Sharing is required");await this.mutate((O)=>O.storage.shareCrmPipeline({path:{id:this.id},body:{sharing:$}}))}async setTrashed($){await this.mutate((O)=>O.storage.trashCrmPipeline({path:{id:this.id},body:{trashed:$}}))}async sharePermissions(){return Q(await this.client.storage.getCrmPipelinePermissions({path:{id:this.id}}))}async updateSharePermissions($){return this.mutate((O)=>O.storage.updateCrmPipelinePermissions({path:{id:this.id},body:$O($)}))}async table(){return Tj.from(this.client,this,await this.tableRecord())}tableRecord(){return this.tableDetail.get()}rows(){return c(async($)=>{let O=Q(await this.client.storage.getCrmPipelineRows({path:{id:this.id},query:{after:$}}));return{items:O.rows.map((j)=>JO.from(this.client,this,j)),nextCursor:O.next}})}queryRows($={}){if($.rows?.some((O)=>O.pipeline.id!==this.id))throw Error("Rows belong to another pipeline");return c(async(O)=>{let j=Q(await this.client.storage.queryCrmPipelineRows({path:{id:this.id},body:{after:O,query:$.query,rowIds:$.rows?.map((x)=>x.id)}}));return{items:j.rows.map((x)=>JO.from(this.client,this,x)),nextCursor:j.next}})}async applyOps($,O){if(O?.baseVersions?.some((S)=>S.table.pipeline.id!==this.id))throw Error("Table belongs to another pipeline");let j={ops:$,baseVersions:O?.baseVersions?Object.fromEntries(O.baseVersions.map((S)=>[S.table.id,S.version])):void 0},x=await this.mutate((S)=>S.storage.applyCrmPipelineOps({path:{id:this.id},body:j}));return this.tableDetail.clear(),x}}class Tj extends P{pipeline;toJSON(){return{...super.toJSON(),pipelineId:this.pipeline.id}}constructor($,O,j){super($,j.table.id,j);this.pipeline=O}static from($,O,j){return new Tj($,O,j)}fetch(){return this.pipeline.tableRecord()}async columns(){return(await this.pipeline.tableRecord()).columns.map(($)=>Rj.from(this.client,this,$))}async version(){return(await this.pipeline.tableRecord()).table.version}rowById($){return JO.byId(this.client,this.pipeline,$)}rows(){return this.pipeline.rows()}}class JO extends P{pipeline;toJSON(){return{...super.toJSON(),pipelineId:this.pipeline.id}}constructor($,O,j,x){super($,j,x);this.pipeline=O}static byId($,O,j){return new JO($,O,j)}static from($,O,j){return new JO($,O,j.rowId,j)}async fetch(){for await(let $ of this.pipeline.queryRows({rows:[this]}))if($.id===this.id)return $.detail.get();throw new E(`Pipeline row ${this.id} is unavailable`)}cells=this.field("cells");async refresh(){this.detail.clear(),await this.detail.get()}}class Rj extends P{table;toJSON(){return{...super.toJSON(),pipelineId:this.table.pipeline.id,tableId:this.table.id}}constructor($,O,j){super($,j.column.id,j);this.table=O}static from($,O,j){return new Rj($,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 Zx{client;constructor($){this.client=$}byId($){return jO.byId(this.client,$)}async list(){return Q(await this.client.storage.listCrmPipelines()).map(($)=>jO.from(this.client,$))}async create($){return jO.from(this.client,Q(await this.client.storage.createCrmPipeline({body:$})))}}class Xx{client;pipelines;constructor($){this.client=$;this.pipelines=new Zx($)}companyById($){return k$.byId(this.client,$)}contactById($){return A$.byId(this.client,$)}async contactByEmail($){let{contact:O}=Q(await this.client.storage.getContactByEmail({query:{email:$}}));return O?A$.from(this.client,O):void 0}async searchContacts($,O={}){let{contacts:j}=Q(await this.client.storage.searchContacts({query:{query:$,limit:O.limit}}));return j.map((x)=>A$.from(this.client,x))}async createCompany($){return k$.from(this.client,Q(await this.client.storage.createCrmCompany({body:$})))}async createContact($){return A$.from(this.client,Q(await this.client.storage.createCrmTeamContact({body:$})))}async blockedDomains(){return Q(await this.client.storage.listCrmBlockedDomains()).map(($)=>$.domain)}async blockDomain($){Q(await this.client.storage.blockCrmDomain({path:{domain:$}}))}async unblockDomain($){Q(await this.client.storage.unblockCrmDomain({path:{domain:$}}))}async settings(){return Q(await this.client.storage.getCrmTeamSettings())}async updateSettings($){return Q(await this.client.storage.putCrmTeamSettings({body:$}))}async setStages($){return Q(await this.client.storage.putCrmTeamStages({body:$}))}async resetStages(){Q(await this.client.storage.resetCrmTeamStages())}searchCompanies($){return k$.search(this.client,$)}}var Kx,T5=new Uint8Array(16);function Dj(){if(!Kx){if(typeof crypto>"u"||!crypto.getRandomValues)throw Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Kx=crypto.getRandomValues.bind(crypto)}return Kx(T5)}var j$=[];for(let $=0;$<256;++$)j$.push(($+256).toString(16).slice(1));function O2($,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 Yx={};function R5($,O,j){let x;if($)x=j2($.random??$.rng?.()??Dj(),$.msecs,$.seq,O,j);else{let S=Date.now(),K=Dj();D5(Yx,S,K),x=j2(K,Yx.msecs,Yx.seq,O,j)}return O??O2(x)}function D5($,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 j2($,O,j,x,S=0){if($.length<16)throw Error("Random bytes length must be >= 16");if(!x)x=new Uint8Array(16),S=0;else if(S<0||S+16>x.length)throw RangeError(`UUID byte range ${S}:${S+15} is out of buffer bounds`);return O??=Date.now(),j??=$[6]*127<<24|$[7]<<16|$[8]<<8|$[9],x[S++]=O/1099511627776&255,x[S++]=O/4294967296&255,x[S++]=O/16777216&255,x[S++]=O/65536&255,x[S++]=O/256&255,x[S++]=O&255,x[S++]=112|j>>>28&15,x[S++]=j>>>20&255,x[S++]=128|j>>>14&63,x[S++]=j>>>6&255,x[S++]=j<<2&255|$[10]&3,x[S++]=$[11],x[S++]=$[12],x[S++]=$[13],x[S++]=$[14],x[S++]=$[15],x}var c$=R5;class F${table;id;constructor($,O){this.table=$;this.id=O}static byId($,O){return new F$($,O)}async detail(){let{columns:$}=await this.table.detail(),O=$.find((j)=>j.column.id===this.id);if(!O)throw new E(`column ${this.id} is not on table ${this.table.id}`);return O}async name(){let $=await this.detail();return $.column.display_name??$.definition.definition.display_name}async rename($){return await this.table.database.renameColumn(this,$),this}async inferType($){return await this.table.database.inferColumnType(this,$),this}changeType($){return this.table.database.changeColumnType(this,$)}convertIntoNewColumn($){return this.table.database.convertColumnIntoNewColumn(this,$)}casts(){return this.table.database.columnCasts(this)}async delete(){await this.table.database.deleteColumn(this)}async dataType(){return(await this.detail()).definition.definition.data_type}async isMultiSelect(){return(await this.detail()).definition.definition.is_multi_select}async position(){return(await this.detail()).column.position}async definition(){return(await this.detail()).definition}async config(){return(await this.detail()).column.config??void 0}async addOptions($){return await this.table.database.addColumnOptions(this,$),this}toJSON(){return{id:this.id,tableId:this.table.id}}}class E${table;id;constructor($,O){this.table=$;this.id=O}static byId($,O){return new E$($,O)}history(){return this.table.database.rowHistory(this)}toJSON(){return{id:this.id,tableId:this.table.id}}}class _j{table;id;constructor($,O){this.table=$;this.id=O}static byId($,O){return new _j($,O)}async detail(){let{views:$}=await this.table.detail(),O=$.find((j)=>j.id===this.id);if(!O)throw new E(`view ${this.id} is not on table ${this.table.id}`);return O}async name(){return(await this.detail()).name}async position(){return(await this.detail()).position}async layout(){return(await this.detail()).layout}async query(){return(await this.detail()).query}positions(){return this.table.database.viewPositions(this)}toJSON(){return{id:this.id,tableId:this.table.id}}}class V${database;id;constructor($,O){this.database=$;this.id=O}static byId($,O){return new V$($,O)}async detail(){let{tables:$}=await this.database.schema(),O=$.find((j)=>j.table.id===this.id);if(!O)throw new E(`table ${this.id} is not in database ${this.database.id}`);return O}async name(){return(await this.detail()).table.name}async rename($){return await this.database.renameTable(this,$),this}async version(){return(await this.detail()).table.version}async position(){return(await this.detail()).table.position}async columns(){let{columns:$}=await this.detail();return $.map((O)=>F$.byId(this,O.column.id))}addColumn($){return this.database.addColumn(this,$)}async reorderColumns($){return await this.database.reorderColumns(this,$),this}row($){return E$.byId(this,$)}async views(){let{views:$}=await this.detail();return $.map((O)=>_j.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 Mj($,O,j,x={}){let S=Q(await $.storage.queryDatabases({body:{sql:j,databaseId:x.database?.id,baseVersions:Object.fromEntries((x.baseVersions??[]).map(({table:G,version:J})=>[G.id,J]))}})),K=new Map;for(let G of[x.database,...(x.baseVersions??[]).map(({table:J})=>J.database)]){if(!G)continue;let J=K.get(G.id);if(J)J.add(G);else K.set(G.id,new Set([G]))}let Z=(G)=>{let J=K.get(G)?.values().next().value;if(J)return J;let I=O($,G);return K.set(G,new Set([I])),I},X=(G)=>{let J=S.tableDatabases[G];if(!J)throw Error(`SQL response is missing the owner of table ${G}`);return V$.byId(Z(J),G)},Y=new Set(Object.keys(S.newVersions).map((G)=>X(G).database.id));if(S.statement.kind==="schema")Y.add(S.statement.databaseId);for(let G of Y)for(let J of K.get(G)??[])J.invalidateSchema();let L=k(S.statement).with({kind:"select"},(G)=>G).with({kind:"schema"},({databaseId:G,summary:J})=>({kind:"schema",database:Z(G),summary:J})).with({kind:"insert"},{kind:"update"},{kind:"delete"},({kind:G,tableId:J,tableName:I})=>({kind:G,table:X(J),tableName:I})).with({kind:"alterColumnType"},({tableId:G,tableName:J,columnId:I,columnName:z,to:W})=>{let V=X(G);return{kind:"alterColumnType",table:V,tableName:J,column:F$.byId(V,I),columnName:z,to:W}}).exhaustive();return{result:S.result?_5(S.result,X,S.tableDatabases):void 0,changesApplied:S.changesApplied,insertedRows:L.kind==="insert"?S.insertedRowIds.map((G)=>E$.byId(L.table,G)):[],newVersions:Object.entries(S.newVersions).map(([G,J])=>({table:X(G),version:J})),readVersions:Object.entries(S.readVersions).map(([G,J])=>({table:X(G),version:J})),truncatedTables:S.truncatedTables,statement:L}}function _5($,O,j){let x=$.sourceTable&&j[$.sourceTable]?O($.sourceTable):void 0;return{columns:$.columns.map(({relatedTable:S,...K})=>({...K,relatedTable:S&&j[S]?O(S):void 0})),rows:$.rows,sourceTable:x,rowHandles:x?$.rowIds.map((S)=>E$.byId(x,S)):[]}}class Cj{table;id;createdBy;record;constructor($,O,j,x){this.table=$;this.id=O;this.createdBy=j;this.record=x}static fromRecord($,O,j){return new Cj($,j.id,O,j)}get tokenPrefix(){return this.record.tokenPrefix}get createdAt(){return this.record.createdAt}delete(){return this.table.database.deleteWebhook(this)}toJSON(){return{id:this.id,tableId:this.table.id,tokenPrefix:this.tokenPrefix}}}class Jx extends e${op;row;column;taken;constructor($,O){super($,O);this.name="MacroOpRefusedError",this.message=O.message,this.op=O.op,this.row=O.row,this.column=O.column,this.taken=O.taken}}function Pj($){return k($).with({type:"relation"},({table:O})=>({type:"relation",database:O.database.id,table:O.id})).with({type:t.not("relation")},(O)=>O).exhaustive()}var M5={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 C5($){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})=>M5[O]).with({type:"relation"},()=>"Relation").exhaustive(()=>"Column")}function Qx($){return $.map((O)=>({id:c$(),label:O}))}function x2($,O,j){return $?.kind===O&&"change"in $&&$.change.kind===j}function Gx($){return k($).with({kind:"reorder_tables"},({kind:O})=>O).with({kind:t.union("table","column","rows","view")},({kind:O,change:j})=>`${O}.${j.kind}`).exhaustive(()=>"unknown")}function d$($,O,j){let[x]=$;if($.length!==1||!x2(x,O,j))throw new f(`expected one ${O}.${j} result, got ${$.map(Gx).join(", ")||"none"}`);return x}class Q$ extends P{access=new $$(this.client,"database",this);async fetch(){return Q(await this.client.storage.getDatabase({path:{id:this.id}}))}assertOwns($,O){if(O.id!==this.id)throw new f(`${$} does not belong to database ${this.id}`)}static byId($,O){return new Q$($,O)}static async create($,O){let j=Q(await $.storage.createDatabase({body:{name:O.name}}));return new Q$($,j.id)}async duplicate($){let O=Q(await this.client.storage.duplicateDatabase({path:{id:this.id},body:{name:$?.name}}));return new Q$(this.client,O.id)}static async list($){return Q(await $.storage.listDatabases()).map((j)=>new Q$($,j.database.id))}query($,O){return Mj(this.client,Q$.byId,$,{...O,database:this})}invalidateSchema(){this.detail.clear()}schema(){return this.detail.get()}name=this.mappedField("database",($)=>$.name);owner=this.mappedField("database",($)=>C.byId(this.client,$.owner_id));createdAt=this.mappedField("database",($)=>$.created_at);trashedAt=this.mappedField("database",($)=>$.trashed_at??void 0);grant=this.field("grant");tables=this.mappedField("tables",($)=>$.map((O)=>V$.byId(this,O.table.id)));async table($){let{tables:O}=await this.schema(),j=O.find((x)=>x.table.name===$);return j?V$.byId(this,j.table.id):void 0}async createTable($){let{table:O}=d$(await this.applyOps([{kind:"table",table:c$(),change:{kind:"create",name:$.name}}]),"table","created");return V$.byId(this,O)}async applyOps($,O={}){let j={ops:$};if(O.baseVersions!==void 0){for(let{table:S}of O.baseVersions)this.assertOwns(`table ${S.id}`,S.database);j.baseVersions=Object.fromEntries(O.baseVersions.map(({table:S,version:K})=>[S.id,K]))}let{results:x}=await this.mutate(async(S)=>{let K=await S.storage.applyDatabaseOps({path:{id:this.id},body:j});if(K.error!==void 0&&"op"in K.error)throw new Jx(K.response?.status??0,K.error);return K});return x}async reorderTables($){for(let x of $)this.assertOwns(`table ${x.id}`,x.database);let O=await this.applyOps([{kind:"reorder_tables",order:$.map((x)=>x.id)}]),[j]=O;if(O.length!==1||j?.kind!=="reorder_tables")throw new f(`expected one reorder_tables result, got ${O.map(Gx).join(", ")||"none"}`);return j.tables.map(({table:x})=>V$.byId(this,x))}async deleteTable($){this.assertOwns(`table ${$.id}`,$.database),d$(await this.applyOps([{kind:"table",table:$.id,change:{kind:"delete"}}]),"table","deleted")}async columnCasts($){return this.assertOwns(`column ${$.id}`,$.table.database),Q(await this.client.storage.listDatabaseColumnCasts({path:{id:this.id,table_id:$.table.id,column_id:$.id}}))}async viewPositions($){this.assertOwns(`view ${$.id}`,$.table.database);let{positions:O}=Q(await this.client.storage.getDatabaseViewPositions({path:{id:this.id,view_id:$.id}}));return O}async rowHistory($){this.assertOwns(`row ${$.id}`,$.table.database);let{changes:O}=Q(await this.client.storage.getDatabaseRowHistory({path:{id:this.id,table_id:$.table.id,row_id:$.id}}));return O}async importTable($){let O=await this.mutate((j)=>j.storage.importDatabaseTable({path:{id:this.id},body:$}));return V$.byId(this,O.id)}webhookOf($){return Cj.fromRecord(V$.byId(this,$.tableId),C.byId(this.client,$.createdBy),$)}async webhooks(){let{webhooks:$}=Q(await this.client.storage.listDatabaseWebhooks({path:{id:this.id}}));return $.map((O)=>this.webhookOf(O))}async createWebhook($){this.assertOwns("table",$.database);let O=Q(await this.client.storage.createDatabaseWebhook({path:{id:this.id},body:{tableId:$.id}}));return{webhook:this.webhookOf(O.webhook),token:O.token}}async deleteWebhook($){this.assertOwns("webhook",$.table.database),Q(await this.client.storage.deleteDatabaseWebhook({path:{id:this.id,webhook_id:$.id}}))}async sharePermissions(){return Q(await this.client.storage.getDatabasePermissions({path:{id:this.id}}))}updateSharePermissions($){return this.mutate((O)=>O.storage.updateDatabasePermissions({path:{id:this.id},body:$}))}async changeColumnType($,O){this.assertOwns(`column ${$.id}`,$.table.database);let j=await $.table.version();return d$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"change_type",to:Pj(O.to)}}],{baseVersions:[{table:$.table,version:j}]}),"column","type_changed")}async columnConversion($,O){return this.assertOwns(`column ${$.id}`,$.table.database),Q(await this.client.storage.convertDatabaseColumn({path:{id:this.id,table_id:$.table.id,column_id:$.id},body:{to:Pj(O)}}))}async convertColumnIntoNewColumn($,O){let j=await this.columnConversion($,O.to),x=O.name??`${await $.name()} (${C5(O.to)})`,S=c$(),K=[{kind:"column",table:$.table.id,column:S,change:{kind:"create",definition:{source:"new",name:x,type:Pj(O.to),options:Qx(j.options)},after:$.id}}];if(j.cells.length>0)K.push({kind:"rows",table:$.table.id,change:{kind:"update",changes:{kind:"per_row",rows:j.cells.map(({row:X,value:Y})=>({row:X,cells:[{column:S,value:Y}]}))}}});let[Z]=await this.applyOps(K,{baseVersions:[{table:$.table,version:j.tableVersion}]});if(!x2(Z,"column","created"))throw new f(`expected a column.created result, got ${Z?Gx(Z):"none"}`);return F$.byId($.table,Z.column)}async deleteColumn($){this.assertOwns(`column ${$.id}`,$.table.database);let O=await $.table.version(),{tableVersion:j}=d$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"delete"}}],{baseVersions:[{table:$.table,version:O}]}),"column","deleted");return j}async reorderColumns($,O){this.assertOwns(`table ${$.id}`,$.database);for(let S of O)if(S.table.id!==$.id)throw new f(`column ${S.id} does not belong to table ${$.id}`);let j=await $.version(),{tableVersion:x}=d$(await this.applyOps([{kind:"table",table:$.id,change:{kind:"reorder_columns",order:O.map((S)=>S.id)}}],{baseVersions:[{table:$,version:j}]}),"table","columns_reordered");if(x===void 0)throw new f(`table ${$.id} reordered its columns without a version`);return x}async renameTable($,O){this.assertOwns(`table ${$.id}`,$.database);let j=await $.name(),{tableVersion:x}=d$(await this.applyOps([{kind:"table",table:$.id,change:{kind:"rename",name:O,previousName:j}}]),"table","renamed");if(x===void 0)throw new f(`table ${$.id} was renamed without a version`);return x}async renameColumn($,O){this.assertOwns(`column ${$.id}`,$.table.database);let j=await $.name(),{tableVersion:x}=d$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"rename",name:O,previousName:j}}]),"column","renamed");return x}async inferColumnType($,O){return this.assertOwns(`column ${$.id}`,$.table.database),this.mutate((j)=>j.storage.inferDatabaseColumnType({path:{id:this.id,table_id:$.table.id,column_id:$.id},body:{dataType:O.dataType,baseVersion:O.baseVersion,...O.specificEntityType!==void 0?{specificEntityType:O.specificEntityType}:{}}}))}async addColumn($,O){if(this.assertOwns(`table ${$.id}`,$.database),O.after!==void 0&&O.after.table.id!==$.id)throw new f(`column ${O.after.id} does not belong to table ${$.id}`);let j="property"in O?{source:"existing",property:O.property.id}:{source:"new",name:O.name,type:Pj(O.type),...O.options!==void 0?{options:Qx(O.options)}:{},...O.inferType!==void 0?{inferType:O.inferType}:{}},{column:x}=d$(await this.applyOps([{kind:"column",table:$.id,column:c$(),change:{kind:"create",definition:j,...O.after!==void 0?{after:O.after.id}:{}}}]),"column","created");return F$.byId($,x)}async addColumnOptions($,O){return this.assertOwns(`column ${$.id}`,$.table.database),d$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"add_options",options:Qx(O)}}]),"column","options_added")}}class Vx{client;constructor($){this.client=$}query($,O){return Mj(this.client,Q$.byId,$,O)}byId($){return Q$.byId(this.client,$)}create($){return Q$.create(this.client,$)}list(){return Q$.list(this.client)}}class VO extends P{document;toJSON(){return{...super.toJSON(),documentId:this.document.id}}constructor($,O,j,x){super($,j,x);this.document=O}static byId($,O,j){return new VO($,O,j)}static from($,O,j){return new VO($,O,j.uuid,j)}async fetch(){let $=Q(await this.client.storage.getDocumentAnchors({path:{document_id:this.document.id}})).data.find((O)=>O.uuid===this.id);if(!$)throw new E(`Annotation ${this.id} is unavailable`);return $}kind=this.field("anchorType");page=this.field("page");async edit($){if(await this.kind()!=="placeable")throw Error("Only placeable comment annotations can be edited");await this.mutate((O)=>O.storage.editAnchor({body:{...$,uuid:this.id,anchorType:"free-comment",fileType:"pdf"}}))}async delete(){if(await this.kind()!=="highlight")throw Error("Only standalone highlights can be deleted with this endpoint");await this.mutate(($)=>$.storage.deleteAnchor({body:{uuid:this.id,anchorType:"highlight",fileType:"pdf"}}))}}class l$ extends P{documentId;constructor($,O,j,x){super($,j,x);this.documentId=O}get path(){return{parent_type:"document",parent_id:this.documentId,id:this.id}}async fetch(){return Q(await this.client.storage.entityMessageGetMessage({path:this.path}))}static byId($,O,j){return new l$($,O,j)}static from($,O,j){return new l$($,O,j.id,j)}text=this.field("content");createdAt=this.field("created_at");updatedAt=this.field("updated_at");async threadId(){return(await this.detail.get()).thread_id??this.id}document(){return w.byId(this.client,this.documentId)}async author(){return C.byId(this.client,(await this.detail.get()).sender_id)}async reply($){return this.document().comment($,{threadId:await this.threadId()})}async edit($){let{content:O,mentions:j}=O$($);return await this.mutate((x)=>x.storage.entityMessageEdit({path:this.path,body:{content:O,mentions:j}})),this}async delete(){await this.mutate(($)=>$.storage.entityMessageDeleteMessage({path:this.path}))}}class eO{client;document;id;detail;constructor($,O,j){this.client=$;this.document=O;this.id=j;this.detail=new W$(async()=>Q(await this.client.storage.getDocumentVersion({path:{document_id:O.id,document_version_id:j}})).data)}static byId($,O,j){return new eO($,O,j)}read(){return this.detail.get()}toJSON(){return{id:this.id,documentId:this.document.id}}}var P5=8;class w extends K${async anchors(){return Q(await this.client.storage.getDocumentAnchors({path:{document_id:this.id}})).data.map(($)=>VO.from(this.client,this,$))}async createHighlight($){return VO.from(this.client,this,Q(await this.client.storage.createAnchor({path:{document_id:this.id},body:{...$,fileType:"pdf",anchorType:"highlight"}})))}version($){return eO.byId(this.client,this,$)}async sharePermissions(){return Q(await this.client.storage.getDocumentPermissionsV2({path:{document_id:this.id}})).documentPermissions}async permissionsToken(){return Q(await this.client.storage.getDocumentPermissionsToken({path:{document_id:this.id}})).token}async prepareSave($){return Q(await this.client.storage.presaveDocumentHandler({path:{document_id:this.id},body:{newBom:$}})).data}async save($){return(await this.mutate((O)=>O.storage.saveDocumentHandler({path:{document_id:this.id},body:$}))).data}async simpleSave(){return(await this.mutate(($)=>$.storage.simpleSave({path:{document_id:this.id}}))).data}messageThreadById($){return L$.byId(this.client,{type:"document",entity:this},$)}timelinePage($){return b$(this.client,{type:"document",entity:this},(O)=>l$.from(this.client,this.id,O),$)}access=new $$(this.client,"document",this);async fetch(){let{data:$}=Q(await this.client.storage.getDocument({path:{document_id:this.id}}));return $.documentMetadata}static byId($,O){return new w($,O)}static async create($,O){let{documentId:j}=Q(await $.storage.createMarkdownHandler({body:{documentName:O.name,markdown:O.markdown??null,projectId:O.project?.id??null}}));return new w($,j)}static async createSnippet($,O){let{documentId:j}=Q(await $.storage.createSnippetHandler({body:{snippetName:O.name,markdown:O.markdown??null,projectId:O.project?.id??null}}));return new w($,j)}static async createSkill($,O){let{documentId:j}=Q(await $.storage.createSkillHandler({body:{skillName:O.name,markdown:O.markdown??null,projectId:O.project?.id??null}}));return new w($,j)}static recent($,O){let j=O?.pageSize??50;return c(async(x)=>{let S=Q(await $.storage.getUserDocumentsHandler({query:{limit:j,offset:x?Number(x):0,...O?.fileType!==void 0?{file_type:O.fileType}:{}}})),K=S.data?.next_offset;return{items:(S.data?.documents??[]).map((Z)=>new w($,Z.documentId)),nextCursor:K!=null?String(K):null}})}static async recentlyDeleted($){let{data:O}=Q(await $.storage.recentlyDeleted({}));return O.items.filter((j)=>j.type==="document").map((j)=>new w($,j.id))}entityType="document";propertyEntityType="DOCUMENT";name=this.field("documentName");fileType=this.field("fileType");project=this.mappedField("projectId",($)=>$?n.byId(this.client,$):void 0);owner=this.mappedField("owner",($)=>C.byId(this.client,$));branchedFrom=this.mappedField("branchedFromId",($)=>$?w.byId(this.client,$):void 0);createdAt=this.field("createdAt");updatedAt=this.field("updatedAt");deletedAt=this.field("deletedAt");async content(){let{text:$}=Q(await this.client.storage.getDocumentTextContent({path:{document_id:this.id}}));if($!==null)return $;let{presigned_url:O}=Q(await this.client.storage.exportDocument({path:{document_id:this.id}})),j=await fetch(O);if(!j.ok)throw new e$(j.status,{message:"failed to download document content"});return j.text()}async rename($){await this.mutate((O)=>O.storage.editDocument({path:{document_id:this.id},body:{documentName:$}}))}async move($){await this.mutate((O)=>O.storage.editDocument({path:{document_id:this.id},body:{projectId:$?.id??""}}))}async delete($){await this.mutate((O)=>$?.permanent?O.storage.permanentlyDeleteDocument({path:{document_id:this.id}}):O.storage.deleteDocument({path:{document_id:this.id}}))}async restore(){await this.mutate(($)=>$.storage.revertDeleteDocument({path:{document_id:this.id}}))}async copy($){let{data:O}=Q(await this.client.storage.copyDocument({path:{document_id:this.id},query:$.versionId!==void 0?{version_id:$.versionId}:void 0,body:{documentName:$.name}}));return new w(this.client,O.documentMetadata.documentId)}async comments(){let $={parent_type:"document",parent_id:this.id},O=c(async(x)=>{let S=Q(await this.client.storage.messageTimeline({path:$,query:{selection:JSON.stringify({limit:100,cursor:x})}}));return{items:S.items,nextCursor:S.next_cursor}}),j=[];for await(let x of O)j.push(x);return cO(j,P5,async(x)=>{let{state:S,root:K,replies:Z}=Q(await this.client.storage.entityMessageGetThread({path:{...$,id:x.id}}));return{thread:S,comments:[K,...Z].map((X)=>l$.from(this.client,this.id,X))}})}async comment($,O){let j=await this.mutate((x)=>x.storage.entityMessageCreate({path:{parent_type:"document",parent_id:this.id},body:{...O$($),thread_id:O?.threadId??null}}));return l$.from(this.client,this.id,j)}async shortId(){return Q(await this.client.storage.getDocumentShortId({path:{document_id:this.id}}))}async teamShare(){return Q(await this.client.storage.getDocumentTeamShare({path:{document_id:this.id}}))}async setTeamShare($){await this.mutate((O)=>O.storage.setDocumentTeamShare({path:{document_id:this.id},body:{shareWithTeam:$}}))}async githubPullRequests(){let{pullRequests:$}=Q(await this.client.storage.getDocumentGithubPullRequests({path:{document_id:this.id}}));return $}async branchName(){let{branchName:$}=Q(await this.client.storage.getDocumentBranchName({path:{document_id:this.id}}));return $}webUrl(){return`${this.client.webAppUrl}/app/md/${this.id}`}static search=x$({filters:{document_filters:{}},type:"document",make:($,O)=>new w($,O.document_id)});toMention(){let $=this.detail.peek();return{tag:o$("m-document-mention",{documentId:this.id,documentName:$?.documentName??"",blockName:$?.fileType??"md"}),mention:{entity_type:"document",entity_id:this.id}}}}class Aj{id;name;constructor($,O){this.id=$;this.name=O}static async list($){let{skills:O}=Q(await $.storage.getSystemSkillsHandler());return O.map((j)=>new Aj(j.id,j.name))}}class Wx{client;async byTeamSlug($){let O=Q(await this.client.storage.getDocumentByTeamSlug({path:{slug:$}}));if(typeof O!=="object"||O===null||!("data"in O)||typeof O.data!=="object"||O.data===null||!("documentMetadata"in O.data)||typeof O.data.documentMetadata!=="object"||O.data.documentMetadata===null||!("documentId"in O.data.documentMetadata)||typeof O.data.documentMetadata.documentId!=="string")throw Error("Invalid team task document response");return w.byId(this.client,O.data.documentMetadata.documentId)}async validatePermissionsToken($){let O=Q(await this.client.storage.validateDocumentPermissionsToken({body:{token:$}}));return{document:w.byId(this.client,O.document_id),user:O.user_id?C.byId(this.client,O.user_id):void 0,accessLevel:O.access_level,expiresAt:O.exp,issuer:O.iss}}async createUpload($){let O={documentName:$.name,sha:$.sha,fileType:$.fileType,mimeType:$.mimeType,projectId:$.project?.id,teamId:$.team?.id,branchedFromId:$.branchedFrom?.id,emailAttachmentId:$.attachment?.id,isTask:$.isTask},j=Q(await this.client.storage.createDocument({body:O})).data;return{document:w.byId(this.client,j.documentMetadata.documentId),uploadUrl:j.presignedUrl??void 0,contentType:j.contentType,content:j.documentMetadata.content}}constructor($){this.client=$}byId($){return w.byId(this.client,$)}create($){return w.create(this.client,$)}async createCanvas($){let O=Q(await this.client.storage.createCanvasHandler({body:{documentName:$.name,projectId:$.project?.id}}));return w.byId(this.client,O.documentId)}createSnippet($){return w.createSnippet(this.client,$)}createSkill($){return w.createSkill(this.client,$)}systemSkills(){return Aj.list(this.client)}search($,O){return w.search(this.client,$,O)}recent($){return w.recent(this.client,$)}recentlyDeleted(){return w.recentlyDeleted(this.client)}}class WO extends P{async fetch(){let{attachment:$}=Q(await this.client.email.getAttachment({path:{id:this.id}}));return $}static byId($,O){return new WO($,O)}static from($,O){return new WO($,O.db_id,O)}filename=this.field("filename");mimeType=this.field("mime_type");size=this.field("size_bytes");dataUrl=this.field("data_url");sfsId=this.field("sfs_id");contentId=this.field("content_id");async toDocument(){let{document_id:$}=Q(await this.client.email.getAttachmentDocumentId({path:{id:this.id}}));return w.byId(this.client,$)}}class z$ extends K${access=new $$(this.client,"email_thread",this);async followup(){return Q(await this.client.storage.getEmailFollowup({path:{thread_id:this.id}}))}async setFollowup($){return Q(await this.client.storage.setEmailFollowup({path:{thread_id:this.id},body:$}))}async calendarInvitations(){return Q(await this.client.email.getThreadCalendarInvitations({path:{thread_id:this.id}}))}async addEventToCalendar($,O,j={}){let x=Q(await this.client.email.copyThreadCalendarInvitation({path:{thread_id:this.id,message_id:$.id,invitation_id:O.id},body:{calendarId:j.calendar?.id}}));return S$.fromRecord(this.client,x)}async readReceipts(){let{receipts:$}=Q(await this.client.email.getThreadReadReceipts({path:{thread_id:this.id}}));return $.map((O)=>({message:U$.byId(this.client,O.message_id),openCount:O.open_count,firstOpenedAt:O.first_opened_at??void 0,lastOpenedAt:O.last_opened_at??void 0}))}async update($){await this.mutate((O)=>O.storage.editThreadV2({path:{thread_id:this.id},body:{projectId:$.project===void 0?void 0:$.project?.id??null,sharePermission:$.sharePermission?$O($.sharePermission):void 0}}))}entityType="email_thread";propertyEntityType="THREAD";async fetch(){let{thread:$}=Q(await this.client.email.getThread({path:{thread_id:this.id},query:{limit:100}}));return $}static byId($,O){return new z$($,O)}createdAt=this.field("created_at");updatedAt=this.field("updated_at");isRead=this.field("is_read");inboxVisible=this.field("inbox_visible");accessLevel=this.field("access_level");providerId=this.field("provider_id");link=this.mappedField("link_id",($)=>R$.byId(this.client,$));project=this.mappedField("project_id",($)=>$?n.byId(this.client,$):void 0);latestInboundAt=this.field("latest_inbound_message_ts");latestOutboundAt=this.field("latest_outbound_message_ts");latestNonSpamAt=this.field("latest_non_spam_message_ts");async subject(){let{messages:$}=await this.detail.get();for(let O of $)if(O.subject)return O.subject;return}async participants(){let{messages:$}=await this.detail.get(),O=new Map;for(let j of $)for(let x of[j.from,...j.to,...j.cc,...j.bcc])if(x&&!O.has(x.email))O.set(x.email,x);return[...O.values()]}async messages($){return Q(await this.client.email.getThreadMessagesHandler({path:{id:this.id},query:{...$?.since?{since:$.since}:{},...$?.limit?{limit:$.limit}:{}}})).map((j)=>U$.from(this.client,j))}async attachments(){let{messages:$}=await this.detail.get();return $.flatMap((O)=>O.attachments.map((j)=>WO.from(this.client,j)))}async reply($){let O=$.subject??await this.subject()??"",{message:j}=await this.mutate((x)=>x.email.sendMessage({body:{message:{thread_db_id:this.id,replying_to_id:$.replyingTo?.id??null,to:$.to,cc:$.cc??null,bcc:$.bcc??null,subject:O,body_text:$.bodyText}}}));return j.db_id?U$.byId(this.client,j.db_id):void 0}async archive($=!0){await this.mutate((O)=>O.email.archiveThread({path:{id:this.id},body:{value:$}}))}static async archiveMany($,O,j=!0){let x=[];for(let S=0;S<O.length;S+=100){let K=O.slice(S,S+100),Z=Q(await $.email.archiveThreads({body:{thread_ids:K.map((Y)=>Y.id),value:j}})),X=new Set(Z.failed_thread_ids);for(let Y of K)if(Y.detail.clear(),X.has(Y.id))x.push(Y)}return x}async updateState($){await this.mutate((O)=>O.email.updateThreadState({path:{id:this.id},body:$}))}async operations(){return Q(await this.client.email.threadOperations({path:{id:this.id}}))}async markSeen(){await this.mutate(($)=>$.email.threadSeen({path:{id:this.id}}))}async addLabel($){await this.mutate((O)=>O.email.addRemoveThreadLabel({path:{id:this.id},body:{label_id:$.id,value:!0}}))}async removeLabel($){await this.mutate((O)=>O.email.addRemoveThreadLabel({path:{id:this.id},body:{label_id:$.id,value:!1}}))}async moveToProject($){await this.mutate((O)=>O.email.updateThreadProject({path:{thread_id:this.id},body:{projectId:$?.id??null}}))}static search=x$({filters:{email_filters:{}},type:"email",make:($,O)=>new z$($,O.thread_id)})}class U$ extends P{async fetch(){return Q(await this.client.email.getMessage({path:{id:this.id}}))}static byId($,O){return new U$($,O)}static from($,O){return new U$($,O.db_id,O)}static async send($,O){let{message:j}=Q(await $.email.sendMessage({body:{message:{to:O.to,cc:O.cc??null,bcc:O.bcc??null,subject:O.subject,body_text:O.bodyText}}}));return j.db_id?U$.byId($,j.db_id):void 0}subject=this.field("subject");from=this.field("from");to=this.field("to");cc=this.field("cc");bcc=this.field("bcc");body=this.field("body_parsed");sentAt=this.field("internal_date_ts");labels=this.field("labels");link=this.mappedField("link_id",($)=>R$.byId(this.client,$));async operationStatus(){return Q(await this.client.email.messageOperationStatus({path:{id:this.id}}))}async resolveOperation($){await this.mutate((O)=>O.email.resolveMessageOperation({path:{id:this.id},body:$}))}async completeDraftAttachment($,O=0){let j=await this.link();await this.mutate((x)=>x.email.completeDraftAttachment({path:{id:this.id,attachment_id:$},query:{draft_generation:O},headers:{"X-Email-Link-Id":j.id}}))}async transferDraft($){let O=await this.detail.get();return this.mutate((j)=>j.email.transferDraft({path:{id:this.id},body:{...$,draft_generation:$.draft_generation??O.draft_generation??0},headers:{"X-Email-Link-Id":O.link_id}}))}async addLabel($){await this.mutate((O)=>O.email.addRemoveLabel({body:{label_id:$.id,message_ids:[this.id],value:!0}}))}async removeLabel($){await this.mutate((O)=>O.email.addRemoveLabel({body:{label_id:$.id,message_ids:[this.id],value:!1}}))}async thread(){return z$.byId(this.client,(await this.detail.get()).thread_db_id)}async downloadEml(){return Q(await this.client.email.getMessageEml({path:{id:this.id},parseAs:"blob"}))}}class BO extends U${async draftContext(){let $=await this.detail.get();return{headers:{"X-Email-Link-Id":$.link_id},query:{draft_generation:$.draft_generation??0}}}static byId($,O){return new BO($,O)}draftGeneration=this.field("draft_generation");async update($){let{headers:O,query:j}=await this.draftContext();await this.mutate((x)=>x.email.createDraft({headers:O,body:{draft:{...Bx($),db_id:this.id,draft_generation:$.draftGeneration??j.draft_generation}}}))}async delete(){let{headers:$,query:O}=await this.draftContext();await this.mutate((j)=>j.email.deleteDraft({path:{id:this.id},headers:$,query:O}))}async schedule($,O){let{headers:j,query:x}=await this.draftContext();await this.mutate((S)=>S.email.upsertScheduledMessage({path:{id:this.id},headers:j,query:x,body:{send_time:$,include_signature:O?.includeSignature}}))}async unschedule(){let{headers:$,query:O}=await this.draftContext();await this.mutate((j)=>j.email.deleteScheduledDraft({path:{message_id:this.id},headers:$,query:O}))}async addAttachment($){let O={file_name:$.fileName,sha:$.sha,size:$.size,upload_id:$.uploadId},{headers:j,query:x}=await this.draftContext(),S=await this.mutate((K)=>K.email.addDraftAttachment({path:{id:this.id},headers:j,query:x,body:O}));return{attachment:oO.byId(this.client,this,S.attachment_id,!1,x.draft_generation),uploadUrl:S.upload_url,contentType:S.content_type}}async forwardAttachment($){let{headers:O,query:j}=await this.draftContext(),x=await this.mutate((S)=>S.email.addForwardedAttachment({path:{id:this.id},headers:O,query:j,body:{attachment_id:$.id}}));return oO.byId(this.client,this,x.attachment_id,!0,j.draft_generation)}async removeAttachment($){if($.draft.id!==this.id)throw Error("Attachment belongs to another draft");let{headers:O}=await this.draftContext(),j={draft_generation:$.draftGeneration};if($.forwarded)await this.mutate((x)=>x.email.removeForwardedAttachment({path:{id:this.id,attachment_id:$.id},headers:O,query:j}));else await this.mutate((x)=>x.email.removeDraftAttachment({path:{id:this.id,attachment_id:$.id},headers:O,query:j}))}async verifyAttachment($){if($.draft.id!==this.id||$.forwarded)throw Error("Expected an uploaded attachment on this draft");await this.completeDraftAttachment($.id,$.draftGeneration)}}class oO{draft;id;forwarded;draftGeneration;constructor($,O,j,x){this.draft=$;this.id=O;this.forwarded=j;this.draftGeneration=x}static byId($,O,j,x=!1,S=0){return new oO(O,j,x,S)}complete(){return this.draft.verifyAttachment(this)}remove(){return this.draft.removeAttachment(this)}toJSON(){return{id:this.id,draftId:this.draft.id,forwarded:this.forwarded,draftGeneration:this.draftGeneration}}}function Bx($){let{bodyText:O,bodyHtml:j,bodyMacro:x,headers:S,includeSignature:K,draftGeneration:Z,thread:X,replyingTo:Y,...L}=$;return{...L,body_text:O,body_html:j===void 0?void 0:btoa(Array.from(new TextEncoder().encode(j),(G)=>String.fromCharCode(G)).join("")).replaceAll("+","-").replaceAll("/","_").replaceAll("=",""),body_macro:x,headers_json:S,include_signature:K,draft_generation:Z,thread_db_id:X?.id,replying_to_id:Y?.id}}class LO extends P{inbox;constructor($,O,j,x){super($,O,j);this.inbox=x}get headers(){return this.inbox?{"X-Email-Link-Id":this.inbox.id}:void 0}static byId($,O,j){return new LO($,O,void 0,j)}static from($,O,j){return new LO($,O.id,O,j)}async fetch(){let $=Q(await this.client.email.listEmailFilters({headers:this.headers})).filters.find((O)=>O.id===this.id);if(!$)throw new E(`Email filter ${this.id} is unavailable`);return $}emailAddress=this.field("email_address");emailDomain=this.field("email_domain");isImportant=this.field("is_important");async setImportant($){let O=await this.detail.get();await this.mutate((j)=>j.email.upsertEmailFilter({headers:this.headers,body:{email_address:O.email_address,email_domain:O.email_domain,is_important:$}}))}async delete(){await this.mutate(($)=>$.email.deleteEmailFilter({path:{id:this.id},headers:this.headers}))}}class xO extends P{async fetch(){let{labels:$}=Q(await this.client.email.listLabels()),O=$.find((j)=>j.id===this.id);if(!O)throw new E(`label ${this.id} not found`);return O}static byId($,O){return new xO($,O)}static async list($){let{labels:O}=Q(await $.email.listLabels());return O.map((j)=>new xO($,j.id,j))}static async create($,O){let{label:j}=Q(await $.email.createLabel({body:{label_name:O}}));if(!j.id)throw new f("created label has no id");return new xO($,j.id)}async delete(){Q(await this.client.email.deleteLabel({path:{id:this.id}}))}name=this.field("name");linkId=this.field("linkId");type=this.field("type");createdAt=this.field("createdAt");labelListVisibility=this.field("labelListVisibility");messageListVisibility=this.field("messageListVisibility")}class Lx{client;async createDraft($,O){let j=Q(await this.client.email.createDraft({body:{draft:Bx($)},headers:O?{"X-Email-Link-Id":O.id}:void 0}));if(!j.draft.db_id)throw Error("Draft response has no message id");return BO.byId(this.client,j.draft.db_id)}draftById($){return BO.byId(this.client,$)}async*scheduled($){let O=$?.pageSize??100;if(!Number.isInteger(O)||O<1)throw Error("pageSize must be positive");let j=Math.min(O,1000);for(let x=0;;x+=j){let S=Q(await this.client.email.getScheduledMessages({query:{offset:x,limit:j},headers:$?.inbox?{"X-Email-Link-Id":$.inbox.id}:void 0}));for(let K of S.messages)yield BO.byId(this.client,K.db_id);if(S.messages.length<j)return}}async filters($){return Q(await this.client.email.listEmailFilters({headers:$?{"X-Email-Link-Id":$.id}:void 0})).filters.map((O)=>LO.from(this.client,O,$))}async upsertFilter($,O){return LO.from(this.client,Q(await this.client.email.upsertEmailFilter({headers:O?{"X-Email-Link-Id":O.id}:void 0,body:{email_address:$.emailAddress,email_domain:$.emailDomain,is_important:$.isImportant}})).filter,O)}async contacts(){return Q(await this.client.email.listContacts()).contacts}reminders($){let{inboxes:O,...j}=$??{};return c(async(x)=>{let S=Q(await this.client.storage.listEmailReminders({query:{...j,inboxIds:O?.map((K)=>K.id),cursor:x}}));return{items:S.items.map(({threadId:K,...Z})=>({...Z,thread:z$.byId(this.client,K)})),nextCursor:S.nextCursor}})}constructor($){this.client=$}byId($){return z$.byId(this.client,$)}message($){return U$.byId(this.client,$)}attachment($){return WO.byId(this.client,$)}link($){return R$.byId(this.client,$)}links(){return R$.list(this.client)}async connectionProviders(){return Q(await this.client.auth.emailConnectionProviders())}async recoverDraftTransfer($){return Q(await this.client.email.recoverDraftTransfer({path:{id:$}}))}send($){return U$.send(this.client,$)}search($,O){return z$.search(this.client,$,O)}inbox($){return c(async(O)=>{let j=Q(await this.client.email.previewsInboxCursor({path:{view:"inbox"},query:{...$?.pageSize?{limit:$.pageSize}:{},...$?.sort?{sort_method:$.sort}:{},...O?{cursor:O}:{}}}));return{items:j.items.map((x)=>z$.byId(this.client,x.id)),nextCursor:j.next_cursor}})}label($){return xO.byId(this.client,$)}labels(){return xO.list(this.client)}createLabel($){return xO.create(this.client,$)}archive($,O=!0){return z$.archiveMany(this.client,$,O)}async deleteLabel($){Q(await this.client.email.deleteLabel({path:{id:$.id}}))}async blockSender($){Q(await this.client.email.blockSender({body:{email_address:$}}))}async unblockSender($){Q(await this.client.email.unblockSender({body:{email_address:$}}))}async blockedSenders(){return Q(await this.client.email.listBlockedSenders()).blocked_emails}}class TO{client;id;constructor($,O){this.client=$;this.id=O}static byId($,O){return new TO($,O)}async delete(){Q(await this.client.storage.deleteEntityMention({path:{mention_id:this.id}}))}toJSON(){return{id:this.id}}}class Nx{client;constructor($){this.client=$}byId($){return TO.byId(this.client,$)}async create($,O){let j=Q(await this.client.storage.createEntityMention({body:{source_entity_id:$.entity.id,source_entity_type:$.type,entity_id:O.entity.id,entity_type:O.type}}));return TO.byId(this.client,j.id)}}function Ux($,O){return{chat:NO.byId($,O.id),name:O.name,announcements:O.announcements}}class NO extends P{static byId($,O){return new NO($,O)}static from($,O){return new NO($,O.jid,O)}async fetch(){let{chats:$}=Q(await this.client.storage.whatsappChats()),O=$.find((j)=>j.jid===this.id);if(!O)throw new E("WhatsApp chat is not available");return O}kind=this.field("kind");name=this.field("name");phoneNumber=this.field("phoneNumber");lastActivityAt=this.field("lastActivityAt");archived=this.field("archived");pinned=this.field("pinned");canAdd=this.field("canAdd");cannotAddReason=this.field("cannotAddReason");community=this.mappedField("community",($)=>$?Ux(this.client,$):void 0);added=this.mappedField("added",($)=>$?g$.byId(this.client,$.id):void 0);shared=this.mappedField("shared",($)=>$?g$.byId(this.client,$.id):void 0);async add(){let $=await this.kind(),O=await this.mutate((j)=>j.storage.externalChatAdd({body:{provider:"whatsapp",remoteId:this.id,kind:$}}));return g$.byId(this.client,O.chatId)}async refresh(){return this.detail.clear(),await this.detail.get(),this}}class M$ extends P{chat;constructor($,O,j,x){super($,j,x);this.chat=O}static byId($,O,j){return new M$($,O,j)}static from($,O,j){return new M$($,O,j.id,j)}async fetch(){return Q(await this.client.storage.externalChatMessage({path:{chat_id:this.chat.id,message_id:this.id}}))}body=this.field("body");sender=this.field("sender");sentAt=this.field("sentAt");editedAt=this.field("editedAt");deleted=this.field("deleted");reactions=this.field("reactions");deliveryState=this.field("deliveryState");kind=this.field("kind");forwarded=this.field("forwarded");viewOnce=this.field("viewOnce");mentions=this.field("mentions");rich=this.field("rich");replyTo=this.mappedField("replyTo",($)=>$?M$.byId(this.client,this.chat,$):void 0);attachments=this.mappedField("attachments",($)=>$.map((O)=>({ordinal:O.ordinal,state:O.state,fileName:O.fileName,mime:O.mime,size:O.size,width:O.width??void 0,height:O.height??void 0,durationSeconds:O.durationSeconds??void 0,presentation:O.presentation??void 0,url:O.fileId?`${this.client.hosts["static-files"]}/file/${O.fileId}`:void 0})))}class SO{chat;id;record;constructor($,O,j){this.chat=$;this.id=O;this.record=j}static byId($,O){return new SO($,O)}static from($,O){return new SO($,O.jid,O)}get displayName(){return this.record?.displayName??void 0}get mentionToken(){return this.id.split("@")[0]??this.id}get admin(){return this.record?.admin}toJSON(){return{id:this.id,chat:this.chat.id,displayName:this.displayName,admin:this.admin}}}class ZO{id;chat;filename;kind;constructor($,O,j,x){this.id=$;this.chat=O;this.filename=j;this.kind=x}static byId($,O){return new ZO(O,$)}static from($,O){return new ZO(O.uploadId,$,O.filename,O.kind)}toJSON(){return{id:this.id,chat:this.chat.id,filename:this.filename,kind:this.kind}}}class XO extends P{chat;constructor($,O,j,x){super($,j,x);this.chat=O}static byId($,O,j){return new XO($,O,j)}static from($,O,j){return new XO($,O,j.id,j)}async fetch(){let O=Q(await this.client.storage.externalChatDelivery({path:{chat_id:this.chat.id},body:[this.id]})).find((j)=>j.id===this.id);if(!O)throw new E("External chat send is not available");return O}state=this.field("state");errorCode=this.field("errorCode");createdAt=this.field("createdAt");message=this.mappedField("messageId",($)=>$?M$.byId(this.client,this.chat,$):void 0);async request(){let{payload:$}=await this.detail.get(),O=$.message,j=k(O).returnType().with({type:"media"},(x)=>({type:"media",upload:ZO.byId(this.chat,x.uploadId),caption:x.caption??void 0})).with({type:"mutation"},(x)=>({type:"mutation",message:M$.byId(this.client,this.chat,x.messageId),operation:x.operation,text:x.text??void 0})).with({type:"text"},(x)=>({type:"text",text:x.text,mentions:(x.mentions??[]).map((S)=>SO.byId(this.chat,S))})).exhaustive();return{idempotencyKey:$.idempotencyKey,message:j,replyTo:$.replyTo?M$.byId(this.client,this.chat,$.replyTo):void 0}}async refresh(){return this.detail.clear(),await this.detail.get(),this}}class g$ extends H${entityType="external_chat";static byId($,O){return new g$($,O)}async fetch(){return Q(await this.client.storage.externalChat({path:{chat_id:this.id}}))}provider=this.field("provider");name=this.field("name");kind=this.field("kind");canSend=this.field("canSend");sendReason=this.field("sendReason");sendingIdentity=this.field("sendingIdentity");unreadCount=this.field("unreadCount");backfill=this.field("backfill");limits=this.field("limits");members=this.field("members");participants=this.mappedField("members",($)=>($?.participants??[]).map((O)=>SO.from(this,O)));disappearingSeconds=this.field("disappearingSeconds");owner=this.mappedField("userId",($)=>C.byId(this.client,$));async community(){let{provider:$,community:O}=await this.detail.get();if(!O)return;return k($).with("whatsapp",()=>Ux(this.client,O)).exhaustive()}async*messages($={}){yield*c(async(O)=>{let j=Q(await this.client.storage.externalChatMessages({path:{chat_id:this.id},query:{before:O,limit:$.limit}}));return{items:j.messages.map((x)=>M$.from(this.client,this,x)),nextCursor:j.nextCursor}})}async markRead($){this.assertChat($.chat),await this.mutate((O)=>O.storage.externalChatRead({path:{chat_id:this.id},body:{messageId:$.id}}))}async permissions(){return Q(await this.client.storage.externalChatPermissions({path:{chat_id:this.id}}))}async updatePermissions($){await this.mutate((O)=>O.storage.externalChatUpdatePermissions({path:{chat_id:this.id},body:$}))}async remove(){await this.mutate(($)=>$.storage.externalChatRemove({path:{chat_id:this.id}}))}async upload($){let O=Q(await this.client.storage.externalChatUpload({path:{chat_id:this.id},body:{file:$}}));return ZO.from(this,O)}async send($,O){if(O.replyTo)this.assertChat(O.replyTo.chat);let j=k($).returnType().with({type:"text"},(S)=>{let K=S.mentions??[];for(let Z of K)this.assertChat(Z.chat);return{type:"text",text:S.text,mentions:K.map((Z)=>Z.id)}}).with({type:"media"},(S)=>{return this.assertChat(S.upload.chat),{type:"media",uploadId:S.upload.id,caption:S.caption}}).with({type:"mutation"},(S)=>{return this.assertChat(S.message.chat),{type:"mutation",messageId:S.message.id,operation:S.operation,text:S.text}}).exhaustive(),x=await this.mutate((S)=>S.storage.externalChatSend({path:{chat_id:this.id},body:{idempotencyKey:O.idempotencyKey,message:j,replyTo:O.replyTo?.id}}));return XO.from(this.client,this,x)}async sends(){return Q(await this.client.storage.externalChatSends({path:{chat_id:this.id}})).map(($)=>XO.from(this.client,this,$))}async delivery($){for(let O of $)this.assertChat(O.chat);return Q(await this.client.storage.externalChatDelivery({path:{chat_id:this.id},body:$.map((O)=>O.id)})).map((O)=>XO.from(this.client,this,O))}async messageAttachments($){for(let O of $)this.assertChat(O.chat);return Q(await this.client.storage.externalChatMessageAttachments({path:{chat_id:this.id},body:$.map((O)=>O.id)})).map((O)=>({message:M$.byId(this.client,this,O.messageId),attachments:O.attachments.map((j)=>({ordinal:j.ordinal,state:j.state,fileName:j.fileName,mime:j.mime,size:j.size,url:j.fileId?`${this.client.hosts["static-files"]}/file/${j.fileId}`:void 0}))}))}async refresh(){return this.detail.clear(),await this.detail.get(),this}assertChat($){if($.id!==this.id)throw Error("External chat reference belongs to another chat")}}class zx{client;constructor($){this.client=$}async list(){return Q(await this.client.storage.externalChats()).map(($)=>g$.byId(this.client,$.id))}byId($){return g$.byId(this.client,$)}}class Ix{client;constructor($){this.client=$}async list($={}){let{favorites:O}=Q(await this.client.storage.listFavorites({query:{entityType:$.entityTypes,entityId:$.entityIds}}));return O}async add($){return Q(await this.client.storage.addFavorite({body:{entityId:$.id,entityType:$.entityType}}))}async remove($){Q(await this.client.storage.removeFavoriteByEntity({path:{entity_type:$.entityType,entity_id:$.id}}))}async reorder($){Q(await this.client.storage.reorderFavorites({body:{favorites:$}}))}}class KO extends H${entityType="foreign_entity";async fetch(){return Q(await this.client.storage.getForeignEntity({path:{id:this.id}}))}static byId($,O){return new KO($,O)}static fromRecord($,O){return new KO($,O.id,O)}foreignEntityId=this.field("foreignEntityId");source=this.field("foreignEntitySource");storedForId=this.field("storedForId");storedForAuthEntity=this.field("storedForAuthEntity");createdAt=this.field("createdAt");updatedAt=this.field("updatedAt");async metadata(){return(await this.detail.get()).metadata}}function S2({login:$,...O}){return{...O,login:$??void 0}}class Hx{client;constructor($){this.client=$}byId($){return KO.byId(this.client,$)}async bySource($,O){return KO.fromRecord(this.client,Q(await this.client.storage.getForeignEntityBySource({path:{source:$,foreign_entity_id:O}})))}async githubPullRequestFacets(){let{repositories:$,authors:O,assignees:j,labels:x}=Q(await this.client.storage.getGithubPullRequestFacets());return{repositories:$,authors:O.map(S2),assignees:j.map(S2),labels:x.map(({color:S,...K})=>({...K,color:S??void 0}))}}}class r${form;id;constructor($,O){this.form=$;this.id=O}static byId($,O){return new r$($,O)}async detail(){let O=(await this.form.schema()).sections.flatMap((j)=>j.kind==="questions"?j.questions:[]).find((j)=>j.id===this.id);if(!O)throw new E(`question ${this.id} is not on form ${this.form.id}`);return O}async title(){return(await this.detail()).title}async column(){return F$.byId(await this.form.table(),(await this.detail()).column)}async options(){return(await this.detail()).options.map(($)=>UO.byId(this,$.id))}}class UO{question;id;constructor($,O){this.question=$;this.id=O}static byId($,O){return new UO($,O)}async detail(){let $=(await this.question.detail()).options.find((O)=>O.id===this.id);if(!$)throw new E(`option ${this.id} is not on question ${this.question.id}`);return $}async label(){return(await this.detail()).label}async color(){return(await this.detail()).color??void 0}}class RO{form;id;detail;constructor($,O,j){this.form=$;this.id=O;this.detail=new W$(()=>this.load(),j)}async load(){let $=await this.form.myResponse();if($.kind==="anonymous"||$.response.id!==this.id)throw new E(`response ${this.id} is not your current response`);return $}static byId($,O,j){return new RO($,O,j)}async status(){return(await this.detail.get()).status}async row(){return(await this.detail.get()).row}async answers(){return(await this.detail.get()).answers}async booking(){return(await this.detail.get()).booking}async refresh(){let $=await this.load();return this.detail=new W$(()=>this.load(),$),this}}class p${form;id;constructor($,O){this.form=$;this.id=O}static byId($,O){return new p$($,O)}async detail(){let $=(await this.form.schema()).sections.find((O)=>O.id===this.id);if(!$)throw new E(`section ${this.id} is not on form ${this.form.id}`);return $}async title(){return(await this.detail()).title}async questions(){let $=await this.detail();return $.kind==="questions"?$.questions.map((O)=>r$.byId(this.form,O.id)):[]}}class Fj{entityType;id;constructor($,O){this.entityType=$;this.id=O}static byId($,O){return new Fj($,O)}}class y$ extends P{async fetch(){return Q(await this.client.storage.getForm({path:{id:this.id}}))}static byId($,O){return new y$($,O)}static async create($,O){let j=Q(await $.storage.createForm({body:{name:O.name,source:O.table?{kind:"table",databaseId:O.table.database.id,tableId:O.table.id}:{kind:"new"}}}));return new y$($,j.form.id,j)}static async list($,O){if(!O)return Q(await $.storage.listAccessibleForms()).map(({form:S})=>new y$($,S.id));return Q(await $.storage.listForms({query:{databaseId:O.id}})).map((x)=>new y$($,x.id))}schema(){return this.detail.get()}name=this.mappedField("form",($)=>$.name);description=this.mappedField("form",($)=>$.description);owner=this.mappedField("form",($)=>C.byId(this.client,$.ownerId));database=this.mappedField("form",($)=>Q$.byId(this.client,$.databaseId));table=this.mappedField("form",($)=>V$.byId(Q$.byId(this.client,$.databaseId),$.tableId));audience=this.mappedField("form",($)=>$.audience);status=this.mappedField("form",($)=>$.status);closesAt=this.mappedField("form",($)=>$.closesAt??void 0);access=this.field("access");async sections(){return(await this.detail.get()).sections.map(($)=>p$.byId(this,$.id))}async questions(){return(await this.detail.get()).sections.flatMap(($)=>$.kind==="questions"?$.questions.map((O)=>r$.byId(this,O.id)):[])}async update($){return await this.mutate((O)=>O.storage.updateForm({path:{id:this.id},body:$})),this}assertOwns($){if($.form.id!==this.id)throw new f(`question or section does not belong to form ${this.id}`)}async replaceLayout($){let O=await this.table(),j=(Z)=>{if(Z.table.id!==O.id||Z.table.database.id!==O.database.id)throw new f(`column does not belong to form ${this.id}'s table`);return Z.id},x=(Z)=>({conjunction:Z.conjunction,conditions:Z.conditions.map((X)=>k(X).with({kind:"group"},(Y)=>({kind:"group",...x(Y)})).with({kind:"condition"},(Y)=>({kind:"condition",column:j(Y.column),test:k(Y.test).with({kind:"options"},(L)=>({...L,options:L.options.map((G)=>G.id)})).with({kind:"entities"},(L)=>({...L,entities:L.entities.map((G)=>G.id)})).with({kind:t.union("presence","text","number","date","dateRange","checkbox")},(L)=>L).exhaustive()})).exhaustive())}),S={sections:$.map((Z)=>{if(Z.section)this.assertOwns(Z.section);let X={id:Z.section?.id??c$(),title:Z.title,description:Z.description??""};return k(Z).with({kind:"booking"},(Y)=>({...X,kind:"booking",target:Y.target})).with({kind:"gate"},(Y)=>({...X,kind:"gate",rules:x(Y.rules),message:Y.message})).with({kind:"questions"},(Y)=>({...X,kind:"questions",questions:Y.questions.map((L)=>{if(L.question)this.assertOwns(L.question);return{id:L.question?.id??c$(),column:j(L.column),helpText:L.helpText??"",required:L.required??!1,widget:L.widget??null}})})).exhaustive()})},K=await this.mutate((Z)=>Z.storage.putFormLayout({path:{id:this.id},body:S}));return{form:this,publicationError:K.publicationError}}wireAnswers($){return $.map(({question:O,value:j})=>{this.assertOwns(O);let x=k(j).with({type:"rows"},(S)=>({type:"rows",value:S.value.map((K)=>K.id)})).with({type:"options"},(S)=>({type:"options",value:S.value.map((K)=>{if(K.question.id!==O.id||K.question.form.id!==this.id)throw new f("option does not belong to the answered question");return{id:K.id}})})).with({type:"entities"},(S)=>({type:"entities",value:S.value.map(({entityType:K,entity:Z})=>({entityType:K,entityId:Z.id}))})).with({type:t.union("text","number","boolean","date","date_range","link","clear")},(S)=>S).exhaustive();return{question:O.id,value:x}})}unlockedBooking($){return $?{...$,section:p$.byId(this,$.section)}:void 0}async outcome($,O){return k($).with({outcome:"stopped"},(j)=>({...j,section:p$.byId(this,j.section)})).with({outcome:"submitted"},async(j)=>{let x=E$.byId(await this.table(),j.row),S=this.unlockedBooking(j.booking);return{outcome:"submitted",response:RO.byId(this,j.response,{status:"submitted",row:x,answers:O,booking:S}),row:x,...S?{booking:S}:{}}}).exhaustive()}async submit($){let O={answers:this.wireAnswers($)};return this.outcome(Q(await this.client.storage.submitFormResponse({path:{id:this.id},body:O})),$)}async editResponse($){let O={answers:this.wireAnswers($)};return this.outcome(Q(await this.client.storage.editMyFormResponse({path:{id:this.id},body:O})),$)}async myResponse(){let $=Q(await this.client.storage.getMyFormResponse({path:{id:this.id}}));if($.kind==="anonymous")return{kind:"anonymous"};let O=await this.table(),j=await Promise.all($.answers.map(async(K)=>{let Z=r$.byId(this,K.question),X=await k(K.value).with({type:"options"},(Y)=>({type:"options",value:Y.value.map((L)=>{if(!("id"in L))throw new f("stored form answers must reference options by id");return UO.byId(Z,L.id)})})).with({type:"entities"},(Y)=>({type:"entities",value:Y.value.map((L)=>({entityType:L.entityType,entity:Fj.byId(L.entityType,L.entityId)}))})).with({type:"rows"},async(Y)=>{let L=await Z.detail();if(L.kind.type!=="relation")throw new f("row answer requires a relation question");let G=V$.byId(Q$.byId(this.client,L.kind.database),L.kind.table);return{type:"rows",value:Y.value.map((J)=>E$.byId(G,J))}}).with({type:t.union("text","number","boolean","date","date_range","link","clear")},(Y)=>Y).exhaustive(()=>{throw new f(`answer to question ${Z.id} has a type this SDK doesn't know`)});return{question:Z,value:X}})),x=$.response.row?E$.byId(O,$.response.row):void 0,S=this.unlockedBooking($.booking);return{kind:"saved",...S?{booking:S}:{},response:RO.byId(this,$.response.id,{status:$.response.status,row:x,answers:j,booking:S}),status:$.response.status,stoppedAtSection:$.response.stoppedAtSection?p$.byId(this,$.response.stoppedAtSection):void 0,row:x,submittedAt:$.response.submittedAt,updatedAt:$.response.updatedAt,answers:j}}async responseSummary(){let $=Q(await this.client.storage.getFormResponseSummary({path:{id:this.id}}));return{...$,stoppedBySection:$.stoppedBySection.map((O)=>({section:p$.byId(this,O.section),count:O.count}))}}async tally(){return Q(await this.client.storage.getFormTally({path:{id:this.id}})).questions.map((O)=>{let j=r$.byId(this,O.question);return{question:j,responses:O.responses,buckets:O.buckets.flatMap((x)=>k(x.value).with({kind:"option"},(S)=>[{count:x.count,value:{kind:"option",option:UO.byId(j,S.option)}}]).with({kind:"checkbox"},(S)=>[{count:x.count,value:S}]).exhaustive((S)=>{return console.warn("macro sdk: unknown form tally bucket",S),[]}))}})}async sharePermissions(){return Q(await this.client.storage.getFormPermissions({path:{id:this.id}}))}updateSharePermissions($){return this.mutate((O)=>O.storage.updateFormPermissions({path:{id:this.id},body:$}))}webUrl(){return`${this.client.webAppUrl}/app/form/${this.id}`}respondUrl(){return`${this.client.webAppUrl}/app/form/${this.id}/respond`}}class Tx{client;constructor($){this.client=$}byId($){return y$.byId(this.client,$)}create($){return y$.create(this.client,$)}list($){return y$.list(this.client,$)}}class DO extends P{static byId($,O){return new DO($,O)}async fetch(){return Q(await this.client.storage.getGithubPullRequest({path:{id:this.id}}))}title=this.field("title");url=this.field("url");status=this.field("status");async changes(){let $=Q(await this.client.storage.getGithubPullRequestChanges({path:{id:this.id}}));return{changeset:$.changeset?new Rx(this.client,this,$.changeset):void 0,error:$.error??void 0}}}class Rx{client;pullRequest;record;constructor($,O,j){this.client=$;this.pullRequest=O;this.record=j}get id(){return this.record.id}async patch(){return Q(await this.client.storage.getGithubPullRequestChangesPatch({path:{id:this.pullRequest.id},query:{changeset:this.id}})).patch}toJSON(){return{pullRequestId:this.pullRequest.id,...this.record}}}class Dx{client;constructor($){this.client=$}byId($){return DO.byId(this.client,$)}forEntity($){return DO.byId(this.client,$.id)}}class _O extends P{static byId($,O){return new _O($,O)}async fetch(){return Q(await this.client.storage.getHarnessPairing({path:{code:this.id}}))}name=this.field("requested_name");expiresAt=this.field("expires_at");async approve($){let O={name:$?.name,team_id:$?.team?.id,allow_permission_bypass:$?.allowPermissionBypass};return B$.from(this.client,await this.mutate((j)=>j.storage.approveHarnessPairing({path:{code:this.id},body:O})))}}class $j{client;id;constructor($,O){this.client=$;this.id=O}static byId($,O){return new $j($,O)}async claim($){let O=Q(await this.client.storage.claimHarnessPairing({path:{pairing_id:this.id},body:{device_secret:$}}));return"harness"in O?{harness:B$.from(this.client,O.harness),token:O.token}:void 0}toJSON(){return{id:this.id}}}class _x{client;constructor($){this.client=$}byId($){return B$.byId(this.client,$)}async list(){return Q(await this.client.storage.listHarnesses()).map(($)=>B$.from(this.client,$))}async me(){return B$.from(this.client,Q(await this.client.storage.getSelfHarness()))}async deleteSelf(){Q(await this.client.storage.deleteSelfHarness())}async agents(){return Q(await this.client.storage.listHarnessAgents()).map(($)=>T$.byId(this.client,$.bot_id))}async sessions(){return Q(await this.client.storage.listHarnessSessions()).map(($)=>d.byId(this.client,$.session_id))}pairing($){return _O.byId(this.client,$)}async createPairing($){let O=Q(await this.client.storage.createHarnessPairing({body:$}));return{pairing:_O.byId(this.client,O.code),device:$j.byId(this.client,O.pairing_id),deviceSecret:O.device_secret,expiresAt:O.expires_at,pollIntervalSeconds:O.poll_interval_seconds}}}class Ej{id;url;width;height;constructor($,O,j,x){this.id=$;this.url=O;this.width=j;this.height=x}static byId($,O,j){return new Ej(O,`${$.hosts["static-files"]}/file/${O}`,j?.width,j?.height)}toJSON(){return{id:this.id,url:this.url,width:this.width,height:this.height}}}class qj extends Ej{width;height;mimeType;sizeBytes;note;constructor($,O,j,x,S,K,Z){super($,O,j,x);this.width=j;this.height=x;this.mimeType=S;this.sizeBytes=K;this.note=Z}toJSON(){return{...super.toJSON(),mimeType:this.mimeType,sizeBytes:this.sizeBytes,note:this.note}}}class Mx{client;constructor($){this.client=$}async generate($){let O=Q(await this.client.cognition.generateImage({body:{prompt:$.prompt,aspectRatio:$.aspectRatio??null,referenceImages:($.referenceImages??[]).map(A5)}}));return new qj(O.staticFileId,O.url,O.width,O.height,O.mimeType,O.sizeBytes,O.note??void 0)}}function A5($){return $ instanceof w?{type:"document",id:$.id}:{type:"staticFile",id:$.id}}var F5="00000001-0000-0000-0000-000000000001",Z2="00000001-0000-0000-0000-000000000002",E5="00000001-0000-0000-0000-000000000004",q5="00000001-0000-0000-0000-000000000014",w5="00000001-0000-0000-0002-000000000001",f5="00000001-0000-0000-0002-000000000004";function b5($){let O=$.match(/^https:\/\/github\.com\/([^/]+)\/([^/]+)\/pull\/([1-9][0-9]*)\/?(?:[?#].*)?$/i);if(!O)throw Error(`Expected a GitHub pull request URL like https://github.com/owner/repo/pull/1, got ${$}`);return`${O[1]}/${O[2]}/pull/${O[3]}`}class G$ extends w{static byId($,O){return new G$($,O)}static async create($,O){let{documentId:j}=Q(await $.storage.createTaskHandler({body:{taskName:O.name,markdown:O.markdown??null,projectId:O.project?.id??null,teamId:O.team?.id??null,shareWithTeam:O.shareWithTeam??!0,propertyValues:await k5($,O)}}));return new G$($,j)}static async summaries($,O){if(O.length===0)return[];let{previews:j}=Q(await $.storage.getBatchPreviewHandler({body:{document_ids:O.map((S)=>S.id)}})),x=new Map(j.flatMap((S)=>S.type==="access"?[[S.document_id,S]]:[]));return O.flatMap((S)=>{let K=x.get(S.id);if(!K)return[];return[{task:S,name:K.document_name,owner:C.byId($,K.owner),updatedAt:K.updated_at??void 0,completed:K.sub_type?.type==="task"&&K.sub_type.is_completed}]})}static async findSimilar($,O){let{results:j}=Q(await $.storage.taskSimilaritySearchHandler({body:{taskName:O.title,markdown:O.body??null}}));return j.map((x)=>({task:new G$($,x.taskId),name:x.taskName,similarity:x.vectorScore}))}static async forPullRequest($,O){let j=b5(O),{pullRequests:x}=Q(await $.storage.getGithubPullRequestTasks({body:{githubKeys:[j]}}));return(x[0]?.taskIds??[]).map((S)=>new G$($,S))}async completed(){let{subType:$}=await this.detail.get();if($!=="task")return;let j=(await this.properties()).find((x)=>x.definition.id===Z2)?.value;return j?.type==="SelectOption"&&j.value.includes(f5)}webUrl(){return`${this.client.webAppUrl}/app/task/${this.id}`}static search=x$({filters:{document_filters:{sub_types:["task"],task_filters:{}}},type:"document",make:($,O)=>new G$($,O.document_id)})}async function k5($,O){if(!O.initiative&&!O.assignees&&!O.dueDate)return null;let j=O.assignees??[await C.me($)],x=[{propertyId:Z2,value:{type:"select_option",option_id:w5}}];if(j.length>0)x.push({propertyId:F5,value:{type:"multi_entity_reference",references:j.map((S)=>({entity_id:S.id,entity_type:"USER"}))}});if(O.initiative)x.push({propertyId:q5,value:{type:"entity_reference",reference:{entity_id:O.initiative.id,entity_type:"INITIATIVE"}}});if(O.dueDate)x.push({propertyId:E5,value:{type:"date",value:O.dueDate.toISOString()}});return x}class a$ extends P{access=new $$(this.client,"initiative",this);static byId($,O){return new a$($,O)}static from($,O){return new a$($,O.id,O)}async fetch(){return Q(await this.client.storage.getInitiative({path:{initiative_id:this.id}}))}name=this.field("name");owner=this.mappedField("ownerId",($)=>C.byId(this.client,$));members=this.mappedField("memberIds",($)=>$.map((O)=>C.byId(this.client,O)));tasks=this.mappedField("taskIds",($)=>$.map((O)=>G$.byId(this.client,O)));accessLevel=this.field("userAccessLevel");sharePermissions=this.field("sharePermission");async update($){await this.mutate((O)=>O.storage.updateInitiative({path:{initiative_id:this.id},body:{name:$.name,memberIds:$.members?.map((j)=>j.id),sharePermission:$.sharePermission?$O($.sharePermission):void 0}}))}async delete(){await this.mutate(($)=>$.storage.deleteInitiative({path:{initiative_id:this.id}}))}}class Cx{client;constructor($){this.client=$}byId($){return a$.byId(this.client,$)}async list(){return Q(await this.client.storage.listInitiatives()).initiatives.map(($)=>a$.byId(this.client,$.id))}async summaries(){return Q(await this.client.storage.listInitiatives()).initiatives.map(($)=>({initiative:a$.byId(this.client,$.id),name:$.name,updatedAt:$.updatedAt}))}async create($){return a$.from(this.client,Q(await this.client.storage.createInitiative({body:{name:$.name,description:$.description,memberIds:$.members?.map((O)=>O.id),shareWithTeam:$.shareWithTeam,propertyValues:$.propertyValues}})))}}class Px{client;constructor($){this.client=$}byId($){return D$.byId(this.client,$)}async create($){return D$.from(this.client,Q(await this.client.storage.meetingCreate({body:$})))}async list(){return Q(await this.client.storage.meetingList()).meetings.map(($)=>D$.from(this.client,$))}async active(){return Q(await this.client.storage.meetingListActive()).meetings.map(($)=>D$.from(this.client,$))}async lookup($){return D$.from(this.client,Q(await this.client.storage.meetingLookup({path:{token:$}})))}}class zO extends P{async fetch(){return Q(await this.client.notification.getTypedNotificationById({path:{notification_id:this.id}}))}static byId($,O){return new zO($,O)}static from($,O){return new zO($,O.id,O)}static list($,O){return c(async(j)=>{let x=Q(await $.notification.listTypedNotifications({query:{...O?.pageSize?{limit:O.pageSize}:{},...O?.states!==void 0?{states:O.states.join(",")}:{},...j?{cursor:j}:{}}}));return{items:x.items.map((S)=>zO.from($,S)),nextCursor:x.next_cursor}})}type=this.field("notification_event_type");createdAt=this.field("created_at");updatedAt=this.field("updated_at");state=this.field("state");done=this.mappedField("state",($)=>$==="done");sent=this.field("sent");viewedAt=this.field("viewed_at");deletedAt=this.field("deleted_at");owner=this.mappedField("owner_id",($)=>C.byId(this.client,$));sender=this.mappedField("sender_id",($)=>$?C.byId(this.client,$):void 0);metadata=this.field("notification_metadata");async seen(){return await this.state()!=="unseen"}async markSeen(){await this.mutate(($)=>$.notification.bulkMarkNotificationsSeen({body:{notificationIds:[this.id]}}))}async markDone(){await this.mutate(($)=>$.notification.bulkMarkNotificationsDone({body:{notificationIds:[this.id]}}))}async markUndone(){await this.mutate(($)=>$.notification.bulkMarkNotificationsUndone({body:{notificationIds:[this.id]}}))}async delete(){await this.mutate(($)=>$.notification.deleteUserNotificationV2({path:{notification_id:this.id}}))}}class Ax{client;constructor($){this.client=$}byId($){return zO.byId(this.client,$)}list($){return zO.list(this.client,$)}async markSeen($){Q(await this.client.notification.bulkMarkNotificationsSeen({body:{notificationIds:$}}))}async markDone($){Q(await this.client.notification.bulkMarkNotificationsDone({body:{notificationIds:$}}))}async delete($){Q(await this.client.notification.bulkDeleteUserNotificationsV2({body:{notificationIds:$}}))}async preferences(){return Q(await this.client.notification.getNotificationTypePreferences())}async enableType($){Q(await this.client.notification.enableNotificationType({path:{notification_event_type:$}}))}async disableType($){Q(await this.client.notification.disableNotificationType({path:{notification_event_type:$}}))}}class Fx{client;constructor($){this.client=$}async list(){let{data:$}=Q(await this.client.storage.getPinsHandler({}));return $?.recent??[]}async add($,O){Q(await this.client.storage.addPinHandler({path:{pinned_item_id:$.id},body:{pinType:$.entityType,pinIndex:O.index}}))}async remove($){Q(await this.client.storage.removePinHandler({path:{pinned_item_id:$.id},body:{pinType:$.entityType}}))}async reorder($){Q(await this.client.storage.reorderPinsHandler({body:$}))}}class Ex{client;constructor($){this.client=$}byId($){return n.byId(this.client,$)}create($){return n.create(this.client,$)}search($,O){return n.search(this.client,$,O)}}class MO{client;definitionId;id;record;constructor($,O,j,x){this.client=$;this.definitionId=O;this.id=j;this.record=x}static from($,O,j){return new MO($,O,j.id,j)}get value(){return this.record.value}get color(){return this.record.color??void 0}get displayOrder(){return this.record.display_order}get createdAt(){return this.record.created_at}get updatedAt(){return this.record.updated_at}async update($){return this.record=Q(await this.client.properties.updatePropertyOption({path:{definition_id:this.definitionId,option_id:this.id},body:$})),this}async delete(){Q(await this.client.properties.deletePropertyOption({path:{definition_id:this.definitionId,option_id:this.id}}))}}class YO{client;id;detail;constructor($,O,j){this.client=$;this.id=O;this.detail=new W$(()=>this.fetch(),j)}async fetch(){return Q(await this.client.properties.getPropertyDefinition({path:{definition_id:this.id}}))}static async create($,O){let j=Q(await $.properties.createPropertyDefinition({body:{display_name:O.displayName,scope:O.scope,data_type:O.dataType}}));return new YO($,j.id,j)}static byId($,O){return new YO($,O)}static fromRecord($,O){return new YO($,O.id,O)}get displayName(){return this.detail.get().then(($)=>$.display_name)}get dataType(){return this.detail.get().then(($)=>$.data_type)}get owner(){return this.detail.get().then(($)=>$.owner)}get isSystem(){return this.detail.get().then(($)=>$.is_system)}get isMultiSelect(){return this.detail.get().then(($)=>$.is_multi_select)}get createdAt(){return this.detail.get().then(($)=>$.created_at)}get updatedAt(){return this.detail.get().then(($)=>$.updated_at)}async delete(){return Q(await this.client.properties.deletePropertyDefinition({path:{definition_id:this.id}}))}async options(){return Q(await this.client.properties.getPropertyOptions({path:{definition_id:this.id}})).map((O)=>MO.from(this.client,this.id,O))}async addOption($){let O=Q(await this.client.properties.addPropertyOption({path:{definition_id:this.id},body:$}));return MO.from(this.client,this.id,O)}async updateOption($,O){let j=Q(await this.client.properties.updatePropertyOption({path:{definition_id:this.id,option_id:$.id},body:O}));return MO.from(this.client,this.id,j)}async deleteOption($){return Q(await this.client.properties.deletePropertyOption({path:{definition_id:this.id,option_id:$.id}}))}}class qx{client;constructor($){this.client=$}async list($){return Q(await this.client.properties.listProperties({query:{scope:$?.scope??"all",...$?.forEntityType!==void 0?{for_entity_type:$.forEntityType}:{}}})).map((j)=>{let x="definition"in j?j.definition:j;return YO.fromRecord(this.client,x)})}create($){return YO.create(this.client,$)}definition($){return YO.byId(this.client,$)}async bulkEntityProperties($){return Q(await this.client.properties.getBulkEntityProperties({body:$}))}async updateEntityPropertyOptions($,O){return Q(await this.client.properties.bulkUpdateEntitiesPropertyOptions({body:{entities:$.map((x)=>x.propertyReference()),property_id:O.property.id,...O.add?{add_option_ids:O.add.map((x)=>x.id)}:{},...O.remove?{remove_option_ids:O.remove.map((x)=>x.id)}:{}}})).results}async addEntityPropertyOption($){return Q(await this.client.properties.addEntityPropertyOption({path:{...$.entity.propertyReference(),property_id:$.property.id,option_id:$.option.id}}))}async removeEntityPropertyOption($){return Q(await this.client.properties.removeEntityPropertyOption({path:{...$.entity.propertyReference(),property_id:$.property.id,option_id:$.option.id}}))}async tags(){return Q(await this.client.properties.listTags({}))}}class wx{client;constructor($){this.client=$}async link(){let $=Q(await this.client.auth.getReferralCode()),O=new URL("/app/signup",this.client.webAppUrl);return O.searchParams.set("referral_code",$),{code:$,url:O.toString()}}async invite($){let O=$.trim();if(!O)throw new f("invite needs an email address");Q(await this.client.auth.sendReferralCode({body:{recipient:O}}))}}function fx($){return k($).with({type:"cron"},(O)=>O).with({type:"events"},(O)=>({type:"events",filters:O.filters.map(({entities:j,...x})=>({...x,ids:j?.map((S)=>S.entity.id)}))})).exhaustive()}function g5($){return k($).with({type:"multiple"},(O)=>({type:"multiple",triggers:O.triggers.map(fx)})).with({type:"cron"},fx).with({type:"events"},fx).exhaustive()}class v$ extends P{static byId($,O){return new v$($,O)}static from($,O){if(!O.id)throw Error("Routine response has no id");return new v$($,O.id,O)}async fetch(){return Q(await this.client.scheduledAction.getScheduledAction({path:{id:this.id}}))}name=this.field("name");trigger=this.field("trigger");enabled=this.field("enabled");runVisibility=this.field("run_visibility");nextRunAt=this.field("next_run_at");revision=this.field("configuration_revision");owner=this.mappedField("owner",($)=>C.byId(this.client,$));sourceTemplate=this.mappedField("template_id",($)=>$?v$.byId(this.client,$):void 0);async template(){let $=await this.client.scheduledAction.getScheduledActionTemplate({path:{id:this.id}});if($.response?.status===404)return;return this.toTemplate(Q($))}async shareAsTemplate($){return this.toTemplate(Q(await this.client.scheduledAction.shareScheduledActionTemplate({path:{id:this.id},body:$})))}async activateTemplate($){return v$.from(this.client,Q(await this.client.scheduledAction.activateScheduledActionTemplate({path:{id:this.id},body:{...wj($),enabled:$.enabled??!0}})))}toTemplate($){return new X2(this,C.byId(this.client,$.author),$)}async stopSharingTemplate(){Q(await this.client.scheduledAction.unshareScheduledActionTemplate({path:{id:this.id}}))}async update($){await this.mutate((O)=>O.scheduledAction.updateScheduledAction({path:{id:this.id},body:wj($)}))}async setEnabled($){await this.mutate((O)=>O.scheduledAction.setScheduledActionEnabled({path:{id:this.id},body:{enabled:$}}))}async execute(){let $=Q(await this.client.scheduledAction.executeScheduledActionNow({path:{id:this.id}}));if($.resource)return k($.resource).with({type:"agent"},(O)=>d.byId(this.client,O.id)).with({type:"chat"},(O)=>Y$.byId(this.client,O.id)).exhaustive();return $.chat_id?Y$.byId(this.client,$.chat_id):void 0}async history(){return Q(await this.client.scheduledAction.listScheduledActionHistory({path:{id:this.id}})).map(($)=>new bx(this,$))}async delete(){await this.mutate(($)=>$.scheduledAction.deleteScheduledAction({path:{id:this.id}}))}}class X2{routine;author;record;constructor($,O,j){this.routine=$;this.author=O;this.record=j}activate($){return this.routine.activateTemplate($)}toJSON(){return this.record}}class bx{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 wj($){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:g5($.trigger),task:{...O}}}class kx{client;constructor($){this.client=$}byId($){return v$.byId(this.client,$)}async create($){return v$.from(this.client,Q(await this.client.scheduledAction.createScheduledAction({body:{...wj($),enabled:$.enabled??!0}})))}async list($){return Q(await this.client.scheduledAction.listScheduledActions({query:{include_events:$?.includeEvents}})).map((O)=>v$.from(this.client,O))}}class gx{client;constructor($){this.client=$}byId($){return G$.byId(this.client,$)}create($){return G$.create(this.client,$)}summaries($){return G$.summaries(this.client,$)}findSimilar($){return G$.findSimilar(this.client,$)}forPullRequest($){return G$.forPullRequest(this.client,$)}search($,O){return G$.search(this.client,$,O)}}class yx{client;constructor($){this.client=$}byId($){return _$.byId(this.client,$)}current(){return _$.current(this.client)}list(){return _$.list(this.client)}}class vx{client;constructor($){this.client=$}async get($){return Q(await this.client.unfurl.getUnfurl({query:{url:$}}))}async bulk($){return Q(await this.client.unfurl.getUnfurlBulk({body:{url_list:$}}))}}class hx{client;constructor($){this.client=$}byId($){return C.byId(this.client,$)}me(){return C.me(this.client)}async search($){let O=$.trim().toLocaleLowerCase();if(!O)throw Error("A person search needs a name or email.");let j=await this.client.contacts.getContacts();if(j.response?.status===404)return[];let{contacts:x}=Q(j),S=[...new Set(x)],K=[];for(let Z=0;Z<S.length;Z+=100){let X=S.slice(Z,Z+100),{names:Y}=Q(await this.client.auth.getUserNamesWithEmail({body:{user_ids:X}})),L=new Map(Y.map((G)=>[G.id,G]));for(let G of X){let J=L.get(G)??{id:G};if(`${[J.first_name,J.last_name].filter(Boolean).join(" ")} ${G}`.toLocaleLowerCase().includes(O))K.push(C.fromName(this.client,J))}}return K}}class QO extends P{signingSecret;constructor($,O,j,x){super($,O,j);this.signingSecret=x}async fetch(){return Q(await this.client.storage.getWebhook({path:{webhook_id:this.id}}))}static async create($,O){let j=Q(await $.storage.createWebhook({body:{endpoint_url:O.url,namespace:O.namespace,name:O.name,filters:O.filters,scope:O.scope??"user",...O.headers!==void 0?{headers:O.headers}:{}}}));return new QO($,j.id,j,j.signing_secret)}static byId($,O){return new QO($,O)}static fromRecord($,O){return new QO($,O.id,O)}name=this.field("name");namespace=this.field("namespace");endpointUrl=this.field("endpoint_url");status=this.field("status");isValid=this.field("is_valid");filters=this.field("filters");createdAt=this.field("created_at");workspaceId=this.field("workspace_id");createdBy=this.mappedField("created_by_user_id",($)=>C.byId(this.client,$));async scope(){let $=await this.detail.get();return $.workspace_id===$.created_by_user_id?"user":"team"}async update($){await this.mutate((O)=>O.storage.patchWebhook({path:{webhook_id:this.id},body:$}))}async rename($){await this.update({name:$})}async setUrl($){await this.update({endpoint_url:$})}async setFilters($){await this.update({filters:$})}async pause(){await this.update({status:"paused"})}async resume(){await this.update({status:"active"})}async delete(){await this.mutate(($)=>$.storage.deleteWebhook({path:{webhook_id:this.id}}))}async validate(){return this.mutate(($)=>$.storage.validateWebhook({path:{webhook_id:this.id}}))}}class mx{client;constructor($){this.client=$}create($){return QO.create(this.client,$)}byId($){return QO.byId(this.client,$)}async list(){let{webhooks:$}=Q(await this.client.storage.listWebhooks());return $.map((O)=>QO.fromRecord(this.client,O))}}class CO extends P{static byId($,O){return new CO($,O)}static from($,O){return new CO($,O.id,O)}async fetch(){let{account:$}=Q(await this.client.storage.whatsappAccount());if($?.id!==this.id)throw new E("WhatsApp account is not available");return $}state=this.field("state");identity=this.field("identityJid");owner=this.mappedField("userId",($)=>C.byId(this.client,$));async refresh(){return this.detail.clear(),await this.detail.get(),this}}class ux{client;constructor($){this.client=$}async account(){let{account:$}=Q(await this.client.storage.whatsappAccount());return $?CO.from(this.client,$):void 0}async chats(){return Q(await this.client.storage.whatsappChats()).chats.map(($)=>NO.from(this.client,$))}}function cx($){if("properties"in $.data)return $.data.properties;if($.tag==="calendarEvent")return $.data.extra.properties;return[]}function K2($,O,j){let x=[];for(let S of cx(O)){if(S.definition.data_type!=="TAG"||S.value?.type!=="SelectOption")continue;for(let K of S.value.value){let Z=j.get(K);if(Z&&!x.some((X)=>X.label===Z.label&&X.scope===Z.scope))x.push(Z)}}switch(O.tag){case"document":return{type:"document",id:O.data.id,entity:w.byId($,O.data.id),snapshot:O,tags:x,name:O.data.name,fileType:O.data.fileType,subType:O.data.subType?.type};case"chat":return{type:"ai_chat",id:O.data.id,entity:Y$.byId($,O.data.id),snapshot:O,tags:x,name:O.data.name};case"project":return{type:"project",id:O.data.id,entity:n.byId($,O.data.id),snapshot:O,tags:x,name:O.data.name};case"emailThread":return{type:"email",id:O.data.id,entity:z$.byId($,O.data.id),snapshot:O,tags:x,subject:O.data.name,snippet:O.data.snippet,senderName:O.data.senderName,senderEmail:O.data.senderEmail,inboxVisible:O.data.inboxVisible,isRead:O.data.isRead,isDraft:O.data.isDraft};case"channel":return{type:"channel",id:O.data.channel.id,entity:b.byId($,O.data.channel.id),snapshot:O,tags:x,name:O.data.channel.name};case"channelThread":return{type:"channel_thread",id:O.data.id,entity:new h$($,O.data.channel_id,O.data.id),snapshot:O,tags:x,channelId:O.data.channel_id};case"call":return{type:"call",id:O.data.callId,entity:J$.byId($,O.data.callId),snapshot:O,tags:x,createdBy:O.data.createdBy};case"calendarEvent":return{type:"calendar_event",id:O.data.id,entity:S$.byId($,O.data.id),snapshot:O,tags:x,title:O.data.title,status:O.data.status,location:O.data.location,conferenceUrl:O.data.conferenceUrl,conferenceProvider:O.data.conferenceProvider,time:O.data.time};case"foreignEntity":return{type:"foreign_entity",id:O.data.id,entity:KO.byId($,O.data.id),snapshot:O,tags:x,foreignEntityId:O.data.foreignEntityId,foreignEntitySource:O.data.foreignEntitySource,metadata:O.data.metadata};default:throw Error(`Unexpected workspace entity type: ${O.tag}`)}}var Y2="00000000-0000-0000-0000-000000000000",dx={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()),Q2=($,O)=>$==null?O:{"&":[$,O]};function lx($,O){if(!$||typeof $!=="object"||Array.isArray($))throw Error(`Invalid workspace ${O}: expected a filter expression.`);let j=Object.entries($),x=j[0];if(j.length!==1||x===void 0)throw Error(`Invalid workspace ${O}: use exactly one of l, &, |, !.`);let[S,K]=x;if(S==="l")return;if(S==="!"){lx(K,`${O}.!`);return}if(S!=="&"&&S!=="|")throw Error(`Invalid workspace ${O}: use l, &, | or !.`);if(!Array.isArray(K)||K.length!==2)throw Error(`Invalid workspace ${O}.${S}: expected exactly two expressions. Use {l: {...}} for a single condition; nest binary operators for three or more.`);K.forEach((Z,X)=>{lx(Z,`${O}.${S}[${X}]`)})}class bj{client;tagSets;constructor($){this.client=$}sets(){return this.tagSets??=this.client.properties.listTags({}).then(Q),this.tagSets}async tagMap(){let $=new Map;for(let O of await this.sets())for(let j of O.options)if(j.value.type==="string")$.set(j.id,{label:j.value.value,scope:O.scope==="user"?"personal":"team"});return $}async body($){for(let[S,K,Z]of[["sortBy",$.sortBy,["recently_viewed","recently_updated","recently_created"]],["emailPreset",$.emailPreset,["signal"]],["tagsMatch",$.tagsMatch,["any","all"]]])if(K!==void 0&&!Z.includes(K))throw Error(`Invalid workspace ${S}: ${K}`);if($.includeTypes!==void 0&&(!Array.isArray($.includeTypes)||$.includeTypes.some((S)=>!Object.hasOwn(dx,S))))throw Error(`Invalid workspace includeTypes. Supported values: ${Object.keys(dx).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)lx($[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:Y2}},favorites_only:$.favoritesOnly,expand:!0,limit:Math.max(1,Math.min(500,Math.trunc($.limit??50))),sort_method:$.sortBy==="recently_viewed"?"viewed_at":$.sortBy==="recently_created"?"created_at":"updated_at",sort_direction:"desc",emailView:$.emailView??"inbox"};if($.emailPreset==="signal")O.ef={"&":[{l:{Importance:!0}},{l:{Shared:"exclude"}}]};let j=$.inbox?.trim();if(j){let{links:S}=Q(await this.client.email.listLinks()),K=S.filter((X)=>fj(X.email_address)===fj(j)),Z=K[0];if(!Z)throw Error(`No connected inbox matches "${j}". Connected inboxes: ${S.map((X)=>X.email_address).join(", ")}.`);if(K.length>1)throw Error(`Multiple connected inboxes match "${j}"; cannot pick one.`);O.ef=Q2(O.ef,{l:{Owner:Z.id}})}let x=$.includeTypes??($.emailPreset==="signal"?["email"]:void 0);if(x?.length){for(let[S,[K,Z]]of Object.entries(dx))if(!x.includes(S))O[K]={l:{[Z]:Y2}}}if($.tags?.length){let S=(await this.sets()).flatMap((Y)=>{let L=Y.definition;if(!L)return[];return Y.options.flatMap((G)=>G.value.type==="string"?[{id:G.id,definitionId:L.id,label:G.value.value,scope:Y.scope==="user"?"personal":"team"}]:[])}),K=new Map;for(let Y of $.tags){let L=S.filter((G)=>fj(G.label)===fj(Y.label.trim())&&(!Y.scope||G.scope===Y.scope));if(!L.length)throw Error(`Unknown tag "${Y.label}". Available tags: ${S.map((G)=>`${G.label} (${G.scope})`).join(", ")}.`);if($.tagsMatch==="all"&&L.length>1)throw Error(`Tag "${Y.label}" is ambiguous; specify personal or team scope.`);for(let G of L)K.set(G.id,G)}let X=[...K.values()].map((Y)=>({l:{pd:Y.definitionId,v:{so:Y.id}}})).reduce((Y,L)=>Y===void 0?L:{[$.tagsMatch==="all"?"&":"|"]:[Y,L]},void 0);O.propf=Q2(O.propf,X)}return O}}class rx{client;constructor($){this.client=$}async page($={}){let O=new bj(this.client);return this.fetch(O,await O.body($),$.cursor)}async*list($={}){let O=new bj(this.client),j=await O.body($);yield*c((x)=>this.fetch(O,j,x))}async fetch($,O,j){let x=Q(await this.client.storage.postItemsSoupAst({body:O,query:j?{cursor:j}:void 0})),K=x.items.some((Z)=>cx(Z).some((X)=>X.definition.data_type==="TAG"))?await $.tagMap():new Map;return{items:x.items.map((Z)=>K2(this.client,Z,K)),nextCursor:x.next_cursor,hasMore:x.next_cursor!=null}}}function G2({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...G}){let J,I=Y??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,H=G.signal??new AbortController().signal;while(!0){if(H.aborted)break;B++;let A=G.headers instanceof Headers?G.headers:new Headers(G.headers);if(J!==void 0)A.set("Last-Event-ID",J);try{let D={redirect:"follow",...G,body:G.serializedBody,headers:A,signal:H},_=new Request(L,D);if($)_=await $(L,D);let N=await(G.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let T=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{T.cancel()}catch{}};H.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await T.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
`);let y=U.split(`
`);U=y.pop()??"";for(let a of y){let i=a.split(`
`),F=[],v;for(let R of i)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))v=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let m=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(m))V=m}let M,h=!1;if(F.length){let R=F.join(`
-`);try{M=JSON.parse(R),h=!0}catch{M=R}}if(h){if(S)await S(M);if(x)M=await x(M)}if(j?.({data:M,event:v,id:J,retry:V}),F.length)yield M}}}finally{H.removeEventListener("abort",g),T.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var 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"&"}},kj=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((Y)=>encodeURIComponent(Y))).join(y5(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=g5(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return PO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},PO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},gj=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let Y=[];Object.entries(S).forEach(([G,J])=>{Y=[...Y,G,$?J:encodeURIComponent(J)]});let L=Y.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=v5(x),X=Object.entries(S).map(([Y,L])=>PO({allowReserved:$,name:x==="deepObject"?`${j}[${Y}]`:Y,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var h5=/\{[^{}]+\}/g,m5=({path:$,url:O})=>{let j=O,x=O.match(h5);if(x)for(let S of x){let K=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))K=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let Y=$[Z];if(Y===void 0||Y===null)continue;if(Array.isArray(Y)){j=j.replace(S,kj({explode:K,name:Z,style:X,value:Y}));continue}if(typeof Y==="object"){j=j.replace(S,gj({explode:K,name:Z,style:X,value:Y,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${PO({name:Z,value:Y})}`);continue}let L=encodeURIComponent(X==="label"?`.${Y}`:Y);j=j.replace(S,L)}return j},G2=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=m5({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function rx($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var J2=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var V2={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var W2=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let Y=kj({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(Y)S.push(Y)}else if(typeof Z==="object"){let Y=gj({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(Y)S.push(Y)}else{let Y=PO({allowReserved:X.allowReserved,name:K,value:Z});if(Y)S.push(Y)}}return S.join("&")}},B2=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},u5=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function L2($){for(let O of $.security??[]){if(u5($,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 px=($)=>G2({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:W2($.querySerializer),url:$.url}),ax=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=vj($.headers,O.headers),j},c5=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},vj=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?c5(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class yj{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var N2=()=>({error:new yj,request:new yj,response:new yj}),d5=W2({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),l5={"Content-Type":"application/json"},Oj=($={})=>({...V2,headers:l5,parseAs:"auto",querySerializer:d5,...$});var ix=($={})=>{let O=ax(Oj(),$),j=()=>({...O}),x=(G)=>{return O=ax(O,G),j()},S=N2(),K=async(G)=>{let J={...O,...G,fetch:G.fetch??O.fetch??globalThis.fetch,headers:vj(O.headers,G.headers),serializedBody:void 0};if(J.security)await L2(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let I=J,z=px(I);return{opts:I,url:z}},Z=async(G)=>{let J=G.throwOnError??O.throwOnError,I=G.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(G),H={redirect:"follow",...V,body:rx(V)};z=new Request(B,H);for(let N of S.request.fns)if(N)z=await N(z,V);let A=V.fetch;W=await A(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?B2(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let T;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":T=await W[N]();break;case"json":{let U=await W.text();T=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(T);if(V.responseTransformer)T=await V.responseTransformer(T)}return V.responseStyle==="data"?T:{data:T,...D}}let _=await W.text(),q;try{q=JSON.parse(_)}catch{}throw q??_}catch(V){let B=V;for(let H of S.error.fns)if(H)B=await H(B,W,z,G);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(G)=>(J)=>Z({...J,method:G}),Y=(G)=>async(J)=>{let{opts:I,url:z}=await K(J);return Q2({...I,body:I.body,method:G,onRequest:async(W,V)=>{let B=new Request(W,V);for(let H of S.request.fns)if(H)B=await H(B,I);return B},serializedBody:rx(I),url:z})};return{buildUrl:(G)=>px({...O,...G}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:Y("CONNECT"),delete:Y("DELETE"),get:Y("GET"),head:Y("HEAD"),options:Y("OPTIONS"),patch:Y("PATCH"),post:Y("POST"),put:Y("PUT"),trace:Y("TRACE")},trace:X("TRACE")}};var U2=ix(Oj());class z2{client;constructor($){this.client=$?.client??U2}}class I2{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class hj extends z2{static __registry=new I2;constructor($){super($);hj.__registry.set(this,$?.key)}getAgentAutoArchivePreferences($){return($?.client??this.client).get({url:"/agent-auto-archive-preferences",...$})}putAgentAutoArchivePreferences($){return($.client??this.client).put({url:"/agent-auto-archive-preferences",...$,headers:{"Content-Type":"application/json",...$.headers}})}discoverAgentCapabilitiesHandler($){return($.client??this.client).post({security:[{scheme:"bearer",type:"http"}],url:"/agent-capabilities/discover",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAgentCodingPreferences($){return($?.client??this.client).get({url:"/agent-coding-preferences",...$})}putAgentCodingPreferences($){return($.client??this.client).put({url:"/agent-coding-preferences",...$,headers:{"Content-Type":"application/json",...$.headers}})}listAgentConversations($){return($.client??this.client).get({security:[{scheme:"bearer",type:"http"}],url:"/agent-conversations/{channel_id}",...$})}startFreshAgentConversation($){return($.client??this.client).post({security:[{scheme:"bearer",type:"http"}],url:"/agent-conversations/{channel_id}/{bot_id}/start-fresh",...$,headers:{"Content-Type":"application/json",...$.headers}})}retryAgentConversationTurn($){return($.client??this.client).post({security:[{scheme:"bearer",type:"http"}],url:"/agent-conversations/{channel_id}/{bot_id}/turns/{source}/retry",...$,headers:{"Content-Type":"application/json",...$.headers}})}chooseAgentMode($){return($.client??this.client).post({security:[{scheme:"bearer",type:"http"}],url:"/agent-mode-choice",...$,headers:{"Content-Type":"application/json",...$.headers}})}loadAgentModelsHandler($){return($.client??this.client).post({security:[{scheme:"bearer",type:"http"}],url:"/agent-models/load",...$,headers:{"Content-Type":"application/json",...$.headers}})}listAgentRepositories($){return($?.client??this.client).get({security:[{scheme:"bearer",type:"http"}],url:"/agent-repositories",...$})}listAgentRepositoryBranches($){return($.client??this.client).get({security:[{scheme:"bearer",type:"http"}],url:"/agent-repositories/branches",...$})}getAgentSandboxSize($){return($?.client??this.client).get({url:"/agent-sandbox-size",...$})}putAgentSandboxSize($){return($.client??this.client).put({url:"/agent-sandbox-size",...$,headers:{"Content-Type":"application/json",...$.headers}})}createAgentSession($){return($.client??this.client).post({url:"/agent-sessions",...$,headers:{"Content-Type":"application/json",...$.headers}})}agentSessionsForPullRequest($){return($.client??this.client).post({url:"/agent-sessions/by-pull-request",...$,headers:{"Content-Type":"application/json",...$.headers}})}agentSessionsForPullRequests($){return($.client??this.client).post({url:"/agent-sessions/by-pull-requests",...$,headers:{"Content-Type":"application/json",...$.headers}})}previewAgentSessions($){return($.client??this.client).post({url:"/agent-sessions/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}warmAgentSessionHandler($){return($.client??this.client).post({url:"/agent-sessions/warm",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteAgentSession($){return($.client??this.client).delete({url:"/agent-sessions/{session_id}",...$})}getAgentSession($){return($.client??this.client).get({url:"/agent-sessions/{session_id}",...$})}reportAgentSessionAppConnected($){return($.client??this.client).post({url:"/agent-sessions/{session_id}/app-connections",...$,headers:{"Content-Type":"application/json",...$.headers}})}setAgentSessionArchived($){return($.client??this.client).put({url:"/agent-sessions/{session_id}/archived",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAgentSessionAutoArchive($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/auto-archive",...$})}putAgentSessionAutoArchive($){return($.client??this.client).put({url:"/agent-sessions/{session_id}/auto-archive",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAgentSessionChanges($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/changes",...$})}getAgentSessionChangesPatch($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/changes/patch",...$})}refreshAgentSessionChanges($){return($.client??this.client).post({url:"/agent-sessions/{session_id}/changes/refresh",...$})}getCodeExecution($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/code-executions/{execution_id}",...$})}listExecutionReviews($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/code-executions/{execution_id}/reviews",...$})}controlAgentSession($){return($.client??this.client).post({url:"/agent-sessions/{session_id}/control",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAgentSessionLog($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/log",...$})}getAgentSessionFoldedLog($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/log/folded",...$})}renameAgentSession($){return($.client??this.client).put({url:"/agent-sessions/{session_id}/name",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAgentSessionPermissions($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/permissions",...$})}updateAgentSessionPermissions($){return($.client??this.client).patch({url:"/agent-sessions/{session_id}/permissions",...$,headers:{"Content-Type":"application/json",...$.headers}})}unlinkAgentSessionPullRequest($){return($.client??this.client).delete({url:"/agent-sessions/{session_id}/pull-requests",...$})}listAgentSessionPullRequests($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/pull-requests",...$})}linkAgentSessionPullRequest($){return($.client??this.client).put({url:"/agent-sessions/{session_id}/pull-requests",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAgentSessionQueue($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/queue",...$})}removeQueuedAction($){return($.client??this.client).delete({url:"/agent-sessions/{session_id}/queue/{action_id}",...$})}editQueuedAction($){return($.client??this.client).put({url:"/agent-sessions/{session_id}/queue/{action_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}steerQueuedAction($){return($.client??this.client).post({url:"/agent-sessions/{session_id}/queue/{action_id}/steer",...$})}createSessionReview($){return($.client??this.client).post({url:"/agent-sessions/{session_id}/reviews",...$,headers:{"Content-Type":"application/json",...$.headers}})}getSessionReview($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/reviews/{review_id}",...$})}decideSessionReview($){return($.client??this.client).post({url:"/agent-sessions/{session_id}/reviews/{review_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}putAgentSessionSandboxSize($){return($.client??this.client).put({url:"/agent-sessions/{session_id}/sandbox-size",...$,headers:{"Content-Type":"application/json",...$.headers}})}answerAgentSessionToolApproval($){return($.client??this.client).post({url:"/agent-sessions/{session_id}/tool-approvals/{approval_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}presentSessionView($){return($.client??this.client).post({url:"/agent-sessions/{session_id}/views",...$,headers:{"Content-Type":"application/json",...$.headers}})}classify($){return($.client??this.client).post({url:"/universal_input/classify",...$,headers:{"Content-Type":"application/json",...$.headers}})}extract($){return($.client??this.client).post({url:"/universal_input/extract",...$,headers:{"Content-Type":"application/json",...$.headers}})}}function H2({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...G}){let J,I=Y??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,H=G.signal??new AbortController().signal;while(!0){if(H.aborted)break;B++;let A=G.headers instanceof Headers?G.headers:new Headers(G.headers);if(J!==void 0)A.set("Last-Event-ID",J);try{let D={redirect:"follow",...G,body:G.serializedBody,headers:A,signal:H},_=new Request(L,D);if($)_=await $(L,D);let N=await(G.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let T=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{T.cancel()}catch{}};H.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await T.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
+`);try{M=JSON.parse(R),h=!0}catch{M=R}}if(h){if(S)await S(M);if(x)M=await x(M)}if(j?.({data:M,event:v,id:J,retry:V}),F.length)yield M}}}finally{H.removeEventListener("abort",g),T.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var y5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},v5=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},h5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},kj=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((Y)=>encodeURIComponent(Y))).join(v5(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=y5(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return PO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},PO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},gj=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let Y=[];Object.entries(S).forEach(([G,J])=>{Y=[...Y,G,$?J:encodeURIComponent(J)]});let L=Y.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=h5(x),X=Object.entries(S).map(([Y,L])=>PO({allowReserved:$,name:x==="deepObject"?`${j}[${Y}]`:Y,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var m5=/\{[^{}]+\}/g,u5=({path:$,url:O})=>{let j=O,x=O.match(m5);if(x)for(let S of x){let K=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))K=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let Y=$[Z];if(Y===void 0||Y===null)continue;if(Array.isArray(Y)){j=j.replace(S,kj({explode:K,name:Z,style:X,value:Y}));continue}if(typeof Y==="object"){j=j.replace(S,gj({explode:K,name:Z,style:X,value:Y,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${PO({name:Z,value:Y})}`);continue}let L=encodeURIComponent(X==="label"?`.${Y}`:Y);j=j.replace(S,L)}return j},J2=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=u5({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function px($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var V2=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var W2={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var B2=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let Y=kj({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(Y)S.push(Y)}else if(typeof Z==="object"){let Y=gj({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(Y)S.push(Y)}else{let Y=PO({allowReserved:X.allowReserved,name:K,value:Z});if(Y)S.push(Y)}}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},c5=($,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(c5($,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 ax=($)=>J2({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:B2($.querySerializer),url:$.url}),ix=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=vj($.headers,O.headers),j},d5=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},vj=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?d5(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class yj{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var U2=()=>({error:new yj,request:new yj,response:new yj}),l5=B2({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),r5={"Content-Type":"application/json"},Oj=($={})=>({...W2,headers:r5,parseAs:"auto",querySerializer:l5,...$});var nx=($={})=>{let O=ix(Oj(),$),j=()=>({...O}),x=(G)=>{return O=ix(O,G),j()},S=U2(),K=async(G)=>{let J={...O,...G,fetch:G.fetch??O.fetch??globalThis.fetch,headers:vj(O.headers,G.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=ax(I);return{opts:I,url:z}},Z=async(G)=>{let J=G.throwOnError??O.throwOnError,I=G.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(G),H={redirect:"follow",...V,body:px(V)};z=new Request(B,H);for(let N of S.request.fns)if(N)z=await N(z,V);let A=V.fetch;W=await A(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?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 T;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":T=await W[N]();break;case"json":{let U=await W.text();T=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(T);if(V.responseTransformer)T=await V.responseTransformer(T)}return V.responseStyle==="data"?T:{data:T,...D}}let _=await W.text(),q;try{q=JSON.parse(_)}catch{}throw q??_}catch(V){let B=V;for(let H of S.error.fns)if(H)B=await H(B,W,z,G);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(G)=>(J)=>Z({...J,method:G}),Y=(G)=>async(J)=>{let{opts:I,url:z}=await K(J);return G2({...I,body:I.body,method:G,onRequest:async(W,V)=>{let B=new Request(W,V);for(let H of S.request.fns)if(H)B=await H(B,I);return B},serializedBody:px(I),url:z})};return{buildUrl:(G)=>ax({...O,...G}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:Y("CONNECT"),delete:Y("DELETE"),get:Y("GET"),head:Y("HEAD"),options:Y("OPTIONS"),patch:Y("PATCH"),post:Y("POST"),put:Y("PUT"),trace:Y("TRACE")},trace:X("TRACE")}};var z2=nx(Oj());class I2{client;constructor($){this.client=$?.client??z2}}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 hj extends I2{static __registry=new H2;constructor($){super($);hj.__registry.set(this,$?.key)}getAgentAutoArchivePreferences($){return($?.client??this.client).get({url:"/agent-auto-archive-preferences",...$})}putAgentAutoArchivePreferences($){return($.client??this.client).put({url:"/agent-auto-archive-preferences",...$,headers:{"Content-Type":"application/json",...$.headers}})}discoverAgentCapabilitiesHandler($){return($.client??this.client).post({security:[{scheme:"bearer",type:"http"}],url:"/agent-capabilities/discover",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAgentCodingPreferences($){return($?.client??this.client).get({url:"/agent-coding-preferences",...$})}putAgentCodingPreferences($){return($.client??this.client).put({url:"/agent-coding-preferences",...$,headers:{"Content-Type":"application/json",...$.headers}})}listAgentConversations($){return($.client??this.client).get({security:[{scheme:"bearer",type:"http"}],url:"/agent-conversations/{channel_id}",...$})}startFreshAgentConversation($){return($.client??this.client).post({security:[{scheme:"bearer",type:"http"}],url:"/agent-conversations/{channel_id}/{bot_id}/start-fresh",...$,headers:{"Content-Type":"application/json",...$.headers}})}retryAgentConversationTurn($){return($.client??this.client).post({security:[{scheme:"bearer",type:"http"}],url:"/agent-conversations/{channel_id}/{bot_id}/turns/{source}/retry",...$,headers:{"Content-Type":"application/json",...$.headers}})}chooseAgentMode($){return($.client??this.client).post({security:[{scheme:"bearer",type:"http"}],url:"/agent-mode-choice",...$,headers:{"Content-Type":"application/json",...$.headers}})}loadAgentModelsHandler($){return($.client??this.client).post({security:[{scheme:"bearer",type:"http"}],url:"/agent-models/load",...$,headers:{"Content-Type":"application/json",...$.headers}})}listAgentRepositories($){return($?.client??this.client).get({security:[{scheme:"bearer",type:"http"}],url:"/agent-repositories",...$})}listAgentRepositoryBranches($){return($.client??this.client).get({security:[{scheme:"bearer",type:"http"}],url:"/agent-repositories/branches",...$})}getAgentSandboxSize($){return($?.client??this.client).get({url:"/agent-sandbox-size",...$})}putAgentSandboxSize($){return($.client??this.client).put({url:"/agent-sandbox-size",...$,headers:{"Content-Type":"application/json",...$.headers}})}createAgentSession($){return($.client??this.client).post({url:"/agent-sessions",...$,headers:{"Content-Type":"application/json",...$.headers}})}agentSessionsForPullRequest($){return($.client??this.client).post({url:"/agent-sessions/by-pull-request",...$,headers:{"Content-Type":"application/json",...$.headers}})}agentSessionsForPullRequests($){return($.client??this.client).post({url:"/agent-sessions/by-pull-requests",...$,headers:{"Content-Type":"application/json",...$.headers}})}previewAgentSessions($){return($.client??this.client).post({url:"/agent-sessions/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}warmAgentSessionHandler($){return($.client??this.client).post({url:"/agent-sessions/warm",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteAgentSession($){return($.client??this.client).delete({url:"/agent-sessions/{session_id}",...$})}getAgentSession($){return($.client??this.client).get({url:"/agent-sessions/{session_id}",...$})}reportAgentSessionAppConnected($){return($.client??this.client).post({url:"/agent-sessions/{session_id}/app-connections",...$,headers:{"Content-Type":"application/json",...$.headers}})}setAgentSessionArchived($){return($.client??this.client).put({url:"/agent-sessions/{session_id}/archived",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAgentSessionAutoArchive($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/auto-archive",...$})}putAgentSessionAutoArchive($){return($.client??this.client).put({url:"/agent-sessions/{session_id}/auto-archive",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAgentSessionChanges($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/changes",...$})}getAgentSessionChangesPatch($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/changes/patch",...$})}refreshAgentSessionChanges($){return($.client??this.client).post({url:"/agent-sessions/{session_id}/changes/refresh",...$})}getCodeExecution($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/code-executions/{execution_id}",...$})}listExecutionReviews($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/code-executions/{execution_id}/reviews",...$})}controlAgentSession($){return($.client??this.client).post({url:"/agent-sessions/{session_id}/control",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAgentSessionLog($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/log",...$})}getAgentSessionFoldedLog($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/log/folded",...$})}renameAgentSession($){return($.client??this.client).put({url:"/agent-sessions/{session_id}/name",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAgentSessionPermissions($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/permissions",...$})}updateAgentSessionPermissions($){return($.client??this.client).patch({url:"/agent-sessions/{session_id}/permissions",...$,headers:{"Content-Type":"application/json",...$.headers}})}unlinkAgentSessionPullRequest($){return($.client??this.client).delete({url:"/agent-sessions/{session_id}/pull-requests",...$})}listAgentSessionPullRequests($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/pull-requests",...$})}linkAgentSessionPullRequest($){return($.client??this.client).put({url:"/agent-sessions/{session_id}/pull-requests",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAgentSessionQueue($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/queue",...$})}removeQueuedAction($){return($.client??this.client).delete({url:"/agent-sessions/{session_id}/queue/{action_id}",...$})}editQueuedAction($){return($.client??this.client).put({url:"/agent-sessions/{session_id}/queue/{action_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}steerQueuedAction($){return($.client??this.client).post({url:"/agent-sessions/{session_id}/queue/{action_id}/steer",...$})}createSessionReview($){return($.client??this.client).post({url:"/agent-sessions/{session_id}/reviews",...$,headers:{"Content-Type":"application/json",...$.headers}})}getSessionReview($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/reviews/{review_id}",...$})}decideSessionReview($){return($.client??this.client).post({url:"/agent-sessions/{session_id}/reviews/{review_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}putAgentSessionSandboxSize($){return($.client??this.client).put({url:"/agent-sessions/{session_id}/sandbox-size",...$,headers:{"Content-Type":"application/json",...$.headers}})}answerAgentSessionToolApproval($){return($.client??this.client).post({url:"/agent-sessions/{session_id}/tool-approvals/{approval_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}presentSessionView($){return($.client??this.client).post({url:"/agent-sessions/{session_id}/views",...$,headers:{"Content-Type":"application/json",...$.headers}})}classify($){return($.client??this.client).post({url:"/universal_input/classify",...$,headers:{"Content-Type":"application/json",...$.headers}})}extract($){return($.client??this.client).post({url:"/universal_input/extract",...$,headers:{"Content-Type":"application/json",...$.headers}})}}function T2({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...G}){let J,I=Y??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,H=G.signal??new AbortController().signal;while(!0){if(H.aborted)break;B++;let A=G.headers instanceof Headers?G.headers:new Headers(G.headers);if(J!==void 0)A.set("Last-Event-ID",J);try{let D={redirect:"follow",...G,body:G.serializedBody,headers:A,signal:H},_=new Request(L,D);if($)_=await $(L,D);let N=await(G.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let T=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{T.cancel()}catch{}};H.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await T.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
`);let y=U.split(`
`);U=y.pop()??"";for(let a of y){let i=a.split(`
`),F=[],v;for(let R of i)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))v=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let m=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(m))V=m}let M,h=!1;if(F.length){let R=F.join(`
-`);try{M=JSON.parse(R),h=!0}catch{M=R}}if(h){if(S)await S(M);if(x)M=await x(M)}if(j?.({data:M,event:v,id:J,retry:V}),F.length)yield M}}}finally{H.removeEventListener("abort",g),T.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var 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"&"}},mj=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((Y)=>encodeURIComponent(Y))).join(p5(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=r5(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return AO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},AO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},uj=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let Y=[];Object.entries(S).forEach(([G,J])=>{Y=[...Y,G,$?J:encodeURIComponent(J)]});let L=Y.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=a5(x),X=Object.entries(S).map(([Y,L])=>AO({allowReserved:$,name:x==="deepObject"?`${j}[${Y}]`:Y,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var i5=/\{[^{}]+\}/g,n5=({path:$,url:O})=>{let j=O,x=O.match(i5);if(x)for(let S of x){let K=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))K=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let Y=$[Z];if(Y===void 0||Y===null)continue;if(Array.isArray(Y)){j=j.replace(S,mj({explode:K,name:Z,style:X,value:Y}));continue}if(typeof Y==="object"){j=j.replace(S,uj({explode:K,name:Z,style:X,value:Y,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${AO({name:Z,value:Y})}`);continue}let L=encodeURIComponent(X==="label"?`.${Y}`:Y);j=j.replace(S,L)}return j},T2=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;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 nx($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var R2=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var D2={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var _2=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let Y=mj({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(Y)S.push(Y)}else if(typeof Z==="object"){let Y=uj({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(Y)S.push(Y)}else{let Y=AO({allowReserved:X.allowReserved,name:K,value:Z});if(Y)S.push(Y)}}return S.join("&")}},M2=($)=>{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 C2($){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 sx=($)=>T2({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:_2($.querySerializer),url:$.url}),tx=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=dj($.headers,O.headers),j},t5=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},dj=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?t5(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class cj{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var P2=()=>({error:new cj,request:new cj,response:new cj}),e5=_2({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),o5={"Content-Type":"application/json"},jj=($={})=>({...D2,headers:o5,parseAs:"auto",querySerializer:e5,...$});var ex=($={})=>{let O=tx(jj(),$),j=()=>({...O}),x=(G)=>{return O=tx(O,G),j()},S=P2(),K=async(G)=>{let J={...O,...G,fetch:G.fetch??O.fetch??globalThis.fetch,headers:dj(O.headers,G.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=sx(I);return{opts:I,url:z}},Z=async(G)=>{let J=G.throwOnError??O.throwOnError,I=G.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(G),H={redirect:"follow",...V,body:nx(V)};z=new Request(B,H);for(let N of S.request.fns)if(N)z=await N(z,V);let A=V.fetch;W=await A(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?M2(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let T;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":T=await W[N]();break;case"json":{let U=await W.text();T=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(T);if(V.responseTransformer)T=await V.responseTransformer(T)}return V.responseStyle==="data"?T:{data:T,...D}}let _=await W.text(),q;try{q=JSON.parse(_)}catch{}throw q??_}catch(V){let B=V;for(let H of S.error.fns)if(H)B=await H(B,W,z,G);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(G)=>(J)=>Z({...J,method:G}),Y=(G)=>async(J)=>{let{opts:I,url:z}=await K(J);return H2({...I,body:I.body,method:G,onRequest:async(W,V)=>{let B=new Request(W,V);for(let H of S.request.fns)if(H)B=await H(B,I);return B},serializedBody:nx(I),url:z})};return{buildUrl:(G)=>sx({...O,...G}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:Y("CONNECT"),delete:Y("DELETE"),get:Y("GET"),head:Y("HEAD"),options:Y("OPTIONS"),patch:Y("PATCH"),post:Y("POST"),put:Y("PUT"),trace:Y("TRACE")},trace:X("TRACE")}};var A2=ex(jj());class F2{client;constructor($){this.client=$?.client??A2}}class E2{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class lj extends F2{static __registry=new E2;constructor($){super($);lj.__registry.set(this,$?.key)}deleteAgentApiKey($){return($.client??this.client).delete({url:"/agents/{agent_id}/api-key",...$})}getAgentApiKey($){return($.client??this.client).get({url:"/agents/{agent_id}/api-key",...$})}putAgentApiKey($){return($.client??this.client).put({url:"/agents/{agent_id}/api-key",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateAiBillingAutoReload($){return($.client??this.client).patch({url:"/ai-billing/auto-reload",...$,headers:{"Content-Type":"application/json",...$.headers}})}createAiCreditCheckout($){return($.client??this.client).post({url:"/ai-billing/credits/checkout",...$,headers:{"Content-Type":"application/json",...$.headers}})}purchaseAiCredits($){return($.client??this.client).post({url:"/ai-billing/credits/purchase",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateAiBillingOverage($){return($.client??this.client).patch({url:"/ai-billing/overage",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAiBillingPlans($){return($?.client??this.client).get({url:"/ai-billing/plans",...$})}getAiBillingSummary($){return($?.client??this.client).get({url:"/ai-billing/summary",...$})}disconnectCodex($){return($?.client??this.client).delete({url:"/codex",...$})}getCodexConnection($){return($?.client??this.client).get({url:"/codex",...$})}configureCodex($){return($.client??this.client).put({url:"/codex/config",...$,headers:{"Content-Type":"application/json",...$.headers}})}listCodexEnvironments($){return($?.client??this.client).get({url:"/codex/environments",...$})}startCodexLogin($){return($?.client??this.client).post({url:"/codex/login",...$})}cancelCodexLogin($){return($.client??this.client).delete({url:"/codex/login/{attempt_id}",...$})}pollCodexLogin($){return($.client??this.client).get({url:"/codex/login/{attempt_id}",...$})}deleteCursorApiKey($){return($?.client??this.client).delete({url:"/cursor-api-key",...$})}getCursorApiKey($){return($?.client??this.client).get({url:"/cursor-api-key",...$})}putCursorApiKey($){return($.client??this.client).put({url:"/cursor-api-key",...$,headers:{"Content-Type":"application/json",...$.headers}})}putCursorDefaultModel($){return($.client??this.client).put({url:"/cursor-api-key/default-model",...$,headers:{"Content-Type":"application/json",...$.headers}})}listCursorModels($){return($?.client??this.client).get({url:"/cursor-api-key/models",...$})}verifyFusionauthUserEmail($){return($.client??this.client).get({url:"/email/fusionauth/verify/{verification_id}",...$})}resendFusionauthVerifyUserEmail($){return($.client??this.client).post({url:"/email/fusionauth_resend",...$,headers:{"Content-Type":"application/json",...$.headers}})}generateEmailLink($){return($.client??this.client).post({url:"/email/generate/link",...$,headers:{"Content-Type":"application/json",...$.headers}})}verifyEmailLink($){return($.client??this.client).get({url:"/email/verify/{verification_id}",...$})}setGithubPullRequestDraft($){return($.client??this.client).post({url:"/github_pull_requests/draft",...$,headers:{"Content-Type":"application/json",...$.headers}})}enrichGithubPullRequests($){return($.client??this.client).post({url:"/github_pull_requests/enrich",...$,headers:{"Content-Type":"application/json",...$.headers}})}mergeGithubPullRequest($){return($.client??this.client).post({url:"/github_pull_requests/merge",...$,headers:{"Content-Type":"application/json",...$.headers}})}getGithubPullRequestMergeability($){return($.client??this.client).post({url:"/github_pull_requests/mergeability",...$,headers:{"Content-Type":"application/json",...$.headers}})}setGithubPullRequestState($){return($.client??this.client).post({url:"/github_pull_requests/state",...$,headers:{"Content-Type":"application/json",...$.headers}})}listGtmInviteLinks($){return($?.client??this.client).get({url:"/gtm-invite/links",...$})}createGtmInviteLink($){return($.client??this.client).post({url:"/gtm-invite/links",...$,headers:{"Content-Type":"application/json",...$.headers}})}revokeGtmInviteLink($){return($.client??this.client).delete({url:"/gtm-invite/links/{id}",...$})}getGtmInviteOffer($){return($?.client??this.client).get({url:"/gtm-invite/offer",...$})}resolveGtmInviteLink($){return($.client??this.client).get({url:"/gtm-invite/public/{token}",...$})}redeemGtmInviteLink($){return($.client??this.client).post({url:"/gtm-invite/redeem",...$,headers:{"Content-Type":"application/json",...$.headers}})}healthHandler($){return($?.client??this.client).get({url:"/health",...$})}macroApiToken($){return($.client??this.client).get({url:"/jwt/macro_api_token",...$})}refresh($){return($?.client??this.client).post({url:"/jwt/refresh",...$})}createInProgressLink($){return($?.client??this.client).post({url:"/link",...$})}emailConnectionProviders($){return($?.client??this.client).get({url:"/link/email/providers",...$})}deleteGithubLink($){return($?.client??this.client).delete({url:"/link/github",...$})}initGithubLink($){return($.client??this.client).post({url:"/link/github",...$})}checkGithubLinkStatus($){return($?.client??this.client).get({url:"/link/github/status",...$})}initGmailLink($){return($.client??this.client).post({url:"/link/gmail",...$})}checkGmailLinkStatus($){return($?.client??this.client).get({url:"/link/gmail/status",...$})}initOutlookLink($){return($?.client??this.client).post({url:"/link/outlook",...$})}appleLogin($){return($.client??this.client).post({url:"/login/apple",...$,headers:{"Content-Type":"application/json",...$.headers}})}passwordLogin($){return($.client??this.client).post({url:"/login/password",...$,headers:{"Content-Type":"application/json",...$.headers}})}passwordlessLogin($){return($.client??this.client).post({url:"/login/passwordless",...$,headers:{"Content-Type":"application/json",...$.headers}})}ssoLogin($){return($.client??this.client).get({url:"/login/sso",...$})}logout($){return($?.client??this.client).post({url:"/logout",...$})}createMergeRequest($){return($.client??this.client).post({url:"/merge",...$,headers:{"Content-Type":"application/json",...$.headers}})}verifyMergeRequest($){return($.client??this.client).get({url:"/merge/verify/{code}",...$})}sendMobileWelcomeEmail($){return($.client??this.client).post({url:"/mobile-welcome-email",...$,headers:{"Content-Type":"application/json",...$.headers}})}passwordlessCallback($){return($.client??this.client).get({url:"/oauth/passwordless/{code}",...$})}oauthRedirect($){return($?.client??this.client).get({url:"/oauth/redirect",...$})}oauth2Callback($){return($.client??this.client).get({url:"/oauth2/{provider}/callback",...$})}getPermissions($){return($?.client??this.client).get({url:"/permissions",...$})}getUserPermissions($){return($?.client??this.client).get({url:"/permissions/me",...$})}getReferralCode($){return($?.client??this.client).get({url:"/referral/code",...$})}sendReferralCode($){return($.client??this.client).post({url:"/referral/send",...$,headers:{"Content-Type":"application/json",...$.headers}})}sessionCreation($){return($?.client??this.client).post({url:"/session",...$})}sessionLogin($){return($.client??this.client).get({url:"/session/login/{session_code}",...$})}getSystemStatus($){return($?.client??this.client).get({url:"/system-status",...$})}setSystemStatus($){return($.client??this.client).post({url:"/system-status",...$,headers:{"Content-Type":"application/json",...$.headers}})}listSystemStatusHistory($){return($?.client??this.client).get({url:"/system-status/history",...$})}deleteTeam($){return($?.client??this.client).delete({url:"/team",...$})}getTeam($){return($?.client??this.client).get({url:"/team",...$})}patchTeam($){return($.client??this.client).patch({url:"/team",...$,headers:{"Content-Type":"application/json",...$.headers}})}createTeam($){return($.client??this.client).post({url:"/team",...$,headers:{"Content-Type":"application/json",...$.headers}})}toggleTeamAutoJoinDomain($){return($?.client??this.client).post({url:"/team/auto-join-domain/toggle",...$})}patchTeamCrmSettings($){return($.client??this.client).patch({url:"/team/crm",...$,headers:{"Content-Type":"application/json",...$.headers}})}sendTeamDomainNotice($){return($?.client??this.client).post({url:"/team/domain-notice",...$})}inviteToTeam($){return($.client??this.client).post({url:"/team/invite",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteTeamInviteLink($){return($?.client??this.client).delete({url:"/team/invite-link",...$})}getTeamInviteLink($){return($?.client??this.client).get({url:"/team/invite-link",...$})}createTeamInviteLink($){return($?.client??this.client).post({url:"/team/invite-link",...$})}joinTeamByInviteLink($){return($.client??this.client).post({url:"/team/invite-link/join",...$,headers:{"Content-Type":"application/json",...$.headers}})}getTeamByInviteLink($){return($.client??this.client).post({url:"/team/invite-link/team",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteTeamInviteHandler($){return($.client??this.client).delete({url:"/team/invite/{team_invite_id}",...$})}getTeamInvites($){return($?.client??this.client).get({url:"/team/invites",...$})}rejectInvitation($){return($.client??this.client).delete({url:"/team/join/{team_invite_id}",...$})}joinTeam($){return($.client??this.client).get({url:"/team/join/{team_invite_id}",...$})}patchTeamMemberPlan($){return($.client??this.client).patch({url:"/team/members/{member_user_id}/plan",...$,headers:{"Content-Type":"application/json",...$.headers}})}toggleTeamNonAdminInvites($){return($?.client??this.client).post({url:"/team/non-admin-invites/toggle",...$})}removeUserFromTeam($){return($.client??this.client).delete({url:"/team/remove/{remove_user_id}",...$})}getUserTeams($){return($?.client??this.client).get({url:"/team/user",...$})}getUserInvites($){return($?.client??this.client).get({url:"/team/user/invites",...$})}getUserNames($){return($.client??this.client).post({url:"/user/get_names",...$,headers:{"Content-Type":"application/json",...$.headers}})}getUserNamesWithEmail($){return($.client??this.client).post({url:"/user/get_names_with_email",...$,headers:{"Content-Type":"application/json",...$.headers}})}patchUserGroup($){return($.client??this.client).patch({url:"/user/group",...$,headers:{"Content-Type":"application/json",...$.headers}})}getUserLanguage($){return($?.client??this.client).get({url:"/user/language",...$})}putUserLanguage($){return($.client??this.client).put({url:"/user/language",...$,headers:{"Content-Type":"application/json",...$.headers}})}getLegacyUserPermissions($){return($?.client??this.client).get({url:"/user/legacy_user_permissions",...$})}getUserLinkExists($){return($.client??this.client).get({url:"/user/link_exists",...$})}deleteUser($){return($?.client??this.client).delete({url:"/user/me",...$})}getUserInfo($){return($?.client??this.client).get({url:"/user/me",...$})}getUserName($){return($?.client??this.client).get({url:"/user/name",...$})}putUserName($){return($?.client??this.client).put({url:"/user/name",...$})}patchUserOnboarding($){return($.client??this.client).patch({url:"/user/onboarding",...$,headers:{"Content-Type":"application/json",...$.headers}})}getUserOrganization($){return($?.client??this.client).get({url:"/user/organization",...$})}putProfilePicture($){return($.client??this.client).put({url:"/user/profile_picture",...$})}postProfilePictures($){return($.client??this.client).post({url:"/user/profile_pictures",...$,headers:{"Content-Type":"application/json",...$.headers}})}getUserQuota($){return($?.client??this.client).get({url:"/user/quota",...$})}createCheckoutSessionV2($){return($.client??this.client).post({url:"/user/stripe/checkoutv2",...$,headers:{"Content-Type":"application/json",...$.headers}})}getSubscriptionStatus($){return($?.client??this.client).get({url:"/user/stripe/plan",...$})}changePlan($){return($.client??this.client).post({url:"/user/stripe/plan",...$,headers:{"Content-Type":"application/json",...$.headers}})}createPortalSession($){return($.client??this.client).post({url:"/user/stripe/portal",...$,headers:{"Content-Type":"application/json",...$.headers}})}getTrialEligibility($){return($?.client??this.client).get({url:"/user/stripe/trial_eligibility",...$})}patchUserTutorial($){return($.client??this.client).patch({url:"/user/tutorial",...$,headers:{"Content-Type":"application/json",...$.headers}})}}function q2({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...G}){let J,I=Y??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,H=G.signal??new AbortController().signal;while(!0){if(H.aborted)break;B++;let A=G.headers instanceof Headers?G.headers:new Headers(G.headers);if(J!==void 0)A.set("Last-Event-ID",J);try{let D={redirect:"follow",...G,body:G.serializedBody,headers:A,signal:H},_=new Request(L,D);if($)_=await $(L,D);let N=await(G.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let T=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{T.cancel()}catch{}};H.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await T.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
+`);try{M=JSON.parse(R),h=!0}catch{M=R}}if(h){if(S)await S(M);if(x)M=await x(M)}if(j?.({data:M,event:v,id:J,retry:V}),F.length)yield M}}}finally{H.removeEventListener("abort",g),T.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var p5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},a5=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},i5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},mj=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((Y)=>encodeURIComponent(Y))).join(a5(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=p5(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return AO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},AO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},uj=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let Y=[];Object.entries(S).forEach(([G,J])=>{Y=[...Y,G,$?J:encodeURIComponent(J)]});let L=Y.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=i5(x),X=Object.entries(S).map(([Y,L])=>AO({allowReserved:$,name:x==="deepObject"?`${j}[${Y}]`:Y,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var n5=/\{[^{}]+\}/g,s5=({path:$,url:O})=>{let j=O,x=O.match(n5);if(x)for(let S of x){let K=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))K=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let Y=$[Z];if(Y===void 0||Y===null)continue;if(Array.isArray(Y)){j=j.replace(S,mj({explode:K,name:Z,style:X,value:Y}));continue}if(typeof Y==="object"){j=j.replace(S,uj({explode:K,name:Z,style:X,value:Y,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${AO({name:Z,value:Y})}`);continue}let L=encodeURIComponent(X==="label"?`.${Y}`:Y);j=j.replace(S,L)}return j},R2=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=s5({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function sx($){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 K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let Y=mj({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(Y)S.push(Y)}else if(typeof Z==="object"){let Y=uj({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(Y)S.push(Y)}else{let Y=AO({allowReserved:X.allowReserved,name:K,value:Z});if(Y)S.push(Y)}}return S.join("&")}},C2=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},t5=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function P2($){for(let O of $.security??[]){if(t5($,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 tx=($)=>R2({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:M2($.querySerializer),url:$.url}),ex=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=dj($.headers,O.headers),j},e5=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},dj=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?e5(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class cj{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var A2=()=>({error:new cj,request:new cj,response:new cj}),o5=M2({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),$S={"Content-Type":"application/json"},jj=($={})=>({..._2,headers:$S,parseAs:"auto",querySerializer:o5,...$});var ox=($={})=>{let O=ex(jj(),$),j=()=>({...O}),x=(G)=>{return O=ex(O,G),j()},S=A2(),K=async(G)=>{let J={...O,...G,fetch:G.fetch??O.fetch??globalThis.fetch,headers:dj(O.headers,G.headers),serializedBody:void 0};if(J.security)await P2(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let I=J,z=tx(I);return{opts:I,url:z}},Z=async(G)=>{let J=G.throwOnError??O.throwOnError,I=G.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(G),H={redirect:"follow",...V,body:sx(V)};z=new Request(B,H);for(let N of S.request.fns)if(N)z=await N(z,V);let A=V.fetch;W=await A(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?C2(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let T;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":T=await W[N]();break;case"json":{let U=await W.text();T=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(T);if(V.responseTransformer)T=await V.responseTransformer(T)}return V.responseStyle==="data"?T:{data:T,...D}}let _=await W.text(),q;try{q=JSON.parse(_)}catch{}throw q??_}catch(V){let B=V;for(let H of S.error.fns)if(H)B=await H(B,W,z,G);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(G)=>(J)=>Z({...J,method:G}),Y=(G)=>async(J)=>{let{opts:I,url:z}=await K(J);return T2({...I,body:I.body,method:G,onRequest:async(W,V)=>{let B=new Request(W,V);for(let H of S.request.fns)if(H)B=await H(B,I);return B},serializedBody:sx(I),url:z})};return{buildUrl:(G)=>tx({...O,...G}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:Y("CONNECT"),delete:Y("DELETE"),get:Y("GET"),head:Y("HEAD"),options:Y("OPTIONS"),patch:Y("PATCH"),post:Y("POST"),put:Y("PUT"),trace:Y("TRACE")},trace:X("TRACE")}};var F2=ox(jj());class E2{client;constructor($){this.client=$?.client??F2}}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 lj extends E2{static __registry=new q2;constructor($){super($);lj.__registry.set(this,$?.key)}deleteAgentApiKey($){return($.client??this.client).delete({url:"/agents/{agent_id}/api-key",...$})}getAgentApiKey($){return($.client??this.client).get({url:"/agents/{agent_id}/api-key",...$})}putAgentApiKey($){return($.client??this.client).put({url:"/agents/{agent_id}/api-key",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateAiBillingAutoReload($){return($.client??this.client).patch({url:"/ai-billing/auto-reload",...$,headers:{"Content-Type":"application/json",...$.headers}})}createAiCreditCheckout($){return($.client??this.client).post({url:"/ai-billing/credits/checkout",...$,headers:{"Content-Type":"application/json",...$.headers}})}purchaseAiCredits($){return($.client??this.client).post({url:"/ai-billing/credits/purchase",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateAiBillingOverage($){return($.client??this.client).patch({url:"/ai-billing/overage",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAiBillingPlans($){return($?.client??this.client).get({url:"/ai-billing/plans",...$})}getAiBillingSummary($){return($?.client??this.client).get({url:"/ai-billing/summary",...$})}disconnectCodex($){return($?.client??this.client).delete({url:"/codex",...$})}getCodexConnection($){return($?.client??this.client).get({url:"/codex",...$})}configureCodex($){return($.client??this.client).put({url:"/codex/config",...$,headers:{"Content-Type":"application/json",...$.headers}})}listCodexEnvironments($){return($?.client??this.client).get({url:"/codex/environments",...$})}startCodexLogin($){return($?.client??this.client).post({url:"/codex/login",...$})}cancelCodexLogin($){return($.client??this.client).delete({url:"/codex/login/{attempt_id}",...$})}pollCodexLogin($){return($.client??this.client).get({url:"/codex/login/{attempt_id}",...$})}deleteCursorApiKey($){return($?.client??this.client).delete({url:"/cursor-api-key",...$})}getCursorApiKey($){return($?.client??this.client).get({url:"/cursor-api-key",...$})}putCursorApiKey($){return($.client??this.client).put({url:"/cursor-api-key",...$,headers:{"Content-Type":"application/json",...$.headers}})}putCursorDefaultModel($){return($.client??this.client).put({url:"/cursor-api-key/default-model",...$,headers:{"Content-Type":"application/json",...$.headers}})}listCursorModels($){return($?.client??this.client).get({url:"/cursor-api-key/models",...$})}verifyFusionauthUserEmail($){return($.client??this.client).get({url:"/email/fusionauth/verify/{verification_id}",...$})}resendFusionauthVerifyUserEmail($){return($.client??this.client).post({url:"/email/fusionauth_resend",...$,headers:{"Content-Type":"application/json",...$.headers}})}generateEmailLink($){return($.client??this.client).post({url:"/email/generate/link",...$,headers:{"Content-Type":"application/json",...$.headers}})}verifyEmailLink($){return($.client??this.client).get({url:"/email/verify/{verification_id}",...$})}setGithubPullRequestDraft($){return($.client??this.client).post({url:"/github_pull_requests/draft",...$,headers:{"Content-Type":"application/json",...$.headers}})}enrichGithubPullRequests($){return($.client??this.client).post({url:"/github_pull_requests/enrich",...$,headers:{"Content-Type":"application/json",...$.headers}})}mergeGithubPullRequest($){return($.client??this.client).post({url:"/github_pull_requests/merge",...$,headers:{"Content-Type":"application/json",...$.headers}})}getGithubPullRequestMergeability($){return($.client??this.client).post({url:"/github_pull_requests/mergeability",...$,headers:{"Content-Type":"application/json",...$.headers}})}setGithubPullRequestState($){return($.client??this.client).post({url:"/github_pull_requests/state",...$,headers:{"Content-Type":"application/json",...$.headers}})}listGtmInviteLinks($){return($?.client??this.client).get({url:"/gtm-invite/links",...$})}createGtmInviteLink($){return($.client??this.client).post({url:"/gtm-invite/links",...$,headers:{"Content-Type":"application/json",...$.headers}})}revokeGtmInviteLink($){return($.client??this.client).delete({url:"/gtm-invite/links/{id}",...$})}getGtmInviteOffer($){return($?.client??this.client).get({url:"/gtm-invite/offer",...$})}resolveGtmInviteLink($){return($.client??this.client).get({url:"/gtm-invite/public/{token}",...$})}redeemGtmInviteLink($){return($.client??this.client).post({url:"/gtm-invite/redeem",...$,headers:{"Content-Type":"application/json",...$.headers}})}healthHandler($){return($?.client??this.client).get({url:"/health",...$})}macroApiToken($){return($.client??this.client).get({url:"/jwt/macro_api_token",...$})}refresh($){return($?.client??this.client).post({url:"/jwt/refresh",...$})}createInProgressLink($){return($?.client??this.client).post({url:"/link",...$})}emailConnectionProviders($){return($?.client??this.client).get({url:"/link/email/providers",...$})}deleteGithubLink($){return($?.client??this.client).delete({url:"/link/github",...$})}initGithubLink($){return($.client??this.client).post({url:"/link/github",...$})}checkGithubLinkStatus($){return($?.client??this.client).get({url:"/link/github/status",...$})}initGmailLink($){return($.client??this.client).post({url:"/link/gmail",...$})}checkGmailLinkStatus($){return($?.client??this.client).get({url:"/link/gmail/status",...$})}initOutlookLink($){return($?.client??this.client).post({url:"/link/outlook",...$})}appleLogin($){return($.client??this.client).post({url:"/login/apple",...$,headers:{"Content-Type":"application/json",...$.headers}})}passwordLogin($){return($.client??this.client).post({url:"/login/password",...$,headers:{"Content-Type":"application/json",...$.headers}})}passwordlessLogin($){return($.client??this.client).post({url:"/login/passwordless",...$,headers:{"Content-Type":"application/json",...$.headers}})}ssoLogin($){return($.client??this.client).get({url:"/login/sso",...$})}logout($){return($?.client??this.client).post({url:"/logout",...$})}createMergeRequest($){return($.client??this.client).post({url:"/merge",...$,headers:{"Content-Type":"application/json",...$.headers}})}verifyMergeRequest($){return($.client??this.client).get({url:"/merge/verify/{code}",...$})}sendMobileWelcomeEmail($){return($.client??this.client).post({url:"/mobile-welcome-email",...$,headers:{"Content-Type":"application/json",...$.headers}})}passwordlessCallback($){return($.client??this.client).get({url:"/oauth/passwordless/{code}",...$})}oauthRedirect($){return($?.client??this.client).get({url:"/oauth/redirect",...$})}oauth2Callback($){return($.client??this.client).get({url:"/oauth2/{provider}/callback",...$})}getPermissions($){return($?.client??this.client).get({url:"/permissions",...$})}getUserPermissions($){return($?.client??this.client).get({url:"/permissions/me",...$})}getReferralCode($){return($?.client??this.client).get({url:"/referral/code",...$})}sendReferralCode($){return($.client??this.client).post({url:"/referral/send",...$,headers:{"Content-Type":"application/json",...$.headers}})}sessionCreation($){return($?.client??this.client).post({url:"/session",...$})}sessionLogin($){return($.client??this.client).get({url:"/session/login/{session_code}",...$})}getSystemStatus($){return($?.client??this.client).get({url:"/system-status",...$})}setSystemStatus($){return($.client??this.client).post({url:"/system-status",...$,headers:{"Content-Type":"application/json",...$.headers}})}listSystemStatusHistory($){return($?.client??this.client).get({url:"/system-status/history",...$})}deleteTeam($){return($?.client??this.client).delete({url:"/team",...$})}getTeam($){return($?.client??this.client).get({url:"/team",...$})}patchTeam($){return($.client??this.client).patch({url:"/team",...$,headers:{"Content-Type":"application/json",...$.headers}})}createTeam($){return($.client??this.client).post({url:"/team",...$,headers:{"Content-Type":"application/json",...$.headers}})}toggleTeamAutoJoinDomain($){return($?.client??this.client).post({url:"/team/auto-join-domain/toggle",...$})}patchTeamCrmSettings($){return($.client??this.client).patch({url:"/team/crm",...$,headers:{"Content-Type":"application/json",...$.headers}})}sendTeamDomainNotice($){return($?.client??this.client).post({url:"/team/domain-notice",...$})}inviteToTeam($){return($.client??this.client).post({url:"/team/invite",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteTeamInviteLink($){return($?.client??this.client).delete({url:"/team/invite-link",...$})}getTeamInviteLink($){return($?.client??this.client).get({url:"/team/invite-link",...$})}createTeamInviteLink($){return($?.client??this.client).post({url:"/team/invite-link",...$})}joinTeamByInviteLink($){return($.client??this.client).post({url:"/team/invite-link/join",...$,headers:{"Content-Type":"application/json",...$.headers}})}getTeamByInviteLink($){return($.client??this.client).post({url:"/team/invite-link/team",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteTeamInviteHandler($){return($.client??this.client).delete({url:"/team/invite/{team_invite_id}",...$})}getTeamInvites($){return($?.client??this.client).get({url:"/team/invites",...$})}rejectInvitation($){return($.client??this.client).delete({url:"/team/join/{team_invite_id}",...$})}joinTeam($){return($.client??this.client).get({url:"/team/join/{team_invite_id}",...$})}patchTeamMemberPlan($){return($.client??this.client).patch({url:"/team/members/{member_user_id}/plan",...$,headers:{"Content-Type":"application/json",...$.headers}})}toggleTeamNonAdminInvites($){return($?.client??this.client).post({url:"/team/non-admin-invites/toggle",...$})}removeUserFromTeam($){return($.client??this.client).delete({url:"/team/remove/{remove_user_id}",...$})}getUserTeams($){return($?.client??this.client).get({url:"/team/user",...$})}getUserInvites($){return($?.client??this.client).get({url:"/team/user/invites",...$})}getUserNames($){return($.client??this.client).post({url:"/user/get_names",...$,headers:{"Content-Type":"application/json",...$.headers}})}getUserNamesWithEmail($){return($.client??this.client).post({url:"/user/get_names_with_email",...$,headers:{"Content-Type":"application/json",...$.headers}})}patchUserGroup($){return($.client??this.client).patch({url:"/user/group",...$,headers:{"Content-Type":"application/json",...$.headers}})}getUserLanguage($){return($?.client??this.client).get({url:"/user/language",...$})}putUserLanguage($){return($.client??this.client).put({url:"/user/language",...$,headers:{"Content-Type":"application/json",...$.headers}})}getLegacyUserPermissions($){return($?.client??this.client).get({url:"/user/legacy_user_permissions",...$})}getUserLinkExists($){return($.client??this.client).get({url:"/user/link_exists",...$})}deleteUser($){return($?.client??this.client).delete({url:"/user/me",...$})}getUserInfo($){return($?.client??this.client).get({url:"/user/me",...$})}getUserName($){return($?.client??this.client).get({url:"/user/name",...$})}putUserName($){return($?.client??this.client).put({url:"/user/name",...$})}patchUserOnboarding($){return($.client??this.client).patch({url:"/user/onboarding",...$,headers:{"Content-Type":"application/json",...$.headers}})}getUserOrganization($){return($?.client??this.client).get({url:"/user/organization",...$})}putProfilePicture($){return($.client??this.client).put({url:"/user/profile_picture",...$})}postProfilePictures($){return($.client??this.client).post({url:"/user/profile_pictures",...$,headers:{"Content-Type":"application/json",...$.headers}})}getUserQuota($){return($?.client??this.client).get({url:"/user/quota",...$})}createCheckoutSessionV2($){return($.client??this.client).post({url:"/user/stripe/checkoutv2",...$,headers:{"Content-Type":"application/json",...$.headers}})}getSubscriptionStatus($){return($?.client??this.client).get({url:"/user/stripe/plan",...$})}changePlan($){return($.client??this.client).post({url:"/user/stripe/plan",...$,headers:{"Content-Type":"application/json",...$.headers}})}createPortalSession($){return($.client??this.client).post({url:"/user/stripe/portal",...$,headers:{"Content-Type":"application/json",...$.headers}})}getTrialEligibility($){return($?.client??this.client).get({url:"/user/stripe/trial_eligibility",...$})}patchUserTutorial($){return($.client??this.client).patch({url:"/user/tutorial",...$,headers:{"Content-Type":"application/json",...$.headers}})}}function w2({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...G}){let J,I=Y??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,H=G.signal??new AbortController().signal;while(!0){if(H.aborted)break;B++;let A=G.headers instanceof Headers?G.headers:new Headers(G.headers);if(J!==void 0)A.set("Last-Event-ID",J);try{let D={redirect:"follow",...G,body:G.serializedBody,headers:A,signal:H},_=new Request(L,D);if($)_=await $(L,D);let N=await(G.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let T=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{T.cancel()}catch{}};H.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await T.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
`);let y=U.split(`
`);U=y.pop()??"";for(let a of y){let i=a.split(`
`),F=[],v;for(let R of i)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))v=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let m=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(m))V=m}let M,h=!1;if(F.length){let R=F.join(`
-`);try{M=JSON.parse(R),h=!0}catch{M=R}}if(h){if(S)await S(M);if(x)M=await x(M)}if(j?.({data:M,event:v,id:J,retry:V}),F.length)yield M}}}finally{H.removeEventListener("abort",g),T.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var $S=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},OS=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},jS=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},rj=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((Y)=>encodeURIComponent(Y))).join(OS(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=$S(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return FO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},FO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},pj=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let Y=[];Object.entries(S).forEach(([G,J])=>{Y=[...Y,G,$?J:encodeURIComponent(J)]});let L=Y.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=jS(x),X=Object.entries(S).map(([Y,L])=>FO({allowReserved:$,name:x==="deepObject"?`${j}[${Y}]`:Y,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var xS=/\{[^{}]+\}/g,SS=({path:$,url:O})=>{let j=O,x=O.match(xS);if(x)for(let S of x){let K=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))K=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let Y=$[Z];if(Y===void 0||Y===null)continue;if(Array.isArray(Y)){j=j.replace(S,rj({explode:K,name:Z,style:X,value:Y}));continue}if(typeof Y==="object"){j=j.replace(S,pj({explode:K,name:Z,style:X,value:Y,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${FO({name:Z,value:Y})}`);continue}let L=encodeURIComponent(X==="label"?`.${Y}`:Y);j=j.replace(S,L)}return j},w2=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=SS({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function ox($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var f2=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var b2={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var k2=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let Y=rj({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(Y)S.push(Y)}else if(typeof Z==="object"){let Y=pj({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(Y)S.push(Y)}else{let Y=FO({allowReserved:X.allowReserved,name:K,value:Z});if(Y)S.push(Y)}}return S.join("&")}},g2=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},ZS=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function y2($){for(let O of $.security??[]){if(ZS($,O.name))continue;let j=await f2(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var $1=($)=>w2({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:k2($.querySerializer),url:$.url}),O1=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=ij($.headers,O.headers),j},XS=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},ij=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?XS(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class aj{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var v2=()=>({error:new aj,request:new aj,response:new aj}),KS=k2({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),YS={"Content-Type":"application/json"},xj=($={})=>({...b2,headers:YS,parseAs:"auto",querySerializer:KS,...$});var j1=($={})=>{let O=O1(xj(),$),j=()=>({...O}),x=(G)=>{return O=O1(O,G),j()},S=v2(),K=async(G)=>{let J={...O,...G,fetch:G.fetch??O.fetch??globalThis.fetch,headers:ij(O.headers,G.headers),serializedBody:void 0};if(J.security)await y2(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let I=J,z=$1(I);return{opts:I,url:z}},Z=async(G)=>{let J=G.throwOnError??O.throwOnError,I=G.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(G),H={redirect:"follow",...V,body:ox(V)};z=new Request(B,H);for(let N of S.request.fns)if(N)z=await N(z,V);let A=V.fetch;W=await A(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?g2(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let T;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":T=await W[N]();break;case"json":{let U=await W.text();T=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(T);if(V.responseTransformer)T=await V.responseTransformer(T)}return V.responseStyle==="data"?T:{data:T,...D}}let _=await W.text(),q;try{q=JSON.parse(_)}catch{}throw q??_}catch(V){let B=V;for(let H of S.error.fns)if(H)B=await H(B,W,z,G);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(G)=>(J)=>Z({...J,method:G}),Y=(G)=>async(J)=>{let{opts:I,url:z}=await K(J);return q2({...I,body:I.body,method:G,onRequest:async(W,V)=>{let B=new Request(W,V);for(let H of S.request.fns)if(H)B=await H(B,I);return B},serializedBody:ox(I),url:z})};return{buildUrl:(G)=>$1({...O,...G}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:Y("CONNECT"),delete:Y("DELETE"),get:Y("GET"),head:Y("HEAD"),options:Y("OPTIONS"),patch:Y("PATCH"),post:Y("POST"),put:Y("PUT"),trace:Y("TRACE")},trace:X("TRACE")}};var h2=j1(xj());class m2{client;constructor($){this.client=$?.client??h2}}class u2{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class nj extends m2{static __registry=new u2;constructor($){super($);nj.__registry.set(this,$?.key)}getAvailabilityCalendars($){return($?.client??this.client).get({url:"/availability-calendars",...$})}setAvailabilityCalendar($){return($.client??this.client).put({url:"/availability-calendars/{calendar_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}listCalendars($){return($?.client??this.client).get({url:"/calendars",...$})}createCalendarEvent($){return($.client??this.client).post({url:"/events",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteCalendarEvent($){return($.client??this.client).delete({url:"/events/{event_id}",...$})}updateCalendarEvent($){return($.client??this.client).patch({url:"/events/{event_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}copyCalendarEvent($){return($.client??this.client).post({url:"/events/{event_id}/copy",...$,headers:{"Content-Type":"application/json",...$.headers}})}inviteCalendarEventGuests($){return($.client??this.client).post({url:"/events/{event_id}/guests",...$,headers:{"Content-Type":"application/json",...$.headers}})}calendarEventProviderUrl($){return($.client??this.client).get({url:"/events/{event_id}/provider-url",...$})}prepareCalendarReplacement($){return($.client??this.client).post({url:"/events/{event_id}/replacement",...$,headers:{"Content-Type":"application/json",...$.headers}})}rsvpCalendarEvent($){return($.client??this.client).put({url:"/events/{event_id}/rsvp",...$,headers:{"Content-Type":"application/json",...$.headers}})}healthHandler($){return($?.client??this.client).get({url:"/health",...$})}respondToJoinRequest($){return($.client??this.client).put({url:"/join-requests/{request_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}discardCalendarReplacement($){return($.client??this.client).delete({url:"/replacements/{operation_id}",...$})}calendarReplacementStatus($){return($.client??this.client).get({url:"/replacements/{operation_id}",...$})}confirmCalendarReplacement($){return($.client??this.client).post({url:"/replacements/{operation_id}/confirm",...$})}getTeamSharing($){return($?.client??this.client).get({url:"/team-sharing",...$})}setTeamSharing($){return($.client??this.client).put({url:"/team-sharing",...$,headers:{"Content-Type":"application/json",...$.headers}})}}function c2({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...G}){let J,I=Y??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,H=G.signal??new AbortController().signal;while(!0){if(H.aborted)break;B++;let A=G.headers instanceof Headers?G.headers:new Headers(G.headers);if(J!==void 0)A.set("Last-Event-ID",J);try{let D={redirect:"follow",...G,body:G.serializedBody,headers:A,signal:H},_=new Request(L,D);if($)_=await $(L,D);let N=await(G.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let T=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{T.cancel()}catch{}};H.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await T.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
+`);try{M=JSON.parse(R),h=!0}catch{M=R}}if(h){if(S)await S(M);if(x)M=await x(M)}if(j?.({data:M,event:v,id:J,retry:V}),F.length)yield M}}}finally{H.removeEventListener("abort",g),T.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var OS=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},jS=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},xS=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},rj=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((Y)=>encodeURIComponent(Y))).join(jS(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=OS(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return FO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},FO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},pj=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let Y=[];Object.entries(S).forEach(([G,J])=>{Y=[...Y,G,$?J:encodeURIComponent(J)]});let L=Y.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=xS(x),X=Object.entries(S).map(([Y,L])=>FO({allowReserved:$,name:x==="deepObject"?`${j}[${Y}]`:Y,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var SS=/\{[^{}]+\}/g,ZS=({path:$,url:O})=>{let j=O,x=O.match(SS);if(x)for(let S of x){let K=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))K=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let Y=$[Z];if(Y===void 0||Y===null)continue;if(Array.isArray(Y)){j=j.replace(S,rj({explode:K,name:Z,style:X,value:Y}));continue}if(typeof Y==="object"){j=j.replace(S,pj({explode:K,name:Z,style:X,value:Y,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${FO({name:Z,value:Y})}`);continue}let L=encodeURIComponent(X==="label"?`.${Y}`:Y);j=j.replace(S,L)}return j},f2=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=ZS({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function $1($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var 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 K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let Y=rj({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(Y)S.push(Y)}else if(typeof Z==="object"){let Y=pj({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(Y)S.push(Y)}else{let Y=FO({allowReserved:X.allowReserved,name:K,value:Z});if(Y)S.push(Y)}}return S.join("&")}},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},XS=($,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(XS($,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 O1=($)=>f2({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:g2($.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=ij($.headers,O.headers),j},KS=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},ij=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?KS(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class aj{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var h2=()=>({error:new aj,request:new aj,response:new aj}),YS=g2({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),QS={"Content-Type":"application/json"},xj=($={})=>({...k2,headers:QS,parseAs:"auto",querySerializer:YS,...$});var x1=($={})=>{let O=j1(xj(),$),j=()=>({...O}),x=(G)=>{return O=j1(O,G),j()},S=h2(),K=async(G)=>{let J={...O,...G,fetch:G.fetch??O.fetch??globalThis.fetch,headers:ij(O.headers,G.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=O1(I);return{opts:I,url:z}},Z=async(G)=>{let J=G.throwOnError??O.throwOnError,I=G.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(G),H={redirect:"follow",...V,body:$1(V)};z=new Request(B,H);for(let N of S.request.fns)if(N)z=await N(z,V);let A=V.fetch;W=await A(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?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 T;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":T=await W[N]();break;case"json":{let U=await W.text();T=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(T);if(V.responseTransformer)T=await V.responseTransformer(T)}return V.responseStyle==="data"?T:{data:T,...D}}let _=await W.text(),q;try{q=JSON.parse(_)}catch{}throw q??_}catch(V){let B=V;for(let H of S.error.fns)if(H)B=await H(B,W,z,G);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(G)=>(J)=>Z({...J,method:G}),Y=(G)=>async(J)=>{let{opts:I,url:z}=await K(J);return w2({...I,body:I.body,method:G,onRequest:async(W,V)=>{let B=new Request(W,V);for(let H of S.request.fns)if(H)B=await H(B,I);return B},serializedBody:$1(I),url:z})};return{buildUrl:(G)=>O1({...O,...G}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:Y("CONNECT"),delete:Y("DELETE"),get:Y("GET"),head:Y("HEAD"),options:Y("OPTIONS"),patch:Y("PATCH"),post:Y("POST"),put:Y("PUT"),trace:Y("TRACE")},trace:X("TRACE")}};var m2=x1(xj());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 nj extends u2{static __registry=new c2;constructor($){super($);nj.__registry.set(this,$?.key)}getAvailabilityCalendars($){return($?.client??this.client).get({url:"/availability-calendars",...$})}setAvailabilityCalendar($){return($.client??this.client).put({url:"/availability-calendars/{calendar_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}listCalendars($){return($?.client??this.client).get({url:"/calendars",...$})}createCalendarEvent($){return($.client??this.client).post({url:"/events",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteCalendarEvent($){return($.client??this.client).delete({url:"/events/{event_id}",...$})}updateCalendarEvent($){return($.client??this.client).patch({url:"/events/{event_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}copyCalendarEvent($){return($.client??this.client).post({url:"/events/{event_id}/copy",...$,headers:{"Content-Type":"application/json",...$.headers}})}inviteCalendarEventGuests($){return($.client??this.client).post({url:"/events/{event_id}/guests",...$,headers:{"Content-Type":"application/json",...$.headers}})}calendarEventProviderUrl($){return($.client??this.client).get({url:"/events/{event_id}/provider-url",...$})}prepareCalendarReplacement($){return($.client??this.client).post({url:"/events/{event_id}/replacement",...$,headers:{"Content-Type":"application/json",...$.headers}})}rsvpCalendarEvent($){return($.client??this.client).put({url:"/events/{event_id}/rsvp",...$,headers:{"Content-Type":"application/json",...$.headers}})}healthHandler($){return($?.client??this.client).get({url:"/health",...$})}respondToJoinRequest($){return($.client??this.client).put({url:"/join-requests/{request_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}discardCalendarReplacement($){return($.client??this.client).delete({url:"/replacements/{operation_id}",...$})}calendarReplacementStatus($){return($.client??this.client).get({url:"/replacements/{operation_id}",...$})}confirmCalendarReplacement($){return($.client??this.client).post({url:"/replacements/{operation_id}/confirm",...$})}getTeamSharing($){return($?.client??this.client).get({url:"/team-sharing",...$})}setTeamSharing($){return($.client??this.client).put({url:"/team-sharing",...$,headers:{"Content-Type":"application/json",...$.headers}})}}function d2({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...G}){let J,I=Y??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,H=G.signal??new AbortController().signal;while(!0){if(H.aborted)break;B++;let A=G.headers instanceof Headers?G.headers:new Headers(G.headers);if(J!==void 0)A.set("Last-Event-ID",J);try{let D={redirect:"follow",...G,body:G.serializedBody,headers:A,signal:H},_=new Request(L,D);if($)_=await $(L,D);let N=await(G.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let T=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{T.cancel()}catch{}};H.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await T.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
`);let y=U.split(`
`);U=y.pop()??"";for(let a of y){let i=a.split(`
`),F=[],v;for(let R of i)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))v=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let m=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(m))V=m}let M,h=!1;if(F.length){let R=F.join(`
-`);try{M=JSON.parse(R),h=!0}catch{M=R}}if(h){if(S)await S(M);if(x)M=await x(M)}if(j?.({data:M,event:v,id:J,retry:V}),F.length)yield M}}}finally{H.removeEventListener("abort",g),T.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var QS=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},GS=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},JS=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},sj=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((Y)=>encodeURIComponent(Y))).join(GS(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=QS(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return EO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},EO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},tj=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let Y=[];Object.entries(S).forEach(([G,J])=>{Y=[...Y,G,$?J:encodeURIComponent(J)]});let L=Y.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=JS(x),X=Object.entries(S).map(([Y,L])=>EO({allowReserved:$,name:x==="deepObject"?`${j}[${Y}]`:Y,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var VS=/\{[^{}]+\}/g,WS=({path:$,url:O})=>{let j=O,x=O.match(VS);if(x)for(let S of x){let K=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))K=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let Y=$[Z];if(Y===void 0||Y===null)continue;if(Array.isArray(Y)){j=j.replace(S,sj({explode:K,name:Z,style:X,value:Y}));continue}if(typeof Y==="object"){j=j.replace(S,tj({explode:K,name:Z,style:X,value:Y,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${EO({name:Z,value:Y})}`);continue}let L=encodeURIComponent(X==="label"?`.${Y}`:Y);j=j.replace(S,L)}return j},d2=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=WS({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function x1($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var l2=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var r2={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var p2=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let Y=sj({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(Y)S.push(Y)}else if(typeof Z==="object"){let Y=tj({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(Y)S.push(Y)}else{let Y=EO({allowReserved:X.allowReserved,name:K,value:Z});if(Y)S.push(Y)}}return S.join("&")}},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},BS=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function i2($){for(let O of $.security??[]){if(BS($,O.name))continue;let j=await l2(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var S1=($)=>d2({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:p2($.querySerializer),url:$.url}),Z1=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=oj($.headers,O.headers),j},LS=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},oj=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?LS(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class ej{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var n2=()=>({error:new ej,request:new ej,response:new ej}),NS=p2({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),US={"Content-Type":"application/json"},Sj=($={})=>({...r2,headers:US,parseAs:"auto",querySerializer:NS,...$});var X1=($={})=>{let O=Z1(Sj(),$),j=()=>({...O}),x=(G)=>{return O=Z1(O,G),j()},S=n2(),K=async(G)=>{let J={...O,...G,fetch:G.fetch??O.fetch??globalThis.fetch,headers:oj(O.headers,G.headers),serializedBody:void 0};if(J.security)await i2(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let I=J,z=S1(I);return{opts:I,url:z}},Z=async(G)=>{let J=G.throwOnError??O.throwOnError,I=G.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(G),H={redirect:"follow",...V,body:x1(V)};z=new Request(B,H);for(let N of S.request.fns)if(N)z=await N(z,V);let A=V.fetch;W=await A(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?a2(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let T;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":T=await W[N]();break;case"json":{let U=await W.text();T=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(T);if(V.responseTransformer)T=await V.responseTransformer(T)}return V.responseStyle==="data"?T:{data:T,...D}}let _=await W.text(),q;try{q=JSON.parse(_)}catch{}throw q??_}catch(V){let B=V;for(let H of S.error.fns)if(H)B=await H(B,W,z,G);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(G)=>(J)=>Z({...J,method:G}),Y=(G)=>async(J)=>{let{opts:I,url:z}=await K(J);return c2({...I,body:I.body,method:G,onRequest:async(W,V)=>{let B=new Request(W,V);for(let H of S.request.fns)if(H)B=await H(B,I);return B},serializedBody:x1(I),url:z})};return{buildUrl:(G)=>S1({...O,...G}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:Y("CONNECT"),delete:Y("DELETE"),get:Y("GET"),head:Y("HEAD"),options:Y("OPTIONS"),patch:Y("PATCH"),post:Y("POST"),put:Y("PUT"),trace:Y("TRACE")},trace:X("TRACE")}};var s2=X1(Sj());class t2{client;constructor($){this.client=$?.client??s2}}class e2{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class $0 extends t2{static __registry=new e2;constructor($){super($);$0.__registry.set(this,$?.key)}setPricingHandler($){return($.client??this.client).post({url:"/ai-cost/pricing",...$,headers:{"Content-Type":"application/json",...$.headers}})}getUsageHandler($){return($.client??this.client).post({url:"/ai-cost/usage",...$,headers:{"Content-Type":"application/json",...$.headers}})}upsertAiProjection($){return($.client??this.client).post({url:"/ai-projections",...$,headers:{"Content-Type":"application/json",...$.headers}})}getChatsForAttachmentHandler($){return($.client??this.client).get({url:"/attachments/{attachment_id}/chats",...$})}deleteChat($){return($.client??this.client).delete({url:"/chat/{chat_id}",...$})}patchChat($){return($.client??this.client).patch({url:"/chat/{chat_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}permanentlyDeleteChat($){return($.client??this.client).delete({url:"/chat/{chat_id}/permanent",...$})}createChat($){return($.client??this.client).post({url:"/chats",...$,headers:{"Content-Type":"application/json",...$.headers}})}getChatHistoryHandler($){return($.client??this.client).get({url:"/chats/history/{chat_id}",...$})}getChatHistoryBatchMessagesHandler($){return($.client??this.client).post({url:"/chats/history_batch_messages",...$,headers:{"Content-Type":"application/json",...$.headers}})}getChat($){return($.client??this.client).get({url:"/chats/{chat_id}",...$})}copyChat($){return($.client??this.client).post({url:"/chats/{chat_id}/copy",...$})}getChatPermissions($){return($.client??this.client).get({url:"/chats/{chat_id}/permissions",...$})}revertDeleteChat($){return($.client??this.client).put({url:"/chats/{chat_id}/revert_delete",...$})}callTool($){return($.client??this.client).post({url:"/chats/{chat_id}/tool/call",...$,headers:{"Content-Type":"application/json",...$.headers}})}rejectToolCall($){return($.client??this.client).post({url:"/chats/{chat_id}/tool/reject",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateToolResponse($){return($.client??this.client).post({url:"/chats/{chat_id}/tool/response/update",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateToolCall($){return($.client??this.client).post({url:"/chats/{chat_id}/tool/update",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCitationHandler($){return($.client??this.client).get({url:"/citations/{id}",...$})}generateDatabaseQuery($){return($.client??this.client).post({url:"/database-query",...$,headers:{"Content-Type":"application/json",...$.headers}})}decisions($){return($.client??this.client).post({url:"/decisions",...$,headers:{"Content-Type":"application/json",...$.headers}})}healthHandler($){return($?.client??this.client).get({url:"/health",...$})}generateImage($){return($.client??this.client).post({url:"/images/generate",...$,headers:{"Content-Type":"application/json",...$.headers}})}notionReportHandler($){return($?.client??this.client).get({url:"/import/notion",...$})}cancelNotionHandler($){return($?.client??this.client).post({url:"/import/notion/cancel",...$})}runImportHandler($){return($.client??this.client).post({url:"/import/run",...$,headers:{"Content-Type":"application/json",...$.headers}})}discoverHandler($){return($.client??this.client).post({url:"/import/runs/{source}/discover",...$})}getStateHandler($){return($?.client??this.client).get({url:"/import/state",...$})}workspaceReportHandler($){return($.client??this.client).get({url:"/import/workspaces/{source}",...$})}cancelWorkspaceHandler($){return($.client??this.client).post({url:"/import/workspaces/{source}/cancel",...$})}deleteMcpServer($){return($.client??this.client).delete({url:"/mcp/servers",...$})}listMcpServers($){return($?.client??this.client).get({url:"/mcp/servers",...$})}addMcpServer($){return($.client??this.client).post({url:"/mcp/servers",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateMcpServer($){return($.client??this.client).put({url:"/mcp/servers",...$,headers:{"Content-Type":"application/json",...$.headers}})}mcpAuthCallback($){return($?.client??this.client).get({url:"/mcp/servers/auth/callback",...$})}mcpOauthClientMetadata($){return($?.client??this.client).get({url:"/mcp/servers/auth/client-metadata",...$})}startMcpAuth($){return($.client??this.client).post({url:"/mcp/servers/auth/start",...$,headers:{"Content-Type":"application/json",...$.headers}})}getMemoryHandler($){return($?.client??this.client).get({url:"/memory",...$})}getStateHandler2($){return($?.client??this.client).get({url:"/onboarding",...$})}completeHandler($){return($.client??this.client).post({url:"/onboarding/complete",...$,headers:{"Content-Type":"application/json",...$.headers}})}dismissedPromptsHandler($){return($?.client??this.client).get({url:"/onboarding/prompts",...$})}dismissPromptHandler($){return($.client??this.client).post({url:"/onboarding/prompts/{prompt_id}/dismiss",...$})}browsePipedreamMcpCatalog($){return($?.client??this.client).get({url:"/pipedream/mcp/catalog",...$})}completePipedreamMcpConnection($){return($.client??this.client).post({url:"/pipedream/mcp/complete",...$,headers:{"Content-Type":"application/json",...$.headers}})}completePipedreamMcpConnect($){return($.client??this.client).post({url:"/pipedream/mcp/connect/complete",...$,headers:{"Content-Type":"application/json",...$.headers}})}deletePipedreamMcpConnection($){return($.client??this.client).delete({url:"/pipedream/mcp/connections",...$})}listPipedreamMcpConnections($){return($?.client??this.client).get({url:"/pipedream/mcp/connections",...$})}updatePipedreamMcpConnection($){return($.client??this.client).put({url:"/pipedream/mcp/connections",...$,headers:{"Content-Type":"application/json",...$.headers}})}listPipedreamMcpOverlays($){return($?.client??this.client).get({url:"/pipedream/mcp/overlays",...$})}recoverPipedreamMcpConnection($){return($.client??this.client).post({url:"/pipedream/mcp/recover",...$,headers:{"Content-Type":"application/json",...$.headers}})}createPipedreamMcpToken($){return($?.client??this.client).post({url:"/pipedream/mcp/token",...$,headers:{"Content-Type":"application/json",...$?.headers}})}getBatchPreview($){return($.client??this.client).post({url:"/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}sendChatMessage($){return($.client??this.client).post({url:"/stream/chat/message",...$,headers:{"Content-Type":"application/json",...$.headers}})}stopChatStream($){return($.client??this.client).post({url:"/stream/chat/message/stop",...$,headers:{"Content-Type":"application/json",...$.headers}})}structuredCompletion($){return($.client??this.client).post({url:"/structured-completion",...$,headers:{"Content-Type":"application/json",...$.headers}})}}function o2({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...G}){let J,I=Y??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,H=G.signal??new AbortController().signal;while(!0){if(H.aborted)break;B++;let A=G.headers instanceof Headers?G.headers:new Headers(G.headers);if(J!==void 0)A.set("Last-Event-ID",J);try{let D={redirect:"follow",...G,body:G.serializedBody,headers:A,signal:H},_=new Request(L,D);if($)_=await $(L,D);let N=await(G.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let T=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{T.cancel()}catch{}};H.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await T.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
+`);try{M=JSON.parse(R),h=!0}catch{M=R}}if(h){if(S)await S(M);if(x)M=await x(M)}if(j?.({data:M,event:v,id:J,retry:V}),F.length)yield M}}}finally{H.removeEventListener("abort",g),T.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var GS=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},JS=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},VS=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},sj=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((Y)=>encodeURIComponent(Y))).join(JS(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=GS(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return EO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},EO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},tj=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let Y=[];Object.entries(S).forEach(([G,J])=>{Y=[...Y,G,$?J:encodeURIComponent(J)]});let L=Y.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=VS(x),X=Object.entries(S).map(([Y,L])=>EO({allowReserved:$,name:x==="deepObject"?`${j}[${Y}]`:Y,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var WS=/\{[^{}]+\}/g,BS=({path:$,url:O})=>{let j=O,x=O.match(WS);if(x)for(let S of x){let K=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))K=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let Y=$[Z];if(Y===void 0||Y===null)continue;if(Array.isArray(Y)){j=j.replace(S,sj({explode:K,name:Z,style:X,value:Y}));continue}if(typeof Y==="object"){j=j.replace(S,tj({explode:K,name:Z,style:X,value:Y,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${EO({name:Z,value:Y})}`);continue}let L=encodeURIComponent(X==="label"?`.${Y}`:Y);j=j.replace(S,L)}return j},l2=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=BS({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function S1($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var r2=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var p2={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var a2=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let Y=sj({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(Y)S.push(Y)}else if(typeof Z==="object"){let Y=tj({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(Y)S.push(Y)}else{let Y=EO({allowReserved:X.allowReserved,name:K,value:Z});if(Y)S.push(Y)}}return S.join("&")}},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},LS=($,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(LS($,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 Z1=($)=>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=oj($.headers,O.headers),j},NS=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},oj=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?NS(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class ej{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var s2=()=>({error:new ej,request:new ej,response:new ej}),US=a2({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),zS={"Content-Type":"application/json"},Sj=($={})=>({...p2,headers:zS,parseAs:"auto",querySerializer:US,...$});var K1=($={})=>{let O=X1(Sj(),$),j=()=>({...O}),x=(G)=>{return O=X1(O,G),j()},S=s2(),K=async(G)=>{let J={...O,...G,fetch:G.fetch??O.fetch??globalThis.fetch,headers:oj(O.headers,G.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=Z1(I);return{opts:I,url:z}},Z=async(G)=>{let J=G.throwOnError??O.throwOnError,I=G.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(G),H={redirect:"follow",...V,body:S1(V)};z=new Request(B,H);for(let N of S.request.fns)if(N)z=await N(z,V);let A=V.fetch;W=await A(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?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 T;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":T=await W[N]();break;case"json":{let U=await W.text();T=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(T);if(V.responseTransformer)T=await V.responseTransformer(T)}return V.responseStyle==="data"?T:{data:T,...D}}let _=await W.text(),q;try{q=JSON.parse(_)}catch{}throw q??_}catch(V){let B=V;for(let H of S.error.fns)if(H)B=await H(B,W,z,G);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(G)=>(J)=>Z({...J,method:G}),Y=(G)=>async(J)=>{let{opts:I,url:z}=await K(J);return d2({...I,body:I.body,method:G,onRequest:async(W,V)=>{let B=new Request(W,V);for(let H of S.request.fns)if(H)B=await H(B,I);return B},serializedBody:S1(I),url:z})};return{buildUrl:(G)=>Z1({...O,...G}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:Y("CONNECT"),delete:Y("DELETE"),get:Y("GET"),head:Y("HEAD"),options:Y("OPTIONS"),patch:Y("PATCH"),post:Y("POST"),put:Y("PUT"),trace:Y("TRACE")},trace:X("TRACE")}};var t2=K1(Sj());class e2{client;constructor($){this.client=$?.client??t2}}class o2{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class $0 extends e2{static __registry=new o2;constructor($){super($);$0.__registry.set(this,$?.key)}setPricingHandler($){return($.client??this.client).post({url:"/ai-cost/pricing",...$,headers:{"Content-Type":"application/json",...$.headers}})}getUsageHandler($){return($.client??this.client).post({url:"/ai-cost/usage",...$,headers:{"Content-Type":"application/json",...$.headers}})}upsertAiProjection($){return($.client??this.client).post({url:"/ai-projections",...$,headers:{"Content-Type":"application/json",...$.headers}})}getChatsForAttachmentHandler($){return($.client??this.client).get({url:"/attachments/{attachment_id}/chats",...$})}deleteChat($){return($.client??this.client).delete({url:"/chat/{chat_id}",...$})}patchChat($){return($.client??this.client).patch({url:"/chat/{chat_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}permanentlyDeleteChat($){return($.client??this.client).delete({url:"/chat/{chat_id}/permanent",...$})}createChat($){return($.client??this.client).post({url:"/chats",...$,headers:{"Content-Type":"application/json",...$.headers}})}getChatHistoryHandler($){return($.client??this.client).get({url:"/chats/history/{chat_id}",...$})}getChatHistoryBatchMessagesHandler($){return($.client??this.client).post({url:"/chats/history_batch_messages",...$,headers:{"Content-Type":"application/json",...$.headers}})}getChat($){return($.client??this.client).get({url:"/chats/{chat_id}",...$})}copyChat($){return($.client??this.client).post({url:"/chats/{chat_id}/copy",...$})}getChatPermissions($){return($.client??this.client).get({url:"/chats/{chat_id}/permissions",...$})}revertDeleteChat($){return($.client??this.client).put({url:"/chats/{chat_id}/revert_delete",...$})}callTool($){return($.client??this.client).post({url:"/chats/{chat_id}/tool/call",...$,headers:{"Content-Type":"application/json",...$.headers}})}rejectToolCall($){return($.client??this.client).post({url:"/chats/{chat_id}/tool/reject",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateToolResponse($){return($.client??this.client).post({url:"/chats/{chat_id}/tool/response/update",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateToolCall($){return($.client??this.client).post({url:"/chats/{chat_id}/tool/update",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCitationHandler($){return($.client??this.client).get({url:"/citations/{id}",...$})}generateDatabaseQuery($){return($.client??this.client).post({url:"/database-query",...$,headers:{"Content-Type":"application/json",...$.headers}})}decisions($){return($.client??this.client).post({url:"/decisions",...$,headers:{"Content-Type":"application/json",...$.headers}})}healthHandler($){return($?.client??this.client).get({url:"/health",...$})}generateImage($){return($.client??this.client).post({url:"/images/generate",...$,headers:{"Content-Type":"application/json",...$.headers}})}notionReportHandler($){return($?.client??this.client).get({url:"/import/notion",...$})}cancelNotionHandler($){return($?.client??this.client).post({url:"/import/notion/cancel",...$})}runImportHandler($){return($.client??this.client).post({url:"/import/run",...$,headers:{"Content-Type":"application/json",...$.headers}})}discoverHandler($){return($.client??this.client).post({url:"/import/runs/{source}/discover",...$})}getStateHandler($){return($?.client??this.client).get({url:"/import/state",...$})}workspaceReportHandler($){return($.client??this.client).get({url:"/import/workspaces/{source}",...$})}cancelWorkspaceHandler($){return($.client??this.client).post({url:"/import/workspaces/{source}/cancel",...$})}deleteMcpServer($){return($.client??this.client).delete({url:"/mcp/servers",...$})}listMcpServers($){return($?.client??this.client).get({url:"/mcp/servers",...$})}addMcpServer($){return($.client??this.client).post({url:"/mcp/servers",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateMcpServer($){return($.client??this.client).put({url:"/mcp/servers",...$,headers:{"Content-Type":"application/json",...$.headers}})}mcpAuthCallback($){return($?.client??this.client).get({url:"/mcp/servers/auth/callback",...$})}mcpOauthClientMetadata($){return($?.client??this.client).get({url:"/mcp/servers/auth/client-metadata",...$})}startMcpAuth($){return($.client??this.client).post({url:"/mcp/servers/auth/start",...$,headers:{"Content-Type":"application/json",...$.headers}})}getMemoryHandler($){return($?.client??this.client).get({url:"/memory",...$})}getStateHandler2($){return($?.client??this.client).get({url:"/onboarding",...$})}completeHandler($){return($.client??this.client).post({url:"/onboarding/complete",...$,headers:{"Content-Type":"application/json",...$.headers}})}dismissedPromptsHandler($){return($?.client??this.client).get({url:"/onboarding/prompts",...$})}dismissPromptHandler($){return($.client??this.client).post({url:"/onboarding/prompts/{prompt_id}/dismiss",...$})}browsePipedreamMcpCatalog($){return($?.client??this.client).get({url:"/pipedream/mcp/catalog",...$})}completePipedreamMcpConnection($){return($.client??this.client).post({url:"/pipedream/mcp/complete",...$,headers:{"Content-Type":"application/json",...$.headers}})}completePipedreamMcpConnect($){return($.client??this.client).post({url:"/pipedream/mcp/connect/complete",...$,headers:{"Content-Type":"application/json",...$.headers}})}deletePipedreamMcpConnection($){return($.client??this.client).delete({url:"/pipedream/mcp/connections",...$})}listPipedreamMcpConnections($){return($?.client??this.client).get({url:"/pipedream/mcp/connections",...$})}updatePipedreamMcpConnection($){return($.client??this.client).put({url:"/pipedream/mcp/connections",...$,headers:{"Content-Type":"application/json",...$.headers}})}listPipedreamMcpOverlays($){return($?.client??this.client).get({url:"/pipedream/mcp/overlays",...$})}recoverPipedreamMcpConnection($){return($.client??this.client).post({url:"/pipedream/mcp/recover",...$,headers:{"Content-Type":"application/json",...$.headers}})}createPipedreamMcpToken($){return($?.client??this.client).post({url:"/pipedream/mcp/token",...$,headers:{"Content-Type":"application/json",...$?.headers}})}getBatchPreview($){return($.client??this.client).post({url:"/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}sendChatMessage($){return($.client??this.client).post({url:"/stream/chat/message",...$,headers:{"Content-Type":"application/json",...$.headers}})}stopChatStream($){return($.client??this.client).post({url:"/stream/chat/message/stop",...$,headers:{"Content-Type":"application/json",...$.headers}})}structuredCompletion($){return($.client??this.client).post({url:"/structured-completion",...$,headers:{"Content-Type":"application/json",...$.headers}})}}function $6({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...G}){let J,I=Y??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,H=G.signal??new AbortController().signal;while(!0){if(H.aborted)break;B++;let A=G.headers instanceof Headers?G.headers:new Headers(G.headers);if(J!==void 0)A.set("Last-Event-ID",J);try{let D={redirect:"follow",...G,body:G.serializedBody,headers:A,signal:H},_=new Request(L,D);if($)_=await $(L,D);let N=await(G.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let T=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{T.cancel()}catch{}};H.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await T.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
`);let y=U.split(`
`);U=y.pop()??"";for(let a of y){let i=a.split(`
`),F=[],v;for(let R of i)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))v=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let m=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(m))V=m}let M,h=!1;if(F.length){let R=F.join(`
-`);try{M=JSON.parse(R),h=!0}catch{M=R}}if(h){if(S)await S(M);if(x)M=await x(M)}if(j?.({data:M,event:v,id:J,retry:V}),F.length)yield M}}}finally{H.removeEventListener("abort",g),T.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var zS=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},IS=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},HS=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},O0=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((Y)=>encodeURIComponent(Y))).join(IS(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=zS(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return qO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},qO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},j0=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let Y=[];Object.entries(S).forEach(([G,J])=>{Y=[...Y,G,$?J:encodeURIComponent(J)]});let L=Y.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=HS(x),X=Object.entries(S).map(([Y,L])=>qO({allowReserved:$,name:x==="deepObject"?`${j}[${Y}]`:Y,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var TS=/\{[^{}]+\}/g,RS=({path:$,url:O})=>{let j=O,x=O.match(TS);if(x)for(let S of x){let K=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))K=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let Y=$[Z];if(Y===void 0||Y===null)continue;if(Array.isArray(Y)){j=j.replace(S,O0({explode:K,name:Z,style:X,value:Y}));continue}if(typeof Y==="object"){j=j.replace(S,j0({explode:K,name:Z,style:X,value:Y,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${qO({name:Z,value:Y})}`);continue}let L=encodeURIComponent(X==="label"?`.${Y}`:Y);j=j.replace(S,L)}return j},$6=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=RS({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function K1($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var O6=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var j6={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var x6=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let Y=O0({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(Y)S.push(Y)}else if(typeof Z==="object"){let Y=j0({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(Y)S.push(Y)}else{let Y=qO({allowReserved:X.allowReserved,name:K,value:Z});if(Y)S.push(Y)}}return S.join("&")}},S6=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},DS=($,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(DS($,O.name))continue;let j=await O6(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var Y1=($)=>$6({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:x6($.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=S0($.headers,O.headers),j},_S=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},S0=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?_S(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class x0{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var X6=()=>({error:new x0,request:new x0,response:new x0}),MS=x6({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),CS={"Content-Type":"application/json"},Zj=($={})=>({...j6,headers:CS,parseAs:"auto",querySerializer:MS,...$});var G1=($={})=>{let O=Q1(Zj(),$),j=()=>({...O}),x=(G)=>{return O=Q1(O,G),j()},S=X6(),K=async(G)=>{let J={...O,...G,fetch:G.fetch??O.fetch??globalThis.fetch,headers:S0(O.headers,G.headers),serializedBody:void 0};if(J.security)await Z6(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let I=J,z=Y1(I);return{opts:I,url:z}},Z=async(G)=>{let J=G.throwOnError??O.throwOnError,I=G.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(G),H={redirect:"follow",...V,body:K1(V)};z=new Request(B,H);for(let N of S.request.fns)if(N)z=await N(z,V);let A=V.fetch;W=await A(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?S6(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let T;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":T=await W[N]();break;case"json":{let U=await W.text();T=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(T);if(V.responseTransformer)T=await V.responseTransformer(T)}return V.responseStyle==="data"?T:{data:T,...D}}let _=await W.text(),q;try{q=JSON.parse(_)}catch{}throw q??_}catch(V){let B=V;for(let H of S.error.fns)if(H)B=await H(B,W,z,G);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(G)=>(J)=>Z({...J,method:G}),Y=(G)=>async(J)=>{let{opts:I,url:z}=await K(J);return o2({...I,body:I.body,method:G,onRequest:async(W,V)=>{let B=new Request(W,V);for(let H of S.request.fns)if(H)B=await H(B,I);return B},serializedBody:K1(I),url:z})};return{buildUrl:(G)=>Y1({...O,...G}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:Y("CONNECT"),delete:Y("DELETE"),get:Y("GET"),head:Y("HEAD"),options:Y("OPTIONS"),patch:Y("PATCH"),post:Y("POST"),put:Y("PUT"),trace:Y("TRACE")},trace:X("TRACE")}};var K6=G1(Zj());class Y6{client;constructor($){this.client=$?.client??K6}}class Q6{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class Z0 extends Y6{static __registry=new Q6;constructor($){super($);Z0.__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 G6({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...G}){let J,I=Y??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,H=G.signal??new AbortController().signal;while(!0){if(H.aborted)break;B++;let A=G.headers instanceof Headers?G.headers:new Headers(G.headers);if(J!==void 0)A.set("Last-Event-ID",J);try{let D={redirect:"follow",...G,body:G.serializedBody,headers:A,signal:H},_=new Request(L,D);if($)_=await $(L,D);let N=await(G.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let T=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{T.cancel()}catch{}};H.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await T.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
+`);try{M=JSON.parse(R),h=!0}catch{M=R}}if(h){if(S)await S(M);if(x)M=await x(M)}if(j?.({data:M,event:v,id:J,retry:V}),F.length)yield M}}}finally{H.removeEventListener("abort",g),T.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var IS=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},HS=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},TS=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},O0=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((Y)=>encodeURIComponent(Y))).join(HS(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=IS(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return qO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},qO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},j0=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let Y=[];Object.entries(S).forEach(([G,J])=>{Y=[...Y,G,$?J:encodeURIComponent(J)]});let L=Y.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=TS(x),X=Object.entries(S).map(([Y,L])=>qO({allowReserved:$,name:x==="deepObject"?`${j}[${Y}]`:Y,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var RS=/\{[^{}]+\}/g,DS=({path:$,url:O})=>{let j=O,x=O.match(RS);if(x)for(let S of x){let K=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))K=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let Y=$[Z];if(Y===void 0||Y===null)continue;if(Array.isArray(Y)){j=j.replace(S,O0({explode:K,name:Z,style:X,value:Y}));continue}if(typeof Y==="object"){j=j.replace(S,j0({explode:K,name:Z,style:X,value:Y,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${qO({name:Z,value:Y})}`);continue}let L=encodeURIComponent(X==="label"?`.${Y}`:Y);j=j.replace(S,L)}return j},O6=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=DS({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 j6=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var x6={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var S6=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let Y=O0({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(Y)S.push(Y)}else if(typeof Z==="object"){let Y=j0({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(Y)S.push(Y)}else{let Y=qO({allowReserved:X.allowReserved,name:K,value:Z});if(Y)S.push(Y)}}return S.join("&")}},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},_S=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function X6($){for(let O of $.security??[]){if(_S($,O.name))continue;let j=await j6(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var Q1=($)=>O6({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:S6($.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=S0($.headers,O.headers),j},MS=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},S0=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?MS(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class x0{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 x0,request:new x0,response:new x0}),CS=S6({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),PS={"Content-Type":"application/json"},Zj=($={})=>({...x6,headers:PS,parseAs:"auto",querySerializer:CS,...$});var J1=($={})=>{let O=G1(Zj(),$),j=()=>({...O}),x=(G)=>{return O=G1(O,G),j()},S=K6(),K=async(G)=>{let J={...O,...G,fetch:G.fetch??O.fetch??globalThis.fetch,headers:S0(O.headers,G.headers),serializedBody:void 0};if(J.security)await X6(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let I=J,z=Q1(I);return{opts:I,url:z}},Z=async(G)=>{let J=G.throwOnError??O.throwOnError,I=G.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(G),H={redirect:"follow",...V,body:Y1(V)};z=new Request(B,H);for(let N of S.request.fns)if(N)z=await N(z,V);let A=V.fetch;W=await A(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?Z6(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let T;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":T=await W[N]();break;case"json":{let U=await W.text();T=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(T);if(V.responseTransformer)T=await V.responseTransformer(T)}return V.responseStyle==="data"?T:{data:T,...D}}let _=await W.text(),q;try{q=JSON.parse(_)}catch{}throw q??_}catch(V){let B=V;for(let H of S.error.fns)if(H)B=await H(B,W,z,G);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(G)=>(J)=>Z({...J,method:G}),Y=(G)=>async(J)=>{let{opts:I,url:z}=await K(J);return $6({...I,body:I.body,method:G,onRequest:async(W,V)=>{let B=new Request(W,V);for(let H of S.request.fns)if(H)B=await H(B,I);return B},serializedBody:Y1(I),url:z})};return{buildUrl:(G)=>Q1({...O,...G}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:Y("CONNECT"),delete:Y("DELETE"),get:Y("GET"),head:Y("HEAD"),options:Y("OPTIONS"),patch:Y("PATCH"),post:Y("POST"),put:Y("PUT"),trace:Y("TRACE")},trace:X("TRACE")}};var Y6=J1(Zj());class Q6{client;constructor($){this.client=$?.client??Y6}}class G6{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 Z0 extends Q6{static __registry=new G6;constructor($){super($);Z0.__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 J6({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...G}){let J,I=Y??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,H=G.signal??new AbortController().signal;while(!0){if(H.aborted)break;B++;let A=G.headers instanceof Headers?G.headers:new Headers(G.headers);if(J!==void 0)A.set("Last-Event-ID",J);try{let D={redirect:"follow",...G,body:G.serializedBody,headers:A,signal:H},_=new Request(L,D);if($)_=await $(L,D);let N=await(G.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let T=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{T.cancel()}catch{}};H.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await T.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
`);let y=U.split(`
`);U=y.pop()??"";for(let a of y){let i=a.split(`
`),F=[],v;for(let R of i)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))v=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let m=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(m))V=m}let M,h=!1;if(F.length){let R=F.join(`
-`);try{M=JSON.parse(R),h=!0}catch{M=R}}if(h){if(S)await S(M);if(x)M=await x(M)}if(j?.({data:M,event:v,id:J,retry:V}),F.length)yield M}}}finally{H.removeEventListener("abort",g),T.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var PS=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},AS=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},FS=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},X0=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((Y)=>encodeURIComponent(Y))).join(AS(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=PS(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return wO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},wO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},K0=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let Y=[];Object.entries(S).forEach(([G,J])=>{Y=[...Y,G,$?J:encodeURIComponent(J)]});let L=Y.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=FS(x),X=Object.entries(S).map(([Y,L])=>wO({allowReserved:$,name:x==="deepObject"?`${j}[${Y}]`:Y,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var ES=/\{[^{}]+\}/g,qS=({path:$,url:O})=>{let j=O,x=O.match(ES);if(x)for(let S of x){let K=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))K=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let Y=$[Z];if(Y===void 0||Y===null)continue;if(Array.isArray(Y)){j=j.replace(S,X0({explode:K,name:Z,style:X,value:Y}));continue}if(typeof Y==="object"){j=j.replace(S,K0({explode:K,name:Z,style:X,value:Y,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${wO({name:Z,value:Y})}`);continue}let L=encodeURIComponent(X==="label"?`.${Y}`:Y);j=j.replace(S,L)}return j},J6=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=qS({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function J1($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var V6=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var W6={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var B6=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let Y=X0({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(Y)S.push(Y)}else if(typeof Z==="object"){let Y=K0({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(Y)S.push(Y)}else{let Y=wO({allowReserved:X.allowReserved,name:K,value:Z});if(Y)S.push(Y)}}return S.join("&")}},L6=($)=>{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},wS=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function N6($){for(let O of $.security??[]){if(wS($,O.name))continue;let j=await V6(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var V1=($)=>J6({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:B6($.querySerializer),url:$.url}),W1=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=Q0($.headers,O.headers),j},fS=($)=>{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?fS(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class Y0{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var U6=()=>({error:new Y0,request:new Y0,response:new Y0}),bS=B6({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),kS={"Content-Type":"application/json"},Xj=($={})=>({...W6,headers:kS,parseAs:"auto",querySerializer:bS,...$});var B1=($={})=>{let O=W1(Xj(),$),j=()=>({...O}),x=(G)=>{return O=W1(O,G),j()},S=U6(),K=async(G)=>{let J={...O,...G,fetch:G.fetch??O.fetch??globalThis.fetch,headers:Q0(O.headers,G.headers),serializedBody:void 0};if(J.security)await N6(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=V1(I);return{opts:I,url:z}},Z=async(G)=>{let J=G.throwOnError??O.throwOnError,I=G.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(G),H={redirect:"follow",...V,body:J1(V)};z=new Request(B,H);for(let N of S.request.fns)if(N)z=await N(z,V);let A=V.fetch;W=await A(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?L6(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let T;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":T=await W[N]();break;case"json":{let U=await W.text();T=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(T);if(V.responseTransformer)T=await V.responseTransformer(T)}return V.responseStyle==="data"?T:{data:T,...D}}let _=await W.text(),q;try{q=JSON.parse(_)}catch{}throw q??_}catch(V){let B=V;for(let H of S.error.fns)if(H)B=await H(B,W,z,G);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(G)=>(J)=>Z({...J,method:G}),Y=(G)=>async(J)=>{let{opts:I,url:z}=await K(J);return G6({...I,body:I.body,method:G,onRequest:async(W,V)=>{let B=new Request(W,V);for(let H of S.request.fns)if(H)B=await H(B,I);return B},serializedBody:J1(I),url:z})};return{buildUrl:(G)=>V1({...O,...G}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:Y("CONNECT"),delete:Y("DELETE"),get:Y("GET"),head:Y("HEAD"),options:Y("OPTIONS"),patch:Y("PATCH"),post:Y("POST"),put:Y("PUT"),trace:Y("TRACE")},trace:X("TRACE")}};var z6=B1(Xj());class I6{client;constructor($){this.client=$?.client??z6}}class H6{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class G0 extends I6{static __registry=new H6;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}",...$})}getMessageEml($){return($.client??this.client).get({url:"/email/messages/{id}/eml",...$})}patchSettings($){return($.client??this.client).patch({url:"/email/settings",...$,headers:{"Content-Type":"application/json",...$.headers}})}mailboxSettingsOperations($){return($?.client??this.client).get({url:"/email/settings/operations",...$})}disableSync($){return($?.client??this.client).delete({url:"/email/sync",...$})}archiveThreads($){return($.client??this.client).patch({url:"/email/threads/archived",...$,headers:{"Content-Type":"application/json",...$.headers}})}previewsInboxCursor($){return($.client??this.client).get({url:"/email/threads/previews/cursor/{view}",...$})}archiveThread($){return($.client??this.client).patch({url:"/email/threads/{id}/archived",...$,headers:{"Content-Type":"application/json",...$.headers}})}addRemoveThreadLabel($){return($.client??this.client).patch({url:"/email/threads/{id}/labels",...$,headers:{"Content-Type":"application/json",...$.headers}})}getThreadMessagesHandler($){return($.client??this.client).get({url:"/email/threads/{id}/messages",...$})}threadOperations($){return($.client??this.client).get({url:"/email/threads/{id}/operations",...$})}threadSeen($){return($.client??this.client).post({url:"/email/threads/{id}/seen",...$})}updateThreadState($){return($.client??this.client).patch({url:"/email/threads/{id}/state",...$,headers:{"Content-Type":"application/json",...$.headers}})}getThread($){return($.client??this.client).get({url:"/email/threads/{thread_id}",...$})}getThreadCalendarInvitations($){return($.client??this.client).get({url:"/email/threads/{thread_id}/calendar-invitations",...$})}copyThreadCalendarInvitation($){return($.client??this.client).post({url:"/email/threads/{thread_id}/messages/{message_id}/calendar-invitations/{invitation_id}/copy",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateThreadProject($){return($.client??this.client).patch({url:"/email/threads/{thread_id}/project",...$,headers:{"Content-Type":"application/json",...$.headers}})}getThreadReadReceipts($){return($.client??this.client).get({url:"/email/threads/{thread_id}/read-receipts",...$})}healthHandler($){return($?.client??this.client).get({url:"/health",...$})}getReadReceiptPixel($){return($.client??this.client).get({url:"/opens/{token}",...$})}}function T6({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...G}){let J,I=Y??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,H=G.signal??new AbortController().signal;while(!0){if(H.aborted)break;B++;let A=G.headers instanceof Headers?G.headers:new Headers(G.headers);if(J!==void 0)A.set("Last-Event-ID",J);try{let D={redirect:"follow",...G,body:G.serializedBody,headers:A,signal:H},_=new Request(L,D);if($)_=await $(L,D);let N=await(G.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let T=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{T.cancel()}catch{}};H.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await T.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
+`);try{M=JSON.parse(R),h=!0}catch{M=R}}if(h){if(S)await S(M);if(x)M=await x(M)}if(j?.({data:M,event:v,id:J,retry:V}),F.length)yield M}}}finally{H.removeEventListener("abort",g),T.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var AS=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},FS=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},ES=($)=>{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((Y)=>encodeURIComponent(Y))).join(FS(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=AS(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return wO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},wO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},K0=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let Y=[];Object.entries(S).forEach(([G,J])=>{Y=[...Y,G,$?J:encodeURIComponent(J)]});let L=Y.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=ES(x),X=Object.entries(S).map(([Y,L])=>wO({allowReserved:$,name:x==="deepObject"?`${j}[${Y}]`:Y,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var qS=/\{[^{}]+\}/g,wS=({path:$,url:O})=>{let j=O,x=O.match(qS);if(x)for(let S of x){let K=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))K=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let Y=$[Z];if(Y===void 0||Y===null)continue;if(Array.isArray(Y)){j=j.replace(S,X0({explode:K,name:Z,style:X,value:Y}));continue}if(typeof Y==="object"){j=j.replace(S,K0({explode:K,name:Z,style:X,value:Y,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${wO({name:Z,value:Y})}`);continue}let L=encodeURIComponent(X==="label"?`.${Y}`:Y);j=j.replace(S,L)}return j},V6=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=wS({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function V1($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var W6=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 B6={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var L6=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let Y=X0({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(Y)S.push(Y)}else if(typeof Z==="object"){let Y=K0({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(Y)S.push(Y)}else{let Y=wO({allowReserved:X.allowReserved,name:K,value:Z});if(Y)S.push(Y)}}return S.join("&")}},N6=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},fS=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function U6($){for(let O of $.security??[]){if(fS($,O.name))continue;let j=await W6(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=($)=>V6({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:L6($.querySerializer),url:$.url}),B1=($,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},bS=($)=>{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?bS(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class Y0{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var z6=()=>({error:new Y0,request:new Y0,response:new Y0}),kS=L6({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),gS={"Content-Type":"application/json"},Xj=($={})=>({...B6,headers:gS,parseAs:"auto",querySerializer:kS,...$});var L1=($={})=>{let O=B1(Xj(),$),j=()=>({...O}),x=(G)=>{return O=B1(O,G),j()},S=z6(),K=async(G)=>{let J={...O,...G,fetch:G.fetch??O.fetch??globalThis.fetch,headers:Q0(O.headers,G.headers),serializedBody:void 0};if(J.security)await U6(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let I=J,z=W1(I);return{opts:I,url:z}},Z=async(G)=>{let J=G.throwOnError??O.throwOnError,I=G.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(G),H={redirect:"follow",...V,body:V1(V)};z=new Request(B,H);for(let N of S.request.fns)if(N)z=await N(z,V);let A=V.fetch;W=await A(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?N6(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let T;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":T=await W[N]();break;case"json":{let U=await W.text();T=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(T);if(V.responseTransformer)T=await V.responseTransformer(T)}return V.responseStyle==="data"?T:{data:T,...D}}let _=await W.text(),q;try{q=JSON.parse(_)}catch{}throw q??_}catch(V){let B=V;for(let H of S.error.fns)if(H)B=await H(B,W,z,G);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(G)=>(J)=>Z({...J,method:G}),Y=(G)=>async(J)=>{let{opts:I,url:z}=await K(J);return J6({...I,body:I.body,method:G,onRequest:async(W,V)=>{let B=new Request(W,V);for(let H of S.request.fns)if(H)B=await H(B,I);return B},serializedBody:V1(I),url:z})};return{buildUrl:(G)=>W1({...O,...G}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:Y("CONNECT"),delete:Y("DELETE"),get:Y("GET"),head:Y("HEAD"),options:Y("OPTIONS"),patch:Y("PATCH"),post:Y("POST"),put:Y("PUT"),trace:Y("TRACE")},trace:X("TRACE")}};var I6=L1(Xj());class H6{client;constructor($){this.client=$?.client??I6}}class T6{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 T6;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}",...$})}getMessageEml($){return($.client??this.client).get({url:"/email/messages/{id}/eml",...$})}patchSettings($){return($.client??this.client).patch({url:"/email/settings",...$,headers:{"Content-Type":"application/json",...$.headers}})}mailboxSettingsOperations($){return($?.client??this.client).get({url:"/email/settings/operations",...$})}disableSync($){return($?.client??this.client).delete({url:"/email/sync",...$})}archiveThreads($){return($.client??this.client).patch({url:"/email/threads/archived",...$,headers:{"Content-Type":"application/json",...$.headers}})}previewsInboxCursor($){return($.client??this.client).get({url:"/email/threads/previews/cursor/{view}",...$})}archiveThread($){return($.client??this.client).patch({url:"/email/threads/{id}/archived",...$,headers:{"Content-Type":"application/json",...$.headers}})}addRemoveThreadLabel($){return($.client??this.client).patch({url:"/email/threads/{id}/labels",...$,headers:{"Content-Type":"application/json",...$.headers}})}getThreadMessagesHandler($){return($.client??this.client).get({url:"/email/threads/{id}/messages",...$})}threadOperations($){return($.client??this.client).get({url:"/email/threads/{id}/operations",...$})}threadSeen($){return($.client??this.client).post({url:"/email/threads/{id}/seen",...$})}updateThreadState($){return($.client??this.client).patch({url:"/email/threads/{id}/state",...$,headers:{"Content-Type":"application/json",...$.headers}})}getThread($){return($.client??this.client).get({url:"/email/threads/{thread_id}",...$})}getThreadCalendarInvitations($){return($.client??this.client).get({url:"/email/threads/{thread_id}/calendar-invitations",...$})}copyThreadCalendarInvitation($){return($.client??this.client).post({url:"/email/threads/{thread_id}/messages/{message_id}/calendar-invitations/{invitation_id}/copy",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateThreadProject($){return($.client??this.client).patch({url:"/email/threads/{thread_id}/project",...$,headers:{"Content-Type":"application/json",...$.headers}})}getThreadReadReceipts($){return($.client??this.client).get({url:"/email/threads/{thread_id}/read-receipts",...$})}healthHandler($){return($?.client??this.client).get({url:"/health",...$})}getReadReceiptPixel($){return($.client??this.client).get({url:"/opens/{token}",...$})}}function R6({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...G}){let J,I=Y??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,H=G.signal??new AbortController().signal;while(!0){if(H.aborted)break;B++;let A=G.headers instanceof Headers?G.headers:new Headers(G.headers);if(J!==void 0)A.set("Last-Event-ID",J);try{let D={redirect:"follow",...G,body:G.serializedBody,headers:A,signal:H},_=new Request(L,D);if($)_=await $(L,D);let N=await(G.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let T=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{T.cancel()}catch{}};H.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await T.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
`);let y=U.split(`
`);U=y.pop()??"";for(let a of y){let i=a.split(`
`),F=[],v;for(let R of i)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))v=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let m=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(m))V=m}let M,h=!1;if(F.length){let R=F.join(`
-`);try{M=JSON.parse(R),h=!0}catch{M=R}}if(h){if(S)await S(M);if(x)M=await x(M)}if(j?.({data:M,event:v,id:J,retry:V}),F.length)yield M}}}finally{H.removeEventListener("abort",g),T.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var gS=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},yS=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},vS=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},J0=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((Y)=>encodeURIComponent(Y))).join(yS(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=gS(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return fO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},fO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},V0=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let Y=[];Object.entries(S).forEach(([G,J])=>{Y=[...Y,G,$?J:encodeURIComponent(J)]});let L=Y.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=vS(x),X=Object.entries(S).map(([Y,L])=>fO({allowReserved:$,name:x==="deepObject"?`${j}[${Y}]`:Y,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var hS=/\{[^{}]+\}/g,mS=({path:$,url:O})=>{let j=O,x=O.match(hS);if(x)for(let S of x){let K=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))K=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let Y=$[Z];if(Y===void 0||Y===null)continue;if(Array.isArray(Y)){j=j.replace(S,J0({explode:K,name:Z,style:X,value:Y}));continue}if(typeof Y==="object"){j=j.replace(S,V0({explode:K,name:Z,style:X,value:Y,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${fO({name:Z,value:Y})}`);continue}let L=encodeURIComponent(X==="label"?`.${Y}`:Y);j=j.replace(S,L)}return j},R6=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=mS({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function L1($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var D6=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 _6={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var M6=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let Y=J0({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(Y)S.push(Y)}else if(typeof Z==="object"){let Y=V0({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(Y)S.push(Y)}else{let Y=fO({allowReserved:X.allowReserved,name:K,value:Z});if(Y)S.push(Y)}}return S.join("&")}},C6=($)=>{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},uS=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function P6($){for(let O of $.security??[]){if(uS($,O.name))continue;let j=await D6(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 N1=($)=>R6({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:M6($.querySerializer),url:$.url}),U1=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=B0($.headers,O.headers),j},cS=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},B0=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?cS(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class W0{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 A6=()=>({error:new W0,request:new W0,response:new W0}),dS=M6({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),lS={"Content-Type":"application/json"},Kj=($={})=>({..._6,headers:lS,parseAs:"auto",querySerializer:dS,...$});var z1=($={})=>{let O=U1(Kj(),$),j=()=>({...O}),x=(G)=>{return O=U1(O,G),j()},S=A6(),K=async(G)=>{let J={...O,...G,fetch:G.fetch??O.fetch??globalThis.fetch,headers:B0(O.headers,G.headers),serializedBody:void 0};if(J.security)await P6(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=N1(I);return{opts:I,url:z}},Z=async(G)=>{let J=G.throwOnError??O.throwOnError,I=G.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(G),H={redirect:"follow",...V,body:L1(V)};z=new Request(B,H);for(let N of S.request.fns)if(N)z=await N(z,V);let A=V.fetch;W=await A(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?C6(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let T;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":T=await W[N]();break;case"json":{let U=await W.text();T=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(T);if(V.responseTransformer)T=await V.responseTransformer(T)}return V.responseStyle==="data"?T:{data:T,...D}}let _=await W.text(),q;try{q=JSON.parse(_)}catch{}throw q??_}catch(V){let B=V;for(let H of S.error.fns)if(H)B=await H(B,W,z,G);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(G)=>(J)=>Z({...J,method:G}),Y=(G)=>async(J)=>{let{opts:I,url:z}=await K(J);return T6({...I,body:I.body,method:G,onRequest:async(W,V)=>{let B=new Request(W,V);for(let H of S.request.fns)if(H)B=await H(B,I);return B},serializedBody:L1(I),url:z})};return{buildUrl:(G)=>N1({...O,...G}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:Y("CONNECT"),delete:Y("DELETE"),get:Y("GET"),head:Y("HEAD"),options:Y("OPTIONS"),patch:Y("PATCH"),post:Y("POST"),put:Y("PUT"),trace:Y("TRACE")},trace:X("TRACE")}};var F6=z1(Kj());class E6{client;constructor($){this.client=$?.client??F6}}class q6{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class L0 extends E6{static __registry=new q6;constructor($){super($);L0.__registry.set(this,$?.key)}healthHandler($){return($?.client??this.client).get({url:"/health",...$})}getUnsubscribes($){return($?.client??this.client).get({url:"/unsubscribe",...$})}unsubscribeEmail($){return($?.client??this.client).post({url:"/unsubscribe/email",...$})}removeUnsubscribeItem($){return($.client??this.client).delete({url:"/unsubscribe/item/{item_type}/{item_id}",...$})}unsubscribeItem($){return($.client??this.client).post({url:"/unsubscribe/item/{item_type}/{item_id}",...$})}removeUnsubscribeItems($){return($.client??this.client).delete({url:"/unsubscribe/items",...$,headers:{"Content-Type":"application/json",...$.headers}})}unsubscribeItems($){return($.client??this.client).post({url:"/unsubscribe/items",...$,headers:{"Content-Type":"application/json",...$.headers}})}removeUnsubscribeAll($){return($?.client??this.client).delete({url:"/unsubscribe/mute",...$})}unsubscribeAll($){return($?.client??this.client).post({url:"/unsubscribe/mute",...$})}listTypedNotifications($){return($?.client??this.client).get({url:"/v1/user_notifications",...$})}bulkGetTypedNotificationsByEventItemIds($){return($.client??this.client).post({url:"/v1/user_notifications/item/bulk",...$,headers:{"Content-Type":"application/json",...$.headers}})}getTypedNotificationsByEventItemId($){return($.client??this.client).get({url:"/v1/user_notifications/item/{event_item_id}",...$})}getNotificationTypePreferences($){return($?.client??this.client).get({url:"/v1/user_notifications/preferences",...$})}disableNotificationType($){return($.client??this.client).put({url:"/v1/user_notifications/preferences/{notification_event_type}/disable",...$})}enableNotificationType($){return($.client??this.client).put({url:"/v1/user_notifications/preferences/{notification_event_type}/enable",...$})}getTypedNotificationById($){return($.client??this.client).get({url:"/v1/user_notifications/{notification_id}",...$})}bulkDeleteUserNotificationsV2($){return($.client??this.client).delete({url:"/v2/user_notifications/bulk",...$,headers:{"Content-Type":"application/json",...$.headers}})}bulkMarkNotificationsDone($){return($.client??this.client).patch({url:"/v2/user_notifications/bulk/done",...$,headers:{"Content-Type":"application/json",...$.headers}})}bulkMarkNotificationsSeen($){return($.client??this.client).patch({url:"/v2/user_notifications/bulk/seen",...$,headers:{"Content-Type":"application/json",...$.headers}})}bulkMarkNotificationsUndone($){return($.client??this.client).patch({url:"/v2/user_notifications/bulk/undone",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteUserNotificationV2($){return($.client??this.client).delete({url:"/v2/user_notifications/{notification_id}",...$})}}function w6({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...G}){let J,I=Y??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,H=G.signal??new AbortController().signal;while(!0){if(H.aborted)break;B++;let A=G.headers instanceof Headers?G.headers:new Headers(G.headers);if(J!==void 0)A.set("Last-Event-ID",J);try{let D={redirect:"follow",...G,body:G.serializedBody,headers:A,signal:H},_=new Request(L,D);if($)_=await $(L,D);let N=await(G.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let T=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{T.cancel()}catch{}};H.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await T.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
+`);try{M=JSON.parse(R),h=!0}catch{M=R}}if(h){if(S)await S(M);if(x)M=await x(M)}if(j?.({data:M,event:v,id:J,retry:V}),F.length)yield M}}}finally{H.removeEventListener("abort",g),T.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var yS=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},vS=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},hS=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},J0=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((Y)=>encodeURIComponent(Y))).join(vS(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=yS(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return fO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},fO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},V0=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let Y=[];Object.entries(S).forEach(([G,J])=>{Y=[...Y,G,$?J:encodeURIComponent(J)]});let L=Y.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=hS(x),X=Object.entries(S).map(([Y,L])=>fO({allowReserved:$,name:x==="deepObject"?`${j}[${Y}]`:Y,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var mS=/\{[^{}]+\}/g,uS=({path:$,url:O})=>{let j=O,x=O.match(mS);if(x)for(let S of x){let K=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))K=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let Y=$[Z];if(Y===void 0||Y===null)continue;if(Array.isArray(Y)){j=j.replace(S,J0({explode:K,name:Z,style:X,value:Y}));continue}if(typeof Y==="object"){j=j.replace(S,V0({explode:K,name:Z,style:X,value:Y,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${fO({name:Z,value:Y})}`);continue}let L=encodeURIComponent(X==="label"?`.${Y}`:Y);j=j.replace(S,L)}return j},D6=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=uS({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function N1($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var _6=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 M6={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var C6=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let Y=J0({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(Y)S.push(Y)}else if(typeof Z==="object"){let Y=V0({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(Y)S.push(Y)}else{let Y=fO({allowReserved:X.allowReserved,name:K,value:Z});if(Y)S.push(Y)}}return S.join("&")}},P6=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},cS=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function A6($){for(let O of $.security??[]){if(cS($,O.name))continue;let j=await _6(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var U1=($)=>D6({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:C6($.querySerializer),url:$.url}),z1=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=B0($.headers,O.headers),j},dS=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},B0=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?dS(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class W0{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 F6=()=>({error:new W0,request:new W0,response:new W0}),lS=C6({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),rS={"Content-Type":"application/json"},Kj=($={})=>({...M6,headers:rS,parseAs:"auto",querySerializer:lS,...$});var I1=($={})=>{let O=z1(Kj(),$),j=()=>({...O}),x=(G)=>{return O=z1(O,G),j()},S=F6(),K=async(G)=>{let J={...O,...G,fetch:G.fetch??O.fetch??globalThis.fetch,headers:B0(O.headers,G.headers),serializedBody:void 0};if(J.security)await A6(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let I=J,z=U1(I);return{opts:I,url:z}},Z=async(G)=>{let J=G.throwOnError??O.throwOnError,I=G.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(G),H={redirect:"follow",...V,body:N1(V)};z=new Request(B,H);for(let N of S.request.fns)if(N)z=await N(z,V);let A=V.fetch;W=await A(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?P6(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let T;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":T=await W[N]();break;case"json":{let U=await W.text();T=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(T);if(V.responseTransformer)T=await V.responseTransformer(T)}return V.responseStyle==="data"?T:{data:T,...D}}let _=await W.text(),q;try{q=JSON.parse(_)}catch{}throw q??_}catch(V){let B=V;for(let H of S.error.fns)if(H)B=await H(B,W,z,G);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(G)=>(J)=>Z({...J,method:G}),Y=(G)=>async(J)=>{let{opts:I,url:z}=await K(J);return R6({...I,body:I.body,method:G,onRequest:async(W,V)=>{let B=new Request(W,V);for(let H of S.request.fns)if(H)B=await H(B,I);return B},serializedBody:N1(I),url:z})};return{buildUrl:(G)=>U1({...O,...G}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:Y("CONNECT"),delete:Y("DELETE"),get:Y("GET"),head:Y("HEAD"),options:Y("OPTIONS"),patch:Y("PATCH"),post:Y("POST"),put:Y("PUT"),trace:Y("TRACE")},trace:X("TRACE")}};var E6=I1(Kj());class q6{client;constructor($){this.client=$?.client??E6}}class w6{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 L0 extends q6{static __registry=new w6;constructor($){super($);L0.__registry.set(this,$?.key)}healthHandler($){return($?.client??this.client).get({url:"/health",...$})}getUnsubscribes($){return($?.client??this.client).get({url:"/unsubscribe",...$})}unsubscribeEmail($){return($?.client??this.client).post({url:"/unsubscribe/email",...$})}removeUnsubscribeItem($){return($.client??this.client).delete({url:"/unsubscribe/item/{item_type}/{item_id}",...$})}unsubscribeItem($){return($.client??this.client).post({url:"/unsubscribe/item/{item_type}/{item_id}",...$})}removeUnsubscribeItems($){return($.client??this.client).delete({url:"/unsubscribe/items",...$,headers:{"Content-Type":"application/json",...$.headers}})}unsubscribeItems($){return($.client??this.client).post({url:"/unsubscribe/items",...$,headers:{"Content-Type":"application/json",...$.headers}})}removeUnsubscribeAll($){return($?.client??this.client).delete({url:"/unsubscribe/mute",...$})}unsubscribeAll($){return($?.client??this.client).post({url:"/unsubscribe/mute",...$})}listTypedNotifications($){return($?.client??this.client).get({url:"/v1/user_notifications",...$})}bulkGetTypedNotificationsByEventItemIds($){return($.client??this.client).post({url:"/v1/user_notifications/item/bulk",...$,headers:{"Content-Type":"application/json",...$.headers}})}getTypedNotificationsByEventItemId($){return($.client??this.client).get({url:"/v1/user_notifications/item/{event_item_id}",...$})}getNotificationTypePreferences($){return($?.client??this.client).get({url:"/v1/user_notifications/preferences",...$})}disableNotificationType($){return($.client??this.client).put({url:"/v1/user_notifications/preferences/{notification_event_type}/disable",...$})}enableNotificationType($){return($.client??this.client).put({url:"/v1/user_notifications/preferences/{notification_event_type}/enable",...$})}getTypedNotificationById($){return($.client??this.client).get({url:"/v1/user_notifications/{notification_id}",...$})}bulkDeleteUserNotificationsV2($){return($.client??this.client).delete({url:"/v2/user_notifications/bulk",...$,headers:{"Content-Type":"application/json",...$.headers}})}bulkMarkNotificationsDone($){return($.client??this.client).patch({url:"/v2/user_notifications/bulk/done",...$,headers:{"Content-Type":"application/json",...$.headers}})}bulkMarkNotificationsSeen($){return($.client??this.client).patch({url:"/v2/user_notifications/bulk/seen",...$,headers:{"Content-Type":"application/json",...$.headers}})}bulkMarkNotificationsUndone($){return($.client??this.client).patch({url:"/v2/user_notifications/bulk/undone",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteUserNotificationV2($){return($.client??this.client).delete({url:"/v2/user_notifications/{notification_id}",...$})}}function f6({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...G}){let J,I=Y??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,H=G.signal??new AbortController().signal;while(!0){if(H.aborted)break;B++;let A=G.headers instanceof Headers?G.headers:new Headers(G.headers);if(J!==void 0)A.set("Last-Event-ID",J);try{let D={redirect:"follow",...G,body:G.serializedBody,headers:A,signal:H},_=new Request(L,D);if($)_=await $(L,D);let N=await(G.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let T=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{T.cancel()}catch{}};H.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await T.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
`);let y=U.split(`
`);U=y.pop()??"";for(let a of y){let i=a.split(`
`),F=[],v;for(let R of i)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))v=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let m=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(m))V=m}let M,h=!1;if(F.length){let R=F.join(`
-`);try{M=JSON.parse(R),h=!0}catch{M=R}}if(h){if(S)await S(M);if(x)M=await x(M)}if(j?.({data:M,event:v,id:J,retry:V}),F.length)yield M}}}finally{H.removeEventListener("abort",g),T.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var rS=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},pS=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},aS=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},N0=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((Y)=>encodeURIComponent(Y))).join(pS(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=rS(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return bO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},bO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},U0=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let Y=[];Object.entries(S).forEach(([G,J])=>{Y=[...Y,G,$?J:encodeURIComponent(J)]});let L=Y.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=aS(x),X=Object.entries(S).map(([Y,L])=>bO({allowReserved:$,name:x==="deepObject"?`${j}[${Y}]`:Y,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var iS=/\{[^{}]+\}/g,nS=({path:$,url:O})=>{let j=O,x=O.match(iS);if(x)for(let S of x){let K=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))K=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let Y=$[Z];if(Y===void 0||Y===null)continue;if(Array.isArray(Y)){j=j.replace(S,N0({explode:K,name:Z,style:X,value:Y}));continue}if(typeof Y==="object"){j=j.replace(S,U0({explode:K,name:Z,style:X,value:Y,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${bO({name:Z,value:Y})}`);continue}let L=encodeURIComponent(X==="label"?`.${Y}`:Y);j=j.replace(S,L)}return j},f6=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=nS({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function I1($){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 k6={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var g6=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let Y=N0({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(Y)S.push(Y)}else if(typeof Z==="object"){let Y=U0({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(Y)S.push(Y)}else{let Y=bO({allowReserved:X.allowReserved,name:K,value:Z});if(Y)S.push(Y)}}return S.join("&")}},y6=($)=>{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},sS=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function v6($){for(let O of $.security??[]){if(sS($,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 H1=($)=>f6({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:g6($.querySerializer),url:$.url}),T1=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=I0($.headers,O.headers),j},tS=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},I0=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?tS(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class z0{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var h6=()=>({error:new z0,request:new z0,response:new z0}),eS=g6({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),oS={"Content-Type":"application/json"},Yj=($={})=>({...k6,headers:oS,parseAs:"auto",querySerializer:eS,...$});var R1=($={})=>{let O=T1(Yj(),$),j=()=>({...O}),x=(G)=>{return O=T1(O,G),j()},S=h6(),K=async(G)=>{let J={...O,...G,fetch:G.fetch??O.fetch??globalThis.fetch,headers:I0(O.headers,G.headers),serializedBody:void 0};if(J.security)await v6(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let I=J,z=H1(I);return{opts:I,url:z}},Z=async(G)=>{let J=G.throwOnError??O.throwOnError,I=G.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(G),H={redirect:"follow",...V,body:I1(V)};z=new Request(B,H);for(let N of S.request.fns)if(N)z=await N(z,V);let A=V.fetch;W=await A(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?y6(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let T;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":T=await W[N]();break;case"json":{let U=await W.text();T=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(T);if(V.responseTransformer)T=await V.responseTransformer(T)}return V.responseStyle==="data"?T:{data:T,...D}}let _=await W.text(),q;try{q=JSON.parse(_)}catch{}throw q??_}catch(V){let B=V;for(let H of S.error.fns)if(H)B=await H(B,W,z,G);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(G)=>(J)=>Z({...J,method:G}),Y=(G)=>async(J)=>{let{opts:I,url:z}=await K(J);return w6({...I,body:I.body,method:G,onRequest:async(W,V)=>{let B=new Request(W,V);for(let H of S.request.fns)if(H)B=await H(B,I);return B},serializedBody:I1(I),url:z})};return{buildUrl:(G)=>H1({...O,...G}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:Y("CONNECT"),delete:Y("DELETE"),get:Y("GET"),head:Y("HEAD"),options:Y("OPTIONS"),patch:Y("PATCH"),post:Y("POST"),put:Y("PUT"),trace:Y("TRACE")},trace:X("TRACE")}};var m6=R1(Yj());class u6{client;constructor($){this.client=$?.client??m6}}class c6{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 u6{static __registry=new c6;constructor($){super($);H0.__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 d6({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...G}){let J,I=Y??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,H=G.signal??new AbortController().signal;while(!0){if(H.aborted)break;B++;let A=G.headers instanceof Headers?G.headers:new Headers(G.headers);if(J!==void 0)A.set("Last-Event-ID",J);try{let D={redirect:"follow",...G,body:G.serializedBody,headers:A,signal:H},_=new Request(L,D);if($)_=await $(L,D);let N=await(G.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let T=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{T.cancel()}catch{}};H.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await T.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
+`);try{M=JSON.parse(R),h=!0}catch{M=R}}if(h){if(S)await S(M);if(x)M=await x(M)}if(j?.({data:M,event:v,id:J,retry:V}),F.length)yield M}}}finally{H.removeEventListener("abort",g),T.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var pS=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},aS=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},iS=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},N0=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((Y)=>encodeURIComponent(Y))).join(aS(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=pS(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return bO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},bO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},U0=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let Y=[];Object.entries(S).forEach(([G,J])=>{Y=[...Y,G,$?J:encodeURIComponent(J)]});let L=Y.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=iS(x),X=Object.entries(S).map(([Y,L])=>bO({allowReserved:$,name:x==="deepObject"?`${j}[${Y}]`:Y,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var nS=/\{[^{}]+\}/g,sS=({path:$,url:O})=>{let j=O,x=O.match(nS);if(x)for(let S of x){let K=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))K=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let Y=$[Z];if(Y===void 0||Y===null)continue;if(Array.isArray(Y)){j=j.replace(S,N0({explode:K,name:Z,style:X,value:Y}));continue}if(typeof Y==="object"){j=j.replace(S,U0({explode:K,name:Z,style:X,value:Y,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${bO({name:Z,value:Y})}`);continue}let L=encodeURIComponent(X==="label"?`.${Y}`:Y);j=j.replace(S,L)}return j},b6=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=sS({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 k6=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 g6={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var y6=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let Y=N0({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(Y)S.push(Y)}else if(typeof Z==="object"){let Y=U0({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(Y)S.push(Y)}else{let Y=bO({allowReserved:X.allowReserved,name:K,value:Z});if(Y)S.push(Y)}}return S.join("&")}},v6=($)=>{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},tS=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function h6($){for(let O of $.security??[]){if(tS($,O.name))continue;let j=await k6(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 T1=($)=>b6({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:y6($.querySerializer),url:$.url}),R1=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=I0($.headers,O.headers),j},eS=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},I0=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?eS(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class z0{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var m6=()=>({error:new z0,request:new z0,response:new z0}),oS=y6({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),$9={"Content-Type":"application/json"},Yj=($={})=>({...g6,headers:$9,parseAs:"auto",querySerializer:oS,...$});var D1=($={})=>{let O=R1(Yj(),$),j=()=>({...O}),x=(G)=>{return O=R1(O,G),j()},S=m6(),K=async(G)=>{let J={...O,...G,fetch:G.fetch??O.fetch??globalThis.fetch,headers:I0(O.headers,G.headers),serializedBody:void 0};if(J.security)await h6(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=T1(I);return{opts:I,url:z}},Z=async(G)=>{let J=G.throwOnError??O.throwOnError,I=G.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(G),H={redirect:"follow",...V,body:H1(V)};z=new Request(B,H);for(let N of S.request.fns)if(N)z=await N(z,V);let A=V.fetch;W=await A(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?v6(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let T;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":T=await W[N]();break;case"json":{let U=await W.text();T=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(T);if(V.responseTransformer)T=await V.responseTransformer(T)}return V.responseStyle==="data"?T:{data:T,...D}}let _=await W.text(),q;try{q=JSON.parse(_)}catch{}throw q??_}catch(V){let B=V;for(let H of S.error.fns)if(H)B=await H(B,W,z,G);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(G)=>(J)=>Z({...J,method:G}),Y=(G)=>async(J)=>{let{opts:I,url:z}=await K(J);return f6({...I,body:I.body,method:G,onRequest:async(W,V)=>{let B=new Request(W,V);for(let H of S.request.fns)if(H)B=await H(B,I);return B},serializedBody:H1(I),url:z})};return{buildUrl:(G)=>T1({...O,...G}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:Y("CONNECT"),delete:Y("DELETE"),get:Y("GET"),head:Y("HEAD"),options:Y("OPTIONS"),patch:Y("PATCH"),post:Y("POST"),put:Y("PUT"),trace:Y("TRACE")},trace:X("TRACE")}};var u6=D1(Yj());class c6{client;constructor($){this.client=$?.client??u6}}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 H0 extends c6{static __registry=new d6;constructor($){super($);H0.__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 l6({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...G}){let J,I=Y??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,H=G.signal??new AbortController().signal;while(!0){if(H.aborted)break;B++;let A=G.headers instanceof Headers?G.headers:new Headers(G.headers);if(J!==void 0)A.set("Last-Event-ID",J);try{let D={redirect:"follow",...G,body:G.serializedBody,headers:A,signal:H},_=new Request(L,D);if($)_=await $(L,D);let N=await(G.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let T=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{T.cancel()}catch{}};H.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await T.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
`);let y=U.split(`
`);U=y.pop()??"";for(let a of y){let i=a.split(`
`),F=[],v;for(let R of i)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))v=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let m=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(m))V=m}let M,h=!1;if(F.length){let R=F.join(`
-`);try{M=JSON.parse(R),h=!0}catch{M=R}}if(h){if(S)await S(M);if(x)M=await x(M)}if(j?.({data:M,event:v,id:J,retry:V}),F.length)yield M}}}finally{H.removeEventListener("abort",g),T.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var $9=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},O9=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},j9=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},T0=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((Y)=>encodeURIComponent(Y))).join(O9(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=$9(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return kO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},kO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},R0=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let Y=[];Object.entries(S).forEach(([G,J])=>{Y=[...Y,G,$?J:encodeURIComponent(J)]});let L=Y.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=j9(x),X=Object.entries(S).map(([Y,L])=>kO({allowReserved:$,name:x==="deepObject"?`${j}[${Y}]`:Y,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var x9=/\{[^{}]+\}/g,S9=({path:$,url:O})=>{let j=O,x=O.match(x9);if(x)for(let S of x){let K=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))K=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let Y=$[Z];if(Y===void 0||Y===null)continue;if(Array.isArray(Y)){j=j.replace(S,T0({explode:K,name:Z,style:X,value:Y}));continue}if(typeof Y==="object"){j=j.replace(S,R0({explode:K,name:Z,style:X,value:Y,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${kO({name:Z,value:Y})}`);continue}let L=encodeURIComponent(X==="label"?`.${Y}`:Y);j=j.replace(S,L)}return j},l6=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=S9({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function D1($){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 r6=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 p6={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var a6=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let Y=T0({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(Y)S.push(Y)}else if(typeof Z==="object"){let Y=R0({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(Y)S.push(Y)}else{let Y=kO({allowReserved:X.allowReserved,name:K,value:Z});if(Y)S.push(Y)}}return S.join("&")}},i6=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},Z9=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function n6($){for(let O of $.security??[]){if(Z9($,O.name))continue;let j=await r6(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var _1=($)=>l6({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:a6($.querySerializer),url:$.url}),M1=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=_0($.headers,O.headers),j},X9=($)=>{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?X9(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class D0{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 s6=()=>({error:new D0,request:new D0,response:new D0}),K9=a6({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),Y9={"Content-Type":"application/json"},Qj=($={})=>({...p6,headers:Y9,parseAs:"auto",querySerializer:K9,...$});var C1=($={})=>{let O=M1(Qj(),$),j=()=>({...O}),x=(G)=>{return O=M1(O,G),j()},S=s6(),K=async(G)=>{let J={...O,...G,fetch:G.fetch??O.fetch??globalThis.fetch,headers:_0(O.headers,G.headers),serializedBody:void 0};if(J.security)await n6(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=_1(I);return{opts:I,url:z}},Z=async(G)=>{let J=G.throwOnError??O.throwOnError,I=G.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(G),H={redirect:"follow",...V,body:D1(V)};z=new Request(B,H);for(let N of S.request.fns)if(N)z=await N(z,V);let A=V.fetch;W=await A(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?i6(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let T;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":T=await W[N]();break;case"json":{let U=await W.text();T=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(T);if(V.responseTransformer)T=await V.responseTransformer(T)}return V.responseStyle==="data"?T:{data:T,...D}}let _=await W.text(),q;try{q=JSON.parse(_)}catch{}throw q??_}catch(V){let B=V;for(let H of S.error.fns)if(H)B=await H(B,W,z,G);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(G)=>(J)=>Z({...J,method:G}),Y=(G)=>async(J)=>{let{opts:I,url:z}=await K(J);return d6({...I,body:I.body,method:G,onRequest:async(W,V)=>{let B=new Request(W,V);for(let H of S.request.fns)if(H)B=await H(B,I);return B},serializedBody:D1(I),url:z})};return{buildUrl:(G)=>_1({...O,...G}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:Y("CONNECT"),delete:Y("DELETE"),get:Y("GET"),head:Y("HEAD"),options:Y("OPTIONS"),patch:Y("PATCH"),post:Y("POST"),put:Y("PUT"),trace:Y("TRACE")},trace:X("TRACE")}};var t6=C1(Qj());class e6{client;constructor($){this.client=$?.client??t6}}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 M0 extends e6{static __registry=new o6;constructor($){super($);M0.__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 $7({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...G}){let J,I=Y??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,H=G.signal??new AbortController().signal;while(!0){if(H.aborted)break;B++;let A=G.headers instanceof Headers?G.headers:new Headers(G.headers);if(J!==void 0)A.set("Last-Event-ID",J);try{let D={redirect:"follow",...G,body:G.serializedBody,headers:A,signal:H},_=new Request(L,D);if($)_=await $(L,D);let N=await(G.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let T=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{T.cancel()}catch{}};H.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await T.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
+`);try{M=JSON.parse(R),h=!0}catch{M=R}}if(h){if(S)await S(M);if(x)M=await x(M)}if(j?.({data:M,event:v,id:J,retry:V}),F.length)yield M}}}finally{H.removeEventListener("abort",g),T.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var O9=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},j9=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},x9=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},T0=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((Y)=>encodeURIComponent(Y))).join(j9(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=O9(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return kO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},kO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},R0=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let Y=[];Object.entries(S).forEach(([G,J])=>{Y=[...Y,G,$?J:encodeURIComponent(J)]});let L=Y.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=x9(x),X=Object.entries(S).map(([Y,L])=>kO({allowReserved:$,name:x==="deepObject"?`${j}[${Y}]`:Y,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var S9=/\{[^{}]+\}/g,Z9=({path:$,url:O})=>{let j=O,x=O.match(S9);if(x)for(let S of x){let K=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))K=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let Y=$[Z];if(Y===void 0||Y===null)continue;if(Array.isArray(Y)){j=j.replace(S,T0({explode:K,name:Z,style:X,value:Y}));continue}if(typeof Y==="object"){j=j.replace(S,R0({explode:K,name:Z,style:X,value:Y,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${kO({name:Z,value:Y})}`);continue}let L=encodeURIComponent(X==="label"?`.${Y}`:Y);j=j.replace(S,L)}return j},r6=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=Z9({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function _1($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var p6=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var a6={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var i6=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let Y=T0({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(Y)S.push(Y)}else if(typeof Z==="object"){let Y=R0({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(Y)S.push(Y)}else{let Y=kO({allowReserved:X.allowReserved,name:K,value:Z});if(Y)S.push(Y)}}return S.join("&")}},n6=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},X9=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function s6($){for(let O of $.security??[]){if(X9($,O.name))continue;let j=await p6(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var M1=($)=>r6({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:i6($.querySerializer),url:$.url}),C1=($,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},K9=($)=>{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?K9(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class D0{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 D0,request:new D0,response:new D0}),Y9=i6({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),Q9={"Content-Type":"application/json"},Qj=($={})=>({...a6,headers:Q9,parseAs:"auto",querySerializer:Y9,...$});var P1=($={})=>{let O=C1(Qj(),$),j=()=>({...O}),x=(G)=>{return O=C1(O,G),j()},S=t6(),K=async(G)=>{let J={...O,...G,fetch:G.fetch??O.fetch??globalThis.fetch,headers:_0(O.headers,G.headers),serializedBody:void 0};if(J.security)await s6(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let I=J,z=M1(I);return{opts:I,url:z}},Z=async(G)=>{let J=G.throwOnError??O.throwOnError,I=G.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(G),H={redirect:"follow",...V,body:_1(V)};z=new Request(B,H);for(let N of S.request.fns)if(N)z=await N(z,V);let A=V.fetch;W=await A(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?n6(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let T;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":T=await W[N]();break;case"json":{let U=await W.text();T=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(T);if(V.responseTransformer)T=await V.responseTransformer(T)}return V.responseStyle==="data"?T:{data:T,...D}}let _=await W.text(),q;try{q=JSON.parse(_)}catch{}throw q??_}catch(V){let B=V;for(let H of S.error.fns)if(H)B=await H(B,W,z,G);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(G)=>(J)=>Z({...J,method:G}),Y=(G)=>async(J)=>{let{opts:I,url:z}=await K(J);return l6({...I,body:I.body,method:G,onRequest:async(W,V)=>{let B=new Request(W,V);for(let H of S.request.fns)if(H)B=await H(B,I);return B},serializedBody:_1(I),url:z})};return{buildUrl:(G)=>M1({...O,...G}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:Y("CONNECT"),delete:Y("DELETE"),get:Y("GET"),head:Y("HEAD"),options:Y("OPTIONS"),patch:Y("PATCH"),post:Y("POST"),put:Y("PUT"),trace:Y("TRACE")},trace:X("TRACE")}};var e6=P1(Qj());class o6{client;constructor($){this.client=$?.client??e6}}class $7{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class M0 extends o6{static __registry=new $7;constructor($){super($);M0.__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 O7({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...G}){let J,I=Y??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,H=G.signal??new AbortController().signal;while(!0){if(H.aborted)break;B++;let A=G.headers instanceof Headers?G.headers:new Headers(G.headers);if(J!==void 0)A.set("Last-Event-ID",J);try{let D={redirect:"follow",...G,body:G.serializedBody,headers:A,signal:H},_=new Request(L,D);if($)_=await $(L,D);let N=await(G.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let T=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{T.cancel()}catch{}};H.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await T.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
`);let y=U.split(`
`);U=y.pop()??"";for(let a of y){let i=a.split(`
`),F=[],v;for(let R of i)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))v=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let m=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(m))V=m}let M,h=!1;if(F.length){let R=F.join(`
-`);try{M=JSON.parse(R),h=!0}catch{M=R}}if(h){if(S)await S(M);if(x)M=await x(M)}if(j?.({data:M,event:v,id:J,retry:V}),F.length)yield M}}}finally{H.removeEventListener("abort",g),T.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var Q9=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},G9=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},J9=($)=>{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((Y)=>encodeURIComponent(Y))).join(G9(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=Q9(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return gO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},gO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},P0=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let Y=[];Object.entries(S).forEach(([G,J])=>{Y=[...Y,G,$?J:encodeURIComponent(J)]});let L=Y.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=J9(x),X=Object.entries(S).map(([Y,L])=>gO({allowReserved:$,name:x==="deepObject"?`${j}[${Y}]`:Y,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var V9=/\{[^{}]+\}/g,W9=({path:$,url:O})=>{let j=O,x=O.match(V9);if(x)for(let S of x){let K=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))K=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let Y=$[Z];if(Y===void 0||Y===null)continue;if(Array.isArray(Y)){j=j.replace(S,C0({explode:K,name:Z,style:X,value:Y}));continue}if(typeof Y==="object"){j=j.replace(S,P0({explode:K,name:Z,style:X,value:Y,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${gO({name:Z,value:Y})}`);continue}let L=encodeURIComponent(X==="label"?`.${Y}`:Y);j=j.replace(S,L)}return j},O7=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=W9({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function P1($){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 j7=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var x7={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var S7=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let Y=C0({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(Y)S.push(Y)}else if(typeof Z==="object"){let Y=P0({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(Y)S.push(Y)}else{let Y=gO({allowReserved:X.allowReserved,name:K,value:Z});if(Y)S.push(Y)}}return S.join("&")}},Z7=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},B9=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function X7($){for(let O of $.security??[]){if(B9($,O.name))continue;let j=await j7(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var A1=($)=>O7({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:S7($.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=F0($.headers,O.headers),j},L9=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},F0=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?L9(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class A0{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 K7=()=>({error:new A0,request:new A0,response:new A0}),N9=S7({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),U9={"Content-Type":"application/json"},Gj=($={})=>({...x7,headers:U9,parseAs:"auto",querySerializer:N9,...$});var E1=($={})=>{let O=F1(Gj(),$),j=()=>({...O}),x=(G)=>{return O=F1(O,G),j()},S=K7(),K=async(G)=>{let J={...O,...G,fetch:G.fetch??O.fetch??globalThis.fetch,headers:F0(O.headers,G.headers),serializedBody:void 0};if(J.security)await X7(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let I=J,z=A1(I);return{opts:I,url:z}},Z=async(G)=>{let J=G.throwOnError??O.throwOnError,I=G.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(G),H={redirect:"follow",...V,body:P1(V)};z=new Request(B,H);for(let N of S.request.fns)if(N)z=await N(z,V);let A=V.fetch;W=await A(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?Z7(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let T;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":T=await W[N]();break;case"json":{let U=await W.text();T=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(T);if(V.responseTransformer)T=await V.responseTransformer(T)}return V.responseStyle==="data"?T:{data:T,...D}}let _=await W.text(),q;try{q=JSON.parse(_)}catch{}throw q??_}catch(V){let B=V;for(let H of S.error.fns)if(H)B=await H(B,W,z,G);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(G)=>(J)=>Z({...J,method:G}),Y=(G)=>async(J)=>{let{opts:I,url:z}=await K(J);return $7({...I,body:I.body,method:G,onRequest:async(W,V)=>{let B=new Request(W,V);for(let H of S.request.fns)if(H)B=await H(B,I);return B},serializedBody:P1(I),url:z})};return{buildUrl:(G)=>A1({...O,...G}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:Y("CONNECT"),delete:Y("DELETE"),get:Y("GET"),head:Y("HEAD"),options:Y("OPTIONS"),patch:Y("PATCH"),post:Y("POST"),put:Y("PUT"),trace:Y("TRACE")},trace:X("TRACE")}};var Y7=E1(Gj());class Q7{client;constructor($){this.client=$?.client??Y7}}class G7{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 E0 extends Q7{static __registry=new G7;constructor($){super($);E0.__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 J7=($,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 q1={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)=>J7(O,j,S));else J7(O,j,x)}),O}},w1={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};function V7({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...G}){let J,I=Y??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,H=G.signal??new AbortController().signal;while(!0){if(H.aborted)break;B++;let A=G.headers instanceof Headers?G.headers:new Headers(G.headers);if(J!==void 0)A.set("Last-Event-ID",J);try{let D={redirect:"follow",...G,body:G.serializedBody,headers:A,signal:H},_=new Request(L,D);if($)_=await $(L,D);let N=await(G.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let T=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{T.cancel()}catch{}};H.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await T.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
+`);try{M=JSON.parse(R),h=!0}catch{M=R}}if(h){if(S)await S(M);if(x)M=await x(M)}if(j?.({data:M,event:v,id:J,retry:V}),F.length)yield M}}}finally{H.removeEventListener("abort",g),T.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var G9=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},J9=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},V9=($)=>{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((Y)=>encodeURIComponent(Y))).join(J9(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=G9(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return gO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},gO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},P0=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let Y=[];Object.entries(S).forEach(([G,J])=>{Y=[...Y,G,$?J:encodeURIComponent(J)]});let L=Y.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=V9(x),X=Object.entries(S).map(([Y,L])=>gO({allowReserved:$,name:x==="deepObject"?`${j}[${Y}]`:Y,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var W9=/\{[^{}]+\}/g,B9=({path:$,url:O})=>{let j=O,x=O.match(W9);if(x)for(let S of x){let K=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))K=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let Y=$[Z];if(Y===void 0||Y===null)continue;if(Array.isArray(Y)){j=j.replace(S,C0({explode:K,name:Z,style:X,value:Y}));continue}if(typeof Y==="object"){j=j.replace(S,P0({explode:K,name:Z,style:X,value:Y,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${gO({name:Z,value:Y})}`);continue}let L=encodeURIComponent(X==="label"?`.${Y}`:Y);j=j.replace(S,L)}return j},j7=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=B9({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 x7=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 S7={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var Z7=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let Y=C0({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(Y)S.push(Y)}else if(typeof Z==="object"){let Y=P0({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(Y)S.push(Y)}else{let Y=gO({allowReserved:X.allowReserved,name:K,value:Z});if(Y)S.push(Y)}}return S.join("&")}},X7=($)=>{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},L9=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function K7($){for(let O of $.security??[]){if(L9($,O.name))continue;let j=await x7(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 F1=($)=>j7({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:Z7($.querySerializer),url:$.url}),E1=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=F0($.headers,O.headers),j},N9=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},F0=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?N9(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class A0{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 Y7=()=>({error:new A0,request:new A0,response:new A0}),U9=Z7({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),z9={"Content-Type":"application/json"},Gj=($={})=>({...S7,headers:z9,parseAs:"auto",querySerializer:U9,...$});var q1=($={})=>{let O=E1(Gj(),$),j=()=>({...O}),x=(G)=>{return O=E1(O,G),j()},S=Y7(),K=async(G)=>{let J={...O,...G,fetch:G.fetch??O.fetch??globalThis.fetch,headers:F0(O.headers,G.headers),serializedBody:void 0};if(J.security)await K7(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=F1(I);return{opts:I,url:z}},Z=async(G)=>{let J=G.throwOnError??O.throwOnError,I=G.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(G),H={redirect:"follow",...V,body:A1(V)};z=new Request(B,H);for(let N of S.request.fns)if(N)z=await N(z,V);let A=V.fetch;W=await A(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?X7(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let T;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":T=await W[N]();break;case"json":{let U=await W.text();T=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(T);if(V.responseTransformer)T=await V.responseTransformer(T)}return V.responseStyle==="data"?T:{data:T,...D}}let _=await W.text(),q;try{q=JSON.parse(_)}catch{}throw q??_}catch(V){let B=V;for(let H of S.error.fns)if(H)B=await H(B,W,z,G);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(G)=>(J)=>Z({...J,method:G}),Y=(G)=>async(J)=>{let{opts:I,url:z}=await K(J);return O7({...I,body:I.body,method:G,onRequest:async(W,V)=>{let B=new Request(W,V);for(let H of S.request.fns)if(H)B=await H(B,I);return B},serializedBody:A1(I),url:z})};return{buildUrl:(G)=>F1({...O,...G}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:Y("CONNECT"),delete:Y("DELETE"),get:Y("GET"),head:Y("HEAD"),options:Y("OPTIONS"),patch:Y("PATCH"),post:Y("POST"),put:Y("PUT"),trace:Y("TRACE")},trace:X("TRACE")}};var Q7=q1(Gj());class G7{client;constructor($){this.client=$?.client??Q7}}class J7{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class E0 extends G7{static __registry=new J7;constructor($){super($);E0.__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 V7=($,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 w1={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)=>V7(O,j,S));else V7(O,j,x)}),O}},f1={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};function W7({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...G}){let J,I=Y??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,H=G.signal??new AbortController().signal;while(!0){if(H.aborted)break;B++;let A=G.headers instanceof Headers?G.headers:new Headers(G.headers);if(J!==void 0)A.set("Last-Event-ID",J);try{let D={redirect:"follow",...G,body:G.serializedBody,headers:A,signal:H},_=new Request(L,D);if($)_=await $(L,D);let N=await(G.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let T=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{T.cancel()}catch{}};H.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await T.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
`);let y=U.split(`
`);U=y.pop()??"";for(let a of y){let i=a.split(`
`),F=[],v;for(let R of i)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))v=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let m=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(m))V=m}let M,h=!1;if(F.length){let R=F.join(`
-`);try{M=JSON.parse(R),h=!0}catch{M=R}}if(h){if(S)await S(M);if(x)M=await x(M)}if(j?.({data:M,event:v,id:J,retry:V}),F.length)yield M}}}finally{H.removeEventListener("abort",g),T.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var z9=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},I9=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},H9=($)=>{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((Y)=>encodeURIComponent(Y))).join(I9(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=z9(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return yO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},yO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},w0=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let Y=[];Object.entries(S).forEach(([G,J])=>{Y=[...Y,G,$?J:encodeURIComponent(J)]});let L=Y.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=H9(x),X=Object.entries(S).map(([Y,L])=>yO({allowReserved:$,name:x==="deepObject"?`${j}[${Y}]`:Y,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var T9=/\{[^{}]+\}/g,R9=({path:$,url:O})=>{let j=O,x=O.match(T9);if(x)for(let S of x){let K=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))K=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let Y=$[Z];if(Y===void 0||Y===null)continue;if(Array.isArray(Y)){j=j.replace(S,q0({explode:K,name:Z,style:X,value:Y}));continue}if(typeof Y==="object"){j=j.replace(S,w0({explode:K,name:Z,style:X,value:Y,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${yO({name:Z,value:Y})}`);continue}let L=encodeURIComponent(X==="label"?`.${Y}`:Y);j=j.replace(S,L)}return j},W7=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=R9({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function f1($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var B7=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 L7=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let Y=q0({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(Y)S.push(Y)}else if(typeof Z==="object"){let Y=w0({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(Y)S.push(Y)}else{let Y=yO({allowReserved:X.allowReserved,name:K,value:Z});if(Y)S.push(Y)}}return S.join("&")}},N7=($)=>{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},D9=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function U7($){for(let O of $.security??[]){if(D9($,O.name))continue;let j=await B7(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=($)=>W7({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:L7($.querySerializer),url:$.url}),k1=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=b0($.headers,O.headers),j},_9=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},b0=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?_9(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class f0{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var z7=()=>({error:new f0,request:new f0,response:new f0}),M9=L7({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),C9={"Content-Type":"application/json"},Jj=($={})=>({...w1,headers:C9,parseAs:"auto",querySerializer:M9,...$});var Vj=($={})=>{let O=k1(Jj(),$),j=()=>({...O}),x=(G)=>{return O=k1(O,G),j()},S=z7(),K=async(G)=>{let J={...O,...G,fetch:G.fetch??O.fetch??globalThis.fetch,headers:b0(O.headers,G.headers),serializedBody:void 0};if(J.security)await U7(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let I=J,z=b1(I);return{opts:I,url:z}},Z=async(G)=>{let J=G.throwOnError??O.throwOnError,I=G.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(G),H={redirect:"follow",...V,body:f1(V)};z=new Request(B,H);for(let N of S.request.fns)if(N)z=await N(z,V);let A=V.fetch;W=await A(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?N7(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let T;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":T=await W[N]();break;case"json":{let U=await W.text();T=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(T);if(V.responseTransformer)T=await V.responseTransformer(T)}return V.responseStyle==="data"?T:{data:T,...D}}let _=await W.text(),q;try{q=JSON.parse(_)}catch{}throw q??_}catch(V){let B=V;for(let H of S.error.fns)if(H)B=await H(B,W,z,G);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(G)=>(J)=>Z({...J,method:G}),Y=(G)=>async(J)=>{let{opts:I,url:z}=await K(J);return V7({...I,body:I.body,method:G,onRequest:async(W,V)=>{let B=new Request(W,V);for(let H of S.request.fns)if(H)B=await H(B,I);return B},serializedBody:f1(I),url:z})};return{buildUrl:(G)=>b1({...O,...G}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:Y("CONNECT"),delete:Y("DELETE"),get:Y("GET"),head:Y("HEAD"),options:Y("OPTIONS"),patch:Y("PATCH"),post:Y("POST"),put:Y("PUT"),trace:Y("TRACE")},trace:X("TRACE")}};var I7=Vj(Jj());class H7{client;constructor($){this.client=$?.client??I7}}class T7{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class k0 extends H7{static __registry=new T7;constructor($){super($);k0.__registry.set(this,$?.key)}listAgents($){return($?.client??this.client).get({url:"/agents",...$})}createAgent($){return($.client??this.client).post({url:"/agents",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateAgent($){return($.client??this.client).put({url:"/agents/{agent_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteAnchor($){return($.client??this.client).delete({url:"/annotations/anchors",...$,headers:{"Content-Type":"application/json",...$.headers}})}editAnchor($){return($.client??this.client).patch({url:"/annotations/anchors",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDocumentAnchors($){return($.client??this.client).get({url:"/annotations/anchors/document/{document_id}",...$})}createAnchor($){return($.client??this.client).post({url:"/annotations/anchors/document/{document_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getSelfBot($){return($?.client??this.client).get({url:"/bots/me",...$})}getBotOwnerProfiles($){return($?.client??this.client).get({url:"/bots/profiles",...$})}listBotChannels($){return($.client??this.client).get({url:"/bots/{bot_id}/channels",...$})}removeBotFromChannelByBot($){return($.client??this.client).delete({url:"/bots/{bot_id}/channels/{channel_id}",...$})}listOccurrences($){return($.client??this.client).get({url:"/calendar-events",...$})}mentionPreviews($){return($.client??this.client).post({url:"/calendar-events/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}listTeamCalendar($){return($.client??this.client).get({url:"/calendar-events/team",...$})}listTeamOutOfOffice($){return($.client??this.client).get({url:"/calendar-events/team-out-of-office",...$})}eventIcs($){return($.client??this.client).get({url:"/calendar-events/{event_id}/ics",...$})}listJoinRequests($){return($.client??this.client).get({url:"/calendar-events/{event_id}/join-requests",...$})}requestToJoin($){return($.client??this.client).post({url:"/calendar-events/{event_id}/join-requests",...$})}getActiveCalls($){return($?.client??this.client).get({url:"/call/active",...$})}guestCallChatRead($){return($.client??this.client).get({url:"/call/guest-chat/{call_id}",...$})}guestCallChatPost($){return($.client??this.client).post({url:"/call/guest-chat/{call_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}meetingLookup($){return($.client??this.client).get({url:"/call/join/{token}",...$})}meetingGuestJoin($){return($.client??this.client).post({url:"/call/join/{token}",...$,headers:{"Content-Type":"application/json",...$.headers}})}meetingLeave($){return($.client??this.client).post({url:"/call/join/{token}/leave",...$})}meetingGuestParticipants($){return($.client??this.client).get({url:"/call/join/{token}/participants",...$})}meetingList($){return($?.client??this.client).get({url:"/call/meetings",...$})}meetingCreate($){return($.client??this.client).post({url:"/call/meetings",...$,headers:{"Content-Type":"application/json",...$.headers}})}meetingListActive($){return($?.client??this.client).get({url:"/call/meetings/active",...$})}meetingInvitePermissions($){return($.client??this.client).get({url:"/call/meetings/invite/{token}",...$})}meetingInvite($){return($.client??this.client).post({url:"/call/meetings/invite/{token}",...$,headers:{"Content-Type":"application/json",...$.headers}})}meetingInviteUsers($){return($.client??this.client).post({url:"/call/meetings/invite/{token}/users",...$,headers:{"Content-Type":"application/json",...$.headers}})}meetingJoin($){return($.client??this.client).post({url:"/call/meetings/join/{token}",...$})}meetingParticipants($){return($.client??this.client).get({url:"/call/meetings/join/{token}/participants",...$})}meetingPrepare($){return($?.client??this.client).post({url:"/call/meetings/prepare",...$})}meetingCancelPreparation($){return($.client??this.client).delete({url:"/call/meetings/prepare/{preparation_id}",...$})}meetingCancel($){return($.client??this.client).delete({url:"/call/meetings/{meeting_id}",...$})}meetingUpdate($){return($.client??this.client).patch({url:"/call/meetings/{meeting_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getBatchCallRecordPreview($){return($.client??this.client).post({url:"/call/record/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteCallRecord($){return($.client??this.client).delete({url:"/call/record/{call_id}",...$})}getCallRecord($){return($.client??this.client).get({url:"/call/record/{call_id}",...$})}editCallRecord($){return($.client??this.client).patch({url:"/call/record/{call_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}declineCall($){return($.client??this.client).post({url:"/call/record/{call_id}/decline",...$})}meetingShare($){return($.client??this.client).post({url:"/call/record/{call_id}/link",...$})}toggleShareWithTeam($){return($.client??this.client).post({url:"/call/record/{call_id}/share-with-team/toggle",...$})}editCallTranscript($){return($.client??this.client).patch({url:"/call/record/{call_id}/transcript",...$,headers:{"Content-Type":"application/json",...$.headers}})}getRingStatus($){return($.client??this.client).get({url:"/call/ring-status/{call_id}",...$})}declineRing($){return($.client??this.client).post({url:"/call/ring-status/{call_id}/decline",...$})}callWebhook($){return($?.client??this.client).post({url:"/call/webhook",...$})}leaveOrEndCall($){return($.client??this.client).delete({url:"/call/{channel_id}",...$})}getOrCreateCall($){return($.client??this.client).get({url:"/call/{channel_id}",...$})}checkActiveCall($){return($.client??this.client).get({url:"/call/{channel_id}/active",...$})}ingestTranscript($){return($.client??this.client).post({url:"/call/{room_name}/transcript",...$,headers:{"Content-Type":"application/json",...$.headers}})}listChannelLabels($){return($?.client??this.client).get({url:"/channel-labels",...$})}createChannelLabel($){return($.client??this.client).post({url:"/channel-labels",...$,headers:{"Content-Type":"application/json",...$.headers}})}setChannelLabel($){return($.client??this.client).put({url:"/channel-labels/channels/{channel_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}previewSmartTag($){return($.client??this.client).post({url:"/channel-labels/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteChannelLabel($){return($.client??this.client).delete({url:"/channel-labels/{label_id}",...$})}renameChannelLabel($){return($.client??this.client).patch({url:"/channel-labels/{label_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}createChannel($){return($.client??this.client).post({url:"/channels",...$,headers:{"Content-Type":"application/json",...$.headers}})}getActivity($){return($?.client??this.client).get({url:"/channels/activity",...$})}postActivity($){return($.client??this.client).post({url:"/channels/activity",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAttachmentReferences($){return($.client??this.client).get({url:"/channels/attachments/{entity_type}/{entity_id}/references",...$})}getOrCreateDm($){return($.client??this.client).post({url:"/channels/get_or_create_dm",...$,headers:{"Content-Type":"application/json",...$.headers}})}getOrCreatePrivate($){return($.client??this.client).post({url:"/channels/get_or_create_private",...$,headers:{"Content-Type":"application/json",...$.headers}})}joinChannelByCode($){return($.client??this.client).post({url:"/channels/join/{join_code}",...$})}createEntityMention($){return($.client??this.client).post({url:"/channels/mentions",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteEntityMention($){return($.client??this.client).delete({url:"/channels/mentions/{mention_id}",...$})}getBatchChannelPreview($){return($.client??this.client).post({url:"/channels/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteChannel($){return($.client??this.client).delete({url:"/channels/{channel_id}",...$})}getChannel($){return($.client??this.client).get({url:"/channels/{channel_id}",...$})}patchChannel($){return($.client??this.client).patch({url:"/channels/{channel_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getChannelAttachments($){return($.client??this.client).get({url:"/channels/{channel_id}/attachments",...$})}createChannelScopedBot($){return($.client??this.client).post({url:"/channels/{channel_id}/bots/scoped",...$,headers:{"Content-Type":"application/json",...$.headers}})}joinChannel($){return($.client??this.client).post({url:"/channels/{channel_id}/join",...$})}getChannelJoinLink($){return($.client??this.client).get({url:"/channels/{channel_id}/join-link",...$})}leaveChannel($){return($.client??this.client).post({url:"/channels/{channel_id}/leave",...$})}removeParticipants($){return($.client??this.client).delete({url:"/channels/{channel_id}/participants",...$,headers:{"Content-Type":"application/json",...$.headers}})}getChannelParticipants($){return($.client??this.client).get({url:"/channels/{channel_id}/participants",...$})}addParticipants($){return($.client??this.client).post({url:"/channels/{channel_id}/participants",...$,headers:{"Content-Type":"application/json",...$.headers}})}setChannelPicture($){return($.client??this.client).put({url:"/channels/{channel_id}/profile_picture",...$,headers:{"Content-Type":"application/json",...$.headers}})}postChannelBotWebhook($){return($.client??this.client).post({url:"/channels/{channel_id}/webhook",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteCollabSurface($){return($.client??this.client).delete({url:"/collab_surfaces/{id}",...$})}getCollabSurface($){return($.client??this.client).get({url:"/collab_surfaces/{id}",...$})}ensureCollabSurface($){return($.client??this.client).put({url:"/collab_surfaces/{id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}createCollabSurfaceToken($){return($.client??this.client).post({url:"/collab_surfaces/{id}/token",...$})}getChannels($){return($?.client??this.client).get({url:"/comms/channels",...$})}listCrmBlockedDomains($){return($?.client??this.client).get({url:"/crm/blocked-domains",...$})}unblockCrmDomain($){return($.client??this.client).delete({url:"/crm/blocked-domains/{domain}",...$})}blockCrmDomain($){return($.client??this.client).put({url:"/crm/blocked-domains/{domain}",...$})}createCrmCompany($){return($.client??this.client).post({url:"/crm/companies",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCompany($){return($.client??this.client).get({url:"/crm/companies/{company_id}",...$})}listCompanyContacts($){return($.client??this.client).get({url:"/crm/companies/{company_id}/contacts",...$})}createCrmContact($){return($.client??this.client).post({url:"/crm/companies/{company_id}/contacts",...$,headers:{"Content-Type":"application/json",...$.headers}})}setEmailSync($){return($.client??this.client).put({url:"/crm/companies/{company_id}/email-sync",...$,headers:{"Content-Type":"application/json",...$.headers}})}setCompanyHidden($){return($.client??this.client).put({url:"/crm/companies/{company_id}/hidden",...$,headers:{"Content-Type":"application/json",...$.headers}})}setCrmCompanyName($){return($.client??this.client).put({url:"/crm/companies/{company_id}/name",...$,headers:{"Content-Type":"application/json",...$.headers}})}searchContacts($){return($?.client??this.client).get({url:"/crm/contacts",...$})}createCrmTeamContact($){return($.client??this.client).post({url:"/crm/contacts",...$,headers:{"Content-Type":"application/json",...$.headers}})}getContactByEmail($){return($.client??this.client).get({url:"/crm/contacts/by-email",...$})}getContact($){return($.client??this.client).get({url:"/crm/contacts/{contact_id}",...$})}setContactHidden($){return($.client??this.client).put({url:"/crm/contacts/{contact_id}/hidden",...$,headers:{"Content-Type":"application/json",...$.headers}})}setCrmContactName($){return($.client??this.client).put({url:"/crm/contacts/{contact_id}/name",...$,headers:{"Content-Type":"application/json",...$.headers}})}listCrmPipelines($){return($?.client??this.client).get({url:"/crm/pipelines",...$})}createCrmPipeline($){return($.client??this.client).post({url:"/crm/pipelines",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCrmPipeline($){return($.client??this.client).get({url:"/crm/pipelines/{id}",...$})}renameCrmPipeline($){return($.client??this.client).put({url:"/crm/pipelines/{id}/name",...$,headers:{"Content-Type":"application/json",...$.headers}})}applyCrmPipelineOps($){return($.client??this.client).post({url:"/crm/pipelines/{id}/ops",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCrmPipelinePermissions($){return($.client??this.client).get({url:"/crm/pipelines/{id}/permissions",...$})}updateCrmPipelinePermissions($){return($.client??this.client).patch({url:"/crm/pipelines/{id}/permissions",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCrmPipelineRows($){return($.client??this.client).get({url:"/crm/pipelines/{id}/rows",...$})}queryCrmPipelineRows($){return($.client??this.client).post({url:"/crm/pipelines/{id}/rows",...$,headers:{"Content-Type":"application/json",...$.headers}})}shareCrmPipeline($){return($.client??this.client).put({url:"/crm/pipelines/{id}/sharing",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCrmPipelineTable($){return($.client??this.client).get({url:"/crm/pipelines/{id}/table",...$})}trashCrmPipeline($){return($.client??this.client).put({url:"/crm/pipelines/{id}/trash",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCrmTeamSettings($){return($?.client??this.client).get({url:"/crm/settings",...$})}putCrmTeamSettings($){return($.client??this.client).put({url:"/crm/settings",...$,headers:{"Content-Type":"application/json",...$.headers}})}resetCrmTeamStages($){return($?.client??this.client).delete({url:"/crm/stages",...$})}putCrmTeamStages($){return($.client??this.client).put({url:"/crm/stages",...$,headers:{"Content-Type":"application/json",...$.headers}})}listDatabases($){return($?.client??this.client).get({url:"/databases",...$})}createDatabase($){return($.client??this.client).post({url:"/databases",...$,headers:{"Content-Type":"application/json",...$.headers}})}saveDatabaseQuery($){return($.client??this.client).post({url:"/databases/queries",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDatabaseQuery($){return($.client??this.client).get({url:"/databases/queries/{query_id}",...$})}queryDatabases($){return($.client??this.client).post({url:"/databases/query",...$,headers:{"Content-Type":"application/json",...$.headers}})}ensureStarterHandler($){return($?.client??this.client).post({url:"/databases/starter",...$})}deliverDatabaseWebhook($){return($.client??this.client).post({url:"/databases/webhooks/{token}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDatabase($){return($.client??this.client).get({url:"/databases/{id}",...$})}shareDatabaseAwareness($){return($.client??this.client).put({url:"/databases/{id}/awareness",...$,headers:{"Content-Type":"application/json",...$.headers}})}undoDatabaseChange($){return($.client??this.client).post({url:"/databases/{id}/changes/{change}/undo",...$})}duplicateDatabase($){return($.client??this.client).post({url:"/databases/{id}/duplicate",...$,headers:{"Content-Type":"application/json",...$.headers}})}importDatabaseTable($){return($.client??this.client).post({url:"/databases/{id}/import",...$,headers:{"Content-Type":"application/json",...$.headers}})}applyDatabaseOps($){return($.client??this.client).post({url:"/databases/{id}/ops",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDatabasePermissions($){return($.client??this.client).get({url:"/databases/{id}/permissions",...$})}updateDatabasePermissions($){return($.client??this.client).patch({url:"/databases/{id}/permissions",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDatabaseTableChanges($){return($.client??this.client).get({url:"/databases/{id}/tables/{table_id}/changes",...$})}listDatabaseColumnCasts($){return($.client??this.client).get({url:"/databases/{id}/tables/{table_id}/columns/{column_id}/casts",...$})}convertDatabaseColumn($){return($.client??this.client).post({url:"/databases/{id}/tables/{table_id}/columns/{column_id}/conversion",...$,headers:{"Content-Type":"application/json",...$.headers}})}inferDatabaseColumnType($){return($.client??this.client).post({url:"/databases/{id}/tables/{table_id}/columns/{column_id}/infer-type",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDatabaseRowHistory($){return($.client??this.client).get({url:"/databases/{id}/tables/{table_id}/rows/{row_id}/history",...$})}getDatabaseViewPositions($){return($.client??this.client).get({url:"/databases/{id}/views/{view_id}/positions",...$})}listDatabaseWebhooks($){return($.client??this.client).get({url:"/databases/{id}/webhooks",...$})}createDatabaseWebhook($){return($.client??this.client).post({url:"/databases/{id}/webhooks",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteDatabaseWebhook($){return($.client??this.client).delete({url:"/databases/{id}/webhooks/{webhook_id}",...$})}transcribeDictation($){return($.client??this.client).post({bodySerializer:null,url:"/dictation/transcribe",...$,headers:{"Content-Type":"audio/webm",...$.headers}})}getUserDocumentsHandler($){return($.client??this.client).get({url:"/documents",...$})}createDocument($){return($.client??this.client).post({url:"/documents",...$,headers:{"Content-Type":"application/json",...$.headers}})}createCanvasHandler($){return($.client??this.client).post({url:"/documents/create_canvas",...$,headers:{"Content-Type":"application/json",...$.headers}})}createMarkdownHandler($){return($.client??this.client).post({url:"/documents/create_markdown",...$,headers:{"Content-Type":"application/json",...$.headers}})}createSkillHandler($){return($.client??this.client).post({url:"/documents/create_skill",...$,headers:{"Content-Type":"application/json",...$.headers}})}createSnippetHandler($){return($.client??this.client).post({url:"/documents/create_snippet",...$,headers:{"Content-Type":"application/json",...$.headers}})}createTaskHandler($){return($.client??this.client).post({url:"/documents/create_task",...$,headers:{"Content-Type":"application/json",...$.headers}})}getGithubPullRequestTasks($){return($.client??this.client).post({url:"/documents/github_prs/tasks",...$,headers:{"Content-Type":"application/json",...$.headers}})}initializeUserDocuments($){return($?.client??this.client).post({url:"/documents/initialize_user_documents",...$})}getDocumentListHandler($){return($?.client??this.client).get({url:"/documents/list",...$})}validateDocumentPermissionsToken($){return($.client??this.client).post({url:"/documents/permissions_token/validate",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDocumentPermissionsToken($){return($.client??this.client).post({url:"/documents/permissions_token/{document_id}",...$})}presaveDocumentHandler($){return($.client??this.client).put({url:"/documents/presave/{document_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getBatchPreviewHandler($){return($.client??this.client).post({url:"/documents/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}taskSimilaritySearchHandler($){return($.client??this.client).post({url:"/documents/similarity_search",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDocumentByTeamSlug($){return($.client??this.client).get({url:"/documents/slug/{slug}",...$})}handler($){return($?.client??this.client).get({url:"/documents/starter_docs",...$})}getSystemSkillsHandler($){return($?.client??this.client).get({url:"/documents/system_skills",...$})}deleteDocument($){return($.client??this.client).delete({url:"/documents/{document_id}",...$})}getDocument($){return($.client??this.client).get({url:"/documents/{document_id}",...$})}editDocument($){return($.client??this.client).patch({url:"/documents/{document_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}saveDocumentHandler($){return($.client??this.client).put({url:"/documents/{document_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDocumentBranchName($){return($.client??this.client).get({url:"/documents/{document_id}/branch_name",...$})}copyDocument($){return($.client??this.client).post({url:"/documents/{document_id}/copy",...$,headers:{"Content-Type":"application/json",...$.headers}})}exportDocument($){return($.client??this.client).get({url:"/documents/{document_id}/export",...$})}getDocumentGithubPullRequests($){return($.client??this.client).get({url:"/documents/{document_id}/github_prs",...$})}getLocationHandler($){return($.client??this.client).get({url:"/documents/{document_id}/location",...$})}getDocumentLocationV3($){return($.client??this.client).get({url:"/documents/{document_id}/location_v3",...$})}permanentlyDeleteDocument($){return($.client??this.client).delete({url:"/documents/{document_id}/permanent",...$})}getDocumentProcessingResult($){return($.client??this.client).get({url:"/documents/{document_id}/processing",...$})}jobProcessingResultHandler($){return($.client??this.client).get({url:"/documents/{document_id}/processing/{job_id}",...$})}revertDeleteDocument($){return($.client??this.client).put({url:"/documents/{document_id}/revert_delete",...$})}getDocumentShortId($){return($.client??this.client).get({url:"/documents/{document_id}/short_id",...$})}simpleSave($){return($.client??this.client).put({url:"/documents/{document_id}/simple_save",...$})}getDocumentTeamShare($){return($.client??this.client).get({url:"/documents/{document_id}/team_share",...$})}setDocumentTeamShare($){return($.client??this.client).put({url:"/documents/{document_id}/team_share",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDocumentTextContent($){return($.client??this.client).get({url:"/documents/{document_id}/text-content",...$})}getDocumentViewsHandler($){return($.client??this.client).get({url:"/documents/{document_id}/views",...$})}getDocumentVersion($){return($.client??this.client).get({url:"/documents/{document_id}/{document_version_id}",...$})}accessRequestsState($){return($.client??this.client).get({url:"/entities/{entity_type}/{entity_id}/access-requests",...$})}accessRequestsCancel($){return($.client??this.client).delete({url:"/entities/{entity_type}/{entity_id}/access-requests/mine",...$})}accessRequestsSubmit($){return($.client??this.client).put({url:"/entities/{entity_type}/{entity_id}/access-requests/mine",...$,headers:{"Content-Type":"application/json",...$.headers}})}accessRequestsResolve($){return($.client??this.client).post({url:"/entities/{entity_type}/{entity_id}/access-requests/{request_id}/resolve",...$,headers:{"Content-Type":"application/json",...$.headers}})}accessRequestsDirect($){return($.client??this.client).get({url:"/entities/{entity_type}/{entity_id}/direct-access",...$})}accessRequestsRemoveDirect($){return($.client??this.client).delete({url:"/entities/{entity_type}/{entity_id}/direct-access/{user_id}",...$})}accessRequestsSetDirect($){return($.client??this.client).put({url:"/entities/{entity_type}/{entity_id}/direct-access/{user_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getEntityPermission($){return($.client??this.client).get({url:"/entity/{entity_type}/{entity_id}/permissions",...$})}externalChats($){return($?.client??this.client).get({url:"/external-chats",...$})}externalChatAdd($){return($.client??this.client).post({url:"/external-chats",...$,headers:{"Content-Type":"application/json",...$.headers}})}externalChatRemove($){return($.client??this.client).delete({url:"/external-chats/{chat_id}",...$})}externalChat($){return($.client??this.client).get({url:"/external-chats/{chat_id}",...$})}externalChatUpload($){return($.client??this.client).post({...q1,url:"/external-chats/{chat_id}/attachments",...$,headers:{"Content-Type":null,...$.headers}})}externalChatDelivery($){return($.client??this.client).post({url:"/external-chats/{chat_id}/delivery",...$,headers:{"Content-Type":"application/json",...$.headers}})}externalChatMessages($){return($.client??this.client).get({url:"/external-chats/{chat_id}/messages",...$})}externalChatMessageAttachments($){return($.client??this.client).post({url:"/external-chats/{chat_id}/messages/attachments",...$,headers:{"Content-Type":"application/json",...$.headers}})}externalChatMessage($){return($.client??this.client).get({url:"/external-chats/{chat_id}/messages/{message_id}",...$})}externalChatPermissions($){return($.client??this.client).get({url:"/external-chats/{chat_id}/permissions",...$})}externalChatUpdatePermissions($){return($.client??this.client).patch({url:"/external-chats/{chat_id}/permissions",...$,headers:{"Content-Type":"application/json",...$.headers}})}externalChatRead($){return($.client??this.client).post({url:"/external-chats/{chat_id}/read",...$,headers:{"Content-Type":"application/json",...$.headers}})}externalChatSends($){return($.client??this.client).get({url:"/external-chats/{chat_id}/sends",...$})}externalChatSend($){return($.client??this.client).post({url:"/external-chats/{chat_id}/sends",...$,headers:{"Content-Type":"application/json",...$.headers}})}listFavorites($){return($?.client??this.client).get({url:"/favorites",...$})}addFavorite($){return($.client??this.client).post({url:"/favorites",...$,headers:{"Content-Type":"application/json",...$.headers}})}reorderFavorites($){return($.client??this.client).patch({url:"/favorites/reorder",...$,headers:{"Content-Type":"application/json",...$.headers}})}removeFavoriteByEntity($){return($.client??this.client).delete({url:"/favorites/{entity_type}/{entity_id}",...$})}getForeignEntityBySource($){return($.client??this.client).get({url:"/foreign_entity/by_source/{source}/{foreign_entity_id}",...$})}getForeignEntity($){return($.client??this.client).get({url:"/foreign_entity/{id}",...$})}listForms($){return($.client??this.client).get({url:"/forms",...$})}createForm($){return($.client??this.client).post({url:"/forms",...$,headers:{"Content-Type":"application/json",...$.headers}})}listAccessibleForms($){return($?.client??this.client).get({url:"/forms/accessible",...$})}getForm($){return($.client??this.client).get({url:"/forms/{id}",...$})}updateForm($){return($.client??this.client).patch({url:"/forms/{id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}collaborateForm($){return($.client??this.client).post({url:"/forms/{id}/collaboration",...$})}putFormLayout($){return($.client??this.client).put({url:"/forms/{id}/layout",...$,headers:{"Content-Type":"application/json",...$.headers}})}getFormPermissions($){return($.client??this.client).get({url:"/forms/{id}/permissions",...$})}updateFormPermissions($){return($.client??this.client).patch({url:"/forms/{id}/permissions",...$,headers:{"Content-Type":"application/json",...$.headers}})}submitFormResponse($){return($.client??this.client).post({url:"/forms/{id}/responses",...$,headers:{"Content-Type":"application/json",...$.headers}})}getMyFormResponse($){return($.client??this.client).get({url:"/forms/{id}/responses/mine",...$})}editMyFormResponse($){return($.client??this.client).put({url:"/forms/{id}/responses/mine",...$,headers:{"Content-Type":"application/json",...$.headers}})}getFormResponseSummary($){return($.client??this.client).get({url:"/forms/{id}/responses/summary",...$})}getFormTally($){return($.client??this.client).get({url:"/forms/{id}/tally",...$})}installSync($){return($?.client??this.client).get({url:"/github/install-sync",...$})}getGithubPullRequestFacets($){return($?.client??this.client).get({url:"/github_pull_requests/facets",...$})}getGithubPullRequest($){return($.client??this.client).get({url:"/github_pull_requests/{id}",...$})}getGithubPullRequestChanges($){return($.client??this.client).get({url:"/github_pull_requests/{id}/changes",...$})}getGithubPullRequestChangesPatch($){return($.client??this.client).get({url:"/github_pull_requests/{id}/changes/patch",...$})}createHarnessPairing($){return($.client??this.client).post({url:"/harness-pairings",...$,headers:{"Content-Type":"application/json",...$.headers}})}getHarnessPairing($){return($.client??this.client).get({url:"/harness-pairings/{code}",...$})}approveHarnessPairing($){return($.client??this.client).post({url:"/harness-pairings/{code}/approve",...$,headers:{"Content-Type":"application/json",...$.headers}})}claimHarnessPairing($){return($.client??this.client).post({url:"/harness-pairings/{pairing_id}/claim",...$,headers:{"Content-Type":"application/json",...$.headers}})}listHarnesses($){return($?.client??this.client).get({url:"/harnesses",...$})}deleteSelfHarness($){return($?.client??this.client).delete({url:"/harnesses/me",...$})}getSelfHarness($){return($?.client??this.client).get({url:"/harnesses/me",...$})}listHarnessAgents($){return($?.client??this.client).get({url:"/harnesses/me/agents",...$})}listHarnessSessions($){return($?.client??this.client).get({url:"/harnesses/me/sessions",...$})}deleteHarness($){return($.client??this.client).delete({url:"/harnesses/{harness_id}",...$})}healthHandler($){return($?.client??this.client).get({url:"/health",...$})}getHistoryHandler($){return($?.client??this.client).get({url:"/history",...$})}deleteHistoryHandler($){return($.client??this.client).delete({url:"/history/{item_type}/{item_id}",...$})}upsertHistoryHandler($){return($.client??this.client).post({url:"/history/{item_type}/{item_id}",...$})}listInitiatives($){return($?.client??this.client).get({url:"/initiatives",...$})}createInitiative($){return($.client??this.client).post({url:"/initiatives",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteInitiative($){return($.client??this.client).delete({url:"/initiatives/{initiative_id}",...$})}getInitiative($){return($.client??this.client).get({url:"/initiatives/{initiative_id}",...$})}updateInitiative($){return($.client??this.client).patch({url:"/initiatives/{initiative_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getInstructionsHandler($){return($?.client??this.client).get({url:"/instructions",...$})}createInstructionsHandler($){return($?.client??this.client).post({url:"/instructions",...$})}getItemsSoup($){return($?.client??this.client).get({url:"/items/soup",...$})}postItemsSoup($){return($.client??this.client).post({url:"/items/soup",...$,headers:{"Content-Type":"application/json",...$.headers}})}postItemsSoupAst($){return($.client??this.client).post({url:"/items/soup/ast",...$,headers:{"Content-Type":"application/json",...$.headers}})}postItemsSoupAstGrouped($){return($.client??this.client).post({url:"/items/soup/ast/grouped",...$,headers:{"Content-Type":"application/json",...$.headers}})}messageTimeline($){return($.client??this.client).get({url:"/messages/{parent_type}/{parent_id}",...$})}entityMessageCreate($){return($.client??this.client).post({url:"/messages/{parent_type}/{parent_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}entityMessageDeleteMessage($){return($.client??this.client).delete({url:"/messages/{parent_type}/{parent_id}/items/{id}",...$})}entityMessageGetMessage($){return($.client??this.client).get({url:"/messages/{parent_type}/{parent_id}/items/{id}",...$})}entityMessageEdit($){return($.client??this.client).patch({url:"/messages/{parent_type}/{parent_id}/items/{id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}entityMessageReact($){return($.client??this.client).post({url:"/messages/{parent_type}/{parent_id}/items/{id}/reactions",...$,headers:{"Content-Type":"application/json",...$.headers}})}entityMessageLegacy($){return($.client??this.client).get({url:"/messages/{parent_type}/{parent_id}/legacy/{legacy_id}",...$})}entityMessageDeleteThread($){return($.client??this.client).delete({url:"/messages/{parent_type}/{parent_id}/threads/{id}",...$})}entityMessageGetThread($){return($.client??this.client).get({url:"/messages/{parent_type}/{parent_id}/threads/{id}",...$})}entityMessagePatchThread($){return($.client??this.client).patch({url:"/messages/{parent_type}/{parent_id}/threads/{id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}messageTimelineEntries($){return($.client??this.client).get({url:"/messages/{parent_type}/{parent_id}/timeline",...$})}entityMessageTyping($){return($.client??this.client).post({url:"/messages/{parent_type}/{parent_id}/typing",...$,headers:{"Content-Type":"application/json",...$.headers}})}getPinsHandler($){return($?.client??this.client).get({url:"/pins",...$})}reorderPinsHandler($){return($.client??this.client).patch({url:"/pins",...$,headers:{"Content-Type":"application/json",...$.headers}})}removePinHandler($){return($.client??this.client).delete({url:"/pins/{pinned_item_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}addPinHandler($){return($.client??this.client).post({url:"/pins/{pinned_item_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getProjectsHandler($){return($?.client??this.client).get({url:"/projects",...$})}createProjectHandler($){return($.client??this.client).post({url:"/projects",...$,headers:{"Content-Type":"application/json",...$.headers}})}getPendingProjectsHandler($){return($?.client??this.client).get({url:"/projects/pending",...$})}getBatchProjectPreview($){return($.client??this.client).post({url:"/projects/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}uploadFolderHandler($){return($.client??this.client).post({url:"/projects/upload",...$,headers:{"Content-Type":"application/json",...$.headers}})}uploadExtractFolderHandler($){return($.client??this.client).post({url:"/projects/upload_extract",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteProjectHandler($){return($.client??this.client).delete({url:"/projects/{id}",...$})}getProjectHandler($){return($.client??this.client).get({url:"/projects/{id}",...$})}getProjectUserAccessLevel($){return($.client??this.client).get({url:"/projects/{id}/access_level",...$})}getProjectContentHandler($){return($.client??this.client).get({url:"/projects/{id}/content",...$})}permanentlyDeleteProject($){return($.client??this.client).delete({url:"/projects/{id}/permanent",...$})}getProjectPermissionsV2($){return($.client??this.client).get({url:"/projects/{id}/permissions",...$})}revertDeleteProject($){return($.client??this.client).put({url:"/projects/{id}/revert_delete",...$})}recentlyDeleted($){return($?.client??this.client).get({url:"/recents/deleted",...$})}listEmailReminders($){return($?.client??this.client).get({url:"/reminders/email/collection",...$})}getEmailFollowup($){return($.client??this.client).get({url:"/reminders/email/{thread_id}",...$})}setEmailFollowup($){return($.client??this.client).put({url:"/reminders/email/{thread_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getViewsHandler($){return($?.client??this.client).get({url:"/saved_views",...$})}createViewHandler($){return($.client??this.client).post({url:"/saved_views",...$,headers:{"Content-Type":"application/json",...$.headers}})}excludeDefaultViewHandler($){return($.client??this.client).post({url:"/saved_views/exclude_default",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteViewHandler($){return($.client??this.client).delete({url:"/saved_views/{saved_view_id}",...$})}patchViewHandler($){return($.client??this.client).patch({url:"/saved_views/{saved_view_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}listSlackImports($){return($?.client??this.client).get({url:"/slack/imports",...$})}createSlackImport($){return($.client??this.client).post({url:"/slack/imports",...$,headers:{"Content-Type":"application/json",...$.headers}})}getSlackImport($){return($.client??this.client).get({url:"/slack/imports/{job_id}",...$})}cancelSlackImport($){return($.client??this.client).post({url:"/slack/imports/{job_id}/cancel",...$})}finalizeSlackImport($){return($.client??this.client).post({url:"/slack/imports/{job_id}/finalize",...$})}registerSlackImportUploads($){return($.client??this.client).post({url:"/slack/imports/{job_id}/uploads",...$,headers:{"Content-Type":"application/json",...$.headers}})}completeSlackImportUploads($){return($.client??this.client).post({url:"/slack/imports/{job_id}/uploads/complete",...$,headers:{"Content-Type":"application/json",...$.headers}})}bulkWakeupSyncServiceDocuments($){return($.client??this.client).post({url:"/sync_service/wakeup",...$,headers:{"Content-Type":"application/json",...$.headers}})}editThreadV2($){return($.client??this.client).patch({url:"/threads/{thread_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}listUserApiKeys($){return($?.client??this.client).get({url:"/user-api-keys",...$})}createUserApiKey($){return($.client??this.client).post({url:"/user-api-keys",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteUserApiKey($){return($.client??this.client).delete({url:"/user-api-keys/{id}",...$})}deleteUserDocumentViewLocation($){return($.client??this.client).delete({url:"/user_document_view_location/{document_id}",...$})}getUserDocumentViewLocation($){return($.client??this.client).get({url:"/user_document_view_location/{document_id}",...$})}upsertUserDocumentViewLocation($){return($.client??this.client).post({url:"/user_document_view_location/{document_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDocumentPermissionsV2($){return($.client??this.client).get({url:"/v2/documents/{document_id}/permissions",...$})}editProjectV2($){return($.client??this.client).patch({url:"/v2/projects/{id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}streamEvents($){return($.client??this.client).sse.get({url:"/webhook/events/stream",...$})}listWebhooks($){return($?.client??this.client).get({url:"/webhook/webhooks",...$})}createWebhook($){return($.client??this.client).post({url:"/webhook/webhooks",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteWebhook($){return($.client??this.client).delete({url:"/webhook/webhooks/{webhook_id}",...$})}getWebhook($){return($.client??this.client).get({url:"/webhook/webhooks/{webhook_id}",...$})}patchWebhook($){return($.client??this.client).patch({url:"/webhook/webhooks/{webhook_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}validateWebhook($){return($.client??this.client).post({url:"/webhook/webhooks/{webhook_id}/validate",...$})}whatsappAccount($){return($?.client??this.client).get({url:"/whatsapp/account",...$})}whatsappChats($){return($?.client??this.client).get({url:"/whatsapp/chats",...$})}whatsappConnect($){return($.client??this.client).post({url:"/whatsapp/connect",...$,headers:{"Content-Type":"application/json",...$.headers}})}whatsappDisconnect($){return($.client??this.client).post({url:"/whatsapp/disconnect",...$,headers:{"Content-Type":"application/json",...$.headers}})}whatsappImportHistory($){return($?.client??this.client).post({url:"/whatsapp/history-import",...$})}whatsappStartLookup($){return($.client??this.client).post({url:"/whatsapp/lookups",...$,headers:{"Content-Type":"application/json",...$.headers}})}whatsappLookup($){return($.client??this.client).get({url:"/whatsapp/lookups/{id}",...$})}whatsappCancelPairing($){return($.client??this.client).delete({url:"/whatsapp/pairing/{id}",...$})}whatsappPairing($){return($.client??this.client).get({url:"/whatsapp/pairing/{id}",...$})}whatsappPasskey($){return($.client??this.client).post({url:"/whatsapp/pairing/{id}/passkey",...$,headers:{"Content-Type":"application/json",...$.headers}})}}function R7({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...G}){let J,I=Y??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,H=G.signal??new AbortController().signal;while(!0){if(H.aborted)break;B++;let A=G.headers instanceof Headers?G.headers:new Headers(G.headers);if(J!==void 0)A.set("Last-Event-ID",J);try{let D={redirect:"follow",...G,body:G.serializedBody,headers:A,signal:H},_=new Request(L,D);if($)_=await $(L,D);let N=await(G.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let T=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{T.cancel()}catch{}};H.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await T.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
+`);try{M=JSON.parse(R),h=!0}catch{M=R}}if(h){if(S)await S(M);if(x)M=await x(M)}if(j?.({data:M,event:v,id:J,retry:V}),F.length)yield M}}}finally{H.removeEventListener("abort",g),T.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var I9=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},H9=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},T9=($)=>{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((Y)=>encodeURIComponent(Y))).join(H9(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=I9(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return yO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},yO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},w0=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let Y=[];Object.entries(S).forEach(([G,J])=>{Y=[...Y,G,$?J:encodeURIComponent(J)]});let L=Y.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=T9(x),X=Object.entries(S).map(([Y,L])=>yO({allowReserved:$,name:x==="deepObject"?`${j}[${Y}]`:Y,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var R9=/\{[^{}]+\}/g,D9=({path:$,url:O})=>{let j=O,x=O.match(R9);if(x)for(let S of x){let K=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))K=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let Y=$[Z];if(Y===void 0||Y===null)continue;if(Array.isArray(Y)){j=j.replace(S,q0({explode:K,name:Z,style:X,value:Y}));continue}if(typeof Y==="object"){j=j.replace(S,w0({explode:K,name:Z,style:X,value:Y,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${yO({name:Z,value:Y})}`);continue}let L=encodeURIComponent(X==="label"?`.${Y}`:Y);j=j.replace(S,L)}return j},B7=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=D9({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function b1($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var L7=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 N7=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let Y=q0({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(Y)S.push(Y)}else if(typeof Z==="object"){let Y=w0({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(Y)S.push(Y)}else{let Y=yO({allowReserved:X.allowReserved,name:K,value:Z});if(Y)S.push(Y)}}return S.join("&")}},U7=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},_9=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function z7($){for(let O of $.security??[]){if(_9($,O.name))continue;let j=await L7(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var k1=($)=>B7({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:N7($.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=b0($.headers,O.headers),j},M9=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},b0=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?M9(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class f0{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var I7=()=>({error:new f0,request:new f0,response:new f0}),C9=N7({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),P9={"Content-Type":"application/json"},Jj=($={})=>({...f1,headers:P9,parseAs:"auto",querySerializer:C9,...$});var Vj=($={})=>{let O=g1(Jj(),$),j=()=>({...O}),x=(G)=>{return O=g1(O,G),j()},S=I7(),K=async(G)=>{let J={...O,...G,fetch:G.fetch??O.fetch??globalThis.fetch,headers:b0(O.headers,G.headers),serializedBody:void 0};if(J.security)await z7(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let I=J,z=k1(I);return{opts:I,url:z}},Z=async(G)=>{let J=G.throwOnError??O.throwOnError,I=G.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(G),H={redirect:"follow",...V,body:b1(V)};z=new Request(B,H);for(let N of S.request.fns)if(N)z=await N(z,V);let A=V.fetch;W=await A(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?U7(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let T;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":T=await W[N]();break;case"json":{let U=await W.text();T=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(T);if(V.responseTransformer)T=await V.responseTransformer(T)}return V.responseStyle==="data"?T:{data:T,...D}}let _=await W.text(),q;try{q=JSON.parse(_)}catch{}throw q??_}catch(V){let B=V;for(let H of S.error.fns)if(H)B=await H(B,W,z,G);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(G)=>(J)=>Z({...J,method:G}),Y=(G)=>async(J)=>{let{opts:I,url:z}=await K(J);return W7({...I,body:I.body,method:G,onRequest:async(W,V)=>{let B=new Request(W,V);for(let H of S.request.fns)if(H)B=await H(B,I);return B},serializedBody:b1(I),url:z})};return{buildUrl:(G)=>k1({...O,...G}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:Y("CONNECT"),delete:Y("DELETE"),get:Y("GET"),head:Y("HEAD"),options:Y("OPTIONS"),patch:Y("PATCH"),post:Y("POST"),put:Y("PUT"),trace:Y("TRACE")},trace:X("TRACE")}};var H7=Vj(Jj());class T7{client;constructor($){this.client=$?.client??H7}}class R7{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class k0 extends T7{static __registry=new R7;constructor($){super($);k0.__registry.set(this,$?.key)}listAgents($){return($?.client??this.client).get({url:"/agents",...$})}createAgent($){return($.client??this.client).post({url:"/agents",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateAgent($){return($.client??this.client).put({url:"/agents/{agent_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteAnchor($){return($.client??this.client).delete({url:"/annotations/anchors",...$,headers:{"Content-Type":"application/json",...$.headers}})}editAnchor($){return($.client??this.client).patch({url:"/annotations/anchors",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDocumentAnchors($){return($.client??this.client).get({url:"/annotations/anchors/document/{document_id}",...$})}createAnchor($){return($.client??this.client).post({url:"/annotations/anchors/document/{document_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getSelfBot($){return($?.client??this.client).get({url:"/bots/me",...$})}getBotOwnerProfiles($){return($?.client??this.client).get({url:"/bots/profiles",...$})}listBotChannels($){return($.client??this.client).get({url:"/bots/{bot_id}/channels",...$})}removeBotFromChannelByBot($){return($.client??this.client).delete({url:"/bots/{bot_id}/channels/{channel_id}",...$})}listOccurrences($){return($.client??this.client).get({url:"/calendar-events",...$})}mentionPreviews($){return($.client??this.client).post({url:"/calendar-events/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}listTeamCalendar($){return($.client??this.client).get({url:"/calendar-events/team",...$})}listTeamOutOfOffice($){return($.client??this.client).get({url:"/calendar-events/team-out-of-office",...$})}eventIcs($){return($.client??this.client).get({url:"/calendar-events/{event_id}/ics",...$})}listJoinRequests($){return($.client??this.client).get({url:"/calendar-events/{event_id}/join-requests",...$})}requestToJoin($){return($.client??this.client).post({url:"/calendar-events/{event_id}/join-requests",...$})}getActiveCalls($){return($?.client??this.client).get({url:"/call/active",...$})}guestCallChatRead($){return($.client??this.client).get({url:"/call/guest-chat/{call_id}",...$})}guestCallChatPost($){return($.client??this.client).post({url:"/call/guest-chat/{call_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}meetingLookup($){return($.client??this.client).get({url:"/call/join/{token}",...$})}meetingGuestJoin($){return($.client??this.client).post({url:"/call/join/{token}",...$,headers:{"Content-Type":"application/json",...$.headers}})}meetingLeave($){return($.client??this.client).post({url:"/call/join/{token}/leave",...$})}meetingGuestParticipants($){return($.client??this.client).get({url:"/call/join/{token}/participants",...$})}meetingList($){return($?.client??this.client).get({url:"/call/meetings",...$})}meetingCreate($){return($.client??this.client).post({url:"/call/meetings",...$,headers:{"Content-Type":"application/json",...$.headers}})}meetingListActive($){return($?.client??this.client).get({url:"/call/meetings/active",...$})}meetingInvitePermissions($){return($.client??this.client).get({url:"/call/meetings/invite/{token}",...$})}meetingInvite($){return($.client??this.client).post({url:"/call/meetings/invite/{token}",...$,headers:{"Content-Type":"application/json",...$.headers}})}meetingInviteUsers($){return($.client??this.client).post({url:"/call/meetings/invite/{token}/users",...$,headers:{"Content-Type":"application/json",...$.headers}})}meetingJoin($){return($.client??this.client).post({url:"/call/meetings/join/{token}",...$})}meetingParticipants($){return($.client??this.client).get({url:"/call/meetings/join/{token}/participants",...$})}meetingPrepare($){return($?.client??this.client).post({url:"/call/meetings/prepare",...$})}meetingCancelPreparation($){return($.client??this.client).delete({url:"/call/meetings/prepare/{preparation_id}",...$})}meetingCancel($){return($.client??this.client).delete({url:"/call/meetings/{meeting_id}",...$})}meetingUpdate($){return($.client??this.client).patch({url:"/call/meetings/{meeting_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getBatchCallRecordPreview($){return($.client??this.client).post({url:"/call/record/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteCallRecord($){return($.client??this.client).delete({url:"/call/record/{call_id}",...$})}getCallRecord($){return($.client??this.client).get({url:"/call/record/{call_id}",...$})}editCallRecord($){return($.client??this.client).patch({url:"/call/record/{call_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}declineCall($){return($.client??this.client).post({url:"/call/record/{call_id}/decline",...$})}meetingShare($){return($.client??this.client).post({url:"/call/record/{call_id}/link",...$})}toggleShareWithTeam($){return($.client??this.client).post({url:"/call/record/{call_id}/share-with-team/toggle",...$})}editCallTranscript($){return($.client??this.client).patch({url:"/call/record/{call_id}/transcript",...$,headers:{"Content-Type":"application/json",...$.headers}})}getRingStatus($){return($.client??this.client).get({url:"/call/ring-status/{call_id}",...$})}declineRing($){return($.client??this.client).post({url:"/call/ring-status/{call_id}/decline",...$})}callWebhook($){return($?.client??this.client).post({url:"/call/webhook",...$})}leaveOrEndCall($){return($.client??this.client).delete({url:"/call/{channel_id}",...$})}getOrCreateCall($){return($.client??this.client).get({url:"/call/{channel_id}",...$})}checkActiveCall($){return($.client??this.client).get({url:"/call/{channel_id}/active",...$})}ingestTranscript($){return($.client??this.client).post({url:"/call/{room_name}/transcript",...$,headers:{"Content-Type":"application/json",...$.headers}})}listChannelLabels($){return($?.client??this.client).get({url:"/channel-labels",...$})}createChannelLabel($){return($.client??this.client).post({url:"/channel-labels",...$,headers:{"Content-Type":"application/json",...$.headers}})}setChannelLabel($){return($.client??this.client).put({url:"/channel-labels/channels/{channel_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}previewSmartTag($){return($.client??this.client).post({url:"/channel-labels/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteChannelLabel($){return($.client??this.client).delete({url:"/channel-labels/{label_id}",...$})}renameChannelLabel($){return($.client??this.client).patch({url:"/channel-labels/{label_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}createChannel($){return($.client??this.client).post({url:"/channels",...$,headers:{"Content-Type":"application/json",...$.headers}})}getActivity($){return($?.client??this.client).get({url:"/channels/activity",...$})}postActivity($){return($.client??this.client).post({url:"/channels/activity",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAttachmentReferences($){return($.client??this.client).get({url:"/channels/attachments/{entity_type}/{entity_id}/references",...$})}getOrCreateDm($){return($.client??this.client).post({url:"/channels/get_or_create_dm",...$,headers:{"Content-Type":"application/json",...$.headers}})}getOrCreatePrivate($){return($.client??this.client).post({url:"/channels/get_or_create_private",...$,headers:{"Content-Type":"application/json",...$.headers}})}joinChannelByCode($){return($.client??this.client).post({url:"/channels/join/{join_code}",...$})}createEntityMention($){return($.client??this.client).post({url:"/channels/mentions",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteEntityMention($){return($.client??this.client).delete({url:"/channels/mentions/{mention_id}",...$})}getBatchChannelPreview($){return($.client??this.client).post({url:"/channels/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteChannel($){return($.client??this.client).delete({url:"/channels/{channel_id}",...$})}getChannel($){return($.client??this.client).get({url:"/channels/{channel_id}",...$})}patchChannel($){return($.client??this.client).patch({url:"/channels/{channel_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getChannelAttachments($){return($.client??this.client).get({url:"/channels/{channel_id}/attachments",...$})}createChannelScopedBot($){return($.client??this.client).post({url:"/channels/{channel_id}/bots/scoped",...$,headers:{"Content-Type":"application/json",...$.headers}})}joinChannel($){return($.client??this.client).post({url:"/channels/{channel_id}/join",...$})}getChannelJoinLink($){return($.client??this.client).get({url:"/channels/{channel_id}/join-link",...$})}leaveChannel($){return($.client??this.client).post({url:"/channels/{channel_id}/leave",...$})}removeParticipants($){return($.client??this.client).delete({url:"/channels/{channel_id}/participants",...$,headers:{"Content-Type":"application/json",...$.headers}})}getChannelParticipants($){return($.client??this.client).get({url:"/channels/{channel_id}/participants",...$})}addParticipants($){return($.client??this.client).post({url:"/channels/{channel_id}/participants",...$,headers:{"Content-Type":"application/json",...$.headers}})}setChannelPicture($){return($.client??this.client).put({url:"/channels/{channel_id}/profile_picture",...$,headers:{"Content-Type":"application/json",...$.headers}})}postChannelBotWebhook($){return($.client??this.client).post({url:"/channels/{channel_id}/webhook",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteCollabSurface($){return($.client??this.client).delete({url:"/collab_surfaces/{id}",...$})}getCollabSurface($){return($.client??this.client).get({url:"/collab_surfaces/{id}",...$})}ensureCollabSurface($){return($.client??this.client).put({url:"/collab_surfaces/{id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}createCollabSurfaceToken($){return($.client??this.client).post({url:"/collab_surfaces/{id}/token",...$})}getChannels($){return($?.client??this.client).get({url:"/comms/channels",...$})}listCrmBlockedDomains($){return($?.client??this.client).get({url:"/crm/blocked-domains",...$})}unblockCrmDomain($){return($.client??this.client).delete({url:"/crm/blocked-domains/{domain}",...$})}blockCrmDomain($){return($.client??this.client).put({url:"/crm/blocked-domains/{domain}",...$})}createCrmCompany($){return($.client??this.client).post({url:"/crm/companies",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCompany($){return($.client??this.client).get({url:"/crm/companies/{company_id}",...$})}listCompanyContacts($){return($.client??this.client).get({url:"/crm/companies/{company_id}/contacts",...$})}createCrmContact($){return($.client??this.client).post({url:"/crm/companies/{company_id}/contacts",...$,headers:{"Content-Type":"application/json",...$.headers}})}setEmailSync($){return($.client??this.client).put({url:"/crm/companies/{company_id}/email-sync",...$,headers:{"Content-Type":"application/json",...$.headers}})}setCompanyHidden($){return($.client??this.client).put({url:"/crm/companies/{company_id}/hidden",...$,headers:{"Content-Type":"application/json",...$.headers}})}setCrmCompanyName($){return($.client??this.client).put({url:"/crm/companies/{company_id}/name",...$,headers:{"Content-Type":"application/json",...$.headers}})}searchContacts($){return($?.client??this.client).get({url:"/crm/contacts",...$})}createCrmTeamContact($){return($.client??this.client).post({url:"/crm/contacts",...$,headers:{"Content-Type":"application/json",...$.headers}})}getContactByEmail($){return($.client??this.client).get({url:"/crm/contacts/by-email",...$})}getContact($){return($.client??this.client).get({url:"/crm/contacts/{contact_id}",...$})}setContactHidden($){return($.client??this.client).put({url:"/crm/contacts/{contact_id}/hidden",...$,headers:{"Content-Type":"application/json",...$.headers}})}setCrmContactName($){return($.client??this.client).put({url:"/crm/contacts/{contact_id}/name",...$,headers:{"Content-Type":"application/json",...$.headers}})}listCrmPipelines($){return($?.client??this.client).get({url:"/crm/pipelines",...$})}createCrmPipeline($){return($.client??this.client).post({url:"/crm/pipelines",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCrmPipeline($){return($.client??this.client).get({url:"/crm/pipelines/{id}",...$})}renameCrmPipeline($){return($.client??this.client).put({url:"/crm/pipelines/{id}/name",...$,headers:{"Content-Type":"application/json",...$.headers}})}applyCrmPipelineOps($){return($.client??this.client).post({url:"/crm/pipelines/{id}/ops",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCrmPipelinePermissions($){return($.client??this.client).get({url:"/crm/pipelines/{id}/permissions",...$})}updateCrmPipelinePermissions($){return($.client??this.client).patch({url:"/crm/pipelines/{id}/permissions",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCrmPipelineRows($){return($.client??this.client).get({url:"/crm/pipelines/{id}/rows",...$})}queryCrmPipelineRows($){return($.client??this.client).post({url:"/crm/pipelines/{id}/rows",...$,headers:{"Content-Type":"application/json",...$.headers}})}shareCrmPipeline($){return($.client??this.client).put({url:"/crm/pipelines/{id}/sharing",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCrmPipelineTable($){return($.client??this.client).get({url:"/crm/pipelines/{id}/table",...$})}trashCrmPipeline($){return($.client??this.client).put({url:"/crm/pipelines/{id}/trash",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCrmTeamSettings($){return($?.client??this.client).get({url:"/crm/settings",...$})}putCrmTeamSettings($){return($.client??this.client).put({url:"/crm/settings",...$,headers:{"Content-Type":"application/json",...$.headers}})}resetCrmTeamStages($){return($?.client??this.client).delete({url:"/crm/stages",...$})}putCrmTeamStages($){return($.client??this.client).put({url:"/crm/stages",...$,headers:{"Content-Type":"application/json",...$.headers}})}listDatabases($){return($?.client??this.client).get({url:"/databases",...$})}createDatabase($){return($.client??this.client).post({url:"/databases",...$,headers:{"Content-Type":"application/json",...$.headers}})}saveDatabaseQuery($){return($.client??this.client).post({url:"/databases/queries",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDatabaseQuery($){return($.client??this.client).get({url:"/databases/queries/{query_id}",...$})}queryDatabases($){return($.client??this.client).post({url:"/databases/query",...$,headers:{"Content-Type":"application/json",...$.headers}})}ensureStarterHandler($){return($?.client??this.client).post({url:"/databases/starter",...$})}deliverDatabaseWebhook($){return($.client??this.client).post({url:"/databases/webhooks/{token}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDatabase($){return($.client??this.client).get({url:"/databases/{id}",...$})}shareDatabaseAwareness($){return($.client??this.client).put({url:"/databases/{id}/awareness",...$,headers:{"Content-Type":"application/json",...$.headers}})}undoDatabaseChange($){return($.client??this.client).post({url:"/databases/{id}/changes/{change}/undo",...$})}duplicateDatabase($){return($.client??this.client).post({url:"/databases/{id}/duplicate",...$,headers:{"Content-Type":"application/json",...$.headers}})}importDatabaseTable($){return($.client??this.client).post({url:"/databases/{id}/import",...$,headers:{"Content-Type":"application/json",...$.headers}})}applyDatabaseOps($){return($.client??this.client).post({url:"/databases/{id}/ops",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDatabasePermissions($){return($.client??this.client).get({url:"/databases/{id}/permissions",...$})}updateDatabasePermissions($){return($.client??this.client).patch({url:"/databases/{id}/permissions",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDatabaseTableChanges($){return($.client??this.client).get({url:"/databases/{id}/tables/{table_id}/changes",...$})}listDatabaseColumnCasts($){return($.client??this.client).get({url:"/databases/{id}/tables/{table_id}/columns/{column_id}/casts",...$})}convertDatabaseColumn($){return($.client??this.client).post({url:"/databases/{id}/tables/{table_id}/columns/{column_id}/conversion",...$,headers:{"Content-Type":"application/json",...$.headers}})}inferDatabaseColumnType($){return($.client??this.client).post({url:"/databases/{id}/tables/{table_id}/columns/{column_id}/infer-type",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDatabaseRowHistory($){return($.client??this.client).get({url:"/databases/{id}/tables/{table_id}/rows/{row_id}/history",...$})}getDatabaseViewPositions($){return($.client??this.client).get({url:"/databases/{id}/views/{view_id}/positions",...$})}listDatabaseWebhooks($){return($.client??this.client).get({url:"/databases/{id}/webhooks",...$})}createDatabaseWebhook($){return($.client??this.client).post({url:"/databases/{id}/webhooks",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteDatabaseWebhook($){return($.client??this.client).delete({url:"/databases/{id}/webhooks/{webhook_id}",...$})}transcribeDictation($){return($.client??this.client).post({bodySerializer:null,url:"/dictation/transcribe",...$,headers:{"Content-Type":"audio/webm",...$.headers}})}getUserDocumentsHandler($){return($.client??this.client).get({url:"/documents",...$})}createDocument($){return($.client??this.client).post({url:"/documents",...$,headers:{"Content-Type":"application/json",...$.headers}})}createCanvasHandler($){return($.client??this.client).post({url:"/documents/create_canvas",...$,headers:{"Content-Type":"application/json",...$.headers}})}createMarkdownHandler($){return($.client??this.client).post({url:"/documents/create_markdown",...$,headers:{"Content-Type":"application/json",...$.headers}})}createSkillHandler($){return($.client??this.client).post({url:"/documents/create_skill",...$,headers:{"Content-Type":"application/json",...$.headers}})}createSnippetHandler($){return($.client??this.client).post({url:"/documents/create_snippet",...$,headers:{"Content-Type":"application/json",...$.headers}})}createTaskHandler($){return($.client??this.client).post({url:"/documents/create_task",...$,headers:{"Content-Type":"application/json",...$.headers}})}getGithubPullRequestTasks($){return($.client??this.client).post({url:"/documents/github_prs/tasks",...$,headers:{"Content-Type":"application/json",...$.headers}})}initializeUserDocuments($){return($?.client??this.client).post({url:"/documents/initialize_user_documents",...$})}getDocumentListHandler($){return($?.client??this.client).get({url:"/documents/list",...$})}validateDocumentPermissionsToken($){return($.client??this.client).post({url:"/documents/permissions_token/validate",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDocumentPermissionsToken($){return($.client??this.client).post({url:"/documents/permissions_token/{document_id}",...$})}presaveDocumentHandler($){return($.client??this.client).put({url:"/documents/presave/{document_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getBatchPreviewHandler($){return($.client??this.client).post({url:"/documents/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}taskSimilaritySearchHandler($){return($.client??this.client).post({url:"/documents/similarity_search",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDocumentByTeamSlug($){return($.client??this.client).get({url:"/documents/slug/{slug}",...$})}handler($){return($?.client??this.client).get({url:"/documents/starter_docs",...$})}getSystemSkillsHandler($){return($?.client??this.client).get({url:"/documents/system_skills",...$})}deleteDocument($){return($.client??this.client).delete({url:"/documents/{document_id}",...$})}getDocument($){return($.client??this.client).get({url:"/documents/{document_id}",...$})}editDocument($){return($.client??this.client).patch({url:"/documents/{document_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}saveDocumentHandler($){return($.client??this.client).put({url:"/documents/{document_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDocumentBranchName($){return($.client??this.client).get({url:"/documents/{document_id}/branch_name",...$})}copyDocument($){return($.client??this.client).post({url:"/documents/{document_id}/copy",...$,headers:{"Content-Type":"application/json",...$.headers}})}exportDocument($){return($.client??this.client).get({url:"/documents/{document_id}/export",...$})}getDocumentGithubPullRequests($){return($.client??this.client).get({url:"/documents/{document_id}/github_prs",...$})}getLocationHandler($){return($.client??this.client).get({url:"/documents/{document_id}/location",...$})}getDocumentLocationV3($){return($.client??this.client).get({url:"/documents/{document_id}/location_v3",...$})}permanentlyDeleteDocument($){return($.client??this.client).delete({url:"/documents/{document_id}/permanent",...$})}getDocumentProcessingResult($){return($.client??this.client).get({url:"/documents/{document_id}/processing",...$})}jobProcessingResultHandler($){return($.client??this.client).get({url:"/documents/{document_id}/processing/{job_id}",...$})}revertDeleteDocument($){return($.client??this.client).put({url:"/documents/{document_id}/revert_delete",...$})}getDocumentShortId($){return($.client??this.client).get({url:"/documents/{document_id}/short_id",...$})}simpleSave($){return($.client??this.client).put({url:"/documents/{document_id}/simple_save",...$})}getDocumentTeamShare($){return($.client??this.client).get({url:"/documents/{document_id}/team_share",...$})}setDocumentTeamShare($){return($.client??this.client).put({url:"/documents/{document_id}/team_share",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDocumentTextContent($){return($.client??this.client).get({url:"/documents/{document_id}/text-content",...$})}getDocumentViewsHandler($){return($.client??this.client).get({url:"/documents/{document_id}/views",...$})}getDocumentVersion($){return($.client??this.client).get({url:"/documents/{document_id}/{document_version_id}",...$})}accessRequestsState($){return($.client??this.client).get({url:"/entities/{entity_type}/{entity_id}/access-requests",...$})}accessRequestsCancel($){return($.client??this.client).delete({url:"/entities/{entity_type}/{entity_id}/access-requests/mine",...$})}accessRequestsSubmit($){return($.client??this.client).put({url:"/entities/{entity_type}/{entity_id}/access-requests/mine",...$,headers:{"Content-Type":"application/json",...$.headers}})}accessRequestsResolve($){return($.client??this.client).post({url:"/entities/{entity_type}/{entity_id}/access-requests/{request_id}/resolve",...$,headers:{"Content-Type":"application/json",...$.headers}})}accessRequestsDirect($){return($.client??this.client).get({url:"/entities/{entity_type}/{entity_id}/direct-access",...$})}accessRequestsRemoveDirect($){return($.client??this.client).delete({url:"/entities/{entity_type}/{entity_id}/direct-access/{user_id}",...$})}accessRequestsSetDirect($){return($.client??this.client).put({url:"/entities/{entity_type}/{entity_id}/direct-access/{user_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getEntityPermission($){return($.client??this.client).get({url:"/entity/{entity_type}/{entity_id}/permissions",...$})}externalChats($){return($?.client??this.client).get({url:"/external-chats",...$})}externalChatAdd($){return($.client??this.client).post({url:"/external-chats",...$,headers:{"Content-Type":"application/json",...$.headers}})}externalChatRemove($){return($.client??this.client).delete({url:"/external-chats/{chat_id}",...$})}externalChat($){return($.client??this.client).get({url:"/external-chats/{chat_id}",...$})}externalChatUpload($){return($.client??this.client).post({...w1,url:"/external-chats/{chat_id}/attachments",...$,headers:{"Content-Type":null,...$.headers}})}externalChatDelivery($){return($.client??this.client).post({url:"/external-chats/{chat_id}/delivery",...$,headers:{"Content-Type":"application/json",...$.headers}})}externalChatMessages($){return($.client??this.client).get({url:"/external-chats/{chat_id}/messages",...$})}externalChatMessageAttachments($){return($.client??this.client).post({url:"/external-chats/{chat_id}/messages/attachments",...$,headers:{"Content-Type":"application/json",...$.headers}})}externalChatMessage($){return($.client??this.client).get({url:"/external-chats/{chat_id}/messages/{message_id}",...$})}externalChatPermissions($){return($.client??this.client).get({url:"/external-chats/{chat_id}/permissions",...$})}externalChatUpdatePermissions($){return($.client??this.client).patch({url:"/external-chats/{chat_id}/permissions",...$,headers:{"Content-Type":"application/json",...$.headers}})}externalChatRead($){return($.client??this.client).post({url:"/external-chats/{chat_id}/read",...$,headers:{"Content-Type":"application/json",...$.headers}})}externalChatSends($){return($.client??this.client).get({url:"/external-chats/{chat_id}/sends",...$})}externalChatSend($){return($.client??this.client).post({url:"/external-chats/{chat_id}/sends",...$,headers:{"Content-Type":"application/json",...$.headers}})}listFavorites($){return($?.client??this.client).get({url:"/favorites",...$})}addFavorite($){return($.client??this.client).post({url:"/favorites",...$,headers:{"Content-Type":"application/json",...$.headers}})}reorderFavorites($){return($.client??this.client).patch({url:"/favorites/reorder",...$,headers:{"Content-Type":"application/json",...$.headers}})}removeFavoriteByEntity($){return($.client??this.client).delete({url:"/favorites/{entity_type}/{entity_id}",...$})}getForeignEntityBySource($){return($.client??this.client).get({url:"/foreign_entity/by_source/{source}/{foreign_entity_id}",...$})}getForeignEntity($){return($.client??this.client).get({url:"/foreign_entity/{id}",...$})}listForms($){return($.client??this.client).get({url:"/forms",...$})}createForm($){return($.client??this.client).post({url:"/forms",...$,headers:{"Content-Type":"application/json",...$.headers}})}listAccessibleForms($){return($?.client??this.client).get({url:"/forms/accessible",...$})}getForm($){return($.client??this.client).get({url:"/forms/{id}",...$})}updateForm($){return($.client??this.client).patch({url:"/forms/{id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}collaborateForm($){return($.client??this.client).post({url:"/forms/{id}/collaboration",...$})}putFormLayout($){return($.client??this.client).put({url:"/forms/{id}/layout",...$,headers:{"Content-Type":"application/json",...$.headers}})}getFormPermissions($){return($.client??this.client).get({url:"/forms/{id}/permissions",...$})}updateFormPermissions($){return($.client??this.client).patch({url:"/forms/{id}/permissions",...$,headers:{"Content-Type":"application/json",...$.headers}})}submitFormResponse($){return($.client??this.client).post({url:"/forms/{id}/responses",...$,headers:{"Content-Type":"application/json",...$.headers}})}getMyFormResponse($){return($.client??this.client).get({url:"/forms/{id}/responses/mine",...$})}editMyFormResponse($){return($.client??this.client).put({url:"/forms/{id}/responses/mine",...$,headers:{"Content-Type":"application/json",...$.headers}})}getFormResponseSummary($){return($.client??this.client).get({url:"/forms/{id}/responses/summary",...$})}getFormTally($){return($.client??this.client).get({url:"/forms/{id}/tally",...$})}installSync($){return($?.client??this.client).get({url:"/github/install-sync",...$})}getGithubPullRequestFacets($){return($?.client??this.client).get({url:"/github_pull_requests/facets",...$})}getGithubPullRequest($){return($.client??this.client).get({url:"/github_pull_requests/{id}",...$})}getGithubPullRequestChanges($){return($.client??this.client).get({url:"/github_pull_requests/{id}/changes",...$})}getGithubPullRequestChangesPatch($){return($.client??this.client).get({url:"/github_pull_requests/{id}/changes/patch",...$})}createHarnessPairing($){return($.client??this.client).post({url:"/harness-pairings",...$,headers:{"Content-Type":"application/json",...$.headers}})}getHarnessPairing($){return($.client??this.client).get({url:"/harness-pairings/{code}",...$})}approveHarnessPairing($){return($.client??this.client).post({url:"/harness-pairings/{code}/approve",...$,headers:{"Content-Type":"application/json",...$.headers}})}claimHarnessPairing($){return($.client??this.client).post({url:"/harness-pairings/{pairing_id}/claim",...$,headers:{"Content-Type":"application/json",...$.headers}})}listHarnesses($){return($?.client??this.client).get({url:"/harnesses",...$})}deleteSelfHarness($){return($?.client??this.client).delete({url:"/harnesses/me",...$})}getSelfHarness($){return($?.client??this.client).get({url:"/harnesses/me",...$})}listHarnessAgents($){return($?.client??this.client).get({url:"/harnesses/me/agents",...$})}listHarnessSessions($){return($?.client??this.client).get({url:"/harnesses/me/sessions",...$})}deleteHarness($){return($.client??this.client).delete({url:"/harnesses/{harness_id}",...$})}healthHandler($){return($?.client??this.client).get({url:"/health",...$})}getHistoryHandler($){return($?.client??this.client).get({url:"/history",...$})}deleteHistoryHandler($){return($.client??this.client).delete({url:"/history/{item_type}/{item_id}",...$})}upsertHistoryHandler($){return($.client??this.client).post({url:"/history/{item_type}/{item_id}",...$})}listInitiatives($){return($?.client??this.client).get({url:"/initiatives",...$})}createInitiative($){return($.client??this.client).post({url:"/initiatives",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteInitiative($){return($.client??this.client).delete({url:"/initiatives/{initiative_id}",...$})}getInitiative($){return($.client??this.client).get({url:"/initiatives/{initiative_id}",...$})}updateInitiative($){return($.client??this.client).patch({url:"/initiatives/{initiative_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getInstructionsHandler($){return($?.client??this.client).get({url:"/instructions",...$})}createInstructionsHandler($){return($?.client??this.client).post({url:"/instructions",...$})}getItemsSoup($){return($?.client??this.client).get({url:"/items/soup",...$})}postItemsSoup($){return($.client??this.client).post({url:"/items/soup",...$,headers:{"Content-Type":"application/json",...$.headers}})}postItemsSoupAst($){return($.client??this.client).post({url:"/items/soup/ast",...$,headers:{"Content-Type":"application/json",...$.headers}})}postItemsSoupAstGrouped($){return($.client??this.client).post({url:"/items/soup/ast/grouped",...$,headers:{"Content-Type":"application/json",...$.headers}})}messageTimeline($){return($.client??this.client).get({url:"/messages/{parent_type}/{parent_id}",...$})}entityMessageCreate($){return($.client??this.client).post({url:"/messages/{parent_type}/{parent_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}entityMessageDeleteMessage($){return($.client??this.client).delete({url:"/messages/{parent_type}/{parent_id}/items/{id}",...$})}entityMessageGetMessage($){return($.client??this.client).get({url:"/messages/{parent_type}/{parent_id}/items/{id}",...$})}entityMessageEdit($){return($.client??this.client).patch({url:"/messages/{parent_type}/{parent_id}/items/{id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}entityMessageReact($){return($.client??this.client).post({url:"/messages/{parent_type}/{parent_id}/items/{id}/reactions",...$,headers:{"Content-Type":"application/json",...$.headers}})}entityMessageLegacy($){return($.client??this.client).get({url:"/messages/{parent_type}/{parent_id}/legacy/{legacy_id}",...$})}entityMessageDeleteThread($){return($.client??this.client).delete({url:"/messages/{parent_type}/{parent_id}/threads/{id}",...$})}entityMessageGetThread($){return($.client??this.client).get({url:"/messages/{parent_type}/{parent_id}/threads/{id}",...$})}entityMessagePatchThread($){return($.client??this.client).patch({url:"/messages/{parent_type}/{parent_id}/threads/{id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}messageTimelineEntries($){return($.client??this.client).get({url:"/messages/{parent_type}/{parent_id}/timeline",...$})}entityMessageTyping($){return($.client??this.client).post({url:"/messages/{parent_type}/{parent_id}/typing",...$,headers:{"Content-Type":"application/json",...$.headers}})}getPinsHandler($){return($?.client??this.client).get({url:"/pins",...$})}reorderPinsHandler($){return($.client??this.client).patch({url:"/pins",...$,headers:{"Content-Type":"application/json",...$.headers}})}removePinHandler($){return($.client??this.client).delete({url:"/pins/{pinned_item_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}addPinHandler($){return($.client??this.client).post({url:"/pins/{pinned_item_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getProjectsHandler($){return($?.client??this.client).get({url:"/projects",...$})}createProjectHandler($){return($.client??this.client).post({url:"/projects",...$,headers:{"Content-Type":"application/json",...$.headers}})}getPendingProjectsHandler($){return($?.client??this.client).get({url:"/projects/pending",...$})}getBatchProjectPreview($){return($.client??this.client).post({url:"/projects/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}uploadFolderHandler($){return($.client??this.client).post({url:"/projects/upload",...$,headers:{"Content-Type":"application/json",...$.headers}})}uploadExtractFolderHandler($){return($.client??this.client).post({url:"/projects/upload_extract",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteProjectHandler($){return($.client??this.client).delete({url:"/projects/{id}",...$})}getProjectHandler($){return($.client??this.client).get({url:"/projects/{id}",...$})}getProjectUserAccessLevel($){return($.client??this.client).get({url:"/projects/{id}/access_level",...$})}getProjectContentHandler($){return($.client??this.client).get({url:"/projects/{id}/content",...$})}permanentlyDeleteProject($){return($.client??this.client).delete({url:"/projects/{id}/permanent",...$})}getProjectPermissionsV2($){return($.client??this.client).get({url:"/projects/{id}/permissions",...$})}revertDeleteProject($){return($.client??this.client).put({url:"/projects/{id}/revert_delete",...$})}recentlyDeleted($){return($?.client??this.client).get({url:"/recents/deleted",...$})}listEmailReminders($){return($?.client??this.client).get({url:"/reminders/email/collection",...$})}getEmailFollowup($){return($.client??this.client).get({url:"/reminders/email/{thread_id}",...$})}setEmailFollowup($){return($.client??this.client).put({url:"/reminders/email/{thread_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getViewsHandler($){return($?.client??this.client).get({url:"/saved_views",...$})}createViewHandler($){return($.client??this.client).post({url:"/saved_views",...$,headers:{"Content-Type":"application/json",...$.headers}})}excludeDefaultViewHandler($){return($.client??this.client).post({url:"/saved_views/exclude_default",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteViewHandler($){return($.client??this.client).delete({url:"/saved_views/{saved_view_id}",...$})}patchViewHandler($){return($.client??this.client).patch({url:"/saved_views/{saved_view_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}listSlackImports($){return($?.client??this.client).get({url:"/slack/imports",...$})}createSlackImport($){return($.client??this.client).post({url:"/slack/imports",...$,headers:{"Content-Type":"application/json",...$.headers}})}getSlackImport($){return($.client??this.client).get({url:"/slack/imports/{job_id}",...$})}cancelSlackImport($){return($.client??this.client).post({url:"/slack/imports/{job_id}/cancel",...$})}finalizeSlackImport($){return($.client??this.client).post({url:"/slack/imports/{job_id}/finalize",...$})}registerSlackImportUploads($){return($.client??this.client).post({url:"/slack/imports/{job_id}/uploads",...$,headers:{"Content-Type":"application/json",...$.headers}})}completeSlackImportUploads($){return($.client??this.client).post({url:"/slack/imports/{job_id}/uploads/complete",...$,headers:{"Content-Type":"application/json",...$.headers}})}bulkWakeupSyncServiceDocuments($){return($.client??this.client).post({url:"/sync_service/wakeup",...$,headers:{"Content-Type":"application/json",...$.headers}})}editThreadV2($){return($.client??this.client).patch({url:"/threads/{thread_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}listUserApiKeys($){return($?.client??this.client).get({url:"/user-api-keys",...$})}createUserApiKey($){return($.client??this.client).post({url:"/user-api-keys",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteUserApiKey($){return($.client??this.client).delete({url:"/user-api-keys/{id}",...$})}deleteUserDocumentViewLocation($){return($.client??this.client).delete({url:"/user_document_view_location/{document_id}",...$})}getUserDocumentViewLocation($){return($.client??this.client).get({url:"/user_document_view_location/{document_id}",...$})}upsertUserDocumentViewLocation($){return($.client??this.client).post({url:"/user_document_view_location/{document_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDocumentPermissionsV2($){return($.client??this.client).get({url:"/v2/documents/{document_id}/permissions",...$})}editProjectV2($){return($.client??this.client).patch({url:"/v2/projects/{id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}streamEvents($){return($.client??this.client).sse.get({url:"/webhook/events/stream",...$})}listWebhooks($){return($?.client??this.client).get({url:"/webhook/webhooks",...$})}createWebhook($){return($.client??this.client).post({url:"/webhook/webhooks",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteWebhook($){return($.client??this.client).delete({url:"/webhook/webhooks/{webhook_id}",...$})}getWebhook($){return($.client??this.client).get({url:"/webhook/webhooks/{webhook_id}",...$})}patchWebhook($){return($.client??this.client).patch({url:"/webhook/webhooks/{webhook_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}validateWebhook($){return($.client??this.client).post({url:"/webhook/webhooks/{webhook_id}/validate",...$})}whatsappAccount($){return($?.client??this.client).get({url:"/whatsapp/account",...$})}whatsappChats($){return($?.client??this.client).get({url:"/whatsapp/chats",...$})}whatsappConnect($){return($.client??this.client).post({url:"/whatsapp/connect",...$,headers:{"Content-Type":"application/json",...$.headers}})}whatsappDisconnect($){return($.client??this.client).post({url:"/whatsapp/disconnect",...$,headers:{"Content-Type":"application/json",...$.headers}})}whatsappImportHistory($){return($?.client??this.client).post({url:"/whatsapp/history-import",...$})}whatsappStartLookup($){return($.client??this.client).post({url:"/whatsapp/lookups",...$,headers:{"Content-Type":"application/json",...$.headers}})}whatsappLookup($){return($.client??this.client).get({url:"/whatsapp/lookups/{id}",...$})}whatsappCancelPairing($){return($.client??this.client).delete({url:"/whatsapp/pairing/{id}",...$})}whatsappPairing($){return($.client??this.client).get({url:"/whatsapp/pairing/{id}",...$})}whatsappPasskey($){return($.client??this.client).post({url:"/whatsapp/pairing/{id}/passkey",...$,headers:{"Content-Type":"application/json",...$.headers}})}}function D7({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...G}){let J,I=Y??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,H=G.signal??new AbortController().signal;while(!0){if(H.aborted)break;B++;let A=G.headers instanceof Headers?G.headers:new Headers(G.headers);if(J!==void 0)A.set("Last-Event-ID",J);try{let D={redirect:"follow",...G,body:G.serializedBody,headers:A,signal:H},_=new Request(L,D);if($)_=await $(L,D);let N=await(G.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let T=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{T.cancel()}catch{}};H.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await T.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
`);let y=U.split(`
`);U=y.pop()??"";for(let a of y){let i=a.split(`
`),F=[],v;for(let R of i)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))v=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let m=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(m))V=m}let M,h=!1;if(F.length){let R=F.join(`
-`);try{M=JSON.parse(R),h=!0}catch{M=R}}if(h){if(S)await S(M);if(x)M=await x(M)}if(j?.({data:M,event:v,id:J,retry:V}),F.length)yield M}}}finally{H.removeEventListener("abort",g),T.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var P9=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},A9=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},F9=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},g0=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((Y)=>encodeURIComponent(Y))).join(A9(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=P9(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return vO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},vO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},y0=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let Y=[];Object.entries(S).forEach(([G,J])=>{Y=[...Y,G,$?J:encodeURIComponent(J)]});let L=Y.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=F9(x),X=Object.entries(S).map(([Y,L])=>vO({allowReserved:$,name:x==="deepObject"?`${j}[${Y}]`:Y,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var E9=/\{[^{}]+\}/g,q9=({path:$,url:O})=>{let j=O,x=O.match(E9);if(x)for(let S of x){let K=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))K=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let Y=$[Z];if(Y===void 0||Y===null)continue;if(Array.isArray(Y)){j=j.replace(S,g0({explode:K,name:Z,style:X,value:Y}));continue}if(typeof Y==="object"){j=j.replace(S,y0({explode:K,name:Z,style:X,value:Y,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${vO({name:Z,value:Y})}`);continue}let L=encodeURIComponent(X==="label"?`.${Y}`:Y);j=j.replace(S,L)}return j},D7=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=q9({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function g1($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var _7=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 M7={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var C7=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let Y=g0({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(Y)S.push(Y)}else if(typeof Z==="object"){let Y=y0({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(Y)S.push(Y)}else{let Y=vO({allowReserved:X.allowReserved,name:K,value:Z});if(Y)S.push(Y)}}return S.join("&")}},P7=($)=>{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},w9=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function A7($){for(let O of $.security??[]){if(w9($,O.name))continue;let j=await _7(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var y1=($)=>D7({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:C7($.querySerializer),url:$.url}),v1=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=h0($.headers,O.headers),j},f9=($)=>{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?f9(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class v0{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 F7=()=>({error:new v0,request:new v0,response:new v0}),b9=C7({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),k9={"Content-Type":"application/json"},Wj=($={})=>({...M7,headers:k9,parseAs:"auto",querySerializer:b9,...$});var h1=($={})=>{let O=v1(Wj(),$),j=()=>({...O}),x=(G)=>{return O=v1(O,G),j()},S=F7(),K=async(G)=>{let J={...O,...G,fetch:G.fetch??O.fetch??globalThis.fetch,headers:h0(O.headers,G.headers),serializedBody:void 0};if(J.security)await A7(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let I=J,z=y1(I);return{opts:I,url:z}},Z=async(G)=>{let J=G.throwOnError??O.throwOnError,I=G.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(G),H={redirect:"follow",...V,body:g1(V)};z=new Request(B,H);for(let N of S.request.fns)if(N)z=await N(z,V);let A=V.fetch;W=await A(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?P7(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let T;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":T=await W[N]();break;case"json":{let U=await W.text();T=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(T);if(V.responseTransformer)T=await V.responseTransformer(T)}return V.responseStyle==="data"?T:{data:T,...D}}let _=await W.text(),q;try{q=JSON.parse(_)}catch{}throw q??_}catch(V){let B=V;for(let H of S.error.fns)if(H)B=await H(B,W,z,G);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(G)=>(J)=>Z({...J,method:G}),Y=(G)=>async(J)=>{let{opts:I,url:z}=await K(J);return R7({...I,body:I.body,method:G,onRequest:async(W,V)=>{let B=new Request(W,V);for(let H of S.request.fns)if(H)B=await H(B,I);return B},serializedBody:g1(I),url:z})};return{buildUrl:(G)=>y1({...O,...G}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:Y("CONNECT"),delete:Y("DELETE"),get:Y("GET"),head:Y("HEAD"),options:Y("OPTIONS"),patch:Y("PATCH"),post:Y("POST"),put:Y("PUT"),trace:Y("TRACE")},trace:X("TRACE")}};var E7=h1(Wj());class q7{client;constructor($){this.client=$?.client??E7}}class w7{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class m0 extends q7{static __registry=new w7;constructor($){super($);m0.__registry.set(this,$?.key)}proxyRequestHandler($){return($.client??this.client).get({url:"/proxy",...$})}getUnfurl($){return($.client??this.client).get({url:"/unfurl",...$})}getUnfurlBulk($){return($.client??this.client).post({url:"/unfurl/bulk",...$,headers:{"Content-Type":"application/json",...$.headers}})}}var f7={dev:"https://dev.macro.com",prod:"https://macro.com",local:"http://localhost:3000"},m1={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 g9($,O){let j=O?.channel_id;return O&&j?{channel:b.byId($,j),thread:new h$($,j,O.thread_id)}:{channel:void 0,thread:void 0}}function q$($,O){return{session:d.byId($,O.session_id),owner:C.byId($,O.owner_id),...g9($,O.origin)}}function hO($,O,j){let x=O.origin?.channel_id;return x&&j?o.byId($,x,j):void 0}function mO($,O){return O?C.byId($,O):void 0}function b7($,O){return k(O).with({event_type:"agent_session.opened"},({metadata:j})=>({event_type:"agent_session.opened",metadata:j,...q$($,j.identity)})).with({event_type:"agent_session.turn_started"},({metadata:j})=>({event_type:"agent_session.turn_started",metadata:j,...q$($,j.identity),actor:mO($,j.actor),announcement:hO($,j.identity,j.announcement_message_id)})).with({event_type:"agent_session.turn_ended"},({metadata:j})=>({event_type:"agent_session.turn_ended",metadata:j,...q$($,j.identity),actor:mO($,j.actor),announcement:hO($,j.identity,j.announcement_message_id)})).with({event_type:"agent_session.command_rejected"},({metadata:j})=>({event_type:"agent_session.command_rejected",metadata:j,...q$($,j.identity),actor:mO($,j.actor),announcement:hO($,j.identity,j.announcement_message_id)})).with({event_type:"agent_session.settled"},({metadata:j})=>({event_type:"agent_session.settled",metadata:j,...q$($,j.identity),actor:mO($,j.last_turn?.actor),announcement:hO($,j.identity,j.last_turn?.announcement_message_id)})).with({event_type:"agent_session.waiting_for_input"},({metadata:j})=>({event_type:"agent_session.waiting_for_input",metadata:j,...q$($,j.identity),announcement:hO($,j.identity,j.announcement_message_id)})).with({event_type:"agent_session.input_received"},({metadata:j})=>({event_type:"agent_session.input_received",metadata:j,...q$($,j.identity)})).with({event_type:"agent_session.mentioned"},({metadata:j})=>({event_type:"agent_session.mentioned",metadata:j,...q$($,j.identity),mentionedBy:mO($,j.mentioned_by),mentioned:j.mentioned.map((x)=>C.byId($,x))})).with({event_type:"agent_session.stopped"},({metadata:j})=>({event_type:"agent_session.stopped",metadata:j,...q$($,j.identity),actor:mO($,j.turn_in_flight?.actor),announcement:hO($,j.identity,j.turn_in_flight?.announcement_message_id)})).with({event_type:"agent_session.renamed"},({metadata:j})=>({event_type:"agent_session.renamed",metadata:j,...q$($,j.identity)})).with({event_type:"agent_session.deleted"},({metadata:j})=>({event_type:"agent_session.deleted",metadata:j,...q$($,j.identity)})).exhaustive((j)=>{console.warn("macro sdk: unknown agent session event",j);return})}var k7="macro|";function C$($,O){return O.startsWith(k7)&&O.length>k7.length?C.byId($,O.toLowerCase()):void 0}function g7($,O){return k(O).with({event_type:"channel.created"},({metadata:j})=>({event_type:"channel.created",metadata:j,channel:b.byId($,j.channel_id),actor:C$($,j.actor),participants:j.participant_user_ids.map((x)=>C.byId($,x))})).with({event_type:"channel.updated"},({metadata:j})=>({event_type:"channel.updated",metadata:j,channel:b.byId($,j.channel_id),actor:C$($,j.actor)})).with({event_type:"channel.deleted"},({metadata:j})=>({event_type:"channel.deleted",metadata:j,channel:b.byId($,j.channel_id),actor:C$($,j.actor)})).with({event_type:"channel.picture_changed"},({metadata:j})=>({event_type:"channel.picture_changed",metadata:j,channel:b.byId($,j.channel_id),actor:C$($,j.actor)})).with({event_type:"channel.participant_added"},({metadata:j})=>({event_type:"channel.participant_added",metadata:j,channel:b.byId($,j.channel_id),addedBy:C$($,j.added_by),addedUsers:j.added_user_ids.map((x)=>C.byId($,x))})).with({event_type:"channel.participant_removed"},({metadata:j})=>({event_type:"channel.participant_removed",metadata:j,channel:b.byId($,j.channel_id),removedBy:C.byId($,j.removed_by),removedUsers:j.removed_user_ids.map((x)=>C.byId($,x))})).exhaustive((j)=>{console.warn("macro sdk: unknown channel event",j);return})}function y7($,O){return k(O).with({event_type:"document.created"},({metadata:j})=>({event_type:"document.created",metadata:j,document:w.byId($,j.document_id),owner:C.byId($,j.owner),project:j.project_id?n.byId($,j.project_id):void 0})).with({event_type:"document.updated"},({metadata:j})=>({event_type:"document.updated",metadata:j,document:w.byId($,j.document_id),owner:C.byId($,j.owner),actor:j.actor_user_id?C.byId($,j.actor_user_id):void 0,project:j.project_id?n.byId($,j.project_id):void 0,previousProject:j.previous_project_id?n.byId($,j.previous_project_id):void 0})).with({event_type:"document.deleted"},({metadata:j})=>({event_type:"document.deleted",metadata:j,document:w.byId($,j.document_id),actor:j.actor_user_id?C.byId($,j.actor_user_id):void 0,project:j.project_id?n.byId($,j.project_id):void 0})).with({event_type:"document.content_uploaded"},({metadata:j})=>({event_type:"document.content_uploaded",metadata:j,document:w.byId($,j.document_id),owner:C.byId($,j.owner)})).with({event_type:"document.sync_content_updated"},({metadata:j})=>({event_type:"document.sync_content_updated",metadata:j,document:w.byId($,j.document_id)})).with({event_type:"document.purged"},({metadata:j})=>({event_type:"document.purged",metadata:j,document:w.byId($,j.document_id)})).with({event_type:"document.copied"},({metadata:j})=>({event_type:"document.copied",metadata:j,document:w.byId($,j.document_id),sourceDocument:w.byId($,j.source_document_id),owner:C.byId($,j.owner),project:j.project_id?n.byId($,j.project_id):void 0})).with({event_type:"document.interaction"},({metadata:j})=>({event_type:"document.interaction",metadata:j,document:w.byId($,j.document_id)})).exhaustive((j)=>{console.warn("macro sdk: unknown document event",j);return})}function uO($,O,j=[]){let x=O.parent;if(x.type==="call")return{type:"call",call:J$.byId($,x.id),message:u$.byId($,x.id,O.message_id),threadId:x.id};if(x.type==="channel")return{type:"channel",channel:b.byId($,x.id),message:o.byId($,x.id,O.message_id,j),thread:O.thread_id?new h$($,x.id,O.thread_id):void 0};return{type:"document",document:w.byId($,x.id),comment:l$.byId($,x.id,O.message_id),threadId:O.root_id}}function v7($,O){return k(O).with({event_type:"message.posted"},({metadata:j})=>({event_type:"message.posted",metadata:j,target:uO($,j,j.mentions),sender:C$($,j.sender)})).with({event_type:"message.mentioned"},({metadata:j})=>({event_type:"message.mentioned",metadata:j,target:uO($,j),sender:C$($,j.sender)})).with({event_type:"message.patched"},({metadata:j})=>({event_type:"message.patched",metadata:j,target:uO($,j),actor:C$($,j.actor)})).with({event_type:"message.deleted"},({metadata:j})=>({event_type:"message.deleted",metadata:j,target:uO($,j),actor:C$($,j.actor)})).with({event_type:"message.attachment_created"},({metadata:j})=>({event_type:"message.attachment_created",metadata:j,target:uO($,j),actor:C$($,j.actor)})).with({event_type:"message.attachment_removed"},({metadata:j})=>({event_type:"message.attachment_removed",metadata:j,target:uO($,j),actor:C$($,j.actor)})).exhaustive((j)=>{console.warn("macro sdk: unknown message event",j);return})}async function h7($){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 y9="webhook.validation.test";function v9($,O){return k(O).with({event_type:t.string.startsWith("document.")},(j)=>y7($,j)).with({event_type:t.string.startsWith("channel.")},(j)=>g7($,j)).with({event_type:t.string.startsWith("message.")},(j)=>v7($,j)).with({event_type:t.string.startsWith("agent_session.")},(j)=>b7($,j)).otherwise(()=>{return})}class u1{client;secret;handlers=new Map;constructor($,O){this.client=$;this.secret=O}on($,O){let j=this.handlers.get($)??new Set;return j.add(O),this.handlers.set($,j),()=>j.delete(O)}onSelfMention($){return this.on("message.mentioned",async(O)=>{if(O.metadata.mentioned.entity_id.toLowerCase()!==(await this.client.myPrincipalId()).toLowerCase())return;await $(O)})}async listen($={}){let O=$.filters??this.filtersFromHandlers();if(O.length===0||O.every((K)=>K.events.length===0))throw new f("listen() needs filters — pass filters or register handlers with .on() first");let j=new AbortController;if($.signal)if($.signal.aborted)j.abort();else $.signal.addEventListener("abort",()=>j.abort(),{once:!0});let{stream:x}=await this.client.storage.streamEvents({query:{scope:$.scope??"user",filters:JSON.stringify(O)},signal:j.signal});return(async()=>{try{for await(let K of x)await this.dispatchEvent(K)}catch{if(j.signal.aborted)return;throw new f("event stream failed")}})().catch(()=>{}),()=>{j.abort()}}async handle($,O){if(!this.secret)throw new f("webhookSecret is required to verify incoming webhook deliveries");if(!await h7({secret:this.secret,timestamp:O.timestamp??"",rawBody:$,signature:O.signature??""}))throw new f("invalid webhook signature");if(O.event===y9)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=v9(this.client,j);if(!S)return;await Promise.all([...x].map((K)=>K(S)))}}function m7(){return}var h9=0,c1;function m9($){c1=$}function I$($,O,j){if(!j&&!c1)return $;let x=(S)=>{for(let K of[c1,j])try{Promise.resolve(K?.(S)).catch(()=>{})}catch{}};return new Proxy($,{get(S,K,Z){let X=Reflect.get(S,K,Z);if(typeof K!=="string"||typeof X!=="function")return X;return async(...Y)=>{let L={id:++h9,service:O,operation:K};x({...L,status:"started"});try{let G=await Reflect.apply(X,S,Y),J=G!==null&&typeof G==="object"&&"error"in G&&G.error!=null;return x({...L,status:J?"failed":"completed"}),G}catch(G){throw x({...L,status:"failed"}),G}}}})}var c7="x-macro-user-api-key",u9="mak_",d1="mbot_";function c9($){return k($).with(t.string.startsWith(d1),()=>{throw Error("bot token passed as a user credential. Use auth: { type: 'bot', token } or MACRO_BOT_TOKEN.")}).with(t.string.startsWith(u9),(O)=>[c7,O]).otherwise((O)=>["Authorization",`Bearer ${O}`])}async function u7($){return typeof $==="function"?await $():$}async function d9($,O,j){return k($).with({type:"bot"},async(x)=>{let S=await u7(x.token);if(!S.startsWith(d1))throw Error("user API key passed as a bot token. Use auth: { type: 'user', apiKey } or MACRO_API_KEY.");let K=[["x-macro-bot-token",S]];if(!j?.hasBotScope)K.push(["x-macro-bot-scope",x.scope??(O?"user":"team")]);if(O)K.push(["x-macro-bot-for-macro-user-id",O]);return K}).with({type:"user",apiKey:t.string},({apiKey:x})=>{if(x.startsWith(d1))throw Error("bot token passed as a user credential. Use auth: { type: 'bot', token } or MACRO_BOT_TOKEN.");return[[c7,x]]}).with({type:"user"},async({token:x})=>{return[c9(await u7(x))]}).exhaustive()}class l1{scheduledAction;unfurl;agentHarness;auth;calendar;cognition;contacts;email;notification;properties;search;storage;webAppUrl;wsVerify;events;authConfig;hosts;localPortmap;requestedAs;selfBotRecord;selfPrincipal;constructor($){let O=l9($),j=O==="local"?m7():void 0,x={...m1[O],...j?.hosts,...$.hosts};this.hosts=x,this.localPortmap=j;let S=typeof process<"u"?{}.MACRO_WEB_URL:void 0;if(this.webAppUrl=$.webAppUrl??S??j?.webAppUrl??f7[O],this.authConfig=r9($),this.requestedAs=$.requestedAs,this.requestedAs&&this.authConfig.type!=="bot")throw Error("requestedAs() requires bot auth — a user token always acts as its own user");this.wsVerify=$.wsVerify,this.scheduledAction=I$(new M0({client:this.makeClient(x["scheduled-action"])}),"scheduled-action",$.onRequest),this.unfurl=I$(new m0({client:this.makeClient(x.unfurl)}),"unfurl",$.onRequest),this.agentHarness=I$(new hj({client:this.makeClient(x["agent-harness"])}),"agent-harness",$.onRequest),this.auth=I$(new lj({client:this.makeClient(x.auth)}),"auth",$.onRequest),this.calendar=I$(new nj({client:this.makeClient(x.calendar)}),"calendar",$.onRequest),this.cognition=I$(new $0({client:this.makeClient(x.cognition)}),"cognition",$.onRequest),this.contacts=I$(new Z0({client:this.makeClient(x.contacts)}),"contacts",$.onRequest),this.email=I$(new G0({client:this.makeClient(x.email)}),"email",$.onRequest),this.notification=I$(new L0({client:this.makeClient(x.notification)}),"notification",$.onRequest),this.properties=I$(new H0({client:this.makeClient(x.properties)}),"properties",$.onRequest),this.search=I$(new E0({client:this.makeClient(x.search)}),"search",$.onRequest),this.storage=I$(new k0({client:this.makeClient(x.storage)}),"storage",$.onRequest);let K=typeof process<"u"?{}.MACRO_WEBHOOK_SECRET:void 0,Z=$.webhookSecret??K;this.events=new u1(this,Z)}hasActingUser(){return this.authConfig.type==="user"||this.requestedAs!==void 0}selfBot(){return this.selfBotRecord??=new aO(this).me().catch(($)=>{throw this.selfBotRecord=void 0,$}),this.selfBotRecord}myPrincipalId(){return this.selfPrincipal??=(this.authConfig.type==="bot"?this.selfBot().then(($)=>`bot|${$.id}`):C.me(this).then(($)=>$.id)).catch(($)=>{throw this.selfPrincipal=void 0,$}),this.selfPrincipal}makeClient($){let O=Vj({baseUrl:$});return O.interceptors.request.use(async(j)=>{let x=await d9(this.authConfig,this.requestedAs,{hasBotScope:j.headers.has("x-macro-bot-scope")});for(let[S,K]of x)j.headers.set(S,K);return j}),O}}function l9($){if($.env)return $.env;let O=typeof process<"u"?{}.MACRO_ENV:void 0;if(!O)return"prod";if(!(O in m1))throw Error(`invalid MACRO_ENV "${O}" — expected local, dev, or prod`);return O}function r9($){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 r1{id;constructor($){this.id=$}static byId($){return new r1($)}toJSON(){return{id:this.id}}}class d7{routines;unfurls;agents;initiatives;apiKeys;harnesses;meetings;githubPullRequests;entityMentions;agentSessions;ai;bots;calendar;calls;channels;externalChats;whatsapp;chats;crm;databases;documents;email;favorites;foreignEntities;forms;images;notifications;pins;projects;properties;referrals;tasks;teams;users;webhooks;workspace;events;webAppUrl;_client;opts;constructor($){this.opts=$;let O=new l1($);this._client=O,this.routines=new bx(O),this.unfurls=new yx(O),this.agents=new s0(O),this.initiatives=new Mx(O),this.apiKeys=new e0(O),this.harnesses=new Dx(O),this.meetings=new Cx(O),this.githubPullRequests=new Rx(O),this.entityMentions=new Lx(O),this.agentSessions=new n0(O),this.ai=new t0(O),this.bots=new aO(O),this.calendar=new o0(O),this.calls=new $x(O),this.channels=new jx(O),this.externalChats=new Ux(O),this.whatsapp=new mx(O),this.chats=new xx(O),this.crm=new Zx(O),this.databases=new Jx(O),this.documents=new Vx(O),this.email=new Bx(O),this.favorites=new zx(O),this.foreignEntities=new Ix(O),this.forms=new Hx(O),this.images=new _x(O),this.notifications=new Px(O),this.pins=new Ax(O),this.projects=new Fx(O),this.properties=new Ex(O),this.referrals=new qx(O),this.tasks=new kx(O),this.teams=new gx(O),this.users=new vx(O),this.webhooks=new hx(O),this.workspace=new lx(O),this.events=O.events,this.webAppUrl=O.webAppUrl}myPrincipalId(){return this._client.myPrincipalId()}requestedAs($){return new d7({...this.opts,requestedAs:$.id})}}export{o$ as wrapXml,O$ as toBody,m9 as observeRequests,Y5 as msg,K5 as here,NO as WhatsAppChat,CO as WhatsAppAccount,OO as UserApiKey,pO as ToolApproval,HO as TeamInvite,Ej as StaticImage,N$ as SessionReview,fx as RoutineExecution,v$ as Routine,i0 as ReviewItem,Tx as PullRequestChangeset,Tj as PipelineTable,JO as PipelineRow,Rj as PipelineColumn,L$ as MessageThread,D$ as Meeting,Gx as MacroOpRefusedError,d7 as Macro,a$ as Initiative,_O as HarnessPairing,B$ as Harness,DO as GithubPullRequest,qj as GeneratedImage,p$ as FormSection,RO as FormResponse,Fj as FormReference,r$ as FormQuestion,UO as FormOption,y$ as Form,ZO as ExternalChatUpload,XO as ExternalChatSend,SO as ExternalChatParticipant,M$ as ExternalChatMessage,g$ as ExternalChat,TO as EntityMention,$$ as EntityAccess,LO as EmailFilter,BO as EmailDraft,oO as DraftAttachment,eO as DocumentVersion,VO as DocumentAnchor,$j as DevicePairing,jO as CrmPipeline,a0 as ConversationTurn,rO as CodeExecution,sO as ChatMessage,nO as ChatGeneration,r1 as ChannelPicture,GO as ChannelActivity,Uj as AgentConversation,T$ as Agent,IO as AccessRequest};
+`);try{M=JSON.parse(R),h=!0}catch{M=R}}if(h){if(S)await S(M);if(x)M=await x(M)}if(j?.({data:M,event:v,id:J,retry:V}),F.length)yield M}}}finally{H.removeEventListener("abort",g),T.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var A9=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},F9=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},E9=($)=>{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((Y)=>encodeURIComponent(Y))).join(F9(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=A9(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return vO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},vO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},y0=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let Y=[];Object.entries(S).forEach(([G,J])=>{Y=[...Y,G,$?J:encodeURIComponent(J)]});let L=Y.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=E9(x),X=Object.entries(S).map(([Y,L])=>vO({allowReserved:$,name:x==="deepObject"?`${j}[${Y}]`:Y,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var q9=/\{[^{}]+\}/g,w9=({path:$,url:O})=>{let j=O,x=O.match(q9);if(x)for(let S of x){let K=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))K=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let Y=$[Z];if(Y===void 0||Y===null)continue;if(Array.isArray(Y)){j=j.replace(S,g0({explode:K,name:Z,style:X,value:Y}));continue}if(typeof Y==="object"){j=j.replace(S,y0({explode:K,name:Z,style:X,value:Y,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${vO({name:Z,value:Y})}`);continue}let L=encodeURIComponent(X==="label"?`.${Y}`:Y);j=j.replace(S,L)}return j},_7=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=w9({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 M7=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 C7={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var P7=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let Y=g0({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(Y)S.push(Y)}else if(typeof Z==="object"){let Y=y0({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(Y)S.push(Y)}else{let Y=vO({allowReserved:X.allowReserved,name:K,value:Z});if(Y)S.push(Y)}}return S.join("&")}},A7=($)=>{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},f9=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function F7($){for(let O of $.security??[]){if(f9($,O.name))continue;let j=await M7(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var v1=($)=>_7({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:P7($.querySerializer),url:$.url}),h1=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=h0($.headers,O.headers),j},b9=($)=>{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?b9(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class v0{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 E7=()=>({error:new v0,request:new v0,response:new v0}),k9=P7({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),g9={"Content-Type":"application/json"},Wj=($={})=>({...C7,headers:g9,parseAs:"auto",querySerializer:k9,...$});var m1=($={})=>{let O=h1(Wj(),$),j=()=>({...O}),x=(G)=>{return O=h1(O,G),j()},S=E7(),K=async(G)=>{let J={...O,...G,fetch:G.fetch??O.fetch??globalThis.fetch,headers:h0(O.headers,G.headers),serializedBody:void 0};if(J.security)await F7(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=v1(I);return{opts:I,url:z}},Z=async(G)=>{let J=G.throwOnError??O.throwOnError,I=G.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(G),H={redirect:"follow",...V,body:y1(V)};z=new Request(B,H);for(let N of S.request.fns)if(N)z=await N(z,V);let A=V.fetch;W=await A(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?A7(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let T;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":T=await W[N]();break;case"json":{let U=await W.text();T=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(T);if(V.responseTransformer)T=await V.responseTransformer(T)}return V.responseStyle==="data"?T:{data:T,...D}}let _=await W.text(),q;try{q=JSON.parse(_)}catch{}throw q??_}catch(V){let B=V;for(let H of S.error.fns)if(H)B=await H(B,W,z,G);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(G)=>(J)=>Z({...J,method:G}),Y=(G)=>async(J)=>{let{opts:I,url:z}=await K(J);return D7({...I,body:I.body,method:G,onRequest:async(W,V)=>{let B=new Request(W,V);for(let H of S.request.fns)if(H)B=await H(B,I);return B},serializedBody:y1(I),url:z})};return{buildUrl:(G)=>v1({...O,...G}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:Y("CONNECT"),delete:Y("DELETE"),get:Y("GET"),head:Y("HEAD"),options:Y("OPTIONS"),patch:Y("PATCH"),post:Y("POST"),put:Y("PUT"),trace:Y("TRACE")},trace:X("TRACE")}};var q7=m1(Wj());class w7{client;constructor($){this.client=$?.client??q7}}class f7{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 m0 extends w7{static __registry=new f7;constructor($){super($);m0.__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 b7={dev:"https://dev.macro.com",prod:"https://macro.com",local:"http://localhost:3000"},u1={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 y9($,O){let j=O?.channel_id;return O&&j?{channel:b.byId($,j),thread:new h$($,j,O.thread_id)}:{channel:void 0,thread:void 0}}function q$($,O){return{session:d.byId($,O.session_id),owner:C.byId($,O.owner_id),...y9($,O.origin)}}function hO($,O,j){let x=O.origin?.channel_id;return x&&j?o.byId($,x,j):void 0}function mO($,O){return O?C.byId($,O):void 0}function k7($,O){return k(O).with({event_type:"agent_session.opened"},({metadata:j})=>({event_type:"agent_session.opened",metadata:j,...q$($,j.identity)})).with({event_type:"agent_session.turn_started"},({metadata:j})=>({event_type:"agent_session.turn_started",metadata:j,...q$($,j.identity),actor:mO($,j.actor),announcement:hO($,j.identity,j.announcement_message_id)})).with({event_type:"agent_session.turn_ended"},({metadata:j})=>({event_type:"agent_session.turn_ended",metadata:j,...q$($,j.identity),actor:mO($,j.actor),announcement:hO($,j.identity,j.announcement_message_id)})).with({event_type:"agent_session.command_rejected"},({metadata:j})=>({event_type:"agent_session.command_rejected",metadata:j,...q$($,j.identity),actor:mO($,j.actor),announcement:hO($,j.identity,j.announcement_message_id)})).with({event_type:"agent_session.settled"},({metadata:j})=>({event_type:"agent_session.settled",metadata:j,...q$($,j.identity),actor:mO($,j.last_turn?.actor),announcement:hO($,j.identity,j.last_turn?.announcement_message_id)})).with({event_type:"agent_session.waiting_for_input"},({metadata:j})=>({event_type:"agent_session.waiting_for_input",metadata:j,...q$($,j.identity),announcement:hO($,j.identity,j.announcement_message_id)})).with({event_type:"agent_session.input_received"},({metadata:j})=>({event_type:"agent_session.input_received",metadata:j,...q$($,j.identity)})).with({event_type:"agent_session.mentioned"},({metadata:j})=>({event_type:"agent_session.mentioned",metadata:j,...q$($,j.identity),mentionedBy:mO($,j.mentioned_by),mentioned:j.mentioned.map((x)=>C.byId($,x))})).with({event_type:"agent_session.stopped"},({metadata:j})=>({event_type:"agent_session.stopped",metadata:j,...q$($,j.identity),actor:mO($,j.turn_in_flight?.actor),announcement:hO($,j.identity,j.turn_in_flight?.announcement_message_id)})).with({event_type:"agent_session.renamed"},({metadata:j})=>({event_type:"agent_session.renamed",metadata:j,...q$($,j.identity)})).with({event_type:"agent_session.deleted"},({metadata:j})=>({event_type:"agent_session.deleted",metadata:j,...q$($,j.identity)})).exhaustive((j)=>{console.warn("macro sdk: unknown agent session event",j);return})}var g7="macro|";function C$($,O){return O.startsWith(g7)&&O.length>g7.length?C.byId($,O.toLowerCase()):void 0}function y7($,O){return k(O).with({event_type:"channel.created"},({metadata:j})=>({event_type:"channel.created",metadata:j,channel:b.byId($,j.channel_id),actor:C$($,j.actor),participants:j.participant_user_ids.map((x)=>C.byId($,x))})).with({event_type:"channel.updated"},({metadata:j})=>({event_type:"channel.updated",metadata:j,channel:b.byId($,j.channel_id),actor:C$($,j.actor)})).with({event_type:"channel.deleted"},({metadata:j})=>({event_type:"channel.deleted",metadata:j,channel:b.byId($,j.channel_id),actor:C$($,j.actor)})).with({event_type:"channel.picture_changed"},({metadata:j})=>({event_type:"channel.picture_changed",metadata:j,channel:b.byId($,j.channel_id),actor:C$($,j.actor)})).with({event_type:"channel.participant_added"},({metadata:j})=>({event_type:"channel.participant_added",metadata:j,channel:b.byId($,j.channel_id),addedBy:C$($,j.added_by),addedUsers:j.added_user_ids.map((x)=>C.byId($,x))})).with({event_type:"channel.participant_removed"},({metadata:j})=>({event_type:"channel.participant_removed",metadata:j,channel:b.byId($,j.channel_id),removedBy:C.byId($,j.removed_by),removedUsers:j.removed_user_ids.map((x)=>C.byId($,x))})).exhaustive((j)=>{console.warn("macro sdk: unknown channel event",j);return})}function v7($,O){return k(O).with({event_type:"document.created"},({metadata:j})=>({event_type:"document.created",metadata:j,document:w.byId($,j.document_id),owner:C.byId($,j.owner),project:j.project_id?n.byId($,j.project_id):void 0})).with({event_type:"document.updated"},({metadata:j})=>({event_type:"document.updated",metadata:j,document:w.byId($,j.document_id),owner:C.byId($,j.owner),actor:j.actor_user_id?C.byId($,j.actor_user_id):void 0,project:j.project_id?n.byId($,j.project_id):void 0,previousProject:j.previous_project_id?n.byId($,j.previous_project_id):void 0})).with({event_type:"document.deleted"},({metadata:j})=>({event_type:"document.deleted",metadata:j,document:w.byId($,j.document_id),actor:j.actor_user_id?C.byId($,j.actor_user_id):void 0,project:j.project_id?n.byId($,j.project_id):void 0})).with({event_type:"document.content_uploaded"},({metadata:j})=>({event_type:"document.content_uploaded",metadata:j,document:w.byId($,j.document_id),owner:C.byId($,j.owner)})).with({event_type:"document.sync_content_updated"},({metadata:j})=>({event_type:"document.sync_content_updated",metadata:j,document:w.byId($,j.document_id)})).with({event_type:"document.purged"},({metadata:j})=>({event_type:"document.purged",metadata:j,document:w.byId($,j.document_id)})).with({event_type:"document.copied"},({metadata:j})=>({event_type:"document.copied",metadata:j,document:w.byId($,j.document_id),sourceDocument:w.byId($,j.source_document_id),owner:C.byId($,j.owner),project:j.project_id?n.byId($,j.project_id):void 0})).with({event_type:"document.interaction"},({metadata:j})=>({event_type:"document.interaction",metadata:j,document:w.byId($,j.document_id)})).exhaustive((j)=>{console.warn("macro sdk: unknown document event",j);return})}function uO($,O,j=[]){let x=O.parent;if(x.type==="call")return{type:"call",call:J$.byId($,x.id),message:u$.byId($,x.id,O.message_id),threadId:x.id};if(x.type==="channel")return{type:"channel",channel:b.byId($,x.id),message:o.byId($,x.id,O.message_id,j),thread:O.thread_id?new h$($,x.id,O.thread_id):void 0};return{type:"document",document:w.byId($,x.id),comment:l$.byId($,x.id,O.message_id),threadId:O.root_id}}function h7($,O){return k(O).with({event_type:"message.posted"},({metadata:j})=>({event_type:"message.posted",metadata:j,target:uO($,j,j.mentions),sender:C$($,j.sender)})).with({event_type:"message.mentioned"},({metadata:j})=>({event_type:"message.mentioned",metadata:j,target:uO($,j),sender:C$($,j.sender)})).with({event_type:"message.patched"},({metadata:j})=>({event_type:"message.patched",metadata:j,target:uO($,j),actor:C$($,j.actor)})).with({event_type:"message.deleted"},({metadata:j})=>({event_type:"message.deleted",metadata:j,target:uO($,j),actor:C$($,j.actor)})).with({event_type:"message.attachment_created"},({metadata:j})=>({event_type:"message.attachment_created",metadata:j,target:uO($,j),actor:C$($,j.actor)})).with({event_type:"message.attachment_removed"},({metadata:j})=>({event_type:"message.attachment_removed",metadata:j,target:uO($,j),actor:C$($,j.actor)})).exhaustive((j)=>{console.warn("macro sdk: unknown message event",j);return})}async function m7($){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 v9="webhook.validation.test";function h9($,O){return k(O).with({event_type:t.string.startsWith("document.")},(j)=>v7($,j)).with({event_type:t.string.startsWith("channel.")},(j)=>y7($,j)).with({event_type:t.string.startsWith("message.")},(j)=>h7($,j)).with({event_type:t.string.startsWith("agent_session.")},(j)=>k7($,j)).otherwise(()=>{return})}class c1{client;secret;handlers=new Map;constructor($,O){this.client=$;this.secret=O}on($,O){let j=this.handlers.get($)??new Set;return j.add(O),this.handlers.set($,j),()=>j.delete(O)}onSelfMention($){return this.on("message.mentioned",async(O)=>{if(O.metadata.mentioned.entity_id.toLowerCase()!==(await this.client.myPrincipalId()).toLowerCase())return;await $(O)})}async listen($={}){let O=$.filters??this.filtersFromHandlers();if(O.length===0||O.every((K)=>K.events.length===0))throw new f("listen() needs filters — pass filters or register handlers with .on() first");let j=new AbortController;if($.signal)if($.signal.aborted)j.abort();else $.signal.addEventListener("abort",()=>j.abort(),{once:!0});let{stream:x}=await this.client.storage.streamEvents({query:{scope:$.scope??"user",filters:JSON.stringify(O)},signal:j.signal});return(async()=>{try{for await(let K of x)await this.dispatchEvent(K)}catch{if(j.signal.aborted)return;throw new f("event stream failed")}})().catch(()=>{}),()=>{j.abort()}}async handle($,O){if(!this.secret)throw new f("webhookSecret is required to verify incoming webhook deliveries");if(!await m7({secret:this.secret,timestamp:O.timestamp??"",rawBody:$,signature:O.signature??""}))throw new f("invalid webhook signature");if(O.event===v9)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=h9(this.client,j);if(!S)return;await Promise.all([...x].map((K)=>K(S)))}}function u7(){return}var m9=0,d1;function u9($){d1=$}function I$($,O,j){if(!j&&!d1)return $;let x=(S)=>{for(let K of[d1,j])try{Promise.resolve(K?.(S)).catch(()=>{})}catch{}};return new Proxy($,{get(S,K,Z){let X=Reflect.get(S,K,Z);if(typeof K!=="string"||typeof X!=="function")return X;return async(...Y)=>{let L={id:++m9,service:O,operation:K};x({...L,status:"started"});try{let G=await Reflect.apply(X,S,Y),J=G!==null&&typeof G==="object"&&"error"in G&&G.error!=null;return x({...L,status:J?"failed":"completed"}),G}catch(G){throw x({...L,status:"failed"}),G}}}})}var d7="x-macro-user-api-key",c9="mak_",l1="mbot_";function d9($){return k($).with(t.string.startsWith(l1),()=>{throw Error("bot token passed as a user credential. Use auth: { type: 'bot', token } or MACRO_BOT_TOKEN.")}).with(t.string.startsWith(c9),(O)=>[d7,O]).otherwise((O)=>["Authorization",`Bearer ${O}`])}async function c7($){return typeof $==="function"?await $():$}async function l9($,O,j){return k($).with({type:"bot"},async(x)=>{let S=await c7(x.token);if(!S.startsWith(l1))throw Error("user API key passed as a bot token. Use auth: { type: 'user', apiKey } or MACRO_API_KEY.");let K=[["x-macro-bot-token",S]];if(!j?.hasBotScope)K.push(["x-macro-bot-scope",x.scope??(O?"user":"team")]);if(O)K.push(["x-macro-bot-for-macro-user-id",O]);return K}).with({type:"user",apiKey:t.string},({apiKey:x})=>{if(x.startsWith(l1))throw Error("bot token passed as a user credential. Use auth: { type: 'bot', token } or MACRO_BOT_TOKEN.");return[[d7,x]]}).with({type:"user"},async({token:x})=>{return[d9(await c7(x))]}).exhaustive()}class r1{scheduledAction;unfurl;agentHarness;auth;calendar;cognition;contacts;email;notification;properties;search;storage;webAppUrl;wsVerify;events;authConfig;hosts;localPortmap;requestedAs;selfBotRecord;selfPrincipal;constructor($){let O=r9($),j=O==="local"?u7():void 0,x={...u1[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??b7[O],this.authConfig=p9($),this.requestedAs=$.requestedAs,this.requestedAs&&this.authConfig.type!=="bot")throw Error("requestedAs() requires bot auth — a user token always acts as its own user");this.wsVerify=$.wsVerify,this.scheduledAction=I$(new M0({client:this.makeClient(x["scheduled-action"])}),"scheduled-action",$.onRequest),this.unfurl=I$(new m0({client:this.makeClient(x.unfurl)}),"unfurl",$.onRequest),this.agentHarness=I$(new hj({client:this.makeClient(x["agent-harness"])}),"agent-harness",$.onRequest),this.auth=I$(new lj({client:this.makeClient(x.auth)}),"auth",$.onRequest),this.calendar=I$(new nj({client:this.makeClient(x.calendar)}),"calendar",$.onRequest),this.cognition=I$(new $0({client:this.makeClient(x.cognition)}),"cognition",$.onRequest),this.contacts=I$(new Z0({client:this.makeClient(x.contacts)}),"contacts",$.onRequest),this.email=I$(new G0({client:this.makeClient(x.email)}),"email",$.onRequest),this.notification=I$(new L0({client:this.makeClient(x.notification)}),"notification",$.onRequest),this.properties=I$(new H0({client:this.makeClient(x.properties)}),"properties",$.onRequest),this.search=I$(new E0({client:this.makeClient(x.search)}),"search",$.onRequest),this.storage=I$(new k0({client:this.makeClient(x.storage)}),"storage",$.onRequest);let K=typeof process<"u"?{}.MACRO_WEBHOOK_SECRET:void 0,Z=$.webhookSecret??K;this.events=new c1(this,Z)}hasActingUser(){return this.authConfig.type==="user"||this.requestedAs!==void 0}selfBot(){return this.selfBotRecord??=new aO(this).me().catch(($)=>{throw this.selfBotRecord=void 0,$}),this.selfBotRecord}myPrincipalId(){return this.selfPrincipal??=(this.authConfig.type==="bot"?this.selfBot().then(($)=>`bot|${$.id}`):C.me(this).then(($)=>$.id)).catch(($)=>{throw this.selfPrincipal=void 0,$}),this.selfPrincipal}makeClient($){let O=Vj({baseUrl:$});return O.interceptors.request.use(async(j)=>{let x=await l9(this.authConfig,this.requestedAs,{hasBotScope:j.headers.has("x-macro-bot-scope")});for(let[S,K]of x)j.headers.set(S,K);return j}),O}}function r9($){if($.env)return $.env;let O=typeof process<"u"?{}.MACRO_ENV:void 0;if(!O)return"prod";if(!(O in u1))throw Error(`invalid MACRO_ENV "${O}" — expected local, dev, or prod`);return O}function p9($){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 p1{id;constructor($){this.id=$}static byId($){return new p1($)}toJSON(){return{id:this.id}}}class l7{routines;unfurls;agents;initiatives;apiKeys;harnesses;meetings;githubPullRequests;entityMentions;agentSessions;ai;bots;calendar;calls;channels;externalChats;whatsapp;chats;crm;databases;documents;email;favorites;foreignEntities;forms;images;notifications;pins;projects;properties;referrals;tasks;teams;users;webhooks;workspace;events;webAppUrl;_client;opts;constructor($){this.opts=$;let O=new r1($);this._client=O,this.routines=new kx(O),this.unfurls=new vx(O),this.agents=new t0(O),this.initiatives=new Cx(O),this.apiKeys=new o0(O),this.harnesses=new _x(O),this.meetings=new Px(O),this.githubPullRequests=new Dx(O),this.entityMentions=new Nx(O),this.agentSessions=new s0(O),this.ai=new e0(O),this.bots=new aO(O),this.calendar=new $x(O),this.calls=new Ox(O),this.channels=new xx(O),this.externalChats=new zx(O),this.whatsapp=new ux(O),this.chats=new Sx(O),this.crm=new Xx(O),this.databases=new Vx(O),this.documents=new Wx(O),this.email=new Lx(O),this.favorites=new Ix(O),this.foreignEntities=new Hx(O),this.forms=new Tx(O),this.images=new Mx(O),this.notifications=new Ax(O),this.pins=new Fx(O),this.projects=new Ex(O),this.properties=new qx(O),this.referrals=new wx(O),this.tasks=new gx(O),this.teams=new yx(O),this.users=new hx(O),this.webhooks=new mx(O),this.workspace=new rx(O),this.events=O.events,this.webAppUrl=O.webAppUrl}myPrincipalId(){return this._client.myPrincipalId()}requestedAs($){return new l7({...this.opts,requestedAs:$.id})}}export{o$ as wrapXml,O$ as toBody,u9 as observeRequests,Q5 as msg,Y5 as here,NO as WhatsAppChat,CO as WhatsAppAccount,OO as UserApiKey,pO as ToolApproval,HO as TeamInvite,Ej as StaticImage,N$ as SessionReview,bx as RoutineExecution,v$ as Routine,n0 as ReviewItem,Rx as PullRequestChangeset,Tj as PipelineTable,JO as PipelineRow,Rj as PipelineColumn,L$ as MessageThread,D$ as Meeting,Jx as MacroOpRefusedError,l7 as Macro,a$ as Initiative,_O as HarnessPairing,B$ as Harness,DO as GithubPullRequest,qj as GeneratedImage,p$ as FormSection,RO as FormResponse,Fj as FormReference,r$ as FormQuestion,UO as FormOption,y$ as Form,ZO as ExternalChatUpload,XO as ExternalChatSend,SO as ExternalChatParticipant,M$ as ExternalChatMessage,g$ as ExternalChat,TO as EntityMention,$$ as EntityAccess,LO as EmailFilter,BO as EmailDraft,oO as DraftAttachment,eO as DocumentVersion,VO as DocumentAnchor,$j as DevicePairing,jO as CrmPipeline,a0 as ConversationTurn,rO as CodeExecution,sO as ChatMessage,nO as ChatGeneration,p1 as ChannelPicture,GO as ChannelActivity,Uj as AgentConversation,T$ as Agent,IO as AccessRequest};
diff --git a/crates/email/Cargo.toml b/crates/email/Cargo.toml
index 8ef6bf5197..ae67806b7e 100644
--- a/crates/email/Cargo.toml
+++ b/crates/email/Cargo.toml
@@ -26,7 +26,9 @@ ai_schema = ["dep:schemars"]
ai_tools = [
"dep:ai_toolset",
"dep:async-trait",
+ "dep:email_validator",
"dep:schemars",
+ "dep:specta",
"ports",
]
axum = [
@@ -61,6 +63,7 @@ async-trait = { workspace = true, optional = true }
aws-sdk-s3 = { workspace = true, optional = true }
base64 = { workspace = true }
lexical_client = { path = "../lexical_client" }
+email_validator = { path = "../email_validator", optional = true }
entity_access = { path = "../entity_access" }
entity_access_management = { path = "../entity_access_management", default-features = false, features = [
"ports",
@@ -98,6 +101,7 @@ recursion = { workspace = true }
reqwest = { workspace = true, optional = true }
rootcause = { workspace = true }
schemars = { workspace = true, optional = true, features = ["uuid1"] }
+specta = { workspace = true, optional = true, features = ["uuid"] }
serde = { workspace = true }
serde_json = { workspace = true }
serde_with = { workspace = true }
diff --git a/crates/email/src/inbound/toolset.rs b/crates/email/src/inbound/toolset.rs
index 0230950674..ccfd6f2e94 100644
--- a/crates/email/src/inbound/toolset.rs
+++ b/crates/email/src/inbound/toolset.rs
@@ -28,7 +28,7 @@ pub use get_thread::{GetThread, GetThreadResponse};
pub use list_inboxes::{ListInboxes, ListInboxesResponse, ToolInbox};
pub use list_labels::{ListLabels, ListLabelsResponse, ToolLabel};
pub use send_confirmed_email::SendConfirmedEmail;
-pub use send_email::{EmailAttachment, SendEmail, SendEmailResponse};
+pub use send_email::{EmailAttachment, EmailRecipient, SendEmail, SendEmailResponse};
pub use set_sender_policy::{SetSenderPolicy, SetSenderPolicyResponse, ToolSenderPolicy};
pub use update_thread_labels::{UpdateThreadLabels, UpdateThreadLabelsResponse};
diff --git a/crates/email/src/inbound/toolset/send_email.rs b/crates/email/src/inbound/toolset/send_email.rs
index aa3eb22d56..b371138f7b 100644
--- a/crates/email/src/inbound/toolset/send_email.rs
+++ b/crates/email/src/inbound/toolset/send_email.rs
@@ -7,6 +7,7 @@ use crate::domain::{
use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};
use ai_toolset::{ToolAnnotated, ToolAnnotations};
use async_trait::async_trait;
+use email_validator::EmailAddress;
use entity_access::domain::{models::ViewAccessLevel, ports::EntityAccessService};
use macro_user_id::user_id::MacroUserIdStr;
use model_entity::EntityType;
@@ -17,11 +18,11 @@ use uuid::Uuid;
use super::EmailToolContext;
/// A recipient for an email.
-#[derive(Debug, Clone, Deserialize, JsonSchema)]
+#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, specta::Type)]
#[serde(rename_all = "camelCase")]
pub struct EmailRecipient {
/// The recipient's email address.
- pub email: String,
+ pub email: EmailAddress,
/// The recipient's display name (optional).
#[serde(default)]
pub name: Option<String>,
@@ -30,7 +31,7 @@ pub struct EmailRecipient {
impl From<EmailRecipient> for ContactInfo {
fn from(r: EmailRecipient) -> Self {
ContactInfo {
- email: r.email,
+ email: r.email.into_inner(),
name: r.name,
photo_url: None,
}
@@ -38,7 +39,7 @@ impl From<EmailRecipient> for ContactInfo {
}
/// A Macro document attached to an outgoing email as a file.
-#[derive(Debug, Clone, Deserialize, JsonSchema)]
+#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, specta::Type)]
#[serde(rename_all = "camelCase")]
pub struct EmailAttachment {
/// The id of the Macro document to attach. It must be a stored file -
@@ -49,7 +50,7 @@ pub struct EmailAttachment {
}
/// Compose and send an email. Creates a draft and immediately queues it for delivery.
-#[derive(Debug, Deserialize, JsonSchema, Clone)]
+#[derive(Debug, Serialize, Deserialize, JsonSchema, specta::Type, Clone)]
#[schemars(
title = "SendEmail",
description = "Draft, compose, and send an email the user confirms in a review card or composer. Use this tool whenever the user asks you to draft, write, compose, or send an email (or reply to one) from the agent session view or from chat — never write the email as plain text there. It opens the draft for the user to review, edit, and confirm before it is sent, so it is the correct tool even when the user only wants a draft. Do NOT use it for a prompt that came from a channel or document thread — the context block names a conversation parent when it did, and there is no surface to review a draft in: write the email out in your reply, ask whether to send it, and use SendConfirmedEmail once the user approves. To reply to an existing message, provide the replying_to_id; the reply then goes out from the inbox that received it unless `from` says otherwise. To attach files, list the Macro documents in attachments — uploaded files such as PDFs, images, spreadsheets, or Word documents the user can view; the user can add or remove attachments in the composer before sending. Write the body in Markdown — use **bold**, *italics*, lists, links, and other standard Markdown formatting. The draft composer renders the Markdown for the user to review and edit; the composer produces HTML that is sent as the actual email body."
@@ -97,7 +98,7 @@ pub struct SendEmail {
}
/// Response from the SendEmail tool.
-#[derive(Debug, Serialize, JsonSchema)]
+#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, specta::Type)]
#[serde(rename_all = "camelCase")]
pub enum SendEmailResponse {
Sent {
diff --git a/crates/email_validator/Cargo.toml b/crates/email_validator/Cargo.toml
index 96466eede5..700a4ddcc2 100644
--- a/crates/email_validator/Cargo.toml
+++ b/crates/email_validator/Cargo.toml
@@ -6,5 +6,12 @@ version = "0.1.0"
[dependencies]
lazy_static = { workspace = true }
+nutype = { workspace = true }
regex = { workspace = true }
+schemars = { workspace = true }
+serde = { workspace = true }
+specta = { workspace = true }
workspace-hack = { version = "0.1", path = "../workspace-hack" }
+
+[dev-dependencies]
+serde_json = { workspace = true }
diff --git a/crates/email_validator/src/lib.rs b/crates/email_validator/src/lib.rs
index 4b6c4163bf..215bc3db39 100644
--- a/crates/email_validator/src/lib.rs
+++ b/crates/email_validator/src/lib.rs
@@ -113,3 +113,14 @@ mod tests {
}
}
}
+
+/// An address that passes [`is_valid_email`]; decoding rejects any other string.
+#[nutype::nutype(
+ validate(predicate = |address| is_valid_email(address)),
+ derive(Debug, Clone, PartialEq, Eq, Hash, AsRef, Display, Serialize, Deserialize),
+ derive_unchecked(schemars::JsonSchema, specta::Type)
+)]
+pub struct EmailAddress(String);
+
+#[cfg(test)]
+mod test;
diff --git a/crates/email_validator/src/test.rs b/crates/email_validator/src/test.rs
new file mode 100644
index 0000000000..d07bf020f8
--- /dev/null
+++ b/crates/email_validator/src/test.rs
@@ -0,0 +1,10 @@
+use super::EmailAddress;
+
+#[test]
+fn decodes_only_valid_addresses() {
+ let address: EmailAddress = serde_json::from_str(r#""[email protected]""#).unwrap();
+ assert_eq!(address.as_ref(), "[email protected]");
+
+ assert!(serde_json::from_str::<EmailAddress>(r#""Ada <[email protected]>""#).is_err());
+ assert!(serde_json::from_str::<EmailAddress>(r#""ada@""#).is_err());
+}
diff --git a/crates/import/Cargo.toml b/crates/import/Cargo.toml
index 15d09ba778..b7f1b07162 100644
--- a/crates/import/Cargo.toml
+++ b/crates/import/Cargo.toml
@@ -34,6 +34,7 @@ properties = { path = "../properties", default-features = false, features = [
] }
regex = { workspace = true }
schemars = { workspace = true }
+specta = { workspace = true, features = ["uuid"] }
serde = { workspace = true }
serde_json = { workspace = true }
sqlx = { workspace = true }
diff --git a/crates/import/src/domain/models.rs b/crates/import/src/domain/models.rs
index b1819c43a8..07b1634d00 100644
--- a/crates/import/src/domain/models.rs
+++ b/crates/import/src/domain/models.rs
@@ -165,6 +165,7 @@ impl ImportSource {
Serialize,
Deserialize,
JsonSchema,
+ specta::Type,
ToSchema,
strum::EnumString,
strum::AsRefStr,
@@ -278,6 +279,7 @@ pub enum Initiator {
Deserialize,
ToSchema,
JsonSchema,
+ specta::Type,
strum::EnumString,
strum::AsRefStr,
)]
@@ -900,7 +902,17 @@ pub struct ImportRun {
/// What a planning run has found in the source so far.
#[derive(
- Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema, ToSchema,
+ Debug,
+ Clone,
+ Copy,
+ Default,
+ PartialEq,
+ Eq,
+ Serialize,
+ Deserialize,
+ JsonSchema,
+ specta::Type,
+ ToSchema,
)]
#[serde(rename_all = "camelCase")]
pub struct ScanCounts {
@@ -921,7 +933,9 @@ pub struct ImportState {
}
/// One object a workspace import report calls out.
-#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, ToSchema)]
+#[derive(
+ Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, specta::Type, ToSchema,
+)]
#[serde(rename_all = "camelCase")]
pub struct NotionReportItem {
/// The ledger row.
@@ -939,7 +953,9 @@ pub struct NotionReportItem {
}
/// Where a Notion workspace import stands.
-#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema, ToSchema)]
+#[derive(
+ Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema, specta::Type, ToSchema,
+)]
#[serde(rename_all = "camelCase")]
pub struct NotionImportReport {
/// Provider items skipped because they were unreadable, or optional features unavailable.
diff --git a/crates/import/src/domain/models/notion_sharing.rs b/crates/import/src/domain/models/notion_sharing.rs
index ba77283d40..84515b3d7f 100644
--- a/crates/import/src/domain/models/notion_sharing.rs
+++ b/crates/import/src/domain/models/notion_sharing.rs
@@ -56,7 +56,9 @@ pub struct NotionWriteChoices {
}
/// A teammate who already imported some of a plan's objects.
-#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, ToSchema)]
+#[derive(
+ Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, specta::Type, ToSchema,
+)]
#[serde(rename_all = "camelCase")]
pub struct NotionImporter {
/// The teammate, by email.
diff --git a/crates/workspace-hack/Cargo.toml b/crates/workspace-hack/Cargo.toml
index 0b9d7dfc99..2f93a6e500 100644
--- a/crates/workspace-hack/Cargo.toml
+++ b/crates/workspace-hack/Cargo.toml
@@ -145,6 +145,7 @@ sha2 = { version = "0.10", features = ["oid"] }
simd-adler32 = { version = "0.3" }
slab = { version = "0.4" }
smallvec = { version = "1", default-features = false, features = ["const_new", "serde"] }
+specta = { version = "2.0.0-rc.25", features = ["chrono", "derive", "uuid"] }
spin = { version = "0.9", default-features = false, features = ["once", "spin_mutex"] }
sqlx-core = { version = "0.8", features = ["_rt-tokio", "_tls-rustls-ring-webpki", "any", "chrono", "json", "migrate", "offline", "uuid"] }
sqlx-postgres = { version = "0.8", default-features = false, features = ["any", "chrono", "json", "migrate", "offline", "uuid"] }
@@ -311,6 +312,8 @@ sha2 = { version = "0.10", features = ["oid"] }
simd-adler32 = { version = "0.3" }
slab = { version = "0.4" }
smallvec = { version = "1", default-features = false, features = ["const_new", "serde"] }
+specta = { version = "2.0.0-rc.25", features = ["chrono", "derive", "uuid"] }
+specta-macros = { version = "2.0.0-rc.25", features = ["serde"] }
spin = { version = "0.9", default-features = false, features = ["once", "spin_mutex"] }
sqlx-core = { version = "0.8", features = ["_rt-tokio", "_tls-rustls-ring-webpki", "any", "chrono", "json", "migrate", "offline", "uuid"] }
sqlx-postgres = { version = "0.8", default-features = false, features = ["any", "chrono", "json", "migrate", "offline", "uuid"] }
diff --git a/packages/code-mode-sdk/src/documentation.test.ts b/packages/code-mode-sdk/src/documentation.test.ts
index 62275807e4..3b6d0d7c87 100644
--- a/packages/code-mode-sdk/src/documentation.test.ts
+++ b/packages/code-mode-sdk/src/documentation.test.ts
@@ -164,7 +164,7 @@ describe('TypeDoc documentation packaging', () => {
};
expect(entity('agentSessions')).toContain('### SessionReview');
expect(entity('agentSessions')).toContain('`SessionReview.submitAll`');
- expect(docs.symbols.ReviewRecord).toContain('presentedAt');
+ expect(docs.symbols.ReviewRecord_Serialize).toContain('presentedAt');
expect(docs.symbols.SessionReview).not.toContain('property-parent');
expect(docs.symbols.SessionReview).not.toContain('property-client');
expect(docs.symbols.SessionReview).not.toContain('private constructor');
diff --git a/packages/sdk-docs/reference/generated/agent-harness/types.gen/README.md b/packages/sdk-docs/reference/generated/agent-harness/types.gen/README.md
index f9b129b229..8907b24c34 100644
--- a/packages/sdk-docs/reference/generated/agent-harness/types.gen/README.md
+++ b/packages/sdk-docs/reference/generated/agent-harness/types.gen/README.md
@@ -331,9 +331,6 @@
- [ReviewDecision](type-aliases/ReviewDecision.md)
- [ReviewDecisionContext](type-aliases/ReviewDecisionContext.md)
- [ReviewId](type-aliases/ReviewId.md)
-- [ReviewItem](type-aliases/ReviewItem.md)
-- [ReviewItemStatus](type-aliases/ReviewItemStatus.md)
-- [ReviewKind](type-aliases/ReviewKind.md)
- [ReviewRecord](type-aliases/ReviewRecord.md)
- [SandboxSize](type-aliases/SandboxSize.md)
- [SandboxSizeBody](type-aliases/SandboxSizeBody.md)
diff --git a/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/CreateReview.md b/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/CreateReview.md
index 2cbf9bc2a7..6468b89c83 100644
--- a/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/CreateReview.md
+++ b/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/CreateReview.md
@@ -1,14 +1,13 @@
# Type Alias: CreateReview
-> **CreateReview** = \{ `drafts`: `unknown`[]; `executionId?`: `null` \| [`ExecutionId`](ExecutionId.md); `kind`: [`ReviewKind`](ReviewKind.md); `title`: `string`; \}
+> **CreateReview** = \{\[`key`: `string`\]: `unknown`; \} & \{ `executionId?`: `null` \| [`ExecutionId`](ExecutionId.md); `title`: `string`; \}
-Review creation. Drafts are validated by the action's owning adapter.
+Review creation. Decoding it validates every draft; creating a review only
+presents the drafts, and the account holder acts separately.
-## Properties
+## Type Declaration
-| Property | Type | Description |
+| Name | Type | Description |
| ------ | ------ | ------ |
-| <a id="property-drafts"></a> `drafts` | `unknown`[] | One to one hundred independent drafts. Email: {subject, body: Markdown, to: [{email, name?}], cc?: [{email, name?}], bcc?: [{email, name?}], replyingToId?, attachments?: [{documentId}]}. Calendar: {title, time: {kind: "timed", startsAt: ISO datetime, endsAt: ISO datetime, timeZone?: IANA zone} or {kind: "allDay", startDate: ISO date, endDate: exclusive ISO date}, description?, location?, attendees?: [{email, isOptional?}]}. Import: exactly one draft {source: "notion" \| "linear" \| "jira"}, presenting the plan ImportFromNotion, ImportFromLinear or ImportFromJira staged. Creating any review only presents these drafts; the user acts separately. |
-| <a id="property-executionid"></a> `executionId?` | `null` \| [`ExecutionId`](ExecutionId.md) | - |
-| <a id="property-kind"></a> `kind` | [`ReviewKind`](ReviewKind.md) | Existing UI and action to use. |
-| <a id="property-title"></a> `title` | `string` | Stack label. |
+| `executionId?` | `null` \| [`ExecutionId`](ExecutionId.md) | - |
+| `title` | `string` | Stack label. |
diff --git a/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/ReviewDecision.md b/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/ReviewDecision.md
index 9ae72af80e..fe6facae25 100644
--- a/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/ReviewDecision.md
+++ b/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/ReviewDecision.md
@@ -1,6 +1,6 @@
# Type Alias: ReviewDecision
-> **ReviewDecision** = \{ `action`: `"edit"`; `draft`: `unknown`; `item`: `string`; `revision`: `number`; \} \| \{ `action`: `"submit"`; `items`: `string`[]; `revision`: `number`; \} \| \{ `action`: `"dismiss"`; `items`: `string`[]; `revision`: `number`; \}
+> **ReviewDecision** = \{ `action`: `"edit"`; `draft`: \{\[`key`: `string`\]: `unknown`; \}; `item`: `string`; `revision`: `number`; \} \| \{ `action`: `"submit"`; `items`: `string`[]; `revision`: `number`; \} \| \{ `action`: `"dismiss"`; `items`: `string`[]; `revision`: `number`; \}
One atomic user decision against the displayed revision.
@@ -8,12 +8,12 @@ One atomic user decision against the displayed revision.
### Type Literal
-\{ `action`: `"edit"`; `draft`: `unknown`; `item`: `string`; `revision`: `number`; \}
+\{ `action`: `"edit"`; `draft`: \{\[`key`: `string`\]: `unknown`; \}; `item`: `string`; `revision`: `number`; \}
| Name | Type | Description |
| ------ | ------ | ------ |
| `action` | `"edit"` | - |
-| `draft` | `unknown` | Replacement action arguments. |
+| `draft` | \{\[`key`: `string`\]: `unknown`; \} | Replacement action arguments, keyed by the review's kind. |
| `item` | `string` | Pending item to update. |
| `revision` | `number` | Revision displayed by the caller. |
diff --git a/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/ReviewItem.md b/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/ReviewItem.md
deleted file mode 100644
index c177b891fb..0000000000
--- a/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/ReviewItem.md
+++ /dev/null
@@ -1,16 +0,0 @@
-# Type Alias: ReviewItem
-
-> **ReviewItem** = \{ `draft`: `unknown`; `edited?`: `boolean`; `error?`: `string` \| `null`; `id`: `string`; `result?`: `unknown`; `status`: [`ReviewItemStatus`](ReviewItemStatus.md); \}
-
-One editable item and its durable outcome.
-
-## Properties
-
-| Property | Type | Description |
-| ------ | ------ | ------ |
-| <a id="property-draft"></a> `draft` | `unknown` | Validated arguments for the existing composer/action. |
-| <a id="property-edited"></a> `edited?` | `boolean` | Whether the account holder edited this draft before deciding. |
-| <a id="property-error"></a> `error?` | `string` \| `null` | Failure or uncertainty description. |
-| <a id="property-id"></a> `id` | `string` | Stable item identity across stack navigation and edits. |
-| <a id="property-result"></a> `result?` | `unknown` | Actual backend response, never a model assertion. |
-| <a id="property-status"></a> `status` | [`ReviewItemStatus`](ReviewItemStatus.md) | Current outcome. |
diff --git a/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/ReviewItemStatus.md b/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/ReviewItemStatus.md
deleted file mode 100644
index 5cd8e19eb7..0000000000
--- a/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/ReviewItemStatus.md
+++ /dev/null
@@ -1,5 +0,0 @@
-# Type Alias: ReviewItemStatus
-
-> **ReviewItemStatus** = `"pending"` \| `"submitting"` \| `"completed"` \| `"dismissed"` \| `"unknown"`
-
-Review item state, shared with notification consumers.
diff --git a/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/ReviewKind.md b/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/ReviewKind.md
deleted file mode 100644
index d39811e1f9..0000000000
--- a/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/ReviewKind.md
+++ /dev/null
@@ -1,5 +0,0 @@
-# Type Alias: ReviewKind
-
-> **ReviewKind** = `"email"` \| `"calendar"` \| `"import"`
-
-The component and action used to finish a review.
diff --git a/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/ReviewRecord.md b/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/ReviewRecord.md
index 59fb328317..ce06a7c268 100644
--- a/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/ReviewRecord.md
+++ b/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/ReviewRecord.md
@@ -1,21 +1,19 @@
# Type Alias: ReviewRecord
-> **ReviewRecord** = \{ `actingUser?`: `string` \| `null`; `decision?`: `null` \| [`ReviewDecisionContext`](ReviewDecisionContext.md); `executionId?`: `null` \| [`ExecutionId`](ExecutionId.md); `id`: [`ReviewId`](ReviewId.md); `items`: [`ReviewItem`](ReviewItem.md)[]; `kind`: [`ReviewKind`](ReviewKind.md); `presentedAt?`: `number` \| `null`; `revision`: `number`; `sessionId`: `string`; `title`: `string`; `updatedAt`: `number`; \}
+> **ReviewRecord** = \{\[`key`: `string`\]: `unknown`; \} & \{ `actingUser`: `string`; `decision?`: `null` \| [`ReviewDecisionContext`](ReviewDecisionContext.md); `executionId?`: `null` \| [`ExecutionId`](ExecutionId.md); `id`: [`ReviewId`](ReviewId.md); `presentedAt?`: `number` \| `null`; `revision`: `number`; `sessionId`: `string`; `title`: `string`; `updatedAt`: `number`; \}
Full UI record, fetched outside the model context.
-## Properties
+## Type Declaration
-| Property | Type | Description |
+| Name | Type | Description |
| ------ | ------ | ------ |
-| <a id="property-actinguser"></a> `actingUser?` | `string` \| `null` | Account whose email/calendar the drafts use; historical records use the session owner. |
-| <a id="property-decision"></a> `decision?` | `null` \| [`ReviewDecisionContext`](ReviewDecisionContext.md) | - |
-| <a id="property-executionid"></a> `executionId?` | `null` \| [`ExecutionId`](ExecutionId.md) | - |
-| <a id="property-id"></a> `id` | [`ReviewId`](ReviewId.md) | Review identity. |
-| <a id="property-items"></a> `items` | [`ReviewItem`](ReviewItem.md)[] | Drafts and per-item outcomes. |
-| <a id="property-kind"></a> `kind` | [`ReviewKind`](ReviewKind.md) | Component kind. |
-| <a id="property-presentedat"></a> `presentedAt?` | `number` \| `null` | Durable presentation acknowledgment, separate from user decisions. |
-| <a id="property-revision"></a> `revision` | `number` | Compare-and-swap revision for edits and submissions. |
-| <a id="property-sessionid"></a> `sessionId` | `string` | Owning session. |
-| <a id="property-title"></a> `title` | `string` | Stack label. |
-| <a id="property-updatedat"></a> `updatedAt` | `number` | Milliseconds since epoch of the last state change. |
+| `actingUser` | `string` | Account whose email/calendar the drafts use. |
+| `decision?` | `null` \| [`ReviewDecisionContext`](ReviewDecisionContext.md) | - |
+| `executionId?` | `null` \| [`ExecutionId`](ExecutionId.md) | - |
+| `id` | [`ReviewId`](ReviewId.md) | Review identity. |
+| `presentedAt?` | `number` \| `null` | Durable presentation acknowledgment, separate from user decisions. |
+| `revision` | `number` | Compare-and-swap revision for edits and submissions. |
+| `sessionId` | `string` | Owning session. |
+| `title` | `string` | Stack label. |
+| `updatedAt` | `number` | Milliseconds since epoch of the last state change. |
diff --git a/packages/sdk-docs/reference/generated/agent-reviews/README.md b/packages/sdk-docs/reference/generated/agent-reviews/README.md
new file mode 100644
index 0000000000..f9844d5286
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/agent-reviews/README.md
@@ -0,0 +1,62 @@
+# generated/agent-reviews
+
+## Type Aliases
+
+- [AttendeeInput](type-aliases/AttendeeInput.md)
+- [AutoDeclineModeInput](type-aliases/AutoDeclineModeInput.md)
+- [CalendarEventTypeInput](type-aliases/CalendarEventTypeInput.md)
+- [CreateCalendarEvent](type-aliases/CreateCalendarEvent.md)
+- [CreateCalendarEvent\_Deserialize](type-aliases/CreateCalendarEvent_Deserialize.md)
+- [CreateCalendarEvent\_Serialize](type-aliases/CreateCalendarEvent_Serialize.md)
+- [CreateReview](type-aliases/CreateReview.md)
+- [CreateReview\_Deserialize](type-aliases/CreateReview_Deserialize.md)
+- [CreateReview\_Serialize](type-aliases/CreateReview_Serialize.md)
+- [DecisionVia](type-aliases/DecisionVia.md)
+- [DraftList](type-aliases/DraftList.md)
+- [EmailAddress](type-aliases/EmailAddress.md)
+- [EmailAttachment](type-aliases/EmailAttachment.md)
+- [EmailRecipient](type-aliases/EmailRecipient.md)
+- [EventReminderOverrideInput](type-aliases/EventReminderOverrideInput.md)
+- [EventRemindersInput](type-aliases/EventRemindersInput.md)
+- [EventTimeInput](type-aliases/EventTimeInput.md)
+- [ExecutionId](type-aliases/ExecutionId.md)
+- [GuestPolicy](type-aliases/GuestPolicy.md)
+- [ImportDraft](type-aliases/ImportDraft.md)
+- [ImportKind](type-aliases/ImportKind.md)
+- [ImportReviewSource](type-aliases/ImportReviewSource.md)
+- [ItemStatus](type-aliases/ItemStatus.md)
+- [NotionImporter](type-aliases/NotionImporter.md)
+- [NotionImportReport](type-aliases/NotionImportReport.md)
+- [NotionImportReport\_Deserialize](type-aliases/NotionImportReport_Deserialize.md)
+- [NotionImportReport\_Serialize](type-aliases/NotionImportReport_Serialize.md)
+- [NotionReportItem](type-aliases/NotionReportItem.md)
+- [NotionReportItem\_Deserialize](type-aliases/NotionReportItem_Deserialize.md)
+- [NotionReportItem\_Serialize](type-aliases/NotionReportItem_Serialize.md)
+- [OutOfOfficeInput](type-aliases/OutOfOfficeInput.md)
+- [ReviewDecision](type-aliases/ReviewDecision.md)
+- [ReviewDecision\_Deserialize](type-aliases/ReviewDecision_Deserialize.md)
+- [ReviewDecision\_Serialize](type-aliases/ReviewDecision_Serialize.md)
+- [ReviewDecisionContext](type-aliases/ReviewDecisionContext.md)
+- [ReviewDraft](type-aliases/ReviewDraft.md)
+- [ReviewDraft\_Deserialize](type-aliases/ReviewDraft_Deserialize.md)
+- [ReviewDraft\_Serialize](type-aliases/ReviewDraft_Serialize.md)
+- [ReviewDrafts](type-aliases/ReviewDrafts.md)
+- [ReviewDrafts\_Deserialize](type-aliases/ReviewDrafts_Deserialize.md)
+- [ReviewDrafts\_Serialize](type-aliases/ReviewDrafts_Serialize.md)
+- [ReviewId](type-aliases/ReviewId.md)
+- [ReviewItem](type-aliases/ReviewItem.md)
+- [ReviewItems](type-aliases/ReviewItems.md)
+- [ReviewItems\_Deserialize](type-aliases/ReviewItems_Deserialize.md)
+- [ReviewItems\_Serialize](type-aliases/ReviewItems_Serialize.md)
+- [ReviewItemState](type-aliases/ReviewItemState.md)
+- [ReviewRecord](type-aliases/ReviewRecord.md)
+- [ReviewRecord\_Deserialize](type-aliases/ReviewRecord_Deserialize.md)
+- [ReviewRecord\_Serialize](type-aliases/ReviewRecord_Serialize.md)
+- [ReviewTitle](type-aliases/ReviewTitle.md)
+- [RunStatus](type-aliases/RunStatus.md)
+- [ScanCounts](type-aliases/ScanCounts.md)
+- [SendEmail](type-aliases/SendEmail.md)
+- [SendEmailResponse](type-aliases/SendEmailResponse.md)
+- [ToolCalendarEvent](type-aliases/ToolCalendarEvent.md)
+- [ToolEventAttendee](type-aliases/ToolEventAttendee.md)
+- [ToolEventRole](type-aliases/ToolEventRole.md)
diff --git a/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/AttendeeInput.md b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/AttendeeInput.md
new file mode 100644
index 0000000000..6a60c96f82
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/AttendeeInput.md
@@ -0,0 +1,12 @@
+# Type Alias: AttendeeInput
+
+> **AttendeeInput** = \{ `email`: [`EmailAddress`](EmailAddress.md); `isOptional?`: `boolean`; \}
+
+An attendee supplied to a calendar tool.
+
+## Properties
+
+| Property | Type | Description |
+| ------ | ------ | ------ |
+| <a id="property-email"></a> `email` | [`EmailAddress`](EmailAddress.md) | Attendee email address. |
+| <a id="property-isoptional"></a> `isOptional?` | `boolean` | Whether attendance is optional. |
diff --git a/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/AutoDeclineModeInput.md b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/AutoDeclineModeInput.md
new file mode 100644
index 0000000000..42abe7c9b4
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/AutoDeclineModeInput.md
@@ -0,0 +1,5 @@
+# Type Alias: AutoDeclineModeInput
+
+> **AutoDeclineModeInput** = `"decline_none"` \| `"decline_all"` \| `"decline_new_only"`
+
+How an out-of-office event handles conflicting invitations.
diff --git a/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/CalendarEventTypeInput.md b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/CalendarEventTypeInput.md
new file mode 100644
index 0000000000..69cb1a3881
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/CalendarEventTypeInput.md
@@ -0,0 +1,5 @@
+# Type Alias: CalendarEventTypeInput
+
+> **CalendarEventTypeInput** = `"default"` \| `"out_of_office"`
+
+The kind of event a create tool call makes.
diff --git a/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/CreateCalendarEvent.md b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/CreateCalendarEvent.md
new file mode 100644
index 0000000000..dd7aba7f45
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/CreateCalendarEvent.md
@@ -0,0 +1,5 @@
+# Type Alias: CreateCalendarEvent
+
+> **CreateCalendarEvent** = [`CreateCalendarEvent_Serialize`](CreateCalendarEvent_Serialize.md) \| [`CreateCalendarEvent_Deserialize`](CreateCalendarEvent_Deserialize.md)
+
+Create a calendar event.
diff --git a/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/CreateCalendarEvent_Deserialize.md b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/CreateCalendarEvent_Deserialize.md
new file mode 100644
index 0000000000..8f005a5bbc
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/CreateCalendarEvent_Deserialize.md
@@ -0,0 +1,19 @@
+# Type Alias: CreateCalendarEvent\_Deserialize
+
+> **CreateCalendarEvent\_Deserialize** = \{ `addMacroCall?`: `boolean`; `attendees?`: [`AttendeeInput`](AttendeeInput.md)[]; `calendarId?`: `string` \| `null`; `description?`: `string` \| `null`; `eventType?`: [`CalendarEventTypeInput`](CalendarEventTypeInput.md); `guestPolicy?`: [`GuestPolicy`](GuestPolicy.md) \| `null`; `location?`: `string` \| `null`; `outOfOffice?`: [`OutOfOfficeInput`](OutOfOfficeInput.md) \| `null`; `recurrenceLines?`: `string`[]; `reminders?`: [`EventRemindersInput`](EventRemindersInput.md) \| `null`; `time`: [`EventTimeInput`](EventTimeInput.md); `title`: `string`; \} & \{ `addConference?`: `boolean`; \} \| \{ `addGoogleMeet?`: `boolean`; \}
+
+Create a calendar event.
+
+## Union Members
+
+\{ `addMacroCall?`: `boolean`; `attendees?`: [`AttendeeInput`](AttendeeInput.md)[]; `calendarId?`: `string` \| `null`; `description?`: `string` \| `null`; `eventType?`: [`CalendarEventTypeInput`](CalendarEventTypeInput.md); `guestPolicy?`: [`GuestPolicy`](GuestPolicy.md) \| `null`; `location?`: `string` \| `null`; `outOfOffice?`: [`OutOfOfficeInput`](OutOfOfficeInput.md) \| `null`; `recurrenceLines?`: `string`[]; `reminders?`: [`EventRemindersInput`](EventRemindersInput.md) \| `null`; `time`: [`EventTimeInput`](EventTimeInput.md); `title`: `string`; \} & \{ `addConference?`: `boolean`; \}
+
+***
+
+### Type Literal
+
+\{ `addGoogleMeet?`: `boolean`; \}
+
+| Name | Type | Description |
+| ------ | ------ | ------ |
+| `addGoogleMeet?` | `boolean` | Whether to attach the calendar provider's meeting conference. |
diff --git a/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/CreateCalendarEvent_Serialize.md b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/CreateCalendarEvent_Serialize.md
new file mode 100644
index 0000000000..c9be1976f8
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/CreateCalendarEvent_Serialize.md
@@ -0,0 +1,23 @@
+# Type Alias: CreateCalendarEvent\_Serialize
+
+> **CreateCalendarEvent\_Serialize** = \{ `addConference`: `boolean`; `addMacroCall`: `boolean`; `attendees`: [`AttendeeInput`](AttendeeInput.md)[]; `calendarId`: `string` \| `null`; `description`: `string` \| `null`; `eventType`: [`CalendarEventTypeInput`](CalendarEventTypeInput.md); `guestPolicy`: [`GuestPolicy`](GuestPolicy.md) \| `null`; `location`: `string` \| `null`; `outOfOffice`: [`OutOfOfficeInput`](OutOfOfficeInput.md) \| `null`; `recurrenceLines`: `string`[]; `reminders`: [`EventRemindersInput`](EventRemindersInput.md) \| `null`; `time`: [`EventTimeInput`](EventTimeInput.md); `title`: `string`; \}
+
+Create a calendar event.
+
+## Properties
+
+| Property | Type | Description |
+| ------ | ------ | ------ |
+| <a id="property-addconference"></a> `addConference` | `boolean` | Whether to attach the calendar provider's meeting conference. |
+| <a id="property-addmacrocall"></a> `addMacroCall` | `boolean` | Whether to attach a Macro meeting link. |
+| <a id="property-attendees"></a> `attendees` | [`AttendeeInput`](AttendeeInput.md)[] | Attendees to invite. |
+| <a id="property-calendarid"></a> `calendarId` | `string` \| `null` | Calendar to create the event on. |
+| <a id="property-description"></a> `description` | `string` \| `null` | Optional event body. |
+| <a id="property-eventtype"></a> `eventType` | [`CalendarEventTypeInput`](CalendarEventTypeInput.md) | Kind of event to create. |
+| <a id="property-guestpolicy"></a> `guestPolicy` | [`GuestPolicy`](GuestPolicy.md) \| `null` | What guests may do with the event. |
+| <a id="property-location"></a> `location` | `string` \| `null` | Optional location label. |
+| <a id="property-outofoffice"></a> `outOfOffice` | [`OutOfOfficeInput`](OutOfOfficeInput.md) \| `null` | Out-of-office decline behavior. |
+| <a id="property-recurrencelines"></a> `recurrenceLines` | `string`[] | Recurrence properties. |
+| <a id="property-reminders"></a> `reminders` | [`EventRemindersInput`](EventRemindersInput.md) \| `null` | Reminder configuration. |
+| <a id="property-time"></a> `time` | [`EventTimeInput`](EventTimeInput.md) | Timed or all-day span. |
+| <a id="property-title"></a> `title` | `string` | Display title. |
diff --git a/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/CreateReview.md b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/CreateReview.md
new file mode 100644
index 0000000000..cb64d5c902
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/CreateReview.md
@@ -0,0 +1,6 @@
+# Type Alias: CreateReview
+
+> **CreateReview** = [`CreateReview_Serialize`](CreateReview_Serialize.md) \| [`CreateReview_Deserialize`](CreateReview_Deserialize.md)
+
+Review creation. Decoding it validates every draft; creating a review only
+ presents the drafts, and the account holder acts separately.
diff --git a/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/CreateReview_Deserialize.md b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/CreateReview_Deserialize.md
new file mode 100644
index 0000000000..a5dbc14f99
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/CreateReview_Deserialize.md
@@ -0,0 +1,13 @@
+# Type Alias: CreateReview\_Deserialize
+
+> **CreateReview\_Deserialize** = \{ `executionId?`: [`ExecutionId`](ExecutionId.md) \| `null`; `title`: [`ReviewTitle`](ReviewTitle.md); \} & [`ReviewDrafts_Deserialize`](ReviewDrafts_Deserialize.md)
+
+Review creation. Decoding it validates every draft; creating a review only
+ presents the drafts, and the account holder acts separately.
+
+## Type Declaration
+
+| Name | Type | Description |
+| ------ | ------ | ------ |
+| `executionId?` | [`ExecutionId`](ExecutionId.md) \| `null` | Optional code execution that prepared these drafts. |
+| `title` | [`ReviewTitle`](ReviewTitle.md) | Stack label. |
diff --git a/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/CreateReview_Serialize.md b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/CreateReview_Serialize.md
new file mode 100644
index 0000000000..bb14f9eddc
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/CreateReview_Serialize.md
@@ -0,0 +1,13 @@
+# Type Alias: CreateReview\_Serialize
+
+> **CreateReview\_Serialize** = \{ `executionId`: [`ExecutionId`](ExecutionId.md) \| `null`; `title`: [`ReviewTitle`](ReviewTitle.md); \} & [`ReviewDrafts_Serialize`](ReviewDrafts_Serialize.md)
+
+Review creation. Decoding it validates every draft; creating a review only
+ presents the drafts, and the account holder acts separately.
+
+## Type Declaration
+
+| Name | Type | Description |
+| ------ | ------ | ------ |
+| `executionId` | [`ExecutionId`](ExecutionId.md) \| `null` | Optional code execution that prepared these drafts. |
+| `title` | [`ReviewTitle`](ReviewTitle.md) | Stack label. |
diff --git a/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/DecisionVia.md b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/DecisionVia.md
new file mode 100644
index 0000000000..9f6f0962af
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/DecisionVia.md
@@ -0,0 +1,5 @@
+# Type Alias: DecisionVia
+
+> **DecisionVia** = `"card"` \| `"chat"` \| `"inbox"`
+
+Surface of a review decision.
diff --git a/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/DraftList.md b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/DraftList.md
new file mode 100644
index 0000000000..4ba1aaa863
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/DraftList.md
@@ -0,0 +1,11 @@
+# Type Alias: DraftList\<Draft\>
+
+> **DraftList**\<`Draft`\> = `Draft`[]
+
+One to [`MAX_DRAFTS`] drafts of one kind.
+
+## Type Parameters
+
+| Type Parameter |
+| ------ |
+| <a id="type-parameter-draft"></a> `Draft` |
diff --git a/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/EmailAddress.md b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/EmailAddress.md
new file mode 100644
index 0000000000..8ac5768d00
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/EmailAddress.md
@@ -0,0 +1,5 @@
+# Type Alias: EmailAddress
+
+> **EmailAddress** = `string`
+
+An address that passes [`is_valid_email`]; decoding rejects any other string.
diff --git a/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/EmailAttachment.md b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/EmailAttachment.md
new file mode 100644
index 0000000000..7ae2cf0bfa
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/EmailAttachment.md
@@ -0,0 +1,11 @@
+# Type Alias: EmailAttachment
+
+> **EmailAttachment** = \{ `documentId`: `string`; \}
+
+A Macro document attached to an outgoing email as a file.
+
+## Properties
+
+| Property | Type | Description |
+| ------ | ------ | ------ |
+| <a id="property-documentid"></a> `documentId` | `string` | The id of the Macro document to attach. It must be a stored file - an uploaded PDF, image, spreadsheet, Word document, or other upload - that the user can view. A Macro-native document (one written in the editor) has no file to attach; link to it in the body instead. |
diff --git a/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/EmailRecipient.md b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/EmailRecipient.md
new file mode 100644
index 0000000000..3a75ce9fe3
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/EmailRecipient.md
@@ -0,0 +1,12 @@
+# Type Alias: EmailRecipient
+
+> **EmailRecipient** = \{ `email`: [`EmailAddress`](EmailAddress.md); `name?`: `string` \| `null`; \}
+
+A recipient for an email.
+
+## Properties
+
+| Property | Type | Description |
+| ------ | ------ | ------ |
+| <a id="property-email"></a> `email` | [`EmailAddress`](EmailAddress.md) | The recipient's email address. |
+| <a id="property-name"></a> `name?` | `string` \| `null` | The recipient's display name (optional). |
diff --git a/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/EventReminderOverrideInput.md b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/EventReminderOverrideInput.md
new file mode 100644
index 0000000000..f02bb885dc
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/EventReminderOverrideInput.md
@@ -0,0 +1,12 @@
+# Type Alias: EventReminderOverrideInput
+
+> **EventReminderOverrideInput** = \{ `method`: `string`; `minutes`: `number`; \}
+
+One reminder override supplied to a calendar tool.
+
+## Properties
+
+| Property | Type | Description |
+| ------ | ------ | ------ |
+| <a id="property-method"></a> `method` | `string` | Provider reminder method. `popup` creates a Macro notification. |
+| <a id="property-minutes"></a> `minutes` | `number` | Minutes before the event start. |
diff --git a/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/EventRemindersInput.md b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/EventRemindersInput.md
new file mode 100644
index 0000000000..818c019a77
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/EventRemindersInput.md
@@ -0,0 +1,12 @@
+# Type Alias: EventRemindersInput
+
+> **EventRemindersInput** = \{ `overrides?`: [`EventReminderOverrideInput`](EventReminderOverrideInput.md)[]; `useDefault`: `boolean`; \}
+
+Reminder configuration supplied when creating a calendar event.
+
+## Properties
+
+| Property | Type | Description |
+| ------ | ------ | ------ |
+| <a id="property-overrides"></a> `overrides?` | [`EventReminderOverrideInput`](EventReminderOverrideInput.md)[] | Overrides used when calendar defaults are disabled. |
+| <a id="property-usedefault"></a> `useDefault` | `boolean` | Whether the selected calendar's default reminders should apply. |
diff --git a/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/EventTimeInput.md b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/EventTimeInput.md
new file mode 100644
index 0000000000..8baafeb4a8
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/EventTimeInput.md
@@ -0,0 +1,34 @@
+# Type Alias: EventTimeInput
+
+> **EventTimeInput** = \{ `endsAt`: `string`; `kind`: `"timed"`; `startsAt`: `string`; `timeZone?`: `string` \| `null`; \} \| \{ `endDate`: `string`; `kind`: `"allDay"`; `startDate`: `string`; \}
+
+The mutually exclusive time shape supplied to calendar tools.
+
+## Union Members
+
+### Type Literal
+
+\{ `endsAt`: `string`; `kind`: `"timed"`; `startsAt`: `string`; `timeZone?`: `string` \| `null`; \}
+
+A clock-time event with absolute instants.
+
+| Name | Type | Description |
+| ------ | ------ | ------ |
+| `endsAt` | `string` | Exclusive end instant, RFC 3339 UTC. Must be after the start. |
+| `kind` | `"timed"` | - |
+| `startsAt` | `string` | Inclusive start instant, RFC 3339 UTC (e.g. 2026-08-20T17:00:00Z). |
+| `timeZone?` | `string` \| `null` | IANA time zone the event was scheduled in (e.g. America/New_York). Recurring events expand in this zone. |
+
+***
+
+### Type Literal
+
+\{ `endDate`: `string`; `kind`: `"allDay"`; `startDate`: `string`; \}
+
+An all-day event spanning whole local dates.
+
+| Name | Type | Description |
+| ------ | ------ | ------ |
+| `endDate` | `string` | Exclusive local end date (YYYY-MM-DD); the day after the last covered day, so a one-day event ends the next date. |
+| `kind` | `"allDay"` | - |
+| `startDate` | `string` | Inclusive local start date (YYYY-MM-DD). |
diff --git a/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/ExecutionId.md b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/ExecutionId.md
new file mode 100644
index 0000000000..d38ed54d76
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/ExecutionId.md
@@ -0,0 +1,5 @@
+# Type Alias: ExecutionId
+
+> **ExecutionId** = `string`
+
+Caller-selected UUID persisted in tool input before execution begins.
diff --git a/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/GuestPolicy.md b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/GuestPolicy.md
new file mode 100644
index 0000000000..828e70c1c4
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/GuestPolicy.md
@@ -0,0 +1,14 @@
+# Type Alias: GuestPolicy
+
+> **GuestPolicy** = \{ `canInviteOthers`: `boolean`; `canModify`: `boolean`; `canSeeOtherGuests`: `boolean`; \}
+
+The switches an organizer sets on an event to bound what its guests may
+ do. Google omits a switch from the payload while it holds its default.
+
+## Properties
+
+| Property | Type | Description |
+| ------ | ------ | ------ |
+| <a id="property-caninviteothers"></a> `canInviteOthers` | `boolean` | Whether guests may invite others. |
+| <a id="property-canmodify"></a> `canModify` | `boolean` | Whether guests may change the event, including its guest list. |
+| <a id="property-canseeotherguests"></a> `canSeeOtherGuests` | `boolean` | Whether guests may see the guest list. |
diff --git a/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/ImportDraft.md b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/ImportDraft.md
new file mode 100644
index 0000000000..8931f01eaa
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/ImportDraft.md
@@ -0,0 +1,17 @@
+# Type Alias: ImportDraft
+
+> **ImportDraft** = \{ `excluded?`: `string`[]; `personal?`: `string`[]; `shared?`: `string`[]; `source`: [`ImportReviewSource`](ImportReviewSource.md); \}
+
+The one draft an import review carries: which source's staged plan it
+ presents, the plan rows the user took out of it, and the rows whose
+ sharing they changed: `shared` to share with their team, `personal` to
+ keep to themselves.
+
+## Properties
+
+| Property | Type | Description |
+| ------ | ------ | ------ |
+| <a id="property-excluded"></a> `excluded?` | `string`[] | Plan rows left out of the import. |
+| <a id="property-personal"></a> `personal?` | `string`[] | Plan rows kept private although the plan shares them. |
+| <a id="property-shared"></a> `shared?` | `string`[] | Plan rows shared with the team although the plan keeps them private. |
+| <a id="property-source"></a> `source` | [`ImportReviewSource`](ImportReviewSource.md) | The staged plan's source; fixed once the review is presented. |
diff --git a/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/ImportKind.md b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/ImportKind.md
new file mode 100644
index 0000000000..6e9a61aa35
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/ImportKind.md
@@ -0,0 +1,7 @@
+# Type Alias: ImportKind
+
+> **ImportKind** = `"issue"` \| `"project"` \| `"document"` \| `"page"` \| `"database"` \| `"data_source"` \| `"row"` \| `"jira_issue"` \| `"jira_project"` \| `"jira_epic"` \| `"channel"`
+
+What an imported item is in its source system. Each source has its own
+ kinds; a Notion database and a Notion page, or a Linear project and a
+ Linear issue, are tracked and deduplicated separately.
diff --git a/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/ImportReviewSource.md b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/ImportReviewSource.md
new file mode 100644
index 0000000000..f50e854cac
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/ImportReviewSource.md
@@ -0,0 +1,5 @@
+# Type Alias: ImportReviewSource
+
+> **ImportReviewSource** = `"notion"` \| `"linear"` \| `"jira"`
+
+Which source's staged plan an import review presents.
diff --git a/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/ItemStatus.md b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/ItemStatus.md
new file mode 100644
index 0000000000..d6acbe8ac7
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/ItemStatus.md
@@ -0,0 +1,5 @@
+# Type Alias: ItemStatus
+
+> **ItemStatus** = `"pending"` \| `"submitting"` \| `"completed"` \| `"dismissed"` \| `"unknown"`
+
+Review item state, shared with notification consumers.
diff --git a/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/NotionImportReport.md b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/NotionImportReport.md
new file mode 100644
index 0000000000..568d0e1f93
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/NotionImportReport.md
@@ -0,0 +1,5 @@
+# Type Alias: NotionImportReport
+
+> **NotionImportReport** = [`NotionImportReport_Serialize`](NotionImportReport_Serialize.md) \| [`NotionImportReport_Deserialize`](NotionImportReport_Deserialize.md)
+
+Where a Notion workspace import stands.
diff --git a/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/NotionImportReport_Deserialize.md b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/NotionImportReport_Deserialize.md
new file mode 100644
index 0000000000..7bd6d0f888
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/NotionImportReport_Deserialize.md
@@ -0,0 +1,38 @@
+# Type Alias: NotionImportReport\_Deserialize
+
+> **NotionImportReport\_Deserialize** = \{ `alreadyImportedBy?`: [`NotionImporter`](NotionImporter.md)[]; `alreadyInMacro?`: `number`; `copy`: `number`; `databaseRows`: `number`; `databases`: `number`; `dataSources`: `number`; `deciding?`: `number`; `documents`: `number`; `error?`: `string` \| `null`; `failures?`: [`NotionReportItem_Deserialize`](NotionReportItem_Deserialize.md)[]; `hand`: `number`; `handItems?`: [`NotionReportItem_Deserialize`](NotionReportItem_Deserialize.md)[]; `imported`: `number`; `issues?`: `number`; `onTeam?`: `boolean`; `pages`: `number`; `projects?`: `number`; `reviewId?`: `string` \| `null`; `scanned?`: [`ScanCounts`](ScanCounts.md) \| `null`; `sharedWithTeam?`: `number`; `skip`: `number`; `status?`: [`RunStatus`](RunStatus.md) \| `null`; `taskRows`: `number`; `tasks`: `number`; `waiting`: `number`; `waitingOnTeammates?`: `number`; `warnings?`: `string`[]; `writing`: `number`; \}
+
+Where a Notion workspace import stands.
+
+## Properties
+
+| Property | Type | Description |
+| ------ | ------ | ------ |
+| <a id="property-alreadyimportedby"></a> `alreadyImportedBy?` | [`NotionImporter`](NotionImporter.md)[] | Who imported the objects already in Macro, most first. |
+| <a id="property-alreadyinmacro"></a> `alreadyInMacro?` | `number` | Plan objects a teammate already imported and shared with the team; they link to that copy and are not counted as copies. |
+| <a id="property-copy"></a> `copy` | `number` | Objects to copy as they are. |
+| <a id="property-databaserows"></a> `databaseRows` | `number` | Rows those databases hold, every one counted while planning. |
+| <a id="property-databases"></a> `databases` | `number` | Data sources written as databases. |
+| <a id="property-datasources"></a> `dataSources` | `number` | Data sources (database tables) in the plan. |
+| <a id="property-deciding"></a> `deciding?` | `number` | Plan objects the decision model has not answered for yet, while planning is still `running`. |
+| <a id="property-documents"></a> `documents` | `number` | Pages written as documents. |
+| <a id="property-error"></a> `error?` | `string` \| `null` | Why the run failed, when it did. |
+| <a id="property-failures"></a> `failures?` | [`NotionReportItem_Deserialize`](NotionReportItem_Deserialize.md)[] | Objects that failed to import, with the failure. |
+| <a id="property-hand"></a> `hand` | `number` | Objects that need handling by hand. |
+| <a id="property-handitems"></a> `handItems?` | [`NotionReportItem_Deserialize`](NotionReportItem_Deserialize.md)[] | Objects that need handling by hand, with reasons. |
+| <a id="property-imported"></a> `imported` | `number` | Plan objects already imported. |
+| <a id="property-issues"></a> `issues?` | `number` | Tracker issues in the plan. |
+| <a id="property-onteam"></a> `onTeam?` | `boolean` | Whether the user is on a team. Without one, everything the import writes stays visible only to them. |
+| <a id="property-pages"></a> `pages` | `number` | Pages in the plan. |
+| <a id="property-projects"></a> `projects?` | `number` | Tracker groups written as Macro projects. |
+| <a id="property-reviewid"></a> `reviewId?` | `string` \| `null` | The review the plan is tied to, once presented. |
+| <a id="property-scanned"></a> `scanned?` | [`ScanCounts`](ScanCounts.md) \| `null` | What planning has found in Notion so far, while it is `running`. |
+| <a id="property-sharedwithteam"></a> `sharedWithTeam?` | `number` | Written plan objects shared with the user's team. |
+| <a id="property-skip"></a> `skip` | `number` | Objects left in Notion. |
+| <a id="property-status"></a> `status?` | [`RunStatus`](RunStatus.md) \| `null` | The run's state: `running` while planning, `ready` once a plan is staged, `importing` while writing, `completed`, `failed`, or `dismissed` when cancelled. Absent before the first run. |
+| <a id="property-taskrows"></a> `taskRows` | `number` | Tasks the task lists become, one per row. |
+| <a id="property-tasks"></a> `tasks` | `number` | Data sources whose rows become tasks. |
+| <a id="property-waiting"></a> `waiting` | `number` | Plan objects still waiting to be written. |
+| <a id="property-waitingonteammates"></a> `waitingOnTeammates?` | `number` | Plan objects waiting for a teammate who is writing the same object for the team; they link to the teammate's copy once it is written. |
+| <a id="property-warnings"></a> `warnings?` | `string`[] | Provider items skipped because they were unreadable, or optional features unavailable. |
+| <a id="property-writing"></a> `writing` | `number` | Plan objects being written now. |
diff --git a/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/NotionImportReport_Serialize.md b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/NotionImportReport_Serialize.md
new file mode 100644
index 0000000000..761ca71b94
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/NotionImportReport_Serialize.md
@@ -0,0 +1,38 @@
+# Type Alias: NotionImportReport\_Serialize
+
+> **NotionImportReport\_Serialize** = \{ `alreadyImportedBy`: [`NotionImporter`](NotionImporter.md)[]; `alreadyInMacro`: `number`; `copy`: `number`; `databaseRows`: `number`; `databases`: `number`; `dataSources`: `number`; `deciding`: `number`; `documents`: `number`; `error?`: `string` \| `null`; `failures`: [`NotionReportItem_Serialize`](NotionReportItem_Serialize.md)[]; `hand`: `number`; `handItems`: [`NotionReportItem_Serialize`](NotionReportItem_Serialize.md)[]; `imported`: `number`; `issues`: `number`; `onTeam`: `boolean`; `pages`: `number`; `projects`: `number`; `reviewId?`: `string` \| `null`; `scanned?`: [`ScanCounts`](ScanCounts.md) \| `null`; `sharedWithTeam`: `number`; `skip`: `number`; `status?`: [`RunStatus`](RunStatus.md) \| `null`; `taskRows`: `number`; `tasks`: `number`; `waiting`: `number`; `waitingOnTeammates`: `number`; `warnings?`: `string`[]; `writing`: `number`; \}
+
+Where a Notion workspace import stands.
+
+## Properties
+
+| Property | Type | Description |
+| ------ | ------ | ------ |
+| <a id="property-alreadyimportedby"></a> `alreadyImportedBy` | [`NotionImporter`](NotionImporter.md)[] | Who imported the objects already in Macro, most first. |
+| <a id="property-alreadyinmacro"></a> `alreadyInMacro` | `number` | Plan objects a teammate already imported and shared with the team; they link to that copy and are not counted as copies. |
+| <a id="property-copy"></a> `copy` | `number` | Objects to copy as they are. |
+| <a id="property-databaserows"></a> `databaseRows` | `number` | Rows those databases hold, every one counted while planning. |
+| <a id="property-databases"></a> `databases` | `number` | Data sources written as databases. |
+| <a id="property-datasources"></a> `dataSources` | `number` | Data sources (database tables) in the plan. |
+| <a id="property-deciding"></a> `deciding` | `number` | Plan objects the decision model has not answered for yet, while planning is still `running`. |
+| <a id="property-documents"></a> `documents` | `number` | Pages written as documents. |
+| <a id="property-error"></a> `error?` | `string` \| `null` | Why the run failed, when it did. |
+| <a id="property-failures"></a> `failures` | [`NotionReportItem_Serialize`](NotionReportItem_Serialize.md)[] | Objects that failed to import, with the failure. |
+| <a id="property-hand"></a> `hand` | `number` | Objects that need handling by hand. |
+| <a id="property-handitems"></a> `handItems` | [`NotionReportItem_Serialize`](NotionReportItem_Serialize.md)[] | Objects that need handling by hand, with reasons. |
+| <a id="property-imported"></a> `imported` | `number` | Plan objects already imported. |
+| <a id="property-issues"></a> `issues` | `number` | Tracker issues in the plan. |
+| <a id="property-onteam"></a> `onTeam` | `boolean` | Whether the user is on a team. Without one, everything the import writes stays visible only to them. |
+| <a id="property-pages"></a> `pages` | `number` | Pages in the plan. |
+| <a id="property-projects"></a> `projects` | `number` | Tracker groups written as Macro projects. |
+| <a id="property-reviewid"></a> `reviewId?` | `string` \| `null` | The review the plan is tied to, once presented. |
+| <a id="property-scanned"></a> `scanned?` | [`ScanCounts`](ScanCounts.md) \| `null` | What planning has found in Notion so far, while it is `running`. |
+| <a id="property-sharedwithteam"></a> `sharedWithTeam` | `number` | Written plan objects shared with the user's team. |
+| <a id="property-skip"></a> `skip` | `number` | Objects left in Notion. |
+| <a id="property-status"></a> `status?` | [`RunStatus`](RunStatus.md) \| `null` | The run's state: `running` while planning, `ready` once a plan is staged, `importing` while writing, `completed`, `failed`, or `dismissed` when cancelled. Absent before the first run. |
+| <a id="property-taskrows"></a> `taskRows` | `number` | Tasks the task lists become, one per row. |
+| <a id="property-tasks"></a> `tasks` | `number` | Data sources whose rows become tasks. |
+| <a id="property-waiting"></a> `waiting` | `number` | Plan objects still waiting to be written. |
+| <a id="property-waitingonteammates"></a> `waitingOnTeammates` | `number` | Plan objects waiting for a teammate who is writing the same object for the team; they link to the teammate's copy once it is written. |
+| <a id="property-warnings"></a> `warnings?` | `string`[] | Provider items skipped because they were unreadable, or optional features unavailable. |
+| <a id="property-writing"></a> `writing` | `number` | Plan objects being written now. |
diff --git a/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/NotionImporter.md b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/NotionImporter.md
new file mode 100644
index 0000000000..6042ea16cc
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/NotionImporter.md
@@ -0,0 +1,12 @@
+# Type Alias: NotionImporter
+
+> **NotionImporter** = \{ `by`: `string`; `count`: `number`; \}
+
+A teammate who already imported some of a plan's objects.
+
+## Properties
+
+| Property | Type | Description |
+| ------ | ------ | ------ |
+| <a id="property-by"></a> `by` | `string` | The teammate, by email. |
+| <a id="property-count"></a> `count` | `number` | How many of the plan's objects they imported. |
diff --git a/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/NotionReportItem.md b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/NotionReportItem.md
new file mode 100644
index 0000000000..574d47e6da
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/NotionReportItem.md
@@ -0,0 +1,5 @@
+# Type Alias: NotionReportItem
+
+> **NotionReportItem** = [`NotionReportItem_Serialize`](NotionReportItem_Serialize.md) \| [`NotionReportItem_Deserialize`](NotionReportItem_Deserialize.md)
+
+One object a workspace import report calls out.
diff --git a/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/NotionReportItem_Deserialize.md b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/NotionReportItem_Deserialize.md
new file mode 100644
index 0000000000..ea7de7cc1a
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/NotionReportItem_Deserialize.md
@@ -0,0 +1,15 @@
+# Type Alias: NotionReportItem\_Deserialize
+
+> **NotionReportItem\_Deserialize** = \{ `importId`: `string`; `kind`: [`ImportKind`](ImportKind.md); `reason?`: `string` \| `null`; `title`: `string`; `url?`: `string` \| `null`; \}
+
+One object a workspace import report calls out.
+
+## Properties
+
+| Property | Type | Description |
+| ------ | ------ | ------ |
+| <a id="property-importid"></a> `importId` | `string` | The ledger row. |
+| <a id="property-kind"></a> `kind` | [`ImportKind`](ImportKind.md) | What the object is. |
+| <a id="property-reason"></a> `reason?` | `string` \| `null` | Why it is called out: the decision model's reason, or the failure. |
+| <a id="property-title"></a> `title` | `string` | The object's title. |
+| <a id="property-url"></a> `url?` | `string` \| `null` | Its Notion URL. |
diff --git a/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/NotionReportItem_Serialize.md b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/NotionReportItem_Serialize.md
new file mode 100644
index 0000000000..bfeb09e3a1
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/NotionReportItem_Serialize.md
@@ -0,0 +1,15 @@
+# Type Alias: NotionReportItem\_Serialize
+
+> **NotionReportItem\_Serialize** = \{ `importId`: `string`; `kind`: [`ImportKind`](ImportKind.md); `reason?`: `string` \| `null`; `title`: `string`; `url?`: `string` \| `null`; \}
+
+One object a workspace import report calls out.
+
+## Properties
+
+| Property | Type | Description |
+| ------ | ------ | ------ |
+| <a id="property-importid"></a> `importId` | `string` | The ledger row. |
+| <a id="property-kind"></a> `kind` | [`ImportKind`](ImportKind.md) | What the object is. |
+| <a id="property-reason"></a> `reason?` | `string` \| `null` | Why it is called out: the decision model's reason, or the failure. |
+| <a id="property-title"></a> `title` | `string` | The object's title. |
+| <a id="property-url"></a> `url?` | `string` \| `null` | Its Notion URL. |
diff --git a/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/OutOfOfficeInput.md b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/OutOfOfficeInput.md
new file mode 100644
index 0000000000..49e060de65
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/OutOfOfficeInput.md
@@ -0,0 +1,12 @@
+# Type Alias: OutOfOfficeInput
+
+> **OutOfOfficeInput** = \{ `autoDeclineMode?`: [`AutoDeclineModeInput`](AutoDeclineModeInput.md) \| `null`; `declineMessage?`: `string` \| `null`; \}
+
+Out-of-office decline behavior supplied to the calendar tools.
+
+## Properties
+
+| Property | Type | Description |
+| ------ | ------ | ------ |
+| <a id="property-autodeclinemode"></a> `autoDeclineMode?` | [`AutoDeclineModeInput`](AutoDeclineModeInput.md) \| `null` | How conflicting invitations are handled. Defaults to declining nothing, so the event only blocks time and shows the away status. |
+| <a id="property-declinemessage"></a> `declineMessage?` | `string` \| `null` | Message returned to organizers whose invitations are auto-declined. |
diff --git a/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/ReviewDecision.md b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/ReviewDecision.md
new file mode 100644
index 0000000000..7309056d12
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/ReviewDecision.md
@@ -0,0 +1,5 @@
+# Type Alias: ReviewDecision
+
+> **ReviewDecision** = [`ReviewDecision_Serialize`](ReviewDecision_Serialize.md) \| [`ReviewDecision_Deserialize`](ReviewDecision_Deserialize.md)
+
+One atomic user decision against the displayed revision.
diff --git a/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/ReviewDecisionContext.md b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/ReviewDecisionContext.md
new file mode 100644
index 0000000000..13a6c64db4
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/ReviewDecisionContext.md
@@ -0,0 +1,14 @@
+# Type Alias: ReviewDecisionContext
+
+> **ReviewDecisionContext** = \{ `by`: `string`; `items`: `string`[]; `revision`: `number`; `via`: [`DecisionVia`](DecisionVia.md); \}
+
+Facts about the most recent account-holder decision.
+
+## Properties
+
+| Property | Type | Description |
+| ------ | ------ | ------ |
+| <a id="property-by"></a> `by` | `string` | Authenticated account holder. |
+| <a id="property-items"></a> `items` | `string`[] | Items selected by this decision. |
+| <a id="property-revision"></a> `revision` | `number` | Revision claimed by this batch, used in notification deduplication. |
+| <a id="property-via"></a> `via` | [`DecisionVia`](DecisionVia.md) | Entry surface. |
diff --git a/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/ReviewDecision_Deserialize.md b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/ReviewDecision_Deserialize.md
new file mode 100644
index 0000000000..96ad1d0a30
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/ReviewDecision_Deserialize.md
@@ -0,0 +1,5 @@
+# Type Alias: ReviewDecision\_Deserialize
+
+> **ReviewDecision\_Deserialize** = \{ `action`: `"edit"`; `draft`: [`ReviewDraft_Deserialize`](ReviewDraft_Deserialize.md); `item`: `string`; `revision`: `number`; \} & \{ `items?`: `never`; \} \| \{ `action`: `"submit"`; `items`: `string`[]; `revision`: `number`; \} & \{ `draft?`: `never`; `item?`: `never`; \} \| \{ `action`: `"dismiss"`; `items`: `string`[]; `revision`: `number`; \} & \{ `draft?`: `never`; `item?`: `never`; \}
+
+One atomic user decision against the displayed revision.
diff --git a/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/ReviewDecision_Serialize.md b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/ReviewDecision_Serialize.md
new file mode 100644
index 0000000000..441d047e88
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/ReviewDecision_Serialize.md
@@ -0,0 +1,5 @@
+# Type Alias: ReviewDecision\_Serialize
+
+> **ReviewDecision\_Serialize** = \{ `action`: `"edit"`; `draft`: [`ReviewDraft_Serialize`](ReviewDraft_Serialize.md); `item`: `string`; `revision`: `number`; \} & \{ `items?`: `never`; \} \| \{ `action`: `"submit"`; `items`: `string`[]; `revision`: `number`; \} & \{ `draft?`: `never`; `item?`: `never`; \} \| \{ `action`: `"dismiss"`; `items`: `string`[]; `revision`: `number`; \} & \{ `draft?`: `never`; `item?`: `never`; \}
+
+One atomic user decision against the displayed revision.
diff --git a/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/ReviewDraft.md b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/ReviewDraft.md
new file mode 100644
index 0000000000..ae184ce685
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/ReviewDraft.md
@@ -0,0 +1,5 @@
+# Type Alias: ReviewDraft
+
+> **ReviewDraft** = [`ReviewDraft_Serialize`](ReviewDraft_Serialize.md) \| [`ReviewDraft_Deserialize`](ReviewDraft_Deserialize.md)
+
+One replacement draft, keyed by the kind of the review it edits.
diff --git a/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/ReviewDraft_Deserialize.md b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/ReviewDraft_Deserialize.md
new file mode 100644
index 0000000000..1350c6d86a
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/ReviewDraft_Deserialize.md
@@ -0,0 +1,29 @@
+# Type Alias: ReviewDraft\_Deserialize
+
+> **ReviewDraft\_Deserialize** = \{ `draft`: [`SendEmail`](SendEmail.md); `kind`: `"email"`; \} \| \{ `draft`: [`CreateCalendarEvent_Deserialize`](CreateCalendarEvent_Deserialize.md); `kind`: `"calendar"`; \} \| \{ `draft`: [`ImportDraft`](ImportDraft.md); `kind`: `"import"`; \}
+
+One replacement draft, keyed by the kind of the review it edits.
+
+## Union Members
+
+### Type Literal
+
+\{ `draft`: [`SendEmail`](SendEmail.md); `kind`: `"email"`; \}
+
+An edited email.
+
+***
+
+### Type Literal
+
+\{ `draft`: [`CreateCalendarEvent_Deserialize`](CreateCalendarEvent_Deserialize.md); `kind`: `"calendar"`; \}
+
+An edited calendar event.
+
+***
+
+### Type Literal
+
+\{ `draft`: [`ImportDraft`](ImportDraft.md); `kind`: `"import"`; \}
+
+An edited import plan selection.
diff --git a/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/ReviewDraft_Serialize.md b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/ReviewDraft_Serialize.md
new file mode 100644
index 0000000000..a1c47a67e1
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/ReviewDraft_Serialize.md
@@ -0,0 +1,29 @@
+# Type Alias: ReviewDraft\_Serialize
+
+> **ReviewDraft\_Serialize** = \{ `draft`: [`SendEmail`](SendEmail.md); `kind`: `"email"`; \} \| \{ `draft`: [`CreateCalendarEvent_Serialize`](CreateCalendarEvent_Serialize.md); `kind`: `"calendar"`; \} \| \{ `draft`: [`ImportDraft`](ImportDraft.md); `kind`: `"import"`; \}
+
+One replacement draft, keyed by the kind of the review it edits.
+
+## Union Members
+
+### Type Literal
+
+\{ `draft`: [`SendEmail`](SendEmail.md); `kind`: `"email"`; \}
+
+An edited email.
+
+***
+
+### Type Literal
+
+\{ `draft`: [`CreateCalendarEvent_Serialize`](CreateCalendarEvent_Serialize.md); `kind`: `"calendar"`; \}
+
+An edited calendar event.
+
+***
+
+### Type Literal
+
+\{ `draft`: [`ImportDraft`](ImportDraft.md); `kind`: `"import"`; \}
+
+An edited import plan selection.
diff --git a/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/ReviewDrafts.md b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/ReviewDrafts.md
new file mode 100644
index 0000000000..3e370ca1cc
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/ReviewDrafts.md
@@ -0,0 +1,5 @@
+# Type Alias: ReviewDrafts
+
+> **ReviewDrafts** = [`ReviewDrafts_Serialize`](ReviewDrafts_Serialize.md) \| [`ReviewDrafts_Deserialize`](ReviewDrafts_Deserialize.md)
+
+The drafts a new review presents, keyed by the review's kind.
diff --git a/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/ReviewDrafts_Deserialize.md b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/ReviewDrafts_Deserialize.md
new file mode 100644
index 0000000000..470bcd2ee7
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/ReviewDrafts_Deserialize.md
@@ -0,0 +1,29 @@
+# Type Alias: ReviewDrafts\_Deserialize
+
+> **ReviewDrafts\_Deserialize** = \{ `drafts`: [`DraftList`](DraftList.md)\<[`SendEmail`](SendEmail.md)\>; `kind`: `"email"`; \} \| \{ `drafts`: [`DraftList`](DraftList.md)\<[`CreateCalendarEvent_Deserialize`](CreateCalendarEvent_Deserialize.md)\>; `kind`: `"calendar"`; \} \| \{ `drafts`: \[[`ImportDraft`](ImportDraft.md)\]; `kind`: `"import"`; \}
+
+The drafts a new review presents, keyed by the review's kind.
+
+## Union Members
+
+### Type Literal
+
+\{ `drafts`: [`DraftList`](DraftList.md)\<[`SendEmail`](SendEmail.md)\>; `kind`: `"email"`; \}
+
+Emails, each sent with the SendEmail action (Markdown body).
+
+***
+
+### Type Literal
+
+\{ `drafts`: [`DraftList`](DraftList.md)\<[`CreateCalendarEvent_Deserialize`](CreateCalendarEvent_Deserialize.md)\>; `kind`: `"calendar"`; \}
+
+Calendar events, each created with the CreateCalendarEvent action.
+
+***
+
+### Type Literal
+
+\{ `drafts`: \[[`ImportDraft`](ImportDraft.md)\]; `kind`: `"import"`; \}
+
+Exactly one staged import plan, approved as one item.
diff --git a/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/ReviewDrafts_Serialize.md b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/ReviewDrafts_Serialize.md
new file mode 100644
index 0000000000..ef1741f343
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/ReviewDrafts_Serialize.md
@@ -0,0 +1,29 @@
+# Type Alias: ReviewDrafts\_Serialize
+
+> **ReviewDrafts\_Serialize** = \{ `drafts`: [`DraftList`](DraftList.md)\<[`SendEmail`](SendEmail.md)\>; `kind`: `"email"`; \} \| \{ `drafts`: [`DraftList`](DraftList.md)\<[`CreateCalendarEvent_Serialize`](CreateCalendarEvent_Serialize.md)\>; `kind`: `"calendar"`; \} \| \{ `drafts`: \[[`ImportDraft`](ImportDraft.md)\]; `kind`: `"import"`; \}
+
+The drafts a new review presents, keyed by the review's kind.
+
+## Union Members
+
+### Type Literal
+
+\{ `drafts`: [`DraftList`](DraftList.md)\<[`SendEmail`](SendEmail.md)\>; `kind`: `"email"`; \}
+
+Emails, each sent with the SendEmail action (Markdown body).
+
+***
+
+### Type Literal
+
+\{ `drafts`: [`DraftList`](DraftList.md)\<[`CreateCalendarEvent_Serialize`](CreateCalendarEvent_Serialize.md)\>; `kind`: `"calendar"`; \}
+
+Calendar events, each created with the CreateCalendarEvent action.
+
+***
+
+### Type Literal
+
+\{ `drafts`: \[[`ImportDraft`](ImportDraft.md)\]; `kind`: `"import"`; \}
+
+Exactly one staged import plan, approved as one item.
diff --git a/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/ReviewId.md b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/ReviewId.md
new file mode 100644
index 0000000000..471ebcfa90
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/ReviewId.md
@@ -0,0 +1,5 @@
+# Type Alias: ReviewId
+
+> **ReviewId** = `string`
+
+Persisted review identity.
diff --git a/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/ReviewItem.md b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/ReviewItem.md
new file mode 100644
index 0000000000..7738b0118f
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/ReviewItem.md
@@ -0,0 +1,19 @@
+# Type Alias: ReviewItem\<Draft, Outcome\>
+
+> **ReviewItem**\<`Draft`, `Outcome`\> = \{ `draft`: `Draft`; `result`: `Outcome` \| `null`; \} & [`ReviewItemState`](ReviewItemState.md)
+
+One editable item and its durable outcome.
+
+## Type Parameters
+
+| Type Parameter |
+| ------ |
+| <a id="type-parameter-draft"></a> `Draft` |
+| <a id="type-parameter-outcome"></a> `Outcome` |
+
+## Type Declaration
+
+| Name | Type | Description |
+| ------ | ------ | ------ |
+| `draft` | `Draft` | Arguments for the existing composer and action. |
+| `result` | `Outcome` \| `null` | The action's confirmed response, never a model assertion. |
diff --git a/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/ReviewItemState.md b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/ReviewItemState.md
new file mode 100644
index 0000000000..ebeab5b630
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/ReviewItemState.md
@@ -0,0 +1,14 @@
+# Type Alias: ReviewItemState
+
+> **ReviewItemState** = \{ `edited?`: `boolean`; `error`: `string` \| `null`; `id`: `string`; `status`: [`ItemStatus`](ItemStatus.md); \}
+
+Item facts every kind shares.
+
+## Properties
+
+| Property | Type | Description |
+| ------ | ------ | ------ |
+| <a id="property-edited"></a> `edited?` | `boolean` | Whether the account holder edited this draft before deciding. |
+| <a id="property-error"></a> `error` | `string` \| `null` | Failure or uncertainty description. |
+| <a id="property-id"></a> `id` | `string` | Stable item identity across stack navigation and edits. |
+| <a id="property-status"></a> `status` | [`ItemStatus`](ItemStatus.md) | Current outcome. |
diff --git a/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/ReviewItems.md b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/ReviewItems.md
new file mode 100644
index 0000000000..23d1ceb059
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/ReviewItems.md
@@ -0,0 +1,5 @@
+# Type Alias: ReviewItems
+
+> **ReviewItems** = [`ReviewItems_Serialize`](ReviewItems_Serialize.md) \| [`ReviewItems_Deserialize`](ReviewItems_Deserialize.md)
+
+Saved items keyed by the review's kind.
diff --git a/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/ReviewItems_Deserialize.md b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/ReviewItems_Deserialize.md
new file mode 100644
index 0000000000..9a06d4d751
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/ReviewItems_Deserialize.md
@@ -0,0 +1,29 @@
+# Type Alias: ReviewItems\_Deserialize
+
+> **ReviewItems\_Deserialize** = \{ `items`: [`ReviewItem`](ReviewItem.md)\<[`SendEmail`](SendEmail.md), [`SendEmailResponse`](SendEmailResponse.md)\>[]; `kind`: `"email"`; \} \| \{ `items`: [`ReviewItem`](ReviewItem.md)\<[`CreateCalendarEvent_Deserialize`](CreateCalendarEvent_Deserialize.md), [`ToolCalendarEvent`](ToolCalendarEvent.md)\>[]; `kind`: `"calendar"`; \} \| \{ `items`: \[[`ReviewItem`](ReviewItem.md)\<[`ImportDraft`](ImportDraft.md), [`NotionImportReport_Deserialize`](NotionImportReport_Deserialize.md)\>\]; `kind`: `"import"`; \}
+
+Saved items keyed by the review's kind.
+
+## Union Members
+
+### Type Literal
+
+\{ `items`: [`ReviewItem`](ReviewItem.md)\<[`SendEmail`](SendEmail.md), [`SendEmailResponse`](SendEmailResponse.md)\>[]; `kind`: `"email"`; \}
+
+Email drafts and their send responses.
+
+***
+
+### Type Literal
+
+\{ `items`: [`ReviewItem`](ReviewItem.md)\<[`CreateCalendarEvent_Deserialize`](CreateCalendarEvent_Deserialize.md), [`ToolCalendarEvent`](ToolCalendarEvent.md)\>[]; `kind`: `"calendar"`; \}
+
+Calendar drafts and their created events.
+
+***
+
+### Type Literal
+
+\{ `items`: \[[`ReviewItem`](ReviewItem.md)\<[`ImportDraft`](ImportDraft.md), [`NotionImportReport_Deserialize`](NotionImportReport_Deserialize.md)\>\]; `kind`: `"import"`; \}
+
+The import plan selection and the started write's report.
diff --git a/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/ReviewItems_Serialize.md b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/ReviewItems_Serialize.md
new file mode 100644
index 0000000000..b6dd0734ad
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/ReviewItems_Serialize.md
@@ -0,0 +1,29 @@
+# Type Alias: ReviewItems\_Serialize
+
+> **ReviewItems\_Serialize** = \{ `items`: [`ReviewItem`](ReviewItem.md)\<[`SendEmail`](SendEmail.md), [`SendEmailResponse`](SendEmailResponse.md)\>[]; `kind`: `"email"`; \} \| \{ `items`: [`ReviewItem`](ReviewItem.md)\<[`CreateCalendarEvent_Serialize`](CreateCalendarEvent_Serialize.md), [`ToolCalendarEvent`](ToolCalendarEvent.md)\>[]; `kind`: `"calendar"`; \} \| \{ `items`: \[[`ReviewItem`](ReviewItem.md)\<[`ImportDraft`](ImportDraft.md), [`NotionImportReport_Serialize`](NotionImportReport_Serialize.md)\>\]; `kind`: `"import"`; \}
+
+Saved items keyed by the review's kind.
+
+## Union Members
+
+### Type Literal
+
+\{ `items`: [`ReviewItem`](ReviewItem.md)\<[`SendEmail`](SendEmail.md), [`SendEmailResponse`](SendEmailResponse.md)\>[]; `kind`: `"email"`; \}
+
+Email drafts and their send responses.
+
+***
+
+### Type Literal
+
+\{ `items`: [`ReviewItem`](ReviewItem.md)\<[`CreateCalendarEvent_Serialize`](CreateCalendarEvent_Serialize.md), [`ToolCalendarEvent`](ToolCalendarEvent.md)\>[]; `kind`: `"calendar"`; \}
+
+Calendar drafts and their created events.
+
+***
+
+### Type Literal
+
+\{ `items`: \[[`ReviewItem`](ReviewItem.md)\<[`ImportDraft`](ImportDraft.md), [`NotionImportReport_Serialize`](NotionImportReport_Serialize.md)\>\]; `kind`: `"import"`; \}
+
+The import plan selection and the started write's report.
diff --git a/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/ReviewRecord.md b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/ReviewRecord.md
new file mode 100644
index 0000000000..fd5e8ad42f
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/ReviewRecord.md
@@ -0,0 +1,5 @@
+# Type Alias: ReviewRecord
+
+> **ReviewRecord** = [`ReviewRecord_Serialize`](ReviewRecord_Serialize.md) \| [`ReviewRecord_Deserialize`](ReviewRecord_Deserialize.md)
+
+Full UI record, fetched outside the model context.
diff --git a/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/ReviewRecord_Deserialize.md b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/ReviewRecord_Deserialize.md
new file mode 100644
index 0000000000..54ad69d4c9
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/ReviewRecord_Deserialize.md
@@ -0,0 +1,19 @@
+# Type Alias: ReviewRecord\_Deserialize
+
+> **ReviewRecord\_Deserialize** = \{ `actingUser`: `string`; `decision?`: [`ReviewDecisionContext`](ReviewDecisionContext.md) \| `null`; `executionId`: [`ExecutionId`](ExecutionId.md) \| `null`; `id`: [`ReviewId`](ReviewId.md); `presentedAt?`: `number` \| `null`; `revision`: `number`; `sessionId`: `string`; `title`: [`ReviewTitle`](ReviewTitle.md); `updatedAt`: `number`; \} & [`ReviewItems_Deserialize`](ReviewItems_Deserialize.md)
+
+Full UI record, fetched outside the model context.
+
+## Type Declaration
+
+| Name | Type | Description |
+| ------ | ------ | ------ |
+| `actingUser` | `string` | Account whose email/calendar the drafts use. |
+| `decision?` | [`ReviewDecisionContext`](ReviewDecisionContext.md) \| `null` | Current batch's authenticated decision, preserved for interrupted work. |
+| `executionId` | [`ExecutionId`](ExecutionId.md) \| `null` | Originating code execution, absent for directly presented reviews. |
+| `id` | [`ReviewId`](ReviewId.md) | Review identity. |
+| `presentedAt?` | `number` \| `null` | Durable presentation acknowledgment, separate from user decisions. |
+| `revision` | `number` | Compare-and-swap revision for edits and submissions. |
+| `sessionId` | `string` | Owning session. |
+| `title` | [`ReviewTitle`](ReviewTitle.md) | Stack label. |
+| `updatedAt` | `number` | Milliseconds since epoch of the last state change. |
diff --git a/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/ReviewRecord_Serialize.md b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/ReviewRecord_Serialize.md
new file mode 100644
index 0000000000..af3432924e
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/ReviewRecord_Serialize.md
@@ -0,0 +1,19 @@
+# Type Alias: ReviewRecord\_Serialize
+
+> **ReviewRecord\_Serialize** = \{ `actingUser`: `string`; `decision`: [`ReviewDecisionContext`](ReviewDecisionContext.md) \| `null`; `executionId`: [`ExecutionId`](ExecutionId.md) \| `null`; `id`: [`ReviewId`](ReviewId.md); `presentedAt`: `number` \| `null`; `revision`: `number`; `sessionId`: `string`; `title`: [`ReviewTitle`](ReviewTitle.md); `updatedAt`: `number`; \} & [`ReviewItems_Serialize`](ReviewItems_Serialize.md)
+
+Full UI record, fetched outside the model context.
+
+## Type Declaration
+
+| Name | Type | Description |
+| ------ | ------ | ------ |
+| `actingUser` | `string` | Account whose email/calendar the drafts use. |
+| `decision` | [`ReviewDecisionContext`](ReviewDecisionContext.md) \| `null` | Current batch's authenticated decision, preserved for interrupted work. |
+| `executionId` | [`ExecutionId`](ExecutionId.md) \| `null` | Originating code execution, absent for directly presented reviews. |
+| `id` | [`ReviewId`](ReviewId.md) | Review identity. |
+| `presentedAt` | `number` \| `null` | Durable presentation acknowledgment, separate from user decisions. |
+| `revision` | `number` | Compare-and-swap revision for edits and submissions. |
+| `sessionId` | `string` | Owning session. |
+| `title` | [`ReviewTitle`](ReviewTitle.md) | Stack label. |
+| `updatedAt` | `number` | Milliseconds since epoch of the last state change. |
diff --git a/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/ReviewTitle.md b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/ReviewTitle.md
new file mode 100644
index 0000000000..aba2eeae7e
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/ReviewTitle.md
@@ -0,0 +1,5 @@
+# Type Alias: ReviewTitle
+
+> **ReviewTitle** = `string`
+
+A review stack label: not blank, at most 256 characters.
diff --git a/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/RunStatus.md b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/RunStatus.md
new file mode 100644
index 0000000000..a614f4971f
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/RunStatus.md
@@ -0,0 +1,5 @@
+# Type Alias: RunStatus
+
+> **RunStatus** = `"running"` \| `"ready"` \| `"importing"` \| `"completed"` \| `"failed"` \| `"dismissed"`
+
+Lifecycle of a discovery run (one per user × source).
diff --git a/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/ScanCounts.md b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/ScanCounts.md
new file mode 100644
index 0000000000..22fc3e3d6e
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/ScanCounts.md
@@ -0,0 +1,12 @@
+# Type Alias: ScanCounts
+
+> **ScanCounts** = \{ `dataSources`: `number`; `pages`: `number`; \}
+
+What a planning run has found in the source so far.
+
+## Properties
+
+| Property | Type | Description |
+| ------ | ------ | ------ |
+| <a id="property-datasources"></a> `dataSources` | `number` | Data sources (database tables) found. |
+| <a id="property-pages"></a> `pages` | `number` | Pages found. |
diff --git a/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/SendEmail.md b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/SendEmail.md
new file mode 100644
index 0000000000..c62494a63e
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/SendEmail.md
@@ -0,0 +1,19 @@
+# Type Alias: SendEmail
+
+> **SendEmail** = \{ `attachments?`: [`EmailAttachment`](EmailAttachment.md)[]; `bcc?`: [`EmailRecipient`](EmailRecipient.md)[]; `body`: `string`; `cc?`: [`EmailRecipient`](EmailRecipient.md)[]; `from?`: `string` \| `null`; `includeSignature?`: `boolean` \| `null`; `replyingToId?`: `string` \| `null`; `subject`: `string`; `to`: [`EmailRecipient`](EmailRecipient.md)[]; \}
+
+Compose and send an email. Creates a draft and immediately queues it for delivery.
+
+## Properties
+
+| Property | Type | Description |
+| ------ | ------ | ------ |
+| <a id="property-attachments"></a> `attachments?` | [`EmailAttachment`](EmailAttachment.md)[] | Macro documents to attach as files (optional). Each must be an uploaded file the user can view; together they may total 18 MB. |
+| <a id="property-bcc"></a> `bcc?` | [`EmailRecipient`](EmailRecipient.md)[] | Blind carbon copy recipients (optional). |
+| <a id="property-body"></a> `body` | `string` | The body of the email, written as Markdown. A host with a composer (chat) replaces this with the base64url-encoded HTML the composer exported before the tool runs; a host without one (an agent session) leaves the Markdown, and this tool renders it the same way. |
+| <a id="property-cc"></a> `cc?` | [`EmailRecipient`](EmailRecipient.md)[] | Carbon copy recipients (optional). |
+| <a id="property-from"></a> `from?` | `string` \| `null` | The address of the inbox to send from, when the user has more than one connected and this email belongs to a particular one. Use the exact `emailAddress` of a connected inbox — `ListInboxes` lists them, and `GetThread` reports the `inbox` a thread belongs to. Omit it unless you know which inbox is right: a reply then goes out from the inbox that received the message it answers, and a new email from the user's primary inbox. The user can change it in the composer either way. |
+| <a id="property-includesignature"></a> `includeSignature?` | `boolean` \| `null` | Per-message signature override, set by the composer's signature preview — not normally by you. Omit to use the inbox's default policy (always on a new email; on replies/forwards only when the user enabled it). `false` excludes the signature for this one email. |
+| <a id="property-replyingtoid"></a> `replyingToId?` | `string` \| `null` | The ID of a message to reply to (optional). When set, the email is sent as a reply within the same thread. |
+| <a id="property-subject"></a> `subject` | `string` | The subject line of the email. |
+| <a id="property-to"></a> `to` | [`EmailRecipient`](EmailRecipient.md)[] | The primary recipients (To field). |
diff --git a/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/SendEmailResponse.md b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/SendEmailResponse.md
new file mode 100644
index 0000000000..0233ce3a52
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/SendEmailResponse.md
@@ -0,0 +1,5 @@
+# Type Alias: SendEmailResponse
+
+> **SendEmailResponse** = \{ `sent`: \{ `message_id`: `string`; `thread_id`: `string`; \}; \} & \{ `convertedToDraft?`: `never`; \} \| \{ `convertedToDraft`: \{ `draft_id`: `string`; \}; \} & \{ `sent?`: `never`; \} \| `"userEdited"`
+
+Response from the SendEmail tool.
diff --git a/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/ToolCalendarEvent.md b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/ToolCalendarEvent.md
new file mode 100644
index 0000000000..7a0fcfd6fa
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/ToolCalendarEvent.md
@@ -0,0 +1,31 @@
+# Type Alias: ToolCalendarEvent
+
+> **ToolCalendarEvent** = \{ `attendeeCount`: `number`; `attendees`: [`ToolEventAttendee`](ToolEventAttendee.md)[]; `calendarId`: `string` \| `null`; `calendarName`: `string` \| `null`; `conferenceUrl`: `string` \| `null`; `description`: `string` \| `null`; `end`: `string`; `eventId`: `string`; `inbox`: `string` \| `null`; `isAllDay`: `boolean`; `isReadOnly`: `boolean`; `isRecurring`: `boolean`; `location`: `string` \| `null`; `macroCallUrl`: `string` \| `null`; `myRole`: [`ToolEventRole`](ToolEventRole.md) \| `null`; `organizerEmail`: `string` \| `null`; `recurrenceLines`: `string`[]; `start`: `string`; `status`: `string`; `timeZone`: `string` \| `null`; `title`: `string`; \}
+
+A calendar event as returned by the create and update tools.
+
+## Properties
+
+| Property | Type | Description |
+| ------ | ------ | ------ |
+| <a id="property-attendeecount"></a> `attendeeCount` | `number` | Total number of attendees. |
+| <a id="property-attendees"></a> `attendees` | [`ToolEventAttendee`](ToolEventAttendee.md)[] | Attendees, capped at 20; `attendee_count` has the full number. |
+| <a id="property-calendarid"></a> `calendarId` | `string` \| `null` | Calendar the event belongs to, when known. |
+| <a id="property-calendarname"></a> `calendarName` | `string` \| `null` | Display name of that calendar, when known. |
+| <a id="property-conferenceurl"></a> `conferenceUrl` | `string` \| `null` | Conference join URL, when a conference is attached. |
+| <a id="property-description"></a> `description` | `string` \| `null` | Event body, truncated for brevity. |
+| <a id="property-end"></a> `end` | `string` | Exclusive event end: RFC 3339 UTC instant, or YYYY-MM-DD for all-day events. |
+| <a id="property-eventid"></a> `eventId` | `string` | Macro calendar event id, used by UpdateCalendarEvent and DeleteCalendarEvent. |
+| <a id="property-inbox"></a> `inbox` | `string` \| `null` | Connected inbox address syncing the calendar, when known. It stays the user's own address on a colleague's calendar, so it never says whose calendar it is. |
+| <a id="property-isallday"></a> `isAllDay` | `boolean` | Whether the event covers whole days. |
+| <a id="property-isreadonly"></a> `isReadOnly` | `boolean` | Whether the user's calendar prohibits modifying this event. |
+| <a id="property-isrecurring"></a> `isRecurring` | `boolean` | Whether the event recurs. |
+| <a id="property-location"></a> `location` | `string` \| `null` | Location label, when set. |
+| <a id="property-macrocallurl"></a> `macroCallUrl` | `string` \| `null` | Join URL of the Macro call created with the event, when CreateCalendarEvent was asked for one. |
+| <a id="property-myrole"></a> `myRole` | [`ToolEventRole`](ToolEventRole.md) \| `null` | Whether the user organizes this event or is a guest on it, through that inbox; absent when they are neither, can only write that calendar, or a read-only calendar names them organizer. |
+| <a id="property-organizeremail"></a> `organizerEmail` | `string` \| `null` | Organizer email address, when known. |
+| <a id="property-recurrencelines"></a> `recurrenceLines` | `string`[] | Raw RFC 5545 recurrence properties, when the event recurs. |
+| <a id="property-start"></a> `start` | `string` | Event start: RFC 3339 UTC instant, or YYYY-MM-DD for all-day events. |
+| <a id="property-status"></a> `status` | `string` | Event status: confirmed, tentative, or cancelled. |
+| <a id="property-timezone"></a> `timeZone` | `string` \| `null` | IANA time zone the event was scheduled in, when known. |
+| <a id="property-title"></a> `title` | `string` | Display title. |
diff --git a/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/ToolEventAttendee.md b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/ToolEventAttendee.md
new file mode 100644
index 0000000000..442491c999
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/ToolEventAttendee.md
@@ -0,0 +1,14 @@
+# Type Alias: ToolEventAttendee
+
+> **ToolEventAttendee** = \{ `email`: `string`; `isOptional`: `boolean`; `isOrganizer`: `boolean`; `responseStatus`: `string`; \}
+
+An attendee of a calendar event, as returned by calendar tools.
+
+## Properties
+
+| Property | Type | Description |
+| ------ | ------ | ------ |
+| <a id="property-email"></a> `email` | `string` | Attendee email address. |
+| <a id="property-isoptional"></a> `isOptional` | `boolean` | Whether attendance is optional. |
+| <a id="property-isorganizer"></a> `isOrganizer` | `boolean` | Whether this attendee organized the event. |
+| <a id="property-responsestatus"></a> `responseStatus` | `string` | RSVP state: needs_action, accepted, declined, or tentative. |
diff --git a/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/ToolEventRole.md b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/ToolEventRole.md
new file mode 100644
index 0000000000..175a9fe256
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/agent-reviews/type-aliases/ToolEventRole.md
@@ -0,0 +1,5 @@
+# Type Alias: ToolEventRole
+
+> **ToolEventRole** = `"organizer"` \| `"guest"`
+
+What the user is on one copy of an event, through the inbox holding it.
diff --git a/packages/sdk-docs/reference/modules.md b/packages/sdk-docs/reference/modules.md
index 116f08e418..b56d6afa67 100644
--- a/packages/sdk-docs/reference/modules.md
+++ b/packages/sdk-docs/reference/modules.md
@@ -3,6 +3,7 @@
## Modules
- [generated/agent-harness/types.gen](generated/agent-harness/types.gen/README.md)
+- [generated/agent-reviews](generated/agent-reviews/README.md)
- [generated/auth/types.gen](generated/auth/types.gen/README.md)
- [generated/calendar/types.gen](generated/calendar/types.gen/README.md)
- [generated/cognition/types.gen](generated/cognition/types.gen/README.md)
diff --git a/packages/sdk-docs/reference/src/entities/agent-sessions/review/README.md b/packages/sdk-docs/reference/src/entities/agent-sessions/review/README.md
index 6e01170941..2b4a456e64 100644
--- a/packages/sdk-docs/reference/src/entities/agent-sessions/review/README.md
+++ b/packages/sdk-docs/reference/src/entities/agent-sessions/review/README.md
@@ -9,4 +9,5 @@
- [CreateReviewOptions](type-aliases/CreateReviewOptions.md)
- [ReviewCalendarDraft](type-aliases/ReviewCalendarDraft.md)
+- [ReviewDraft](type-aliases/ReviewDraft.md)
- [ReviewEmailDraft](type-aliases/ReviewEmailDraft.md)
diff --git a/packages/sdk-docs/reference/src/entities/agent-sessions/review/classes/ReviewItem.md b/packages/sdk-docs/reference/src/entities/agent-sessions/review/classes/ReviewItem.md
index 5610d9340d..f20f892eb9 100644
--- a/packages/sdk-docs/reference/src/entities/agent-sessions/review/classes/ReviewItem.md
+++ b/packages/sdk-docs/reference/src/entities/agent-sessions/review/classes/ReviewItem.md
@@ -12,7 +12,7 @@ An item handle scopes edits and decisions to its persisted review.
| Parameter | Type |
| ------ | ------ |
-| `snapshot` | [`ReviewItem`](../../../../../generated/agent-harness/types.gen/type-aliases/ReviewItem.md) |
+| `snapshot` | [`ReviewItem`](../../../../../generated/agent-reviews/type-aliases/ReviewItem.md)\<[`SendEmail`](../../../../../generated/agent-reviews/type-aliases/SendEmail.md), [`SendEmailResponse`](../../../../../generated/agent-reviews/type-aliases/SendEmailResponse.md)\> \| [`ReviewItem`](../../../../../generated/agent-reviews/type-aliases/ReviewItem.md)\<[`CreateCalendarEvent_Serialize`](../../../../../generated/agent-reviews/type-aliases/CreateCalendarEvent_Serialize.md), [`ToolCalendarEvent`](../../../../../generated/agent-reviews/type-aliases/ToolCalendarEvent.md)\> \| [`ReviewItem`](../../../../../generated/agent-reviews/type-aliases/ReviewItem.md)\<[`ImportDraft`](../../../../../generated/agent-reviews/type-aliases/ImportDraft.md), [`NotionImportReport_Serialize`](../../../../../generated/agent-reviews/type-aliases/NotionImportReport_Serialize.md)\> |
| `actions` | \{ `dismiss`: () => `Promise`\<`void`\>; `edit`: (`draft`) => `Promise`\<`void`\>; `submit`: () => `Promise`\<`void`\>; \} |
| `actions.dismiss` | () => `Promise`\<`void`\> |
| `actions.edit` | (`draft`) => `Promise`\<`void`\> |
@@ -28,11 +28,11 @@ An item handle scopes edits and decisions to its persisted review.
#### Get Signature
-> **get** **draft**(): `unknown`
+> **get** **draft**(): [`CreateCalendarEvent_Serialize`](../../../../../generated/agent-reviews/type-aliases/CreateCalendarEvent_Serialize.md) \| [`ImportDraft`](../../../../../generated/agent-reviews/type-aliases/ImportDraft.md) \| [`SendEmail`](../../../../../generated/agent-reviews/type-aliases/SendEmail.md)
##### Returns
-`unknown`
+[`CreateCalendarEvent_Serialize`](../../../../../generated/agent-reviews/type-aliases/CreateCalendarEvent_Serialize.md) \| [`ImportDraft`](../../../../../generated/agent-reviews/type-aliases/ImportDraft.md) \| [`SendEmail`](../../../../../generated/agent-reviews/type-aliases/SendEmail.md)
***
@@ -52,11 +52,13 @@ An item handle scopes edits and decisions to its persisted review.
#### Get Signature
-> **get** **result**(): `unknown`
+> **get** **result**(): [`NotionImportReport_Serialize`](../../../../../generated/agent-reviews/type-aliases/NotionImportReport_Serialize.md) \| [`SendEmailResponse`](../../../../../generated/agent-reviews/type-aliases/SendEmailResponse.md) \| [`ToolCalendarEvent`](../../../../../generated/agent-reviews/type-aliases/ToolCalendarEvent.md) \| `null`
+
+The action's confirmed response, `null` until it completes.
##### Returns
-`unknown`
+[`NotionImportReport_Serialize`](../../../../../generated/agent-reviews/type-aliases/NotionImportReport_Serialize.md) \| [`SendEmailResponse`](../../../../../generated/agent-reviews/type-aliases/SendEmailResponse.md) \| [`ToolCalendarEvent`](../../../../../generated/agent-reviews/type-aliases/ToolCalendarEvent.md) \| `null`
***
@@ -64,11 +66,11 @@ An item handle scopes edits and decisions to its persisted review.
#### Get Signature
-> **get** **status**(): [`ReviewItemStatus`](../../../../../generated/agent-harness/types.gen/type-aliases/ReviewItemStatus.md)
+> **get** **status**(): [`ItemStatus`](../../../../../generated/agent-reviews/type-aliases/ItemStatus.md)
##### Returns
-[`ReviewItemStatus`](../../../../../generated/agent-harness/types.gen/type-aliases/ReviewItemStatus.md)
+[`ItemStatus`](../../../../../generated/agent-reviews/type-aliases/ItemStatus.md)
## Methods
@@ -86,11 +88,13 @@ An item handle scopes edits and decisions to its persisted review.
> **edit**(`draft`): `Promise`\<`void`\>
+Replace this pending draft; `kind` must match the review's.
+
#### Parameters
| Parameter | Type |
| ------ | ------ |
-| `draft` | `unknown` |
+| `draft` | [`ReviewDraft_Deserialize`](../../../../../generated/agent-reviews/type-aliases/ReviewDraft_Deserialize.md) |
#### Returns
diff --git a/packages/sdk-docs/reference/src/entities/agent-sessions/review/classes/SessionReview.md b/packages/sdk-docs/reference/src/entities/agent-sessions/review/classes/SessionReview.md
index 14f8cf35fe..9d0a7086e8 100644
--- a/packages/sdk-docs/reference/src/entities/agent-sessions/review/classes/SessionReview.md
+++ b/packages/sdk-docs/reference/src/entities/agent-sessions/review/classes/SessionReview.md
@@ -4,14 +4,14 @@ A persistent review remains actionable after the code execution ends.
## Extends
-- [`MacroEntity`](../../../entity/classes/MacroEntity.md)\<[`ReviewRecord`](../../../../../generated/agent-harness/types.gen/type-aliases/ReviewRecord.md)\>
+- [`MacroEntity`](../../../entity/classes/MacroEntity.md)\<`ReviewRecord`\>
## Properties
| Property | Modifier | Type | Inherited from |
| ------ | ------ | ------ | ------ |
| <a id="property-id"></a> `id` | `public readonly` | `string` | [`MacroEntity`](../../../entity/classes/MacroEntity.md).[`id`](../../../entity/classes/MacroEntity.md#property-id) |
-| <a id="property-kind"></a> `kind` | `readonly` | () => `Promise`\<[`ReviewKind`](../../../../../generated/agent-harness/types.gen/type-aliases/ReviewKind.md)\> | - |
+| <a id="property-kind"></a> `kind` | `readonly` | () => `Promise`\<`"calendar"` \| `"email"` \| `"import"`\> | - |
| <a id="property-title"></a> `title` | `readonly` | () => `Promise`\<`string`\> | - |
## Methods
@@ -38,13 +38,13 @@ A persistent review remains actionable after the code execution ends.
### reference()
-> **reference**(): `Promise`\<\{ `id`: `string`; `kind`: [`ReviewKind`](../../../../../generated/agent-harness/types.gen/type-aliases/ReviewKind.md); \}\>
+> **reference**(): `Promise`\<\{ `id`: `string`; `kind`: `"calendar"` \| `"email"` \| `"import"`; \}\>
Compact reference for main()'s returned reviews array.
#### Returns
-`Promise`\<\{ `id`: `string`; `kind`: [`ReviewKind`](../../../../../generated/agent-harness/types.gen/type-aliases/ReviewKind.md); \}\>
+`Promise`\<\{ `id`: `string`; `kind`: `"calendar"` \| `"email"` \| `"import"`; \}\>
***
@@ -82,15 +82,15 @@ Submit the saved pending drafts. Never retries a conflict or ambiguous send.
### toJSON()
-> **toJSON**(): \{ `detail?`: [`ReviewRecord`](../../../../../generated/agent-harness/types.gen/type-aliases/ReviewRecord.md); `id`: `string`; \}
+> **toJSON**(): \{ `detail?`: [`ReviewRecord_Serialize`](../../../../../generated/agent-reviews/type-aliases/ReviewRecord_Serialize.md); `id`: `string`; \}
#### Returns
-\{ `detail?`: [`ReviewRecord`](../../../../../generated/agent-harness/types.gen/type-aliases/ReviewRecord.md); `id`: `string`; \}
+\{ `detail?`: [`ReviewRecord_Serialize`](../../../../../generated/agent-reviews/type-aliases/ReviewRecord_Serialize.md); `id`: `string`; \}
| Name | Type |
| ------ | ------ |
-| `detail?` | [`ReviewRecord`](../../../../../generated/agent-harness/types.gen/type-aliases/ReviewRecord.md) |
+| `detail?` | [`ReviewRecord_Serialize`](../../../../../generated/agent-reviews/type-aliases/ReviewRecord_Serialize.md) |
| `id` | `string` |
#### Inherited from
@@ -166,7 +166,7 @@ Present a review in a session without requiring a code execution.
| ------ | ------ |
| `client` | `MacroClient` |
| `session` | [`AgentSession`](../../agent-session/classes/AgentSession.md) |
-| `record` | [`ReviewRecord`](../../../../../generated/agent-harness/types.gen/type-aliases/ReviewRecord.md) |
+| `record` | [`ReviewRecord_Serialize`](../../../../../generated/agent-reviews/type-aliases/ReviewRecord_Serialize.md) |
#### Returns
diff --git a/packages/sdk-docs/reference/src/entities/agent-sessions/review/type-aliases/CreateReviewOptions.md b/packages/sdk-docs/reference/src/entities/agent-sessions/review/type-aliases/CreateReviewOptions.md
index aa7aac251a..46965269d8 100644
--- a/packages/sdk-docs/reference/src/entities/agent-sessions/review/type-aliases/CreateReviewOptions.md
+++ b/packages/sdk-docs/reference/src/entities/agent-sessions/review/type-aliases/CreateReviewOptions.md
@@ -1,3 +1,11 @@
# Type Alias: CreateReviewOptions
-> **CreateReviewOptions** = \{ `drafts`: [`ReviewEmailDraft`](ReviewEmailDraft.md)[]; `kind`: `"email"`; `title`: `string`; \} \| \{ `drafts`: [`ReviewCalendarDraft`](ReviewCalendarDraft.md)[]; `kind`: `"calendar"`; `title`: `string`; \}
+> **CreateReviewOptions** = \{ `title`: [`ReviewTitle`](../../../../../generated/agent-reviews/type-aliases/ReviewTitle.md); \} & [`ReviewDrafts_Deserialize`](../../../../../generated/agent-reviews/type-aliases/ReviewDrafts_Deserialize.md)
+
+A review's kind and its drafts; the execution is attached by the handle.
+
+## Type Declaration
+
+| Name | Type |
+| ------ | ------ |
+| `title` | [`ReviewTitle`](../../../../../generated/agent-reviews/type-aliases/ReviewTitle.md) |
diff --git a/packages/sdk-docs/reference/src/entities/agent-sessions/review/type-aliases/ReviewCalendarDraft.md b/packages/sdk-docs/reference/src/entities/agent-sessions/review/type-aliases/ReviewCalendarDraft.md
index ab9287a847..1aad78cfda 100644
--- a/packages/sdk-docs/reference/src/entities/agent-sessions/review/type-aliases/ReviewCalendarDraft.md
+++ b/packages/sdk-docs/reference/src/entities/agent-sessions/review/type-aliases/ReviewCalendarDraft.md
@@ -1,22 +1,5 @@
# Type Alias: ReviewCalendarDraft
-> **ReviewCalendarDraft** = \{ `addGoogleMeet?`: `boolean`; `addMacroCall?`: `boolean`; `attendees?`: \{ `email`: `string`; `isOptional?`: `boolean`; \}[]; `calendarId?`: `string` \| `null`; `description?`: `string` \| `null`; `eventType?`: `"default"` \| `"out_of_office"`; `location?`: `string` \| `null`; `outOfOffice?`: \{ `autoDeclineMode?`: `"decline_none"` \| `"decline_all"` \| `"decline_new_only"`; `declineMessage?`: `string` \| `null`; \} \| `null`; `recurrenceLines?`: `string`[]; `reminders?`: \{ `overrides?`: \{ `method`: `string`; `minutes`: `number`; \}[]; `useDefault`: `boolean`; \} \| `null`; `time`: [`EventTime`](../../../../../generated/calendar/types.gen/type-aliases/EventTime.md); `title`: `string`; \}
+> **ReviewCalendarDraft** = [`CreateCalendarEvent_Deserialize`](../../../../../generated/agent-reviews/type-aliases/CreateCalendarEvent_Deserialize.md)
Calendar drafts use the existing calendar composer and creation action.
-
-## Properties
-
-| Property | Type |
-| ------ | ------ |
-| <a id="property-addgooglemeet"></a> `addGoogleMeet?` | `boolean` |
-| <a id="property-addmacrocall"></a> `addMacroCall?` | `boolean` |
-| <a id="property-attendees"></a> `attendees?` | \{ `email`: `string`; `isOptional?`: `boolean`; \}[] |
-| <a id="property-calendarid"></a> `calendarId?` | `string` \| `null` |
-| <a id="property-description"></a> `description?` | `string` \| `null` |
-| <a id="property-eventtype"></a> `eventType?` | `"default"` \| `"out_of_office"` |
-| <a id="property-location"></a> `location?` | `string` \| `null` |
-| <a id="property-outofoffice"></a> `outOfOffice?` | \{ `autoDeclineMode?`: `"decline_none"` \| `"decline_all"` \| `"decline_new_only"`; `declineMessage?`: `string` \| `null`; \} \| `null` |
-| <a id="property-recurrencelines"></a> `recurrenceLines?` | `string`[] |
-| <a id="property-reminders"></a> `reminders?` | \{ `overrides?`: \{ `method`: `string`; `minutes`: `number`; \}[]; `useDefault`: `boolean`; \} \| `null` |
-| <a id="property-time"></a> `time` | [`EventTime`](../../../../../generated/calendar/types.gen/type-aliases/EventTime.md) |
-| <a id="property-title"></a> `title` | `string` |
diff --git a/packages/sdk-docs/reference/src/entities/agent-sessions/review/type-aliases/ReviewDraft.md b/packages/sdk-docs/reference/src/entities/agent-sessions/review/type-aliases/ReviewDraft.md
new file mode 100644
index 0000000000..7db1fa852d
--- /dev/null
+++ b/packages/sdk-docs/reference/src/entities/agent-sessions/review/type-aliases/ReviewDraft.md
@@ -0,0 +1,5 @@
+# Type Alias: ReviewDraft
+
+> **ReviewDraft** = [`ReviewDraft_Deserialize`](../../../../../generated/agent-reviews/type-aliases/ReviewDraft_Deserialize.md)
+
+A replacement draft keyed by its review's kind.
diff --git a/packages/sdk-docs/reference/src/entities/agent-sessions/review/type-aliases/ReviewEmailDraft.md b/packages/sdk-docs/reference/src/entities/agent-sessions/review/type-aliases/ReviewEmailDraft.md
index 5976d705fa..30b2e73615 100644
--- a/packages/sdk-docs/reference/src/entities/agent-sessions/review/type-aliases/ReviewEmailDraft.md
+++ b/packages/sdk-docs/reference/src/entities/agent-sessions/review/type-aliases/ReviewEmailDraft.md
@@ -1,18 +1,5 @@
# Type Alias: ReviewEmailDraft
-> **ReviewEmailDraft** = \{ `attachments?`: \{ `documentId`: `string`; \}[]; `bcc?`: \{ `email`: `string`; `name?`: `string` \| `null`; \}[]; `body`: `string`; `cc?`: \{ `email`: `string`; `name?`: `string` \| `null`; \}[]; `includeSignature?`: `boolean` \| `null`; `replyingToId?`: `string` \| `null`; `subject`: `string`; `to`: \{ `email`: `string`; `name?`: `string` \| `null`; \}[]; \}
+> **ReviewEmailDraft** = [`SendEmail`](../../../../../generated/agent-reviews/type-aliases/SendEmail.md)
Markdown is rendered by the ordinary email action; the UI can edit each draft.
-
-## Properties
-
-| Property | Type |
-| ------ | ------ |
-| <a id="property-attachments"></a> `attachments?` | \{ `documentId`: `string`; \}[] |
-| <a id="property-bcc"></a> `bcc?` | \{ `email`: `string`; `name?`: `string` \| `null`; \}[] |
-| <a id="property-body"></a> `body` | `string` |
-| <a id="property-cc"></a> `cc?` | \{ `email`: `string`; `name?`: `string` \| `null`; \}[] |
-| <a id="property-includesignature"></a> `includeSignature?` | `boolean` \| `null` |
-| <a id="property-replyingtoid"></a> `replyingToId?` | `string` \| `null` |
-| <a id="property-subject"></a> `subject` | `string` |
-| <a id="property-to"></a> `to` | \{ `email`: `string`; `name?`: `string` \| `null`; \}[] |
diff --git a/packages/sdk-docs/reference/src/macro/README.md b/packages/sdk-docs/reference/src/macro/README.md
index 40003e53b3..4a4272154c 100644
--- a/packages/sdk-docs/reference/src/macro/README.md
+++ b/packages/sdk-docs/reference/src/macro/README.md
@@ -580,6 +580,12 @@ Re-exports [ReviewCalendarDraft](../entities/agent-sessions/review/type-aliases/
***
+### ReviewDraft
+
+Re-exports [ReviewDraft](../entities/agent-sessions/review/type-aliases/ReviewDraft.md)
+
+***
+
### ReviewEmailDraft
Re-exports [ReviewEmailDraft](../entities/agent-sessions/review/type-aliases/ReviewEmailDraft.md)
diff --git a/packages/sdk-docs/src/render.ts b/packages/sdk-docs/src/render.ts
index 993eb5aa65..36a4fbad05 100644
--- a/packages/sdk-docs/src/render.ts
+++ b/packages/sdk-docs/src/render.ts
@@ -19,6 +19,8 @@ export async function renderSdkDocs(root: string, output: string) {
const entryPoints = [
...new Bun.Glob('src/entities/**/*.ts').scanSync(sdk),
...new Bun.Glob('generated/*/types.gen.ts').scanSync(sdk),
+ // Specta-generated review types the review handles are typed with.
+ 'generated/agent-reviews/index.ts',
'src/macro.ts',
'src/config.ts',
'src/mentions.ts',
diff --git a/packages/sdk/generated/agent-harness/index.ts b/packages/sdk/generated/agent-harness/index.ts
index 9f766316e7..b6bfe18c4a 100644
--- a/packages/sdk/generated/agent-harness/index.ts
+++ b/packages/sdk/generated/agent-harness/index.ts
@@ -1,4 +1,4 @@
// This file is auto-generated by @hey-api/openapi-ts
export { type Options, Sdk } from './sdk.gen';
-export type { AccessLevel, AgentAction, AgentActionId, AgentConfigKindDto, AgentConfigOptionDto, AgentConfigSelectOptionDto, AgentConversationDto, AgentConversationsDto, AgentConversationSessionDto, AgentConversationTurnDto, AgentMode, AgentModeChoiceRequest, AgentModeChoiceResponse, AgentModelDto, AgentModelsStatusDto, AgentPermissionAction, AgentPromptAction, AgentRepositoriesResponse, AgentRepositoryBranchesResponse, AgentRepositoryDto, AgentRespondElicitationAction, AgentSessionChangesPatchResponse, AgentSessionChangesResponse, AgentSessionFoldedLogResponse, AgentSessionLogEntryDto, AgentSessionLogResponse, AgentSessionPreviewData, AgentSessionPreviewDto, AgentSessionQueueResponse, AgentSessionResponse, AgentSessionsForPullRequestData, AgentSessionsForPullRequestError, AgentSessionsForPullRequestErrors, AgentSessionsForPullRequestResponse, AgentSessionsForPullRequestResponses, AgentSessionsForPullRequestsData, AgentSessionsForPullRequestsError, AgentSessionsForPullRequestsErrors, AgentSessionsForPullRequestsResponse, AgentSessionsForPullRequestsResponses, AgentSetConfigOptionAction, AgentSetModelAction, AiAdmissionErrorBody, AiSuggestions, AnswerAgentSessionToolApprovalData, AnswerAgentSessionToolApprovalError, AnswerAgentSessionToolApprovalErrors, AnswerAgentSessionToolApprovalResponse, AnswerAgentSessionToolApprovalResponses, AnswerToolApprovalRequest, AnswerToolApprovalResponse, AppConnectedRequest, ArchiveCause, AutoArchiveOverridesBody, AutoArchivePreferencesBody, BotId, CalendarSuggestions, CallSearchSuggestions, CapabilityHarnessDto, CaptureAttemptDto, CaptureOutcomeDto, ChangedFileDto, ChangesetDto, ChangesetSourceDto, ChannelSearchSuggestions, ChannelSharePermission, ChooseAgentModeData, ChooseAgentModeErrors, ChooseAgentModeResponse, ChooseAgentModeResponses, ClassifyData, ClassifyErrors, ClassifyInputRequest, ClassifyInputResponse, ClassifyResponse, ClassifyResponses, ClientOptions, CodingPreferencesBody, ControlAgentSessionData, ControlAgentSessionError, ControlAgentSessionErrors, ControlAgentSessionResponse, ControlAgentSessionResponses, ControlRequest, ControlResponse, ControlStatusDto, ConversationTurnState, CreateAgentSessionData, CreateAgentSessionError, CreateAgentSessionErrors, CreateAgentSessionRequest, CreateAgentSessionResponse, CreateAgentSessionResponse2, CreateAgentSessionResponses, CreateReview, CreateSessionReviewData, CreateSessionReviewErrors, CreateSessionReviewResponse, CreateSessionReviewResponses, CreateSessionThread, DecideSessionReviewData, DecideSessionReviewErrors, DecideSessionReviewResponse, DecideSessionReviewResponses, DecisionVia, DeleteAgentSessionData, DeleteAgentSessionError, DeleteAgentSessionErrors, DeleteAgentSessionResponses, DiscoverAgentCapabilitiesHandlerData, DiscoverAgentCapabilitiesHandlerErrors, DiscoverAgentCapabilitiesHandlerResponse, DiscoverAgentCapabilitiesHandlerResponses, DiscoverAgentCapabilitiesRequest, DiscoverAgentCapabilitiesResponse, DocumentId, EditQueuedActionData, EditQueuedActionError, EditQueuedActionErrors, EditQueuedActionRequest, EditQueuedActionResponse, EditQueuedActionResponses, ElicitationAnswer, ElicitationContentValue, ElicitationRequestId, EmailSearchSuggestions, EmailSuggestions, ExecutionActivity, ExecutionId, ExecutionRecord, ExecutionStatus, ExternalSessionResponse, ExtractData, ExtractErrors, ExtractInputRequest, ExtractInputResponse, ExtractResponse, ExtractResponses, FileChangeKindDto, GetAgentAutoArchivePreferencesData, GetAgentAutoArchivePreferencesError, GetAgentAutoArchivePreferencesErrors, GetAgentAutoArchivePreferencesResponse, GetAgentAutoArchivePreferencesResponses, GetAgentCodingPreferencesData, GetAgentCodingPreferencesError, GetAgentCodingPreferencesErrors, GetAgentCodingPreferencesResponse, GetAgentCodingPreferencesResponses, GetAgentSandboxSizeData, GetAgentSandboxSizeError, GetAgentSandboxSizeErrors, GetAgentSandboxSizeResponse, GetAgentSandboxSizeResponses, GetAgentSessionAutoArchiveData, GetAgentSessionAutoArchiveError, GetAgentSessionAutoArchiveErrors, GetAgentSessionAutoArchiveResponse, GetAgentSessionAutoArchiveResponses, GetAgentSessionChangesData, GetAgentSessionChangesError, GetAgentSessionChangesErrors, GetAgentSessionChangesPatchData, GetAgentSessionChangesPatchError, GetAgentSessionChangesPatchErrors, GetAgentSessionChangesPatchResponse, GetAgentSessionChangesPatchResponses, GetAgentSessionChangesResponse, GetAgentSessionChangesResponses, GetAgentSessionData, GetAgentSessionError, GetAgentSessionErrors, GetAgentSessionFoldedLogData, GetAgentSessionFoldedLogError, GetAgentSessionFoldedLogErrors, GetAgentSessionFoldedLogResponse, GetAgentSessionFoldedLogResponses, GetAgentSessionLogData, GetAgentSessionLogError, GetAgentSessionLogErrors, GetAgentSessionLogResponse, GetAgentSessionLogResponses, GetAgentSessionPermissionsData, GetAgentSessionPermissionsError, GetAgentSessionPermissionsErrors, GetAgentSessionPermissionsResponse, GetAgentSessionPermissionsResponses, GetAgentSessionQueueData, GetAgentSessionQueueError, GetAgentSessionQueueErrors, GetAgentSessionQueueResponse, GetAgentSessionQueueResponses, GetAgentSessionResponse, GetAgentSessionResponses, GetCodeExecutionData, GetCodeExecutionErrors, GetCodeExecutionResponse, GetCodeExecutionResponses, GetSessionReviewData, GetSessionReviewErrors, GetSessionReviewResponse, GetSessionReviewResponses, GitRefDto, InputIntent, InputPropertyDefinition, InputPropertySuggestion, InputSuggestions, IntentScore, LinkAgentSessionPullRequestData, LinkAgentSessionPullRequestError, LinkAgentSessionPullRequestErrors, LinkAgentSessionPullRequestResponse, LinkAgentSessionPullRequestResponses, LinkShare, ListAgentConversationsData, ListAgentConversationsErrors, ListAgentConversationsResponse, ListAgentConversationsResponses, ListAgentRepositoriesData, ListAgentRepositoriesErrors, ListAgentRepositoriesResponse, ListAgentRepositoriesResponses, ListAgentRepositoryBranchesData, ListAgentRepositoryBranchesErrors, ListAgentRepositoryBranchesResponse, ListAgentRepositoryBranchesResponses, ListAgentSessionPullRequestsData, ListAgentSessionPullRequestsError, ListAgentSessionPullRequestsErrors, ListAgentSessionPullRequestsResponse, ListAgentSessionPullRequestsResponses, ListExecutionReviewsData, ListExecutionReviewsErrors, ListExecutionReviewsResponse, ListExecutionReviewsResponses, LoadAgentModelsHandlerData, LoadAgentModelsHandlerErrors, LoadAgentModelsHandlerResponse, LoadAgentModelsHandlerResponses, LoadAgentModelsRequest, LoadAgentModelsResponse, LogDirectionDto, LogFrameDto, MessageParent, MessageSuggestions, ModelHarnessDto, MonthlyWeekday, NoteSuggestions, PermissionAnswer, PresentSessionViewData, PresentSessionViewErrors, PresentSessionViewResponse, PresentSessionViewResponses, PresentView, PreviewAgentSessionsData, PreviewAgentSessionsError, PreviewAgentSessionsErrors, PreviewAgentSessionsRequest, PreviewAgentSessionsResponse, PreviewAgentSessionsResponse2, PreviewAgentSessionsResponses, PromptAttachment, PullRequestLinkedSession, PullRequestLinkSource, PullRequestSessions, PullRequestSessionsResponse, PullRequestsSessionsResponse, PullRequestUrl, PullRequestUrls, PutAgentAutoArchivePreferencesData, PutAgentAutoArchivePreferencesError, PutAgentAutoArchivePreferencesErrors, PutAgentAutoArchivePreferencesResponse, PutAgentAutoArchivePreferencesResponses, PutAgentCodingPreferencesData, PutAgentCodingPreferencesError, PutAgentCodingPreferencesErrors, PutAgentCodingPreferencesResponse, PutAgentCodingPreferencesResponses, PutAgentSandboxSizeData, PutAgentSandboxSizeError, PutAgentSandboxSizeErrors, PutAgentSandboxSizeResponse, PutAgentSandboxSizeResponses, PutAgentSessionAutoArchiveData, PutAgentSessionAutoArchiveError, PutAgentSessionAutoArchiveErrors, PutAgentSessionAutoArchiveResponse, PutAgentSessionAutoArchiveResponses, PutAgentSessionSandboxSizeData, PutAgentSessionSandboxSizeError, PutAgentSessionSandboxSizeErrors, PutAgentSessionSandboxSizeResponse, PutAgentSessionSandboxSizeResponses, QuerySearchSuggestions, QueuedActionDto, RecordedCallStatus, RecordedToolCall, RecurrenceEnd, RecurrenceFrequency, RecurrenceSuggestion, RefreshAgentSessionChangesData, RefreshAgentSessionChangesError, RefreshAgentSessionChangesErrors, RefreshAgentSessionChangesResponse, RefreshAgentSessionChangesResponses, RemoveQueuedActionData, RemoveQueuedActionError, RemoveQueuedActionErrors, RemoveQueuedActionResponse, RemoveQueuedActionResponses, RenameAgentSessionData, RenameAgentSessionError, RenameAgentSessionErrors, RenameAgentSessionRequest, RenameAgentSessionResponse, RenameAgentSessionResponses, ReportAgentSessionAppConnectedData, ReportAgentSessionAppConnectedError, ReportAgentSessionAppConnectedErrors, ReportAgentSessionAppConnectedResponses, RetryAgentConversationTurnData, RetryAgentConversationTurnErrors, RetryAgentConversationTurnRequest, RetryAgentConversationTurnResponse, RetryAgentConversationTurnResponses, ReviewDecision, ReviewDecisionContext, ReviewId, ReviewItem, ReviewItemStatus, ReviewKind, ReviewRecord, SandboxSize, SandboxSizeBody, SearchSuggestions, SearchType, SessionAutoArchiveResponse, SessionBot, SessionPullRequestLink, SessionPullRequestsResponse, SessionStatusDto, SetAgentSessionArchivedData, SetAgentSessionArchivedError, SetAgentSessionArchivedErrors, SetAgentSessionArchivedRequest, SetAgentSessionArchivedResponse, SetAgentSessionArchivedResponses, SharePermissionV2, StartFreshAgentConversationData, StartFreshAgentConversationErrors, StartFreshAgentConversationRequest, StartFreshAgentConversationResponse, StartFreshAgentConversationResponses, SteerQueuedActionData, SteerQueuedActionError, SteerQueuedActionErrors, SteerQueuedActionResponse, SteerQueuedActionResponses, TaskSearchSuggestions, TaskSuggestions, ToolActor, ToolApprovalAnswerDto, ToolApprovalStatusDto, UnlinkAgentSessionPullRequestData, UnlinkAgentSessionPullRequestError, UnlinkAgentSessionPullRequestErrors, UnlinkAgentSessionPullRequestResponse, UnlinkAgentSessionPullRequestResponses, UpdateAgentSessionPermissionsData, UpdateAgentSessionPermissionsError, UpdateAgentSessionPermissionsErrors, UpdateAgentSessionPermissionsResponse, UpdateAgentSessionPermissionsResponses, UpdateChannelSharePermission, UpdateOperation, UpdateSharePermissionRequestV2, WarmAgentSessionHandlerData, WarmAgentSessionHandlerResponse, WarmAgentSessionHandlerResponses, WarmAgentSessionRequest, WarmAgentSessionResponse, WeekdayCode, WithAgentSessionId } from './types.gen';
+export type { AccessLevel, AgentAction, AgentActionId, AgentConfigKindDto, AgentConfigOptionDto, AgentConfigSelectOptionDto, AgentConversationDto, AgentConversationsDto, AgentConversationSessionDto, AgentConversationTurnDto, AgentMode, AgentModeChoiceRequest, AgentModeChoiceResponse, AgentModelDto, AgentModelsStatusDto, AgentPermissionAction, AgentPromptAction, AgentRepositoriesResponse, AgentRepositoryBranchesResponse, AgentRepositoryDto, AgentRespondElicitationAction, AgentSessionChangesPatchResponse, AgentSessionChangesResponse, AgentSessionFoldedLogResponse, AgentSessionLogEntryDto, AgentSessionLogResponse, AgentSessionPreviewData, AgentSessionPreviewDto, AgentSessionQueueResponse, AgentSessionResponse, AgentSessionsForPullRequestData, AgentSessionsForPullRequestError, AgentSessionsForPullRequestErrors, AgentSessionsForPullRequestResponse, AgentSessionsForPullRequestResponses, AgentSessionsForPullRequestsData, AgentSessionsForPullRequestsError, AgentSessionsForPullRequestsErrors, AgentSessionsForPullRequestsResponse, AgentSessionsForPullRequestsResponses, AgentSetConfigOptionAction, AgentSetModelAction, AiAdmissionErrorBody, AiSuggestions, AnswerAgentSessionToolApprovalData, AnswerAgentSessionToolApprovalError, AnswerAgentSessionToolApprovalErrors, AnswerAgentSessionToolApprovalResponse, AnswerAgentSessionToolApprovalResponses, AnswerToolApprovalRequest, AnswerToolApprovalResponse, AppConnectedRequest, ArchiveCause, AutoArchiveOverridesBody, AutoArchivePreferencesBody, BotId, CalendarSuggestions, CallSearchSuggestions, CapabilityHarnessDto, CaptureAttemptDto, CaptureOutcomeDto, ChangedFileDto, ChangesetDto, ChangesetSourceDto, ChannelSearchSuggestions, ChannelSharePermission, ChooseAgentModeData, ChooseAgentModeErrors, ChooseAgentModeResponse, ChooseAgentModeResponses, ClassifyData, ClassifyErrors, ClassifyInputRequest, ClassifyInputResponse, ClassifyResponse, ClassifyResponses, ClientOptions, CodingPreferencesBody, ControlAgentSessionData, ControlAgentSessionError, ControlAgentSessionErrors, ControlAgentSessionResponse, ControlAgentSessionResponses, ControlRequest, ControlResponse, ControlStatusDto, ConversationTurnState, CreateAgentSessionData, CreateAgentSessionError, CreateAgentSessionErrors, CreateAgentSessionRequest, CreateAgentSessionResponse, CreateAgentSessionResponse2, CreateAgentSessionResponses, CreateReview, CreateSessionReviewData, CreateSessionReviewErrors, CreateSessionReviewResponse, CreateSessionReviewResponses, CreateSessionThread, DecideSessionReviewData, DecideSessionReviewErrors, DecideSessionReviewResponse, DecideSessionReviewResponses, DecisionVia, DeleteAgentSessionData, DeleteAgentSessionError, DeleteAgentSessionErrors, DeleteAgentSessionResponses, DiscoverAgentCapabilitiesHandlerData, DiscoverAgentCapabilitiesHandlerErrors, DiscoverAgentCapabilitiesHandlerResponse, DiscoverAgentCapabilitiesHandlerResponses, DiscoverAgentCapabilitiesRequest, DiscoverAgentCapabilitiesResponse, DocumentId, EditQueuedActionData, EditQueuedActionError, EditQueuedActionErrors, EditQueuedActionRequest, EditQueuedActionResponse, EditQueuedActionResponses, ElicitationAnswer, ElicitationContentValue, ElicitationRequestId, EmailSearchSuggestions, EmailSuggestions, ExecutionActivity, ExecutionId, ExecutionRecord, ExecutionStatus, ExternalSessionResponse, ExtractData, ExtractErrors, ExtractInputRequest, ExtractInputResponse, ExtractResponse, ExtractResponses, FileChangeKindDto, GetAgentAutoArchivePreferencesData, GetAgentAutoArchivePreferencesError, GetAgentAutoArchivePreferencesErrors, GetAgentAutoArchivePreferencesResponse, GetAgentAutoArchivePreferencesResponses, GetAgentCodingPreferencesData, GetAgentCodingPreferencesError, GetAgentCodingPreferencesErrors, GetAgentCodingPreferencesResponse, GetAgentCodingPreferencesResponses, GetAgentSandboxSizeData, GetAgentSandboxSizeError, GetAgentSandboxSizeErrors, GetAgentSandboxSizeResponse, GetAgentSandboxSizeResponses, GetAgentSessionAutoArchiveData, GetAgentSessionAutoArchiveError, GetAgentSessionAutoArchiveErrors, GetAgentSessionAutoArchiveResponse, GetAgentSessionAutoArchiveResponses, GetAgentSessionChangesData, GetAgentSessionChangesError, GetAgentSessionChangesErrors, GetAgentSessionChangesPatchData, GetAgentSessionChangesPatchError, GetAgentSessionChangesPatchErrors, GetAgentSessionChangesPatchResponse, GetAgentSessionChangesPatchResponses, GetAgentSessionChangesResponse, GetAgentSessionChangesResponses, GetAgentSessionData, GetAgentSessionError, GetAgentSessionErrors, GetAgentSessionFoldedLogData, GetAgentSessionFoldedLogError, GetAgentSessionFoldedLogErrors, GetAgentSessionFoldedLogResponse, GetAgentSessionFoldedLogResponses, GetAgentSessionLogData, GetAgentSessionLogError, GetAgentSessionLogErrors, GetAgentSessionLogResponse, GetAgentSessionLogResponses, GetAgentSessionPermissionsData, GetAgentSessionPermissionsError, GetAgentSessionPermissionsErrors, GetAgentSessionPermissionsResponse, GetAgentSessionPermissionsResponses, GetAgentSessionQueueData, GetAgentSessionQueueError, GetAgentSessionQueueErrors, GetAgentSessionQueueResponse, GetAgentSessionQueueResponses, GetAgentSessionResponse, GetAgentSessionResponses, GetCodeExecutionData, GetCodeExecutionErrors, GetCodeExecutionResponse, GetCodeExecutionResponses, GetSessionReviewData, GetSessionReviewErrors, GetSessionReviewResponse, GetSessionReviewResponses, GitRefDto, InputIntent, InputPropertyDefinition, InputPropertySuggestion, InputSuggestions, IntentScore, LinkAgentSessionPullRequestData, LinkAgentSessionPullRequestError, LinkAgentSessionPullRequestErrors, LinkAgentSessionPullRequestResponse, LinkAgentSessionPullRequestResponses, LinkShare, ListAgentConversationsData, ListAgentConversationsErrors, ListAgentConversationsResponse, ListAgentConversationsResponses, ListAgentRepositoriesData, ListAgentRepositoriesErrors, ListAgentRepositoriesResponse, ListAgentRepositoriesResponses, ListAgentRepositoryBranchesData, ListAgentRepositoryBranchesErrors, ListAgentRepositoryBranchesResponse, ListAgentRepositoryBranchesResponses, ListAgentSessionPullRequestsData, ListAgentSessionPullRequestsError, ListAgentSessionPullRequestsErrors, ListAgentSessionPullRequestsResponse, ListAgentSessionPullRequestsResponses, ListExecutionReviewsData, ListExecutionReviewsErrors, ListExecutionReviewsResponse, ListExecutionReviewsResponses, LoadAgentModelsHandlerData, LoadAgentModelsHandlerErrors, LoadAgentModelsHandlerResponse, LoadAgentModelsHandlerResponses, LoadAgentModelsRequest, LoadAgentModelsResponse, LogDirectionDto, LogFrameDto, MessageParent, MessageSuggestions, ModelHarnessDto, MonthlyWeekday, NoteSuggestions, PermissionAnswer, PresentSessionViewData, PresentSessionViewErrors, PresentSessionViewResponse, PresentSessionViewResponses, PresentView, PreviewAgentSessionsData, PreviewAgentSessionsError, PreviewAgentSessionsErrors, PreviewAgentSessionsRequest, PreviewAgentSessionsResponse, PreviewAgentSessionsResponse2, PreviewAgentSessionsResponses, PromptAttachment, PullRequestLinkedSession, PullRequestLinkSource, PullRequestSessions, PullRequestSessionsResponse, PullRequestsSessionsResponse, PullRequestUrl, PullRequestUrls, PutAgentAutoArchivePreferencesData, PutAgentAutoArchivePreferencesError, PutAgentAutoArchivePreferencesErrors, PutAgentAutoArchivePreferencesResponse, PutAgentAutoArchivePreferencesResponses, PutAgentCodingPreferencesData, PutAgentCodingPreferencesError, PutAgentCodingPreferencesErrors, PutAgentCodingPreferencesResponse, PutAgentCodingPreferencesResponses, PutAgentSandboxSizeData, PutAgentSandboxSizeError, PutAgentSandboxSizeErrors, PutAgentSandboxSizeResponse, PutAgentSandboxSizeResponses, PutAgentSessionAutoArchiveData, PutAgentSessionAutoArchiveError, PutAgentSessionAutoArchiveErrors, PutAgentSessionAutoArchiveResponse, PutAgentSessionAutoArchiveResponses, PutAgentSessionSandboxSizeData, PutAgentSessionSandboxSizeError, PutAgentSessionSandboxSizeErrors, PutAgentSessionSandboxSizeResponse, PutAgentSessionSandboxSizeResponses, QuerySearchSuggestions, QueuedActionDto, RecordedCallStatus, RecordedToolCall, RecurrenceEnd, RecurrenceFrequency, RecurrenceSuggestion, RefreshAgentSessionChangesData, RefreshAgentSessionChangesError, RefreshAgentSessionChangesErrors, RefreshAgentSessionChangesResponse, RefreshAgentSessionChangesResponses, RemoveQueuedActionData, RemoveQueuedActionError, RemoveQueuedActionErrors, RemoveQueuedActionResponse, RemoveQueuedActionResponses, RenameAgentSessionData, RenameAgentSessionError, RenameAgentSessionErrors, RenameAgentSessionRequest, RenameAgentSessionResponse, RenameAgentSessionResponses, ReportAgentSessionAppConnectedData, ReportAgentSessionAppConnectedError, ReportAgentSessionAppConnectedErrors, ReportAgentSessionAppConnectedResponses, RetryAgentConversationTurnData, RetryAgentConversationTurnErrors, RetryAgentConversationTurnRequest, RetryAgentConversationTurnResponse, RetryAgentConversationTurnResponses, ReviewDecision, ReviewDecisionContext, ReviewId, ReviewRecord, SandboxSize, SandboxSizeBody, SearchSuggestions, SearchType, SessionAutoArchiveResponse, SessionBot, SessionPullRequestLink, SessionPullRequestsResponse, SessionStatusDto, SetAgentSessionArchivedData, SetAgentSessionArchivedError, SetAgentSessionArchivedErrors, SetAgentSessionArchivedRequest, SetAgentSessionArchivedResponse, SetAgentSessionArchivedResponses, SharePermissionV2, StartFreshAgentConversationData, StartFreshAgentConversationErrors, StartFreshAgentConversationRequest, StartFreshAgentConversationResponse, StartFreshAgentConversationResponses, SteerQueuedActionData, SteerQueuedActionError, SteerQueuedActionErrors, SteerQueuedActionResponse, SteerQueuedActionResponses, TaskSearchSuggestions, TaskSuggestions, ToolActor, ToolApprovalAnswerDto, ToolApprovalStatusDto, UnlinkAgentSessionPullRequestData, UnlinkAgentSessionPullRequestError, UnlinkAgentSessionPullRequestErrors, UnlinkAgentSessionPullRequestResponse, UnlinkAgentSessionPullRequestResponses, UpdateAgentSessionPermissionsData, UpdateAgentSessionPermissionsError, UpdateAgentSessionPermissionsErrors, UpdateAgentSessionPermissionsResponse, UpdateAgentSessionPermissionsResponses, UpdateChannelSharePermission, UpdateOperation, UpdateSharePermissionRequestV2, WarmAgentSessionHandlerData, WarmAgentSessionHandlerResponse, WarmAgentSessionHandlerResponses, WarmAgentSessionRequest, WarmAgentSessionResponse, WeekdayCode, WithAgentSessionId } from './types.gen';
diff --git a/packages/sdk/generated/agent-harness/types.gen.ts b/packages/sdk/generated/agent-harness/types.gen.ts
index 1889eb8a5a..8ffdc9e9ca 100644
--- a/packages/sdk/generated/agent-harness/types.gen.ts
+++ b/packages/sdk/generated/agent-harness/types.gen.ts
@@ -1156,26 +1156,13 @@ export type CreateAgentSessionResponse = {
};
/**
- * Review creation. Drafts are validated by the action's owning adapter.
+ * Review creation. Decoding it validates every draft; creating a review only
+ * presents the drafts, and the account holder acts separately.
*/
export type CreateReview = {
- /**
- * One to one hundred independent drafts. Email: {subject, body: Markdown,
- * to: [{email, name?}], cc?: [{email, name?}], bcc?: [{email, name?}],
- * replyingToId?, attachments?: [{documentId}]}. Calendar: {title,
- * time: {kind: "timed", startsAt: ISO datetime, endsAt: ISO datetime,
- * timeZone?: IANA zone} or {kind: "allDay", startDate: ISO date,
- * endDate: exclusive ISO date}, description?, location?, attendees?:
- * [{email, isOptional?}]}. Import: exactly one draft {source: "notion" | "linear" | "jira"},
- * presenting the plan ImportFromNotion, ImportFromLinear or ImportFromJira staged.
- * Creating any review only presents these drafts; the user acts separately.
- */
- drafts: Array<unknown>;
+ [key: string]: unknown;
+} & {
executionId?: null | ExecutionId;
- /**
- * Existing UI and action to use.
- */
- kind: ReviewKind;
/**
* Stack label.
*/
@@ -2067,9 +2054,11 @@ export type RetryAgentConversationTurnRequest = {
export type ReviewDecision = {
action: 'edit';
/**
- * Replacement action arguments.
+ * Replacement action arguments, keyed by the review's kind.
*/
- draft: unknown;
+ draft: {
+ [key: string]: unknown;
+ };
/**
* Pending item to update.
*/
@@ -2127,68 +2116,22 @@ export type ReviewDecisionContext = {
*/
export type ReviewId = string;
-/**
- * One editable item and its durable outcome.
- */
-export type ReviewItem = {
- /**
- * Validated arguments for the existing composer/action.
- */
- draft: unknown;
- /**
- * Whether the account holder edited this draft before deciding.
- */
- edited?: boolean;
- /**
- * Failure or uncertainty description.
- */
- error?: string | null;
- /**
- * Stable item identity across stack navigation and edits.
- */
- id: string;
- /**
- * Actual backend response, never a model assertion.
- */
- result?: unknown;
- /**
- * Current outcome.
- */
- status: ReviewItemStatus;
-};
-
-/**
- * Review item state, shared with notification consumers.
- */
-export type ReviewItemStatus = 'pending' | 'submitting' | 'completed' | 'dismissed' | 'unknown';
-
-/**
- * The component and action used to finish a review.
- */
-export type ReviewKind = 'email' | 'calendar' | 'import';
-
/**
* Full UI record, fetched outside the model context.
*/
export type ReviewRecord = {
+ [key: string]: unknown;
+} & {
/**
- * Account whose email/calendar the drafts use; historical records use the session owner.
+ * Account whose email/calendar the drafts use.
*/
- actingUser?: string | null;
+ actingUser: string;
decision?: null | ReviewDecisionContext;
executionId?: null | ExecutionId;
/**
* Review identity.
*/
id: ReviewId;
- /**
- * Drafts and per-item outcomes.
- */
- items: Array<ReviewItem>;
- /**
- * Component kind.
- */
- kind: ReviewKind;
/**
* Durable presentation acknowledgment, separate from user decisions.
*/
diff --git a/packages/sdk/generated/agent-reviews/index.ts b/packages/sdk/generated/agent-reviews/index.ts
new file mode 100644
index 0000000000..b0ad58bf89
--- /dev/null
+++ b/packages/sdk/generated/agent-reviews/index.ts
@@ -0,0 +1,857 @@
+// This file has been generated by Specta. Do not edit this file manually.
+/** An attendee supplied to a calendar tool. */
+export type AttendeeInput = {
+ /** Attendee email address. */
+ email: EmailAddress,
+ /** Whether attendance is optional. */
+ isOptional?: boolean,
+};
+
+/** How an out-of-office event handles conflicting invitations. */
+export type AutoDeclineModeInput =
+/** Leave conflicting invitations alone. */
+"decline_none" |
+/** Decline every conflicting invitation, existing and new. */
+"decline_all" |
+/** Decline only invitations that arrive after the event is created. */
+"decline_new_only";
+
+/** The kind of event a create tool call makes. */
+export type CalendarEventTypeInput =
+/** A regular calendar event. */
+"default" |
+/**
+ * A Google out-of-office status event: primary calendar only, timed, no
+ * attendees, and Google shows the user as away and can auto-decline
+ * conflicting invitations.
+ */
+"out_of_office";
+
+/** Create a calendar event. */
+export type CreateCalendarEvent = CreateCalendarEvent_Serialize | CreateCalendarEvent_Deserialize;
+
+/** Create a calendar event. */
+export type CreateCalendarEvent_Deserialize = {
+ /** Display title. */
+ title: string,
+ /** Timed or all-day span. */
+ time: EventTimeInput,
+ /** Optional event body. */
+ description?: string | null,
+ /** Optional location label. */
+ location?: string | null,
+ /** Attendees to invite. */
+ attendees?: AttendeeInput[],
+ /** Recurrence properties. */
+ recurrenceLines?: string[],
+ /** Calendar to create the event on. */
+ calendarId?: string | null,
+ /** Reminder configuration. */
+ reminders?: EventRemindersInput | null,
+ /** Whether to attach a Macro meeting link. */
+ addMacroCall?: boolean,
+ /** Kind of event to create. */
+ eventType?: CalendarEventTypeInput,
+ /** Out-of-office decline behavior. */
+ outOfOffice?: OutOfOfficeInput | null,
+ /** What guests may do with the event. */
+ guestPolicy?: GuestPolicy | null,
+} & {
+ /** Whether to attach the calendar provider's meeting conference. */
+ addConference?: boolean,
+} | {
+ /** Whether to attach the calendar provider's meeting conference. */
+ addGoogleMeet?: boolean,
+};
+
+/** Create a calendar event. */
+export type CreateCalendarEvent_Serialize = {
+ /** Display title. */
+ title: string,
+ /** Timed or all-day span. */
+ time: EventTimeInput,
+ /** Optional event body. */
+ description: string | null,
+ /** Optional location label. */
+ location: string | null,
+ /** Attendees to invite. */
+ attendees: AttendeeInput[],
+ /** Recurrence properties. */
+ recurrenceLines: string[],
+ /** Calendar to create the event on. */
+ calendarId: string | null,
+ /** Reminder configuration. */
+ reminders: EventRemindersInput | null,
+ /** Whether to attach a Macro meeting link. */
+ addMacroCall: boolean,
+ /** Whether to attach the calendar provider's meeting conference. */
+ addConference: boolean,
+ /** Kind of event to create. */
+ eventType: CalendarEventTypeInput,
+ /** Out-of-office decline behavior. */
+ outOfOffice: OutOfOfficeInput | null,
+ /** What guests may do with the event. */
+ guestPolicy: GuestPolicy | null,
+};
+
+/**
+ * Review creation. Decoding it validates every draft; creating a review only
+ * presents the drafts, and the account holder acts separately.
+ */
+export type CreateReview = CreateReview_Serialize | CreateReview_Deserialize;
+
+/**
+ * Review creation. Decoding it validates every draft; creating a review only
+ * presents the drafts, and the account holder acts separately.
+ */
+export type CreateReview_Deserialize = {
+ /** Optional code execution that prepared these drafts. */
+ executionId?: ExecutionId | null,
+ /** Stack label. */
+ title: ReviewTitle,
+} & ReviewDrafts_Deserialize;
+
+/**
+ * Review creation. Decoding it validates every draft; creating a review only
+ * presents the drafts, and the account holder acts separately.
+ */
+export type CreateReview_Serialize = {
+ /** Optional code execution that prepared these drafts. */
+ executionId: ExecutionId | null,
+ /** Stack label. */
+ title: ReviewTitle,
+} & ReviewDrafts_Serialize;
+
+/** Surface of a review decision. */
+export type DecisionVia =
+/** Review card. */
+"card" |
+/** Owner request in chat. */
+"chat" |
+/** Inbox action. */
+"inbox";
+
+/** One to [`MAX_DRAFTS`] drafts of one kind. */
+export type DraftList<Draft> = Draft[];
+
+/** An address that passes [`is_valid_email`]; decoding rejects any other string. */
+export type EmailAddress = string;
+
+/** A Macro document attached to an outgoing email as a file. */
+export type EmailAttachment = {
+ /**
+ * The id of the Macro document to attach. It must be a stored file -
+ * an uploaded PDF, image, spreadsheet, Word document, or other upload -
+ * that the user can view. A Macro-native document (one written in the
+ * editor) has no file to attach; link to it in the body instead.
+ */
+ documentId: string,
+};
+
+/** A recipient for an email. */
+export type EmailRecipient = {
+ /** The recipient's email address. */
+ email: EmailAddress,
+ /** The recipient's display name (optional). */
+ name?: string | null,
+};
+
+/** One reminder override supplied to a calendar tool. */
+export type EventReminderOverrideInput = {
+ /** Provider reminder method. `popup` creates a Macro notification. */
+ method: string,
+ /** Minutes before the event start. */
+ minutes: number,
+};
+
+/** Reminder configuration supplied when creating a calendar event. */
+export type EventRemindersInput = {
+ /** Whether the selected calendar's default reminders should apply. */
+ useDefault: boolean,
+ /** Overrides used when calendar defaults are disabled. */
+ overrides?: EventReminderOverrideInput[],
+};
+
+/** The mutually exclusive time shape supplied to calendar tools. */
+export type EventTimeInput =
+/** A clock-time event with absolute instants. */
+{ kind: "timed";
+/** Inclusive start instant, RFC 3339 UTC (e.g. 2026-08-20T17:00:00Z). */
+startsAt: string;
+/** Exclusive end instant, RFC 3339 UTC. Must be after the start. */
+endsAt: string;
+/**
+ * IANA time zone the event was scheduled in (e.g.
+ * America/New_York). Recurring events expand in this zone.
+ */
+timeZone?: string | null } |
+/** An all-day event spanning whole local dates. */
+{ kind: "allDay";
+/** Inclusive local start date (YYYY-MM-DD). */
+startDate: string;
+/**
+ * Exclusive local end date (YYYY-MM-DD); the day after the last
+ * covered day, so a one-day event ends the next date.
+ */
+endDate: string };
+
+/** Caller-selected UUID persisted in tool input before execution begins. */
+export type ExecutionId = string;
+
+/**
+ * The switches an organizer sets on an event to bound what its guests may
+ * do. Google omits a switch from the payload while it holds its default.
+ */
+export type GuestPolicy = {
+ /** Whether guests may change the event, including its guest list. */
+ canModify: boolean,
+ /** Whether guests may invite others. */
+ canInviteOthers: boolean,
+ /** Whether guests may see the guest list. */
+ canSeeOtherGuests: boolean,
+};
+
+/**
+ * The one draft an import review carries: which source's staged plan it
+ * presents, the plan rows the user took out of it, and the rows whose
+ * sharing they changed: `shared` to share with their team, `personal` to
+ * keep to themselves.
+ */
+export type ImportDraft = {
+ /** The staged plan's source; fixed once the review is presented. */
+ source: ImportReviewSource,
+ /** Plan rows left out of the import. */
+ excluded?: string[],
+ /** Plan rows shared with the team although the plan keeps them private. */
+ shared?: string[],
+ /** Plan rows kept private although the plan shares them. */
+ personal?: string[],
+};
+
+/**
+ * What an imported item is in its source system. Each source has its own
+ * kinds; a Notion database and a Notion page, or a Linear project and a
+ * Linear issue, are tracked and deduplicated separately.
+ */
+export type ImportKind =
+/** A Linear issue. */
+"issue" |
+/** A Linear project. */
+"project" |
+/** A Linear document. */
+"document" |
+/** A Notion page. */
+"page" |
+/** A Notion database. */
+"database" |
+/** One data source (table) of a Notion database. */
+"data_source" |
+/** One row of a Notion data source. */
+"row" |
+/** A Jira issue. */
+"jira_issue" |
+/** A Jira project. */
+"jira_project" |
+/** A Jira epic grouping. */
+"jira_epic" |
+/** A Slack channel. */
+"channel";
+
+/** Which source's staged plan an import review presents. */
+export type ImportReviewSource =
+/** A Notion workspace plan, staged by ImportFromNotion. */
+"notion" |
+/** A Linear plan, staged by ImportFromLinear. */
+"linear" |
+/** A Jira plan, staged by ImportFromJira. */
+"jira";
+
+/** Review item state, shared with notification consumers. */
+export type ItemStatus =
+/** Still awaiting a decision. */
+"pending" |
+/** Claimed for execution. */
+"submitting" |
+/** Confirmed complete. */
+"completed" |
+/** Dismissed by the owner. */
+"dismissed" |
+/** Outcome requires reconciliation. */
+"unknown";
+
+/** Where a Notion workspace import stands. */
+export type NotionImportReport = NotionImportReport_Serialize | NotionImportReport_Deserialize;
+
+/** Where a Notion workspace import stands. */
+export type NotionImportReport_Deserialize = {
+ /** Provider items skipped because they were unreadable, or optional features unavailable. */
+ warnings?: string[],
+ /** Tracker issues in the plan. */
+ issues?: number,
+ /** Tracker groups written as Macro projects. */
+ projects?: number,
+ /**
+ * The run's state: `running` while planning, `ready` once a plan is
+ * staged, `importing` while writing, `completed`, `failed`, or
+ * `dismissed` when cancelled. Absent before the first run.
+ */
+ status?: RunStatus | null,
+ /** Why the run failed, when it did. */
+ error?: string | null,
+ /** What planning has found in Notion so far, while it is `running`. */
+ scanned?: ScanCounts | null,
+ /** Pages in the plan. */
+ pages: number,
+ /** Data sources (database tables) in the plan. */
+ dataSources: number,
+ /**
+ * Plan objects the decision model has not answered for yet, while
+ * planning is still `running`.
+ */
+ deciding?: number,
+ /**
+ * Whether the user is on a team. Without one, everything the import
+ * writes stays visible only to them.
+ */
+ onTeam?: boolean,
+ /** Objects to copy as they are. */
+ copy: number,
+ /** Data sources whose rows become tasks. */
+ tasks: number,
+ /** Objects left in Notion. */
+ skip: number,
+ /** Objects that need handling by hand. */
+ hand: number,
+ /** Pages written as documents. */
+ documents: number,
+ /** Data sources written as databases. */
+ databases: number,
+ /** Rows those databases hold, every one counted while planning. */
+ databaseRows: number,
+ /** Tasks the task lists become, one per row. */
+ taskRows: number,
+ /** Plan objects already imported. */
+ imported: number,
+ /** Plan objects still waiting to be written. */
+ waiting: number,
+ /** Plan objects being written now. */
+ writing: number,
+ /**
+ * Plan objects waiting for a teammate who is writing the same object
+ * for the team; they link to the teammate's copy once it is written.
+ */
+ waitingOnTeammates?: number,
+ /** Written plan objects shared with the user's team. */
+ sharedWithTeam?: number,
+ /**
+ * Plan objects a teammate already imported and shared with the team;
+ * they link to that copy and are not counted as copies.
+ */
+ alreadyInMacro?: number,
+ /** Who imported the objects already in Macro, most first. */
+ alreadyImportedBy?: NotionImporter[],
+ /** The review the plan is tied to, once presented. */
+ reviewId?: string | null,
+ /** Objects that need handling by hand, with reasons. */
+ handItems?: NotionReportItem_Deserialize[],
+ /** Objects that failed to import, with the failure. */
+ failures?: NotionReportItem_Deserialize[],
+};
+
+/** Where a Notion workspace import stands. */
+export type NotionImportReport_Serialize = {
+ /** Provider items skipped because they were unreadable, or optional features unavailable. */
+ warnings?: string[],
+ /** Tracker issues in the plan. */
+ issues: number,
+ /** Tracker groups written as Macro projects. */
+ projects: number,
+ /**
+ * The run's state: `running` while planning, `ready` once a plan is
+ * staged, `importing` while writing, `completed`, `failed`, or
+ * `dismissed` when cancelled. Absent before the first run.
+ */
+ status?: RunStatus | null,
+ /** Why the run failed, when it did. */
+ error?: string | null,
+ /** What planning has found in Notion so far, while it is `running`. */
+ scanned?: ScanCounts | null,
+ /** Pages in the plan. */
+ pages: number,
+ /** Data sources (database tables) in the plan. */
+ dataSources: number,
+ /**
+ * Plan objects the decision model has not answered for yet, while
+ * planning is still `running`.
+ */
+ deciding: number,
+ /**
+ * Whether the user is on a team. Without one, everything the import
+ * writes stays visible only to them.
+ */
+ onTeam: boolean,
+ /** Objects to copy as they are. */
+ copy: number,
+ /** Data sources whose rows become tasks. */
+ tasks: number,
+ /** Objects left in Notion. */
+ skip: number,
+ /** Objects that need handling by hand. */
+ hand: number,
+ /** Pages written as documents. */
+ documents: number,
+ /** Data sources written as databases. */
+ databases: number,
+ /** Rows those databases hold, every one counted while planning. */
+ databaseRows: number,
+ /** Tasks the task lists become, one per row. */
+ taskRows: number,
+ /** Plan objects already imported. */
+ imported: number,
+ /** Plan objects still waiting to be written. */
+ waiting: number,
+ /** Plan objects being written now. */
+ writing: number,
+ /**
+ * Plan objects waiting for a teammate who is writing the same object
+ * for the team; they link to the teammate's copy once it is written.
+ */
+ waitingOnTeammates: number,
+ /** Written plan objects shared with the user's team. */
+ sharedWithTeam: number,
+ /**
+ * Plan objects a teammate already imported and shared with the team;
+ * they link to that copy and are not counted as copies.
+ */
+ alreadyInMacro: number,
+ /** Who imported the objects already in Macro, most first. */
+ alreadyImportedBy: NotionImporter[],
+ /** The review the plan is tied to, once presented. */
+ reviewId?: string | null,
+ /** Objects that need handling by hand, with reasons. */
+ handItems: NotionReportItem_Serialize[],
+ /** Objects that failed to import, with the failure. */
+ failures: NotionReportItem_Serialize[],
+};
+
+/** A teammate who already imported some of a plan's objects. */
+export type NotionImporter = {
+ /** The teammate, by email. */
+ by: string,
+ /** How many of the plan's objects they imported. */
+ count: number,
+};
+
+/** One object a workspace import report calls out. */
+export type NotionReportItem = NotionReportItem_Serialize | NotionReportItem_Deserialize;
+
+/** One object a workspace import report calls out. */
+export type NotionReportItem_Deserialize = {
+ /** The ledger row. */
+ importId: string,
+ /** The object's title. */
+ title: string,
+ /** What the object is. */
+ kind: ImportKind,
+ /** Its Notion URL. */
+ url?: string | null,
+ /** Why it is called out: the decision model's reason, or the failure. */
+ reason?: string | null,
+};
+
+/** One object a workspace import report calls out. */
+export type NotionReportItem_Serialize = {
+ /** The ledger row. */
+ importId: string,
+ /** The object's title. */
+ title: string,
+ /** What the object is. */
+ kind: ImportKind,
+ /** Its Notion URL. */
+ url?: string | null,
+ /** Why it is called out: the decision model's reason, or the failure. */
+ reason?: string | null,
+};
+
+/** Out-of-office decline behavior supplied to the calendar tools. */
+export type OutOfOfficeInput = {
+ /**
+ * How conflicting invitations are handled. Defaults to declining nothing,
+ * so the event only blocks time and shows the away status.
+ */
+ autoDeclineMode?: AutoDeclineModeInput | null,
+ /** Message returned to organizers whose invitations are auto-declined. */
+ declineMessage?: string | null,
+};
+
+/** One atomic user decision against the displayed revision. */
+export type ReviewDecision = ReviewDecision_Serialize | ReviewDecision_Deserialize;
+
+/** Facts about the most recent account-holder decision. */
+export type ReviewDecisionContext = {
+ /** Authenticated account holder. */
+ by: string,
+ /** Entry surface. */
+ via: DecisionVia,
+ /** Revision claimed by this batch, used in notification deduplication. */
+ revision: number,
+ /** Items selected by this decision. */
+ items: string[],
+};
+
+/** One atomic user decision against the displayed revision. */
+export type ReviewDecision_Deserialize =
+/** Save one edited draft. */
+({ action: "edit";
+/** Revision displayed by the caller. */
+revision: number;
+/** Pending item to update. */
+item: string;
+/** Replacement action arguments, keyed by the review's kind. */
+draft: ReviewDraft_Deserialize }) & { items?: never } |
+/** Send/create selected items, or all pending items when empty. */
+({ action: "submit";
+/** Revision displayed by the caller. */
+revision: number;
+/** Pending items, or an empty list to select all pending items. */
+items: string[] }) & { draft?: never; item?: never } |
+/** Dismiss selected pending items, or all pending items when empty. */
+({ action: "dismiss";
+/** Revision displayed by the caller. */
+revision: number;
+/** Pending items, or an empty list to select all pending items. */
+items: string[] }) & { draft?: never; item?: never };
+
+/** One atomic user decision against the displayed revision. */
+export type ReviewDecision_Serialize =
+/** Save one edited draft. */
+({ action: "edit";
+/** Revision displayed by the caller. */
+revision: number;
+/** Pending item to update. */
+item: string;
+/** Replacement action arguments, keyed by the review's kind. */
+draft: ReviewDraft_Serialize }) & { items?: never } |
+/** Send/create selected items, or all pending items when empty. */
+({ action: "submit";
+/** Revision displayed by the caller. */
+revision: number;
+/** Pending items, or an empty list to select all pending items. */
+items: string[] }) & { draft?: never; item?: never } |
+/** Dismiss selected pending items, or all pending items when empty. */
+({ action: "dismiss";
+/** Revision displayed by the caller. */
+revision: number;
+/** Pending items, or an empty list to select all pending items. */
+items: string[] }) & { draft?: never; item?: never };
+
+/** One replacement draft, keyed by the kind of the review it edits. */
+export type ReviewDraft = ReviewDraft_Serialize | ReviewDraft_Deserialize;
+
+/** One replacement draft, keyed by the kind of the review it edits. */
+export type ReviewDraft_Deserialize =
+/** An edited email. */
+{ kind: "email"; draft: SendEmail } |
+/** An edited calendar event. */
+{ kind: "calendar"; draft: CreateCalendarEvent_Deserialize } |
+/** An edited import plan selection. */
+{ kind: "import"; draft: ImportDraft };
+
+/** One replacement draft, keyed by the kind of the review it edits. */
+export type ReviewDraft_Serialize =
+/** An edited email. */
+{ kind: "email"; draft: SendEmail } |
+/** An edited calendar event. */
+{ kind: "calendar"; draft: CreateCalendarEvent_Serialize } |
+/** An edited import plan selection. */
+{ kind: "import"; draft: ImportDraft };
+
+/** The drafts a new review presents, keyed by the review's kind. */
+export type ReviewDrafts = ReviewDrafts_Serialize | ReviewDrafts_Deserialize;
+
+/** The drafts a new review presents, keyed by the review's kind. */
+export type ReviewDrafts_Deserialize =
+/** Emails, each sent with the SendEmail action (Markdown body). */
+{ kind: "email"; drafts: DraftList<SendEmail> } |
+/** Calendar events, each created with the CreateCalendarEvent action. */
+{ kind: "calendar"; drafts: DraftList<CreateCalendarEvent_Deserialize> } |
+/** Exactly one staged import plan, approved as one item. */
+{ kind: "import"; drafts: [ImportDraft] };
+
+/** The drafts a new review presents, keyed by the review's kind. */
+export type ReviewDrafts_Serialize =
+/** Emails, each sent with the SendEmail action (Markdown body). */
+{ kind: "email"; drafts: DraftList<SendEmail> } |
+/** Calendar events, each created with the CreateCalendarEvent action. */
+{ kind: "calendar"; drafts: DraftList<CreateCalendarEvent_Serialize> } |
+/** Exactly one staged import plan, approved as one item. */
+{ kind: "import"; drafts: [ImportDraft] };
+
+/** Persisted review identity. */
+export type ReviewId = string;
+
+/** One editable item and its durable outcome. */
+export type ReviewItem<Draft, Outcome> = {
+ /** Arguments for the existing composer and action. */
+ draft: Draft,
+ /** The action's confirmed response, never a model assertion. */
+ result: Outcome | null,
+} & ReviewItemState;
+
+/** Item facts every kind shares. */
+export type ReviewItemState = {
+ /** Stable item identity across stack navigation and edits. */
+ id: string,
+ /** Whether the account holder edited this draft before deciding. */
+ edited?: boolean,
+ /** Current outcome. */
+ status: ItemStatus,
+ /** Failure or uncertainty description. */
+ error: string | null,
+};
+
+/** Saved items keyed by the review's kind. */
+export type ReviewItems = ReviewItems_Serialize | ReviewItems_Deserialize;
+
+/** Saved items keyed by the review's kind. */
+export type ReviewItems_Deserialize =
+/** Email drafts and their send responses. */
+{ kind: "email"; items: (ReviewItem<SendEmail, SendEmailResponse>)[] } |
+/** Calendar drafts and their created events. */
+{ kind: "calendar"; items: (ReviewItem<CreateCalendarEvent_Deserialize, ToolCalendarEvent>)[] } |
+/** The import plan selection and the started write's report. */
+{ kind: "import"; items: [(ReviewItem<ImportDraft, NotionImportReport_Deserialize>)] };
+
+/** Saved items keyed by the review's kind. */
+export type ReviewItems_Serialize =
+/** Email drafts and their send responses. */
+{ kind: "email"; items: (ReviewItem<SendEmail, SendEmailResponse>)[] } |
+/** Calendar drafts and their created events. */
+{ kind: "calendar"; items: (ReviewItem<CreateCalendarEvent_Serialize, ToolCalendarEvent>)[] } |
+/** The import plan selection and the started write's report. */
+{ kind: "import"; items: [(ReviewItem<ImportDraft, NotionImportReport_Serialize>)] };
+
+/** Full UI record, fetched outside the model context. */
+export type ReviewRecord = ReviewRecord_Serialize | ReviewRecord_Deserialize;
+
+/** Full UI record, fetched outside the model context. */
+export type ReviewRecord_Deserialize = {
+ /** Review identity. */
+ id: ReviewId,
+ /** Owning session. */
+ sessionId: string,
+ /** Account whose email/calendar the drafts use. */
+ actingUser: string,
+ /** Originating code execution, absent for directly presented reviews. */
+ executionId: ExecutionId | null,
+ /** Durable presentation acknowledgment, separate from user decisions. */
+ presentedAt?: number | null,
+ /** Stack label. */
+ title: ReviewTitle,
+ /** Compare-and-swap revision for edits and submissions. */
+ revision: number,
+ /** Milliseconds since epoch of the last state change. */
+ updatedAt: number,
+ /** Current batch's authenticated decision, preserved for interrupted work. */
+ decision?: ReviewDecisionContext | null,
+} & ReviewItems_Deserialize;
+
+/** Full UI record, fetched outside the model context. */
+export type ReviewRecord_Serialize = {
+ /** Review identity. */
+ id: ReviewId,
+ /** Owning session. */
+ sessionId: string,
+ /** Account whose email/calendar the drafts use. */
+ actingUser: string,
+ /** Originating code execution, absent for directly presented reviews. */
+ executionId: ExecutionId | null,
+ /** Durable presentation acknowledgment, separate from user decisions. */
+ presentedAt: number | null,
+ /** Stack label. */
+ title: ReviewTitle,
+ /** Compare-and-swap revision for edits and submissions. */
+ revision: number,
+ /** Milliseconds since epoch of the last state change. */
+ updatedAt: number,
+ /** Current batch's authenticated decision, preserved for interrupted work. */
+ decision: ReviewDecisionContext | null,
+} & ReviewItems_Serialize;
+
+/** A review stack label: not blank, at most 256 characters. */
+export type ReviewTitle = string;
+
+/** Lifecycle of a discovery run (one per user × source). */
+export type RunStatus =
+/**
+ * Slack discovery is staging candidates, or a Notion workspace import is
+ * being planned.
+ */
+"running" |
+/** Discovery or planning finished; staged rows (if any) are ready. */
+"ready" |
+/** An approved Notion workspace import plan is being written. */
+"importing" |
+/**
+ * A Notion workspace import finished writing; `error` notes objects
+ * that could not be imported.
+ */
+"completed" |
+/** Discovery, planning or writing failed; `error` has details. Retryable. */
+"failed" |
+/**
+ * A Notion workspace import was cancelled. Older rows may hold it from
+ * the removed onboarding import, where it meant a dismissed section.
+ */
+"dismissed";
+
+/** What a planning run has found in the source so far. */
+export type ScanCounts = {
+ /** Pages found. */
+ pages: number,
+ /** Data sources (database tables) found. */
+ dataSources: number,
+};
+
+/** Compose and send an email. Creates a draft and immediately queues it for delivery. */
+export type SendEmail = {
+ /** The subject line of the email. */
+ subject: string,
+ /**
+ * The address of the inbox to send from, when the user has more than one
+ * connected and this email belongs to a particular one. Use the exact
+ * `emailAddress` of a connected inbox — `ListInboxes` lists them, and
+ * `GetThread` reports the `inbox` a thread belongs to. Omit it unless
+ * you know which inbox is right: a reply then goes out from the inbox
+ * that received the message it answers, and a new email from the user's
+ * primary inbox. The user can change it in the composer either way.
+ */
+ from?: string | null,
+ /**
+ * The body of the email, written as Markdown. A host with a composer
+ * (chat) replaces this with the base64url-encoded HTML the composer
+ * exported before the tool runs; a host without one (an agent session)
+ * leaves the Markdown, and this tool renders it the same way.
+ */
+ body: string,
+ /** The primary recipients (To field). */
+ to: EmailRecipient[],
+ /** Carbon copy recipients (optional). */
+ cc?: EmailRecipient[],
+ /** Blind carbon copy recipients (optional). */
+ bcc?: EmailRecipient[],
+ /**
+ * The ID of a message to reply to (optional). When set, the email is
+ * sent as a reply within the same thread.
+ */
+ replyingToId?: string | null,
+ /**
+ * Per-message signature override, set by the composer's signature preview —
+ * not normally by you. Omit to use the inbox's default policy (always on a
+ * new email; on replies/forwards only when the user enabled it). `false`
+ * excludes the signature for this one email.
+ */
+ includeSignature?: boolean | null,
+ /**
+ * Macro documents to attach as files (optional). Each must be an
+ * uploaded file the user can view; together they may total 18 MB.
+ */
+ attachments?: EmailAttachment[],
+};
+
+/** Response from the SendEmail tool. */
+export type SendEmailResponse = ({ sent: {
+ /** The database ID of the sent message. */
+ message_id: string,
+ /** The thread ID the message belongs to. */
+ thread_id: string,
+} }) & { convertedToDraft?: never } | ({ convertedToDraft: {
+ draft_id: string,
+} }) & { sent?: never } | "userEdited";
+
+/** A calendar event as returned by the create and update tools. */
+export type ToolCalendarEvent = {
+ /**
+ * Macro calendar event id, used by UpdateCalendarEvent and
+ * DeleteCalendarEvent.
+ */
+ eventId: string,
+ /** Display title. */
+ title: string,
+ /** Event start: RFC 3339 UTC instant, or YYYY-MM-DD for all-day events. */
+ start: string,
+ /**
+ * Exclusive event end: RFC 3339 UTC instant, or YYYY-MM-DD for all-day
+ * events.
+ */
+ end: string,
+ /** Whether the event covers whole days. */
+ isAllDay: boolean,
+ /** IANA time zone the event was scheduled in, when known. */
+ timeZone: string | null,
+ /** Location label, when set. */
+ location: string | null,
+ /** Event body, truncated for brevity. */
+ description: string | null,
+ /** Event status: confirmed, tentative, or cancelled. */
+ status: string,
+ /** Whether the event recurs. */
+ isRecurring: boolean,
+ /** Raw RFC 5545 recurrence properties, when the event recurs. */
+ recurrenceLines: string[],
+ /** Attendees, capped at 20; `attendee_count` has the full number. */
+ attendees: ToolEventAttendee[],
+ /** Total number of attendees. */
+ attendeeCount: number,
+ /** Organizer email address, when known. */
+ organizerEmail: string | null,
+ /** Conference join URL, when a conference is attached. */
+ conferenceUrl: string | null,
+ /**
+ * Join URL of the Macro call created with the event, when
+ * CreateCalendarEvent was asked for one.
+ */
+ macroCallUrl: string | null,
+ /** Whether the user's calendar prohibits modifying this event. */
+ isReadOnly: boolean,
+ /** Calendar the event belongs to, when known. */
+ calendarId: string | null,
+ /** Display name of that calendar, when known. */
+ calendarName: string | null,
+ /**
+ * Connected inbox address syncing the calendar, when known. It stays the
+ * user's own address on a colleague's calendar, so it never says whose
+ * calendar it is.
+ */
+ inbox: string | null,
+ /**
+ * Whether the user organizes this event or is a guest on it, through
+ * that inbox; absent when they are neither, can only write that
+ * calendar, or a read-only calendar names them organizer.
+ */
+ myRole: ToolEventRole | null,
+};
+
+/** An attendee of a calendar event, as returned by calendar tools. */
+export type ToolEventAttendee = {
+ /** Attendee email address. */
+ email: string,
+ /** RSVP state: needs_action, accepted, declined, or tentative. */
+ responseStatus: string,
+ /** Whether this attendee organized the event. */
+ isOrganizer: boolean,
+ /** Whether attendance is optional. */
+ isOptional: boolean,
+};
+
+/** What the user is on one copy of an event, through the inbox holding it. */
+export type ToolEventRole =
+/**
+ * The inbox organizes the event, or the event has no guests and is the
+ * user's own. Being able to write someone else's calendar is not this,
+ * nor is a read-only calendar naming them organizer; `viewerCan` says
+ * what the user may do there.
+ */
+"organizer" |
+/** The inbox is invited to the event. */
+"guest";
diff --git a/packages/sdk/specs/agent-harness.json b/packages/sdk/specs/agent-harness.json
index 949ddf6100..3ef8436dce 100644
--- a/packages/sdk/specs/agent-harness.json
+++ b/packages/sdk/specs/agent-harness.json
@@ -4588,36 +4588,34 @@
}
},
"CreateReview": {
- "type": "object",
- "description": "Review creation. Drafts are validated by the action's owning adapter.",
- "required": ["kind", "title", "drafts"],
- "properties": {
- "drafts": {
- "type": "array",
- "items": {},
- "description": "One to one hundred independent drafts. Email: {subject, body: Markdown,\nto: [{email, name?}], cc?: [{email, name?}], bcc?: [{email, name?}],\nreplyingToId?, attachments?: [{documentId}]}. Calendar: {title,\ntime: {kind: \"timed\", startsAt: ISO datetime, endsAt: ISO datetime,\ntimeZone?: IANA zone} or {kind: \"allDay\", startDate: ISO date,\nendDate: exclusive ISO date}, description?, location?, attendees?:\n[{email, isOptional?}]}. Import: exactly one draft {source: \"notion\" | \"linear\" | \"jira\"},\npresenting the plan ImportFromNotion, ImportFromLinear or ImportFromJira staged.\nCreating any review only presents these drafts; the user acts separately."
+ "allOf": [
+ {
+ "type": "object",
+ "description": "The review's kind (email, calendar, import) and its drafts: 1–100\nSendEmail or CreateCalendarEvent arguments, or exactly one import\nplan selection."
},
- "executionId": {
- "oneOf": [
- {
- "type": "null"
+ {
+ "type": "object",
+ "required": ["title"],
+ "properties": {
+ "executionId": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/ExecutionId",
+ "description": "Optional code execution that prepared these drafts."
+ }
+ ]
},
- {
- "$ref": "#/components/schemas/ExecutionId",
- "description": "Optional code execution that prepared these drafts."
+ "title": {
+ "type": "string",
+ "description": "Stack label."
}
- ]
- },
- "kind": {
- "$ref": "#/components/schemas/ReviewKind",
- "description": "Existing UI and action to use."
- },
- "title": {
- "type": "string",
- "description": "Stack label."
+ }
}
- },
- "additionalProperties": false
+ ],
+ "description": "Review creation. Decoding it validates every draft; creating a review only\npresents the drafts, and the account holder acts separately."
},
"CreateSessionThread": {
"type": "object",
@@ -5887,7 +5885,8 @@
"enum": ["edit"]
},
"draft": {
- "description": "Replacement action arguments."
+ "type": "object",
+ "description": "Replacement action arguments, keyed by the review's kind."
},
"item": {
"type": "string",
@@ -5985,125 +5984,81 @@
"format": "uuid",
"description": "Persisted review identity."
},
- "ReviewItem": {
- "type": "object",
- "description": "One editable item and its durable outcome.",
- "required": ["id", "draft", "status"],
- "properties": {
- "draft": {
- "description": "Validated arguments for the existing composer/action."
- },
- "edited": {
- "type": "boolean",
- "description": "Whether the account holder edited this draft before deciding."
- },
- "error": {
- "type": ["string", "null"],
- "description": "Failure or uncertainty description."
- },
- "id": {
- "type": "string",
- "format": "uuid",
- "description": "Stable item identity across stack navigation and edits."
- },
- "result": {
- "description": "Actual backend response, never a model assertion."
- },
- "status": {
- "$ref": "#/components/schemas/ReviewItemStatus",
- "description": "Current outcome."
- }
- }
- },
- "ReviewItemStatus": {
- "type": "string",
- "description": "Review item state, shared with notification consumers.",
- "enum": ["pending", "submitting", "completed", "dismissed", "unknown"]
- },
- "ReviewKind": {
- "type": "string",
- "description": "The component and action used to finish a review.",
- "enum": ["email", "calendar", "import"]
- },
"ReviewRecord": {
- "type": "object",
- "description": "Full UI record, fetched outside the model context.",
- "required": [
- "id",
- "sessionId",
- "kind",
- "title",
- "revision",
- "updatedAt",
- "items"
- ],
- "properties": {
- "actingUser": {
- "type": ["string", "null"],
- "description": "Account whose email/calendar the drafts use; historical records use the session owner."
+ "allOf": [
+ {
+ "type": "object",
+ "description": "Component kind, drafts and per-item outcomes."
},
- "decision": {
- "oneOf": [
- {
- "type": "null"
+ {
+ "type": "object",
+ "required": [
+ "id",
+ "sessionId",
+ "actingUser",
+ "title",
+ "revision",
+ "updatedAt"
+ ],
+ "properties": {
+ "actingUser": {
+ "type": "string",
+ "description": "Account whose email/calendar the drafts use."
},
- {
- "$ref": "#/components/schemas/ReviewDecisionContext",
- "description": "Current batch's authenticated decision, preserved for interrupted work."
- }
- ]
- },
- "executionId": {
- "oneOf": [
- {
- "type": "null"
+ "decision": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/ReviewDecisionContext",
+ "description": "Current batch's authenticated decision, preserved for interrupted work."
+ }
+ ]
},
- {
- "$ref": "#/components/schemas/ExecutionId",
- "description": "Originating code execution, absent for directly presented reviews."
+ "executionId": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/ExecutionId",
+ "description": "Originating code execution, absent for directly presented reviews."
+ }
+ ]
+ },
+ "id": {
+ "$ref": "#/components/schemas/ReviewId",
+ "description": "Review identity."
+ },
+ "presentedAt": {
+ "type": ["integer", "null"],
+ "format": "int64",
+ "description": "Durable presentation acknowledgment, separate from user decisions."
+ },
+ "revision": {
+ "type": "integer",
+ "format": "int64",
+ "description": "Compare-and-swap revision for edits and submissions."
+ },
+ "sessionId": {
+ "type": "string",
+ "format": "uuid",
+ "description": "Owning session."
+ },
+ "title": {
+ "type": "string",
+ "description": "Stack label."
+ },
+ "updatedAt": {
+ "type": "integer",
+ "format": "int64",
+ "description": "Milliseconds since epoch of the last state change."
}
- ]
- },
- "id": {
- "$ref": "#/components/schemas/ReviewId",
- "description": "Review identity."
- },
- "items": {
- "type": "array",
- "items": {
- "$ref": "#/components/schemas/ReviewItem"
- },
- "description": "Drafts and per-item outcomes."
- },
- "kind": {
- "$ref": "#/components/schemas/ReviewKind",
- "description": "Component kind."
- },
- "presentedAt": {
- "type": ["integer", "null"],
- "format": "int64",
- "description": "Durable presentation acknowledgment, separate from user decisions."
- },
- "revision": {
- "type": "integer",
- "format": "int64",
- "description": "Compare-and-swap revision for edits and submissions."
- },
- "sessionId": {
- "type": "string",
- "format": "uuid",
- "description": "Owning session."
- },
- "title": {
- "type": "string",
- "description": "Stack label."
- },
- "updatedAt": {
- "type": "integer",
- "format": "int64",
- "description": "Milliseconds since epoch of the last state change."
+ }
}
- }
+ ],
+ "description": "Full UI record, fetched outside the model context."
},
"SandboxSize": {
"type": "string",
diff --git a/packages/sdk/src/entities/agent-sessions/review.ts b/packages/sdk/src/entities/agent-sessions/review.ts
index 1903d76d10..14e5dbff9e 100644
--- a/packages/sdk/src/entities/agent-sessions/review.ts
+++ b/packages/sdk/src/entities/agent-sessions/review.ts
@@ -1,13 +1,27 @@
import type {
- ReviewDecision,
- ReviewRecord,
-} from '../../../generated/agent-harness/types.gen';
+ CreateCalendarEvent_Deserialize,
+ ReviewDecision_Deserialize,
+ ReviewDraft_Deserialize,
+ ReviewDrafts_Deserialize,
+ ReviewRecord_Serialize,
+ ReviewTitle,
+ SendEmail,
+} from '../../../generated/agent-reviews';
import { unwrap } from '../../utils';
import type { MacroClient } from '../../utils/client';
import { MacroEntity } from '../entity';
import type { AgentSession } from './agent-session';
import type { CodeExecution } from './code-execution';
+type ReviewRecord = ReviewRecord_Serialize;
+type ReviewDecision = ReviewDecision_Deserialize;
+
+// The HTTP schemas are opaque: the server serializes the Rust review types,
+// whose TypeScript contract is generated from the same Rust types.
+function typedRecord(record: unknown): ReviewRecord {
+ return record as ReviewRecord;
+}
+
/** A persistent review remains actionable after the code execution ends. */
export class SessionReview extends MacroEntity<ReviewRecord> {
private constructor(
@@ -57,7 +71,7 @@ export class SessionReview extends MacroEntity<ReviewRecord> {
body: { ...input, executionId: execution?.id ?? null },
}),
);
- return SessionReview.fromRecord(client, session, record);
+ return SessionReview.fromRecord(client, session, typedRecord(record));
}
static async list(
client: MacroClient,
@@ -72,14 +86,20 @@ export class SessionReview extends MacroEntity<ReviewRecord> {
}),
);
return records.map((record) =>
- SessionReview.fromRecord(client, execution.session(), record),
+ SessionReview.fromRecord(
+ client,
+ execution.session(),
+ typedRecord(record),
+ ),
);
}
protected async fetch(): Promise<ReviewRecord> {
- return unwrap(
- await this.client.agentHarness.getSessionReview({
- path: { session_id: this.parent.id, review_id: this.id },
- }),
+ return typedRecord(
+ unwrap(
+ await this.client.agentHarness.getSessionReview({
+ path: { session_id: this.parent.id, review_id: this.id },
+ }),
+ ),
);
}
readonly title = this.field('title');
@@ -92,7 +112,9 @@ export class SessionReview extends MacroEntity<ReviewRecord> {
return { kind: await this.kind(), id: this.id };
}
async items(): Promise<ReviewItem[]> {
- return (await this.detail.get()).items.map(
+ const record = await this.detail.get();
+ const items: ReviewRecord['items'] = record.items;
+ return items.map(
(item) =>
new ReviewItem(item, {
edit: (draft) =>
@@ -138,7 +160,7 @@ export class ReviewItem {
constructor(
private readonly snapshot: ReviewRecord['items'][number],
private readonly actions: {
- edit: (draft: unknown) => Promise<void>;
+ edit: (draft: ReviewDraft) => Promise<void>;
submit: () => Promise<void>;
dismiss: () => Promise<void>;
},
@@ -149,13 +171,15 @@ export class ReviewItem {
get status(): ReviewRecord['items'][number]['status'] {
return this.snapshot.status;
}
- get draft(): unknown {
+ get draft(): ReviewRecord['items'][number]['draft'] {
return this.snapshot.draft;
}
- get result(): unknown {
+ /** The action's confirmed response, `null` until it completes. */
+ get result(): ReviewRecord['items'][number]['result'] {
return this.snapshot.result;
}
- async edit(draft: unknown): Promise<void> {
+ /** Replace this pending draft; `kind` must match the review's. */
+ async edit(draft: ReviewDraft): Promise<void> {
await this.actions.edit(draft);
}
async submit(): Promise<void> {
@@ -166,38 +190,13 @@ export class ReviewItem {
}
}
+/** A replacement draft keyed by its review's kind. */
+export type ReviewDraft = ReviewDraft_Deserialize;
/** Markdown is rendered by the ordinary email action; the UI can edit each draft. */
-export type ReviewEmailDraft = {
- subject: string;
- body: string;
- to: Array<{ email: string; name?: string | null }>;
- cc?: Array<{ email: string; name?: string | null }>;
- bcc?: Array<{ email: string; name?: string | null }>;
- replyingToId?: string | null;
- includeSignature?: boolean | null;
- attachments?: Array<{ documentId: string }>;
-};
-export type CreateReviewOptions =
- | { kind: 'email'; title: string; drafts: ReviewEmailDraft[] }
- | { kind: 'calendar'; title: string; drafts: ReviewCalendarDraft[] };
+export type ReviewEmailDraft = SendEmail;
/** Calendar drafts use the existing calendar composer and creation action. */
-export type ReviewCalendarDraft = {
- title: string;
- time: import('../../../generated/calendar/types.gen').EventTime;
- description?: string | null;
- location?: string | null;
- attendees?: Array<{ email: string; isOptional?: boolean }>;
- calendarId?: string | null;
- recurrenceLines?: string[];
- addMacroCall?: boolean;
- addGoogleMeet?: boolean;
- reminders?: {
- useDefault: boolean;
- overrides?: Array<{ method: string; minutes: number }>;
- } | null;
- eventType?: 'default' | 'out_of_office';
- outOfOffice?: {
- autoDeclineMode?: 'decline_none' | 'decline_all' | 'decline_new_only';
- declineMessage?: string | null;
- } | null;
-};
+export type ReviewCalendarDraft = CreateCalendarEvent_Deserialize;
+/** A review's kind and its drafts; the execution is attached by the handle. */
+export type CreateReviewOptions = {
+ title: ReviewTitle;
+} & ReviewDrafts_Deserialize;
diff --git a/packages/sdk/src/macro.ts b/packages/sdk/src/macro.ts
index 65c1539919..0c1c570050 100644
--- a/packages/sdk/src/macro.ts
+++ b/packages/sdk/src/macro.ts
@@ -264,6 +264,7 @@ export {
export type {
CreateReviewOptions,
ReviewCalendarDraft,
+ ReviewDraft,
ReviewEmailDraft,
} from './entities/agent-sessions/review';
export { ReviewItem, SessionReview } from './entities/agent-sessions/review';
diff --git a/packages/sdk/tests/reviews.test.ts b/packages/sdk/tests/reviews.test.ts
index 57d6031712..eb88303320 100644
--- a/packages/sdk/tests/reviews.test.ts
+++ b/packages/sdk/tests/reviews.test.ts
@@ -1,5 +1,5 @@
import { afterEach, describe, expect, test } from 'bun:test';
-import type { ReviewRecord } from '../generated/agent-harness/types.gen';
+import type { ReviewRecord_Serialize } from '../generated/agent-reviews';
import { Macro } from '../src/macro';
const originalFetch = globalThis.fetch;
@@ -7,10 +7,13 @@ afterEach(() => {
globalThis.fetch = originalFetch;
});
const executionId = '0198a4cc-e138-7670-a308-a6b766602788';
-const fixture: ReviewRecord = {
+const fixture: ReviewRecord_Serialize = {
id: '0198a4cc-e138-7670-a308-a6b766602799',
sessionId: '0198a4cc-e138-7670-a308-a6b766602700',
+ actingUser: 'macro|[email protected]',
executionId,
+ presentedAt: null,
+ decision: null,
kind: 'email',
title: 'Draft',
revision: 0,
@@ -108,18 +111,24 @@ describe('persistent review handles', () => {
expect(requests).toHaveLength(0);
const [item] = await review.items();
await item.edit({
- subject: 'Updated subject',
- body: 'Updated draft',
- to: [{ email: '[email protected]' }],
+ kind: 'email',
+ draft: {
+ subject: 'Updated subject',
+ body: 'Updated draft',
+ to: [{ email: '[email protected]' }],
+ },
});
expect(requests[1].body).toEqual({
action: 'edit',
revision: 0,
item: item.id,
draft: {
- subject: 'Updated subject',
- body: 'Updated draft',
- to: [{ email: '[email protected]' }],
+ kind: 'email',
+ draft: {
+ subject: 'Updated subject',
+ body: 'Updated draft',
+ to: [{ email: '[email protected]' }],
+ },
},
});
expect(requests[1].request.url).toContain(
diff --git a/services/agent_harness_service/src/code_mode/reviews.rs b/services/agent_harness_service/src/code_mode/reviews.rs
index 6c626a69bc..04a097b259 100644
--- a/services/agent_harness_service/src/code_mode/reviews.rs
+++ b/services/agent_harness_service/src/code_mode/reviews.rs
@@ -9,63 +9,22 @@ use async_trait::async_trait;
use import::domain::models::{NotionImportReport, NotionWriteChoices, RunStatus};
use import::domain::service::WorkspaceImporter;
use macro_user_id::user_id::MacroUserIdStr;
-use serde::Deserialize;
-use serde_json::Value;
+use serde::{Serialize, de::DeserializeOwned};
use std::sync::Arc;
-#[cfg(test)]
-mod test;
-
-/// The one draft an import review carries: which source's staged plan it
-/// presents, the plan rows the user took out of it, and the rows whose
-/// sharing they changed: `shared` to share with their team, `personal` to
-/// keep to themselves.
-#[derive(Debug, Deserialize)]
-#[serde(rename_all = "camelCase", deny_unknown_fields)]
-struct ImportDraft {
- source: ImportReviewSource,
- #[serde(default)]
- excluded: Vec<macro_uuid::Uuid>,
- #[serde(default)]
- shared: Vec<macro_uuid::Uuid>,
- #[serde(default)]
- personal: Vec<macro_uuid::Uuid>,
-}
-
-#[derive(Debug, Deserialize)]
-#[serde(rename_all = "snake_case")]
-enum ImportReviewSource {
- Notion,
- Linear,
- Jira,
-}
-impl ImportReviewSource {
- fn source(self) -> import::domain::models::ImportSource {
- match self {
- Self::Notion => import::domain::models::ImportSource::Notion,
- Self::Linear => import::domain::models::ImportSource::Linear,
- Self::Jira => import::domain::models::ImportSource::Jira,
- }
- }
-}
-
+/// The source of an import review's one draft, fixed at presentation.
fn import_source(
record: &ReviewRecord,
) -> Result<import::domain::models::ImportSource, CodeModeError> {
- let mut sources = record.items.iter().map(|item| {
- serde_json::from_value::<ImportDraft>(item.draft.clone())
- .map(|draft| draft.source.source())
- .map_err(|_| CodeModeError::Invalid("Import draft is malformed.".into()))
- });
- let source = sources
- .next()
- .ok_or_else(|| CodeModeError::Invalid("Import review has no draft.".into()))??;
- if sources.any(|other| other.ok() != Some(source)) {
- return Err(CodeModeError::Invalid(
- "An import review must contain one source.".into(),
- ));
+ match &record.items {
+ ReviewItems::Import(items) => {
+ let [item] = &**items;
+ Ok(item.draft.source.into())
+ }
+ _ => Err(CodeModeError::Invalid(
+ "This is not an import review.".into(),
+ )),
}
- Ok(source)
}
pub struct Actions<S, H> {
@@ -95,15 +54,12 @@ impl<S: AgentSessionRepo, H: AgentSessionNotificationRecipient> ReviewActions fo
.map_err(|error| CodeModeError::Storage(rootcause::report!(error).into()))?,
})
}
- fn validate(&self, kind: ReviewKind, draft: &Value) -> Result<(), CodeModeError> {
- validate_draft(&self.tools, kind, draft)
- }
async fn approvable(
&self,
account_holder: &MacroUserIdStr<'static>,
record: &ReviewRecord,
) -> Result<bool, CodeModeError> {
- if record.kind != ReviewKind::Import {
+ if record.kind() != ReviewKind::Import {
return Ok(true);
}
let report = self
@@ -111,43 +67,53 @@ impl<S: AgentSessionRepo, H: AgentSessionNotificationRecipient> ReviewActions fo
.await?;
Ok(report.review_id == Some(record.id.0) && report.status == Some(RunStatus::Ready))
}
- async fn execute(
+ async fn send_email(
&self,
- owner: &MacroUserIdStr<'static>,
- record: &ReviewRecord,
- draft: Value,
- ) -> Result<Value, CodeModeError> {
- let name = match record.kind {
- ReviewKind::Email => "SendEmail",
- ReviewKind::Calendar => "CreateCalendarEvent",
- ReviewKind::Import => return self.start_import(owner, record, draft).await,
- };
- let mut context = self.context.clone();
- context.usage_context =
- ai_usage::UsageContext::new(ai_usage::AiFeature::AgentSession, owner.clone());
- let result = self
- .tools
- .try_user_tool_call(context, RequestContext::new(owner.clone()), name, &draft)
+ account_holder: &MacroUserIdStr<'static>,
+ draft: &EmailDraft,
+ ) -> Result<EmailResult, CodeModeError> {
+ self.user_action(account_holder, "SendEmail", draft).await
+ }
+ async fn create_calendar_event(
+ &self,
+ account_holder: &MacroUserIdStr<'static>,
+ draft: &CalendarDraft,
+ ) -> Result<CalendarResult, CodeModeError> {
+ self.user_action(account_holder, "CreateCalendarEvent", draft)
.await
- .map_err(|_| CodeModeError::Invalid("Could not submit the reviewed action.".into()))?
- .map_err(|_| {
- CodeModeError::Invalid(
- "The reviewed action did not return a confirmed outcome.".into(),
- )
- })?;
- match result {
- ai_toolset::tool_object::UserToolResponse::UserAction(value) => Ok(value),
- _ => Err(CodeModeError::Invalid(
- "The action was not completed.".into(),
- )),
+ }
+ async fn start_import(
+ &self,
+ account_holder: &MacroUserIdStr<'static>,
+ record: &ReviewRecord,
+ draft: &ImportDraft,
+ ) -> Result<ImportResult, CodeModeError> {
+ let source = import::domain::models::ImportSource::from(draft.source);
+ if source != import_source(record)? {
+ return Err(CodeModeError::Invalid(
+ "The import source cannot change after presentation.".into(),
+ ));
}
+ self.import_service()?
+ .start_workspace_write(
+ account_holder,
+ source,
+ record.id.0,
+ NotionWriteChoices {
+ excluded: draft.excluded.clone(),
+ shared: draft.shared.clone(),
+ personal: draft.personal.clone(),
+ },
+ )
+ .await
+ .map_err(|error| CodeModeError::Invalid(error.to_string()))
}
async fn present(
&self,
owner: &MacroUserIdStr<'static>,
record: &ReviewRecord,
) -> Result<(), CodeModeError> {
- if record.kind == ReviewKind::Import {
+ if record.kind() == ReviewKind::Import {
// The plan is tied to the review before the card appears, so the
// card never shows a plan it cannot approve.
self.import_service()?
@@ -167,7 +133,7 @@ impl<S: AgentSessionRepo, H: AgentSessionNotificationRecipient> ReviewActions fo
agent_session::domain::model::SessionToolPresentation {
tool_call_id: format!("review_{}", record.id.0),
title: "mcp__macro_internal__PresentReview".into(),
- raw_input: serde_json::json!({"reviewId": record.id, "kind": record.kind, "title": record.title}),
+ raw_input: serde_json::json!({"reviewId": record.id, "kind": record.kind(), "title": record.title}),
raw_output: serde_json::json!({"reviewId": record.id, "message": "Presented to the user"}),
},
).await.map_err(|_| CodeModeError::Invalid(format!("Review {} was saved, but presentation is pending. Read this review to retry presentation without creating another draft.", record.id.0)))
@@ -224,66 +190,48 @@ impl<S, H> Actions<S, H> {
})
}
- /// Start writing the approved plan; the write runs in the background,
- /// reports progress through the import state, and tells the session
- /// once it ends.
- async fn start_import(
+ /// Run a user tool with a reviewed draft and decode its confirmed response.
+ async fn user_action<Draft: Serialize, Response: DeserializeOwned>(
&self,
- owner: &MacroUserIdStr<'static>,
- record: &ReviewRecord,
- draft: Value,
- ) -> Result<Value, CodeModeError> {
- let draft: ImportDraft = serde_json::from_value(draft)
- .map_err(|_| CodeModeError::Invalid("Import draft is malformed.".into()))?;
- let source = draft.source.source();
- if source != import_source(record)? {
- return Err(CodeModeError::Invalid(
- "The import source cannot change after presentation.".into(),
- ));
- }
- let report = self
- .import_service()?
- .start_workspace_write(
- owner,
- source,
- record.id.0,
- NotionWriteChoices {
- excluded: draft.excluded,
- shared: draft.shared,
- personal: draft.personal,
- },
+ account_holder: &MacroUserIdStr<'static>,
+ name: &str,
+ draft: &Draft,
+ ) -> Result<Response, CodeModeError> {
+ let arguments = serde_json::to_value(draft)
+ .map_err(|_| CodeModeError::Invalid("Could not submit the reviewed action.".into()))?;
+ let mut context = self.context.clone();
+ context.usage_context =
+ ai_usage::UsageContext::new(ai_usage::AiFeature::AgentSession, account_holder.clone());
+ let result = self
+ .tools
+ .try_user_tool_call(
+ context,
+ RequestContext::new(account_holder.clone()),
+ name,
+ &arguments,
)
.await
- .map_err(|error| CodeModeError::Invalid(error.to_string()))?;
- serde_json::to_value(report).map_err(|_| {
- CodeModeError::Invalid("The import started, but its report could not be read.".into())
- })
- }
-}
-
-fn validate_draft(
- tools: &ai_tools::AiToolSet,
- kind: ReviewKind,
- draft: &Value,
-) -> Result<(), CodeModeError> {
- let invalid =
- || CodeModeError::Invalid("Draft does not match the review component's schema.".into());
- match kind {
- ReviewKind::Email => {
- if !tools.is_valid_tool("SendEmail", draft) {
- return Err(invalid());
- }
- }
- ReviewKind::Calendar => {
- if !tools.is_valid_tool("CreateCalendarEvent", draft) {
- return Err(invalid());
- }
- }
- ReviewKind::Import => {
- if serde_json::from_value::<ImportDraft>(draft.clone()).is_err() {
- return Err(invalid());
+ .map_err(|_| CodeModeError::Invalid("Could not submit the reviewed action.".into()))?
+ .map_err(|_| {
+ CodeModeError::Invalid(
+ "The reviewed action did not return a confirmed outcome.".into(),
+ )
+ })?;
+ match result {
+ ai_toolset::tool_object::UserToolResponse::UserAction(value) => {
+ serde_json::from_value(value).map_err(|_| {
+ tracing::warn!(
+ tool = name,
+ "reviewed action returned an unexpected response"
+ );
+ CodeModeError::Invalid(
+ "The reviewed action did not return a confirmed outcome.".into(),
+ )
+ })
}
+ _ => Err(CodeModeError::Invalid(
+ "The action was not completed.".into(),
+ )),
}
}
- Ok(())
}
diff --git a/services/agent_harness_service/src/code_mode/reviews/test.rs b/services/agent_harness_service/src/code_mode/reviews/test.rs
deleted file mode 100644
index 3761a5fc60..0000000000
--- a/services/agent_harness_service/src/code_mode/reviews/test.rs
+++ /dev/null
@@ -1,59 +0,0 @@
-use super::*;
-use serde_json::json;
-
-#[test]
-fn review_validation_uses_existing_action_contracts() {
- let tools = ai_tools::code_mode_tools();
- let email = json!({"subject":"Review", "body":"**Markdown**", "to":[{"email":"[email protected]"}]});
- assert!(validate_draft(&tools, ReviewKind::Email, &email).is_ok());
- assert!(
- validate_draft(
- &tools,
- ReviewKind::Email,
- &json!({"subject":"missing body"})
- )
- .is_err()
- );
- assert!(
- validate_draft(
- &tools,
- ReviewKind::Calendar,
- &json!({"title":"missing time"})
- )
- .is_err()
- );
-}
-
-#[test]
-fn an_import_review_accepts_each_workspace_source_and_preserves_owner_choices() {
- let tools = ai_tools::code_mode_tools();
- for source in ["notion", "linear", "jira"] {
- assert!(validate_draft(&tools, ReviewKind::Import, &json!({"source": source})).is_ok());
- assert!(
- validate_draft(
- &tools,
- ReviewKind::Import,
- &json!({
- "source": source,
- "excluded": ["01a15623-f76d-7ea0-955d-a9ecb91a520e"],
- "shared": ["01a15623-f76d-7ea0-955d-a9ecb91a520f"],
- "personal": ["01a15623-f76d-7ea0-955d-a9ecb91a5210"]
- })
- )
- .is_ok(),
- "owner choices remain valid for {source}"
- );
- }
- for draft in [
- json!({"source": "slack"}),
- json!({"source": "notion", "excluded": ["not a uuid"]}),
- json!({"source": "notion", "personal": ["not a uuid"]}),
- json!({"source": "notion", "write": "everything"}),
- json!({}),
- ] {
- assert!(
- validate_draft(&tools, ReviewKind::Import, &draft).is_err(),
- "{draft}"
- );
- }
-}
diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/web_app_check_main.rs b/tooling/xtask/crates/xtask_workflows/src/workflows/web_app_check_main.rs
index 12fe04799e..5a409b1211 100644
--- a/tooling/xtask/crates/xtask_workflows/src/workflows/web_app_check_main.rs
+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/web_app_check_main.rs
@@ -332,16 +332,17 @@ fn generate_api_types() -> Step<Run> {
}
/// `gen-api` covers the OpenAPI clients; the types specta writes from the
-/// wire types of the two browser wasm crates and from the dynamic-UI view are
-/// regenerated here, so a Rust change cannot leave them behind.
+/// wire types of the two browser wasm crates, the dynamic-UI view and the agent
+/// review types are regenerated here, so a Rust change cannot leave them behind.
fn check_specta_types() -> Step<Run> {
Step::new("Check Specta Types")
.run(indoc::indoc! {r#"
just gen-agent-fold-types
just gen-database-sql-types
just gen-dynamic-ui-types
- if ! git diff --exit-code -- src/lib/service-clients/service-agent-fold/generated src/lib/core/database-sql/generated src/features/dynamic-ui/generated ../../packages/lexical-core/generated; then
- echo "Generated specta types are stale. Run 'just gen-agent-fold-types', 'just gen-database-sql-types' and 'just gen-dynamic-ui-types' in apps/web and commit the result."
+ just gen-agent-review-types
+ if ! git diff --exit-code -- src/lib/service-clients/service-agent-fold/generated src/lib/core/database-sql/generated src/features/dynamic-ui/generated ../../packages/lexical-core/generated src/lib/service-clients/service-agent-reviews/generated ../../packages/sdk/generated/agent-reviews; then
+ echo "Generated specta types are stale. Run 'just gen-agent-fold-types', 'just gen-database-sql-types', 'just gen-dynamic-ui-types' and 'just gen-agent-review-types' in apps/web and commit the result."
exit 1
fi
"#})
diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/web_app_check_main/test.rs b/tooling/xtask/crates/xtask_workflows/src/workflows/web_app_check_main/test.rs
index 933e66965f..5f49befa89 100644
--- a/tooling/xtask/crates/xtask_workflows/src/workflows/web_app_check_main/test.rs
+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/web_app_check_main/test.rs
@@ -205,6 +205,8 @@ fn generated_code_checks_every_rust_generated_artifact_in_one_job() {
"git status --porcelain -- apps/docs",
"just gen-agent-fold-types",
"just gen-database-sql-types",
+ "just gen-dynamic-ui-types",
+ "just gen-agent-review-types",
];
let positions: Vec<usize> = order
.iter()