Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(harness): register macrod harnesses with device-code pairing (#6030)
Eric Hayes034c7ff283f1
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.jsonindex 01ae531300..26b4043b83 100644--- a/.github/workspace-dep-closures.json+++ b/.github/workspace-dep-closures.json@@ -24,6 +24,8 @@"crates/bot_id","crates/bot_token","crates/cowlike",+ "crates/harness_id",+ "crates/harness_token","crates/macro_auth","crates/macro_authorization","crates/macro_env",@@ -77,6 +79,8 @@"crates/frecency","crates/fusionauth","crates/github",+ "crates/harness_id",+ "crates/harness_token","crates/invite_email","crates/item_filters","crates/kafka_util",@@ -187,6 +191,8 @@"crates/frecency","crates/fusionauth","crates/github",+ "crates/harness_id",+ "crates/harness_token","crates/invite_email","crates/item_filters","crates/kafka_util",@@ -299,6 +305,8 @@"crates/fusionauth","crates/generic_email_domains","crates/github",+ "crates/harness_id",+ "crates/harness_token","crates/import","crates/invite_email","crates/item_filters",@@ -426,6 +434,8 @@"crates/foreign_entity","crates/frecency","crates/generic_email_domains",+ "crates/harness_id",+ "crates/harness_token","crates/import","crates/invite_email","crates/item_filters",@@ -533,6 +543,8 @@"crates/entity_mutation","crates/filter_ast","crates/frecency",+ "crates/harness_id",+ "crates/harness_token","crates/invite_email","crates/item_filters","crates/kafka_util",@@ -600,6 +612,8 @@"crates/entity_mutation","crates/filter_ast","crates/frecency",+ "crates/harness_id",+ "crates/harness_token","crates/invite_email","crates/item_filters","crates/kafka_util",@@ -681,6 +695,8 @@"crates/entity_mutation","crates/filter_ast","crates/frecency",+ "crates/harness_id",+ "crates/harness_token","crates/invite_email","crates/item_filters","crates/kafka_util",@@ -776,6 +792,8 @@"crates/foreign_entity","crates/frecency","crates/generic_email_domains",+ "crates/harness_id",+ "crates/harness_token","crates/import","crates/invite_email","crates/item_filters",@@ -875,6 +893,8 @@"crates/entity_mutation","crates/filter_ast","crates/frecency",+ "crates/harness_id",+ "crates/harness_token","crates/invite_email","crates/item_filters","crates/kafka_util",@@ -963,6 +983,8 @@"crates/foreign_entity","crates/frecency","crates/generic_email_domains",+ "crates/harness_id",+ "crates/harness_token","crates/import","crates/invite_email","crates/item_filters",@@ -1051,6 +1073,8 @@"crates/bot_id","crates/bot_token","crates/cowlike",+ "crates/harness_id",+ "crates/harness_token","crates/macro_auth","crates/macro_authorization","crates/macro_env",@@ -1130,6 +1154,8 @@"crates/fusionauth","crates/generic_email_domains","crates/github",+ "crates/harness_id",+ "crates/harness_token","crates/invite_email","crates/ip_extractor","crates/item_filters",@@ -1220,6 +1246,8 @@"crates/bot_token","crates/cowlike","crates/document_sub_type",+ "crates/harness_id",+ "crates/harness_token","crates/macro_auth","crates/macro_authorization","crates/macro_env",@@ -1270,6 +1298,8 @@"crates/entity_mutation","crates/filter_ast","crates/frecency",+ "crates/harness_id",+ "crates/harness_token","crates/invite_email","crates/item_filters","crates/kafka_util",@@ -1355,6 +1385,8 @@"crates/frecency","crates/graphql_common","crates/graphql_soup_filter_input",+ "crates/harness_id",+ "crates/harness_token","crates/invite_email","crates/item_filter_index","crates/item_filters",@@ -1418,6 +1450,8 @@"crates/calendar_events","crates/channel_sender","crates/cowlike",+ "crates/harness_id",+ "crates/harness_token","crates/invite_email","crates/kafka_util","crates/last_online_tracker",@@ -1464,6 +1498,8 @@"crates/entity_mutation","crates/filter_ast","crates/frecency",+ "crates/harness_id",+ "crates/harness_token","crates/invite_email","crates/item_filters","crates/kafka_util",@@ -1551,6 +1587,8 @@"crates/foreign_entity","crates/frecency","crates/generic_email_domains",+ "crates/harness_id",+ "crates/harness_token","crates/import","crates/invite_email","crates/item_filters",@@ -1656,6 +1694,8 @@"crates/entity_mutation","crates/filter_ast","crates/frecency",+ "crates/harness_id",+ "crates/harness_token","crates/invite_email","crates/item_filters","crates/kafka_util",@@ -1706,6 +1746,8 @@"crates/entity_access_db_utils","crates/entity_access_management","crates/entity_mutation",+ "crates/harness_id",+ "crates/harness_token","crates/kafka_util","crates/macro_auth","crates/macro_authorization",@@ -1768,6 +1810,9 @@"crates/filter_ast","crates/foreign_entity","crates/frecency",+ "crates/harness_id",+ "crates/harness_token",+ "crates/harnesses","crates/invite_email","crates/item_filters","crates/kafka_util",@@ -1859,6 +1904,8 @@"crates/entity_mutation","crates/filter_ast","crates/frecency",+ "crates/harness_id",+ "crates/harness_token","crates/invite_email","crates/item_filters","crates/kafka_util",@@ -1931,6 +1978,8 @@"crates/entity_mutation","crates/filter_ast","crates/frecency",+ "crates/harness_id",+ "crates/harness_token","crates/invite_email","crates/item_filters","crates/kafka_util",@@ -2013,6 +2062,8 @@"crates/graphql_properties","crates/graphql_soup","crates/graphql_soup_filter_input",+ "crates/harness_id",+ "crates/harness_token","crates/invite_email","crates/item_filter_index","crates/item_filters",@@ -2094,6 +2145,8 @@"crates/cowlike","crates/document_sub_type","crates/entity_access",+ "crates/harness_id",+ "crates/harness_token","crates/macro_auth","crates/macro_authorization","crates/macro_env",@@ -2128,6 +2181,8 @@"crates/ensure_exists","crates/filter_ast","crates/frecency",+ "crates/harness_id",+ "crates/harness_token","crates/item_filters","crates/last_online_tracker","crates/macro_auth",@@ -2176,6 +2231,8 @@"crates/bot_token","crates/contacts","crates/cowlike",+ "crates/harness_id",+ "crates/harness_token","crates/macro_auth","crates/macro_authorization","crates/macro_env",@@ -2199,6 +2256,8 @@"crates/cowlike","crates/database_env_vars","crates/document_sub_type",+ "crates/harness_id",+ "crates/harness_token","crates/macro_auth","crates/macro_authorization","crates/macro_aws_config",@@ -2252,6 +2311,8 @@"crates/entity_mutation","crates/filter_ast","crates/frecency",+ "crates/harness_id",+ "crates/harness_token","crates/invite_email","crates/ip_extractor","crates/item_filters",@@ -2327,6 +2388,8 @@"crates/document_sub_type","crates/entity_access","crates/entity_access_db_utils",+ "crates/harness_id",+ "crates/harness_token","crates/invite_email","crates/kafka_util","crates/last_online_tracker",@@ -2440,6 +2503,8 @@"crates/filter_ast","crates/foreign_entity","crates/frecency",+ "crates/harness_id",+ "crates/harness_token","crates/invite_email","crates/item_filters","crates/kafka_util",@@ -2553,6 +2618,8 @@"crates/foreign_entity","crates/frecency","crates/generic_email_domains",+ "crates/harness_id",+ "crates/harness_token","crates/import","crates/invite_email","crates/ip_extractor",@@ -2707,6 +2774,9 @@"crates/graphql_properties","crates/graphql_soup","crates/graphql_soup_filter_input",+ "crates/harness_id",+ "crates/harness_token",+ "crates/harnesses","crates/import","crates/invite_email","crates/ip_extractor",@@ -2812,6 +2882,8 @@"crates/cowlike","crates/document_storage_service_client","crates/document_sub_type",+ "crates/harness_id",+ "crates/harness_token","crates/macro_auth","crates/macro_authorization","crates/macro_env",@@ -2843,6 +2915,8 @@"crates/bot_token","crates/cowlike","crates/document_sub_type",+ "crates/harness_id",+ "crates/harness_token","crates/macro_auth","crates/macro_authorization","crates/macro_aws_config",@@ -2899,6 +2973,8 @@"crates/filter_ast","crates/foreign_entity","crates/frecency",+ "crates/harness_id",+ "crates/harness_token","crates/invite_email","crates/item_filters","crates/kafka_util",@@ -2988,6 +3064,8 @@"crates/filter_ast","crates/foreign_entity","crates/frecency",+ "crates/harness_id",+ "crates/harness_token","crates/invite_email","crates/item_filters","crates/kafka_util",@@ -3065,6 +3143,8 @@"crates/entity_mutation","crates/filter_ast","crates/frecency",+ "crates/harness_id",+ "crates/harness_token","crates/invite_email","crates/item_filters","crates/kafka_util",@@ -3146,6 +3226,8 @@"crates/entity_mutation","crates/filter_ast","crates/frecency",+ "crates/harness_id",+ "crates/harness_token","crates/invite_email","crates/item_filters","crates/kafka_util",@@ -3211,6 +3293,8 @@"crates/channel_sender","crates/cowlike","crates/email_formatting",+ "crates/harness_id",+ "crates/harness_token","crates/invite_email","crates/kafka_util","crates/last_online_tracker",@@ -3256,6 +3340,8 @@"crates/entity_mutation","crates/filter_ast","crates/frecency",+ "crates/harness_id",+ "crates/harness_token","crates/invite_email","crates/item_filters","crates/kafka_util",@@ -3321,6 +3407,8 @@"crates/entity_mutation","crates/filter_ast","crates/frecency",+ "crates/harness_id",+ "crates/harness_token","crates/invite_email","crates/item_filters","crates/kafka_util",@@ -3394,6 +3482,8 @@"crates/filter_ast","crates/frecency","crates/gmail_client",+ "crates/harness_id",+ "crates/harness_token","crates/invite_email","crates/ip_extractor","crates/item_filters",@@ -3476,6 +3566,8 @@"crates/entity_mutation","crates/filter_ast","crates/frecency",+ "crates/harness_id",+ "crates/harness_token","crates/invite_email","crates/item_filters","crates/kafka_util",@@ -3534,6 +3626,8 @@"crates/entity_mutation","crates/filter_ast","crates/frecency",+ "crates/harness_id",+ "crates/harness_token","crates/invite_email","crates/item_filters","crates/kafka_util",@@ -3587,6 +3681,8 @@"crates/cowlike","crates/document_sub_type","crates/entity_access_db_utils",+ "crates/harness_id",+ "crates/harness_token","crates/macro_auth","crates/macro_authorization","crates/macro_db_client",@@ -3642,6 +3738,8 @@"crates/cowlike","crates/document_sub_type","crates/entity_access",+ "crates/harness_id",+ "crates/harness_token","crates/macro_auth","crates/macro_authorization","crates/macro_env",@@ -3695,6 +3793,8 @@"crates/document_sub_type","crates/entity_access","crates/entity_mutation",+ "crates/harness_id",+ "crates/harness_token","crates/macro_auth","crates/macro_authorization","crates/macro_env",@@ -3725,6 +3825,8 @@"crates/document_sub_type","crates/entity_access","crates/favorites",+ "crates/harness_id",+ "crates/harness_token","crates/macro_auth","crates/macro_authorization","crates/macro_env",@@ -3759,6 +3861,8 @@"crates/entity_access","crates/filter_ast","crates/foreign_entity",+ "crates/harness_id",+ "crates/harness_token","crates/item_filters","crates/macro_auth","crates/macro_authorization",@@ -3834,6 +3938,8 @@"crates/frecency","crates/fusionauth","crates/github",+ "crates/harness_id",+ "crates/harness_token","crates/invite_email","crates/item_filters","crates/kafka_util",@@ -3910,6 +4016,8 @@"crates/filter_ast","crates/graphql_activity","crates/graphql_common",+ "crates/harness_id",+ "crates/harness_token","crates/item_filters","crates/kafka_util","crates/macro_auth",@@ -3952,6 +4060,8 @@"crates/frecency","crates/graphql_channel","crates/graphql_common",+ "crates/harness_id",+ "crates/harness_token","crates/invite_email","crates/item_filters","crates/kafka_util",@@ -3994,6 +4104,8 @@"crates/document_sub_type","crates/filter_ast","crates/graphql_common",+ "crates/harness_id",+ "crates/harness_token","crates/item_filters","crates/macro_auth","crates/macro_authorization",@@ -4033,6 +4145,8 @@"crates/frecency","crates/graphql_common","crates/graphql_email",+ "crates/harness_id",+ "crates/harness_token","crates/invite_email","crates/item_filters","crates/kafka_util",@@ -4109,6 +4223,8 @@"crates/graphql_permission","crates/graphql_soup","crates/graphql_soup_filter_input",+ "crates/harness_id",+ "crates/harness_token","crates/invite_email","crates/item_filter_index","crates/item_filters",@@ -4189,6 +4305,8 @@"crates/entity_access","crates/favorites","crates/graphql_favorite",+ "crates/harness_id",+ "crates/harness_token","crates/macro_auth","crates/macro_authorization","crates/macro_env",@@ -4219,6 +4337,8 @@"crates/filter_ast","crates/graphql_common","crates/graphql_notification",+ "crates/harness_id",+ "crates/harness_token","crates/invite_email","crates/item_filters","crates/kafka_util",@@ -4257,6 +4377,8 @@"crates/document_sub_type","crates/entity_access","crates/graphql_permission",+ "crates/harness_id",+ "crates/harness_token","crates/macro_auth","crates/macro_authorization","crates/macro_env",@@ -4293,6 +4415,8 @@"crates/filter_ast","crates/graphql_common","crates/graphql_properties",+ "crates/harness_id",+ "crates/harness_token","crates/invite_email","crates/item_filters","crates/kafka_util",@@ -4367,6 +4491,8 @@"crates/graphql_permission","crates/graphql_soup","crates/graphql_soup_filter_input",+ "crates/harness_id",+ "crates/harness_token","crates/invite_email","crates/item_filter_index","crates/item_filters",@@ -4443,6 +4569,8 @@"crates/filter_ast","crates/graphql_common","crates/graphql_soup_filter_input",+ "crates/harness_id",+ "crates/harness_token","crates/item_filters","crates/macro_auth","crates/macro_authorization",@@ -4458,6 +4586,31 @@"crates/remote_env_var","crates/workspace-hack"],+ "harness_id": [+ "crates/harness_id",+ "crates/workspace-hack"+ ],+ "harness_token": [+ "crates/harness_token",+ "crates/workspace-hack"+ ],+ "harnesses": [+ "crates/bot_id",+ "crates/bot_token",+ "crates/cowlike",+ "crates/harness_id",+ "crates/harness_token",+ "crates/harnesses",+ "crates/macro_auth",+ "crates/macro_authorization",+ "crates/macro_env",+ "crates/macro_env_var",+ "crates/macro_user_id",+ "crates/model-error-response",+ "crates/model_user",+ "crates/remote_env_var",+ "crates/workspace-hack"+ ],"image_optimizer": ["crates/macro_aws_config","crates/macro_entrypoint",@@ -4476,6 +4629,8 @@"crates/cowlike","crates/document_sub_type","crates/entity_access_db_utils",+ "crates/harness_id",+ "crates/harness_token","crates/ip_extractor","crates/macro_auth","crates/macro_authorization",@@ -4528,6 +4683,8 @@"crates/document_sub_type","crates/entity_access","crates/entity_access_db_utils",+ "crates/harness_id",+ "crates/harness_token","crates/import","crates/invite_email","crates/kafka_util",@@ -4572,6 +4729,8 @@"crates/bot_token","crates/broadcast","crates/cowlike",+ "crates/harness_id",+ "crates/harness_token","crates/invite_email","crates/kafka_util","crates/last_online_tracker",@@ -4663,6 +4822,8 @@"crates/entity_mutation","crates/filter_ast","crates/frecency",+ "crates/harness_id",+ "crates/harness_token","crates/invite_email","crates/item_filters","crates/kafka_util",@@ -4740,6 +4901,8 @@"crates/entity_mutation","crates/filter_ast","crates/frecency",+ "crates/harness_id",+ "crates/harness_token","crates/invite_email","crates/item_filters","crates/kafka_util",@@ -4824,6 +4987,8 @@"crates/bot_id","crates/bot_token","crates/cowlike",+ "crates/harness_id",+ "crates/harness_token","crates/macro_auth","crates/macro_authorization","crates/macro_env",@@ -4875,6 +5040,8 @@"crates/cowlike","crates/document_sub_type","crates/entity_access_db_utils",+ "crates/harness_id",+ "crates/harness_token","crates/macro_auth","crates/macro_authorization","crates/macro_db_client",@@ -4943,6 +5110,8 @@"crates/cowlike","crates/document_sub_type","crates/entity_access_db_utils",+ "crates/harness_id",+ "crates/harness_token","crates/ip_extractor","crates/macro_auth","crates/macro_authorization",@@ -4997,6 +5166,8 @@"crates/bot_token","crates/cowlike","crates/document_sub_type",+ "crates/harness_id",+ "crates/harness_token","crates/macro_auth","crates/macro_authorization","crates/macro_env",@@ -5053,6 +5224,8 @@"crates/bot_id","crates/bot_token","crates/cowlike",+ "crates/harness_id",+ "crates/harness_token","crates/macro_auth","crates/macro_authorization","crates/macro_env",@@ -5077,6 +5250,8 @@"crates/bot_id","crates/bot_token","crates/cowlike",+ "crates/harness_id",+ "crates/harness_token","crates/macro_auth","crates/macro_authorization","crates/macro_env",@@ -5139,6 +5314,8 @@"crates/frecency","crates/fusionauth","crates/generic_email_domains",+ "crates/harness_id",+ "crates/harness_token","crates/import","crates/invite_email","crates/item_filters",@@ -5263,6 +5440,8 @@"crates/foreign_entity","crates/frecency","crates/generic_email_domains",+ "crates/harness_id",+ "crates/harness_token","crates/import","crates/invite_email","crates/item_filters",@@ -5366,6 +5545,8 @@"crates/bot_token","crates/cowlike","crates/document_sub_type",+ "crates/harness_id",+ "crates/harness_token","crates/macro_auth","crates/macro_authorization","crates/macro_env",@@ -5404,6 +5585,8 @@"crates/broadcast","crates/channel_sender","crates/cowlike",+ "crates/harness_id",+ "crates/harness_token","crates/invite_email","crates/kafka_util","crates/last_online_tracker",@@ -5509,6 +5692,8 @@"crates/entity_mutation","crates/filter_ast","crates/frecency",+ "crates/harness_id",+ "crates/harness_token","crates/invite_email","crates/item_filters","crates/kafka_util",@@ -5591,6 +5776,8 @@"crates/entity_mutation","crates/filter_ast","crates/frecency",+ "crates/harness_id",+ "crates/harness_token","crates/invite_email","crates/item_filters","crates/kafka_util",@@ -5657,6 +5844,8 @@"crates/entity_mutation","crates/filter_ast","crates/frecency",+ "crates/harness_id",+ "crates/harness_token","crates/invite_email","crates/item_filters","crates/kafka_util",@@ -5714,6 +5903,8 @@"crates/bot_token","crates/broadcast","crates/cowlike",+ "crates/harness_id",+ "crates/harness_token","crates/kafka_util","crates/last_online_tracker","crates/macro_auth",@@ -5741,6 +5932,8 @@"crates/broadcast","crates/channel_sender","crates/cowlike",+ "crates/harness_id",+ "crates/harness_token","crates/invite_email","crates/kafka_util","crates/last_online_tracker",@@ -5773,6 +5966,8 @@"crates/channel_sender","crates/cowlike","crates/email_formatting",+ "crates/harness_id",+ "crates/harness_token","crates/invite_email","crates/kafka_util","crates/last_online_tracker",@@ -5812,6 +6007,8 @@"crates/document_sub_type","crates/email_formatting","crates/entity_access_db_utils",+ "crates/harness_id",+ "crates/harness_token","crates/invite_email","crates/ip_extractor","crates/kafka_util",@@ -5879,6 +6076,8 @@"crates/entity_access","crates/entity_access_db_utils","crates/generic_email_domains",+ "crates/harness_id",+ "crates/harness_token","crates/import","crates/invite_email","crates/kafka_util",@@ -5951,6 +6150,8 @@"crates/entity_mutation","crates/filter_ast","crates/frecency",+ "crates/harness_id",+ "crates/harness_token","crates/invite_email","crates/item_filters","crates/kafka_util",@@ -6016,6 +6217,8 @@"crates/entity_mutation","crates/filter_ast","crates/frecency",+ "crates/harness_id",+ "crates/harness_token","crates/invite_email","crates/item_filters","crates/kafka_util",@@ -6064,6 +6267,8 @@"crates/bot_id","crates/bot_token","crates/cowlike",+ "crates/harness_id",+ "crates/harness_token","crates/macro_auth","crates/macro_authorization","crates/macro_env",@@ -6112,6 +6317,8 @@"crates/filter_ast","crates/foreign_entity","crates/frecency",+ "crates/harness_id",+ "crates/harness_token","crates/invite_email","crates/item_filters","crates/kafka_util",@@ -6190,6 +6397,8 @@"crates/document_sub_type","crates/entity_access","crates/entity_access_db_utils",+ "crates/harness_id",+ "crates/harness_token","crates/invite_email","crates/kafka_util","crates/last_online_tracker",@@ -6237,6 +6446,8 @@"crates/document_sub_type","crates/entity_access","crates/entity_access_db_utils",+ "crates/harness_id",+ "crates/harness_token","crates/invite_email","crates/kafka_util","crates/last_online_tracker",@@ -6285,6 +6496,8 @@"crates/bot_token","crates/broadcast","crates/cowlike",+ "crates/harness_id",+ "crates/harness_token","crates/invite_email","crates/ip_extractor","crates/kafka_util",@@ -6320,6 +6533,8 @@"crates/cowlike","crates/document_sub_type","crates/entity_access",+ "crates/harness_id",+ "crates/harness_token","crates/invite_email","crates/kafka_util","crates/last_online_tracker",@@ -6419,6 +6634,8 @@"crates/foreign_entity","crates/frecency","crates/generic_email_domains",+ "crates/harness_id",+ "crates/harness_token","crates/import","crates/invite_email","crates/item_filters",@@ -6540,6 +6757,8 @@"crates/filter_ast","crates/foreign_entity","crates/frecency",+ "crates/harness_id",+ "crates/harness_token","crates/invite_email","crates/ip_extractor","crates/item_filters",@@ -6643,6 +6862,8 @@"crates/entity_mutation","crates/filter_ast","crates/frecency",+ "crates/harness_id",+ "crates/harness_token","crates/invite_email","crates/item_filters","crates/kafka_util",@@ -6726,6 +6947,8 @@"crates/entity_mutation","crates/filter_ast","crates/frecency",+ "crates/harness_id",+ "crates/harness_token","crates/invite_email","crates/item_filters","crates/kafka_util",@@ -6783,6 +7006,8 @@"crates/cowlike","crates/document_storage_service_client","crates/document_sub_type",+ "crates/harness_id",+ "crates/harness_token","crates/macro_auth","crates/macro_authorization","crates/macro_entrypoint",@@ -6846,6 +7071,8 @@"crates/filter_ast","crates/frecency","crates/fusionauth",+ "crates/harness_id",+ "crates/harness_token","crates/invite_email","crates/item_filters","crates/kafka_util",@@ -6962,6 +7189,8 @@"crates/filter_ast","crates/foreign_entity","crates/frecency",+ "crates/harness_id",+ "crates/harness_token","crates/invite_email","crates/item_filters","crates/kafka_util",@@ -7047,6 +7276,8 @@"crates/filter_ast","crates/foreign_entity","crates/frecency",+ "crates/harness_id",+ "crates/harness_token","crates/invite_email","crates/item_filters","crates/kafka_util",@@ -7123,6 +7354,8 @@"crates/frecency","crates/graphql_common","crates/graphql_soup_filter_input",+ "crates/harness_id",+ "crates/harness_token","crates/invite_email","crates/item_filter_index","crates/item_filters",@@ -7201,6 +7434,8 @@"crates/filter_ast","crates/foreign_entity","crates/frecency",+ "crates/harness_id",+ "crates/harness_token","crates/invite_email","crates/item_filter_index","crates/item_filters",@@ -7283,6 +7518,8 @@"crates/filter_ast","crates/foreign_entity","crates/frecency",+ "crates/harness_id",+ "crates/harness_token","crates/invite_email","crates/item_filters","crates/kafka_util",@@ -7367,6 +7604,8 @@"crates/entity_mutation","crates/filter_ast","crates/frecency",+ "crates/harness_id",+ "crates/harness_token","crates/invite_email","crates/item_filters","crates/kafka_util",@@ -7429,6 +7668,8 @@"crates/bot_token","crates/cowlike","crates/document_sub_type",+ "crates/harness_id",+ "crates/harness_token","crates/macro_auth","crates/macro_authorization","crates/macro_aws_config",@@ -7488,6 +7729,8 @@"crates/bot_token","crates/cowlike","crates/document_sub_type",+ "crates/harness_id",+ "crates/harness_token","crates/macro_auth","crates/macro_authorization","crates/macro_env",@@ -7513,6 +7756,8 @@"crates/bot_id","crates/bot_token","crates/cowlike",+ "crates/harness_id",+ "crates/harness_token","crates/macro_auth","crates/macro_authorization","crates/macro_env",@@ -7569,6 +7814,8 @@"crates/entity_mutation","crates/filter_ast","crates/frecency",+ "crates/harness_id",+ "crates/harness_token","crates/invite_email","crates/item_filters","crates/kafka_util",@@ -7648,6 +7895,8 @@"crates/filter_ast","crates/frecency","crates/generic_email_domains",+ "crates/harness_id",+ "crates/harness_token","crates/invite_email","crates/item_filters","crates/kafka_util",@@ -7738,6 +7987,8 @@"crates/entity_mutation","crates/filter_ast","crates/frecency",+ "crates/harness_id",+ "crates/harness_token","crates/invite_email","crates/item_filters","crates/kafka_util",@@ -7804,6 +8055,8 @@"crates/entity_mutation","crates/filter_ast","crates/frecency",+ "crates/harness_id",+ "crates/harness_token","crates/invite_email","crates/item_filters","crates/kafka_util",@@ -7851,6 +8104,8 @@"crates/bot_id","crates/bot_token","crates/cowlike",+ "crates/harness_id",+ "crates/harness_token","crates/macro_auth","crates/macro_authorization","crates/macro_env",@@ -7872,6 +8127,8 @@"crates/cowlike","crates/document_sub_type","crates/entity_access_db_utils",+ "crates/harness_id",+ "crates/harness_token","crates/macro_auth","crates/macro_authorization","crates/macro_db_client",@@ -7941,6 +8198,8 @@"crates/filter_ast","crates/foreign_entity","crates/frecency",+ "crates/harness_id",+ "crates/harness_token","crates/invite_email","crates/item_filters","crates/kafka_util",diff --git a/.sqlx/query-d05b1c840950c3ead42dd8dce64bcb73a79bb293cf5fc5232bab344d04ffed43.json b/.sqlx/query-0057301723d11cedc003eab4fb1355b7352cd9a137f0e8807c802e88f538c7ee.jsonsimilarity index 71%rename from .sqlx/query-d05b1c840950c3ead42dd8dce64bcb73a79bb293cf5fc5232bab344d04ffed43.jsonrename to .sqlx/query-0057301723d11cedc003eab4fb1355b7352cd9a137f0e8807c802e88f538c7ee.jsonindex 4bb0f825a9..b57820aaac 100644--- a/.sqlx/query-d05b1c840950c3ead42dd8dce64bcb73a79bb293cf5fc5232bab344d04ffed43.json+++ b/.sqlx/query-0057301723d11cedc003eab4fb1355b7352cd9a137f0e8807c802e88f538c7ee.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT\n b.id,\n b.kind,\n b.owner_user_id,\n b.team_id,\n b.name,\n b.handle,\n b.description,\n b.avatar_url,\n b.created_by,\n b.created_at,\n b.updated_at,\n b.deleted_at,\n b.has_agent,\n a.instructions,\n a.harness,\n a.default_model,\n a.channel_scope,\n ARRAY(\n SELECT p.channel_id\n FROM comms_channel_participants p\n WHERE p.user_id = 'bot|' || b.id::text\n AND p.left_at IS NULL\n ORDER BY p.channel_id\n ) AS \"channel_ids!\"\n FROM bots b\n INNER JOIN agent_configs a ON a.bot_id = b.id\n WHERE b.kind = 'owned'\n AND b.deleted_at IS NULL\n AND (\n b.owner_user_id = $1\n OR b.team_id IN (\n SELECT team_id FROM team_user WHERE user_id = $1\n )\n )\n ORDER BY b.created_at ASC, b.id ASC\n ",+ "query": "\n SELECT\n b.id,\n b.kind,\n b.owner_user_id,\n b.team_id,\n b.name,\n b.handle,\n b.description,\n b.avatar_url,\n b.created_by,\n b.created_at,\n b.updated_at,\n b.deleted_at,\n b.has_agent,\n a.instructions,\n a.harness,\n a.harness_id,\n a.default_model,\n a.channel_scope,\n ARRAY(\n SELECT p.channel_id\n FROM comms_channel_participants p\n WHERE p.user_id = 'bot|' || b.id::text\n AND p.left_at IS NULL\n ORDER BY p.channel_id\n ) AS \"channel_ids!\"\n FROM bots b\n INNER JOIN agent_configs a ON a.bot_id = b.id\n WHERE b.kind = 'owned'\n AND b.deleted_at IS NULL\n AND (\n b.owner_user_id = $1\n OR b.team_id IN (\n SELECT team_id FROM team_user WHERE user_id = $1\n )\n )\n ORDER BY b.created_at ASC, b.id ASC\n ","describe": {"columns": [{@@ -80,16 +80,21 @@},{"ordinal": 15,+ "name": "harness_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 16,"name": "default_model","type_info": "Text"},{- "ordinal": 16,+ "ordinal": 17,"name": "channel_scope","type_info": "Text"},{- "ordinal": 17,+ "ordinal": 18,"name": "channel_ids!","type_info": "UuidArray"}@@ -115,10 +120,11 @@false,false,false,+ true,false,false,null]},- "hash": "d05b1c840950c3ead42dd8dce64bcb73a79bb293cf5fc5232bab344d04ffed43"+ "hash": "0057301723d11cedc003eab4fb1355b7352cd9a137f0e8807c802e88f538c7ee"}diff --git a/.sqlx/query-0d925eefe7a5d058b803ba33c4740afdfbb1e1fba609a1333016cf779771c38a.json b/.sqlx/query-0d925eefe7a5d058b803ba33c4740afdfbb1e1fba609a1333016cf779771c38a.jsonnew file mode 100644index 0000000000..0f3441d2ae--- /dev/null+++ b/.sqlx/query-0d925eefe7a5d058b803ba33c4740afdfbb1e1fba609a1333016cf779771c38a.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE harnesses\n SET deleted_at = now(), updated_at = now()\n WHERE id = $1 AND deleted_at IS NULL\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "0d925eefe7a5d058b803ba33c4740afdfbb1e1fba609a1333016cf779771c38a"+}diff --git a/.sqlx/query-635357c9b365a422c05d7cbc82d25924f435ea3697a6ec62311f2d40e0548544.json b/.sqlx/query-2193da6edede173e322e1f6f7ca1206ea8523c16b99d723be67afaa56c7075ec.jsonsimilarity index 56%rename from .sqlx/query-635357c9b365a422c05d7cbc82d25924f435ea3697a6ec62311f2d40e0548544.jsonrename to .sqlx/query-2193da6edede173e322e1f6f7ca1206ea8523c16b99d723be67afaa56c7075ec.jsonindex cc31b1c5a5..9e290f05bc 100644--- a/.sqlx/query-635357c9b365a422c05d7cbc82d25924f435ea3697a6ec62311f2d40e0548544.json+++ b/.sqlx/query-2193da6edede173e322e1f6f7ca1206ea8523c16b99d723be67afaa56c7075ec.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n UPDATE agent_configs\n SET instructions = $2,\n harness = $3,\n default_model = $4,\n channel_scope = $5,\n updated_at = now()\n WHERE bot_id = $1\n ",+ "query": "\n UPDATE agent_configs\n SET instructions = $2,\n harness = $3,\n harness_id = $4,\n default_model = $5,\n channel_scope = $6,\n updated_at = now()\n WHERE bot_id = $1\n ","describe": {"columns": [],"parameters": {@@ -8,11 +8,12 @@"Uuid","Text","Text",+ "Uuid","Text","Text"]},"nullable": []},- "hash": "635357c9b365a422c05d7cbc82d25924f435ea3697a6ec62311f2d40e0548544"+ "hash": "2193da6edede173e322e1f6f7ca1206ea8523c16b99d723be67afaa56c7075ec"}diff --git a/.sqlx/query-308407c450a391bd26c2b23bd4b03dca0596ba14972654d7dd2178f47cd4e1dc.json b/.sqlx/query-308407c450a391bd26c2b23bd4b03dca0596ba14972654d7dd2178f47cd4e1dc.jsonnew file mode 100644index 0000000000..7952ce2af8--- /dev/null+++ b/.sqlx/query-308407c450a391bd26c2b23bd4b03dca0596ba14972654d7dd2178f47cd4e1dc.json@@ -0,0 +1,28 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT owner_user_id, team_id\n FROM harnesses\n WHERE id = $1 AND deleted_at IS NULL\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "owner_user_id",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "team_id",+ "type_info": "Uuid"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ true,+ true+ ]+ },+ "hash": "308407c450a391bd26c2b23bd4b03dca0596ba14972654d7dd2178f47cd4e1dc"+}diff --git a/.sqlx/query-a4d77f4ccdf193d761babe6a541a21653703d17bfd823441427187f27ad21b53.json b/.sqlx/query-39d74321afaaed143e3462074610e033ce0c07edbb1744bf012fc6ca9534b209.jsonsimilarity index 75%rename from .sqlx/query-a4d77f4ccdf193d761babe6a541a21653703d17bfd823441427187f27ad21b53.jsonrename to .sqlx/query-39d74321afaaed143e3462074610e033ce0c07edbb1744bf012fc6ca9534b209.jsonindex 17416b7ec8..bee02f81d6 100644--- a/.sqlx/query-a4d77f4ccdf193d761babe6a541a21653703d17bfd823441427187f27ad21b53.json+++ b/.sqlx/query-39d74321afaaed143e3462074610e033ce0c07edbb1744bf012fc6ca9534b209.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT\n b.id,\n b.kind,\n b.owner_user_id,\n b.team_id,\n b.name,\n b.handle,\n b.description,\n b.avatar_url,\n b.created_by,\n b.created_at,\n b.updated_at,\n b.deleted_at,\n b.has_agent,\n a.instructions,\n a.harness,\n a.default_model,\n a.channel_scope,\n ARRAY(\n SELECT p.channel_id\n FROM comms_channel_participants p\n WHERE p.user_id = 'bot|' || b.id::text\n AND p.left_at IS NULL\n ORDER BY p.channel_id\n ) AS \"channel_ids!\"\n FROM bots b\n INNER JOIN agent_configs a ON a.bot_id = b.id\n WHERE b.id = $1\n AND b.kind = 'owned'\n AND b.deleted_at IS NULL\n ",+ "query": "\n SELECT\n b.id,\n b.kind,\n b.owner_user_id,\n b.team_id,\n b.name,\n b.handle,\n b.description,\n b.avatar_url,\n b.created_by,\n b.created_at,\n b.updated_at,\n b.deleted_at,\n b.has_agent,\n a.instructions,\n a.harness,\n a.harness_id,\n a.default_model,\n a.channel_scope,\n ARRAY(\n SELECT p.channel_id\n FROM comms_channel_participants p\n WHERE p.user_id = 'bot|' || b.id::text\n AND p.left_at IS NULL\n ORDER BY p.channel_id\n ) AS \"channel_ids!\"\n FROM bots b\n INNER JOIN agent_configs a ON a.bot_id = b.id\n WHERE b.id = $1\n AND b.kind = 'owned'\n AND b.deleted_at IS NULL\n ","describe": {"columns": [{@@ -80,16 +80,21 @@},{"ordinal": 15,+ "name": "harness_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 16,"name": "default_model","type_info": "Text"},{- "ordinal": 16,+ "ordinal": 17,"name": "channel_scope","type_info": "Text"},{- "ordinal": 17,+ "ordinal": 18,"name": "channel_ids!","type_info": "UuidArray"}@@ -115,10 +120,11 @@false,false,false,+ true,false,false,null]},- "hash": "a4d77f4ccdf193d761babe6a541a21653703d17bfd823441427187f27ad21b53"+ "hash": "39d74321afaaed143e3462074610e033ce0c07edbb1744bf012fc6ca9534b209"}diff --git a/.sqlx/query-42ad7423977f6bc3b9c42cba56eb2e81a82d147e79c29c43e0bd316b731293b6.json b/.sqlx/query-42ad7423977f6bc3b9c42cba56eb2e81a82d147e79c29c43e0bd316b731293b6.jsonnew file mode 100644index 0000000000..259eaf8105--- /dev/null+++ b/.sqlx/query-42ad7423977f6bc3b9c42cba56eb2e81a82d147e79c29c43e0bd316b731293b6.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT ac.harness_id\n FROM agent_configs ac\n JOIN harnesses h ON h.id = ac.harness_id\n WHERE ac.bot_id = $1 AND h.deleted_at IS NULL\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "harness_id",+ "type_info": "Uuid"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ true+ ]+ },+ "hash": "42ad7423977f6bc3b9c42cba56eb2e81a82d147e79c29c43e0bd316b731293b6"+}diff --git a/.sqlx/query-42f75f261b91698eb160964f5d5ba56c19602fb2c113bde6d00ecf62ee87812d.json b/.sqlx/query-42f75f261b91698eb160964f5d5ba56c19602fb2c113bde6d00ecf62ee87812d.jsonnew file mode 100644index 0000000000..dbc72fa69a--- /dev/null+++ b/.sqlx/query-42f75f261b91698eb160964f5d5ba56c19602fb2c113bde6d00ecf62ee87812d.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE harness_tokens\n SET last_used_at = now()\n WHERE id = $1\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "42f75f261b91698eb160964f5d5ba56c19602fb2c113bde6d00ecf62ee87812d"+}diff --git a/.sqlx/query-4376ae3d9e02625711ee2c47124c27406214ba66194a516c971b0a0b8c3ac909.json b/.sqlx/query-4376ae3d9e02625711ee2c47124c27406214ba66194a516c971b0a0b8c3ac909.jsonnew file mode 100644index 0000000000..f62112e4c3--- /dev/null+++ b/.sqlx/query-4376ae3d9e02625711ee2c47124c27406214ba66194a516c971b0a0b8c3ac909.json@@ -0,0 +1,34 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT b.id, b.name, b.handle\n FROM agent_configs ac\n JOIN bots b ON b.id = ac.bot_id\n WHERE ac.harness_id = $1\n AND b.deleted_at IS NULL\n AND b.has_agent\n ORDER BY b.created_at\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "name",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "handle",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false,+ false,+ false+ ]+ },+ "hash": "4376ae3d9e02625711ee2c47124c27406214ba66194a516c971b0a0b8c3ac909"+}diff --git a/.sqlx/query-462894fae868528fbf10226edf99171a52bdcd0377f40616c3c304ab6a106f25.json b/.sqlx/query-462894fae868528fbf10226edf99171a52bdcd0377f40616c3c304ab6a106f25.jsonnew file mode 100644index 0000000000..704ff32bfb--- /dev/null+++ b/.sqlx/query-462894fae868528fbf10226edf99171a52bdcd0377f40616c3c304ab6a106f25.json@@ -0,0 +1,58 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT code, requested_name, host_info, requested_scope, status, created_at,\n expires_at\n FROM harness_pairing_requests\n WHERE code = $1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "code",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "requested_name",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "host_info",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "requested_scope",+ "type_info": "Text"+ },+ {+ "ordinal": 4,+ "name": "status",+ "type_info": "Text"+ },+ {+ "ordinal": 5,+ "name": "created_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 6,+ "name": "expires_at",+ "type_info": "Timestamptz"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ false,+ false,+ true,+ true,+ false,+ false,+ false+ ]+ },+ "hash": "462894fae868528fbf10226edf99171a52bdcd0377f40616c3c304ab6a106f25"+}diff --git a/.sqlx/query-50e821ab6b81df124e4335310966a5ba2ccbc811da6df94b09e9288aa9e53011.json b/.sqlx/query-50e821ab6b81df124e4335310966a5ba2ccbc811da6df94b09e9288aa9e53011.jsonnew file mode 100644index 0000000000..e443511006--- /dev/null+++ b/.sqlx/query-50e821ab6b81df124e4335310966a5ba2ccbc811da6df94b09e9288aa9e53011.json@@ -0,0 +1,17 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO harness_tokens (id, harness_id, token_hash, token_prefix)\n VALUES ($1, $2, $3, $4)\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Uuid",+ "Bytea",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "50e821ab6b81df124e4335310966a5ba2ccbc811da6df94b09e9288aa9e53011"+}diff --git a/.sqlx/query-7082641d64d8cb00e41495a47e02f49271c15b88738515059349b07511865876.json b/.sqlx/query-7082641d64d8cb00e41495a47e02f49271c15b88738515059349b07511865876.jsonnew file mode 100644index 0000000000..5587f7f88a--- /dev/null+++ b/.sqlx/query-7082641d64d8cb00e41495a47e02f49271c15b88738515059349b07511865876.json@@ -0,0 +1,40 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT device_secret_hash, status, expires_at, harness_id\n FROM harness_pairing_requests\n WHERE id = $1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "device_secret_hash",+ "type_info": "Bytea"+ },+ {+ "ordinal": 1,+ "name": "status",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "expires_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 3,+ "name": "harness_id",+ "type_info": "Uuid"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false,+ false,+ false,+ true+ ]+ },+ "hash": "7082641d64d8cb00e41495a47e02f49271c15b88738515059349b07511865876"+}diff --git a/.sqlx/query-ec69dbdf2fa28215718f9170a0664b4fc4302de767765ab6629615b810c15cce.json b/.sqlx/query-76c662c3c7b23512dfa8a466c1e1fa4f03306e93e17003876ceab7081a88ef76.jsonsimilarity index 53%rename from .sqlx/query-ec69dbdf2fa28215718f9170a0664b4fc4302de767765ab6629615b810c15cce.jsonrename to .sqlx/query-76c662c3c7b23512dfa8a466c1e1fa4f03306e93e17003876ceab7081a88ef76.jsonindex 991d6191ca..a14ea9e6aa 100644--- a/.sqlx/query-ec69dbdf2fa28215718f9170a0664b4fc4302de767765ab6629615b810c15cce.json+++ b/.sqlx/query-76c662c3c7b23512dfa8a466c1e1fa4f03306e93e17003876ceab7081a88ef76.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n INSERT INTO agent_configs (\n bot_id, instructions, harness, default_model, channel_scope\n )\n VALUES ($1, $2, $3, $4, $5)\n ",+ "query": "\n INSERT INTO agent_configs (\n bot_id, instructions, harness, harness_id, default_model, channel_scope\n )\n VALUES ($1, $2, $3, $4, $5, $6)\n ","describe": {"columns": [],"parameters": {@@ -8,11 +8,12 @@"Uuid","Text","Text",+ "Uuid","Text","Text"]},"nullable": []},- "hash": "ec69dbdf2fa28215718f9170a0664b4fc4302de767765ab6629615b810c15cce"+ "hash": "76c662c3c7b23512dfa8a466c1e1fa4f03306e93e17003876ceab7081a88ef76"}diff --git a/.sqlx/query-7c44900ff1b6056f0476aabe7fb01f3acbfaa80c6ab3bef064f0fe2cb08553f3.json b/.sqlx/query-7c44900ff1b6056f0476aabe7fb01f3acbfaa80c6ab3bef064f0fe2cb08553f3.jsonnew file mode 100644index 0000000000..0e3d5e61b8--- /dev/null+++ b/.sqlx/query-7c44900ff1b6056f0476aabe7fb01f3acbfaa80c6ab3bef064f0fe2cb08553f3.json@@ -0,0 +1,12 @@+{+ "db_name": "PostgreSQL",+ "query": "\n DELETE FROM harness_pairing_requests\n WHERE expires_at <= now() AND status <> 'approved'\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": []+ },+ "nullable": []+ },+ "hash": "7c44900ff1b6056f0476aabe7fb01f3acbfaa80c6ab3bef064f0fe2cb08553f3"+}diff --git a/.sqlx/query-82c3b95aadd28046ab7667de3da9684503d8e27e3ac59f931593b37928769c90.json b/.sqlx/query-82c3b95aadd28046ab7667de3da9684503d8e27e3ac59f931593b37928769c90.jsonnew file mode 100644index 0000000000..79a3d45a71--- /dev/null+++ b/.sqlx/query-82c3b95aadd28046ab7667de3da9684503d8e27e3ac59f931593b37928769c90.json@@ -0,0 +1,34 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n id AS fusion_user_id,\n email,\n \"organizationId\" AS \"organization_id?\"\n FROM \"User\"\n WHERE email = $1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "fusion_user_id",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "email",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "organization_id?",+ "type_info": "Int4"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ false,+ false,+ true+ ]+ },+ "hash": "82c3b95aadd28046ab7667de3da9684503d8e27e3ac59f931593b37928769c90"+}diff --git a/.sqlx/query-9a4cae02a8b2462b906ebbb6fec71cb77d6fe055a789a6abb2cb363b4ee00640.json b/.sqlx/query-9a4cae02a8b2462b906ebbb6fec71cb77d6fe055a789a6abb2cb363b4ee00640.jsonnew file mode 100644index 0000000000..1c60487a43--- /dev/null+++ b/.sqlx/query-9a4cae02a8b2462b906ebbb6fec71cb77d6fe055a789a6abb2cb363b4ee00640.json@@ -0,0 +1,46 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n ht.id AS token_id,\n h.id AS harness_id,\n h.owner_user_id,\n h.team_id,\n h.created_by\n FROM harness_tokens ht\n JOIN harnesses h ON h.id = ht.harness_id\n WHERE ht.token_hash = $1\n AND ht.revoked_at IS NULL\n AND h.deleted_at IS NULL\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "token_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "harness_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 2,+ "name": "owner_user_id",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "team_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 4,+ "name": "created_by",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Bytea"+ ]+ },+ "nullable": [+ false,+ false,+ true,+ true,+ false+ ]+ },+ "hash": "9a4cae02a8b2462b906ebbb6fec71cb77d6fe055a789a6abb2cb363b4ee00640"+}diff --git a/.sqlx/query-9cf0d65adf0369dd4429aac0c7b3a01044286c7ab8b1631f80cd98e87f2ba6f4.json b/.sqlx/query-9cf0d65adf0369dd4429aac0c7b3a01044286c7ab8b1631f80cd98e87f2ba6f4.jsonnew file mode 100644index 0000000000..faa11c557f--- /dev/null+++ b/.sqlx/query-9cf0d65adf0369dd4429aac0c7b3a01044286c7ab8b1631f80cd98e87f2ba6f4.json@@ -0,0 +1,18 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO harnesses (id, kind, name, owner_user_id, team_id, created_by)\n VALUES ($1, 'macrod', $2, $3, $4, $5)\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Text",+ "Text",+ "Uuid",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "9cf0d65adf0369dd4429aac0c7b3a01044286c7ab8b1631f80cd98e87f2ba6f4"+}diff --git a/.sqlx/query-9de80e4162ec9a996091d800b6443786761dac66d571344961abc576eec19563.json b/.sqlx/query-9de80e4162ec9a996091d800b6443786761dac66d571344961abc576eec19563.jsonnew file mode 100644index 0000000000..be99890e62--- /dev/null+++ b/.sqlx/query-9de80e4162ec9a996091d800b6443786761dac66d571344961abc576eec19563.json@@ -0,0 +1,28 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n count(*) AS \"total!\",\n count(*) FILTER (WHERE requested_name = $1) AS \"with_same_name!\"\n FROM harness_pairing_requests\n WHERE status = 'pending' AND expires_at > now()\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "total!",+ "type_info": "Int8"+ },+ {+ "ordinal": 1,+ "name": "with_same_name!",+ "type_info": "Int8"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ null,+ null+ ]+ },+ "hash": "9de80e4162ec9a996091d800b6443786761dac66d571344961abc576eec19563"+}diff --git a/.sqlx/query-ade51572ac68619218ad84c1c13af9094229cb0c46ccb980bbb9b463d4260c73.json b/.sqlx/query-ade51572ac68619218ad84c1c13af9094229cb0c46ccb980bbb9b463d4260c73.jsonnew file mode 100644index 0000000000..20549f8366--- /dev/null+++ b/.sqlx/query-ade51572ac68619218ad84c1c13af9094229cb0c46ccb980bbb9b463d4260c73.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE harness_pairing_requests\n SET status = 'claimed', claimed_at = now()\n WHERE id = $1 AND status = 'approved'\n RETURNING harness_id AS \"harness_id!\"\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "harness_id!",+ "type_info": "Uuid"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ true+ ]+ },+ "hash": "ade51572ac68619218ad84c1c13af9094229cb0c46ccb980bbb9b463d4260c73"+}diff --git a/.sqlx/query-b4d134196b124c4c4a6b0ca5ceb6c8b0c14fbe1d11ad9c260c9108a27f64134d.json b/.sqlx/query-b4d134196b124c4c4a6b0ca5ceb6c8b0c14fbe1d11ad9c260c9108a27f64134d.jsonnew file mode 100644index 0000000000..7ce5d5b8f8--- /dev/null+++ b/.sqlx/query-b4d134196b124c4c4a6b0ca5ceb6c8b0c14fbe1d11ad9c260c9108a27f64134d.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "UPDATE harnesses SET last_disconnected_at = now() WHERE id = $1",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "b4d134196b124c4c4a6b0ca5ceb6c8b0c14fbe1d11ad9c260c9108a27f64134d"+}diff --git a/.sqlx/query-bb5f40af2c31290cf842e508fc7affce72ecaf1ba8b9b5d040cec43ba5c0c153.json b/.sqlx/query-bb5f40af2c31290cf842e508fc7affce72ecaf1ba8b9b5d040cec43ba5c0c153.jsonnew file mode 100644index 0000000000..3613de6046--- /dev/null+++ b/.sqlx/query-bb5f40af2c31290cf842e508fc7affce72ecaf1ba8b9b5d040cec43ba5c0c153.json@@ -0,0 +1,76 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n id, kind, name, owner_user_id, team_id, created_by,\n created_at, updated_at, last_connected_at, last_disconnected_at\n FROM harnesses\n WHERE id = $1 AND deleted_at IS NULL\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "kind",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "name",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "owner_user_id",+ "type_info": "Text"+ },+ {+ "ordinal": 4,+ "name": "team_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 5,+ "name": "created_by",+ "type_info": "Text"+ },+ {+ "ordinal": 6,+ "name": "created_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 7,+ "name": "updated_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 8,+ "name": "last_connected_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 9,+ "name": "last_disconnected_at",+ "type_info": "Timestamptz"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false,+ false,+ false,+ true,+ true,+ false,+ false,+ false,+ true,+ true+ ]+ },+ "hash": "bb5f40af2c31290cf842e508fc7affce72ecaf1ba8b9b5d040cec43ba5c0c153"+}diff --git a/.sqlx/query-c5d9dc079f9b708c5aaafcaca95fe001fd7a6df89e2710c20123b63c31fa9b99.json b/.sqlx/query-c5d9dc079f9b708c5aaafcaca95fe001fd7a6df89e2710c20123b63c31fa9b99.jsonnew file mode 100644index 0000000000..b5a6895d69--- /dev/null+++ b/.sqlx/query-c5d9dc079f9b708c5aaafcaca95fe001fd7a6df89e2710c20123b63c31fa9b99.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE harness_tokens\n SET revoked_at = now()\n WHERE harness_id = $1 AND revoked_at IS NULL\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "c5d9dc079f9b708c5aaafcaca95fe001fd7a6df89e2710c20123b63c31fa9b99"+}diff --git a/.sqlx/query-ca706ffa9077b59f2cfb7b159c25286e43761bede515094d756ae517cb6d6d75.json b/.sqlx/query-ca706ffa9077b59f2cfb7b159c25286e43761bede515094d756ae517cb6d6d75.jsonnew file mode 100644index 0000000000..df12419592--- /dev/null+++ b/.sqlx/query-ca706ffa9077b59f2cfb7b159c25286e43761bede515094d756ae517cb6d6d75.json@@ -0,0 +1,76 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n id, kind, name, owner_user_id, team_id, created_by,\n created_at, updated_at, last_connected_at, last_disconnected_at\n FROM harnesses\n WHERE deleted_at IS NULL\n AND (\n owner_user_id = $1\n OR team_id IN (SELECT team_id FROM team_user WHERE user_id = $1)\n )\n ORDER BY created_at DESC\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "kind",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "name",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "owner_user_id",+ "type_info": "Text"+ },+ {+ "ordinal": 4,+ "name": "team_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 5,+ "name": "created_by",+ "type_info": "Text"+ },+ {+ "ordinal": 6,+ "name": "created_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 7,+ "name": "updated_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 8,+ "name": "last_connected_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 9,+ "name": "last_disconnected_at",+ "type_info": "Timestamptz"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ false,+ false,+ false,+ true,+ true,+ false,+ false,+ false,+ true,+ true+ ]+ },+ "hash": "ca706ffa9077b59f2cfb7b159c25286e43761bede515094d756ae517cb6d6d75"+}diff --git a/.sqlx/query-ea316ad555009caf25e3a6d8f25ee154f8b0611efbbc2c1e7354c46becbaa476.json b/.sqlx/query-ea316ad555009caf25e3a6d8f25ee154f8b0611efbbc2c1e7354c46becbaa476.jsonnew file mode 100644index 0000000000..2a933bd832--- /dev/null+++ b/.sqlx/query-ea316ad555009caf25e3a6d8f25ee154f8b0611efbbc2c1e7354c46becbaa476.json@@ -0,0 +1,16 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE harness_pairing_requests\n SET status = 'approved', harness_id = $2, approved_by = $3\n WHERE code = $1 AND status = 'pending' AND expires_at > now()\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Uuid",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "ea316ad555009caf25e3a6d8f25ee154f8b0611efbbc2c1e7354c46becbaa476"+}diff --git a/.sqlx/query-f1bfc93ff556e8fc22dbc7788dc5474aa042c379d0f255faa0b487c5480bffcb.json b/.sqlx/query-f1bfc93ff556e8fc22dbc7788dc5474aa042c379d0f255faa0b487c5480bffcb.jsonnew file mode 100644index 0000000000..9512791b63--- /dev/null+++ b/.sqlx/query-f1bfc93ff556e8fc22dbc7788dc5474aa042c379d0f255faa0b487c5480bffcb.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "UPDATE harnesses SET last_connected_at = now() WHERE id = $1",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "f1bfc93ff556e8fc22dbc7788dc5474aa042c379d0f255faa0b487c5480bffcb"+}diff --git a/.sqlx/query-f24bd1d4434b2306156cd933271e4854c541d13bf5f3d22da5f366bf4b1a8639.json b/.sqlx/query-f24bd1d4434b2306156cd933271e4854c541d13bf5f3d22da5f366bf4b1a8639.jsonnew file mode 100644index 0000000000..501b81f4c2--- /dev/null+++ b/.sqlx/query-f24bd1d4434b2306156cd933271e4854c541d13bf5f3d22da5f366bf4b1a8639.json@@ -0,0 +1,20 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO harness_pairing_requests\n (id, code, device_secret_hash, requested_name, host_info, requested_scope,\n expires_at)\n VALUES ($1, $2, $3, $4, $5, $6, $7)\n ON CONFLICT (code) DO NOTHING\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Text",+ "Bytea",+ "Text",+ "Text",+ "Text",+ "Timestamptz"+ ]+ },+ "nullable": []+ },+ "hash": "f24bd1d4434b2306156cd933271e4854c541d13bf5f3d22da5f366bf4b1a8639"+}diff --git a/Cargo.lock b/Cargo.lockindex af3654d768..e0f345a1d6 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -252,6 +252,7 @@ dependencies = ["dashmap","entity_access","futures",+ "harness_id","kafka_util","lexical_client","macro_authorization",@@ -261,6 +262,7 @@ dependencies = ["macro_user_id","macro_uuid","mockall",+ "model_user","pipedream_mcp","reqwest 0.13.4","rootcause",@@ -305,6 +307,7 @@ dependencies = ["database_env_vars","entity_access","github",+ "harness_id","kafka_util","lexical_client","macro_auth",@@ -407,6 +410,7 @@ dependencies = ["dashmap","entity_access","entity_access_db_utils",+ "harness_id","macro_authorization","macro_db_migrator","macro_service_urls",@@ -414,6 +418,7 @@ dependencies = ["macro_uuid","mockall","model-entity",+ "model_user","non_empty","rootcause","serde",@@ -2765,6 +2770,7 @@ dependencies = ["channels","chrono","entity_access",+ "harness_id","hex","macro_authorization","macro_db_migrator",@@ -3539,6 +3545,8 @@ dependencies = ["chrono","clap","dashmap",+ "harness_id",+ "harnesses","macro_event_broker","macro_user_id","macro_uuid",@@ -5096,6 +5104,7 @@ dependencies = ["futures","github","graphql_soup",+ "harnesses","hex","http-body-util","jsonwebtoken 10.3.0",@@ -7326,6 +7335,56 @@ dependencies = ["thiserror 2.0.18",]+[[package]]+name = "harness_id"+version = "0.1.0"+dependencies = [+ "serde",+ "serde_json",+ "sqlx",+ "thiserror 2.0.18",+ "utoipa",+ "uuid",+ "workspace-hack",+]++[[package]]+name = "harness_token"+version = "0.1.0"+dependencies = [+ "sha2 0.10.9",+ "workspace-hack",+]++[[package]]+name = "harnesses"+version = "0.1.0"+dependencies = [+ "anyhow",+ "axum",+ "bot_id",+ "chrono",+ "constant_time_eq",+ "harness_id",+ "harness_token",+ "hex",+ "macro_authorization",+ "macro_db_migrator",+ "macro_user_id",+ "mockall",+ "model-error-response",+ "rand 0.9.4",+ "serde",+ "serde_json",+ "sqlx",+ "thiserror 2.0.18",+ "tokio",+ "tracing",+ "utoipa",+ "uuid",+ "workspace-hack",+]+[[package]]name = "hash32"version = "0.2.1"@@ -9405,6 +9464,8 @@ dependencies = ["bot_token","constant_time_eq","cookie",+ "harness_id",+ "harness_token","http-body-util","jsonwebtoken 10.3.0","macro_auth",diff --git a/Cargo.toml b/Cargo.tomlindex 5ee31efc63..351c26263f 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -45,6 +45,9 @@ members = ["crates/graphql_properties","crates/graphql_soup","crates/graphql_soup_filter_input",+ "crates/harness_id",+ "crates/harness_token",+ "crates/harnesses","crates/import","crates/item_filter_index","crates/integration_tests/local_e2e",diff --git a/apps/docs/AI/bring-your-own.mdx b/apps/docs/AI/bring-your-own.mdxindex 0f3eb4e4ee..e3c11699f4 100644--- a/apps/docs/AI/bring-your-own.mdx+++ b/apps/docs/AI/bring-your-own.mdx@@ -12,10 +12,12 @@ description: "Connect a self-hosted ACP agent harness to Macro with macrod."You can run any [Agent Client Protocol (ACP)](https://zed.dev/acp)-compatible agent harness directly in Macro.-Macro provides `macrod`, a small daemon that runs on your computer and waits for agent sessions. When you start a session or @mention your custom agent, `macrod` launches your configured harness, sends it the prompt, and bridges its ACP connection to Macro.+Macro provides `macrod`, a small daemon that runs on your computer and waits for agent sessions. When you @mention an agent that runs on your harness, `macrod` launches your configured harness, sends it the prompt, and bridges its ACP connection to Macro.++A harness can be **private** (only you can run agents on it) or **team** (any teammate can create agents that run on it).<Warning>- Self-hosted agents can run real commands on your computer. Anyone who can prompt the agent may be able to affect its configured workspace. Use a dedicated workspace and grant channel access carefully.+ Self-hosted agents can run real commands on your computer. Anyone who can prompt an agent bound to your harness may be able to affect its configured workspace. Use a dedicated workspace, grant channel access carefully, and think twice before sharing a harness with your team.</Warning>## Before you start@@ -31,12 +33,6 @@ You need:</Tip><Steps>- <Step title="Create a Macro agent">- Open **Settings → Bots → Create bot**. Enable **Make this bot a coding agent**, choose the channels it can join, and create it.-- Copy the agent token when it appears. Macro shows it only once, but you can create a new one later if you lose it.- </Step>-<Step title="Prepare an agent harness">Install your preferred ACP-compatible agent and identify the command that starts its ACP server. Verify that command before configuring `macrod`.@@ -74,15 +70,16 @@ You need:</Step><Step title="Configure macrod">- Create `macro.toml` beside the `macrod` binary:+ Create `macro.toml` beside the `macrod` binary. No tokens or account details go here - identity comes from pairing in the next step.```toml[macro]api_url = "https://agent-harness.macro.com"storage_url = "https://cloud-storage.macro.com"- owner_user_id = "macro|[email protected]"- bot_token = "mbot_..."- bot_scope = "user"++ [identity]+ # Optional: how this machine shows up in Settings. Defaults to its hostname.+ name = "my-macbook"[server]port = 8790@@ -97,20 +94,30 @@ You need:repo_url = "https://github.com/you/your-repository"```- Change `[email protected]` in `owner_user_id` to the email address you use to sign in to Macro. Replace `mbot_...` with the token from the first step. Set `command` and `args` to the ACP launch command from the second step.+ Set `command` and `args` to the ACP launch command from the first step.</Step>- <Step title="Start the agent">- Keep the HTTPS tunnel running, then start `macrod` from a shell where your harness command is available:+ <Step title="Pair the daemon">+ Start `macrod` from a shell where your harness command is available:```bash./macrod --config ./macro.toml```- When `macrod` reports that it is listening for agent triggers, @mention the agent in one of its Macro channels.+ On first run it prints a pairing code and a link into Macro's **Settings → Harness** page. Open the link, confirm the code matches, choose **Private** or **Team**, and approve. `macrod` picks the credential up automatically and saves it to `macro.credentials.json` next to the config.++ To pair again later (for example after revoking the harness), run `./macrod login`.+ </Step>++ <Step title="Create an agent on your harness">+ Open **Settings → Agents → New agent** and pick your harness under **Harness**. If the harness is shared with your team, teammates can do the same.++ Then @mention the agent in a channel it can reach. `macrod` opens the session and your local harness answers.</Step></Steps>## Keep it connected-Both `macrod` and your HTTPS tunnel must stay running for you to start self-hosted agent sessions from Macro.+Both `macrod` and your HTTPS tunnel must stay running for you to start self-hosted agent sessions from Macro. The **Settings → Harness** page shows whether your daemon is currently connected.++To stop a harness for good, remove it from **Settings → Harness**; that revokes its credential, and the daemon will tell you to run `macrod login` if you start it again.diff --git a/apps/web/src/features/settings/Agents.test.tsx b/apps/web/src/features/settings/Agents.test.tsxindex da39accb0b..57455963bd 100644--- a/apps/web/src/features/settings/Agents.test.tsx+++ b/apps/web/src/features/settings/Agents.test.tsx@@ -50,6 +50,16 @@ vi.mock('@queries/auth/cursor-api-key', () => ({useCursorModelsQuery: () => cursorMocks.models,}));+const harnessMocks = vi.hoisted(() => ({+ query: {+ data: [] as unknown[],+ },+}));++vi.mock('@queries/harnesses/harnesses', () => ({+ useHarnessesQuery: () => harnessMocks.query,+}));+vi.mock('@queries/agents/agents', () => ({useAgentsQuery: () => agentMocks.query,useCreateAgentMutation: () => ({@@ -112,8 +122,21 @@ beforeEach(() => {agentMocks.currentUserId = 'macro|[email protected]';agentMocks.currentTeam = { team: { id: 'team-1' } };agentMocks.isTeamOwner = false;+ harnessMocks.query.data = [];});+const MACROD_HARNESS = {+ id: '3f1c9d2e-8a4b-4c5d-9e6f-1a2b3c4d5e6f',+ kind: 'macrod',+ name: 'Dev box',+ owner: { type: 'user', user_id: 'macro|[email protected]' },+ created_by: 'macro|[email protected]',+ created_at: '2026-08-27T12:00:00Z',+ updated_at: '2026-08-27T12:00:00Z',+ connected: true,+ last_connected_at: '2026-08-27T12:34:00Z',+};+describe('Agents', () => {it('lists the built-in global Macro agent as a team agent', () => {render(() => <Agents />);@@ -513,4 +536,103 @@ describe('Agents', () => {within(defaultModel).getByRole('option', { name: 'Cursor Small' })).toHaveProperty('selected', true);});++ it('offers registered macrod harnesses in the harness picker', () => {+ harnessMocks.query.data = [MACROD_HARNESS];++ render(() => <Agents />);+ fireEvent.click(screen.getByRole('button', { name: 'Create agent' }));++ const dialog = screen.getByRole('dialog');+ const harness = within(dialog).getByLabelText('Harness');+ expect(within(harness).getAllByRole('option')).toHaveLength(2);+ expect(+ within(harness).getByRole('option', { name: 'Dev box' })+ ).toBeTruthy();+ });++ it('swaps the model select for a free-text input seeded with default for macrod harnesses', () => {+ harnessMocks.query.data = [MACROD_HARNESS];++ render(() => <Agents />);+ fireEvent.click(screen.getByRole('button', { name: 'Create agent' }));++ const dialog = screen.getByRole('dialog');+ const harness = within(dialog).getByLabelText('Harness');+ fireEvent.change(harness, { target: { value: MACROD_HARNESS.id } });++ const defaultModel = within(dialog).getByLabelText('Default model');+ expect(defaultModel.tagName).toBe('INPUT');+ expect(defaultModel).toHaveProperty('value', 'default');+ });++ it('submits macrod agents with the macrod slug and harness id', async () => {+ harnessMocks.query.data = [MACROD_HARNESS];++ render(() => <Agents />);+ fireEvent.click(screen.getByRole('button', { name: 'Create agent' }));++ const dialog = screen.getByRole('dialog');+ fireEvent.input(within(dialog).getByLabelText('Name'), {+ target: { value: 'Bug fixer' },+ });+ fireEvent.change(within(dialog).getByLabelText('Harness'), {+ target: { value: MACROD_HARNESS.id },+ });+ fireEvent.click(+ within(dialog).getByRole('button', { name: 'Create agent' })+ );++ await waitFor(() => {+ expect(agentMocks.create).toHaveBeenCalledWith({+ avatarUrl: undefined,+ channelIds: [],+ channelScope: 'all',+ defaultModel: 'default',+ handle: 'bug-fixer',+ harness: 'macrod',+ harnessId: MACROD_HARNESS.id,+ name: 'Bug fixer',+ instructions: '',+ teamId: undefined,+ });+ });+ });++ it('preselects the bound macrod harness when editing', () => {+ harnessMocks.query.data = [MACROD_HARNESS];+ agentMocks.query.data = [+ {+ bot: {+ id: 'agent-1',+ kind: 'owned',+ owner: { type: 'user', user_id: 'macro|[email protected]' },+ name: 'Bug fixer',+ handle: 'bug-fixer',+ description: 'Finds and fixes bugs.',+ has_agent: true,+ created_at: '2026-08-27T12:00:00Z',+ updated_at: '2026-08-27T12:00:00Z',+ },+ instructions: 'Fix the root cause.',+ harness: 'macrod',+ harness_id: MACROD_HARNESS.id,+ default_model: 'default',+ channel_scope: 'all',+ channel_ids: [],+ },+ ];++ render(() => <Agents />);+ fireEvent.click(screen.getByRole('button', { name: 'Edit Bug fixer' }));++ const dialog = screen.getByRole('dialog');+ expect(within(dialog).getByLabelText('Harness')).toHaveProperty(+ 'value',+ MACROD_HARNESS.id+ );+ const defaultModel = within(dialog).getByLabelText('Default model');+ expect(defaultModel.tagName).toBe('INPUT');+ expect(defaultModel).toHaveProperty('value', 'default');+ });});diff --git a/apps/web/src/features/settings/Agents.tsx b/apps/web/src/features/settings/Agents.tsxindex a895c309ac..eb02f71007 100644--- a/apps/web/src/features/settings/Agents.tsx+++ b/apps/web/src/features/settings/Agents.tsx@@ -11,6 +11,7 @@ import TrashIcon from '@phosphor/trash.svg';import UploadIcon from '@phosphor/upload-simple.svg';import XIcon from '@phosphor/x.svg';import {+ type AgentWithHarnessId,type CreateAgentParams,useAgentsQuery,useCreateAgentMutation,@@ -21,14 +22,19 @@ import {useCursorApiKeyStatusQuery,useCursorModelsQuery,} from '@queries/auth/cursor-api-key';+import { useHarnessesQuery } from '@queries/harnesses/harnesses';import { useCurrentTeamQuery, useIsTeamOwner } from '@queries/team/teams';-import type { Agent } from '@service-storage/generated/schemas/agent';import { Avatar, Button, Dialog, Panel } from '@ui';import { createMemo, createSignal, For, Show } from 'solid-js';import { botAssignableChannelOptions } from '../channel/Bots/botChannelOptions';import { canDeleteBot } from '../channel/Bots/botPermissions';import { ChannelMultiSelect } from '../channel/Bots/ChannelMultiSelect';-import { SettingsCard, SettingsPage, SettingsSection } from './primitives';+import {+ ChoiceRow,+ SettingsCard,+ SettingsPage,+ SettingsSection,+} from './primitives';type AgentShare = 'Private' | 'Team';type ChannelMode = 'all' | 'selected';@@ -43,7 +49,7 @@ type AgentSummary = {defaultModel: string;channelSummary: string;share: AgentShare;- persistedAgent?: Agent;+ persistedAgent?: AgentWithHarnessId;editable?: boolean;};@@ -51,6 +57,8 @@ type ConnectedHarness = {id: string;name: string;models: readonly HarnessModel[];+ kind: 'builtin' | 'macrod';+ connected?: boolean;};type HarnessModel = {@@ -66,6 +74,7 @@ const IN_MEMORY_HARNESS: ConnectedHarness = {models: [Model.sonnet5, Model.opus5, Model.haiku45, Model.gpt56].map((model) => ({ id: model, name: MODEL_PRETTYNAME[model] })),+ kind: 'builtin',};const MACRO_AGENT: AgentSummary = {@@ -82,8 +91,8 @@ const MACRO_AGENT: AgentSummary = {/** Settings page for viewing and creating persistent agents. */export function Agents() {const [creating, setCreating] = createSignal(false);- const [editingAgent, setEditingAgent] = createSignal<Agent>();- const [deletingAgent, setDeletingAgent] = createSignal<Agent>();+ const [editingAgent, setEditingAgent] = createSignal<AgentWithHarnessId>();+ const [deletingAgent, setDeletingAgent] = createSignal<AgentWithHarnessId>();const channelsContext = useChannelsContext();const currentUserId = useUserId();const agentsQuery = useAgentsQuery();@@ -95,6 +104,7 @@ export function Agents() {const cursorStatus = useCursorApiKeyStatusQuery();const cursorConnected = () => cursorStatus.data?.registered ?? false;const cursorModels = useCursorModelsQuery(cursorConnected);+ const harnessesQuery = useHarnessesQuery();const connectedHarnesses = (): readonly ConnectedHarness[] => [IN_MEMORY_HARNESS,...(cursorConnected()@@ -106,20 +116,29 @@ export function Agents() {id: model.id,name: model.displayName,})),+ kind: 'builtin' as const,},]: []),+ ...(harnessesQuery.data ?? []).map((harness) => ({+ id: harness.id,+ name:+ harness.owner.type === 'team' ? `${harness.name} · Team` : harness.name,+ models: [],+ kind: 'macrod' as const,+ connected: harness.connected,+ })),];const channelOptions = createMemo(() =>botAssignableChannelOptions(channelsContext.channels()));const currentTeamId = () => currentTeamQuery.data?.team.id;const canShareWithTeam = () => currentTeamId() !== undefined;- const isAgentCreator = (agent: Agent) =>+ const isAgentCreator = (agent: AgentWithHarnessId) =>agent.bot.created_by === currentUserId();- const canMakePrivate = (agent: Agent) =>+ const canMakePrivate = (agent: AgentWithHarnessId) =>agent.bot.owner?.type !== 'team' || isAgentCreator(agent);- const canDeleteAgent = (agent: Agent) =>+ const canDeleteAgent = (agent: AgentWithHarnessId) =>canDeleteBot(agent.bot, currentUserId(), currentTeamId(), isTeamOwner());const agents = createMemo(() =>(agentsQuery.data ?? []).map((agent) =>@@ -299,11 +318,12 @@ export function Agents() {}function summarizeAgent(- agent: Agent,+ agent: AgentWithHarnessId,harnesses: readonly ConnectedHarness[],channels: readonly ChannelOption[]): AgentSummary {- const harness = harnesses.find((option) => option.id === agent.harness);+ const harnessKey = agent.harness_id ?? agent.harness;+ const harness = harnesses.find((option) => option.id === harnessKey);const model = harness?.models.find((option) => option.id === agent.default_model);@@ -323,7 +343,7 @@ function summarizeAgent(tag: agent.bot.handle,avatarUrl: agent.bot.avatar_url ?? undefined,instructions: agent.instructions,- harness: harness?.name ?? harnessName(agent.harness),+ harness: harness?.name ?? harnessName(harnessKey),defaultModel: model?.name ?? agent.default_model,channelSummary,share: agent.bot.owner?.type === 'team' ? 'Team' : 'Private',@@ -335,7 +355,9 @@ function summarizeAgent(function harnessName(id: string): string {if (id === 'in-memory') return 'In-memory';if (id === 'cursor') return 'Cursor';- return id;+ // Any other id is a registered macrod harness uuid; if it is not in the+ // connected list any more, the harness has been removed.+ return 'Disconnected harness';}function AgentRow(props: {@@ -473,7 +495,7 @@ function AgentDeleteDialog(props: {}function AgentDialog(props: {- agent?: Agent;+ agent?: AgentWithHarnessId;connectedHarnesses: readonly ConnectedHarness[];currentTeamId?: string;canShareWithTeam: boolean;@@ -492,7 +514,10 @@ function AgentDialog(props: {props.agent?.instructions ?? '');const [harnessId, setHarnessId] = createSignal(- props.agent?.harness ?? props.connectedHarnesses[0]?.id ?? ''+ props.agent?.harness_id ??+ props.agent?.harness ??+ props.connectedHarnesses[0]?.id ??+ '');const selectedHarness = () =>props.connectedHarnesses.find((harness) => harness.id === harnessId());@@ -522,7 +547,10 @@ function AgentDialog(props: {const handleHarnessChange = (id: string) => {setHarnessId(id);const harness = props.connectedHarnesses.find((option) => option.id === id);- setDefaultModelId(harness?.models[0]?.id ?? '');+ // macrod treats 'default' as "use the harness's own configured model".+ setDefaultModelId(+ harness?.kind === 'macrod' ? 'default' : (harness?.models[0]?.id ?? '')+ );};const handleAvatarInput = (file: File | undefined) => {@@ -554,13 +582,17 @@ function AgentDialog(props: {const submit = async () => {if (!canCreate()) return;+ const harness = selectedHarness();const saved = await props.onSave({avatarUrl: avatarUrl(),channelIds: channelMode() === 'all' ? [] : selectedChannelIds(),channelScope: channelMode(),defaultModel: selectedDefaultModelId(),handle: slugAgentTag(tag()),- harness: selectedHarness()?.id ?? '',+ // Registered macrod harnesses send the 'macrod' slug plus their uuid;+ // built-ins keep sending their own slug with no harness id.+ harness: harness?.kind === 'macrod' ? 'macrod' : (harness?.id ?? ''),+ harnessId: harness?.kind === 'macrod' ? harness.id : undefined,name: name().trim(),instructions: instructions().trim(),teamId: selectedTeamId(),@@ -722,24 +754,38 @@ function AgentDialog(props: {<span class="text-xs font-medium text-ink">Default model</span>- <select- class="settings-input w-full"- value={selectedDefaultModelId()}- onChange={(event) =>- setDefaultModelId(event.currentTarget.value)+ <Show+ when={selectedHarness()?.kind === 'macrod'}+ fallback={+ <select+ class="settings-input w-full"+ value={selectedDefaultModelId()}+ onChange={(event) =>+ setDefaultModelId(event.currentTarget.value)+ }+ >+ <For each={selectedHarness()?.models ?? []}>+ {(model) => (+ <option+ value={model.id}+ selected={model.id === selectedDefaultModelId()}+ >+ {model.name}+ </option>+ )}+ </For>+ </select>}>- <For each={selectedHarness()?.models ?? []}>- {(model) => (- <option- value={model.id}- selected={model.id === selectedDefaultModelId()}- >- {model.name}- </option>- )}- </For>- </select>+ <input+ class="settings-input w-full"+ placeholder="default"+ value={defaultModelId()}+ onInput={(event) =>+ setDefaultModelId(event.currentTarget.value)+ }+ />+ </Show></label></div></AgentFormSection>@@ -864,43 +910,6 @@ function AgentFormSection(props: {);}-function ChoiceRow(props: {- name: string;- value: string;- checked: boolean;- title: string;- description: string;- disabled?: boolean;- onChange: () => void;-}) {- return (- <label- class="flex min-w-0 items-start gap-3 rounded-lg border border-edge-muted p-3 has-checked:border-accent has-checked:bg-accent-bg"- classList={{- 'cursor-not-allowed opacity-50': props.disabled,- 'cursor-pointer': !props.disabled,- }}- >- <input- type="radio"- name={props.name}- value={props.value}- checked={props.checked}- disabled={props.disabled}- onChange={props.onChange}- aria-label={props.title}- class="mt-0.5 accent-accent"- />- <span class="min-w-0">- <span class="block text-sm font-medium text-ink">{props.title}</span>- <span class="mt-0.5 block text-xs text-ink-muted">- {props.description}- </span>- </span>- </label>- );-}-function slugAgentTag(value: string): string {return value.toLowerCase()diff --git a/apps/web/src/features/settings/Harness.test.tsx b/apps/web/src/features/settings/Harness.test.tsxindex d11ef8edd8..774a01b290 100644--- a/apps/web/src/features/settings/Harness.test.tsx+++ b/apps/web/src/features/settings/Harness.test.tsx@@ -2,8 +2,14 @@* @vitest-environment jsdom*/-import { fireEvent, render, screen, waitFor } from '@solidjs/testing-library';-import { beforeEach, describe, expect, it, vi } from 'vitest';+import {+ fireEvent,+ render,+ screen,+ waitFor,+ within,+} from '@solidjs/testing-library';+import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';import { Harness } from './Harness';const mocks = vi.hoisted(() => ({@@ -27,6 +33,28 @@ const mocks = vi.hoisted(() => ({toastFailure: vi.fn(),}));+const harnessMocks = vi.hoisted(() => ({+ query: {+ data: [] as unknown[],+ isError: false,+ },+ deleteHarness: vi.fn(),+ approve: vi.fn(),+ pairing: {+ data: {+ code: 'KX7M-4QHD',+ requested_name: 'Dev laptop',+ requested_scope: null,+ host: 'erics-mbp.local',+ created_at: '2026-08-27T12:00:00Z',+ expires_at: new Date(Date.now() + 10 * 60_000).toISOString(),+ },+ isError: false,+ },+ searchParams: { pair: undefined as string | undefined },+ setSearchParams: vi.fn(),+}));+vi.mock('@queries/auth/cursor-api-key', () => ({useCursorApiKeyStatusQuery: () => mocks.status,useSaveCursorApiKey: () => ({@@ -44,6 +72,43 @@ vi.mock('@queries/auth/cursor-api-key', () => ({}),}));+vi.mock('@queries/harnesses/harnesses', () => ({+ useHarnessesQuery: () => harnessMocks.query,+ useDeleteHarnessMutation: () => ({+ mutateAsync: harnessMocks.deleteHarness,+ isPending: false,+ }),+ useHarnessPairingQuery: (code: () => string | undefined) => ({+ get data() {+ return code() && !harnessMocks.pairing.isError+ ? harnessMocks.pairing.data+ : undefined;+ },+ get isError() {+ return Boolean(code()) && harnessMocks.pairing.isError;+ },+ get error() {+ return harnessMocks.pairing.isError ? new Error('gone') : null;+ },+ }),+ useApproveHarnessPairingMutation: () => ({+ mutateAsync: harnessMocks.approve,+ isPending: false,+ }),+ invalidateHarnesses: vi.fn(),+}));++vi.mock('@queries/team/teams', () => ({+ useCurrentTeamQuery: () => ({ data: { team: { id: 'team-1' } } }),+}));++vi.mock('@solidjs/router', () => ({+ useSearchParams: () => [+ harnessMocks.searchParams,+ harnessMocks.setSearchParams,+ ],+}));+vi.mock('@core/component/Toast/Toast', () => ({toast: {success: mocks.toastSuccess,@@ -51,6 +116,22 @@ vi.mock('@core/component/Toast/Toast', () => ({},}));+const REGISTERED_HARNESS = {+ id: '3f1c9d2e-8a4b-4c5d-9e6f-1a2b3c4d5e6f',+ kind: 'macrod',+ name: 'Dev box',+ owner: { type: 'team', team_id: 'team-1' },+ created_by: 'macro|[email protected]',+ created_at: '2026-08-27T12:00:00Z',+ updated_at: '2026-08-27T12:00:00Z',+ connected: true,+ last_connected_at: '2026-08-27T12:34:00Z',+};++beforeAll(() => {+ vi.stubGlobal('scrollTo', vi.fn());+});+beforeEach(() => {vi.clearAllMocks();mocks.status.data = {@@ -61,6 +142,12 @@ beforeEach(() => {mocks.status.isPlaceholderData = false;mocks.save.mockResolvedValue(undefined);mocks.disconnect.mockResolvedValue(undefined);+ harnessMocks.query.data = [];+ harnessMocks.query.isError = false;+ harnessMocks.pairing.isError = false;+ harnessMocks.deleteHarness.mockResolvedValue(undefined);+ harnessMocks.approve.mockResolvedValue(REGISTERED_HARNESS);+ harnessMocks.searchParams.pair = undefined;});describe('Harness', () => {@@ -149,4 +236,81 @@ describe('Harness', () => {'https://docs.macro.com/AI/bring-your-own');});++ it('offers "Enter pairing code" in the header and empty state', () => {+ render(() => <Harness />);++ expect(+ screen.getAllByRole('button', { name: 'Enter pairing code' })+ ).toHaveLength(2);+ });++ it('renders a registered harness row', () => {+ harnessMocks.query.data = [REGISTERED_HARNESS];++ render(() => <Harness />);++ expect(screen.getByText('Dev box')).toBeTruthy();+ expect(screen.getByText('Team')).toBeTruthy();+ expect(screen.getByRole('img', { name: 'Connected' })).toBeTruthy();+ expect(screen.getByText(/Last connected /)).toBeTruthy();+ expect(screen.queryByText('Never connected')).toBeNull();+ });++ it('shows a disconnected private harness that never connected', () => {+ harnessMocks.query.data = [+ {+ ...REGISTERED_HARNESS,+ owner: { type: 'user', user_id: 'macro|[email protected]' },+ connected: false,+ last_connected_at: null,+ },+ ];++ render(() => <Harness />);++ expect(screen.getByText('Private')).toBeTruthy();+ expect(screen.getByRole('img', { name: 'Disconnected' })).toBeTruthy();+ expect(screen.getByText('Never connected')).toBeTruthy();+ });++ it('confirms before removing a harness', async () => {+ harnessMocks.query.data = [REGISTERED_HARNESS];++ render(() => <Harness />);+ fireEvent.click(screen.getByRole('button', { name: 'Remove' }));++ const dialog = screen.getByRole('dialog');+ expect(within(dialog).getByText('Remove Dev box?')).toBeTruthy();+ expect(+ within(dialog).getByText(/Agents using this harness will stop running/)+ ).toBeTruthy();+ expect(harnessMocks.deleteHarness).not.toHaveBeenCalled();++ fireEvent.click(+ within(dialog).getByRole('button', { name: 'Remove harness' })+ );++ await waitFor(() => {+ expect(harnessMocks.deleteHarness).toHaveBeenCalledWith({+ harnessId: REGISTERED_HARNESS.id,+ });+ expect(mocks.toastSuccess).toHaveBeenCalledWith('Harness removed');+ expect(screen.queryByRole('dialog')).toBeNull();+ });+ });++ it('opens the pairing dialog prefilled from the pair search param', async () => {+ harnessMocks.searchParams.pair = 'KX7M-4QHD';++ render(() => <Harness />);++ const dialog = screen.getByRole('dialog');+ expect(within(dialog).getByText('KX7M-4QHD')).toBeTruthy();+ expect(within(dialog).getByText('Dev laptop')).toBeTruthy();+ expect(harnessMocks.setSearchParams).toHaveBeenCalledWith(+ { pair: undefined },+ { replace: true }+ );+ });});diff --git a/apps/web/src/features/settings/Harness.tsx b/apps/web/src/features/settings/Harness.tsxindex 1a5077abe9..7435fc65c7 100644--- a/apps/web/src/features/settings/Harness.tsx+++ b/apps/web/src/features/settings/Harness.tsx@@ -11,26 +11,31 @@ import {useSaveCursorApiKey,useSetCursorDefaultModel,} from '@queries/auth/cursor-api-key';-import { Button } from '@ui';-import { createSignal, For, type JSX, Show } from 'solid-js';+import {+ useDeleteHarnessMutation,+ useHarnessesQuery,+} from '@queries/harnesses/harnesses';+import type { Harness as RegisteredHarness } from '@service-storage/client';+import { useSearchParams } from '@solidjs/router';+import { Button, Dialog, Panel } from '@ui';+import { createSignal, For, type JSX, onMount, Show } from 'solid-js';+import { HarnessPairingDialog } from './HarnessPairingDialog';+import { ConnectAction, StatusDot } from './integration-ui';import { SettingsCard, SettingsPage } from './primitives';const BYOA_DOCS_URL = 'https://docs.macro.com/AI/bring-your-own';const CURSOR_KEY_PREFIX = 'crsr_';-type ConnectedAgent = {- id: string;- name: string;- description: string;-};--// Connected-agent data will replace this empty list when BYOA is wired up.-const connectedAgents: ConnectedAgent[] = [];-function failureMessage(error: unknown, fallback: string): string {return (error instanceof ThrownResultError && error.message) || fallback;}+function lastConnectedText(harness: RegisteredHarness): string {+ return harness.last_connected_at+ ? `Last connected ${new Date(harness.last_connected_at).toLocaleString()}`+ : 'Never connected';+}+/** Settings UI for choosing and configuring the available agent harnesses. */export function Harness() {const [cursorApiKey, setCursorApiKey] = createSignal('');@@ -38,6 +43,35 @@ export function Harness() {const saveCursorApiKey = useSaveCursorApiKey();const disconnectCursor = useDisconnectCursorApiKey();const cursorRegistered = () => cursorStatus.data?.registered ?? false;+ const harnessesQuery = useHarnessesQuery();+ const deleteHarnessMutation = useDeleteHarnessMutation();+ const [pairingDialog, setPairingDialog] = createSignal<{+ initialCode?: string;+ }>();+ const [removingHarness, setRemovingHarness] =+ createSignal<RegisteredHarness>();+ const [searchParams, setSearchParams] = useSearchParams();++ onMount(() => {+ const pair = searchParams.pair;+ if (typeof pair === 'string' && pair.length > 0) {+ setPairingDialog({ initialCode: pair });+ setSearchParams({ pair: undefined }, { replace: true });+ }+ });++ const removeHarness = async () => {+ const current = removingHarness();+ if (!current) return;++ try {+ await deleteHarnessMutation.mutateAsync({ harnessId: current.id });+ setRemovingHarness(undefined);+ toast.success('Harness removed');+ } catch (error) {+ toast.failure(failureMessage(error, 'Failed to remove harness'));+ }+ };// Only worth fetching once there is a key to ask Cursor through.const cursorModels = useCursorModelsQuery(cursorRegistered);@@ -229,15 +263,26 @@ export function Harness() {<div class="min-w-0 flex-1"><div class="flex items-center justify-between gap-4"><h2 class="text-sm font-medium text-ink">Bring your own agent</h2>- <a- href={BYOA_DOCS_URL}- target="_blank"- rel="noopener noreferrer"- class="inline-flex shrink-0 items-center gap-1.5 rounded-md px-2 py-1 text-sm font-medium text-ink-muted outline-none transition-colors hover:bg-ink/4 hover:text-ink focus-visible:bg-ink/6"- >- Setup guide- <ArrowUpRightIcon class="size-3.5 opacity-70" />- </a>+ <div class="flex shrink-0 items-center gap-1">+ <Button+ type="button"+ variant="outline"+ size="sm"+ depth={3}+ onClick={() => setPairingDialog({})}+ >+ Enter pairing code+ </Button>+ <a+ href={BYOA_DOCS_URL}+ target="_blank"+ rel="noopener noreferrer"+ class="inline-flex shrink-0 items-center gap-1.5 rounded-md px-2 py-1 text-sm font-medium text-ink-muted outline-none transition-colors hover:bg-ink/4 hover:text-ink focus-visible:bg-ink/6"+ >+ Setup guide+ <ArrowUpRightIcon class="size-3.5 opacity-70" />+ </a>+ </div></div><p class="mt-1 text-sm text-ink-muted">Install macrod on your computer to connect Claude or another@@ -249,36 +294,138 @@ export function Harness() {Connected agents</div><For- each={connectedAgents}+ each={harnessesQuery.data ?? []}fallback={<div class="flex flex-col items-center py-6 text-center"><p class="text-sm text-ink">No agents connected</p><p class="mt-1 text-xs text-ink-extra-muted">Agents connected through macrod will appear here.</p>+ <Button+ type="button"+ variant="outline"+ size="sm"+ depth={3}+ class="mt-3"+ onClick={() => setPairingDialog({})}+ >+ Enter pairing code+ </Button></div>}>- {(agent) => (+ {(harness) => (<div class="flex items-center justify-between gap-4 px-4 py-3"><div class="min-w-0">- <p class="truncate text-sm text-ink">{agent.name}</p>- <p class="truncate text-xs text-ink-extra-muted">- {agent.description}+ <div class="flex min-w-0 items-center gap-2">+ <p class="truncate text-sm text-ink">{harness.name}</p>+ <span class="shrink-0 rounded-full border border-edge-muted px-2 py-0.5 text-xxs font-medium uppercase text-ink-extra-muted">+ {harness.owner.type === 'team' ? 'Team' : 'Private'}+ </span>+ <StatusDot+ state={+ harness.connected ? 'connected' : 'disconnected'+ }+ label={+ harness.connected ? 'Connected' : 'Disconnected'+ }+ />+ </div>+ <p class="mt-0.5 truncate text-xs text-ink-extra-muted">+ {lastConnectedText(harness)}</p></div>- <span class="text-xs text-success">Connected</span>+ <ConnectAction+ label="Remove"+ variant="danger"+ onClick={() => setRemovingHarness(harness)}+ /></div>)}</For>+ <Show when={harnessesQuery.isError}>+ <p class="px-4 py-3 text-xs text-negative">+ Could not load your harnesses. Try refreshing this page.+ </p>+ </Show></div></div></section></SettingsCard>++ <Show when={pairingDialog()} keyed>+ {(dialog) => (+ <HarnessPairingDialog+ initialCode={dialog.initialCode}+ onClose={() => setPairingDialog(undefined)}+ />+ )}+ </Show>+ <Show when={removingHarness()} keyed>+ {(harness) => (+ <HarnessRemoveDialog+ harnessName={harness.name}+ pending={deleteHarnessMutation.isPending}+ onClose={() => setRemovingHarness(undefined)}+ onConfirm={() => void removeHarness()}+ />+ )}+ </Show></SettingsPage>);}+function HarnessRemoveDialog(props: {+ harnessName: string;+ pending: boolean;+ onClose: () => void;+ onConfirm: () => void;+}) {+ return (+ <Dialog+ open+ onOpenChange={(open) => !open && !props.pending && props.onClose()}+ position="center"+ visibleScrim+ class="w-[min(480px,calc(100vw-16px))]"+ >+ <Panel depth={2} class="rounded-xl text-ink">+ <Panel.Header class="px-5 py-3">+ <Dialog.Title class="text-sm font-semibold">+ Remove {props.harnessName}?+ </Dialog.Title>+ </Panel.Header>+ <Panel.Body class="p-5">+ <Dialog.Description class="text-sm leading-5 text-ink-muted">+ Agents using this harness will stop running until it's reconnected.+ macrod on that machine will need to pair again.+ </Dialog.Description>+ </Panel.Body>+ <Panel.Footer class="justify-end gap-2 px-5 py-3">+ <Button+ type="button"+ variant="ghost"+ size="sm"+ disabled={props.pending}+ onClick={props.onClose}+ >+ Cancel+ </Button>+ <Button+ type="button"+ variant="danger"+ size="sm"+ disabled={props.pending}+ onClick={props.onConfirm}+ >+ {props.pending ? 'Removing…' : 'Remove harness'}+ </Button>+ </Panel.Footer>+ </Panel>+ </Dialog>+ );+}+function HarnessIcon(props: { children: JSX.Element }) {return (<div class="flex size-9 shrink-0 items-center justify-center rounded-lg bg-ink/4 text-ink-muted [&_svg]:size-5">diff --git a/apps/web/src/features/settings/HarnessPairingDialog.test.tsx b/apps/web/src/features/settings/HarnessPairingDialog.test.tsxnew file mode 100644index 0000000000..5f529ac3d3--- /dev/null+++ b/apps/web/src/features/settings/HarnessPairingDialog.test.tsx@@ -0,0 +1,195 @@+/**+ * @vitest-environment jsdom+ */++import {+ fireEvent,+ render,+ screen,+ waitFor,+ within,+} from '@solidjs/testing-library';+import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';+import { HarnessPairingDialog } from './HarnessPairingDialog';++const mocks = vi.hoisted(() => ({+ pairing: {+ data: {+ code: 'KX7M-4QHD',+ requested_name: 'Dev laptop',+ requested_scope: null,+ host: 'erics-mbp.local',+ created_at: '2026-08-27T12:00:00Z',+ expires_at: new Date(Date.now() + 10 * 60_000).toISOString(),+ },+ isError: false,+ },+ approve: vi.fn(),+ toastSuccess: vi.fn(),+ toastFailure: vi.fn(),+ currentTeam: { team: { id: 'team-1' } } as { team: { id: string } } | null,+}));++vi.mock('@queries/harnesses/harnesses', () => ({+ useHarnessPairingQuery: (code: () => string | undefined) => ({+ get data() {+ return code() && !mocks.pairing.isError ? mocks.pairing.data : undefined;+ },+ get isError() {+ return Boolean(code()) && mocks.pairing.isError;+ },+ get error() {+ return mocks.pairing.isError ? new Error('gone') : null;+ },+ }),+ useApproveHarnessPairingMutation: () => ({+ mutateAsync: mocks.approve,+ isPending: false,+ }),+}));++vi.mock('@queries/team/teams', () => ({+ useCurrentTeamQuery: () => ({ data: mocks.currentTeam }),+}));++vi.mock('@core/component/Toast/Toast', () => ({+ toast: {+ success: mocks.toastSuccess,+ failure: mocks.toastFailure,+ },+}));++beforeAll(() => {+ vi.stubGlobal('scrollTo', vi.fn());+});++beforeEach(() => {+ vi.clearAllMocks();+ mocks.pairing.isError = false;+ mocks.approve.mockResolvedValue({ id: 'harness-1' });+ mocks.currentTeam = { team: { id: 'team-1' } };+});++describe('HarnessPairingDialog', () => {+ it('looks up a typed code and shows the pairing request', () => {+ render(() => <HarnessPairingDialog onClose={() => {}} />);++ const dialog = screen.getByRole('dialog');+ const codeInput = within(dialog).getByLabelText('Pairing code');+ fireEvent.input(codeInput, { target: { value: 'kx7m-4qhd' } });+ expect(codeInput).toHaveProperty('value', 'KX7M-4QHD');++ fireEvent.click(within(dialog).getByRole('button', { name: 'Look up' }));++ expect(within(dialog).getByText('KX7M-4QHD')).toBeTruthy();+ expect(+ within(dialog).getByText(/Confirm this matches the code macrod printed/)+ ).toBeTruthy();+ expect(within(dialog).getByText('Dev laptop')).toBeTruthy();+ expect(within(dialog).getByText('erics-mbp.local')).toBeTruthy();+ expect(within(dialog).getByText(/Expires in \d+ minutes/)).toBeTruthy();+ expect(within(dialog).getByLabelText('Name')).toHaveProperty(+ 'value',+ 'Dev laptop'+ );+ });++ it('approves a private harness without a team id', async () => {+ render(() => (+ <HarnessPairingDialog initialCode="KX7M-4QHD" onClose={() => {}} />+ ));++ const dialog = screen.getByRole('dialog');+ fireEvent.input(within(dialog).getByLabelText('Name'), {+ target: { value: 'Home desktop' },+ });+ fireEvent.click(within(dialog).getByRole('button', { name: 'Approve' }));++ await waitFor(() => {+ expect(mocks.approve).toHaveBeenCalledWith({+ code: 'KX7M-4QHD',+ name: 'Home desktop',+ teamId: undefined,+ });+ expect(mocks.toastSuccess).toHaveBeenCalledWith('Harness connected');+ });+ });++ it('approves a team harness with the current team id', async () => {+ render(() => (+ <HarnessPairingDialog initialCode="KX7M-4QHD" onClose={() => {}} />+ ));++ const dialog = screen.getByRole('dialog');+ fireEvent.click(within(dialog).getByLabelText('Team'));+ fireEvent.click(within(dialog).getByRole('button', { name: 'Approve' }));++ await waitFor(() => {+ expect(mocks.approve).toHaveBeenCalledWith({+ code: 'KX7M-4QHD',+ name: 'Dev laptop',+ teamId: 'team-1',+ });+ });+ });++ it('disables the Team choice without a team', () => {+ mocks.currentTeam = null;++ render(() => (+ <HarnessPairingDialog initialCode="KX7M-4QHD" onClose={() => {}} />+ ));++ const dialog = screen.getByRole('dialog');+ expect(within(dialog).getByLabelText('Team')).toHaveProperty(+ 'disabled',+ true+ );+ expect(+ within(dialog).getByText(+ 'Create or join a team before sharing harnesses.'+ )+ ).toBeTruthy();+ });++ it('shows the invalid-code copy when the lookup fails', () => {+ mocks.pairing.isError = true;++ render(() => (+ <HarnessPairingDialog initialCode="KX7M-4QHD" onClose={() => {}} />+ ));++ const dialog = screen.getByRole('dialog');+ expect(+ within(dialog).getByText(+ 'This pairing code is invalid, expired, or already claimed.'+ )+ ).toBeTruthy();++ fireEvent.click(+ within(dialog).getByRole('button', { name: 'Try another code' })+ );+ expect(within(dialog).getByLabelText('Pairing code')).toBeTruthy();+ });++ it('shows the success phase after approving', async () => {+ const onClose = vi.fn();+ render(() => (+ <HarnessPairingDialog initialCode="KX7M-4QHD" onClose={onClose} />+ ));++ const dialog = screen.getByRole('dialog');+ fireEvent.click(within(dialog).getByRole('button', { name: 'Approve' }));++ await waitFor(() => {+ expect(+ within(dialog).getByText(+ 'Harness connected. macrod will finish pairing automatically.'+ )+ ).toBeTruthy();+ });++ fireEvent.click(within(dialog).getByRole('button', { name: 'Done' }));+ expect(onClose).toHaveBeenCalledOnce();+ });+});diff --git a/apps/web/src/features/settings/HarnessPairingDialog.tsx b/apps/web/src/features/settings/HarnessPairingDialog.tsxnew file mode 100644index 0000000000..461c3d1e1f--- /dev/null+++ b/apps/web/src/features/settings/HarnessPairingDialog.tsx@@ -0,0 +1,344 @@+import { toast } from '@core/component/Toast/Toast';+import { ThrownResultError } from '@core/util/result';+import {+ useApproveHarnessPairingMutation,+ useHarnessPairingQuery,+} from '@queries/harnesses/harnesses';+import { useCurrentTeamQuery } from '@queries/team/teams';+import { Button, Dialog, Panel } from '@ui';+import { createEffect, createSignal, Match, Show, Switch } from 'solid-js';+import { ChoiceRow } from './primitives';++const PAIRING_ERROR_FALLBACK =+ 'This pairing code is invalid, expired, or already claimed.';++type HarnessShare = 'Private' | 'Team';++function failureMessage(error: unknown, fallback: string): string {+ return (error instanceof ThrownResultError && error.message) || fallback;+}++function expiresInMinutes(expiresAt: string): number {+ return Math.max(+ 0,+ Math.round((new Date(expiresAt).getTime() - Date.now()) / 60_000)+ );+}++/**+ * Dialog that walks the user through approving a macrod pairing request:+ * enter the printed code, review the request, and approve it as a private or+ * team harness.+ */+export function HarnessPairingDialog(props: {+ initialCode?: string;+ onClose: () => void;+}) {+ const [codeInput, setCodeInput] = createSignal(props.initialCode ?? '');+ const [committedCode, setCommittedCode] = createSignal<string | undefined>(+ props.initialCode || undefined+ );+ const [approved, setApproved] = createSignal(false);+ const [approveError, setApproveError] = createSignal<string>();+ const [name, setName] = createSignal('');+ const [nameEdited, setNameEdited] = createSignal(false);+ const [share, setShare] = createSignal<HarnessShare>('Private');+ const [shareEdited, setShareEdited] = createSignal(false);++ const pairingQuery = useHarnessPairingQuery(committedCode);+ const approveMutation = useApproveHarnessPairingMutation();+ const currentTeamQuery = useCurrentTeamQuery();+ const currentTeamId = () => currentTeamQuery.data?.team.id;+ const canShareWithTeam = () => currentTeamId() !== undefined;++ createEffect(() => {+ const pairing = pairingQuery.data;+ if (!pairing) return;+ if (!nameEdited()) setName(pairing.requested_name);+ // The daemon's config may ask for a scope; preselect it, but the person+ // approving keeps the final say.+ if (+ !shareEdited() &&+ pairing.requested_scope === 'team' &&+ canShareWithTeam()+ ) {+ setShare('Team');+ }+ });++ const lookupError = () =>+ committedCode() !== undefined && pairingQuery.isError+ ? failureMessage(pairingQuery.error, PAIRING_ERROR_FALLBACK)+ : undefined;+ const errorMessage = () => approveError() ?? lookupError();++ const lookUp = () => {+ const code = codeInput().trim().toUpperCase();+ if (code.length === 0) return;+ setCodeInput(code);+ setCommittedCode(code);+ };++ const tryAnotherCode = () => {+ setCommittedCode(undefined);+ setApproveError(undefined);+ setNameEdited(false);+ setName('');+ setShare('Private');+ setShareEdited(false);+ };++ const canApprove = () =>+ !approveMutation.isPending &&+ name().trim().length > 0 &&+ (share() === 'Private' || canShareWithTeam());++ const approve = async () => {+ const pairing = pairingQuery.data;+ if (!pairing || !canApprove()) return;++ setApproveError(undefined);+ try {+ await approveMutation.mutateAsync({+ code: pairing.code,+ name: name().trim(),+ teamId: share() === 'Team' ? currentTeamId() : undefined,+ });+ setApproved(true);+ toast.success('Harness connected');+ } catch (error) {+ setApproveError(failureMessage(error, PAIRING_ERROR_FALLBACK));+ }+ };++ return (+ <Dialog+ open+ onOpenChange={(open) =>+ !open && !approveMutation.isPending && props.onClose()+ }+ position="center"+ visibleScrim+ class="w-[min(480px,calc(100vw-16px))]"+ >+ <Panel depth={2} class="rounded-xl text-ink">+ <Panel.Header class="px-5 py-3">+ <Dialog.Title class="text-sm font-semibold">+ {approved() ? 'Harness connected' : 'Connect a harness'}+ </Dialog.Title>+ </Panel.Header>+ <Panel.Body class="p-5">+ <Switch>+ <Match when={approved()}>+ <p class="text-sm leading-5 text-ink-muted">+ Harness connected. macrod will finish pairing automatically.+ </p>+ </Match>++ <Match when={errorMessage()}>+ {(message) => (+ <div class="flex flex-col gap-3">+ <p class="text-sm leading-5 text-negative">{message()}</p>+ <div>+ <Button+ type="button"+ variant="outline"+ size="sm"+ onClick={tryAnotherCode}+ >+ Try another code+ </Button>+ </div>+ </div>+ )}+ </Match>++ <Match when={pairingQuery.data}>+ {(pairing) => (+ <div class="flex flex-col gap-4">+ <div class="flex flex-col gap-1.5">+ <div class="rounded-lg border border-edge-muted bg-ink/[0.025] px-3 py-3 text-center font-mono text-2xl tracking-[0.2em] text-ink">+ {pairing().code}+ </div>+ <p class="text-xs text-ink-muted">+ Confirm this matches the code macrod printed.+ </p>+ </div>++ <div class="flex flex-col gap-0.5 text-xs text-ink-muted">+ <span>+ Requested name:{' '}+ <span class="text-ink">{pairing().requested_name}</span>+ </span>+ <Show when={pairing().host}>+ {(host) => (+ <span>+ Host: <span class="text-ink">{host()}</span>+ </span>+ )}+ </Show>+ <span>+ Expires in {expiresInMinutes(pairing().expires_at)}{' '}+ minutes+ </span>+ </div>++ <label class="flex flex-col gap-1.5">+ <span class="text-xs font-medium text-ink">Name</span>+ <input+ class="settings-input w-full"+ value={name()}+ onInput={(event) => {+ setNameEdited(true);+ setName(event.currentTarget.value);+ }}+ />+ </label>++ <fieldset class="grid grid-cols-2 gap-2 mobile:grid-cols-1">+ <legend class="sr-only">Share</legend>+ <ChoiceRow+ name="harness-share"+ value="private"+ checked={share() === 'Private'}+ title="Private"+ description="Only you can run agents on this harness."+ onChange={() => {+ setShareEdited(true);+ setShare('Private');+ }}+ />+ <ChoiceRow+ name="harness-share"+ value="team"+ checked={share() === 'Team'}+ title="Team"+ description={+ canShareWithTeam()+ ? 'Your team can run agents on this harness.'+ : 'Create or join a team before sharing harnesses.'+ }+ disabled={!canShareWithTeam()}+ onChange={() => {+ setShareEdited(true);+ setShare('Team');+ }}+ />+ </fieldset>+ </div>+ )}+ </Match>++ <Match when={committedCode()}>+ <p class="text-sm text-ink-muted">Looking up pairing code…</p>+ </Match>++ <Match when>+ <div class="flex flex-col gap-1.5">+ <label+ for="harness-pairing-code"+ class="text-xs font-medium text-ink"+ >+ Pairing code+ </label>+ <div class="flex min-w-0 items-center gap-2 rounded-lg border border-edge-muted bg-ink/[0.025] px-3 py-2">+ <input+ id="harness-pairing-code"+ autofocus+ autocomplete="off"+ spellcheck={false}+ class="min-w-0 flex-1 bg-transparent font-mono text-sm uppercase tracking-widest text-ink outline-none"+ placeholder="KX7M-4QHD"+ value={codeInput()}+ onInput={(event) =>+ setCodeInput(event.currentTarget.value.toUpperCase())+ }+ onKeyDown={(event) => {+ if (event.key === 'Enter') lookUp();+ }}+ />+ </div>+ <p class="text-xs text-ink-extra-muted">+ Run macrod on your computer and enter the code it prints.+ </p>+ </div>+ </Match>+ </Switch>+ </Panel.Body>+ <Panel.Footer class="justify-end gap-2 px-5 py-3">+ <Switch>+ <Match when={approved()}>+ <Button+ type="button"+ variant="cta"+ size="sm"+ onClick={props.onClose}+ >+ Done+ </Button>+ </Match>+ <Match when={errorMessage()}>+ <Button+ type="button"+ variant="ghost"+ size="sm"+ onClick={props.onClose}+ >+ Close+ </Button>+ </Match>+ <Match when={pairingQuery.data}>+ <Button+ type="button"+ variant="ghost"+ size="sm"+ disabled={approveMutation.isPending}+ onClick={props.onClose}+ >+ Cancel+ </Button>+ <Button+ type="button"+ variant="cta"+ size="sm"+ disabled={!canApprove()}+ onClick={() => void approve()}+ >+ {approveMutation.isPending ? 'Approving…' : 'Approve'}+ </Button>+ </Match>+ <Match when={committedCode()}>+ <Button+ type="button"+ variant="ghost"+ size="sm"+ onClick={props.onClose}+ >+ Cancel+ </Button>+ </Match>+ <Match when>+ <Button+ type="button"+ variant="ghost"+ size="sm"+ onClick={props.onClose}+ >+ Cancel+ </Button>+ <Button+ type="button"+ variant="cta"+ size="sm"+ disabled={codeInput().trim().length === 0}+ onClick={lookUp}+ >+ Look up+ </Button>+ </Match>+ </Switch>+ </Panel.Footer>+ </Panel>+ </Dialog>+ );+}diff --git a/apps/web/src/features/settings/primitives.tsx b/apps/web/src/features/settings/primitives.tsxindex 78b1c88305..28a46e182e 100644--- a/apps/web/src/features/settings/primitives.tsx+++ b/apps/web/src/features/settings/primitives.tsx@@ -179,6 +179,48 @@ export function SettingsRow(props: {);}+/**+ * A radio choice rendered as a bordered card: a title and one-line description+ * beside the radio input. Used by the agent dialog's channel/share pickers and+ * the harness pairing dialog's Private/Team picker.+ */+export function ChoiceRow(props: {+ name: string;+ value: string;+ checked: boolean;+ title: string;+ description: string;+ disabled?: boolean;+ onChange: () => void;+}) {+ return (+ <label+ class="flex min-w-0 items-start gap-3 rounded-lg border border-edge-muted p-3 has-checked:border-accent has-checked:bg-accent-bg"+ classList={{+ 'cursor-not-allowed opacity-50': props.disabled,+ 'cursor-pointer': !props.disabled,+ }}+ >+ <input+ type="radio"+ name={props.name}+ value={props.value}+ checked={props.checked}+ disabled={props.disabled}+ onChange={props.onChange}+ aria-label={props.title}+ class="mt-0.5 accent-accent"+ />+ <span class="min-w-0">+ <span class="block text-sm font-medium text-ink">{props.title}</span>+ <span class="mt-0.5 block text-xs text-ink-muted">+ {props.description}+ </span>+ </span>+ </label>+ );+}+/*** A row for an integration / service: a brand icon, a title + one-line* description, and a trailing action slot. Used by the Connected accounts anddiff --git a/apps/web/src/lib/queries/agents/agents.ts b/apps/web/src/lib/queries/agents/agents.tsindex 7ac66841c2..42451f533b 100644--- a/apps/web/src/lib/queries/agents/agents.ts+++ b/apps/web/src/lib/queries/agents/agents.ts@@ -8,6 +8,12 @@ import type { AgentChannelScope } from '@service-storage/generated/schemas/agentimport { useMutation, useQuery } from '@tanstack/solid-query';import { agentKeys } from './keys';+/**+ * `Agent` plus the macrod harness binding the backend now returns; the field+ * is not yet in the generated schema.+ */+export type AgentWithHarnessId = Agent & { harness_id?: string | null };+export type CreateAgentParams = {avatarUrl?: string;channelIds: string[];@@ -16,6 +22,8 @@ export type CreateAgentParams = {description?: string;handle: string;harness: string;+ /** The registered macrod harness to run on; omit for built-in harnesses. */+ harnessId?: string;name: string;instructions: string;teamId?: string;@@ -33,7 +41,7 @@ export type DeleteAgentParams = {export function useAgentsQuery() {return useQuery(() => ({queryKey: agentKeys.list.queryKey,- queryFn: async (): Promise<Agent[]> =>+ queryFn: async (): Promise<AgentWithHarnessId[]> =>await throwOnErr(() => storageServiceClient.getAgents()),}));}@@ -65,6 +73,7 @@ export function useCreateAgentMutation() {description: vars.description,handle: vars.handle,harness: vars.harness,+ harness_id: vars.harnessId,name: vars.name,instructions: vars.instructions,team_id: vars.teamId,@@ -95,6 +104,7 @@ export function useUpdateAgentMutation() {description: vars.description,handle: vars.handle,harness: vars.harness,+ harness_id: vars.harnessId,name: vars.name,instructions: vars.instructions,team_id: vars.teamId,diff --git a/apps/web/src/lib/queries/harnesses/harnesses.ts b/apps/web/src/lib/queries/harnesses/harnesses.tsnew file mode 100644index 0000000000..3bda39a246--- /dev/null+++ b/apps/web/src/lib/queries/harnesses/harnesses.ts@@ -0,0 +1,100 @@+import { throwOnErr } from '@core/util/result';+import { invalidateAgents } from '@queries/agents/agents';+import { queryClient } from '@queries/client';+import {+ type Harness,+ type HarnessPairing,+ storageServiceClient,+} from '@service-storage/client';+import { useMutation, useQuery } from '@tanstack/solid-query';+import { harnessKeys } from './keys';++export type ApproveHarnessPairingParams = {+ code: string;+ name?: string;+ teamId?: string;+};++export type DeleteHarnessParams = {+ harnessId: string;+};++/**+ * The macrod harnesses registered for the signed-in user (and their team).+ * Refetched on a short interval so the connected indicator tracks the daemon+ * heartbeat without a manual refresh.+ */+export function useHarnessesQuery() {+ return useQuery(() => ({+ queryKey: harnessKeys.list.queryKey,+ queryFn: async (): Promise<Harness[]> =>+ await throwOnErr(() => storageServiceClient.getHarnesses()),+ refetchInterval: 15_000,+ }));+}++export function invalidateHarnesses() {+ return queryClient.invalidateQueries({+ queryKey: harnessKeys.list.queryKey,+ });+}++/**+ * Looks up a pending pairing request by its printed code. Disabled until a+ * code is committed, and never retried: a 404/410 is an answer (invalid or+ * expired code), not a transient failure.+ */+export function useHarnessPairingQuery(code: () => string | undefined) {+ return useQuery(() => ({+ queryKey: harnessKeys.pairing(code() ?? '').queryKey,+ queryFn: async (): Promise<HarnessPairing> =>+ await throwOnErr(() =>+ storageServiceClient.getHarnessPairing({ code: code() ?? '' })+ ),+ enabled: (code() ?? '').length > 0,+ retry: false,+ }));+}++export function useApproveHarnessPairingMutation() {+ return useMutation(() => ({+ gcTime: 0,+ mutationFn: async (vars: ApproveHarnessPairingParams) =>+ await throwOnErr(() =>+ storageServiceClient.approveHarnessPairing({+ code: vars.code,+ name: vars.name,+ team_id: vars.teamId,+ })+ ),+ onSuccess: async (_harness, vars) => {+ queryClient.removeQueries({+ queryKey: harnessKeys.pairing(vars.code).queryKey,+ });+ await invalidateHarnesses();+ },+ onError: (error) =>+ console.error('failed to approve harness pairing', error),+ }));+}++export function useDeleteHarnessMutation() {+ return useMutation(() => ({+ gcTime: 0,+ mutationFn: async (vars: DeleteHarnessParams) =>+ await throwOnErr(() =>+ storageServiceClient.deleteHarness({ harness_id: vars.harnessId })+ ),+ onSuccess: async (_data, vars) => {+ queryClient.setQueryData<Harness[]>(+ harnessKeys.list.queryKey,+ (current = []) =>+ current.filter((harness) => harness.id !== vars.harnessId)+ );+ // Agents bound to the removed harness now resolve to "Disconnected+ // harness"; refresh them so the agents surface reflects that.+ await invalidateAgents();+ },+ onError: (error) => console.error('failed to delete harness', error),+ }));+}diff --git a/apps/web/src/lib/queries/harnesses/keys.ts b/apps/web/src/lib/queries/harnesses/keys.tsnew file mode 100644index 0000000000..cce55472f4--- /dev/null+++ b/apps/web/src/lib/queries/harnesses/keys.ts@@ -0,0 +1,6 @@+import { createQueryKeys } from '@lukemorales/query-key-factory';++export const harnessKeys = createQueryKeys('harnesses', {+ list: null,+ pairing: (code: string) => [code],+});diff --git a/apps/web/src/lib/service-clients/service-storage/client.ts b/apps/web/src/lib/service-clients/service-storage/client.tsindex 4b4c552021..0d2f8d50c9 100644--- a/apps/web/src/lib/service-clients/service-storage/client.ts+++ b/apps/web/src/lib/service-clients/service-storage/client.ts@@ -287,6 +287,46 @@ type WithBotId = { bot_id: string };type WithAgentId = { agent_id: string };type WithChannelId = { channel_id: string };+/** Who owns a registered harness: the registering user or their team. */+export type HarnessOwner =+ | { type: 'user'; user_id: string }+ | { type: 'team'; team_id: string };++/** A macrod harness registered with the workspace. */+export type Harness = {+ id: string;+ kind: 'macrod';+ name: string;+ owner: HarnessOwner;+ created_by: string;+ created_at: string;+ updated_at: string;+ connected: boolean;+ last_connected_at: string | null;+};++/** A pending macrod pairing request, looked up by its printed code. */+export type HarnessPairing = {+ code: string;+ requested_name: string;+ host: string | null;+ /** The scope the daemon's config asked for; preselects the dialog. */+ requested_scope: 'private' | 'team' | null;+ created_at: string;+ expires_at: string;+};++type ApproveHarnessPairingRequest = {+ name?: string;+ team_id?: string;+};++/**+ * The optional macrod harness binding on agent requests/responses. The backend+ * field is not yet in the generated schemas, so it is layered on here.+ */+type WithHarnessId = { harness_id?: string | null };+type CreateBotRequest = {team_id?: string;name: string;@@ -537,31 +577,71 @@ export const storageServiceClient = {async getAgents() {return (- await dssFetch<Agent[]>(`/agents`, {+ await dssFetch<(Agent & WithHarnessId)[]>(`/agents`, {method: 'GET',})).map((result) => result);},- async createAgent(args: CreateAgentRequest) {+ async createAgent(args: CreateAgentRequest & WithHarnessId) {return (- await dssFetch<Agent>(`/agents`, {+ await dssFetch<Agent & WithHarnessId>(`/agents`, {method: 'POST',body: JSON.stringify(args),})).map((result) => result);},- async updateAgent(args: WithAgentId & UpdateAgentRequest) {+ async updateAgent(args: WithAgentId & UpdateAgentRequest & WithHarnessId) {const { agent_id, ...request } = args;return (- await dssFetch<Agent>(`/agents/${agent_id}`, {+ await dssFetch<Agent & WithHarnessId>(`/agents/${agent_id}`, {method: 'PUT',body: JSON.stringify(request),})).map((result) => result);},+ async getHarnesses() {+ return (+ await dssFetch<Harness[]>(`/harnesses`, {+ method: 'GET',+ })+ ).map((result) => result);+ },++ async getHarnessPairing(args: { code: string }) {+ return (+ await dssFetch<HarnessPairing>(+ `/harness-pairings/${encodeURIComponent(args.code)}`,+ {+ method: 'GET',+ }+ )+ ).map((result) => result);+ },++ async approveHarnessPairing(+ args: { code: string } & ApproveHarnessPairingRequest+ ) {+ const { code, ...request } = args;+ return (+ await dssFetch<Harness>(+ `/harness-pairings/${encodeURIComponent(code)}/approve`,+ {+ method: 'POST',+ body: JSON.stringify(request),+ }+ )+ ).map((result) => result);+ },++ async deleteHarness(args: { harness_id: string }) {+ return await dssFetch(`/harnesses/${args.harness_id}`, {+ method: 'DELETE',+ });+ },+async createBot(args: CreateBotRequest) {return (await dssFetch<Bot>(`/bots`, {diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/agent.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agent.tsindex 84d3dce724..88f439df93 100644--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/agent.ts+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agent.ts@@ -6,6 +6,7 @@*/import type { AgentChannelScope } from './agentChannelScope';+import type { AgentHarnessId } from './agentHarnessId';import type { Bot } from './bot';/**@@ -22,6 +23,7 @@ export interface Agent {default_model: string;/** Harness used to run the agent. */harness: string;+ harness_id?: AgentHarnessId;/** Instructions supplied to the agent at the start of a conversation. */instructions: string;}diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentHarnessId.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentHarnessId.tsnew file mode 100644index 0000000000..6f69311a03--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentHarnessId.ts@@ -0,0 +1,9 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { HarnessId } from './harnessId';++export type AgentHarnessId = null | HarnessId;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/approvePairingRequest.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/approvePairingRequest.tsnew file mode 100644index 0000000000..396b1bfcd8--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/approvePairingRequest.ts@@ -0,0 +1,18 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { ApprovePairingRequestName } from './approvePairingRequestName';+import type { ApprovePairingRequestTeamId } from './approvePairingRequestTeamId';++/**+ * Request to approve a pairing and register the harness.+ */+export interface ApprovePairingRequest {+ /** Display name override. Defaults to the daemon's requested name. */+ name?: ApprovePairingRequestName;+ /** Owning team. Omit for a private, user-owned harness. */+ team_id?: ApprovePairingRequestTeamId;+}diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/approvePairingRequestName.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/approvePairingRequestName.tsnew file mode 100644index 0000000000..0cd02f6c32--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/approvePairingRequestName.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Display name override. Defaults to the daemon's requested name.+ */+export type ApprovePairingRequestName = string | null;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/approvePairingRequestTeamId.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/approvePairingRequestTeamId.tsnew file mode 100644index 0000000000..f03e50b6f7--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/approvePairingRequestTeamId.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Owning team. Omit for a private, user-owned harness.+ */+export type ApprovePairingRequestTeamId = string | null;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/claimPairingRequest.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/claimPairingRequest.tsnew file mode 100644index 0000000000..3bc263a571--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/claimPairingRequest.ts@@ -0,0 +1,16 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Request to claim an approved pairing's credential.++The daemon serializes this, so both derives are used.+ */+export interface ClaimPairingRequest {+ /** The claim credential returned when the pairing was created. */+ device_secret: string;+}diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/claimedPairing.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/claimedPairing.tsnew file mode 100644index 0000000000..c74068eb49--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/claimedPairing.ts@@ -0,0 +1,17 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { Harness } from './harness';++/**+ * The credential released to the daemon when a pairing is claimed.+ */+export interface ClaimedPairing {+ /** The registered harness. */+ harness: Harness;+ /** The raw harness bearer token. Shown only here; only its hash is stored. */+ token: string;+}diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/createAgentRequest.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/createAgentRequest.tsindex 09ee915492..d502af2d9b 100644--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/createAgentRequest.ts+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/createAgentRequest.ts@@ -8,6 +8,7 @@import type { AgentChannelScope } from './agentChannelScope';import type { CreateAgentRequestAvatarUrl } from './createAgentRequestAvatarUrl';import type { CreateAgentRequestDescription } from './createAgentRequestDescription';+import type { CreateAgentRequestHarnessId } from './createAgentRequestHarnessId';import type { CreateAgentRequestTeamId } from './createAgentRequestTeamId';/**@@ -28,6 +29,7 @@ export interface CreateAgentRequest {handle: string;/** Harness used to run the agent. */harness: string;+ harness_id?: CreateAgentRequestHarnessId;/** Instructions supplied to the agent at the start of a conversation. */instructions: string;/** Display name. */diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/createAgentRequestHarnessId.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/createAgentRequestHarnessId.tsnew file mode 100644index 0000000000..141210d156--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/createAgentRequestHarnessId.ts@@ -0,0 +1,9 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { HarnessId } from './harnessId';++export type CreateAgentRequestHarnessId = null | HarnessId;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/createPairingRequest.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/createPairingRequest.tsnew file mode 100644index 0000000000..3d6b2269e2--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/createPairingRequest.ts@@ -0,0 +1,21 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { CreatePairingRequestHost } from './createPairingRequestHost';+import type { CreatePairingRequestScope } from './createPairingRequestScope';++/**+ * Request to open a pairing: the daemon asks for a code the user approves.++The daemon serializes this, so both derives are used.+ */+export interface CreatePairingRequest {+ /** Display-only description of the machine, e.g. `eric@macbook / darwin`. */+ host?: CreatePairingRequestHost;+ /** Requested harness display name (typically the machine's hostname). */+ name: string;+ scope?: CreatePairingRequestScope;+}diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/createPairingRequestHost.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/createPairingRequestHost.tsnew file mode 100644index 0000000000..5348576e29--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/createPairingRequestHost.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Display-only description of the machine, e.g. `eric@macbook / darwin`.+ */+export type CreatePairingRequestHost = string | null;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/createPairingRequestScope.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/createPairingRequestScope.tsnew file mode 100644index 0000000000..5b22e095a5--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/createPairingRequestScope.ts@@ -0,0 +1,9 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { RequestedHarnessScope } from './requestedHarnessScope';++export type CreatePairingRequestScope = null | RequestedHarnessScope;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/createdPairing.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/createdPairing.tsnew file mode 100644index 0000000000..a42e36d402--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/createdPairing.ts@@ -0,0 +1,28 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * A pairing the daemon created, including its claim credential.++`device_secret` is returned exactly once and never stored raw; the daemon+keeps it to claim the harness credential after approval.+ */+export interface CreatedPairing {+ /** Human-readable code the user confirms in the web app, `XXXX-XXXX`. */+ code: string;+ /** Claim credential the daemon must present. Shown only here. */+ device_secret: string;+ /** When the pairing expires. */+ expires_at: string;+ /** Pairing id used to poll for the claim. */+ pairing_id: string;+ /**+ * Suggested delay between claim polls.+ * @minimum 0+ */+ poll_interval_seconds: number;+}diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/harness.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/harness.tsnew file mode 100644index 0000000000..fe41a2d2bc--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/harness.ts@@ -0,0 +1,35 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { HarnessId } from './harnessId';+import type { HarnessLastConnectedAt } from './harnessLastConnectedAt';+import type { HarnessOwner } from './harnessOwner';++/**+ * A registered user-run harness.++Clients deserialize this, so both derives are used.+ */+export interface Harness {+ /** Whether the daemon currently holds a runtime connection. */+ connected: boolean;+ /** Creation timestamp. */+ created_at: string;+ /** User that registered this harness. */+ created_by: string;+ /** Harness id. */+ id: HarnessId;+ /** Runtime kind. Currently always `macrod`. */+ kind: string;+ /** When the daemon last attached a runtime connection. */+ last_connected_at?: HarnessLastConnectedAt;+ /** Display name. */+ name: string;+ /** Owner. */+ owner: HarnessOwner;+ /** Update timestamp. */+ updated_at: string;+}diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/harnessAgent.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/harnessAgent.tsnew file mode 100644index 0000000000..a893afb62a--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/harnessAgent.ts@@ -0,0 +1,19 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { BotId } from './botId';++/**+ * An agent bound to a harness, as listed for the daemon.+ */+export interface HarnessAgent {+ /** The agent's bot id. */+ bot_id: BotId;+ /** Stable `@` handle. */+ handle: string;+ /** Display name. */+ name: string;+}diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/harnessId.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/harnessId.tsnew file mode 100644index 0000000000..919448b3d9--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/harnessId.ts@@ -0,0 +1,8 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++export type HarnessId = string;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/harnessLastConnectedAt.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/harnessLastConnectedAt.tsnew file mode 100644index 0000000000..4e238c09ed--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/harnessLastConnectedAt.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * When the daemon last attached a runtime connection.+ */+export type HarnessLastConnectedAt = string | null;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/harnessOwner.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/harnessOwner.tsnew file mode 100644index 0000000000..073d2003e8--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/harnessOwner.ts@@ -0,0 +1,16 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { HarnessOwnerOneOf } from './harnessOwnerOneOf';+import type { HarnessOwnerOneOfThree } from './harnessOwnerOneOfThree';++/**+ * Harness owner.++Exactly one of a user or a team, mirroring the bots owner pattern. There+are no system harnesses.+ */+export type HarnessOwner = HarnessOwnerOneOf | HarnessOwnerOneOfThree;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/harnessOwnerOneOf.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/harnessOwnerOneOf.tsnew file mode 100644index 0000000000..63448df876--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/harnessOwnerOneOf.ts@@ -0,0 +1,16 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { HarnessOwnerOneOfType } from './harnessOwnerOneOfType';++/**+ * User-owned (private) harness.+ */+export type HarnessOwnerOneOf = {+ type: HarnessOwnerOneOfType;+ /** Owner user id. */+ user_id: string;+};diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/harnessOwnerOneOfThree.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/harnessOwnerOneOfThree.tsnew file mode 100644index 0000000000..5d12c1af60--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/harnessOwnerOneOfThree.ts@@ -0,0 +1,16 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { HarnessOwnerOneOfThreeType } from './harnessOwnerOneOfThreeType';++/**+ * Team-owned harness, usable by every team member.+ */+export type HarnessOwnerOneOfThree = {+ /** Owner team id. */+ team_id: string;+ type: HarnessOwnerOneOfThreeType;+};diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/harnessOwnerOneOfThreeType.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/harnessOwnerOneOfThreeType.tsnew file mode 100644index 0000000000..fb869d9caf--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/harnessOwnerOneOfThreeType.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++export type HarnessOwnerOneOfThreeType =+ (typeof HarnessOwnerOneOfThreeType)[keyof typeof HarnessOwnerOneOfThreeType];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const HarnessOwnerOneOfThreeType = {+ team: 'team',+} as const;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/harnessOwnerOneOfType.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/harnessOwnerOneOfType.tsnew file mode 100644index 0000000000..9ed79aced2--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/harnessOwnerOneOfType.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++export type HarnessOwnerOneOfType =+ (typeof HarnessOwnerOneOfType)[keyof typeof HarnessOwnerOneOfType];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const HarnessOwnerOneOfType = {+ user: 'user',+} as const;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.tsindex 89e985e42a..d3025e9f88 100644--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts@@ -15,6 +15,7 @@ export * from './addParticipantsRequest';export * from './addPinRequest';export * from './agent';export * from './agentChannelScope';+export * from './agentHarnessId';export * from './anchor';export * from './anchorId';export * from './anchorIdOneOf';@@ -119,6 +120,9 @@ export * from './apiThreadInfo';export * from './apiThreadInfoLatestReplyAt';export * from './apiThreadReply';export * from './apiThreadReplyEditedAt';+export * from './approvePairingRequest';+export * from './approvePairingRequestName';+export * from './approvePairingRequestTeamId';export * from './attendeeResponseStatus';export * from './basicDocument';export * from './basicDocumentBranchedFromId';@@ -281,6 +285,8 @@ export * from './chatProjectId';export * from './chatTokenCount';export * from './chatType';export * from './chatUpdatedAt';+export * from './claimedPairing';+export * from './claimPairingRequest';export * from './cloudStorageItemType';export * from './collabSurfaceResponse';export * from './collabSurfaceResponseParentEntityType';@@ -302,6 +308,7 @@ export * from './copyDocumentResponse';export * from './createAgentRequest';export * from './createAgentRequestAvatarUrl';export * from './createAgentRequestDescription';+export * from './createAgentRequestHarnessId';export * from './createAgentRequestTeamId';export * from './createBotRequest';export * from './createBotRequestAvatarUrl';@@ -354,6 +361,7 @@ export * from './createDocumentRequestTeamId';export * from './createDocumentResponseData';export * from './createDocumentResponseDataAllOf';export * from './createDocumentResponseDataAllOfFileType';+export * from './createdPairing';export * from './createdUserApiKey';export * from './createEntityMentionRequest';export * from './createEntityMentionResponse';@@ -364,6 +372,9 @@ export * from './createMarkdownDocumentRequestMarkdown';export * from './createMarkdownDocumentRequestProjectId';export * from './createMarkdownDocumentResponse';export * from './createMarkdownHandler200';+export * from './createPairingRequest';+export * from './createPairingRequestHost';+export * from './createPairingRequestScope';export * from './createProjectRequest';export * from './createProjectRequestProjectParentId';export * from './createProjectResponse';@@ -746,6 +757,15 @@ export * from './groupedSoupPageOneOfFour';export * from './groupedSoupPageOneOfFourAllOf';export * from './groupedSoupPageOneOfFourAllOfMode';export * from './groupedSoupSort';+export * from './harness';+export * from './harnessAgent';+export * from './harnessId';+export * from './harnessLastConnectedAt';+export * from './harnessOwner';+export * from './harnessOwnerOneOf';+export * from './harnessOwnerOneOfThree';+export * from './harnessOwnerOneOfThreeType';+export * from './harnessOwnerOneOfType';export * from './hashMap';export * from './hashMapOneOf';export * from './hashMapOneOfAllOf';@@ -784,6 +804,9 @@ export * from './newChannelAttachmentWidth';export * from './notificationFilters';export * from './notificationFiltersDone';export * from './notificationFiltersSeen';+export * from './pairingDetails';+export * from './pairingDetailsHost';+export * from './pairingDetailsRequestedScope';export * from './params';export * from './paramsExpand';export * from './paramsLimit';@@ -853,6 +876,7 @@ export * from './pdfHighlightRectAnchorRequest';export * from './pdfPlaceableCommentAnchor';export * from './pdfPlaceableCommentAnchorRequest';export * from './pdfPlaceableCommentAnchorRequestUuid';+export * from './pendingClaimResponse';export * from './pinnedItem';export * from './pinRequest';export * from './postActivityRequest';@@ -955,6 +979,7 @@ export * from './remindersListNextCursor';export * from './removeParticipantsRequest';export * from './reorderFavoritesRequest';export * from './reorderPinRequest';+export * from './requestedHarnessScope';export * from './ringStatus';export * from './ringStatusResponse';export * from './s3ObjectInfo';@@ -1188,6 +1213,7 @@ export * from './unthreadedPdfUuidRequestOneOfAttachmentType';export * from './updateAgentRequest';export * from './updateAgentRequestAvatarUrl';export * from './updateAgentRequestDescription';+export * from './updateAgentRequestHarnessId';export * from './updateAgentRequestTeamId';export * from './updateChannelSharePermission';export * from './updateChannelSharePermissionAccessLevel';diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/pairingDetails.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/pairingDetails.tsnew file mode 100644index 0000000000..e86243b231--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/pairingDetails.ts@@ -0,0 +1,25 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { PairingDetailsHost } from './pairingDetailsHost';+import type { PairingDetailsRequestedScope } from './pairingDetailsRequestedScope';++/**+ * A pending pairing, as shown to the approving user.+ */+export interface PairingDetails {+ /** The pairing code, normalized to `XXXX-XXXX`. */+ code: string;+ /** When the pairing was created. */+ created_at: string;+ /** When the pairing expires. */+ expires_at: string;+ /** Display-only description of the machine. */+ host?: PairingDetailsHost;+ /** Harness display name the daemon asked for. */+ requested_name: string;+ requested_scope?: PairingDetailsRequestedScope;+}diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/pairingDetailsHost.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/pairingDetailsHost.tsnew file mode 100644index 0000000000..b84eb9c65e--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/pairingDetailsHost.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Display-only description of the machine.+ */+export type PairingDetailsHost = string | null;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/pairingDetailsRequestedScope.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/pairingDetailsRequestedScope.tsnew file mode 100644index 0000000000..559f9df11e--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/pairingDetailsRequestedScope.ts@@ -0,0 +1,9 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { RequestedHarnessScope } from './requestedHarnessScope';++export type PairingDetailsRequestedScope = null | RequestedHarnessScope;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/pendingClaimResponse.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/pendingClaimResponse.tsnew file mode 100644index 0000000000..cfe7bb65f7--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/pendingClaimResponse.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Body returned while a claim is still waiting for approval.+ */+export interface PendingClaimResponse {+ /** Always `pending`. */+ status: string;+}diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/requestedHarnessScope.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/requestedHarnessScope.tsnew file mode 100644index 0000000000..7d11b4f79a--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/requestedHarnessScope.ts@@ -0,0 +1,21 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * The ownership scope a daemon's config asks for.++Advisory, not binding: the approving user confirms it in the dialog, which+arrives preselected to this. Approval is what actually sets ownership.+ */+export type RequestedHarnessScope =+ (typeof RequestedHarnessScope)[keyof typeof RequestedHarnessScope];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const RequestedHarnessScope = {+ private: 'private',+ team: 'team',+} as const;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/updateAgentRequest.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/updateAgentRequest.tsindex 1a103d9589..90ba9fe239 100644--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/updateAgentRequest.ts+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/updateAgentRequest.ts@@ -8,6 +8,7 @@import type { AgentChannelScope } from './agentChannelScope';import type { UpdateAgentRequestAvatarUrl } from './updateAgentRequestAvatarUrl';import type { UpdateAgentRequestDescription } from './updateAgentRequestDescription';+import type { UpdateAgentRequestHarnessId } from './updateAgentRequestHarnessId';import type { UpdateAgentRequestTeamId } from './updateAgentRequestTeamId';/**@@ -28,6 +29,7 @@ export interface UpdateAgentRequest {handle: string;/** Harness used to run the agent. */harness: string;+ harness_id?: UpdateAgentRequestHarnessId;/** Instructions supplied to the agent at the start of a conversation. */instructions: string;/** Display name. */diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/updateAgentRequestHarnessId.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/updateAgentRequestHarnessId.tsnew file mode 100644index 0000000000..2d3f4d3e89--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/updateAgentRequestHarnessId.ts@@ -0,0 +1,9 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { HarnessId } from './harnessId';++export type UpdateAgentRequestHarnessId = null | HarnessId;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts b/apps/web/src/lib/service-clients/service-storage/generated/zod.tsindex 485222958a..953a51b874 100644--- a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts+++ b/apps/web/src/lib/service-clients/service-storage/generated/zod.ts@@ -71,6 +71,7 @@ export const listAgentsResponseItem = zod.string().describe('Model selected specifically for this agent.'),harness: zod.string().describe('Harness used to run the agent.'),+ harness_id: zod.union([zod.null(), zod.string()]).optional(),instructions: zod.string().describe(@@ -106,6 +107,7 @@ export const createAgentBody = zoddescription: zod.string().nullish().describe('Optional description.'),handle: zod.string().describe('Stable `@` handle.'),harness: zod.string().describe('Harness used to run the agent.'),+ harness_id: zod.union([zod.null(), zod.string()]).optional(),instructions: zod.string().describe(@@ -149,6 +151,7 @@ export const updateAgentBody = zoddescription: zod.string().nullish().describe('Optional description.'),handle: zod.string().describe('Stable `@` handle.'),harness: zod.string().describe('Harness used to run the agent.'),+ harness_id: zod.union([zod.null(), zod.string()]).optional(),instructions: zod.string().describe(@@ -226,6 +229,7 @@ export const updateAgentResponse = zod.string().describe('Model selected specifically for this agent.'),harness: zod.string().describe('Harness used to run the agent.'),+ harness_id: zod.union([zod.null(), zod.string()]).optional(),instructions: zod.string().describe(@@ -8174,6 +8178,262 @@ export const getForeignEntityResponse = zod}).describe('A persisted mapping to an entity owned by an external system.');+/**+ * Unauthenticated by design: the daemon has no credential yet - obtaining one+is the point. The pairing releases nothing until a signed-in user approves+it, and creation is throttled in the domain service.+ * @summary Handler for `POST /harness-pairings`.+ */+export const createHarnessPairingBody = zod+ .object({+ host: zod+ .string()+ .nullish()+ .describe(+ 'Display-only description of the machine, e.g. `eric@macbook \/ darwin`.'+ ),+ name: zod+ .string()+ .describe(+ "Requested harness display name (typically the machine's hostname)."+ ),+ scope: zod+ .union([+ zod.null(),+ zod+ .enum(['private', 'team'])+ .describe(+ "The ownership scope a daemon's config asks for.\n\nAdvisory, not binding: the approving user confirms it in the dialog, which\narrives preselected to this. Approval is what actually sets ownership."+ ),+ ])+ .optional(),+ })+ .describe(+ 'Request to open a pairing: the daemon asks for a code the user approves.\n\nThe daemon serializes this, so both derives are used.'+ );++/**+ * @summary Handler for `GET /harness-pairings/{code}`.+ */+export const getHarnessPairingParams = zod.object({+ code: zod.string().describe('Pairing code'),+});++export const getHarnessPairingResponse = zod+ .object({+ code: zod.string().describe('The pairing code, normalized to `XXXX-XXXX`.'),+ created_at: zod.iso.datetime({}).describe('When the pairing was created.'),+ expires_at: zod.iso.datetime({}).describe('When the pairing expires.'),+ host: zod+ .string()+ .nullish()+ .describe('Display-only description of the machine.'),+ requested_name: zod+ .string()+ .describe('Harness display name the daemon asked for.'),+ requested_scope: zod+ .union([+ zod.null(),+ zod+ .enum(['private', 'team'])+ .describe(+ "The ownership scope a daemon's config asks for.\n\nAdvisory, not binding: the approving user confirms it in the dialog, which\narrives preselected to this. Approval is what actually sets ownership."+ ),+ ])+ .optional(),+ })+ .describe('A pending pairing, as shown to the approving user.');++/**+ * @summary Handler for `POST /harness-pairings/{code}/approve`.+ */+export const approveHarnessPairingParams = zod.object({+ code: zod.string().describe('Pairing code'),+});++export const approveHarnessPairingBody = zod+ .object({+ name: zod+ .string()+ .nullish()+ .describe(+ "Display name override. Defaults to the daemon's requested name."+ ),+ team_id: zod+ .uuid()+ .nullish()+ .describe('Owning team. Omit for a private, user-owned harness.'),+ })+ .describe('Request to approve a pairing and register the harness.');++export const approveHarnessPairingResponse = zod+ .object({+ connected: zod+ .boolean()+ .describe('Whether the daemon currently holds a runtime connection.'),+ created_at: zod.iso.datetime({}).describe('Creation timestamp.'),+ created_by: zod.string().describe('User that registered this harness.'),+ id: zod.string(),+ kind: zod.string().describe('Runtime kind. Currently always `macrod`.'),+ last_connected_at: zod.iso+ .datetime({})+ .nullish()+ .describe('When the daemon last attached a runtime connection.'),+ name: zod.string().describe('Display name.'),+ owner: zod+ .union([+ zod+ .object({+ type: zod.enum(['user']),+ user_id: zod.string().describe('Owner user id.'),+ })+ .describe('User-owned (private) harness.'),+ zod+ .object({+ team_id: zod.uuid().describe('Owner team id.'),+ type: zod.enum(['team']),+ })+ .describe('Team-owned harness, usable by every team member.'),+ ])+ .describe(+ 'Harness owner.\n\nExactly one of a user or a team, mirroring the bots owner pattern. There\nare no system harnesses.'+ ),+ updated_at: zod.iso.datetime({}).describe('Update timestamp.'),+ })+ .describe(+ 'A registered user-run harness.\n\nClients deserialize this, so both derives are used.'+ );++/**+ * Unauthenticated like pairing creation; the device secret minted alongside+the pairing is the credential, and the pairing id (not the short user+code) addresses it.+ * @summary Handler for `POST /harness-pairings/{pairing_id}/claim`.+ */+export const claimHarnessPairingParams = zod.object({+ pairing_id: zod.uuid().describe('Pairing ID'),+});++export const claimHarnessPairingBody = zod+ .object({+ device_secret: zod+ .string()+ .describe('The claim credential returned when the pairing was created.'),+ })+ .describe(+ "Request to claim an approved pairing's credential.\n\nThe daemon serializes this, so both derives are used."+ );++export const claimHarnessPairingResponse = zod+ .object({+ harness: zod+ .object({+ connected: zod+ .boolean()+ .describe('Whether the daemon currently holds a runtime connection.'),+ created_at: zod.iso.datetime({}).describe('Creation timestamp.'),+ created_by: zod.string().describe('User that registered this harness.'),+ id: zod.string(),+ kind: zod.string().describe('Runtime kind. Currently always `macrod`.'),+ last_connected_at: zod.iso+ .datetime({})+ .nullish()+ .describe('When the daemon last attached a runtime connection.'),+ name: zod.string().describe('Display name.'),+ owner: zod+ .union([+ zod+ .object({+ type: zod.enum(['user']),+ user_id: zod.string().describe('Owner user id.'),+ })+ .describe('User-owned (private) harness.'),+ zod+ .object({+ team_id: zod.uuid().describe('Owner team id.'),+ type: zod.enum(['team']),+ })+ .describe('Team-owned harness, usable by every team member.'),+ ])+ .describe(+ 'Harness owner.\n\nExactly one of a user or a team, mirroring the bots owner pattern. There\nare no system harnesses.'+ ),+ updated_at: zod.iso.datetime({}).describe('Update timestamp.'),+ })+ .describe(+ 'A registered user-run harness.\n\nClients deserialize this, so both derives are used.'+ ),+ token: zod+ .string()+ .describe(+ 'The raw harness bearer token. Shown only here; only its hash is stored.'+ ),+ })+ .describe('The credential released to the daemon when a pairing is claimed.');++/**+ * @summary Handler for `GET /harnesses`.+ */+export const listHarnessesResponseItem = zod+ .object({+ connected: zod+ .boolean()+ .describe('Whether the daemon currently holds a runtime connection.'),+ created_at: zod.iso.datetime({}).describe('Creation timestamp.'),+ created_by: zod.string().describe('User that registered this harness.'),+ id: zod.string(),+ kind: zod.string().describe('Runtime kind. Currently always `macrod`.'),+ last_connected_at: zod.iso+ .datetime({})+ .nullish()+ .describe('When the daemon last attached a runtime connection.'),+ name: zod.string().describe('Display name.'),+ owner: zod+ .union([+ zod+ .object({+ type: zod.enum(['user']),+ user_id: zod.string().describe('Owner user id.'),+ })+ .describe('User-owned (private) harness.'),+ zod+ .object({+ team_id: zod.uuid().describe('Owner team id.'),+ type: zod.enum(['team']),+ })+ .describe('Team-owned harness, usable by every team member.'),+ ])+ .describe(+ 'Harness owner.\n\nExactly one of a user or a team, mirroring the bots owner pattern. There\nare no system harnesses.'+ ),+ updated_at: zod.iso.datetime({}).describe('Update timestamp.'),+ })+ .describe(+ 'A registered user-run harness.\n\nClients deserialize this, so both derives are used.'+ );+export const listHarnessesResponse = zod.array(listHarnessesResponseItem);++/**+ * @summary Handler for `GET /harnesses/me/agents`.+ */+export const listHarnessAgentsResponseItem = zod+ .object({+ bot_id: zod.string(),+ handle: zod.string().describe('Stable `@` handle.'),+ name: zod.string().describe('Display name.'),+ })+ .describe('An agent bound to a harness, as listed for the daemon.');+export const listHarnessAgentsResponse = zod.array(+ listHarnessAgentsResponseItem+);++/**+ * @summary Handler for `DELETE /harnesses/{harness_id}`.+ */+export const deleteHarnessParams = zod.object({+ harness_id: zod.string().describe('Harness ID'),+});+/*** @summary Gets the users history*/diff --git a/apps/web/src/lib/service-clients/service-storage/openapi.json b/apps/web/src/lib/service-clients/service-storage/openapi.jsonindex 75ce6c3709..9337378ff8 100644--- a/apps/web/src/lib/service-clients/service-storage/openapi.json+++ b/apps/web/src/lib/service-clients/service-storage/openapi.json@@ -8636,6 +8636,465 @@}}},+ "/harness-pairings": {+ "post": {+ "tags": ["harnesses"],+ "summary": "Handler for `POST /harness-pairings`.",+ "description": "Unauthenticated by design: the daemon has no credential yet - obtaining one\nis the point. The pairing releases nothing until a signed-in user approves\nit, and creation is throttled in the domain service.",+ "operationId": "create_harness_pairing",+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CreatePairingRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "201": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CreatedPairing"+ }+ }+ }+ },+ "400": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "429": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ }+ },+ "/harness-pairings/{code}": {+ "get": {+ "tags": ["harnesses"],+ "summary": "Handler for `GET /harness-pairings/{code}`.",+ "operationId": "get_harness_pairing",+ "parameters": [+ {+ "name": "code",+ "in": "path",+ "description": "Pairing code",+ "required": true,+ "schema": {+ "type": "string"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/PairingDetails"+ }+ }+ }+ },+ "400": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "401": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "404": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "410": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ }+ },+ "/harness-pairings/{code}/approve": {+ "post": {+ "tags": ["harnesses"],+ "summary": "Handler for `POST /harness-pairings/{code}/approve`.",+ "operationId": "approve_harness_pairing",+ "parameters": [+ {+ "name": "code",+ "in": "path",+ "description": "Pairing code",+ "required": true,+ "schema": {+ "type": "string"+ }+ }+ ],+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApprovePairingRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/Harness"+ }+ }+ }+ },+ "400": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "401": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "404": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "410": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ }+ },+ "/harness-pairings/{pairing_id}/claim": {+ "post": {+ "tags": ["harnesses"],+ "summary": "Handler for `POST /harness-pairings/{pairing_id}/claim`.",+ "description": "Unauthenticated like pairing creation; the device secret minted alongside\nthe pairing is the credential, and the pairing id (not the short user\ncode) addresses it.",+ "operationId": "claim_harness_pairing",+ "parameters": [+ {+ "name": "pairing_id",+ "in": "path",+ "description": "Pairing ID",+ "required": true,+ "schema": {+ "type": "string",+ "format": "uuid"+ }+ }+ ],+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ClaimPairingRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ClaimedPairing"+ }+ }+ }+ },+ "202": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/PendingClaimResponse"+ }+ }+ }+ },+ "401": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "404": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "410": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ }+ },+ "/harnesses": {+ "get": {+ "tags": ["harnesses"],+ "summary": "Handler for `GET /harnesses`.",+ "operationId": "list_harnesses",+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/Harness"+ }+ }+ }+ }+ },+ "401": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ }+ },+ "/harnesses/me/agents": {+ "get": {+ "tags": ["harnesses"],+ "summary": "Handler for `GET /harnesses/me/agents`.",+ "operationId": "list_harness_agents",+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/HarnessAgent"+ }+ }+ }+ }+ },+ "401": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ }+ },+ "/harnesses/{harness_id}": {+ "delete": {+ "tags": ["harnesses"],+ "summary": "Handler for `DELETE /harnesses/{harness_id}`.",+ "operationId": "delete_harness",+ "parameters": [+ {+ "name": "harness_id",+ "in": "path",+ "description": "Harness ID",+ "required": true,+ "schema": {+ "$ref": "#/components/schemas/HarnessId"+ }+ }+ ],+ "responses": {+ "204": {+ "description": ""+ },+ "401": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "404": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ }+ },"/health": {"get": {"tags": ["health"],@@ -11941,6 +12400,17 @@"type": "string","description": "Harness used to run the agent."},+ "harness_id": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/HarnessId",+ "description": "Registered harness the agent runs on, when `harness` is `macrod`."+ }+ ]+ },"instructions": {"type": "string","description": "Instructions supplied to the agent at the start of a conversation."@@ -13236,6 +13706,21 @@}}},+ "ApprovePairingRequest": {+ "type": "object",+ "description": "Request to approve a pairing and register the harness.",+ "properties": {+ "name": {+ "type": ["string", "null"],+ "description": "Display name override. Defaults to the daemon's requested name."+ },+ "team_id": {+ "type": ["string", "null"],+ "format": "uuid",+ "description": "Owning team. Omit for a private, user-owned harness."+ }+ }+ },"AttendeeResponseStatus": {"type": "string","description": "RSVP state for an attendee.",@@ -15517,6 +16002,32 @@}}},+ "ClaimPairingRequest": {+ "type": "object",+ "description": "Request to claim an approved pairing's credential.\n\nThe daemon serializes this, so both derives are used.",+ "required": ["device_secret"],+ "properties": {+ "device_secret": {+ "type": "string",+ "description": "The claim credential returned when the pairing was created."+ }+ }+ },+ "ClaimedPairing": {+ "type": "object",+ "description": "The credential released to the daemon when a pairing is claimed.",+ "required": ["harness", "token"],+ "properties": {+ "harness": {+ "$ref": "#/components/schemas/Harness",+ "description": "The registered harness."+ },+ "token": {+ "type": "string",+ "description": "The raw harness bearer token. Shown only here; only its hash is stored."+ }+ }+ },"CloudStorageItemType": {"type": "string","enum": ["document", "chat", "project"]@@ -15732,6 +16243,17 @@"type": "string","description": "Harness used to run the agent."},+ "harness_id": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/HarnessId",+ "description": "Registered harness to run on. Required when `harness` is `macrod`,\nforbidden otherwise."+ }+ ]+ },"instructions": {"type": "string","description": "Instructions supplied to the agent at the start of a conversation."@@ -16261,6 +16783,32 @@}}},+ "CreatePairingRequest": {+ "type": "object",+ "description": "Request to open a pairing: the daemon asks for a code the user approves.\n\nThe daemon serializes this, so both derives are used.",+ "required": ["name"],+ "properties": {+ "host": {+ "type": ["string", "null"],+ "description": "Display-only description of the machine, e.g. `eric@macbook / darwin`."+ },+ "name": {+ "type": "string",+ "description": "Requested harness display name (typically the machine's hostname)."+ },+ "scope": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/RequestedHarnessScope",+ "description": "The scope the daemon's config asks for; the approval dialog arrives\npreselected to it."+ }+ ]+ }+ }+ },"CreateProjectRequest": {"type": "object","required": ["name"],@@ -16673,6 +17221,43 @@}}},+ "CreatedPairing": {+ "type": "object",+ "description": "A pairing the daemon created, including its claim credential.\n\n`device_secret` is returned exactly once and never stored raw; the daemon\nkeeps it to claim the harness credential after approval.",+ "required": [+ "pairing_id",+ "code",+ "device_secret",+ "expires_at",+ "poll_interval_seconds"+ ],+ "properties": {+ "code": {+ "type": "string",+ "description": "Human-readable code the user confirms in the web app, `XXXX-XXXX`."+ },+ "device_secret": {+ "type": "string",+ "description": "Claim credential the daemon must present. Shown only here."+ },+ "expires_at": {+ "type": "string",+ "format": "date-time",+ "description": "When the pairing expires."+ },+ "pairing_id": {+ "type": "string",+ "format": "uuid",+ "description": "Pairing id used to poll for the claim."+ },+ "poll_interval_seconds": {+ "type": "integer",+ "format": "int64",+ "description": "Suggested delay between claim polls.",+ "minimum": 0+ }+ }+ },"CreatedUserApiKey": {"type": "object","description": "A newly minted key: safe metadata plus the secret, shown only once.",@@ -20637,6 +21222,119 @@"description": "Sort method for grouped queries (frecency not supported).","enum": ["viewed_at", "created_at", "updated_at", "viewed_updated"]},+ "Harness": {+ "type": "object",+ "description": "A registered user-run harness.\n\nClients deserialize this, so both derives are used.",+ "required": [+ "id",+ "kind",+ "name",+ "owner",+ "created_by",+ "created_at",+ "updated_at",+ "connected"+ ],+ "properties": {+ "connected": {+ "type": "boolean",+ "description": "Whether the daemon currently holds a runtime connection."+ },+ "created_at": {+ "type": "string",+ "format": "date-time",+ "description": "Creation timestamp."+ },+ "created_by": {+ "type": "string",+ "description": "User that registered this harness."+ },+ "id": {+ "$ref": "#/components/schemas/HarnessId",+ "description": "Harness id."+ },+ "kind": {+ "type": "string",+ "description": "Runtime kind. Currently always `macrod`."+ },+ "last_connected_at": {+ "type": ["string", "null"],+ "format": "date-time",+ "description": "When the daemon last attached a runtime connection."+ },+ "name": {+ "type": "string",+ "description": "Display name."+ },+ "owner": {+ "$ref": "#/components/schemas/HarnessOwner",+ "description": "Owner."+ },+ "updated_at": {+ "type": "string",+ "format": "date-time",+ "description": "Update timestamp."+ }+ }+ },+ "HarnessAgent": {+ "type": "object",+ "description": "An agent bound to a harness, as listed for the daemon.",+ "required": ["bot_id", "name", "handle"],+ "properties": {+ "bot_id": {+ "$ref": "#/components/schemas/BotId",+ "description": "The agent's bot id."+ },+ "handle": {+ "type": "string",+ "description": "Stable `@` handle."+ },+ "name": {+ "type": "string",+ "description": "Display name."+ }+ }+ },+ "HarnessId": {+ "type": "string"+ },+ "HarnessOwner": {+ "oneOf": [+ {+ "type": "object",+ "description": "User-owned (private) harness.",+ "required": ["user_id", "type"],+ "properties": {+ "type": {+ "type": "string",+ "enum": ["user"]+ },+ "user_id": {+ "type": "string",+ "description": "Owner user id."+ }+ }+ },+ {+ "type": "object",+ "description": "Team-owned harness, usable by every team member.",+ "required": ["team_id", "type"],+ "properties": {+ "team_id": {+ "type": "string",+ "format": "uuid",+ "description": "Owner team id."+ },+ "type": {+ "type": "string",+ "enum": ["team"]+ }+ }+ }+ ],+ "description": "Harness owner.\n\nExactly one of a user or a team, mirroring the bots owner pattern. There\nare no system harnesses."+ },"HashMap": {"type": "object","additionalProperties": {@@ -20940,6 +21638,46 @@}}},+ "PairingDetails": {+ "type": "object",+ "description": "A pending pairing, as shown to the approving user.",+ "required": ["code", "requested_name", "created_at", "expires_at"],+ "properties": {+ "code": {+ "type": "string",+ "description": "The pairing code, normalized to `XXXX-XXXX`."+ },+ "created_at": {+ "type": "string",+ "format": "date-time",+ "description": "When the pairing was created."+ },+ "expires_at": {+ "type": "string",+ "format": "date-time",+ "description": "When the pairing expires."+ },+ "host": {+ "type": ["string", "null"],+ "description": "Display-only description of the machine."+ },+ "requested_name": {+ "type": "string",+ "description": "Harness display name the daemon asked for."+ },+ "requested_scope": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/RequestedHarnessScope",+ "description": "The scope the daemon's config asked for, when it named one."+ }+ ]+ }+ }+ },"Params": {"type": "object","description": "Query parameters shared by soup endpoints.",@@ -21615,6 +22353,17 @@}}},+ "PendingClaimResponse": {+ "type": "object",+ "description": "Body returned while a claim is still waiting for approval.",+ "required": ["status"],+ "properties": {+ "status": {+ "type": "string",+ "description": "Always `pending`."+ }+ }+ },"PinRequest": {"type": "object","required": ["pinType"],@@ -22613,6 +23362,11 @@}}},+ "RequestedHarnessScope": {+ "type": "string",+ "description": "The ownership scope a daemon's config asks for.\n\nAdvisory, not binding: the approving user confirms it in the dialog, which\narrives preselected to this. Approval is what actually sets ownership.",+ "enum": ["private", "team"]+ },"RingStatus": {"type": "string","description": "Per-user status of an incoming-call ring, as reported by the\nring-status endpoint while a native client is ringing.",@@ -25023,6 +25777,17 @@"type": "string","description": "Harness used to run the agent."},+ "harness_id": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/HarnessId",+ "description": "Registered harness to run on. Required when `harness` is `macrod`,\nforbidden otherwise."+ }+ ]+ },"instructions": {"type": "string","description": "Instructions supplied to the agent at the start of a conversation."diff --git a/crates/agent_harness/Cargo.toml b/crates/agent_harness/Cargo.tomlindex a0aae9de6a..f1f07cd120 100644--- a/crates/agent_harness/Cargo.toml+++ b/crates/agent_harness/Cargo.toml@@ -19,6 +19,7 @@ anyhow = { workspace = true }axum = { workspace = true, features = ["ws"] }base64 = { workspace = true }bot_id = { path = "../bot_id" }+harness_id = { path = "../harness_id" }channel_sender = { path = "../channel_sender" }chrono = { workspace = true }channels = { path = "../channels", features = ["ports"] }@@ -57,4 +58,6 @@ workspace-hack = { version = "0.1", path = "../workspace-hack" }agent_fold = { path = "../agent_fold", features = ["test-utils"] }agent_session = { path = "../agent_session", features = ["test-utils"] }bot_id = { path = "../bot_id", features = ["test-utils"] }+harness_id = { path = "../harness_id", features = ["test-utils"] }mockall = { workspace = true }+model_user = { path = "../model_user" }diff --git a/crates/agent_harness/src/domain/model.rs b/crates/agent_harness/src/domain/model.rsindex 56f32a242b..54db102f1e 100644--- a/crates/agent_harness/src/domain/model.rs+++ b/crates/agent_harness/src/domain/model.rs@@ -91,6 +91,9 @@ impl AgentKind {match harness {"cursor" => Self::Cursor,"in-memory" | "macro-inmem" => Self::InMemory,+ // Registered macrod harnesses are the deliberate external case:+ // the agent's `harness_id` names whose daemon serves it.+ harness_id::MACROD_HARNESS_SLUG => Self::External,_ => Self::External,}}diff --git a/crates/agent_harness/src/domain/ports.rs b/crates/agent_harness/src/domain/ports.rsindex d419392b1d..4d95d29508 100644--- a/crates/agent_harness/src/domain/ports.rs+++ b/crates/agent_harness/src/domain/ports.rs@@ -1,9 +1,14 @@//! Outbound capabilities required by the harness domain.+use std::future::Future;+use std::pin::Pin;+use std::sync::Arc;+use agent_session::domain::connection::RuntimeAttachment;use agent_session::domain::model::{AgentSessionId, ReplicaAddress, SandboxSize};use agent_session::domain::ports::AgentConnector;use bot_id::BotId;+use harness_id::HarnessId;use macro_user_id::user_id::MacroUserIdStr;@@ -54,6 +59,35 @@ impl CommandForwarder for NoPeers {#[cfg(test)]mod test;+/// Resolves which registered harness currently serves a bot's sessions.+///+/// Resolved at bind time, not stamped at session creation, so rebinding an+/// agent to another harness re-routes its existing sessions.+pub trait HarnessBindings: Send + Sync + 'static {+ /// The bot's current harness binding, or `None` for an unbound bot.+ fn harness_for(+ &self,+ bot: BotId,+ ) -> impl Future<Output = anyhow::Result<Option<HarnessId>>> + Send;+}++/// Durable attach/detach bookkeeping for harness runtime connections.+///+/// The registry itself is in-process liveness; this is what lets the rest of+/// the product (the harness settings page) see whether a daemon is up.+/// Methods take `Arc<Self>` and return owned futures so the registry can fire+/// them from its own background tasks.+pub trait HarnessPresence: Send + Sync + 'static {+ /// A runtime attached for this harness.+ fn connected(self: Arc<Self>, harness: HarnessId) -> Pin<Box<dyn Future<Output = ()> + Send>>;++ /// This harness's runtime connection closed.+ fn disconnected(+ self: Arc<Self>,+ harness: HarnessId,+ ) -> Pin<Box<dyn Future<Output = ()> + Send>>;+}+/// Resolves the runtime configuration for a bot that may receive agent/// session triggers.pub trait AgentRuntimeDirectory: Send + Sync + 'static {diff --git a/crates/agent_harness/src/domain/service/test.rs b/crates/agent_harness/src/domain/service/test.rsindex 72d2f5eb52..261e5af89f 100644--- a/crates/agent_harness/src/domain/service/test.rs+++ b/crates/agent_harness/src/domain/service/test.rs@@ -182,12 +182,30 @@ type TestHarness = AgentHarnessService<>,MockContainerManager,AnnouncerMock,- Arc<RuntimeRegistry<ContainerSender>>,+ TestConnections,PromptContextMock,PromptComposerMock,EgressProvisionerMock,>;+/// Bot-to-harness bindings for tests: every bot maps to the harness sharing+/// its uuid, so tests attach runtimes by [`harness_for_bot`].+#[derive(Clone, Default)]+struct MirrorBindings;++impl crate::domain::ports::HarnessBindings for MirrorBindings {+ async fn harness_for(&self, bot: BotId) -> anyhow::Result<Option<harness_id::HarnessId>> {+ Ok(Some(harness_for_bot(bot)))+ }+}++fn harness_for_bot(bot: BotId) -> harness_id::HarnessId {+ harness_id::HarnessId::new_from_uuid(bot.as_uuid())+}++type TestConnections =+ crate::outbound::runtime_registry::HarnessKeyedConnections<MirrorBindings, ContainerSender>;+fn harness_with_edges(prompt_context: PromptContextMock,prompt_composer: PromptComposerMock,@@ -210,7 +228,7 @@ fn harness_with_edges(),containers.clone(),announcer.clone(),- Arc::clone(&runtimes),+ TestConnections::new(MirrorBindings, Arc::clone(&runtimes)),prompt_context,prompt_composer,EgressProvisionerMock::new(),@@ -1267,7 +1285,7 @@ async fn an_external_open_provisions_nothing_and_prompts_nobody() {// session: no handshake, no ACP session, nothing sent - a session nobody// is prompting costs the runtime nothing.let runtime = ContainerMock::default();- runtimes.attach(session.bot_id, runtime.clone());+ runtimes.attach(harness_for_bot(session.bot_id), runtime.clone());assert!(runtime.agent().received_requests().is_empty());assert!(repo.get(session.id)@@ -1307,7 +1325,7 @@ async fn a_bound_session_stays_on_its_connection_until_it_drops() {.expect("open");let first = ContainerMock::default();- runtimes.attach(session.bot_id, first.clone());+ runtimes.attach(harness_for_bot(session.bot_id), first.clone());let (result, ()) = tokio::join!(prompt(&service, session.id, "fix the failing test"),complete_bound_handshake(&first)@@ -1337,7 +1355,7 @@ async fn a_prompt_after_a_redial_restores_the_session_on_the_new_connection() {.expect("open");let first = ContainerMock::default();- runtimes.attach(session.bot_id, first.clone());+ runtimes.attach(harness_for_bot(session.bot_id), first.clone());let (result, ()) = tokio::join!(prompt(&service, session.id, "fix the failing test"),complete_bound_handshake(&first)@@ -1350,7 +1368,7 @@ async fn a_prompt_after_a_redial_restores_the_session_on_the_new_connection() {first.disconnects();await_disconnect(&repo, session.id).await;let second = ContainerMock::default();- runtimes.attach(session.bot_id, second.clone());+ runtimes.attach(harness_for_bot(session.bot_id), second.clone());assert!(second.agent().received_requests().is_empty());let (result, ()) = tokio::join!(@@ -1383,7 +1401,7 @@ async fn a_managed_session_opens_as_the_managed_default_bot() {),containers.clone(),AnnouncerMock::new(),- RuntimeRegistry::<ContainerSender>::new(),+ TestConnections::new(MirrorBindings, RuntimeRegistry::<ContainerSender>::new()),PromptContextMock::default(),PromptComposerMock::default(),EgressProvisionerMock::new(),@@ -1430,7 +1448,7 @@ async fn a_managed_session_resumes_its_sandbox_rather_than_a_dialed_in_runtime()// this deployment's to run, so the dial must not be what the session is// restored onto.let dialed_in = ContainerMock::default();- runtimes.attach(session.bot_id, dialed_in.clone());+ runtimes.attach(harness_for_bot(session.bot_id), dialed_in.clone());let prompted = service.control_event(id,@@ -1855,7 +1873,7 @@ async fn commands_for_a_peer_managed_session_forward_to_its_address() {),MockContainerManager::new(),AnnouncerMock::new(),- RuntimeRegistry::<ContainerSender>::new(),+ TestConnections::new(MirrorBindings, RuntimeRegistry::<ContainerSender>::new()),PromptContextMock::default(),PromptComposerMock::default(),EgressProvisionerMock::new(),@@ -1901,7 +1919,7 @@ async fn a_dead_peers_command_falls_back_to_local_execution() {),MockContainerManager::new(),AnnouncerMock::new(),- RuntimeRegistry::<ContainerSender>::new(),+ TestConnections::new(MirrorBindings, RuntimeRegistry::<ContainerSender>::new()),PromptContextMock::default(),PromptComposerMock::default(),EgressProvisionerMock::new(),diff --git a/crates/agent_harness/src/inbound/runtime_gateway.rs b/crates/agent_harness/src/inbound/runtime_gateway.rsindex 8fe0e704c5..d171c9825b 100644--- a/crates/agent_harness/src/inbound/runtime_gateway.rs+++ b/crates/agent_harness/src/inbound/runtime_gateway.rs@@ -1,34 +1,32 @@-//! The runtime gateway: where external runtimes dial in to serve a bot.+//! The runtime gateway: where user-run harnesses dial in to serve their agents.//!-//! `GET /runtime/ws`, authenticated with the standard bot credential headers-//! (`x-macro-bot-token`, `x-macro-bot-scope`) - a WebSocket upgrade is an-//! ordinary HTTP request, and every runtime dialing in is a real client that-//! can set headers.+//! `GET /runtime/ws`, authenticated with the harness credential header+//! (`x-macro-harness-token`) - a WebSocket upgrade is an ordinary HTTP request,+//! and every runtime dialing in is a real client that can set headers.//!-//! One connection per bot, not per session. ACP initializes per connection and-//! carries a `sessionId` on every session-scoped method, so one socket and one-//! harness process serve every session that bot is running. Which sessions-//! those are is not something the dial declares: the runtime dials once, and-//! sessions are bound to the connection as work arrives for them. A session-//! nobody is prompting costs nothing, and one prompted after a reconnect-//! restores itself on the way to being prompted.+//! One connection per harness, not per bot or per session. ACP initializes per+//! connection and carries a `sessionId` on every session-scoped method, so one+//! socket and one harness process serve every session of every agent bound to+//! the harness. Which sessions those are is not something the dial declares:+//! the runtime dials once, and sessions are bound to the connection as work+//! arrives for them. A session nobody is prompting costs nothing, and one+//! prompted after a reconnect restores itself on the way to being prompted.//!-//! Everything checkable is checked before the upgrade, so a bad dial fails with-//! an HTTP status rather than a dropped socket.+//! The token is the whole gate: a valid, unrevoked credential on a live+//! (undeleted) harness is exactly what the authorizer verifies, so a revoked+//! harness fails authentication rather than a later fact check.use std::sync::Arc;use agent_runtime_protocol::domain::schema::v0::{ToRuntimeMessage, ToServerMessage};use agent_runtime_protocol::outbound::websocket::connect_socket;-use agent_session::domain::ports::BotDirectory;use axum::Router;use axum::extract::ws::WebSocketUpgrade;use axum::extract::{FromRef, State};-use axum::http::StatusCode;-use axum::response::{IntoResponse, Response};+use axum::response::Response;use axum::routing::get;use macro_authorization::{- BotOnly, MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState,+ HarnessOnly, MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState,};use crate::outbound::runtime_registry::RuntimeRegistry;@@ -40,80 +38,61 @@ mod test;pub type GatewaySender = tokio::sync::mpsc::UnboundedSender<ToRuntimeMessage>;/// State for the runtime gateway route.-pub struct RuntimeGatewayState<Bots, Auth> {+pub struct RuntimeGatewayState<Auth> {runtimes: Arc<RuntimeRegistry<GatewaySender>>,- bots: Arc<Bots>,authorization_state: MacroAuthorizationState<Auth>,}-impl<Bots, Auth> RuntimeGatewayState<Bots, Auth> {+impl<Auth> RuntimeGatewayState<Auth> {/// Create gateway state.pub fn new(runtimes: Arc<RuntimeRegistry<GatewaySender>>,- bots: Arc<Bots>,authorization_state: MacroAuthorizationState<Auth>,) -> Self {Self {runtimes,- bots,authorization_state,}}}// Manual Clone impl: everything is behind an Arc.-impl<Bots, Auth> Clone for RuntimeGatewayState<Bots, Auth> {+impl<Auth> Clone for RuntimeGatewayState<Auth> {fn clone(&self) -> Self {Self {runtimes: Arc::clone(&self.runtimes),- bots: Arc::clone(&self.bots),authorization_state: self.authorization_state.clone(),}}}-impl<Bots, Auth> FromRef<RuntimeGatewayState<Bots, Auth>> for MacroAuthorizationState<Auth> {- fn from_ref(state: &RuntimeGatewayState<Bots, Auth>) -> Self {+impl<Auth> FromRef<RuntimeGatewayState<Auth>> for MacroAuthorizationState<Auth> {+ fn from_ref(state: &RuntimeGatewayState<Auth>) -> Self {state.authorization_state.clone()}}/// Build the router serving `GET /ws`. Mount it under `/runtime`.-pub fn runtime_gateway_router<Bots, Auth, S>(state: RuntimeGatewayState<Bots, Auth>) -> Router<S>+pub fn runtime_gateway_router<Auth, S>(state: RuntimeGatewayState<Auth>) -> Router<S>where- Bots: BotDirectory,Auth: MacroAuthorizationService,S: Clone + Send + Sync + 'static,{Router::new()- .route("/ws", get(dial_handler::<Bots, Auth>))+ .route("/ws", get(dial_handler::<Auth>)).with_state(state)}-/// Authenticate a dial and take the socket as this bot's connection.-async fn dial_handler<Bots, Auth>(- State(state): State<RuntimeGatewayState<Bots, Auth>>,- caller: MacroAuthorizationExtractor<Auth, BotOnly>,+/// Authenticate a dial and take the socket as this harness's connection.+async fn dial_handler<Auth>(+ State(state): State<RuntimeGatewayState<Auth>>,+ caller: MacroAuthorizationExtractor<Auth, HarnessOnly>,ws: WebSocketUpgrade,) -> Responsewhere- Bots: BotDirectory,Auth: MacroAuthorizationService,{- let bot = caller.authorization.bot_id;-- // Read rather than trusted from whenever the bot was set up: a bot whose- // agent-hood was revoked, or that turned out managed, must not dial in.- match state.bots.bot_facts(bot).await {- Ok(Some(facts)) if facts.has_agent && !facts.is_managed => {}- Ok(_) => {- return (StatusCode::FORBIDDEN, "not a dialable agent bot").into_response();- }- Err(error) => {- tracing::error!(error = ?error, %bot, "gateway bot lookup failed");- return (StatusCode::INTERNAL_SERVER_ERROR, "bot lookup failed").into_response();- }- }+ let harness = caller.authorization.harness_id;let runtimes = Arc::clone(&state.runtimes);ws.on_upgrade(move |socket| async move {@@ -121,7 +100,7 @@ where// Last dial wins. A runtime that redials has lost its old socket// whether or not this side has noticed, so displacing is the only// answer that lets it recover.- runtimes.attach(bot, transport);- tracing::info!(%bot, "a runtime dialed in");+ runtimes.attach(harness, transport);+ tracing::info!(%harness, "a runtime dialed in");})}diff --git a/crates/agent_harness/src/inbound/runtime_gateway/test.rs b/crates/agent_harness/src/inbound/runtime_gateway/test.rsindex 53a8d2ff5f..49b4294a70 100644--- a/crates/agent_harness/src/inbound/runtime_gateway/test.rs+++ b/crates/agent_harness/src/inbound/runtime_gateway/test.rs@@ -1,24 +1,23 @@//! What the dial route decides, end to end over a real socket: who may take-//! over a bot's connection, and what a refusal looks like to the runtime.+//! over a harness's connection, and what a refusal looks like to the runtime.//!//! A refusal has to be an HTTP status rather than a closed socket, so every//! rejection case asserts the status the upgrade failed with and that nothing//! reached the registry.use super::*;-use agent_session::domain::error::AgentSessionError;-use agent_session::domain::ports::BotFacts;-use bot_id::BotId;+use axum::http::StatusCode;+use harness_id::HarnessId;use macro_authorization::{- BOT_SCOPE_HEADER, BOT_TOKEN_HEADER, BotActingUserClaims, BotAuthentication, BotAuthorizer,- BotScope, InternalAuthConfig, JwtValidator, MacroAuthorizationError,- MacroAuthorizationServiceImpl, NoUserApiKeyAuthorizer, ValidatedIdentity,+ HARNESS_TOKEN_HEADER, HarnessAuthentication, HarnessAuthorizationOwner, HarnessAuthorizer,+ InternalAuthConfig, JwtValidator, MacroAuthorizationError, MacroAuthorizationServiceImpl,+ MacroUserAuthentication, NoBotAuthorizer, NoUserApiKeyAuthorizer, ValidatedIdentity,};use macro_user_id::user_id::MacroUserIdStr;use rootcause::Report;use tokio_tungstenite::tungstenite;-const BOT_TOKEN: &str = "mbot_self_test";+const HARNESS_TOKEN: &str = "mhns_self_test";#[derive(Clone, Default)]struct FakeJwtValidator;@@ -34,62 +33,44 @@ impl JwtValidator for FakeJwtValidator {}}-/// Authorizes exactly one token, as [`BotId::TEST_A`].+/// Authorizes exactly one token, as [`HarnessId::TEST_A`].#[derive(Clone)]-struct SelfBotAuthorizer;+struct SelfHarnessAuthorizer;-impl BotAuthorizer for SelfBotAuthorizer {- async fn authorize_bot(+impl HarnessAuthorizer for SelfHarnessAuthorizer {+ async fn authorize_harness(&self,- bot_token: &str,- bot_scope: BotScope,- _acting_user: Option<BotActingUserClaims>,- ) -> Result<BotAuthentication, Report<MacroAuthorizationError>> {- if bot_token != BOT_TOKEN {+ harness_token: &str,+ _acting_user_claim: Option<String>,+ ) -> Result<HarnessAuthentication, Report<MacroAuthorizationError>> {+ if harness_token != HARNESS_TOKEN {return Err(Report::new(MacroAuthorizationError::InvalidCredentials));}- Ok(BotAuthentication {- bot_id: BotId::TEST_A,+ let macro_user_id =+ MacroUserIdStr::try_from_email("[email protected]").expect("a valid email");+ let user_id = macro_user_id.as_ref().to_owned();+ Ok(HarnessAuthentication {+ harness_id: HarnessId::TEST_A,token_id: macro_uuid::generate_uuid_v7(),- bot_scope,- team_id: None,- acting_user: None,+ owner: HarnessAuthorizationOwner::User {+ user_id: user_id.clone(),+ },+ acting_user: MacroUserAuthentication {+ macro_user_id,+ user_context: model_user::UserContext {+ user_id,+ fusion_user_id: "fusion-owner".to_owned(),+ permissions: None,+ organization_id: None,+ },+ },})}}-/// Answers every lookup the same way.-enum FactsDirectory {- Known(BotFacts),- Unreadable,-}--impl BotDirectory for FactsDirectory {- async fn bot_facts(- &self,- _bot: BotId,- ) -> agent_session::domain::error::Result<Option<BotFacts>> {- match self {- Self::Known(facts) => Ok(Some(facts.clone())),- Self::Unreadable => Err(AgentSessionError::Unknown(anyhow::anyhow!(- "the bots table is unreachable"- ))),- }- }-}--/// A bot whose runtime its operator hosts: the only kind that may dial.-fn external_facts() -> BotFacts {- BotFacts {- has_agent: true,- is_managed: false,- owner_user_id: Some(MacroUserIdStr::try_from_email("[email protected]").unwrap()),- }-}-/// Serve the gateway on a loopback port, returning the registry it feeds and/// the `ws://` base to dial.-async fn serve(directory: FactsDirectory) -> (Arc<RuntimeRegistry<GatewaySender>>, String) {+async fn serve() -> (Arc<RuntimeRegistry<GatewaySender>>, String) {let runtimes = RuntimeRegistry::new();let authorization = MacroAuthorizationServiceImpl::new(FakeJwtValidator,@@ -97,14 +78,14 @@ async fn serve(directory: FactsDirectory) -> (Arc<RuntimeRegistry<GatewaySender>api_key: "test-internal-key".to_string(),default_user_id: None,},- SelfBotAuthorizer,+ NoBotAuthorizer,NoUserApiKeyAuthorizer,- );+ )+ .with_harness_authorizer(SelfHarnessAuthorizer);let app: Router = Router::new().nest("/runtime",runtime_gateway_router(RuntimeGatewayState::new(Arc::clone(&runtimes),- Arc::new(directory),MacroAuthorizationState::new(Arc::new(authorization)),)),);@@ -119,8 +100,7 @@ fn dial_request(base: &str, token: Option<&str>) -> tungstenite::handshake::clielet mut request = format!("{base}/runtime/ws").into_client_request().unwrap();if let Some(token) = token {let headers = request.headers_mut();- headers.insert(BOT_TOKEN_HEADER, token.parse().unwrap());- headers.insert(BOT_SCOPE_HEADER, "user".parse().unwrap());+ headers.insert(HARNESS_TOKEN_HEADER, token.parse().unwrap());}request}@@ -134,73 +114,37 @@ async fn rejected(request: tungstenite::handshake::client::Request) -> StatusCod}#[tokio::test]-async fn a_valid_dial_becomes_the_bots_connection() {- let (runtimes, base) = serve(FactsDirectory::Known(external_facts())).await;+async fn a_valid_dial_becomes_the_harness_connection() {+ let (runtimes, base) = serve().await;- let (_socket, _) = tokio_tungstenite::connect_async(dial_request(&base, Some(BOT_TOKEN)))+ let (_socket, _) = tokio_tungstenite::connect_async(dial_request(&base, Some(HARNESS_TOKEN))).await.expect("the dial is valid");// The registry is populated after the upgrade completes, so the assertion// is a wait rather than a read.- while !runtimes.is_connected(BotId::TEST_A) {+ while !runtimes.is_connected(HarnessId::TEST_A) {tokio::task::yield_now().await;}}#[tokio::test]async fn a_bad_token_is_unauthorized() {- let (runtimes, base) = serve(FactsDirectory::Known(external_facts())).await;+ let (runtimes, base) = serve().await;- let status = rejected(dial_request(&base, Some("mbot_wrong"))).await;+ let status = rejected(dial_request(&base, Some("mhns_wrong"))).await;assert_eq!(status, StatusCode::UNAUTHORIZED);- assert!(!runtimes.is_connected(BotId::TEST_A));+ assert!(!runtimes.is_connected(HarnessId::TEST_A));}#[tokio::test]async fn a_missing_token_is_rejected() {- let (runtimes, base) = serve(FactsDirectory::Known(external_facts())).await;+ let (runtimes, base) = serve().await;let status = rejected(dial_request(&base, None)).await;// No credentials at all: the extractor rejects before anything runs.assert_eq!(status, StatusCode::UNAUTHORIZED);- assert!(!runtimes.is_connected(BotId::TEST_A));-}--#[tokio::test]-async fn a_managed_bot_may_not_dial() {- let mut facts = external_facts();- facts.is_managed = true;- let (runtimes, base) = serve(FactsDirectory::Known(facts)).await;-- let status = rejected(dial_request(&base, Some(BOT_TOKEN))).await;-- assert_eq!(status, StatusCode::FORBIDDEN);- assert!(!runtimes.is_connected(BotId::TEST_A));-}--#[tokio::test]-async fn revoked_agenthood_may_not_dial() {- let mut facts = external_facts();- facts.has_agent = false;- let (runtimes, base) = serve(FactsDirectory::Known(facts)).await;-- let status = rejected(dial_request(&base, Some(BOT_TOKEN))).await;-- assert_eq!(status, StatusCode::FORBIDDEN);- assert!(!runtimes.is_connected(BotId::TEST_A));-}--#[tokio::test]-async fn an_unreadable_bot_lookup_fails_the_dial() {- let (runtimes, base) = serve(FactsDirectory::Unreadable).await;-- let status = rejected(dial_request(&base, Some(BOT_TOKEN))).await;-- // A lookup that failed is not a lookup that said no: the runtime is told- // to come back rather than that it is unwelcome.- assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR);- assert!(!runtimes.is_connected(BotId::TEST_A));+ assert!(!runtimes.is_connected(HarnessId::TEST_A));}diff --git a/crates/agent_harness/src/outbound/runtime_registry.rs b/crates/agent_harness/src/outbound/runtime_registry.rsindex 9f00c15c60..33ace29517 100644--- a/crates/agent_harness/src/outbound/runtime_registry.rs+++ b/crates/agent_harness/src/outbound/runtime_registry.rs@@ -1,13 +1,13 @@-//! The live runtime connections, one per bot that has dialed in.+//! The live runtime connections, one per harness that has dialed in.//!//! Held here rather than in the domain because a connection is liveness: it//! exists while a socket does, so it is never persisted and never survives a//! restart. What is durable is each session's `acp_session_id`, which is how a//! session re-establishes itself on whatever process dials in next.//!-//! One entry per bot. A bot's runtime dials once and carries every session that-//! bot serves, so this is what makes many ACP sessions share one harness-//! process.+//! One entry per harness. A harness's runtime dials once and carries every+//! session of every agent bound to it, so this is what makes many ACP sessions+//! - across many bots - share one harness process.use std::sync::Arc;@@ -17,21 +17,24 @@ use agent_session::domain::connection::{RuntimeAttachment, RuntimeConnection, Seuse agent_session::domain::model::AgentSessionId;use bot_id::BotId;use dashmap::DashMap;+use harness_id::HarnessId;-use crate::domain::ports::RuntimeConnections;+use crate::domain::ports::{HarnessBindings, HarnessPresence, RuntimeConnections};#[cfg(test)]mod test;-/// Every bot's live runtime connection.+/// Every harness's live runtime connection.pub struct RuntimeRegistry<Sender> {- connections: DashMap<BotId, Arc<RuntimeConnection<Sender>>>,+ connections: DashMap<HarnessId, Arc<RuntimeConnection<Sender>>>,+ presence: Option<Arc<dyn HarnessPresence>>,}impl<Sender> Default for RuntimeRegistry<Sender> {fn default() -> Self {Self {connections: DashMap::new(),+ presence: None,}}}@@ -46,10 +49,19 @@ whereArc::new(Self::default())}- /// Whether a bot currently has a runtime connected.+ /// An empty registry that reports attach/detach to `presence`.#[must_use]- pub fn is_connected(&self, bot: BotId) -> bool {- self.connections.contains_key(&bot)+ pub fn with_presence(presence: Arc<dyn HarnessPresence>) -> Arc<Self> {+ Arc::new(Self {+ connections: DashMap::new(),+ presence: Some(presence),+ })+ }++ /// Whether a harness currently has a runtime connected.+ #[must_use]+ pub fn is_connected(&self, harness: HarnessId) -> bool {+ self.connections.contains_key(&harness)}}@@ -57,11 +69,11 @@ impl<Sender> RuntimeRegistry<Sender>whereSender: TransportSender<ToRuntimeMessage>,{- /// Take over as `bot`'s connection, displacing whatever it had.+ /// Take over as `harness`'s connection, displacing whatever it had.////// Last dial wins: a runtime that redials has necessarily lost its old/// socket, and the sessions it was carrying rebind as they are next used.- pub fn attach<Carrier>(self: &Arc<Self>, bot: BotId, carrier: Carrier)+ pub fn attach<Carrier>(self: &Arc<Self>, harness: HarnessId, carrier: Carrier)whereCarrier: Transport<ToRuntimeMessage, ToServerMessage, Sender = Sender>,{@@ -70,22 +82,29 @@ where// Listed before it is watched: a socket that dies immediately would// otherwise have its eviction run before the entry it is meant to// remove exists, leaving the dead connection listed for good.- if let Some(displaced) = self.connections.insert(bot, Arc::clone(&connection)) {+ if let Some(displaced) = self.connections.insert(harness, Arc::clone(&connection)) {displaced.evict();- tracing::info!(%bot, "a redialed runtime replaced this bot's connection");+ tracing::info!(%harness, "a redialed runtime replaced this harness's connection");}- self.watch_for_close(bot, connection);+ if let Some(presence) = &self.presence {+ tokio::spawn(Arc::clone(presence).connected(harness));+ }+ self.watch_for_close(harness, connection);}/// Drop `connection` from the registry once its transport ends.///- /// Without this, a bot whose runtime went away keeps an entry that+ /// Without this, a harness whose runtime went away keeps an entry that/// [`RuntimeConnections::bind`] will hand out: sessions attach to a closed/// socket, their handshake writes succeed into nothing, and every prompt/// fails until some later dial happens to displace it. A registry of live/// connections has to stop listing the dead ones.- fn watch_for_close(self: &Arc<Self>, bot: BotId, connection: Arc<RuntimeConnection<Sender>>) {- tokio::spawn(Arc::clone(self).drop_when_closed(bot, connection));+ fn watch_for_close(+ self: &Arc<Self>,+ harness: HarnessId,+ connection: Arc<RuntimeConnection<Sender>>,+ ) {+ tokio::spawn(Arc::clone(self).drop_when_closed(harness, connection));}/// The body of that watch: wait for the end, then unlist it.@@ -94,25 +113,48 @@ where/// race a task it has no handle on.async fn drop_when_closed(self: Arc<Self>,- bot: BotId,+ harness: HarnessId,connection: Arc<RuntimeConnection<Sender>>,) {connection.closed().await;// Only if it is still this connection: a redial that already replaced// it owns the entry now, and evicting that would take the live socket- // down along with the dead one.+ // down along with the dead one. The presence write follows the same+ // rule, so a displaced socket's death never marks the live redial+ // disconnected.let removed = self.connections- .remove_if(&bot, |_, current| Arc::ptr_eq(current, &connection))+ .remove_if(&harness, |_, current| Arc::ptr_eq(current, &connection)).is_some();if removed {- tracing::info!(%bot, "dropped this bot's closed runtime connection");+ if let Some(presence) = &self.presence {+ tokio::spawn(Arc::clone(presence).disconnected(harness));+ }+ tracing::info!(%harness, "dropped this harness's closed runtime connection");}}}-impl<Sender> RuntimeConnections for Arc<RuntimeRegistry<Sender>>+/// [`RuntimeConnections`] over the harness-keyed registry.+///+/// The domain binds sessions by bot; this resolves the bot's *current*+/// harness binding on every bind, so rebinding an agent to another harness+/// re-routes its existing sessions without restamping anything.+pub struct HarnessKeyedConnections<Bindings, Sender> {+ bindings: Bindings,+ registry: Arc<RuntimeRegistry<Sender>>,+}++impl<Bindings, Sender> HarnessKeyedConnections<Bindings, Sender> {+ /// Wrap the registry with a bot-to-harness resolver.+ pub fn new(bindings: Bindings, registry: Arc<RuntimeRegistry<Sender>>) -> Self {+ Self { bindings, registry }+ }+}++impl<Bindings, Sender> RuntimeConnections for HarnessKeyedConnections<Bindings, Sender>where+ Bindings: HarnessBindings,Sender: TransportSender<ToRuntimeMessage>,{type Connector = SessionChannel<Sender>;@@ -122,7 +164,19 @@ wherebot: BotId,session: AgentSessionId,) -> Option<RuntimeAttachment<SessionChannel<Sender>>> {- let connection = self.connections.get(&bot).map(|entry| Arc::clone(&entry))?;+ let harness = match self.bindings.harness_for(bot).await {+ Ok(Some(harness)) => harness,+ Ok(None) => return None,+ Err(error) => {+ tracing::error!(error = ?error, %bot, "bot-to-harness resolution failed");+ return None;+ }+ };+ let connection = self+ .registry+ .connections+ .get(&harness)+ .map(|entry| Arc::clone(&entry))?;Some(connection.bind(session).await)}}diff --git a/crates/agent_harness/src/outbound/runtime_registry/test.rs b/crates/agent_harness/src/outbound/runtime_registry/test.rsindex 28da30152a..a5e7bb3486 100644--- a/crates/agent_harness/src/outbound/runtime_registry/test.rs+++ b/crates/agent_harness/src/outbound/runtime_registry/test.rs@@ -1,16 +1,52 @@//! Binding rules of the registry: what a session finds when it looks for its-//! bot's runtime, and what a redial does to whatever was there.+//! bot's runtime - resolved through the bot's harness binding - and what a+//! redial does to whatever was there.++use std::collections::HashMap;+use std::future::Future;+use std::sync::Mutex;use super::*;use crate::testing::helpers::containers::{ContainerMock, ContainerSender};+/// Static bot-to-harness bindings for tests.+#[derive(Default)]+struct FakeBindings {+ bindings: Mutex<HashMap<BotId, HarnessId>>,+}++impl FakeBindings {+ fn bound(bot: BotId, harness: HarnessId) -> Self {+ let bindings = Self::default();+ bindings.bindings.lock().unwrap().insert(bot, harness);+ bindings+ }+}++impl HarnessBindings for Arc<FakeBindings> {+ async fn harness_for(&self, bot: BotId) -> anyhow::Result<Option<HarnessId>> {+ Ok(self.bindings.lock().unwrap().get(&bot).copied())+ }+}++fn connections(+ bindings: Arc<FakeBindings>,+ registry: &Arc<RuntimeRegistry<ContainerSender>>,+) -> HarnessKeyedConnections<Arc<FakeBindings>, ContainerSender> {+ HarnessKeyedConnections::new(bindings, Arc::clone(registry))+}+#[tokio::test]-async fn a_bot_with_no_runtime_has_nothing_to_bind_to() {+async fn a_harness_with_no_runtime_has_nothing_to_bind_to() {let registry = RuntimeRegistry::<ContainerSender>::new();+ let bound = connections(+ Arc::new(FakeBindings::bound(BotId::TEST_A, HarnessId::TEST_A)),+ ®istry,+ );- assert!(!registry.is_connected(BotId::TEST_A));+ assert!(!registry.is_connected(HarnessId::TEST_A));assert!(- registry+ bound.bind(BotId::TEST_A, AgentSessionId::TEST_A).await.is_none()@@ -18,43 +54,94 @@ async fn a_bot_with_no_runtime_has_nothing_to_bind_to() {}#[tokio::test]-async fn a_session_binds_onto_its_bots_connection() {+async fn a_session_binds_onto_its_harness_connection() {let registry = RuntimeRegistry::new();- registry.attach(BotId::TEST_A, ContainerMock::default());+ registry.attach(HarnessId::TEST_A, ContainerMock::default());+ let bound = connections(+ Arc::new(FakeBindings::bound(BotId::TEST_A, HarnessId::TEST_A)),+ ®istry,+ );- assert!(registry.is_connected(BotId::TEST_A));+ assert!(registry.is_connected(HarnessId::TEST_A));assert!(- registry+ bound.bind(BotId::TEST_A, AgentSessionId::TEST_A).await.is_some());- // A connection belongs to one bot only.+ // An unbound bot finds nothing, whatever is connected.assert!(- registry+ bound.bind(BotId::TEST_B, AgentSessionId::TEST_A).await.is_none());}+#[tokio::test]+async fn a_bot_bound_to_a_disconnected_harness_has_nothing_to_bind_to() {+ let registry = RuntimeRegistry::new();+ registry.attach(HarnessId::TEST_A, ContainerMock::default());+ let bound = connections(+ Arc::new(FakeBindings::bound(BotId::TEST_A, HarnessId::TEST_B)),+ ®istry,+ );++ assert!(+ bound+ .bind(BotId::TEST_A, AgentSessionId::TEST_A)+ .await+ .is_none()+ );+}++#[tokio::test]+async fn many_bots_sessions_share_one_harness_connection() {+ let registry = RuntimeRegistry::new();+ registry.attach(HarnessId::TEST_A, ContainerMock::default());+ let bindings = Arc::new(FakeBindings::bound(BotId::TEST_A, HarnessId::TEST_A));+ bindings+ .bindings+ .lock()+ .unwrap()+ .insert(BotId::TEST_B, HarnessId::TEST_A);+ let bound = connections(bindings, ®istry);++ assert!(+ bound+ .bind(BotId::TEST_A, AgentSessionId::TEST_A)+ .await+ .is_some()+ );+ assert!(+ bound+ .bind(BotId::TEST_B, AgentSessionId::TEST_B)+ .await+ .is_some()+ );+}+#[tokio::test]async fn a_redial_displaces_the_previous_connection() {let registry = RuntimeRegistry::new();- registry.attach(BotId::TEST_A, ContainerMock::default());- registry+ registry.attach(HarnessId::TEST_A, ContainerMock::default());+ let bound = connections(+ Arc::new(FakeBindings::bound(BotId::TEST_A, HarnessId::TEST_A)),+ ®istry,+ );+ bound.bind(BotId::TEST_A, AgentSessionId::TEST_A).await.expect("the first dial is bindable");- registry.attach(BotId::TEST_A, ContainerMock::default());+ registry.attach(HarnessId::TEST_A, ContainerMock::default());- // Displacing leaves the bot connected, and the session that was riding on- // the old connection binds again onto the new one - which is how a+ // Displacing leaves the harness connected, and the session that was riding+ // on the old connection binds again onto the new one - which is how a// reconnect restores it.- assert!(registry.is_connected(BotId::TEST_A));+ assert!(registry.is_connected(HarnessId::TEST_A));assert!(- registry+ bound.bind(BotId::TEST_A, AgentSessionId::TEST_A).await.is_some()@@ -65,22 +152,26 @@ async fn a_redial_displaces_the_previous_connection() {async fn a_closed_connection_is_unlisted_so_nothing_binds_onto_it() {let registry = RuntimeRegistry::new();let runtime = ContainerMock::default();- registry.attach(BotId::TEST_A, runtime.clone());+ registry.attach(HarnessId::TEST_A, runtime.clone());let connection = registry.connections- .get(&BotId::TEST_A)+ .get(&HarnessId::TEST_A).map(|entry| Arc::clone(&entry)).expect("the dial is listed");+ let bound = connections(+ Arc::new(FakeBindings::bound(BotId::TEST_A, HarnessId::TEST_A)),+ ®istry,+ );runtime.disconnects();// The same work `attach` spawns, awaited here rather than raced.Arc::clone(®istry)- .drop_when_closed(BotId::TEST_A, connection)+ .drop_when_closed(HarnessId::TEST_A, connection).await;- assert!(!registry.is_connected(BotId::TEST_A));+ assert!(!registry.is_connected(HarnessId::TEST_A));assert!(- registry+ bound.bind(BotId::TEST_A, AgentSessionId::TEST_A).await.is_none()@@ -91,24 +182,28 @@ async fn a_closed_connection_is_unlisted_so_nothing_binds_onto_it() {async fn a_redials_connection_outlives_the_one_it_displaced() {let registry = RuntimeRegistry::new();let first = ContainerMock::default();- registry.attach(BotId::TEST_A, first.clone());+ registry.attach(HarnessId::TEST_A, first.clone());let displaced = registry.connections- .get(&BotId::TEST_A)+ .get(&HarnessId::TEST_A).map(|entry| Arc::clone(&entry)).expect("the first dial is listed");+ let bound = connections(+ Arc::new(FakeBindings::bound(BotId::TEST_A, HarnessId::TEST_A)),+ ®istry,+ );- registry.attach(BotId::TEST_A, ContainerMock::default());+ registry.attach(HarnessId::TEST_A, ContainerMock::default());first.disconnects();Arc::clone(®istry)- .drop_when_closed(BotId::TEST_A, displaced)+ .drop_when_closed(HarnessId::TEST_A, displaced).await;// The dead connection's eviction must not unlist the live one that took- // its place, or a redial would leave the bot unreachable.- assert!(registry.is_connected(BotId::TEST_A));+ // its place, or a redial would leave the harness unreachable.+ assert!(registry.is_connected(HarnessId::TEST_A));assert!(- registry+ bound.bind(BotId::TEST_A, AgentSessionId::TEST_A).await.is_some()@@ -116,20 +211,56 @@ async fn a_redials_connection_outlives_the_one_it_displaced() {}#[tokio::test]-async fn one_connection_carries_many_sessions() {- let registry = RuntimeRegistry::new();- registry.attach(BotId::TEST_A, ContainerMock::default());+async fn attach_and_close_report_presence() {+ #[derive(Default)]+ struct RecordingPresence {+ events: Mutex<Vec<(HarnessId, &'static str)>>,+ }- assert!(- registry- .bind(BotId::TEST_A, AgentSessionId::TEST_A)- .await- .is_some()- );- assert!(- registry- .bind(BotId::TEST_A, AgentSessionId::TEST_B)- .await- .is_some()- );+ impl HarnessPresence for RecordingPresence {+ fn connected(+ self: Arc<Self>,+ harness: HarnessId,+ ) -> std::pin::Pin<Box<dyn Future<Output = ()> + Send>> {+ Box::pin(async move {+ self.events.lock().unwrap().push((harness, "connected"));+ })+ }++ fn disconnected(+ self: Arc<Self>,+ harness: HarnessId,+ ) -> std::pin::Pin<Box<dyn Future<Output = ()> + Send>> {+ Box::pin(async move {+ self.events.lock().unwrap().push((harness, "disconnected"));+ })+ }+ }++ let presence = Arc::new(RecordingPresence::default());+ let registry: Arc<RuntimeRegistry<ContainerSender>> =+ RuntimeRegistry::with_presence(Arc::clone(&presence) as Arc<dyn HarnessPresence>);+ let runtime = ContainerMock::default();+ registry.attach(HarnessId::TEST_A, runtime.clone());+ let connection = registry+ .connections+ .get(&HarnessId::TEST_A)+ .map(|entry| Arc::clone(&entry))+ .expect("the dial is listed");++ runtime.disconnects();+ Arc::clone(®istry)+ .drop_when_closed(HarnessId::TEST_A, connection)+ .await;++ // The connected write is spawned; give it a beat to land.+ for _ in 0..100 {+ if presence.events.lock().unwrap().len() >= 2 {+ break;+ }+ tokio::task::yield_now().await;+ }+ let events = presence.events.lock().unwrap().clone();+ assert!(events.contains(&(HarnessId::TEST_A, "connected")));+ assert!(events.contains(&(HarnessId::TEST_A, "disconnected")));}diff --git a/crates/agent_session/Cargo.toml b/crates/agent_session/Cargo.tomlindex 71a8c17972..e121d87f8f 100644--- a/crates/agent_session/Cargo.toml+++ b/crates/agent_session/Cargo.toml@@ -11,6 +11,7 @@ test-utils = ["dep:mockall", "agent_fold/test-utils"][dependencies]agent-client-protocol = { workspace = true }+harness_id = { path = "../harness_id" }agent = { path = "../agent" }ai_usage = { path = "../ai_usage" }dashmap = { workspace = true }@@ -50,6 +51,8 @@ workspace-hack = { version = "0.1", path = "../workspace-hack" }[dev-dependencies]agent-client-protocol = { workspace = true }bot_id = { path = "../bot_id", features = ["test-utils"] }+harness_id = { path = "../harness_id", features = ["test-utils"] }+model_user = { path = "../model_user" }non_empty = { path = "../non_empty" }agent_fold = { path = "../agent_fold", features = ["test-utils"] }axum = { workspace = true, features = ["ws"] }diff --git a/crates/agent_session/src/domain/ports.rs b/crates/agent_session/src/domain/ports.rsindex 7a1f321422..0ed3fff4cc 100644--- a/crates/agent_session/src/domain/ports.rs+++ b/crates/agent_session/src/domain/ports.rs@@ -30,6 +30,8 @@ pub struct BotFacts {pub is_managed: bool,/// The user who owns the bot, when it is user-owned.pub owner_user_id: Option<MacroUserIdStr<'static>>,+ /// The registered harness this bot's agent is bound to, when it is one.+ pub harness_id: Option<harness_id::HarnessId>,}/// Read-only lookup of the bots sessions may be opened for.diff --git a/crates/agent_session/src/inbound/axum_router.rs b/crates/agent_session/src/inbound/axum_router.rsindex c3c022df5b..e238ef4798 100644--- a/crates/agent_session/src/inbound/axum_router.rs+++ b/crates/agent_session/src/inbound/axum_router.rs@@ -33,7 +33,7 @@ use entity_access::domain::ports::EntityAccessService;use entity_access::inbound::axum_extractors::AgentSessionAccessLevelExtractor;use macro_authorization::{ActingUser, MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState,- UserOrBot, UserOrBotAuthorization,+ UserBotOrHarness, UserBotOrHarnessAuthorization,};use macro_user_id::user_id::MacroUserIdStr;use macro_uuid::Uuid;@@ -535,7 +535,7 @@ pub async fn control_agent_session_handler<>(_access: AgentSessionAccessLevelExtractor<OwnerAccessLevel, Access, Auth>,State(state): State<AgentSessionControlState<R, Access, Auth>>,- caller: MacroAuthorizationExtractor<Auth, UserOrBot>,+ caller: MacroAuthorizationExtractor<Auth, UserBotOrHarness>,Path(session_id): Path<Uuid>,Json(req): Json<ControlRequest>,) -> Result<Json<AgentActionId>, AgentSessionApiError> {@@ -1121,17 +1121,21 @@ fn validate_workspace(workspace: &str) -> Result<(), CreateSessionApiError> {/// Resolve which bot the session runs for, from the principal and the body.fn resolve_bot(- caller: &UserOrBotAuthorization,+ caller: &UserBotOrHarnessAuthorization,body_bot: Option<Uuid>,) -> Result<BotId, CreateSessionApiError> {match caller {- UserOrBotAuthorization::Bot(bot) => match body_bot {+ UserBotOrHarnessAuthorization::Bot(bot) => match body_bot {Some(named) if named != bot.bot_id.as_uuid() => Err(CreateSessionApiError::NotYourBot),_ => Ok(bot.bot_id),},- UserOrBotAuthorization::User(_) => body_bot- .map(BotId::new_from_uuid)- .ok_or(CreateSessionApiError::BotRequired),+ // A harness serves many bots, so nothing is implied by the token: the+ // body must say which bound agent this session runs for.+ UserBotOrHarnessAuthorization::User(_) | UserBotOrHarnessAuthorization::Harness(_) => {+ body_bot+ .map(BotId::new_from_uuid)+ .ok_or(CreateSessionApiError::BotRequired)+ }}}@@ -1139,11 +1143,21 @@ fn resolve_bot(////// A user caller always owns their own sessions. A bot caller's verified/// acting user wins when present; otherwise the body's claimed owner is-/// accepted (see [`CreateAgentSessionRequest::owner`] for the trust model).+/// accepted (see [`CreateAgentSessionRequest::owner`] for the trust model). A+/// harness caller always has a verified acting user - the harness owner by+/// default - so the body's claim wins for it the way it does for bots: the+/// daemon opens sessions for whoever mentioned the agent, and channel-scoped+/// mention senders need not be verifiable against harness ownership.fn resolve_owner(- caller: &UserOrBotAuthorization,+ caller: &UserBotOrHarnessAuthorization,claimed: Option<String>,) -> Result<MacroUserIdStr<'static>, CreateSessionApiError> {+ if let UserBotOrHarnessAuthorization::Harness(_) = caller+ && let Some(claimed) = claimed+ {+ return MacroUserIdStr::try_from(claimed)+ .map_err(|_| CreateSessionApiError::UnparseableOwner);+ }if let Some(user) = caller.acting_user() {return Ok(user.macro_user_id.clone());}@@ -1180,7 +1194,7 @@ pub async fn create_agent_session_handler<Auth: MacroAuthorizationService,>(State(state): State<CreateSessionState<Opener, Bots, Auth>>,- caller: MacroAuthorizationExtractor<Auth, UserOrBot>,+ caller: MacroAuthorizationExtractor<Auth, UserBotOrHarness>,Json(request): Json<CreateAgentSessionRequest>,) -> Result<(StatusCode, Json<CreateAgentSessionResponse>), CreateSessionApiError> {// Blank instructions are "none" stated clumsily; normalized once here so@@ -1229,6 +1243,7 @@ pub async fn create_agent_session_handler<has_agent,is_managed,owner_user_id,+ harness_id,} = state.bots.bot_facts(bot_id)@@ -1243,11 +1258,17 @@ pub async fn create_agent_session_handler<// A team-owned bot has no owner_user_id, so no user token passes this// check: its sessions are opened with the bot's own token until team// membership is modeled here.- if let UserOrBotAuthorization::User(user) = &caller.authorization+ if let UserBotOrHarnessAuthorization::User(user) = &caller.authorization&& owner_user_id.as_ref() != Some(&user.macro_user_id){return Err(CreateSessionApiError::NotYourBot);}+ // A harness may open sessions only for agents currently bound to it.+ if let UserBotOrHarnessAuthorization::Harness(harness) = &caller.authorization+ && harness_id != Some(harness.harness_id)+ {+ return Err(CreateSessionApiError::NotYourBot);+ }validate_workspace(&workspace)?;let owner = resolve_owner(&caller.authorization, request.owner)?;diff --git a/crates/agent_session/src/inbound/axum_router/test.rs b/crates/agent_session/src/inbound/axum_router/test.rsindex 42ff459b94..4f88deab58 100644--- a/crates/agent_session/src/inbound/axum_router/test.rs+++ b/crates/agent_session/src/inbound/axum_router/test.rs@@ -5,14 +5,17 @@ use axum::http::{Request, header};use chrono::Utc;use macro_authorization::{BOT_SCOPE_HEADER, BOT_TOKEN_HEADER, BotActingUserClaims, BotAuthentication, BotAuthorizer,- BotScope, InternalAuthConfig, JwtValidator, MacroAuthorizationError,- MacroAuthorizationServiceImpl, NoUserApiKeyAuthorizer, ValidatedIdentity,+ BotScope, HARNESS_TOKEN_HEADER, HarnessAuthentication, HarnessAuthorizationOwner,+ HarnessAuthorizer, InternalAuthConfig, JwtValidator, MacroAuthorizationError,+ MacroAuthorizationServiceImpl, MacroUserAuthentication, NoUserApiKeyAuthorizer,+ ValidatedIdentity,};use rootcause::Report;use std::sync::{Arc, Mutex};use tower::ServiceExt;const BOT_TOKEN: &str = "mbot_self_test";+const HARNESS_TOKEN: &str = "mhns_self_test";const OWNER: &str = "macro|[email protected]";const STRANGER: &str = "macro|[email protected]";@@ -54,6 +57,43 @@ impl BotAuthorizer for SelfBotAuthorizer {}}+/// Accepts exactly [`HARNESS_TOKEN`] as [`harness_id::HarnessId::TEST_A`],+/// acting for [`OWNER`].+#[derive(Clone)]+struct SelfHarnessAuthorizer;++impl HarnessAuthorizer for SelfHarnessAuthorizer {+ async fn authorize_harness(+ &self,+ harness_token: &str,+ acting_user_claim: Option<String>,+ ) -> Result<HarnessAuthentication, Report<MacroAuthorizationError>> {+ if harness_token != HARNESS_TOKEN {+ return Err(Report::new(MacroAuthorizationError::InvalidCredentials));+ }+ let macro_user_id =+ MacroUserIdStr::try_from(acting_user_claim.unwrap_or_else(|| OWNER.to_owned()))+ .map_err(|_| Report::new(MacroAuthorizationError::ActingUserNotAuthorized))?;+ let user_id = macro_user_id.as_ref().to_owned();+ Ok(HarnessAuthentication {+ harness_id: harness_id::HarnessId::TEST_A,+ token_id: Uuid::new_v4(),+ owner: HarnessAuthorizationOwner::User {+ user_id: user_id.clone(),+ },+ acting_user: MacroUserAuthentication {+ macro_user_id,+ user_context: model_user::UserContext {+ user_id,+ fusion_user_id: "fusion-owner".to_owned(),+ permissions: None,+ organization_id: None,+ },+ },+ })+ }+}+/// Records opens and answers with a canned session row.#[derive(Default)]struct RecordingOpener {@@ -140,6 +180,7 @@ impl OneBotDirectory {has_agent: true,is_managed: false,owner_user_id: Some(MacroUserIdStr::try_from(OWNER.to_owned()).unwrap()),+ harness_id: Some(harness_id::HarnessId::TEST_A),},}}@@ -150,6 +191,7 @@ impl OneBotDirectory {has_agent: true,is_managed: true,owner_user_id: None,+ harness_id: None,},}}@@ -160,6 +202,7 @@ impl OneBotDirectory {has_agent: false,is_managed: false,owner_user_id: Some(MacroUserIdStr::try_from(OWNER.to_owned()).unwrap()),+ harness_id: None,},}}@@ -180,7 +223,8 @@ fn router_for(opener: Arc<RecordingOpener>, bots: OneBotDirectory) -> Router {},SelfBotAuthorizer,NoUserApiKeyAuthorizer,- );+ )+ .with_harness_authorizer(SelfHarnessAuthorizer);agent_session_create_router(CreateSessionState::new(opener,Arc::new(bots),@@ -215,6 +259,14 @@ fn as_bot(request_body: String) -> Request<Body> {.unwrap()}+fn as_harness(request_body: String) -> Request<Body> {+ Request::post("/")+ .header(header::CONTENT_TYPE, "application/json")+ .header(HARNESS_TOKEN_HEADER, HARNESS_TOKEN)+ .body(Body::from(request_body))+ .unwrap()+}+fn as_user(user: &str, request_body: String) -> Request<Body> {Request::post("/").header(header::CONTENT_TYPE, "application/json")@@ -304,6 +356,57 @@ async fn a_bot_may_not_name_another_bot() {assert!(opener.opened.lock().unwrap().is_empty());}+#[tokio::test]+async fn a_harness_opens_a_session_for_a_bound_agent() {+ let opener = Arc::new(RecordingOpener::default());+ let request = as_harness(body(+ Some(BotId::TEST_A.as_uuid()),+ "/srv/agent",+ Some(STRANGER),+ ));++ let response = router(opener.clone()).oneshot(request).await.unwrap();++ assert_eq!(response.status(), StatusCode::CREATED);+ let opened = opener.opened.lock().unwrap();+ assert_eq!(opened[0].bot_id, BotId::TEST_A);+ // The body's claimed owner wins for harness callers: the daemon opens+ // sessions for whoever mentioned the agent.+ assert_eq!(opened[0].owner.as_ref(), STRANGER);+}++#[tokio::test]+async fn a_harness_may_not_open_sessions_for_an_unbound_agent() {+ // The one bot the directory serves is bound to a different harness.+ let opener = Arc::new(RecordingOpener::default());+ let mut bots = OneBotDirectory::external_agent();+ bots.facts.harness_id = Some(harness_id::HarnessId::TEST_B);+ let request = as_harness(body(+ Some(BotId::TEST_A.as_uuid()),+ "/srv/agent",+ Some(OWNER),+ ));++ let response = router_for(opener.clone(), bots)+ .oneshot(request)+ .await+ .unwrap();++ assert_eq!(response.status(), StatusCode::FORBIDDEN);+ assert!(opener.opened.lock().unwrap().is_empty());+}++#[tokio::test]+async fn a_harness_caller_must_name_a_bot() {+ let opener = Arc::new(RecordingOpener::default());+ let request = as_harness(body(None, "/srv/agent", Some(OWNER)));++ let response = router(opener.clone()).oneshot(request).await.unwrap();++ assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);+ assert!(opener.opened.lock().unwrap().is_empty());+}+#[tokio::test]async fn a_user_caller_must_name_a_bot() {let opener = Arc::new(RecordingOpener::default());diff --git a/crates/agent_trigger/src/domain/service/test.rs b/crates/agent_trigger/src/domain/service/test.rsindex 47483a90a3..760143e6da 100644--- a/crates/agent_trigger/src/domain/service/test.rs+++ b/crates/agent_trigger/src/domain/service/test.rs@@ -61,6 +61,7 @@ fn agent_with(bot_id: BotId, owner: BotOwner, channel_scope: AgentChannelScope)bot: owned_bot(bot_id, owner),instructions: String::new(),harness: "in-memory".to_owned(),+ harness_id: None,default_model: "model".to_owned(),channel_scope,channel_ids: vec![],diff --git a/crates/bots/Cargo.toml b/crates/bots/Cargo.tomlindex a3428a9fff..c9f3e5d36b 100644--- a/crates/bots/Cargo.toml+++ b/crates/bots/Cargo.toml@@ -38,6 +38,7 @@ async-trait = { workspace = true, optional = true }axum = { workspace = true, optional = true }bot_id = { path = "../bot_id", features = ["schema"] }bot_token = { path = "../bot_token" }+harness_id = { path = "../harness_id", features = ["schema", "sqlx"] }channels = { path = "../channels", optional = true, default-features = false, features = ["ports"] }chrono = { workspace = true }entity_access = { path = "../entity_access", optional = true, default-features = false }diff --git a/crates/bots/src/domain/models.rs b/crates/bots/src/domain/models.rsindex e04ca6775b..d84f8f85a8 100644--- a/crates/bots/src/domain/models.rs+++ b/crates/bots/src/domain/models.rs@@ -7,6 +7,27 @@ use uuid::Uuid;/// Shared bot id used by bot principals.pub use bot_id::BotId;+/// Shared harness id used by agent-harness bindings.+pub use harness_id::HarnessId;++/// Owner of a registered harness an agent wants to run on.+///+/// Kept minimal on purpose: the bots domain only needs enough to decide+/// whether a caller may bind an agent to the harness. Mirrors the harnesses+/// domain's `HarnessOwner`, whose table enforces exactly one owner.+#[derive(Debug, Clone, PartialEq, Eq)]+pub enum HarnessOwner {+ /// User-owned (private) harness.+ User {+ /// Owner user id.+ user_id: String,+ },+ /// Team-owned harness, usable by every team member.+ Team {+ /// Owner team id.+ team_id: Uuid,+ },+}/// Bot kind.#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]@@ -195,6 +216,8 @@ pub struct Agent {pub instructions: String,/// Harness used to run the agent.pub harness: String,+ /// Registered harness the agent runs on, when `harness` is `macrod`.+ pub harness_id: Option<HarnessId>,/// Model selected specifically for this agent.pub default_model: String,/// Whether the agent is global or channel-specific.@@ -209,6 +232,10 @@ pub struct Agent {pub struct CreateAgentRequest {/// Team owner. Omit for a private, user-owned agent.pub team_id: Option<Uuid>,+ /// Registered harness to run on. Required when `harness` is `macrod`,+ /// forbidden otherwise.+ #[serde(default)]+ pub harness_id: Option<HarnessId>,/// Display name.pub name: String,/// Stable `@` handle.@@ -236,6 +263,10 @@ pub struct CreateAgentRequest {pub struct UpdateAgentRequest {/// Team owner. Omit to make the agent private to the caller.pub team_id: Option<Uuid>,+ /// Registered harness to run on. Required when `harness` is `macrod`,+ /// forbidden otherwise.+ #[serde(default)]+ pub harness_id: Option<HarnessId>,/// Display name.pub name: String,/// Stable `@` handle.diff --git a/crates/bots/src/domain/ports.rs b/crates/bots/src/domain/ports.rsindex 05bccc6119..72229fc61d 100644--- a/crates/bots/src/domain/ports.rs+++ b/crates/bots/src/domain/ports.rs@@ -4,7 +4,7 @@ use super::models::{Agent, AuthenticatedBot, Bot, BotChannel, BotChannelListCaller, BotId, BotOwner, BotToken,BotTokenCandidate, CreateAgentRequest, CreateBotRequest, CreateBotTokenRequest,CreateBotTokenResponse, CreateChannelScopedBotRequest, CreateChannelScopedBotResponse,- PatchBotRequest, UpdateAgentRequest,+ HarnessId, HarnessOwner, PatchBotRequest, UpdateAgentRequest,};use bot_token::HashedBotToken;use entity_access::domain::models::{EntityAccessReceipt, MemberParticipantRole};@@ -88,6 +88,12 @@ pub trait BotRepo: Send + Sync + 'static {team_id: Uuid,) -> impl Future<Output = Result<bool, Self::Err>> + Send;+ /// Get the owner of an active registered harness.+ fn get_harness_owner(+ &self,+ harness_id: HarnessId,+ ) -> impl Future<Output = Result<Option<HarnessOwner>, Self::Err>> + Send;+/// Check whether a bot is an active channel participant.fn bot_active_in_channel(&self,diff --git a/crates/bots/src/domain/service.rs b/crates/bots/src/domain/service.rsindex 4900e950b8..fbaf053176 100644--- a/crates/bots/src/domain/service.rs+++ b/crates/bots/src/domain/service.rs@@ -6,7 +6,7 @@ use super::{Agent, AgentChannelScope, AuthenticatedBot, Bot, BotChannel, BotChannelListCaller, BotId,BotKind, BotOwner, BotToken, BotTokenCandidate, CreateAgentRequest, CreateBotRequest,CreateBotTokenRequest, CreateChannelScopedBotRequest, CreateChannelScopedBotResponse,- PatchBotRequest, UpdateAgentRequest,+ HarnessId, HarnessOwner, PatchBotRequest, UpdateAgentRequest,},ports::{BotError, BotRepo, BotService},tokens,@@ -52,6 +52,7 @@ struct AgentFields<'a> {name: &'a str,handle: &'a str,harness: &'a str,+ harness_id: Option<HarnessId>,default_model: &'a str,channel_scope: AgentChannelScope,channel_ids: &'a [Uuid],@@ -63,6 +64,7 @@ impl<'a> From<&'a CreateAgentRequest> for AgentFields<'a> {name: &req.name,handle: &req.handle,harness: &req.harness,+ harness_id: req.harness_id,default_model: &req.default_model,channel_scope: req.channel_scope,channel_ids: &req.channel_ids,@@ -76,6 +78,7 @@ impl<'a> From<&'a UpdateAgentRequest> for AgentFields<'a> {name: &req.name,handle: &req.handle,harness: &req.harness,+ harness_id: req.harness_id,default_model: &req.default_model,channel_scope: req.channel_scope,channel_ids: &req.channel_ids,@@ -88,6 +91,7 @@ fn validate_agent_fields(name,handle,harness,+ harness_id,default_model,channel_scope,channel_ids,@@ -104,6 +108,21 @@ fn validate_agent_fields("agent harness must not be empty".to_string(),));}+ // The `macrod` slug and a registered harness travel together: the slug+ // selects the external runtime path, the id says whose daemon serves it.+ match (harness == harness_id::MACROD_HARNESS_SLUG, harness_id) {+ (true, None) => {+ return Err(BotError::BadRequest(+ "agents on the macrod harness must reference a registered harness".to_string(),+ ));+ }+ (false, Some(_)) => {+ return Err(BotError::BadRequest(+ "harness_id applies only to the macrod harness".to_string(),+ ));+ }+ _ => {}+ }if default_model.trim().is_empty() {return Err(BotError::BadRequest("agent default model must not be empty".to_string(),@@ -209,6 +228,59 @@ where})}+ /// Ensure the resolved agent owner may run agents on a registered harness.+ ///+ /// A team agent must run on its own team's harness - never on a private+ /// one, so a teammate's mention can never execute on a machine only one+ /// person controls. A private agent may run on the caller's own harness+ /// or on a team harness of a team the caller belongs to.+ async fn ensure_harness_usable(+ &self,+ caller: MacroUserIdStr<'static>,+ owner: &BotOwner,+ harness_id: Option<HarnessId>,+ ) -> Result<(), BotError> {+ let Some(harness_id) = harness_id else {+ return Ok(());+ };+ let harness_owner = self+ .repo+ .get_harness_owner(harness_id)+ .await+ .map_err(|err| BotError::Repo(err.into()))?+ .ok_or_else(|| BotError::BadRequest("unknown harness".to_string()))?;++ let usable = match (owner, harness_owner) {+ (+ BotOwner::Team { team_id },+ HarnessOwner::Team {+ team_id: harness_team,+ },+ ) => *team_id == harness_team,+ (BotOwner::Team { .. }, HarnessOwner::User { .. }) => false,+ (+ BotOwner::User { user_id },+ HarnessOwner::User {+ user_id: harness_user,+ },+ ) => *user_id == harness_user,+ (+ BotOwner::User { .. },+ HarnessOwner::Team {+ team_id: harness_team,+ },+ ) => self+ .repo+ .user_has_team(caller, harness_team)+ .await+ .map_err(|err| BotError::Repo(err.into()))?,+ };+ if !usable {+ return Err(BotError::Unauthorized);+ }+ Ok(())+ }+async fn owner_for_agent_update(&self,caller: MacroUserIdStr<'static>,@@ -322,6 +394,8 @@ wherelet owner = self.agent_owner_for_request(caller.clone(), req.team_id).await?;+ self.ensure_harness_usable(caller.clone(), &owner, req.harness_id)+ .await?;let created_by_user_id = caller.clone();let agent = self.repo@@ -371,6 +445,8 @@ wherelet owner = self.owner_for_agent_update(caller.clone(), ¤t, req.team_id).await?;+ self.ensure_harness_usable(caller.clone(), &owner, req.harness_id)+ .await?;let requested_name = req.name.clone();let requested_handle = req.handle.clone();let requested_description = req.description.clone();diff --git a/crates/bots/src/inbound/axum_router.rs b/crates/bots/src/inbound/axum_router.rsindex f9acdad6b2..7e5e8df539 100644--- a/crates/bots/src/inbound/axum_router.rs+++ b/crates/bots/src/inbound/axum_router.rs@@ -492,6 +492,9 @@ pub async fn list_bot_channels_handler<let caller = match authorization.authorization {MacroAuthorization::User(user) => BotChannelListCaller::User(user.macro_user_id),MacroAuthorization::Bot(bot) => BotChannelListCaller::Bot(bot.bot_id),+ MacroAuthorization::Harness(_) => {+ return Err(BotsHandlerErr::Bot(BotError::Unauthorized));+ }MacroAuthorization::Internal(_) => BotChannelListCaller::Internal,};Ok(Json(diff --git a/crates/bots/src/outbound/pg_bots_repo.rs b/crates/bots/src/outbound/pg_bots_repo.rsindex 4aa6f87ce9..da60fa2cc2 100644--- a/crates/bots/src/outbound/pg_bots_repo.rs+++ b/crates/bots/src/outbound/pg_bots_repo.rs@@ -7,7 +7,8 @@ use crate::domain::{models::{Agent, AgentChannelScope, AuthenticatedBot, Bot, BotChannel, BotChannelType, BotId,BotKind, BotOwner, BotToken, BotTokenCandidate, CreateAgentRequest, CreateBotRequest,- CreateBotTokenRequest, CreateChannelScopedBotRequest, PatchBotRequest, UpdateAgentRequest,+ CreateBotTokenRequest, CreateChannelScopedBotRequest, HarnessId, HarnessOwner,+ PatchBotRequest, UpdateAgentRequest,},ports::BotRepo,};@@ -107,6 +108,7 @@ struct AgentRow {has_agent: bool,instructions: String,harness: String,+ harness_id: Option<Uuid>,default_model: String,channel_scope: String,channel_ids: Vec<Uuid>,@@ -141,6 +143,7 @@ impl TryFrom<AgentRow> for Agent {bot,instructions: row.instructions,harness: row.harness,+ harness_id: row.harness_id.map(HarnessId::new_from_uuid),default_model: row.default_model,channel_scope,channel_ids: row.channel_ids,@@ -307,13 +310,14 @@ impl BotRepo for PgBotsRepo {sqlx::query!(r#"INSERT INTO agent_configs (- bot_id, instructions, harness, default_model, channel_scope+ bot_id, instructions, harness, harness_id, default_model, channel_scope)- VALUES ($1, $2, $3, $4, $5)+ VALUES ($1, $2, $3, $4, $5, $6)"#,bot_id.as_uuid(),&req.instructions,&req.harness,+ req.harness_id.map(HarnessId::as_uuid),&req.default_model,req.channel_scope.as_str(),)@@ -345,6 +349,7 @@ impl BotRepo for PgBotsRepo {bot: map_bot_row(bot_row)?,instructions: req.instructions,harness: req.harness,+ harness_id: req.harness_id,default_model: req.default_model,channel_scope: req.channel_scope,channel_ids: req.channel_ids,@@ -414,14 +419,16 @@ impl BotRepo for PgBotsRepo {UPDATE agent_configsSET instructions = $2,harness = $3,- default_model = $4,- channel_scope = $5,+ harness_id = $4,+ default_model = $5,+ channel_scope = $6,updated_at = now()WHERE bot_id = $1"#,bot_id.as_uuid(),&req.instructions,&req.harness,+ req.harness_id.map(HarnessId::as_uuid),&req.default_model,req.channel_scope.as_str(),)@@ -470,6 +477,7 @@ impl BotRepo for PgBotsRepo {bot: map_bot_row(bot_row)?,instructions: req.instructions,harness: req.harness,+ harness_id: req.harness_id,default_model: req.default_model,channel_scope: req.channel_scope,channel_ids: req.channel_ids,@@ -499,6 +507,7 @@ impl BotRepo for PgBotsRepo {b.has_agent,a.instructions,a.harness,+ a.harness_id,a.default_model,a.channel_scope,ARRAY(@@ -788,6 +797,7 @@ impl BotRepo for PgBotsRepo {b.has_agent,a.instructions,a.harness,+ a.harness_id,a.default_model,a.channel_scope,ARRAY(@@ -812,6 +822,31 @@ impl BotRepo for PgBotsRepo {row.map(Agent::try_from).transpose()}+ async fn get_harness_owner(+ &self,+ harness_id: HarnessId,+ ) -> Result<Option<HarnessOwner>, Self::Err> {+ let row = sqlx::query!(+ r#"+ SELECT owner_user_id, team_id+ FROM harnesses+ WHERE id = $1 AND deleted_at IS NULL+ "#,+ harness_id.as_uuid(),+ )+ .fetch_optional(&self.pool)+ .await+ .context("failed to fetch harness owner")?;++ row.map(|row| match (row.owner_user_id, row.team_id) {+ (Some(user_id), None) => Ok(HarnessOwner::User { user_id }),+ (None, Some(team_id)) => Ok(HarnessOwner::Team { team_id }),+ // Unreachable: harnesses_owner_check enforces exactly one owner.+ _ => Err(anyhow::anyhow!("harness {harness_id} violates owner xor")),+ })+ .transpose()+ }+async fn user_has_team(&self,caller: MacroUserIdStr<'static>,diff --git a/crates/bots/src/outbound/pg_bots_repo/tests.rs b/crates/bots/src/outbound/pg_bots_repo/tests.rsindex 4e9ebb0d5b..3d90f44c40 100644--- a/crates/bots/src/outbound/pg_bots_repo/tests.rs+++ b/crates/bots/src/outbound/pg_bots_repo/tests.rs@@ -78,6 +78,7 @@ fn create_agent_req(handle: &str, channel_scope: AgentChannelScope) -> CreateAgeavatar_url: Some("https://static.example/bug-fixer.png".to_string()),instructions: "Fix the root cause and add tests.".to_string(),harness: "cursor".to_string(),+ harness_id: None,default_model: "cursor-small".to_string(),channel_scope,channel_ids: Vec::new(),@@ -93,6 +94,7 @@ fn update_agent_req(handle: &str, channel_scope: AgentChannelScope) -> UpdateAgeavatar_url: None,instructions: "Diagnose first, then make the smallest tested fix.".to_string(),harness: "in-memory".to_string(),+ harness_id: None,default_model: "claude-sonnet-4-5".to_string(),channel_scope,channel_ids: Vec::new(),@@ -1463,3 +1465,150 @@ async fn scheduling_failures_do_not_change_successful_mutations(Ok(())}++async fn insert_harness(+ pool: &PgPool,+ owner_user_id: Option<&str>,+ team_id: Option<Uuid>,+) -> anyhow::Result<HarnessId> {+ let harness_id = Uuid::new_v4();+ sqlx::query!(+ r#"+ INSERT INTO harnesses (id, name, owner_user_id, team_id, created_by)+ VALUES ($1, 'test harness', $2, $3, $4)+ "#,+ harness_id,+ owner_user_id,+ team_id,+ owner_user_id.unwrap_or(USER_OWNER),+ )+ .execute(pool)+ .await?;+ Ok(HarnessId::new_from_uuid(harness_id))+}++fn macrod_agent_req(handle: &str, harness_id: Option<HarnessId>) -> CreateAgentRequest {+ CreateAgentRequest {+ harness: "macrod".to_string(),+ harness_id,+ ..create_agent_req(handle, AgentChannelScope::All)+ }+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn macrod_agents_require_a_registered_usable_harness(pool: PgPool) -> anyhow::Result<()> {+ let service = service(&pool);+ insert_user(&pool, USER_OWNER).await?;+ insert_user(&pool, USER_OTHER).await?;++ // The slug and the binding travel together.+ let missing_id = service+ .create_agent(user_id(USER_OWNER), macrod_agent_req("macrod-agent", None))+ .await;+ assert!(matches!(missing_id, Err(BotError::BadRequest(_))));++ let mut mismatched = create_agent_req("mismatched-agent", AgentChannelScope::All);+ mismatched.harness_id = Some(HarnessId::new_from_uuid(Uuid::new_v4()));+ let mismatched = service.create_agent(user_id(USER_OWNER), mismatched).await;+ assert!(matches!(mismatched, Err(BotError::BadRequest(_))));++ // An unknown harness id is rejected.+ let unknown = service+ .create_agent(+ user_id(USER_OWNER),+ macrod_agent_req(+ "unknown-harness",+ Some(HarnessId::new_from_uuid(Uuid::new_v4())),+ ),+ )+ .await;+ assert!(matches!(unknown, Err(BotError::BadRequest(_))));++ // The owner binds their own private harness; a stranger cannot.+ let private_harness = insert_harness(&pool, Some(USER_OWNER), None).await?;+ let agent = service+ .create_agent(+ user_id(USER_OWNER),+ macrod_agent_req("my-macrod-agent", Some(private_harness)),+ )+ .await?;+ assert_eq!(agent.harness, "macrod");+ assert_eq!(agent.harness_id, Some(private_harness));++ let stranger = service+ .create_agent(+ user_id(USER_OTHER),+ macrod_agent_req("stolen-harness", Some(private_harness)),+ )+ .await;+ assert!(matches!(stranger, Err(BotError::Unauthorized)));++ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn team_harnesses_back_member_agents_but_not_team_agents_on_private_harnesses(+ pool: PgPool,+) -> anyhow::Result<()> {+ let service = service(&pool);+ insert_user(&pool, USER_OWNER).await?;+ let team_id = Uuid::new_v4();+ insert_team_user(&pool, team_id, TEAM_OWNER, "owner").await?;+ insert_team_user(&pool, team_id, TEAM_MEMBER, "member").await?;+ let team_harness = insert_harness(&pool, None, Some(team_id)).await?;++ // A member's private agent may run on the team harness.+ let member_agent = service+ .create_agent(+ user_id(TEAM_MEMBER),+ macrod_agent_req("member-on-team-harness", Some(team_harness)),+ )+ .await?;+ assert_eq!(member_agent.harness_id, Some(team_harness));++ // A team agent may run on the team's own harness.+ let mut team_agent = macrod_agent_req("team-on-team-harness", Some(team_harness));+ team_agent.team_id = Some(team_id);+ let team_agent = service+ .create_agent(user_id(TEAM_MEMBER), team_agent)+ .await?;+ assert_eq!(team_agent.harness_id, Some(team_harness));++ // A non-member cannot use the team harness.+ insert_user(&pool, USER_OTHER).await?;+ let outsider = service+ .create_agent(+ user_id(USER_OTHER),+ macrod_agent_req("outsider-on-team-harness", Some(team_harness)),+ )+ .await;+ assert!(matches!(outsider, Err(BotError::Unauthorized)));++ // A team agent must never run on a private harness.+ let private_harness = insert_harness(&pool, Some(TEAM_MEMBER), None).await?;+ let mut team_on_private = macrod_agent_req("team-on-private-harness", Some(private_harness));+ team_on_private.team_id = Some(team_id);+ let team_on_private = service+ .create_agent(user_id(TEAM_MEMBER), team_on_private)+ .await;+ assert!(matches!(team_on_private, Err(BotError::Unauthorized)));++ // Updates re-check the binding: moving the member's agent onto their own+ // private harness works, and clearing the slug clears the binding.+ let mut update = update_agent_req("member-on-team-harness", AgentChannelScope::All);+ update.harness = "macrod".to_string();+ update.harness_id = Some(private_harness);+ let updated = service+ .update_agent(user_id(TEAM_MEMBER), member_agent.bot.id, update)+ .await?;+ assert_eq!(updated.harness_id, Some(private_harness));++ let mut cleared = update_agent_req("member-on-team-harness", AgentChannelScope::All);+ cleared.harness = "in-memory".to_string();+ let cleared = service+ .update_agent(user_id(TEAM_MEMBER), member_agent.bot.id, cleared)+ .await?;+ assert_eq!(cleared.harness_id, None);++ Ok(())+}diff --git a/crates/coding_agent_worker/Cargo.toml b/crates/coding_agent_worker/Cargo.tomlindex be6f5eed4d..e65b51731e 100644--- a/crates/coding_agent_worker/Cargo.toml+++ b/crates/coding_agent_worker/Cargo.toml@@ -21,7 +21,10 @@ bot_id = { path = "../bot_id" }# Only the domain models: the daemon reads `GET /bots/me` and the webhook# API's bodies, and wants none of either crate's server-side machinery.bots = { path = "../bots", default-features = false }+chrono = { workspace = true }clap = { workspace = true }+harness_id = { path = "../harness_id" }+harnesses = { path = "../harnesses", default-features = false }dashmap = { workspace = true }macro_event_broker = { path = "../macro_event_broker", default-features = false }macro_user_id = { path = "../macro_user_id" }@@ -50,4 +53,5 @@ bot_id = { path = "../bot_id", features = ["test-utils"] }channel_sender = { path = "../channel_sender" }channels = { path = "../channels", default-features = false }chrono = { workspace = true }+harness_id = { path = "../harness_id", features = ["test-utils"] }tower = { workspace = true, features = ["util"] }diff --git a/crates/coding_agent_worker/config.example.toml b/crates/coding_agent_worker/config.example.tomlindex a1bd9de681..50250dbd3d 100644--- a/crates/coding_agent_worker/config.example.toml+++ b/crates/coding_agent_worker/config.example.toml@@ -1,18 +1,28 @@-# Everything a coding agent daemon needs to serve one bot's sessions.+# Everything a coding agent daemon needs to serve one harness's sessions.+#+# Deliberately credential-free: run `macrod login` (or just `macrod` on a+# fresh setup) to pair this daemon with a Macro deployment. Pairing prints a+# code, you approve it in the web app (choosing private or team), and the+# minted credential is kept in `macro.credentials.json` next to this file.[macro]# Base URL of the agent-harness service. Its ws(s) twin hosts the runtime# gateway the daemon dials per session.api_url = "http://localhost:50009/agent-harness"-# Base URL of the storage service (bots + webhook APIs); the daemon-# registers its own trigger feed there at boot.+# Base URL of the storage service (harness pairing + webhook APIs); the+# daemon registers its own trigger feed there at boot.storage_url = "http://localhost:50009/dss"-# The user who owns the bot; registration acts for them.-owner_user_id = "macro|[email protected]"-# The bot's API token.-bot_token = "mbot_0123456789ab_0123456789abcdef"-# Optional; `user` unless the bot is team-owned and acts in its team scope.-bot_scope = "user"+# Optional: base URL of the Macro web app, used only to print the pairing+# link. Defaults to https://macro.com/app.+web_url = "http://localhost:3000/app"++[identity]+# Optional: the harness name pairing requests; the approving user may rename+# it. Defaults to this machine's hostname.+name = "erics-macbook"+# Optional: "private" (default) or "team". Team harnesses can run agents any+# of your teammates create. The approval dialog arrives preselected to this.+scope = "private"[server]# Port `POST /macro-events` is served on.diff --git a/crates/coding_agent_worker/src/config.rs b/crates/coding_agent_worker/src/config.rsindex e2a0181317..8181ae5f3a 100644--- a/crates/coding_agent_worker/src/config.rs+++ b/crates/coding_agent_worker/src/config.rs@@ -1,6 +1,10 @@-//! The daemon's one input: a TOML file describing the bot it serves, the-//! webhook server it listens on, and the harness it runs per session. See-//! `config.example.toml` at the crate root.+//! The daemon's one input: a TOML file describing the Macro deployment it+//! serves, the webhook server it listens on, and the harness it runs per+//! session. See `config.example.toml` at the crate root.+//!+//! Deliberately credential-free: identity comes from pairing (`macrod login`,+//! or the first `macrod` run), which persists the harness credential in a+//! state file next to this config.use serde::Deserialize;use std::path::{Path, PathBuf};@@ -12,9 +16,12 @@ mod test;#[derive(Debug, Clone, Deserialize)]#[serde(deny_unknown_fields)]pub struct Config {- /// The Macro deployment this bot's sessions live in.+ /// The Macro deployment this harness's sessions live in.#[serde(rename = "macro")]pub macro_api: MacroApi,+ /// How this daemon introduces itself when pairing.+ #[serde(default)]+ pub identity: Identity,/// The webhook server this daemon listens on.pub server: Server,/// The harness process spawned per session.@@ -23,8 +30,7 @@ pub struct Config {pub workspace: Workspace,}-/// The Macro deployment this bot's sessions live in, and how to act as the-/// bot there.+/// The Macro deployment this harness's sessions live in.#[derive(Debug, Clone, Deserialize)]#[serde(deny_unknown_fields)]pub struct MacroApi {@@ -32,17 +38,12 @@ pub struct MacroApi {/// `http://localhost:50009/agent-harness`. Sessions are created and/// prompted here, and its `ws(s)` twin hosts the runtime gateway.pub api_url: String,- /// Base URL of the storage service, e.g. `http://localhost:50009/storage`.- /// Hosts the bots and webhook APIs the daemon registers itself with.+ /// Base URL of the storage service, e.g. `http://localhost:50009/dss`.+ /// Hosts the harness pairing and webhook APIs.pub storage_url: String,- /// The user who owns the bot; webhook registration acts for them.- pub owner_user_id: String,- /// The bot's API token (`mbot_...`).- pub bot_token: String,- /// Bot scope requests authorize under; `user` unless the bot is- /// team-owned and should act in its team scope.- #[serde(default = "default_bot_scope")]- pub bot_scope: String,+ /// Base URL of the Macro web app, used only to print the pairing link.+ #[serde(default = "default_web_url")]+ pub web_url: String,}impl MacroApi {@@ -55,6 +56,38 @@ impl MacroApi {.replacen("http://", "ws://", 1);format!("{base}/runtime/ws")}++ /// The settings-page URL where a pairing code is approved.+ pub fn pairing_approval_url(&self, code: &str) -> String {+ let base = self.web_url.trim_end_matches('/');+ format!("{base}/settings/harness?pair={code}")+ }+}++/// How this daemon introduces itself when pairing.+#[derive(Debug, Clone, Default, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct Identity {+ /// Requested harness display name; the approving user may rename it.+ /// Defaults to this machine's hostname.+ #[serde(default)]+ pub name: Option<String>,+ /// Whether the harness should be private to the approving user or shared+ /// with their team. Advisory: the approval dialog arrives preselected to+ /// this, and the approving user has the final say.+ #[serde(default)]+ pub scope: IdentityScope,+}++/// The ownership scope this daemon's pairing asks for.+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum IdentityScope {+ /// Only the approving user can run agents on this harness.+ #[default]+ Private,+ /// Any of the approving user's teammates can bind agents to it.+ Team,}/// The webhook server this daemon listens on.@@ -102,8 +135,8 @@ pub struct Workspace {pub repo_url: Option<String>,}-fn default_bot_scope() -> String {- "user".to_owned()+fn default_web_url() -> String {+ "https://macro.com/app".to_owned()}/// Why a config failed to load.diff --git a/crates/coding_agent_worker/src/config/test.rs b/crates/coding_agent_worker/src/config/test.rsindex 8f5a5c519c..afe82144c7 100644--- a/crates/coding_agent_worker/src/config/test.rs+++ b/crates/coding_agent_worker/src/config/test.rs@@ -8,7 +8,8 @@ fn the_example_config_parses() {assert_eq!(config.harness.command, "opencode");assert_eq!(config.harness.args, vec!["acp"]);assert_eq!(config.server.port, 8790);- assert_eq!(config.macro_api.bot_scope, "user");+ assert_eq!(config.identity.name.as_deref(), Some("erics-macbook"));+ assert_eq!(config.identity.scope, IdentityScope::Private);assert_eq!(config.server.signing_secret, None);assert_eq!(config.server.public_url,@@ -23,13 +24,40 @@ fn unknown_fields_are_rejected() {}#[test]-fn args_and_scope_default() {+fn removed_credential_fields_fail_loudly() {+ // Pre-pairing configs carried bot credentials; a stale one should fail+ // with a parse error pointing at the removed key rather than serve with+ // half an identity.+ let stale = EXAMPLE.replace(+ "storage_url = \"http://localhost:50009/dss\"",+ "storage_url = \"http://localhost:50009/dss\"\nbot_token = \"mbot_x\"",+ );+ assert!(toml::from_str::<Config>(&stale).is_err());+}++#[test]+fn identity_args_and_web_url_default() {let trimmed = EXAMPLE.replace("args = [\"acp\"]\n", "")- .replace("bot_scope = \"user\"\n", "");- let config: Config = toml::from_str(&trimmed).expect("args and scope are optional");+ .replace("[identity]\n", "")+ .replace("name = \"erics-macbook\"\n", "")+ .replace("scope = \"private\"\n", "")+ .replace("web_url = \"http://localhost:3000/app\"\n", "");+ let config: Config = toml::from_str(&trimmed).expect("identity, args, web_url are optional");assert!(config.harness.args.is_empty());- assert_eq!(config.macro_api.bot_scope, "user");+ assert_eq!(config.identity.name, None);+ assert_eq!(config.identity.scope, IdentityScope::Private);+ assert_eq!(config.macro_api.web_url, "https://macro.com/app");+}++#[test]+fn identity_scope_accepts_team() {+ let team = EXAMPLE.replace("scope = \"private\"", "scope = \"team\"");+ let config: Config = toml::from_str(&team).expect("team scope parses");+ assert_eq!(config.identity.scope, IdentityScope::Team);++ let bogus = EXAMPLE.replace("scope = \"private\"", "scope = \"public\"");+ assert!(toml::from_str::<Config>(&bogus).is_err());}#[test]@@ -43,12 +71,14 @@ fn the_gateway_url_is_the_api_base_with_a_websocket_scheme() {let secure = MacroApi {api_url: "https://agent-harness.macro.com/".to_owned(),storage_url: "https://cloud-storage.macro.com".to_owned(),- owner_user_id: "macro|[email protected]".to_owned(),- bot_token: "mbot_x".to_owned(),- bot_scope: "user".to_owned(),+ web_url: "https://macro.com/app/".to_owned(),};assert_eq!(secure.gateway_url(),"wss://agent-harness.macro.com/runtime/ws",);+ assert_eq!(+ secure.pairing_approval_url("KX7M-4QHD"),+ "https://macro.com/app/settings/harness?pair=KX7M-4QHD",+ );}diff --git a/crates/coding_agent_worker/src/dispatch.rs b/crates/coding_agent_worker/src/dispatch.rsindex 653b81d347..35aff72c20 100644--- a/crates/coding_agent_worker/src/dispatch.rs+++ b/crates/coding_agent_worker/src/dispatch.rs@@ -41,6 +41,7 @@ impl WorkExecutor for Dispatcher {async fn execute(&self, work: TriggerWork) -> Result<(), DispatchError> {match work {TriggerWork::OpenAndPrompt {+ bot,sender,channel_id,thread_id,@@ -48,9 +49,10 @@ impl WorkExecutor for Dispatcher {content,} => {let request = CreateAgentSessionRequest {- // The bot is the one whose credentials this daemon holds,- // and naming another one is refused anyway.- bot_id: None,+ // A harness serves many agents, so the token implies no+ // bot: name the mentioned agent, and the service verifies+ // it is bound to this harness.+ bot_id: Some(bot.as_uuid()),workspace: Some(self.workspace.path.to_string_lossy().into_owned()),// External sessions carry no first prompt: this daemon is// the runtime, and it delivers the mention itself throughdiff --git a/crates/coding_agent_worker/src/main.rs b/crates/coding_agent_worker/src/main.rsindex 929b38abab..e51a955b85 100644--- a/crates/coding_agent_worker/src/main.rs+++ b/crates/coding_agent_worker/src/main.rs@@ -1,6 +1,10 @@-//! The coding agent daemon: serve a bot's agent sessions from this machine.+//! The coding agent daemon: serve a registered harness's agent sessions from+//! this machine.//!-//! Boots a signed-webhook receiver and waits. Each `agent_trigger.new`+//! First run pairs the daemon with a Macro deployment: it prints a code, the+//! user approves it in the web app (choosing private or team), and the minted+//! harness credential is persisted next to the config. Every run after that+//! boots a signed-webhook receiver and waits. Each `agent_trigger.new`//! delivery opens a session over the harness service's API, dials its//! runtime gateway, spawns the configured harness in ACP mode, bridges its//! stdio to the websocket, and forwards the mention as the first prompt;@@ -14,26 +18,44 @@ mod outbound;mod runtime;mod webhook;-use clap::Parser;+use clap::{Parser, Subcommand};use config::Config;use rootcause::prelude::ResultExt as _;use std::path::PathBuf;use std::process::ExitCode;+use std::sync::Arc;+use std::time::Duration;use crate::dispatch::Dispatcher;use crate::outbound::agent_session::HarnessApi;+use crate::outbound::credentials::{CredentialStore as _, FileCredentialStore, HarnessCredentials};+use crate::outbound::pairing;use crate::outbound::registration::FeedReconciler;use crate::runtime::Runtime;use crate::webhook::{WebhookState, webhook_router};-/// Serve a bot's agent sessions: host the webhook receiver, bridge each-/// triggered session to a harness.+/// How often the bound-agent set is re-read and the feed reconciled to it, so+/// a teammate's newly bound agent starts triggering without a restart.+const FEED_RECONCILE_INTERVAL: Duration = Duration::from_secs(60);++/// Serve a harness's agent sessions: host the webhook receiver, bridge each+/// triggered session to a harness process.#[derive(Parser)]#[command(name = "macrod", version)]struct Args {/// Path to the daemon's TOML config.#[arg(long, default_value = "macro.toml")]config: PathBuf,+ #[command(subcommand)]+ command: Option<Command>,+}++/// What to do; none means serve.+#[derive(Subcommand)]+enum Command {+ /// Pair this daemon with a Macro deployment, replacing any stored+ /// credential.+ Login,}#[tokio::main]@@ -51,7 +73,11 @@ async fn main() -> ExitCode {let _ = rustls::crypto::aws_lc_rs::default_provider().install_default();let args = Args::parse();- match run(&args.config).await {+ let outcome = match args.command {+ Some(Command::Login) => login(&args.config).await,+ None => run(&args.config).await,+ };+ match outcome {Ok(()) => ExitCode::SUCCESS,Err(error) => {tracing::error!(error = ?error, "daemon exited with an error");@@ -60,9 +86,48 @@ async fn main() -> ExitCode {}}+/// Pair (or re-pair) and persist the credential.+async fn login(config_path: &std::path::Path) -> rootcause::Result<()> {+ let config = Config::load(config_path)?;+ let store = FileCredentialStore::for_config(config_path);+ if let Some(existing) = store.load()? {+ println!(+ "Replacing the stored credential for harness {} - the old harness row stays listed until you remove it in Settings -> Harness.",+ existing.harness_id+ );+ }+ let credentials = pair_and_save(&config, &store).await?;+ println!(+ "Run `macrod` to start serving harness {}.",+ credentials.harness_id+ );+ Ok(())+}++async fn pair_and_save(+ config: &Config,+ store: &FileCredentialStore,+) -> rootcause::Result<HarnessCredentials> {+ let credentials = pairing::pair(config).await?;+ store.save(&credentials)?;+ println!("Credentials saved to {}.", store.path().display());+ Ok(credentials)+}+async fn run(config_path: &std::path::Path) -> rootcause::Result<()> {let config = Config::load(config_path)?;+ // Identity: from the pairing state file, pairing interactively on a+ // first run so `macrod` with a fresh config walks straight into setup.+ let store = FileCredentialStore::for_config(config_path);+ let credentials = match store.load()? {+ Some(credentials) => credentials,+ None => {+ println!("No credentials found - pairing this daemon first.");+ pair_and_save(&config, &store).await?+ }+ };+// The ACP launch config carries command, args, and env but no working// directory, and every session this daemon serves runs in the one// configured workspace - so the daemon's own cwd is the harness's cwd.@@ -71,26 +136,54 @@ async fn run(config_path: &std::path::Path) -> rootcause::Result<()> {config.workspace.path.display()))?;- // The feed: make sure one exists, points here, and we hold its secret.- // An explicit config secret skips registration entirely (manual setups).- let reconciler = FeedReconciler::new(&config.macro_api, &config.server, config_path);- let (signing_secret, needs_validation) = match &config.server.signing_secret {- Some(secret) => (secret.clone(), None),+ // The feed: make sure one exists, points here, covers the bound agents,+ // and we hold its secret. An explicit config secret skips registration+ // entirely (manual setups).+ let reconciler = Arc::new(FeedReconciler::new(+ &config.macro_api,+ &config.server,+ credentials.clone(),+ config_path,+ ));+ let signing_secret = Arc::new(std::sync::RwLock::new(String::new()));+ match &config.server.signing_secret {+ Some(secret) => {+ *signing_secret.write().expect("signing secret lock") = secret.clone();+ }None => {- let feed = reconciler+ // `None` is a daemon with nothing bound yet: it serves anyway,+ // and the reconcile loop registers the feed the moment an agent+ // is bound in the app.+ let initial = reconciler.ensure_feed().await- .context("failed to register this bot's trigger feed")?;- let needs_validation = (!feed.is_valid).then_some(feed.webhook_id);- (feed.signing_secret, needs_validation)+ .context("failed to register this harness's trigger feed")?;+ if let Some(feed) = &initial {+ *signing_secret.write().expect("signing secret lock") = feed.signing_secret.clone();+ }+ // Validation probes the endpoint, so it can only pass once we+ // serve; request it from the side once the listener is up, and+ // keep the feed covering the bound-agent set from then on.+ let reconciler = Arc::clone(&reconciler);+ let signing_secret = Arc::clone(&signing_secret);+ tokio::spawn(async move {+ let mut current = None;+ if let Some(feed) = initial {+ if !feed.is_valid {+ reconciler.request_validation(&feed.webhook_id).await;+ }+ current = Some(feed.webhook_id);+ }+ reconcile_forever(reconciler, signing_secret, current).await;+ });}- };+ }- let api = HarnessApi::new(&config.macro_api);- let runtime = Runtime::new(config.macro_api.clone(), config.harness.clone());+ let api = HarnessApi::new(&config.macro_api, &credentials);+ let runtime = Runtime::new(&config.macro_api, &credentials, config.harness.clone());let app = webhook_router(WebhookState {executor: Dispatcher::new(api, runtime, config.workspace.clone()),- signing_secret,+ signing_secret: Arc::clone(&signing_secret),});let port = config.server.port;@@ -100,17 +193,12 @@ async fn run(config_path: &std::path::Path) -> rootcause::Result<()> {tracing::info!(port,api = %config.macro_api.api_url,+ harness_id = %credentials.harness_id,harness = %config.harness.command,workspace = %config.workspace.path.display(),"daemon listening for agent triggers");- // Validation probes the endpoint, so it can only pass once we serve;- // request it from the side once the listener is up.- if let Some(webhook_id) = needs_validation {- tokio::spawn(async move { reconciler.request_validation(&webhook_id).await });- }-axum::serve(listener, app).with_graceful_shutdown(shutdown_signal()).await@@ -118,6 +206,40 @@ async fn run(config_path: &std::path::Path) -> rootcause::Result<()> {Ok(())}+/// Keep the feed covering the bound-agent set: registered once anything is+/// bound, replaced (along with the secret the receiver verifies with) when+/// the set or endpoint changes, and dropped when nothing is bound any more.+async fn reconcile_forever(+ reconciler: Arc<FeedReconciler>,+ signing_secret: Arc<std::sync::RwLock<String>>,+ mut current_webhook_id: Option<String>,+) {+ loop {+ tokio::time::sleep(FEED_RECONCILE_INTERVAL).await;+ match reconciler.ensure_feed().await {+ Ok(Some(feed)) => {+ if current_webhook_id.as_deref() != Some(feed.webhook_id.as_str()) {+ tracing::info!(webhook_id = %feed.webhook_id, "trigger feed registered");+ *signing_secret.write().expect("signing secret lock") =+ feed.signing_secret.clone();+ if !feed.is_valid {+ reconciler.request_validation(&feed.webhook_id).await;+ }+ current_webhook_id = Some(feed.webhook_id);+ }+ }+ Ok(None) => {+ if current_webhook_id.take().is_some() {+ tracing::info!("trigger feed removed; no agents are bound any more");+ }+ }+ Err(error) => {+ tracing::warn!(error = ?error, "trigger feed reconciliation failed; will retry");+ }+ }+ }+}+async fn shutdown_signal() {let _ = tokio::signal::ctrl_c().await;tracing::info!("shutting down");diff --git a/crates/coding_agent_worker/src/outbound/agent_session.rs b/crates/coding_agent_worker/src/outbound/agent_session.rsindex 99893e5dc2..898f37f533 100644--- a/crates/coding_agent_worker/src/outbound/agent_session.rs+++ b/crates/coding_agent_worker/src/outbound/agent_session.rs@@ -1,6 +1,6 @@//! The daemon's client for the agent-harness service: open sessions, drive-//! them. Both calls act as the bot, and control calls additionally act for-//! the user whose mention they forward.+//! them. Both calls act as the harness, and control calls additionally act+//! for the user whose mention they forward.use agent_runtime_protocol::domain::action::AgentAction;use agent_session::domain::model::AgentSessionId;@@ -12,10 +12,10 @@ use macro_user_id::user_id::MacroUserIdStr;use reqwest::StatusCode;use crate::config::MacroApi;+use crate::outbound::credentials::HarnessCredentials;-const BOT_TOKEN_HEADER: &str = "x-macro-bot-token";-const BOT_SCOPE_HEADER: &str = "x-macro-bot-scope";-const BOT_ACTING_USER_HEADER: &str = "x-macro-bot-for-macro-user-id";+const HARNESS_TOKEN_HEADER: &str = "x-macro-harness-token";+const HARNESS_ACTING_USER_HEADER: &str = "x-macro-harness-for-macro-user-id";/// A failure calling the agent-harness service.#[derive(Debug, thiserror::Error)]@@ -23,8 +23,8 @@ pub enum ApiError {/// The request could not be sent or the response not read.#[error(transparent)]Http(#[from] reqwest::Error),- /// This bot already has a session for the thread.- #[error("this bot already has a session for this thread")]+ /// A bound agent already has a session for the thread.+ #[error("this agent already has a session for this thread")]ThreadSessionExists {/// The existing session, when the service could name it.session: Option<AgentSessionId>,@@ -39,26 +39,24 @@ pub enum ApiError {},}-/// Client for the agent-harness service, acting as one bot.+/// Client for the agent-harness service, acting as one harness.pub struct HarnessApi {http: reqwest::Client,base: String,- bot_token: String,- bot_scope: String,+ token: String,}impl HarnessApi {- /// Build a client from the daemon's config.- pub fn new(config: &MacroApi) -> Self {+ /// Build a client from the daemon's config and paired credentials.+ pub fn new(config: &MacroApi, credentials: &HarnessCredentials) -> Self {Self {http: reqwest::Client::new(),base: config.api_url.trim_end_matches('/').to_owned(),- bot_token: config.bot_token.clone(),- bot_scope: config.bot_scope.clone(),+ token: credentials.token.clone(),}}- /// Open an external session for this bot.+ /// Open an external session for one of this harness's bound agents.////// A thread routes to at most one of a bot's sessions, so a redelivered/// mention lands on [`ApiError::ThreadSessionExists`] carrying the@@ -70,8 +68,7 @@ impl HarnessApi {let response = self.http.post(format!("{}/agent-sessions", self.base))- .header(BOT_TOKEN_HEADER, &self.bot_token)- .header(BOT_SCOPE_HEADER, &self.bot_scope)+ .header(HARNESS_TOKEN_HEADER, &self.token).json(request).send().await?;@@ -100,9 +97,8 @@ impl HarnessApi {let response = self.http.post(format!("{}/agent-sessions/{session}/control", self.base))- .header(BOT_TOKEN_HEADER, &self.bot_token)- .header(BOT_SCOPE_HEADER, &self.bot_scope)- .header(BOT_ACTING_USER_HEADER, actor.as_ref())+ .header(HARNESS_TOKEN_HEADER, &self.token)+ .header(HARNESS_ACTING_USER_HEADER, actor.as_ref()).json(&ControlRequest { action }).send().await?;@@ -128,5 +124,11 @@ async fn refuse_errors(response: reqwest::Response) -> Result<reqwest::Response,return Ok(response);}let message = response.text().await.unwrap_or_default();+ if status == StatusCode::UNAUTHORIZED || status == StatusCode::FORBIDDEN {+ tracing::error!(+ %status,+ "the server refused this harness's credentials; run `macrod login` to re-pair"+ );+ }Err(ApiError::Refused { status, message })}diff --git a/crates/coding_agent_worker/src/outbound/credentials.rs b/crates/coding_agent_worker/src/outbound/credentials.rsnew file mode 100644index 0000000000..b0b8c67111--- /dev/null+++ b/crates/coding_agent_worker/src/outbound/credentials.rs@@ -0,0 +1,107 @@+//! The daemon's persisted identity: which harness this machine is, and the+//! bearer token that proves it.+//!+//! Written once by pairing and read at every boot, in a state file next to+//! the config - the same shape as the webhook feed state. Losing the file is+//! recoverable by pairing again.++use std::path::{Path, PathBuf};++use harness_id::HarnessId;+use rootcause::prelude::ResultExt as _;+use serde::{Deserialize, Serialize};++#[cfg(test)]+mod test;++/// Whether the harness is private to its owner or shared with a team.+///+/// Persisted because the webhook feed the daemon registers must live in the+/// matching workspace: a team harness's feed subscribes in the team workspace+/// so teammates' agents' triggers reach it.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum HarnessScope {+ /// Owned by one user.+ User,+ /// Owned by a team.+ Team,+}++/// The credential pairing minted for this daemon.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct HarnessCredentials {+ /// The registered harness this daemon serves.+ pub harness_id: HarnessId,+ /// The bearer token (`mhns_...`).+ pub token: String,+ /// The harness's ownership scope.+ pub scope: HarnessScope,+}++/// Where credentials live and how they are read back.+pub trait CredentialStore {+ /// The persisted credentials, or `None` before the first pairing.+ fn load(&self) -> rootcause::Result<Option<HarnessCredentials>>;++ /// Persist newly minted credentials.+ fn save(&self, credentials: &HarnessCredentials) -> rootcause::Result<()>;+}++/// Credentials in a mode-600 JSON file next to the config.+pub struct FileCredentialStore {+ path: PathBuf,+}++impl FileCredentialStore {+ /// The store for the daemon config at `config_path`.+ pub fn for_config(config_path: &Path) -> Self {+ Self {+ path: credentials_path(config_path),+ }+ }++ /// Where the file lives, for messages that tell the user about it.+ pub fn path(&self) -> &Path {+ &self.path+ }++ fn failure(&self) -> String {+ format!(+ "failed to use the credentials file at {}",+ self.path.display()+ )+ }+}++/// Where the credentials live: next to the config they belong to.+pub fn credentials_path(config_path: &Path) -> PathBuf {+ config_path.with_extension("credentials.json")+}++impl CredentialStore for FileCredentialStore {+ fn load(&self) -> rootcause::Result<Option<HarnessCredentials>> {+ let found = std::fs::read_to_string(&self.path);+ if let Err(error) = &found+ && error.kind() == std::io::ErrorKind::NotFound+ {+ return Ok(None);+ }+ let raw = found.context(self.failure())?;+ // Credentials we cannot parse are credentials we do not have; the+ // caller sends the user back through pairing.+ Ok(serde_json::from_str(&raw).ok())+ }++ fn save(&self, credentials: &HarnessCredentials) -> rootcause::Result<()> {+ let raw = serde_json::to_string_pretty(credentials).expect("a serializable credential");+ std::fs::write(&self.path, raw).context(self.failure())?;+ // The token authenticates this harness; keep it out of other users' reach.+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt as _;+ let _ = std::fs::set_permissions(&self.path, std::fs::Permissions::from_mode(0o600));+ }+ Ok(())+ }+}diff --git a/crates/coding_agent_worker/src/outbound/credentials/test.rs b/crates/coding_agent_worker/src/outbound/credentials/test.rsnew file mode 100644index 0000000000..aab80a9480--- /dev/null+++ b/crates/coding_agent_worker/src/outbound/credentials/test.rs@@ -0,0 +1,40 @@+use super::*;+use harness_id::HarnessId;++fn credentials() -> HarnessCredentials {+ HarnessCredentials {+ harness_id: HarnessId::TEST_A,+ token: "mhns_abc_secret".to_owned(),+ scope: HarnessScope::Team,+ }+}++#[test]+fn round_trips_and_restricts_permissions() {+ let dir = std::env::temp_dir().join(format!("macrod-cred-test-{}", std::process::id()));+ std::fs::create_dir_all(&dir).unwrap();+ let config_path = dir.join("macro.toml");+ let store = FileCredentialStore::for_config(&config_path);++ assert!(store.load().unwrap().is_none());++ store.save(&credentials()).unwrap();+ assert_eq!(store.load().unwrap(), Some(credentials()));+ assert_eq!(store.path(), dir.join("macro.credentials.json").as_path());++ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt as _;+ let mode = std::fs::metadata(store.path())+ .unwrap()+ .permissions()+ .mode();+ assert_eq!(mode & 0o777, 0o600);+ }++ // Unparseable state is treated as absent, sending the user to re-pair.+ std::fs::write(store.path(), "not json").unwrap();+ assert!(store.load().unwrap().is_none());++ let _ = std::fs::remove_dir_all(&dir);+}diff --git a/crates/coding_agent_worker/src/outbound/link.rs b/crates/coding_agent_worker/src/outbound/link.rsindex ef5fb9860b..c34d5a59dc 100644--- a/crates/coding_agent_worker/src/outbound/link.rs+++ b/crates/coding_agent_worker/src/outbound/link.rs@@ -4,22 +4,17 @@ use agent_runtime_protocol::domain::connection::RuntimeChannel;use agent_runtime_protocol::outbound::websocket::connect_runtime;use tokio_tungstenite::tungstenite::client::IntoClientRequest;-/// Dial a session's gateway URL - the `gatewayUrl` returned by-/// `POST /agent-sessions`, taken verbatim - presenting the bot's API token-/// with the standard bot credential headers. A WebSocket upgrade is an-/// ordinary HTTP request, so the same headers every other bot call uses-/// work here too.+/// Dial the runtime gateway, presenting the harness credential. A WebSocket+/// upgrade is an ordinary HTTP request, so the same header every other+/// harness call uses works here too.pub async fn dial(gateway_url: &str,- bot_token: &str,- bot_scope: &str,+ harness_token: &str,) -> Result<RuntimeChannel, tokio_tungstenite::tungstenite::Error> {let mut request = gateway_url.into_client_request()?;let headers = request.headers_mut();- let token = bot_token.parse().map_err(bad_header)?;- headers.insert("x-macro-bot-token", token);- let scope = bot_scope.parse().map_err(bad_header)?;- headers.insert("x-macro-bot-scope", scope);+ let token = harness_token.parse().map_err(bad_header)?;+ headers.insert("x-macro-harness-token", token);let (stream, _response) = tokio_tungstenite::connect_async(request).await?;Ok(connect_runtime(stream))}@@ -29,7 +24,7 @@ fn bad_header() -> tokio_tungstenite::tungstenite::Error {tokio_tungstenite::tungstenite::Error::Url(tokio_tungstenite::tungstenite::error::UrlError::UnableToConnect(- "bot credentials are not valid header values".to_owned(),+ "the harness credential is not a valid header value".to_owned(),),)}diff --git a/crates/coding_agent_worker/src/outbound/mod.rs b/crates/coding_agent_worker/src/outbound/mod.rsindex b8921c29b9..bb69857e36 100644--- a/crates/coding_agent_worker/src/outbound/mod.rs+++ b/crates/coding_agent_worker/src/outbound/mod.rs@@ -7,5 +7,7 @@//! runtime surprise on someone's laptop.pub mod agent_session;+pub mod credentials;pub mod link;+pub mod pairing;pub mod registration;diff --git a/crates/coding_agent_worker/src/outbound/pairing.rs b/crates/coding_agent_worker/src/outbound/pairing.rsnew file mode 100644index 0000000000..7b361cc5a4--- /dev/null+++ b/crates/coding_agent_worker/src/outbound/pairing.rs@@ -0,0 +1,151 @@+//! The daemon's half of device-code pairing: ask for a code, tell the user+//! where to approve it, poll until the credential is released.++use std::time::Duration;++use harnesses::domain::models::{+ ClaimPairingRequest, ClaimedPairing, CreatePairingRequest, CreatedPairing,+ RequestedHarnessScope,+};+use reqwest::StatusCode;+use rootcause::prelude::ResultExt as _;++use crate::config::Config;+use crate::outbound::credentials::{HarnessCredentials, HarnessScope};++/// How long past the server-stated expiry polling keeps trying: zero. The+/// server keeps an approved pairing claimable, so expiry here only ends the+/// wait for a user who never approved.+const POLL_GRACE: Duration = Duration::ZERO;++/// Walk the whole pairing flow interactively and return minted credentials.+///+/// Prints the code and approval link to stdout on purpose: this is the one+/// conversation the daemon has with a human.+pub async fn pair(config: &Config) -> rootcause::Result<HarnessCredentials> {+ let http = reqwest::Client::new();+ let base = config+ .macro_api+ .storage_url+ .trim_end_matches('/')+ .to_owned();++ let name = config+ .identity+ .name+ .clone()+ .or_else(local_hostname)+ .unwrap_or_else(|| "macrod".to_owned());+ let host = host_info();+ let scope = match config.identity.scope {+ crate::config::IdentityScope::Private => RequestedHarnessScope::Private,+ crate::config::IdentityScope::Team => RequestedHarnessScope::Team,+ };++ let response = http+ .post(format!("{base}/harness-pairings"))+ .json(&CreatePairingRequest {+ name,+ host: Some(host),+ scope: Some(scope),+ })+ .send()+ .await+ .context("could not reach the service to start pairing")?;+ if !response.status().is_success() {+ let status = response.status();+ let message = response.text().await.unwrap_or_default();+ rootcause::bail!("the service refused to start pairing ({status}): {message}");+ }+ let pairing: CreatedPairing = response+ .json()+ .await+ .context("could not read the pairing the service created")?;++ let approval_url = config.macro_api.pairing_approval_url(&pairing.code);+ let expires_in = (pairing.expires_at - chrono::Utc::now())+ .to_std()+ .unwrap_or_default();+ println!();+ println!(" Your pairing code: {}", pairing.code);+ let scope_word = match scope {+ RequestedHarnessScope::Private => "private",+ RequestedHarnessScope::Team => "team",+ };+ println!();+ println!(" Open {approval_url}");+ println!(" and approve this daemon (confirm the code; it asks to be {scope_word}).");+ println!();+ println!(+ " Waiting for approval... (expires in {} minutes)",+ expires_in.as_secs() / 60+ );++ let poll_interval = Duration::from_secs(pairing.poll_interval_seconds.max(1));+ let deadline = tokio::time::Instant::now() + expires_in + POLL_GRACE;+ loop {+ tokio::time::sleep(poll_interval).await;+ if tokio::time::Instant::now() > deadline {+ rootcause::bail!(+ "the pairing expired before it was approved; run `macrod login` to start over"+ );+ }++ let response = http+ .post(format!(+ "{base}/harness-pairings/{}/claim",+ pairing.pairing_id+ ))+ .json(&ClaimPairingRequest {+ device_secret: pairing.device_secret.clone(),+ })+ .send()+ .await+ .context("could not reach the service to poll the pairing")?;+ match response.status() {+ StatusCode::ACCEPTED => continue,+ StatusCode::OK => {+ let claimed: ClaimedPairing = response+ .json()+ .await+ .context("could not read the claimed credential")?;+ let scope = match claimed.harness.owner {+ harnesses::domain::models::HarnessOwner::User { .. } => HarnessScope::User,+ harnesses::domain::models::HarnessOwner::Team { .. } => HarnessScope::Team,+ };+ println!(+ "Approved. This machine is now the harness \"{}\" ({}).",+ claimed.harness.name, claimed.harness.id+ );+ return Ok(HarnessCredentials {+ harness_id: claimed.harness.id,+ token: claimed.token,+ scope,+ });+ }+ StatusCode::GONE => {+ rootcause::bail!(+ "the pairing is no longer claimable (expired or already used); run `macrod login` to start over"+ );+ }+ status => {+ let message = response.text().await.unwrap_or_default();+ rootcause::bail!("the service refused the pairing poll ({status}): {message}");+ }+ }+ }+}++fn local_hostname() -> Option<String> {+ std::process::Command::new("hostname")+ .output()+ .ok()+ .filter(|output| output.status.success())+ .map(|output| String::from_utf8_lossy(&output.stdout).trim().to_owned())+ .filter(|name| !name.is_empty())+}++fn host_info() -> String {+ let host = local_hostname().unwrap_or_else(|| "unknown-host".to_owned());+ format!("{host} / {}", std::env::consts::OS)+}diff --git a/crates/coding_agent_worker/src/outbound/registration.rs b/crates/coding_agent_worker/src/outbound/registration.rsindex 16b2ebba3c..f3dc409db7 100644--- a/crates/coding_agent_worker/src/outbound/registration.rs+++ b/crates/coding_agent_worker/src/outbound/registration.rs@@ -1,22 +1,28 @@-//! Boot-time webhook feed reconciliation: make sure this daemon's bot has a-//! validated trigger feed pointing at this daemon, without any manual step.+//! Webhook feed reconciliation: make sure this harness has a validated+//! trigger feed pointing at this daemon and covering every agent bound to it.//!-//! The flow is deliberately the plain webhook API driven as the bot acting-//! for its owner: who am I (`/bots/me`), do I have a feed (list), is it-//! mine and current (endpoint match), verify it if unverified, create it if-//! missing. It leans on no server-side affordance beyond that API: the feed-//! is an ordinary webhook, scoped to this bot by an `ids` filter and found-//! again by the namespace this daemon mints for it.+//! The flow is deliberately the plain webhook API driven as the harness: which+//! agents am I serving (`/harnesses/me/agents`), do I have a feed (list), is+//! it mine and current (endpoint and bound-agent match), verify it if+//! unverified, create it if missing or stale. It leans on no server-side+//! affordance beyond that API: the feed is an ordinary webhook, scoped to the+//! bound bots by an `ids` filter and found again by the namespace this daemon+//! mints for it.+//!+//! Run at boot and then periodically: a teammate binding a new agent to this+//! harness changes the bound set, and the feed must grow to cover it without+//! a daemon restart.//!//! Secrets are only ever returned at creation, so the daemon persists its//! feed's id and secret in a state file next to the config. Losing the file//! is recoverable: the stale feed is deleted and recreated.+use std::collections::BTreeSet;use std::path::{Path, PathBuf};use agent_trigger::domain::broker_events::AgentTriggerEventName;-use bot_id::BotId;-use bots::domain::models::Bot;+use harness_id::HarnessId;+use harnesses::domain::models::HarnessAgent;use rootcause::prelude::ResultExt as _;use serde::{Deserialize, Serialize};use strum::IntoEnumIterator as _;@@ -26,21 +32,17 @@ use webhook::domain::models::{};use crate::config::{MacroApi, Server};+use crate::outbound::credentials::{HarnessCredentials, HarnessScope};#[cfg(test)]mod test;-const BOT_TOKEN_HEADER: &str = "x-macro-bot-token";-const BOT_SCOPE_HEADER: &str = "x-macro-bot-scope";-const BOT_ACTING_USER_HEADER: &str = "x-macro-bot-for-macro-user-id";+const HARNESS_TOKEN_HEADER: &str = "x-macro-harness-token";-/// The namespace a daemon's feed carries: derived from its bot, so the feed-/// can be found again without the server marking it as that bot's.-///-/// Takes the `BotId` rather than its rendering, so no other identifier can be-/// mistaken for the bot this feed belongs to.-fn feed_namespace(bot: BotId) -> String {- format!("agent-feed-{bot}")+/// The namespace a daemon's feed carries: derived from its harness, so the+/// feed can be found again without the server marking it as this harness's.+fn feed_namespace(harness: HarnessId) -> String {+ format!("harness-feed-{harness}")}/// Every event a trigger feed carries, straight from the topic's own@@ -124,24 +126,27 @@ pub fn state_path(config_path: &Path) -> PathBuf {config_path.with_extension("webhook-state.json")}-/// The webhook-feed reconciler for one bot on one deployment.+/// The webhook-feed reconciler for one harness on one deployment.pub(crate) struct FeedReconciler<S = FileFeedStateStore> {http: reqwest::Client,base: String,- macro_api: MacroApi,- owner_user_id: String,+ credentials: HarnessCredentials,public_url: String,state_store: S,}impl FeedReconciler<FileFeedStateStore> {- /// Build a reconciler from the daemon's config.- pub fn new(macro_api: &MacroApi, server: &Server, config_path: &Path) -> Self {+ /// Build a reconciler from the daemon's config and paired credentials.+ pub fn new(+ macro_api: &MacroApi,+ server: &Server,+ credentials: HarnessCredentials,+ config_path: &Path,+ ) -> Self {Self {http: reqwest::Client::new(),base: macro_api.storage_url.trim_end_matches('/').to_owned(),- macro_api: macro_api.clone(),- owner_user_id: macro_api.owner_user_id.clone(),+ credentials,public_url: server.public_url.clone(),state_store: FileFeedStateStore {path: state_path(config_path),@@ -152,10 +157,7 @@ impl FeedReconciler<FileFeedStateStore> {impl<S: FeedStateStore> FeedReconciler<S> {fn credentialed(&self, request: reqwest::RequestBuilder) -> reqwest::RequestBuilder {- request- .header(BOT_TOKEN_HEADER, &self.macro_api.bot_token)- .header(BOT_SCOPE_HEADER, &self.macro_api.bot_scope)- .header(BOT_ACTING_USER_HEADER, &self.owner_user_id)+ request.header(HARNESS_TOKEN_HEADER, &self.credentials.token)}async fn read<T: serde::de::DeserializeOwned>(@@ -179,16 +181,44 @@ impl<S: FeedStateStore> FeedReconciler<S> {.context(format!("could not read the service's answer to {what}"))?)}- /// Reconcile: return a feed that exists, points at this daemon, and- /// whose secret this daemon holds.- pub async fn ensure_feed(&self) -> rootcause::Result<FeedRegistration> {- let me: Bot = self+ /// The agents currently bound to this harness, as sorted bot-id strings -+ /// the shape the feed filter carries.+ pub async fn bound_bot_ids(&self) -> rootcause::Result<Vec<String>> {+ let agents: Vec<HarnessAgent> = self.read(- "identify the bot",- self.http.get(format!("{}/bots/me", self.base)),+ "list this harness's agents",+ self.http.get(format!("{}/harnesses/me/agents", self.base)),).await?;- let bot = me.id;+ let ids: BTreeSet<String> = agents+ .into_iter()+ .map(|agent| agent.bot_id.to_string())+ .collect();+ Ok(ids.into_iter().collect())+ }++ /// Whether an existing feed row already covers exactly `bot_ids`.+ fn covers(row: &Webhook, public_url: &str, bot_ids: &[String]) -> bool {+ if row.endpoint_url != public_url {+ return false;+ }+ let current: BTreeSet<&str> = row+ .filters+ .iter()+ .flat_map(|filter| filter.ids.iter().flatten())+ .map(String::as_str)+ .collect();+ let wanted: BTreeSet<&str> = bot_ids.iter().map(String::as_str).collect();+ current == wanted+ }++ /// Reconcile: return a feed that exists, points at this daemon, and+ /// covers every agent currently bound to this harness - or `None` while+ /// nothing is bound, since a filter over no bots is nothing to subscribe+ /// to (and the webhook API rightly refuses an empty ids list).+ pub async fn ensure_feed(&self) -> rootcause::Result<Option<FeedRegistration>> {+ let harness = self.credentials.harness_id;+ let bot_ids = self.bound_bot_ids().await?;let list: ListWebhooksResponse = self.read(@@ -199,26 +229,28 @@ impl<S: FeedStateStore> FeedReconciler<S> {let mine: Vec<&Webhook> = list.webhooks.iter()- .filter(|row| row.namespace == feed_namespace(bot))+ .filter(|row| row.namespace == feed_namespace(harness)).collect();- // The remembered feed, when it still exists and points here.- if let Some(state) = self.state_store.load()?+ // The remembered feed, when it still exists, points here, and covers+ // the current bound set.+ if !bot_ids.is_empty()+ && let Some(state) = self.state_store.load()?&& let Some(row) = mine.iter().find(|row| row.id == state.webhook_id)- && row.endpoint_url == self.public_url+ && Self::covers(row, &self.public_url, &bot_ids){- return Ok(FeedRegistration {+ return Ok(Some(FeedRegistration {webhook_id: state.webhook_id,signing_secret: state.signing_secret,is_valid: row.is_valid,- });+ }));}- // Anything else of ours is a feed whose secret is lost or whose- // endpoint moved: delete before recreating, since one bot needs- // exactly one feed.+ // Anything else of ours is a feed whose secret is lost, whose+ // endpoint moved, or whose bound set changed: delete before+ // recreating, since one harness needs exactly one feed.for row in mine {- tracing::info!(webhook_id = %row.id, "removing this bot's stale trigger feed");+ tracing::info!(webhook_id = %row.id, "removing this harness's stale trigger feed");let response = self.credentialed(self.http@@ -231,23 +263,39 @@ impl<S: FeedStateStore> FeedReconciler<S> {}}+ if bot_ids.is_empty() {+ tracing::warn!(+ "no agents are bound to this harness yet; the trigger feed will be registered \+ once one is (Settings -> Agents)"+ );+ return Ok(None);+ }++ // A team harness's feed subscribes in the team workspace so triggers+ // for teammates' agents - fanned out to every accessor's workspaces -+ // reach it.+ let scope = match self.credentials.scope {+ HarnessScope::User => WebhookScope::User,+ HarnessScope::Team => WebhookScope::Team,+ };let created: CreateWebhookResponse = self.read("create the trigger feed",self.http.post(format!("{}/webhook/webhooks", self.base)).json(&CreateWebhookRequest {- scope: WebhookScope::User,- namespace: feed_namespace(bot),+ scope,+ namespace: feed_namespace(harness),name: "Agent trigger feed".to_owned(),endpoint_url: self.public_url.clone(),headers: None,- // Scoped to this bot: trigger events name the bot they- // are for, so without this the feed would receive- // every bot's triggers in channels its owner can see.+ // Scoped to this harness's agents: trigger events name+ // the bot they are for, so without this the feed would+ // receive every bot's triggers in channels its+ // workspace can see.filters: vec![WebhookFilter {events: trigger_events(),- ids: Some(vec![bot.to_string()]),+ ids: Some(bot_ids),}],}),)@@ -257,13 +305,13 @@ impl<S: FeedStateStore> FeedReconciler<S> {webhook_id: created.id.clone(),signing_secret: created.signing_secret.clone(),})?;- tracing::info!(webhook_id = %created.id, %bot, "trigger feed registered");+ tracing::info!(webhook_id = %created.id, %harness, "trigger feed registered");- Ok(FeedRegistration {+ Ok(Some(FeedRegistration {webhook_id: created.id,signing_secret: created.signing_secret,is_valid: created.is_valid,- })+ }))}/// Ask the service to validate the feed's endpoint; call once serving.diff --git a/crates/coding_agent_worker/src/runtime.rs b/crates/coding_agent_worker/src/runtime.rsindex 3ff1f2ba9f..8bb158d86a 100644--- a/crates/coding_agent_worker/src/runtime.rs+++ b/crates/coding_agent_worker/src/runtime.rs@@ -1,11 +1,12 @@//! This daemon's one connection to the harness service, and the one harness//! process behind it.//!-//! A daemon serves a single bot, and a bot's runtime is a single connection:-//! ACP initializes per connection and tags every session-scoped message with a-//! `sessionId`, so one socket and one harness process carry every session this-//! bot is running. The service decides which sessions those are - it binds a-//! session when work arrives for it - so nothing here is per-session at all.+//! A daemon serves a single registered harness, and a harness's runtime is a+//! single connection: ACP initializes per connection and tags every+//! session-scoped message with a `sessionId`, so one socket and one harness+//! process carry every session of every agent bound to this harness. The+//! service decides which sessions those are - it binds a session when work+//! arrives for it - so nothing here is per-session or per-bot at all.//!//! What that buys: a harness starts once per daemon rather than once per//! session, so only the first mention after boot pays for a cold agent.@@ -21,6 +22,7 @@ use tokio_tungstenite::tungstenite;use crate::config::{Harness, MacroApi};use crate::harness;+use crate::outbound::credentials::HarnessCredentials;use crate::outbound::link;/// A dial races the delivery that asked for it, so it retries quickly and@@ -35,13 +37,14 @@ const DIAL_RETRY_DELAY: Duration = Duration::from_millis(500);/// rebuild itself forever. Nobody is waiting on these, so they back off.const REBUILD_ATTEMPTS: usize = 4;-/// The daemon's connection to its bot's sessions.+/// The daemon's connection to its harness's sessions.////// At most one is live. The flag is the claim on it: a delivery that finds it/// unset dials, and the task serving the connection clears it on the way out,/// so "set" always means "somebody is serving, or about to be".pub struct Runtime {- macro_api: MacroApi,+ gateway_url: String,+ token: String,harness: Harness,live: Arc<AtomicBool>,}@@ -49,9 +52,10 @@ pub struct Runtime {impl Runtime {/// A runtime that dials with the given credentials and spawns the given/// harness.- pub fn new(macro_api: MacroApi, harness: Harness) -> Self {+ pub fn new(macro_api: &MacroApi, credentials: &HarnessCredentials, harness: Harness) -> Self {Self {- macro_api,+ gateway_url: macro_api.gateway_url(),+ token: credentials.token.clone(),harness,live: Arc::new(AtomicBool::new(false)),}@@ -69,8 +73,7 @@ impl Runtime {return Ok(());}- let url = self.macro_api.gateway_url();- let channel = match dial(&self.macro_api, &url, dial_strategy()).await {+ let channel = match dial(&self.token, &self.gateway_url, dial_strategy()).await {Ok(channel) => channel,Err(error) => {self.live.store(false, Ordering::Release);@@ -79,9 +82,9 @@ impl Runtime {};tokio::spawn(serve(- url,+ self.gateway_url.clone(),channel,- self.macro_api.clone(),+ self.token.clone(),self.harness.clone(),Arc::clone(&self.live),));@@ -96,7 +99,7 @@ impl Runtime {async fn serve(gateway_url: String,channel: RuntimeChannel,- macro_api: MacroApi,+ token: String,harness: Harness,live: Arc<AtomicBool>,) {@@ -107,7 +110,7 @@ async fn serve(Ok(()) => tracing::info!("harness bridge ended"),Err(error) => {tracing::warn!(error = ?error, "harness bridge ended with an error");- rebuild(&gateway_url, ¯o_api, &harness).await;+ rebuild(&gateway_url, &token, &harness).await;}}live.store(false, Ordering::Release);@@ -115,11 +118,11 @@ async fn serve(/// Dial and serve again, as one retried operation: ending cleanly stops it, as/// does a gateway verdict no retry can change.-async fn rebuild(gateway_url: &str, macro_api: &MacroApi, harness: &Harness) {+async fn rebuild(gateway_url: &str, token: &str, harness: &Harness) {let outcome = RetryIf::start(rebuild_strategy(),|| async {- let channel = dial(macro_api, gateway_url, dial_strategy())+ let channel = dial(token, gateway_url, dial_strategy()).await.map_err(ServeError::Dial)?;tracing::info!("harness bridge restarting");@@ -160,26 +163,31 @@ fn worth_rebuilding(error: &ServeError) -> bool {/// Dial the gateway, retrying on the failures a retry can fix.async fn dial(- macro_api: &MacroApi,+ token: &str,gateway_url: &str,strategy: impl IntoIterator<Item = Duration>,) -> Result<RuntimeChannel, tungstenite::Error> {- RetryIf::start(- strategy,- || link::dial(gateway_url, ¯o_api.bot_token, ¯o_api.bot_scope),- worth_redialing,- )- .await+ RetryIf::start(strategy, || link::dial(gateway_url, token), worth_redialing).await}/// Whether dialing again could plausibly answer differently. A 4xx is the-/// gateway's verdict on this bot - not an agent bot, credentials refused - and+/// gateway's verdict on this harness - credentials refused or revoked - and/// asking again only repeats it.fn worth_redialing(error: &tungstenite::Error) -> bool {- !matches!(- error,- tungstenite::Error::Http(response) if response.status().is_client_error()- )+ if let tungstenite::Error::Http(response) = error+ && response.status().is_client_error()+ {+ if response.status() == tungstenite::http::StatusCode::UNAUTHORIZED+ || response.status() == tungstenite::http::StatusCode::FORBIDDEN+ {+ tracing::error!(+ status = %response.status(),+ "the gateway refused this harness's credentials; run `macrod login` to re-pair"+ );+ }+ return false;+ }+ true}fn dial_strategy() -> impl Iterator<Item = Duration> {diff --git a/crates/coding_agent_worker/src/webhook.rs b/crates/coding_agent_worker/src/webhook.rsindex 2c7ea379ce..abfdbc8bb2 100644--- a/crates/coding_agent_worker/src/webhook.rs+++ b/crates/coding_agent_worker/src/webhook.rs@@ -17,6 +17,7 @@ use axum::body::Bytes;use axum::extract::State;use axum::http::{HeaderMap, StatusCode};use axum::routing::post;+use bot_id::BotId;use macro_event_broker::Event;use macro_user_id::user_id::MacroUserIdStr;use macro_uuid::Uuid;@@ -35,6 +36,9 @@ pub enum TriggerWork {/// Open a session for a mention, serve it, and forward the mention as/// its first prompt.OpenAndPrompt {+ /// The mentioned agent the session runs for. One harness serves many+ /// agents, so the daemon must name the bot when creating the session.+ bot: BotId,/// Who asked; owns the session and authors the prompt.sender: MacroUserIdStr<'static>,/// Channel the mention was posted in.@@ -82,6 +86,7 @@ pub fn trigger_to_work(event: AgentTriggerTopicEvent) -> Result<TriggerWork, Ski.cloned().ok_or(Skipped::NotFromUser)?;Ok(TriggerWork::OpenAndPrompt {+ bot: mentioned.bot_id,sender,channel_id: message.channel_id,// A top-level mention roots its own thread; a mention inside@@ -122,8 +127,10 @@ pub trait WorkExecutor: Send + Sync + 'static {pub struct WebhookState<Executor> {/// Where translated work goes.pub executor: Executor,- /// The webhook's signing secret, shared with the deliverer.- pub signing_secret: String,+ /// The webhook's signing secret, shared with the deliverer. Behind a lock+ /// because feed reconciliation replaces the feed - and its secret - when+ /// the bound-agent set changes.+ pub signing_secret: std::sync::Arc<std::sync::RwLock<String>>,}/// Build the router serving `POST /macro-events`.@@ -144,7 +151,12 @@ async fn ingest<Executor: WorkExecutor>(else {return StatusCode::UNAUTHORIZED;};- if !webhook_signature::verify(&state.signing_secret, timestamp, &body, signature) {+ let signing_secret = state+ .signing_secret+ .read()+ .expect("signing secret lock")+ .clone();+ if !webhook_signature::verify(&signing_secret, timestamp, &body, signature) {return StatusCode::UNAUTHORIZED;}diff --git a/crates/coding_agent_worker/src/webhook/test.rs b/crates/coding_agent_worker/src/webhook/test.rsindex 2fdd790db1..441f774e41 100644--- a/crates/coding_agent_worker/src/webhook/test.rs+++ b/crates/coding_agent_worker/src/webhook/test.rs@@ -57,6 +57,7 @@ fn a_mention_becomes_open_and_prompt_rooting_its_own_thread() {assert_eq!(work,TriggerWork::OpenAndPrompt {+ bot: bot_id::BotId::TEST_A,sender: sender(),channel_id: Uuid::from_u128(1),thread_id: Uuid::from_u128(2),@@ -127,7 +128,7 @@ fn state() -> Arc<WebhookState<std::sync::Arc<RecordingExecutor>>> {Arc::new(WebhookState {executor,- signing_secret: SECRET.to_owned(),+ signing_secret: std::sync::Arc::new(std::sync::RwLock::new(SECRET.to_owned())),})}diff --git a/crates/entity_access/src/inbound/axum_extractors/entity_body.rs b/crates/entity_access/src/inbound/axum_extractors/entity_body.rsindex c701726737..a5dd0ee0ea 100644--- a/crates/entity_access/src/inbound/axum_extractors/entity_body.rs+++ b/crates/entity_access/src/inbound/axum_extractors/entity_body.rs@@ -101,6 +101,7 @@ whereMacroAuthorization::User(user) | MacroAuthorization::Internal(Some(user)) => {user.macro_user_id}+ MacroAuthorization::Harness(_) => return Err(ExtractorError::Unauthorized),MacroAuthorization::Bot(_) | MacroAuthorization::Internal(None) => {unreachable!("bot and identity-less internal access returned above")}diff --git a/crates/entity_access/src/inbound/axum_extractors/entity_permission.rs b/crates/entity_access/src/inbound/axum_extractors/entity_permission.rsindex 028d219975..b7c8b2c552 100644--- a/crates/entity_access/src/inbound/axum_extractors/entity_permission.rs+++ b/crates/entity_access/src/inbound/axum_extractors/entity_permission.rs@@ -91,6 +91,7 @@ wherelet (is_internal_access, acting_user) = match authorization.authorization.as_ref() {Some(MacroAuthorization::User(user)) => (false, Some(user)),Some(MacroAuthorization::Internal(user)) => (true, user.as_ref()),+ Some(MacroAuthorization::Harness(_)) => return Err(ExtractorError::Unauthorized),Some(MacroAuthorization::Bot(_)) => unreachable!("bot authorization returned above"),None => (false, None),};diff --git a/crates/entity_access/src/inbound/axum_extractors/pin.rs b/crates/entity_access/src/inbound/axum_extractors/pin.rsindex 0faf29d5d5..d597d2155f 100644--- a/crates/entity_access/src/inbound/axum_extractors/pin.rs+++ b/crates/entity_access/src/inbound/axum_extractors/pin.rs@@ -80,7 +80,9 @@ whereSome(user.macro_user_id.clone())}MacroAuthorization::Bot(_) => None,- MacroAuthorization::Internal(None) => return Err(ExtractorError::Unauthorized),+ MacroAuthorization::Harness(_) | MacroAuthorization::Internal(None) => {+ return Err(ExtractorError::Unauthorized);+ }};let Path(PinParams { pinned_item_id }) = req@@ -135,7 +137,9 @@ where_marker: PhantomData,}}- MacroAuthorization::Internal(None) => return Err(ExtractorError::Unauthorized),+ MacroAuthorization::Harness(_) | MacroAuthorization::Internal(None) => {+ return Err(ExtractorError::Unauthorized);+ }};Ok(Self {diff --git a/crates/entity_access/src/inbound/axum_extractors/project.rs b/crates/entity_access/src/inbound/axum_extractors/project.rsindex ba8af05203..27149c44db 100644--- a/crates/entity_access/src/inbound/axum_extractors/project.rs+++ b/crates/entity_access/src/inbound/axum_extractors/project.rs@@ -89,9 +89,10 @@ wherelet macro_user_id = match authorization.authorization.as_ref() {Some(MacroAuthorization::User(user))| Some(MacroAuthorization::Internal(Some(user))) => Some(user.macro_user_id.clone()),- Some(MacroAuthorization::Bot(_)) | Some(MacroAuthorization::Internal(None)) | None => {- None- }+ Some(MacroAuthorization::Bot(_))+ | Some(MacroAuthorization::Harness(_))+ | Some(MacroAuthorization::Internal(None))+ | None => None,};if let Some(ref user_id) = macro_user_id@@ -345,6 +346,7 @@ whereget_project_access_receipt(service.as_ref(), Some(user.macro_user_id), project.id()).await?}+ Some(MacroAuthorization::Harness(_)) => return Err(ExtractorError::Unauthorized),None => get_project_access_receipt(service.as_ref(), None, project.id()).await?,};diff --git a/crates/entity_access/src/inbound/axum_extractors/team.rs b/crates/entity_access/src/inbound/axum_extractors/team.rsindex df30fe642b..d6f563bab5 100644--- a/crates/entity_access/src/inbound/axum_extractors/team.rs+++ b/crates/entity_access/src/inbound/axum_extractors/team.rs@@ -142,7 +142,7 @@ whereMacroAuthorization::Bot(authentication) => {bot_team_access_outcome::<T, Svc>(service, &authentication).await}- MacroAuthorization::Internal(None) => {+ MacroAuthorization::Harness(_) | MacroAuthorization::Internal(None) => {Err(ExtractorError::UnauthorizedWithMessage("unauthorized"))}}diff --git a/crates/harness_id/Cargo.toml b/crates/harness_id/Cargo.tomlnew file mode 100644index 0000000000..2dc358aedc--- /dev/null+++ b/crates/harness_id/Cargo.toml@@ -0,0 +1,21 @@+[package]+edition = "2024"+name = "harness_id"+publish = false+version = "0.1.0"++[features]+schema = ["dep:utoipa"]+sqlx = ["dep:sqlx"]+test-utils = []++[dependencies]+serde = { workspace = true }+sqlx = { workspace = true, optional = true }+thiserror = { workspace = true }+utoipa = { workspace = true, optional = true }+uuid = { workspace = true }+workspace-hack = { version = "0.1", path = "../workspace-hack" }++[dev-dependencies]+serde_json = { workspace = true }diff --git a/crates/harness_id/src/lib.rs b/crates/harness_id/src/lib.rsnew file mode 100644index 0000000000..58cc7703bd--- /dev/null+++ b/crates/harness_id/src/lib.rs@@ -0,0 +1,136 @@+#![deny(missing_docs)]++//! Harness identity primitives.+//!+//! A harness is a user-run agent runtime (a macrod daemon) registered with+//! Macro. Its id is shared by the registration API, the authorization layer,+//! and the runtime gateway, so the newtype lives in this leaf crate the way+//! [`bot_id`](https://docs.rs) does for bots, keeping those crates decoupled.++use serde::{Deserialize, Serialize};+use uuid::Uuid;++#[cfg(test)]+mod test;++/// Runtime slug persisted on agents served by a registered harness.+///+/// `agent_configs.harness` keeps holding the runtime slug for built-in+/// runtimes; agents bound to a registered harness store this sentinel plus+/// the harness row id.+pub const MACROD_HARNESS_SLUG: &str = "macrod";++/// A harness id UUID.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]+#[serde(transparent)]+pub struct HarnessId(Uuid);++impl HarnessId {+ #[cfg(any(test, feature = "test-utils"))]+ #[allow(missing_docs)]+ pub const TEST_A: Self = Self(Uuid::from_u128(0x4A125A));++ #[cfg(any(test, feature = "test-utils"))]+ #[allow(missing_docs)]+ pub const TEST_B: Self = Self(Uuid::from_u128(0x4A125B));++ /// Build a harness id from its UUID.+ pub const fn new_from_uuid(id: Uuid) -> Self {+ Self(id)+ }++ /// Return the underlying UUID.+ pub const fn as_uuid(self) -> Uuid {+ self.0+ }++ /// Parse a harness id from its UUID string representation.+ pub fn parse_uuid_str(value: &str) -> Result<Self, HarnessIdParseError> {+ Uuid::parse_str(value)+ .map(Self)+ .map_err(|_| HarnessIdParseError::invalid(value))+ }+}++impl std::fmt::Display for HarnessId {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ write!(f, "{}", self.0)+ }+}++impl std::str::FromStr for HarnessId {+ type Err = HarnessIdParseError;++ fn from_str(value: &str) -> Result<Self, Self::Err> {+ Self::parse_uuid_str(value)+ }+}++/// Error returned when a harness id cannot be parsed.+#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]+#[error("invalid harness id: {value}")]+pub struct HarnessIdParseError {+ value: String,+}++impl HarnessIdParseError {+ fn invalid(value: &str) -> Self {+ Self {+ value: value.to_string(),+ }+ }+}++#[cfg(feature = "schema")]+impl utoipa::ToSchema for HarnessId {+ fn name() -> std::borrow::Cow<'static, str> {+ std::borrow::Cow::Borrowed("HarnessId")+ }+}++#[cfg(feature = "schema")]+impl utoipa::PartialSchema for HarnessId {+ fn schema() -> utoipa::openapi::RefOr<utoipa::openapi::schema::Schema> {+ String::schema()+ }+}++#[cfg(feature = "sqlx")]+impl sqlx::Type<sqlx::Postgres> for HarnessId {+ fn type_info() -> sqlx::postgres::PgTypeInfo {+ <Uuid as sqlx::Type<sqlx::Postgres>>::type_info()+ }++ fn compatible(ty: &sqlx::postgres::PgTypeInfo) -> bool {+ <Uuid as sqlx::Type<sqlx::Postgres>>::compatible(ty)+ }+}++#[cfg(feature = "sqlx")]+impl sqlx::postgres::PgHasArrayType for HarnessId {+ fn array_type_info() -> sqlx::postgres::PgTypeInfo {+ <Uuid as sqlx::postgres::PgHasArrayType>::array_type_info()+ }+}++#[cfg(feature = "sqlx")]+impl<'q> sqlx::Encode<'q, sqlx::Postgres> for HarnessId {+ fn encode_by_ref(+ &self,+ buf: &mut sqlx::postgres::PgArgumentBuffer,+ ) -> Result<sqlx::encode::IsNull, sqlx::error::BoxDynError> {+ <Uuid as sqlx::Encode<sqlx::Postgres>>::encode_by_ref(&self.0, buf)+ }++ fn size_hint(&self) -> usize {+ <Uuid as sqlx::Encode<sqlx::Postgres>>::size_hint(&self.0)+ }+}++#[cfg(feature = "sqlx")]+impl<'r> sqlx::Decode<'r, sqlx::Postgres> for HarnessId {+ fn decode(value: sqlx::postgres::PgValueRef<'r>) -> Result<Self, sqlx::error::BoxDynError> {+ let value = <Uuid as sqlx::Decode<sqlx::Postgres>>::decode(value)?;+ Ok(Self(value))+ }+}diff --git a/crates/harness_id/src/test.rs b/crates/harness_id/src/test.rsnew file mode 100644index 0000000000..c1852c8bce--- /dev/null+++ b/crates/harness_id/src/test.rs@@ -0,0 +1,24 @@+use super::*;++#[test]+fn round_trips_through_display_and_from_str() {+ let id = HarnessId::TEST_A;+ let text = id.to_string();+ let parsed: HarnessId = text.parse().expect("display output parses");+ assert_eq!(parsed, id);+}++#[test]+fn rejects_non_uuid_input() {+ let error = HarnessId::parse_uuid_str("not-a-uuid").unwrap_err();+ assert_eq!(error.to_string(), "invalid harness id: not-a-uuid");+}++#[test]+fn serde_is_transparent() {+ let id = HarnessId::TEST_B;+ let json = serde_json::to_string(&id).expect("serializes");+ assert_eq!(json, format!("\"{}\"", id.as_uuid()));+ let back: HarnessId = serde_json::from_str(&json).expect("deserializes");+ assert_eq!(back, id);+}diff --git a/crates/harness_token/Cargo.toml b/crates/harness_token/Cargo.tomlnew file mode 100644index 0000000000..42f8763e1f--- /dev/null+++ b/crates/harness_token/Cargo.toml@@ -0,0 +1,9 @@+[package]+edition = "2024"+name = "harness_token"+publish = false+version = "0.1.0"++[dependencies]+sha2 = { workspace = true }+workspace-hack = { version = "0.1", path = "../workspace-hack" }diff --git a/crates/harness_token/src/lib.rs b/crates/harness_token/src/lib.rsnew file mode 100644index 0000000000..3e30ba788f--- /dev/null+++ b/crates/harness_token/src/lib.rs@@ -0,0 +1,71 @@+//! Hash and display-prefix helpers for harness bearer tokens.+//!+//! Mint (`harnesses`) and auth-time lookup (`macro_authorization`) both+//! persist or match `token_hash`. This crate owns that digest so the two+//! sides cannot drift, without either crate depending on the other. It is the+//! harness sibling of `bot_token`.++#![deny(missing_docs)]++use sha2::{Digest, Sha256};++#[cfg(test)]+mod test;++/// Number of characters used as a fallback display prefix.+const FALLBACK_PREFIX_CHARS: usize = 12;++/// SHA-256 of a raw harness bearer token's UTF-8 bytes.+pub fn hash_token(token: &str) -> [u8; 32] {+ Sha256::digest(token.as_bytes()).into()+}++/// Display prefix for a harness bearer token.+///+/// Current tokens look like `mhns_<hex>_<secret>`. The displayed prefix is+/// `mhns_<hex>`. Tokens that do not match that shape use the first 12 hex+/// characters of the SHA-256, never a raw substring of the secret.+pub fn token_prefix(token: &str) -> String {+ if let Some(rest) = token.strip_prefix("mhns_")+ && let Some((prefix, _)) = rest.split_once('_')+ && !prefix.is_empty()+ {+ return format!("mhns_{prefix}");+ }+ fallback_prefix(token)+}++fn fallback_prefix(token: &str) -> String {+ hash_token(token)+ .into_iter()+ .take(FALLBACK_PREFIX_CHARS / 2)+ .fold(+ String::with_capacity(FALLBACK_PREFIX_CHARS),+ |mut out, byte| {+ use std::fmt::Write;+ let _ = write!(out, "{byte:02x}");+ out+ },+ )+}++/// Hash and display prefix derived from a raw harness bearer token.+///+/// Persist this. Never persist the raw secret.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct HashedHarnessToken {+ /// SHA-256 of the raw token UTF-8 bytes.+ pub hash: [u8; 32],+ /// Display prefix (`mhns_<hex>` or a hash-derived fallback).+ pub prefix: String,+}++impl HashedHarnessToken {+ /// Hash a raw bearer token for storage.+ pub fn from_raw(token: &str) -> Self {+ Self {+ hash: hash_token(token),+ prefix: token_prefix(token),+ }+ }+}diff --git a/crates/harness_token/src/test.rs b/crates/harness_token/src/test.rsnew file mode 100644index 0000000000..f006846b40--- /dev/null+++ b/crates/harness_token/src/test.rs@@ -0,0 +1,36 @@+use super::*;++#[test]+fn hashes_utf8_bytes_with_sha256() {+ use sha2::{Digest, Sha256};++ let hash = hash_token("mhns_abc_secret");+ let expected: [u8; 32] = Sha256::digest(b"mhns_abc_secret").into();+ assert_eq!(hash, expected);+ assert_ne!(hash, hash_token("mhns_abc_other"));+}++#[test]+fn token_prefix_uses_mhns_segment_or_hash_fallback() {+ assert_eq!(+ token_prefix("mhns_aabbccddeeff_aabbccddeeffrest"),+ "mhns_aabbccddeeff"+ );++ let leftover = "550e8400-e29b-41d4-a716-446655440000";+ let leftover_prefix = token_prefix(leftover);+ assert_eq!(leftover_prefix.len(), 12);+ assert_ne!(leftover_prefix, leftover);++ assert_eq!(token_prefix("short").len(), 12);+ assert_ne!(token_prefix("short"), "short");+}++#[test]+fn hashed_harness_token_does_not_retain_the_raw_secret() {+ let raw = "mhns_aabbccddeeff_aabbccddeeffsecret";+ let hashed = HashedHarnessToken::from_raw(raw);+ assert_eq!(hashed.hash, hash_token(raw));+ assert_eq!(hashed.prefix, "mhns_aabbccddeeff");+ assert_ne!(hashed.prefix, raw);+}diff --git a/crates/harnesses/Cargo.toml b/crates/harnesses/Cargo.tomlnew file mode 100644index 0000000000..c08025b70a--- /dev/null+++ b/crates/harnesses/Cargo.toml@@ -0,0 +1,48 @@+[package]+edition = "2024"+name = "harnesses"+publish = false+version = "0.1.0"++[features]+default = ["inbound", "outbound", "ports"]+inbound = [+ "dep:axum",+ "dep:macro_authorization",+ "macro_authorization/axum",+ "dep:model-error-response",+ "dep:utoipa",+ "ports",+]+outbound = ["dep:sqlx", "ports"]+ports = ["dep:tokio"]+test-utils = ["dep:mockall", "ports"]++[dependencies]+anyhow = { workspace = true }+axum = { workspace = true, optional = true }+bot_id = { path = "../bot_id", features = ["schema"] }+chrono = { workspace = true }+constant_time_eq = { workspace = true }+harness_id = { path = "../harness_id", features = ["schema", "sqlx"] }+harness_token = { path = "../harness_token" }+hex = { workspace = true }+macro_authorization = { path = "../macro_authorization", optional = true, default-features = false }+macro_user_id = { path = "../macro_user_id" }+mockall = { workspace = true, optional = true }+model-error-response = { path = "../model-error-response", optional = true }+rand = { workspace = true }+serde = { workspace = true }+sqlx = { workspace = true, optional = true }+thiserror = { workspace = true }+tokio = { workspace = true, optional = true }+tracing = { workspace = true }+utoipa = { workspace = true, optional = true }+uuid = { workspace = true }+workspace-hack = { version = "0.1", path = "../workspace-hack" }++[dev-dependencies]+harness_id = { path = "../harness_id", features = ["test-utils"] }+macro_db_migrator = { path = "../macro_db_migrator" }+serde_json = { workspace = true }+tokio = { workspace = true, features = ["macros", "rt-multi-thread"] }diff --git a/crates/harnesses/src/domain/mod.rs b/crates/harnesses/src/domain/mod.rsnew file mode 100644index 0000000000..27a4fef7c6--- /dev/null+++ b/crates/harnesses/src/domain/mod.rs@@ -0,0 +1,10 @@+//! Harness domain.++/// Domain models.+pub mod models;+/// Ports connecting the domain to its adapters.+pub mod ports;+/// Domain service implementation.+pub mod service;+/// Pairing code, device secret, and harness token generation.+pub mod tokens;diff --git a/crates/harnesses/src/domain/models.rs b/crates/harnesses/src/domain/models.rsnew file mode 100644index 0000000000..9300ad0eea--- /dev/null+++ b/crates/harnesses/src/domain/models.rs@@ -0,0 +1,217 @@+//! Harness domain models.++use bot_id::BotId;+use chrono::{DateTime, Utc};+use harness_id::HarnessId;+use serde::{Deserialize, Serialize};+use uuid::Uuid;++/// Harness owner.+///+/// Exactly one of a user or a team, mirroring the bots owner pattern. There+/// are no system harnesses.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]+#[serde(rename_all = "snake_case", tag = "type")]+pub enum HarnessOwner {+ /// User-owned (private) harness.+ User {+ /// Owner user id.+ user_id: String,+ },+ /// Team-owned harness, usable by every team member.+ Team {+ /// Owner team id.+ team_id: Uuid,+ },+}++/// A registered user-run harness.+///+/// Clients deserialize this, so both derives are used.+#[derive(Debug, Clone, Serialize, Deserialize)]+#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]+pub struct Harness {+ /// Harness id.+ pub id: HarnessId,+ /// Runtime kind. Currently always `macrod`.+ pub kind: String,+ /// Display name.+ pub name: String,+ /// Owner.+ pub owner: HarnessOwner,+ /// User that registered this harness.+ pub created_by: String,+ /// Creation timestamp.+ pub created_at: DateTime<Utc>,+ /// Update timestamp.+ pub updated_at: DateTime<Utc>,+ /// Whether the daemon currently holds a runtime connection.+ pub connected: bool,+ /// When the daemon last attached a runtime connection.+ pub last_connected_at: Option<DateTime<Utc>>,+}++/// The ownership scope a daemon's config asks for.+///+/// Advisory, not binding: the approving user confirms it in the dialog, which+/// arrives preselected to this. Approval is what actually sets ownership.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]+#[serde(rename_all = "snake_case")]+pub enum RequestedHarnessScope {+ /// Owned by the approving user alone.+ Private,+ /// Shared with the approving user's team.+ Team,+}++impl RequestedHarnessScope {+ /// Storage representation.+ pub const fn as_str(self) -> &'static str {+ match self {+ Self::Private => "private",+ Self::Team => "team",+ }+ }+}++impl std::str::FromStr for RequestedHarnessScope {+ type Err = String;++ fn from_str(value: &str) -> Result<Self, Self::Err> {+ match value {+ "private" => Ok(Self::Private),+ "team" => Ok(Self::Team),+ other => Err(format!("unknown requested harness scope: {other}")),+ }+ }+}++/// Request to open a pairing: the daemon asks for a code the user approves.+///+/// The daemon serializes this, so both derives are used.+#[derive(Debug, Clone, Serialize, Deserialize)]+#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]+pub struct CreatePairingRequest {+ /// Requested harness display name (typically the machine's hostname).+ pub name: String,+ /// Display-only description of the machine, e.g. `eric@macbook / darwin`.+ pub host: Option<String>,+ /// The scope the daemon's config asks for; the approval dialog arrives+ /// preselected to it.+ #[serde(default)]+ pub scope: Option<RequestedHarnessScope>,+}++/// A pairing the daemon created, including its claim credential.+///+/// `device_secret` is returned exactly once and never stored raw; the daemon+/// keeps it to claim the harness credential after approval.+#[derive(Debug, Clone, Serialize, Deserialize)]+#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]+pub struct CreatedPairing {+ /// Pairing id used to poll for the claim.+ pub pairing_id: Uuid,+ /// Human-readable code the user confirms in the web app, `XXXX-XXXX`.+ pub code: String,+ /// Claim credential the daemon must present. Shown only here.+ pub device_secret: String,+ /// When the pairing expires.+ pub expires_at: DateTime<Utc>,+ /// Suggested delay between claim polls.+ pub poll_interval_seconds: u64,+}++/// A pending pairing, as shown to the approving user.+#[derive(Debug, Clone, Serialize, Deserialize)]+#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]+pub struct PairingDetails {+ /// The pairing code, normalized to `XXXX-XXXX`.+ pub code: String,+ /// Harness display name the daemon asked for.+ pub requested_name: String,+ /// Display-only description of the machine.+ pub host: Option<String>,+ /// The scope the daemon's config asked for, when it named one.+ pub requested_scope: Option<RequestedHarnessScope>,+ /// When the pairing was created.+ pub created_at: DateTime<Utc>,+ /// When the pairing expires.+ pub expires_at: DateTime<Utc>,+}++/// Request to approve a pairing and register the harness.+#[derive(Debug, Clone, Serialize, Deserialize)]+#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]+pub struct ApprovePairingRequest {+ /// Display name override. Defaults to the daemon's requested name.+ pub name: Option<String>,+ /// Owning team. Omit for a private, user-owned harness.+ pub team_id: Option<Uuid>,+}++/// Request to claim an approved pairing's credential.+///+/// The daemon serializes this, so both derives are used.+#[derive(Debug, Clone, Serialize, Deserialize)]+#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]+pub struct ClaimPairingRequest {+ /// The claim credential returned when the pairing was created.+ pub device_secret: String,+}++/// Outcome of a claim poll.+#[derive(Debug, Clone)]+pub enum ClaimOutcome {+ /// The user has not approved the pairing yet; poll again.+ Pending,+ /// The pairing was approved; the credential is released exactly once.+ Claimed(ClaimedPairing),+}++/// The credential released to the daemon when a pairing is claimed.+#[derive(Debug, Clone, Serialize, Deserialize)]+#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]+pub struct ClaimedPairing {+ /// The registered harness.+ pub harness: Harness,+ /// The raw harness bearer token. Shown only here; only its hash is stored.+ pub token: String,+}++/// An agent bound to a harness, as listed for the daemon.+#[derive(Debug, Clone, Serialize, Deserialize)]+#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]+pub struct HarnessAgent {+ /// The agent's bot id.+ pub bot_id: BotId,+ /// Display name.+ pub name: String,+ /// Stable `@` handle.+ pub handle: String,+}++/// Persisted pairing state consumed by the domain service.+#[derive(Debug, Clone, PartialEq, Eq)]+pub enum PairingStatus {+ /// Waiting for user approval.+ Pending,+ /// Approved; the credential has not been claimed yet.+ Approved,+ /// The credential was released.+ Claimed,+}++/// A pairing row as the claim path sees it.+#[derive(Debug, Clone)]+pub struct PairingClaimFacts {+ /// SHA-256 of the device secret.+ pub device_secret_hash: [u8; 32],+ /// Current status.+ pub status: PairingStatus,+ /// When the pairing expires.+ pub expires_at: DateTime<Utc>,+ /// The harness created at approval, when approved or claimed.+ pub harness_id: Option<HarnessId>,+}diff --git a/crates/harnesses/src/domain/ports.rs b/crates/harnesses/src/domain/ports.rsnew file mode 100644index 0000000000..8ec98a6b82--- /dev/null+++ b/crates/harnesses/src/domain/ports.rs@@ -0,0 +1,232 @@+//! Harness ports.++use std::future::Future;++use chrono::{DateTime, Utc};+use harness_id::HarnessId;+use harness_token::HashedHarnessToken;+use macro_user_id::user_id::MacroUserIdStr;+use uuid::Uuid;++use super::models::{+ ApprovePairingRequest, ClaimOutcome, ClaimPairingRequest, CreatePairingRequest, CreatedPairing,+ Harness, HarnessAgent, HarnessOwner, PairingClaimFacts, PairingDetails, PairingStatus,+ RequestedHarnessScope,+};++/// A pairing row to persist.+#[derive(Debug, Clone)]+pub struct NewPairing {+ /// Pairing id.+ pub id: Uuid,+ /// Normalized pairing code, `XXXX-XXXX`.+ pub code: String,+ /// SHA-256 of the device secret.+ pub device_secret_hash: [u8; 32],+ /// Requested harness display name.+ pub requested_name: String,+ /// Display-only machine description.+ pub host: Option<String>,+ /// The scope the daemon's config asked for.+ pub requested_scope: Option<RequestedHarnessScope>,+ /// When the pairing expires.+ pub expires_at: DateTime<Utc>,+}++/// A harness row to create at approval.+#[derive(Debug, Clone)]+pub struct NewHarness {+ /// Harness id.+ pub id: HarnessId,+ /// Display name.+ pub name: String,+ /// Owner.+ pub owner: HarnessOwner,+ /// The approving user.+ pub created_by: MacroUserIdStr<'static>,+}++/// A pairing row as the lookup and approval paths see it.+#[derive(Debug, Clone)]+pub struct PairingRow {+ /// The user-facing details.+ pub details: PairingDetails,+ /// Current status.+ pub status: PairingStatus,+}++/// Open (pending, unexpired) pairing counts used to throttle creation.+#[derive(Debug, Clone, Copy)]+pub struct OpenPairingCounts {+ /// Every open pairing.+ pub total: i64,+ /// Open pairings requesting the same name.+ pub with_same_name: i64,+}++/// Harness repository.+#[cfg_attr(feature = "test-utils", mockall::automock(type Err = anyhow::Error;))]+pub trait HarnessRepo: Send + Sync + 'static {+ /// Repository error.+ type Err: Into<anyhow::Error> + Send;++ /// Persist a pairing. Returns `false` when the code is already taken.+ fn insert_pairing(+ &self,+ pairing: NewPairing,+ ) -> impl Future<Output = Result<bool, Self::Err>> + Send;++ /// Drop expired pairing rows.+ fn delete_expired_pairings(&self) -> impl Future<Output = Result<(), Self::Err>> + Send;++ /// Count open pairings for creation throttling.+ fn count_open_pairings(+ &self,+ requested_name: &str,+ ) -> impl Future<Output = Result<OpenPairingCounts, Self::Err>> + Send;++ /// Get a pairing by normalized code, whatever its status.+ fn get_pairing(+ &self,+ code: &str,+ ) -> impl Future<Output = Result<Option<PairingRow>, Self::Err>> + Send;++ /// Create the harness and approve its pairing atomically.+ ///+ /// Applies only to a pending, unexpired pairing; returns `None` when the+ /// pairing raced to another state.+ fn approve_pairing(+ &self,+ code: &str,+ harness: NewHarness,+ ) -> impl Future<Output = Result<Option<Harness>, Self::Err>> + Send;++ /// Get the facts the claim path verifies.+ fn pairing_claim_facts(+ &self,+ pairing_id: Uuid,+ ) -> impl Future<Output = Result<Option<PairingClaimFacts>, Self::Err>> + Send;++ /// Release an approved pairing's credential atomically.+ ///+ /// Flips the pairing to claimed and persists the hashed token in one+ /// transaction; returns `None` when the pairing is not claimable (raced,+ /// expired, or already claimed).+ fn claim_pairing(+ &self,+ pairing_id: Uuid,+ token_id: Uuid,+ token: HashedHarnessToken,+ ) -> impl Future<Output = Result<Option<Harness>, Self::Err>> + Send;++ /// List active harnesses owned by the caller or any of their teams.+ fn list_visible_harnesses(+ &self,+ caller: MacroUserIdStr<'static>,+ ) -> impl Future<Output = Result<Vec<Harness>, Self::Err>> + Send;++ /// Get an active harness by id.+ fn get_harness(+ &self,+ harness_id: HarnessId,+ ) -> impl Future<Output = Result<Option<Harness>, Self::Err>> + Send;++ /// Soft-delete a harness and revoke its tokens.+ fn delete_harness(+ &self,+ harness_id: HarnessId,+ ) -> impl Future<Output = Result<bool, Self::Err>> + Send;++ /// Check team membership.+ fn user_has_team(+ &self,+ caller: MacroUserIdStr<'static>,+ team_id: Uuid,+ ) -> impl Future<Output = Result<bool, Self::Err>> + Send;++ /// Check whether a user owns a team.+ fn user_owns_team(+ &self,+ caller: MacroUserIdStr<'static>,+ team_id: Uuid,+ ) -> impl Future<Output = Result<bool, Self::Err>> + Send;++ /// List active agents bound to a harness.+ fn list_bound_agents(+ &self,+ harness_id: HarnessId,+ ) -> impl Future<Output = Result<Vec<HarnessAgent>, Self::Err>> + Send;+}++/// Harness service.+#[cfg_attr(feature = "test-utils", mockall::automock)]+pub trait HarnessService: Send + Sync + 'static {+ /// Open a pairing for an unauthenticated daemon.+ fn create_pairing(+ &self,+ req: CreatePairingRequest,+ ) -> impl Future<Output = Result<CreatedPairing, HarnessError>> + Send;++ /// Show a pending pairing to the approving user.+ fn get_pairing(+ &self,+ code: &str,+ ) -> impl Future<Output = Result<PairingDetails, HarnessError>> + Send;++ /// Approve a pairing, registering the harness for the caller or a team.+ fn approve_pairing(+ &self,+ caller: MacroUserIdStr<'static>,+ code: &str,+ req: ApprovePairingRequest,+ ) -> impl Future<Output = Result<Harness, HarnessError>> + Send;++ /// Poll an approved pairing's credential with the device secret.+ fn claim_pairing(+ &self,+ pairing_id: Uuid,+ req: ClaimPairingRequest,+ ) -> impl Future<Output = Result<ClaimOutcome, HarnessError>> + Send;++ /// List harnesses visible to the caller.+ fn list_harnesses(+ &self,+ caller: MacroUserIdStr<'static>,+ ) -> impl Future<Output = Result<Vec<Harness>, HarnessError>> + Send;++ /// Revoke a harness the caller may manage.+ fn delete_harness(+ &self,+ caller: MacroUserIdStr<'static>,+ harness_id: HarnessId,+ ) -> impl Future<Output = Result<(), HarnessError>> + Send;++ /// List agents bound to the authenticated harness.+ fn list_bound_agents(+ &self,+ harness_id: HarnessId,+ ) -> impl Future<Output = Result<Vec<HarnessAgent>, HarnessError>> + Send;+}++/// Harness service error.+#[derive(Debug, thiserror::Error)]+pub enum HarnessError {+ /// Bad request.+ #[error("{0}")]+ BadRequest(String),+ /// Not found.+ #[error("{0}")]+ NotFound(String),+ /// The pairing can no longer be used (expired, denied, or already claimed).+ #[error("{0}")]+ Gone(String),+ /// Unauthorized.+ #[error("unauthorized")]+ Unauthorized,+ /// Pairing creation is throttled.+ #[error("too many open pairing requests")]+ Throttled,+ /// Repository error.+ #[error(transparent)]+ Repo(#[from] anyhow::Error),+}diff --git a/crates/harnesses/src/domain/service.rs b/crates/harnesses/src/domain/service.rsnew file mode 100644index 0000000000..ff60e58272--- /dev/null+++ b/crates/harnesses/src/domain/service.rs@@ -0,0 +1,331 @@+//! Harness domain service.++#[cfg(test)]+mod test;++use chrono::{Duration, Utc};+use constant_time_eq::constant_time_eq;+use harness_id::HarnessId;+use harness_token::HashedHarnessToken;+use macro_user_id::user_id::MacroUserIdStr;+use uuid::Uuid;++use super::{+ models::{+ ApprovePairingRequest, ClaimOutcome, ClaimPairingRequest, ClaimedPairing,+ CreatePairingRequest, CreatedPairing, Harness, HarnessAgent, HarnessOwner, PairingDetails,+ PairingStatus,+ },+ ports::{HarnessError, HarnessRepo, HarnessService, NewHarness, NewPairing},+ tokens,+};++/// How long a pairing stays claimable.+const PAIRING_TTL_MINUTES: i64 = 15;+/// Suggested delay between claim polls.+const POLL_INTERVAL_SECONDS: u64 = 5;+/// Cap on open pairings across the deployment; pairing is a human-paced flow.+const MAX_OPEN_PAIRINGS: i64 = 32;+/// Cap on open pairings requesting one name, bounding one stuck daemon.+const MAX_OPEN_PAIRINGS_PER_NAME: i64 = 4;+/// Attempts to find an unused pairing code before giving up.+const CODE_ATTEMPTS: usize = 5;+const MAX_NAME_CHARS: usize = 100;+const MAX_HOST_CHARS: usize = 200;++/// Harness service backed by a repository.+#[derive(Debug, Clone)]+pub struct HarnessServiceImpl<R> {+ repo: R,+}++impl<R> HarnessServiceImpl<R> {+ /// Create a harness service backed by the supplied repository.+ pub fn new(repo: R) -> Self {+ Self { repo }+ }+}++impl<R> HarnessServiceImpl<R>+where+ R: HarnessRepo,+{+ async fn ensure_may_manage(+ &self,+ caller: &MacroUserIdStr<'static>,+ harness: &Harness,+ ) -> Result<(), HarnessError> {+ let may_manage = match &harness.owner {+ HarnessOwner::User { user_id } => user_id == caller.as_ref(),+ // Same rule as team bots: the registrant or the team owner.+ HarnessOwner::Team { team_id } => {+ harness.created_by == caller.as_ref()+ || self+ .repo+ .user_owns_team(caller.clone(), *team_id)+ .await+ .map_err(Into::into)?+ }+ };+ if !may_manage {+ return Err(HarnessError::Unauthorized);+ }+ Ok(())+ }+}++impl<R> HarnessService for HarnessServiceImpl<R>+where+ R: HarnessRepo,+{+ #[tracing::instrument(skip_all, err)]+ async fn create_pairing(+ &self,+ req: CreatePairingRequest,+ ) -> Result<CreatedPairing, HarnessError> {+ let name = req.name.trim();+ if name.is_empty() || name.chars().count() > MAX_NAME_CHARS {+ return Err(HarnessError::BadRequest(format!(+ "name must be 1..={MAX_NAME_CHARS} characters"+ )));+ }+ let host = req+ .host+ .as_deref()+ .map(str::trim)+ .filter(|host| !host.is_empty())+ .map(|host| host.chars().take(MAX_HOST_CHARS).collect::<String>());++ self.repo+ .delete_expired_pairings()+ .await+ .map_err(Into::into)?;+ let counts = self+ .repo+ .count_open_pairings(name)+ .await+ .map_err(Into::into)?;+ if counts.total >= MAX_OPEN_PAIRINGS || counts.with_same_name >= MAX_OPEN_PAIRINGS_PER_NAME+ {+ return Err(HarnessError::Throttled);+ }++ let device_secret = tokens::generate_device_secret();+ let device_secret_hash = harness_token::hash_token(&device_secret);+ let expires_at = Utc::now() + Duration::minutes(PAIRING_TTL_MINUTES);+ let pairing_id = Uuid::new_v4();++ for _ in 0..CODE_ATTEMPTS {+ let code = tokens::generate_pairing_code();+ let inserted = self+ .repo+ .insert_pairing(NewPairing {+ id: pairing_id,+ code: code.clone(),+ device_secret_hash,+ requested_name: name.to_owned(),+ host: host.clone(),+ requested_scope: req.scope,+ expires_at,+ })+ .await+ .map_err(Into::into)?;+ if inserted {+ return Ok(CreatedPairing {+ pairing_id,+ code,+ device_secret,+ expires_at,+ poll_interval_seconds: POLL_INTERVAL_SECONDS,+ });+ }+ }++ Err(HarnessError::Repo(anyhow::anyhow!(+ "could not find an unused pairing code"+ )))+ }++ #[tracing::instrument(skip(self), err)]+ async fn get_pairing(&self, code: &str) -> Result<PairingDetails, HarnessError> {+ let code = tokens::normalize_pairing_code(code)+ .ok_or_else(|| HarnessError::BadRequest("malformed pairing code".to_owned()))?;+ let pairing = self+ .repo+ .get_pairing(&code)+ .await+ .map_err(Into::into)?+ .ok_or_else(|| HarnessError::NotFound("unknown pairing code".to_owned()))?;++ if pairing.status != PairingStatus::Pending {+ return Err(HarnessError::Gone(+ "this pairing was already approved".to_owned(),+ ));+ }+ if pairing.details.expires_at <= Utc::now() {+ return Err(HarnessError::Gone("this pairing expired".to_owned()));+ }++ Ok(pairing.details)+ }++ #[tracing::instrument(skip(self, req), fields(caller = %caller), err)]+ async fn approve_pairing(+ &self,+ caller: MacroUserIdStr<'static>,+ code: &str,+ req: ApprovePairingRequest,+ ) -> Result<Harness, HarnessError> {+ // Reuses the pending/expired policy so approval failures report the+ // same way the lookup does.+ let details = self.get_pairing(code).await?;+ let code = tokens::normalize_pairing_code(code).expect("get_pairing validated the code");++ let name = match &req.name {+ Some(name) => {+ let name = name.trim();+ if name.is_empty() || name.chars().count() > MAX_NAME_CHARS {+ return Err(HarnessError::BadRequest(format!(+ "name must be 1..={MAX_NAME_CHARS} characters"+ )));+ }+ name.to_owned()+ }+ None => details.requested_name,+ };++ // Any current member may register a team harness, mirroring team+ // agents: harnesses exist to serve agents teammates create.+ let owner = match req.team_id {+ Some(team_id) => {+ let is_member = self+ .repo+ .user_has_team(caller.clone(), team_id)+ .await+ .map_err(Into::into)?;+ if !is_member {+ return Err(HarnessError::Unauthorized);+ }+ HarnessOwner::Team { team_id }+ }+ None => HarnessOwner::User {+ user_id: caller.as_ref().to_owned(),+ },+ };++ self.repo+ .approve_pairing(+ &code,+ NewHarness {+ id: HarnessId::new_from_uuid(Uuid::new_v4()),+ name,+ owner,+ created_by: caller,+ },+ )+ .await+ .map_err(Into::into)?+ .ok_or_else(|| HarnessError::Gone("this pairing is no longer pending".to_owned()))+ }++ #[tracing::instrument(skip(self, req), err)]+ async fn claim_pairing(+ &self,+ pairing_id: Uuid,+ req: ClaimPairingRequest,+ ) -> Result<ClaimOutcome, HarnessError> {+ let facts = self+ .repo+ .pairing_claim_facts(pairing_id)+ .await+ .map_err(Into::into)?+ .ok_or_else(|| HarnessError::NotFound("unknown pairing".to_owned()))?;++ let presented = harness_token::hash_token(&req.device_secret);+ if !constant_time_eq(&presented, &facts.device_secret_hash) {+ return Err(HarnessError::Unauthorized);+ }++ match facts.status {+ PairingStatus::Claimed => {+ return Err(HarnessError::Gone(+ "this pairing's credential was already claimed".to_owned(),+ ));+ }+ PairingStatus::Pending if facts.expires_at <= Utc::now() => {+ return Err(HarnessError::Gone("this pairing expired".to_owned()));+ }+ PairingStatus::Pending => return Ok(ClaimOutcome::Pending),+ // An approved pairing stays claimable past its expiry: the user+ // already said yes, and the daemon polling a few minutes late+ // should not force a re-pair.+ PairingStatus::Approved => {}+ }++ let token = tokens::generate_harness_token();+ let harness = self+ .repo+ .claim_pairing(+ pairing_id,+ Uuid::new_v4(),+ HashedHarnessToken::from_raw(&token),+ )+ .await+ .map_err(Into::into)?+ .ok_or_else(|| {+ HarnessError::Gone("this pairing's credential was already claimed".to_owned())+ })?;++ Ok(ClaimOutcome::Claimed(ClaimedPairing { harness, token }))+ }++ #[tracing::instrument(skip(self), fields(caller = %caller), err)]+ async fn list_harnesses(+ &self,+ caller: MacroUserIdStr<'static>,+ ) -> Result<Vec<Harness>, HarnessError> {+ Ok(self+ .repo+ .list_visible_harnesses(caller)+ .await+ .map_err(Into::into)?)+ }++ #[tracing::instrument(skip(self), fields(caller = %caller), err)]+ async fn delete_harness(+ &self,+ caller: MacroUserIdStr<'static>,+ harness_id: HarnessId,+ ) -> Result<(), HarnessError> {+ let harness = self+ .repo+ .get_harness(harness_id)+ .await+ .map_err(Into::into)?+ .ok_or_else(|| HarnessError::NotFound("unknown harness".to_owned()))?;++ self.ensure_may_manage(&caller, &harness).await?;++ if !self+ .repo+ .delete_harness(harness_id)+ .await+ .map_err(Into::into)?+ {+ return Err(HarnessError::NotFound("unknown harness".to_owned()));+ }+ Ok(())+ }++ #[tracing::instrument(skip(self), err)]+ async fn list_bound_agents(+ &self,+ harness_id: HarnessId,+ ) -> Result<Vec<HarnessAgent>, HarnessError> {+ Ok(self+ .repo+ .list_bound_agents(harness_id)+ .await+ .map_err(Into::into)?)+ }+}diff --git a/crates/harnesses/src/domain/service/test.rs b/crates/harnesses/src/domain/service/test.rsnew file mode 100644index 0000000000..2c1b980c09--- /dev/null+++ b/crates/harnesses/src/domain/service/test.rs@@ -0,0 +1,576 @@+use std::sync::{Arc, Mutex};++use chrono::Duration;+use macro_user_id::user_id::MacroUserIdStr;++use super::*;+use crate::domain::{+ models::{PairingClaimFacts, RequestedHarnessScope},+ ports::{OpenPairingCounts, PairingRow},+};++const OWNER_ID: &str = "macro|[email protected]";+const MEMBER_ID: &str = "macro|[email protected]";+const CODE: &str = "KX7M-4QHD";+const TEAM_ID: Uuid = Uuid::from_u128(7);++fn caller(id: &str) -> MacroUserIdStr<'static> {+ MacroUserIdStr::try_from(id.to_string()).unwrap()+}++fn harness(owner: HarnessOwner) -> Harness {+ Harness {+ id: HarnessId::TEST_A,+ kind: "macrod".to_owned(),+ name: "erics-macbook".to_owned(),+ owner,+ created_by: OWNER_ID.to_owned(),+ created_at: Utc::now(),+ updated_at: Utc::now(),+ connected: false,+ last_connected_at: None,+ }+}++fn pending_pairing() -> PairingRow {+ PairingRow {+ details: PairingDetails {+ code: CODE.to_owned(),+ requested_name: "erics-macbook".to_owned(),+ host: Some("eric@macbook / darwin".to_owned()),+ requested_scope: Some(RequestedHarnessScope::Team),+ created_at: Utc::now(),+ expires_at: Utc::now() + Duration::minutes(10),+ },+ status: PairingStatus::Pending,+ }+}++#[derive(Debug, Default)]+struct Calls {+ inserted_pairings: Vec<NewPairing>,+ approved: Vec<(String, NewHarness)>,+ claimed: Vec<Uuid>,+ deleted: Vec<HarnessId>,+ team_lookups: Vec<(String, Uuid)>,+}++#[derive(Clone, Default)]+struct FakeRepo {+ open_counts: OpenPairingCountsConfig,+ insert_conflicts: usize,+ pairing: Option<PairingRow>,+ claim_facts: Option<PairingClaimFacts>,+ approve_result: Option<Harness>,+ claim_result: Option<Harness>,+ harness: Option<Harness>,+ delete_result: bool,+ user_has_team: bool,+ user_owns_team: bool,+ calls: Arc<Mutex<Calls>>,+}++#[derive(Clone, Copy, Debug, Default)]+struct OpenPairingCountsConfig {+ total: i64,+ with_same_name: i64,+}++impl HarnessRepo for FakeRepo {+ type Err = anyhow::Error;++ async fn insert_pairing(&self, pairing: NewPairing) -> Result<bool, Self::Err> {+ let mut calls = self.calls.lock().unwrap();+ calls.inserted_pairings.push(pairing);+ Ok(calls.inserted_pairings.len() > self.insert_conflicts)+ }++ async fn delete_expired_pairings(&self) -> Result<(), Self::Err> {+ Ok(())+ }++ async fn count_open_pairings(&self, _name: &str) -> Result<OpenPairingCounts, Self::Err> {+ Ok(OpenPairingCounts {+ total: self.open_counts.total,+ with_same_name: self.open_counts.with_same_name,+ })+ }++ async fn get_pairing(&self, _code: &str) -> Result<Option<PairingRow>, Self::Err> {+ Ok(self.pairing.clone())+ }++ async fn approve_pairing(+ &self,+ code: &str,+ harness: NewHarness,+ ) -> Result<Option<Harness>, Self::Err> {+ self.calls+ .lock()+ .unwrap()+ .approved+ .push((code.to_owned(), harness));+ Ok(self.approve_result.clone())+ }++ async fn pairing_claim_facts(+ &self,+ _pairing_id: Uuid,+ ) -> Result<Option<PairingClaimFacts>, Self::Err> {+ Ok(self.claim_facts.clone())+ }++ async fn claim_pairing(+ &self,+ pairing_id: Uuid,+ _token_id: Uuid,+ _token: HashedHarnessToken,+ ) -> Result<Option<Harness>, Self::Err> {+ self.calls.lock().unwrap().claimed.push(pairing_id);+ Ok(self.claim_result.clone())+ }++ async fn list_visible_harnesses(+ &self,+ _caller: MacroUserIdStr<'static>,+ ) -> Result<Vec<Harness>, Self::Err> {+ Ok(self.harness.clone().into_iter().collect())+ }++ async fn get_harness(&self, _harness_id: HarnessId) -> Result<Option<Harness>, Self::Err> {+ Ok(self.harness.clone())+ }++ async fn delete_harness(&self, harness_id: HarnessId) -> Result<bool, Self::Err> {+ self.calls.lock().unwrap().deleted.push(harness_id);+ Ok(self.delete_result)+ }++ async fn user_has_team(+ &self,+ caller: MacroUserIdStr<'static>,+ team_id: Uuid,+ ) -> Result<bool, Self::Err> {+ self.calls+ .lock()+ .unwrap()+ .team_lookups+ .push((caller.as_ref().to_owned(), team_id));+ Ok(self.user_has_team)+ }++ async fn user_owns_team(+ &self,+ _caller: MacroUserIdStr<'static>,+ _team_id: Uuid,+ ) -> Result<bool, Self::Err> {+ Ok(self.user_owns_team)+ }++ async fn list_bound_agents(+ &self,+ _harness_id: HarnessId,+ ) -> Result<Vec<HarnessAgent>, Self::Err> {+ Ok(Vec::new())+ }+}++fn service(repo: FakeRepo) -> HarnessServiceImpl<FakeRepo> {+ HarnessServiceImpl::new(repo)+}++#[tokio::test]+async fn creating_a_pairing_returns_code_and_secret_and_persists_only_hashes() {+ let repo = FakeRepo::default();+ let created = service(repo.clone())+ .create_pairing(CreatePairingRequest {+ name: " erics-macbook ".to_owned(),+ host: Some("eric@macbook".to_owned()),+ scope: Some(RequestedHarnessScope::Team),+ })+ .await+ .unwrap();++ assert_eq!(created.code.len(), 9);+ assert!(!created.device_secret.is_empty());+ assert!(created.expires_at > Utc::now());++ let calls = repo.calls.lock().unwrap();+ let inserted = &calls.inserted_pairings[0];+ assert_eq!(inserted.requested_name, "erics-macbook");+ assert_eq!(inserted.requested_scope, Some(RequestedHarnessScope::Team));+ assert_eq!(inserted.code, created.code);+ assert_eq!(+ inserted.device_secret_hash,+ harness_token::hash_token(&created.device_secret)+ );+}++#[tokio::test]+async fn pairing_creation_retries_code_collisions() {+ let repo = FakeRepo {+ insert_conflicts: 2,+ ..FakeRepo::default()+ };+ let created = service(repo.clone())+ .create_pairing(CreatePairingRequest {+ name: "erics-macbook".to_owned(),+ host: None,+ scope: None,+ })+ .await+ .unwrap();++ let calls = repo.calls.lock().unwrap();+ assert_eq!(calls.inserted_pairings.len(), 3);+ assert_eq!(calls.inserted_pairings[2].code, created.code);+}++#[tokio::test]+async fn pairing_creation_is_throttled_and_validates_the_name() {+ let throttled = FakeRepo {+ open_counts: OpenPairingCountsConfig {+ total: MAX_OPEN_PAIRINGS,+ with_same_name: 0,+ },+ ..FakeRepo::default()+ };+ let result = service(throttled)+ .create_pairing(CreatePairingRequest {+ name: "erics-macbook".to_owned(),+ host: None,+ scope: None,+ })+ .await;+ assert!(matches!(result, Err(HarnessError::Throttled)));++ let result = service(FakeRepo::default())+ .create_pairing(CreatePairingRequest {+ name: " ".to_owned(),+ host: None,+ scope: None,+ })+ .await;+ assert!(matches!(result, Err(HarnessError::BadRequest(_))));+}++#[tokio::test]+async fn pairing_lookup_normalizes_codes_and_reports_state() {+ let repo = FakeRepo {+ pairing: Some(pending_pairing()),+ ..FakeRepo::default()+ };+ let details = service(repo).get_pairing("kx7m 4qhd").await.unwrap();+ assert_eq!(details.requested_name, "erics-macbook");++ let missing = service(FakeRepo::default()).get_pairing(CODE).await;+ assert!(matches!(missing, Err(HarnessError::NotFound(_))));++ let mut expired = pending_pairing();+ expired.details.expires_at = Utc::now() - Duration::minutes(1);+ let repo = FakeRepo {+ pairing: Some(expired),+ ..FakeRepo::default()+ };+ assert!(matches!(+ service(repo).get_pairing(CODE).await,+ Err(HarnessError::Gone(_))+ ));++ let mut approved = pending_pairing();+ approved.status = PairingStatus::Approved;+ let repo = FakeRepo {+ pairing: Some(approved),+ ..FakeRepo::default()+ };+ assert!(matches!(+ service(repo).get_pairing(CODE).await,+ Err(HarnessError::Gone(_))+ ));++ assert!(matches!(+ service(FakeRepo::default()).get_pairing("nope").await,+ Err(HarnessError::BadRequest(_))+ ));+}++#[tokio::test]+async fn approval_registers_a_private_harness_for_the_caller() {+ let repo = FakeRepo {+ pairing: Some(pending_pairing()),+ approve_result: Some(harness(HarnessOwner::User {+ user_id: OWNER_ID.to_owned(),+ })),+ ..FakeRepo::default()+ };+ let approved = service(repo.clone())+ .approve_pairing(+ caller(OWNER_ID),+ "kx7m4qhd",+ ApprovePairingRequest {+ name: None,+ team_id: None,+ },+ )+ .await+ .unwrap();+ assert_eq!(approved.name, "erics-macbook");++ let calls = repo.calls.lock().unwrap();+ let (code, new_harness) = &calls.approved[0];+ assert_eq!(code, CODE);+ assert_eq!(new_harness.name, "erics-macbook");+ assert_eq!(+ new_harness.owner,+ HarnessOwner::User {+ user_id: OWNER_ID.to_owned()+ }+ );+ assert_eq!(new_harness.created_by.as_ref(), OWNER_ID);+ assert!(calls.team_lookups.is_empty());+}++#[tokio::test]+async fn team_approval_requires_membership_and_honors_the_name_override() {+ let repo = FakeRepo {+ pairing: Some(pending_pairing()),+ approve_result: Some(harness(HarnessOwner::Team { team_id: TEAM_ID })),+ user_has_team: true,+ ..FakeRepo::default()+ };+ service(repo.clone())+ .approve_pairing(+ caller(MEMBER_ID),+ CODE,+ ApprovePairingRequest {+ name: Some("team box".to_owned()),+ team_id: Some(TEAM_ID),+ },+ )+ .await+ .unwrap();++ let calls = repo.calls.lock().unwrap();+ let (_, new_harness) = &calls.approved[0];+ assert_eq!(new_harness.name, "team box");+ assert_eq!(new_harness.owner, HarnessOwner::Team { team_id: TEAM_ID });+ assert_eq!(calls.team_lookups[0], (MEMBER_ID.to_owned(), TEAM_ID));++ let repo = FakeRepo {+ pairing: Some(pending_pairing()),+ user_has_team: false,+ ..FakeRepo::default()+ };+ let result = service(repo)+ .approve_pairing(+ caller(MEMBER_ID),+ CODE,+ ApprovePairingRequest {+ name: None,+ team_id: Some(TEAM_ID),+ },+ )+ .await;+ assert!(matches!(result, Err(HarnessError::Unauthorized)));+}++#[tokio::test]+async fn approval_race_reports_gone() {+ let repo = FakeRepo {+ pairing: Some(pending_pairing()),+ approve_result: None,+ ..FakeRepo::default()+ };+ let result = service(repo)+ .approve_pairing(+ caller(OWNER_ID),+ CODE,+ ApprovePairingRequest {+ name: None,+ team_id: None,+ },+ )+ .await;+ assert!(matches!(result, Err(HarnessError::Gone(_))));+}++fn claim_facts(status: PairingStatus, secret: &str) -> PairingClaimFacts {+ PairingClaimFacts {+ device_secret_hash: harness_token::hash_token(secret),+ status,+ expires_at: Utc::now() + Duration::minutes(10),+ harness_id: Some(HarnessId::TEST_A),+ }+}++#[tokio::test]+async fn claim_verifies_the_secret_then_walks_pending_to_claimed() {+ let secret = "device-secret";+ let pairing_id = Uuid::new_v4();++ let repo = FakeRepo {+ claim_facts: Some(claim_facts(PairingStatus::Pending, secret)),+ ..FakeRepo::default()+ };+ let outcome = service(repo)+ .claim_pairing(+ pairing_id,+ ClaimPairingRequest {+ device_secret: secret.to_owned(),+ },+ )+ .await+ .unwrap();+ assert!(matches!(outcome, ClaimOutcome::Pending));++ let repo = FakeRepo {+ claim_facts: Some(claim_facts(PairingStatus::Approved, secret)),+ claim_result: Some(harness(HarnessOwner::User {+ user_id: OWNER_ID.to_owned(),+ })),+ ..FakeRepo::default()+ };+ let outcome = service(repo.clone())+ .claim_pairing(+ pairing_id,+ ClaimPairingRequest {+ device_secret: secret.to_owned(),+ },+ )+ .await+ .unwrap();+ let ClaimOutcome::Claimed(claimed) = outcome else {+ panic!("expected a claimed outcome");+ };+ assert!(claimed.token.starts_with("mhns_"));+ assert_eq!(repo.calls.lock().unwrap().claimed, [pairing_id]);+}++#[tokio::test]+async fn claim_rejects_bad_secrets_and_dead_pairings() {+ let secret = "device-secret";+ let pairing_id = Uuid::new_v4();++ let repo = FakeRepo {+ claim_facts: Some(claim_facts(PairingStatus::Approved, secret)),+ ..FakeRepo::default()+ };+ let result = service(repo)+ .claim_pairing(+ pairing_id,+ ClaimPairingRequest {+ device_secret: "wrong".to_owned(),+ },+ )+ .await;+ assert!(matches!(result, Err(HarnessError::Unauthorized)));++ let repo = FakeRepo {+ claim_facts: Some(claim_facts(PairingStatus::Claimed, secret)),+ ..FakeRepo::default()+ };+ let result = service(repo)+ .claim_pairing(+ pairing_id,+ ClaimPairingRequest {+ device_secret: secret.to_owned(),+ },+ )+ .await;+ assert!(matches!(result, Err(HarnessError::Gone(_))));++ let mut expired = claim_facts(PairingStatus::Pending, secret);+ expired.expires_at = Utc::now() - Duration::minutes(1);+ let repo = FakeRepo {+ claim_facts: Some(expired),+ ..FakeRepo::default()+ };+ let result = service(repo)+ .claim_pairing(+ pairing_id,+ ClaimPairingRequest {+ device_secret: secret.to_owned(),+ },+ )+ .await;+ assert!(matches!(result, Err(HarnessError::Gone(_))));++ let result = service(FakeRepo::default())+ .claim_pairing(+ pairing_id,+ ClaimPairingRequest {+ device_secret: secret.to_owned(),+ },+ )+ .await;+ assert!(matches!(result, Err(HarnessError::NotFound(_))));+}++#[tokio::test]+async fn private_harnesses_are_deletable_only_by_their_owner() {+ let repo = FakeRepo {+ harness: Some(harness(HarnessOwner::User {+ user_id: OWNER_ID.to_owned(),+ })),+ delete_result: true,+ ..FakeRepo::default()+ };+ service(repo.clone())+ .delete_harness(caller(OWNER_ID), HarnessId::TEST_A)+ .await+ .unwrap();+ assert_eq!(repo.calls.lock().unwrap().deleted, [HarnessId::TEST_A]);++ let repo = FakeRepo {+ harness: Some(harness(HarnessOwner::User {+ user_id: OWNER_ID.to_owned(),+ })),+ ..FakeRepo::default()+ };+ let result = service(repo)+ .delete_harness(caller(MEMBER_ID), HarnessId::TEST_A)+ .await;+ assert!(matches!(result, Err(HarnessError::Unauthorized)));+}++#[tokio::test]+async fn team_harnesses_are_deletable_by_their_registrant_or_the_team_owner() {+ // The registrant.+ let repo = FakeRepo {+ harness: Some(harness(HarnessOwner::Team { team_id: TEAM_ID })),+ delete_result: true,+ ..FakeRepo::default()+ };+ service(repo)+ .delete_harness(caller(OWNER_ID), HarnessId::TEST_A)+ .await+ .unwrap();++ // The team owner.+ let repo = FakeRepo {+ harness: Some(harness(HarnessOwner::Team { team_id: TEAM_ID })),+ delete_result: true,+ user_owns_team: true,+ ..FakeRepo::default()+ };+ service(repo)+ .delete_harness(caller(MEMBER_ID), HarnessId::TEST_A)+ .await+ .unwrap();++ // A plain member who did not register it.+ let repo = FakeRepo {+ harness: Some(harness(HarnessOwner::Team { team_id: TEAM_ID })),+ user_has_team: true,+ ..FakeRepo::default()+ };+ let result = service(repo)+ .delete_harness(caller(MEMBER_ID), HarnessId::TEST_A)+ .await;+ assert!(matches!(result, Err(HarnessError::Unauthorized)));++ let result = service(FakeRepo::default())+ .delete_harness(caller(OWNER_ID), HarnessId::TEST_A)+ .await;+ assert!(matches!(result, Err(HarnessError::NotFound(_))));+}diff --git a/crates/harnesses/src/domain/tokens.rs b/crates/harnesses/src/domain/tokens.rsnew file mode 100644index 0000000000..44f5f1d05a--- /dev/null+++ b/crates/harnesses/src/domain/tokens.rs@@ -0,0 +1,130 @@+//! Pairing code, device secret, and harness token generation.++use rand::{Rng, RngCore};++/// Unambiguous, uppercase pairing-code alphabet (no `0/O`, `1/I/L`, `U/V`).+const CODE_ALPHABET: &[u8] = b"23456789ABCDEFGHJKMNPQRSTWXYZ";+/// Pairing-code length, excluding the display hyphen.+const CODE_CHARS: usize = 8;+const TOKEN_SECRET_BYTES: usize = 32;+const TOKEN_PREFIX_BYTES: usize = 6;+const DEVICE_SECRET_BYTES: usize = 32;++/// Generate a pairing code, rendered `XXXX-XXXX`.+pub fn generate_pairing_code() -> String {+ let mut rng = rand::rng();+ let mut code = String::with_capacity(CODE_CHARS + 1);+ for index in 0..CODE_CHARS {+ if index == CODE_CHARS / 2 {+ code.push('-');+ }+ let symbol = CODE_ALPHABET[rng.random_range(0..CODE_ALPHABET.len())];+ code.push(symbol as char);+ }+ code+}++/// Normalize user input to the stored pairing-code form, `XXXX-XXXX`.+///+/// Uppercases and strips separators so `kx7m 4qhd` and `KX7M-4QHD` both+/// resolve. Returns `None` when the residue is not exactly the code length.+pub fn normalize_pairing_code(input: &str) -> Option<String> {+ let symbols: Vec<char> = input+ .chars()+ .filter(|symbol| !symbol.is_whitespace() && *symbol != '-')+ .map(|symbol| symbol.to_ascii_uppercase())+ .collect();+ if symbols.len() != CODE_CHARS {+ return None;+ }++ let mut code = String::with_capacity(CODE_CHARS + 1);+ for (index, symbol) in symbols.into_iter().enumerate() {+ if index == CODE_CHARS / 2 {+ code.push('-');+ }+ code.push(symbol);+ }+ Some(code)+}++/// Generate an `mhns_<prefix>_<secret>` harness bearer token.+pub fn generate_harness_token() -> String {+ let mut secret = [0_u8; TOKEN_SECRET_BYTES];+ rand::rng().fill_bytes(&mut secret);+ let secret_hex = hex::encode(secret);+ let prefix = &secret_hex[..TOKEN_PREFIX_BYTES * 2];++ format!("mhns_{prefix}_{secret_hex}")+}++/// Generate the claim credential the daemon keeps between create and claim.+pub fn generate_device_secret() -> String {+ let mut secret = [0_u8; DEVICE_SECRET_BYTES];+ rand::rng().fill_bytes(&mut secret);+ hex::encode(secret)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn pairing_code_has_expected_shape() {+ let code = generate_pairing_code();+ assert_eq!(code.len(), CODE_CHARS + 1);+ assert_eq!(code.as_bytes()[CODE_CHARS / 2], b'-');+ assert!(+ code.chars()+ .filter(|symbol| *symbol != '-')+ .all(|symbol| CODE_ALPHABET.contains(&(symbol as u8)))+ );+ }++ #[test]+ fn normalization_accepts_messy_input_and_rejects_wrong_lengths() {+ assert_eq!(+ normalize_pairing_code("kx7m 4qhd").as_deref(),+ Some("KX7M-4QHD")+ );+ assert_eq!(+ normalize_pairing_code("KX7M-4QHD").as_deref(),+ Some("KX7M-4QHD")+ );+ assert_eq!(+ normalize_pairing_code("kx7m4qhd").as_deref(),+ Some("KX7M-4QHD")+ );+ assert!(normalize_pairing_code("short").is_none());+ assert!(normalize_pairing_code("way-too-long-code").is_none());+ }++ #[test]+ fn generated_codes_round_trip_through_normalization() {+ let code = generate_pairing_code();+ assert_eq!(normalize_pairing_code(&code).as_deref(), Some(&*code));+ }++ #[test]+ fn harness_token_has_expected_shape() {+ let token = generate_harness_token();+ let parts: Vec<_> = token.split('_').collect();+ assert_eq!(parts.len(), 3);+ assert_eq!(parts[0], "mhns");+ assert_eq!(parts[1].len(), TOKEN_PREFIX_BYTES * 2);+ assert_eq!(parts[2].len(), TOKEN_SECRET_BYTES * 2);+ assert!(parts[2].starts_with(parts[1]));+ assert_eq!(+ harness_token::token_prefix(&token),+ format!("mhns_{}", parts[1])+ );+ }++ #[test]+ fn device_secrets_are_long_and_unique() {+ let first = generate_device_secret();+ let second = generate_device_secret();+ assert_eq!(first.len(), DEVICE_SECRET_BYTES * 2);+ assert_ne!(first, second);+ }+}diff --git a/crates/harnesses/src/inbound/axum_router.rs b/crates/harnesses/src/inbound/axum_router.rsnew file mode 100644index 0000000000..3b77b42f35--- /dev/null+++ b/crates/harnesses/src/inbound/axum_router.rs@@ -0,0 +1,348 @@+//! Axum router for harness registration and device-code pairing.++use std::sync::Arc;++use axum::{+ Json, Router,+ extract::{FromRef, Path, State},+ http::StatusCode,+ response::{IntoResponse, Response},+ routing::{delete, get, post},+};+use harness_id::HarnessId;+use macro_authorization::{+ HarnessOnly, MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState,+ UserOrInternal,+};+use model_error_response::ErrorResponse;+use serde::Serialize;+use uuid::Uuid;++use crate::domain::{+ models::{+ ApprovePairingRequest, ClaimOutcome, ClaimPairingRequest, ClaimedPairing,+ CreatePairingRequest, CreatedPairing, Harness, HarnessAgent, PairingDetails,+ },+ ports::{HarnessError, HarnessService},+};++/// State for the harnesses router.+pub struct HarnessesRouterState<S, Auth> {+ service: Arc<S>,+ authorization_state: MacroAuthorizationState<Auth>,+}++impl<S, Auth> Clone for HarnessesRouterState<S, Auth> {+ fn clone(&self) -> Self {+ Self {+ service: self.service.clone(),+ authorization_state: self.authorization_state.clone(),+ }+ }+}++impl<S: HarnessService, Auth> HarnessesRouterState<S, Auth> {+ /// Create a router state.+ pub fn new(service: S, authorization_state: MacroAuthorizationState<Auth>) -> Self {+ Self {+ service: Arc::new(service),+ authorization_state,+ }+ }+}++impl<S, Auth> FromRef<HarnessesRouterState<S, Auth>> for MacroAuthorizationState<Auth> {+ fn from_ref(state: &HarnessesRouterState<S, Auth>) -> Self {+ state.authorization_state.clone()+ }+}++/// Pairing code path.+#[derive(Debug, serde::Deserialize)]+pub struct PairingCodePath {+ /// Pairing code as the user typed it.+ pub code: String,+}++/// Pairing id path.+#[derive(Debug, serde::Deserialize)]+pub struct PairingIdPath {+ /// Pairing id.+ pub pairing_id: Uuid,+}++/// Harness path.+#[derive(Debug, serde::Deserialize)]+pub struct HarnessPath {+ /// Harness id.+ pub harness_id: HarnessId,+}++/// Create a harnesses router.+pub fn harnesses_router<S, Auth, T>(state: HarnessesRouterState<S, Auth>) -> Router<T>+where+ S: HarnessService,+ Auth: MacroAuthorizationService,+ T: Send + Sync,+{+ Router::new()+ .route("/harness-pairings", post(create_pairing_handler::<S, Auth>))+ .route(+ "/harness-pairings/{code}",+ get(get_pairing_handler::<S, Auth>),+ )+ .route(+ "/harness-pairings/{code}/approve",+ post(approve_pairing_handler::<S, Auth>),+ )+ .route(+ "/harness-pairings/{pairing_id}/claim",+ post(claim_pairing_handler::<S, Auth>),+ )+ .route("/harnesses", get(list_harnesses_handler::<S, Auth>))+ .route(+ "/harnesses/me/agents",+ get(list_bound_agents_handler::<S, Auth>),+ )+ .route(+ "/harnesses/{harness_id}",+ delete(delete_harness_handler::<S, Auth>),+ )+ .with_state(state)+}++/// Body returned while a claim is still waiting for approval.+#[derive(Debug, Serialize, utoipa::ToSchema)]+pub struct PendingClaimResponse {+ /// Always `pending`.+ pub status: &'static str,+}++/// Handler for `POST /harness-pairings`.+///+/// Unauthenticated by design: the daemon has no credential yet - obtaining one+/// is the point. The pairing releases nothing until a signed-in user approves+/// it, and creation is throttled in the domain service.+#[utoipa::path(+ post,+ tag = "harnesses",+ operation_id = "create_harness_pairing",+ path = "/harness-pairings",+ request_body = CreatePairingRequest,+ responses(+ (status = 201, body = CreatedPairing),+ (status = 400, body = ErrorResponse),+ (status = 429, body = ErrorResponse),+ (status = 500, body = ErrorResponse),+ )+)]+pub async fn create_pairing_handler<S: HarnessService, Auth: MacroAuthorizationService>(+ State(state): State<HarnessesRouterState<S, Auth>>,+ Json(req): Json<CreatePairingRequest>,+) -> Result<(StatusCode, Json<CreatedPairing>), HarnessesHandlerErr> {+ let pairing = state.service.create_pairing(req).await?;+ Ok((StatusCode::CREATED, Json(pairing)))+}++/// Handler for `GET /harness-pairings/{code}`.+#[utoipa::path(+ get,+ tag = "harnesses",+ operation_id = "get_harness_pairing",+ path = "/harness-pairings/{code}",+ params(("code" = String, Path, description = "Pairing code")),+ responses(+ (status = 200, body = PairingDetails),+ (status = 400, body = ErrorResponse),+ (status = 401, body = ErrorResponse),+ (status = 404, body = ErrorResponse),+ (status = 410, body = ErrorResponse),+ (status = 500, body = ErrorResponse),+ )+)]+pub async fn get_pairing_handler<S: HarnessService, Auth: MacroAuthorizationService>(+ State(state): State<HarnessesRouterState<S, Auth>>,+ _authorization: MacroAuthorizationExtractor<Auth, UserOrInternal>,+ Path(path): Path<PairingCodePath>,+) -> Result<Json<PairingDetails>, HarnessesHandlerErr> {+ Ok(Json(state.service.get_pairing(&path.code).await?))+}++/// Handler for `POST /harness-pairings/{code}/approve`.+#[utoipa::path(+ post,+ tag = "harnesses",+ operation_id = "approve_harness_pairing",+ path = "/harness-pairings/{code}/approve",+ params(("code" = String, Path, description = "Pairing code")),+ request_body = ApprovePairingRequest,+ responses(+ (status = 200, body = Harness),+ (status = 400, body = ErrorResponse),+ (status = 401, body = ErrorResponse),+ (status = 404, body = ErrorResponse),+ (status = 410, body = ErrorResponse),+ (status = 500, body = ErrorResponse),+ )+)]+pub async fn approve_pairing_handler<S: HarnessService, Auth: MacroAuthorizationService>(+ State(state): State<HarnessesRouterState<S, Auth>>,+ authorization: MacroAuthorizationExtractor<Auth, UserOrInternal>,+ Path(path): Path<PairingCodePath>,+ Json(req): Json<ApprovePairingRequest>,+) -> Result<Json<Harness>, HarnessesHandlerErr> {+ let harness = state+ .service+ .approve_pairing(+ authorization.authorization.user.macro_user_id,+ &path.code,+ req,+ )+ .await?;+ Ok(Json(harness))+}++/// Handler for `POST /harness-pairings/{pairing_id}/claim`.+///+/// Unauthenticated like pairing creation; the device secret minted alongside+/// the pairing is the credential, and the pairing id (not the short user+/// code) addresses it.+#[utoipa::path(+ post,+ tag = "harnesses",+ operation_id = "claim_harness_pairing",+ path = "/harness-pairings/{pairing_id}/claim",+ params(("pairing_id" = Uuid, Path, description = "Pairing ID")),+ request_body = ClaimPairingRequest,+ responses(+ (status = 200, body = ClaimedPairing),+ (status = 202, body = PendingClaimResponse),+ (status = 401, body = ErrorResponse),+ (status = 404, body = ErrorResponse),+ (status = 410, body = ErrorResponse),+ (status = 500, body = ErrorResponse),+ )+)]+pub async fn claim_pairing_handler<S: HarnessService, Auth: MacroAuthorizationService>(+ State(state): State<HarnessesRouterState<S, Auth>>,+ Path(path): Path<PairingIdPath>,+ Json(req): Json<ClaimPairingRequest>,+) -> Result<Response, HarnessesHandlerErr> {+ match state.service.claim_pairing(path.pairing_id, req).await? {+ ClaimOutcome::Pending => Ok((+ StatusCode::ACCEPTED,+ Json(PendingClaimResponse { status: "pending" }),+ )+ .into_response()),+ ClaimOutcome::Claimed(claimed) => Ok(Json(claimed).into_response()),+ }+}++/// Handler for `GET /harnesses`.+#[utoipa::path(+ get,+ tag = "harnesses",+ operation_id = "list_harnesses",+ path = "/harnesses",+ responses(+ (status = 200, body = Vec<Harness>),+ (status = 401, body = ErrorResponse),+ (status = 500, body = ErrorResponse),+ )+)]+pub async fn list_harnesses_handler<S: HarnessService, Auth: MacroAuthorizationService>(+ State(state): State<HarnessesRouterState<S, Auth>>,+ authorization: MacroAuthorizationExtractor<Auth, UserOrInternal>,+) -> Result<Json<Vec<Harness>>, HarnessesHandlerErr> {+ Ok(Json(+ state+ .service+ .list_harnesses(authorization.authorization.user.macro_user_id)+ .await?,+ ))+}++/// Handler for `DELETE /harnesses/{harness_id}`.+#[utoipa::path(+ delete,+ tag = "harnesses",+ operation_id = "delete_harness",+ path = "/harnesses/{harness_id}",+ params(("harness_id" = HarnessId, Path, description = "Harness ID")),+ responses(+ (status = 204),+ (status = 401, body = ErrorResponse),+ (status = 404, body = ErrorResponse),+ (status = 500, body = ErrorResponse),+ )+)]+pub async fn delete_harness_handler<S: HarnessService, Auth: MacroAuthorizationService>(+ State(state): State<HarnessesRouterState<S, Auth>>,+ authorization: MacroAuthorizationExtractor<Auth, UserOrInternal>,+ Path(path): Path<HarnessPath>,+) -> Result<StatusCode, HarnessesHandlerErr> {+ state+ .service+ .delete_harness(+ authorization.authorization.user.macro_user_id,+ path.harness_id,+ )+ .await?;+ Ok(StatusCode::NO_CONTENT)+}++/// Handler for `GET /harnesses/me/agents`.+#[utoipa::path(+ get,+ tag = "harnesses",+ operation_id = "list_harness_agents",+ path = "/harnesses/me/agents",+ responses(+ (status = 200, body = Vec<HarnessAgent>),+ (status = 401, body = ErrorResponse),+ (status = 500, body = ErrorResponse),+ )+)]+pub async fn list_bound_agents_handler<S: HarnessService, Auth: MacroAuthorizationService>(+ State(state): State<HarnessesRouterState<S, Auth>>,+ authorization: MacroAuthorizationExtractor<Auth, HarnessOnly>,+) -> Result<Json<Vec<HarnessAgent>>, HarnessesHandlerErr> {+ Ok(Json(+ state+ .service+ .list_bound_agents(authorization.authorization.harness_id)+ .await?,+ ))+}++/// Harnesses handler error.+#[derive(Debug, thiserror::Error)]+pub enum HarnessesHandlerErr {+ /// Domain error.+ #[error(transparent)]+ Harness(#[from] HarnessError),+}++impl IntoResponse for HarnessesHandlerErr {+ fn into_response(self) -> Response {+ let Self::Harness(error) = &self;+ let status = match error {+ HarnessError::BadRequest(_) => StatusCode::BAD_REQUEST,+ HarnessError::NotFound(_) => StatusCode::NOT_FOUND,+ HarnessError::Gone(_) => StatusCode::GONE,+ HarnessError::Unauthorized => StatusCode::UNAUTHORIZED,+ HarnessError::Throttled => StatusCode::TOO_MANY_REQUESTS,+ HarnessError::Repo(_) => StatusCode::INTERNAL_SERVER_ERROR,+ };+ if status == StatusCode::INTERNAL_SERVER_ERROR {+ tracing::error!(error=?self, "harnesses handler error");+ }+ (+ status,+ Json(ErrorResponse {+ message: self.to_string().into(),+ }),+ )+ .into_response()+ }+}diff --git a/crates/harnesses/src/inbound/mod.rs b/crates/harnesses/src/inbound/mod.rsnew file mode 100644index 0000000000..be2d3e1c6e--- /dev/null+++ b/crates/harnesses/src/inbound/mod.rs@@ -0,0 +1,4 @@+//! Inbound HTTP adapters.++/// Axum router for harness registration and pairing.+pub mod axum_router;diff --git a/crates/harnesses/src/lib.rs b/crates/harnesses/src/lib.rsnew file mode 100644index 0000000000..1763b5085b--- /dev/null+++ b/crates/harnesses/src/lib.rs@@ -0,0 +1,17 @@+#![deny(missing_docs)]+//! User-run agent harness (macrod) registration hex crate.+//!+//! A harness is a daemon a user runs on their own machine to serve agent+//! sessions with a local AI harness. This crate owns the harness registry:+//! device-code pairing (create, approve, claim), the harness list the settings+//! UI renders, revocation, and the bound-agent listing the daemon reconciles+//! its webhook feed from.++/// Domain models, ports, and service.+pub mod domain;+#[cfg(feature = "inbound")]+/// Inbound HTTP adapters.+pub mod inbound;+#[cfg(feature = "outbound")]+/// Postgres adapters.+pub mod outbound;diff --git a/crates/harnesses/src/outbound/mod.rs b/crates/harnesses/src/outbound/mod.rsnew file mode 100644index 0000000000..2b81aca7af--- /dev/null+++ b/crates/harnesses/src/outbound/mod.rs@@ -0,0 +1,4 @@+//! Postgres adapters.++/// Postgres harness repository.+pub mod pg_harness_repo;diff --git a/crates/harnesses/src/outbound/pg_harness_repo.rs b/crates/harnesses/src/outbound/pg_harness_repo.rsnew file mode 100644index 0000000000..f2fcb936a8--- /dev/null+++ b/crates/harnesses/src/outbound/pg_harness_repo.rs@@ -0,0 +1,476 @@+//! Postgres harness repository.++#[cfg(test)]+mod tests;++use anyhow::Context;+use chrono::{DateTime, Utc};+use harness_id::HarnessId;+use harness_token::HashedHarnessToken;+use macro_user_id::user_id::MacroUserIdStr;+use sqlx::PgPool;+use uuid::Uuid;++use crate::domain::{+ models::{+ Harness, HarnessAgent, HarnessOwner, PairingClaimFacts, PairingDetails, PairingStatus,+ RequestedHarnessScope,+ },+ ports::{HarnessRepo, NewHarness, NewPairing, OpenPairingCounts, PairingRow},+};++/// Postgres-backed harness repository.+#[derive(Clone, Debug)]+pub struct PgHarnessRepo {+ pool: PgPool,+}++impl PgHarnessRepo {+ /// Create a repository backed by the supplied pool.+ pub fn new(pool: PgPool) -> Self {+ Self { pool }+ }+}++struct HarnessRow {+ id: Uuid,+ kind: String,+ name: String,+ owner_user_id: Option<String>,+ team_id: Option<Uuid>,+ created_by: String,+ created_at: DateTime<Utc>,+ updated_at: DateTime<Utc>,+ last_connected_at: Option<DateTime<Utc>>,+ last_disconnected_at: Option<DateTime<Utc>>,+}++impl TryFrom<HarnessRow> for Harness {+ type Error = anyhow::Error;++ fn try_from(row: HarnessRow) -> Result<Self, Self::Error> {+ let owner = match (row.owner_user_id, row.team_id) {+ (Some(user_id), None) => HarnessOwner::User { user_id },+ (None, Some(team_id)) => HarnessOwner::Team { team_id },+ _ => anyhow::bail!("harness row violated its owner invariant"),+ };+ let connected = match (row.last_connected_at, row.last_disconnected_at) {+ (Some(connected_at), Some(disconnected_at)) => connected_at > disconnected_at,+ (Some(_), None) => true,+ (None, _) => false,+ };++ Ok(Self {+ id: HarnessId::new_from_uuid(row.id),+ kind: row.kind,+ name: row.name,+ owner,+ created_by: row.created_by,+ created_at: row.created_at,+ updated_at: row.updated_at,+ connected,+ last_connected_at: row.last_connected_at,+ })+ }+}++fn pairing_status(status: &str) -> anyhow::Result<PairingStatus> {+ match status {+ "pending" => Ok(PairingStatus::Pending),+ "approved" => Ok(PairingStatus::Approved),+ "claimed" => Ok(PairingStatus::Claimed),+ other => anyhow::bail!("unknown pairing status: {other}"),+ }+}++async fn fetch_harness(+ executor: impl sqlx::PgExecutor<'_>,+ harness_id: Uuid,+) -> anyhow::Result<Option<Harness>> {+ let row = sqlx::query_as!(+ HarnessRow,+ r#"+ SELECT+ id, kind, name, owner_user_id, team_id, created_by,+ created_at, updated_at, last_connected_at, last_disconnected_at+ FROM harnesses+ WHERE id = $1 AND deleted_at IS NULL+ "#,+ harness_id,+ )+ .fetch_optional(executor)+ .await+ .context("failed to fetch harness")?;++ row.map(Harness::try_from).transpose()+}++impl HarnessRepo for PgHarnessRepo {+ type Err = anyhow::Error;++ async fn insert_pairing(&self, pairing: NewPairing) -> Result<bool, Self::Err> {+ let inserted = sqlx::query!(+ r#"+ INSERT INTO harness_pairing_requests+ (id, code, device_secret_hash, requested_name, host_info, requested_scope,+ expires_at)+ VALUES ($1, $2, $3, $4, $5, $6, $7)+ ON CONFLICT (code) DO NOTHING+ "#,+ pairing.id,+ pairing.code,+ &pairing.device_secret_hash[..],+ pairing.requested_name,+ pairing.host,+ pairing.requested_scope.map(RequestedHarnessScope::as_str),+ pairing.expires_at,+ )+ .execute(&self.pool)+ .await+ .context("failed to insert pairing")?;++ Ok(inserted.rows_affected() == 1)+ }++ async fn delete_expired_pairings(&self) -> Result<(), Self::Err> {+ sqlx::query!(+ r#"+ DELETE FROM harness_pairing_requests+ WHERE expires_at <= now() AND status <> 'approved'+ "#+ )+ .execute(&self.pool)+ .await+ .context("failed to delete expired pairings")?;+ Ok(())+ }++ async fn count_open_pairings(+ &self,+ requested_name: &str,+ ) -> Result<OpenPairingCounts, Self::Err> {+ let row = sqlx::query!(+ r#"+ SELECT+ count(*) AS "total!",+ count(*) FILTER (WHERE requested_name = $1) AS "with_same_name!"+ FROM harness_pairing_requests+ WHERE status = 'pending' AND expires_at > now()+ "#,+ requested_name,+ )+ .fetch_one(&self.pool)+ .await+ .context("failed to count open pairings")?;++ Ok(OpenPairingCounts {+ total: row.total,+ with_same_name: row.with_same_name,+ })+ }++ async fn get_pairing(&self, code: &str) -> Result<Option<PairingRow>, Self::Err> {+ let row = sqlx::query!(+ r#"+ SELECT code, requested_name, host_info, requested_scope, status, created_at,+ expires_at+ FROM harness_pairing_requests+ WHERE code = $1+ "#,+ code,+ )+ .fetch_optional(&self.pool)+ .await+ .context("failed to fetch pairing")?;++ row.map(|row| {+ let requested_scope = row+ .requested_scope+ .as_deref()+ .map(str::parse::<RequestedHarnessScope>)+ .transpose()+ .map_err(anyhow::Error::msg)?;+ Ok(PairingRow {+ details: PairingDetails {+ code: row.code,+ requested_name: row.requested_name,+ host: row.host_info,+ requested_scope,+ created_at: row.created_at,+ expires_at: row.expires_at,+ },+ status: pairing_status(&row.status)?,+ })+ })+ .transpose()+ }++ async fn approve_pairing(+ &self,+ code: &str,+ harness: NewHarness,+ ) -> Result<Option<Harness>, Self::Err> {+ let mut tx = self.pool.begin().await.context("failed to begin tx")?;++ let (owner_user_id, team_id) = match &harness.owner {+ HarnessOwner::User { user_id } => (Some(user_id.as_str()), None),+ HarnessOwner::Team { team_id } => (None, Some(*team_id)),+ };+ sqlx::query!(+ r#"+ INSERT INTO harnesses (id, kind, name, owner_user_id, team_id, created_by)+ VALUES ($1, 'macrod', $2, $3, $4, $5)+ "#,+ harness.id.as_uuid(),+ harness.name,+ owner_user_id,+ team_id,+ harness.created_by.as_ref(),+ )+ .execute(&mut *tx)+ .await+ .context("failed to insert harness")?;++ let approved = sqlx::query!(+ r#"+ UPDATE harness_pairing_requests+ SET status = 'approved', harness_id = $2, approved_by = $3+ WHERE code = $1 AND status = 'pending' AND expires_at > now()+ "#,+ code,+ harness.id.as_uuid(),+ harness.created_by.as_ref(),+ )+ .execute(&mut *tx)+ .await+ .context("failed to approve pairing")?;++ if approved.rows_affected() != 1 {+ // Roll the harness insert back: the pairing raced to another state.+ tx.rollback().await.context("failed to roll back")?;+ return Ok(None);+ }++ let created = fetch_harness(&mut *tx, harness.id.as_uuid())+ .await?+ .context("approved harness row missing")?;+ tx.commit().await.context("failed to commit")?;+ Ok(Some(created))+ }++ async fn pairing_claim_facts(+ &self,+ pairing_id: Uuid,+ ) -> Result<Option<PairingClaimFacts>, Self::Err> {+ let row = sqlx::query!(+ r#"+ SELECT device_secret_hash, status, expires_at, harness_id+ FROM harness_pairing_requests+ WHERE id = $1+ "#,+ pairing_id,+ )+ .fetch_optional(&self.pool)+ .await+ .context("failed to fetch pairing claim facts")?;++ row.map(|row| {+ let device_secret_hash: [u8; 32] = row+ .device_secret_hash+ .try_into()+ .map_err(|_| anyhow::anyhow!("persisted device secret hash is not 32 bytes"))?;+ Ok(PairingClaimFacts {+ device_secret_hash,+ status: pairing_status(&row.status)?,+ expires_at: row.expires_at,+ harness_id: row.harness_id.map(HarnessId::new_from_uuid),+ })+ })+ .transpose()+ }++ async fn claim_pairing(+ &self,+ pairing_id: Uuid,+ token_id: Uuid,+ token: HashedHarnessToken,+ ) -> Result<Option<Harness>, Self::Err> {+ let mut tx = self.pool.begin().await.context("failed to begin tx")?;++ let claimed = sqlx::query_scalar!(+ r#"+ UPDATE harness_pairing_requests+ SET status = 'claimed', claimed_at = now()+ WHERE id = $1 AND status = 'approved'+ RETURNING harness_id AS "harness_id!"+ "#,+ pairing_id,+ )+ .fetch_optional(&mut *tx)+ .await+ .context("failed to claim pairing")?;++ let Some(harness_id) = claimed else {+ tx.rollback().await.context("failed to roll back")?;+ return Ok(None);+ };++ sqlx::query!(+ r#"+ INSERT INTO harness_tokens (id, harness_id, token_hash, token_prefix)+ VALUES ($1, $2, $3, $4)+ "#,+ token_id,+ harness_id,+ &token.hash[..],+ token.prefix,+ )+ .execute(&mut *tx)+ .await+ .context("failed to persist harness token")?;++ let harness = fetch_harness(&mut *tx, harness_id)+ .await?+ .context("claimed harness row missing")?;+ tx.commit().await.context("failed to commit")?;+ Ok(Some(harness))+ }++ async fn list_visible_harnesses(+ &self,+ caller: MacroUserIdStr<'static>,+ ) -> Result<Vec<Harness>, Self::Err> {+ let rows = sqlx::query_as!(+ HarnessRow,+ r#"+ SELECT+ id, kind, name, owner_user_id, team_id, created_by,+ created_at, updated_at, last_connected_at, last_disconnected_at+ FROM harnesses+ WHERE deleted_at IS NULL+ AND (+ owner_user_id = $1+ OR team_id IN (SELECT team_id FROM team_user WHERE user_id = $1)+ )+ ORDER BY created_at DESC+ "#,+ caller.as_ref(),+ )+ .fetch_all(&self.pool)+ .await+ .context("failed to list harnesses")?;++ rows.into_iter().map(Harness::try_from).collect()+ }++ async fn get_harness(&self, harness_id: HarnessId) -> Result<Option<Harness>, Self::Err> {+ fetch_harness(&self.pool, harness_id.as_uuid()).await+ }++ async fn delete_harness(&self, harness_id: HarnessId) -> Result<bool, Self::Err> {+ let mut tx = self.pool.begin().await.context("failed to begin tx")?;++ let deleted = sqlx::query!(+ r#"+ UPDATE harnesses+ SET deleted_at = now(), updated_at = now()+ WHERE id = $1 AND deleted_at IS NULL+ "#,+ harness_id.as_uuid(),+ )+ .execute(&mut *tx)+ .await+ .context("failed to delete harness")?;++ sqlx::query!(+ r#"+ UPDATE harness_tokens+ SET revoked_at = now()+ WHERE harness_id = $1 AND revoked_at IS NULL+ "#,+ harness_id.as_uuid(),+ )+ .execute(&mut *tx)+ .await+ .context("failed to revoke harness tokens")?;++ tx.commit().await.context("failed to commit")?;+ Ok(deleted.rows_affected() == 1)+ }++ async fn user_has_team(+ &self,+ caller: MacroUserIdStr<'static>,+ team_id: Uuid,+ ) -> Result<bool, Self::Err> {+ let has_team = sqlx::query_scalar!(+ r#"+ SELECT EXISTS (+ SELECT 1+ FROM team_user+ WHERE user_id = $1 AND team_id = $2+ ) AS "has_team!"+ "#,+ caller.as_ref(),+ team_id,+ )+ .fetch_one(&self.pool)+ .await+ .context("failed to check team membership")?;+ Ok(has_team)+ }++ async fn user_owns_team(+ &self,+ caller: MacroUserIdStr<'static>,+ team_id: Uuid,+ ) -> Result<bool, Self::Err> {+ let owns_team = sqlx::query_scalar!(+ r#"+ SELECT EXISTS (+ SELECT 1+ FROM team_user+ WHERE user_id = $1+ AND team_id = $2+ AND team_role = 'owner'::team_role+ ) AS "owns_team!"+ "#,+ caller.as_ref(),+ team_id,+ )+ .fetch_one(&self.pool)+ .await+ .context("failed to check team ownership")?;+ Ok(owns_team)+ }++ async fn list_bound_agents(+ &self,+ harness_id: HarnessId,+ ) -> Result<Vec<HarnessAgent>, Self::Err> {+ let rows = sqlx::query!(+ r#"+ SELECT b.id, b.name, b.handle+ FROM agent_configs ac+ JOIN bots b ON b.id = ac.bot_id+ WHERE ac.harness_id = $1+ AND b.deleted_at IS NULL+ AND b.has_agent+ ORDER BY b.created_at+ "#,+ harness_id.as_uuid(),+ )+ .fetch_all(&self.pool)+ .await+ .context("failed to list bound agents")?;++ Ok(rows+ .into_iter()+ .map(|row| HarnessAgent {+ bot_id: bot_id::BotId::new_from_uuid(row.id),+ name: row.name,+ handle: row.handle,+ })+ .collect())+ }+}diff --git a/crates/harnesses/src/outbound/pg_harness_repo/tests.rs b/crates/harnesses/src/outbound/pg_harness_repo/tests.rsnew file mode 100644index 0000000000..8152369376--- /dev/null+++ b/crates/harnesses/src/outbound/pg_harness_repo/tests.rs@@ -0,0 +1,389 @@+use chrono::Duration;+use macro_db_migrator::MACRO_DB_MIGRATIONS;++use super::*;+use crate::domain::tokens;++const OWNER_ID: &str = "macro|[email protected]";++fn caller() -> MacroUserIdStr<'static> {+ MacroUserIdStr::try_from(OWNER_ID.to_string()).unwrap()+}++async fn insert_user(pool: &PgPool, user_id: &str) {+ let email = user_id.split_once('|').map(|(_, email)| email).unwrap();+ let macro_user_id = Uuid::new_v4();+ sqlx::query!(+ r#"+ INSERT INTO macro_user (id, username, email, stripe_customer_id)+ VALUES ($1, $2, $2, $3)+ ON CONFLICT (id) DO NOTHING+ "#,+ macro_user_id,+ email,+ format!("stripe_{macro_user_id}"),+ )+ .execute(pool)+ .await+ .unwrap();+ sqlx::query!(+ r#"+ INSERT INTO "User" (id, email, macro_user_id)+ VALUES ($1, $2, $3)+ ON CONFLICT (id) DO NOTHING+ "#,+ user_id,+ email,+ macro_user_id,+ )+ .execute(pool)+ .await+ .unwrap();+}++fn new_pairing(code: &str, secret: &str) -> NewPairing {+ NewPairing {+ id: Uuid::new_v4(),+ code: code.to_owned(),+ device_secret_hash: harness_token::hash_token(secret),+ requested_name: "erics-macbook".to_owned(),+ host: Some("eric@macbook / darwin".to_owned()),+ requested_scope: Some(RequestedHarnessScope::Team),+ expires_at: Utc::now() + Duration::minutes(15),+ }+}++fn new_harness() -> NewHarness {+ NewHarness {+ id: HarnessId::new_from_uuid(Uuid::new_v4()),+ name: "erics-macbook".to_owned(),+ owner: HarnessOwner::User {+ user_id: OWNER_ID.to_owned(),+ },+ created_by: caller(),+ }+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn pairing_walks_create_approve_claim_exactly_once(pool: PgPool) {+ let repo = PgHarnessRepo::new(pool.clone());+ let pairing = new_pairing("KX7M-4QHD", "secret");+ assert!(repo.insert_pairing(pairing.clone()).await.unwrap());+ // The code is unique while the pairing is open.+ assert!(!repo.insert_pairing(pairing.clone()).await.unwrap());++ let row = repo.get_pairing("KX7M-4QHD").await.unwrap().unwrap();+ assert_eq!(row.status, PairingStatus::Pending);+ assert_eq!(row.details.requested_name, "erics-macbook");+ assert_eq!(+ row.details.requested_scope,+ Some(RequestedHarnessScope::Team)+ );++ let harness = repo+ .approve_pairing("KX7M-4QHD", new_harness())+ .await+ .unwrap()+ .expect("pending pairing approves");+ assert_eq!(harness.name, "erics-macbook");+ assert!(!harness.connected);++ // A second approval races to nothing and leaks no harness row.+ assert!(+ repo.approve_pairing("KX7M-4QHD", new_harness())+ .await+ .unwrap()+ .is_none()+ );+ let harness_count = sqlx::query_scalar!(r#"SELECT count(*) AS "count!" FROM harnesses"#)+ .fetch_one(&pool)+ .await+ .unwrap();+ assert_eq!(harness_count, 1);++ let facts = repo+ .pairing_claim_facts(pairing.id)+ .await+ .unwrap()+ .expect("facts exist");+ assert_eq!(facts.status, PairingStatus::Approved);+ assert_eq!(facts.harness_id, Some(harness.id));+ assert_eq!(+ facts.device_secret_hash,+ harness_token::hash_token("secret")+ );++ let token = tokens::generate_harness_token();+ let claimed = repo+ .claim_pairing(+ pairing.id,+ Uuid::new_v4(),+ HashedHarnessToken::from_raw(&token),+ )+ .await+ .unwrap()+ .expect("approved pairing claims");+ assert_eq!(claimed.id, harness.id);++ // Claiming is single-use.+ assert!(+ repo.claim_pairing(+ pairing.id,+ Uuid::new_v4(),+ HashedHarnessToken::from_raw(&token)+ )+ .await+ .unwrap()+ .is_none()+ );++ let token_count = sqlx::query_scalar!(r#"SELECT count(*) AS "count!" FROM harness_tokens"#)+ .fetch_one(&pool)+ .await+ .unwrap();+ assert_eq!(token_count, 1);+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn open_pairing_counts_and_expiry_cleanup(pool: PgPool) {+ let repo = PgHarnessRepo::new(pool.clone());+ assert!(+ repo.insert_pairing(new_pairing("AAAA-AAAA", "one"))+ .await+ .unwrap()+ );+ let mut expired = new_pairing("BBBB-BBBB", "two");+ expired.expires_at = Utc::now() - Duration::minutes(1);+ assert!(repo.insert_pairing(expired).await.unwrap());+ let mut other_name = new_pairing("CCCC-CCCC", "three");+ other_name.requested_name = "other".to_owned();+ assert!(repo.insert_pairing(other_name).await.unwrap());++ let counts = repo.count_open_pairings("erics-macbook").await.unwrap();+ assert_eq!(counts.total, 2);+ assert_eq!(counts.with_same_name, 1);++ repo.delete_expired_pairings().await.unwrap();+ assert!(repo.get_pairing("BBBB-BBBB").await.unwrap().is_none());+ assert!(repo.get_pairing("AAAA-AAAA").await.unwrap().is_some());+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn visibility_spans_own_and_team_harnesses(pool: PgPool) {+ let repo = PgHarnessRepo::new(pool.clone());++ // A private harness owned by the caller.+ sqlx::query!(+ r#"+ INSERT INTO harnesses (id, name, owner_user_id, created_by)+ VALUES ($1, 'mine', $2, $2)+ "#,+ Uuid::new_v4(),+ OWNER_ID,+ )+ .execute(&pool)+ .await+ .unwrap();++ // A team harness registered by someone else on the caller's team.+ insert_user(&pool, OWNER_ID).await;+ let team_id = Uuid::new_v4();+ sqlx::query!(+ r#"INSERT INTO team (id, name, owner_id) VALUES ($1, 'Team', $2)"#,+ team_id,+ OWNER_ID,+ )+ .execute(&pool)+ .await+ .unwrap();+ sqlx::query!(+ r#"+ INSERT INTO team_user (user_id, team_id, team_role)+ VALUES ($1, $2, 'member'::team_role)+ "#,+ OWNER_ID,+ team_id,+ )+ .execute(&pool)+ .await+ .unwrap();+ sqlx::query!(+ r#"+ INSERT INTO harnesses (id, name, team_id, created_by)+ VALUES ($1, 'teams', $2, 'macro|[email protected]')+ "#,+ Uuid::new_v4(),+ team_id,+ )+ .execute(&pool)+ .await+ .unwrap();++ // Someone else's private harness stays invisible.+ sqlx::query!(+ r#"+ INSERT INTO harnesses (id, name, owner_user_id, created_by)+ VALUES ($1, 'theirs', $2, $2)+ "#,+ Uuid::new_v4(),+ "macro|[email protected]",+ )+ .execute(&pool)+ .await+ .unwrap();++ let visible = repo.list_visible_harnesses(caller()).await.unwrap();+ let mut names: Vec<_> = visible.iter().map(|h| h.name.as_str()).collect();+ names.sort_unstable();+ assert_eq!(names, ["mine", "teams"]);++ assert!(repo.user_has_team(caller(), team_id).await.unwrap());+ assert!(!repo.user_owns_team(caller(), team_id).await.unwrap());+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn deletion_soft_deletes_and_revokes_tokens(pool: PgPool) {+ let repo = PgHarnessRepo::new(pool.clone());+ let harness_id = Uuid::new_v4();+ sqlx::query!(+ r#"+ INSERT INTO harnesses (id, name, owner_user_id, created_by)+ VALUES ($1, 'mine', $2, $2)+ "#,+ harness_id,+ OWNER_ID,+ )+ .execute(&pool)+ .await+ .unwrap();+ let hashed = HashedHarnessToken::from_raw("mhns_abc_secret");+ sqlx::query!(+ r#"+ INSERT INTO harness_tokens (id, harness_id, token_hash, token_prefix)+ VALUES ($1, $2, $3, $4)+ "#,+ Uuid::new_v4(),+ harness_id,+ &hashed.hash[..],+ hashed.prefix,+ )+ .execute(&pool)+ .await+ .unwrap();++ let harness_id = HarnessId::new_from_uuid(harness_id);+ assert!(repo.delete_harness(harness_id).await.unwrap());+ assert!(repo.get_harness(harness_id).await.unwrap().is_none());+ assert!(!repo.delete_harness(harness_id).await.unwrap());++ let unrevoked = sqlx::query_scalar!(+ r#"SELECT count(*) AS "count!" FROM harness_tokens WHERE revoked_at IS NULL"#+ )+ .fetch_one(&pool)+ .await+ .unwrap();+ assert_eq!(unrevoked, 0);+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn connected_state_follows_the_presence_timestamps(pool: PgPool) {+ let repo = PgHarnessRepo::new(pool.clone());+ let harness_id = Uuid::new_v4();+ sqlx::query!(+ r#"+ INSERT INTO harnesses (id, name, owner_user_id, created_by, last_connected_at)+ VALUES ($1, 'mine', $2, $2, now())+ "#,+ harness_id,+ OWNER_ID,+ )+ .execute(&pool)+ .await+ .unwrap();+ let harness_id = HarnessId::new_from_uuid(harness_id);++ let harness = repo.get_harness(harness_id).await.unwrap().unwrap();+ assert!(harness.connected);++ sqlx::query!(r#"UPDATE harnesses SET last_disconnected_at = now() + interval '1 second'"#)+ .execute(&pool)+ .await+ .unwrap();+ let harness = repo.get_harness(harness_id).await.unwrap().unwrap();+ assert!(!harness.connected);+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn bound_agents_lists_only_live_agents_of_this_harness(pool: PgPool) {+ let repo = PgHarnessRepo::new(pool.clone());+ let harness_id = Uuid::new_v4();+ sqlx::query!(+ r#"+ INSERT INTO harnesses (id, name, owner_user_id, created_by)+ VALUES ($1, 'mine', $2, $2)+ "#,+ harness_id,+ OWNER_ID,+ )+ .execute(&pool)+ .await+ .unwrap();++ let bot_id = Uuid::new_v4();+ sqlx::query!(+ r#"+ INSERT INTO bots (id, kind, owner_user_id, name, handle, has_agent)+ VALUES ($1, 'owned', $2, 'Bound agent', $3, true)+ "#,+ bot_id,+ OWNER_ID,+ format!("bound-{bot_id}"),+ )+ .execute(&pool)+ .await+ .unwrap();+ sqlx::query!(+ r#"+ INSERT INTO agent_configs (bot_id, instructions, harness, default_model, channel_scope, harness_id)+ VALUES ($1, 'prompt', 'macrod', 'default', 'all', $2)+ "#,+ bot_id,+ harness_id,+ )+ .execute(&pool)+ .await+ .unwrap();++ // An unbound agent on another runtime.+ let other_bot = Uuid::new_v4();+ sqlx::query!(+ r#"+ INSERT INTO bots (id, kind, owner_user_id, name, handle, has_agent)+ VALUES ($1, 'owned', $2, 'Unbound agent', $3, true)+ "#,+ other_bot,+ OWNER_ID,+ format!("unbound-{other_bot}"),+ )+ .execute(&pool)+ .await+ .unwrap();+ sqlx::query!(+ r#"+ INSERT INTO agent_configs (bot_id, instructions, harness, default_model, channel_scope)+ VALUES ($1, 'prompt', 'in-memory', 'default', 'all')+ "#,+ other_bot,+ )+ .execute(&pool)+ .await+ .unwrap();++ let agents = repo+ .list_bound_agents(HarnessId::new_from_uuid(harness_id))+ .await+ .unwrap();+ assert_eq!(agents.len(), 1);+ assert_eq!(agents[0].bot_id.as_uuid(), bot_id);+ assert_eq!(agents[0].name, "Bound agent");+}diff --git a/crates/macro_authorization/Cargo.toml b/crates/macro_authorization/Cargo.tomlindex 30c1e80f70..74931c6f77 100644--- a/crates/macro_authorization/Cargo.toml+++ b/crates/macro_authorization/Cargo.toml@@ -21,6 +21,8 @@ axum = { workspace = true, optional = true }bot_id = { path = "../bot_id" }bot_token = { path = "../bot_token" }constant_time_eq = { workspace = true }+harness_id = { path = "../harness_id" }+harness_token = { path = "../harness_token" }macro_auth = { path = "../macro_auth", optional = true }macro_env_var = { path = "../macro_env_var", optional = true }macro_user_id = { path = "../macro_user_id" }@@ -37,6 +39,7 @@ workspace-hack = { version = "0.1", path = "../workspace-hack" }[dev-dependencies]cookie = { workspace = true }+harness_id = { path = "../harness_id", features = ["test-utils"] }http-body-util = { workspace = true }jsonwebtoken = { workspace = true }macro_auth = { path = "../macro_auth", features = ["testing"] }diff --git a/crates/macro_authorization/src/domain.rs b/crates/macro_authorization/src/domain.rsindex 467e83248b..f3681ff36b 100644--- a/crates/macro_authorization/src/domain.rs+++ b/crates/macro_authorization/src/domain.rs@@ -2,6 +2,8 @@/// Bot credential authorization policy.pub mod bot_authorizer;+/// Harness credential authorization policy.+pub mod harness_authorizer;/// Models produced and consumed by the authorization domain.pub mod models;/// Interfaces that connect the authorization domain to its adapters.diff --git a/crates/macro_authorization/src/domain/harness_authorizer.rs b/crates/macro_authorization/src/domain/harness_authorizer.rsnew file mode 100644index 0000000000..308c86bea1--- /dev/null+++ b/crates/macro_authorization/src/domain/harness_authorizer.rs@@ -0,0 +1,129 @@+//! Harness credential authorization policy.++#[cfg(test)]+mod test;++use model_user::UserContext;+use rootcause::Report;++use super::{+ models::{+ HarnessAuthentication, HarnessAuthorizationOwner, HarnessTokenAuthorization,+ MacroAuthorizationError, MacroUserAuthentication, ResolvedBotActingUser,+ },+ ports::{HarnessAuthorizationRepo, HarnessAuthorizer},+};++/// Harness authorizer backed by transport-independent authorization facts.+#[derive(Clone, Debug)]+pub struct HarnessAuthorizerService<R> {+ repo: R,+}++impl<R> HarnessAuthorizerService<R> {+ /// Create a harness authorizer backed by the supplied repository.+ pub fn new(repo: R) -> Self {+ Self { repo }+ }+}++impl<R> HarnessAuthorizerService<R>+where+ R: HarnessAuthorizationRepo,+{+ /// Resolve and verify the user this harness request acts for.+ ///+ /// A forwarded claim must be authorized against harness ownership: the+ /// owner for private harnesses, any current team member for team-owned+ /// ones. The default (owner or creator) passes the same check so a+ /// creator who left the owning team no longer authenticates its harness.+ async fn resolve_acting_user(+ &self,+ token: &HarnessTokenAuthorization,+ claim: Option<String>,+ ) -> Result<ResolvedBotActingUser, Report<MacroAuthorizationError>> {+ let user_id = claim.unwrap_or_else(|| match &token.owner {+ HarnessAuthorizationOwner::User { user_id } => user_id.clone(),+ HarnessAuthorizationOwner::Team { .. } => token.created_by.clone(),+ });++ let acting_user = self+ .repo+ .find_user(&user_id)+ .await+ .map_err(|error| repository_error(error, "find harness acting user"))?+ .ok_or_else(|| Report::new(MacroAuthorizationError::ActingUserNotAuthorized))?;++ let authorized = match &token.owner {+ HarnessAuthorizationOwner::User { user_id: owner } => {+ owner == acting_user.macro_user_id.as_ref()+ }+ HarnessAuthorizationOwner::Team { team_id } => self+ .repo+ .user_has_team(&acting_user.fusion_user_id, *team_id)+ .await+ .map_err(|error| repository_error(error, "check harness team membership"))?,+ };++ if !authorized {+ return Err(Report::new(+ MacroAuthorizationError::ActingUserNotAuthorized,+ ));+ }++ Ok(acting_user)+ }+}++impl<R> HarnessAuthorizer for HarnessAuthorizerService<R>+where+ R: HarnessAuthorizationRepo,+{+ async fn authorize_harness(+ &self,+ harness_token: &str,+ acting_user_claim: Option<String>,+ ) -> Result<HarnessAuthentication, Report<MacroAuthorizationError>> {+ let token = self+ .repo+ .find_valid_harness_token(harness_token)+ .await+ .map_err(|error| repository_error(error, "find valid harness token"))?+ .ok_or_else(|| Report::new(MacroAuthorizationError::InvalidCredentials))?;++ self.repo+ .mark_harness_token_used(token.token_id)+ .await+ .map_err(|error| repository_error(error, "mark harness token used"))?;++ let acting_user = self.resolve_acting_user(&token, acting_user_claim).await?;++ Ok(HarnessAuthentication {+ harness_id: token.harness_id,+ token_id: token.token_id,+ owner: token.owner,+ acting_user: user_authentication(acting_user),+ })+ }+}++fn user_authentication(acting_user: ResolvedBotActingUser) -> MacroUserAuthentication {+ let user_id = acting_user.macro_user_id.as_ref().to_owned();+ MacroUserAuthentication {+ macro_user_id: acting_user.macro_user_id,+ user_context: UserContext {+ user_id,+ fusion_user_id: acting_user.fusion_user_id,+ permissions: None,+ organization_id: acting_user.organization_id,+ },+ }+}++fn repository_error(+ error: impl std::fmt::Debug,+ operation: &'static str,+) -> Report<MacroAuthorizationError> {+ tracing::error!(error=?error, operation, "harness authorization repository failed");+ Report::new(MacroAuthorizationError::Unavailable)+}diff --git a/crates/macro_authorization/src/domain/harness_authorizer/test.rs b/crates/macro_authorization/src/domain/harness_authorizer/test.rsnew file mode 100644index 0000000000..45362275af--- /dev/null+++ b/crates/macro_authorization/src/domain/harness_authorizer/test.rs@@ -0,0 +1,258 @@+use std::sync::{Arc, Mutex};++use harness_id::HarnessId;+use macro_user_id::user_id::MacroUserIdStr;+use uuid::Uuid;++use super::*;+use crate::domain::ports::HarnessAuthorizationRepo;++const RAW_TOKEN: &str = "mhns_test_secret";+const OWNER_ID: &str = "macro|[email protected]";+const MEMBER_ID: &str = "macro|[email protected]";+const FUSION_USER_ID: &str = "fusion-owner";+const TEAM_ID: Uuid = Uuid::from_u128(3);++#[derive(Clone, Copy, Debug, Eq, PartialEq)]+enum Failure {+ FindToken,+ MarkTokenUsed,+ FindUser,+ UserHasTeam,+}++#[derive(Debug, Default)]+struct Calls {+ tokens: Vec<String>,+ marked_token_ids: Vec<Uuid>,+ user_lookups: Vec<String>,+ team_lookups: Vec<(String, Uuid)>,+}++#[derive(Clone)]+struct FakeRepo {+ token: Option<HarnessTokenAuthorization>,+ user: Option<ResolvedBotActingUser>,+ user_has_team: bool,+ failure: Option<Failure>,+ calls: Arc<Mutex<Calls>>,+}++impl FakeRepo {+ fn owned_by_user() -> Self {+ Self {+ token: Some(HarnessTokenAuthorization {+ harness_id: HarnessId::TEST_A,+ token_id: Uuid::from_u128(2),+ owner: HarnessAuthorizationOwner::User {+ user_id: OWNER_ID.to_string(),+ },+ created_by: OWNER_ID.to_string(),+ }),+ user: Some(resolved_user(OWNER_ID)),+ user_has_team: true,+ failure: None,+ calls: Arc::new(Mutex::new(Calls::default())),+ }+ }++ fn owned_by_team() -> Self {+ let mut repo = Self::owned_by_user();+ let token = repo.token.as_mut().unwrap();+ token.owner = HarnessAuthorizationOwner::Team { team_id: TEAM_ID };+ repo+ }++ fn fail_at(mut self, failure: Failure) -> Self {+ self.failure = Some(failure);+ self+ }+}++impl HarnessAuthorizationRepo for FakeRepo {+ type Err = &'static str;++ async fn find_valid_harness_token(+ &self,+ token: &str,+ ) -> Result<Option<HarnessTokenAuthorization>, Self::Err> {+ self.calls.lock().unwrap().tokens.push(token.to_string());+ if self.failure == Some(Failure::FindToken) {+ return Err("find token failed");+ }+ Ok(self.token.clone())+ }++ async fn mark_harness_token_used(&self, token_id: Uuid) -> Result<(), Self::Err> {+ self.calls.lock().unwrap().marked_token_ids.push(token_id);+ if self.failure == Some(Failure::MarkTokenUsed) {+ return Err("mark used failed");+ }+ Ok(())+ }++ async fn find_user(+ &self,+ macro_user_id: &str,+ ) -> Result<Option<ResolvedBotActingUser>, Self::Err> {+ self.calls+ .lock()+ .unwrap()+ .user_lookups+ .push(macro_user_id.to_string());+ if self.failure == Some(Failure::FindUser) {+ return Err("find user failed");+ }+ Ok(self+ .user+ .clone()+ .filter(|user| user.macro_user_id.as_ref() == macro_user_id))+ }++ async fn user_has_team(&self, fusion_user_id: &str, team_id: Uuid) -> Result<bool, Self::Err> {+ self.calls+ .lock()+ .unwrap()+ .team_lookups+ .push((fusion_user_id.to_string(), team_id));+ if self.failure == Some(Failure::UserHasTeam) {+ return Err("team lookup failed");+ }+ Ok(self.user_has_team)+ }+}++fn resolved_user(macro_user_id: &str) -> ResolvedBotActingUser {+ ResolvedBotActingUser {+ macro_user_id: MacroUserIdStr::try_from(macro_user_id.to_string()).unwrap(),+ fusion_user_id: FUSION_USER_ID.to_string(),+ organization_id: Some(42),+ }+}++fn assert_error(+ result: Result<HarnessAuthentication, Report<MacroAuthorizationError>>,+ expected: MacroAuthorizationError,+) {+ assert_eq!(result.unwrap_err().current_context(), &expected);+}++#[tokio::test]+async fn authorizes_private_harness_with_owner_as_default_acting_user() {+ let repo = FakeRepo::owned_by_user();+ let authentication = HarnessAuthorizerService::new(repo.clone())+ .authorize_harness(RAW_TOKEN, None)+ .await+ .unwrap();++ let token = repo.token.as_ref().unwrap();+ assert_eq!(authentication.harness_id, token.harness_id);+ assert_eq!(authentication.token_id, token.token_id);+ assert_eq!(authentication.acting_user.macro_user_id.as_ref(), OWNER_ID);++ let calls = repo.calls.lock().unwrap();+ assert_eq!(calls.tokens, [RAW_TOKEN]);+ assert_eq!(calls.marked_token_ids, [token.token_id]);+ assert_eq!(calls.user_lookups, [OWNER_ID]);+ assert!(calls.team_lookups.is_empty());+}++#[tokio::test]+async fn team_harness_defaults_to_its_creator_and_checks_membership() {+ let repo = FakeRepo::owned_by_team();+ let authentication = HarnessAuthorizerService::new(repo.clone())+ .authorize_harness(RAW_TOKEN, None)+ .await+ .unwrap();++ assert_eq!(authentication.acting_user.macro_user_id.as_ref(), OWNER_ID);+ assert_eq!(+ repo.calls.lock().unwrap().team_lookups,+ [(FUSION_USER_ID.to_string(), TEAM_ID)]+ );+}++#[tokio::test]+async fn verified_claim_becomes_the_acting_user_for_team_members() {+ let mut repo = FakeRepo::owned_by_team();+ repo.user = Some(resolved_user(MEMBER_ID));++ let authentication = HarnessAuthorizerService::new(repo.clone())+ .authorize_harness(RAW_TOKEN, Some(MEMBER_ID.to_string()))+ .await+ .unwrap();++ assert_eq!(authentication.acting_user.macro_user_id.as_ref(), MEMBER_ID);+ assert_eq!(repo.calls.lock().unwrap().user_lookups, [MEMBER_ID]);+}++#[tokio::test]+async fn rejects_claims_for_users_outside_the_owning_team() {+ let mut repo = FakeRepo::owned_by_team();+ repo.user = Some(resolved_user(MEMBER_ID));+ repo.user_has_team = false;++ let result = HarnessAuthorizerService::new(repo)+ .authorize_harness(RAW_TOKEN, Some(MEMBER_ID.to_string()))+ .await;++ assert_error(result, MacroAuthorizationError::ActingUserNotAuthorized);+}++#[tokio::test]+async fn private_harness_rejects_claims_for_anyone_but_the_owner() {+ let mut repo = FakeRepo::owned_by_user();+ repo.user = Some(resolved_user(MEMBER_ID));++ let result = HarnessAuthorizerService::new(repo)+ .authorize_harness(RAW_TOKEN, Some(MEMBER_ID.to_string()))+ .await;++ assert_error(result, MacroAuthorizationError::ActingUserNotAuthorized);+}++#[tokio::test]+async fn rejects_claims_for_unknown_users() {+ let repo = FakeRepo::owned_by_user();++ let result = HarnessAuthorizerService::new(repo)+ .authorize_harness(RAW_TOKEN, Some("macro|[email protected]".to_string()))+ .await;++ assert_error(result, MacroAuthorizationError::ActingUserNotAuthorized);+}++#[tokio::test]+async fn rejects_unknown_token_without_marking_or_policy_lookups() {+ let mut repo = FakeRepo::owned_by_user();+ repo.token = None;++ let result = HarnessAuthorizerService::new(repo.clone())+ .authorize_harness(RAW_TOKEN, None)+ .await;++ assert_error(result, MacroAuthorizationError::InvalidCredentials);+ let calls = repo.calls.lock().unwrap();+ assert!(calls.marked_token_ids.is_empty());+ assert!(calls.user_lookups.is_empty());+}++#[tokio::test]+async fn maps_repository_failures_to_unavailable() {+ for failure in [+ Failure::FindToken,+ Failure::MarkTokenUsed,+ Failure::FindUser,+ ] {+ let result = HarnessAuthorizerService::new(FakeRepo::owned_by_user().fail_at(failure))+ .authorize_harness(RAW_TOKEN, None)+ .await;+ assert_error(result, MacroAuthorizationError::Unavailable);+ }++ let result =+ HarnessAuthorizerService::new(FakeRepo::owned_by_team().fail_at(Failure::UserHasTeam))+ .authorize_harness(RAW_TOKEN, None)+ .await;+ assert_error(result, MacroAuthorizationError::Unavailable);+}diff --git a/crates/macro_authorization/src/domain/models.rs b/crates/macro_authorization/src/domain/models.rsindex 0a271162fb..fe942d8e31 100644--- a/crates/macro_authorization/src/domain/models.rs+++ b/crates/macro_authorization/src/domain/models.rs@@ -4,6 +4,7 @@ mod test;use std::{collections::HashSet, fmt};use bot_id::BotId;+use harness_id::HarnessId;use macro_user_id::user_id::MacroUserIdStr;use model_user::UserContext;use thiserror::Error;@@ -61,6 +62,28 @@ pub struct BotAuthentication {pub acting_user: Option<MacroUserAuthentication>,}+/// A harness principal whose token has been validated.+///+/// The raw token is deliberately excluded so it cannot flow into handlers,+/// tracing spans, or logs after authentication.+#[derive(Clone, Debug)]+pub struct HarnessAuthentication {+ /// The validated harness.+ pub harness_id: HarnessId,+ /// The token row used to authenticate, for audit and telemetry.+ pub token_id: Uuid,+ /// The harness owner used by acting-user policy.+ pub owner: HarnessAuthorizationOwner,+ /// The verified user this request acts for.+ ///+ /// Always resolved server-side: the claimed user when the daemon forwards+ /// one (a mention sender, verified against harness ownership), otherwise+ /// the harness owner for private harnesses or its creator for team+ /// harnesses. A guaranteed acting user lets acting-user-gated endpoints+ /// (webhook feed registration) admit harness callers unchanged.+ pub acting_user: MacroUserAuthentication,+}+/// How the caller authenticated.////// This enum is exhaustive so adding an authentication source requires every@@ -71,6 +94,8 @@ pub enum MacroAuthorization {User(MacroUserAuthentication),/// A caller authenticated with a bot token.Bot(BotAuthentication),+ /// A caller authenticated with a harness token.+ Harness(HarnessAuthentication),/// An internally authenticated service, optionally acting for a user.Internal(Option<MacroUserAuthentication>),}@@ -81,6 +106,7 @@ impl MacroAuthorization {match self {Self::User(user) => Some(user),Self::Bot(bot) => bot.acting_user.as_ref(),+ Self::Harness(harness) => Some(&harness.acting_user),Self::Internal(user) => user.as_ref(),}}@@ -94,7 +120,15 @@ impl MacroAuthorization {pub fn bot(&self) -> Option<&BotAuthentication> {match self {Self::Bot(bot) => Some(bot),- Self::User(_) | Self::Internal(_) => None,+ Self::User(_) | Self::Harness(_) | Self::Internal(_) => None,+ }+ }++ /// Return the authenticated harness principal, when the caller is a harness.+ pub fn harness(&self) -> Option<&HarnessAuthentication> {+ match self {+ Self::Harness(harness) => Some(harness),+ Self::User(_) | Self::Bot(_) | Self::Internal(_) => None,}}}@@ -116,6 +150,39 @@ pub enum BotAuthorizationOwner {System,}+/// Ownership facts for a harness whose token has been validated.+///+/// Unlike bots, a harness always has a user or team owner; there are no+/// system harnesses.+#[derive(Clone, Debug, Eq, PartialEq)]+pub enum HarnessAuthorizationOwner {+ /// A harness owned by one Macro user.+ User {+ /// The owning Macro user identifier.+ user_id: String,+ },+ /// A harness owned by a team.+ Team {+ /// The owning team identifier.+ team_id: Uuid,+ },+}++/// Valid harness-token facts returned by the authorization repository.+#[derive(Clone, Debug, Eq, PartialEq)]+pub struct HarnessTokenAuthorization {+ /// The authenticated harness.+ pub harness_id: HarnessId,+ /// The token row used to authenticate.+ pub token_id: Uuid,+ /// The harness owner used by acting-user policy.+ pub owner: HarnessAuthorizationOwner,+ /// The Macro user id that registered the harness.+ ///+ /// The default acting user for team-owned harnesses.+ pub created_by: String,+}+/// Valid bot-token facts returned by the authorization repository.#[derive(Clone, Debug, Eq, PartialEq)]pub struct BotTokenAuthorization {diff --git a/crates/macro_authorization/src/domain/ports.rs b/crates/macro_authorization/src/domain/ports.rsindex cc063be382..136cd56575 100644--- a/crates/macro_authorization/src/domain/ports.rs+++ b/crates/macro_authorization/src/domain/ports.rs@@ -4,9 +4,9 @@ use model_user::UserContext;use rootcause::Report;use super::models::{- BotActingUserClaims, BotAuthentication, BotScope, BotTokenAuthorization,- InternalIdentityClaims, MacroAuthorizationError, ResolvedApiKeyUser, ResolvedBotActingUser,- ValidatedIdentity,+ BotActingUserClaims, BotAuthentication, BotScope, BotTokenAuthorization, HarnessAuthentication,+ HarnessTokenAuthorization, InternalIdentityClaims, MacroAuthorizationError, ResolvedApiKeyUser,+ ResolvedBotActingUser, ValidatedIdentity,};use uuid::Uuid;@@ -102,6 +102,65 @@ impl UserApiKeyAuthorizer for NoUserApiKeyAuthorizer {}}+/// Persistence facts required to authorize harness credentials.+pub trait HarnessAuthorizationRepo: Clone + Send + Sync + 'static {+ /// Repository error.+ type Err: Debug + Send;++ /// Find a currently valid token and its harness ownership facts.+ fn find_valid_harness_token(+ &self,+ token: &str,+ ) -> impl Future<Output = Result<Option<HarnessTokenAuthorization>, Self::Err>> + Send;++ /// Mark a validated token as used.+ fn mark_harness_token_used(+ &self,+ token_id: Uuid,+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;++ /// Resolve a Macro user id to user-store facts.+ fn find_user(+ &self,+ macro_user_id: &str,+ ) -> impl Future<Output = Result<Option<ResolvedBotActingUser>, Self::Err>> + Send;++ /// Check whether a user is a current member of a team.+ fn user_has_team(+ &self,+ fusion_user_id: &str,+ team_id: Uuid,+ ) -> impl Future<Output = Result<bool, Self::Err>> + Send;+}++/// Validates harness credentials and resolves verified acting-user identities.+pub trait HarnessAuthorizer: Clone + Send + Sync + 'static {+ /// Authorize a harness token, verifying and resolving the acting user.+ ///+ /// `acting_user_claim` is an unverified Macro user id the daemon forwards+ /// (a mention sender); absent, the acting user defaults to the harness+ /// owner or, for team harnesses, its creator.+ fn authorize_harness(+ &self,+ harness_token: &str,+ acting_user_claim: Option<String>,+ ) -> impl Future<Output = Result<HarnessAuthentication, Report<MacroAuthorizationError>>> + Send;+}++/// Harness authorizer used by services that do not support harness authentication.+#[derive(Clone)]+pub struct NoHarnessAuthorizer;++impl HarnessAuthorizer for NoHarnessAuthorizer {+ async fn authorize_harness(+ &self,+ _harness_token: &str,+ _acting_user_claim: Option<String>,+ ) -> Result<HarnessAuthentication, Report<MacroAuthorizationError>> {+ Err(Report::new(MacroAuthorizationError::InvalidCredentials))+ }+}+/// Cryptographic credential validation used by the authorization domain.////// Implementations resolve any required secrets during startup, allowing this@@ -136,6 +195,19 @@ pub trait MacroAuthorizationService: Clone + Send + Sync + 'static {async { Err(Report::new(MacroAuthorizationError::InvalidCredentials)) }}+ /// Authorize a harness token, verifying any acting-user claim.+ ///+ /// Services reject harness credentials unless they explicitly provide a+ /// harness authorizer.+ fn authorize_harness(+ &self,+ _harness_token: &str,+ _acting_user_claim: Option<String>,+ ) -> impl Future<Output = Result<HarnessAuthentication, Report<MacroAuthorizationError>>> + Send+ {+ async { Err(Report::new(MacroAuthorizationError::InvalidCredentials)) }+ }+/// Authorize an internal service-to-service caller.////// Returns `Ok(None)` when the key is valid but no identity is establisheddiff --git a/crates/macro_authorization/src/domain/service.rs b/crates/macro_authorization/src/domain/service.rsindex ddbdd23dab..8fe1aa230b 100644--- a/crates/macro_authorization/src/domain/service.rs+++ b/crates/macro_authorization/src/domain/service.rs@@ -9,10 +9,13 @@ use rootcause::Report;use super::{models::{- BotActingUserClaims, BotAuthentication, BotScope, InternalAuthConfig,- InternalIdentityClaims, MacroAuthorizationError,+ BotActingUserClaims, BotAuthentication, BotScope, HarnessAuthentication,+ InternalAuthConfig, InternalIdentityClaims, MacroAuthorizationError,+ },+ ports::{+ BotAuthorizer, HarnessAuthorizer, JwtValidator, MacroAuthorizationService,+ NoHarnessAuthorizer, UserApiKeyAuthorizer,},- ports::{BotAuthorizer, JwtValidator, MacroAuthorizationService, UserApiKeyAuthorizer},};type BotAuthorizationFuture<'a> = Pin<@@ -65,6 +68,39 @@ where}}+type HarnessAuthorizationFuture<'a> = Pin<+ Box<+ dyn Future<Output = Result<HarnessAuthentication, Report<MacroAuthorizationError>>>+ + Send+ + 'a,+ >,+>;++trait DynHarnessAuthorizer: Send + Sync {+ fn authorize_harness<'a>(+ &'a self,+ harness_token: &'a str,+ acting_user_claim: Option<String>,+ ) -> HarnessAuthorizationFuture<'a>;+}++impl<H> DynHarnessAuthorizer for H+where+ H: HarnessAuthorizer,+{+ fn authorize_harness<'a>(+ &'a self,+ harness_token: &'a str,+ acting_user_claim: Option<String>,+ ) -> HarnessAuthorizationFuture<'a> {+ Box::pin(HarnessAuthorizer::authorize_harness(+ self,+ harness_token,+ acting_user_claim,+ ))+ }+}+/// Default authorization service backed by a credential validator.#[derive(Clone)]pub struct MacroAuthorizationServiceImpl<V> {@@ -72,10 +108,14 @@ pub struct MacroAuthorizationServiceImpl<V> {internal_auth: InternalAuthConfig,bot_authorizer: Arc<dyn DynBotAuthorizer>,user_api_key_authorizer: Arc<dyn DynUserApiKeyAuthorizer>,+ harness_authorizer: Arc<dyn DynHarnessAuthorizer>,}impl<V> MacroAuthorizationServiceImpl<V> {/// Create an authorization service with required user, internal, bot, and user API key authorization dependencies.+ ///+ /// Harness credentials are rejected unless a harness authorizer is+ /// supplied with [`Self::with_harness_authorizer`].pub fn new(validator: V,internal_auth: InternalAuthConfig,@@ -87,8 +127,16 @@ impl<V> MacroAuthorizationServiceImpl<V> {internal_auth,bot_authorizer: Arc::new(bot_authorizer),user_api_key_authorizer: Arc::new(user_api_key_authorizer),+ harness_authorizer: Arc::new(NoHarnessAuthorizer),}}++ /// Accept harness credentials, validating them with the supplied authorizer.+ #[must_use]+ pub fn with_harness_authorizer(mut self, harness_authorizer: impl HarnessAuthorizer) -> Self {+ self.harness_authorizer = Arc::new(harness_authorizer);+ self+ }}impl<V> MacroAuthorizationService for MacroAuthorizationServiceImpl<V>@@ -163,6 +211,36 @@ whereOk(user)}+ #[tracing::instrument(+ err,+ skip_all,+ fields(+ harness_id = tracing::field::Empty,+ token_id = tracing::field::Empty,+ acting_user_id = tracing::field::Empty,+ )+ )]+ async fn authorize_harness(+ &self,+ harness_token: &str,+ acting_user_claim: Option<String>,+ ) -> Result<HarnessAuthentication, Report<MacroAuthorizationError>> {+ let harness = self+ .harness_authorizer+ .authorize_harness(harness_token, acting_user_claim)+ .await?;++ let span = tracing::Span::current();+ span.record("harness_id", tracing::field::display(harness.harness_id));+ span.record("token_id", tracing::field::display(harness.token_id));+ span.record(+ "acting_user_id",+ tracing::field::display(&harness.acting_user.macro_user_id),+ );++ Ok(harness)+ }+async fn authorize_internal(&self,provided_key: &str,diff --git a/crates/macro_authorization/src/inbound.rs b/crates/macro_authorization/src/inbound.rsindex 348d650457..7e4b6c92a4 100644--- a/crates/macro_authorization/src/inbound.rs+++ b/crates/macro_authorization/src/inbound.rs@@ -8,12 +8,14 @@ pub use axum::{ActingEntity, ActingUser, ActingUserAuthorization, AnyPrincipal, AuthorizationPolicy,BOT_FOR_FUSIONAUTH_USER_ID_HEADER, BOT_FOR_MACRO_USER_ID_HEADER,BOT_FOR_ORGANIZATION_ID_HEADER, BOT_SCOPE_HEADER, BOT_TOKEN_HEADER, BotOnly,- INTERNAL_API_KEY_HEADER, INTERNAL_FUSIONAUTH_USER_ID_HEADER,- INTERNAL_MACRO_ORGANIZATION_ID_HEADER, INTERNAL_MACRO_USER_ID_HEADER, InternalAuthorization,- InternalEntity, InternalOnly, LEGACY_DSS_INTERNAL_API_KEY_HEADER,- LEGACY_DSS_INTERNAL_MACRO_USER_ID_HEADER, MacroAuthorizationExtractor,- MacroAuthorizationRejection, MacroAuthorizationState, OptionalMacroAuthorizationExtractor,- USER_API_KEY_HEADER, UserOnly, UserOrBot, UserOrBotAuthorization, UserOrBotEntity,- UserOrInternal, UserOrInternalAuthorization, UserOrInternalCaller, UserOrInternalEntity,- UserOrInternalService, UserOrInternalServiceAuthorization,+ HARNESS_FOR_MACRO_USER_ID_HEADER, HARNESS_TOKEN_HEADER, HarnessOnly, INTERNAL_API_KEY_HEADER,+ INTERNAL_FUSIONAUTH_USER_ID_HEADER, INTERNAL_MACRO_ORGANIZATION_ID_HEADER,+ INTERNAL_MACRO_USER_ID_HEADER, InternalAuthorization, InternalEntity, InternalOnly,+ LEGACY_DSS_INTERNAL_API_KEY_HEADER, LEGACY_DSS_INTERNAL_MACRO_USER_ID_HEADER,+ MacroAuthorizationExtractor, MacroAuthorizationRejection, MacroAuthorizationState,+ OptionalMacroAuthorizationExtractor, USER_API_KEY_HEADER, UserBotOrHarness,+ UserBotOrHarnessAuthorization, UserBotOrHarnessEntity, UserOnly, UserOrBot,+ UserOrBotAuthorization, UserOrBotEntity, UserOrInternal, UserOrInternalAuthorization,+ UserOrInternalCaller, UserOrInternalEntity, UserOrInternalService,+ UserOrInternalServiceAuthorization,};diff --git a/crates/macro_authorization/src/inbound/axum.rs b/crates/macro_authorization/src/inbound/axum.rsindex 58d478e8a0..2993cf14ad 100644--- a/crates/macro_authorization/src/inbound/axum.rs+++ b/crates/macro_authorization/src/inbound/axum.rs@@ -2,6 +2,7 @@mod test;mod bot;+mod harness;mod internal;mod macro_authorization;mod optional;@@ -17,6 +18,7 @@ use ::axum::{response::{IntoResponse, Response},};use bot_id::BotId;+use harness_id::HarnessId;use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};use model_error_response::ErrorResponse;use model_user::UserContext;@@ -27,6 +29,7 @@ pub use bot::{BOT_FOR_FUSIONAUTH_USER_ID_HEADER, BOT_FOR_MACRO_USER_ID_HEADER,BOT_FOR_ORGANIZATION_ID_HEADER, BOT_SCOPE_HEADER, BOT_TOKEN_HEADER,};+pub use harness::{HARNESS_FOR_MACRO_USER_ID_HEADER, HARNESS_TOKEN_HEADER};#[allow(deprecated)]pub use internal::{INTERNAL_API_KEY_HEADER, INTERNAL_FUSIONAUTH_USER_ID_HEADER,@@ -36,8 +39,9 @@ pub use internal::{pub use macro_authorization::MacroAuthorizationExtractor;pub use optional::OptionalMacroAuthorizationExtractor;pub use policy::{- ActingUser, ActingUserAuthorization, AnyPrincipal, AuthorizationPolicy, BotOnly,- InternalAuthorization, InternalEntity, InternalOnly, UserOnly, UserOrBot,+ ActingUser, ActingUserAuthorization, AnyPrincipal, AuthorizationPolicy, BotOnly, HarnessOnly,+ InternalAuthorization, InternalEntity, InternalOnly, UserBotOrHarness,+ UserBotOrHarnessAuthorization, UserBotOrHarnessEntity, UserOnly, UserOrBot,UserOrBotAuthorization, UserOrBotEntity, UserOrInternal, UserOrInternalAuthorization,UserOrInternalCaller, UserOrInternalEntity, UserOrInternalService,UserOrInternalServiceAuthorization,@@ -53,6 +57,8 @@ pub use user_api_key::USER_API_KEY_HEADER;pub enum ActingEntity<'a> {/// A directly authenticated bot.Bot(BotId),+ /// A directly authenticated harness.+ Harness(HarnessId),/// A directly authenticated Macro user.User(&'a str),/// An authenticated internal service.@@ -64,6 +70,7 @@ impl<'a> From<&'a MacroAuthorization> for ActingEntity<'a> {match authorization {MacroAuthorization::User(user) => Self::User(user.macro_user_id.as_ref()),MacroAuthorization::Bot(bot) => Self::Bot(bot.bot_id),+ MacroAuthorization::Harness(harness) => Self::Harness(harness.harness_id),MacroAuthorization::Internal(_) => Self::Internal,}}@@ -73,6 +80,7 @@ impl fmt::Display for ActingEntity<'_> {fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {match self {Self::Bot(bot_id) => bot_id.fmt(formatter),+ Self::Harness(harness_id) => harness_id.fmt(formatter),Self::User(user_id) => formatter.write_str(user_id.as_ref()),Self::Internal => formatter.write_str("internal"),}diff --git a/crates/macro_authorization/src/inbound/axum/harness.rs b/crates/macro_authorization/src/inbound/axum/harness.rsnew file mode 100644index 0000000000..be3f57ba1d--- /dev/null+++ b/crates/macro_authorization/src/inbound/axum/harness.rs@@ -0,0 +1,80 @@+use ::axum::{+ extract::FromRef,+ http::{HeaderMap, StatusCode, request::Parts},+};+use rootcause::Report;++use crate::{HarnessAuthentication, MacroAuthorizationError, MacroAuthorizationService};++use super::{MacroAuthorizationRejection, MacroAuthorizationState, rejection, status_rejection};++/// Header carrying a harness authentication token.+pub const HARNESS_TOKEN_HEADER: &str = "x-macro-harness-token";+/// Header carrying the Macro user ID a harness claims to act for.+pub const HARNESS_FOR_MACRO_USER_ID_HEADER: &str = "x-macro-harness-for-macro-user-id";++pub(super) async fn authorize_optional_harness_request<S, Svc>(+ parts: &Parts,+ state: &S,+) -> Result<Option<HarnessAuthentication>, MacroAuthorizationRejection>+where+ MacroAuthorizationState<Svc>: FromRef<S>,+ Svc: MacroAuthorizationService,+{+ let Some(token) = harness_token(&parts.headers)? else {+ return Ok(None);+ };+ let claim = harness_acting_user_claim(&parts.headers)?;+ let authorization = MacroAuthorizationState::<Svc>::from_ref(state);+ let harness = authorization+ .service+ .authorize_harness(&token, claim)+ .await+ .map_err(harness_authorization_rejection)?;++ Ok(Some(harness))+}++fn harness_token(headers: &HeaderMap) -> Result<Option<String>, MacroAuthorizationRejection> {+ let Some(header) = headers.get(HARNESS_TOKEN_HEADER) else {+ return Ok(None);+ };+ let token = header.to_str().map_err(|_| rejection("unauthorized"))?;+ if token.trim().is_empty() {+ return Err(rejection("unauthorized"));+ }++ Ok(Some(token.to_owned()))+}++fn harness_acting_user_claim(+ headers: &HeaderMap,+) -> Result<Option<String>, MacroAuthorizationRejection> {+ headers+ .get(HARNESS_FOR_MACRO_USER_ID_HEADER)+ .map(|header| {+ header+ .to_str()+ .map(str::to_owned)+ .map_err(|_| status_rejection(StatusCode::BAD_REQUEST, "invalid harness claims"))+ })+ .transpose()+}++fn harness_authorization_rejection(+ error: Report<MacroAuthorizationError>,+) -> MacroAuthorizationRejection {+ let rejection = match error.current_context() {+ MacroAuthorizationError::CredentialsExpired+ | MacroAuthorizationError::InvalidCredentials => rejection("unauthorized"),+ MacroAuthorizationError::ActingUserNotAuthorized+ | MacroAuthorizationError::BotScopeNotAuthorized => {+ status_rejection(StatusCode::FORBIDDEN, "forbidden")+ }+ MacroAuthorizationError::Unavailable => {+ status_rejection(StatusCode::INTERNAL_SERVER_ERROR, "internal server error")+ }+ };+ tracing::error!(error=?error, "harness authorization failed");+ rejection+}diff --git a/crates/macro_authorization/src/inbound/axum/macro_authorization.rs b/crates/macro_authorization/src/inbound/axum/macro_authorization.rsindex 07296835f9..b491f0289a 100644--- a/crates/macro_authorization/src/inbound/axum/macro_authorization.rs+++ b/crates/macro_authorization/src/inbound/axum/macro_authorization.rs@@ -10,6 +10,7 @@ use crate::{MacroAuthorization, MacroAuthorizationService};use super::{AuthorizationPolicy, MacroAuthorizationRejection, MacroAuthorizationState,bot::{BOT_TOKEN_HEADER, authorize_optional_bot_request},+ harness::{HARNESS_TOKEN_HEADER, authorize_optional_harness_request},internal::{authorize_internal_request, internal_header_convention},rejection, status_rejection,user::{authorize_optional_user_request, explicit_user_credential_present},@@ -73,10 +74,12 @@ wherelet internal_convention = internal_header_convention(&parts.headers);let has_bot_token = parts.headers.contains_key(BOT_TOKEN_HEADER);let has_user_api_key = parts.headers.contains_key(USER_API_KEY_HEADER);+ let has_harness_token = parts.headers.contains_key(HARNESS_TOKEN_HEADER);let has_explicit_user_credential = explicit_user_credential_present(parts);let explicit_credential_count = usize::from(internal_convention.is_some())+ usize::from(has_bot_token)+ usize::from(has_user_api_key)+ + usize::from(has_harness_token)+ usize::from(has_explicit_user_credential);if explicit_credential_count > 1 {@@ -102,6 +105,13 @@ wherereturn Ok(Some(MacroAuthorization::Bot(bot)));}+ if has_harness_token {+ let harness = authorize_optional_harness_request::<S, Svc>(parts, state)+ .await?+ .expect("harness token presence was checked");+ return Ok(Some(MacroAuthorization::Harness(harness)));+ }+authorize_optional_user_request::<S, Svc>(parts, state).await.map(|user| user.map(MacroAuthorization::User))diff --git a/crates/macro_authorization/src/inbound/axum/policy.rs b/crates/macro_authorization/src/inbound/axum/policy.rsindex 97f334a5f5..f75768d63d 100644--- a/crates/macro_authorization/src/inbound/axum/policy.rs+++ b/crates/macro_authorization/src/inbound/axum/policy.rs@@ -2,8 +2,11 @@ use std::fmt;use ::axum::http::StatusCode;use bot_id::BotId;+use harness_id::HarnessId;-use crate::{BotAuthentication, MacroAuthorization, MacroUserAuthentication};+use crate::{+ BotAuthentication, HarnessAuthentication, MacroAuthorization, MacroUserAuthentication,+};use super::{ActingEntity, MacroAuthorizationRejection, rejection, status_rejection};@@ -47,6 +50,12 @@ pub struct UserOrBot;/// Admits only authenticated bots.pub struct BotOnly;+/// Admits only authenticated harnesses.+pub struct HarnessOnly;++/// Admits directly authenticated users, bots, and harnesses.+pub struct UserBotOrHarness;+/// Admits only authenticated internal services.pub struct InternalOnly;@@ -124,6 +133,49 @@ impl UserOrBotAuthorization {}}+/// A directly authenticated user, bot, or harness.+#[derive(Clone, Debug)]+pub enum UserBotOrHarnessAuthorization {+ /// A directly authenticated user.+ User(MacroUserAuthentication),+ /// An authenticated bot, optionally acting for a user.+ Bot(BotAuthentication),+ /// An authenticated harness, acting for its verified user.+ Harness(HarnessAuthentication),+}++impl UserBotOrHarnessAuthorization {+ /// Return the authenticated or verified user the caller acts for, if any.+ pub fn acting_user(&self) -> Option<&MacroUserAuthentication> {+ match self {+ Self::User(user) => Some(user),+ Self::Bot(bot) => bot.acting_user.as_ref(),+ Self::Harness(harness) => Some(&harness.acting_user),+ }+ }+}++/// Acting entity for policies that admit users, bots, and harnesses.+#[derive(Clone, Copy, Debug, Eq, PartialEq)]+pub enum UserBotOrHarnessEntity<'a> {+ /// A directly authenticated Macro user.+ User(&'a str),+ /// An authenticated bot.+ Bot(BotId),+ /// An authenticated harness.+ Harness(HarnessId),+}++impl fmt::Display for UserBotOrHarnessEntity<'_> {+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {+ match self {+ Self::User(user_id) => formatter.write_str(user_id),+ Self::Bot(bot_id) => bot_id.fmt(formatter),+ Self::Harness(harness_id) => harness_id.fmt(formatter),+ }+ }+}+/// Any principal narrowed to its verified acting user.#[derive(Clone, Debug)]#[non_exhaustive]@@ -206,7 +258,7 @@ impl AuthorizationPolicy for UserOrInternal {caller: UserOrInternalCaller::Internal,}),MacroAuthorization::Internal(None) => Err(rejection("unauthorized")),- MacroAuthorization::Bot(_) => Err(forbidden()),+ MacroAuthorization::Bot(_) | MacroAuthorization::Harness(_) => Err(forbidden()),}}@@ -232,7 +284,7 @@ impl AuthorizationPolicy for UserOrInternalService {MacroAuthorization::Internal(user) => {Ok(UserOrInternalServiceAuthorization::Internal(user))}- MacroAuthorization::Bot(_) => Err(forbidden()),+ MacroAuthorization::Bot(_) | MacroAuthorization::Harness(_) => Err(forbidden()),}}@@ -278,7 +330,9 @@ impl AuthorizationPolicy for UserOnly {) -> Result<Self::Output, MacroAuthorizationRejection> {match authorization {MacroAuthorization::User(user) => Ok(user),- MacroAuthorization::Bot(_) | MacroAuthorization::Internal(_) => Err(forbidden()),+ MacroAuthorization::Bot(_)+ | MacroAuthorization::Harness(_)+ | MacroAuthorization::Internal(_) => Err(forbidden()),}}@@ -297,7 +351,7 @@ impl AuthorizationPolicy for UserOrBot {match authorization {MacroAuthorization::User(user) => Ok(UserOrBotAuthorization::User(user)),MacroAuthorization::Bot(bot) => Ok(UserOrBotAuthorization::Bot(bot)),- MacroAuthorization::Internal(_) => Err(forbidden()),+ MacroAuthorization::Harness(_) | MacroAuthorization::Internal(_) => Err(forbidden()),}}@@ -320,7 +374,9 @@ impl AuthorizationPolicy for BotOnly {) -> Result<Self::Output, MacroAuthorizationRejection> {match authorization {MacroAuthorization::Bot(bot) => Ok(bot),- MacroAuthorization::User(_) | MacroAuthorization::Internal(_) => Err(forbidden()),+ MacroAuthorization::User(_)+ | MacroAuthorization::Harness(_)+ | MacroAuthorization::Internal(_) => Err(forbidden()),}}@@ -329,6 +385,56 @@ impl AuthorizationPolicy for BotOnly {}}+impl AuthorizationPolicy for HarnessOnly {+ type Output = HarnessAuthentication;+ type ActingEntity<'a> = HarnessId;++ fn narrow(+ authorization: MacroAuthorization,+ ) -> Result<Self::Output, MacroAuthorizationRejection> {+ match authorization {+ MacroAuthorization::Harness(harness) => Ok(harness),+ MacroAuthorization::User(_)+ | MacroAuthorization::Bot(_)+ | MacroAuthorization::Internal(_) => Err(forbidden()),+ }+ }++ fn acting_entity(output: &Self::Output) -> Self::ActingEntity<'_> {+ output.harness_id+ }+}++impl AuthorizationPolicy for UserBotOrHarness {+ type Output = UserBotOrHarnessAuthorization;+ type ActingEntity<'a> = UserBotOrHarnessEntity<'a>;++ fn narrow(+ authorization: MacroAuthorization,+ ) -> Result<Self::Output, MacroAuthorizationRejection> {+ match authorization {+ MacroAuthorization::User(user) => Ok(UserBotOrHarnessAuthorization::User(user)),+ MacroAuthorization::Bot(bot) => Ok(UserBotOrHarnessAuthorization::Bot(bot)),+ MacroAuthorization::Harness(harness) => {+ Ok(UserBotOrHarnessAuthorization::Harness(harness))+ }+ MacroAuthorization::Internal(_) => Err(forbidden()),+ }+ }++ fn acting_entity(output: &Self::Output) -> Self::ActingEntity<'_> {+ match output {+ UserBotOrHarnessAuthorization::User(user) => {+ UserBotOrHarnessEntity::User(user.macro_user_id.as_ref())+ }+ UserBotOrHarnessAuthorization::Bot(bot) => UserBotOrHarnessEntity::Bot(bot.bot_id),+ UserBotOrHarnessAuthorization::Harness(harness) => {+ UserBotOrHarnessEntity::Harness(harness.harness_id)+ }+ }+ }+}+impl AuthorizationPolicy for InternalOnly {type Output = InternalAuthorization;type ActingEntity<'a> = InternalEntity;@@ -338,7 +444,9 @@ impl AuthorizationPolicy for InternalOnly {) -> Result<Self::Output, MacroAuthorizationRejection> {match authorization {MacroAuthorization::Internal(acting_user) => Ok(InternalAuthorization { acting_user }),- MacroAuthorization::User(_) | MacroAuthorization::Bot(_) => Err(forbidden()),+ MacroAuthorization::User(_)+ | MacroAuthorization::Bot(_)+ | MacroAuthorization::Harness(_) => Err(forbidden()),}}@@ -375,6 +483,8 @@ mod sealed {impl Sealed for super::UserOnly {}impl Sealed for super::UserOrBot {}impl Sealed for super::BotOnly {}+ impl Sealed for super::HarnessOnly {}+ impl Sealed for super::UserBotOrHarness {}impl Sealed for super::InternalOnly {}impl Sealed for super::AnyPrincipal {}}diff --git a/crates/macro_authorization/src/lib.rs b/crates/macro_authorization/src/lib.rsindex 72d15d56b2..299783dbac 100644--- a/crates/macro_authorization/src/lib.rs+++ b/crates/macro_authorization/src/lib.rs@@ -28,6 +28,8 @@//! | [`UserOnly`] | Directly authenticated user | [`MacroUserAuthentication`] |//! | [`UserOrBot`] | Directly authenticated user or bot | [`UserOrBotAuthorization`] |//! | [`BotOnly`] | Bot, with optional acting user | [`BotAuthentication`] |+//! | [`UserBotOrHarness`] | Directly authenticated user, bot, or harness | [`UserBotOrHarnessAuthorization`] |+//! | [`HarnessOnly`] | Harness, acting for its verified user | [`HarnessAuthentication`] |//! | [`InternalOnly`] | Internal service, with optional acting user | [`InternalAuthorization`] |//! | [`AnyPrincipal`] | Any authenticated principal | [`MacroAuthorization`] |//!@@ -58,15 +60,18 @@ pub mod outbound;pub use domain::{bot_authorizer::BotAuthorizerService,+ harness_authorizer::HarnessAuthorizerService,models::{BotActingUserClaims, BotAuthentication, BotAuthorizationOwner, BotScope,- BotTokenAuthorization, InternalAuthConfig, InternalIdentityClaims, MacroAuthorization,+ BotTokenAuthorization, HarnessAuthentication, HarnessAuthorizationOwner,+ HarnessTokenAuthorization, InternalAuthConfig, InternalIdentityClaims, MacroAuthorization,MacroAuthorizationError, MacroUserAuthentication, ResolvedApiKeyUser,ResolvedBotActingUser, ValidatedIdentity,},ports::{- BotAuthorizationRepo, BotAuthorizer, JwtValidator, MacroAuthorizationService,- NoBotAuthorizer, NoUserApiKeyAuthorizer, UserApiKeyAuthorizationRepo, UserApiKeyAuthorizer,+ BotAuthorizationRepo, BotAuthorizer, HarnessAuthorizationRepo, HarnessAuthorizer,+ JwtValidator, MacroAuthorizationService, NoBotAuthorizer, NoHarnessAuthorizer,+ NoUserApiKeyAuthorizer, UserApiKeyAuthorizationRepo, UserApiKeyAuthorizer,},service::MacroAuthorizationServiceImpl,user_api_key_authorizer::UserApiKeyAuthorizerService,@@ -78,14 +83,16 @@ pub use inbound::{ActingEntity, ActingUser, ActingUserAuthorization, AnyPrincipal, AuthorizationPolicy,BOT_FOR_FUSIONAUTH_USER_ID_HEADER, BOT_FOR_MACRO_USER_ID_HEADER,BOT_FOR_ORGANIZATION_ID_HEADER, BOT_SCOPE_HEADER, BOT_TOKEN_HEADER, BotOnly,- INTERNAL_API_KEY_HEADER, INTERNAL_FUSIONAUTH_USER_ID_HEADER,- INTERNAL_MACRO_ORGANIZATION_ID_HEADER, INTERNAL_MACRO_USER_ID_HEADER, InternalAuthorization,- InternalEntity, InternalOnly, LEGACY_DSS_INTERNAL_API_KEY_HEADER,- LEGACY_DSS_INTERNAL_MACRO_USER_ID_HEADER, MacroAuthorizationExtractor,- MacroAuthorizationRejection, MacroAuthorizationState, OptionalMacroAuthorizationExtractor,- USER_API_KEY_HEADER, UserOnly, UserOrBot, UserOrBotAuthorization, UserOrBotEntity,- UserOrInternal, UserOrInternalAuthorization, UserOrInternalCaller, UserOrInternalEntity,- UserOrInternalService, UserOrInternalServiceAuthorization,+ HARNESS_FOR_MACRO_USER_ID_HEADER, HARNESS_TOKEN_HEADER, HarnessOnly, INTERNAL_API_KEY_HEADER,+ INTERNAL_FUSIONAUTH_USER_ID_HEADER, INTERNAL_MACRO_ORGANIZATION_ID_HEADER,+ INTERNAL_MACRO_USER_ID_HEADER, InternalAuthorization, InternalEntity, InternalOnly,+ LEGACY_DSS_INTERNAL_API_KEY_HEADER, LEGACY_DSS_INTERNAL_MACRO_USER_ID_HEADER,+ MacroAuthorizationExtractor, MacroAuthorizationRejection, MacroAuthorizationState,+ OptionalMacroAuthorizationExtractor, USER_API_KEY_HEADER, UserBotOrHarness,+ UserBotOrHarnessAuthorization, UserBotOrHarnessEntity, UserOnly, UserOrBot,+ UserOrBotAuthorization, UserOrBotEntity, UserOrInternal, UserOrInternalAuthorization,+ UserOrInternalCaller, UserOrInternalEntity, UserOrInternalService,+ UserOrInternalServiceAuthorization,};/// JWT validation adapters for user-authenticated and internal-only services.#[cfg(feature = "outbound")]@@ -95,3 +102,6 @@ pub use outbound::{MacroAuthJwtValidator, NoopMacroAuthJwtValidator};pub use outbound::{PgBotAuthorizationRepo, PgBotAuthorizer, PgUserApiKeyAuthorizationRepo, PgUserApiKeyAuthorizer,};+/// PostgreSQL harness authorization repository and concrete authorizer.+#[cfg(feature = "postgres")]+pub use outbound::{PgHarnessAuthorizationRepo, PgHarnessAuthorizer};diff --git a/crates/macro_authorization/src/outbound.rs b/crates/macro_authorization/src/outbound.rsindex 12ba7ef72f..4b7594bdec 100644--- a/crates/macro_authorization/src/outbound.rs+++ b/crates/macro_authorization/src/outbound.rs@@ -9,6 +9,9 @@ pub mod noop;/// PostgreSQL facts for bot authorization.#[cfg(feature = "postgres")]pub mod pg_bot_authorization;+/// PostgreSQL facts for harness authorization.+#[cfg(feature = "postgres")]+pub mod pg_harness_authorization;/// PostgreSQL facts for user API key authorization.#[cfg(feature = "postgres")]pub mod pg_user_api_key_authorization;@@ -22,6 +25,9 @@ pub use noop::NoopMacroAuthJwtValidator;/// PostgreSQL bot authorization repository and concrete authorizer.#[cfg(feature = "postgres")]pub use pg_bot_authorization::{PgBotAuthorizationRepo, PgBotAuthorizer};+/// PostgreSQL harness authorization repository and concrete authorizer.+#[cfg(feature = "postgres")]+pub use pg_harness_authorization::{PgHarnessAuthorizationRepo, PgHarnessAuthorizer};/// PostgreSQL user API key authorization repository and concrete authorizer.#[cfg(feature = "postgres")]pub use pg_user_api_key_authorization::{PgUserApiKeyAuthorizationRepo, PgUserApiKeyAuthorizer};diff --git a/crates/macro_authorization/src/outbound/pg_harness_authorization.rs b/crates/macro_authorization/src/outbound/pg_harness_authorization.rsnew file mode 100644index 0000000000..f39910e41b--- /dev/null+++ b/crates/macro_authorization/src/outbound/pg_harness_authorization.rs@@ -0,0 +1,185 @@+//! PostgreSQL harness authorization facts.++#[cfg(test)]+mod test;++use harness_id::HarnessId;+use macro_user_id::user_id::MacroUserIdStr;+use sqlx::PgPool;+use thiserror::Error;+use uuid::Uuid;++use crate::domain::{+ models::{HarnessAuthorizationOwner, HarnessTokenAuthorization, ResolvedBotActingUser},+ ports::HarnessAuthorizationRepo,+};++/// PostgreSQL facts required by harness authorization policy.+#[derive(Clone, Debug)]+pub struct PgHarnessAuthorizationRepo {+ pool: PgPool,+}++impl PgHarnessAuthorizationRepo {+ /// Create a PostgreSQL harness authorization repository.+ pub fn new(pool: PgPool) -> Self {+ Self { pool }+ }+}++/// Harness authorizer backed by PostgreSQL.+pub type PgHarnessAuthorizer =+ crate::domain::harness_authorizer::HarnessAuthorizerService<PgHarnessAuthorizationRepo>;++/// PostgreSQL harness authorization repository error.+#[derive(Debug, Error)]+pub enum PgHarnessAuthorizationRepoError {+ /// A database operation failed.+ #[error("harness authorization database operation failed")]+ Database(#[from] sqlx::Error),+ /// Persisted harness ownership data violated its schema invariant.+ #[error("invalid persisted harness ownership data")]+ InvalidHarnessOwner,+ /// Persisted user data could not be represented as a Macro user identifier.+ #[error("invalid persisted user email")]+ InvalidUserEmail,+}++#[derive(Debug)]+struct HarnessTokenAuthorizationRow {+ token_id: Uuid,+ harness_id: Uuid,+ owner_user_id: Option<String>,+ team_id: Option<Uuid>,+ created_by: String,+}++impl TryFrom<HarnessTokenAuthorizationRow> for HarnessTokenAuthorization {+ type Error = PgHarnessAuthorizationRepoError;++ fn try_from(row: HarnessTokenAuthorizationRow) -> Result<Self, Self::Error> {+ let owner = match (row.owner_user_id, row.team_id) {+ (Some(user_id), None) => HarnessAuthorizationOwner::User { user_id },+ (None, Some(team_id)) => HarnessAuthorizationOwner::Team { team_id },+ _ => return Err(PgHarnessAuthorizationRepoError::InvalidHarnessOwner),+ };++ Ok(Self {+ harness_id: HarnessId::new_from_uuid(row.harness_id),+ token_id: row.token_id,+ owner,+ created_by: row.created_by,+ })+ }+}++#[derive(Debug)]+struct UserRow {+ fusion_user_id: String,+ email: String,+ organization_id: Option<i32>,+}++impl TryFrom<UserRow> for ResolvedBotActingUser {+ type Error = PgHarnessAuthorizationRepoError;++ fn try_from(row: UserRow) -> Result<Self, Self::Error> {+ Ok(Self {+ macro_user_id: MacroUserIdStr::try_from_email(&row.email)+ .map_err(|_| PgHarnessAuthorizationRepoError::InvalidUserEmail)?,+ fusion_user_id: row.fusion_user_id,+ organization_id: row.organization_id,+ })+ }+}++impl HarnessAuthorizationRepo for PgHarnessAuthorizationRepo {+ type Err = PgHarnessAuthorizationRepoError;++ async fn find_valid_harness_token(+ &self,+ token: &str,+ ) -> Result<Option<HarnessTokenAuthorization>, Self::Err> {+ let token_hash = harness_token::hash_token(token);+ let row = sqlx::query_as!(+ HarnessTokenAuthorizationRow,+ r#"+ SELECT+ ht.id AS token_id,+ h.id AS harness_id,+ h.owner_user_id,+ h.team_id,+ h.created_by+ FROM harness_tokens ht+ JOIN harnesses h ON h.id = ht.harness_id+ WHERE ht.token_hash = $1+ AND ht.revoked_at IS NULL+ AND h.deleted_at IS NULL+ "#,+ &token_hash[..],+ )+ .fetch_optional(&self.pool)+ .await?;++ row.map(HarnessTokenAuthorization::try_from).transpose()+ }++ async fn mark_harness_token_used(&self, token_id: Uuid) -> Result<(), Self::Err> {+ sqlx::query!(+ r#"+ UPDATE harness_tokens+ SET last_used_at = now()+ WHERE id = $1+ "#,+ token_id,+ )+ .execute(&self.pool)+ .await?;++ Ok(())+ }++ async fn find_user(+ &self,+ macro_user_id: &str,+ ) -> Result<Option<ResolvedBotActingUser>, Self::Err> {+ let Ok(macro_user_id) = MacroUserIdStr::try_from(macro_user_id) else {+ return Ok(None);+ };++ let row = sqlx::query_as!(+ UserRow,+ r#"+ SELECT+ id AS fusion_user_id,+ email,+ "organizationId" AS "organization_id?"+ FROM "User"+ WHERE email = $1+ "#,+ macro_user_id.email_str(),+ )+ .fetch_optional(&self.pool)+ .await?;++ row.map(ResolvedBotActingUser::try_from).transpose()+ }++ async fn user_has_team(&self, fusion_user_id: &str, team_id: Uuid) -> Result<bool, Self::Err> {+ let has_team = sqlx::query_scalar!(+ r#"+ SELECT EXISTS (+ SELECT 1+ FROM team_user+ WHERE user_id = $1 AND team_id = $2+ ) AS "has_team!"+ "#,+ fusion_user_id,+ team_id,+ )+ .fetch_one(&self.pool)+ .await?;++ Ok(has_team)+ }+}diff --git a/crates/macro_authorization/src/outbound/pg_harness_authorization/test.rs b/crates/macro_authorization/src/outbound/pg_harness_authorization/test.rsnew file mode 100644index 0000000000..f3a5ad1dc5--- /dev/null+++ b/crates/macro_authorization/src/outbound/pg_harness_authorization/test.rs@@ -0,0 +1,212 @@+use macro_db_migrator::MACRO_DB_MIGRATIONS;+use sqlx::PgPool;++use super::*;+use crate::domain::ports::HarnessAuthorizationRepo as _;++const TOKEN: &str = "mhns_authorization_test_secret";+const USER_ID: &str = "macro|[email protected]";+const USER_EMAIL: &str = "[email protected]";+const FUSION_USER_ID: &str = "fusion-harness-authorization";++async fn insert_harness_token(+ pool: &PgPool,+ owner_user_id: Option<&str>,+ team_id: Option<Uuid>,+ revoked: bool,+) -> (Uuid, Uuid) {+ let harness_id = Uuid::new_v4();+ let token_id = Uuid::new_v4();+ sqlx::query!(+ r#"+ INSERT INTO harnesses (id, kind, name, owner_user_id, team_id, created_by)+ VALUES ($1, 'macrod', 'Authorization harness', $2, $3, $4)+ "#,+ harness_id,+ owner_user_id,+ team_id,+ USER_ID,+ )+ .execute(pool)+ .await+ .unwrap();+ let hashed = harness_token::HashedHarnessToken::from_raw(TOKEN);+ sqlx::query!(+ r#"+ INSERT INTO harness_tokens (id, harness_id, token_hash, token_prefix, revoked_at)+ VALUES ($1, $2, $3, $4, CASE WHEN $5 THEN now() ELSE NULL END)+ "#,+ token_id,+ harness_id,+ &hashed.hash[..],+ hashed.prefix,+ revoked,+ )+ .execute(pool)+ .await+ .unwrap();+ (harness_id, token_id)+}++async fn insert_user(pool: &PgPool) {+ let macro_user_id = Uuid::new_v4();+ sqlx::query!(+ r#"+ INSERT INTO macro_user (id, username, email, stripe_customer_id)+ VALUES ($1, $2, $2, $3)+ "#,+ macro_user_id,+ USER_EMAIL,+ format!("stripe_{macro_user_id}"),+ )+ .execute(pool)+ .await+ .unwrap();+ sqlx::query!(+ r#"+ INSERT INTO "User" (id, email, macro_user_id)+ VALUES ($1, $2, $3)+ "#,+ FUSION_USER_ID,+ USER_EMAIL,+ macro_user_id,+ )+ .execute(pool)+ .await+ .unwrap();+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn finds_valid_token_owner_and_marks_usage(pool: PgPool) {+ let (harness_id, token_id) = insert_harness_token(&pool, Some(USER_ID), None, false).await;+ let repo = PgHarnessAuthorizationRepo::new(pool.clone());++ let token = repo+ .find_valid_harness_token(TOKEN)+ .await+ .unwrap()+ .expect("valid token");+ assert_eq!(token.harness_id.as_uuid(), harness_id);+ assert_eq!(token.token_id, token_id);+ assert_eq!(+ token.owner,+ HarnessAuthorizationOwner::User {+ user_id: USER_ID.to_string()+ }+ );+ assert_eq!(token.created_by, USER_ID);++ repo.mark_harness_token_used(token_id).await.unwrap();+ let last_used_at = sqlx::query_scalar!(+ r#"SELECT last_used_at FROM harness_tokens WHERE id = $1"#,+ token_id,+ )+ .fetch_one(&pool)+ .await+ .unwrap();+ assert!(last_used_at.is_some());+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn team_owned_harness_reports_its_team(pool: PgPool) {+ insert_user(&pool).await;+ let team_id = Uuid::new_v4();+ sqlx::query!(+ r#"INSERT INTO team (id, name, owner_id) VALUES ($1, 'Harness team', $2)"#,+ team_id,+ FUSION_USER_ID,+ )+ .execute(&pool)+ .await+ .unwrap();+ insert_harness_token(&pool, None, Some(team_id), false).await;++ let repo = PgHarnessAuthorizationRepo::new(pool);+ let token = repo+ .find_valid_harness_token(TOKEN)+ .await+ .unwrap()+ .expect("valid token");+ assert_eq!(token.owner, HarnessAuthorizationOwner::Team { team_id });+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn rejects_unknown_revoked_and_deleted_harness_tokens(pool: PgPool) {+ let repo = PgHarnessAuthorizationRepo::new(pool.clone());+ assert!(+ repo.find_valid_harness_token("unknown")+ .await+ .unwrap()+ .is_none()+ );++ insert_harness_token(&pool, Some(USER_ID), None, true).await;+ assert!(+ repo.find_valid_harness_token(TOKEN)+ .await+ .unwrap()+ .is_none()+ );++ sqlx::query!("UPDATE harness_tokens SET revoked_at = NULL")+ .execute(&pool)+ .await+ .unwrap();+ sqlx::query!("UPDATE harnesses SET deleted_at = now()")+ .execute(&pool)+ .await+ .unwrap();+ assert!(+ repo.find_valid_harness_token(TOKEN)+ .await+ .unwrap()+ .is_none()+ );+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn resolves_users_by_macro_identifier(pool: PgPool) {+ insert_user(&pool).await;+ let repo = PgHarnessAuthorizationRepo::new(pool);++ let user = repo.find_user(USER_ID).await.unwrap().expect("user");+ assert_eq!(user.macro_user_id.as_ref(), USER_ID);+ assert_eq!(user.fusion_user_id, FUSION_USER_ID);++ assert!(repo.find_user("not-a-macro-id").await.unwrap().is_none());+ assert!(+ repo.find_user("macro|[email protected]")+ .await+ .unwrap()+ .is_none()+ );+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn checks_current_team_membership(pool: PgPool) {+ insert_user(&pool).await;+ let team_id = Uuid::new_v4();+ sqlx::query!(+ r#"INSERT INTO team (id, name, owner_id) VALUES ($1, 'Harness team', $2)"#,+ team_id,+ FUSION_USER_ID,+ )+ .execute(&pool)+ .await+ .unwrap();+ sqlx::query!(+ r#"+ INSERT INTO team_user (user_id, team_id, team_role)+ VALUES ($1, $2, 'member'::team_role)+ "#,+ FUSION_USER_ID,+ team_id,+ )+ .execute(&pool)+ .await+ .unwrap();++ let repo = PgHarnessAuthorizationRepo::new(pool);+ assert!(repo.user_has_team(FUSION_USER_ID, team_id).await.unwrap());+ assert!(!repo.user_has_team("someone-else", team_id).await.unwrap());+}diff --git a/crates/macro_db_client/migrations/20260831201832_create_harnesses.down.sql b/crates/macro_db_client/migrations/20260831201832_create_harnesses.down.sqlnew file mode 100644index 0000000000..b92672371f--- /dev/null+++ b/crates/macro_db_client/migrations/20260831201832_create_harnesses.down.sql@@ -0,0 +1,12 @@+-- Reverse of create_harnesses: unbind agents first, then drop the harness+-- tables in dependency order (pairing requests and tokens reference+-- harnesses). Destroys registered harnesses, their credentials, and any open+-- pairings; agents bound to a harness lose the binding, and the slug check is+-- lifted with the column.+ALTER TABLE agent_configs+ DROP CONSTRAINT agent_configs_harness_id_slug_check,+ DROP COLUMN harness_id;++DROP TABLE public.harness_pairing_requests;+DROP TABLE public.harness_tokens;+DROP TABLE public.harnesses;diff --git a/crates/macro_db_client/migrations/20260831201832_create_harnesses.up.sql b/crates/macro_db_client/migrations/20260831201832_create_harnesses.up.sqlnew file mode 100644index 0000000000..5c5e75af83--- /dev/null+++ b/crates/macro_db_client/migrations/20260831201832_create_harnesses.up.sql@@ -0,0 +1,94 @@+-- User-run agent harnesses (macrod daemons) and their credentials.+--+-- A harness is the machine-side runtime an agent's sessions execute on. It is+-- owned by exactly one user (private) or one team (shared with every member),+-- mirroring the bots owner-XOR pattern. Rows are soft-deleted so revoked+-- harnesses stay auditable.+CREATE TABLE public.harnesses (+ id uuid PRIMARY KEY,+ kind text NOT NULL DEFAULT 'macrod' CHECK (kind IN ('macrod')),+ name text NOT NULL CHECK (name <> ''),+ owner_user_id text,+ team_id uuid REFERENCES public.team(id) ON DELETE CASCADE,+ created_by text NOT NULL,+ created_at timestamptz NOT NULL DEFAULT now(),+ updated_at timestamptz NOT NULL DEFAULT now(),+ deleted_at timestamptz,+ -- Presence bookkeeping written by the runtime gateway on socket+ -- attach/detach. Connected means last_connected_at is the newer of the two.+ last_connected_at timestamptz,+ last_disconnected_at timestamptz,+ CONSTRAINT harnesses_owner_check CHECK (+ (owner_user_id IS NOT NULL)::int + (team_id IS NOT NULL)::int = 1+ )+);++CREATE INDEX harnesses_owner_user_id_idx+ ON public.harnesses (owner_user_id)+ WHERE deleted_at IS NULL;++CREATE INDEX harnesses_team_id_idx+ ON public.harnesses (team_id)+ WHERE deleted_at IS NULL;++-- Bearer credentials a harness daemon authenticates with. Only the SHA-256 of+-- the raw token is stored; the raw secret is shown once at pairing claim.+CREATE TABLE public.harness_tokens (+ id uuid PRIMARY KEY,+ harness_id uuid NOT NULL REFERENCES public.harnesses(id) ON DELETE CASCADE,+ token_hash bytea NOT NULL,+ token_prefix text NOT NULL,+ last_used_at timestamptz,+ revoked_at timestamptz,+ created_at timestamptz NOT NULL DEFAULT now()+);++CREATE INDEX harness_tokens_harness_id_idx ON public.harness_tokens (harness_id);+CREATE UNIQUE INDEX harness_tokens_token_hash_uq ON public.harness_tokens (token_hash);++-- Device-code pairing requests. A daemon creates one unauthenticated, the user+-- approves it in the web app (creating the harness row), and the daemon claims+-- the credential with the device secret it kept. The raw harness token is+-- minted at claim time, never stored.+CREATE TABLE public.harness_pairing_requests (+ id uuid PRIMARY KEY,+ code text NOT NULL UNIQUE,+ device_secret_hash bytea NOT NULL,+ requested_name text NOT NULL CHECK (requested_name <> ''),+ host_info text,+ -- The scope the daemon's config asked for. Advisory: the approving user+ -- still confirms it in the dialog, which arrives preselected to this.+ -- Null for daemons that predate the field.+ requested_scope text CHECK (requested_scope IN ('private', 'team')),+ status text NOT NULL DEFAULT 'pending'+ CHECK (status IN ('pending', 'approved', 'claimed')),+ -- Cascade: pairing rows are ephemeral bookkeeping, and an approved row is+ -- deliberately never garbage-collected — without the cascade it would+ -- block the team-delete path that hard-deletes team harnesses.+ harness_id uuid REFERENCES public.harnesses(id) ON DELETE CASCADE,+ approved_by text,+ expires_at timestamptz NOT NULL,+ claimed_at timestamptz,+ created_at timestamptz NOT NULL DEFAULT now()+);++CREATE INDEX harness_pairing_requests_expires_at_idx+ ON public.harness_pairing_requests (expires_at);++-- Bind agents to registered harnesses.+--+-- `agent_configs.harness` stays the runtime slug ('in-memory', 'cursor', ...).+-- An agent served by a user-run macrod daemon stores the sentinel slug+-- 'macrod' plus the registered harness row it runs on. The check keeps a+-- harness_id from ever riding along with a managed runtime slug; the reverse+-- is allowed — a macrod agent with a null harness_id is unbound, which is+-- what SET NULL leaves behind when its harness is hard-deleted (a member's+-- personal agent must survive its team's deletion; it can be rebound later).+ALTER TABLE agent_configs+ ADD COLUMN harness_id uuid REFERENCES public.harnesses(id) ON DELETE SET NULL,+ ADD CONSTRAINT agent_configs_harness_id_slug_check+ CHECK (harness_id IS NULL OR harness = 'macrod');++-- Sessions do not copy the binding: routing resolves the agent's current+-- harness_id at bind time, so rebinding an agent re-routes existing sessions.+CREATE INDEX agent_configs_harness_id_idx ON agent_configs (harness_id);diff --git a/packages/sdk/generated/storage/index.ts b/packages/sdk/generated/storage/index.tsindex aac63c2f92..f67d820cbd 100644--- a/packages/sdk/generated/storage/index.ts+++ b/packages/sdk/generated/storage/index.ts@@ -1,4 +1,4 @@// This file is auto-generated by @hey-api/openapi-tsexport { type Options, Sdk } from './sdk.gen';-export type { AccessLevel, ActiveCallsResponse, ActiveCallSummary, ActivityType, AddFavoriteData, AddFavoriteError, AddFavoriteErrors, AddFavoriteRequest, AddFavoriteResponse, AddFavoriteResponses, AddParticipantsData, AddParticipantsError, AddParticipantsErrors, AddParticipantsRequest, AddParticipantsResponses, AddPinHandlerData, AddPinHandlerError, AddPinHandlerErrors, AddPinHandlerResponse, AddPinHandlerResponses, AddPinRequest, Agent, AgentChannelScope, Anchor, AnchorId, AnchorRequest, AnchorResponse, AnnotationIncrementalUpdate, ApiActivity, ApiAttachmentChannelReference, ApiAttachmentEntityReference, ApiAttachmentGenericReference, ApiChannelAttachment, ApiChannelAttachmentsPage, ApiChannelContextMessage, ApiChannelDetail, ApiChannelListMessage, ApiChannelListPage, ApiChannelListParticipant, ApiChannelListType, ApiChannelMessage, ApiChannelMessageKind, ApiChannelMessagesPage, ApiChannelParticipant, ApiChannelWithLatest, ApiCountedReaction, ApiEntityFilterAst, ApiGroupByField, ApiGroupMeta, ApiMessageAttachment, ApiMessageSender, ApiMessageSenderType, ApiParticipantListRole, ApiParticipantRole, ApiPropertyEntityType, ApiResolvedChannelMessage, ApiThreadInfo, ApiThreadReply, AttendeeResponseStatus, BasicDocument, BasicDocumentSubType, BomPart, Bot, BotChannel, BotChannelType, BotId, BotKind, BotOwner, BotToken, BranchNameResponse, BTreeMap, BulkWakeupRequest, BulkWakeupResponse, BulkWakeupSyncServiceDocumentsData, BulkWakeupSyncServiceDocumentsErrors, BulkWakeupSyncServiceDocumentsResponse, BulkWakeupSyncServiceDocumentsResponses, CalendarAttendee, CalendarEvent, CalendarEventFilters, CalendarMentionEvent, CalendarMentionPreviewItem, CalendarMentionPreviewKind, CalendarMentionPreviewRequest, CalendarMentionPreviewRequestItem, CalendarMentionPreviewResponse, CalendarOccurrence, CalendarOccurrenceItem, CalendarOccurrenceResponse, CalendarSyncStatus, CallActiveResponse, CallFilters, CallRecord, CallRecordParticipant, CallRecordPreview, CallRecordPreviewData, CallRecordTranscriptSegment, CallStatus, CallTokenResponse, CallWebhookData, CallWebhookError, CallWebhookErrors, CallWebhookResponses, Channel, ChannelCreatedMetadata, ChannelDeletedMetadata, ChannelEventAttachment, ChannelFilters, ChannelJoinCodeResponse, ChannelMentionedMetadata, ChannelMessage, ChannelMessageAttachmentCreatedMetadata, ChannelMessageAttachmentRemovedMetadata, ChannelMessageDeletedMetadata, ChannelMessageFilters, ChannelMessagePatchedMetadata, ChannelMessagePostedMetadata, ChannelParticipant, ChannelParticipantAddedMetadata, ChannelParticipantRemovedMetadata, ChannelPreview, ChannelPreviewData, ChannelSender, ChannelSharePermission, ChannelThreadFilters, ChannelTopicEvent, ChannelType, ChannelUpdatedMetadata, ChannelWebhookRequest, ChannelWebhookResponse, ChannelWithParticipants, Chat, ChatFilters, CheckActiveCallData, CheckActiveCallError, CheckActiveCallErrors, CheckActiveCallResponse, CheckActiveCallResponses, ClientOptions, CloudStorageItemType, CollabSurfaceResponse, CollabSurfaceTokenResponse, Comment, CommentThread, ConferenceProvider, CopyDocumentData, CopyDocumentError, CopyDocumentErrors, CopyDocumentQueryParams, CopyDocumentRequest, CopyDocumentResponse, CopyDocumentResponse2, CopyDocumentResponses, CreateAgentData, CreateAgentError, CreateAgentErrors, CreateAgentRequest, CreateAgentResponse, CreateAgentResponses, CreateAnchorData, CreateAnchorError, CreateAnchorErrors, CreateAnchorResponse, CreateAnchorResponses, CreateBotRequest, CreateBulkDocumentResponse, CreateBulkDocumentResponseData, CreateChannelData, CreateChannelError, CreateChannelErrors, CreateChannelRequest, CreateChannelResponse, CreateChannelResponse2, CreateChannelResponses, CreateChannelScopedBotData, CreateChannelScopedBotError, CreateChannelScopedBotErrors, CreateChannelScopedBotRequest, CreateChannelScopedBotResponse, CreateChannelScopedBotResponse2, CreateChannelScopedBotResponses, CreateCollabSurfaceTokenData, CreateCollabSurfaceTokenError, CreateCollabSurfaceTokenErrors, CreateCollabSurfaceTokenResponse, CreateCollabSurfaceTokenResponses, CreateCommentData, CreateCommentError, CreateCommentErrors, CreateCommentRequest, CreateCommentResponse, CreateCommentResponse2, CreateCommentResponses, CreateCrmCommentData, CreateCrmCommentError, CreateCrmCommentErrors, CreateCrmCommentRequest, CreateCrmCommentResponse, CreateCrmCommentResponses, CreateCrmCompanyData, CreateCrmCompanyError, CreateCrmCompanyErrors, CreateCrmCompanyRequest, CreateCrmCompanyResponse, CreateCrmCompanyResponses, CreateCrmContactData, CreateCrmContactError, CreateCrmContactErrors, CreateCrmContactRequest, CreateCrmContactResponse, CreateCrmContactResponses, CreateDocumentData, CreateDocumentError, CreateDocumentErrors, CreateDocumentRequest, CreateDocumentResponse, CreateDocumentResponseData, CreateDocumentResponses, CreatedUserApiKey, CreateEntityMentionData, CreateEntityMentionError, CreateEntityMentionErrors, CreateEntityMentionRequest, CreateEntityMentionResponse, CreateEntityMentionResponse2, CreateEntityMentionResponses, CreateInstructionsDocumentResponse, CreateInstructionsHandlerData, CreateInstructionsHandlerError, CreateInstructionsHandlerErrors, CreateInstructionsHandlerResponse, CreateInstructionsHandlerResponses, CreateMarkdownDocumentRequest, CreateMarkdownDocumentResponse, CreateMarkdownHandlerData, CreateMarkdownHandlerError, CreateMarkdownHandlerErrors, CreateMarkdownHandlerResponse, CreateMarkdownHandlerResponses, CreateProjectHandlerData, CreateProjectHandlerError, CreateProjectHandlerErrors, CreateProjectHandlerResponse, CreateProjectHandlerResponses, CreateProjectRequest, CreateProjectResponse, CreateReminderData, CreateReminderError, CreateReminderErrors, CreateReminderRequest, CreateReminderResponse, CreateReminderResponses, CreateSkillHandlerData, CreateSkillHandlerError, CreateSkillHandlerErrors, CreateSkillHandlerResponse, CreateSkillHandlerResponses, CreateSkillRequest, CreateSkillResponse, CreateSnippetHandlerData, CreateSnippetHandlerError, CreateSnippetHandlerErrors, CreateSnippetHandlerResponse, CreateSnippetHandlerResponses, CreateSnippetRequest, CreateSnippetResponse, CreateTaskHandlerData, CreateTaskHandlerError, CreateTaskHandlerErrors, CreateTaskHandlerResponse, CreateTaskHandlerResponses, CreateTaskRequest, CreateTaskResponse, CreateUnthreadedAnchorRequest, CreateUnthreadedAnchorResponse, CreateUnthreadedPdfAnchorRequest, CreateUserApiKeyData, CreateUserApiKeyError, CreateUserApiKeyErrors, CreateUserApiKeyRequest, CreateUserApiKeyResponse, CreateUserApiKeyResponses, CreateViewHandlerData, CreateViewHandlerError, CreateViewHandlerErrors, CreateViewHandlerResponse, CreateViewHandlerResponses, CreateViewRequest, CreateWebhookData, CreateWebhookError, CreateWebhookErrors, CreateWebhookRequest, CreateWebhookResponse, CreateWebhookResponse2, CreateWebhookResponses, CrmComment, CrmCommentEntityType, CrmCommentThread, CrmCompanyFilters, CrmCompanyResponse, CrmContactResponse, CrmDomainResponse, CrmPermissionRole, CrmTeamSettingsResponse, CrmThread, CustomSpeakerAssignment, DataType, DeleteAnchorData, DeleteAnchorError, DeleteAnchorErrors, DeleteAnchorInfo, DeleteAnchorResponse, DeleteAnchorResponses, DeleteCallRecordData, DeleteCallRecordError, DeleteCallRecordErrors, DeleteCallRecordResponse, DeleteCallRecordResponses, DeleteChannelData, DeleteChannelError, DeleteChannelErrors, DeleteChannelResponse, DeleteChannelResponses, DeleteCollabSurfaceData, DeleteCollabSurfaceError, DeleteCollabSurfaceErrors, DeleteCollabSurfaceResponse, DeleteCollabSurfaceResponses, DeleteCommentData, DeleteCommentError, DeleteCommentErrors, DeleteCommentRequest, DeleteCommentResponse, DeleteCommentResponse2, DeleteCommentResponses, DeleteCrmCommentData, DeleteCrmCommentError, DeleteCrmCommentErrors, DeleteCrmCommentResponse, DeleteCrmCommentResponses, DeleteCrmCommentResult, DeleteDocumentData, DeleteDocumentError, DeleteDocumentErrors, DeleteDocumentResponse, DeleteDocumentResponses, DeleteEntityMentionData, DeleteEntityMentionError, DeleteEntityMentionErrors, DeleteEntityMentionResponse, DeleteEntityMentionResponse2, DeleteEntityMentionResponses, DeleteHistoryHandlerData, DeleteHistoryHandlerError, DeleteHistoryHandlerErrors, DeleteHistoryHandlerResponse, DeleteHistoryHandlerResponses, DeleteMessageData, DeleteMessageError, DeleteMessageErrors, DeleteMessageQuery, DeleteMessageResponse, DeleteMessageResponses, DeleteProjectHandlerData, DeleteProjectHandlerError, DeleteProjectHandlerErrors, DeleteProjectHandlerResponse, DeleteProjectHandlerResponses, DeleteReminderData, DeleteReminderError, DeleteReminderErrors, DeleteReminderResponse, DeleteReminderResponses, DeleteThreadInfo, DeleteUnthreadedAnchorRequest, DeleteUnthreadedAnchorResponse, DeleteUnthreadedPdfAnchorRequest, DeleteUserApiKeyData, DeleteUserApiKeyError, DeleteUserApiKeyErrors, DeleteUserApiKeyResponse, DeleteUserApiKeyResponses, DeleteUserDocumentViewLocationData, DeleteUserDocumentViewLocationError, DeleteUserDocumentViewLocationErrors, DeleteUserDocumentViewLocationResponse, DeleteUserDocumentViewLocationResponses, DeleteViewHandlerData, DeleteViewHandlerError, DeleteViewHandlerErrors, DeleteViewHandlerResponses, DeleteWebhookData, DeleteWebhookError, DeleteWebhookErrors, DeleteWebhookResponse, DeleteWebhookResponses, DocumentBasic, DocumentContent, DocumentContentLocation, DocumentContentState, DocumentContentUploadedMetadata, DocumentCopiedMetadata, DocumentCreatedMetadata, DocumentDeletedMetadata, DocumentFilters, DocumentInteractionMetadata, DocumentMetadata, DocumentMetadataWithContent, DocumentPermissionsToken, DocumentPermissionsTokenRequest, DocumentPermissionsTokenResponse, DocumentPreview, DocumentPreviewData, DocumentPreviewDataSubType, DocumentPurgedMetadata, DocumentResponse, DocumentResponseMetadata, DocumentResponseMetadataWithContent, DocumentStorageServiceApiVersion, DocumentSubType, DocumentSyncContentUpdatedMetadata, DocumentTeamShareResponse, DocumentTopicEvent, DocumentUpdatedMetadata, EditAnchorData, EditAnchorError, EditAnchorErrors, EditAnchorRequest, EditAnchorResponse, EditAnchorResponse2, EditAnchorResponses, EditCallRecordData, EditCallRecordError, EditCallRecordErrors, EditCallRecordRequest, EditCallRecordResponse, EditCallRecordResponses, EditCallTranscriptData, EditCallTranscriptError, EditCallTranscriptErrors, EditCallTranscriptRequest, EditCallTranscriptResponse, EditCallTranscriptResponses, EditCommentData, EditCommentError, EditCommentErrors, EditCommentRequest, EditCommentResponse, EditCommentResponse2, EditCommentResponses, EditCrmCommentData, EditCrmCommentError, EditCrmCommentErrors, EditCrmCommentRequest, EditCrmCommentResponse, EditCrmCommentResponses, EditDocumentData, EditDocumentError, EditDocumentErrors, EditDocumentResponse, EditDocumentResponse2, EditDocumentResponses, EditDocumentServiceArgs, EditPdfAnchorRequest, EditPdfPlaceableCommentAnchorRequest, EditProjectV2Data, EditProjectV2Error, EditProjectV2Errors, EditProjectV2Response, EditProjectV2Responses, EditThreadV2Data, EditThreadV2Error, EditThreadV2Errors, EditThreadV2Response, EditThreadV2Responses, EmailFilters, EmptyResponse, EnsureCollabSurfaceData, EnsureCollabSurfaceError, EnsureCollabSurfaceErrors, EnsureCollabSurfaceRequest, EnsureCollabSurfaceResponse, EnsureCollabSurfaceResponses, EntityFilters, EntityPermission, EntityPermissionResponse, EntityReference, EntityType, ErrorResponse, EventReminderOverride, EventReminders, EventStatus, EventTime, EventTransparency, EventType, EventVisibility, ExcludedDefaultView, ExcludeDefaultViewHandlerData, ExcludeDefaultViewHandlerError, ExcludeDefaultViewHandlerErrors, ExcludeDefaultViewHandlerResponses, ExcludeDefaultViewRequest, ExportDocumentData, ExportDocumentError, ExportDocumentErrors, ExportDocumentResponse, ExportDocumentResponse2, ExportDocumentResponses, Favorite, FavoriteEntityRef, FavoritesList, FileSystemNodeWithIds, FileType, FileTypeUpdate, FolderItem, ForeignEntity, ForeignEntityFilters, GenericErrorResponse, GenericResponse, GenericSuccessResponse, GetActiveCallsData, GetActiveCallsError, GetActiveCallsErrors, GetActiveCallsResponse, GetActiveCallsResponses, GetActivityData, GetActivityError, GetActivityErrors, GetActivityResponse, GetActivityResponses, GetAttachmentReferencesData, GetAttachmentReferencesError, GetAttachmentReferencesErrors, GetAttachmentReferencesResponse, GetAttachmentReferencesResponse2, GetAttachmentReferencesResponses, GetBatchCallRecordPreviewData, GetBatchCallRecordPreviewError, GetBatchCallRecordPreviewErrors, GetBatchCallRecordPreviewRequest, GetBatchCallRecordPreviewResponse, GetBatchCallRecordPreviewResponse2, GetBatchCallRecordPreviewResponses, GetBatchChannelPreviewData, GetBatchChannelPreviewError, GetBatchChannelPreviewErrors, GetBatchChannelPreviewRequest, GetBatchChannelPreviewResponse, GetBatchChannelPreviewResponse2, GetBatchChannelPreviewResponses, GetBatchPreviewHandlerData, GetBatchPreviewHandlerError, GetBatchPreviewHandlerErrors, GetBatchPreviewHandlerResponse, GetBatchPreviewHandlerResponses, GetBatchPreviewRequest, GetBatchPreviewResponse, GetBatchProjectPreviewData, GetBatchProjectPreviewError, GetBatchProjectPreviewErrors, GetBatchProjectPreviewRequest, GetBatchProjectPreviewResponse, GetBatchProjectPreviewResponse2, GetBatchProjectPreviewResponses, GetCallRecordData, GetCallRecordError, GetCallRecordErrors, GetCallRecordResponse, GetCallRecordResponses, GetChannelAttachmentsData, GetChannelAttachmentsError, GetChannelAttachmentsErrors, GetChannelAttachmentsResponse, GetChannelAttachmentsResponses, GetChannelData, GetChannelError, GetChannelErrors, GetChannelJoinLinkData, GetChannelJoinLinkError, GetChannelJoinLinkErrors, GetChannelJoinLinkResponse, GetChannelJoinLinkResponses, GetChannelMessagesData, GetChannelMessagesError, GetChannelMessagesErrors, GetChannelMessagesResponse, GetChannelMessagesResponses, GetChannelParticipantsData, GetChannelParticipantsError, GetChannelParticipantsErrors, GetChannelParticipantsResponse, GetChannelParticipantsResponses, GetChannelResponse, GetChannelResponses, GetChannelsData, GetChannelsError, GetChannelsErrors, GetChannelsResponse, GetChannelsResponses, GetCollabSurfaceData, GetCollabSurfaceError, GetCollabSurfaceErrors, GetCollabSurfaceResponse, GetCollabSurfaceResponses, GetCompanyData, GetCompanyError, GetCompanyErrors, GetCompanyResponse, GetCompanyResponses, GetContactByEmailData, GetContactByEmailError, GetContactByEmailErrors, GetContactByEmailResponse, GetContactByEmailResponse2, GetContactByEmailResponses, GetContactData, GetContactError, GetContactErrors, GetContactResponse, GetContactResponses, GetCrmTeamSettingsData, GetCrmTeamSettingsError, GetCrmTeamSettingsErrors, GetCrmTeamSettingsResponse, GetCrmTeamSettingsResponses, GetDocumentAnchorsData, GetDocumentAnchorsError, GetDocumentAnchorsErrors, GetDocumentAnchorsResponse, GetDocumentAnchorsResponses, GetDocumentBranchNameData, GetDocumentBranchNameError, GetDocumentBranchNameErrors, GetDocumentBranchNameResponse, GetDocumentBranchNameResponses, GetDocumentByTeamSlugData, GetDocumentByTeamSlugError, GetDocumentByTeamSlugErrors, GetDocumentByTeamSlugResponse, GetDocumentByTeamSlugResponses, GetDocumentCommentsData, GetDocumentCommentsError, GetDocumentCommentsErrors, GetDocumentCommentsResponse, GetDocumentCommentsResponses, GetDocumentData, GetDocumentError, GetDocumentErrors, GetDocumentGithubPullRequestsData, GetDocumentGithubPullRequestsError, GetDocumentGithubPullRequestsErrors, GetDocumentGithubPullRequestsResponse, GetDocumentGithubPullRequestsResponses, GetDocumentKeyResponse, GetDocumentKeyResponseData, GetDocumentListHandlerData, GetDocumentListHandlerError, GetDocumentListHandlerErrors, GetDocumentListHandlerResponse, GetDocumentListHandlerResponses, GetDocumentListResult, GetDocumentLocationV3Data, GetDocumentLocationV3Error, GetDocumentLocationV3Errors, GetDocumentLocationV3Response, GetDocumentLocationV3Responses, GetDocumentPermissionsResponseDataV2, GetDocumentPermissionsTokenData, GetDocumentPermissionsTokenError, GetDocumentPermissionsTokenErrors, GetDocumentPermissionsTokenResponse, GetDocumentPermissionsTokenResponses, GetDocumentPermissionsV2Data, GetDocumentPermissionsV2Error, GetDocumentPermissionsV2Errors, GetDocumentPermissionsV2Response, GetDocumentPermissionsV2Responses, GetDocumentProcessingResult, GetDocumentProcessingResultData, GetDocumentProcessingResultError, GetDocumentProcessingResultErrors, GetDocumentProcessingResultResponse, GetDocumentProcessingResultResponse2, GetDocumentProcessingResultResponses, GetDocumentResponse, GetDocumentResponse2, GetDocumentResponseData, GetDocumentResponses, GetDocumentSearchResponse, GetDocumentShortIdData, GetDocumentShortIdError, GetDocumentShortIdErrors, GetDocumentShortIdResponse, GetDocumentShortIdResponses, GetDocumentsResponse, GetDocumentTeamShareData, GetDocumentTeamShareError, GetDocumentTeamShareErrors, GetDocumentTeamShareResponse, GetDocumentTeamShareResponses, GetDocumentUserAccessLevelResponse, GetDocumentVersionData, GetDocumentVersionError, GetDocumentVersionErrors, GetDocumentVersionResponse, GetDocumentVersionResponses, GetDocumentViewsHandlerData, GetDocumentViewsHandlerError, GetDocumentViewsHandlerErrors, GetDocumentViewsHandlerResponse, GetDocumentViewsHandlerResponses, GetEntityPermissionData, GetEntityPermissionErrors, GetEntityPermissionResponse, GetEntityPermissionResponses, GetForeignEntityData, GetForeignEntityError, GetForeignEntityErrors, GetForeignEntityResponse, GetForeignEntityResponses, GetHistoryHandlerData, GetHistoryHandlerError, GetHistoryHandlerErrors, GetHistoryHandlerResponse, GetHistoryHandlerResponses, GetInstructionsDocumentResponse, GetInstructionsHandlerData, GetInstructionsHandlerError, GetInstructionsHandlerErrors, GetInstructionsHandlerResponse, GetInstructionsHandlerResponses, GetItemsSoupData, GetItemsSoupError, GetItemsSoupErrors, GetItemsSoupResponse, GetItemsSoupResponses, GetLocationHandlerData, GetLocationHandlerError, GetLocationHandlerErrors, GetLocationHandlerResponse, GetLocationHandlerResponses, GetMessageWithContextData, GetMessageWithContextError, GetMessageWithContextErrors, GetMessageWithContextResponse, GetMessageWithContextResponse2, GetMessageWithContextResponses, GetOrCreateAction, GetOrCreateCallData, GetOrCreateCallError, GetOrCreateCallErrors, GetOrCreateCallResponse, GetOrCreateCallResponses, GetOrCreateChannelResponse, GetOrCreateDmData, GetOrCreateDmError, GetOrCreateDmErrors, GetOrCreateDmRequest, GetOrCreateDmResponse, GetOrCreateDmResponses, GetOrCreatePrivateData, GetOrCreatePrivateError, GetOrCreatePrivateErrors, GetOrCreatePrivateRequest, GetOrCreatePrivateResponse, GetOrCreatePrivateResponses, GetPendingProjectsHandlerData, GetPendingProjectsHandlerError, GetPendingProjectsHandlerErrors, GetPendingProjectsHandlerResponse, GetPendingProjectsHandlerResponses, GetPinsHandlerData, GetPinsHandlerError, GetPinsHandlerErrors, GetPinsHandlerResponse, GetPinsHandlerResponses, GetPinsResponse, GetProjectContentHandlerData, GetProjectContentHandlerError, GetProjectContentHandlerErrors, GetProjectContentHandlerResponse, GetProjectContentHandlerResponses, GetProjectContentResponse, GetProjectHandlerData, GetProjectHandlerError, GetProjectHandlerErrors, GetProjectHandlerResponse, GetProjectHandlerResponses, GetProjectPermissionsV2Data, GetProjectPermissionsV2Error, GetProjectPermissionsV2Errors, GetProjectPermissionsV2Response, GetProjectPermissionsV2Responses, GetProjectResponse, GetProjectResponseData, GetProjectsHandlerData, GetProjectsHandlerError, GetProjectsHandlerErrors, GetProjectsHandlerResponse, GetProjectsHandlerResponses, GetProjectsResponse, GetProjectUserAccessLevelData, GetProjectUserAccessLevelError, GetProjectUserAccessLevelErrors, GetProjectUserAccessLevelResponse, GetProjectUserAccessLevelResponses, GetReminderData, GetReminderError, GetReminderErrors, GetReminderResponse, GetReminderResponses, GetRingStatusData, GetRingStatusError, GetRingStatusErrors, GetRingStatusResponse, GetRingStatusResponses, GetSelfBotData, GetSelfBotError, GetSelfBotErrors, GetSelfBotResponse, GetSelfBotResponses, GetSystemSkillsHandlerData, GetSystemSkillsHandlerError, GetSystemSkillsHandlerErrors, GetSystemSkillsHandlerResponse, GetSystemSkillsHandlerResponses, GetThreadRepliesData, GetThreadRepliesError, GetThreadRepliesErrors, GetThreadRepliesResponse, GetThreadRepliesResponses, GetUserDocumentsHandlerData, GetUserDocumentsHandlerError, GetUserDocumentsHandlerErrors, GetUserDocumentsHandlerResponse, GetUserDocumentsHandlerResponses, GetUserDocumentViewLocationData, GetUserDocumentViewLocationError, GetUserDocumentViewLocationErrors, GetUserDocumentViewLocationResponse, GetUserDocumentViewLocationResponses, GetUserHistoryResponse, GetViewsHandlerData, GetViewsHandlerError, GetViewsHandlerErrors, GetViewsHandlerResponse, GetViewsHandlerResponses, GetWebhookData, GetWebhookError, GetWebhookErrors, GetWebhookResponse, GetWebhookResponses, GithubPullRequest, GithubPullRequestCheckRun, GithubPullRequestComment, GithubPullRequestsResponse, GroupedInitialParams, GroupedPageParams, GroupedSoupGroupPage, GroupedSoupInitialPage, GroupedSoupPage, GroupedSoupSort, HandlerData, HandlerError, HandlerErrors, HandlerResponse, HandlerResponses, HashMap, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, HighlightType, IngestTranscriptData, IngestTranscriptError, IngestTranscriptErrors, IngestTranscriptResponses, InitializeUserDocumentsData, InitializeUserDocumentsError, InitializeUserDocumentsErrors, InitializeUserDocumentsResponse, InitializeUserDocumentsResponses, InstallSyncData, InstallSyncErrors, InteractionReason, Item, ItemWithUserAccessLevel, JobProcessingResultHandlerData, JobProcessingResultHandlerError, JobProcessingResultHandlerErrors, JobProcessingResultHandlerResponse, JobProcessingResultHandlerResponses, JoinChannelByCodeData, JoinChannelByCodeError, JoinChannelByCodeErrors, JoinChannelByCodeResponses, JoinChannelData, JoinChannelError, JoinChannelErrors, JoinChannelResponses, LatestMessage, LeaveCallResponse, LeaveChannelData, LeaveChannelError, LeaveChannelErrors, LeaveChannelResponses, LeaveOrEndCallData, LeaveOrEndCallError, LeaveOrEndCallErrors, LeaveOrEndCallResponse, LeaveOrEndCallResponses, LinkShare, ListAgentsData, ListAgentsError, ListAgentsErrors, ListAgentsResponse, ListAgentsResponses, ListBotChannelsData, ListBotChannelsError, ListBotChannelsErrors, ListBotChannelsResponse, ListBotChannelsResponses, ListCompanyContactsData, ListCompanyContactsError, ListCompanyContactsErrors, ListCompanyContactsResponse, ListCompanyContactsResponses, ListCrmCommentsData, ListCrmCommentsError, ListCrmCommentsErrors, ListCrmCommentsResponse, ListCrmCommentsResponses, ListFavoritesData, ListFavoritesError, ListFavoritesErrors, ListFavoritesResponse, ListFavoritesResponses, ListOccurrencesData, ListOccurrencesErrors, ListOccurrencesResponse, ListOccurrencesResponses, ListRemindersData, ListRemindersError, ListRemindersErrors, ListRemindersResponse, ListRemindersResponses, ListUserApiKeysData, ListUserApiKeysError, ListUserApiKeysErrors, ListUserApiKeysResponse, ListUserApiKeysResponses, ListWebhooksData, ListWebhooksError, ListWebhooksErrors, ListWebhooksResponse, ListWebhooksResponse2, ListWebhooksResponses, LocationResponseData, LocationResponseV3, MacroUserIdStr, MentionPreviewsData, MentionPreviewsErrors, MentionPreviewsResponse, MentionPreviewsResponses, Mentions, NewChannelAttachment, NotificationFilters, Params, ParticipantRole, PatchBotRequest, PatchChannelData, PatchChannelError, PatchChannelErrors, PatchChannelRequest, PatchChannelResponse, PatchChannelResponses, PatchMessageData, PatchMessageError, PatchMessageErrors, PatchMessageRequest, PatchMessageResponse, PatchMessageResponses, PatchProjectRequestV2, PatchThreadRequestV2, PatchViewHandlerData, PatchViewHandlerError, PatchViewHandlerErrors, PatchViewHandlerResponses, PatchWebhookData, PatchWebhookError, PatchWebhookErrors, PatchWebhookRequest, PatchWebhookResponse, PatchWebhookResponses, PdfAnchor, PdfAnchorId, PdfAnchorRequest, PdfHighlightAnchor, PdfHighlightAnchorRequest, PdfHighlightRect, PdfHighlightRectAnchorRequest, PdfPlaceableCommentAnchor, PdfPlaceableCommentAnchorRequest, PermanentlyDeleteDocumentData, PermanentlyDeleteDocumentError, PermanentlyDeleteDocumentErrors, PermanentlyDeleteDocumentResponse, PermanentlyDeleteDocumentResponses, PermanentlyDeleteProjectData, PermanentlyDeleteProjectError, PermanentlyDeleteProjectErrors, PermanentlyDeleteProjectResponse, PermanentlyDeleteProjectResponses, PinnedItem, PinRequest, PostActivityData, PostActivityError, PostActivityErrors, PostActivityRequest, PostActivityResponse, PostActivityResponses, PostChannelBotWebhookData, PostChannelBotWebhookError, PostChannelBotWebhookErrors, PostChannelBotWebhookResponse, PostChannelBotWebhookResponses, PostChannelMessagesData, PostChannelMessagesError, PostChannelMessagesErrors, PostChannelMessagesResponse, PostChannelMessagesResponses, PostGroupedSoupAstGroupPageRequest, PostGroupedSoupAstInitialRequest, PostGroupedSoupAstRequest, PostItemsSoupAstData, PostItemsSoupAstError, PostItemsSoupAstErrors, PostItemsSoupAstGroupedData, PostItemsSoupAstGroupedError, PostItemsSoupAstGroupedErrors, PostItemsSoupAstGroupedResponse, PostItemsSoupAstGroupedResponses, PostItemsSoupAstResponse, PostItemsSoupAstResponses, PostItemsSoupData, PostItemsSoupError, PostItemsSoupErrors, PostItemsSoupResponse, PostItemsSoupResponses, PostMessageData, PostMessageError, PostMessageErrors, PostMessageRequest, PostMessageResponse, PostMessageResponse2, PostMessageResponses, PostReactionData, PostReactionError, PostReactionErrors, PostReactionRequest, PostReactionResponse, PostReactionResponses, PostSoupAstRequest, PostSoupRequest, PostTypingData, PostTypingError, PostTypingErrors, PostTypingRequest, PostTypingResponse, PostTypingResponses, PresaveDocumentHandlerData, PresaveDocumentHandlerError, PresaveDocumentHandlerErrors, PresaveDocumentHandlerResponse, PresaveDocumentHandlerResponses, PreSaveDocumentRequest, PreSaveDocumentResponse, PreSaveDocumentResponseData, PresignedUrl, Project, ProjectDeleteResponseData, ProjectDocumentStatus, ProjectFilters, ProjectPreview, ProjectPreviewData, PropertyDefinition, PropertyFilter, PropertyInput, PropertyOwner, PropertyValue, PutCrmTeamSettingsData, PutCrmTeamSettingsError, PutCrmTeamSettingsErrors, PutCrmTeamSettingsResponse, PutCrmTeamSettingsResponses, ReactionAction, RecentlyDeletedData, RecentlyDeletedError, RecentlyDeletedErrors, RecentlyDeletedResponse, RecentlyDeletedResponseData, RecentlyDeletedResponses, Reminder, ReminderFilters, ReminderSchedule, RemindersList, RemoveBotFromChannelByBotData, RemoveBotFromChannelByBotError, RemoveBotFromChannelByBotErrors, RemoveBotFromChannelByBotResponse, RemoveBotFromChannelByBotResponses, RemoveFavoriteByEntityData, RemoveFavoriteByEntityError, RemoveFavoriteByEntityErrors, RemoveFavoriteByEntityResponses, RemoveParticipantsData, RemoveParticipantsError, RemoveParticipantsErrors, RemoveParticipantsRequest, RemoveParticipantsResponses, RemovePinHandlerData, RemovePinHandlerError, RemovePinHandlerErrors, RemovePinHandlerResponse, RemovePinHandlerResponses, ReorderFavoritesData, ReorderFavoritesError, ReorderFavoritesErrors, ReorderFavoritesRequest, ReorderFavoritesResponses, ReorderPinRequest, ReorderPinsHandlerData, ReorderPinsHandlerError, ReorderPinsHandlerErrors, ReorderPinsHandlerResponse, ReorderPinsHandlerResponses, ResolveChannelMessageData, ResolveChannelMessageError, ResolveChannelMessageErrors, ResolveChannelMessageResponse, ResolveChannelMessageResponses, RevertDeleteDocumentData, RevertDeleteDocumentError, RevertDeleteDocumentErrors, RevertDeleteDocumentResponse, RevertDeleteDocumentResponses, RevertDeleteProjectData, RevertDeleteProjectError, RevertDeleteProjectErrors, RevertDeleteProjectResponse, RevertDeleteProjectResponses, RingStatus, RingStatusResponse, S3ObjectInfo, SaveBomPart, SaveDocumentHandlerData, SaveDocumentHandlerError, SaveDocumentHandlerErrors, SaveDocumentHandlerResponse, SaveDocumentHandlerResponses, SaveDocumentRequest, SaveDocumentResponse, SaveDocumentResponseData, SetCompanyHiddenData, SetCompanyHiddenError, SetCompanyHiddenErrors, SetCompanyHiddenRequest, SetCompanyHiddenResponse, SetCompanyHiddenResponses, SetCompanyNameRequest, SetContactHiddenData, SetContactHiddenError, SetContactHiddenErrors, SetContactHiddenRequest, SetContactHiddenResponse, SetContactHiddenResponses, SetContactNameRequest, SetCrmCompanyNameData, SetCrmCompanyNameError, SetCrmCompanyNameErrors, SetCrmCompanyNameResponse, SetCrmCompanyNameResponses, SetCrmContactNameData, SetCrmContactNameError, SetCrmContactNameErrors, SetCrmContactNameResponse, SetCrmContactNameResponses, SetDocumentTeamShareData, SetDocumentTeamShareError, SetDocumentTeamShareErrors, SetDocumentTeamShareRequest, SetDocumentTeamShareResponse, SetDocumentTeamShareResponses, SetEmailSyncData, SetEmailSyncError, SetEmailSyncErrors, SetEmailSyncRequest, SetEmailSyncResponse, SetEmailSyncResponses, SetPropertyValue, SharedEmailFilter, SharePermissionV2, ShortIdResponse, SimpleMention, SimpleSaveData, SimpleSaveError, SimpleSaveErrors, SimpleSaveResponse, SimpleSaveResponses, SoupApiItem, SoupApiSort, SoupApiSortDirection, SoupAttachment, SoupCalendarEventSoupPropertiesField, SoupCalendarEventTime, SoupCallRecordParticipant, SoupCallRecordSoupPropertiesField, SoupChannel, SoupChannelThread, SoupChatSoupPropertiesField, SoupContact, SoupCountedReaction, SoupCrmCompanySoupPropertiesField, SoupCrmDomain, SoupDocumentSoupPropertiesField, SoupDocumentSubType, SoupEmailThreadPreview, SoupEnrichedEmailThreadPreviewSoupPropertiesField, SoupForeignEntity, SoupItem, SoupLabel, SoupLabelListVisibility, SoupLabelType, SoupMessageAttachment, SoupMessageListVisibility, SoupMessageSender, SoupMessageSenderType, SoupPage, SoupProjectSoupPropertiesField, SoupPropertiesField, SoupProperty, SoupReminderReference, SoupReminderSchedule, SoupReminderSoupPropertiesField, SoupThreadInfo, SoupThreadReply, StarterDocumentsResponse, String, SuccessResponse, SurfaceState, SyncServiceVersionId, SystemSkillSummary, TagFilterMode, TaskFilters, TeamRole, Thread, ThreadResponse, ToggleShareWithTeamData, ToggleShareWithTeamError, ToggleShareWithTeamErrors, ToggleShareWithTeamResponse, ToggleShareWithTeamResponses, TranscriptSegmentRequest, TypedSuccessResponse, TypedSuccessResponseGetDocumentResponseData, TypingAction, UnthreadedPdfUuidRequest, UpdateAgentData, UpdateAgentError, UpdateAgentErrors, UpdateAgentRequest, UpdateAgentResponse, UpdateAgentResponses, UpdateChannelSharePermission, UpdateCrmTeamSettingsRequest, UpdateOperation, UpdateReminderData, UpdateReminderError, UpdateReminderErrors, UpdateReminderRequest, UpdateReminderResponse, UpdateReminderResponses, UpdateSharePermissionRequestV2, UploadDocumentStatus, UploadExtractFolderHandlerData, UploadExtractFolderHandlerError, UploadExtractFolderHandlerErrors, UploadExtractFolderHandlerResponse, UploadExtractFolderHandlerResponses, UploadExtractFolderRequest, UploadFolderHandlerData, UploadFolderHandlerError, UploadFolderHandlerErrors, UploadFolderHandlerResponse, UploadFolderHandlerResponses, UploadFolderRequest, UpsertHistoryHandlerData, UpsertHistoryHandlerError, UpsertHistoryHandlerErrors, UpsertHistoryHandlerResponse, UpsertHistoryHandlerResponses, UpsertUserDocumentViewLocationData, UpsertUserDocumentViewLocationError, UpsertUserDocumentViewLocationErrors, UpsertUserDocumentViewLocationRequest, UpsertUserDocumentViewLocationResponse, UpsertUserDocumentViewLocationResponses, UserApiKeyId, UserApiKeyInfo, UserApiKeysList, UserDocumentsResponse, UserDocumentViewLocation, UserDocumentViewLocationResponse, UserPinsResponse, UserViewsResponse, ValidateDocumentPermissionsTokenData, ValidateDocumentPermissionsTokenError, ValidateDocumentPermissionsTokenErrors, ValidateDocumentPermissionsTokenResponse, ValidateDocumentPermissionsTokenResponses, ValidateWebhookData, ValidateWebhookError, ValidateWebhookErrors, ValidateWebhookResponse, ValidateWebhookResponse2, ValidateWebhookResponses, Vec, View, ViewPatch, ViewsResponse, Webhook, WebhookEvent, WebhookFilter, WebhookScope, WebhookStatus, WebhookValidationTestEvent, WithCallId, WithChannelId, WithDocumentId, WithProjectId } from './types.gen';+export type { AccessLevel, ActiveCallsResponse, ActiveCallSummary, ActivityType, AddFavoriteData, AddFavoriteError, AddFavoriteErrors, AddFavoriteRequest, AddFavoriteResponse, AddFavoriteResponses, AddParticipantsData, AddParticipantsError, AddParticipantsErrors, AddParticipantsRequest, AddParticipantsResponses, AddPinHandlerData, AddPinHandlerError, AddPinHandlerErrors, AddPinHandlerResponse, AddPinHandlerResponses, AddPinRequest, Agent, AgentChannelScope, Anchor, AnchorId, AnchorRequest, AnchorResponse, AnnotationIncrementalUpdate, ApiActivity, ApiAttachmentChannelReference, ApiAttachmentEntityReference, ApiAttachmentGenericReference, ApiChannelAttachment, ApiChannelAttachmentsPage, ApiChannelContextMessage, ApiChannelDetail, ApiChannelListMessage, ApiChannelListPage, ApiChannelListParticipant, ApiChannelListType, ApiChannelMessage, ApiChannelMessageKind, ApiChannelMessagesPage, ApiChannelParticipant, ApiChannelWithLatest, ApiCountedReaction, ApiEntityFilterAst, ApiGroupByField, ApiGroupMeta, ApiMessageAttachment, ApiMessageSender, ApiMessageSenderType, ApiParticipantListRole, ApiParticipantRole, ApiPropertyEntityType, ApiResolvedChannelMessage, ApiThreadInfo, ApiThreadReply, ApproveHarnessPairingData, ApproveHarnessPairingError, ApproveHarnessPairingErrors, ApproveHarnessPairingResponse, ApproveHarnessPairingResponses, ApprovePairingRequest, AttendeeResponseStatus, BasicDocument, BasicDocumentSubType, BomPart, Bot, BotChannel, BotChannelType, BotId, BotKind, BotOwner, BotToken, BranchNameResponse, BTreeMap, BulkWakeupRequest, BulkWakeupResponse, BulkWakeupSyncServiceDocumentsData, BulkWakeupSyncServiceDocumentsErrors, BulkWakeupSyncServiceDocumentsResponse, BulkWakeupSyncServiceDocumentsResponses, CalendarAttendee, CalendarEvent, CalendarEventFilters, CalendarMentionEvent, CalendarMentionPreviewItem, CalendarMentionPreviewKind, CalendarMentionPreviewRequest, CalendarMentionPreviewRequestItem, CalendarMentionPreviewResponse, CalendarOccurrence, CalendarOccurrenceItem, CalendarOccurrenceResponse, CalendarSyncStatus, CallActiveResponse, CallFilters, CallRecord, CallRecordParticipant, CallRecordPreview, CallRecordPreviewData, CallRecordTranscriptSegment, CallStatus, CallTokenResponse, CallWebhookData, CallWebhookError, CallWebhookErrors, CallWebhookResponses, Channel, ChannelCreatedMetadata, ChannelDeletedMetadata, ChannelEventAttachment, ChannelFilters, ChannelJoinCodeResponse, ChannelMentionedMetadata, ChannelMessage, ChannelMessageAttachmentCreatedMetadata, ChannelMessageAttachmentRemovedMetadata, ChannelMessageDeletedMetadata, ChannelMessageFilters, ChannelMessagePatchedMetadata, ChannelMessagePostedMetadata, ChannelParticipant, ChannelParticipantAddedMetadata, ChannelParticipantRemovedMetadata, ChannelPreview, ChannelPreviewData, ChannelSender, ChannelSharePermission, ChannelThreadFilters, ChannelTopicEvent, ChannelType, ChannelUpdatedMetadata, ChannelWebhookRequest, ChannelWebhookResponse, ChannelWithParticipants, Chat, ChatFilters, CheckActiveCallData, CheckActiveCallError, CheckActiveCallErrors, CheckActiveCallResponse, CheckActiveCallResponses, ClaimedPairing, ClaimHarnessPairingData, ClaimHarnessPairingError, ClaimHarnessPairingErrors, ClaimHarnessPairingResponse, ClaimHarnessPairingResponses, ClaimPairingRequest, ClientOptions, CloudStorageItemType, CollabSurfaceResponse, CollabSurfaceTokenResponse, Comment, CommentThread, ConferenceProvider, CopyDocumentData, CopyDocumentError, CopyDocumentErrors, CopyDocumentQueryParams, CopyDocumentRequest, CopyDocumentResponse, CopyDocumentResponse2, CopyDocumentResponses, CreateAgentData, CreateAgentError, CreateAgentErrors, CreateAgentRequest, CreateAgentResponse, CreateAgentResponses, CreateAnchorData, CreateAnchorError, CreateAnchorErrors, CreateAnchorResponse, CreateAnchorResponses, CreateBotRequest, CreateBulkDocumentResponse, CreateBulkDocumentResponseData, CreateChannelData, CreateChannelError, CreateChannelErrors, CreateChannelRequest, CreateChannelResponse, CreateChannelResponse2, CreateChannelResponses, CreateChannelScopedBotData, CreateChannelScopedBotError, CreateChannelScopedBotErrors, CreateChannelScopedBotRequest, CreateChannelScopedBotResponse, CreateChannelScopedBotResponse2, CreateChannelScopedBotResponses, CreateCollabSurfaceTokenData, CreateCollabSurfaceTokenError, CreateCollabSurfaceTokenErrors, CreateCollabSurfaceTokenResponse, CreateCollabSurfaceTokenResponses, CreateCommentData, CreateCommentError, CreateCommentErrors, CreateCommentRequest, CreateCommentResponse, CreateCommentResponse2, CreateCommentResponses, CreateCrmCommentData, CreateCrmCommentError, CreateCrmCommentErrors, CreateCrmCommentRequest, CreateCrmCommentResponse, CreateCrmCommentResponses, CreateCrmCompanyData, CreateCrmCompanyError, CreateCrmCompanyErrors, CreateCrmCompanyRequest, CreateCrmCompanyResponse, CreateCrmCompanyResponses, CreateCrmContactData, CreateCrmContactError, CreateCrmContactErrors, CreateCrmContactRequest, CreateCrmContactResponse, CreateCrmContactResponses, CreateDocumentData, CreateDocumentError, CreateDocumentErrors, CreateDocumentRequest, CreateDocumentResponse, CreateDocumentResponseData, CreateDocumentResponses, CreatedPairing, CreatedUserApiKey, CreateEntityMentionData, CreateEntityMentionError, CreateEntityMentionErrors, CreateEntityMentionRequest, CreateEntityMentionResponse, CreateEntityMentionResponse2, CreateEntityMentionResponses, CreateHarnessPairingData, CreateHarnessPairingError, CreateHarnessPairingErrors, CreateHarnessPairingResponse, CreateHarnessPairingResponses, CreateInstructionsDocumentResponse, CreateInstructionsHandlerData, CreateInstructionsHandlerError, CreateInstructionsHandlerErrors, CreateInstructionsHandlerResponse, CreateInstructionsHandlerResponses, CreateMarkdownDocumentRequest, CreateMarkdownDocumentResponse, CreateMarkdownHandlerData, CreateMarkdownHandlerError, CreateMarkdownHandlerErrors, CreateMarkdownHandlerResponse, CreateMarkdownHandlerResponses, CreatePairingRequest, CreateProjectHandlerData, CreateProjectHandlerError, CreateProjectHandlerErrors, CreateProjectHandlerResponse, CreateProjectHandlerResponses, CreateProjectRequest, CreateProjectResponse, CreateReminderData, CreateReminderError, CreateReminderErrors, CreateReminderRequest, CreateReminderResponse, CreateReminderResponses, CreateSkillHandlerData, CreateSkillHandlerError, CreateSkillHandlerErrors, CreateSkillHandlerResponse, CreateSkillHandlerResponses, CreateSkillRequest, CreateSkillResponse, CreateSnippetHandlerData, CreateSnippetHandlerError, CreateSnippetHandlerErrors, CreateSnippetHandlerResponse, CreateSnippetHandlerResponses, CreateSnippetRequest, CreateSnippetResponse, CreateTaskHandlerData, CreateTaskHandlerError, CreateTaskHandlerErrors, CreateTaskHandlerResponse, CreateTaskHandlerResponses, CreateTaskRequest, CreateTaskResponse, CreateUnthreadedAnchorRequest, CreateUnthreadedAnchorResponse, CreateUnthreadedPdfAnchorRequest, CreateUserApiKeyData, CreateUserApiKeyError, CreateUserApiKeyErrors, CreateUserApiKeyRequest, CreateUserApiKeyResponse, CreateUserApiKeyResponses, CreateViewHandlerData, CreateViewHandlerError, CreateViewHandlerErrors, CreateViewHandlerResponse, CreateViewHandlerResponses, CreateViewRequest, CreateWebhookData, CreateWebhookError, CreateWebhookErrors, CreateWebhookRequest, CreateWebhookResponse, CreateWebhookResponse2, CreateWebhookResponses, CrmComment, CrmCommentEntityType, CrmCommentThread, CrmCompanyFilters, CrmCompanyResponse, CrmContactResponse, CrmDomainResponse, CrmPermissionRole, CrmTeamSettingsResponse, CrmThread, CustomSpeakerAssignment, DataType, DeleteAnchorData, DeleteAnchorError, DeleteAnchorErrors, DeleteAnchorInfo, DeleteAnchorResponse, DeleteAnchorResponses, DeleteCallRecordData, DeleteCallRecordError, DeleteCallRecordErrors, DeleteCallRecordResponse, DeleteCallRecordResponses, DeleteChannelData, DeleteChannelError, DeleteChannelErrors, DeleteChannelResponse, DeleteChannelResponses, DeleteCollabSurfaceData, DeleteCollabSurfaceError, DeleteCollabSurfaceErrors, DeleteCollabSurfaceResponse, DeleteCollabSurfaceResponses, DeleteCommentData, DeleteCommentError, DeleteCommentErrors, DeleteCommentRequest, DeleteCommentResponse, DeleteCommentResponse2, DeleteCommentResponses, DeleteCrmCommentData, DeleteCrmCommentError, DeleteCrmCommentErrors, DeleteCrmCommentResponse, DeleteCrmCommentResponses, DeleteCrmCommentResult, DeleteDocumentData, DeleteDocumentError, DeleteDocumentErrors, DeleteDocumentResponse, DeleteDocumentResponses, DeleteEntityMentionData, DeleteEntityMentionError, DeleteEntityMentionErrors, DeleteEntityMentionResponse, DeleteEntityMentionResponse2, DeleteEntityMentionResponses, DeleteHarnessData, DeleteHarnessError, DeleteHarnessErrors, DeleteHarnessResponse, DeleteHarnessResponses, DeleteHistoryHandlerData, DeleteHistoryHandlerError, DeleteHistoryHandlerErrors, DeleteHistoryHandlerResponse, DeleteHistoryHandlerResponses, DeleteMessageData, DeleteMessageError, DeleteMessageErrors, DeleteMessageQuery, DeleteMessageResponse, DeleteMessageResponses, DeleteProjectHandlerData, DeleteProjectHandlerError, DeleteProjectHandlerErrors, DeleteProjectHandlerResponse, DeleteProjectHandlerResponses, DeleteReminderData, DeleteReminderError, DeleteReminderErrors, DeleteReminderResponse, DeleteReminderResponses, DeleteThreadInfo, DeleteUnthreadedAnchorRequest, DeleteUnthreadedAnchorResponse, DeleteUnthreadedPdfAnchorRequest, DeleteUserApiKeyData, DeleteUserApiKeyError, DeleteUserApiKeyErrors, DeleteUserApiKeyResponse, DeleteUserApiKeyResponses, DeleteUserDocumentViewLocationData, DeleteUserDocumentViewLocationError, DeleteUserDocumentViewLocationErrors, DeleteUserDocumentViewLocationResponse, DeleteUserDocumentViewLocationResponses, DeleteViewHandlerData, DeleteViewHandlerError, DeleteViewHandlerErrors, DeleteViewHandlerResponses, DeleteWebhookData, DeleteWebhookError, DeleteWebhookErrors, DeleteWebhookResponse, DeleteWebhookResponses, DocumentBasic, DocumentContent, DocumentContentLocation, DocumentContentState, DocumentContentUploadedMetadata, DocumentCopiedMetadata, DocumentCreatedMetadata, DocumentDeletedMetadata, DocumentFilters, DocumentInteractionMetadata, DocumentMetadata, DocumentMetadataWithContent, DocumentPermissionsToken, DocumentPermissionsTokenRequest, DocumentPermissionsTokenResponse, DocumentPreview, DocumentPreviewData, DocumentPreviewDataSubType, DocumentPurgedMetadata, DocumentResponse, DocumentResponseMetadata, DocumentResponseMetadataWithContent, DocumentStorageServiceApiVersion, DocumentSubType, DocumentSyncContentUpdatedMetadata, DocumentTeamShareResponse, DocumentTopicEvent, DocumentUpdatedMetadata, EditAnchorData, EditAnchorError, EditAnchorErrors, EditAnchorRequest, EditAnchorResponse, EditAnchorResponse2, EditAnchorResponses, EditCallRecordData, EditCallRecordError, EditCallRecordErrors, EditCallRecordRequest, EditCallRecordResponse, EditCallRecordResponses, EditCallTranscriptData, EditCallTranscriptError, EditCallTranscriptErrors, EditCallTranscriptRequest, EditCallTranscriptResponse, EditCallTranscriptResponses, EditCommentData, EditCommentError, EditCommentErrors, EditCommentRequest, EditCommentResponse, EditCommentResponse2, EditCommentResponses, EditCrmCommentData, EditCrmCommentError, EditCrmCommentErrors, EditCrmCommentRequest, EditCrmCommentResponse, EditCrmCommentResponses, EditDocumentData, EditDocumentError, EditDocumentErrors, EditDocumentResponse, EditDocumentResponse2, EditDocumentResponses, EditDocumentServiceArgs, EditPdfAnchorRequest, EditPdfPlaceableCommentAnchorRequest, EditProjectV2Data, EditProjectV2Error, EditProjectV2Errors, EditProjectV2Response, EditProjectV2Responses, EditThreadV2Data, EditThreadV2Error, EditThreadV2Errors, EditThreadV2Response, EditThreadV2Responses, EmailFilters, EmptyResponse, EnsureCollabSurfaceData, EnsureCollabSurfaceError, EnsureCollabSurfaceErrors, EnsureCollabSurfaceRequest, EnsureCollabSurfaceResponse, EnsureCollabSurfaceResponses, EntityFilters, EntityPermission, EntityPermissionResponse, EntityReference, EntityType, ErrorResponse, EventReminderOverride, EventReminders, EventStatus, EventTime, EventTransparency, EventType, EventVisibility, ExcludedDefaultView, ExcludeDefaultViewHandlerData, ExcludeDefaultViewHandlerError, ExcludeDefaultViewHandlerErrors, ExcludeDefaultViewHandlerResponses, ExcludeDefaultViewRequest, ExportDocumentData, ExportDocumentError, ExportDocumentErrors, ExportDocumentResponse, ExportDocumentResponse2, ExportDocumentResponses, Favorite, FavoriteEntityRef, FavoritesList, FileSystemNodeWithIds, FileType, FileTypeUpdate, FolderItem, ForeignEntity, ForeignEntityFilters, GenericErrorResponse, GenericResponse, GenericSuccessResponse, GetActiveCallsData, GetActiveCallsError, GetActiveCallsErrors, GetActiveCallsResponse, GetActiveCallsResponses, GetActivityData, GetActivityError, GetActivityErrors, GetActivityResponse, GetActivityResponses, GetAttachmentReferencesData, GetAttachmentReferencesError, GetAttachmentReferencesErrors, GetAttachmentReferencesResponse, GetAttachmentReferencesResponse2, GetAttachmentReferencesResponses, GetBatchCallRecordPreviewData, GetBatchCallRecordPreviewError, GetBatchCallRecordPreviewErrors, GetBatchCallRecordPreviewRequest, GetBatchCallRecordPreviewResponse, GetBatchCallRecordPreviewResponse2, GetBatchCallRecordPreviewResponses, GetBatchChannelPreviewData, GetBatchChannelPreviewError, GetBatchChannelPreviewErrors, GetBatchChannelPreviewRequest, GetBatchChannelPreviewResponse, GetBatchChannelPreviewResponse2, GetBatchChannelPreviewResponses, GetBatchPreviewHandlerData, GetBatchPreviewHandlerError, GetBatchPreviewHandlerErrors, GetBatchPreviewHandlerResponse, GetBatchPreviewHandlerResponses, GetBatchPreviewRequest, GetBatchPreviewResponse, GetBatchProjectPreviewData, GetBatchProjectPreviewError, GetBatchProjectPreviewErrors, GetBatchProjectPreviewRequest, GetBatchProjectPreviewResponse, GetBatchProjectPreviewResponse2, GetBatchProjectPreviewResponses, GetCallRecordData, GetCallRecordError, GetCallRecordErrors, GetCallRecordResponse, GetCallRecordResponses, GetChannelAttachmentsData, GetChannelAttachmentsError, GetChannelAttachmentsErrors, GetChannelAttachmentsResponse, GetChannelAttachmentsResponses, GetChannelData, GetChannelError, GetChannelErrors, GetChannelJoinLinkData, GetChannelJoinLinkError, GetChannelJoinLinkErrors, GetChannelJoinLinkResponse, GetChannelJoinLinkResponses, GetChannelMessagesData, GetChannelMessagesError, GetChannelMessagesErrors, GetChannelMessagesResponse, GetChannelMessagesResponses, GetChannelParticipantsData, GetChannelParticipantsError, GetChannelParticipantsErrors, GetChannelParticipantsResponse, GetChannelParticipantsResponses, GetChannelResponse, GetChannelResponses, GetChannelsData, GetChannelsError, GetChannelsErrors, GetChannelsResponse, GetChannelsResponses, GetCollabSurfaceData, GetCollabSurfaceError, GetCollabSurfaceErrors, GetCollabSurfaceResponse, GetCollabSurfaceResponses, GetCompanyData, GetCompanyError, GetCompanyErrors, GetCompanyResponse, GetCompanyResponses, GetContactByEmailData, GetContactByEmailError, GetContactByEmailErrors, GetContactByEmailResponse, GetContactByEmailResponse2, GetContactByEmailResponses, GetContactData, GetContactError, GetContactErrors, GetContactResponse, GetContactResponses, GetCrmTeamSettingsData, GetCrmTeamSettingsError, GetCrmTeamSettingsErrors, GetCrmTeamSettingsResponse, GetCrmTeamSettingsResponses, GetDocumentAnchorsData, GetDocumentAnchorsError, GetDocumentAnchorsErrors, GetDocumentAnchorsResponse, GetDocumentAnchorsResponses, GetDocumentBranchNameData, GetDocumentBranchNameError, GetDocumentBranchNameErrors, GetDocumentBranchNameResponse, GetDocumentBranchNameResponses, GetDocumentByTeamSlugData, GetDocumentByTeamSlugError, GetDocumentByTeamSlugErrors, GetDocumentByTeamSlugResponse, GetDocumentByTeamSlugResponses, GetDocumentCommentsData, GetDocumentCommentsError, GetDocumentCommentsErrors, GetDocumentCommentsResponse, GetDocumentCommentsResponses, GetDocumentData, GetDocumentError, GetDocumentErrors, GetDocumentGithubPullRequestsData, GetDocumentGithubPullRequestsError, GetDocumentGithubPullRequestsErrors, GetDocumentGithubPullRequestsResponse, GetDocumentGithubPullRequestsResponses, GetDocumentKeyResponse, GetDocumentKeyResponseData, GetDocumentListHandlerData, GetDocumentListHandlerError, GetDocumentListHandlerErrors, GetDocumentListHandlerResponse, GetDocumentListHandlerResponses, GetDocumentListResult, GetDocumentLocationV3Data, GetDocumentLocationV3Error, GetDocumentLocationV3Errors, GetDocumentLocationV3Response, GetDocumentLocationV3Responses, GetDocumentPermissionsResponseDataV2, GetDocumentPermissionsTokenData, GetDocumentPermissionsTokenError, GetDocumentPermissionsTokenErrors, GetDocumentPermissionsTokenResponse, GetDocumentPermissionsTokenResponses, GetDocumentPermissionsV2Data, GetDocumentPermissionsV2Error, GetDocumentPermissionsV2Errors, GetDocumentPermissionsV2Response, GetDocumentPermissionsV2Responses, GetDocumentProcessingResult, GetDocumentProcessingResultData, GetDocumentProcessingResultError, GetDocumentProcessingResultErrors, GetDocumentProcessingResultResponse, GetDocumentProcessingResultResponse2, GetDocumentProcessingResultResponses, GetDocumentResponse, GetDocumentResponse2, GetDocumentResponseData, GetDocumentResponses, GetDocumentSearchResponse, GetDocumentShortIdData, GetDocumentShortIdError, GetDocumentShortIdErrors, GetDocumentShortIdResponse, GetDocumentShortIdResponses, GetDocumentsResponse, GetDocumentTeamShareData, GetDocumentTeamShareError, GetDocumentTeamShareErrors, GetDocumentTeamShareResponse, GetDocumentTeamShareResponses, GetDocumentUserAccessLevelResponse, GetDocumentVersionData, GetDocumentVersionError, GetDocumentVersionErrors, GetDocumentVersionResponse, GetDocumentVersionResponses, GetDocumentViewsHandlerData, GetDocumentViewsHandlerError, GetDocumentViewsHandlerErrors, GetDocumentViewsHandlerResponse, GetDocumentViewsHandlerResponses, GetEntityPermissionData, GetEntityPermissionErrors, GetEntityPermissionResponse, GetEntityPermissionResponses, GetForeignEntityData, GetForeignEntityError, GetForeignEntityErrors, GetForeignEntityResponse, GetForeignEntityResponses, GetHarnessPairingData, GetHarnessPairingError, GetHarnessPairingErrors, GetHarnessPairingResponse, GetHarnessPairingResponses, GetHistoryHandlerData, GetHistoryHandlerError, GetHistoryHandlerErrors, GetHistoryHandlerResponse, GetHistoryHandlerResponses, GetInstructionsDocumentResponse, GetInstructionsHandlerData, GetInstructionsHandlerError, GetInstructionsHandlerErrors, GetInstructionsHandlerResponse, GetInstructionsHandlerResponses, GetItemsSoupData, GetItemsSoupError, GetItemsSoupErrors, GetItemsSoupResponse, GetItemsSoupResponses, GetLocationHandlerData, GetLocationHandlerError, GetLocationHandlerErrors, GetLocationHandlerResponse, GetLocationHandlerResponses, GetMessageWithContextData, GetMessageWithContextError, GetMessageWithContextErrors, GetMessageWithContextResponse, GetMessageWithContextResponse2, GetMessageWithContextResponses, GetOrCreateAction, GetOrCreateCallData, GetOrCreateCallError, GetOrCreateCallErrors, GetOrCreateCallResponse, GetOrCreateCallResponses, GetOrCreateChannelResponse, GetOrCreateDmData, GetOrCreateDmError, GetOrCreateDmErrors, GetOrCreateDmRequest, GetOrCreateDmResponse, GetOrCreateDmResponses, GetOrCreatePrivateData, GetOrCreatePrivateError, GetOrCreatePrivateErrors, GetOrCreatePrivateRequest, GetOrCreatePrivateResponse, GetOrCreatePrivateResponses, GetPendingProjectsHandlerData, GetPendingProjectsHandlerError, GetPendingProjectsHandlerErrors, GetPendingProjectsHandlerResponse, GetPendingProjectsHandlerResponses, GetPinsHandlerData, GetPinsHandlerError, GetPinsHandlerErrors, GetPinsHandlerResponse, GetPinsHandlerResponses, GetPinsResponse, GetProjectContentHandlerData, GetProjectContentHandlerError, GetProjectContentHandlerErrors, GetProjectContentHandlerResponse, GetProjectContentHandlerResponses, GetProjectContentResponse, GetProjectHandlerData, GetProjectHandlerError, GetProjectHandlerErrors, GetProjectHandlerResponse, GetProjectHandlerResponses, GetProjectPermissionsV2Data, GetProjectPermissionsV2Error, GetProjectPermissionsV2Errors, GetProjectPermissionsV2Response, GetProjectPermissionsV2Responses, GetProjectResponse, GetProjectResponseData, GetProjectsHandlerData, GetProjectsHandlerError, GetProjectsHandlerErrors, GetProjectsHandlerResponse, GetProjectsHandlerResponses, GetProjectsResponse, GetProjectUserAccessLevelData, GetProjectUserAccessLevelError, GetProjectUserAccessLevelErrors, GetProjectUserAccessLevelResponse, GetProjectUserAccessLevelResponses, GetReminderData, GetReminderError, GetReminderErrors, GetReminderResponse, GetReminderResponses, GetRingStatusData, GetRingStatusError, GetRingStatusErrors, GetRingStatusResponse, GetRingStatusResponses, GetSelfBotData, GetSelfBotError, GetSelfBotErrors, GetSelfBotResponse, GetSelfBotResponses, GetSystemSkillsHandlerData, GetSystemSkillsHandlerError, GetSystemSkillsHandlerErrors, GetSystemSkillsHandlerResponse, GetSystemSkillsHandlerResponses, GetThreadRepliesData, GetThreadRepliesError, GetThreadRepliesErrors, GetThreadRepliesResponse, GetThreadRepliesResponses, GetUserDocumentsHandlerData, GetUserDocumentsHandlerError, GetUserDocumentsHandlerErrors, GetUserDocumentsHandlerResponse, GetUserDocumentsHandlerResponses, GetUserDocumentViewLocationData, GetUserDocumentViewLocationError, GetUserDocumentViewLocationErrors, GetUserDocumentViewLocationResponse, GetUserDocumentViewLocationResponses, GetUserHistoryResponse, GetViewsHandlerData, GetViewsHandlerError, GetViewsHandlerErrors, GetViewsHandlerResponse, GetViewsHandlerResponses, GetWebhookData, GetWebhookError, GetWebhookErrors, GetWebhookResponse, GetWebhookResponses, GithubPullRequest, GithubPullRequestCheckRun, GithubPullRequestComment, GithubPullRequestsResponse, GroupedInitialParams, GroupedPageParams, GroupedSoupGroupPage, GroupedSoupInitialPage, GroupedSoupPage, GroupedSoupSort, HandlerData, HandlerError, HandlerErrors, HandlerResponse, HandlerResponses, Harness, HarnessAgent, HarnessId, HarnessOwner, HashMap, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, HighlightType, IngestTranscriptData, IngestTranscriptError, IngestTranscriptErrors, IngestTranscriptResponses, InitializeUserDocumentsData, InitializeUserDocumentsError, InitializeUserDocumentsErrors, InitializeUserDocumentsResponse, InitializeUserDocumentsResponses, InstallSyncData, InstallSyncErrors, InteractionReason, Item, ItemWithUserAccessLevel, JobProcessingResultHandlerData, JobProcessingResultHandlerError, JobProcessingResultHandlerErrors, JobProcessingResultHandlerResponse, JobProcessingResultHandlerResponses, JoinChannelByCodeData, JoinChannelByCodeError, JoinChannelByCodeErrors, JoinChannelByCodeResponses, JoinChannelData, JoinChannelError, JoinChannelErrors, JoinChannelResponses, LatestMessage, LeaveCallResponse, LeaveChannelData, LeaveChannelError, LeaveChannelErrors, LeaveChannelResponses, LeaveOrEndCallData, LeaveOrEndCallError, LeaveOrEndCallErrors, LeaveOrEndCallResponse, LeaveOrEndCallResponses, LinkShare, ListAgentsData, ListAgentsError, ListAgentsErrors, ListAgentsResponse, ListAgentsResponses, ListBotChannelsData, ListBotChannelsError, ListBotChannelsErrors, ListBotChannelsResponse, ListBotChannelsResponses, ListCompanyContactsData, ListCompanyContactsError, ListCompanyContactsErrors, ListCompanyContactsResponse, ListCompanyContactsResponses, ListCrmCommentsData, ListCrmCommentsError, ListCrmCommentsErrors, ListCrmCommentsResponse, ListCrmCommentsResponses, ListFavoritesData, ListFavoritesError, ListFavoritesErrors, ListFavoritesResponse, ListFavoritesResponses, ListHarnessAgentsData, ListHarnessAgentsError, ListHarnessAgentsErrors, ListHarnessAgentsResponse, ListHarnessAgentsResponses, ListHarnessesData, ListHarnessesError, ListHarnessesErrors, ListHarnessesResponse, ListHarnessesResponses, ListOccurrencesData, ListOccurrencesErrors, ListOccurrencesResponse, ListOccurrencesResponses, ListRemindersData, ListRemindersError, ListRemindersErrors, ListRemindersResponse, ListRemindersResponses, ListUserApiKeysData, ListUserApiKeysError, ListUserApiKeysErrors, ListUserApiKeysResponse, ListUserApiKeysResponses, ListWebhooksData, ListWebhooksError, ListWebhooksErrors, ListWebhooksResponse, ListWebhooksResponse2, ListWebhooksResponses, LocationResponseData, LocationResponseV3, MacroUserIdStr, MentionPreviewsData, MentionPreviewsErrors, MentionPreviewsResponse, MentionPreviewsResponses, Mentions, NewChannelAttachment, NotificationFilters, PairingDetails, Params, ParticipantRole, PatchBotRequest, PatchChannelData, PatchChannelError, PatchChannelErrors, PatchChannelRequest, PatchChannelResponse, PatchChannelResponses, PatchMessageData, PatchMessageError, PatchMessageErrors, PatchMessageRequest, PatchMessageResponse, PatchMessageResponses, PatchProjectRequestV2, PatchThreadRequestV2, PatchViewHandlerData, PatchViewHandlerError, PatchViewHandlerErrors, PatchViewHandlerResponses, PatchWebhookData, PatchWebhookError, PatchWebhookErrors, PatchWebhookRequest, PatchWebhookResponse, PatchWebhookResponses, PdfAnchor, PdfAnchorId, PdfAnchorRequest, PdfHighlightAnchor, PdfHighlightAnchorRequest, PdfHighlightRect, PdfHighlightRectAnchorRequest, PdfPlaceableCommentAnchor, PdfPlaceableCommentAnchorRequest, PendingClaimResponse, PermanentlyDeleteDocumentData, PermanentlyDeleteDocumentError, PermanentlyDeleteDocumentErrors, PermanentlyDeleteDocumentResponse, PermanentlyDeleteDocumentResponses, PermanentlyDeleteProjectData, PermanentlyDeleteProjectError, PermanentlyDeleteProjectErrors, PermanentlyDeleteProjectResponse, PermanentlyDeleteProjectResponses, PinnedItem, PinRequest, PostActivityData, PostActivityError, PostActivityErrors, PostActivityRequest, PostActivityResponse, PostActivityResponses, PostChannelBotWebhookData, PostChannelBotWebhookError, PostChannelBotWebhookErrors, PostChannelBotWebhookResponse, PostChannelBotWebhookResponses, PostChannelMessagesData, PostChannelMessagesError, PostChannelMessagesErrors, PostChannelMessagesResponse, PostChannelMessagesResponses, PostGroupedSoupAstGroupPageRequest, PostGroupedSoupAstInitialRequest, PostGroupedSoupAstRequest, PostItemsSoupAstData, PostItemsSoupAstError, PostItemsSoupAstErrors, PostItemsSoupAstGroupedData, PostItemsSoupAstGroupedError, PostItemsSoupAstGroupedErrors, PostItemsSoupAstGroupedResponse, PostItemsSoupAstGroupedResponses, PostItemsSoupAstResponse, PostItemsSoupAstResponses, PostItemsSoupData, PostItemsSoupError, PostItemsSoupErrors, PostItemsSoupResponse, PostItemsSoupResponses, PostMessageData, PostMessageError, PostMessageErrors, PostMessageRequest, PostMessageResponse, PostMessageResponse2, PostMessageResponses, PostReactionData, PostReactionError, PostReactionErrors, PostReactionRequest, PostReactionResponse, PostReactionResponses, PostSoupAstRequest, PostSoupRequest, PostTypingData, PostTypingError, PostTypingErrors, PostTypingRequest, PostTypingResponse, PostTypingResponses, PresaveDocumentHandlerData, PresaveDocumentHandlerError, PresaveDocumentHandlerErrors, PresaveDocumentHandlerResponse, PresaveDocumentHandlerResponses, PreSaveDocumentRequest, PreSaveDocumentResponse, PreSaveDocumentResponseData, PresignedUrl, Project, ProjectDeleteResponseData, ProjectDocumentStatus, ProjectFilters, ProjectPreview, ProjectPreviewData, PropertyDefinition, PropertyFilter, PropertyInput, PropertyOwner, PropertyValue, PutCrmTeamSettingsData, PutCrmTeamSettingsError, PutCrmTeamSettingsErrors, PutCrmTeamSettingsResponse, PutCrmTeamSettingsResponses, ReactionAction, RecentlyDeletedData, RecentlyDeletedError, RecentlyDeletedErrors, RecentlyDeletedResponse, RecentlyDeletedResponseData, RecentlyDeletedResponses, Reminder, ReminderFilters, ReminderSchedule, RemindersList, RemoveBotFromChannelByBotData, RemoveBotFromChannelByBotError, RemoveBotFromChannelByBotErrors, RemoveBotFromChannelByBotResponse, RemoveBotFromChannelByBotResponses, RemoveFavoriteByEntityData, RemoveFavoriteByEntityError, RemoveFavoriteByEntityErrors, RemoveFavoriteByEntityResponses, RemoveParticipantsData, RemoveParticipantsError, RemoveParticipantsErrors, RemoveParticipantsRequest, RemoveParticipantsResponses, RemovePinHandlerData, RemovePinHandlerError, RemovePinHandlerErrors, RemovePinHandlerResponse, RemovePinHandlerResponses, ReorderFavoritesData, ReorderFavoritesError, ReorderFavoritesErrors, ReorderFavoritesRequest, ReorderFavoritesResponses, ReorderPinRequest, ReorderPinsHandlerData, ReorderPinsHandlerError, ReorderPinsHandlerErrors, ReorderPinsHandlerResponse, ReorderPinsHandlerResponses, RequestedHarnessScope, ResolveChannelMessageData, ResolveChannelMessageError, ResolveChannelMessageErrors, ResolveChannelMessageResponse, ResolveChannelMessageResponses, RevertDeleteDocumentData, RevertDeleteDocumentError, RevertDeleteDocumentErrors, RevertDeleteDocumentResponse, RevertDeleteDocumentResponses, RevertDeleteProjectData, RevertDeleteProjectError, RevertDeleteProjectErrors, RevertDeleteProjectResponse, RevertDeleteProjectResponses, RingStatus, RingStatusResponse, S3ObjectInfo, SaveBomPart, SaveDocumentHandlerData, SaveDocumentHandlerError, SaveDocumentHandlerErrors, SaveDocumentHandlerResponse, SaveDocumentHandlerResponses, SaveDocumentRequest, SaveDocumentResponse, SaveDocumentResponseData, SetCompanyHiddenData, SetCompanyHiddenError, SetCompanyHiddenErrors, SetCompanyHiddenRequest, SetCompanyHiddenResponse, SetCompanyHiddenResponses, SetCompanyNameRequest, SetContactHiddenData, SetContactHiddenError, SetContactHiddenErrors, SetContactHiddenRequest, SetContactHiddenResponse, SetContactHiddenResponses, SetContactNameRequest, SetCrmCompanyNameData, SetCrmCompanyNameError, SetCrmCompanyNameErrors, SetCrmCompanyNameResponse, SetCrmCompanyNameResponses, SetCrmContactNameData, SetCrmContactNameError, SetCrmContactNameErrors, SetCrmContactNameResponse, SetCrmContactNameResponses, SetDocumentTeamShareData, SetDocumentTeamShareError, SetDocumentTeamShareErrors, SetDocumentTeamShareRequest, SetDocumentTeamShareResponse, SetDocumentTeamShareResponses, SetEmailSyncData, SetEmailSyncError, SetEmailSyncErrors, SetEmailSyncRequest, SetEmailSyncResponse, SetEmailSyncResponses, SetPropertyValue, SharedEmailFilter, SharePermissionV2, ShortIdResponse, SimpleMention, SimpleSaveData, SimpleSaveError, SimpleSaveErrors, SimpleSaveResponse, SimpleSaveResponses, SoupApiItem, SoupApiSort, SoupApiSortDirection, SoupAttachment, SoupCalendarEventSoupPropertiesField, SoupCalendarEventTime, SoupCallRecordParticipant, SoupCallRecordSoupPropertiesField, SoupChannel, SoupChannelThread, SoupChatSoupPropertiesField, SoupContact, SoupCountedReaction, SoupCrmCompanySoupPropertiesField, SoupCrmDomain, SoupDocumentSoupPropertiesField, SoupDocumentSubType, SoupEmailThreadPreview, SoupEnrichedEmailThreadPreviewSoupPropertiesField, SoupForeignEntity, SoupItem, SoupLabel, SoupLabelListVisibility, SoupLabelType, SoupMessageAttachment, SoupMessageListVisibility, SoupMessageSender, SoupMessageSenderType, SoupPage, SoupProjectSoupPropertiesField, SoupPropertiesField, SoupProperty, SoupReminderReference, SoupReminderSchedule, SoupReminderSoupPropertiesField, SoupThreadInfo, SoupThreadReply, StarterDocumentsResponse, String, SuccessResponse, SurfaceState, SyncServiceVersionId, SystemSkillSummary, TagFilterMode, TaskFilters, TeamRole, Thread, ThreadResponse, ToggleShareWithTeamData, ToggleShareWithTeamError, ToggleShareWithTeamErrors, ToggleShareWithTeamResponse, ToggleShareWithTeamResponses, TranscriptSegmentRequest, TypedSuccessResponse, TypedSuccessResponseGetDocumentResponseData, TypingAction, UnthreadedPdfUuidRequest, UpdateAgentData, UpdateAgentError, UpdateAgentErrors, UpdateAgentRequest, UpdateAgentResponse, UpdateAgentResponses, UpdateChannelSharePermission, UpdateCrmTeamSettingsRequest, UpdateOperation, UpdateReminderData, UpdateReminderError, UpdateReminderErrors, UpdateReminderRequest, UpdateReminderResponse, UpdateReminderResponses, UpdateSharePermissionRequestV2, UploadDocumentStatus, UploadExtractFolderHandlerData, UploadExtractFolderHandlerError, UploadExtractFolderHandlerErrors, UploadExtractFolderHandlerResponse, UploadExtractFolderHandlerResponses, UploadExtractFolderRequest, UploadFolderHandlerData, UploadFolderHandlerError, UploadFolderHandlerErrors, UploadFolderHandlerResponse, UploadFolderHandlerResponses, UploadFolderRequest, UpsertHistoryHandlerData, UpsertHistoryHandlerError, UpsertHistoryHandlerErrors, UpsertHistoryHandlerResponse, UpsertHistoryHandlerResponses, UpsertUserDocumentViewLocationData, UpsertUserDocumentViewLocationError, UpsertUserDocumentViewLocationErrors, UpsertUserDocumentViewLocationRequest, UpsertUserDocumentViewLocationResponse, UpsertUserDocumentViewLocationResponses, UserApiKeyId, UserApiKeyInfo, UserApiKeysList, UserDocumentsResponse, UserDocumentViewLocation, UserDocumentViewLocationResponse, UserPinsResponse, UserViewsResponse, ValidateDocumentPermissionsTokenData, ValidateDocumentPermissionsTokenError, ValidateDocumentPermissionsTokenErrors, ValidateDocumentPermissionsTokenResponse, ValidateDocumentPermissionsTokenResponses, ValidateWebhookData, ValidateWebhookError, ValidateWebhookErrors, ValidateWebhookResponse, ValidateWebhookResponse2, ValidateWebhookResponses, Vec, View, ViewPatch, ViewsResponse, Webhook, WebhookEvent, WebhookFilter, WebhookScope, WebhookStatus, WebhookValidationTestEvent, WithCallId, WithChannelId, WithDocumentId, WithProjectId } from './types.gen';diff --git a/packages/sdk/generated/storage/sdk.gen.ts b/packages/sdk/generated/storage/sdk.gen.tsindex 6289590bec..1a99837c8c 100644--- a/packages/sdk/generated/storage/sdk.gen.ts+++ b/packages/sdk/generated/storage/sdk.gen.ts@@ -2,7 +2,7 @@import type { Client, ClientMeta, Options as Options2, RequestResult, TDataShape } from './client';import { client } from './client.gen';-import type { AddFavoriteData, AddFavoriteErrors, AddFavoriteResponses, AddParticipantsData, AddParticipantsErrors, AddParticipantsResponses, AddPinHandlerData, AddPinHandlerErrors, AddPinHandlerResponses, BulkWakeupSyncServiceDocumentsData, BulkWakeupSyncServiceDocumentsErrors, BulkWakeupSyncServiceDocumentsResponses, CallWebhookData, CallWebhookErrors, CallWebhookResponses, CheckActiveCallData, CheckActiveCallErrors, CheckActiveCallResponses, CopyDocumentData, CopyDocumentErrors, CopyDocumentResponses, CreateAgentData, CreateAgentErrors, CreateAgentResponses, CreateAnchorData, CreateAnchorErrors, CreateAnchorResponses, CreateChannelData, CreateChannelErrors, CreateChannelResponses, CreateChannelScopedBotData, CreateChannelScopedBotErrors, CreateChannelScopedBotResponses, CreateCollabSurfaceTokenData, CreateCollabSurfaceTokenErrors, CreateCollabSurfaceTokenResponses, CreateCommentData, CreateCommentErrors, CreateCommentResponses, CreateCrmCommentData, CreateCrmCommentErrors, CreateCrmCommentResponses, CreateCrmCompanyData, CreateCrmCompanyErrors, CreateCrmCompanyResponses, CreateCrmContactData, CreateCrmContactErrors, CreateCrmContactResponses, CreateDocumentData, CreateDocumentErrors, CreateDocumentResponses, CreateEntityMentionData, CreateEntityMentionErrors, CreateEntityMentionResponses, CreateInstructionsHandlerData, CreateInstructionsHandlerErrors, CreateInstructionsHandlerResponses, CreateMarkdownHandlerData, CreateMarkdownHandlerErrors, CreateMarkdownHandlerResponses, CreateProjectHandlerData, CreateProjectHandlerErrors, CreateProjectHandlerResponses, CreateReminderData, CreateReminderErrors, CreateReminderResponses, CreateSkillHandlerData, CreateSkillHandlerErrors, CreateSkillHandlerResponses, CreateSnippetHandlerData, CreateSnippetHandlerErrors, CreateSnippetHandlerResponses, CreateTaskHandlerData, CreateTaskHandlerErrors, CreateTaskHandlerResponses, CreateUserApiKeyData, CreateUserApiKeyErrors, CreateUserApiKeyResponses, CreateViewHandlerData, CreateViewHandlerErrors, CreateViewHandlerResponses, CreateWebhookData, CreateWebhookErrors, CreateWebhookResponses, DeleteAnchorData, DeleteAnchorErrors, DeleteAnchorResponses, DeleteCallRecordData, DeleteCallRecordErrors, DeleteCallRecordResponses, DeleteChannelData, DeleteChannelErrors, DeleteChannelResponses, DeleteCollabSurfaceData, DeleteCollabSurfaceErrors, DeleteCollabSurfaceResponses, DeleteCommentData, DeleteCommentErrors, DeleteCommentResponses, DeleteCrmCommentData, DeleteCrmCommentErrors, DeleteCrmCommentResponses, DeleteDocumentData, DeleteDocumentErrors, DeleteDocumentResponses, DeleteEntityMentionData, DeleteEntityMentionErrors, DeleteEntityMentionResponses, DeleteHistoryHandlerData, DeleteHistoryHandlerErrors, DeleteHistoryHandlerResponses, DeleteMessageData, DeleteMessageErrors, DeleteMessageResponses, DeleteProjectHandlerData, DeleteProjectHandlerErrors, DeleteProjectHandlerResponses, DeleteReminderData, DeleteReminderErrors, DeleteReminderResponses, DeleteUserApiKeyData, DeleteUserApiKeyErrors, DeleteUserApiKeyResponses, DeleteUserDocumentViewLocationData, DeleteUserDocumentViewLocationErrors, DeleteUserDocumentViewLocationResponses, DeleteViewHandlerData, DeleteViewHandlerErrors, DeleteViewHandlerResponses, DeleteWebhookData, DeleteWebhookErrors, DeleteWebhookResponses, EditAnchorData, EditAnchorErrors, EditAnchorResponses, EditCallRecordData, EditCallRecordErrors, EditCallRecordResponses, EditCallTranscriptData, EditCallTranscriptErrors, EditCallTranscriptResponses, EditCommentData, EditCommentErrors, EditCommentResponses, EditCrmCommentData, EditCrmCommentErrors, EditCrmCommentResponses, EditDocumentData, EditDocumentErrors, EditDocumentResponses, EditProjectV2Data, EditProjectV2Errors, EditProjectV2Responses, EditThreadV2Data, EditThreadV2Errors, EditThreadV2Responses, EnsureCollabSurfaceData, EnsureCollabSurfaceErrors, EnsureCollabSurfaceResponses, ExcludeDefaultViewHandlerData, ExcludeDefaultViewHandlerErrors, ExcludeDefaultViewHandlerResponses, ExportDocumentData, ExportDocumentErrors, ExportDocumentResponses, GetActiveCallsData, GetActiveCallsErrors, GetActiveCallsResponses, GetActivityData, GetActivityErrors, GetActivityResponses, GetAttachmentReferencesData, GetAttachmentReferencesErrors, GetAttachmentReferencesResponses, GetBatchCallRecordPreviewData, GetBatchCallRecordPreviewErrors, GetBatchCallRecordPreviewResponses, GetBatchChannelPreviewData, GetBatchChannelPreviewErrors, GetBatchChannelPreviewResponses, GetBatchPreviewHandlerData, GetBatchPreviewHandlerErrors, GetBatchPreviewHandlerResponses, GetBatchProjectPreviewData, GetBatchProjectPreviewErrors, GetBatchProjectPreviewResponses, GetCallRecordData, GetCallRecordErrors, GetCallRecordResponses, GetChannelAttachmentsData, GetChannelAttachmentsErrors, GetChannelAttachmentsResponses, GetChannelData, GetChannelErrors, GetChannelJoinLinkData, GetChannelJoinLinkErrors, GetChannelJoinLinkResponses, GetChannelMessagesData, GetChannelMessagesErrors, GetChannelMessagesResponses, GetChannelParticipantsData, GetChannelParticipantsErrors, GetChannelParticipantsResponses, GetChannelResponses, GetChannelsData, GetChannelsErrors, GetChannelsResponses, GetCollabSurfaceData, GetCollabSurfaceErrors, GetCollabSurfaceResponses, GetCompanyData, GetCompanyErrors, GetCompanyResponses, GetContactByEmailData, GetContactByEmailErrors, GetContactByEmailResponses, GetContactData, GetContactErrors, GetContactResponses, GetCrmTeamSettingsData, GetCrmTeamSettingsErrors, GetCrmTeamSettingsResponses, GetDocumentAnchorsData, GetDocumentAnchorsErrors, GetDocumentAnchorsResponses, GetDocumentBranchNameData, GetDocumentBranchNameErrors, GetDocumentBranchNameResponses, GetDocumentByTeamSlugData, GetDocumentByTeamSlugErrors, GetDocumentByTeamSlugResponses, GetDocumentCommentsData, GetDocumentCommentsErrors, GetDocumentCommentsResponses, GetDocumentData, GetDocumentErrors, GetDocumentGithubPullRequestsData, GetDocumentGithubPullRequestsErrors, GetDocumentGithubPullRequestsResponses, GetDocumentListHandlerData, GetDocumentListHandlerErrors, GetDocumentListHandlerResponses, GetDocumentLocationV3Data, GetDocumentLocationV3Errors, GetDocumentLocationV3Responses, GetDocumentPermissionsTokenData, GetDocumentPermissionsTokenErrors, GetDocumentPermissionsTokenResponses, GetDocumentPermissionsV2Data, GetDocumentPermissionsV2Errors, GetDocumentPermissionsV2Responses, GetDocumentProcessingResultData, GetDocumentProcessingResultErrors, GetDocumentProcessingResultResponses, GetDocumentResponses, GetDocumentShortIdData, GetDocumentShortIdErrors, GetDocumentShortIdResponses, GetDocumentTeamShareData, GetDocumentTeamShareErrors, GetDocumentTeamShareResponses, GetDocumentVersionData, GetDocumentVersionErrors, GetDocumentVersionResponses, GetDocumentViewsHandlerData, GetDocumentViewsHandlerErrors, GetDocumentViewsHandlerResponses, GetEntityPermissionData, GetEntityPermissionErrors, GetEntityPermissionResponses, GetForeignEntityData, GetForeignEntityErrors, GetForeignEntityResponses, GetHistoryHandlerData, GetHistoryHandlerErrors, GetHistoryHandlerResponses, GetInstructionsHandlerData, GetInstructionsHandlerErrors, GetInstructionsHandlerResponses, GetItemsSoupData, GetItemsSoupErrors, GetItemsSoupResponses, GetLocationHandlerData, GetLocationHandlerErrors, GetLocationHandlerResponses, GetMessageWithContextData, GetMessageWithContextErrors, GetMessageWithContextResponses, GetOrCreateCallData, GetOrCreateCallErrors, GetOrCreateCallResponses, GetOrCreateDmData, GetOrCreateDmErrors, GetOrCreateDmResponses, GetOrCreatePrivateData, GetOrCreatePrivateErrors, GetOrCreatePrivateResponses, GetPendingProjectsHandlerData, GetPendingProjectsHandlerErrors, GetPendingProjectsHandlerResponses, GetPinsHandlerData, GetPinsHandlerErrors, GetPinsHandlerResponses, GetProjectContentHandlerData, GetProjectContentHandlerErrors, GetProjectContentHandlerResponses, GetProjectHandlerData, GetProjectHandlerErrors, GetProjectHandlerResponses, GetProjectPermissionsV2Data, GetProjectPermissionsV2Errors, GetProjectPermissionsV2Responses, GetProjectsHandlerData, GetProjectsHandlerErrors, GetProjectsHandlerResponses, GetProjectUserAccessLevelData, GetProjectUserAccessLevelErrors, GetProjectUserAccessLevelResponses, GetReminderData, GetReminderErrors, GetReminderResponses, GetRingStatusData, GetRingStatusErrors, GetRingStatusResponses, GetSelfBotData, GetSelfBotErrors, GetSelfBotResponses, GetSystemSkillsHandlerData, GetSystemSkillsHandlerErrors, GetSystemSkillsHandlerResponses, GetThreadRepliesData, GetThreadRepliesErrors, GetThreadRepliesResponses, GetUserDocumentsHandlerData, GetUserDocumentsHandlerErrors, GetUserDocumentsHandlerResponses, GetUserDocumentViewLocationData, GetUserDocumentViewLocationErrors, GetUserDocumentViewLocationResponses, GetViewsHandlerData, GetViewsHandlerErrors, GetViewsHandlerResponses, GetWebhookData, GetWebhookErrors, GetWebhookResponses, HandlerData, HandlerErrors, HandlerResponses, HealthHandlerData, HealthHandlerResponses, IngestTranscriptData, IngestTranscriptErrors, IngestTranscriptResponses, InitializeUserDocumentsData, InitializeUserDocumentsErrors, InitializeUserDocumentsResponses, InstallSyncData, InstallSyncErrors, JobProcessingResultHandlerData, JobProcessingResultHandlerErrors, JobProcessingResultHandlerResponses, JoinChannelByCodeData, JoinChannelByCodeErrors, JoinChannelByCodeResponses, JoinChannelData, JoinChannelErrors, JoinChannelResponses, LeaveChannelData, LeaveChannelErrors, LeaveChannelResponses, LeaveOrEndCallData, LeaveOrEndCallErrors, LeaveOrEndCallResponses, ListAgentsData, ListAgentsErrors, ListAgentsResponses, ListBotChannelsData, ListBotChannelsErrors, ListBotChannelsResponses, ListCompanyContactsData, ListCompanyContactsErrors, ListCompanyContactsResponses, ListCrmCommentsData, ListCrmCommentsErrors, ListCrmCommentsResponses, ListFavoritesData, ListFavoritesErrors, ListFavoritesResponses, ListOccurrencesData, ListOccurrencesErrors, ListOccurrencesResponses, ListRemindersData, ListRemindersErrors, ListRemindersResponses, ListUserApiKeysData, ListUserApiKeysErrors, ListUserApiKeysResponses, ListWebhooksData, ListWebhooksErrors, ListWebhooksResponses, MentionPreviewsData, MentionPreviewsErrors, MentionPreviewsResponses, PatchChannelData, PatchChannelErrors, PatchChannelResponses, PatchMessageData, PatchMessageErrors, PatchMessageResponses, PatchViewHandlerData, PatchViewHandlerErrors, PatchViewHandlerResponses, PatchWebhookData, PatchWebhookErrors, PatchWebhookResponses, PermanentlyDeleteDocumentData, PermanentlyDeleteDocumentErrors, PermanentlyDeleteDocumentResponses, PermanentlyDeleteProjectData, PermanentlyDeleteProjectErrors, PermanentlyDeleteProjectResponses, PostActivityData, PostActivityErrors, PostActivityResponses, PostChannelBotWebhookData, PostChannelBotWebhookErrors, PostChannelBotWebhookResponses, PostChannelMessagesData, PostChannelMessagesErrors, PostChannelMessagesResponses, PostItemsSoupAstData, PostItemsSoupAstErrors, PostItemsSoupAstGroupedData, PostItemsSoupAstGroupedErrors, PostItemsSoupAstGroupedResponses, PostItemsSoupAstResponses, PostItemsSoupData, PostItemsSoupErrors, PostItemsSoupResponses, PostMessageData, PostMessageErrors, PostMessageResponses, PostReactionData, PostReactionErrors, PostReactionResponses, PostTypingData, PostTypingErrors, PostTypingResponses, PresaveDocumentHandlerData, PresaveDocumentHandlerErrors, PresaveDocumentHandlerResponses, PutCrmTeamSettingsData, PutCrmTeamSettingsErrors, PutCrmTeamSettingsResponses, RecentlyDeletedData, RecentlyDeletedErrors, RecentlyDeletedResponses, RemoveBotFromChannelByBotData, RemoveBotFromChannelByBotErrors, RemoveBotFromChannelByBotResponses, RemoveFavoriteByEntityData, RemoveFavoriteByEntityErrors, RemoveFavoriteByEntityResponses, RemoveParticipantsData, RemoveParticipantsErrors, RemoveParticipantsResponses, RemovePinHandlerData, RemovePinHandlerErrors, RemovePinHandlerResponses, ReorderFavoritesData, ReorderFavoritesErrors, ReorderFavoritesResponses, ReorderPinsHandlerData, ReorderPinsHandlerErrors, ReorderPinsHandlerResponses, ResolveChannelMessageData, ResolveChannelMessageErrors, ResolveChannelMessageResponses, RevertDeleteDocumentData, RevertDeleteDocumentErrors, RevertDeleteDocumentResponses, RevertDeleteProjectData, RevertDeleteProjectErrors, RevertDeleteProjectResponses, SaveDocumentHandlerData, SaveDocumentHandlerErrors, SaveDocumentHandlerResponses, SetCompanyHiddenData, SetCompanyHiddenErrors, SetCompanyHiddenResponses, SetContactHiddenData, SetContactHiddenErrors, SetContactHiddenResponses, SetCrmCompanyNameData, SetCrmCompanyNameErrors, SetCrmCompanyNameResponses, SetCrmContactNameData, SetCrmContactNameErrors, SetCrmContactNameResponses, SetDocumentTeamShareData, SetDocumentTeamShareErrors, SetDocumentTeamShareResponses, SetEmailSyncData, SetEmailSyncErrors, SetEmailSyncResponses, SimpleSaveData, SimpleSaveErrors, SimpleSaveResponses, ToggleShareWithTeamData, ToggleShareWithTeamErrors, ToggleShareWithTeamResponses, UpdateAgentData, UpdateAgentErrors, UpdateAgentResponses, UpdateReminderData, UpdateReminderErrors, UpdateReminderResponses, UploadExtractFolderHandlerData, UploadExtractFolderHandlerErrors, UploadExtractFolderHandlerResponses, UploadFolderHandlerData, UploadFolderHandlerErrors, UploadFolderHandlerResponses, UpsertHistoryHandlerData, UpsertHistoryHandlerErrors, UpsertHistoryHandlerResponses, UpsertUserDocumentViewLocationData, UpsertUserDocumentViewLocationErrors, UpsertUserDocumentViewLocationResponses, ValidateDocumentPermissionsTokenData, ValidateDocumentPermissionsTokenErrors, ValidateDocumentPermissionsTokenResponses, ValidateWebhookData, ValidateWebhookErrors, ValidateWebhookResponses } from './types.gen';+import type { AddFavoriteData, AddFavoriteErrors, AddFavoriteResponses, AddParticipantsData, AddParticipantsErrors, AddParticipantsResponses, AddPinHandlerData, AddPinHandlerErrors, AddPinHandlerResponses, ApproveHarnessPairingData, ApproveHarnessPairingErrors, ApproveHarnessPairingResponses, BulkWakeupSyncServiceDocumentsData, BulkWakeupSyncServiceDocumentsErrors, BulkWakeupSyncServiceDocumentsResponses, CallWebhookData, CallWebhookErrors, CallWebhookResponses, CheckActiveCallData, CheckActiveCallErrors, CheckActiveCallResponses, ClaimHarnessPairingData, ClaimHarnessPairingErrors, ClaimHarnessPairingResponses, CopyDocumentData, CopyDocumentErrors, CopyDocumentResponses, CreateAgentData, CreateAgentErrors, CreateAgentResponses, CreateAnchorData, CreateAnchorErrors, CreateAnchorResponses, CreateChannelData, CreateChannelErrors, CreateChannelResponses, CreateChannelScopedBotData, CreateChannelScopedBotErrors, CreateChannelScopedBotResponses, CreateCollabSurfaceTokenData, CreateCollabSurfaceTokenErrors, CreateCollabSurfaceTokenResponses, CreateCommentData, CreateCommentErrors, CreateCommentResponses, CreateCrmCommentData, CreateCrmCommentErrors, CreateCrmCommentResponses, CreateCrmCompanyData, CreateCrmCompanyErrors, CreateCrmCompanyResponses, CreateCrmContactData, CreateCrmContactErrors, CreateCrmContactResponses, CreateDocumentData, CreateDocumentErrors, CreateDocumentResponses, CreateEntityMentionData, CreateEntityMentionErrors, CreateEntityMentionResponses, CreateHarnessPairingData, CreateHarnessPairingErrors, CreateHarnessPairingResponses, CreateInstructionsHandlerData, CreateInstructionsHandlerErrors, CreateInstructionsHandlerResponses, CreateMarkdownHandlerData, CreateMarkdownHandlerErrors, CreateMarkdownHandlerResponses, CreateProjectHandlerData, CreateProjectHandlerErrors, CreateProjectHandlerResponses, CreateReminderData, CreateReminderErrors, CreateReminderResponses, CreateSkillHandlerData, CreateSkillHandlerErrors, CreateSkillHandlerResponses, CreateSnippetHandlerData, CreateSnippetHandlerErrors, CreateSnippetHandlerResponses, CreateTaskHandlerData, CreateTaskHandlerErrors, CreateTaskHandlerResponses, CreateUserApiKeyData, CreateUserApiKeyErrors, CreateUserApiKeyResponses, CreateViewHandlerData, CreateViewHandlerErrors, CreateViewHandlerResponses, CreateWebhookData, CreateWebhookErrors, CreateWebhookResponses, DeleteAnchorData, DeleteAnchorErrors, DeleteAnchorResponses, DeleteCallRecordData, DeleteCallRecordErrors, DeleteCallRecordResponses, DeleteChannelData, DeleteChannelErrors, DeleteChannelResponses, DeleteCollabSurfaceData, DeleteCollabSurfaceErrors, DeleteCollabSurfaceResponses, DeleteCommentData, DeleteCommentErrors, DeleteCommentResponses, DeleteCrmCommentData, DeleteCrmCommentErrors, DeleteCrmCommentResponses, DeleteDocumentData, DeleteDocumentErrors, DeleteDocumentResponses, DeleteEntityMentionData, DeleteEntityMentionErrors, DeleteEntityMentionResponses, DeleteHarnessData, DeleteHarnessErrors, DeleteHarnessResponses, DeleteHistoryHandlerData, DeleteHistoryHandlerErrors, DeleteHistoryHandlerResponses, DeleteMessageData, DeleteMessageErrors, DeleteMessageResponses, DeleteProjectHandlerData, DeleteProjectHandlerErrors, DeleteProjectHandlerResponses, DeleteReminderData, DeleteReminderErrors, DeleteReminderResponses, DeleteUserApiKeyData, DeleteUserApiKeyErrors, DeleteUserApiKeyResponses, DeleteUserDocumentViewLocationData, DeleteUserDocumentViewLocationErrors, DeleteUserDocumentViewLocationResponses, DeleteViewHandlerData, DeleteViewHandlerErrors, DeleteViewHandlerResponses, DeleteWebhookData, DeleteWebhookErrors, DeleteWebhookResponses, EditAnchorData, EditAnchorErrors, EditAnchorResponses, EditCallRecordData, EditCallRecordErrors, EditCallRecordResponses, EditCallTranscriptData, EditCallTranscriptErrors, EditCallTranscriptResponses, EditCommentData, EditCommentErrors, EditCommentResponses, EditCrmCommentData, EditCrmCommentErrors, EditCrmCommentResponses, EditDocumentData, EditDocumentErrors, EditDocumentResponses, EditProjectV2Data, EditProjectV2Errors, EditProjectV2Responses, EditThreadV2Data, EditThreadV2Errors, EditThreadV2Responses, EnsureCollabSurfaceData, EnsureCollabSurfaceErrors, EnsureCollabSurfaceResponses, ExcludeDefaultViewHandlerData, ExcludeDefaultViewHandlerErrors, ExcludeDefaultViewHandlerResponses, ExportDocumentData, ExportDocumentErrors, ExportDocumentResponses, GetActiveCallsData, GetActiveCallsErrors, GetActiveCallsResponses, GetActivityData, GetActivityErrors, GetActivityResponses, GetAttachmentReferencesData, GetAttachmentReferencesErrors, GetAttachmentReferencesResponses, GetBatchCallRecordPreviewData, GetBatchCallRecordPreviewErrors, GetBatchCallRecordPreviewResponses, GetBatchChannelPreviewData, GetBatchChannelPreviewErrors, GetBatchChannelPreviewResponses, GetBatchPreviewHandlerData, GetBatchPreviewHandlerErrors, GetBatchPreviewHandlerResponses, GetBatchProjectPreviewData, GetBatchProjectPreviewErrors, GetBatchProjectPreviewResponses, GetCallRecordData, GetCallRecordErrors, GetCallRecordResponses, GetChannelAttachmentsData, GetChannelAttachmentsErrors, GetChannelAttachmentsResponses, GetChannelData, GetChannelErrors, GetChannelJoinLinkData, GetChannelJoinLinkErrors, GetChannelJoinLinkResponses, GetChannelMessagesData, GetChannelMessagesErrors, GetChannelMessagesResponses, GetChannelParticipantsData, GetChannelParticipantsErrors, GetChannelParticipantsResponses, GetChannelResponses, GetChannelsData, GetChannelsErrors, GetChannelsResponses, GetCollabSurfaceData, GetCollabSurfaceErrors, GetCollabSurfaceResponses, GetCompanyData, GetCompanyErrors, GetCompanyResponses, GetContactByEmailData, GetContactByEmailErrors, GetContactByEmailResponses, GetContactData, GetContactErrors, GetContactResponses, GetCrmTeamSettingsData, GetCrmTeamSettingsErrors, GetCrmTeamSettingsResponses, GetDocumentAnchorsData, GetDocumentAnchorsErrors, GetDocumentAnchorsResponses, GetDocumentBranchNameData, GetDocumentBranchNameErrors, GetDocumentBranchNameResponses, GetDocumentByTeamSlugData, GetDocumentByTeamSlugErrors, GetDocumentByTeamSlugResponses, GetDocumentCommentsData, GetDocumentCommentsErrors, GetDocumentCommentsResponses, GetDocumentData, GetDocumentErrors, GetDocumentGithubPullRequestsData, GetDocumentGithubPullRequestsErrors, GetDocumentGithubPullRequestsResponses, GetDocumentListHandlerData, GetDocumentListHandlerErrors, GetDocumentListHandlerResponses, GetDocumentLocationV3Data, GetDocumentLocationV3Errors, GetDocumentLocationV3Responses, GetDocumentPermissionsTokenData, GetDocumentPermissionsTokenErrors, GetDocumentPermissionsTokenResponses, GetDocumentPermissionsV2Data, GetDocumentPermissionsV2Errors, GetDocumentPermissionsV2Responses, GetDocumentProcessingResultData, GetDocumentProcessingResultErrors, GetDocumentProcessingResultResponses, GetDocumentResponses, GetDocumentShortIdData, GetDocumentShortIdErrors, GetDocumentShortIdResponses, GetDocumentTeamShareData, GetDocumentTeamShareErrors, GetDocumentTeamShareResponses, GetDocumentVersionData, GetDocumentVersionErrors, GetDocumentVersionResponses, GetDocumentViewsHandlerData, GetDocumentViewsHandlerErrors, GetDocumentViewsHandlerResponses, GetEntityPermissionData, GetEntityPermissionErrors, GetEntityPermissionResponses, GetForeignEntityData, GetForeignEntityErrors, GetForeignEntityResponses, GetHarnessPairingData, GetHarnessPairingErrors, GetHarnessPairingResponses, GetHistoryHandlerData, GetHistoryHandlerErrors, GetHistoryHandlerResponses, GetInstructionsHandlerData, GetInstructionsHandlerErrors, GetInstructionsHandlerResponses, GetItemsSoupData, GetItemsSoupErrors, GetItemsSoupResponses, GetLocationHandlerData, GetLocationHandlerErrors, GetLocationHandlerResponses, GetMessageWithContextData, GetMessageWithContextErrors, GetMessageWithContextResponses, GetOrCreateCallData, GetOrCreateCallErrors, GetOrCreateCallResponses, GetOrCreateDmData, GetOrCreateDmErrors, GetOrCreateDmResponses, GetOrCreatePrivateData, GetOrCreatePrivateErrors, GetOrCreatePrivateResponses, GetPendingProjectsHandlerData, GetPendingProjectsHandlerErrors, GetPendingProjectsHandlerResponses, GetPinsHandlerData, GetPinsHandlerErrors, GetPinsHandlerResponses, GetProjectContentHandlerData, GetProjectContentHandlerErrors, GetProjectContentHandlerResponses, GetProjectHandlerData, GetProjectHandlerErrors, GetProjectHandlerResponses, GetProjectPermissionsV2Data, GetProjectPermissionsV2Errors, GetProjectPermissionsV2Responses, GetProjectsHandlerData, GetProjectsHandlerErrors, GetProjectsHandlerResponses, GetProjectUserAccessLevelData, GetProjectUserAccessLevelErrors, GetProjectUserAccessLevelResponses, GetReminderData, GetReminderErrors, GetReminderResponses, GetRingStatusData, GetRingStatusErrors, GetRingStatusResponses, GetSelfBotData, GetSelfBotErrors, GetSelfBotResponses, GetSystemSkillsHandlerData, GetSystemSkillsHandlerErrors, GetSystemSkillsHandlerResponses, GetThreadRepliesData, GetThreadRepliesErrors, GetThreadRepliesResponses, GetUserDocumentsHandlerData, GetUserDocumentsHandlerErrors, GetUserDocumentsHandlerResponses, GetUserDocumentViewLocationData, GetUserDocumentViewLocationErrors, GetUserDocumentViewLocationResponses, GetViewsHandlerData, GetViewsHandlerErrors, GetViewsHandlerResponses, GetWebhookData, GetWebhookErrors, GetWebhookResponses, HandlerData, HandlerErrors, HandlerResponses, HealthHandlerData, HealthHandlerResponses, IngestTranscriptData, IngestTranscriptErrors, IngestTranscriptResponses, InitializeUserDocumentsData, InitializeUserDocumentsErrors, InitializeUserDocumentsResponses, InstallSyncData, InstallSyncErrors, JobProcessingResultHandlerData, JobProcessingResultHandlerErrors, JobProcessingResultHandlerResponses, JoinChannelByCodeData, JoinChannelByCodeErrors, JoinChannelByCodeResponses, JoinChannelData, JoinChannelErrors, JoinChannelResponses, LeaveChannelData, LeaveChannelErrors, LeaveChannelResponses, LeaveOrEndCallData, LeaveOrEndCallErrors, LeaveOrEndCallResponses, ListAgentsData, ListAgentsErrors, ListAgentsResponses, ListBotChannelsData, ListBotChannelsErrors, ListBotChannelsResponses, ListCompanyContactsData, ListCompanyContactsErrors, ListCompanyContactsResponses, ListCrmCommentsData, ListCrmCommentsErrors, ListCrmCommentsResponses, ListFavoritesData, ListFavoritesErrors, ListFavoritesResponses, ListHarnessAgentsData, ListHarnessAgentsErrors, ListHarnessAgentsResponses, ListHarnessesData, ListHarnessesErrors, ListHarnessesResponses, ListOccurrencesData, ListOccurrencesErrors, ListOccurrencesResponses, ListRemindersData, ListRemindersErrors, ListRemindersResponses, ListUserApiKeysData, ListUserApiKeysErrors, ListUserApiKeysResponses, ListWebhooksData, ListWebhooksErrors, ListWebhooksResponses, MentionPreviewsData, MentionPreviewsErrors, MentionPreviewsResponses, PatchChannelData, PatchChannelErrors, PatchChannelResponses, PatchMessageData, PatchMessageErrors, PatchMessageResponses, PatchViewHandlerData, PatchViewHandlerErrors, PatchViewHandlerResponses, PatchWebhookData, PatchWebhookErrors, PatchWebhookResponses, PermanentlyDeleteDocumentData, PermanentlyDeleteDocumentErrors, PermanentlyDeleteDocumentResponses, PermanentlyDeleteProjectData, PermanentlyDeleteProjectErrors, PermanentlyDeleteProjectResponses, PostActivityData, PostActivityErrors, PostActivityResponses, PostChannelBotWebhookData, PostChannelBotWebhookErrors, PostChannelBotWebhookResponses, PostChannelMessagesData, PostChannelMessagesErrors, PostChannelMessagesResponses, PostItemsSoupAstData, PostItemsSoupAstErrors, PostItemsSoupAstGroupedData, PostItemsSoupAstGroupedErrors, PostItemsSoupAstGroupedResponses, PostItemsSoupAstResponses, PostItemsSoupData, PostItemsSoupErrors, PostItemsSoupResponses, PostMessageData, PostMessageErrors, PostMessageResponses, PostReactionData, PostReactionErrors, PostReactionResponses, PostTypingData, PostTypingErrors, PostTypingResponses, PresaveDocumentHandlerData, PresaveDocumentHandlerErrors, PresaveDocumentHandlerResponses, PutCrmTeamSettingsData, PutCrmTeamSettingsErrors, PutCrmTeamSettingsResponses, RecentlyDeletedData, RecentlyDeletedErrors, RecentlyDeletedResponses, RemoveBotFromChannelByBotData, RemoveBotFromChannelByBotErrors, RemoveBotFromChannelByBotResponses, RemoveFavoriteByEntityData, RemoveFavoriteByEntityErrors, RemoveFavoriteByEntityResponses, RemoveParticipantsData, RemoveParticipantsErrors, RemoveParticipantsResponses, RemovePinHandlerData, RemovePinHandlerErrors, RemovePinHandlerResponses, ReorderFavoritesData, ReorderFavoritesErrors, ReorderFavoritesResponses, ReorderPinsHandlerData, ReorderPinsHandlerErrors, ReorderPinsHandlerResponses, ResolveChannelMessageData, ResolveChannelMessageErrors, ResolveChannelMessageResponses, RevertDeleteDocumentData, RevertDeleteDocumentErrors, RevertDeleteDocumentResponses, RevertDeleteProjectData, RevertDeleteProjectErrors, RevertDeleteProjectResponses, SaveDocumentHandlerData, SaveDocumentHandlerErrors, SaveDocumentHandlerResponses, SetCompanyHiddenData, SetCompanyHiddenErrors, SetCompanyHiddenResponses, SetContactHiddenData, SetContactHiddenErrors, SetContactHiddenResponses, SetCrmCompanyNameData, SetCrmCompanyNameErrors, SetCrmCompanyNameResponses, SetCrmContactNameData, SetCrmContactNameErrors, SetCrmContactNameResponses, SetDocumentTeamShareData, SetDocumentTeamShareErrors, SetDocumentTeamShareResponses, SetEmailSyncData, SetEmailSyncErrors, SetEmailSyncResponses, SimpleSaveData, SimpleSaveErrors, SimpleSaveResponses, ToggleShareWithTeamData, ToggleShareWithTeamErrors, ToggleShareWithTeamResponses, UpdateAgentData, UpdateAgentErrors, UpdateAgentResponses, UpdateReminderData, UpdateReminderErrors, UpdateReminderResponses, UploadExtractFolderHandlerData, UploadExtractFolderHandlerErrors, UploadExtractFolderHandlerResponses, UploadFolderHandlerData, UploadFolderHandlerErrors, UploadFolderHandlerResponses, UpsertHistoryHandlerData, UpsertHistoryHandlerErrors, UpsertHistoryHandlerResponses, UpsertUserDocumentViewLocationData, UpsertUserDocumentViewLocationErrors, UpsertUserDocumentViewLocationResponses, ValidateDocumentPermissionsTokenData, ValidateDocumentPermissionsTokenErrors, ValidateDocumentPermissionsTokenResponses, ValidateWebhookData, ValidateWebhookErrors, ValidateWebhookResponses } from './types.gen';export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown> = Options2<TData, ThrowOnError, TResponse> & {/**@@ -1462,6 +1462,84 @@ export class Sdk extends HeyApiClient {return (options?.client ?? this.client).get<unknown, InstallSyncErrors, ThrowOnError>({ url: '/github/install-sync', ...options });}+ /**+ * Handler for `POST /harness-pairings`.+ *+ * Unauthenticated by design: the daemon has no credential yet - obtaining one+ * is the point. The pairing releases nothing until a signed-in user approves+ * it, and creation is throttled in the domain service.+ */+ public createHarnessPairing<ThrowOnError extends boolean = false>(options: Options<CreateHarnessPairingData, ThrowOnError>): RequestResult<CreateHarnessPairingResponses, CreateHarnessPairingErrors, ThrowOnError> {+ return (options.client ?? this.client).post<CreateHarnessPairingResponses, CreateHarnessPairingErrors, ThrowOnError>({+ url: '/harness-pairings',+ ...options,+ headers: {+ 'Content-Type': 'application/json',+ ...options.headers+ }+ });+ }++ /**+ * Handler for `GET /harness-pairings/{code}`.+ */+ public getHarnessPairing<ThrowOnError extends boolean = false>(options: Options<GetHarnessPairingData, ThrowOnError>): RequestResult<GetHarnessPairingResponses, GetHarnessPairingErrors, ThrowOnError> {+ return (options.client ?? this.client).get<GetHarnessPairingResponses, GetHarnessPairingErrors, ThrowOnError>({ url: '/harness-pairings/{code}', ...options });+ }++ /**+ * Handler for `POST /harness-pairings/{code}/approve`.+ */+ public approveHarnessPairing<ThrowOnError extends boolean = false>(options: Options<ApproveHarnessPairingData, ThrowOnError>): RequestResult<ApproveHarnessPairingResponses, ApproveHarnessPairingErrors, ThrowOnError> {+ return (options.client ?? this.client).post<ApproveHarnessPairingResponses, ApproveHarnessPairingErrors, ThrowOnError>({+ url: '/harness-pairings/{code}/approve',+ ...options,+ headers: {+ 'Content-Type': 'application/json',+ ...options.headers+ }+ });+ }++ /**+ * Handler for `POST /harness-pairings/{pairing_id}/claim`.+ *+ * Unauthenticated like pairing creation; the device secret minted alongside+ * the pairing is the credential, and the pairing id (not the short user+ * code) addresses it.+ */+ public claimHarnessPairing<ThrowOnError extends boolean = false>(options: Options<ClaimHarnessPairingData, ThrowOnError>): RequestResult<ClaimHarnessPairingResponses, ClaimHarnessPairingErrors, ThrowOnError> {+ return (options.client ?? this.client).post<ClaimHarnessPairingResponses, ClaimHarnessPairingErrors, ThrowOnError>({+ url: '/harness-pairings/{pairing_id}/claim',+ ...options,+ headers: {+ 'Content-Type': 'application/json',+ ...options.headers+ }+ });+ }++ /**+ * Handler for `GET /harnesses`.+ */+ public listHarnesses<ThrowOnError extends boolean = false>(options?: Options<ListHarnessesData, ThrowOnError>): RequestResult<ListHarnessesResponses, ListHarnessesErrors, ThrowOnError> {+ return (options?.client ?? this.client).get<ListHarnessesResponses, ListHarnessesErrors, ThrowOnError>({ url: '/harnesses', ...options });+ }++ /**+ * Handler for `GET /harnesses/me/agents`.+ */+ public listHarnessAgents<ThrowOnError extends boolean = false>(options?: Options<ListHarnessAgentsData, ThrowOnError>): RequestResult<ListHarnessAgentsResponses, ListHarnessAgentsErrors, ThrowOnError> {+ return (options?.client ?? this.client).get<ListHarnessAgentsResponses, ListHarnessAgentsErrors, ThrowOnError>({ url: '/harnesses/me/agents', ...options });+ }++ /**+ * Handler for `DELETE /harnesses/{harness_id}`.+ */+ public deleteHarness<ThrowOnError extends boolean = false>(options: Options<DeleteHarnessData, ThrowOnError>): RequestResult<DeleteHarnessResponses, DeleteHarnessErrors, ThrowOnError> {+ return (options.client ?? this.client).delete<DeleteHarnessResponses, DeleteHarnessErrors, ThrowOnError>({ url: '/harnesses/{harness_id}', ...options });+ }+/*** Health check*/diff --git a/packages/sdk/generated/storage/types.gen.ts b/packages/sdk/generated/storage/types.gen.tsindex 19af388fd7..53870054a1 100644--- a/packages/sdk/generated/storage/types.gen.ts+++ b/packages/sdk/generated/storage/types.gen.ts@@ -110,6 +110,7 @@ export type Agent = {* Harness used to run the agent.*/harness: string;+ harness_id?: null | HarnessId;/*** Instructions supplied to the agent at the start of a conversation.*/@@ -967,6 +968,20 @@ export type ApiThreadReply = {updated_at: string;};+/**+ * Request to approve a pairing and register the harness.+ */+export type ApprovePairingRequest = {+ /**+ * Display name override. Defaults to the daemon's requested name.+ */+ name?: string | null;+ /**+ * Owning team. Omit for a private, user-owned harness.+ */+ team_id?: string | null;+};+/*** RSVP state for an attendee.*/@@ -2603,6 +2618,32 @@ export type ChatFilters = {role?: Array<string>;};+/**+ * Request to claim an approved pairing's credential.+ *+ * The daemon serializes this, so both derives are used.+ */+export type ClaimPairingRequest = {+ /**+ * The claim credential returned when the pairing was created.+ */+ device_secret: string;+};++/**+ * The credential released to the daemon when a pairing is claimed.+ */+export type ClaimedPairing = {+ /**+ * The registered harness.+ */+ harness: Harness;+ /**+ * The raw harness bearer token. Shown only here; only its hash is stored.+ */+ token: string;+};+export type CloudStorageItemType = 'document' | 'chat' | 'project';/**@@ -2738,6 +2779,7 @@ export type CreateAgentRequest = {* Harness used to run the agent.*/harness: string;+ harness_id?: null | HarnessId;/*** Instructions supplied to the agent at the start of a conversation.*/@@ -3141,6 +3183,23 @@ export type CreateMarkdownDocumentResponse = {token: string;};+/**+ * Request to open a pairing: the daemon asks for a code the user approves.+ *+ * The daemon serializes this, so both derives are used.+ */+export type CreatePairingRequest = {+ /**+ * Display-only description of the machine, e.g. `eric@macbook / darwin`.+ */+ host?: string | null;+ /**+ * Requested harness display name (typically the machine's hostname).+ */+ name: string;+ scope?: null | RequestedHarnessScope;+};+export type CreateProjectRequest = {/*** The name of the project.@@ -3428,6 +3487,35 @@ export type CreateWebhookResponse = {workspace_id: string;};+/**+ * A pairing the daemon created, including its claim credential.+ *+ * `device_secret` is returned exactly once and never stored raw; the daemon+ * keeps it to claim the harness credential after approval.+ */+export type CreatedPairing = {+ /**+ * Human-readable code the user confirms in the web app, `XXXX-XXXX`.+ */+ code: string;+ /**+ * Claim credential the daemon must present. Shown only here.+ */+ device_secret: string;+ /**+ * When the pairing expires.+ */+ expires_at: string;+ /**+ * Pairing id used to poll for the claim.+ */+ pairing_id: string;+ /**+ * Suggested delay between claim polls.+ */+ poll_interval_seconds: number;+};+/*** A newly minted key: safe metadata plus the secret, shown only once.*/@@ -5732,6 +5820,90 @@ export type GroupedSoupPage = (GroupedSoupInitialPage & {*/export type GroupedSoupSort = 'viewed_at' | 'created_at' | 'updated_at' | 'viewed_updated';+/**+ * A registered user-run harness.+ *+ * Clients deserialize this, so both derives are used.+ */+export type Harness = {+ /**+ * Whether the daemon currently holds a runtime connection.+ */+ connected: boolean;+ /**+ * Creation timestamp.+ */+ created_at: string;+ /**+ * User that registered this harness.+ */+ created_by: string;+ /**+ * Harness id.+ */+ id: HarnessId;+ /**+ * Runtime kind. Currently always `macrod`.+ */+ kind: string;+ /**+ * When the daemon last attached a runtime connection.+ */+ last_connected_at?: string | null;+ /**+ * Display name.+ */+ name: string;+ /**+ * Owner.+ */+ owner: HarnessOwner;+ /**+ * Update timestamp.+ */+ updated_at: string;+};++/**+ * An agent bound to a harness, as listed for the daemon.+ */+export type HarnessAgent = {+ /**+ * The agent's bot id.+ */+ bot_id: BotId;+ /**+ * Stable `@` handle.+ */+ handle: string;+ /**+ * Display name.+ */+ name: string;+};++export type HarnessId = string;++/**+ * Harness owner.+ *+ * Exactly one of a user or a team, mirroring the bots owner pattern. There+ * are no system harnesses.+ */+export type HarnessOwner = {+ type: 'user';+ /**+ * Owner user id.+ */+ user_id: string;+} | {+ /**+ * Owner team id.+ */+ team_id: string;+ type: 'team';+};+export type HashMap = {[key: string]: (PresignedUrl & {type: 'external';@@ -5895,6 +6067,33 @@ export type NotificationFilters = {seen?: boolean | null;};+/**+ * A pending pairing, as shown to the approving user.+ */+export type PairingDetails = {+ /**+ * The pairing code, normalized to `XXXX-XXXX`.+ */+ code: string;+ /**+ * When the pairing was created.+ */+ created_at: string;+ /**+ * When the pairing expires.+ */+ expires_at: string;+ /**+ * Display-only description of the machine.+ */+ host?: string | null;+ /**+ * Harness display name the daemon asked for.+ */+ requested_name: string;+ requested_scope?: null | RequestedHarnessScope;+};+/*** Query parameters shared by soup endpoints.*/@@ -6133,6 +6332,16 @@ export type PdfPlaceableCommentAnchorRequest = {yPct: number;};+/**+ * Body returned while a claim is still waiting for approval.+ */+export type PendingClaimResponse = {+ /**+ * Always `pending`.+ */+ status: string;+};+export type PinRequest = {/*** The type of the pin@@ -6728,6 +6937,14 @@ export type ReorderPinRequest = {pinnedItemType: string;};+/**+ * The ownership scope a daemon's config asks for.+ *+ * Advisory, not binding: the approving user confirms it in the dialog, which+ * arrives preselected to this. Approval is what actually sets ownership.+ */+export type RequestedHarnessScope = 'private' | 'team';+/*** Per-user status of an incoming-call ring, as reported by the* ring-status endpoint while a native client is ringing.@@ -8341,6 +8558,7 @@ export type UpdateAgentRequest = {* Harness used to run the agent.*/harness: string;+ harness_id?: null | HarnessId;/*** Instructions supplied to the agent at the start of a conversation.*/@@ -12231,6 +12449,177 @@ export type InstallSyncErrors = {401: unknown;};+export type CreateHarnessPairingData = {+ body: CreatePairingRequest;+ path?: never;+ query?: never;+ url: '/harness-pairings';+};++export type CreateHarnessPairingErrors = {+ 400: ErrorResponse;+ 429: ErrorResponse;+ 500: ErrorResponse;+};++export type CreateHarnessPairingError = CreateHarnessPairingErrors[keyof CreateHarnessPairingErrors];++export type CreateHarnessPairingResponses = {+ 201: CreatedPairing;+};++export type CreateHarnessPairingResponse = CreateHarnessPairingResponses[keyof CreateHarnessPairingResponses];++export type GetHarnessPairingData = {+ body?: never;+ path: {+ /**+ * Pairing code+ */+ code: string;+ };+ query?: never;+ url: '/harness-pairings/{code}';+};++export type GetHarnessPairingErrors = {+ 400: ErrorResponse;+ 401: ErrorResponse;+ 404: ErrorResponse;+ 410: ErrorResponse;+ 500: ErrorResponse;+};++export type GetHarnessPairingError = GetHarnessPairingErrors[keyof GetHarnessPairingErrors];++export type GetHarnessPairingResponses = {+ 200: PairingDetails;+};++export type GetHarnessPairingResponse = GetHarnessPairingResponses[keyof GetHarnessPairingResponses];++export type ApproveHarnessPairingData = {+ body: ApprovePairingRequest;+ path: {+ /**+ * Pairing code+ */+ code: string;+ };+ query?: never;+ url: '/harness-pairings/{code}/approve';+};++export type ApproveHarnessPairingErrors = {+ 400: ErrorResponse;+ 401: ErrorResponse;+ 404: ErrorResponse;+ 410: ErrorResponse;+ 500: ErrorResponse;+};++export type ApproveHarnessPairingError = ApproveHarnessPairingErrors[keyof ApproveHarnessPairingErrors];++export type ApproveHarnessPairingResponses = {+ 200: Harness;+};++export type ApproveHarnessPairingResponse = ApproveHarnessPairingResponses[keyof ApproveHarnessPairingResponses];++export type ClaimHarnessPairingData = {+ body: ClaimPairingRequest;+ path: {+ /**+ * Pairing ID+ */+ pairing_id: string;+ };+ query?: never;+ url: '/harness-pairings/{pairing_id}/claim';+};++export type ClaimHarnessPairingErrors = {+ 401: ErrorResponse;+ 404: ErrorResponse;+ 410: ErrorResponse;+ 500: ErrorResponse;+};++export type ClaimHarnessPairingError = ClaimHarnessPairingErrors[keyof ClaimHarnessPairingErrors];++export type ClaimHarnessPairingResponses = {+ 200: ClaimedPairing;+ 202: PendingClaimResponse;+};++export type ClaimHarnessPairingResponse = ClaimHarnessPairingResponses[keyof ClaimHarnessPairingResponses];++export type ListHarnessesData = {+ body?: never;+ path?: never;+ query?: never;+ url: '/harnesses';+};++export type ListHarnessesErrors = {+ 401: ErrorResponse;+ 500: ErrorResponse;+};++export type ListHarnessesError = ListHarnessesErrors[keyof ListHarnessesErrors];++export type ListHarnessesResponses = {+ 200: Array<Harness>;+};++export type ListHarnessesResponse = ListHarnessesResponses[keyof ListHarnessesResponses];++export type ListHarnessAgentsData = {+ body?: never;+ path?: never;+ query?: never;+ url: '/harnesses/me/agents';+};++export type ListHarnessAgentsErrors = {+ 401: ErrorResponse;+ 500: ErrorResponse;+};++export type ListHarnessAgentsError = ListHarnessAgentsErrors[keyof ListHarnessAgentsErrors];++export type ListHarnessAgentsResponses = {+ 200: Array<HarnessAgent>;+};++export type ListHarnessAgentsResponse = ListHarnessAgentsResponses[keyof ListHarnessAgentsResponses];++export type DeleteHarnessData = {+ body?: never;+ path: {+ /**+ * Harness ID+ */+ harness_id: HarnessId;+ };+ query?: never;+ url: '/harnesses/{harness_id}';+};++export type DeleteHarnessErrors = {+ 401: ErrorResponse;+ 404: ErrorResponse;+ 500: ErrorResponse;+};++export type DeleteHarnessError = DeleteHarnessErrors[keyof DeleteHarnessErrors];++export type DeleteHarnessResponses = {+ 204: void;+};++export type DeleteHarnessResponse = DeleteHarnessResponses[keyof DeleteHarnessResponses];+export type HealthHandlerData = {body?: never;path?: never;diff --git a/packages/sdk/specs/storage.json b/packages/sdk/specs/storage.jsonindex 75ce6c3709..9337378ff8 100644--- a/packages/sdk/specs/storage.json+++ b/packages/sdk/specs/storage.json@@ -8636,6 +8636,465 @@}}},+ "/harness-pairings": {+ "post": {+ "tags": ["harnesses"],+ "summary": "Handler for `POST /harness-pairings`.",+ "description": "Unauthenticated by design: the daemon has no credential yet - obtaining one\nis the point. The pairing releases nothing until a signed-in user approves\nit, and creation is throttled in the domain service.",+ "operationId": "create_harness_pairing",+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CreatePairingRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "201": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CreatedPairing"+ }+ }+ }+ },+ "400": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "429": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ }+ },+ "/harness-pairings/{code}": {+ "get": {+ "tags": ["harnesses"],+ "summary": "Handler for `GET /harness-pairings/{code}`.",+ "operationId": "get_harness_pairing",+ "parameters": [+ {+ "name": "code",+ "in": "path",+ "description": "Pairing code",+ "required": true,+ "schema": {+ "type": "string"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/PairingDetails"+ }+ }+ }+ },+ "400": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "401": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "404": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "410": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ }+ },+ "/harness-pairings/{code}/approve": {+ "post": {+ "tags": ["harnesses"],+ "summary": "Handler for `POST /harness-pairings/{code}/approve`.",+ "operationId": "approve_harness_pairing",+ "parameters": [+ {+ "name": "code",+ "in": "path",+ "description": "Pairing code",+ "required": true,+ "schema": {+ "type": "string"+ }+ }+ ],+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApprovePairingRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/Harness"+ }+ }+ }+ },+ "400": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "401": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "404": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "410": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ }+ },+ "/harness-pairings/{pairing_id}/claim": {+ "post": {+ "tags": ["harnesses"],+ "summary": "Handler for `POST /harness-pairings/{pairing_id}/claim`.",+ "description": "Unauthenticated like pairing creation; the device secret minted alongside\nthe pairing is the credential, and the pairing id (not the short user\ncode) addresses it.",+ "operationId": "claim_harness_pairing",+ "parameters": [+ {+ "name": "pairing_id",+ "in": "path",+ "description": "Pairing ID",+ "required": true,+ "schema": {+ "type": "string",+ "format": "uuid"+ }+ }+ ],+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ClaimPairingRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ClaimedPairing"+ }+ }+ }+ },+ "202": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/PendingClaimResponse"+ }+ }+ }+ },+ "401": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "404": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "410": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ }+ },+ "/harnesses": {+ "get": {+ "tags": ["harnesses"],+ "summary": "Handler for `GET /harnesses`.",+ "operationId": "list_harnesses",+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/Harness"+ }+ }+ }+ }+ },+ "401": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ }+ },+ "/harnesses/me/agents": {+ "get": {+ "tags": ["harnesses"],+ "summary": "Handler for `GET /harnesses/me/agents`.",+ "operationId": "list_harness_agents",+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/HarnessAgent"+ }+ }+ }+ }+ },+ "401": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ }+ },+ "/harnesses/{harness_id}": {+ "delete": {+ "tags": ["harnesses"],+ "summary": "Handler for `DELETE /harnesses/{harness_id}`.",+ "operationId": "delete_harness",+ "parameters": [+ {+ "name": "harness_id",+ "in": "path",+ "description": "Harness ID",+ "required": true,+ "schema": {+ "$ref": "#/components/schemas/HarnessId"+ }+ }+ ],+ "responses": {+ "204": {+ "description": ""+ },+ "401": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "404": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ }+ },"/health": {"get": {"tags": ["health"],@@ -11941,6 +12400,17 @@"type": "string","description": "Harness used to run the agent."},+ "harness_id": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/HarnessId",+ "description": "Registered harness the agent runs on, when `harness` is `macrod`."+ }+ ]+ },"instructions": {"type": "string","description": "Instructions supplied to the agent at the start of a conversation."@@ -13236,6 +13706,21 @@}}},+ "ApprovePairingRequest": {+ "type": "object",+ "description": "Request to approve a pairing and register the harness.",+ "properties": {+ "name": {+ "type": ["string", "null"],+ "description": "Display name override. Defaults to the daemon's requested name."+ },+ "team_id": {+ "type": ["string", "null"],+ "format": "uuid",+ "description": "Owning team. Omit for a private, user-owned harness."+ }+ }+ },"AttendeeResponseStatus": {"type": "string","description": "RSVP state for an attendee.",@@ -15517,6 +16002,32 @@}}},+ "ClaimPairingRequest": {+ "type": "object",+ "description": "Request to claim an approved pairing's credential.\n\nThe daemon serializes this, so both derives are used.",+ "required": ["device_secret"],+ "properties": {+ "device_secret": {+ "type": "string",+ "description": "The claim credential returned when the pairing was created."+ }+ }+ },+ "ClaimedPairing": {+ "type": "object",+ "description": "The credential released to the daemon when a pairing is claimed.",+ "required": ["harness", "token"],+ "properties": {+ "harness": {+ "$ref": "#/components/schemas/Harness",+ "description": "The registered harness."+ },+ "token": {+ "type": "string",+ "description": "The raw harness bearer token. Shown only here; only its hash is stored."+ }+ }+ },"CloudStorageItemType": {"type": "string","enum": ["document", "chat", "project"]@@ -15732,6 +16243,17 @@"type": "string","description": "Harness used to run the agent."},+ "harness_id": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/HarnessId",+ "description": "Registered harness to run on. Required when `harness` is `macrod`,\nforbidden otherwise."+ }+ ]+ },"instructions": {"type": "string","description": "Instructions supplied to the agent at the start of a conversation."@@ -16261,6 +16783,32 @@}}},+ "CreatePairingRequest": {+ "type": "object",+ "description": "Request to open a pairing: the daemon asks for a code the user approves.\n\nThe daemon serializes this, so both derives are used.",+ "required": ["name"],+ "properties": {+ "host": {+ "type": ["string", "null"],+ "description": "Display-only description of the machine, e.g. `eric@macbook / darwin`."+ },+ "name": {+ "type": "string",+ "description": "Requested harness display name (typically the machine's hostname)."+ },+ "scope": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/RequestedHarnessScope",+ "description": "The scope the daemon's config asks for; the approval dialog arrives\npreselected to it."+ }+ ]+ }+ }+ },"CreateProjectRequest": {"type": "object","required": ["name"],@@ -16673,6 +17221,43 @@}}},+ "CreatedPairing": {+ "type": "object",+ "description": "A pairing the daemon created, including its claim credential.\n\n`device_secret` is returned exactly once and never stored raw; the daemon\nkeeps it to claim the harness credential after approval.",+ "required": [+ "pairing_id",+ "code",+ "device_secret",+ "expires_at",+ "poll_interval_seconds"+ ],+ "properties": {+ "code": {+ "type": "string",+ "description": "Human-readable code the user confirms in the web app, `XXXX-XXXX`."+ },+ "device_secret": {+ "type": "string",+ "description": "Claim credential the daemon must present. Shown only here."+ },+ "expires_at": {+ "type": "string",+ "format": "date-time",+ "description": "When the pairing expires."+ },+ "pairing_id": {+ "type": "string",+ "format": "uuid",+ "description": "Pairing id used to poll for the claim."+ },+ "poll_interval_seconds": {+ "type": "integer",+ "format": "int64",+ "description": "Suggested delay between claim polls.",+ "minimum": 0+ }+ }+ },"CreatedUserApiKey": {"type": "object","description": "A newly minted key: safe metadata plus the secret, shown only once.",@@ -20637,6 +21222,119 @@"description": "Sort method for grouped queries (frecency not supported).","enum": ["viewed_at", "created_at", "updated_at", "viewed_updated"]},+ "Harness": {+ "type": "object",+ "description": "A registered user-run harness.\n\nClients deserialize this, so both derives are used.",+ "required": [+ "id",+ "kind",+ "name",+ "owner",+ "created_by",+ "created_at",+ "updated_at",+ "connected"+ ],+ "properties": {+ "connected": {+ "type": "boolean",+ "description": "Whether the daemon currently holds a runtime connection."+ },+ "created_at": {+ "type": "string",+ "format": "date-time",+ "description": "Creation timestamp."+ },+ "created_by": {+ "type": "string",+ "description": "User that registered this harness."+ },+ "id": {+ "$ref": "#/components/schemas/HarnessId",+ "description": "Harness id."+ },+ "kind": {+ "type": "string",+ "description": "Runtime kind. Currently always `macrod`."+ },+ "last_connected_at": {+ "type": ["string", "null"],+ "format": "date-time",+ "description": "When the daemon last attached a runtime connection."+ },+ "name": {+ "type": "string",+ "description": "Display name."+ },+ "owner": {+ "$ref": "#/components/schemas/HarnessOwner",+ "description": "Owner."+ },+ "updated_at": {+ "type": "string",+ "format": "date-time",+ "description": "Update timestamp."+ }+ }+ },+ "HarnessAgent": {+ "type": "object",+ "description": "An agent bound to a harness, as listed for the daemon.",+ "required": ["bot_id", "name", "handle"],+ "properties": {+ "bot_id": {+ "$ref": "#/components/schemas/BotId",+ "description": "The agent's bot id."+ },+ "handle": {+ "type": "string",+ "description": "Stable `@` handle."+ },+ "name": {+ "type": "string",+ "description": "Display name."+ }+ }+ },+ "HarnessId": {+ "type": "string"+ },+ "HarnessOwner": {+ "oneOf": [+ {+ "type": "object",+ "description": "User-owned (private) harness.",+ "required": ["user_id", "type"],+ "properties": {+ "type": {+ "type": "string",+ "enum": ["user"]+ },+ "user_id": {+ "type": "string",+ "description": "Owner user id."+ }+ }+ },+ {+ "type": "object",+ "description": "Team-owned harness, usable by every team member.",+ "required": ["team_id", "type"],+ "properties": {+ "team_id": {+ "type": "string",+ "format": "uuid",+ "description": "Owner team id."+ },+ "type": {+ "type": "string",+ "enum": ["team"]+ }+ }+ }+ ],+ "description": "Harness owner.\n\nExactly one of a user or a team, mirroring the bots owner pattern. There\nare no system harnesses."+ },"HashMap": {"type": "object","additionalProperties": {@@ -20940,6 +21638,46 @@}}},+ "PairingDetails": {+ "type": "object",+ "description": "A pending pairing, as shown to the approving user.",+ "required": ["code", "requested_name", "created_at", "expires_at"],+ "properties": {+ "code": {+ "type": "string",+ "description": "The pairing code, normalized to `XXXX-XXXX`."+ },+ "created_at": {+ "type": "string",+ "format": "date-time",+ "description": "When the pairing was created."+ },+ "expires_at": {+ "type": "string",+ "format": "date-time",+ "description": "When the pairing expires."+ },+ "host": {+ "type": ["string", "null"],+ "description": "Display-only description of the machine."+ },+ "requested_name": {+ "type": "string",+ "description": "Harness display name the daemon asked for."+ },+ "requested_scope": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/RequestedHarnessScope",+ "description": "The scope the daemon's config asked for, when it named one."+ }+ ]+ }+ }+ },"Params": {"type": "object","description": "Query parameters shared by soup endpoints.",@@ -21615,6 +22353,17 @@}}},+ "PendingClaimResponse": {+ "type": "object",+ "description": "Body returned while a claim is still waiting for approval.",+ "required": ["status"],+ "properties": {+ "status": {+ "type": "string",+ "description": "Always `pending`."+ }+ }+ },"PinRequest": {"type": "object","required": ["pinType"],@@ -22613,6 +23362,11 @@}}},+ "RequestedHarnessScope": {+ "type": "string",+ "description": "The ownership scope a daemon's config asks for.\n\nAdvisory, not binding: the approving user confirms it in the dialog, which\narrives preselected to this. Approval is what actually sets ownership.",+ "enum": ["private", "team"]+ },"RingStatus": {"type": "string","description": "Per-user status of an incoming-call ring, as reported by the\nring-status endpoint while a native client is ringing.",@@ -25023,6 +25777,17 @@"type": "string","description": "Harness used to run the agent."},+ "harness_id": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/HarnessId",+ "description": "Registered harness to run on. Required when `harness` is `macrod`,\nforbidden otherwise."+ }+ ]+ },"instructions": {"type": "string","description": "Instructions supplied to the agent at the start of a conversation."diff --git a/packages/sdk/src/coverage/skipped.ts b/packages/sdk/src/coverage/skipped.tsindex 403d7fcb42..e232f9b16e 100644--- a/packages/sdk/src/coverage/skipped.ts+++ b/packages/sdk/src/coverage/skipped.ts@@ -309,14 +309,18 @@ export const storageExcluded = [] as const satisfies readonly (keyof StorageSdk)[];export const storageBacklog = [+ 'approveHarnessPairing',+ 'claimHarnessPairing','createAgent','createAnchor','createDocument','createEntityMention',+ 'createHarnessPairing','createReminder','createUserApiKey','deleteAnchor','deleteEntityMention',+ 'deleteHarness','deleteReminder','deleteUserApiKey','editAnchor',@@ -331,8 +335,11 @@ export const storageBacklog = ['getEntityPermission','getProjectPermissionsV2','getProjectUserAccessLevel',+ 'getHarnessPairing','getReminder','listAgents',+ 'listHarnessAgents',+ 'listHarnesses','listOccurrences','listReminders','listUserApiKeys',diff --git a/services/agent_harness_service/Cargo.toml b/services/agent_harness_service/Cargo.tomlindex f37bc1a14d..ff09fd2a95 100644--- a/services/agent_harness_service/Cargo.toml+++ b/services/agent_harness_service/Cargo.toml@@ -25,6 +25,7 @@ ai_usage = { path = "../../crates/ai_usage" }aws-sdk-sqs = { workspace = true }bot_id = { path = "../../crates/bot_id" }bots = { path = "../../crates/bots" }+harness_id = { path = "../../crates/harness_id" }connection_gateway_client = { path = "../../crates/connection_gateway_client" }aws-sdk-kms = { workspace = true }cursor_api_key = { path = "../../crates/cursor_api_key" }diff --git a/services/agent_harness_service/src/api.rs b/services/agent_harness_service/src/api.rsindex ddf3807c2f..8a79d6bd62 100644--- a/services/agent_harness_service/src/api.rs+++ b/services/agent_harness_service/src/api.rs@@ -61,7 +61,7 @@ pub async fn setup_and_serve<T, R, Opener, Bots, Access, Auth, Harness>(read_state: AgentSessionRouterState<T, Access, Auth>,control_state: AgentSessionControlState<R, Access, Auth>,create_state: CreateSessionState<Opener, Bots, Auth>,- gateway_state: RuntimeGatewayState<Bots, Auth>,+ gateway_state: RuntimeGatewayState<Auth>,forward_state: ForwardGatewayState<Harness, Auth>,port: u16,shutdown: impl Future<Output = ()> + Send + 'static,@@ -103,7 +103,7 @@ fn api_router<T, R, Opener, Bots, Access, Auth, Harness>(read_state: AgentSessionRouterState<T, Access, Auth>,control_state: AgentSessionControlState<R, Access, Auth>,create_state: CreateSessionState<Opener, Bots, Auth>,- gateway_state: RuntimeGatewayState<Bots, Auth>,+ gateway_state: RuntimeGatewayState<Auth>,forward_state: ForwardGatewayState<Harness, Auth>,) -> Routerwherediff --git a/services/agent_harness_service/src/bots_directory.rs b/services/agent_harness_service/src/bots_directory.rsindex 44d657172e..ec4c165c84 100644--- a/services/agent_harness_service/src/bots_directory.rs+++ b/services/agent_harness_service/src/bots_directory.rs@@ -46,23 +46,28 @@ impl BotDirectory for PgBotDirectory {}Some(BotOwner::Team { .. }) | None => None,};- let is_managed = if row.has_agent {- self.repo+ let (is_managed, harness_id) = if row.has_agent {+ let agent = self+ .repo.get_agent(bot).await- .map_err(AgentSessionError::Unknown)?+ .map_err(AgentSessionError::Unknown)?;+ let harness_id = agent.as_ref().and_then(|agent| agent.harness_id);+ let is_managed = agent.map_or_else(|| AgentKind::of(bot),|agent| AgentKind::from_harness(&agent.harness),)- .is_managed()+ .is_managed();+ (is_managed, harness_id)} else {- false+ (false, None)};Ok(Some(BotFacts {has_agent: row.has_agent,is_managed,owner_user_id,+ harness_id,}))}}diff --git a/services/agent_harness_service/src/harness_bindings.rs b/services/agent_harness_service/src/harness_bindings.rsnew file mode 100644index 0000000000..2e16f32478--- /dev/null+++ b/services/agent_harness_service/src/harness_bindings.rs@@ -0,0 +1,91 @@+//! Postgres adapters for harness-keyed runtime routing.+//!+//! Composition-root adapters: [`PgHarnessBindings`] answers "which registered+//! harness serves this bot right now" for session binding, and+//! [`PgHarnessPresence`] writes the attach/detach bookkeeping the harness+//! settings page reads connection state from.++use std::future::Future;+use std::pin::Pin;+use std::sync::Arc;++use agent_harness::domain::ports::{HarnessBindings, HarnessPresence};+use bot_id::BotId;+use harness_id::HarnessId;+use sqlx::PgPool;++/// [`HarnessBindings`] over the `agent_configs` table.+#[derive(Clone)]+pub struct PgHarnessBindings {+ pool: PgPool,+}++impl PgHarnessBindings {+ /// Wrap a pool.+ pub fn new(pool: PgPool) -> Self {+ Self { pool }+ }+}++impl HarnessBindings for PgHarnessBindings {+ async fn harness_for(&self, bot: BotId) -> anyhow::Result<Option<HarnessId>> {+ let harness_id = sqlx::query_scalar!(+ r#"+ SELECT ac.harness_id+ FROM agent_configs ac+ JOIN harnesses h ON h.id = ac.harness_id+ WHERE ac.bot_id = $1 AND h.deleted_at IS NULL+ "#,+ bot.as_uuid(),+ )+ .fetch_optional(&self.pool)+ .await?;++ Ok(harness_id.flatten().map(HarnessId::new_from_uuid))+ }+}++/// [`HarnessPresence`] over the `harnesses` table.+pub struct PgHarnessPresence {+ pool: PgPool,+}++impl PgHarnessPresence {+ /// Wrap a pool.+ pub fn new(pool: PgPool) -> Self {+ Self { pool }+ }+}++impl HarnessPresence for PgHarnessPresence {+ fn connected(self: Arc<Self>, harness: HarnessId) -> Pin<Box<dyn Future<Output = ()> + Send>> {+ Box::pin(async move {+ let result = sqlx::query!(+ r#"UPDATE harnesses SET last_connected_at = now() WHERE id = $1"#,+ harness.as_uuid(),+ )+ .execute(&self.pool)+ .await;+ if let Err(error) = result {+ tracing::error!(error = ?error, %harness, "failed to record harness attach");+ }+ })+ }++ fn disconnected(+ self: Arc<Self>,+ harness: HarnessId,+ ) -> Pin<Box<dyn Future<Output = ()> + Send>> {+ Box::pin(async move {+ let result = sqlx::query!(+ r#"UPDATE harnesses SET last_disconnected_at = now() WHERE id = $1"#,+ harness.as_uuid(),+ )+ .execute(&self.pool)+ .await;+ if let Err(error) = result {+ tracing::error!(error = ?error, %harness, "failed to record harness detach");+ }+ })+ }+}diff --git a/services/agent_harness_service/src/main.rs b/services/agent_harness_service/src/main.rsindex 6a1d5aedc3..4bf2dea003 100644--- a/services/agent_harness_service/src/main.rs+++ b/services/agent_harness_service/src/main.rs@@ -12,6 +12,7 @@ mod api;mod bots_directory;mod config;mod containers;+mod harness_bindings;mod trigger;use std::{future::Future, pin::Pin, sync::Arc};@@ -46,7 +47,7 @@ use agent_harness::outbound::egress::EgressProvisioner;use agent_harness::outbound::forward::HttpCommandForwarder;use agent_harness::outbound::local::{LocalContainerManager, LocalSettings};use agent_harness::outbound::routing::RoutedContainerManager;-use agent_harness::outbound::runtime_registry::RuntimeRegistry;+use agent_harness::outbound::runtime_registry::{HarnessKeyedConnections, RuntimeRegistry};use agent_inmem::outbound::log_frames::LogFrameSource;use agent_inmem::outbound::manager::InMemAgentManager;use agent_inmem::outbound::rig_engine::RigTurnEngine;@@ -81,13 +82,14 @@ use cursor_cloud_agents::domain::model::RepoUrl as CursorRepoUrl;use github::domain::service::{InstallationTokenConfig, InstallationTokenService};use github::outbound::github_sync_client::GithubSyncClientImpl;use github::outbound::pg_github_sync_repo::PgGithubSyncRepo;+use harness_bindings::{PgHarnessBindings, PgHarnessPresence};use kafka_util::{GroupName, KafkaEventConsumer, consumer_span, record_span_error};use lexical_client::LexicalClient;use macro_auth::middleware::decode_jwt::JwtValidationArgs;use macro_authorization::{InternalAuthConfig, MacroAuthJwtValidator, MacroAuthorizationServiceImpl,- MacroAuthorizationState, PgBotAuthorizationRepo, PgBotAuthorizer,- PgUserApiKeyAuthorizationRepo, PgUserApiKeyAuthorizer,+ MacroAuthorizationState, PgBotAuthorizationRepo, PgBotAuthorizer, PgHarnessAuthorizationRepo,+ PgHarnessAuthorizer, PgUserApiKeyAuthorizationRepo, PgUserApiKeyAuthorizer,};use macro_entrypoint::{MacroEntrypoint, shutdown_signal};use macro_event_broker::{@@ -454,10 +456,11 @@ async fn run() -> anyhow::Result<()> {let prompt_context =ChannelPromptContextAdapter::new(channel_service, Arc::clone(&entity_access));- // One connection per bot, shared by every session that bot runs. Held- // here because the gateway puts dialed-in sockets into it and the harness- // takes sessions out of it.- let runtimes = RuntimeRegistry::new();+ // One connection per harness, shared by every session of every agent+ // bound to it. Held here because the gateway puts dialed-in sockets into+ // it and the harness takes sessions out of it. Attach/detach is mirrored+ // to the harnesses table so the settings page can show connection state.+ let runtimes = RuntimeRegistry::with_presence(Arc::new(PgHarnessPresence::new(pool.clone())));let mut defaults = HarnessDefaults::new(SessionDefaults {bot_id,model: config.harness_model.clone(),@@ -506,7 +509,7 @@ async fn run() -> anyhow::Result<()> {sessions,containers,announcer,- Arc::clone(&runtimes),+ HarnessKeyedConnections::new(PgHarnessBindings::new(pool.clone()), Arc::clone(&runtimes)),prompt_context,prompt_composer,EgressProvisioner::new(Arc::clone(&mcp_connections), config.egress_base_url.clone()),@@ -528,7 +531,10 @@ async fn run() -> anyhow::Result<()> {},PgBotAuthorizer::new(PgBotAuthorizationRepo::new(pool.clone())),PgUserApiKeyAuthorizer::new(PgUserApiKeyAuthorizationRepo::new(pool.clone())),- );+ )+ .with_harness_authorizer(PgHarnessAuthorizer::new(PgHarnessAuthorizationRepo::new(+ pool.clone(),+ )));let read_state = AgentSessionRouterState::new(AgentSessionServiceImpl::new(session_repo.clone(),@@ -551,7 +557,6 @@ async fn run() -> anyhow::Result<()> {);let gateway_state = RuntimeGatewayState::new(runtimes,- bots_directory,MacroAuthorizationState::new(Arc::new(authorization_service.clone())),);let forward_state = ForwardGatewayState::new(diff --git a/services/document_storage_service/Cargo.toml b/services/document_storage_service/Cargo.tomlindex 23755fd520..0057cfb512 100644--- a/services/document_storage_service/Cargo.toml+++ b/services/document_storage_service/Cargo.toml@@ -111,6 +111,7 @@ github = { path = "../../crates/github", default-features = false, features = ["sync",] }graphql_soup = { path = "../../crates/graphql_soup" }+harnesses = { path = "../../crates/harnesses" }hex = { workspace = true }http-body-util = { workspace = true }jsonwebtoken = { workspace = true }diff --git a/services/document_storage_service/src/api.rs b/services/document_storage_service/src/api.rsindex c6b65cf161..523a1ff0a4 100644--- a/services/document_storage_service/src/api.rs+++ b/services/document_storage_service/src/api.rs@@ -216,6 +216,9 @@ fn api_router(state: ApiContext) -> Router {.merge(bots::inbound::axum_router::bots_router(state.bots_state.clone(),))+ .merge(harnesses::inbound::axum_router::harnesses_router(+ state.harnesses_state.clone(),+ )).merge(bots::inbound::channel_webhook_router::channel_scoped_bot_router(state.channel_bot_webhook_state.clone(),diff --git a/services/document_storage_service/src/api/context.rs b/services/document_storage_service/src/api/context.rsindex 819c94304e..6365cbeba2 100644--- a/services/document_storage_service/src/api/context.rs+++ b/services/document_storage_service/src/api/context.rs@@ -369,6 +369,15 @@ pub(crate) type DssBotService = BotServiceImpl<PgBotsRepo, DssEventBroker>;pub(crate) type DssBotsState =BotsRouterState<DssBotService, EntityAccessService, AuthorizationService>;+/// Type alias for the harnesses service wired into DSS.+pub(crate) type DssHarnessService = harnesses::domain::service::HarnessServiceImpl<+ harnesses::outbound::pg_harness_repo::PgHarnessRepo,+>;++/// Type alias for the harnesses router state.+pub(crate) type DssHarnessesState =+ harnesses::inbound::axum_router::HarnessesRouterState<DssHarnessService, AuthorizationService>;+/// Type alias for the channel bot webhook router state.pub(crate) type DssChannelBotWebhookState = ChannelBotWebhookRouterState<DssBotService,@@ -543,6 +552,7 @@ pub(crate) struct ApiContext {/// the channels router (starter-doc seeding records mention backlinks).pub channel_service: Arc<DssChannelService>,pub bots_state: DssBotsState,+ pub harnesses_state: DssHarnessesState,pub channel_bot_webhook_state: DssChannelBotWebhookState,pub call_state: DssCallState,pub call_webhook_state: DssCallWebhookState,diff --git a/services/document_storage_service/src/api/swagger.rs b/services/document_storage_service/src/api/swagger.rsindex 1b93aac784..5514b2230d 100644--- a/services/document_storage_service/src/api/swagger.rs+++ b/services/document_storage_service/src/api/swagger.rs@@ -254,6 +254,15 @@ use utoipa::OpenApi;channels::inbound::axum_router::get_activity_handler,channels::inbound::axum_router::post_activity_handler,+ // harnesses+ harnesses::inbound::axum_router::create_pairing_handler,+ harnesses::inbound::axum_router::get_pairing_handler,+ harnesses::inbound::axum_router::approve_pairing_handler,+ harnesses::inbound::axum_router::claim_pairing_handler,+ harnesses::inbound::axum_router::list_harnesses_handler,+ harnesses::inbound::axum_router::delete_harness_handler,+ harnesses::inbound::axum_router::list_bound_agents_handler,+// botsbots::inbound::axum_router::create_agent_handler,bots::inbound::axum_router::list_agents_handler,@@ -564,6 +573,18 @@ use utoipa::OpenApi;ApiActivity,PostActivityRequest,+ // Harnesses+ harnesses::domain::models::Harness,+ harnesses::domain::models::HarnessOwner,+ harnesses::domain::models::HarnessAgent,+ harnesses::domain::models::CreatePairingRequest,+ harnesses::domain::models::CreatedPairing,+ harnesses::domain::models::PairingDetails,+ harnesses::domain::models::ApprovePairingRequest,+ harnesses::domain::models::ClaimPairingRequest,+ harnesses::domain::models::ClaimedPairing,+ harnesses::inbound::axum_router::PendingClaimResponse,+// Botsbots::domain::models::Agent,bots::domain::models::AgentChannelScope,diff --git a/services/document_storage_service/src/main.rs b/services/document_storage_service/src/main.rsindex fe9f4eec60..60a788e4ad 100644--- a/services/document_storage_service/src/main.rs+++ b/services/document_storage_service/src/main.rs@@ -85,12 +85,13 @@ use frecency::{domain::services::FrecencyQueryServiceImpl, outbound::postgres::Fuse github::domain::service::{GithubSyncConfig, GithubSyncServiceImpl};use github::outbound::github_sync_client::GithubSyncClientImpl;use github::outbound::pg_github_sync_repo::PgGithubSyncRepo;+use harnesses::outbound::pg_harness_repo::PgHarnessRepo;use lexical_client::LexicalClient;use macro_auth::middleware::decode_jwt::JwtValidationArgs;use macro_authorization::{InternalAuthConfig, MacroAuthJwtValidator, MacroAuthorizationServiceImpl,- MacroAuthorizationState, PgBotAuthorizationRepo, PgBotAuthorizer,- PgUserApiKeyAuthorizationRepo, PgUserApiKeyAuthorizer,+ MacroAuthorizationState, PgBotAuthorizationRepo, PgBotAuthorizer, PgHarnessAuthorizationRepo,+ PgHarnessAuthorizer, PgUserApiKeyAuthorizationRepo, PgUserApiKeyAuthorizer,};use macro_entrypoint::MacroEntrypoint;use macro_env_var::maybe_env_vars;@@ -329,8 +330,13 @@ async fn run() -> anyhow::Result<()> {},PgBotAuthorizer::new(PgBotAuthorizationRepo::new(db.clone())),PgUserApiKeyAuthorizer::new(PgUserApiKeyAuthorizationRepo::new(db.clone())),- );+ )+ .with_harness_authorizer(PgHarnessAuthorizer::new(PgHarnessAuthorizationRepo::new(+ db.clone(),+ )));let authorization_state = MacroAuthorizationState::new(Arc::new(authorization_service));+ let harnesses_service =+ harnesses::domain::service::HarnessServiceImpl::new(PgHarnessRepo::new(db.clone()));// Initialize OpenSearch clientlet opensearch_client = OpensearchClient::new(@@ -1358,6 +1364,10 @@ async fn run() -> anyhow::Result<()> {(*entity_access_service).clone(),authorization_state.clone(),),+ harnesses_state: harnesses::inbound::axum_router::HarnessesRouterState::new(+ harnesses_service,+ authorization_state.clone(),+ ),channel_bot_webhook_state,call_state,call_webhook_state,