Skip to content

armgit / macro

Public Imported from GitHub
0

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

feat(ai): enforce user usage quotas behind a default-off flag (#7270)

Will Hutchinsona365c54ce62a
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.json
index 75e020fa75..38c8a15c85 100644
--- a/.github/workspace-dep-closures.json
+++ b/.github/workspace-dep-closures.json
@@ -52,8 +52,10 @@
"crates/agent_fold",
"crates/agent_runtime_protocol",
"crates/agent_session",
+ "crates/ai_billing",
"crates/ai_toolset",
"crates/ai_usage",
+ "crates/analytics_client",
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
@@ -88,6 +90,7 @@
"crates/frecency",
"crates/fusionauth",
"crates/genai_telemetry",
+ "crates/generic_email_domains",
"crates/github",
"crates/google_token",
"crates/harness_id",
@@ -139,6 +142,7 @@
"crates/properties",
"crates/rate_limit",
"crates/remote_env_var",
+ "crates/roles_and_permissions",
"crates/s3_key",
"crates/secretsmanager_client",
"crates/share_permission_db_utils",
@@ -150,6 +154,7 @@
"crates/system_properties",
"crates/system_skills",
"crates/task_dedup",
+ "crates/teams",
"crates/unfurl",
"crates/user_quota",
"crates/workspace-hack"
@@ -161,8 +166,10 @@
"crates/agent_fold",
"crates/agent_runtime_protocol",
"crates/agent_session",
+ "crates/ai_billing",
"crates/ai_toolset",
"crates/ai_usage",
+ "crates/analytics_client",
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
@@ -197,6 +204,7 @@
"crates/frecency",
"crates/fusionauth",
"crates/genai_telemetry",
+ "crates/generic_email_domains",
"crates/github",
"crates/google_token",
"crates/harness_id",
@@ -250,6 +258,7 @@
"crates/properties",
"crates/rate_limit",
"crates/remote_env_var",
+ "crates/roles_and_permissions",
"crates/s3_key",
"crates/secretsmanager_client",
"crates/share_permission_db_utils",
@@ -261,6 +270,7 @@
"crates/system_properties",
"crates/system_skills",
"crates/task_dedup",
+ "crates/teams",
"crates/unfurl",
"crates/user_quota",
"crates/workspace-hack"
@@ -282,8 +292,10 @@
"crates/agent_runtime_protocol",
"crates/agent_session",
"crates/agent_trigger",
+ "crates/ai_billing",
"crates/ai_toolset",
"crates/ai_usage",
+ "crates/analytics_client",
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
@@ -324,6 +336,7 @@
"crates/frecency",
"crates/fusionauth",
"crates/genai_telemetry",
+ "crates/generic_email_domains",
"crates/github",
"crates/google_token",
"crates/harness_id",
@@ -377,6 +390,7 @@
"crates/properties",
"crates/rate_limit",
"crates/remote_env_var",
+ "crates/roles_and_permissions",
"crates/s3_key",
"crates/secretsmanager_client",
"crates/share_permission_db_utils",
@@ -389,6 +403,7 @@
"crates/system_properties",
"crates/system_skills",
"crates/task_dedup",
+ "crates/teams",
"crates/unfurl",
"crates/user_quota",
"crates/workspace-hack"
@@ -404,6 +419,7 @@
"crates/agent_runtime_protocol",
"crates/agent_session",
"crates/agent_trigger",
+ "crates/ai_billing",
"crates/ai_tools",
"crates/ai_toolset",
"crates/ai_usage",
@@ -562,6 +578,7 @@
"crates/agent_inmem",
"crates/agent_runtime_protocol",
"crates/agent_session",
+ "crates/ai_billing",
"crates/ai_tools",
"crates/ai_toolset",
"crates/ai_usage",
@@ -749,23 +766,31 @@
"crates/agent_fold",
"crates/agent_runtime_protocol",
"crates/agent_session",
+ "crates/ai_billing",
"crates/ai_toolset",
"crates/ai_usage",
+ "crates/analytics_client",
"crates/attachment",
+ "crates/authentication_service_client",
"crates/bot_id",
"crates/bot_token",
"crates/bots",
"crates/broadcast",
+ "crates/calendar_events",
"crates/channel_sender",
"crates/channels",
"crates/connection_gateway_client",
"crates/connection_gateway_models",
"crates/contacts",
"crates/cowlike",
+ "crates/crm",
"crates/database_env_vars",
"crates/document_sub_type",
+ "crates/email",
+ "crates/email_utils",
"crates/entity_access",
"crates/entity_access_db_utils",
+ "crates/entity_access_management",
"crates/entity_mutation",
"crates/entity_registry/entity_registry",
"crates/entity_registry/entity_registry_db_utils",
@@ -773,6 +798,8 @@
"crates/filter_ast",
"crates/frecency",
"crates/genai_telemetry",
+ "crates/generic_email_domains",
+ "crates/google_token",
"crates/harness_id",
"crates/harness_token",
"crates/initiative",
@@ -780,6 +807,7 @@
"crates/item_filters",
"crates/kafka_util",
"crates/last_online_tracker",
+ "crates/lexical_client",
"crates/macro_auth",
"crates/macro_authorization",
"crates/macro_aws_config",
@@ -801,7 +829,9 @@
"crates/model_notifications",
"crates/model_owner",
"crates/model_user",
+ "crates/models_ai_projection",
"crates/models_bulk_upload",
+ "crates/models_email",
"crates/models_entity_access_management",
"crates/models_pagination",
"crates/models_permissions",
@@ -814,10 +844,15 @@
"crates/properties",
"crates/rate_limit",
"crates/remote_env_var",
+ "crates/roles_and_permissions",
+ "crates/s3_key",
"crates/share_permission_db_utils",
+ "crates/sqs_client",
"crates/sqs_worker",
"crates/static_file_service_client",
"crates/system_properties",
+ "crates/teams",
+ "crates/unfurl",
"crates/workspace-hack"
],
"agent_trigger": [
@@ -827,24 +862,32 @@
"crates/agent_runtime_protocol",
"crates/agent_session",
"crates/agent_trigger",
+ "crates/ai_billing",
"crates/ai_toolset",
"crates/ai_usage",
+ "crates/analytics_client",
"crates/attachment",
+ "crates/authentication_service_client",
"crates/bot_id",
"crates/bot_token",
"crates/bots",
"crates/broadcast",
+ "crates/calendar_events",
"crates/channel_sender",
"crates/channels",
"crates/connection_gateway_client",
"crates/connection_gateway_models",
"crates/contacts",
"crates/cowlike",
+ "crates/crm",
"crates/database_env_vars",
"crates/document_storage_service_client",
"crates/document_sub_type",
+ "crates/email",
+ "crates/email_utils",
"crates/entity_access",
"crates/entity_access_db_utils",
+ "crates/entity_access_management",
"crates/entity_mutation",
"crates/entity_registry/entity_registry",
"crates/entity_registry/entity_registry_db_utils",
@@ -852,6 +895,8 @@
"crates/filter_ast",
"crates/frecency",
"crates/genai_telemetry",
+ "crates/generic_email_domains",
+ "crates/google_token",
"crates/harness_id",
"crates/harness_token",
"crates/initiative",
@@ -881,7 +926,9 @@
"crates/model_notifications",
"crates/model_owner",
"crates/model_user",
+ "crates/models_ai_projection",
"crates/models_bulk_upload",
+ "crates/models_email",
"crates/models_entity_access_management",
"crates/models_pagination",
"crates/models_permissions",
@@ -894,11 +941,16 @@
"crates/properties",
"crates/rate_limit",
"crates/remote_env_var",
+ "crates/roles_and_permissions",
+ "crates/s3_key",
"crates/share_permission_db_utils",
+ "crates/sqs_client",
"crates/sqs_worker",
"crates/static_file",
"crates/static_file_service_client",
"crates/system_properties",
+ "crates/teams",
+ "crates/unfurl",
"crates/workspace-hack"
],
"agent_trigger_service": [
@@ -908,13 +960,17 @@
"crates/agent_runtime_protocol",
"crates/agent_session",
"crates/agent_trigger",
+ "crates/ai_billing",
"crates/ai_toolset",
"crates/ai_usage",
+ "crates/analytics_client",
"crates/attachment",
+ "crates/authentication_service_client",
"crates/bot_id",
"crates/bot_token",
"crates/bots",
"crates/broadcast",
+ "crates/calendar_events",
"crates/channel_sender",
"crates/channels",
"crates/connection_gateway_client",
@@ -925,8 +981,11 @@
"crates/database_env_vars",
"crates/document_storage_service_client",
"crates/document_sub_type",
+ "crates/email",
+ "crates/email_utils",
"crates/entity_access",
"crates/entity_access_db_utils",
+ "crates/entity_access_management",
"crates/entity_mutation",
"crates/entity_registry/entity_registry",
"crates/entity_registry/entity_registry_db_utils",
@@ -934,6 +993,8 @@
"crates/filter_ast",
"crates/frecency",
"crates/genai_telemetry",
+ "crates/generic_email_domains",
+ "crates/google_token",
"crates/harness_id",
"crates/harness_token",
"crates/initiative",
@@ -965,7 +1026,9 @@
"crates/model_notifications",
"crates/model_owner",
"crates/model_user",
+ "crates/models_ai_projection",
"crates/models_bulk_upload",
+ "crates/models_email",
"crates/models_entity_access_management",
"crates/models_pagination",
"crates/models_permissions",
@@ -978,11 +1041,15 @@
"crates/properties",
"crates/rate_limit",
"crates/remote_env_var",
+ "crates/roles_and_permissions",
+ "crates/s3_key",
"crates/share_permission_db_utils",
+ "crates/sqs_client",
"crates/sqs_worker",
"crates/static_file",
"crates/static_file_service_client",
"crates/system_properties",
+ "crates/teams",
"crates/unfurl",
"crates/workspace-hack",
"services/agent_trigger_service"
@@ -1084,6 +1151,7 @@
"crates/agent_fold",
"crates/agent_runtime_protocol",
"crates/agent_session",
+ "crates/ai_billing",
"crates/ai_projections",
"crates/ai_tools",
"crates/ai_toolset",
@@ -1313,6 +1381,7 @@
"crates/agent_fold",
"crates/agent_runtime_protocol",
"crates/agent_session",
+ "crates/ai_billing",
"crates/ai_tools",
"crates/ai_toolset",
"crates/ai_usage",
@@ -1481,24 +1550,94 @@
"crates/workspace-hack"
],
"anthropic": [
+ "crates/activity",
+ "crates/agent",
+ "crates/agent_fold",
+ "crates/agent_runtime_protocol",
+ "crates/ai_billing",
"crates/ai_toolset",
"crates/ai_usage",
+ "crates/analytics_client",
"crates/anthropic",
+ "crates/attachment",
+ "crates/authentication_service_client",
"crates/bot_id",
"crates/bot_token",
+ "crates/broadcast",
+ "crates/calendar_events",
+ "crates/channel_sender",
+ "crates/channels",
+ "crates/connection_gateway_client",
+ "crates/connection_gateway_models",
+ "crates/contacts",
"crates/cowlike",
+ "crates/crm",
+ "crates/database_env_vars",
+ "crates/document_sub_type",
+ "crates/email",
+ "crates/email_utils",
+ "crates/entity_access",
+ "crates/entity_access_db_utils",
+ "crates/entity_access_management",
+ "crates/entity_mutation",
+ "crates/filter_ast",
+ "crates/frecency",
"crates/genai_telemetry",
+ "crates/generic_email_domains",
+ "crates/google_token",
"crates/harness_id",
"crates/harness_token",
+ "crates/initiative",
+ "crates/invite_email",
+ "crates/item_filters",
+ "crates/kafka_util",
+ "crates/last_online_tracker",
+ "crates/lexical_client",
"crates/macro_auth",
"crates/macro_authorization",
+ "crates/macro_aws_config",
+ "crates/macro_entrypoint",
"crates/macro_env",
"crates/macro_env_var",
+ "crates/macro_event_broker",
+ "crates/macro_event_topics",
+ "crates/macro_service_urls",
+ "crates/macro_tower_layers",
"crates/macro_user_id",
"crates/macro_uuid",
+ "crates/mention_utils",
+ "crates/messages",
+ "crates/model",
+ "crates/model-entity",
"crates/model-error-response",
+ "crates/model_file_type",
+ "crates/model_notifications",
+ "crates/model_owner",
"crates/model_user",
+ "crates/models_ai_projection",
+ "crates/models_bulk_upload",
+ "crates/models_email",
+ "crates/models_entity_access_management",
+ "crates/models_pagination",
+ "crates/models_permissions",
+ "crates/models_properties",
+ "crates/models_sfs",
+ "crates/non_empty",
+ "crates/notification",
+ "crates/notification_state",
+ "crates/prompt",
+ "crates/properties",
+ "crates/rate_limit",
"crates/remote_env_var",
+ "crates/roles_and_permissions",
+ "crates/s3_key",
+ "crates/share_permission_db_utils",
+ "crates/sqs_client",
+ "crates/sqs_worker",
+ "crates/static_file_service_client",
+ "crates/system_properties",
+ "crates/teams",
+ "crates/unfurl",
"crates/workspace-hack"
],
"attachment": [
@@ -1786,8 +1925,10 @@
"crates/agent_fold",
"crates/agent_runtime_protocol",
"crates/agent_session",
+ "crates/ai_billing",
"crates/ai_toolset",
"crates/ai_usage",
+ "crates/analytics_client",
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
@@ -1828,6 +1969,7 @@
"crates/frecency",
"crates/fusionauth",
"crates/genai_telemetry",
+ "crates/generic_email_domains",
"crates/github",
"crates/google_token",
"crates/graphql_common",
@@ -1889,6 +2031,7 @@
"crates/readonly_pool",
"crates/reminders",
"crates/remote_env_var",
+ "crates/roles_and_permissions",
"crates/s3_key",
"crates/secretsmanager_client",
"crates/share_permission_db_utils",
@@ -1903,6 +2046,7 @@
"crates/system_properties",
"crates/system_skills",
"crates/task_dedup",
+ "crates/teams",
"crates/unfurl",
"crates/user_quota",
"crates/workspace-hack"
@@ -2100,6 +2244,7 @@
"crates/agent_fold",
"crates/agent_runtime_protocol",
"crates/agent_session",
+ "crates/ai_billing",
"crates/ai_tools",
"crates/ai_toolset",
"crates/ai_usage",
@@ -2429,13 +2574,17 @@
"crates/agent_fold",
"crates/agent_runtime_protocol",
"crates/agent_session",
+ "crates/ai_billing",
"crates/ai_toolset",
"crates/ai_usage",
+ "crates/analytics_client",
"crates/attachment",
+ "crates/authentication_service_client",
"crates/bot_id",
"crates/bot_token",
"crates/bots",
"crates/broadcast",
+ "crates/calendar_events",
"crates/channel_sender",
"crates/channels",
"crates/codex_cloud_agents",
@@ -2443,10 +2592,14 @@
"crates/connection_gateway_models",
"crates/contacts",
"crates/cowlike",
+ "crates/crm",
"crates/database_env_vars",
"crates/document_sub_type",
+ "crates/email",
+ "crates/email_utils",
"crates/entity_access",
"crates/entity_access_db_utils",
+ "crates/entity_access_management",
"crates/entity_mutation",
"crates/entity_registry/entity_registry",
"crates/entity_registry/entity_registry_db_utils",
@@ -2454,6 +2607,8 @@
"crates/filter_ast",
"crates/frecency",
"crates/genai_telemetry",
+ "crates/generic_email_domains",
+ "crates/google_token",
"crates/harness_id",
"crates/harness_token",
"crates/initiative",
@@ -2461,6 +2616,7 @@
"crates/item_filters",
"crates/kafka_util",
"crates/last_online_tracker",
+ "crates/lexical_client",
"crates/macro_auth",
"crates/macro_authorization",
"crates/macro_aws_config",
@@ -2482,7 +2638,9 @@
"crates/model_notifications",
"crates/model_owner",
"crates/model_user",
+ "crates/models_ai_projection",
"crates/models_bulk_upload",
+ "crates/models_email",
"crates/models_entity_access_management",
"crates/models_pagination",
"crates/models_permissions",
@@ -2495,10 +2653,15 @@
"crates/properties",
"crates/rate_limit",
"crates/remote_env_var",
+ "crates/roles_and_permissions",
+ "crates/s3_key",
"crates/share_permission_db_utils",
+ "crates/sqs_client",
"crates/sqs_worker",
"crates/static_file_service_client",
"crates/system_properties",
+ "crates/teams",
+ "crates/unfurl",
"crates/workspace-hack"
],
"codex_connection": [
@@ -2507,13 +2670,17 @@
"crates/agent_fold",
"crates/agent_runtime_protocol",
"crates/agent_session",
+ "crates/ai_billing",
"crates/ai_toolset",
"crates/ai_usage",
+ "crates/analytics_client",
"crates/attachment",
+ "crates/authentication_service_client",
"crates/bot_id",
"crates/bot_token",
"crates/bots",
"crates/broadcast",
+ "crates/calendar_events",
"crates/channel_sender",
"crates/channels",
"crates/codex_cloud_agents",
@@ -2522,10 +2689,14 @@
"crates/connection_gateway_models",
"crates/contacts",
"crates/cowlike",
+ "crates/crm",
"crates/database_env_vars",
"crates/document_sub_type",
+ "crates/email",
+ "crates/email_utils",
"crates/entity_access",
"crates/entity_access_db_utils",
+ "crates/entity_access_management",
"crates/entity_mutation",
"crates/entity_registry/entity_registry",
"crates/entity_registry/entity_registry_db_utils",
@@ -2533,6 +2704,8 @@
"crates/filter_ast",
"crates/frecency",
"crates/genai_telemetry",
+ "crates/generic_email_domains",
+ "crates/google_token",
"crates/harness_id",
"crates/harness_token",
"crates/initiative",
@@ -2540,6 +2713,7 @@
"crates/item_filters",
"crates/kafka_util",
"crates/last_online_tracker",
+ "crates/lexical_client",
"crates/macro_auth",
"crates/macro_authorization",
"crates/macro_aws_config",
@@ -2561,7 +2735,9 @@
"crates/model_notifications",
"crates/model_owner",
"crates/model_user",
+ "crates/models_ai_projection",
"crates/models_bulk_upload",
+ "crates/models_email",
"crates/models_entity_access_management",
"crates/models_pagination",
"crates/models_permissions",
@@ -2574,10 +2750,15 @@
"crates/properties",
"crates/rate_limit",
"crates/remote_env_var",
+ "crates/roles_and_permissions",
+ "crates/s3_key",
"crates/share_permission_db_utils",
+ "crates/sqs_client",
"crates/sqs_worker",
"crates/static_file_service_client",
"crates/system_properties",
+ "crates/teams",
+ "crates/unfurl",
"crates/workspace-hack"
],
"coding_agent_worker": [
@@ -2587,8 +2768,10 @@
"crates/agent_runtime_protocol",
"crates/agent_session",
"crates/agent_trigger",
+ "crates/ai_billing",
"crates/ai_toolset",
"crates/ai_usage",
+ "crates/analytics_client",
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
@@ -2624,6 +2807,7 @@
"crates/foreign_entity",
"crates/frecency",
"crates/genai_telemetry",
+ "crates/generic_email_domains",
"crates/google_token",
"crates/harness_id",
"crates/harness_token",
@@ -2675,6 +2859,7 @@
"crates/properties",
"crates/rate_limit",
"crates/remote_env_var",
+ "crates/roles_and_permissions",
"crates/s3_key",
"crates/secretsmanager_client",
"crates/share_permission_db_utils",
@@ -2687,6 +2872,7 @@
"crates/system_properties",
"crates/system_skills",
"crates/task_dedup",
+ "crates/teams",
"crates/unfurl",
"crates/user_quota",
"crates/webhook",
@@ -2838,6 +3024,7 @@
"crates/agent_fold",
"crates/agent_runtime_protocol",
"crates/agent_session",
+ "crates/ai_billing",
"crates/ai_tools",
"crates/ai_toolset",
"crates/ai_usage",
@@ -3338,24 +3525,32 @@
"crates/agent_fold",
"crates/agent_runtime_protocol",
"crates/agent_session",
+ "crates/ai_billing",
"crates/ai_toolset",
"crates/ai_usage",
+ "crates/analytics_client",
"crates/attachment",
+ "crates/authentication_service_client",
"crates/bot_id",
"crates/bot_token",
"crates/bots",
"crates/broadcast",
+ "crates/calendar_events",
"crates/channel_sender",
"crates/channels",
"crates/connection_gateway_client",
"crates/connection_gateway_models",
"crates/contacts",
"crates/cowlike",
+ "crates/crm",
"crates/cursor_cloud_agents",
"crates/database_env_vars",
"crates/document_sub_type",
+ "crates/email",
+ "crates/email_utils",
"crates/entity_access",
"crates/entity_access_db_utils",
+ "crates/entity_access_management",
"crates/entity_mutation",
"crates/entity_registry/entity_registry",
"crates/entity_registry/entity_registry_db_utils",
@@ -3363,6 +3558,8 @@
"crates/filter_ast",
"crates/frecency",
"crates/genai_telemetry",
+ "crates/generic_email_domains",
+ "crates/google_token",
"crates/harness_id",
"crates/harness_token",
"crates/initiative",
@@ -3370,6 +3567,7 @@
"crates/item_filters",
"crates/kafka_util",
"crates/last_online_tracker",
+ "crates/lexical_client",
"crates/macro_auth",
"crates/macro_authorization",
"crates/macro_aws_config",
@@ -3391,7 +3589,9 @@
"crates/model_notifications",
"crates/model_owner",
"crates/model_user",
+ "crates/models_ai_projection",
"crates/models_bulk_upload",
+ "crates/models_email",
"crates/models_entity_access_management",
"crates/models_pagination",
"crates/models_permissions",
@@ -3404,10 +3604,15 @@
"crates/properties",
"crates/rate_limit",
"crates/remote_env_var",
+ "crates/roles_and_permissions",
+ "crates/s3_key",
"crates/share_permission_db_utils",
+ "crates/sqs_client",
"crates/sqs_worker",
"crates/static_file_service_client",
"crates/system_properties",
+ "crates/teams",
+ "crates/unfurl",
"crates/workspace-hack"
],
"database_env_vars": [
@@ -3470,8 +3675,10 @@
"crates/agent",
"crates/agent_fold",
"crates/agent_runtime_protocol",
+ "crates/ai_billing",
"crates/ai_toolset",
"crates/ai_usage",
+ "crates/analytics_client",
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
@@ -3506,6 +3713,7 @@
"crates/foreign_entity",
"crates/frecency",
"crates/genai_telemetry",
+ "crates/generic_email_domains",
"crates/google_token",
"crates/harness_id",
"crates/harness_token",
@@ -3571,6 +3779,7 @@
"crates/system_properties",
"crates/system_skills",
"crates/task_dedup",
+ "crates/teams",
"crates/unfurl",
"crates/user_quota",
"crates/workspace-hack",
@@ -3762,6 +3971,7 @@
"crates/agent_runtime_protocol",
"crates/agent_session",
"crates/agent_trigger",
+ "crates/ai_billing",
"crates/ai_tools",
"crates/ai_toolset",
"crates/ai_usage",
@@ -4017,8 +4227,10 @@
"crates/agent",
"crates/agent_fold",
"crates/agent_runtime_protocol",
+ "crates/ai_billing",
"crates/ai_toolset",
"crates/ai_usage",
+ "crates/analytics_client",
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
@@ -4052,6 +4264,7 @@
"crates/foreign_entity",
"crates/frecency",
"crates/genai_telemetry",
+ "crates/generic_email_domains",
"crates/google_token",
"crates/harness_id",
"crates/harness_token",
@@ -4102,6 +4315,7 @@
"crates/properties",
"crates/rate_limit",
"crates/remote_env_var",
+ "crates/roles_and_permissions",
"crates/s3_key",
"crates/secretsmanager_client",
"crates/share_permission_db_utils",
@@ -4113,6 +4327,7 @@
"crates/system_properties",
"crates/system_skills",
"crates/task_dedup",
+ "crates/teams",
"crates/unfurl",
"crates/user_quota",
"crates/workspace-hack",
@@ -4123,8 +4338,10 @@
"crates/agent",
"crates/agent_fold",
"crates/agent_runtime_protocol",
+ "crates/ai_billing",
"crates/ai_toolset",
"crates/ai_usage",
+ "crates/analytics_client",
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
@@ -4157,6 +4374,7 @@
"crates/foreign_entity",
"crates/frecency",
"crates/genai_telemetry",
+ "crates/generic_email_domains",
"crates/google_token",
"crates/harness_id",
"crates/harness_token",
@@ -4207,6 +4425,7 @@
"crates/properties",
"crates/rate_limit",
"crates/remote_env_var",
+ "crates/roles_and_permissions",
"crates/s3_key",
"crates/secretsmanager_client",
"crates/share_permission_db_utils",
@@ -4218,6 +4437,7 @@
"crates/system_properties",
"crates/system_skills",
"crates/task_dedup",
+ "crates/teams",
"crates/unfurl",
"crates/user_quota",
"crates/workspace-hack"
@@ -5209,8 +5429,10 @@
"crates/agent",
"crates/agent_fold",
"crates/agent_runtime_protocol",
+ "crates/ai_billing",
"crates/ai_toolset",
"crates/ai_usage",
+ "crates/analytics_client",
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
@@ -5244,6 +5466,7 @@
"crates/frecency",
"crates/fusionauth",
"crates/genai_telemetry",
+ "crates/generic_email_domains",
"crates/github",
"crates/google_token",
"crates/harness_id",
@@ -5295,6 +5518,7 @@
"crates/properties",
"crates/rate_limit",
"crates/remote_env_var",
+ "crates/roles_and_permissions",
"crates/s3_key",
"crates/secretsmanager_client",
"crates/share_permission_db_utils",
@@ -5306,6 +5530,7 @@
"crates/system_properties",
"crates/system_skills",
"crates/task_dedup",
+ "crates/teams",
"crates/unfurl",
"crates/user_quota",
"crates/workspace-hack"
@@ -5573,8 +5798,10 @@
"crates/agent_fold",
"crates/agent_runtime_protocol",
"crates/agent_session",
+ "crates/ai_billing",
"crates/ai_toolset",
"crates/ai_usage",
+ "crates/analytics_client",
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
@@ -5613,6 +5840,7 @@
"crates/frecency",
"crates/fusionauth",
"crates/genai_telemetry",
+ "crates/generic_email_domains",
"crates/github",
"crates/google_token",
"crates/graphql_common",
@@ -5694,6 +5922,7 @@
"crates/system_properties",
"crates/system_skills",
"crates/task_dedup",
+ "crates/teams",
"crates/unfurl",
"crates/user_quota",
"crates/workspace-hack"
@@ -5705,8 +5934,10 @@
"crates/agent_fold",
"crates/agent_runtime_protocol",
"crates/agent_session",
+ "crates/ai_billing",
"crates/ai_toolset",
"crates/ai_usage",
+ "crates/analytics_client",
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
@@ -5745,6 +5976,7 @@
"crates/frecency",
"crates/fusionauth",
"crates/genai_telemetry",
+ "crates/generic_email_domains",
"crates/github",
"crates/google_token",
"crates/graphql_common",
@@ -5827,6 +6059,7 @@
"crates/system_properties",
"crates/system_skills",
"crates/task_dedup",
+ "crates/teams",
"crates/unfurl",
"crates/user_quota",
"crates/workspace-hack"
@@ -5838,8 +6071,10 @@
"crates/agent_fold",
"crates/agent_runtime_protocol",
"crates/agent_session",
+ "crates/ai_billing",
"crates/ai_toolset",
"crates/ai_usage",
+ "crates/analytics_client",
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
@@ -5878,6 +6113,7 @@
"crates/frecency",
"crates/fusionauth",
"crates/genai_telemetry",
+ "crates/generic_email_domains",
"crates/github",
"crates/google_token",
"crates/graphql_common",
@@ -5959,6 +6195,7 @@
"crates/system_properties",
"crates/system_skills",
"crates/task_dedup",
+ "crates/teams",
"crates/unfurl",
"crates/user_quota",
"crates/workspace-hack"
@@ -6108,6 +6345,7 @@
"crates/agent_fold",
"crates/agent_runtime_protocol",
"crates/agent_session",
+ "crates/ai_billing",
"crates/ai_tools",
"crates/ai_toolset",
"crates/ai_usage",
@@ -6258,8 +6496,10 @@
"crates/agent_fold",
"crates/agent_runtime_protocol",
"crates/agent_session",
+ "crates/ai_billing",
"crates/ai_toolset",
"crates/ai_usage",
+ "crates/analytics_client",
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
@@ -6298,6 +6538,7 @@
"crates/frecency",
"crates/fusionauth",
"crates/genai_telemetry",
+ "crates/generic_email_domains",
"crates/github",
"crates/google_token",
"crates/graphql_common",
@@ -6378,6 +6619,7 @@
"crates/system_properties",
"crates/system_skills",
"crates/task_dedup",
+ "crates/teams",
"crates/unfurl",
"crates/user_quota",
"crates/workspace-hack"
@@ -6459,8 +6701,10 @@
"crates/agent",
"crates/agent_fold",
"crates/agent_runtime_protocol",
+ "crates/ai_billing",
"crates/ai_toolset",
"crates/ai_usage",
+ "crates/analytics_client",
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
@@ -6493,6 +6737,7 @@
"crates/foreign_entity",
"crates/frecency",
"crates/genai_telemetry",
+ "crates/generic_email_domains",
"crates/google_token",
"crates/harness_id",
"crates/harness_token",
@@ -6544,6 +6789,7 @@
"crates/properties",
"crates/rate_limit",
"crates/remote_env_var",
+ "crates/roles_and_permissions",
"crates/s3_key",
"crates/secretsmanager_client",
"crates/share_permission_db_utils",
@@ -6555,6 +6801,7 @@
"crates/system_properties",
"crates/system_skills",
"crates/task_dedup",
+ "crates/teams",
"crates/unfurl",
"crates/user_quota",
"crates/workspace-hack"
@@ -6623,29 +6870,50 @@
"import": [
"crates/activity",
"crates/agent",
+ "crates/agent_fold",
+ "crates/agent_runtime_protocol",
+ "crates/ai_billing",
"crates/ai_toolset",
"crates/ai_usage",
+ "crates/analytics_client",
"crates/attachment",
+ "crates/authentication_service_client",
"crates/bot_id",
"crates/bot_token",
"crates/broadcast",
+ "crates/calendar_events",
"crates/channel_sender",
+ "crates/channels",
"crates/connection_gateway_client",
"crates/connection_gateway_models",
+ "crates/contacts",
"crates/cowlike",
+ "crates/crm",
"crates/database_env_vars",
"crates/document_sub_type",
+ "crates/email",
+ "crates/email_utils",
"crates/entity_access",
"crates/entity_access_db_utils",
+ "crates/entity_access_management",
+ "crates/entity_mutation",
+ "crates/filter_ast",
+ "crates/frecency",
"crates/genai_telemetry",
+ "crates/generic_email_domains",
+ "crates/google_token",
"crates/harness_id",
"crates/harness_token",
"crates/import",
+ "crates/initiative",
"crates/invite_email",
+ "crates/item_filters",
"crates/kafka_util",
"crates/last_online_tracker",
+ "crates/lexical_client",
"crates/macro_auth",
"crates/macro_authorization",
+ "crates/macro_aws_config",
"crates/macro_entrypoint",
"crates/macro_env",
"crates/macro_env_var",
@@ -6659,6 +6927,7 @@
"crates/mcp_select",
"crates/mcp_toolset",
"crates/mention_utils",
+ "crates/messages",
"crates/model",
"crates/model-entity",
"crates/model-error-response",
@@ -6666,11 +6935,14 @@
"crates/model_notifications",
"crates/model_owner",
"crates/model_user",
+ "crates/models_ai_projection",
"crates/models_bulk_upload",
+ "crates/models_email",
"crates/models_entity_access_management",
"crates/models_pagination",
"crates/models_permissions",
"crates/models_properties",
+ "crates/models_sfs",
"crates/non_empty",
"crates/notification",
"crates/notification_state",
@@ -6679,7 +6951,15 @@
"crates/properties",
"crates/rate_limit",
"crates/remote_env_var",
+ "crates/roles_and_permissions",
+ "crates/s3_key",
+ "crates/share_permission_db_utils",
+ "crates/sqs_client",
+ "crates/sqs_worker",
+ "crates/static_file_service_client",
"crates/system_properties",
+ "crates/teams",
+ "crates/unfurl",
"crates/workspace-hack"
],
"initiative": [
@@ -6743,8 +7023,10 @@
"crates/agent",
"crates/agent_fold",
"crates/agent_runtime_protocol",
+ "crates/ai_billing",
"crates/ai_toolset",
"crates/ai_usage",
+ "crates/analytics_client",
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
@@ -6777,6 +7059,7 @@
"crates/foreign_entity",
"crates/frecency",
"crates/genai_telemetry",
+ "crates/generic_email_domains",
"crates/google_token",
"crates/harness_id",
"crates/harness_token",
@@ -6828,6 +7111,7 @@
"crates/properties",
"crates/rate_limit",
"crates/remote_env_var",
+ "crates/roles_and_permissions",
"crates/s3_key",
"crates/secretsmanager_client",
"crates/share_permission_db_utils",
@@ -6839,6 +7123,7 @@
"crates/system_properties",
"crates/system_skills",
"crates/task_dedup",
+ "crates/teams",
"crates/unfurl",
"crates/user_quota",
"crates/workspace-hack"
@@ -7403,6 +7688,7 @@
"crates/agent_fold",
"crates/agent_runtime_protocol",
"crates/agent_session",
+ "crates/ai_billing",
"crates/ai_tools",
"crates/ai_toolset",
"crates/ai_usage",
@@ -7560,6 +7846,7 @@
"crates/agent_fold",
"crates/agent_runtime_protocol",
"crates/agent_session",
+ "crates/ai_billing",
"crates/ai_tools",
"crates/ai_toolset",
"crates/ai_usage",
@@ -8376,30 +8663,50 @@
"onboarding": [
"crates/activity",
"crates/agent",
+ "crates/agent_fold",
+ "crates/agent_runtime_protocol",
+ "crates/ai_billing",
"crates/ai_toolset",
"crates/ai_usage",
+ "crates/analytics_client",
"crates/attachment",
+ "crates/authentication_service_client",
"crates/bot_id",
"crates/bot_token",
"crates/broadcast",
+ "crates/calendar_events",
"crates/channel_sender",
+ "crates/channels",
"crates/connection_gateway_client",
"crates/connection_gateway_models",
+ "crates/contacts",
"crates/cowlike",
+ "crates/crm",
"crates/database_env_vars",
"crates/document_sub_type",
+ "crates/email",
+ "crates/email_utils",
"crates/entity_access",
"crates/entity_access_db_utils",
+ "crates/entity_access_management",
+ "crates/entity_mutation",
+ "crates/filter_ast",
+ "crates/frecency",
"crates/genai_telemetry",
"crates/generic_email_domains",
+ "crates/google_token",
"crates/harness_id",
"crates/harness_token",
"crates/import",
+ "crates/initiative",
"crates/invite_email",
+ "crates/item_filters",
"crates/kafka_util",
"crates/last_online_tracker",
+ "crates/lexical_client",
"crates/macro_auth",
"crates/macro_authorization",
+ "crates/macro_aws_config",
"crates/macro_entrypoint",
"crates/macro_env",
"crates/macro_env_var",
@@ -8413,6 +8720,7 @@
"crates/mcp_select",
"crates/mcp_toolset",
"crates/mention_utils",
+ "crates/messages",
"crates/model",
"crates/model-entity",
"crates/model-error-response",
@@ -8420,11 +8728,14 @@
"crates/model_notifications",
"crates/model_owner",
"crates/model_user",
+ "crates/models_ai_projection",
"crates/models_bulk_upload",
+ "crates/models_email",
"crates/models_entity_access_management",
"crates/models_pagination",
"crates/models_permissions",
"crates/models_properties",
+ "crates/models_sfs",
"crates/non_empty",
"crates/notification",
"crates/notification_state",
@@ -8434,7 +8745,15 @@
"crates/properties",
"crates/rate_limit",
"crates/remote_env_var",
+ "crates/roles_and_permissions",
+ "crates/s3_key",
+ "crates/share_permission_db_utils",
+ "crates/sqs_client",
+ "crates/sqs_worker",
+ "crates/static_file_service_client",
"crates/system_properties",
+ "crates/teams",
+ "crates/unfurl",
"crates/workspace-hack"
],
"opensearch_client": [
@@ -8643,8 +8962,10 @@
"crates/agent_preview",
"crates/agent_runtime_protocol",
"crates/agent_session",
+ "crates/ai_billing",
"crates/ai_toolset",
"crates/ai_usage",
+ "crates/analytics_client",
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
@@ -8679,6 +9000,7 @@
"crates/frecency",
"crates/fusionauth",
"crates/genai_telemetry",
+ "crates/generic_email_domains",
"crates/github",
"crates/google_token",
"crates/harness_id",
@@ -8735,6 +9057,7 @@
"crates/properties",
"crates/rate_limit",
"crates/remote_env_var",
+ "crates/roles_and_permissions",
"crates/s3_key",
"crates/secretsmanager_client",
"crates/share_permission_db_utils",
@@ -8746,6 +9069,7 @@
"crates/system_properties",
"crates/system_skills",
"crates/task_dedup",
+ "crates/teams",
"crates/unfurl",
"crates/user_quota",
"crates/workspace-hack",
@@ -8756,8 +9080,10 @@
"crates/agent",
"crates/agent_fold",
"crates/agent_runtime_protocol",
+ "crates/ai_billing",
"crates/ai_toolset",
"crates/ai_usage",
+ "crates/analytics_client",
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
@@ -8791,6 +9117,7 @@
"crates/foreign_entity",
"crates/frecency",
"crates/genai_telemetry",
+ "crates/generic_email_domains",
"crates/google_token",
"crates/harness_id",
"crates/harness_token",
@@ -8843,6 +9170,7 @@
"crates/properties",
"crates/rate_limit",
"crates/remote_env_var",
+ "crates/roles_and_permissions",
"crates/s3_key",
"crates/secretsmanager_client",
"crates/share_permission_db_utils",
@@ -8854,6 +9182,7 @@
"crates/system_properties",
"crates/system_skills",
"crates/task_dedup",
+ "crates/teams",
"crates/unfurl",
"crates/user_quota",
"crates/workspace-hack"
@@ -9099,6 +9428,7 @@
"crates/agent_fold",
"crates/agent_runtime_protocol",
"crates/agent_session",
+ "crates/ai_billing",
"crates/ai_tools",
"crates/ai_toolset",
"crates/ai_usage",
@@ -9247,8 +9577,10 @@
"crates/agent_fold",
"crates/agent_runtime_protocol",
"crates/agent_session",
+ "crates/ai_billing",
"crates/ai_toolset",
"crates/ai_usage",
+ "crates/analytics_client",
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
@@ -9287,6 +9619,7 @@
"crates/foreign_entity",
"crates/frecency",
"crates/genai_telemetry",
+ "crates/generic_email_domains",
"crates/google_token",
"crates/harness_id",
"crates/harness_token",
@@ -9364,6 +9697,7 @@
"crates/system_properties",
"crates/system_skills",
"crates/task_dedup",
+ "crates/teams",
"crates/unfurl",
"crates/user_quota",
"crates/workspace-hack",
@@ -9375,8 +9709,10 @@
"crates/agent_fold",
"crates/agent_runtime_protocol",
"crates/agent_session",
+ "crates/ai_billing",
"crates/ai_toolset",
"crates/ai_usage",
+ "crates/analytics_client",
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
@@ -9409,6 +9745,7 @@
"crates/filter_ast",
"crates/frecency",
"crates/genai_telemetry",
+ "crates/generic_email_domains",
"crates/google_token",
"crates/harness_id",
"crates/harness_token",
@@ -9441,6 +9778,7 @@
"crates/model_notifications",
"crates/model_owner",
"crates/model_user",
+ "crates/models_ai_projection",
"crates/models_bulk_upload",
"crates/models_dcs",
"crates/models_email",
@@ -9466,12 +9804,16 @@
"crates/readonly_pool",
"crates/reminders",
"crates/remote_env_var",
+ "crates/roles_and_permissions",
+ "crates/s3_key",
"crates/search_service",
"crates/secretsmanager_client",
"crates/share_permission_db_utils",
+ "crates/sqs_client",
"crates/sqs_worker",
"crates/static_file_service_client",
"crates/system_properties",
+ "crates/teams",
"crates/unfurl",
"crates/user_quota",
"crates/workspace-hack"
@@ -9750,8 +10092,10 @@
"crates/agent_fold",
"crates/agent_runtime_protocol",
"crates/agent_session",
+ "crates/ai_billing",
"crates/ai_toolset",
"crates/ai_usage",
+ "crates/analytics_client",
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
@@ -9788,6 +10132,7 @@
"crates/frecency",
"crates/fusionauth",
"crates/genai_telemetry",
+ "crates/generic_email_domains",
"crates/github",
"crates/google_token",
"crates/harness_id",
@@ -9848,6 +10193,7 @@
"crates/readonly_pool",
"crates/reminders",
"crates/remote_env_var",
+ "crates/roles_and_permissions",
"crates/s3_key",
"crates/search_service_client",
"crates/secretsmanager_client",
@@ -9862,6 +10208,7 @@
"crates/system_properties",
"crates/system_skills",
"crates/task_dedup",
+ "crates/teams",
"crates/unfurl",
"crates/user_quota",
"crates/workspace-hack"
@@ -9877,8 +10224,10 @@
"crates/agent_fold",
"crates/agent_runtime_protocol",
"crates/agent_session",
+ "crates/ai_billing",
"crates/ai_toolset",
"crates/ai_usage",
+ "crates/analytics_client",
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
@@ -9915,6 +10264,7 @@
"crates/frecency",
"crates/fusionauth",
"crates/genai_telemetry",
+ "crates/generic_email_domains",
"crates/github",
"crates/google_token",
"crates/harness_id",
@@ -9971,6 +10321,7 @@
"crates/readonly_pool",
"crates/reminders",
"crates/remote_env_var",
+ "crates/roles_and_permissions",
"crates/s3_key",
"crates/secretsmanager_client",
"crates/share_permission_db_utils",
@@ -9983,6 +10334,7 @@
"crates/system_properties",
"crates/system_skills",
"crates/task_dedup",
+ "crates/teams",
"crates/unfurl",
"crates/user_quota",
"crates/workspace-hack"
@@ -9994,8 +10346,10 @@
"crates/agent_fold",
"crates/agent_runtime_protocol",
"crates/agent_session",
+ "crates/ai_billing",
"crates/ai_toolset",
"crates/ai_usage",
+ "crates/analytics_client",
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
@@ -10033,6 +10387,7 @@
"crates/frecency",
"crates/fusionauth",
"crates/genai_telemetry",
+ "crates/generic_email_domains",
"crates/github",
"crates/google_token",
"crates/graphql_common",
@@ -10094,6 +10449,7 @@
"crates/readonly_pool",
"crates/reminders",
"crates/remote_env_var",
+ "crates/roles_and_permissions",
"crates/s3_key",
"crates/secretsmanager_client",
"crates/share_permission_db_utils",
@@ -10108,6 +10464,7 @@
"crates/system_properties",
"crates/system_skills",
"crates/task_dedup",
+ "crates/teams",
"crates/unfurl",
"crates/user_quota",
"crates/workspace-hack"
@@ -10119,8 +10476,10 @@
"crates/agent_fold",
"crates/agent_runtime_protocol",
"crates/agent_session",
+ "crates/ai_billing",
"crates/ai_toolset",
"crates/ai_usage",
+ "crates/analytics_client",
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
@@ -10157,6 +10516,7 @@
"crates/frecency",
"crates/fusionauth",
"crates/genai_telemetry",
+ "crates/generic_email_domains",
"crates/github",
"crates/google_token",
"crates/harness_id",
@@ -10215,6 +10575,7 @@
"crates/readonly_pool",
"crates/reminders",
"crates/remote_env_var",
+ "crates/roles_and_permissions",
"crates/s3_key",
"crates/secretsmanager_client",
"crates/share_permission_db_utils",
@@ -10228,6 +10589,7 @@
"crates/system_properties",
"crates/system_skills",
"crates/task_dedup",
+ "crates/teams",
"crates/unfurl",
"crates/user_quota",
"crates/workspace-hack"
@@ -10237,8 +10599,10 @@
"crates/agent",
"crates/agent_fold",
"crates/agent_runtime_protocol",
+ "crates/ai_billing",
"crates/ai_toolset",
"crates/ai_usage",
+ "crates/analytics_client",
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
@@ -10273,6 +10637,7 @@
"crates/foreign_entity",
"crates/frecency",
"crates/genai_telemetry",
+ "crates/generic_email_domains",
"crates/google_token",
"crates/harness_id",
"crates/harness_token",
@@ -10338,6 +10703,7 @@
"crates/system_properties",
"crates/system_skills",
"crates/task_dedup",
+ "crates/teams",
"crates/unfurl",
"crates/user_quota",
"crates/workspace-hack"
@@ -10980,8 +11346,10 @@
"crates/agent_runtime_protocol",
"crates/agent_session",
"crates/agent_trigger",
+ "crates/ai_billing",
"crates/ai_toolset",
"crates/ai_usage",
+ "crates/analytics_client",
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
@@ -11016,6 +11384,7 @@
"crates/foreign_entity",
"crates/frecency",
"crates/genai_telemetry",
+ "crates/generic_email_domains",
"crates/google_token",
"crates/harness_id",
"crates/harness_token",
@@ -11066,6 +11435,7 @@
"crates/properties",
"crates/rate_limit",
"crates/remote_env_var",
+ "crates/roles_and_permissions",
"crates/s3_key",
"crates/secretsmanager_client",
"crates/share_permission_db_utils",
@@ -11078,6 +11448,7 @@
"crates/system_properties",
"crates/system_skills",
"crates/task_dedup",
+ "crates/teams",
"crates/unfurl",
"crates/user_quota",
"crates/webhook",
diff --git a/.sqlx/query-868810c2bc77f71ff76184c0490b6e8bb39d9a2874441f48bd64947cca7280f1.json b/.sqlx/query-039e91325b454f78eaaba921deee2cda2dd09d78073173b60ff32306d8991024.json
similarity index 83%
rename from .sqlx/query-868810c2bc77f71ff76184c0490b6e8bb39d9a2874441f48bd64947cca7280f1.json
rename to .sqlx/query-039e91325b454f78eaaba921deee2cda2dd09d78073173b60ff32306d8991024.json
index 51fa430929..f957d53197 100644
--- a/.sqlx/query-868810c2bc77f71ff76184c0490b6e8bb39d9a2874441f48bd64947cca7280f1.json
+++ b/.sqlx/query-039e91325b454f78eaaba921deee2cda2dd09d78073173b60ff32306d8991024.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT user_id, COALESCE(SUM(\n COALESCE(\n total::float8,\n (input_tokens::float8 / 1000000.0) * $4\n + (output_tokens::float8 / 1000000.0) * $5\n )\n ), 0)::float8 AS \"usd!\"\n FROM ai_usage\n WHERE user_id = ANY($1)\n AND created_at >= $2\n AND created_at < $3\n AND feature <> ALL($6)\n GROUP BY user_id\n ",
+ "query": "\n SELECT user_id, COALESCE(SUM(\n COALESCE(\n total::float8,\n (input_tokens::float8 / 1000000.0) * $4\n + (output_tokens::float8 / 1000000.0) * $5\n )\n ), 0)::float8 AS \"usd!\"\n FROM ai_usage\n WHERE user_id = ANY($1)\n AND created_at >= $2\n AND created_at < $3\n AND count_usage = TRUE\n GROUP BY user_id\n ",
"describe": {
"columns": [
{
@@ -20,8 +20,7 @@
"Timestamptz",
"Timestamptz",
"Float8",
- "Float8",
- "TextArray"
+ "Float8"
]
},
"nullable": [
@@ -29,5 +28,5 @@
null
]
},
- "hash": "868810c2bc77f71ff76184c0490b6e8bb39d9a2874441f48bd64947cca7280f1"
+ "hash": "039e91325b454f78eaaba921deee2cda2dd09d78073173b60ff32306d8991024"
}
diff --git a/.sqlx/query-148ee5761f03d50f605eb76cb23f8ff83b338b73bd69685deab2034d4d21104a.json b/.sqlx/query-148ee5761f03d50f605eb76cb23f8ff83b338b73bd69685deab2034d4d21104a.json
new file mode 100644
index 0000000000..9b4f0dda8f
--- /dev/null
+++ b/.sqlx/query-148ee5761f03d50f605eb76cb23f8ff83b338b73bd69685deab2034d4d21104a.json
@@ -0,0 +1,26 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT id, count_usage FROM ai_usage ORDER BY id",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "count_usage",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": []
+ },
+ "nullable": [
+ false,
+ false
+ ]
+ },
+ "hash": "148ee5761f03d50f605eb76cb23f8ff83b338b73bd69685deab2034d4d21104a"
+}
diff --git a/.sqlx/query-c552084079684d8689a7330053ba60061cd45ce5071f59c394858f3fb2c8ea09.json b/.sqlx/query-2263d555eaf02a3751ad11b4e8dad617b604ff14f25a9f68f996f478fc5a9ae0.json
similarity index 62%
rename from .sqlx/query-c552084079684d8689a7330053ba60061cd45ce5071f59c394858f3fb2c8ea09.json
rename to .sqlx/query-2263d555eaf02a3751ad11b4e8dad617b604ff14f25a9f68f996f478fc5a9ae0.json
index 52bef1d396..9f0f67b00d 100644
--- a/.sqlx/query-c552084079684d8689a7330053ba60061cd45ce5071f59c394858f3fb2c8ea09.json
+++ b/.sqlx/query-2263d555eaf02a3751ad11b4e8dad617b604ff14f25a9f68f996f478fc5a9ae0.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n INSERT INTO ai_usage (\n id, feature, user_id, entity, model,\n input_tokens, output_tokens, audio_seconds,\n price_per_million_in, price_per_million_out, price_per_audio_minute, total\n )\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)\n ",
+ "query": "\n INSERT INTO ai_usage (\n id, feature, user_id, entity, model,\n input_tokens, output_tokens, audio_seconds,\n price_per_million_in, price_per_million_out, price_per_audio_minute, total,\n count_usage\n )\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)\n ",
"describe": {
"columns": [],
"parameters": {
@@ -16,10 +16,11 @@
"Float4",
"Float4",
"Float4",
- "Float4"
+ "Float4",
+ "Bool"
]
},
"nullable": []
},
- "hash": "c552084079684d8689a7330053ba60061cd45ce5071f59c394858f3fb2c8ea09"
+ "hash": "2263d555eaf02a3751ad11b4e8dad617b604ff14f25a9f68f996f478fc5a9ae0"
}
diff --git a/.sqlx/query-5f9e7585eb577e5078ec97258f650dc5014688de2f1e1f7cc666895aee59cfa0.json b/.sqlx/query-5f9e7585eb577e5078ec97258f650dc5014688de2f1e1f7cc666895aee59cfa0.json
new file mode 100644
index 0000000000..89ab941a64
--- /dev/null
+++ b/.sqlx/query-5f9e7585eb577e5078ec97258f650dc5014688de2f1e1f7cc666895aee59cfa0.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "INSERT INTO ai_usage (id, feature, user_id, model, input_tokens, output_tokens)\n VALUES ($1, 'chat', $2, 'legacy-model', 1000000, 1000000)",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "5f9e7585eb577e5078ec97258f650dc5014688de2f1e1f7cc666895aee59cfa0"
+}
diff --git a/.sqlx/query-86b8905de61002d7be77fd8ed1b411dd86157c409cd3c53d22794407d5bf7e76.json b/.sqlx/query-86b8905de61002d7be77fd8ed1b411dd86157c409cd3c53d22794407d5bf7e76.json
new file mode 100644
index 0000000000..7c40a440bf
--- /dev/null
+++ b/.sqlx/query-86b8905de61002d7be77fd8ed1b411dd86157c409cd3c53d22794407d5bf7e76.json
@@ -0,0 +1,17 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "INSERT INTO ai_usage (id, feature, user_id, model, input_tokens, output_tokens,\n total, created_at, count_usage)\n VALUES ($1, 'chat', $2, 'test-model', 0, 0, 1.0, $3, $4)",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Timestamptz",
+ "Bool"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "86b8905de61002d7be77fd8ed1b411dd86157c409cd3c53d22794407d5bf7e76"
+}
diff --git a/.sqlx/query-d6a5674577c2af2e7d97a655029ffeb635dacfd02e08cb5f018c65913ff994b3.json b/.sqlx/query-d6a5674577c2af2e7d97a655029ffeb635dacfd02e08cb5f018c65913ff994b3.json
new file mode 100644
index 0000000000..34c4dd6d25
--- /dev/null
+++ b/.sqlx/query-d6a5674577c2af2e7d97a655029ffeb635dacfd02e08cb5f018c65913ff994b3.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "INSERT INTO ai_usage (id, feature, user_id, model, input_tokens, output_tokens)\n VALUES ($1, 'chat', $2, $3, 1000000, 0)",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "d6a5674577c2af2e7d97a655029ffeb635dacfd02e08cb5f018c65913ff994b3"
+}
diff --git a/Cargo.lock b/Cargo.lock
index c8cd901ed6..ec3399a480 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -329,6 +329,7 @@ dependencies = [
"agent_runtime_protocol",
"agent_session",
"agent_trigger",
+ "ai_billing",
"ai_usage",
"anyhow",
"async-trait",
@@ -399,6 +400,7 @@ dependencies = [
"agent_runtime_protocol",
"agent_session",
"agent_trigger",
+ "ai_billing",
"ai_tools",
"ai_toolset",
"ai_usage",
@@ -453,6 +455,7 @@ dependencies = [
"rdkafka",
"redis",
"rmcp",
+ "roles_and_permissions",
"rootcause",
"secretsmanager_client",
"serde",
@@ -460,6 +463,7 @@ dependencies = [
"sqlx",
"static_file",
"static_file_service_client",
+ "teams",
"tokio",
"tokio-retry",
"tokio-util",
@@ -481,6 +485,7 @@ dependencies = [
"agent_fold",
"agent_runtime_protocol",
"agent_session",
+ "ai_billing",
"ai_tools",
"ai_toolset",
"ai_usage",
@@ -589,6 +594,7 @@ dependencies = [
"agent-client-protocol",
"agent_fold",
"agent_runtime_protocol",
+ "ai_billing",
"ai_toolset",
"ai_usage",
"anyhow",
@@ -648,6 +654,7 @@ version = "0.1.0"
dependencies = [
"agent",
"agent_session",
+ "ai_billing",
"ai_usage",
"anyhow",
"async-trait",
@@ -689,6 +696,7 @@ version = "0.1.0"
dependencies = [
"agent_session",
"agent_trigger",
+ "ai_billing",
"ai_usage",
"anyhow",
"bots",
@@ -705,15 +713,18 @@ dependencies = [
"lexical_client",
"macro_config",
"macro_entrypoint",
+ "macro_env",
"macro_env_var",
"macro_event_broker",
"macro_service_urls",
"messages",
"rdkafka",
+ "roles_and_permissions",
"rootcause",
"serde_json",
"sqlx",
"static_file",
+ "teams",
"tokio",
"tracing",
"workspace-hack",
@@ -842,6 +853,7 @@ version = "0.1.0"
dependencies = [
"activity",
"agent",
+ "ai_billing",
"ai_toolset",
"ai_usage",
"anthropic",
@@ -973,6 +985,7 @@ dependencies = [
"chrono",
"macro_authorization",
"macro_db_migrator",
+ "macro_env_var",
"macro_user_id",
"macro_uuid",
"rootcause",
@@ -1106,6 +1119,7 @@ dependencies = [
name = "anthropic"
version = "0.2.0"
dependencies = [
+ "ai_billing",
"ai_toolset",
"ai_usage",
"anyhow",
@@ -1116,6 +1130,7 @@ dependencies = [
"futures",
"lazy_static",
"macro_env_var",
+ "macro_user_id",
"rand 0.9.4",
"regex",
"reqwest 0.13.4",
@@ -1808,6 +1823,7 @@ version = "0.1.0"
dependencies = [
"aes-gcm 0.10.3",
"ai_billing",
+ "ai_usage",
"analytics_client",
"anyhow",
"async-stripe",
@@ -3709,6 +3725,7 @@ name = "channel_bots"
version = "0.1.0"
dependencies = [
"agent",
+ "ai_billing",
"ai_tools",
"ai_toolset",
"ai_usage",
@@ -5878,6 +5895,7 @@ dependencies = [
"activity",
"agent_changes",
"agent_session",
+ "ai_billing",
"ai_tools",
"ai_usage",
"analytics_client",
@@ -5991,6 +6009,7 @@ dependencies = [
"regex",
"reminders",
"reqwest 0.13.4",
+ "roles_and_permissions",
"rootcause",
"s3_key",
"saved_views",
@@ -6010,6 +6029,7 @@ dependencies = [
"sync_service_hex",
"system_properties",
"task_dedup",
+ "teams",
"thiserror 2.0.18",
"tokio",
"tokio-util",
@@ -6119,6 +6139,7 @@ name = "documents"
version = "0.1.0"
dependencies = [
"activity",
+ "ai_billing",
"ai_toolset",
"ai_usage",
"anyhow",
@@ -9507,6 +9528,7 @@ name = "import"
version = "0.1.0"
dependencies = [
"agent",
+ "ai_billing",
"ai_toolset",
"ai_usage",
"anyhow",
@@ -11375,6 +11397,7 @@ dependencies = [
name = "mcp_service"
version = "0.1.0"
dependencies = [
+ "ai_billing",
"ai_tools",
"ai_toolset",
"ai_usage",
@@ -11423,6 +11446,7 @@ dependencies = [
"reminders",
"reqwest 0.13.4",
"rmcp",
+ "roles_and_permissions",
"search_service_client",
"secretsmanager_client",
"serde_json",
@@ -11430,6 +11454,7 @@ dependencies = [
"sqlx",
"sqs_client",
"sync_service_client",
+ "teams",
"tokio",
"tokio-util",
"tracing",
@@ -15837,6 +15862,7 @@ dependencies = [
"agent",
"agent_runtime_protocol",
"agent_session",
+ "ai_billing",
"ai_tools",
"ai_toolset",
"ai_usage",
@@ -15887,12 +15913,14 @@ dependencies = [
"notification",
"rdkafka",
"reqwest 0.13.4",
+ "roles_and_permissions",
"rootcause",
"secretsmanager_client",
"serde",
"serde_json",
"share_permission_db_utils",
"sqlx",
+ "teams",
"thiserror 2.0.18",
"tokio",
"tokio-util",
diff --git a/apps/web/src/features/email-compose/primitives/email-composer.test.ts b/apps/web/src/features/email-compose/primitives/email-composer.test.ts
index 5928d7843b..2e190a82d4 100644
--- a/apps/web/src/features/email-compose/primitives/email-composer.test.ts
+++ b/apps/web/src/features/email-compose/primitives/email-composer.test.ts
@@ -4,7 +4,8 @@ import { decodeBase64Utf8 } from '../core/decode-base64';
import { createComposeContext } from '../tests/capabilities';
import { mountEmailComposer } from '../tests/composer';
-beforeEach(() => vi.useFakeTimers());
+// Keep the scheduling fixtures in the future regardless of the wall clock.
+beforeEach(() => vi.useFakeTimers({ now: new Date('2026-09-01T12:00:00Z') }));
afterEach(() => vi.useRealTimers());
function hoursFromNow(hours: number): Date {
diff --git a/apps/web/src/features/email-compose/primitives/send-schedule.test.ts b/apps/web/src/features/email-compose/primitives/send-schedule.test.ts
index 939109d073..e26758cdc0 100644
--- a/apps/web/src/features/email-compose/primitives/send-schedule.test.ts
+++ b/apps/web/src/features/email-compose/primitives/send-schedule.test.ts
@@ -879,7 +879,8 @@ describe('send and schedule ordering', () => {
state.dispose();
}
});
- beforeEach(() => vi.useFakeTimers());
+ // Keep the scheduling fixtures in the future regardless of the wall clock.
+ beforeEach(() => vi.useFakeTimers({ now: new Date('2026-09-01T12:00:00Z') }));
afterEach(() => vi.useRealTimers());
it('serializes the last reply edit on disposal and reuses the ID from its first save', async () => {
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/client.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/client.ts
index 7627a3a4ae..86609da6c2 100644
--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/client.ts
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/client.ts
@@ -12,6 +12,7 @@ import type {
AgentSessionLogResponse,
AgentSessionQueueResponse,
AgentSessionResponse,
+ AiAdmissionErrorBody,
CompleteRequest,
ControlRequest,
ControlResponse,
@@ -479,6 +480,11 @@ export type createAgentSessionResponse401 = {
status: 401;
};
+export type createAgentSessionResponse402 = {
+ data: AiAdmissionErrorBody;
+ status: 402;
+};
+
export type createAgentSessionResponse403 = {
data: string;
status: 403;
@@ -499,16 +505,23 @@ export type createAgentSessionResponse500 = {
status: 500;
};
+export type createAgentSessionResponse503 = {
+ data: AiAdmissionErrorBody;
+ status: 503;
+};
+
export type createAgentSessionResponseSuccess =
createAgentSessionResponse201 & {
headers: Headers;
};
export type createAgentSessionResponseError = (
| createAgentSessionResponse401
+ | createAgentSessionResponse402
| createAgentSessionResponse403
| createAgentSessionResponse404
| createAgentSessionResponse422
| createAgentSessionResponse500
+ | createAgentSessionResponse503
) & {
headers: Headers;
};
@@ -1021,6 +1034,11 @@ export type controlAgentSessionResponse401 = {
status: 401;
};
+export type controlAgentSessionResponse402 = {
+ data: AiAdmissionErrorBody;
+ status: 402;
+};
+
export type controlAgentSessionResponse403 = {
data: string;
status: 403;
@@ -1036,15 +1054,28 @@ export type controlAgentSessionResponse500 = {
status: 500;
};
+export type controlAgentSessionResponse503ApplicationJson = {
+ data: AiAdmissionErrorBody;
+ status: 503;
+};
+
+export type controlAgentSessionResponse503TextPlain = {
+ data: string;
+ status: 503;
+};
+
export type controlAgentSessionResponseSuccess =
controlAgentSessionResponse200 & {
headers: Headers;
};
export type controlAgentSessionResponseError = (
| controlAgentSessionResponse401
+ | controlAgentSessionResponse402
| controlAgentSessionResponse403
| controlAgentSessionResponse422
| controlAgentSessionResponse500
+ | controlAgentSessionResponse503ApplicationJson
+ | controlAgentSessionResponse503TextPlain
) & {
headers: Headers;
};
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/aiAdmissionErrorBody.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/aiAdmissionErrorBody.ts
new file mode 100644
index 0000000000..8a5375e066
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/aiAdmissionErrorBody.ts
@@ -0,0 +1,17 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Public admission error payload. Handlers with additional fields can reuse the
+domain error's code and message and [`admission_status`].
+ */
+export interface AiAdmissionErrorBody {
+ /** Stable denial or unavailability code. */
+ code: string;
+ /** Human-readable explanation, without internal billing diagnostics. */
+ error: string;
+}
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/index.ts
index c4cec09642..806cdca63d 100644
--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/index.ts
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/index.ts
@@ -84,6 +84,7 @@ export * from './agentSessionResponseThreadId';
export * from './agentSessionResponseThreadParent';
export * from './agentSetConfigOptionAction';
export * from './agentSetModelAction';
+export * from './aiAdmissionErrorBody';
export * from './botId';
export * from './capabilityHarnessDto';
export * from './captureAttemptDto';
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/openapi.json b/apps/web/src/lib/service-clients/service-agent-harness/openapi.json
index 2d529594a7..b23e9212d1 100644
--- a/apps/web/src/lib/service-clients/service-agent-harness/openapi.json
+++ b/apps/web/src/lib/service-clients/service-agent-harness/openapi.json
@@ -314,6 +314,16 @@
}
}
},
+ "402": {
+ "description": "AI allowance exhausted",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/AiAdmissionErrorBody"
+ }
+ }
+ }
+ },
"403": {
"description": "",
"content": {
@@ -353,6 +363,16 @@
}
}
}
+ },
+ "503": {
+ "description": "AI usage validation unavailable; retry later",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/AiAdmissionErrorBody"
+ }
+ }
+ }
}
}
}
@@ -836,6 +856,16 @@
}
}
},
+ "402": {
+ "description": "AI allowance exhausted",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/AiAdmissionErrorBody"
+ }
+ }
+ }
+ },
"403": {
"description": "",
"content": {
@@ -865,6 +895,21 @@
}
}
}
+ },
+ "503": {
+ "description": "AI usage validation unavailable, or replica draining; retry later",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/AiAdmissionErrorBody"
+ }
+ },
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
}
}
}
@@ -2308,6 +2353,21 @@
}
}
},
+ "AiAdmissionErrorBody": {
+ "type": "object",
+ "description": "Public admission error payload. Handlers with additional fields can reuse the\ndomain error's code and message and [`admission_status`].",
+ "required": ["error", "code"],
+ "properties": {
+ "code": {
+ "type": "string",
+ "description": "Stable denial or unavailability code."
+ },
+ "error": {
+ "type": "string",
+ "description": "Human-readable explanation, without internal billing diagnostics."
+ }
+ }
+ },
"BotId": {
"type": "string"
},
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/client.ts b/apps/web/src/lib/service-clients/service-cognition/generated/client.ts
index 4d56788f3c..489d52ce25 100644
--- a/apps/web/src/lib/service-clients/service-cognition/generated/client.ts
+++ b/apps/web/src/lib/service-clients/service-cognition/generated/client.ts
@@ -6,6 +6,7 @@
*/
import type {
AddServerRequest,
+ AiAdmissionErrorBody,
BrowsePipedreamMcpCatalogParams,
CallToolRequest,
CallToolResponse,
@@ -1336,18 +1337,30 @@ export type retryGatherHandlerResponse400 = {
status: 400;
};
+export type retryGatherHandlerResponse402 = {
+ data: AiAdmissionErrorBody;
+ status: 402;
+};
+
export type retryGatherHandlerResponse500 = {
data: void;
status: 500;
};
+export type retryGatherHandlerResponse503 = {
+ data: AiAdmissionErrorBody;
+ status: 503;
+};
+
export type retryGatherHandlerResponseSuccess =
retryGatherHandlerResponse204 & {
headers: Headers;
};
export type retryGatherHandlerResponseError = (
| retryGatherHandlerResponse400
+ | retryGatherHandlerResponse402
| retryGatherHandlerResponse500
+ | retryGatherHandlerResponse503
) & {
headers: Headers;
};
@@ -2437,6 +2450,11 @@ export type sendChatMessageResponse403 = {
status: 403;
};
+export type sendChatMessageResponse503 = {
+ data: ChatMessageError;
+ status: 503;
+};
+
export type sendChatMessageResponseSuccess = sendChatMessageResponse200 & {
headers: Headers;
};
@@ -2445,6 +2463,7 @@ export type sendChatMessageResponseError = (
| sendChatMessageResponse401
| sendChatMessageResponse402
| sendChatMessageResponse403
+ | sendChatMessageResponse503
) & {
headers: Headers;
};
@@ -2546,7 +2565,7 @@ export type structuredCompletionResponse401 = {
};
export type structuredCompletionResponse402 = {
- data: void;
+ data: StructuredCompletionError;
status: 402;
};
@@ -2555,6 +2574,11 @@ export type structuredCompletionResponse500 = {
status: 500;
};
+export type structuredCompletionResponse503 = {
+ data: StructuredCompletionError;
+ status: 503;
+};
+
export type structuredCompletionResponseSuccess =
structuredCompletionResponse200 & {
headers: Headers;
@@ -2564,6 +2588,7 @@ export type structuredCompletionResponseError = (
| structuredCompletionResponse401
| structuredCompletionResponse402
| structuredCompletionResponse500
+ | structuredCompletionResponse503
) & {
headers: Headers;
};
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/aiAdmissionErrorBody.ts b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/aiAdmissionErrorBody.ts
new file mode 100644
index 0000000000..0b3f7709bb
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/aiAdmissionErrorBody.ts
@@ -0,0 +1,17 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * Document Cognition Service
+ * OpenAPI spec version: 1.0.0
+ */
+
+/**
+ * Public admission error payload. Handlers with additional fields can reuse the
+domain error's code and message and [`admission_status`].
+ */
+export interface AiAdmissionErrorBody {
+ /** Stable denial or unavailability code. */
+ code: string;
+ /** Human-readable explanation, without internal billing diagnostics. */
+ error: string;
+}
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/chatMessageError.ts b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/chatMessageError.ts
index 3644ad825b..8ef2febba8 100644
--- a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/chatMessageError.ts
+++ b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/chatMessageError.ts
@@ -11,7 +11,7 @@ import type { ChatMessageErrorStreamId } from './chatMessageErrorStreamId';
* Error response for chat message endpoints
*/
export interface ChatMessageError {
- /** Stable machine-readable code for payment-required errors. */
+ /** Stable machine-readable code for admission errors (402 or 503). */
code?: ChatMessageErrorCode;
error: string;
stream_id?: ChatMessageErrorStreamId;
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/chatMessageErrorCode.ts b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/chatMessageErrorCode.ts
index 6ff0bdc3ed..85e9f1fe4d 100644
--- a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/chatMessageErrorCode.ts
+++ b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/chatMessageErrorCode.ts
@@ -6,6 +6,6 @@
*/
/**
- * Stable machine-readable code for payment-required errors.
+ * Stable machine-readable code for admission errors (402 or 503).
*/
export type ChatMessageErrorCode = string | null;
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/index.ts
index bce9b62295..eaae779e77 100644
--- a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/index.ts
+++ b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/index.ts
@@ -7,6 +7,7 @@
export * from './accessLevel';
export * from './addServerRequest';
+export * from './aiAdmissionErrorBody';
export * from './aiFeature';
export * from './assistantMessagePart';
export * from './assistantMessagePartOneOf';
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/structuredCompletionError.ts b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/structuredCompletionError.ts
index e6fe795433..c903a7d0f3 100644
--- a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/structuredCompletionError.ts
+++ b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/structuredCompletionError.ts
@@ -7,7 +7,7 @@
import type { StructuredCompletionErrorCode } from './structuredCompletionErrorCode';
export interface StructuredCompletionError {
- /** Stable machine-readable code for payment-required errors. */
+ /** Stable machine-readable code for admission errors (402 or 503). */
code?: StructuredCompletionErrorCode;
error: string;
}
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/structuredCompletionErrorCode.ts b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/structuredCompletionErrorCode.ts
index e27f8bc8bc..47f0f1d926 100644
--- a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/structuredCompletionErrorCode.ts
+++ b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/structuredCompletionErrorCode.ts
@@ -6,6 +6,6 @@
*/
/**
- * Stable machine-readable code for payment-required errors.
+ * Stable machine-readable code for admission errors (402 or 503).
*/
export type StructuredCompletionErrorCode = string | null;
diff --git a/apps/web/src/lib/service-clients/service-cognition/openapi.json b/apps/web/src/lib/service-clients/service-cognition/openapi.json
index 0253b8d90c..a97e82efa5 100644
--- a/apps/web/src/lib/service-clients/service-cognition/openapi.json
+++ b/apps/web/src/lib/service-clients/service-cognition/openapi.json
@@ -1149,8 +1149,28 @@
"400": {
"description": "Unknown import source"
},
+ "402": {
+ "description": "AI allowance exhausted",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/AiAdmissionErrorBody"
+ }
+ }
+ }
+ },
"500": {
"description": "Internal server error"
+ },
+ "503": {
+ "description": "AI usage validation unavailable; retry later",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/AiAdmissionErrorBody"
+ }
+ }
+ }
}
}
}
@@ -2030,6 +2050,16 @@
}
}
}
+ },
+ "503": {
+ "description": "AI usage validation unavailable — retry later",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ChatMessageError"
+ }
+ }
+ }
}
}
}
@@ -2113,7 +2143,14 @@
"description": "Unauthorized"
},
"402": {
- "description": "Payment required"
+ "description": "Payment required",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/StructuredCompletionError"
+ }
+ }
+ }
},
"500": {
"description": "Internal error",
@@ -2124,6 +2161,16 @@
}
}
}
+ },
+ "503": {
+ "description": "AI usage validation unavailable — retry later",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/StructuredCompletionError"
+ }
+ }
+ }
}
}
}
@@ -2151,6 +2198,21 @@
}
}
},
+ "AiAdmissionErrorBody": {
+ "type": "object",
+ "description": "Public admission error payload. Handlers with additional fields can reuse the\ndomain error's code and message and [`admission_status`].",
+ "required": ["error", "code"],
+ "properties": {
+ "code": {
+ "type": "string",
+ "description": "Stable denial or unavailability code."
+ },
+ "error": {
+ "type": "string",
+ "description": "Human-readable explanation, without internal billing diagnostics."
+ }
+ }
+ },
"AiFeature": {
"type": "string",
"description": "Everything we use AI for. The wire / DB form of each variant is its\n`snake_case` name.",
@@ -2579,7 +2641,7 @@
"properties": {
"code": {
"type": ["string", "null"],
- "description": "Stable machine-readable code for payment-required errors."
+ "description": "Stable machine-readable code for admission errors (402 or 503)."
},
"error": {
"type": "string"
@@ -4598,7 +4660,7 @@
"properties": {
"code": {
"type": ["string", "null"],
- "description": "Stable machine-readable code for payment-required errors."
+ "description": "Stable machine-readable code for admission errors (402 or 503)."
},
"error": {
"type": "string"
diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/generated/client.ts b/apps/web/src/lib/service-clients/service-scheduled-action/generated/client.ts
index 049508ba81..d9feec36d5 100644
--- a/apps/web/src/lib/service-clients/service-scheduled-action/generated/client.ts
+++ b/apps/web/src/lib/service-clients/service-scheduled-action/generated/client.ts
@@ -7,6 +7,7 @@
*/
import type {
ActionExecutionRecord,
+ AiAdmissionErrorBody,
CreateScheduledAction,
EmptyResponse,
InProgressExecution,
@@ -425,6 +426,11 @@ export type executeScheduledActionNowResponse401 = {
status: 401;
};
+export type executeScheduledActionNowResponse402 = {
+ data: AiAdmissionErrorBody;
+ status: 402;
+};
+
export type executeScheduledActionNowResponse404 = {
data: string;
status: 404;
@@ -440,6 +446,11 @@ export type executeScheduledActionNowResponse500 = {
status: 500;
};
+export type executeScheduledActionNowResponse503 = {
+ data: AiAdmissionErrorBody;
+ status: 503;
+};
+
export type executeScheduledActionNowResponseSuccess =
executeScheduledActionNowResponse200 & {
headers: Headers;
@@ -447,9 +458,11 @@ export type executeScheduledActionNowResponseSuccess =
export type executeScheduledActionNowResponseError = (
| executeScheduledActionNowResponse400
| executeScheduledActionNowResponse401
+ | executeScheduledActionNowResponse402
| executeScheduledActionNowResponse404
| executeScheduledActionNowResponse409
| executeScheduledActionNowResponse500
+ | executeScheduledActionNowResponse503
) & {
headers: Headers;
};
diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/aiAdmissionErrorBody.ts b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/aiAdmissionErrorBody.ts
new file mode 100644
index 0000000000..4ddbd58e07
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/aiAdmissionErrorBody.ts
@@ -0,0 +1,18 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * scheduled_action
+ * API for managing scheduled actions
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Public admission error payload. Handlers with additional fields can reuse the
+domain error's code and message and [`admission_status`].
+ */
+export interface AiAdmissionErrorBody {
+ /** Stable denial or unavailability code. */
+ code: string;
+ /** Human-readable explanation, without internal billing diagnostics. */
+ error: string;
+}
diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/index.ts
index 1d23ae7230..473ae0fa8b 100644
--- a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/index.ts
+++ b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/index.ts
@@ -25,6 +25,7 @@ export * from './agentTask';
export * from './agentTaskAgent';
export * from './agentTaskAgentProperty';
export * from './agentTaskModel';
+export * from './aiAdmissionErrorBody';
export * from './createScheduledAction';
export * from './emptyResponse';
export * from './eventFilter';
diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/openapi.json b/apps/web/src/lib/service-clients/service-scheduled-action/openapi.json
index cdc331a606..00b6c827e0 100644
--- a/apps/web/src/lib/service-clients/service-scheduled-action/openapi.json
+++ b/apps/web/src/lib/service-clients/service-scheduled-action/openapi.json
@@ -431,6 +431,16 @@
}
}
},
+ "402": {
+ "description": "AI allowance exhausted",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/AiAdmissionErrorBody"
+ }
+ }
+ }
+ },
"404": {
"description": "",
"content": {
@@ -460,6 +470,16 @@
}
}
}
+ },
+ "503": {
+ "description": "AI usage validation unavailable; retry later",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/AiAdmissionErrorBody"
+ }
+ }
+ }
}
}
}
@@ -703,6 +723,21 @@
}
}
},
+ "AiAdmissionErrorBody": {
+ "type": "object",
+ "description": "Public admission error payload. Handlers with additional fields can reuse the\ndomain error's code and message and [`admission_status`].",
+ "required": ["error", "code"],
+ "properties": {
+ "code": {
+ "type": "string",
+ "description": "Stable denial or unavailability code."
+ },
+ "error": {
+ "type": "string",
+ "description": "Human-readable explanation, without internal billing diagnostics."
+ }
+ }
+ },
"CreateScheduledAction": {
"oneOf": [
{
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEvent.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEvent.ts
index 2840469b7f..1b875bf711 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEvent.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEvent.ts
@@ -14,6 +14,7 @@ import type { AgentSessionLifecycleEventOneOfOneseven } from './agentSessionLife
import type { AgentSessionLifecycleEventOneOfOnethree } from './agentSessionLifecycleEventOneOfOnethree';
import type { AgentSessionLifecycleEventOneOfSeven } from './agentSessionLifecycleEventOneOfSeven';
import type { AgentSessionLifecycleEventOneOfThree } from './agentSessionLifecycleEventOneOfThree';
+import type { AgentSessionLifecycleEventOneOfTwoone } from './agentSessionLifecycleEventOneOfTwoone';
/**
* Events publishable to [`MacroAgentSessionLifecycleTopic`].
@@ -33,4 +34,5 @@ export type AgentSessionLifecycleEvent =
| AgentSessionLifecycleEventOneOfOnethree
| AgentSessionLifecycleEventOneOfOnefive
| AgentSessionLifecycleEventOneOfOneseven
- | AgentSessionLifecycleEventOneOfOnenine;
+ | AgentSessionLifecycleEventOneOfOnenine
+ | AgentSessionLifecycleEventOneOfTwoone;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfNine.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfNine.ts
index d24797cb3d..249a56be32 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfNine.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfNine.ts
@@ -5,13 +5,13 @@
* OpenAPI spec version: 0.1.0
*/
import type { AgentSessionLifecycleEventOneOfNineEventType } from './agentSessionLifecycleEventOneOfNineEventType';
-import type { WaitingForInputMetadata } from './waitingForInputMetadata';
+import type { SessionSettledMetadata } from './sessionSettledMetadata';
/**
- * The agent is blocked on a question to its owner.
+ * A turn ended with nothing queued behind it.
*/
export type AgentSessionLifecycleEventOneOfNine = {
event_type: AgentSessionLifecycleEventOneOfNineEventType;
- /** The agent is blocked on a question to its owner. */
- metadata: WaitingForInputMetadata;
+ /** A turn ended with nothing queued behind it. */
+ metadata: SessionSettledMetadata;
};
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfNineEventType.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfNineEventType.ts
index 16e5d4f4be..047f6014eb 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfNineEventType.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfNineEventType.ts
@@ -10,5 +10,5 @@ export type AgentSessionLifecycleEventOneOfNineEventType =
// eslint-disable-next-line @typescript-eslint/no-redeclare
export const AgentSessionLifecycleEventOneOfNineEventType = {
- agent_sessionwaiting_for_input: 'agent_session.waiting_for_input',
+ agent_sessionsettled: 'agent_session.settled',
} as const;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfOnefive.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfOnefive.ts
index 6fa33629f4..6607f4f9cf 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfOnefive.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfOnefive.ts
@@ -5,13 +5,13 @@
* OpenAPI spec version: 0.1.0
*/
import type { AgentSessionLifecycleEventOneOfOnefiveEventType } from './agentSessionLifecycleEventOneOfOnefiveEventType';
-import type { SessionStoppedMetadata } from './sessionStoppedMetadata';
+import type { SessionMentionedMetadata } from './sessionMentionedMetadata';
/**
- * The session's live actor is gone.
+ * A prompt named other users who can open the session.
*/
export type AgentSessionLifecycleEventOneOfOnefive = {
event_type: AgentSessionLifecycleEventOneOfOnefiveEventType;
- /** The session's live actor is gone. */
- metadata: SessionStoppedMetadata;
+ /** A prompt named other users who can open the session. */
+ metadata: SessionMentionedMetadata;
};
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfOnefiveEventType.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfOnefiveEventType.ts
index 5f3420e5c5..3cc4960b1f 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfOnefiveEventType.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfOnefiveEventType.ts
@@ -10,5 +10,5 @@ export type AgentSessionLifecycleEventOneOfOnefiveEventType =
// eslint-disable-next-line @typescript-eslint/no-redeclare
export const AgentSessionLifecycleEventOneOfOnefiveEventType = {
- agent_sessionstopped: 'agent_session.stopped',
+ agent_sessionmentioned: 'agent_session.mentioned',
} as const;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfOnenine.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfOnenine.ts
index c42e3b39c9..9b73a9d2a9 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfOnenine.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfOnenine.ts
@@ -5,13 +5,13 @@
* OpenAPI spec version: 0.1.0
*/
import type { AgentSessionLifecycleEventOneOfOnenineEventType } from './agentSessionLifecycleEventOneOfOnenineEventType';
-import type { SessionDeletedMetadata } from './sessionDeletedMetadata';
+import type { SessionRenamedMetadata } from './sessionRenamedMetadata';
/**
- * The session was deleted.
+ * The session was renamed.
*/
export type AgentSessionLifecycleEventOneOfOnenine = {
event_type: AgentSessionLifecycleEventOneOfOnenineEventType;
- /** The session was deleted. */
- metadata: SessionDeletedMetadata;
+ /** The session was renamed. */
+ metadata: SessionRenamedMetadata;
};
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfOnenineEventType.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfOnenineEventType.ts
index 1c1b18fb78..ebd217726c 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfOnenineEventType.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfOnenineEventType.ts
@@ -10,5 +10,5 @@ export type AgentSessionLifecycleEventOneOfOnenineEventType =
// eslint-disable-next-line @typescript-eslint/no-redeclare
export const AgentSessionLifecycleEventOneOfOnenineEventType = {
- agent_sessiondeleted: 'agent_session.deleted',
+ agent_sessionrenamed: 'agent_session.renamed',
} as const;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfOneone.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfOneone.ts
index 979bddbffe..a2691c0260 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfOneone.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfOneone.ts
@@ -5,13 +5,13 @@
* OpenAPI spec version: 0.1.0
*/
import type { AgentSessionLifecycleEventOneOfOneoneEventType } from './agentSessionLifecycleEventOneOfOneoneEventType';
-import type { InputReceivedMetadata } from './inputReceivedMetadata';
+import type { WaitingForInputMetadata } from './waitingForInputMetadata';
/**
- * The question was answered or withdrawn.
+ * The agent is blocked on a question to its owner.
*/
export type AgentSessionLifecycleEventOneOfOneone = {
event_type: AgentSessionLifecycleEventOneOfOneoneEventType;
- /** The question was answered or withdrawn. */
- metadata: InputReceivedMetadata;
+ /** The agent is blocked on a question to its owner. */
+ metadata: WaitingForInputMetadata;
};
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfOneoneEventType.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfOneoneEventType.ts
index bc1053855e..9711aea383 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfOneoneEventType.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfOneoneEventType.ts
@@ -10,5 +10,5 @@ export type AgentSessionLifecycleEventOneOfOneoneEventType =
// eslint-disable-next-line @typescript-eslint/no-redeclare
export const AgentSessionLifecycleEventOneOfOneoneEventType = {
- agent_sessioninput_received: 'agent_session.input_received',
+ agent_sessionwaiting_for_input: 'agent_session.waiting_for_input',
} as const;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfOneseven.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfOneseven.ts
index 165408921a..52c21373dc 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfOneseven.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfOneseven.ts
@@ -5,13 +5,13 @@
* OpenAPI spec version: 0.1.0
*/
import type { AgentSessionLifecycleEventOneOfOnesevenEventType } from './agentSessionLifecycleEventOneOfOnesevenEventType';
-import type { SessionRenamedMetadata } from './sessionRenamedMetadata';
+import type { SessionStoppedMetadata } from './sessionStoppedMetadata';
/**
- * The session was renamed.
+ * The session's live actor is gone.
*/
export type AgentSessionLifecycleEventOneOfOneseven = {
event_type: AgentSessionLifecycleEventOneOfOnesevenEventType;
- /** The session was renamed. */
- metadata: SessionRenamedMetadata;
+ /** The session's live actor is gone. */
+ metadata: SessionStoppedMetadata;
};
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfOnesevenEventType.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfOnesevenEventType.ts
index 264de63d86..6f59eb5cfa 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfOnesevenEventType.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfOnesevenEventType.ts
@@ -10,5 +10,5 @@ export type AgentSessionLifecycleEventOneOfOnesevenEventType =
// eslint-disable-next-line @typescript-eslint/no-redeclare
export const AgentSessionLifecycleEventOneOfOnesevenEventType = {
- agent_sessionrenamed: 'agent_session.renamed',
+ agent_sessionstopped: 'agent_session.stopped',
} as const;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfOnethree.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfOnethree.ts
index 041c45cde0..87e38e90bf 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfOnethree.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfOnethree.ts
@@ -5,13 +5,13 @@
* OpenAPI spec version: 0.1.0
*/
import type { AgentSessionLifecycleEventOneOfOnethreeEventType } from './agentSessionLifecycleEventOneOfOnethreeEventType';
-import type { SessionMentionedMetadata } from './sessionMentionedMetadata';
+import type { InputReceivedMetadata } from './inputReceivedMetadata';
/**
- * A prompt named other users who can open the session.
+ * The question was answered or withdrawn.
*/
export type AgentSessionLifecycleEventOneOfOnethree = {
event_type: AgentSessionLifecycleEventOneOfOnethreeEventType;
- /** A prompt named other users who can open the session. */
- metadata: SessionMentionedMetadata;
+ /** The question was answered or withdrawn. */
+ metadata: InputReceivedMetadata;
};
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfOnethreeEventType.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfOnethreeEventType.ts
index bd10ccd8d8..e0730b8092 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfOnethreeEventType.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfOnethreeEventType.ts
@@ -10,5 +10,5 @@ export type AgentSessionLifecycleEventOneOfOnethreeEventType =
// eslint-disable-next-line @typescript-eslint/no-redeclare
export const AgentSessionLifecycleEventOneOfOnethreeEventType = {
- agent_sessionmentioned: 'agent_session.mentioned',
+ agent_sessioninput_received: 'agent_session.input_received',
} as const;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfSeven.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfSeven.ts
index a93318a565..c97e211e5f 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfSeven.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfSeven.ts
@@ -5,13 +5,13 @@
* OpenAPI spec version: 0.1.0
*/
import type { AgentSessionLifecycleEventOneOfSevenEventType } from './agentSessionLifecycleEventOneOfSevenEventType';
-import type { SessionSettledMetadata } from './sessionSettledMetadata';
+import type { CommandRejectedMetadata } from './commandRejectedMetadata';
/**
- * A turn ended with nothing queued behind it.
+ * An accepted command was refused before runtime execution.
*/
export type AgentSessionLifecycleEventOneOfSeven = {
event_type: AgentSessionLifecycleEventOneOfSevenEventType;
- /** A turn ended with nothing queued behind it. */
- metadata: SessionSettledMetadata;
+ /** An accepted command was refused before runtime execution. */
+ metadata: CommandRejectedMetadata;
};
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfSevenEventType.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfSevenEventType.ts
index 310100f8d8..3f7ddae5dd 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfSevenEventType.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfSevenEventType.ts
@@ -10,5 +10,5 @@ export type AgentSessionLifecycleEventOneOfSevenEventType =
// eslint-disable-next-line @typescript-eslint/no-redeclare
export const AgentSessionLifecycleEventOneOfSevenEventType = {
- agent_sessionsettled: 'agent_session.settled',
+ agent_sessioncommand_rejected: 'agent_session.command_rejected',
} as const;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfTwoone.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfTwoone.ts
new file mode 100644
index 0000000000..e3454bc1df
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfTwoone.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 { AgentSessionLifecycleEventOneOfTwooneEventType } from './agentSessionLifecycleEventOneOfTwooneEventType';
+import type { SessionDeletedMetadata } from './sessionDeletedMetadata';
+
+/**
+ * The session was deleted.
+ */
+export type AgentSessionLifecycleEventOneOfTwoone = {
+ event_type: AgentSessionLifecycleEventOneOfTwooneEventType;
+ /** The session was deleted. */
+ metadata: SessionDeletedMetadata;
+};
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfTwooneEventType.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfTwooneEventType.ts
new file mode 100644
index 0000000000..6a167e3d5e
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfTwooneEventType.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 AgentSessionLifecycleEventOneOfTwooneEventType =
+ (typeof AgentSessionLifecycleEventOneOfTwooneEventType)[keyof typeof AgentSessionLifecycleEventOneOfTwooneEventType];
+
+// eslint-disable-next-line @typescript-eslint/no-redeclare
+export const AgentSessionLifecycleEventOneOfTwooneEventType = {
+ agent_sessiondeleted: 'agent_session.deleted',
+} as const;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/commandFailure.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/commandFailure.ts
new file mode 100644
index 0000000000..fb046646fe
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/commandFailure.ts
@@ -0,0 +1,18 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Sanitized public details of a command refused before runtime execution.
+ */
+export interface CommandFailure {
+ /** Stable public denial or unavailability code. */
+ code: string;
+ /** Public explanation, never an internal error report. */
+ message: string;
+ /** Whether retrying later may succeed without a policy change. */
+ retryable: boolean;
+}
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/commandRejectedMetadata.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/commandRejectedMetadata.ts
new file mode 100644
index 0000000000..d8cc134b31
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/commandRejectedMetadata.ts
@@ -0,0 +1,26 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { AgentActionId } from './agentActionId';
+import type { CommandFailure } from './commandFailure';
+import type { CommandRejectedMetadataActor } from './commandRejectedMetadataActor';
+import type { CommandRejectedMetadataAnnouncementMessageId } from './commandRejectedMetadataAnnouncementMessageId';
+import type { SessionIdentity } from './sessionIdentity';
+
+/**
+ * An accepted command was refused before it could start a runtime turn.
+ */
+export interface CommandRejectedMetadata {
+ /** The command that will not execute. */
+ action_id: AgentActionId;
+ actor?: CommandRejectedMetadataActor;
+ /** The command's thread announcement, when one was created. */
+ announcement_message_id?: CommandRejectedMetadataAnnouncementMessageId;
+ /** Safe details for clients and downstream consumers. */
+ failure: CommandFailure;
+ /** The session. */
+ identity: SessionIdentity;
+}
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/commandRejectedMetadataActor.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/commandRejectedMetadataActor.ts
new file mode 100644
index 0000000000..876c8e5123
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/commandRejectedMetadataActor.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 { MacroUserIdStr } from './macroUserIdStr';
+
+export type CommandRejectedMetadataActor = null | MacroUserIdStr;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/commandRejectedMetadataAnnouncementMessageId.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/commandRejectedMetadataAnnouncementMessageId.ts
new file mode 100644
index 0000000000..dd8dfa6927
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/commandRejectedMetadataAnnouncementMessageId.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * The command's thread announcement, when one was created.
+ */
+export type CommandRejectedMetadataAnnouncementMessageId = string | null;
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.ts
index add816443d..ff6af104b1 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
@@ -50,6 +50,8 @@ export * from './agentSessionLifecycleEventOneOfSeven';
export * from './agentSessionLifecycleEventOneOfSevenEventType';
export * from './agentSessionLifecycleEventOneOfThree';
export * from './agentSessionLifecycleEventOneOfThreeEventType';
+export * from './agentSessionLifecycleEventOneOfTwoone';
+export * from './agentSessionLifecycleEventOneOfTwooneEventType';
export * from './anchor';
export * from './anchorId';
export * from './anchorIdOneOf';
@@ -370,6 +372,10 @@ export * from './cloudStorageItemType';
export * from './collabSurfaceResponse';
export * from './collabSurfaceResponseParentEntityType';
export * from './collabSurfaceTokenResponse';
+export * from './commandFailure';
+export * from './commandRejectedMetadata';
+export * from './commandRejectedMetadataActor';
+export * from './commandRejectedMetadataAnnouncementMessageId';
export * from './comment';
export * from './commentCreatedAt';
export * from './commentDeletedAt';
diff --git a/apps/web/src/lib/service-clients/service-storage/openapi.json b/apps/web/src/lib/service-clients/service-storage/openapi.json
index a42d94634c..7e0fbcf447 100644
--- a/apps/web/src/lib/service-clients/service-storage/openapi.json
+++ b/apps/web/src/lib/service-clients/service-storage/openapi.json
@@ -16023,6 +16023,21 @@
}
}
},
+ {
+ "type": "object",
+ "description": "An accepted command was refused before runtime execution.",
+ "required": ["metadata", "event_type"],
+ "properties": {
+ "event_type": {
+ "type": "string",
+ "enum": ["agent_session.command_rejected"]
+ },
+ "metadata": {
+ "$ref": "#/components/schemas/CommandRejectedMetadata",
+ "description": "An accepted command was refused before runtime execution."
+ }
+ }
+ },
{
"type": "object",
"description": "A turn ended with nothing queued behind it.",
@@ -20250,6 +20265,60 @@
}
}
},
+ "CommandFailure": {
+ "type": "object",
+ "description": "Sanitized public details of a command refused before runtime execution.",
+ "required": ["code", "message", "retryable"],
+ "properties": {
+ "code": {
+ "type": "string",
+ "description": "Stable public denial or unavailability code."
+ },
+ "message": {
+ "type": "string",
+ "description": "Public explanation, never an internal error report."
+ },
+ "retryable": {
+ "type": "boolean",
+ "description": "Whether retrying later may succeed without a policy change."
+ }
+ }
+ },
+ "CommandRejectedMetadata": {
+ "type": "object",
+ "description": "An accepted command was refused before it could start a runtime turn.",
+ "required": ["identity", "action_id", "failure"],
+ "properties": {
+ "action_id": {
+ "$ref": "#/components/schemas/AgentActionId",
+ "description": "The command that will not execute."
+ },
+ "actor": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/MacroUserIdStr",
+ "description": "Who submitted the command, if acting on a user's behalf."
+ }
+ ]
+ },
+ "announcement_message_id": {
+ "type": ["string", "null"],
+ "format": "uuid",
+ "description": "The command's thread announcement, when one was created."
+ },
+ "failure": {
+ "$ref": "#/components/schemas/CommandFailure",
+ "description": "Safe details for clients and downstream consumers."
+ },
+ "identity": {
+ "$ref": "#/components/schemas/SessionIdentity",
+ "description": "The session."
+ }
+ }
+ },
"Comment": {
"type": "object",
"required": ["commentId", "threadId", "owner", "text"],
diff --git a/crates/agent_harness/Cargo.toml b/crates/agent_harness/Cargo.toml
index 43db767190..4e6c3dc98b 100644
--- a/crates/agent_harness/Cargo.toml
+++ b/crates/agent_harness/Cargo.toml
@@ -5,6 +5,7 @@ publish = false
version = "0.1.0"
[dependencies]
+ai_billing = { path = "../ai_billing" }
claude_cloud_agents = { path = "../claude_cloud_agents" }
async-trait = { workspace = true }
codex_cloud_agents = { path = "../codex_cloud_agents", features = ["postgres"] }
diff --git a/crates/agent_harness/src/domain/error.rs b/crates/agent_harness/src/domain/error.rs
index ae92da7ca0..0013ca981c 100644
--- a/crates/agent_harness/src/domain/error.rs
+++ b/crates/agent_harness/src/domain/error.rs
@@ -12,6 +12,9 @@ pub type Result<T, E = HarnessError> = std::result::Result<T, E>;
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum HarnessError {
+ /// New Macro-funded work was refused or could not be validated.
+ #[error(transparent)]
+ Admission(#[from] ai_billing::AiAdmissionError),
/// A container could not be spawned or reattached.
#[error("container unavailable: {0}")]
Container(String),
diff --git a/crates/agent_harness/src/domain/mod.rs b/crates/agent_harness/src/domain/mod.rs
index d72a205112..3734e4ffd1 100644
--- a/crates/agent_harness/src/domain/mod.rs
+++ b/crates/agent_harness/src/domain/mod.rs
@@ -25,5 +25,7 @@ pub mod claude;
/// Compatible agent model discovery.
pub mod model_load;
+/// Admitted model-backed repository choice, with deterministic paths kept free.
+pub mod repository_choice;
/// Repository selection and fallback policy for hosted coding sessions.
pub(crate) mod repository_selection;
diff --git a/crates/agent_harness/src/domain/notifications.rs b/crates/agent_harness/src/domain/notifications.rs
index ccfc4f01a5..10fa3ea7bb 100644
--- a/crates/agent_harness/src/domain/notifications.rs
+++ b/crates/agent_harness/src/domain/notifications.rs
@@ -150,6 +150,7 @@ pub fn plan(event: &AgentSessionLifecycleEvent, is_coding: bool) -> Vec<PlannedN
AgentSessionLifecycleEvent::Opened(_)
| AgentSessionLifecycleEvent::TurnStarted(_)
| AgentSessionLifecycleEvent::TurnEnded(_)
+ | AgentSessionLifecycleEvent::CommandRejected(_)
| AgentSessionLifecycleEvent::InputReceived(_)
| AgentSessionLifecycleEvent::Stopped(_)
| AgentSessionLifecycleEvent::Renamed(_)
diff --git a/crates/agent_harness/src/domain/repository_choice.rs b/crates/agent_harness/src/domain/repository_choice.rs
new file mode 100644
index 0000000000..dd7c4a658d
--- /dev/null
+++ b/crates/agent_harness/src/domain/repository_choice.rs
@@ -0,0 +1,212 @@
+//! Repository-choice orchestration. Only ambiguous selection spends Macro AI quota.
+
+use std::{future::Future, num::NonZeroUsize, sync::Arc};
+
+use agent_session::domain::{
+ model::{AgentSession, AgentSessionId},
+ ports::AgentSessionRepo,
+};
+use ai_billing::{AiAdmissionService, AiFeature};
+use cursor_cloud_agents::domain::{
+ model::RepoUrl,
+ ports::{RepositoryChooser, SessionIntent},
+};
+use macro_user_id::user_id::MacroUserIdStr;
+
+use super::{
+ ports::ReachableRepositories,
+ repository_selection::{fallback_repository, intent, recent_repository},
+};
+
+#[cfg(test)]
+mod test;
+
+/// Recent sessions initially considered as evidence for a repository choice.
+pub const RECENT_SESSIONS: usize = 5;
+
+/// Model capability; admission and persistence belong to the calling domain service.
+pub trait RepositoryChoiceModel: Send + Sync + 'static {
+ /// Choose one of the authorized candidates, recording usage for the trusted owner.
+ fn decide(
+ &self,
+ owner: &MacroUserIdStr<'_>,
+ prompt: &str,
+ candidates: &[String],
+ recent: &[AgentSession],
+ fallback: &str,
+ ) -> impl Future<Output = Result<String, rootcause::Report>> + Send;
+}
+
+/// Chooses and persists a repository before a hosted agent is minted.
+pub struct RepositoryChoiceService<Repositories, Sessions, Model> {
+ repositories: Arc<Repositories>,
+ sessions: Sessions,
+ model: Model,
+ admission: Arc<dyn AiAdmissionService>,
+ owner: MacroUserIdStr<'static>,
+ session_id: AgentSessionId,
+}
+
+impl<Repositories, Sessions, Model> RepositoryChoiceService<Repositories, Sessions, Model>
+where
+ Repositories: ReachableRepositories,
+ Sessions: AgentSessionRepo,
+ Model: RepositoryChoiceModel,
+{
+ /// Build a chooser for one session and its verified owner.
+ pub fn new(
+ repositories: Arc<Repositories>,
+ sessions: Sessions,
+ model: Model,
+ admission: Arc<dyn AiAdmissionService>,
+ owner: MacroUserIdStr<'static>,
+ session_id: AgentSessionId,
+ ) -> Self {
+ Self {
+ repositories,
+ sessions,
+ model,
+ admission,
+ owner,
+ session_id,
+ }
+ }
+
+ #[tracing::instrument(
+ name = "agent.repository_choice.reachable_repositories",
+ skip_all,
+ err,
+ fields(agent.session.id = %self.session_id)
+ )]
+ async fn reachable_repositories(&self) -> Result<Vec<String>, rootcause::Report> {
+ Ok(self
+ .repositories
+ .for_user(&self.owner)
+ .await
+ .map_err(|error| rootcause::report!("could not list reachable repositories: {error}"))?
+ .into_iter()
+ .map(|repository| repository.url)
+ .collect())
+ }
+
+ /// Recent sessions through the newest accessible repository, excluding this session.
+ #[tracing::instrument(
+ name = "agent.repository_choice.recent_sessions",
+ skip_all,
+ err,
+ fields(agent.session.id = %self.session_id)
+ )]
+ async fn recent_sessions(
+ &self,
+ candidates: &[String],
+ ) -> Result<Vec<AgentSession>, rootcause::Report> {
+ let mut limit = RECENT_SESSIONS + 1;
+ loop {
+ let recent = self
+ .sessions
+ .recent_for_owner(
+ &self.owner,
+ NonZeroUsize::new(limit).expect("a nonzero count"),
+ )
+ .await
+ .map_err(|error| {
+ rootcause::report!("could not read the owner's recent sessions: {error}")
+ })?;
+ let exhausted = recent.len() < limit;
+ let recent: Vec<_> = recent
+ .into_iter()
+ .filter(|session| session.id != self.session_id)
+ .collect();
+ if exhausted || recent_repository(candidates, &recent).is_some() {
+ return Ok(recent);
+ }
+ limit = limit.checked_mul(2).ok_or_else(|| {
+ rootcause::report!("too many sessions to find a recent repository")
+ })?;
+ }
+ }
+}
+
+impl<Repositories, Sessions, Model> RepositoryChooser
+ for RepositoryChoiceService<Repositories, Sessions, Model>
+where
+ Repositories: ReachableRepositories,
+ Sessions: AgentSessionRepo,
+ Model: RepositoryChoiceModel,
+{
+ #[tracing::instrument(name = "agent.repository_choice", skip_all, err,
+ fields(
+ agent.session.id = %self.session_id,
+ agent.repository_choice.candidate_count = tracing::field::Empty,
+ agent.repository_choice.recent_session_count = tracing::field::Empty,
+ agent.repository_choice.outcome = tracing::field::Empty,
+ ))]
+ async fn choose(
+ &self,
+ prompt: &str,
+ _cwd: &std::path::Path,
+ ) -> Result<SessionIntent, rootcause::Report> {
+ // Caller-selected repositories were authorized by the opening service.
+ let session =
+ self.sessions.get(self.session_id).await.map_err(|error| {
+ rootcause::report!("could not read selected repository: {error}")
+ })?;
+ if session.repo_branch.is_some()
+ && let Some(url) = session.repo_url.as_deref()
+ {
+ let repository = RepoUrl::parse(url)
+ .ok_or_else(|| rootcause::report!("invalid selected repository"))?;
+ return Ok(SessionIntent {
+ repository: Some(repository),
+ open_pull_request: true,
+ });
+ }
+ let mut had_candidates = false;
+ let result = async {
+ let candidates = self.reachable_repositories().await?;
+ had_candidates = !candidates.is_empty();
+ tracing::Span::current()
+ .record("agent.repository_choice.candidate_count", candidates.len());
+ let fallback = fallback_repository(&candidates, &[])?;
+ let chosen = if candidates.len() == 1 {
+ intent(&candidates, fallback)?
+ } else {
+ self.admission
+ .admit(&self.owner, AiFeature::AgentRepositoryChoice)
+ .await
+ .map_err(|error| rootcause::report!(error))?;
+ let recent = self.recent_sessions(&candidates).await?;
+ tracing::Span::current()
+ .record("agent.repository_choice.recent_session_count", recent.len());
+ let fallback = fallback_repository(&candidates, &recent)?;
+ let choice = self
+ .model
+ .decide(&self.owner, prompt, &candidates, &recent, fallback)
+ .await?;
+ intent(&candidates, &choice)?
+ };
+
+ // The egress proxy pins git traffic to this row, before agent creation.
+ self.sessions
+ .set_repo_url(
+ self.session_id,
+ chosen.repository.as_ref().map(ToString::to_string),
+ )
+ .await
+ .map_err(|error| {
+ rootcause::report!("could not record the session's repository: {error}")
+ })?;
+ Ok(chosen)
+ }
+ .await;
+ tracing::Span::current().record(
+ "agent.repository_choice.outcome",
+ match &result {
+ Ok(_) => "selected",
+ Err(_) if !had_candidates => "no_candidates",
+ Err(_) => "failed",
+ },
+ );
+ result
+ }
+}
diff --git a/crates/agent_harness/src/domain/repository_choice/test.rs b/crates/agent_harness/src/domain/repository_choice/test.rs
new file mode 100644
index 0000000000..5207a84c7c
--- /dev/null
+++ b/crates/agent_harness/src/domain/repository_choice/test.rs
@@ -0,0 +1,260 @@
+use super::*;
+use agent_session::domain::ports::MockAgentSessionRepo;
+use ai_billing::{AdmissionFuture, AiAdmissionError, DenyReason};
+use std::sync::{
+ Mutex,
+ atomic::{AtomicUsize, Ordering},
+};
+
+const REPO: &str = "https://github.com/macro-inc/macro";
+const OTHER: &str = "https://github.com/macro-inc/infra";
+
+struct StubRepositories(Vec<String>);
+
+#[async_trait::async_trait]
+impl ReachableRepositories for StubRepositories {
+ async fn for_user(
+ &self,
+ user: &MacroUserIdStr<'_>,
+ ) -> crate::domain::error::Result<Vec<crate::domain::model::ReachableRepository>> {
+ assert_eq!(user, &owner());
+ Ok(self
+ .0
+ .iter()
+ .map(|url| crate::domain::model::ReachableRepository {
+ url: url.clone(),
+ default_branch: Some("main".to_owned()),
+ })
+ .collect())
+ }
+}
+
+struct Admission {
+ result: Result<(), AiAdmissionError>,
+ calls: AtomicUsize,
+}
+
+impl AiAdmissionService for Admission {
+ fn admit<'a>(
+ &'a self,
+ user: &'a MacroUserIdStr<'_>,
+ feature: AiFeature,
+ ) -> AdmissionFuture<'a> {
+ assert_eq!(user, &owner());
+ assert_eq!(feature, AiFeature::AgentRepositoryChoice);
+ self.calls.fetch_add(1, Ordering::SeqCst);
+ Box::pin(async { self.result })
+ }
+}
+
+struct Model {
+ calls: Arc<Mutex<Vec<String>>>,
+ admission: Arc<Admission>,
+}
+
+impl RepositoryChoiceModel for Model {
+ async fn decide(
+ &self,
+ user: &MacroUserIdStr<'_>,
+ prompt: &str,
+ candidates: &[String],
+ _recent: &[AgentSession],
+ fallback: &str,
+ ) -> Result<String, rootcause::Report> {
+ assert_eq!(user, &owner());
+ assert_eq!(prompt, "fix home");
+ assert_eq!(self.admission.calls.load(Ordering::SeqCst), 1);
+ assert!(self.admission.result.is_ok());
+ assert!(candidates.contains(&fallback.to_owned()));
+ self.calls.lock().unwrap().push(prompt.to_owned());
+ Ok(fallback.to_owned())
+ }
+}
+
+fn owner() -> MacroUserIdStr<'static> {
+ MacroUserIdStr::try_from("macro|[email protected]".to_owned()).unwrap()
+}
+
+fn admission(result: Result<(), AiAdmissionError>) -> Arc<Admission> {
+ Arc::new(Admission {
+ result,
+ calls: AtomicUsize::new(0),
+ })
+}
+
+fn sessions() -> MockAgentSessionRepo {
+ let mut sessions = MockAgentSessionRepo::new();
+ sessions.expect_get().returning(|id| {
+ Box::pin(async move { Ok(agent_session::testing::test_agent_session(id)) })
+ });
+ sessions
+}
+
+fn chooser(
+ sessions: MockAgentSessionRepo,
+ candidates: &[&str],
+ admission: Arc<Admission>,
+ calls: Arc<Mutex<Vec<String>>>,
+) -> RepositoryChoiceService<StubRepositories, MockAgentSessionRepo, Model> {
+ RepositoryChoiceService::new(
+ Arc::new(StubRepositories(
+ candidates.iter().map(|s| (*s).to_owned()).collect(),
+ )),
+ sessions,
+ Model {
+ calls,
+ admission: admission.clone(),
+ },
+ admission,
+ owner(),
+ AgentSessionId::new(),
+ )
+}
+
+#[tokio::test]
+async fn deterministic_selection_never_checks_quota_or_calls_a_model() {
+ for candidates in [vec![], vec![REPO]] {
+ let mut sessions = sessions();
+ sessions.expect_recent_for_owner().never();
+ let has_repo = !candidates.is_empty();
+ sessions
+ .expect_set_repo_url()
+ .times(usize::from(has_repo))
+ .withf(|_, url| url.as_deref() == Some(REPO))
+ .returning(|_, _| Box::pin(async { Ok(()) }));
+ let gate = admission(Err(AiAdmissionError::Unavailable));
+ let calls = Arc::new(Mutex::new(Vec::new()));
+ let result = chooser(sessions, &candidates, gate.clone(), calls.clone())
+ .choose("fix home", std::path::Path::new(""))
+ .await;
+ if has_repo {
+ assert_eq!(result.unwrap().repository.unwrap().as_str(), REPO);
+ } else {
+ assert!(result.unwrap_err().to_string().contains("Connect GitHub"));
+ }
+ assert_eq!(gate.calls.load(Ordering::SeqCst), 0);
+ assert!(calls.lock().unwrap().is_empty());
+ }
+}
+
+#[tokio::test]
+async fn explicit_repository_bypasses_automatic_selection() {
+ let mut sessions = MockAgentSessionRepo::new();
+ sessions.expect_get().returning(|id| {
+ Box::pin(async move {
+ let mut session = agent_session::testing::test_agent_session(id);
+ session.repo_url = Some(OTHER.into());
+ session.repo_branch = Some(
+ agent_session::domain::repository_branch::RepositoryBranch::parse(
+ "feature/home".into(),
+ )
+ .unwrap(),
+ );
+ Ok(session)
+ })
+ });
+ sessions.expect_set_repo_url().never();
+ sessions.expect_recent_for_owner().never();
+ let gate = admission(Err(AiAdmissionError::Denied(
+ DenyReason::AllowanceExhausted,
+ )));
+ let calls = Arc::new(Mutex::new(Vec::new()));
+ let result = chooser(sessions, &[], gate.clone(), calls.clone())
+ .choose("fix home", std::path::Path::new(""))
+ .await
+ .unwrap();
+ assert_eq!(result.repository.unwrap().as_str(), OTHER);
+ assert_eq!(gate.calls.load(Ordering::SeqCst), 0);
+ assert!(calls.lock().unwrap().is_empty());
+}
+
+#[tokio::test]
+async fn refusal_preserves_the_typed_error_without_model_or_persistence_calls() {
+ for error in [
+ AiAdmissionError::Denied(DenyReason::AllowanceExhausted),
+ AiAdmissionError::Unavailable,
+ ] {
+ let mut sessions = sessions();
+ sessions.expect_recent_for_owner().never();
+ sessions.expect_set_repo_url().never();
+ let gate = admission(Err(error));
+ let calls = Arc::new(Mutex::new(Vec::new()));
+ let report = chooser(sessions, &[REPO, OTHER], gate.clone(), calls.clone())
+ .choose("fix home", std::path::Path::new(""))
+ .await
+ .unwrap_err();
+ assert_eq!(
+ report.downcast_current_context::<AiAdmissionError>(),
+ Some(&error)
+ );
+ assert_eq!(gate.calls.load(Ordering::SeqCst), 1);
+ assert!(calls.lock().unwrap().is_empty());
+ }
+}
+
+#[tokio::test]
+async fn admitted_selection_calls_model_and_persists_its_choice() {
+ let mut sessions = sessions();
+ sessions
+ .expect_recent_for_owner()
+ .once()
+ .returning(|_, _| Box::pin(async { Ok(vec![]) }));
+ sessions
+ .expect_set_repo_url()
+ .once()
+ .withf(|_, url| url.as_deref() == Some(REPO))
+ .returning(|_, _| Box::pin(async { Ok(()) }));
+ let calls = Arc::new(Mutex::new(Vec::new()));
+ let result = chooser(sessions, &[REPO, OTHER], admission(Ok(())), calls.clone())
+ .choose("fix home", std::path::Path::new(""))
+ .await
+ .unwrap();
+ assert_eq!(result.repository.unwrap().as_str(), REPO);
+ assert_eq!(calls.lock().unwrap().len(), 1);
+}
+
+#[tokio::test]
+async fn history_excludes_current_session_and_searches_past_chat_only_sessions() {
+ let current = AgentSessionId::new();
+ let prior = AgentSessionId::new();
+ let mut sessions = MockAgentSessionRepo::new();
+ sessions
+ .expect_recent_for_owner()
+ .once()
+ .withf(|_, limit| limit.get() == 6)
+ .return_once(move |_, _| {
+ Box::pin(async move {
+ Ok((0..6)
+ .map(|i| {
+ let id = if i == 0 {
+ current
+ } else {
+ AgentSessionId::new()
+ };
+ agent_session::testing::test_agent_session(id)
+ })
+ .collect())
+ })
+ });
+ sessions
+ .expect_recent_for_owner()
+ .once()
+ .withf(|_, limit| limit.get() == 12)
+ .return_once(move |_, _| {
+ Box::pin(async move {
+ let mut session = agent_session::testing::test_agent_session(prior);
+ session.repo_url = Some(OTHER.into());
+ Ok(vec![
+ agent_session::testing::test_agent_session(current),
+ session,
+ ])
+ })
+ });
+ let mut service = chooser(sessions, &[], admission(Ok(())), Arc::default());
+ service.session_id = current;
+ let candidates = vec![REPO.to_owned(), OTHER.to_owned()];
+ let recent = service.recent_sessions(&candidates).await.unwrap();
+ assert_eq!(recent.len(), 1);
+ assert_eq!(recent[0].id, prior);
+ assert_eq!(fallback_repository(&candidates, &recent).unwrap(), OTHER);
+}
diff --git a/crates/agent_harness/src/domain/service.rs b/crates/agent_harness/src/domain/service.rs
index b282b7f9be..3ee75dba14 100644
--- a/crates/agent_harness/src/domain/service.rs
+++ b/crates/agent_harness/src/domain/service.rs
@@ -16,6 +16,7 @@
#[cfg(test)]
mod test;
+mod admission;
mod deliver;
mod lifecycle;
mod lifecycle_events;
@@ -124,6 +125,7 @@ struct AgentHarnessInner<
Notifier,
> {
sessions: Sessions,
+ admission: Arc<dyn ai_billing::AiAdmissionService>,
containers: Containers,
announcer: Announcer,
runtimes: Runtimes,
@@ -318,6 +320,7 @@ where
Self {
inner: Arc::new(AgentHarnessInner {
sessions,
+ admission: Arc::new(ai_billing::DisabledAiAdmissionService),
containers,
announcer,
runtimes,
@@ -340,6 +343,14 @@ where
}
}
+ /// Configure shared admission before cloning the harness or starting workers.
+ pub fn with_admission(mut self, admission: Arc<dyn ai_billing::AiAdmissionService>) -> Self {
+ Arc::get_mut(&mut self.inner)
+ .expect("configure admission before sharing the harness")
+ .admission = admission;
+ self
+ }
+
/// Enable explicit repository choices, authorized against the owner's reachable repositories.
pub fn with_repositories(
mut self,
@@ -498,6 +509,7 @@ where
fn into_session_error(error: HarnessError) -> AgentSessionError {
match error {
HarnessError::Session(error) => error,
+ HarnessError::Admission(error) => AgentSessionError::Admission(error),
HarnessError::Disconnected(session) => AgentSessionError::Disconnected(session),
other => AgentSessionError::Unknown(anyhow::anyhow!(other)),
}
diff --git a/crates/agent_harness/src/domain/service/admission.rs b/crates/agent_harness/src/domain/service/admission.rs
new file mode 100644
index 0000000000..1fad4444a8
--- /dev/null
+++ b/crates/agent_harness/src/domain/service/admission.rs
@@ -0,0 +1,173 @@
+//! Quota admission at ingress and dispatch, and rejection of waiting commands.
+//! Session owners fund managed inference; the actor can be a collaborator.
+
+use super::*;
+use agent_session::domain::events::{AgentSessionLifecycleEvent, CommandRejectedMetadata};
+use ai_billing::AiAdmissionError;
+use ai_usage::AiFeature;
+
+impl<
+ Sessions,
+ Containers,
+ Announcer,
+ Runtimes,
+ PromptContext,
+ PromptComposer,
+ Egress,
+ Lifecycle,
+ Mentions,
+ Notifier,
+>
+ AgentHarnessInner<
+ Sessions,
+ Containers,
+ Announcer,
+ Runtimes,
+ PromptContext,
+ PromptComposer,
+ Egress,
+ Lifecycle,
+ Mentions,
+ Notifier,
+ >
+where
+ Sessions: AgentSessionService,
+ Containers: ContainerManager,
+ Announcer: SessionAnnouncer,
+ Runtimes: RuntimeConnections,
+ PromptContext: MessagePromptContext,
+ PromptComposer: AgentPromptComposer,
+ Egress: SandboxEgressProvisioner,
+ Lifecycle: AgentSessionLifecyclePublisher,
+ Mentions: PromptMentions,
+ Notifier: AgentSessionNotifier,
+{
+ /// Origin-bearing commands must be authorized even when they will only
+ /// queue (or arrived over the internal forwarding bus). Direct controls
+ /// carry the access check performed when constructing `ControlEvent`.
+ pub(super) async fn authorize_action(&self, command: &DeliverAction) -> Result<()> {
+ if let Some(origin) = &command.announce {
+ let actor = command.actor.as_ref().ok_or(AgentSessionError::Forbidden)?;
+ self.prompt_context.authorize_origin(actor, origin).await?;
+ }
+ Ok(())
+ }
+
+ pub(super) async fn admit_session(&self, session: &AgentSession) -> Result<()> {
+ let kind = AgentKind::for_session(session.bot_id, &session.harness);
+ if macro_funded(kind) {
+ // Never use the actor or a system fallback for a missing user owner.
+ self.admission
+ .admit(session.owner_user()?, AiFeature::AgentSession)
+ .await?;
+ }
+ Ok(())
+ }
+
+ pub(super) async fn admit_session_id(&self, session_id: AgentSessionId) -> Result<()> {
+ self.admit_session(&self.sessions.get_session(session_id).await?)
+ .await
+ }
+
+ /// Check waiting work without consuming it. Unavailability leaves it for
+ /// the next ordinary queue-driving event, not an immediate retry loop.
+ pub(super) async fn revalidate_queue(&self, session_id: AgentSessionId) -> Result<()> {
+ if let Err(error) = self.admit_session_id(session_id).await {
+ self.reject_waiting_on_denial(session_id, &error).await?;
+ return Err(error);
+ }
+ Ok(())
+ }
+
+ pub(super) async fn reject_waiting_on_denial(
+ &self,
+ session_id: AgentSessionId,
+ error: &HarnessError,
+ ) -> Result<()> {
+ // A steering follow-up may fail while the previous turn still runs.
+ // Only release a provisional busy mark, never that running turn.
+ if self.busy.turn(session_id).is_none() {
+ self.busy.clear(session_id);
+ }
+ let HarnessError::Admission(failure @ AiAdmissionError::Denied(_)) = error else {
+ return Ok(());
+ };
+ let waiting = self.queues.snapshot(session_id);
+ if waiting.is_empty() {
+ return Ok(());
+ }
+ self.queues.drop_session(session_id);
+ if let Err(error) = self.persist_or_rollback(session_id).await {
+ // Keep even newly announced entries if rollback itself cannot read
+ // the store. The next event must revalidate, not forget this work.
+ self.queues.replace(session_id, waiting);
+ return Err(error);
+ }
+ self.publish_queue(session_id).await;
+ // Persist first: never report a terminal rejection while the durable
+ // queue still says that the command will run after a restart.
+ for entry in waiting {
+ self.resolve_announced_reply(
+ session_id,
+ entry.announced,
+ entry.announce.as_ref(),
+ entry.actor.as_ref(),
+ ReplyOutcome::Failed,
+ )
+ .await;
+ self.publish_command_rejected(
+ session_id,
+ entry.action_id,
+ entry.actor,
+ entry.announced,
+ *failure,
+ )
+ .await;
+ }
+ Ok(())
+ }
+
+ pub(super) async fn publish_command_rejected(
+ &self,
+ session_id: AgentSessionId,
+ action_id: AgentActionId,
+ actor: Option<MacroUserIdStr<'static>>,
+ announcement_message_id: Option<macro_uuid::Uuid>,
+ failure: AiAdmissionError,
+ ) {
+ self.publish_lifecycle(session_id, |identity| {
+ AgentSessionLifecycleEvent::CommandRejected(CommandRejectedMetadata {
+ identity,
+ action_id,
+ actor,
+ announcement_message_id,
+ failure: failure.into(),
+ })
+ })
+ .await;
+ }
+
+ pub(super) async fn admit_open(
+ &self,
+ bot: BotId,
+ harness: &str,
+ owner: &MacroUserIdStr<'static>,
+ ) -> Result<()> {
+ if macro_funded(AgentKind::for_session(bot, harness)) {
+ self.admission.admit(owner, AiFeature::AgentSession).await?;
+ }
+ Ok(())
+ }
+}
+
+fn macro_funded(kind: AgentKind) -> bool {
+ match kind {
+ AgentKind::InMemory | AgentKind::SandboxedCoder => true,
+ // Independently billed tools/helpers have their own admission; runtime
+ // execution itself uses the owner's subscription or external provider.
+ AgentKind::Cursor
+ | AgentKind::CodexCloud
+ | AgentKind::ClaudeCloud
+ | AgentKind::External => false,
+ }
+}
diff --git a/crates/agent_harness/src/domain/service/deliver.rs b/crates/agent_harness/src/domain/service/deliver.rs
index a73b603363..e705dc4faf 100644
--- a/crates/agent_harness/src/domain/service/deliver.rs
+++ b/crates/agent_harness/src/domain/service/deliver.rs
@@ -58,6 +58,10 @@ where
announce: _,
} = command;
+ if action.occupies_turn() {
+ self.admit_session_id(session_id).await?;
+ }
+
match self
.sessions
.send_action(session_id, actor.clone(), action.clone(), id)
@@ -137,6 +141,9 @@ where
.await?;
self.restore_queue(session_id).await?;
}
+ if action.occupies_turn() {
+ self.admit_session(&session).await?;
+ }
self.sessions
.send_action(session_id, actor, action, id)
.await?;
@@ -283,11 +290,27 @@ where
let Some(turn) = turn else {
return;
};
- let (Some(message_id), Some(origin), Some(triggered_by)) = (
+ self.resolve_announced_reply(
+ session_id,
turn.announcement_message_id,
turn.announce.as_ref(),
turn.actor.as_ref(),
- ) else {
+ outcome,
+ )
+ .await;
+ }
+
+ /// Resolve an announcement even when its queued command never opened a turn.
+ pub(super) async fn resolve_announced_reply(
+ &self,
+ session_id: AgentSessionId,
+ message_id: Option<macro_uuid::Uuid>,
+ origin: Option<&AnnounceOrigin>,
+ actor: Option<&MacroUserIdStr<'static>>,
+ outcome: ReplyOutcome,
+ ) {
+ let (Some(message_id), Some(origin), Some(triggered_by)) = (message_id, origin, actor)
+ else {
return;
};
let session = match self.sessions.get_session(session_id).await {
diff --git a/crates/agent_harness/src/domain/service/open.rs b/crates/agent_harness/src/domain/service/open.rs
index 8c71915a9d..52ba6d58ff 100644
--- a/crates/agent_harness/src/domain/service/open.rs
+++ b/crates/agent_harness/src/domain/service/open.rs
@@ -247,6 +247,10 @@ where
}
None
};
+ self.inner
+ .admit_open(bot_id, &harness, &owner_user)
+ .await
+ .map_err(into_session_error)?;
let defaults = self.inner.defaults.for_bot(bot_id);
let sandbox_size = self.inner.sessions.user_sandbox_size(&owner_user).await?;
let session_id = request.id.unwrap_or_else(AgentSessionId::new);
@@ -446,6 +450,13 @@ where
.authorize_origin(&actor, &announcement)
.await?;
+ self.admit_open(
+ bot_id,
+ runtime.kind.harness_slug().unwrap_or(&runtime.harness),
+ &actor,
+ )
+ .await?;
+
// Asked before anything exists for the session: a row whose spawn is
// bound to fail would be marked disconnected and leave the thread
// with a chip that never answers. Declining is the bot's reply
diff --git a/crates/agent_harness/src/domain/service/queue.rs b/crates/agent_harness/src/domain/service/queue.rs
index 7dfb4cc182..09fe78a040 100644
--- a/crates/agent_harness/src/domain/service/queue.rs
+++ b/crates/agent_harness/src/domain/service/queue.rs
@@ -587,6 +587,7 @@ where
session_id: AgentSessionId,
command: DeliverAction,
) -> Result<CommandOutcome> {
+ self.authorize_action(&command).await?;
let action_id = command.id;
if self.queues.contains(session_id, action_id) {
return Ok(CommandOutcome::Queued);
@@ -598,6 +599,23 @@ where
{
return Ok(CommandOutcome::Completed);
}
+ let session = self.sessions.get_session(session_id).await?;
+ if let Err(error) = self.admit_session(&session).await {
+ // Forwarding acknowledges bus acceptance before this worker runs.
+ // Publish even an ingress refusal so the submitting replica hears it.
+ if let HarnessError::Admission(failure) = &error {
+ self.publish_command_rejected(
+ session_id,
+ command.id,
+ command.actor.clone(),
+ None,
+ *failure,
+ )
+ .await;
+ }
+ self.reject_waiting_on_denial(session_id, &error).await?;
+ return Err(error);
+ }
let prompt = match &command.action {
AgentAction::Prompt(prompt) => Some(prompt.prompt.clone()),
_ => None,
@@ -706,6 +724,7 @@ where
actor: Option<&MacroUserIdStr<'static>>,
announce: Option<AnnounceOrigin>,
) -> Result<()> {
+ self.revalidate_queue(session_id).await?;
if let Err(error) = self
.deliver(
session_id,
@@ -725,6 +744,9 @@ where
);
}
+ // Stop may have waited for a runtime reconnect; check again before
+ // posting a pending reply for the waiting follow-up.
+ self.revalidate_queue(session_id).await?;
// Front of the queue, so the next prompt turn is this one's.
let prompted_message_id = self.sessions.next_prompt_message_id(session_id).await?;
let announcement = self
@@ -759,7 +781,7 @@ where
/// Persist after a working-copy mutation. A failed write reloads the last
/// good row so this process does not keep a queue the store never saw.
- async fn persist_or_rollback(&self, session_id: AgentSessionId) -> Result<()> {
+ pub(super) async fn persist_or_rollback(&self, session_id: AgentSessionId) -> Result<()> {
if let Err(error) = self.write_queue(session_id).await {
if let Err(reload) = self.reload_queue(session_id).await {
tracing::error!(
@@ -775,15 +797,15 @@ where
/// Put a claimed entry back and persist. A persist failure here loses the
/// in-flight item on the next restart — the same as losing the turn mark.
- async fn requeue_claimed(&self, session_id: AgentSessionId, entry: QueuedEntry) {
+ async fn requeue_claimed(&self, session_id: AgentSessionId, entry: QueuedEntry) -> Result<()> {
self.queues.requeue_front(session_id, entry);
- if let Err(error) = self.write_queue(session_id).await {
+ self.write_queue(session_id).await.inspect_err(|error| {
tracing::error!(
error = ?error,
%session_id,
"failed to persist a requeued agent session action"
);
- }
+ })
}
/// Replace the working copy from the session store.
@@ -863,6 +885,10 @@ where
self.publish_queue(session_id).await;
return Ok(Dispatch::QueueEmpty);
}
+ if self.queues.list(session_id).is_empty() {
+ return Ok(Dispatch::QueueEmpty);
+ }
+ self.revalidate_queue(session_id).await?;
let Some(mut entry) = self.queues.claim_next(session_id) else {
return Ok(Dispatch::QueueEmpty);
};
@@ -880,7 +906,7 @@ where
let prompted_message_id = match self.sessions.next_prompt_message_id(session_id).await {
Ok(message_id) => message_id,
Err(error) => {
- self.requeue_claimed(session_id, entry).await;
+ self.requeue_claimed(session_id, entry).await?;
return Err(error.into());
}
};
@@ -899,10 +925,15 @@ where
)
.await
{
- self.requeue_claimed(session_id, entry).await;
+ self.requeue_claimed(session_id, entry).await?;
return Err(error);
}
+ if let Err(error) = self.admit_session_id(session_id).await {
+ self.requeue_claimed(session_id, entry).await?;
+ self.reject_waiting_on_denial(session_id, &error).await?;
+ return Err(error);
+ }
if entry.announced.is_none() {
let announcement = match self
.announcement(
@@ -916,7 +947,7 @@ where
{
Ok(announcement) => announcement,
Err(error) => {
- self.requeue_claimed(session_id, entry).await;
+ self.requeue_claimed(session_id, entry).await?;
return Err(error);
}
};
@@ -924,7 +955,7 @@ where
match self.announcer.announce(announcement).await {
Ok(announced) => entry.announced = Some(announced.message_id),
Err(error) => {
- self.requeue_claimed(session_id, entry).await;
+ self.requeue_claimed(session_id, entry).await?;
return Err(error);
}
}
@@ -961,7 +992,8 @@ where
Ok(Dispatch::Dispatched)
}
Err(error) => {
- self.requeue_claimed(session_id, entry).await;
+ self.requeue_claimed(session_id, entry).await?;
+ self.reject_waiting_on_denial(session_id, &error).await?;
Err(error)
}
}
diff --git a/crates/agent_harness/src/domain/service/test.rs b/crates/agent_harness/src/domain/service/test.rs
index 6e50e45463..db4f8ed746 100644
--- a/crates/agent_harness/src/domain/service/test.rs
+++ b/crates/agent_harness/src/domain/service/test.rs
@@ -3,6 +3,7 @@
//! recording announcer. Only the edges are doubles.
mod chat_reply;
+mod quota;
mod user_cleanup;
use agent_session::domain::service::AgentSessionService as _;
@@ -907,9 +908,9 @@ async fn context_failure_still_calls_composer_with_empty_messages_and_delivers()
let (result, container) = tokio::join!(open, drive);
result.expect("context lookup is best-effort after Kafka admission");
- // Authorized twice: once before provisioning, once at dispatch, so a
- // revocation between the two still stops the prompt.
- assert_eq!(context.authorized().len(), 2);
+ // Access precedes provisioning and queue admission, and is rechecked at
+ // dispatch so a revocation while queued still stops the prompt.
+ assert_eq!(context.authorized().len(), 3);
assert_eq!(announcer.announced().len(), 1);
assert_eq!(
composer.calls(),
diff --git a/crates/agent_harness/src/domain/service/test/quota.rs b/crates/agent_harness/src/domain/service/test/quota.rs
new file mode 100644
index 0000000000..eb9476f548
--- /dev/null
+++ b/crates/agent_harness/src/domain/service/test/quota.rs
@@ -0,0 +1,753 @@
+use super::*;
+use ai_billing::{AdmissionFuture, AiAdmissionError, AiAdmissionService, DenyReason};
+use ai_usage::AiFeature;
+use model_owner::Owner;
+
+#[derive(Default)]
+struct AdmissionMock {
+ failure: Mutex<Option<AiAdmissionError>>,
+ responses: Mutex<std::collections::VecDeque<Option<AiAdmissionError>>>,
+ calls: Mutex<Vec<(String, AiFeature)>>,
+}
+
+impl AiAdmissionService for AdmissionMock {
+ fn admit<'a>(
+ &'a self,
+ user: &'a MacroUserIdStr<'_>,
+ feature: AiFeature,
+ ) -> AdmissionFuture<'a> {
+ self.calls.lock().unwrap().push((user.to_string(), feature));
+ let failure = self
+ .responses
+ .lock()
+ .unwrap()
+ .pop_front()
+ .unwrap_or(*self.failure.lock().unwrap());
+ Box::pin(async move { failure.map_or(Ok(()), Err) })
+ }
+}
+
+fn denied() -> AiAdmissionError {
+ AiAdmissionError::Denied(DenyReason::AllowanceExhausted)
+}
+
+fn bench(
+ failure: Option<AiAdmissionError>,
+) -> (TestHarness, InMemoryAgentSessionRepo, Arc<AdmissionMock>) {
+ let repo = InMemoryAgentSessionRepo::new();
+ let admission = Arc::new(AdmissionMock {
+ failure: Mutex::new(failure),
+ ..Default::default()
+ });
+ let service = harness_sharing_repo(repo.clone()).with_admission(admission.clone());
+ (service, repo, admission)
+}
+
+async fn session(
+ repo: &InMemoryAgentSessionRepo,
+ bot: BotId,
+ harness: &str,
+ owner: Owner,
+) -> AgentSessionId {
+ let id = AgentSessionId::new();
+ agent_session::domain::ports::AgentSessionRepo::create(
+ repo,
+ CreateAgentSessionParams {
+ id,
+ owner_id: owner,
+ bot_id: bot,
+ thread_id: None,
+ originating_message_id: None,
+ model: "model".into(),
+ harness: harness.into(),
+ repo_url: None,
+ repo_branch: None,
+ workspace: "/workspace".into(),
+ sandbox_size: SandboxSize::Default,
+ instructions: None,
+ mcp_servers: AgentMcpServers::OwnerConnections,
+ egress_token_hash: None,
+ },
+ )
+ .await
+ .unwrap();
+ id
+}
+
+fn action(action: AgentAction) -> DeliverAction {
+ DeliverAction {
+ id: AgentActionId::mint(),
+ action,
+ actor: Some(staff_sender()),
+ announce: None,
+ }
+}
+
+fn assert_no_provisioning(service: &TestHarness) {
+ assert_eq!(service.inner.containers.spawned(), 0);
+ assert_eq!(service.inner.containers.resumed(), 0);
+ assert!(service.inner.egress.provisioned().is_empty());
+ assert!(service.inner.announcer.announced().is_empty());
+ assert!(
+ service
+ .inner
+ .lifecycle_publisher
+ .published()
+ .iter()
+ .all(|event| { matches!(event, AgentSessionLifecycleEvent::CommandRejected(_)) })
+ );
+}
+
+#[tokio::test]
+async fn denied_or_unavailable_trigger_open_has_no_side_effects() {
+ for failure in [denied(), AiAdmissionError::Unavailable] {
+ for (bot, kind, harness) in [
+ (
+ bot_id::MACRO_CODER_BOT_ID,
+ AgentKind::SandboxedCoder,
+ "opencode",
+ ),
+ (BotId::TEST_A, AgentKind::InMemory, "in-memory"),
+ ] {
+ let (service, repo, admission) = bench(Some(failure));
+ let mut open = open_command();
+ open.bot_id = bot;
+ open.runtime.kind = kind;
+ open.runtime.harness = harness.into();
+ mention_origin_mut(&mut open).sender = staff_sender();
+ for origin in [
+ open.origin.clone(),
+ SessionOrigin::TaskAssignment(crate::domain::model::TaskAssignmentOrigin {
+ parent: MessageParent::parse("document", "assigned-task").unwrap(),
+ discussion_id: macro_uuid::generate_uuid_v7(),
+ actor: staff_sender(),
+ prompt: "Work on this task".to_owned(),
+ }),
+ ] {
+ admission.calls.lock().unwrap().clear();
+ open.origin = origin;
+ let id = AgentSessionId::new();
+ let result = service
+ .execute_here(id, HarnessCommand::Open(open.clone()))
+ .await;
+ assert!(matches!(result, Err(HarnessError::Admission(error)) if error == failure));
+ assert!(repo.get(id).await.is_err());
+ assert_eq!(
+ *admission.calls.lock().unwrap(),
+ [(staff_sender().to_string(), AiFeature::AgentSession)]
+ );
+ assert_no_provisioning(&service);
+ }
+ }
+ }
+}
+
+#[tokio::test]
+async fn unauthorized_open_never_consults_billing() {
+ let (service, _, admission) = bench(Some(denied()));
+ let mut open = open_command();
+ open.bot_id = bot_id::MACRO_CODER_BOT_ID;
+ assert!(matches!(
+ service
+ .execute_here(AgentSessionId::new(), HarnessCommand::Open(open.clone()))
+ .await,
+ Err(HarnessError::Session(AgentSessionError::Forbidden))
+ ));
+ mention_origin_mut(&mut open).sender = staff_sender();
+ *service.inner.prompt_context.unauthorized.lock().unwrap() = Some("no access".into());
+ assert!(matches!(
+ service
+ .execute_here(AgentSessionId::new(), HarnessCommand::Open(open))
+ .await,
+ Err(HarnessError::PromptContext(_))
+ ));
+ assert!(admission.calls.lock().unwrap().is_empty());
+ assert_no_provisioning(&service);
+}
+
+#[tokio::test]
+async fn managed_open_checks_quota_before_provisioning_without_an_initial_prompt() {
+ use agent_session::domain::ports::SelectedManagedPersona;
+ for failure in [denied(), AiAdmissionError::Unavailable] {
+ let (service, repo, _) = bench(Some(failure));
+ let id = AgentSessionId::new();
+ let result = service
+ .open_managed_session(OpenManagedSession {
+ id: Some(id),
+ owner: Owner::User(sender()),
+ repo_url: None,
+ repo_branch: None,
+ instructions: None,
+ model: None,
+ prompt: None,
+ profile: Some(SelectedManagedPersona {
+ bot_id: bot_id::MACRO_CODER_BOT_ID,
+ profile: None,
+ }),
+ })
+ .await;
+ assert!(matches!(result, Err(AgentSessionError::Admission(error)) if error == failure));
+ assert!(repo.get(id).await.is_err());
+ assert_no_provisioning(&service);
+ }
+}
+
+#[tokio::test]
+async fn spending_actions_charge_the_persisted_owner_not_the_actor() {
+ for failure in [denied(), AiAdmissionError::Unavailable] {
+ for (bot, harness) in [
+ (bot_id::MACRO_CODER_BOT_ID, "opencode"),
+ (BotId::TEST_A, "macro-inmem"),
+ ] {
+ for action in [AgentAction::prompt("hello"), AgentAction::Compact] {
+ let (service, repo, admission) = bench(Some(failure));
+ let id = session(&repo, bot, harness, Owner::User(sender())).await;
+ // Busy sessions must reject before accepting durable queued work too.
+ service.inner.busy.admit(id);
+ let result = service
+ .execute_here(id, HarnessCommand::Deliver(self::action(action)))
+ .await;
+ assert!(matches!(result, Err(HarnessError::Admission(error)) if error == failure));
+ assert!(repo.list_queued_actions(id).await.unwrap().is_empty());
+ assert_eq!(
+ *admission.calls.lock().unwrap(),
+ [(sender().to_string(), AiFeature::AgentSession)]
+ );
+ assert_no_provisioning(&service);
+ }
+ }
+ }
+}
+
+#[tokio::test]
+async fn externally_funded_runtimes_accept_spending_actions_without_quota_io() {
+ for harness in ["cursor", "codex-cloud", "claude-cloud", "macrod", "custom"] {
+ let (service, repo, admission) = bench(Some(denied()));
+ let id = session(&repo, BotId::TEST_A, harness, Owner::User(staff_sender())).await;
+ service.inner.busy.admit(id);
+ let result = service
+ .execute_here(id, HarnessCommand::Deliver(action(AgentAction::Compact)))
+ .await
+ .unwrap();
+ assert_eq!(result, CommandOutcome::Queued);
+ assert!(admission.calls.lock().unwrap().is_empty());
+ assert_eq!(repo.list_queued_actions(id).await.unwrap().len(), 1);
+ }
+}
+
+#[tokio::test]
+async fn external_open_does_not_check_runtime_quota() {
+ let (service, _, admission) = bench(Some(denied()));
+ service
+ .open_external_session(open_external_request("/srv/agent"))
+ .await
+ .unwrap();
+ assert!(admission.calls.lock().unwrap().is_empty());
+ assert!(service.inner.egress.provisioned().is_empty());
+}
+
+#[tokio::test]
+async fn unauthorized_forwarded_origin_is_rejected_before_billing_or_queueing() {
+ let (service, repo, admission) = bench(Some(denied()));
+ *service.inner.prompt_context.unauthorized.lock().unwrap() = Some("no access".into());
+ let id = session(&repo, BotId::TEST_A, "in-memory", Owner::User(sender())).await;
+ service.inner.busy.admit(id);
+ let result = super::super::ForwardedCommands::execute_forwarded(
+ &service,
+ id,
+ HarnessCommand::Deliver(forward_message("hello")),
+ )
+ .await;
+ assert!(matches!(result, Err(HarnessError::PromptContext(_))));
+ assert!(admission.calls.lock().unwrap().is_empty());
+ assert!(repo.list_queued_actions(id).await.unwrap().is_empty());
+}
+
+#[tokio::test]
+async fn authorized_forwarded_commands_still_require_admission() {
+ let (service, repo, admission) = bench(Some(denied()));
+ let id = session(&repo, BotId::TEST_A, "in-memory", Owner::User(sender())).await;
+ let result = super::super::ForwardedCommands::execute_forwarded(
+ &service,
+ id,
+ HarnessCommand::Deliver(forward_message("hello")),
+ )
+ .await;
+ assert!(matches!(result, Err(HarnessError::Admission(_))));
+ assert_eq!(admission.calls.lock().unwrap().len(), 1);
+ assert_eq!(service.inner.prompt_context.authorized().len(), 1);
+ let events = service.inner.lifecycle_publisher.published();
+ assert!(
+ matches!(events.as_slice(), [AgentSessionLifecycleEvent::CommandRejected(event)]
+ if event.failure.code == denied().code() && !event.failure.retryable)
+ );
+ assert_no_provisioning(&service);
+}
+
+#[tokio::test]
+async fn staff_and_non_user_owner_restrictions_precede_quota() {
+ let (service, repo, admission) = bench(Some(denied()));
+ let id = session(
+ &repo,
+ bot_id::MACRO_CODER_BOT_ID,
+ "opencode",
+ Owner::User(sender()),
+ )
+ .await;
+ let mut command = action(AgentAction::Compact);
+ command.actor = Some(sender());
+ assert!(matches!(
+ service
+ .execute_here(id, HarnessCommand::Deliver(command))
+ .await,
+ Err(HarnessError::Session(AgentSessionError::Forbidden))
+ ));
+ let id = session(&repo, BotId::TEST_A, "in-memory", Owner::Bot(BotId::TEST_A)).await;
+ assert!(matches!(
+ service
+ .execute_here(id, HarnessCommand::Deliver(action(AgentAction::Compact)))
+ .await,
+ Err(HarnessError::Session(AgentSessionError::OwnerNotUser(_)))
+ ));
+ assert!(admission.calls.lock().unwrap().is_empty());
+}
+
+#[tokio::test]
+async fn retries_of_queued_and_in_flight_actions_do_not_recheck_quota() {
+ let (service, repo, admission) = bench(None);
+ let id = session(&repo, BotId::TEST_A, "in-memory", Owner::User(sender())).await;
+ service.inner.busy.admit(id);
+ let command = action(AgentAction::Compact);
+ assert_eq!(
+ service
+ .execute_here(id, HarnessCommand::Deliver(command.clone()))
+ .await
+ .unwrap(),
+ CommandOutcome::Queued
+ );
+ *admission.failure.lock().unwrap() = Some(denied());
+ assert_eq!(
+ service
+ .execute_here(id, HarnessCommand::Deliver(command.clone()))
+ .await
+ .unwrap(),
+ CommandOutcome::Queued
+ );
+ assert_eq!(repo.list_queued_actions(id).await.unwrap().len(), 1);
+ // A fresh replica recognizes a durable queued retry as already admitted.
+ let restarted = harness_sharing_repo(repo.clone()).with_admission(admission.clone());
+ assert_eq!(
+ restarted
+ .execute_here(id, HarnessCommand::Deliver(command.clone()))
+ .await
+ .unwrap(),
+ CommandOutcome::Queued
+ );
+ let entry = service.inner.queues.claim_next(id).unwrap();
+ service.inner.busy.mark_turn(
+ id,
+ crate::domain::queue::InFlightTurn {
+ action_id: entry.action_id,
+ turn: agent_fold::domain::model::TurnId(0),
+ actor: entry.actor,
+ announce: None,
+ announcement_message_id: None,
+ dispatched_at: chrono::Utc::now(),
+ },
+ );
+ assert_eq!(
+ service
+ .execute_here(id, HarnessCommand::Deliver(command))
+ .await
+ .unwrap(),
+ CommandOutcome::Completed
+ );
+ assert_eq!(admission.calls.lock().unwrap().len(), 1);
+}
+
+#[tokio::test]
+async fn non_spending_controls_and_queue_removal_remain_available() {
+ let (service, repo, admission) = bench(None);
+ let id = session(&repo, BotId::TEST_A, "in-memory", Owner::User(sender())).await;
+ service.inner.busy.admit(id);
+ let command = action(AgentAction::Compact);
+ service
+ .execute_here(id, HarnessCommand::Deliver(command.clone()))
+ .await
+ .unwrap();
+ *admission.failure.lock().unwrap() = Some(denied());
+ assert_eq!(service.queued_controls(id).await.unwrap().len(), 1);
+ service
+ .remove_queued_control(id, command.id, Some(sender()))
+ .await
+ .unwrap();
+ assert!(service.queued_controls(id).await.unwrap().is_empty());
+ // A disconnected runtime can still refuse these, but quota must not.
+ for action in [AgentAction::Stop, permission_answer("permission", "once")] {
+ let result = service
+ .execute_here(id, HarnessCommand::Deliver(self::action(action)))
+ .await;
+ assert!(!matches!(result, Err(HarnessError::Admission(_))));
+ }
+ assert_eq!(admission.calls.lock().unwrap().len(), 1);
+}
+
+async fn enqueue_waiting(service: &TestHarness, id: AgentSessionId) -> Vec<AgentActionId> {
+ service.inner.busy.admit(id);
+ let mut ids = Vec::new();
+ for prompt in ["first", "second"] {
+ let command = forward_message(prompt);
+ ids.push(command.id);
+ assert_eq!(
+ service
+ .execute_here(id, HarnessCommand::Deliver(command))
+ .await
+ .unwrap(),
+ CommandOutcome::Queued
+ );
+ }
+ ids
+}
+
+fn turn_ended() -> HarnessCommand {
+ HarnessCommand::Turn(TurnSignal::TurnEnded {
+ turn: agent_fold::domain::model::TurnId(0),
+ action_id: None,
+ stop: agent_fold::domain::model::StopReason::EndTurn,
+ last_text: None,
+ })
+}
+
+fn rejected_ids(service: &TestHarness) -> Vec<AgentActionId> {
+ service
+ .inner
+ .lifecycle_publisher
+ .published()
+ .into_iter()
+ .filter_map(|event| match event {
+ AgentSessionLifecycleEvent::CommandRejected(event) => {
+ assert_eq!(event.failure.code, denied().code());
+ assert!(!event.failure.retryable);
+ Some(event.action_id)
+ }
+ AgentSessionLifecycleEvent::TurnStarted(_) => panic!("rejected work started a turn"),
+ _ => None,
+ })
+ .collect()
+}
+
+#[tokio::test]
+async fn enqueue_then_exhaust_rejects_all_waiting_work_once_even_after_restart() {
+ for restart in [false, true] {
+ let (service, repo, admission) = bench(None);
+ let id = session(&repo, BotId::TEST_A, "in-memory", Owner::User(sender())).await;
+ let ids = enqueue_waiting(&service, id).await;
+ *admission.failure.lock().unwrap() = Some(denied());
+ let service = if restart {
+ harness_sharing_repo(repo.clone()).with_admission(admission.clone())
+ } else {
+ service
+ };
+ assert!(matches!(service.execute_here(id, turn_ended()).await,
+ Err(HarnessError::Admission(error)) if error == denied()));
+ assert_eq!(rejected_ids(&service), ids);
+ assert!(!service.inner.busy.is_pending(id));
+ assert!(repo.list_queued_actions(id).await.unwrap().is_empty());
+ assert!(service.inner.queues.list(id).is_empty());
+ assert!(service.inner.prompt_composer.calls().is_empty());
+ assert_no_provisioning(&service);
+ // Empty-queue events neither recheck billing nor repeat rejection facts.
+ let calls = admission.calls.lock().unwrap().len();
+ service.execute_here(id, turn_ended()).await.unwrap();
+ assert_eq!(admission.calls.lock().unwrap().len(), calls);
+ assert_eq!(rejected_ids(&service), ids);
+ }
+}
+
+#[tokio::test]
+async fn billing_outage_preserves_fifo_and_retries_only_on_a_new_event() {
+ let (service, repo, admission) = bench(None);
+ let id = session(&repo, BotId::TEST_A, "in-memory", Owner::User(sender())).await;
+ let ids = enqueue_waiting(&service, id).await;
+ *admission.failure.lock().unwrap() = Some(AiAdmissionError::Unavailable);
+ for _ in 0..3 {
+ let calls = admission.calls.lock().unwrap().len();
+ assert!(matches!(
+ service.execute_here(id, turn_ended()).await,
+ Err(HarnessError::Admission(AiAdmissionError::Unavailable))
+ ));
+ tokio::task::yield_now().await;
+ assert_eq!(admission.calls.lock().unwrap().len(), calls + 1);
+ assert!(!service.inner.busy.is_pending(id));
+ assert_eq!(
+ repo.list_queued_actions(id)
+ .await
+ .unwrap()
+ .iter()
+ .map(|entry| entry.action_id)
+ .collect::<Vec<_>>(),
+ ids
+ );
+ assert!(service.inner.lifecycle_publisher.published().is_empty());
+ assert!(service.inner.prompt_composer.calls().is_empty());
+ assert_no_provisioning(&service);
+ }
+ let restarted = harness_sharing_repo(repo.clone()).with_admission(admission.clone());
+ assert!(matches!(
+ restarted.execute_here(id, turn_ended()).await,
+ Err(HarnessError::Admission(AiAdmissionError::Unavailable))
+ ));
+ *admission.failure.lock().unwrap() = Some(denied());
+ assert!(restarted.execute_here(id, turn_ended()).await.is_err());
+ assert_eq!(rejected_ids(&restarted), ids);
+}
+
+#[tokio::test]
+async fn admission_changes_during_dispatch_never_reach_the_runtime() {
+ for failure in [denied(), AiAdmissionError::Unavailable] {
+ // Fail before composition, before announcement, or after announcement
+ // immediately before delivery. The last case must clean up the reply.
+ for allowed_checks in 0..3 {
+ let (service, repo, admission) = bench(None);
+ let id = session(&repo, BotId::TEST_A, "in-memory", Owner::User(sender())).await;
+ let ids = enqueue_waiting(&service, id).await;
+ *admission.failure.lock().unwrap() = Some(failure);
+ admission
+ .responses
+ .lock()
+ .unwrap()
+ .extend(vec![None; allowed_checks]);
+ assert!(matches!(service.execute_here(id, turn_ended()).await,
+ Err(HarnessError::Admission(error)) if error == failure));
+ assert!(!service.inner.busy.is_pending(id));
+ assert_eq!(service.inner.containers.resumed(), 0);
+ assert!(service.inner.egress.provisioned().is_empty());
+ assert_eq!(
+ service.inner.prompt_composer.calls().len(),
+ usize::from(allowed_checks > 0)
+ );
+ let announced = service.inner.announcer.announced_messages();
+ assert_eq!(announced.len(), usize::from(allowed_checks == 2));
+ let remaining = repo.list_queued_actions(id).await.unwrap();
+ if failure.is_retryable() {
+ assert_eq!(
+ remaining
+ .iter()
+ .map(|entry| entry.action_id)
+ .collect::<Vec<_>>(),
+ ids
+ );
+ assert_eq!(
+ remaining[0].announced_message_id,
+ announced.first().map(|message| message.message_id)
+ );
+ assert!(service.inner.lifecycle_publisher.published().is_empty());
+ assert!(service.inner.announcer.resolved().is_empty());
+ // Retry while still unavailable must not compose or announce again.
+ assert!(service.execute_here(id, turn_ended()).await.is_err());
+ assert_eq!(service.inner.announcer.announced_messages(), announced);
+ *admission.failure.lock().unwrap() = Some(denied());
+ assert!(service.execute_here(id, turn_ended()).await.is_err());
+ } else {
+ assert!(remaining.is_empty());
+ }
+ assert_eq!(rejected_ids(&service), ids);
+ let resolved = service.inner.announcer.resolved();
+ assert_eq!(resolved.len(), announced.len());
+ if let Some(reply) = resolved.first() {
+ assert_eq!(reply.message_id, announced[0].message_id);
+ assert_eq!(reply.outcome, crate::domain::model::ReplyOutcome::Failed);
+ }
+ }
+ }
+}
+
+#[tokio::test]
+async fn denying_a_steering_follow_up_does_not_cancel_the_running_turn() {
+ let (service, repo, admission) = bench(None);
+ let id = session(&repo, BotId::TEST_A, "in-memory", Owner::User(sender())).await;
+ let running = crate::domain::queue::InFlightTurn {
+ action_id: AgentActionId::mint(),
+ turn: agent_fold::domain::model::TurnId(0),
+ actor: Some(sender()),
+ announce: None,
+ announcement_message_id: None,
+ dispatched_at: chrono::Utc::now(),
+ };
+ service.inner.busy.mark_turn(id, running.clone());
+ // Enqueue succeeds, but steering's revalidation denies before Stop or chip.
+ admission.responses.lock().unwrap().push_back(None);
+ *admission.failure.lock().unwrap() = Some(denied());
+ let command = forward_message("interrupt");
+ let action_id = command.id;
+ assert!(matches!(
+ service
+ .execute_here(id, HarnessCommand::Deliver(command))
+ .await,
+ Err(HarnessError::Admission(_))
+ ));
+ assert_eq!(
+ service.inner.busy.turn(id).unwrap().action_id,
+ running.action_id
+ );
+ assert_eq!(rejected_ids(&service), [action_id]);
+ assert!(repo.list_queued_actions(id).await.unwrap().is_empty());
+ assert_no_provisioning(&service);
+}
+
+#[tokio::test]
+async fn restored_announced_work_resolves_without_inventing_a_turn() {
+ let (service, repo, admission) = bench(None);
+ let id = session(&repo, BotId::TEST_A, "in-memory", Owner::User(sender())).await;
+ let ids = enqueue_waiting(&service, id).await;
+ // The prompt was announced but billing failed immediately before dispatch.
+ admission.responses.lock().unwrap().extend([None, None]);
+ *admission.failure.lock().unwrap() = Some(AiAdmissionError::Unavailable);
+ assert!(service.execute_here(id, turn_ended()).await.is_err());
+ let announcement = service.inner.announcer.announced_messages()[0];
+ let restarted = harness_sharing_repo(repo.clone()).with_admission(admission.clone());
+ *admission.failure.lock().unwrap() = Some(denied());
+ assert!(restarted.execute_here(id, turn_ended()).await.is_err());
+ assert_eq!(rejected_ids(&restarted), ids);
+ let resolved = restarted.inner.announcer.resolved();
+ assert_eq!(resolved.len(), 1);
+ assert_eq!(resolved[0].message_id, announcement.message_id);
+ assert!(repo.list_queued_actions(id).await.unwrap().is_empty());
+ assert_no_provisioning(&restarted);
+}
+
+#[tokio::test]
+async fn recovery_dispatches_the_original_head_without_duplicate_announcements() {
+ let (service, repo, admission) = bench(None);
+ let id = disconnected_session(&repo, &service.inner.containers).await;
+ let ids = enqueue_waiting(&service, id).await;
+ admission.responses.lock().unwrap().extend([None, None]);
+ *admission.failure.lock().unwrap() = Some(AiAdmissionError::Unavailable);
+ assert!(service.execute_here(id, turn_ended()).await.is_err());
+ assert_eq!(service.inner.announcer.announced().len(), 1);
+ assert_eq!(service.inner.containers.resumed(), 0);
+ *admission.failure.lock().unwrap() = None;
+ let dispatch = service.execute_here(id, turn_ended());
+ let resume = async {
+ while service.inner.containers.resumed() == 0 {
+ tokio::task::yield_now().await;
+ }
+ let container = service.inner.containers.container(id).unwrap();
+ complete_resume(&container).await;
+ container.agent().wait_for_requests(3).await;
+ container
+ };
+ let (result, container) = tokio::time::timeout(std::time::Duration::from_secs(5), async {
+ tokio::join!(dispatch, resume)
+ })
+ .await
+ .unwrap();
+ result.unwrap();
+ assert_eq!(
+ prompts(&container.agent()),
+ [vec![ContentBlock::from(context_prompt("first"))]]
+ );
+ assert_eq!(service.inner.busy.turn(id).unwrap().action_id, ids[0]);
+ let remaining = repo.list_queued_actions(id).await.unwrap();
+ assert_eq!(remaining.len(), 1);
+ assert_eq!(remaining[0].action_id, ids[1]);
+ assert_eq!(service.inner.announcer.announced().len(), 1);
+ assert!(service.inner.announcer.resolved().is_empty());
+}
+
+#[tokio::test]
+async fn rejection_persistence_failure_keeps_work_and_defers_reply_resolution() {
+ use crate::domain::queue::QueuedEntry;
+ use agent_session::domain::service::MockAgentSessionService;
+
+ for reload_fails in [false, true] {
+ let id = AgentSessionId::new();
+ let command = forward_message("keep until the rejection is durable");
+ let entry = QueuedEntry {
+ action_id: command.id,
+ action: command.action,
+ actor: command.actor,
+ announce: command.announce,
+ announced: Some(macro_uuid::generate_uuid_v7()),
+ created_at: chrono::Utc::now(),
+ };
+ let stored = entry.to_stored().unwrap();
+ let mut sessions = MockAgentSessionService::new();
+ sessions
+ .expect_replace_queued_actions()
+ .times(2)
+ .returning(|_, entries| {
+ assert!(entries.is_empty());
+ Box::pin(async {
+ Err(AgentSessionError::Unknown(anyhow::anyhow!(
+ "write unavailable"
+ )))
+ })
+ });
+ sessions
+ .expect_list_queued_actions()
+ .times(2)
+ .returning(move |_| {
+ let stored = stored.clone();
+ Box::pin(async move {
+ if reload_fails {
+ Err(AgentSessionError::Unknown(anyhow::anyhow!(
+ "read unavailable"
+ )))
+ } else {
+ Ok(vec![stored])
+ }
+ })
+ });
+ let service = AgentHarnessService::new(
+ sessions,
+ MockContainerManager::new(),
+ AnnouncerMock::new(),
+ TestConnections::new(MirrorBindings, RuntimeRegistry::new()),
+ PromptContextMock::default(),
+ PromptComposerMock::default(),
+ EgressProvisionerMock::new(),
+ NoPeers,
+ KindDefaultPolicies,
+ HarnessDefaultCodingAgents,
+ HarnessDefaults::new(SessionDefaults {
+ bot_id: BotId::TEST_A,
+ model: "model".into(),
+ harness: "in-memory".into(),
+ repo_url: None,
+ }),
+ RecordingLifecyclePublisher::new(),
+ crate::domain::pending::PendingCommands::new(),
+ PromptMentionsMock::new(),
+ NotifierMock::new(),
+ );
+ service.inner.queues.enqueue(id, entry.clone()).unwrap();
+ service.inner.busy.admit(id);
+ for _ in 0..2 {
+ assert!(matches!(
+ service
+ .inner
+ .reject_waiting_on_denial(id, &HarnessError::Admission(denied()))
+ .await,
+ Err(HarnessError::Session(AgentSessionError::Unknown(_)))
+ ));
+ assert!(!service.inner.busy.is_pending(id));
+ let waiting = service.inner.queues.snapshot(id);
+ assert_eq!(waiting.len(), 1);
+ assert_eq!(waiting[0].action_id, entry.action_id);
+ assert_eq!(waiting[0].announced, entry.announced);
+ assert!(service.inner.lifecycle_publisher.published().is_empty());
+ assert!(service.inner.announcer.resolved().is_empty());
+ }
+ }
+}
+
+#[test]
+fn admission_errors_keep_the_session_error_classification() {
+ for failure in [denied(), AiAdmissionError::Unavailable] {
+ assert!(
+ matches!(into_session_error(HarnessError::Admission(failure)),
+ AgentSessionError::Admission(error) if error == failure)
+ );
+ }
+}
diff --git a/crates/agent_harness/src/outbound/cursor/manager.rs b/crates/agent_harness/src/outbound/cursor/manager.rs
index 70a8b8279a..3563b0b69d 100644
--- a/crates/agent_harness/src/outbound/cursor/manager.rs
+++ b/crates/agent_harness/src/outbound/cursor/manager.rs
@@ -161,6 +161,7 @@ pub struct CursorContainerManager<Sessions, Keys, Repositories, Store> {
sessions: Sessions,
repositories: Arc<Repositories>,
usage: Arc<dyn ai_usage::UsageRecorder>,
+ admission: Arc<dyn ai_billing::AiAdmissionService>,
pull_requests: Option<Arc<dyn agent_session::domain::pull_request::SessionPullRequests>>,
working_branches:
Option<Arc<dyn agent_session::domain::working_branch::SessionWorkingBranches>>,
@@ -234,6 +235,7 @@ where
sessions,
repositories,
usage,
+ admission: Arc::new(ai_billing::DisabledAiAdmissionService),
pull_requests: None,
working_branches: None,
journal_storage: JournalStorage::Postgres {
@@ -261,6 +263,7 @@ where
sessions: self.sessions,
repositories: self.repositories,
usage: self.usage,
+ admission: self.admission,
pull_requests: self.pull_requests,
working_branches: self.working_branches,
journal_storage: self.journal_storage,
@@ -292,6 +295,7 @@ where
sessions,
repositories,
usage: Arc::new(ai_usage::NoOpUsageRecorder),
+ admission: Arc::new(ai_billing::DisabledAiAdmissionService),
pull_requests: None,
working_branches: None,
journal_storage: JournalStorage::Memory,
@@ -299,6 +303,12 @@ where
}
}
+ /// Configure admission for Macro-funded helpers, not the owner's Cursor runtime.
+ pub fn with_admission(mut self, admission: Arc<dyn ai_billing::AiAdmissionService>) -> Self {
+ self.admission = admission;
+ self
+ }
+
/// Persist Cursor's returned PR using the shared session operation.
pub fn with_pull_requests(
mut self,
@@ -444,10 +454,11 @@ where
},
));
}
- let chooser = HaikuRepositoryChooser::new(
+ let chooser = crate::domain::repository_choice::RepositoryChoiceService::new(
Arc::clone(&self.repositories),
self.sessions.clone(),
- Arc::clone(&self.usage),
+ HaikuRepositoryChooser::new(Arc::clone(&self.usage)),
+ Arc::clone(&self.admission),
owner,
session_id,
);
diff --git a/crates/agent_harness/src/outbound/cursor/repository_chooser.rs b/crates/agent_harness/src/outbound/cursor/repository_chooser.rs
index 14f7377970..c363b7a5b4 100644
--- a/crates/agent_harness/src/outbound/cursor/repository_chooser.rs
+++ b/crates/agent_harness/src/outbound/cursor/repository_chooser.rs
@@ -1,54 +1,24 @@
-//! Deciding which repository a Cursor session's first prompt belongs to.
-//!
-//! A hosted session has no checkout to read a remote from: it is opened from a
-//! chat message, and the only evidence for where its work belongs is the prompt
-//! itself, the repositories its owner can reach through Macro's GitHub App, and
-//! what that person has been working on lately. So a fast model reads the three
-//! together and picks one candidate.
-//!
-//! Every hosted coding session needs a repository. Ambiguous prompts fall back
-//! to the owner's most recent accessible repository, or the first candidate
-//! when there is no accessible repository in their history.
-//!
-//! The choice is written back to the session row before the agent is minted:
-//! the egress proxy pins the sandbox's git traffic to that column, so a
-//! repository the row does not name is a repository the session cannot reach.
+//! Fast-model implementation of the repository-choice capability.
-use std::num::NonZeroUsize;
use std::sync::Arc;
use agent::structured_output::{DynamicSchema, dynamic_structured_completion};
use agent::{Message, PredefinedModel};
-use agent_session::domain::model::{AgentSession, AgentSessionId};
-use agent_session::domain::ports::AgentSessionRepo;
-use cursor_cloud_agents::domain::model::RepoUrl;
-use cursor_cloud_agents::domain::ports::{RepositoryChooser, SessionIntent};
-use macro_user_id::user_id::MacroUserIdStr;
+use agent_session::domain::model::AgentSession;
+use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};
use serde::Deserialize;
use serde_json::json;
-use crate::domain::ports::ReachableRepositories;
-use crate::domain::repository_selection::{fallback_repository, intent, recent_repository};
+use crate::domain::repository_choice::{RECENT_SESSIONS, RepositoryChoiceModel};
#[cfg(test)]
mod test;
-/// How many of the owner's recent sessions the prompt describes.
-///
-/// Enough to show what someone is in the middle of, few enough that a single
-/// stale session cannot outvote the prompt itself.
-const RECENT_SESSIONS: usize = 5;
-
static SYSTEM_PROMPT: &str = include_str!("repository_chooser/system_prompt.md");
-/// A [`RepositoryChooser`] that reads the prompt with the fast model.
-pub struct HaikuRepositoryChooser<Repositories, Sessions> {
- repositories: Arc<Repositories>,
- sessions: Sessions,
+/// Reads the prompt with the fast model after the domain service admits the work.
+pub struct HaikuRepositoryChooser {
recorder: Arc<dyn ai_usage::UsageRecorder>,
- owner: MacroUserIdStr<'static>,
- session_id: AgentSessionId,
- model: PredefinedModel,
}
/// The model's answer.
@@ -59,108 +29,33 @@ struct ChoiceOutput {
_reason: String,
}
-impl<Repositories, Sessions> HaikuRepositoryChooser<Repositories, Sessions>
-where
- Repositories: ReachableRepositories,
- Sessions: AgentSessionRepo,
-{
- /// Build a chooser for one session, on behalf of its owner.
- pub fn new(
- repositories: Arc<Repositories>,
- sessions: Sessions,
- recorder: Arc<dyn ai_usage::UsageRecorder>,
- owner: MacroUserIdStr<'static>,
- session_id: AgentSessionId,
- ) -> Self {
- Self {
- repositories,
- sessions,
- recorder,
- owner,
- session_id,
- model: PredefinedModel::Fast,
- }
- }
-
- /// Repositories this owner can reach through Macro's GitHub App.
- #[tracing::instrument(
- name = "agent.repository_choice.reachable_repositories",
- skip_all,
- err,
- fields(agent.session.id = %self.session_id)
- )]
- async fn reachable_repositories(&self) -> Result<Vec<String>, rootcause::Report> {
- // The model chooses between urls: they are what the session row is
- // pinned to, and a candidate's default branch is no help in deciding
- // which repository a prompt belongs to.
- Ok(self
- .repositories
- .for_user(&self.owner)
- .await
- .map_err(|error| rootcause::report!("could not list reachable repositories: {error}"))?
- .into_iter()
- .map(|repository| repository.url)
- .collect())
- }
-
- /// Recent sessions through the newest accessible repository, excluding this session.
- #[tracing::instrument(
- name = "agent.repository_choice.recent_sessions",
- skip_all,
- err,
- fields(agent.session.id = %self.session_id)
- )]
- async fn recent_sessions(
- &self,
- candidates: &[String],
- ) -> Result<Vec<AgentSession>, rootcause::Report> {
- let mut limit = RECENT_SESSIONS + 1;
- loop {
- let recent = self
- .sessions
- .recent_for_owner(
- &self.owner,
- NonZeroUsize::new(limit).expect("a nonzero count"),
- )
- .await
- .map_err(|error| {
- rootcause::report!("could not read the owner's recent sessions: {error}")
- })?;
- let exhausted = recent.len() < limit;
- let recent: Vec<_> = recent
- .into_iter()
- .filter(|session| session.id != self.session_id)
- .collect();
- if exhausted || recent_repository(candidates, &recent).is_some() {
- return Ok(recent);
- }
- // Look past recent chat-only sessions for the last accessible repo.
- limit = limit.checked_mul(2).ok_or_else(|| {
- rootcause::report!("too many sessions to find a recent repository")
- })?;
- }
+impl HaikuRepositoryChooser {
+ /// Build a model capability with usage recording.
+ pub fn new(recorder: Arc<dyn ai_usage::UsageRecorder>) -> Self {
+ Self { recorder }
}
+}
- /// Ask the model, and hold it to the candidate list.
+impl RepositoryChoiceModel for HaikuRepositoryChooser {
#[tracing::instrument(
name = "agent.repository_choice.decide",
skip_all,
err,
fields(
- agent.session.id = %self.session_id,
agent.repository_choice.candidate_count = candidates.len(),
agent.repository_choice.recent_session_count = recent.len(),
)
)]
async fn decide(
&self,
+ owner: &MacroUserIdStr<'_>,
prompt: &str,
candidates: &[String],
recent: &[AgentSession],
- ) -> Result<SessionIntent, rootcause::Report> {
- let fallback = fallback_repository(candidates, recent)?;
+ fallback: &str,
+ ) -> Result<String, rootcause::Report> {
let value = dynamic_structured_completion(
- self.model,
+ PredefinedModel::Fast,
SYSTEM_PROMPT,
vec![Message::user(user_message(
prompt, candidates, recent, fallback,
@@ -169,7 +64,7 @@ where
self.recorder.as_ref(),
ai_usage::UsageContext::new(
ai_usage::AiFeature::AgentRepositoryChoice,
- self.owner.clone(),
+ owner.clone().into_owned(),
),
)
.await
@@ -177,89 +72,7 @@ where
let output: ChoiceOutput = serde_json::from_value(value)
.map_err(|error| rootcause::report!("repository choice is not the schema: {error}"))?;
- intent(candidates, &output.repository)
- }
-}
-
-impl<Repositories, Sessions> RepositoryChooser for HaikuRepositoryChooser<Repositories, Sessions>
-where
- Repositories: ReachableRepositories,
- Sessions: AgentSessionRepo,
-{
- #[tracing::instrument(
- name = "agent.repository_choice",
- skip_all,
- err,
- fields(
- agent.session.id = %self.session_id,
- agent.repository_choice.candidate_count = tracing::field::Empty,
- agent.repository_choice.recent_session_count = tracing::field::Empty,
- agent.repository_choice.outcome = tracing::field::Empty,
- )
- )]
- async fn choose(
- &self,
- prompt: &str,
- _cwd: &std::path::Path,
- ) -> Result<SessionIntent, rootcause::Report> {
- // A caller-selected repository was authorized by the opening service.
- // Keep that choice on retries and resumes instead of asking a model to replace it.
- let session =
- self.sessions.get(self.session_id).await.map_err(|error| {
- rootcause::report!("could not read selected repository: {error}")
- })?;
- if session.repo_branch.is_some()
- && let Some(url) = session.repo_url.as_deref()
- {
- let repository = RepoUrl::parse(url)
- .ok_or_else(|| rootcause::report!("invalid selected repository"))?;
- return Ok(SessionIntent {
- repository: Some(repository),
- open_pull_request: true,
- });
- }
- let mut had_candidates = false;
- let result = async {
- let candidates = self.reachable_repositories().await?;
- had_candidates = !candidates.is_empty();
- tracing::Span::current()
- .record("agent.repository_choice.candidate_count", candidates.len());
-
- let fallback = fallback_repository(&candidates, &[])?;
- let chosen = if candidates.len() == 1 {
- intent(&candidates, fallback)?
- } else {
- let recent = self.recent_sessions(&candidates).await?;
- tracing::Span::current()
- .record("agent.repository_choice.recent_session_count", recent.len());
- self.decide(prompt, &candidates, &recent).await?
- };
-
- // Before the agent is minted, because the row is what the egress proxy
- // pins git traffic to.
- self.sessions
- .set_repo_url(
- self.session_id,
- chosen.repository.as_ref().map(ToString::to_string),
- )
- .await
- .map_err(|error| {
- rootcause::report!("could not record the session's repository: {error}")
- })?;
-
- Ok(chosen)
- }
- .await;
-
- tracing::Span::current().record(
- "agent.repository_choice.outcome",
- match &result {
- Ok(_) => "selected",
- Err(_) if !had_candidates => "no_candidates",
- Err(_) => "failed",
- },
- );
- result
+ Ok(output.repository)
}
}
@@ -297,10 +110,7 @@ fn user_message(
message
}
-/// The output schema, with the candidate urls as the only allowed answers.
-///
-/// Constraining the enum rather than only validating afterwards: a model that
-/// cannot express an invented repository mostly does not try to.
+/// Constrain the model to authorized candidates rather than only validating afterwards.
fn choice_schema(candidates: &[String]) -> DynamicSchema {
let allowed: Vec<serde_json::Value> = candidates
.iter()
diff --git a/crates/agent_harness/src/outbound/cursor/repository_chooser/test.rs b/crates/agent_harness/src/outbound/cursor/repository_chooser/test.rs
index 1d8c8b322c..965dc30040 100644
--- a/crates/agent_harness/src/outbound/cursor/repository_chooser/test.rs
+++ b/crates/agent_harness/src/outbound/cursor/repository_chooser/test.rs
@@ -1,46 +1,4 @@
use super::*;
-use agent_session::domain::ports::MockAgentSessionRepo;
-use std::sync::Mutex;
-
-/// A canned listing, with what it was asked for recorded.
-struct StubRepositories {
- repositories: Vec<String>,
- asked_for: Mutex<Vec<String>>,
-}
-
-impl StubRepositories {
- fn with(repositories: &[&str]) -> Arc<Self> {
- Arc::new(Self {
- repositories: repositories.iter().map(|url| (*url).to_owned()).collect(),
- asked_for: Mutex::new(Vec::new()),
- })
- }
-}
-
-#[async_trait::async_trait]
-impl ReachableRepositories for StubRepositories {
- async fn for_user(
- &self,
- user: &MacroUserIdStr<'_>,
- ) -> crate::domain::error::Result<Vec<crate::domain::model::ReachableRepository>> {
- self.asked_for
- .lock()
- .expect("stub poisoned")
- .push(user.to_string());
- Ok(self
- .repositories
- .iter()
- .map(|url| crate::domain::model::ReachableRepository {
- url: url.clone(),
- default_branch: Some("main".to_owned()),
- })
- .collect())
- }
-}
-
-fn owner() -> MacroUserIdStr<'static> {
- MacroUserIdStr::try_from("macro|[email protected]".to_owned()).expect("a valid user id")
-}
fn candidates() -> Vec<String> {
vec![
@@ -49,40 +7,6 @@ fn candidates() -> Vec<String> {
]
}
-/// A coding session cannot start without access to a repository.
-#[tokio::test]
-async fn no_reachable_repository_fails_without_asking_the_model() {
- let session_id = AgentSessionId::new();
- let mut sessions = MockAgentSessionRepo::new();
- sessions.expect_get().returning(|id| {
- Box::pin(async move { Ok(agent_session::testing::test_agent_session(id)) })
- });
- sessions.expect_recent_for_owner().never();
- sessions.expect_set_repo_url().never();
-
- let repositories = StubRepositories::with(&[]);
- let chooser = HaikuRepositoryChooser::new(
- Arc::clone(&repositories),
- sessions,
- Arc::new(ai_usage::NoOpUsageRecorder),
- owner(),
- session_id,
- );
-
- let error = chooser
- .choose("fix the login button", std::path::Path::new(""))
- .await
- .expect_err("GitHub access is required");
- assert!(error.to_string().contains("Connect GitHub"));
- assert_eq!(
- repositories.asked_for.lock().expect("stub poisoned").len(),
- 1,
- "the listing is read once, for the session's owner"
- );
-}
-
-/// The prompt sections are what the model reads; an empty history says so
-/// rather than leaving the section blank for it to interpret.
#[test]
fn the_user_message_carries_candidates_recent_sessions_and_the_prompt() {
let message = user_message("rename the button", &candidates(), &[], &candidates()[0]);
@@ -94,176 +18,11 @@ fn the_user_message_carries_candidates_recent_sessions_and_the_prompt() {
));
}
-/// The model cannot express a repository the user does not reach.
#[test]
fn the_schema_allows_only_candidate_repositories() {
let schema = choice_schema(&candidates());
- let allowed = schema.schema["properties"]["repository"]["enum"]
- .as_array()
- .expect("an enum of allowed answers")
- .clone();
- assert_eq!(
- allowed,
- vec![
- serde_json::json!("https://github.com/macro-inc/macro"),
- serde_json::json!("https://github.com/macro-inc/infra"),
- ]
- );
-}
-
-#[tokio::test]
-async fn history_excludes_the_current_session_without_crowding_out_prior_work() {
- let current = AgentSessionId::new();
- let mut sessions = MockAgentSessionRepo::new();
- let prior: Vec<_> = (0..5).map(|_| AgentSessionId::new()).collect();
- let expected = prior.clone();
- sessions
- .expect_recent_for_owner()
- .once()
- .withf(|_, limit| limit.get() == 6)
- .return_once(move |_, _| {
- Box::pin(async move {
- Ok(std::iter::once(current)
- .chain(prior)
- .map(|id| AgentSession {
- repo_branch: None,
- id,
- name: "session".into(),
- harness: "cursor".into(),
- repo_url: Some("https://github.com/macro-inc/macro".into()),
- ..agent_session::testing::test_agent_session(id)
- })
- .collect())
- })
- });
- let chooser = HaikuRepositoryChooser::new(
- StubRepositories::with(&[]),
- sessions,
- Arc::new(ai_usage::NoOpUsageRecorder),
- owner(),
- current,
- );
- let recent = chooser.recent_sessions(&candidates()).await.unwrap();
- assert_eq!(
- recent.iter().map(|session| session.id).collect::<Vec<_>>(),
- expected
- );
-}
-
-#[tokio::test]
-async fn explicit_repository_bypasses_automatic_selection() {
- let session_id = AgentSessionId::new();
- let mut sessions = MockAgentSessionRepo::new();
- sessions.expect_get().returning(|id| {
- Box::pin(async move {
- let mut session = agent_session::testing::test_agent_session(id);
- session.repo_url = Some("https://github.com/macro-inc/infra".into());
- session.repo_branch = Some(
- agent_session::domain::repository_branch::RepositoryBranch::parse(
- "feature/home".into(),
- )
- .unwrap(),
- );
- Ok(session)
- })
- });
- sessions.expect_set_repo_url().never();
- sessions.expect_recent_for_owner().never();
- let repositories = StubRepositories::with(&[]);
- let chooser = HaikuRepositoryChooser::new(
- Arc::clone(&repositories),
- sessions,
- Arc::new(ai_usage::NoOpUsageRecorder),
- owner(),
- session_id,
- );
- let result = chooser
- .choose("fix home", std::path::Path::new(""))
- .await
- .unwrap();
- assert_eq!(
- result.repository.as_ref().map(RepoUrl::as_str),
- Some("https://github.com/macro-inc/infra")
- );
- assert!(repositories.asked_for.lock().unwrap().is_empty());
-}
-
-#[tokio::test]
-async fn a_single_repository_is_selected_without_a_model_call() {
- let session_id = AgentSessionId::new();
- let mut sessions = MockAgentSessionRepo::new();
- sessions.expect_get().returning(|id| {
- Box::pin(async move { Ok(agent_session::testing::test_agent_session(id)) })
- });
- sessions.expect_recent_for_owner().never();
- sessions
- .expect_set_repo_url()
- .once()
- .withf(|_, url| url.as_deref() == Some("https://github.com/macro-inc/macro"))
- .return_once(|_, _| Box::pin(async { Ok(()) }));
- let chooser = HaikuRepositoryChooser::new(
- StubRepositories::with(&["https://github.com/macro-inc/macro"]),
- sessions,
- Arc::new(ai_usage::NoOpUsageRecorder),
- owner(),
- session_id,
- );
- assert!(
- chooser
- .choose("explain this code", std::path::Path::new(""))
- .await
- .unwrap()
- .repository
- .is_some()
- );
-}
-
-#[tokio::test]
-async fn history_searches_past_recent_sessions_without_repositories() {
- let mut sessions = MockAgentSessionRepo::new();
- sessions
- .expect_recent_for_owner()
- .once()
- .withf(|_, limit| limit.get() == 6)
- .return_once(|_, _| {
- Box::pin(async {
- Ok((0..6)
- .map(|_| {
- let mut session =
- agent_session::testing::test_agent_session(AgentSessionId::new());
- session.repo_url = None;
- session
- })
- .collect())
- })
- });
- sessions
- .expect_recent_for_owner()
- .once()
- .withf(|_, limit| limit.get() == 12)
- .return_once(|_, _| {
- Box::pin(async {
- Ok((0..7)
- .map(|i| {
- let mut session =
- agent_session::testing::test_agent_session(AgentSessionId::new());
- session.repo_url =
- (i == 6).then(|| "https://github.com/macro-inc/infra".into());
- session
- })
- .collect())
- })
- });
- let chooser = HaikuRepositoryChooser::new(
- StubRepositories::with(&[]),
- sessions,
- Arc::new(ai_usage::NoOpUsageRecorder),
- owner(),
- AgentSessionId::new(),
- );
- let recent = chooser.recent_sessions(&candidates()).await.unwrap();
assert_eq!(
- fallback_repository(&candidates(), &recent).unwrap(),
- "https://github.com/macro-inc/infra"
+ schema.schema["properties"]["repository"]["enum"],
+ json!(candidates()),
);
}
diff --git a/crates/agent_inmem/Cargo.toml b/crates/agent_inmem/Cargo.toml
index ddd2f525f3..5f7b1630c1 100644
--- a/crates/agent_inmem/Cargo.toml
+++ b/crates/agent_inmem/Cargo.toml
@@ -5,6 +5,7 @@ publish = false
version = "0.1.0"
[dependencies]
+ai_billing = { path = "../ai_billing" }
agent = { path = "../agent" }
# The egress proxy's domain service, driven in-process: the same verification,
# resolution and stamping a sandbox reaches over the wire, minus the wire.
diff --git a/crates/agent_inmem/src/domain/admission.rs b/crates/agent_inmem/src/domain/admission.rs
new file mode 100644
index 0000000000..a9992846c2
--- /dev/null
+++ b/crates/agent_inmem/src/domain/admission.rs
@@ -0,0 +1,19 @@
+//! Admission for provider-backed turns, independent of the ACP transport.
+
+use ai_billing::domain::{AiAdmissionError, AiAdmissionService};
+use ai_usage::AiFeature;
+use model_owner::Owner;
+
+#[cfg(test)]
+mod test;
+
+/// Admit a new turn using the trusted session owner, never client metadata.
+/// Non-user owners cannot run this runtime's user-scoped tools or be billed;
+/// fail closed rather than substituting a system identity.
+pub async fn admit_turn(
+ admission: &dyn AiAdmissionService,
+ owner: &Owner,
+) -> Result<(), AiAdmissionError> {
+ let user = owner.as_user().ok_or(AiAdmissionError::Unavailable)?;
+ admission.admit(user, AiFeature::AgentSession).await
+}
diff --git a/crates/agent_inmem/src/domain/admission/test.rs b/crates/agent_inmem/src/domain/admission/test.rs
new file mode 100644
index 0000000000..be3b3707d1
--- /dev/null
+++ b/crates/agent_inmem/src/domain/admission/test.rs
@@ -0,0 +1,40 @@
+use super::*;
+use crate::testing::TestAdmission;
+use ai_billing::domain::{DenyReason, DisabledAiAdmissionService};
+use macro_user_id::user_id::MacroUserIdStr;
+
+#[tokio::test]
+async fn turns_use_the_trusted_owner_and_agent_session_feature() {
+ let owner = Owner::User(MacroUserIdStr::try_from_email("[email protected]").unwrap());
+ for result in [
+ Ok(()),
+ Err(AiAdmissionError::Denied(DenyReason::AllowanceExhausted)),
+ Err(AiAdmissionError::Unavailable),
+ ] {
+ let admission = TestAdmission::new(result);
+ assert_eq!(admit_turn(&admission, &owner).await, result);
+ assert_eq!(
+ *admission.calls.lock().unwrap(),
+ vec![("macro|[email protected]".to_owned(), AiFeature::AgentSession)]
+ );
+ }
+ assert_eq!(
+ admit_turn(&DisabledAiAdmissionService, &owner).await,
+ Ok(())
+ );
+}
+
+#[tokio::test]
+async fn unsupported_owners_are_not_substituted_with_system_identity() {
+ let admission = TestAdmission::new(Ok(()));
+ for owner in [
+ Owner::Bot(bot_id::BotId::TEST_A),
+ Owner::Team(macro_uuid::generate_uuid_v7()),
+ ] {
+ assert_eq!(
+ admit_turn(&admission, &owner).await,
+ Err(AiAdmissionError::Unavailable)
+ );
+ }
+ assert!(admission.calls.lock().unwrap().is_empty());
+}
diff --git a/crates/agent_inmem/src/domain/agent.rs b/crates/agent_inmem/src/domain/agent.rs
index f298129641..124d586957 100644
--- a/crates/agent_inmem/src/domain/agent.rs
+++ b/crates/agent_inmem/src/domain/agent.rs
@@ -34,6 +34,7 @@ use agent_client_protocol::{
};
use agent_runtime_protocol::domain::action::MODEL_CONFIG_ID;
use agent_session::domain::model::AgentSessionId;
+use ai_billing::domain::{AiAdmissionError, AiAdmissionService};
use ai_tools::user_tool_review::{
ReviewError, ReviewFieldKind, ReviewForm, ReviewOutcome, ReviewRequest, UserToolReviewer,
};
@@ -42,6 +43,7 @@ use model_owner::Owner;
use tokio_util::sync::CancellationToken;
use tracing::Instrument as _;
+use crate::domain::admission::admit_turn;
use crate::domain::engine::{AgentIdentity, TurnEngine, TurnRequest};
use crate::domain::mcp::{DynMcpToolConnector, dialable_servers};
use crate::domain::model_options::REASONING_EFFORT_CONFIG_ID;
@@ -111,6 +113,8 @@ pub struct AgentState {
pub owner: Owner,
/// Runs the actual turns.
pub engine: Arc<dyn TurnEngine>,
+ /// Admission for new provider-backed turns, including direct ACP requests.
+ pub admission: Arc<dyn AiAdmissionService>,
/// Conversation state, shared with the manager so it survives reattach.
pub store: Arc<SessionStore>,
/// Every outstanding turn's cancellation token - the running turn and any
@@ -625,13 +629,22 @@ pub async fn serve(state: Arc<AgentState>, acp: AcpChannel) -> Result<(), AcpErr
connection.spawn({
let connection = connection.clone();
async move {
- let stop =
+ let result =
run_turn(&state, &connection, request.session_id, prompt, cancel)
.await;
- // A closed connection is the only way this fails,
- // and failing the spawned task would tear the
- // whole (already closing) server down.
- let _ = responder.respond(PromptResponse::new(stop));
+ // A closed connection is the only way responding fails.
+ // Admission failure must not tear down resumable state.
+ let _ = match result {
+ Ok(stop) => responder.respond(PromptResponse::new(stop)),
+ Err(error) => responder.respond_with_error(
+ AcpError::new(-32603, error.to_string()).data(
+ serde_json::json!({
+ "code": error.code(),
+ "retryable": error.is_retryable(),
+ }),
+ ),
+ ),
+ };
Ok(())
}
.instrument(span)
@@ -724,8 +737,22 @@ async fn run_turn(
acp_session_id: SessionId,
prompt: UserPrompt,
cancel: CancellationToken,
-) -> StopReason {
- let _turn = state.turn_lock.lock().await;
+) -> Result<StopReason, AiAdmissionError> {
+ // Mark every exit (including denial or a dropped connection) complete so
+ // cancelled/failed requests do not remain outstanding.
+ let _completed = cancel.clone().drop_guard();
+ let _turn = tokio::select! {
+ biased;
+ _ = cancel.cancelled() => return Ok(StopReason::Cancelled),
+ turn = state.turn_lock.lock() => turn,
+ };
+ // Check at execution time, not enqueue time. Cancellation stays responsive
+ // even if billing is slow, and neither denial nor cancellation adds history.
+ tokio::select! {
+ biased;
+ _ = cancel.cancelled() => return Ok(StopReason::Cancelled),
+ result = admit_turn(state.admission.as_ref(), &state.owner) => result?,
+ }
let TurnInput {
messages,
model,
@@ -811,9 +838,9 @@ async fn run_turn(
state.push_turn(prompt, turn_parts);
if was_cancelled || cancel.is_cancelled() {
- StopReason::Cancelled
+ Ok(StopReason::Cancelled)
} else {
- StopReason::EndTurn
+ Ok(StopReason::EndTurn)
}
}
diff --git a/crates/agent_inmem/src/domain/agent/test.rs b/crates/agent_inmem/src/domain/agent/test.rs
index 0078deffd5..a4b169f66e 100644
--- a/crates/agent_inmem/src/domain/agent/test.rs
+++ b/crates/agent_inmem/src/domain/agent/test.rs
@@ -8,12 +8,15 @@ use agent_client_protocol::schema::v1::{
SessionConfigValueId, SessionNotification, SetSessionConfigOptionRequest, TextContent,
};
use agent_client_protocol::{Client, ConnectionTo};
+use ai_billing::domain::{
+ AiAdmissionError, AiAdmissionService, DenyReason, DisabledAiAdmissionService,
+};
use rig_agent::agent::StreamingError;
use rig_agent::completion::PromptError;
use super::*;
use crate::domain::engine::TurnEngine;
-use crate::testing::{HangingEngine, ScriptedEngine};
+use crate::testing::{HangingEngine, ScriptedEngine, TestAdmission};
use macro_user_id::user_id::MacroUserIdStr;
struct Harness {
@@ -54,6 +57,19 @@ async fn with_agent<Engine, Out>(
where
Engine: TurnEngine,
{
+ with_admission(
+ engine,
+ Arc::new(DisabledAiAdmissionService),
+ async |connection, session, _| scenario(connection, session).await,
+ )
+ .await
+}
+
+async fn with_admission<Engine: TurnEngine, Out>(
+ engine: Arc<Engine>,
+ admission: Arc<dyn AiAdmissionService>,
+ scenario: impl AsyncFnOnce(ConnectionTo<Agent>, SessionId, Arc<AgentState>) -> Out,
+) -> (Vec<SessionNotification>, Vec<SessionConfigOption>, Out) {
let store = Arc::new(SessionStore::new());
let session_id = AgentSessionId::new();
store.insert(
@@ -66,6 +82,7 @@ where
MacroUserIdStr::try_from_email("[email protected]").expect("a valid user id"),
),
engine,
+ admission,
store,
active_cancel: std::sync::Mutex::new(Vec::new()),
turn_lock: tokio::sync::Mutex::new(()),
@@ -76,7 +93,7 @@ where
});
let (client_channel, agent_channel) = AcpChannel::duplex();
- let agent = tokio::spawn(serve(state, agent_channel));
+ let agent = tokio::spawn(serve(Arc::clone(&state), agent_channel));
let harness = Arc::new(Harness {
notifications: std::sync::Mutex::new(Vec::new()),
@@ -122,7 +139,7 @@ where
.send_request(NewSessionRequest::new("/"))
.block_task()
.await?;
- let out = scenario(connection, session.session_id).await;
+ let out = scenario(connection, session.session_id, state).await;
Ok((session.config_options, out))
},
)
@@ -145,6 +162,246 @@ fn text_prompt(session: &SessionId, text: &str) -> PromptRequest {
)
}
+#[tokio::test]
+async fn direct_acp_denials_preserve_history_and_allow_retry() {
+ for failure in [
+ AiAdmissionError::Denied(DenyReason::AllowanceExhausted),
+ AiAdmissionError::Unavailable,
+ ] {
+ let engine = Arc::new(ScriptedEngine::new(vec![StreamPart::Content(
+ "reply".into(),
+ )]));
+ let admission = Arc::new(TestAdmission::new(Ok(())));
+ with_admission(
+ engine.clone(),
+ admission.clone(),
+ async |connection, session, state| {
+ connection
+ .send_request(text_prompt(&session, "first"))
+ .block_task()
+ .await
+ .unwrap();
+ *admission.result.lock().unwrap() = Err(failure);
+ let error = connection
+ .send_request(text_prompt(&session, "denied"))
+ .block_task()
+ .await
+ .unwrap_err();
+ let error = serde_json::to_value(error).unwrap();
+ assert_eq!(error["message"], failure.to_string());
+ assert_eq!(error["data"]["code"], failure.code());
+ assert_eq!(error["data"]["retryable"], failure.is_retryable());
+ assert_eq!(engine.requests().len(), 1);
+ assert_eq!(state.store.get(&state.session_id).unwrap().history.len(), 2);
+ assert!(
+ state
+ .active_cancel
+ .lock()
+ .unwrap()
+ .iter()
+ .all(CancellationToken::is_cancelled)
+ );
+
+ // Loading and deterministic configuration still work with exhausted quota.
+ connection
+ .send_request(ResumeSessionRequest::new(session.clone(), "/"))
+ .block_task()
+ .await
+ .unwrap();
+ connection
+ .send_request(SetSessionConfigOptionRequest::new(
+ session.clone(),
+ MODEL_CONFIG_ID,
+ SessionConfigValueId::new("other-model"),
+ ))
+ .block_task()
+ .await
+ .unwrap();
+ assert_eq!(admission.calls.lock().unwrap().len(), 2);
+ *admission.result.lock().unwrap() = Ok(());
+ connection
+ .send_request(text_prompt(&session, "retry"))
+ .block_task()
+ .await
+ .unwrap();
+ },
+ )
+ .await;
+ assert_eq!(engine.requests()[1].messages, ["first", "reply", "retry"]);
+ assert_eq!(engine.requests()[1].model, "other-model");
+ assert!(
+ admission
+ .calls
+ .lock()
+ .unwrap()
+ .iter()
+ .all(|(user, feature)| user == "macro|[email protected]"
+ && *feature == ai_usage::AiFeature::AgentSession)
+ );
+ }
+}
+
+#[tokio::test]
+async fn deterministic_commands_skip_admission_but_provider_commands_do_not() {
+ let engine = Arc::new(ScriptedEngine::new(vec![]));
+ let admission = Arc::new(TestAdmission::new(Err(AiAdmissionError::Unavailable)));
+ with_admission(
+ engine.clone(),
+ admission.clone(),
+ async |connection, session, _| {
+ for command in ["/compact", "/ask choose | a | b"] {
+ connection
+ .send_request(text_prompt(&session, command))
+ .block_task()
+ .await
+ .unwrap();
+ }
+ assert!(admission.calls.lock().unwrap().is_empty());
+ // Unknown/development command text that reaches the provider is still gated.
+ connection
+ .send_request(text_prompt(&session, "/develop something"))
+ .block_task()
+ .await
+ .unwrap_err();
+ assert_eq!(admission.calls.lock().unwrap().len(), 1);
+ },
+ )
+ .await;
+ assert!(engine.requests().is_empty());
+}
+
+#[tokio::test]
+async fn queued_turns_check_admission_only_when_they_can_execute() {
+ let engine = Arc::new(ScriptedEngine::new(vec![]));
+ let admission = Arc::new(TestAdmission::new(Ok(())));
+ with_admission(
+ engine.clone(),
+ admission.clone(),
+ async |connection, session, state| {
+ let lock = state.turn_lock.lock().await;
+ let prompt = connection.send_request(text_prompt(&session, "queued"));
+ tokio::time::timeout(Duration::from_secs(5), async {
+ while state.active_cancel.lock().unwrap().is_empty() {
+ tokio::task::yield_now().await;
+ }
+ })
+ .await
+ .unwrap();
+ assert!(admission.calls.lock().unwrap().is_empty());
+ *admission.result.lock().unwrap() = Err(AiAdmissionError::Unavailable);
+ drop(lock);
+ prompt.block_task().await.unwrap_err();
+ assert!(
+ state
+ .store
+ .get(&state.session_id)
+ .unwrap()
+ .history
+ .is_empty()
+ );
+ },
+ )
+ .await;
+ assert!(engine.requests().is_empty());
+}
+
+#[tokio::test]
+async fn cancelling_a_queued_turn_skips_admission_and_engine() {
+ let engine = Arc::new(ScriptedEngine::new(vec![]));
+ let admission = Arc::new(TestAdmission::new(Err(AiAdmissionError::Unavailable)));
+ with_admission(
+ engine.clone(),
+ admission.clone(),
+ async |connection, session, state| {
+ let _lock = state.turn_lock.lock().await;
+ let prompt = connection.send_request(text_prompt(&session, "cancel queued"));
+ tokio::time::timeout(Duration::from_secs(5), async {
+ while state.active_cancel.lock().unwrap().is_empty() {
+ tokio::task::yield_now().await;
+ }
+ })
+ .await
+ .unwrap();
+ connection
+ .send_notification(CancelNotification::new(session))
+ .unwrap();
+ let response = tokio::time::timeout(Duration::from_secs(5), prompt.block_task())
+ .await
+ .unwrap()
+ .unwrap();
+ assert_eq!(response.stop_reason, StopReason::Cancelled);
+ assert!(
+ state
+ .store
+ .get(&state.session_id)
+ .unwrap()
+ .history
+ .is_empty()
+ );
+ },
+ )
+ .await;
+ assert!(engine.requests().is_empty());
+ assert!(admission.calls.lock().unwrap().is_empty());
+}
+
+struct WaitingAdmission(tokio::sync::Notify);
+
+impl AiAdmissionService for WaitingAdmission {
+ fn admit<'a>(
+ &'a self,
+ _: &'a MacroUserIdStr<'_>,
+ _: ai_usage::AiFeature,
+ ) -> ai_billing::domain::AdmissionFuture<'a> {
+ Box::pin(async move {
+ self.0.notify_one();
+ std::future::pending().await
+ })
+ }
+}
+
+#[tokio::test]
+async fn cancel_during_billing_does_not_start_engine_or_write_history() {
+ let engine = Arc::new(ScriptedEngine::new(vec![]));
+ let admission = Arc::new(WaitingAdmission(tokio::sync::Notify::new()));
+ with_admission(
+ engine.clone(),
+ admission.clone(),
+ async |connection, session, state| {
+ let prompt = connection.send_request(text_prompt(&session, "cancel during admission"));
+ tokio::time::timeout(Duration::from_secs(5), admission.0.notified())
+ .await
+ .unwrap();
+ connection
+ .send_notification(CancelNotification::new(session))
+ .unwrap();
+ let response = tokio::time::timeout(Duration::from_secs(5), prompt.block_task())
+ .await
+ .unwrap()
+ .unwrap();
+ assert_eq!(response.stop_reason, StopReason::Cancelled);
+ assert!(
+ state
+ .store
+ .get(&state.session_id)
+ .unwrap()
+ .history
+ .is_empty()
+ );
+ assert!(
+ state
+ .active_cancel
+ .lock()
+ .unwrap()
+ .iter()
+ .all(CancellationToken::is_cancelled)
+ );
+ },
+ )
+ .await;
+ assert!(engine.requests().is_empty());
+}
+
#[tokio::test]
async fn new_session_advertises_the_engine_supported_models() {
let (_notifications, config_options, ()) =
@@ -618,6 +875,7 @@ async fn session_new_dials_the_advertised_servers_except_macros_own() {
MacroUserIdStr::try_from_email("[email protected]").expect("a valid user id"),
),
engine: Arc::new(ScriptedEngine::new(Vec::new())),
+ admission: Arc::new(DisabledAiAdmissionService),
store,
active_cancel: std::sync::Mutex::new(Vec::new()),
turn_lock: tokio::sync::Mutex::new(()),
@@ -711,6 +969,7 @@ where
MacroUserIdStr::try_from_email("[email protected]").expect("a valid user id"),
),
engine,
+ admission: Arc::new(DisabledAiAdmissionService),
store,
active_cancel: std::sync::Mutex::new(Vec::new()),
turn_lock: tokio::sync::Mutex::new(()),
diff --git a/crates/agent_inmem/src/domain/mod.rs b/crates/agent_inmem/src/domain/mod.rs
index b8d863e727..ca8b506117 100644
--- a/crates/agent_inmem/src/domain/mod.rs
+++ b/crates/agent_inmem/src/domain/mod.rs
@@ -1,6 +1,7 @@
//! The in-memory agent's domain: the turn engine seam, per-session state, and
//! the ACP agent surface.
+pub mod admission;
pub mod agent;
pub mod engine;
pub mod mcp;
diff --git a/crates/agent_inmem/src/outbound/manager.rs b/crates/agent_inmem/src/outbound/manager.rs
index 29896b62f4..b35905dfc0 100644
--- a/crates/agent_inmem/src/outbound/manager.rs
+++ b/crates/agent_inmem/src/outbound/manager.rs
@@ -13,6 +13,7 @@ use agent_runtime_protocol::domain::channel::Channel;
use agent_runtime_protocol::domain::connection::{RuntimeConnection, ServerChannel};
use agent_runtime_protocol::domain::schema::v0::SystemEvent;
use agent_session::domain::model::AgentSessionId;
+use ai_billing::domain::{AiAdmissionService, DisabledAiAdmissionService};
use dashmap::DashMap;
use model_owner::Owner;
@@ -67,6 +68,7 @@ impl Drop for LiveAgent {
/// Provisions and tears down in-process agents, one per session.
pub struct InMemAgentManager {
engine: Arc<dyn TurnEngine>,
+ admission: Arc<dyn AiAdmissionService>,
frames: Arc<dyn FrameSource>,
mcp: Arc<dyn DynMcpToolConnector>,
enable_dev_commands: bool,
@@ -92,6 +94,7 @@ impl InMemAgentManager {
) -> Self {
Self {
engine,
+ admission: Arc::new(DisabledAiAdmissionService),
frames,
mcp,
enable_dev_commands: false,
@@ -101,6 +104,14 @@ impl InMemAgentManager {
}
}
+ /// Inject the host's configured admission capability for every new turn.
+ /// Production hosts must set this; the constructor defaults to disabled.
+ #[must_use]
+ pub fn with_admission(mut self, admission: Arc<dyn AiAdmissionService>) -> Self {
+ self.admission = admission;
+ self
+ }
+
/// The egress token `attach` was handed for `session`, if this process
/// still holds it.
#[must_use]
@@ -164,6 +175,7 @@ impl InMemAgentManager {
session_id: facts.id,
owner: facts.owner,
engine: Arc::clone(&self.engine),
+ admission: Arc::clone(&self.admission),
store: Arc::clone(&self.store),
active_cancel: std::sync::Mutex::new(Vec::new()),
turn_lock: tokio::sync::Mutex::new(()),
diff --git a/crates/agent_inmem/src/outbound/manager/test.rs b/crates/agent_inmem/src/outbound/manager/test.rs
index cd68c813fe..efd49fd943 100644
--- a/crates/agent_inmem/src/outbound/manager/test.rs
+++ b/crates/agent_inmem/src/outbound/manager/test.rs
@@ -22,7 +22,7 @@ use model_owner::Owner;
use super::*;
use crate::domain::engine::AgentIdentity;
use crate::outbound::log_frames::LogFrameSource;
-use crate::testing::ScriptedEngine;
+use crate::testing::{ScriptedEngine, TestAdmission, disabled_admission};
use agent_session::domain::model::ReplicaId;
use agent_session::domain::ports::{
NoOpAgentSessionNameGenerator, NoOpTurnObserver, NoopLifecyclePublisher,
@@ -193,6 +193,7 @@ async fn a_prompt_runs_end_to_end_through_the_real_session_machine() {
"streamed reply".to_owned(),
)])),
);
+ let manager = manager.with_admission(disabled_admission());
let transport = manager.attach(facts(id), None).await;
sessions
.attach_session(id, RuntimeAttachment::solo(transport))
@@ -290,6 +291,96 @@ async fn a_prompt_runs_end_to_end_through_the_real_session_machine() {
}
}
+#[tokio::test]
+async fn manager_admission_rejects_turns_without_wedging_the_session() {
+ use ai_billing::domain::{AiAdmissionError, DenyReason};
+
+ let repo = InMemoryAgentSessionRepo::new();
+ let sessions = AgentSessionServiceImpl::new(
+ repo.clone(),
+ FoldedMessageService::new(repo.clone()),
+ NoOpRealtime,
+ NoOpAgentSessionNameGenerator,
+ Arc::new(NoOpTurnObserver),
+ Arc::new(NoopLifecyclePublisher),
+ ReplicaId::mint(),
+ );
+ let id = AgentSessionId::new();
+ sessions
+ .create_session(CreateAgentSessionParams {
+ repo_branch: None,
+ id,
+ owner_id: Owner::User(owner()),
+ bot_id: BotId::TEST_A,
+ thread_id: None,
+ originating_message_id: None,
+ model: "anthropic/claude-sonnet-5".to_owned(),
+ harness: "macro-inmem".to_owned(),
+ repo_url: None,
+ workspace: "/workspace".to_owned(),
+ sandbox_size: agent_session::domain::model::SandboxSize::Default,
+ instructions: None,
+ mcp_servers: Default::default(),
+ egress_token_hash: None,
+ })
+ .await
+ .unwrap();
+ let engine = Arc::new(ScriptedEngine::new(vec![]));
+ let denial = AiAdmissionError::Denied(DenyReason::AllowanceExhausted);
+ let admission = Arc::new(TestAdmission::new(Err(denial)));
+ let manager = manager(&repo, engine.clone()).with_admission(admission.clone());
+ let transport = manager.attach(facts(id), None).await;
+ sessions
+ .attach_session(id, RuntimeAttachment::solo(transport))
+ .await
+ .unwrap();
+ sessions
+ .send_action(
+ id,
+ Some(owner()),
+ // Development commands are disabled, so this is provider-backed text.
+ AgentAction::prompt("/ask unavailable"),
+ AgentActionId::mint(),
+ )
+ .await
+ .unwrap();
+ tokio::time::timeout(Duration::from_secs(5), async {
+ loop {
+ if logged_frames(&repo, id)
+ .await
+ .iter()
+ .any(|frame| frame.contains(denial.code()))
+ {
+ break;
+ }
+ tokio::time::sleep(Duration::from_millis(20)).await;
+ }
+ })
+ .await
+ .expect("the runtime must return its sanitized denial");
+ assert!(engine.requests().is_empty());
+ assert!(manager.store.get(&id).unwrap().history.is_empty());
+ assert_eq!(
+ *admission.calls.lock().unwrap(),
+ vec![(owner().to_string(), ai_usage::AiFeature::AgentSession)]
+ );
+
+ // A second prompt must run on the same connection: a rejection is not a
+ // disconnect and must release the session machine's pending turn.
+ *admission.result.lock().unwrap() = Ok(());
+ sessions
+ .send_action(
+ id,
+ Some(owner()),
+ AgentAction::prompt("retry"),
+ AgentActionId::mint(),
+ )
+ .await
+ .unwrap();
+ await_turns(&engine, "retry").await;
+ assert_eq!(engine.requests()[0].messages, ["retry"]);
+}
+
/// A "restart": the second manager shares nothing with the first but the
/// durable repo, the way a new process would. The resumed turn must carry
/// the first turn's conversation, rebuilt from the frame log.
diff --git a/crates/agent_inmem/src/testing.rs b/crates/agent_inmem/src/testing.rs
index 7c65db187f..e2719d720f 100644
--- a/crates/agent_inmem/src/testing.rs
+++ b/crates/agent_inmem/src/testing.rs
@@ -1,10 +1,113 @@
//! Test doubles shared by this crate's tests.
use agent::{AgentError, StreamPart};
+use ai_billing::domain::{AdmissionFuture, AiAdmissionError, AiAdmissionService};
+use ai_usage::AiFeature;
+use macro_user_id::user_id::MacroUserIdStr;
+use std::sync::Mutex;
use tokio::sync::mpsc;
use crate::domain::engine::{AgentIdentity, TurnEngine, TurnRequest};
+/// Mutable admission result, recording the trusted identity and feature.
+pub(crate) struct TestAdmission {
+ pub(crate) result: Mutex<Result<(), AiAdmissionError>>,
+ pub(crate) calls: Mutex<Vec<(String, AiFeature)>>,
+}
+
+impl TestAdmission {
+ pub(crate) fn new(result: Result<(), AiAdmissionError>) -> Self {
+ Self {
+ result: Mutex::new(result),
+ calls: Mutex::new(Vec::new()),
+ }
+ }
+}
+
+impl AiAdmissionService for TestAdmission {
+ fn admit<'a>(
+ &'a self,
+ user: &'a MacroUserIdStr<'_>,
+ feature: AiFeature,
+ ) -> AdmissionFuture<'a> {
+ self.calls.lock().unwrap().push((user.to_string(), feature));
+ let result = *self.result.lock().unwrap();
+ Box::pin(async move { result })
+ }
+}
+
+/// Real disabled policy around unavailable billing: no admission path may touch it.
+pub(crate) fn disabled_admission() -> std::sync::Arc<dyn AiAdmissionService> {
+ std::sync::Arc::new(ai_billing::domain::BillingAdmissionService::new(
+ std::sync::Arc::new(UnavailableBilling),
+ ai_usage::AiUsageEnforcement::Disabled,
+ ))
+}
+
+struct UnavailableBilling;
+
+impl ai_billing::domain::BillingService for UnavailableBilling {
+ async fn check_allowance(
+ &self,
+ _: &MacroUserIdStr<'_>,
+ ) -> ai_billing::domain::Result<ai_billing::domain::AllowanceDecision> {
+ panic!("disabled policy must not contact unavailable billing")
+ }
+
+ async fn snapshot(
+ &self,
+ _: &MacroUserIdStr<'_>,
+ ) -> ai_billing::domain::Result<ai_billing::domain::UsageSnapshot> {
+ panic!("admission must not fetch snapshots")
+ }
+
+ async fn settle(&self, _: &MacroUserIdStr<'_>) -> ai_billing::domain::Result<()> {
+ panic!("admission must not settle")
+ }
+
+ async fn update_overage(
+ &self,
+ _: &MacroUserIdStr<'_>,
+ _: bool,
+ _: i64,
+ ) -> ai_billing::domain::Result<ai_billing::domain::UsageSnapshot> {
+ panic!("admission must not change settings")
+ }
+
+ async fn create_credit_checkout(
+ &self,
+ _: &MacroUserIdStr<'_>,
+ _: i64,
+ _: String,
+ _: String,
+ ) -> ai_billing::domain::Result<String> {
+ panic!("admission must not purchase credits")
+ }
+
+ async fn apply_credit_purchase(
+ &self,
+ _: &MacroUserIdStr<'_>,
+ _: i64,
+ _: &str,
+ ) -> ai_billing::domain::Result<()> {
+ panic!("admission must not apply credits")
+ }
+
+ async fn sync_period(
+ &self,
+ _: &MacroUserIdStr<'_>,
+ _: sqlx::types::chrono::DateTime<sqlx::types::chrono::Utc>,
+ _: sqlx::types::chrono::DateTime<sqlx::types::chrono::Utc>,
+ _: Option<ai_billing::domain::period::SubscriptionPeriod>,
+ ) -> ai_billing::domain::Result<()> {
+ panic!("admission must not sync periods")
+ }
+
+ async fn mark_overage_invoice(&self, _: &str, _: bool) -> ai_billing::domain::Result<()> {
+ panic!("admission must not handle invoices")
+ }
+}
+
/// Models advertised by shared test engines.
pub(crate) const TEST_MODELS: &[&str] = &["anthropic/claude-sonnet-5", "other-model"];
diff --git a/crates/agent_preview/src/domain/service.rs b/crates/agent_preview/src/domain/service.rs
index 7cd6d47980..2d8ec0dcc4 100644
--- a/crates/agent_preview/src/domain/service.rs
+++ b/crates/agent_preview/src/domain/service.rs
@@ -287,7 +287,8 @@ impl PreviewService {
}
self.authority.active(identity.session).await?;
let id = PreviewId::generate();
- let token = random();
+ // OpenSSH rejects usernames beginning with '-', which URL-safe base64 can emit.
+ let token = format!("preview_{}", random());
let preview = Preview {
id: id.clone(),
agent_session_id: identity.session,
diff --git a/crates/agent_preview/src/domain/service/test.rs b/crates/agent_preview/src/domain/service/test.rs
index 3fab21839d..4401213654 100644
--- a/crates/agent_preview/src/domain/service/test.rs
+++ b/crates/agent_preview/src/domain/service/test.rs
@@ -2,6 +2,17 @@ use super::*;
use crate::testing::*;
use entity_access::domain::models::AccessLevel;
+#[tokio::test]
+async fn ssh_credentials_have_a_safe_username_prefix_without_losing_entropy() {
+ let (service, _, _) = fixture(2222);
+ let share = service.share(identity(), 3000).await.unwrap();
+ let payload = share.token.strip_prefix("preview_").unwrap();
+ assert_eq!(URL_SAFE_NO_PAD.decode(payload).unwrap().len(), 32);
+ // The prefix is part of the credential, not merely a client-side decoration.
+ assert!(service.authenticate_ssh(payload).is_err());
+ assert!(service.authenticate_ssh(&share.token).is_ok());
+}
+
#[tokio::test]
async fn ssh_credentials_are_single_use_and_forward_is_scoped() {
let (service, _, _) = fixture(2222);
diff --git a/crates/agent_session/Cargo.toml b/crates/agent_session/Cargo.toml
index fbffa5995d..d8bbd4b135 100644
--- a/crates/agent_session/Cargo.toml
+++ b/crates/agent_session/Cargo.toml
@@ -6,12 +6,15 @@ publish = false
[features]
default = ["inbound", "outbound"]
+# Quota contracts and helper orchestration without enabling session adapters.
+admission = ["dep:ai_billing"]
ai_tools = ["inbound", "dep:ai_toolset", "dep:async-trait", "dep:schemars"]
# The `seed_jsonl` replay binary: an argument parser, and the Postgres
# adapter it writes through.
cli = ["dep:clap", "outbound"]
# The axum router serving sessions over HTTP.
inbound = [
+ "admission",
"dep:axum",
"dep:entity_registry",
"dep:macro_authorization",
@@ -21,6 +24,7 @@ inbound = [
]
# Postgres, the connection gateway, and the model-backed name generator.
outbound = [
+ "admission",
"bots/outbound",
"dep:agent",
"dep:ai_usage",
@@ -40,6 +44,7 @@ schema = ["dep:utoipa", "agent_runtime_protocol/utoipa", "macro_user_id/schema"]
test-utils = ["dep:mockall", "agent_fold/test-utils"]
[dependencies]
+ai_billing = { path = "../ai_billing", optional = true }
lazy-regex = { workspace = true }
ai_toolset = { path = "../ai_toolset", optional = true }
async-trait = { workspace = true, optional = true }
diff --git a/crates/agent_session/src/domain/error.rs b/crates/agent_session/src/domain/error.rs
index 6ecd4ac476..865e0ce344 100644
--- a/crates/agent_session/src/domain/error.rs
+++ b/crates/agent_session/src/domain/error.rs
@@ -1,12 +1,19 @@
use crate::domain::model::AgentSessionId;
use agent_runtime_protocol::domain::action::ActionError;
use agent_runtime_protocol::domain::ports::TransportError;
+#[cfg(feature = "admission")]
+pub use ai_billing::AiAdmissionError;
use model_owner::OwnerType;
use thiserror::Error;
+
pub type Result<T, E = AgentSessionError> = std::result::Result<T, E>;
#[derive(Error, Debug)]
pub enum AgentSessionError {
+ /// New Macro-funded work was refused before execution.
+ #[cfg(feature = "admission")]
+ #[error(transparent)]
+ Admission(#[from] AiAdmissionError),
/// Invalid link or channel sharing input.
#[error("{0}")]
InvalidSharing(&'static str),
@@ -106,6 +113,10 @@ pub enum AgentSessionError {
impl From<rootcause::Report> for AgentSessionError {
fn from(report: rootcause::Report) -> Self {
+ #[cfg(feature = "admission")]
+ if let Some(error) = report.downcast_current_context::<AiAdmissionError>() {
+ return Self::Admission(*error);
+ }
Self::Fold(report)
}
}
diff --git a/crates/agent_session/src/domain/events.rs b/crates/agent_session/src/domain/events.rs
index 5bbda6f9b9..9ebe6d62b6 100644
--- a/crates/agent_session/src/domain/events.rs
+++ b/crates/agent_session/src/domain/events.rs
@@ -198,6 +198,45 @@ pub struct TurnEndedMetadata {
pub queued_remaining: usize,
}
+/// Sanitized public details of a command refused before runtime execution.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
+pub struct CommandFailure {
+ /// Stable public denial or unavailability code.
+ pub code: String,
+ /// Public explanation, never an internal error report.
+ pub message: String,
+ /// Whether retrying later may succeed without a policy change.
+ pub retryable: bool,
+}
+
+#[cfg(feature = "admission")]
+impl From<ai_billing::AiAdmissionError> for CommandFailure {
+ fn from(error: ai_billing::AiAdmissionError) -> Self {
+ Self {
+ code: error.code().to_owned(),
+ message: error.to_string(),
+ retryable: error.is_retryable(),
+ }
+ }
+}
+
+/// An accepted command was refused before it could start a runtime turn.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
+pub struct CommandRejectedMetadata {
+ /// The session.
+ pub identity: SessionIdentity,
+ /// The command that will not execute.
+ pub action_id: AgentActionId,
+ /// Who submitted the command, if acting on a user's behalf.
+ pub actor: Option<MacroUserIdStr<'static>>,
+ /// The command's thread announcement, when one was created.
+ pub announcement_message_id: Option<Uuid>,
+ /// Safe details for clients and downstream consumers.
+ pub failure: CommandFailure,
+}
+
/// A turn ended and nothing is queued: the agent has stopped working.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
@@ -315,6 +354,10 @@ pub enum AgentSessionLifecycleEvent {
#[serde(rename = "agent_session.turn_ended")]
#[strum_discriminants(strum(serialize = "agent_session.turn_ended"))]
TurnEnded(TurnEndedMetadata),
+ /// An accepted command was refused before runtime execution.
+ #[serde(rename = "agent_session.command_rejected")]
+ #[strum_discriminants(strum(serialize = "agent_session.command_rejected"))]
+ CommandRejected(CommandRejectedMetadata),
/// A turn ended with nothing queued behind it.
#[serde(rename = "agent_session.settled")]
#[strum_discriminants(strum(serialize = "agent_session.settled"))]
@@ -353,6 +396,7 @@ impl AgentSessionLifecycleEvent {
Self::Opened(metadata) => &metadata.identity,
Self::TurnStarted(metadata) => &metadata.identity,
Self::TurnEnded(metadata) => &metadata.identity,
+ Self::CommandRejected(metadata) => &metadata.identity,
Self::Settled(metadata) => &metadata.identity,
Self::WaitingForInput(metadata) => &metadata.identity,
Self::InputReceived(metadata) => &metadata.identity,
diff --git a/crates/agent_session/src/domain/events/test.rs b/crates/agent_session/src/domain/events/test.rs
index ac3919f6c7..5af3237d14 100644
--- a/crates/agent_session/src/domain/events/test.rs
+++ b/crates/agent_session/src/domain/events/test.rs
@@ -53,6 +53,17 @@ fn one_of_each() -> Vec<AgentSessionLifecycleEvent> {
stop_reason: "end_turn".to_owned(),
queued_remaining: 0,
}),
+ AgentSessionLifecycleEvent::CommandRejected(CommandRejectedMetadata {
+ identity: identity(),
+ action_id: action_id(),
+ actor: Some(owner()),
+ announcement_message_id: Some(Uuid::from_u128(4)),
+ failure: CommandFailure {
+ code: "ai_billing_unavailable".into(),
+ message: "AI usage validation is temporarily unavailable. Please try again.".into(),
+ retryable: true,
+ },
+ }),
AgentSessionLifecycleEvent::Settled(SessionSettledMetadata {
identity: identity(),
last_turn: Some(TurnSummary {
@@ -101,6 +112,31 @@ fn one_of_each() -> Vec<AgentSessionLifecycleEvent> {
]
}
+#[cfg(feature = "admission")]
+#[test]
+fn admission_failures_have_only_sanitized_public_fields() {
+ use ai_billing::{AiAdmissionError, DenyReason};
+ for error in [
+ AiAdmissionError::Denied(DenyReason::AllowanceExhausted),
+ AiAdmissionError::Denied(DenyReason::OverageLimitReached),
+ AiAdmissionError::Denied(DenyReason::OveragePaymentFailed),
+ AiAdmissionError::Unavailable,
+ ] {
+ let failure = CommandFailure::from(error);
+ assert_eq!(failure.code, error.code());
+ assert_eq!(failure.message, error.to_string());
+ assert_eq!(failure.retryable, error.is_retryable());
+ assert_eq!(
+ serde_json::to_value(failure)
+ .unwrap()
+ .as_object()
+ .unwrap()
+ .len(),
+ 3
+ );
+ }
+}
+
#[test]
fn event_names_match_the_wire() {
use strum::IntoEnumIterator as _;
diff --git a/crates/agent_session/src/domain/mod.rs b/crates/agent_session/src/domain/mod.rs
index ba3a3ebc39..fa2fcb19ce 100644
--- a/crates/agent_session/src/domain/mod.rs
+++ b/crates/agent_session/src/domain/mod.rs
@@ -7,6 +7,8 @@ pub mod error;
pub mod events;
pub mod lifecycle;
pub mod model;
+#[cfg(feature = "admission")]
+pub mod name_generation;
pub mod ports;
pub mod pull_request;
mod sandbox_size;
diff --git a/crates/agent_session/src/domain/name_generation.rs b/crates/agent_session/src/domain/name_generation.rs
new file mode 100644
index 0000000000..fa4c686a9e
--- /dev/null
+++ b/crates/agent_session/src/domain/name_generation.rs
@@ -0,0 +1,47 @@
+//! Optional naming is independently admitted, never a prerequisite for runtime execution.
+
+use std::sync::Arc;
+
+use ai_billing::{AiAdmissionService, AiFeature};
+
+use super::{model::AgentSession, ports::AgentSessionNameGenerator};
+
+#[cfg(test)]
+mod test;
+
+/// Admits Macro-funded naming while leaving the existing session name on refusal.
+#[derive(Clone)]
+pub struct AdmittedAgentSessionNameGenerator<N> {
+ generator: N,
+ admission: Arc<dyn AiAdmissionService>,
+}
+
+impl<N> AdmittedAgentSessionNameGenerator<N> {
+ /// Wrap a name generator with the host's configured admission service.
+ pub fn new(generator: N, admission: Arc<dyn AiAdmissionService>) -> Self {
+ Self {
+ generator,
+ admission,
+ }
+ }
+}
+
+impl<N: AgentSessionNameGenerator> AgentSessionNameGenerator
+ for AdmittedAgentSessionNameGenerator<N>
+{
+ async fn generate_name(
+ &self,
+ session: &AgentSession,
+ initial_prompt: &str,
+ ) -> Result<Option<String>, rootcause::Report> {
+ // Naming must not invent a billing identity for a non-user owner.
+ let Ok(owner) = session.owner_user() else {
+ return Ok(None);
+ };
+ if let Err(error) = self.admission.admit(owner, AiFeature::ChatRename).await {
+ tracing::debug!(code = error.code(), "skipping optional session naming");
+ return Ok(None);
+ }
+ self.generator.generate_name(session, initial_prompt).await
+ }
+}
diff --git a/crates/agent_session/src/domain/name_generation/test.rs b/crates/agent_session/src/domain/name_generation/test.rs
new file mode 100644
index 0000000000..fcc273d88b
--- /dev/null
+++ b/crates/agent_session/src/domain/name_generation/test.rs
@@ -0,0 +1,105 @@
+use super::*;
+use ai_billing::{AdmissionFuture, AiAdmissionError, DenyReason};
+use std::sync::atomic::{AtomicUsize, Ordering};
+
+struct Admission(Result<(), AiAdmissionError>);
+
+impl AiAdmissionService for Admission {
+ fn admit<'a>(
+ &'a self,
+ user: &'a macro_user_id::user_id::MacroUserIdStr<'_>,
+ feature: AiFeature,
+ ) -> AdmissionFuture<'a> {
+ assert_eq!(
+ user,
+ crate::testing::test_agent_session(super::super::model::AgentSessionId::TEST_A)
+ .owner_user()
+ .unwrap()
+ );
+ assert_eq!(feature, AiFeature::ChatRename);
+ Box::pin(async { self.0 })
+ }
+}
+
+#[derive(Clone)]
+struct Namer(Arc<AtomicUsize>);
+
+impl AgentSessionNameGenerator for Namer {
+ async fn generate_name(
+ &self,
+ _session: &AgentSession,
+ _initial_prompt: &str,
+ ) -> Result<Option<String>, rootcause::Report> {
+ self.0.fetch_add(1, Ordering::SeqCst);
+ Ok(Some("Generated name".into()))
+ }
+}
+
+#[tokio::test]
+async fn denied_or_unavailable_naming_retains_fallback_without_provider_calls() {
+ for error in [
+ AiAdmissionError::Denied(DenyReason::AllowanceExhausted),
+ AiAdmissionError::Unavailable,
+ ] {
+ let calls = Arc::new(AtomicUsize::new(0));
+ let generator = AdmittedAgentSessionNameGenerator::new(
+ Namer(calls.clone()),
+ Arc::new(Admission(Err(error))),
+ );
+ let session =
+ crate::testing::test_agent_session(super::super::model::AgentSessionId::TEST_A);
+ let fallback = session.name.clone();
+ let generated = generator
+ .generate_name(&session, "fix login")
+ .await
+ .unwrap();
+ assert!(generated.is_none());
+ assert_eq!(generated.unwrap_or(session.name), fallback);
+ assert_eq!(calls.load(Ordering::SeqCst), 0);
+ }
+}
+
+#[tokio::test]
+async fn non_user_owner_keeps_its_name_without_substituting_a_system_user() {
+ struct NoAdmission;
+ impl AiAdmissionService for NoAdmission {
+ fn admit<'a>(
+ &'a self,
+ _: &'a macro_user_id::user_id::MacroUserIdStr<'_>,
+ _: AiFeature,
+ ) -> AdmissionFuture<'a> {
+ panic!("a missing user must not be replaced with a billing identity");
+ }
+ }
+ let calls = Arc::new(AtomicUsize::new(0));
+ let generator =
+ AdmittedAgentSessionNameGenerator::new(Namer(calls.clone()), Arc::new(NoAdmission));
+ let mut session =
+ crate::testing::test_agent_session(super::super::model::AgentSessionId::TEST_A);
+ session.owner_id = model_owner::Owner::Team(uuid::Uuid::from_u128(1));
+ assert!(
+ generator
+ .generate_name(&session, "fix login")
+ .await
+ .unwrap()
+ .is_none()
+ );
+ assert_eq!(calls.load(Ordering::SeqCst), 0);
+}
+
+#[tokio::test]
+async fn admitted_naming_delegates_once() {
+ let calls = Arc::new(AtomicUsize::new(0));
+ let generator =
+ AdmittedAgentSessionNameGenerator::new(Namer(calls.clone()), Arc::new(Admission(Ok(()))));
+ let session = crate::testing::test_agent_session(super::super::model::AgentSessionId::TEST_A);
+ assert_eq!(
+ generator
+ .generate_name(&session, "fix login")
+ .await
+ .unwrap()
+ .as_deref(),
+ Some("Generated name")
+ );
+ assert_eq!(calls.load(Ordering::SeqCst), 1);
+}
diff --git a/crates/agent_session/src/domain/routines/models.rs b/crates/agent_session/src/domain/routines/models.rs
index 6ba8ccec20..bc168ebbf1 100644
--- a/crates/agent_session/src/domain/routines/models.rs
+++ b/crates/agent_session/src/domain/routines/models.rs
@@ -122,6 +122,10 @@ pub enum RoutineFailureReason {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, thiserror::Error)]
#[serde(rename_all = "snake_case")]
pub enum RoutineSessionError {
+ /// Definitive refusal before Macro-funded work was accepted.
+ #[cfg(feature = "admission")]
+ #[error(transparent)]
+ Admission(#[from] crate::domain::error::AiAdmissionError),
/// Non-v7 execution ids, empty prompt, or blank supplied model.
#[error("invalid routine session command")]
InvalidCommand,
diff --git a/crates/agent_session/src/domain/routines/service.rs b/crates/agent_session/src/domain/routines/service.rs
index 57c4eb871c..e7d3e2007f 100644
--- a/crates/agent_session/src/domain/routines/service.rs
+++ b/crates/agent_session/src/domain/routines/service.rs
@@ -219,7 +219,7 @@ where
},
)
.await
- .map_err(|_| RoutineSessionError::PromptDeliveryUnknown)?;
+ .map_err(prompt_error)?;
if accepted.action_id != action.action_id {
return Err(RoutineSessionError::PromptDeliveryUnknown);
}
@@ -271,8 +271,18 @@ fn validate_session_id(id: AgentSessionId) -> Result<(), RoutineSessionError> {
Ok(())
}
+fn prompt_error(error: AgentSessionError) -> RoutineSessionError {
+ match error {
+ #[cfg(feature = "admission")]
+ AgentSessionError::Admission(error) => RoutineSessionError::Admission(error),
+ _ => RoutineSessionError::PromptDeliveryUnknown,
+ }
+}
+
fn session_error(error: AgentSessionError) -> RoutineSessionError {
match error {
+ #[cfg(feature = "admission")]
+ AgentSessionError::Admission(error) => RoutineSessionError::Admission(error),
AgentSessionError::Forbidden
| AgentSessionError::UnknownOwner
| AgentSessionError::OwnerNotUser(_) => RoutineSessionError::Forbidden,
diff --git a/crates/agent_session/src/domain/routines/service/test.rs b/crates/agent_session/src/domain/routines/service/test.rs
index 85eae3ea00..1e836e8a8e 100644
--- a/crates/agent_session/src/domain/routines/service/test.rs
+++ b/crates/agent_session/src/domain/routines/service/test.rs
@@ -14,6 +14,27 @@ use macro_user_id::user_id::MacroUserIdStr;
use macro_uuid::Uuid;
use std::sync::{Arc, Mutex};
+#[test]
+#[cfg(feature = "admission")]
+fn definitive_admission_failures_survive_routine_preparation_and_prompt_mapping() {
+ use ai_billing::{AiAdmissionError, DenyReason};
+ for error in [
+ AiAdmissionError::Denied(DenyReason::AllowanceExhausted),
+ AiAdmissionError::Denied(DenyReason::OverageLimitReached),
+ AiAdmissionError::Denied(DenyReason::OveragePaymentFailed),
+ AiAdmissionError::Unavailable,
+ ] {
+ let expected = RoutineSessionError::Admission(error);
+ assert_eq!(session_error(AgentSessionError::Admission(error)), expected);
+ assert_eq!(prompt_error(AgentSessionError::Admission(error)), expected);
+ let wire = serde_json::to_vec(&expected).unwrap();
+ assert_eq!(
+ serde_json::from_slice::<RoutineSessionError>(&wire).unwrap(),
+ expected
+ );
+ }
+}
+
#[derive(Clone)]
struct Directory(Arc<Mutex<Option<BotFacts>>>);
diff --git a/crates/agent_session/src/inbound/axum_router.rs b/crates/agent_session/src/inbound/axum_router.rs
index ab1e5dae45..0da6a76807 100644
--- a/crates/agent_session/src/inbound/axum_router.rs
+++ b/crates/agent_session/src/inbound/axum_router.rs
@@ -22,6 +22,7 @@ use agent_runtime_protocol::domain::{
action::{AgentAction, AgentActionId},
schema::v0::SystemEvent,
};
+use ai_billing::inbound::admission::AiAdmissionErrorBody;
use axum::{
Json, Router,
extract::{FromRef, Path, State},
@@ -300,6 +301,7 @@ impl IntoResponse for AgentSessionApiError {
// here, and nothing the caller does again right now will land, so it
// answers 409 with a reason rather than a 500 that reads as a bug
// and buries the one fact worth showing a user.
+ Self::Domain(AgentSessionError::Admission(error)) => error.into_response(),
Self::Domain(AgentSessionError::Disconnected(session_id)) => {
tracing::info!(%session_id, "action refused: the session's runtime is not connected");
(
@@ -951,9 +953,16 @@ async fn ensure_harness_serves_session<R: AgentSessionNotificationRecipient>(
running turn to end and can be edited or removed meanwhile."
),
(status = 401, body = String),
+ (status = 402, description = "AI allowance exhausted", body = AiAdmissionErrorBody),
(status = 403, body = String),
(status = 422, body = String),
(status = 500, body = String),
+ (status = 503, description = "AI usage validation unavailable, or replica draining; retry later",
+ content(
+ (AiAdmissionErrorBody = "application/json"),
+ (String = "text/plain"),
+ )
+ ),
)
)]
/// Perform a control operation on a live agent session.
@@ -1765,6 +1774,7 @@ impl IntoResponse for CreateSessionApiError {
};
return (StatusCode::CONFLICT, Json(body)).into_response();
}
+ Self::Domain(AgentSessionError::Admission(error)) => return error.into_response(),
Self::Domain(AgentSessionError::ThreadSessionExists) => (
StatusCode::CONFLICT,
"this bot already has a session for this thread".to_owned(),
@@ -1911,10 +1921,12 @@ fn principal_owner(
responses(
(status = 201, body = CreateAgentSessionResponse),
(status = 401, body = String),
+ (status = 402, description = "AI allowance exhausted", body = AiAdmissionErrorBody),
(status = 403, body = String),
(status = 404, body = String),
(status = 422, body = String),
(status = 500, body = String),
+ (status = 503, description = "AI usage validation unavailable; retry later", body = AiAdmissionErrorBody),
)
)]
/// Open an agent session served by an external runtime.
diff --git a/crates/agent_session/src/inbound/axum_router/test.rs b/crates/agent_session/src/inbound/axum_router/test.rs
index e010a4d139..6c8bf617c2 100644
--- a/crates/agent_session/src/inbound/axum_router/test.rs
+++ b/crates/agent_session/src/inbound/axum_router/test.rs
@@ -14,6 +14,65 @@ use rootcause::Report;
use std::sync::{Arc, Mutex};
use tower::ServiceExt;
+#[tokio::test]
+async fn admission_maps_to_shared_public_http_contract_on_create_and_control() {
+ use ai_billing::{AiAdmissionError, DenyReason};
+ for (error, status) in [
+ (
+ AiAdmissionError::Denied(DenyReason::AllowanceExhausted),
+ StatusCode::PAYMENT_REQUIRED,
+ ),
+ (
+ AiAdmissionError::Unavailable,
+ StatusCode::SERVICE_UNAVAILABLE,
+ ),
+ ] {
+ let responses = [
+ AgentSessionApiError::Domain(error.into()).into_response(),
+ CreateSessionApiError::Domain(error.into()).into_response(),
+ AgentSessionApiError::Domain(AgentSessionError::from(
+ rootcause::report!(error).into_dynamic(),
+ ))
+ .into_response(),
+ ];
+ for response in responses {
+ assert_eq!(response.status(), status);
+ let body = axum::body::to_bytes(response.into_body(), usize::MAX)
+ .await
+ .unwrap();
+ let value: serde_json::Value = serde_json::from_slice(&body).unwrap();
+ assert_eq!(
+ value,
+ serde_json::json!({"error": error.to_string(), "code": error.code()})
+ );
+ }
+ }
+}
+
+#[test]
+fn openapi_documents_session_admission_failures() {
+ #[derive(utoipa::OpenApi)]
+ #[openapi(paths(create_agent_session_handler, control_agent_session_handler))]
+ struct ApiDoc;
+
+ let schema = serde_json::to_value(<ApiDoc as utoipa::OpenApi>::openapi()).unwrap();
+ for path in ["/agent-sessions", "/agent-sessions/{session_id}/control"] {
+ let responses = &schema["paths"][path]["post"]["responses"];
+ for status in ["402", "503"] {
+ assert_eq!(
+ responses[status]["content"]["application/json"]["schema"]["$ref"],
+ "#/components/schemas/AiAdmissionErrorBody"
+ );
+ }
+ }
+ assert_eq!(
+ schema["paths"]["/agent-sessions/{session_id}/control"]["post"]["responses"]["503"]["content"]
+ ["text/plain"]["schema"]["type"],
+ "string"
+ );
+ assert!(schema["components"]["schemas"]["AiAdmissionErrorBody"].is_object());
+}
+
const BOT_TOKEN: &str = "mbot_self_test";
const HARNESS_TOKEN: &str = "mhns_self_test";
const OWNER: &str = "macro|[email protected]";
diff --git a/crates/agent_session/src/inbound/routine_sessions.rs b/crates/agent_session/src/inbound/routine_sessions.rs
index f92476ccdb..fc6cf45011 100644
--- a/crates/agent_session/src/inbound/routine_sessions.rs
+++ b/crates/agent_session/src/inbound/routine_sessions.rs
@@ -105,6 +105,9 @@ impl From<JsonRejection> for ApiError {
impl IntoResponse for ApiError {
fn into_response(self) -> Response {
let status = match self.0 {
+ RoutineSessionError::Admission(error) => {
+ ai_billing::inbound::admission::admission_status(error)
+ }
RoutineSessionError::InvalidCommand => StatusCode::BAD_REQUEST,
RoutineSessionError::Forbidden => StatusCode::FORBIDDEN,
RoutineSessionError::PersonaUnavailable => StatusCode::NOT_FOUND,
diff --git a/crates/agent_session/src/inbound/routine_sessions/test.rs b/crates/agent_session/src/inbound/routine_sessions/test.rs
index c84f7b67d8..0174419240 100644
--- a/crates/agent_session/src/inbound/routine_sessions/test.rs
+++ b/crates/agent_session/src/inbound/routine_sessions/test.rs
@@ -283,6 +283,16 @@ async fn owner_is_required_and_validated_in_every_command() {
#[tokio::test]
async fn domain_denials_are_preserved_as_content_free_error_codes() {
for (error, status) in [
+ (
+ RoutineSessionError::Admission(ai_billing::AiAdmissionError::Denied(
+ ai_billing::DenyReason::AllowanceExhausted,
+ )),
+ StatusCode::PAYMENT_REQUIRED,
+ ),
+ (
+ RoutineSessionError::Admission(ai_billing::AiAdmissionError::Unavailable),
+ StatusCode::SERVICE_UNAVAILABLE,
+ ),
(RoutineSessionError::InvalidCommand, StatusCode::BAD_REQUEST),
(RoutineSessionError::Forbidden, StatusCode::FORBIDDEN),
(
diff --git a/crates/agent_trigger/Cargo.toml b/crates/agent_trigger/Cargo.toml
index fbeb8955d8..dd4a6318b4 100644
--- a/crates/agent_trigger/Cargo.toml
+++ b/crates/agent_trigger/Cargo.toml
@@ -5,13 +5,16 @@ publish = false
version = "0.1.0"
[features]
+# Keep billing infrastructure out of domain-event-only consumers.
+admission = ["dep:ai_billing"]
# Lexical / fast-model adapters. Off by default: `lexical_client` pulls
# models_search → models_soup → notification → rdkafka, and the self-hosted
# daemon only needs domain events from this crate. Services that construct
# the adapters enable this; do not add it to coding_agent_worker.
-outbound = ["dep:agent", "dep:ai_usage", "dep:async-trait", "dep:document_storage_service_client", "dep:document_sub_type", "dep:lexical_client", "dep:sqlx", "dep:static_file", "channels/ports"]
+outbound = ["admission", "dep:agent", "dep:ai_usage", "dep:async-trait", "dep:document_storage_service_client", "dep:document_sub_type", "dep:lexical_client", "dep:sqlx", "dep:static_file", "channels/ports"]
[dependencies]
+ai_billing = { path = "../ai_billing", optional = true }
agent = { path = "../agent", optional = true }
agent_session = { path = "../agent_session", default-features = false }
ai_usage = { path = "../ai_usage", optional = true }
diff --git a/crates/agent_trigger/src/domain/service.rs b/crates/agent_trigger/src/domain/service.rs
index d25afc0e08..cc60969e44 100644
--- a/crates/agent_trigger/src/domain/service.rs
+++ b/crates/agent_trigger/src/domain/service.rs
@@ -5,6 +5,11 @@ use std::collections::HashSet;
#[cfg(test)]
mod test;
+#[cfg(feature = "admission")]
+use ai_billing::{AiAdmissionService, AiFeature, DisabledAiAdmissionService};
+#[cfg(feature = "admission")]
+use std::sync::Arc;
+
use agent_session::domain::error::Result;
use agent_session::domain::model::{AgentSession, AgentSessionId, ThreadSession};
use agent_session::domain::ports::AgentSessionRepo;
@@ -170,6 +175,8 @@ pub struct AgentTriggerService<Repo, Bots, Teams, Channels, Replies, Judge, Hist
replies: Replies,
judge: Judge,
history: History,
+ #[cfg(feature = "admission")]
+ admission: Arc<dyn AiAdmissionService>,
}
impl<Repo, Bots, Teams, Channels, Replies, Judge, History>
@@ -185,7 +192,7 @@ where
{
/// Creates a trigger service backed by session, bot, membership, and
/// participation lookups.
- pub const fn new(
+ pub fn new(
sessions: Repo,
bots: Bots,
teams: Teams,
@@ -202,9 +209,19 @@ where
replies,
judge,
history,
+ #[cfg(feature = "admission")]
+ admission: Arc::new(DisabledAiAdmissionService),
}
}
+ /// Configure admission for implicit classification, including image captions.
+ /// Explicit mentions and deterministic reply routing are admitted downstream.
+ #[cfg(feature = "admission")]
+ pub fn with_admission(mut self, admission: Arc<dyn AiAdmissionService>) -> Self {
+ self.admission = admission;
+ self
+ }
+
/// Whether `posted` may address `bot_id` under the bot's current scope.
///
/// System agents are global. Persisted all-channel agents are private to
@@ -466,9 +483,9 @@ where
};
// Only a user implicitly addresses an agent; bot traffic must always
// mention explicitly, or bots would relay each other forever.
- if posted.sender.as_user().is_none() {
+ let Some(_user) = posted.sender.as_user() else {
return Ok(None);
- }
+ };
let mut candidates = Vec::new();
for session in self.sessions.find_all_for_thread(thread_id).await? {
if session.thread_parent.as_ref() == Some(&posted.parent)
@@ -506,6 +523,15 @@ where
}
};
+ // The judge may caption attachments before classifying. Admit the whole
+ // optional operation before entering that port, never retrying through a
+ // different model on rejection. Returning no event preserves broker ack.
+ #[cfg(feature = "admission")]
+ if let Err(error) = self.admission.admit(_user, AiFeature::Automation).await {
+ tracing::info!(code = error.code(), "skipping agent trigger inference");
+ return Ok(None);
+ }
+
if self
.is_addressed_to_agent(posted, &self.transcript(posted, invocation, &session).await)
.await
diff --git a/crates/agent_trigger/src/domain/service/test.rs b/crates/agent_trigger/src/domain/service/test.rs
index d64cef576c..e0a934e6cb 100644
--- a/crates/agent_trigger/src/domain/service/test.rs
+++ b/crates/agent_trigger/src/domain/service/test.rs
@@ -1,5 +1,7 @@
use super::*;
+#[cfg(feature = "admission")]
+mod admission;
mod task_assignment;
use agent_session::domain::error::AgentSessionError;
diff --git a/crates/agent_trigger/src/domain/service/test/admission.rs b/crates/agent_trigger/src/domain/service/test/admission.rs
new file mode 100644
index 0000000000..e58420c029
--- /dev/null
+++ b/crates/agent_trigger/src/domain/service/test/admission.rs
@@ -0,0 +1,135 @@
+use super::*;
+use ai_billing::{AdmissionFuture, AiAdmissionError, DenyReason};
+use std::sync::atomic::{AtomicUsize, Ordering};
+
+struct Admission {
+ result: std::result::Result<(), AiAdmissionError>,
+ calls: AtomicUsize,
+}
+
+impl Admission {
+ fn new(result: std::result::Result<(), AiAdmissionError>) -> Arc<Self> {
+ Arc::new(Self {
+ result,
+ calls: AtomicUsize::new(0),
+ })
+ }
+}
+
+impl AiAdmissionService for Admission {
+ fn admit<'a>(
+ &'a self,
+ caller: &'a MacroUserIdStr<'_>,
+ feature: AiFeature,
+ ) -> AdmissionFuture<'a> {
+ // The sender, not the existing session's different owner, pays for inference.
+ assert_eq!(caller, &user());
+ assert_eq!(feature, AiFeature::Automation);
+ self.calls.fetch_add(1, Ordering::SeqCst);
+ Box::pin(async { self.result })
+ }
+}
+
+fn failures() -> [AiAdmissionError; 2] {
+ [
+ AiAdmissionError::Denied(DenyReason::AllowanceExhausted),
+ AiAdmissionError::Unavailable,
+ ]
+}
+
+#[tokio::test]
+async fn rejection_skips_the_entire_judge_including_image_preparation_and_acks() {
+ for failure in failures() {
+ for with_image in [false, true] {
+ let mut posted = message(vec![]);
+ if with_image {
+ posted
+ .attachments
+ .push(messages::domain::events::MessageEventAttachment {
+ attachment_id: Uuid::from_u128(5),
+ entity_type: "static_image".to_owned(),
+ entity_id: "image-to-caption".to_owned(),
+ created_at: Utc::now(),
+ });
+ }
+ let sessions =
+ implicit_sessions(vec![thread_session(AgentSessionId::TEST_A, BotId::TEST_A)]);
+ let admission = Admission::new(Err(failure));
+ let service = service(
+ sessions,
+ agent_bots(),
+ extractor(Ok(None)),
+ MockImplicitTriggerJudge::new(),
+ )
+ .with_admission(admission.clone());
+ assert!(
+ service
+ .evaluate(&posted)
+ .await
+ .expect("ack optional inference")
+ .is_empty()
+ );
+ assert_eq!(admission.calls.load(Ordering::SeqCst), 1);
+ }
+ }
+}
+
+#[tokio::test]
+async fn explicit_mentions_and_reply_targets_route_without_admission() {
+ for failure in failures() {
+ let admission = Admission::new(Err(failure));
+ let (replies, judge) = no_implicit();
+ let mention_service = service(sessions_without_existing(), agent_bots(), replies, judge)
+ .with_admission(admission.clone());
+ assert_eq!(
+ mention_service
+ .evaluate(&message(vec![mention_of(BotId::TEST_A)]))
+ .await
+ .unwrap()
+ .len(),
+ 1
+ );
+ assert_eq!(admission.calls.load(Ordering::SeqCst), 0);
+
+ let sessions =
+ implicit_sessions(vec![thread_session(AgentSessionId::TEST_A, BotId::TEST_A)]);
+ let service = super::service(
+ sessions,
+ agent_bots(),
+ extractor(Ok(Some(reply_to_bot(BotId::TEST_A)))),
+ MockImplicitTriggerJudge::new(),
+ )
+ .with_admission(admission.clone());
+ let events = service.evaluate(&message(vec![])).await.unwrap();
+ assert_eq!(
+ existing_channel_metadata(&events).kind,
+ ThreadMessageKind::ExplicitReply
+ );
+ assert_eq!(admission.calls.load(Ordering::SeqCst), 0);
+ }
+}
+
+#[tokio::test]
+async fn admitted_inference_uses_the_sender_and_does_not_retry_a_failed_judge() {
+ for outcome in [
+ Ok(true),
+ Err(AgentSessionError::Unknown(anyhow::anyhow!(
+ "provider failed"
+ ))),
+ ] {
+ let expected = outcome.is_ok();
+ let admission = Admission::new(Ok(()));
+ let sessions =
+ implicit_sessions(vec![thread_session(AgentSessionId::TEST_A, BotId::TEST_A)]);
+ let service = service(
+ sessions,
+ agent_bots(),
+ extractor(Ok(None)),
+ judge_saying(outcome),
+ )
+ .with_admission(admission.clone());
+ let events = service.evaluate(&message(vec![])).await.unwrap();
+ assert_eq!(!events.is_empty(), expected);
+ assert_eq!(admission.calls.load(Ordering::SeqCst), 1);
+ }
+}
diff --git a/crates/agent_trigger/src/outbound/fast_model_judge.rs b/crates/agent_trigger/src/outbound/fast_model_judge.rs
index 356c8df2ff..d258417f17 100644
--- a/crates/agent_trigger/src/outbound/fast_model_judge.rs
+++ b/crates/agent_trigger/src/outbound/fast_model_judge.rs
@@ -77,6 +77,9 @@ impl ImplicitTriggerJudge for FastModelTriggerJudge {
posted: &MessagePostedMetadata,
transcript: &str,
) -> Result<bool> {
+ let Some(user) = posted.sender.as_user() else {
+ return Ok(false);
+ };
let schema = DynamicSchema {
name: "ImplicitTriggerJudgeOutput".to_string(),
description: Some(
@@ -98,13 +101,7 @@ impl ImplicitTriggerJudge for FastModelTriggerJudge {
}
}),
};
- // The judge runs on behalf of whoever posted the message, so their
- // account carries the tokens; a non-user sender never reaches this
- // point, but attribute it to the system rather than fail if one does.
- let ctx = match posted.sender.as_user() {
- Some(user) => UsageContext::new(AiFeature::Automation, user.clone()),
- None => UsageContext::system(AiFeature::Automation),
- };
+ let ctx = UsageContext::new(AiFeature::Automation, user.clone());
let blurbs =
blurbs_for_attachments(self.images.as_ref(), &posted.attachments, ctx.clone()).await;
diff --git a/crates/agent_trigger/src/outbound/fast_model_judge/test.rs b/crates/agent_trigger/src/outbound/fast_model_judge/test.rs
index c16573c648..3eb912ee8f 100644
--- a/crates/agent_trigger/src/outbound/fast_model_judge/test.rs
+++ b/crates/agent_trigger/src/outbound/fast_model_judge/test.rs
@@ -1,5 +1,42 @@
use super::*;
+struct UnexpectedCaptioner;
+
+#[async_trait::async_trait]
+impl ImageCaptioner for UnexpectedCaptioner {
+ async fn caption(&self, _file_id: &str, _ctx: UsageContext) -> Option<String> {
+ panic!("a missing real caller must never reach image captioning");
+ }
+}
+
+#[tokio::test]
+async fn a_non_user_sender_is_not_replaced_with_system_billing_identity() {
+ use chrono::Utc;
+ use macro_uuid::Uuid;
+ use messages::domain::{events::MessageEventAttachment, models::MessageParent};
+
+ let judge =
+ FastModelTriggerJudge::new(Arc::new(ai_usage::NoOpUsageRecorder), UnexpectedCaptioner);
+ let posted = MessagePostedMetadata {
+ parent: MessageParent::Channel(Uuid::from_u128(1)),
+ message_id: Uuid::from_u128(2),
+ thread_id: Some(Uuid::from_u128(3)),
+ root_id: Uuid::from_u128(3),
+ sender: channel_sender::ChannelSender::new_from_bot(bot_id::MACRO_AI_BOT_ID),
+ triggered_by: None,
+ content: "describe this".to_owned(),
+ mentions: vec![],
+ attachments: vec![MessageEventAttachment {
+ attachment_id: Uuid::from_u128(4),
+ entity_type: "static_image".to_owned(),
+ entity_id: "image-to-caption".to_owned(),
+ created_at: Utc::now(),
+ }],
+ created_at: Utc::now(),
+ };
+ assert!(!judge.is_addressed_to_agent(&posted, "").await.unwrap());
+}
+
#[test]
fn the_judge_is_told_what_an_image_blurb_means() {
assert!(SYSTEM_PROMPT.contains("<this is an image of ...>"));
diff --git a/crates/ai_billing/Cargo.toml b/crates/ai_billing/Cargo.toml
index 7c3308a3b0..a172543393 100644
--- a/crates/ai_billing/Cargo.toml
+++ b/crates/ai_billing/Cargo.toml
@@ -4,6 +4,10 @@ name = "ai_billing"
publish = false
version = "0.1.0"
+[features]
+# Host composition only; admission consumers can keep depending on domain ports.
+pg-admission = ["roles_and_permissions/outbound", "teams/outbound"]
+
[dependencies]
ai_usage = { path = "../ai_usage" }
anyhow = { workspace = true }
diff --git a/crates/ai_billing/src/composition.rs b/crates/ai_billing/src/composition.rs
new file mode 100644
index 0000000000..d643ac4709
--- /dev/null
+++ b/crates/ai_billing/src/composition.rs
@@ -0,0 +1,61 @@
+//! Composition helpers for quota admission without payment collection.
+
+use crate::{
+ AiAdmissionService, AiUsageEnforcement, BillingAdmissionService,
+ domain::BillingServiceImpl,
+ outbound::{NoOpPaymentGateway, PgBillingRepo, PgUsageReader, RolesTeamsEntitlementSource},
+};
+use macro_env::Environment;
+use roles_and_permissions::domain::port::UserRolesAndPermissionsService;
+use sqlx::PgPool;
+use std::sync::Arc;
+use teams::domain::team_repo::TeamRepository;
+
+#[cfg(all(test, feature = "pg-admission"))]
+mod test;
+
+/// Compose quota admission for hosts without an existing billing service.
+/// Adapter construction stays in this owning-domain composition root.
+#[cfg(feature = "pg-admission")]
+pub fn pg_admission_service(
+ pool: PgPool,
+ environment: Environment,
+ enforcement: AiUsageEnforcement,
+) -> Arc<dyn AiAdmissionService> {
+ admission_service(
+ pool.clone(),
+ roles_and_permissions::domain::service::UserRolesAndPermissionsServiceImpl::new(
+ roles_and_permissions::outbound::pgpool::MacroDB::new(pool.clone()),
+ roles_and_permissions::outbound::pgpool::MacroDB::new(pool.clone()),
+ ),
+ teams::outbound::team_repo::TeamRepositoryImpl::new(pool),
+ environment,
+ enforcement,
+ )
+}
+
+/// Compose admission from the host's existing roles service, team repository and
+/// database pool. Both admission and billing receive the same explicit policy.
+/// This service never settles usage, requests collection, or installs financial funding.
+/// Hosts already owning a billing instance can wrap it with [`BillingAdmissionService`].
+pub fn admission_service<P, T>(
+ pool: PgPool,
+ permissions: P,
+ teams: T,
+ environment: Environment,
+ enforcement: AiUsageEnforcement,
+) -> Arc<dyn AiAdmissionService>
+where
+ P: UserRolesAndPermissionsService,
+ T: TeamRepository,
+{
+ let billing = BillingServiceImpl::new(
+ RolesTeamsEntitlementSource::new(permissions, teams),
+ PgUsageReader::new(pool.clone()),
+ PgBillingRepo::new(pool),
+ NoOpPaymentGateway,
+ environment,
+ )
+ .with_enforcement(enforcement);
+ Arc::new(BillingAdmissionService::new(Arc::new(billing), enforcement))
+}
diff --git a/crates/ai_billing/src/composition/test.rs b/crates/ai_billing/src/composition/test.rs
new file mode 100644
index 0000000000..8a4019045b
--- /dev/null
+++ b/crates/ai_billing/src/composition/test.rs
@@ -0,0 +1,100 @@
+use super::*;
+use crate::{AiAdmissionError, AiFeature};
+use macro_user_id::user_id::MacroUserIdStr;
+
+#[sqlx::test(migrator = "macro_db_migrator::MACRO_DB_MIGRATIONS")]
+async fn configured_recorders_preserve_analytics_and_count_only_enabled_billable_usage(
+ pool: PgPool,
+) {
+ use crate::domain::{BillingPeriod, UsageReader, list_rate_cents};
+ use ai_usage::{UsageApiParams, UsageContext, UsageRepo};
+ use std::time::Duration;
+
+ let user = MacroUserIdStr::try_from("macro|[email protected]".to_owned()).unwrap();
+ let disabled =
+ ai_usage::pg_recorder_with_enforcement(pool.clone(), AiUsageEnforcement::Disabled);
+ let enabled = ai_usage::pg_recorder_with_enforcement(pool.clone(), AiUsageEnforcement::Enabled);
+ for (recorder, context) in [
+ (
+ ai_usage::pg_recorder(pool.clone()),
+ UsageContext::new(AiFeature::Chat, user.clone()),
+ ),
+ (disabled, UsageContext::new(AiFeature::Chat, user.clone())),
+ (
+ enabled.clone(),
+ UsageContext::new(AiFeature::Chat, user.clone()),
+ ),
+ (
+ enabled.clone(),
+ UsageContext::new(AiFeature::Memory, user.clone()),
+ ),
+ (enabled, UsageContext::system(AiFeature::Chat)),
+ ] {
+ assert!(recorder.tracking().is_some());
+ recorder.record(context.into_event("claude-opus-5".into(), 1_000_000, 0));
+ }
+
+ let analytics = ai_usage::outbound::PgUsageRepo::new(pool.clone());
+ tokio::time::timeout(Duration::from_secs(5), async {
+ loop {
+ if analytics
+ .query_usage(&UsageApiParams::default())
+ .await
+ .unwrap()
+ .len()
+ == 5
+ {
+ break;
+ }
+ tokio::time::sleep(Duration::from_millis(10)).await;
+ }
+ })
+ .await
+ .expect("all analytics writes must finish, including uncounted usage");
+
+ let usage = PgUsageReader::new(pool)
+ .list_rate_usage_cents_by_user(
+ &[user.clone(), ai_usage::SYSTEM_USER_ID.clone()],
+ BillingPeriod::current(None, chrono::Utc::now()),
+ )
+ .await
+ .unwrap();
+ assert_eq!(usage.len(), 1);
+ assert_eq!(usage[0].user, user);
+ assert_eq!(usage[0].used_cents, list_rate_cents(5.0));
+}
+
+#[tokio::test]
+async fn configured_composition_skips_billing_only_for_disabled_or_exempt_work() {
+ // A closed pool makes every billing access fail immediately, without relying
+ // on a database, network port, or the process environment.
+ let pool = sqlx::postgres::PgPoolOptions::new()
+ .connect_lazy("postgres://localhost/unused")
+ .unwrap();
+ pool.close().await;
+ let user = MacroUserIdStr::try_from("macro|[email protected]".to_owned()).unwrap();
+ for environment in [
+ Environment::Local,
+ Environment::Develop,
+ Environment::Production,
+ ] {
+ let disabled =
+ pg_admission_service(pool.clone(), environment, AiUsageEnforcement::Disabled);
+ assert_eq!(disabled.admit(&user, AiFeature::Chat).await, Ok(()));
+
+ let enabled = pg_admission_service(pool.clone(), environment, AiUsageEnforcement::Enabled);
+ for feature in ai_usage::NON_BILLABLE_AI_FEATURES {
+ assert_eq!(enabled.admit(&user, feature).await, Ok(()));
+ }
+ assert_eq!(
+ enabled
+ .admit(&ai_usage::SYSTEM_USER_ID, AiFeature::Chat)
+ .await,
+ Ok(())
+ );
+ assert_eq!(
+ enabled.admit(&user, AiFeature::Chat).await,
+ Err(AiAdmissionError::Unavailable)
+ );
+ }
+}
diff --git a/crates/ai_billing/src/domain.rs b/crates/ai_billing/src/domain.rs
index 47610b00b2..47db47cc6a 100644
--- a/crates/ai_billing/src/domain.rs
+++ b/crates/ai_billing/src/domain.rs
@@ -1,6 +1,7 @@
//! Domain layer: plans and margin math, the settlement ledger, ports, and the
//! billing service.
+pub mod admission;
pub mod financial;
pub mod ledger;
pub mod models;
@@ -9,6 +10,10 @@ pub mod policy;
pub mod ports;
pub mod service;
+pub use admission::{
+ AdmissionFuture, AiAdmissionError, AiAdmissionService, BillingAdmissionService,
+ DisabledAiAdmissionService,
+};
pub use ledger::{SettlementPlan, SettlementPolicy, SettlementState, plan_settlement};
pub use models::{
AllowanceDecision, AllowanceStore, BillingError, BillingPeriod, BillingSettings,
diff --git a/crates/ai_billing/src/domain/admission.rs b/crates/ai_billing/src/domain/admission.rs
new file mode 100644
index 0000000000..fefe48d75f
--- /dev/null
+++ b/crates/ai_billing/src/domain/admission.rs
@@ -0,0 +1,106 @@
+//! Shared, snapshot-based admission for user-owned AI work. This is not a reservation.
+
+use super::{AllowanceDecision, BillingService, DenyReason};
+use ai_usage::{AiFeature, AiUsageEnforcement};
+use macro_user_id::user_id::MacroUserIdStr;
+use std::{future::Future, pin::Pin, sync::Arc};
+
+#[cfg(test)]
+mod test;
+
+/// Public admission failure. Internal billing diagnostics are logged, never carried here.
+#[derive(
+ Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize, thiserror::Error,
+)]
+#[serde(rename_all = "snake_case")]
+pub enum AiAdmissionError {
+ /// The user's allowance policy refuses new work.
+ #[error("{}", .0.message())]
+ Denied(DenyReason),
+ /// Billing could not validate the request. Retry later without starting AI work.
+ #[error("AI usage validation is temporarily unavailable. Please try again.")]
+ Unavailable,
+}
+
+impl AiAdmissionError {
+ /// Stable public failure code, also suitable for tools and queued commands.
+ pub fn code(self) -> &'static str {
+ match self {
+ Self::Denied(reason) => reason.code(),
+ Self::Unavailable => "ai_billing_unavailable",
+ }
+ }
+
+ /// Whether a bounded retry may succeed without a billing-policy change.
+ pub fn is_retryable(self) -> bool {
+ matches!(self, Self::Unavailable)
+ }
+}
+
+/// Object-safe future returned by the shared admission port.
+pub type AdmissionFuture<'a> =
+ Pin<Box<dyn Future<Output = Result<(), AiAdmissionError>> + Send + 'a>>;
+
+/// Admission for a trusted originating user and a server-selected feature.
+/// Call after authorization, before provider calls or AI-related durable state.
+/// Never substitute the system identity for an unknown or missing caller.
+pub trait AiAdmissionService: Send + Sync + 'static {
+ /// Validate new AI work. Denial and validation failure both prevent execution.
+ fn admit<'a>(&'a self, user: &'a MacroUserIdStr<'_>, feature: AiFeature)
+ -> AdmissionFuture<'a>;
+}
+
+/// Explicitly disabled admission for source-compatible constructors and tests.
+/// Production composition must inject configured admission instead.
+#[derive(Debug, Clone, Copy, Default)]
+pub struct DisabledAiAdmissionService;
+
+impl AiAdmissionService for DisabledAiAdmissionService {
+ fn admit<'a>(
+ &'a self,
+ _user: &'a MacroUserIdStr<'_>,
+ _feature: AiFeature,
+ ) -> AdmissionFuture<'a> {
+ Box::pin(async { Ok(()) })
+ }
+}
+
+/// Shared policy gate around an existing billing service; never requests settlement.
+pub struct BillingAdmissionService<B> {
+ billing: Arc<B>,
+ enforcement: AiUsageEnforcement,
+}
+
+impl<B: BillingService> BillingAdmissionService<B> {
+ /// Wrap billing configured with the same enforcement policy. Existing billing
+ /// instances can be shared with summaries and usage recorders via `Arc`.
+ pub fn new(billing: Arc<B>, enforcement: AiUsageEnforcement) -> Self {
+ Self {
+ billing,
+ enforcement,
+ }
+ }
+}
+
+impl<B: BillingService> AiAdmissionService for BillingAdmissionService<B> {
+ fn admit<'a>(
+ &'a self,
+ user: &'a MacroUserIdStr<'_>,
+ feature: AiFeature,
+ ) -> AdmissionFuture<'a> {
+ // Use exactly the counting policy, before touching any billing port.
+ if !self.enforcement.should_count(user, feature) {
+ return Box::pin(async { Ok(()) });
+ }
+ Box::pin(async move {
+ match self.billing.check_allowance(user).await {
+ Ok(AllowanceDecision::Allow) => Ok(()),
+ Ok(AllowanceDecision::Deny(reason)) => Err(AiAdmissionError::Denied(reason)),
+ Err(error) => {
+ tracing::error!(error = ?error, "AI admission validation failed");
+ Err(AiAdmissionError::Unavailable)
+ }
+ }
+ })
+ }
+}
diff --git a/crates/ai_billing/src/domain/admission/test.rs b/crates/ai_billing/src/domain/admission/test.rs
new file mode 100644
index 0000000000..792d33700d
--- /dev/null
+++ b/crates/ai_billing/src/domain/admission/test.rs
@@ -0,0 +1,156 @@
+use super::*;
+use crate::domain::{Result as BillingResult, UsageSnapshot};
+use ai_usage::domain::ports::SYSTEM_USER_ID;
+use chrono::{DateTime, Utc};
+use std::sync::atomic::{AtomicUsize, Ordering};
+
+struct FakeBilling {
+ decision: Option<AllowanceDecision>,
+ calls: AtomicUsize,
+ fail: bool,
+}
+
+impl FakeBilling {
+ fn new(decision: Option<AllowanceDecision>) -> Arc<Self> {
+ Arc::new(Self {
+ decision,
+ calls: AtomicUsize::new(0),
+ fail: false,
+ })
+ }
+}
+
+impl BillingService for FakeBilling {
+ async fn check_allowance(&self, user: &MacroUserIdStr<'_>) -> BillingResult<AllowanceDecision> {
+ assert_eq!(user.as_ref(), "macro|[email protected]");
+ self.calls.fetch_add(1, Ordering::SeqCst);
+ if self.fail {
+ return Err(crate::BillingError::Storage(anyhow::anyhow!(
+ "private database credentials and diagnostics"
+ )));
+ }
+ Ok(self.decision.expect("billing must not be called"))
+ }
+
+ async fn snapshot(&self, _: &MacroUserIdStr<'_>) -> BillingResult<UsageSnapshot> {
+ panic!("admission must not call snapshot")
+ }
+ async fn settle(&self, _: &MacroUserIdStr<'_>) -> BillingResult<()> {
+ panic!("admission must not settle")
+ }
+ async fn update_overage(
+ &self,
+ _: &MacroUserIdStr<'_>,
+ _: bool,
+ _: i64,
+ ) -> BillingResult<UsageSnapshot> {
+ panic!("admission must not change settings")
+ }
+ async fn create_credit_checkout(
+ &self,
+ _: &MacroUserIdStr<'_>,
+ _: i64,
+ _: String,
+ _: String,
+ ) -> BillingResult<String> {
+ panic!("admission must not purchase credits")
+ }
+ async fn apply_credit_purchase(
+ &self,
+ _: &MacroUserIdStr<'_>,
+ _: i64,
+ _: &str,
+ ) -> BillingResult<()> {
+ panic!("admission must not apply credits")
+ }
+ async fn sync_period(
+ &self,
+ _: &MacroUserIdStr<'_>,
+ _: DateTime<Utc>,
+ _: DateTime<Utc>,
+ _: Option<crate::domain::period::SubscriptionPeriod>,
+ ) -> BillingResult<()> {
+ panic!("admission must not sync periods")
+ }
+ async fn mark_overage_invoice(&self, _: &str, _: bool) -> BillingResult<()> {
+ panic!("admission must not handle invoices")
+ }
+}
+
+fn user() -> MacroUserIdStr<'static> {
+ MacroUserIdStr::try_from("macro|[email protected]").unwrap()
+}
+
+#[tokio::test]
+async fn disabled_exempt_and_system_work_never_calls_billing() {
+ let billing = FakeBilling::new(None);
+ for enforcement in [AiUsageEnforcement::Disabled, AiUsageEnforcement::Enabled] {
+ let admission: Arc<dyn AiAdmissionService> =
+ Arc::new(BillingAdmissionService::new(billing.clone(), enforcement));
+ for feature in crate::domain::models::NON_BILLABLE_AI_FEATURES {
+ admission.admit(&user(), feature).await.unwrap();
+ }
+ admission
+ .admit(&SYSTEM_USER_ID, AiFeature::Chat)
+ .await
+ .unwrap();
+ if !enforcement.is_enabled() {
+ admission.admit(&user(), AiFeature::Chat).await.unwrap();
+ admission
+ .admit(&user(), AiFeature::AiEditing)
+ .await
+ .unwrap();
+ }
+ }
+ assert_eq!(billing.calls.load(Ordering::SeqCst), 0);
+ DisabledAiAdmissionService
+ .admit(&user(), AiFeature::Chat)
+ .await
+ .unwrap();
+}
+
+#[tokio::test]
+async fn enabled_admission_preserves_allowance_decisions() {
+ for decision in [
+ AllowanceDecision::Allow,
+ AllowanceDecision::Deny(DenyReason::AllowanceExhausted),
+ AllowanceDecision::Deny(DenyReason::OverageLimitReached),
+ AllowanceDecision::Deny(DenyReason::OveragePaymentFailed),
+ ] {
+ let billing = FakeBilling::new(Some(decision));
+ let admission = BillingAdmissionService::new(billing.clone(), AiUsageEnforcement::Enabled);
+ for feature in [
+ AiFeature::Chat,
+ AiFeature::AiEditing,
+ AiFeature::ChatRename,
+ AiFeature::AgentRepositoryChoice,
+ ] {
+ let result = admission.admit(&user(), feature).await;
+ match decision {
+ AllowanceDecision::Allow => assert_eq!(result, Ok(())),
+ AllowanceDecision::Deny(reason) => {
+ assert_eq!(result, Err(AiAdmissionError::Denied(reason)));
+ assert!(!result.unwrap_err().is_retryable());
+ }
+ }
+ }
+ assert_eq!(billing.calls.load(Ordering::SeqCst), 4);
+ }
+}
+
+#[tokio::test]
+async fn billing_errors_fail_closed_without_exposing_reports() {
+ let billing = Arc::new(FakeBilling {
+ decision: None,
+ calls: AtomicUsize::new(0),
+ fail: true,
+ });
+ let admission = BillingAdmissionService::new(billing.clone(), AiUsageEnforcement::Enabled);
+ let error = admission.admit(&user(), AiFeature::Chat).await.unwrap_err();
+ assert_eq!(error, AiAdmissionError::Unavailable);
+ assert_eq!(error.code(), "ai_billing_unavailable");
+ assert!(error.is_retryable());
+ assert!(!error.to_string().contains("private"));
+ assert_eq!(format!("{error:?}"), "Unavailable");
+ assert_eq!(billing.calls.load(Ordering::SeqCst), 1);
+}
diff --git a/crates/ai_billing/src/domain/models.rs b/crates/ai_billing/src/domain/models.rs
index 50becdd86a..fec32118e3 100644
--- a/crates/ai_billing/src/domain/models.rs
+++ b/crates/ai_billing/src/domain/models.rs
@@ -1,6 +1,6 @@
//! Plans, the margin math, billing periods, and the API-facing snapshot.
-use ai_usage::AiFeature;
+pub use ai_usage::NON_BILLABLE_AI_FEATURES;
use chrono::{DateTime, Datelike, Months, TimeZone, Utc};
use macro_user_id::user_id::MacroUserIdStr;
use macro_uuid::Uuid;
@@ -27,15 +27,6 @@ pub const TARGET_GROSS_MARGIN_BPS: i64 = 6_000;
const BPS_PER_UNIT: i64 = 10_000;
-/// Features whose provider costs are recorded but never consume allowances,
-/// prepaid credits, or overage. Dictation is the Whispr transcription feature.
-pub const NON_BILLABLE_AI_FEATURES: [AiFeature; 4] = [
- AiFeature::Memory,
- AiFeature::AiProjection,
- AiFeature::CallSummary,
- AiFeature::Dictation,
-];
-
/// Legacy only: convert a provider cost in USD to Macro's list rate in whole cents,
/// rounding up so fractional cents never accrue in the customer's favour.
pub fn list_rate_cents(provider_cost_usd: f64) -> i64 {
diff --git a/crates/ai_billing/src/domain/ports.rs b/crates/ai_billing/src/domain/ports.rs
index 4785becea3..5622aa0a83 100644
--- a/crates/ai_billing/src/domain/ports.rs
+++ b/crates/ai_billing/src/domain/ports.rs
@@ -75,9 +75,10 @@ pub trait EntitlementSource: Send + Sync + 'static {
pub trait UsageReader: Send + Sync + 'static {
/// List-rate usage for each of `users` within `period`.
///
- /// [`NON_BILLABLE_AI_FEATURES`](super::models::NON_BILLABLE_AI_FEATURES)
- /// remain in `ai_usage` for cost tracking but do not consume a user's
- /// allowance, credits, or overage.
+ /// Only rows with the persisted `count_usage = TRUE` decision consume a user's
+ /// allowance, credits, or overage. Historical and uncounted rows remain available
+ /// for cost tracking. The period is inclusive at the start and exclusive at the end;
+ /// users with no counted rows are omitted, and an empty user list returns no rows.
fn list_rate_usage_cents_by_user(
&self,
users: &[MacroUserIdStr<'static>],
diff --git a/crates/ai_billing/src/domain/service.rs b/crates/ai_billing/src/domain/service.rs
index 8fd5ec5823..2976f6dd3f 100644
--- a/crates/ai_billing/src/domain/service.rs
+++ b/crates/ai_billing/src/domain/service.rs
@@ -16,6 +16,7 @@ use super::ports::{
BillingRepo, BillingService, CreditCheckoutRequest, EntitlementSource, OverageChargeRequest,
PaymentGateway, PendingCharge, UsageReader,
};
+use ai_usage::AiUsageEnforcement;
use chrono::{DateTime, Utc};
use macro_env::Environment;
use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};
@@ -31,11 +32,13 @@ pub struct BillingServiceImpl<E, U, R, P> {
repo: R,
payments: P,
environment: Environment,
+ enforcement: AiUsageEnforcement,
period_sync: Option<Arc<dyn PeriodSync>>,
}
impl<E, U, R, P> BillingServiceImpl<E, U, R, P> {
- /// Construct the service. Allowance enforcement and settlement run only in dev.
+ /// Construct with quota enforcement disabled. Settlement remains dev-only.
+ /// Production composition must explicitly install the configured enforcement policy.
pub fn new(entitlements: E, usage: U, repo: R, payments: P, environment: Environment) -> Self {
Self {
entitlements,
@@ -43,10 +46,17 @@ impl<E, U, R, P> BillingServiceImpl<E, U, R, P> {
repo,
payments,
environment,
+ enforcement: AiUsageEnforcement::Disabled,
period_sync: None,
}
}
+ /// Configure quota enforcement independently of the settlement environment guard.
+ pub fn with_enforcement(mut self, enforcement: AiUsageEnforcement) -> Self {
+ self.enforcement = enforcement;
+ self
+ }
+
/// Install verified renewal activation at the composition root only after the
/// producer and rollout gates pass. Absence never authorizes the new policy.
pub fn with_period_sync(mut self, period_sync: Arc<dyn PeriodSync>) -> Self {
@@ -473,7 +483,7 @@ where
{
#[tracing::instrument(skip(self), err)]
async fn check_allowance(&self, user: &MacroUserIdStr<'_>) -> Result<AllowanceDecision> {
- if !matches!(self.environment, Environment::Develop) {
+ if !self.enforcement.is_enabled() {
return Ok(AllowanceDecision::Allow);
}
let position = self.position(user, Utc::now()).await?;
@@ -488,8 +498,8 @@ where
async fn snapshot(&self, user: &MacroUserIdStr<'_>) -> Result<UsageSnapshot> {
let position = self.position(user, Utc::now()).await?;
let mut snapshot = self.snapshot_at(user, &position).await?;
- // Keep the summary consistent with the allowance gate outside dev.
- if !matches!(self.environment, Environment::Develop) {
+ // Keep the summary consistent with the configured allowance gate.
+ if !self.enforcement.is_enabled() {
snapshot.blocked_reason = None;
}
Ok(snapshot)
diff --git a/crates/ai_billing/src/domain/service/test.rs b/crates/ai_billing/src/domain/service/test.rs
index 7f56af64db..f9f1a0954a 100644
--- a/crates/ai_billing/src/domain/service/test.rs
+++ b/crates/ai_billing/src/domain/service/test.rs
@@ -594,7 +594,8 @@ fn premium_service_in(
repo.clone(),
payments.clone(),
environment,
- ),
+ )
+ .with_enforcement(AiUsageEnforcement::Enabled),
repo,
payments,
usage,
@@ -674,9 +675,14 @@ async fn allows_within_allowance_and_denies_past_it() {
}
#[tokio::test]
-async fn outside_dev_allows_exhausted_allowances_caps_and_failed_payments() {
- for environment in [Environment::Production, Environment::Local] {
+async fn disabled_allows_exhausted_allowances_caps_and_failed_payments_in_every_environment() {
+ for environment in [
+ Environment::Local,
+ Environment::Develop,
+ Environment::Production,
+ ] {
let (svc, repo, _, _) = premium_service_in(environment, 1_000_000);
+ let svc = svc.with_enforcement(AiUsageEnforcement::Disabled);
let payer = user("[email protected]");
assert_eq!(
svc.check_allowance(&payer).await.unwrap(),
@@ -684,8 +690,9 @@ async fn outside_dev_allows_exhausted_allowances_caps_and_failed_payments() {
);
assert_eq!(svc.snapshot(&payer).await.unwrap().blocked_reason, None);
- let snapshot = svc.update_overage(&payer, true, 1_000).await.unwrap();
- assert_eq!(snapshot.blocked_reason, None);
+ // Changing settings directly keeps this admission test independent of settlement.
+ repo.update_overage(&payer, true, 1_000).await.unwrap();
+ assert_eq!(svc.snapshot(&payer).await.unwrap().blocked_reason, None);
assert_eq!(
svc.check_allowance(&payer).await.unwrap(),
AllowanceDecision::Allow
@@ -700,6 +707,80 @@ async fn outside_dev_allows_exhausted_allowances_caps_and_failed_payments() {
}
}
+#[tokio::test]
+async fn enabled_enforces_allowances_in_every_environment_without_settlement() {
+ for environment in [
+ Environment::Local,
+ Environment::Develop,
+ Environment::Production,
+ ] {
+ let (svc, repo, payments, usage) = premium_service_in(environment, 4_000);
+ let payer = user("[email protected]");
+ assert_eq!(
+ svc.check_allowance(&payer).await.unwrap(),
+ AllowanceDecision::Deny(DenyReason::AllowanceExhausted)
+ );
+ assert_eq!(
+ svc.snapshot(&payer).await.unwrap().blocked_reason,
+ Some(DenyReason::AllowanceExhausted)
+ );
+ repo.update_overage(&payer, true, 1_000).await.unwrap();
+ *usage.cents.lock().unwrap() = 5_000;
+ assert_eq!(
+ svc.check_allowance(&payer).await.unwrap(),
+ AllowanceDecision::Deny(DenyReason::OverageLimitReached)
+ );
+ repo.state.lock().unwrap().suspended = true;
+ assert_eq!(
+ svc.check_allowance(&payer).await.unwrap(),
+ AllowanceDecision::Deny(DenyReason::OveragePaymentFailed)
+ );
+ assert!(repo.charges().is_empty());
+ assert!(repo.state.lock().unwrap().consumed.is_empty());
+ assert!(payments.opened().is_empty());
+ assert!(payments.payments().is_empty());
+ }
+}
+
+#[tokio::test]
+async fn default_disabled_gate_and_production_settlement_do_not_read_entitlements() {
+ struct PanicEntitlements;
+ impl EntitlementSource for PanicEntitlements {
+ async fn entitlement(&self, _: &MacroUserIdStr<'_>) -> Result<Entitlement> {
+ panic!("must not read entitlements")
+ }
+ async fn stripe_customer_id(&self, _: &MacroUserIdStr<'_>) -> Result<Option<String>> {
+ panic!("must not resolve a payment customer")
+ }
+ async fn team_payer(&self, _: Uuid) -> Result<Option<MacroUserIdStr<'static>>> {
+ panic!("must not resolve a team payer")
+ }
+ }
+ for environment in [
+ Environment::Local,
+ Environment::Develop,
+ Environment::Production,
+ ] {
+ let svc = BillingServiceImpl::new(
+ PanicEntitlements,
+ FakeUsage::default(),
+ FakeRepo::default(),
+ FakePayments::default(),
+ environment,
+ );
+ assert_eq!(
+ svc.check_allowance(&user("[email protected]")).await.unwrap(),
+ AllowanceDecision::Allow
+ );
+ if !matches!(environment, Environment::Develop) {
+ svc.with_enforcement(AiUsageEnforcement::Enabled)
+ .settle(&user("[email protected]"))
+ .await
+ .unwrap();
+ }
+ }
+}
+
#[tokio::test]
async fn outside_dev_preserves_credits_and_never_reserves_or_collects_overage() {
for environment in [Environment::Production, Environment::Local] {
@@ -1077,7 +1158,8 @@ async fn team_seats_keep_allowances_separate_and_share_credits() {
repo.clone(),
FakePayments::default(),
Environment::Develop,
- );
+ )
+ .with_enforcement(AiUsageEnforcement::Enabled);
let owner_snapshot = service.snapshot(&owner).await.unwrap();
assert_eq!(owner_snapshot.used_cents, 0);
diff --git a/crates/ai_billing/src/inbound.rs b/crates/ai_billing/src/inbound.rs
index 72a2c65cb2..88d6a1c13e 100644
--- a/crates/ai_billing/src/inbound.rs
+++ b/crates/ai_billing/src/inbound.rs
@@ -1,5 +1,6 @@
//! Inbound adapters: the axum router.
+pub mod admission;
pub mod axum_router;
pub use axum_router::{AiBillingRouterState, ai_billing_router};
diff --git a/crates/ai_billing/src/inbound/admission.rs b/crates/ai_billing/src/inbound/admission.rs
new file mode 100644
index 0000000000..3702e4344e
--- /dev/null
+++ b/crates/ai_billing/src/inbound/admission.rs
@@ -0,0 +1,44 @@
+//! Sanitized HTTP contract for AI admission failures.
+
+use crate::AiAdmissionError;
+use axum::{
+ Json,
+ http::StatusCode,
+ response::{IntoResponse, Response},
+};
+use serde::Serialize;
+use utoipa::ToSchema;
+
+#[cfg(test)]
+mod test;
+
+/// Public admission error payload. Handlers with additional fields can reuse the
+/// domain error's code and message and [`admission_status`].
+#[derive(Debug, Serialize, ToSchema)]
+pub struct AiAdmissionErrorBody {
+ /// Human-readable explanation, without internal billing diagnostics.
+ pub error: String,
+ /// Stable denial or unavailability code.
+ pub code: String,
+}
+
+/// Map policy refusals to 402 and retryable validation failures to 503.
+pub fn admission_status(error: AiAdmissionError) -> StatusCode {
+ match error {
+ AiAdmissionError::Denied(_) => StatusCode::PAYMENT_REQUIRED,
+ AiAdmissionError::Unavailable => StatusCode::SERVICE_UNAVAILABLE,
+ }
+}
+
+impl IntoResponse for AiAdmissionError {
+ fn into_response(self) -> Response {
+ (
+ admission_status(self),
+ Json(AiAdmissionErrorBody {
+ error: self.to_string(),
+ code: self.code().to_string(),
+ }),
+ )
+ .into_response()
+ }
+}
diff --git a/crates/ai_billing/src/inbound/admission/test.rs b/crates/ai_billing/src/inbound/admission/test.rs
new file mode 100644
index 0000000000..9059611e30
--- /dev/null
+++ b/crates/ai_billing/src/inbound/admission/test.rs
@@ -0,0 +1,39 @@
+use super::*;
+use crate::DenyReason;
+use axum::body::to_bytes;
+
+#[tokio::test]
+async fn denials_preserve_existing_codes_and_messages() {
+ for reason in [
+ DenyReason::AllowanceExhausted,
+ DenyReason::OverageLimitReached,
+ DenyReason::OveragePaymentFailed,
+ ] {
+ let response = AiAdmissionError::Denied(reason).into_response();
+ assert_eq!(response.status(), StatusCode::PAYMENT_REQUIRED);
+ let bytes = to_bytes(response.into_body(), 4096).await.unwrap();
+ let body: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
+ assert_eq!(
+ body,
+ serde_json::json!({"error": reason.message(), "code": reason.code()})
+ );
+ }
+}
+
+#[tokio::test]
+async fn unavailable_is_a_sanitized_retryable_503() {
+ let error = AiAdmissionError::Unavailable;
+ assert!(error.is_retryable());
+ let response = error.into_response();
+ assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
+ assert_eq!(response.headers()["content-type"], "application/json");
+ let bytes = to_bytes(response.into_body(), 4096).await.unwrap();
+ let body: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
+ assert_eq!(
+ body,
+ serde_json::json!({
+ "error": "AI usage validation is temporarily unavailable. Please try again.",
+ "code": "ai_billing_unavailable"
+ })
+ );
+}
diff --git a/crates/ai_billing/src/lib.rs b/crates/ai_billing/src/lib.rs
index c50d79c712..822780fbc3 100644
--- a/crates/ai_billing/src/lib.rs
+++ b/crates/ai_billing/src/lib.rs
@@ -34,12 +34,15 @@
//! whose paid access comes through a team subscription. Each team seat uses
//! only its own plan allowance; credits and overage are shared by the payer.
+pub mod composition;
pub mod domain;
pub mod inbound;
pub mod outbound;
+pub use ai_usage::{AiFeature, AiUsageEnforcement};
pub use domain::{
- AllowanceDecision, BillingError, BillingPeriod, BillingService, BillingSettings,
- CREDIT_PACKS_CENTS, DenyReason, Entitlement, PayerScope, PlanTier, TARGET_GROSS_MARGIN_BPS,
- UsageSnapshot, list_rate_cents,
+ AdmissionFuture, AiAdmissionError, AiAdmissionService, AllowanceDecision,
+ BillingAdmissionService, BillingError, BillingPeriod, BillingService, BillingSettings,
+ CREDIT_PACKS_CENTS, DenyReason, DisabledAiAdmissionService, Entitlement, PayerScope, PlanTier,
+ TARGET_GROSS_MARGIN_BPS, UsageSnapshot, list_rate_cents,
};
diff --git a/crates/ai_billing/src/outbound/pg_usage_reader.rs b/crates/ai_billing/src/outbound/pg_usage_reader.rs
index a6de5bed91..e2cfcba52a 100644
--- a/crates/ai_billing/src/outbound/pg_usage_reader.rs
+++ b/crates/ai_billing/src/outbound/pg_usage_reader.rs
@@ -1,15 +1,14 @@
-//! Reads recorded AI usage from `ai_usage` at Macro's list rate.
+//! Reads prospectively counted AI usage from `ai_usage` at Macro's list rate.
#[cfg(test)]
mod test;
-use crate::domain::models::NON_BILLABLE_AI_FEATURES;
use crate::domain::{BillingError, BillingPeriod, Result, SeatUsage, UsageReader, list_rate_cents};
use macro_user_id::user_id::MacroUserIdStr;
use sqlx::PgPool;
-/// Rows recorded before a model had pricing carry a NULL total. Bill them at
-/// the Opus 5 rate rather than for free; `set_pricing` backfills them later.
+/// Counted rows recorded before a model had pricing carry a NULL total. Price
+/// them at the Opus 5 rate rather than for free; `set_pricing` backfills them later.
///
/// These mirror the `claude-opus-5` row seeded into `ai_pricing` by
/// `20260724182218_seed_claude_opus_5_pricing.sql` ($5 in / $25 out per
@@ -41,7 +40,6 @@ impl UsageReader for PgUsageReader {
return Ok(Vec::new());
}
let ids: Vec<String> = users.iter().map(|u| u.as_ref().to_string()).collect();
- let non_billable_features = NON_BILLABLE_AI_FEATURES.map(|feature| feature.to_string());
let rows = sqlx::query!(
r#"
SELECT user_id, COALESCE(SUM(
@@ -55,7 +53,7 @@ impl UsageReader for PgUsageReader {
WHERE user_id = ANY($1)
AND created_at >= $2
AND created_at < $3
- AND feature <> ALL($6)
+ AND count_usage = TRUE
GROUP BY user_id
"#,
&ids,
@@ -63,7 +61,6 @@ impl UsageReader for PgUsageReader {
period.end,
FALLBACK_PRICE_PER_MILLION_IN,
FALLBACK_PRICE_PER_MILLION_OUT,
- &non_billable_features,
)
.fetch_all(&self.pool)
.await
diff --git a/crates/ai_billing/src/outbound/pg_usage_reader/test.rs b/crates/ai_billing/src/outbound/pg_usage_reader/test.rs
index 9b6dae525f..d0604166fb 100644
--- a/crates/ai_billing/src/outbound/pg_usage_reader/test.rs
+++ b/crates/ai_billing/src/outbound/pg_usage_reader/test.rs
@@ -51,6 +51,127 @@ fn free_completions(user: MacroUserIdStr<'static>) -> [CompletionUsage; 4] {
]
}
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn aggregates_only_persisted_counted_rows_for_requested_seats(pool: PgPool) {
+ let first = MacroUserIdStr::try_from("macro|[email protected]".to_string()).unwrap();
+ let second = MacroUserIdStr::try_from("macro|[email protected]".to_string()).unwrap();
+ let outside = MacroUserIdStr::try_from("macro|[email protected]".to_string()).unwrap();
+ let empty = MacroUserIdStr::try_from("macro|[email protected]".to_string()).unwrap();
+ let repo = PgUsageRepo::new(pool.clone());
+ for (user, total, counted) in [
+ (&first, 1.0, true),
+ (&first, 3.0, true),
+ (&first, 100.0, false),
+ (&second, 2.0, true),
+ (&second, 200.0, false),
+ (&outside, 300.0, true),
+ (&empty, 400.0, false),
+ ] {
+ repo.insert_usage(&completion(user.clone(), AiFeature::Chat, total), counted)
+ .await
+ .unwrap();
+ }
+ // The stored decision, not today's feature classification, is authoritative.
+ repo.insert_usage(&completion(second.clone(), AiFeature::Memory, 1.0), true)
+ .await
+ .unwrap();
+ let mut unpriced = completion(second.clone(), AiFeature::Chat, 0.0);
+ unpriced.cost.price = None;
+ unpriced.cost.amount = UsageAmount::Tokens {
+ input: 1_000_000,
+ output: 1_000_000,
+ };
+ repo.insert_usage(&unpriced, true).await.unwrap(); // $5 input + $25 output
+ repo.insert_usage(&unpriced, false).await.unwrap();
+
+ // A default-false legacy write must never acquire debt via fallback pricing.
+ sqlx::query!(
+ r#"INSERT INTO ai_usage (id, feature, user_id, model, input_tokens, output_tokens)
+ VALUES ($1, 'chat', $2, 'legacy-model', 1000000, 1000000)"#,
+ macro_uuid::generate_uuid_v7(),
+ first.as_ref(),
+ )
+ .execute(&pool)
+ .await
+ .unwrap();
+
+ let reader = PgUsageReader::new(pool);
+ let mut usage = reader
+ .list_rate_usage_cents_by_user(&[first.clone(), second.clone(), empty], current_period())
+ .await
+ .unwrap();
+ usage.sort_by(|a, b| a.user.as_ref().cmp(b.user.as_ref()));
+ assert_eq!(
+ usage,
+ vec![
+ SeatUsage {
+ user: first.clone(),
+ used_cents: 1_000
+ },
+ SeatUsage {
+ user: second,
+ used_cents: 8_250
+ },
+ ]
+ );
+ assert!(
+ reader
+ .list_rate_usage_cents_by_user(&[], current_period())
+ .await
+ .unwrap()
+ .is_empty()
+ );
+ assert_eq!(
+ reader
+ .list_rate_usage_cents_by_user(std::slice::from_ref(&first), current_period())
+ .await
+ .unwrap(),
+ vec![SeatUsage {
+ user: first,
+ used_cents: 1_000
+ }]
+ );
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn billing_period_includes_start_and_excludes_end(pool: PgPool) {
+ let user = MacroUserIdStr::try_from("macro|[email protected]".to_string()).unwrap();
+ let start = chrono::DateTime::from_timestamp(1_800_000_000, 0).unwrap();
+ let end = start + Duration::days(30);
+ for (created_at, count_usage) in [
+ (start - Duration::microseconds(1), true),
+ (start, true),
+ (end - Duration::microseconds(1), true),
+ (end, true),
+ (end + Duration::microseconds(1), true),
+ (start, false),
+ ] {
+ sqlx::query!(
+ r#"INSERT INTO ai_usage (id, feature, user_id, model, input_tokens, output_tokens,
+ total, created_at, count_usage)
+ VALUES ($1, 'chat', $2, 'test-model', 0, 0, 1.0, $3, $4)"#,
+ macro_uuid::generate_uuid_v7(),
+ user.as_ref(),
+ created_at,
+ count_usage,
+ )
+ .execute(&pool)
+ .await
+ .unwrap();
+ }
+ let usage = PgUsageReader::new(pool)
+ .list_rate_usage_cents_by_user(std::slice::from_ref(&user), BillingPeriod { start, end })
+ .await
+ .unwrap();
+ assert_eq!(
+ usage,
+ vec![SeatUsage {
+ user,
+ used_cents: 500
+ }]
+ );
+}
+
fn current_period() -> BillingPeriod {
let now = Utc::now();
BillingPeriod {
@@ -63,11 +184,15 @@ fn current_period() -> BillingPeriod {
async fn free_features_are_recorded_but_only_chat_and_editing_are_metered(pool: PgPool) {
let user = MacroUserIdStr::try_from("macro|[email protected]".to_string()).unwrap();
let usage_repo = PgUsageRepo::new(pool.clone());
- for usage in free_completions(user.clone()).into_iter().chain([
- completion(user.clone(), AiFeature::Chat, 4.0),
- completion(user.clone(), AiFeature::AiEditing, 2.0),
- ]) {
- usage_repo.insert_usage(&usage).await.unwrap();
+ for (usage, count_usage) in free_completions(user.clone())
+ .into_iter()
+ .map(|usage| (usage, false))
+ .chain([
+ (completion(user.clone(), AiFeature::Chat, 4.0), true),
+ (completion(user.clone(), AiFeature::AiEditing, 2.0), true),
+ ])
+ {
+ usage_repo.insert_usage(&usage, count_usage).await.unwrap();
}
let stored_usage = usage_repo
@@ -97,7 +222,7 @@ async fn free_features_are_recorded_but_only_chat_and_editing_are_metered(pool:
assert_eq!(stored_features, expected_features);
let usage = PgUsageReader::new(pool)
- .list_rate_usage_cents_by_user(&[user.clone()], current_period())
+ .list_rate_usage_cents_by_user(std::slice::from_ref(&user), current_period())
.await
.unwrap();
@@ -115,7 +240,7 @@ async fn free_features_alone_do_not_produce_billable_usage(pool: PgPool) {
let user = MacroUserIdStr::try_from("macro|[email protected]".to_string()).unwrap();
let usage_repo = PgUsageRepo::new(pool.clone());
for usage in free_completions(user.clone()) {
- usage_repo.insert_usage(&usage).await.unwrap();
+ usage_repo.insert_usage(&usage, false).await.unwrap();
}
let usage = PgUsageReader::new(pool)
@@ -129,16 +254,20 @@ async fn free_features_alone_do_not_produce_billable_usage(pool: PgPool) {
async fn unpriced_free_features_are_excluded_from_fallback_billing(pool: PgPool) {
let user = MacroUserIdStr::try_from("macro|[email protected]".to_string()).unwrap();
let usage_repo = PgUsageRepo::new(pool.clone());
- for mut usage in free_completions(user.clone()).into_iter().chain([
- completion(user.clone(), AiFeature::Chat, 4.0),
- completion(user.clone(), AiFeature::AiEditing, 2.0),
- ]) {
+ for (mut usage, count_usage) in free_completions(user.clone())
+ .into_iter()
+ .map(|usage| (usage, false))
+ .chain([
+ (completion(user.clone(), AiFeature::Chat, 4.0), true),
+ (completion(user.clone(), AiFeature::AiEditing, 2.0), true),
+ ])
+ {
usage.cost.price = None;
- usage_repo.insert_usage(&usage).await.unwrap();
+ usage_repo.insert_usage(&usage, count_usage).await.unwrap();
}
let usage = PgUsageReader::new(pool)
- .list_rate_usage_cents_by_user(&[user.clone()], current_period())
+ .list_rate_usage_cents_by_user(std::slice::from_ref(&user), current_period())
.await
.unwrap();
diff --git a/crates/ai_billing/src/outbound/settling_recorder.rs b/crates/ai_billing/src/outbound/settling_recorder.rs
index 75fe2d141a..94a09c9f8a 100644
--- a/crates/ai_billing/src/outbound/settling_recorder.rs
+++ b/crates/ai_billing/src/outbound/settling_recorder.rs
@@ -6,7 +6,7 @@ mod test;
use crate::domain::{BillingService, SettlementTrigger};
use ai_usage::domain::service::UsageServiceImpl;
-use ai_usage::{SYSTEM_USER_ID, UsageEvent, UsageRecorder, UsageRepo};
+use ai_usage::{UsageEvent, UsageRecorder, UsageRepo};
use macro_env::Environment;
use std::sync::Arc;
use std::time::Duration;
@@ -19,8 +19,8 @@ const RECORD_RETRY_BACKOFF: [Duration; 3] = [
Duration::from_secs(5),
];
-/// Wraps the Postgres usage recorder. After each row lands it reads the
-/// payer's position and, when there is uncovered usage, triggers settlement
+/// Wraps the Postgres usage recorder. After a counted row lands in dev it reads
+/// the payer's position and, when there is uncovered usage, triggers settlement
/// (credit consumption and overage collection) in the service that owns
/// Stripe. Recording stays best-effort and never delays the completion.
///
@@ -36,7 +36,8 @@ pub struct SettlingUsageRecorder<Repo, B, T> {
}
impl<Repo, B, T> SettlingUsageRecorder<Repo, B, T> {
- /// Build the recorder. Usage is recorded everywhere; settlement is requested only in dev.
+ /// Build the recorder. Usage is recorded everywhere; only counted usage in
+ /// dev can request settlement. The inner service owns the counting policy.
pub fn new(
inner: Arc<UsageServiceImpl<Repo>>,
billing: Arc<B>,
@@ -62,7 +63,8 @@ where
let inner = self.inner.clone();
let billing = self.billing.clone();
let trigger = self.trigger.clone();
- let environment = self.environment;
+ let should_settle =
+ matches!(self.environment, Environment::Develop) && inner.counts_usage(&event);
tokio::spawn(async move {
let user = event.user.clone();
let mut backoff = RECORD_RETRY_BACKOFF.iter();
@@ -87,9 +89,7 @@ where
}
}
}
- if !matches!(environment, Environment::Develop)
- || user.as_ref() == SYSTEM_USER_ID.as_ref()
- {
+ if !should_settle {
return;
}
match billing.snapshot(&user).await {
diff --git a/crates/ai_billing/src/outbound/settling_recorder/test.rs b/crates/ai_billing/src/outbound/settling_recorder/test.rs
index ad58869a73..a7bb834ade 100644
--- a/crates/ai_billing/src/outbound/settling_recorder/test.rs
+++ b/crates/ai_billing/src/outbound/settling_recorder/test.rs
@@ -4,27 +4,32 @@ use crate::domain::{
UsageSnapshot, ledger::build_snapshot,
};
use ai_usage::domain::{Result as UsageResult, UsageError};
-use ai_usage::{AiFeature, CompletionUsage, ModelPricing, UsageApiParams, UsageContext};
+use ai_usage::{
+ AiFeature, AiUsageEnforcement, CompletionUsage, ModelPricing, SYSTEM_USER_ID, UsageApiParams,
+ UsageContext,
+};
use chrono::{DateTime, Utc};
use macro_user_id::user_id::MacroUserIdStr;
-use std::sync::atomic::{AtomicUsize, Ordering};
+use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use tokio::sync::Notify;
#[derive(Clone, Default)]
struct FakeUsageRepo {
attempts: Arc<AtomicUsize>,
recorded: Arc<Notify>,
+ counted: Arc<AtomicBool>,
fail_first: bool,
}
impl UsageRepo for FakeUsageRepo {
- async fn insert_usage(&self, _usage: &CompletionUsage) -> UsageResult<()> {
+ async fn insert_usage(&self, _usage: &CompletionUsage, count_usage: bool) -> UsageResult<()> {
let attempt = self.attempts.fetch_add(1, Ordering::SeqCst);
if self.fail_first && attempt == 0 {
return Err(UsageError::Other(anyhow::anyhow!(
"transient write failure"
)));
}
+ self.counted.store(count_usage, Ordering::SeqCst);
self.recorded.notify_one();
Ok(())
}
@@ -120,6 +125,27 @@ async fn record(
unlimited: bool,
chargeable_cents: i64,
fail_first: bool,
+) -> (usize, usize, usize) {
+ record_with_policy(
+ environment,
+ user,
+ tier,
+ unlimited,
+ chargeable_cents,
+ fail_first,
+ (AiUsageEnforcement::Enabled, AiFeature::Chat),
+ )
+ .await
+}
+
+async fn record_with_policy(
+ environment: Environment,
+ user: MacroUserIdStr<'static>,
+ tier: PlanTier,
+ unlimited: bool,
+ chargeable_cents: i64,
+ fail_first: bool,
+ (enforcement, feature): (AiUsageEnforcement, AiFeature),
) -> (usize, usize, usize) {
let repo = FakeUsageRepo {
fail_first,
@@ -142,21 +168,19 @@ async fn record(
});
let trigger = FakeTrigger::default();
let recorder = SettlingUsageRecorder::new(
- Arc::new(UsageServiceImpl::new(repo.clone())),
+ Arc::new(UsageServiceImpl::new(repo.clone()).with_enforcement(enforcement)),
billing.clone(),
trigger.clone(),
environment,
);
- recorder.record(UsageContext::new(AiFeature::Chat, user).into_event(
- "test-model".into(),
- 10,
- 10,
- ));
+ let should_count = enforcement.should_count(&user, feature);
+ recorder.record(UsageContext::new(feature, user).into_event("test-model".into(), 10, 10));
tokio::time::timeout(Duration::from_secs(2), repo.recorded.notified())
.await
.expect("usage must be recorded in every environment, including after a retry");
// All fake billing/trigger calls are immediately ready; let the recording task finish.
tokio::task::yield_now().await;
+ assert_eq!(repo.counted.load(Ordering::SeqCst), should_count);
(
repo.attempts.load(Ordering::SeqCst),
billing.snapshots.load(Ordering::SeqCst),
@@ -192,6 +216,33 @@ async fn records_everywhere_but_only_requests_settlement_in_dev() {
}
}
+#[tokio::test]
+async fn uncounted_usage_never_reads_billing_or_requests_settlement() {
+ for policy in [
+ (AiUsageEnforcement::Disabled, AiFeature::Chat),
+ (AiUsageEnforcement::Enabled, AiFeature::Memory),
+ (AiUsageEnforcement::Enabled, AiFeature::AiProjection),
+ (AiUsageEnforcement::Enabled, AiFeature::CallSummary),
+ (AiUsageEnforcement::Enabled, AiFeature::Dictation),
+ ] {
+ for fail_first in [false, true] {
+ assert_eq!(
+ record_with_policy(
+ Environment::Develop,
+ user(),
+ PlanTier::Premium,
+ false,
+ 1_000,
+ fail_first,
+ policy
+ )
+ .await,
+ (if fail_first { 2 } else { 1 }, 0, 0)
+ );
+ }
+ }
+}
+
#[tokio::test]
async fn system_usage_never_requests_settlement() {
assert_eq!(
diff --git a/crates/ai_tools/Cargo.toml b/crates/ai_tools/Cargo.toml
index 42b9cebe03..196b02b6b1 100644
--- a/crates/ai_tools/Cargo.toml
+++ b/crates/ai_tools/Cargo.toml
@@ -8,6 +8,7 @@ version = "0.1.0"
test-support = []
[dependencies]
+ai_billing = { path = "../ai_billing", features = ["pg-admission"] }
initiative = { path = "../initiative", default-features = false, features = ["postgres", "resources", "toolset"] }
initiative_documents = { path = "../initiative_documents" }
activity = { path = "../activity", default-features = false, features = ["ai_tools", "outbound"] }
diff --git a/crates/ai_tools/src/ai_operations.rs b/crates/ai_tools/src/ai_operations.rs
new file mode 100644
index 0000000000..7985db470b
--- /dev/null
+++ b/crates/ai_tools/src/ai_operations.rs
@@ -0,0 +1,43 @@
+//! Admission for independently initiated AI work, including direct tool calls.
+
+use ai_billing::domain::admission::{AiAdmissionError, AiAdmissionService};
+use ai_usage::UsageContext;
+use std::{future::Future, sync::Arc};
+
+#[cfg(test)]
+mod test;
+
+/// A refused operation is distinct from a provider failure.
+#[derive(Debug, thiserror::Error)]
+pub enum AiOperationError {
+ /// No provider work was started.
+ #[error("{0}")]
+ Admission(#[from] AiAdmissionError),
+ /// An admitted operation failed during execution.
+ #[error(transparent)]
+ Execution(#[from] anyhow::Error),
+}
+
+/// Runs independent AI operations only after admission for their trusted caller.
+#[derive(Clone)]
+pub struct AiOperations {
+ admission: Arc<dyn AiAdmissionService>,
+}
+
+impl AiOperations {
+ /// Use the host's configured admission service.
+ pub fn new(admission: Arc<dyn AiAdmissionService>) -> Self {
+ Self { admission }
+ }
+
+ /// Admit before constructing or polling provider work. `usage` must carry
+ /// the authenticated caller, not a shared context's placeholder identity.
+ pub async fn run<T, F: Future<Output = anyhow::Result<T>>>(
+ &self,
+ usage: &UsageContext,
+ execute: impl FnOnce() -> F,
+ ) -> Result<T, AiOperationError> {
+ self.admission.admit(&usage.user, usage.feature).await?;
+ Ok(execute().await?)
+ }
+}
diff --git a/crates/ai_tools/src/ai_operations/test.rs b/crates/ai_tools/src/ai_operations/test.rs
new file mode 100644
index 0000000000..107d790174
--- /dev/null
+++ b/crates/ai_tools/src/ai_operations/test.rs
@@ -0,0 +1,48 @@
+use super::*;
+use ai_billing::domain::{DenyReason, admission::AdmissionFuture};
+use ai_usage::AiFeature;
+use macro_user_id::user_id::MacroUserIdStr;
+
+struct Refuse(AiAdmissionError);
+impl AiAdmissionService for Refuse {
+ fn admit<'a>(&'a self, _: &'a MacroUserIdStr<'_>, _: AiFeature) -> AdmissionFuture<'a> {
+ Box::pin(async move { Err(self.0) })
+ }
+}
+
+#[tokio::test]
+async fn refused_operations_never_construct_provider_work() {
+ for error in [
+ AiAdmissionError::Denied(DenyReason::AllowanceExhausted),
+ AiAdmissionError::Unavailable,
+ ] {
+ let operations = AiOperations::new(Arc::new(Refuse(error)));
+ let usage = UsageContext::new(
+ AiFeature::Chat,
+ "macro|[email protected]".to_owned().try_into().unwrap(),
+ );
+ let result = operations
+ .run(&usage, || -> std::future::Ready<anyhow::Result<()>> {
+ panic!("provider must not be called")
+ })
+ .await;
+ assert!(matches!(result, Err(AiOperationError::Admission(actual)) if actual == error));
+ }
+}
+
+#[tokio::test]
+async fn disabled_admission_preserves_results_and_provider_errors() {
+ let operations = AiOperations::new(Arc::new(
+ ai_billing::domain::admission::DisabledAiAdmissionService,
+ ));
+ let usage = UsageContext::system(AiFeature::Chat);
+ assert_eq!(
+ operations.run(&usage, || async { Ok(42) }).await.unwrap(),
+ 42
+ );
+ let error = operations
+ .run::<(), _>(&usage, || async { anyhow::bail!("provider failed") })
+ .await
+ .unwrap_err();
+ assert!(matches!(error, AiOperationError::Execution(_)));
+}
diff --git a/crates/ai_tools/src/build_context.rs b/crates/ai_tools/src/build_context.rs
index ff49b1cf26..6d9036907e 100644
--- a/crates/ai_tools/src/build_context.rs
+++ b/crates/ai_tools/src/build_context.rs
@@ -126,6 +126,9 @@ pub fn build_image_generator_from_env() -> Arc<dyn ImageGenerator> {
/// - `ENABLE_GMAIL_OPS_QUEUE` (if disabled, thread-label updates can't enqueue Gmail sync ops)
/// - `ENABLE_NOTIFICATION_QUEUE` (if disabled, notification status updates skip push clearing)
///
+/// `enforcement` is validated by the host at startup and shared with all other
+/// AI entry points. It configures both quota admission and prospective counting.
+///
/// `event_task_tracker` tracks event publishes started by the context. Callers
/// must retain the original tracker, pass a clone here, and close and drain the
/// original after the host stops broker-backed work.
@@ -133,6 +136,7 @@ pub fn build_image_generator_from_env() -> Arc<dyn ImageGenerator> {
pub async fn build_tool_service_context_from_env(
pool: sqlx::PgPool,
event_task_tracker: TaskTracker,
+ enforcement: ai_usage::AiUsageEnforcement,
) -> anyhow::Result<ToolServiceContext> {
let env = ToolContextEnvVars::new()?;
let maybe_env = ToolContextMaybeEnvVars::new();
@@ -483,7 +487,12 @@ pub async fn build_tool_service_context_from_env(
skill_tool_context,
schedule_tool_context: crate::NoOpScheduleContext,
anthropic_tool_context,
- recorder: ai_usage::pg_recorder(pool.clone()),
+ admission: ai_billing::composition::pg_admission_service(
+ pool.clone(),
+ environment,
+ enforcement,
+ ),
+ recorder: ai_usage::pg_recorder_with_enforcement(pool.clone(), enforcement),
usage_context: ai_usage::UsageContext::system(ai_usage::AiFeature::Chat),
})
}
diff --git a/crates/ai_tools/src/lib.rs b/crates/ai_tools/src/lib.rs
index a68694aeda..0e34831f6e 100644
--- a/crates/ai_tools/src/lib.rs
+++ b/crates/ai_tools/src/lib.rs
@@ -7,6 +7,7 @@ use ai_toolset::schema::{FrontendSchemas, ToolSchemaGenerator, frontend_schemas_
#[cfg(test)]
mod test;
+pub mod ai_operations;
mod build_context;
mod display_results;
mod schemas;
@@ -41,7 +42,7 @@ use self_knowledge::SelfKnowledge;
use skills::inbound::toolset::skill_toolset;
use soup::inbound::toolset::{ListEntities, SoupToolContext};
use std::sync::Arc;
-use subagent::Subagent;
+use subagent::{Subagent, SubagentContext};
use teams::inbound::toolset::team_toolset;
#[cfg(any(test, feature = "test-support"))]
@@ -168,7 +169,7 @@ pub fn tools_for(host: AiHost) -> ToolSetWithPrompt {
};
let toolset = toolset
.add_subtoolset::<ToolImportToolContext>(import_toolset())
- .add_tool::<Subagent, ToolServiceContext>();
+ .add_tool::<Subagent, SubagentContext>();
let toolset = match host {
AiHost::Chat | AiHost::AgentSession | AiHost::ChannelBot => toolset
.add_tool::<SearchTools, ToolServiceContext>()
diff --git a/crates/ai_tools/src/subagent.rs b/crates/ai_tools/src/subagent.rs
index bf0da8c373..10461d3721 100644
--- a/crates/ai_tools/src/subagent.rs
+++ b/crates/ai_tools/src/subagent.rs
@@ -2,15 +2,36 @@ use agent::PredefinedModel;
use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};
use ai_toolset::{ToolAnnotated, ToolAnnotations};
use async_trait::async_trait;
+use axum::extract::FromRef;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
+use std::sync::Arc;
use tokio::select;
use crate::ToolServiceContext;
+use crate::ai_operations::{AiOperationError, AiOperations};
#[cfg(test)]
mod test;
+/// Only the AI capabilities a subagent needs, inherited from the host context.
+#[derive(Clone)]
+pub(crate) struct SubagentContext {
+ operations: AiOperations,
+ recorder: Arc<dyn ai_usage::UsageRecorder>,
+ usage_context: ai_usage::UsageContext,
+}
+
+impl FromRef<ToolServiceContext> for SubagentContext {
+ fn from_ref(context: &ToolServiceContext) -> Self {
+ Self {
+ operations: AiOperations::new(context.admission.clone()),
+ recorder: context.recorder.clone(),
+ usage_context: context.usage_context.clone(),
+ }
+ }
+}
+
fn usage_for_request(
inherited: &ai_usage::UsageContext,
request: &RequestContext,
@@ -19,6 +40,17 @@ fn usage_for_request(
.with_entity(inherited.entity)
}
+fn operation_error(error: AiOperationError) -> ToolCallError {
+ let description = match &error {
+ AiOperationError::Admission(error) => format!("{}: {error}", error.code()),
+ AiOperationError::Execution(_) => "subagent encountered an error".to_string(),
+ };
+ ToolCallError {
+ description,
+ internal_error: error.into(),
+ }
+}
+
static SUBAGENT_MODEL: PredefinedModel = PredefinedModel::Smart;
static SUBAGENT_PROMPT: &str = include_str!("prompts/subagent.md");
@@ -46,13 +78,13 @@ impl ToolAnnotated for Subagent {
}
#[async_trait]
-impl AsyncTool<ToolServiceContext> for Subagent {
+impl AsyncTool<SubagentContext> for Subagent {
type Output = SubagentResponse;
#[tracing::instrument(skip_all, err)]
async fn call(
&self,
- service_context: ServiceContext<ToolServiceContext>,
+ service_context: ServiceContext<SubagentContext>,
request_context: RequestContext,
) -> ToolResult<Self::Output> {
// Subagents have no feature of their own — their usage rolls up into the
@@ -62,13 +94,15 @@ impl AsyncTool<ToolServiceContext> for Subagent {
// cancel token. If the user cancels, drop the in-flight completion and
// report "cancelled" rather than a partial or errored result.
let usage = usage_for_request(&service_context.usage_context, &request_context);
- let completion = agent::complete(
- SUBAGENT_MODEL,
- SUBAGENT_PROMPT,
- &self.task,
- service_context.recorder.as_ref(),
- usage,
- );
+ let completion = service_context.operations.run(&usage, || {
+ agent::complete(
+ SUBAGENT_MODEL,
+ SUBAGENT_PROMPT,
+ &self.task,
+ service_context.recorder.as_ref(),
+ usage.clone(),
+ )
+ });
select! {
biased;
@@ -76,10 +110,7 @@ impl AsyncTool<ToolServiceContext> for Subagent {
result: "cancelled".to_string(),
}),
result = completion => result
- .map_err(|e| ToolCallError {
- description: "subagent encountered an error".to_string(),
- internal_error: e,
- })
+ .map_err(operation_error)
.map(|result| SubagentResponse { result }),
}
}
diff --git a/crates/ai_tools/src/subagent/test.rs b/crates/ai_tools/src/subagent/test.rs
index 488d2d465a..e74550bc00 100644
--- a/crates/ai_tools/src/subagent/test.rs
+++ b/crates/ai_tools/src/subagent/test.rs
@@ -1,9 +1,99 @@
use super::*;
+use ai_billing::domain::{
+ DenyReason,
+ admission::{AdmissionFuture, AiAdmissionError, AiAdmissionService},
+};
use ai_usage::{AiFeature, SYSTEM_USER_ID, UsageContext};
+use macro_user_id::user_id::MacroUserIdStr;
+use std::sync::{Arc, Mutex};
+
+#[derive(Default)]
+struct Admission(Mutex<Vec<(String, AiFeature)>>);
+impl AiAdmissionService for Admission {
+ fn admit<'a>(
+ &'a self,
+ user: &'a MacroUserIdStr<'_>,
+ feature: AiFeature,
+ ) -> AdmissionFuture<'a> {
+ Box::pin(async move {
+ self.0.lock().unwrap().push((user.to_string(), feature));
+ if feature == AiFeature::Memory {
+ return Ok(());
+ }
+ Err(AiAdmissionError::Denied(DenyReason::AllowanceExhausted))
+ })
+ }
+}
+
+#[tokio::test]
+async fn concurrent_callers_are_admitted_as_themselves_with_inherited_feature() {
+ let admission = Arc::new(Admission::default());
+ let operations = AiOperations::new(admission.clone());
+ let first = RequestContext::new("macro|[email protected]".to_owned().try_into().unwrap());
+ let second = RequestContext::new("macro|[email protected]".to_owned().try_into().unwrap());
+ for feature in [AiFeature::Automation, AiFeature::Memory] {
+ let inherited = UsageContext::system(feature);
+ let a = usage_for_request(&inherited, &first);
+ let b = usage_for_request(&inherited, &second);
+ let execute = || async {
+ assert_eq!(feature, AiFeature::Memory, "billable work was refused");
+ Ok(())
+ };
+ let (a, b) = tokio::join!(operations.run(&a, execute), operations.run(&b, execute));
+ assert_eq!(a.is_ok(), feature == AiFeature::Memory);
+ assert_eq!(b.is_ok(), feature == AiFeature::Memory);
+ }
+ let calls = admission.0.lock().unwrap();
+ for feature in [AiFeature::Automation, AiFeature::Memory] {
+ assert!(calls.contains(&(first.user_id.to_string(), feature)));
+ assert!(calls.contains(&(second.user_id.to_string(), feature)));
+ }
+}
+
+#[tokio::test]
+async fn direct_subagent_call_is_gated_and_cancellation_remains_available() {
+ let admission = Arc::new(Admission::default());
+ let context = SubagentContext {
+ operations: AiOperations::new(admission.clone()),
+ recorder: Arc::new(ai_usage::NoOpUsageRecorder),
+ usage_context: UsageContext::system(AiFeature::Automation),
+ };
+ let request = RequestContext::new("macro|[email protected]".to_owned().try_into().unwrap());
+ let tool = Subagent {
+ task: "test".into(),
+ };
+ let error = tool
+ .call(ServiceContext(context.clone()), request.clone())
+ .await
+ .unwrap_err();
+ assert!(
+ error
+ .description
+ .starts_with(DenyReason::AllowanceExhausted.code())
+ );
+ assert_eq!(
+ *admission.0.lock().unwrap(),
+ vec![(request.user_id.to_string(), AiFeature::Automation)]
+ );
+ request.cancel.cancel();
+ let response = tool.call(ServiceContext(context), request).await.unwrap();
+ assert_eq!(response.result, "cancelled");
+ assert_eq!(admission.0.lock().unwrap().len(), 1);
+}
+
+#[test]
+fn admission_output_has_a_public_code_not_internal_diagnostics() {
+ let error = operation_error(AiAdmissionError::Unavailable.into());
+ assert_eq!(
+ error.description,
+ "ai_billing_unavailable: AI usage validation is temporarily unavailable. Please try again."
+ );
+}
#[tokio::test]
async fn shared_system_context_does_not_become_subagent_attribution() {
- let inherited = UsageContext::system(AiFeature::Automation);
+ let entity = uuid::Uuid::now_v7();
+ let inherited = UsageContext::system(AiFeature::Automation).with_entity(Some(entity));
let first = RequestContext::new("macro|[email protected]".to_owned().try_into().unwrap());
let second = RequestContext::new("macro|[email protected]".to_owned().try_into().unwrap());
let (a, b) = tokio::join!(async { usage_for_request(&inherited, &first) }, async {
@@ -13,5 +103,7 @@ async fn shared_system_context_does_not_become_subagent_attribution() {
assert_eq!(b.user, second.user_id);
assert_eq!(a.feature, AiFeature::Automation);
assert_eq!(b.feature, AiFeature::Automation);
+ assert_eq!(a.entity, Some(entity));
+ assert_eq!(b.entity, Some(entity));
assert_eq!(inherited.user, *SYSTEM_USER_ID);
}
diff --git a/crates/ai_tools/src/tool_context.rs b/crates/ai_tools/src/tool_context.rs
index 4dc9099de9..3c4da26fcf 100644
--- a/crates/ai_tools/src/tool_context.rs
+++ b/crates/ai_tools/src/tool_context.rs
@@ -1506,6 +1506,7 @@ pub struct ToolServiceContext {
pub soup_service: Arc<ToolSoupService>,
pub email_service: Arc<ToolEmailService>,
pub activity_tool_context: ToolActivityToolContext,
+ #[from_ref(skip)]
pub document_tool_context: ToolDocumentToolContext,
pub image_generation_tool_context: ToolImageGenerationToolContext,
pub properties_tool_context: ToolPropertiesToolContext,
@@ -1533,6 +1534,9 @@ pub struct ToolServiceContext {
pub schedule_tool_context: NoOpScheduleContext,
#[from_ref(skip)]
pub anthropic_tool_context: AnthropicToolContext,
+ /// Shared admission for independently initiated AI work. Hosts must inject
+ /// their configured service; request identity always comes from RequestContext.
+ pub admission: Arc<dyn ai_billing::domain::admission::AiAdmissionService>,
/// Records token usage / cost for AI calls made with this context.
pub recorder: std::sync::Arc<dyn ai_usage::UsageRecorder>,
/// The usage context (feature/user/entity) of the request currently using
@@ -1544,12 +1548,23 @@ pub struct ToolServiceContext {
impl FromRef<ToolServiceContext> for AnthropicToolContext {
fn from_ref(context: &ToolServiceContext) -> Self {
let mut tools = context.anthropic_tool_context.clone();
+ tools.admission = context.admission.clone();
tools.recorder = context.recorder.clone();
tools.usage_context = context.usage_context.clone();
tools
}
}
+impl FromRef<ToolServiceContext> for ToolDocumentToolContext {
+ fn from_ref(context: &ToolServiceContext) -> Self {
+ context
+ .document_tool_context
+ .clone()
+ .with_admission(context.admission.clone())
+ .with_recorder(context.recorder.clone())
+ }
+}
+
impl ToolServiceContext {
/// Run the mutating tools as `actor`, delegated for the requesting user,
/// instead of the default Macro AI bot. Hosts running a specific agent
diff --git a/crates/ai_usage/Cargo.toml b/crates/ai_usage/Cargo.toml
index 209dc98147..864d2e7be9 100644
--- a/crates/ai_usage/Cargo.toml
+++ b/crates/ai_usage/Cargo.toml
@@ -12,6 +12,7 @@ chrono = { workspace = true }
macro_authorization = { path = "../macro_authorization", default-features = false, features = [
"axum",
] }
+macro_env_var = { path = "../macro_env_var" }
macro_user_id = { path = "../macro_user_id", features = ["schema"] }
macro_uuid = { path = "../macro_uuid" }
serde = { workspace = true }
diff --git a/crates/ai_usage/src/config.rs b/crates/ai_usage/src/config.rs
new file mode 100644
index 0000000000..74666a7550
--- /dev/null
+++ b/crates/ai_usage/src/config.rs
@@ -0,0 +1,51 @@
+//! Startup configuration for prospective AI quota enforcement.
+
+use rootcause::prelude::ResultExt as _;
+
+use crate::domain::counting::AiUsageEnforcement;
+
+#[cfg(test)]
+mod test;
+
+// Keep configuration deserialization outside the domain policy. MacroConfig
+// parses the raw Doppler/environment value as a strict boolean.
+impl<'de> serde::Deserialize<'de> for AiUsageEnforcement {
+ fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
+ let enabled = bool::deserialize(deserializer)?;
+ Ok(if enabled {
+ Self::Enabled
+ } else {
+ Self::Disabled
+ })
+ }
+}
+
+/// Load `ENABLE_AI_USAGE_ENFORCEMENT` once at service startup.
+///
+/// Missing means disabled. Only `true` and `false` are accepted when present;
+/// malformed or non-Unicode values return an error that the host must propagate
+/// to fail startup. This does not enable financial settlement.
+///
+/// Hosts using MacroConfig must call this loader as well: its defaulted fields
+/// treat `null` as absent, but a present non-boolean flag must fail startup. The
+/// returned policy is authoritative (including process-env fallback when the
+/// Doppler application configuration omits the key).
+pub fn load_ai_usage_enforcement() -> Result<AiUsageEnforcement, rootcause::Report> {
+ // Unlike maybe_env_var!, this preserves errors for present non-Unicode values.
+ let value = macro_env_var::optional_read_env_var("ENABLE_AI_USAGE_ENFORCEMENT")
+ .context("failed to read ENABLE_AI_USAGE_ENFORCEMENT")?;
+ parse_enforcement(value.as_deref())
+}
+
+fn parse_enforcement(value: Option<&str>) -> Result<AiUsageEnforcement, rootcause::Report> {
+ let enabled = value
+ .map(str::parse::<bool>)
+ .transpose()
+ .context("ENABLE_AI_USAGE_ENFORCEMENT must be true or false")?
+ .unwrap_or(false);
+ if enabled {
+ Ok(AiUsageEnforcement::Enabled)
+ } else {
+ Ok(AiUsageEnforcement::Disabled)
+ }
+}
diff --git a/crates/ai_usage/src/config/test.rs b/crates/ai_usage/src/config/test.rs
new file mode 100644
index 0000000000..d6af413e8c
--- /dev/null
+++ b/crates/ai_usage/src/config/test.rs
@@ -0,0 +1,34 @@
+use super::*;
+
+#[test]
+fn missing_flag_disables_enforcement() {
+ assert_eq!(
+ parse_enforcement(None).unwrap(),
+ AiUsageEnforcement::Disabled
+ );
+}
+
+#[test]
+fn explicit_boolean_values_select_policy() {
+ assert_eq!(
+ parse_enforcement(Some("false")).unwrap(),
+ AiUsageEnforcement::Disabled
+ );
+ assert_eq!(
+ parse_enforcement(Some("true")).unwrap(),
+ AiUsageEnforcement::Enabled
+ );
+}
+
+#[test]
+fn malformed_present_values_are_errors_not_disabled_defaults() {
+ for value in [
+ "", "TRUE", "False", "1", "0", "yes", " true", "false\n", "garbage", "null",
+ ] {
+ let error = parse_enforcement(Some(value)).unwrap_err();
+ assert!(
+ error.to_string().contains("ENABLE_AI_USAGE_ENFORCEMENT"),
+ "{error}"
+ );
+ }
+}
diff --git a/crates/ai_usage/src/domain/counting.rs b/crates/ai_usage/src/domain/counting.rs
new file mode 100644
index 0000000000..cb0a005dc5
--- /dev/null
+++ b/crates/ai_usage/src/domain/counting.rs
@@ -0,0 +1,62 @@
+//! Shared policy for user quota admission and prospective usage counting.
+
+use macro_user_id::user_id::MacroUserIdStr;
+
+use super::ports::{AiFeature, SYSTEM_USER_ID};
+
+#[cfg(test)]
+mod test;
+
+/// Whether new user AI work is subject to quota admission and usage counting.
+/// This policy does not enable financial settlement or payment collection.
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
+pub enum AiUsageEnforcement {
+ /// Skip quota admission and do not count new usage toward allowances.
+ #[default]
+ Disabled,
+ /// Check quota and count billable, user-owned work.
+ Enabled,
+}
+
+impl AiUsageEnforcement {
+ /// Whether quota enforcement is enabled.
+ pub const fn is_enabled(self) -> bool {
+ matches!(self, Self::Enabled)
+ }
+
+ /// Whether this work requires quota admission and counts toward user usage.
+ /// Callers must supply the trusted originating user and server-selected feature;
+ /// the system identity is only for work with no originating end-user.
+ pub fn should_count(self, user: &MacroUserIdStr<'_>, feature: AiFeature) -> bool {
+ self.is_enabled() && is_billable_feature(feature) && user != &*SYSTEM_USER_ID
+ }
+}
+
+/// Features whose provider costs are recorded but never consume allowances,
+/// prepaid credits, or overage. Dictation is the Whispr transcription feature.
+pub const NON_BILLABLE_AI_FEATURES: [AiFeature; 4] = [
+ AiFeature::Memory,
+ AiFeature::AiProjection,
+ AiFeature::CallSummary,
+ AiFeature::Dictation,
+];
+
+/// Whether a feature's usage is billable, independent of enforcement or identity.
+/// Every new feature must explicitly choose its classification here.
+pub const fn is_billable_feature(feature: AiFeature) -> bool {
+ match feature {
+ AiFeature::Memory
+ | AiFeature::AiProjection
+ | AiFeature::CallSummary
+ | AiFeature::Dictation => false,
+ AiFeature::Chat
+ | AiFeature::Automation
+ | AiFeature::DynamicCompletionsApi
+ | AiFeature::ChatRename
+ | AiFeature::ChannelBot
+ | AiFeature::AiEditing
+ | AiFeature::Import
+ | AiFeature::AgentSession
+ | AiFeature::AgentRepositoryChoice => true,
+ }
+}
diff --git a/crates/ai_usage/src/domain/counting/test.rs b/crates/ai_usage/src/domain/counting/test.rs
new file mode 100644
index 0000000000..675ddc3d77
--- /dev/null
+++ b/crates/ai_usage/src/domain/counting/test.rs
@@ -0,0 +1,53 @@
+use super::*;
+
+const FEATURES: [(AiFeature, bool); 13] = [
+ (AiFeature::Chat, true),
+ (AiFeature::Memory, false),
+ (AiFeature::Automation, true),
+ (AiFeature::DynamicCompletionsApi, true),
+ (AiFeature::ChatRename, true),
+ (AiFeature::CallSummary, false),
+ (AiFeature::ChannelBot, true),
+ (AiFeature::AiProjection, false),
+ (AiFeature::AiEditing, true),
+ (AiFeature::Import, true),
+ (AiFeature::AgentSession, true),
+ (AiFeature::AgentRepositoryChoice, true),
+ (AiFeature::Dictation, false),
+];
+
+#[test]
+fn enforcement_defaults_to_disabled() {
+ assert_eq!(AiUsageEnforcement::default(), AiUsageEnforcement::Disabled);
+ assert!(!AiUsageEnforcement::default().is_enabled());
+ assert!(AiUsageEnforcement::Enabled.is_enabled());
+}
+
+#[test]
+fn feature_classification_preserves_billing_policy() {
+ for (feature, billable) in FEATURES {
+ assert_eq!(is_billable_feature(feature), billable, "{feature:?}");
+ assert_eq!(NON_BILLABLE_AI_FEATURES.contains(&feature), !billable);
+ }
+ assert_eq!(NON_BILLABLE_AI_FEATURES.len(), 4);
+}
+
+#[test]
+fn counting_requires_enabled_policy_billable_feature_and_real_user() {
+ let user = MacroUserIdStr::try_from("macro|[email protected]").unwrap();
+ // A separately parsed system identity must also be exempt, not just the static value.
+ let system = MacroUserIdStr::try_from(SYSTEM_USER_ID.as_ref()).unwrap();
+
+ for policy in [AiUsageEnforcement::Disabled, AiUsageEnforcement::Enabled] {
+ for (feature, billable) in FEATURES {
+ for (identity, is_system) in [(&user, false), (&system, true)] {
+ let expected = policy.is_enabled() && billable && !is_system;
+ assert_eq!(
+ policy.should_count(identity, feature),
+ expected,
+ "{policy:?}, {feature:?}, {identity:?}"
+ );
+ }
+ }
+ }
+}
diff --git a/crates/ai_usage/src/domain/mod.rs b/crates/ai_usage/src/domain/mod.rs
index adce6c32a2..42ddac592c 100644
--- a/crates/ai_usage/src/domain/mod.rs
+++ b/crates/ai_usage/src/domain/mod.rs
@@ -1,11 +1,13 @@
//! Domain layer: the cost model, ports, and the service that computes cost.
+pub mod counting;
pub mod financial;
pub mod financial_service;
pub mod ports;
pub mod service;
pub mod tracking;
+pub use counting::{AiUsageEnforcement, NON_BILLABLE_AI_FEATURES, is_billable_feature};
pub use ports::{
AiFeature, CompletionUsage, FeatureUsage, FinancialFuture, FinancialRateResolver,
FinancialUsage, InvocationFunding, ModelPricing, NoOpUsageRecorder, Price, Result,
diff --git a/crates/ai_usage/src/domain/ports.rs b/crates/ai_usage/src/domain/ports.rs
index ea72c5568c..3e0d862a2e 100644
--- a/crates/ai_usage/src/domain/ports.rs
+++ b/crates/ai_usage/src/domain/ports.rs
@@ -338,15 +338,19 @@ pub type Result<T> = std::result::Result<T, UsageError>;
/// Outbound storage port.
pub trait UsageRepo: Send + Sync + 'static {
- /// Persist a fully-priced completion row.
- fn insert_usage(&self, usage: &CompletionUsage) -> impl Future<Output = Result<()>> + Send;
+ /// Persist a completion row with its domain-computed quota counting decision.
+ fn insert_usage(
+ &self,
+ usage: &CompletionUsage,
+ count_usage: bool,
+ ) -> impl Future<Output = Result<()>> + Send;
/// Fetch the current rate for a model's billing unit, if any.
fn get_pricing(&self, model: &str)
-> impl Future<Output = Result<Option<ModelPricing>>> + Send;
/// Upsert the pricing for a model and recompute the `total` of every
- /// existing `ai_usage` row for that model.
+ /// existing `ai_usage` row for that model, preserving its `count_usage` decision.
fn set_pricing(
&self,
model: &str,
diff --git a/crates/ai_usage/src/domain/service.rs b/crates/ai_usage/src/domain/service.rs
index d72b0bc6a6..c33cca6877 100644
--- a/crates/ai_usage/src/domain/service.rs
+++ b/crates/ai_usage/src/domain/service.rs
@@ -4,6 +4,7 @@ use std::collections::BTreeMap;
use chrono::Utc;
+use super::counting::AiUsageEnforcement;
use super::ports::*;
/// The existing Macro-admin policy for usage reporting and price changes.
@@ -23,12 +24,29 @@ fn require_admin(actor: &macro_user_id::user_id::MacroUserIdStr<'_>) -> Result<(
#[derive(Clone)]
pub struct UsageServiceImpl<Repo> {
repo: Repo,
+ enforcement: AiUsageEnforcement,
}
impl<Repo> UsageServiceImpl<Repo> {
- /// Construct the service over a storage repository.
+ /// Construct the service with prospective quota counting disabled.
pub fn new(repo: Repo) -> Self {
- Self { repo }
+ Self {
+ repo,
+ enforcement: AiUsageEnforcement::Disabled,
+ }
+ }
+
+ /// Set the policy used to count new usage toward user quotas.
+ /// Existing rows and admin analytics are unaffected.
+ pub fn with_enforcement(mut self, enforcement: AiUsageEnforcement) -> Self {
+ self.enforcement = enforcement;
+ self
+ }
+
+ /// Whether this recorder will persist the event as quota-counted usage.
+ /// Settlement wrappers use the same policy as persistence, never a second flag.
+ pub fn counts_usage(&self, event: &UsageEvent) -> bool {
+ self.enforcement.should_count(&event.user, event.feature)
}
}
@@ -48,7 +66,12 @@ where
usage.cost_usd = tracing::field::Empty,
usage.priced = tracing::field::Empty,
))]
- async fn record_event(repo: &Repo, event: UsageEvent) -> Result<()> {
+ async fn record_event(
+ repo: &Repo,
+ enforcement: AiUsageEnforcement,
+ event: UsageEvent,
+ ) -> Result<()> {
+ let count_usage = enforcement.should_count(&event.user, event.feature);
// Store and price by the bare api id; chat hands us `provider/model`.
let model = normalize_model_id(&event.model).to_string();
let mut cost = Usage {
@@ -74,7 +97,7 @@ where
cost,
};
- repo.insert_usage(&row).await
+ repo.insert_usage(&row, count_usage).await
}
/// Resolve pricing and persist `event`, returning once the row is written.
@@ -82,7 +105,7 @@ where
/// [`UsageRecorder::record`] is the fire-and-forget form. Callers that
/// need to act after the row exists (billing settlement) await this one.
pub async fn record_now(&self, event: UsageEvent) -> Result<()> {
- Self::record_event(&self.repo, event).await
+ Self::record_event(&self.repo, self.enforcement, event).await
}
}
@@ -92,9 +115,10 @@ where
{
fn record(&self, event: UsageEvent) {
let repo = self.repo.clone();
+ let enforcement = self.enforcement;
// Recording must never fail or delay the originating call.
tokio::spawn(tracing::Instrument::in_current_span(async move {
- if let Err(e) = Self::record_event(&repo, event).await {
+ if let Err(e) = Self::record_event(&repo, enforcement, event).await {
tracing::error!(error = ?e, "failed to record ai usage");
}
}));
diff --git a/crates/ai_usage/src/domain/service/test.rs b/crates/ai_usage/src/domain/service/test.rs
index 9efe6406de..8646da22b6 100644
--- a/crates/ai_usage/src/domain/service/test.rs
+++ b/crates/ai_usage/src/domain/service/test.rs
@@ -119,11 +119,15 @@ fn normalize_model_id_strips_provider_prefix() {
struct FakeRepo {
pricing: std::sync::Arc<std::sync::Mutex<Option<ModelPricing>>>,
rows: std::sync::Arc<std::sync::Mutex<Vec<CompletionUsage>>>,
+ counting: std::sync::Arc<std::sync::Mutex<Vec<bool>>>,
+ recorded: std::sync::Arc<tokio::sync::Notify>,
}
impl UsageRepo for FakeRepo {
- async fn insert_usage(&self, usage: &CompletionUsage) -> Result<()> {
+ async fn insert_usage(&self, usage: &CompletionUsage, count_usage: bool) -> Result<()> {
self.rows.lock().unwrap().push(usage.clone());
+ self.counting.lock().unwrap().push(count_usage);
+ self.recorded.notify_one();
Ok(())
}
@@ -147,7 +151,10 @@ async fn records_duration_with_the_model_rate_and_user_attribution() {
*repo.pricing.lock().unwrap() = Some(ModelPricing::Audio { per_minute: 0.006 });
let event = UsageContext::new(AiFeature::Dictation, user())
.into_audio_event("whisper-1".into(), std::time::Duration::from_millis(90_500));
- UsageServiceImpl::record_event(&repo, event).await.unwrap();
+ UsageServiceImpl::new(repo.clone())
+ .record_now(event)
+ .await
+ .unwrap();
let rows = repo.rows.lock().unwrap();
assert_eq!(rows.len(), 1);
assert_eq!(rows[0].user, user());
@@ -179,7 +186,10 @@ async fn missing_audio_rate_keeps_usage_unpriced() {
"unpriced-audio-model".into(),
std::time::Duration::from_secs(60),
);
- UsageServiceImpl::record_event(&repo, event).await.unwrap();
+ UsageServiceImpl::new(repo.clone())
+ .record_now(event)
+ .await
+ .unwrap();
let rows = repo.rows.lock().unwrap();
assert_eq!(
rows[0].cost.amount,
@@ -191,6 +201,82 @@ async fn missing_audio_rate_keeps_usage_unpriced() {
}
}
+#[tokio::test]
+async fn both_recording_paths_persist_the_same_counting_policy() {
+ let real_user = MacroUserIdStr::try_from("macro|[email protected]".to_owned()).unwrap();
+ for enforcement in [AiUsageEnforcement::Disabled, AiUsageEnforcement::Enabled] {
+ for actor in [real_user.clone(), SYSTEM_USER_ID.clone()] {
+ for feature in [
+ AiFeature::Chat,
+ AiFeature::AiEditing,
+ AiFeature::Memory,
+ AiFeature::AiProjection,
+ AiFeature::CallSummary,
+ AiFeature::Dictation,
+ ] {
+ for pricing in [
+ None,
+ Some(ModelPricing::Tokens {
+ input: 5.0,
+ output: 25.0,
+ }),
+ ] {
+ let repo = FakeRepo::default();
+ *repo.pricing.lock().unwrap() = pricing;
+ let service = UsageServiceImpl::new(repo.clone()).with_enforcement(enforcement);
+ let event = UsageContext::new(feature, actor.clone()).into_event(
+ "anthropic/test-model".into(),
+ 100,
+ 200,
+ );
+ let expected = enforcement == AiUsageEnforcement::Enabled
+ && actor == real_user
+ && matches!(feature, AiFeature::Chat | AiFeature::AiEditing);
+
+ service.record_now(event.clone()).await.unwrap();
+ repo.recorded.notified().await;
+ service.record(event);
+ tokio::time::timeout(
+ std::time::Duration::from_secs(2),
+ repo.recorded.notified(),
+ )
+ .await
+ .expect("background recording must finish");
+
+ assert_eq!(*repo.counting.lock().unwrap(), vec![expected, expected]);
+ let rows = repo.rows.lock().unwrap();
+ assert_eq!(rows.len(), 2);
+ assert!(rows.iter().all(|row| row.user == actor
+ && row.feature == feature
+ && row.cost.model == "test-model"
+ && row.cost.price.is_some() == pricing.is_some()));
+ }
+ }
+ }
+ }
+}
+
+#[tokio::test]
+async fn default_disabled_writes_do_not_change_previously_counted_usage() {
+ let repo = FakeRepo::default();
+ let enabled = UsageServiceImpl::new(repo.clone()).with_enforcement(AiUsageEnforcement::Enabled);
+ let disabled = UsageServiceImpl::new(repo.clone());
+ let actor = MacroUserIdStr::try_from("macro|[email protected]".to_owned()).unwrap();
+ let event = UsageContext::new(AiFeature::Chat, actor).into_event("model".into(), 100, 200);
+ enabled.record_now(event.clone()).await.unwrap();
+ disabled.record_now(event).await.unwrap();
+ assert_eq!(*repo.counting.lock().unwrap(), vec![true, false]);
+ let summary = disabled
+ .get_usage(user(), UsageApiParams::default())
+ .await
+ .unwrap();
+ assert_eq!(
+ summary.entries[0].entries.len(),
+ 2,
+ "analytics stays unfiltered"
+ );
+}
+
#[tokio::test]
async fn admin_policy_protects_usage_and_price_changes() {
let repo = FakeRepo::default();
diff --git a/crates/ai_usage/src/lib.rs b/crates/ai_usage/src/lib.rs
index e1baaf0d85..7b2ddcfef4 100644
--- a/crates/ai_usage/src/lib.rs
+++ b/crates/ai_usage/src/lib.rs
@@ -15,10 +15,12 @@
//! [`FinancialUsage`] capability. [`financial`] defines immutable provider evidence,
//! exact public usage/customer money, and fail-closed capability selection.
+pub mod config;
pub mod domain;
pub mod inbound;
pub mod outbound;
+pub use domain::counting::{AiUsageEnforcement, NON_BILLABLE_AI_FEATURES, is_billable_feature};
pub use domain::financial;
pub use domain::financial_service::{
CacheWritePolicy, CounterSemantics, FinancialRateCatalog, FinancialUsageRepo,
@@ -73,11 +75,21 @@ impl UsageRecorder for TrackingRecorder {
/// Build Postgres analytics with a separate awaited observational capability.
/// Producers must bind that capability per operation; `record` remains analytics-only.
///
-/// Services construct one of these and thread it into their tool/service
-/// context (and into AI call sites) — there is no global recorder.
+/// Internal/evaluation callers may use this disabled default. Production hosts
+/// must use [`pg_recorder_with_enforcement`] with their startup configuration.
pub fn pg_recorder(pool: sqlx::PgPool) -> Arc<dyn UsageRecorder> {
- let analytics = Arc::new(domain::service::UsageServiceImpl::new(
- outbound::PgUsageRepo::new(pool.clone()),
- ));
+ pg_recorder_with_enforcement(pool, AiUsageEnforcement::Disabled)
+}
+
+/// Build configured prospective usage counting, retaining observational tracking.
+/// This does not enable financial accounting or settlement.
+pub fn pg_recorder_with_enforcement(
+ pool: sqlx::PgPool,
+ enforcement: AiUsageEnforcement,
+) -> Arc<dyn UsageRecorder> {
+ let analytics = Arc::new(
+ domain::service::UsageServiceImpl::new(outbound::PgUsageRepo::new(pool.clone()))
+ .with_enforcement(enforcement),
+ );
with_tracking(analytics, pg_tracking(pool))
}
diff --git a/crates/ai_usage/src/outbound/pg_financial_usage_repo/test.rs b/crates/ai_usage/src/outbound/pg_financial_usage_repo/test.rs
index 71b49da080..0d9a0b832f 100644
--- a/crates/ai_usage/src/outbound/pg_financial_usage_repo/test.rs
+++ b/crates/ai_usage/src/outbound/pg_financial_usage_repo/test.rs
@@ -376,17 +376,20 @@ async fn legacy_analytics_writes_and_repricing_leave_financial_evidence_unchange
output: 0,
};
analytics
- .insert_usage(&CompletionUsage {
- feature: AiFeature::Chat,
- user: SYSTEM_USER_ID.clone(),
- entity: None,
- cost: Usage {
- amount,
- model: "test-model".into(),
- price: Price::compute(pricing, amount),
- created_at: Utc::now(),
+ .insert_usage(
+ &CompletionUsage {
+ feature: AiFeature::Chat,
+ user: SYSTEM_USER_ID.clone(),
+ entity: None,
+ cost: Usage {
+ amount,
+ model: "test-model".into(),
+ price: Price::compute(pricing, amount),
+ created_at: Utc::now(),
+ },
},
- })
+ false,
+ )
.await
.unwrap();
analytics
diff --git a/crates/ai_usage/src/outbound/pg_usage_repo.rs b/crates/ai_usage/src/outbound/pg_usage_repo.rs
index e70b27b579..fd4c3bfee7 100644
--- a/crates/ai_usage/src/outbound/pg_usage_repo.rs
+++ b/crates/ai_usage/src/outbound/pg_usage_repo.rs
@@ -24,7 +24,7 @@ impl PgUsageRepo {
}
impl UsageRepo for PgUsageRepo {
- async fn insert_usage(&self, usage: &CompletionUsage) -> Result<()> {
+ async fn insert_usage(&self, usage: &CompletionUsage, count_usage: bool) -> Result<()> {
let id = macro_uuid::generate_uuid_v7();
let (input_tokens, output_tokens, audio_seconds) = match usage.cost.amount {
UsageAmount::Tokens { input, output } => (
@@ -51,9 +51,10 @@ impl UsageRepo for PgUsageRepo {
INSERT INTO ai_usage (
id, feature, user_id, entity, model,
input_tokens, output_tokens, audio_seconds,
- price_per_million_in, price_per_million_out, price_per_audio_minute, total
+ price_per_million_in, price_per_million_out, price_per_audio_minute, total,
+ count_usage
)
- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)
"#,
id,
usage.feature.to_string(),
@@ -67,6 +68,7 @@ impl UsageRepo for PgUsageRepo {
per_out,
per_audio_minute,
total,
+ count_usage,
)
.execute(&self.inner)
.await?;
diff --git a/crates/ai_usage/src/outbound/pg_usage_repo/test.rs b/crates/ai_usage/src/outbound/pg_usage_repo/test.rs
index 7fcef7278c..7765a613fd 100644
--- a/crates/ai_usage/src/outbound/pg_usage_repo/test.rs
+++ b/crates/ai_usage/src/outbound/pg_usage_repo/test.rs
@@ -53,10 +53,13 @@ async fn insert_and_query_roundtrips(pool: PgPool) {
repo.get_pricing("claude-opus-4-8").await.unwrap().unwrap(),
row.cost.amount,
);
- repo.insert_usage(&row).await.unwrap();
- repo.insert_usage(&completion(AiFeature::Memory, "unknown-model", 10, 20))
- .await
- .unwrap();
+ repo.insert_usage(&row, true).await.unwrap();
+ repo.insert_usage(
+ &completion(AiFeature::Memory, "unknown-model", 10, 20),
+ false,
+ )
+ .await
+ .unwrap();
let all = repo.query_usage(&UsageApiParams::default()).await.unwrap();
assert_eq!(all.len(), 2);
@@ -79,12 +82,10 @@ async fn set_pricing_recomputes_existing_rows(pool: PgPool) {
let repo = PgUsageRepo::new(pool);
// Record with an unknown model so price starts NULL.
- repo.insert_usage(&completion(
- AiFeature::Automation,
- "brand-new-model",
- 1_000_000,
- 0,
- ))
+ repo.insert_usage(
+ &completion(AiFeature::Automation, "brand-new-model", 1_000_000, 0),
+ true,
+ )
.await
.unwrap();
@@ -113,14 +114,70 @@ async fn set_pricing_recomputes_existing_rows(pool: PgPool) {
);
}
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn counting_decisions_survive_repricing_and_remain_visible_to_analytics(pool: PgPool) {
+ let repo = PgUsageRepo::new(pool.clone());
+ let model = "counting-test-model";
+ let row = completion(AiFeature::Chat, model, 1_000_000, 0);
+ repo.insert_usage(&row, true).await.unwrap();
+ repo.insert_usage(&row, false).await.unwrap();
+ // Legacy writers omit the column, just like historical rows before migration.
+ sqlx::query!(
+ r#"INSERT INTO ai_usage (id, feature, user_id, model, input_tokens, output_tokens)
+ VALUES ($1, 'chat', $2, $3, 1000000, 0)"#,
+ macro_uuid::generate_uuid_v7(),
+ row.user.as_ref(),
+ model,
+ )
+ .execute(&pool)
+ .await
+ .unwrap();
+
+ let before = sqlx::query!("SELECT id, count_usage FROM ai_usage ORDER BY id")
+ .fetch_all(&pool)
+ .await
+ .unwrap();
+ assert_eq!(before.iter().filter(|row| row.count_usage).count(), 1);
+ assert_eq!(before.len(), 3);
+
+ for pricing in [
+ ModelPricing::Tokens {
+ input: 2.0,
+ output: 8.0,
+ },
+ ModelPricing::Audio { per_minute: 0.006 },
+ ModelPricing::Tokens {
+ input: 4.0,
+ output: 16.0,
+ },
+ ] {
+ repo.set_pricing(model, pricing).await.unwrap();
+ let after = sqlx::query!("SELECT id, count_usage FROM ai_usage ORDER BY id")
+ .fetch_all(&pool)
+ .await
+ .unwrap();
+ assert!(before.iter().zip(&after).all(
+ |(before, after)| before.id == after.id && before.count_usage == after.count_usage
+ ));
+ let all = repo.query_usage(&UsageApiParams::default()).await.unwrap();
+ assert_eq!(
+ all.len(),
+ 3,
+ "admin analytics includes uncounted and legacy rows"
+ );
+ let expected = Price::compute(pricing, row.cost.amount);
+ assert!(all.iter().all(|row| row.cost.price == expected));
+ }
+}
+
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn query_filters_by_user(pool: PgPool) {
let repo = PgUsageRepo::new(pool);
let mut other = completion(AiFeature::Chat, "claude-opus-4-8", 1, 1);
other.user = MacroUserIdStr::try_from("macro|[email protected]".to_string()).unwrap();
- repo.insert_usage(&other).await.unwrap();
- repo.insert_usage(&completion(AiFeature::Chat, "claude-opus-4-8", 1, 1))
+ repo.insert_usage(&other, true).await.unwrap();
+ repo.insert_usage(&completion(AiFeature::Chat, "claude-opus-4-8", 1, 1), false)
.await
.unwrap();
@@ -175,13 +232,11 @@ async fn duration_usage_roundtrips_and_reprices_without_affecting_tokens(pool: P
repo.get_pricing("whisper-1").await.unwrap().unwrap(),
audio.cost.amount,
);
- repo.insert_usage(&audio).await.unwrap();
- repo.insert_usage(&completion(
- AiFeature::Chat,
- "claude-opus-4-8",
- 1_000_000,
- 0,
- ))
+ repo.insert_usage(&audio, false).await.unwrap();
+ repo.insert_usage(
+ &completion(AiFeature::Chat, "claude-opus-4-8", 1_000_000, 0),
+ true,
+ )
.await
.unwrap();
@@ -241,9 +296,12 @@ async fn duration_usage_roundtrips_and_reprices_without_affecting_tokens(pool: P
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn repricing_cannot_apply_audio_rates_to_token_usage(pool: PgPool) {
let repo = PgUsageRepo::new(pool);
- repo.insert_usage(&completion(AiFeature::Chat, "mixed-history", 1_000_000, 0))
- .await
- .unwrap();
+ repo.insert_usage(
+ &completion(AiFeature::Chat, "mixed-history", 1_000_000, 0),
+ true,
+ )
+ .await
+ .unwrap();
repo.set_pricing("mixed-history", ModelPricing::Audio { per_minute: 0.006 })
.await
.unwrap();
diff --git a/crates/anthropic/Cargo.toml b/crates/anthropic/Cargo.toml
index b2e91ed82b..6038fda2e3 100644
--- a/crates/anthropic/Cargo.toml
+++ b/crates/anthropic/Cargo.toml
@@ -7,14 +7,16 @@ version = "0.2.0"
[features]
default = ["openai"]
openai = ["dep:async-openai"]
-toolset = ["dep:ai_toolset", "dep:async-trait", "dep:anyhow", "dep:ai_usage"]
+toolset = ["dep:ai_billing", "dep:ai_toolset", "dep:async-trait", "dep:anyhow", "dep:ai_usage"]
[dev-dependencies]
+macro_user_id = { path = "../macro_user_id" }
rand = { workspace = true }
tokio = { workspace = true, features = ["test-util"] }
[dependencies]
+ai_billing = { path = "../ai_billing", optional = true }
tokio = { workspace = true, features = ["sync"]}
async-stream = { workspace = true }
futures = { workspace = true }
diff --git a/crates/anthropic/src/toolset.rs b/crates/anthropic/src/toolset.rs
index 5e73a040b8..57a5e2c989 100644
--- a/crates/anthropic/src/toolset.rs
+++ b/crates/anthropic/src/toolset.rs
@@ -30,6 +30,8 @@ pub struct AnthropicToolContext {
pub client: Arc<Client>,
/// The model to use for server tool invocations.
pub model: String,
+ /// Admission for the authenticated caller before any provider execution.
+ pub admission: Arc<dyn ai_billing::domain::admission::AiAdmissionService>,
/// Analytics injection also exposes the separate observational journal.
pub recorder: Arc<dyn UsageRecorder>,
/// Inherited feature/entity only; each call replaces the user from RequestContext.
@@ -41,6 +43,7 @@ impl Clone for AnthropicToolContext {
Self {
client: self.client.clone(),
model: self.model.clone(),
+ admission: self.admission.clone(),
recorder: self.recorder.clone(),
usage_context: self.usage_context.clone(),
}
@@ -53,6 +56,7 @@ impl AnthropicToolContext {
Self {
client: Arc::new(client),
model,
+ admission: Arc::new(ai_billing::domain::admission::DisabledAiAdmissionService),
recorder: Arc::new(ai_usage::NoOpUsageRecorder),
usage_context: UsageContext::system(ai_usage::AiFeature::Chat),
}
@@ -115,6 +119,15 @@ pub(crate) async fn invoke_server_tool(
server_tool: ServerTool,
input: &str,
) -> Result<Vec<ResponseContentKind>, ToolCallError> {
+ context
+ .admission
+ .admit(&request_context.user_id, context.usage_context.feature)
+ .await
+ .map_err(|error| ToolCallError {
+ description: format!("{}: {error}", error.code()),
+ internal_error: error.into(),
+ })?;
+
let request = CreateMessageRequestBody {
model: context.model.clone(),
messages: vec![RequestMessage {
diff --git a/crates/anthropic/src/toolset/test.rs b/crates/anthropic/src/toolset/test.rs
index 171eb849b0..be4653f3c5 100644
--- a/crates/anthropic/src/toolset/test.rs
+++ b/crates/anthropic/src/toolset/test.rs
@@ -1,10 +1,107 @@
use super::*;
use crate::types::response::{Content, MessageResponse, ResponseContentKind};
+use ai_billing::domain::{
+ DenyReason,
+ admission::{AdmissionFuture, AiAdmissionError, AiAdmissionService},
+};
use ai_usage::financial::{FinancialError, WriteDisposition};
use ai_usage::{FinancialFuture, UsageTracking};
+use macro_user_id::user_id::MacroUserIdStr;
use std::sync::Mutex;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
+struct Refuse {
+ error: AiAdmissionError,
+ callers: Mutex<Vec<(String, ai_usage::AiFeature)>>,
+}
+impl AiAdmissionService for Refuse {
+ fn admit<'a>(
+ &'a self,
+ user: &'a MacroUserIdStr<'_>,
+ feature: ai_usage::AiFeature,
+ ) -> AdmissionFuture<'a> {
+ Box::pin(async move {
+ self.callers
+ .lock()
+ .unwrap()
+ .push((user.to_string(), feature));
+ Err(self.error)
+ })
+ }
+}
+
+#[tokio::test]
+async fn direct_tools_refuse_before_both_provider_branches_and_observation() {
+ use ai_toolset::{AsyncTool, ServiceContext};
+ for tracked in [false, true] {
+ for error in [
+ AiAdmissionError::Denied(DenyReason::AllowanceExhausted),
+ AiAdmissionError::Unavailable,
+ ] {
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let mut context = AnthropicToolContext::new(
+ Client::with_config(crate::config::Config {
+ api_base: format!("http://{}", listener.local_addr().unwrap()),
+ ..Default::default()
+ }),
+ "claude-haiku-4-5".into(),
+ );
+ let admission = Arc::new(Refuse {
+ error,
+ callers: Mutex::new(Vec::new()),
+ });
+ context.admission = admission.clone();
+ let journal = Arc::new(Observations::default());
+ if tracked {
+ context.recorder =
+ ai_usage::with_tracking(Arc::new(ai_usage::NoOpUsageRecorder), journal.clone());
+ }
+ context.usage_context = UsageContext::system(ai_usage::AiFeature::Automation);
+ let first =
+ RequestContext::new("macro|[email protected]".to_owned().try_into().unwrap());
+ let second =
+ RequestContext::new("macro|[email protected]".to_owned().try_into().unwrap());
+ let tool = WebSearch {
+ input: "test".into(),
+ };
+ let (a, b) = tokio::join!(
+ tool.call(ServiceContext(context.clone()), first.clone()),
+ tool.call(ServiceContext(context), second.clone()),
+ );
+ for result in [a, b] {
+ assert_eq!(
+ result.unwrap_err().description,
+ format!("{}: {error}", error.code())
+ );
+ }
+ {
+ let callers = admission.callers.lock().unwrap();
+ assert!(
+ callers.contains(&(first.user_id.to_string(), ai_usage::AiFeature::Automation))
+ );
+ assert!(
+ callers
+ .contains(&(second.user_id.to_string(), ai_usage::AiFeature::Automation))
+ );
+ }
+ assert!(journal.begins.lock().unwrap().is_empty());
+ assert!(journal.finals.lock().unwrap().is_empty());
+ assert!(
+ tokio::time::timeout(std::time::Duration::from_millis(10), listener.accept())
+ .await
+ .is_err()
+ );
+ }
+ }
+}
+
+struct NoAnalytics;
+impl UsageRecorder for NoAnalytics {
+ fn record(&self, _: ai_usage::UsageEvent) {
+ panic!("native tools must not introduce a new analytics producer");
+ }
+}
+
#[derive(Default)]
struct Observations {
begins: Mutex<Vec<TrackedInvocation>>,
@@ -60,7 +157,7 @@ async fn context_with_status(
}),
"claude-haiku-4-5".into(),
);
- context.recorder = ai_usage::with_tracking(Arc::new(ai_usage::NoOpUsageRecorder), journal);
+ context.recorder = ai_usage::with_tracking(Arc::new(NoAnalytics), journal);
context.usage_context = UsageContext::system(ai_usage::AiFeature::Automation);
context
}
diff --git a/crates/channel_bots/Cargo.toml b/crates/channel_bots/Cargo.toml
index 735816421e..552936e4e0 100644
--- a/crates/channel_bots/Cargo.toml
+++ b/crates/channel_bots/Cargo.toml
@@ -5,6 +5,7 @@ publish = false
version = "0.1.0"
[dependencies]
+ai_billing = { path = "../ai_billing" }
agent = { path = "../agent" }
ai_usage = { path = "../ai_usage" }
ai_tools = { path = "../ai_tools" }
diff --git a/crates/channel_bots/src/domain/service.rs b/crates/channel_bots/src/domain/service.rs
index a67d872566..6f067d6613 100644
--- a/crates/channel_bots/src/domain/service.rs
+++ b/crates/channel_bots/src/domain/service.rs
@@ -4,6 +4,7 @@ use std::collections::HashSet;
use std::fmt::Write as _;
use std::sync::Arc;
+use ai_billing::{AiAdmissionService, AiFeature, DisabledAiAdmissionService};
use entity_access::domain::models::EntityAccessReceipt;
use messages::domain::{
api::MessageServiceApi,
@@ -269,6 +270,7 @@ pub struct MacroAiHandler<R, Z> {
responder: Arc<R>,
time_zones: Arc<Z>,
marks: Arc<dyn CommentMarks>,
+ admission: Arc<dyn AiAdmissionService>,
}
impl<R, Z> MacroAiHandler<R, Z>
@@ -290,9 +292,16 @@ where
responder,
time_zones,
marks,
+ admission: Arc::new(DisabledAiAdmissionService),
}
}
+ /// Configure admission for response generation on behalf of the invoking user.
+ pub fn with_admission(mut self, admission: Arc<dyn AiAdmissionService>) -> Self {
+ self.admission = admission;
+ self
+ }
+
/// What a mark covers in the document now. Called only after the thread
/// was read under the invoking user's access; a failed lookup leaves the
/// stored snapshot to stand in rather than failing the reply.
@@ -530,8 +539,31 @@ where
// conversation stops here: nothing is prompted from the event alone.
let prompt = self.build_prompt(event).await?;
- // 2. Post the immediate "thinking" message in the thread. The capability
- // carries the requesting user, so the message records who triggered it.
+ let admission = self
+ .admission
+ .admit(&event.requesting_user, AiFeature::ChannelBot)
+ .await;
+ if let Err(error) = admission {
+ tracing::info!(code = error.code(), "bot response admission rejected");
+ if event.trigger == BotTrigger::Inferred {
+ return Ok(());
+ }
+ }
+
+ // Explicit requests get a visible rejection, not a thinking placeholder
+ // or an error that could cause queued callers to redeliver the request.
+ let (content, notification_policy) = match admission {
+ Ok(()) => (
+ THINKING_MESSAGE.to_string(),
+ PostMessageNotificationPolicy::Silent,
+ ),
+ Err(error) => (
+ format!("{} ({})", error, error.code()),
+ PostMessageNotificationPolicy::Default,
+ ),
+ };
+
+ // 2. Post under the requesting user's current capability.
let access = self
.access
.bot_write(&event.requesting_user, parent)
@@ -544,8 +576,8 @@ where
PostMessage {
id: None,
attribution: MessageAttribution::ActingUser,
- notification_policy: PostMessageNotificationPolicy::Silent,
- content: THINKING_MESSAGE.to_string(),
+ notification_policy,
+ content,
thread_id: Some(event.reply_thread_id),
anchor: None,
mentions: Vec::new(),
@@ -554,6 +586,9 @@ where
},
)
.await?;
+ if admission.is_err() {
+ return Ok(());
+ }
let message_id = thinking.id;
// 3. Run the agent loop to produce the reply.
diff --git a/crates/channel_bots/src/domain/service/tests.rs b/crates/channel_bots/src/domain/service/tests.rs
index de9618576e..778705b775 100644
--- a/crates/channel_bots/src/domain/service/tests.rs
+++ b/crates/channel_bots/src/domain/service/tests.rs
@@ -97,6 +97,41 @@ fn expect_placeholder(api: &mut MockMessageServiceApi) {
});
}
+#[tokio::test]
+async fn rejected_responses_never_call_the_provider_and_explicit_requests_show_the_failure() {
+ for failure in admission_failures() {
+ for trigger_kind in [BotTrigger::Mention, BotTrigger::Inferred] {
+ let trigger = message(1, None, "help with this");
+ let mut event = invocation(&trigger);
+ event.trigger = trigger_kind;
+ let mut api = MockMessageServiceApi::new();
+ configure_reads(&mut api, &trigger, thread(trigger.clone(), vec![]));
+ if trigger_kind == BotTrigger::Mention {
+ api.expect_post().once().returning(move |access, input| {
+ assert_eq!(access.acting_user_id(), Some(&user()));
+ assert!(input.content.contains(failure.code()));
+ assert!(input.content.contains(&failure.to_string()));
+ assert!(!input.content.contains(THINKING_MESSAGE));
+ assert_eq!(
+ input.notification_policy,
+ PostMessageNotificationPolicy::Default
+ );
+ Ok(message(2, input.thread_id, &input.content))
+ });
+ }
+ let responder = responder("must not run");
+ let admission = Admission::new(Err(failure));
+ handler(api, Arc::new(Access::default()), responder.clone())
+ .with_admission(admission.clone())
+ .handle(&event)
+ .await
+ .expect("quota failures are handled, not redelivered");
+ assert!(responder.prompts.lock().unwrap().is_empty());
+ assert_eq!(admission.calls.load(std::sync::atomic::Ordering::SeqCst), 1);
+ }
+ }
+}
+
#[tokio::test]
async fn document_invocation_reads_its_thread_and_delivers_a_bot_reply_with_comment_policy() {
let root = message(1, None, "Selected paragraph discussion");
@@ -119,10 +154,13 @@ async fn document_invocation_reads_its_thread_and_delivers_a_bot_reply_with_comm
))
});
let responder = responder("the answer");
+ let admission = Admission::new(Ok(()));
handler(api, Arc::new(Access::default()), responder.clone())
+ .with_admission(admission.clone())
.handle(&invocation(&trigger))
.await
.unwrap();
+ assert_eq!(admission.calls.load(std::sync::atomic::Ordering::SeqCst), 1);
let prompts = responder.prompts.lock().unwrap();
assert!(prompts[0].contains("discussion-document"));
assert!(prompts[0].contains("mentioned you (@macro) in a document discussion."));
diff --git a/crates/channel_bots/src/domain/test.rs b/crates/channel_bots/src/domain/test.rs
index 44c7dc4c4c..782cb74f48 100644
--- a/crates/channel_bots/src/domain/test.rs
+++ b/crates/channel_bots/src/domain/test.rs
@@ -18,6 +18,40 @@ use std::sync::{
};
use uuid::Uuid;
+pub(super) struct Admission {
+ pub result: Result<(), ai_billing::AiAdmissionError>,
+ pub calls: std::sync::atomic::AtomicUsize,
+}
+
+impl Admission {
+ pub fn new(result: Result<(), ai_billing::AiAdmissionError>) -> Arc<Self> {
+ Arc::new(Self {
+ result,
+ calls: std::sync::atomic::AtomicUsize::new(0),
+ })
+ }
+}
+
+impl ai_billing::AiAdmissionService for Admission {
+ fn admit<'a>(
+ &'a self,
+ caller: &'a MacroUserIdStr<'_>,
+ feature: ai_billing::AiFeature,
+ ) -> ai_billing::AdmissionFuture<'a> {
+ assert_eq!(caller, &user());
+ assert_eq!(feature, ai_billing::AiFeature::ChannelBot);
+ self.calls.fetch_add(1, Ordering::SeqCst);
+ Box::pin(async { self.result })
+ }
+}
+
+pub(super) fn admission_failures() -> [ai_billing::AiAdmissionError; 2] {
+ [
+ ai_billing::AiAdmissionError::Denied(ai_billing::DenyReason::AllowanceExhausted),
+ ai_billing::AiAdmissionError::Unavailable,
+ ]
+}
+
pub(super) fn user() -> MacroUserIdStr<'static> {
"macro|[email protected]".to_string().try_into().unwrap()
}
diff --git a/crates/channel_bots/src/domain/trigger_detector.rs b/crates/channel_bots/src/domain/trigger_detector.rs
index cff4066b56..bf5d16ec23 100644
--- a/crates/channel_bots/src/domain/trigger_detector.rs
+++ b/crates/channel_bots/src/domain/trigger_detector.rs
@@ -2,6 +2,7 @@
use std::sync::Arc;
+use ai_billing::{AiAdmissionService, AiFeature, DisabledAiAdmissionService};
use async_trait::async_trait;
use messages::domain::{api::MessageReader, events::MessagePostedMetadata};
use uuid::Uuid;
@@ -26,6 +27,7 @@ pub struct MentionOrInferredDetector<I> {
messages: Arc<dyn MessageReader>,
access: Arc<dyn ConversationAccess>,
classifier: Arc<I>,
+ admission: Arc<dyn AiAdmissionService>,
}
impl<I> MentionOrInferredDetector<I>
@@ -42,9 +44,16 @@ where
messages,
access,
classifier,
+ admission: Arc::new(DisabledAiAdmissionService),
}
}
+ /// Configure admission for optional inference; explicit mentions need no model.
+ pub fn with_admission(mut self, admission: Arc<dyn AiAdmissionService>) -> Self {
+ self.admission = admission;
+ self
+ }
+
/// Load the thread (parent + replies, oldest-first) as a transcript. The
/// candidate message is appended if the reply fetch does not include it
/// yet.
@@ -99,6 +108,14 @@ where
return None;
}
+ self.admission
+ .admit(requesting_user, AiFeature::ChannelBot)
+ .await
+ .inspect_err(|error| {
+ tracing::info!(code = error.code(), "skipping bot trigger inference");
+ })
+ .ok()?;
+
match self
.classifier
.expects_response(requesting_user, &transcript)
diff --git a/crates/channel_bots/src/domain/trigger_detector/tests.rs b/crates/channel_bots/src/domain/trigger_detector/tests.rs
index ba100defd7..be37609fce 100644
--- a/crates/channel_bots/src/domain/trigger_detector/tests.rs
+++ b/crates/channel_bots/src/domain/trigger_detector/tests.rs
@@ -24,6 +24,28 @@ fn classifier(answer: Result<bool, &'static str>) -> Arc<Classifier> {
calls: Mutex::new(vec![]),
})
}
+#[tokio::test]
+async fn admission_failure_suppresses_inference_without_fallback() {
+ for failure in admission_failures() {
+ let mut root = message(1, None, "previous answer");
+ root.sender_id = channel_sender::ChannelSender::new_from_bot(bot_id::MACRO_AI_BOT_ID);
+ let trigger = message(2, Some(root.id), "continue");
+ let mut api = MockMessageServiceApi::new();
+ configure_reads(&mut api, &trigger, thread(root, vec![trigger.clone()]));
+ let classifier = classifier(Ok(true));
+ let admission = Admission::new(Err(failure));
+ let detector = MentionOrInferredDetector::new(
+ Arc::new(api),
+ Arc::new(Access::default()),
+ classifier.clone(),
+ )
+ .with_admission(admission.clone());
+ assert!(detector.detect(&event(&trigger)).await.is_empty());
+ assert!(classifier.calls.lock().unwrap().is_empty());
+ assert_eq!(admission.calls.load(std::sync::atomic::Ordering::SeqCst), 1);
+ }
+}
+
#[tokio::test]
async fn document_mention_triggers_each_canonical_bot_once_without_classification() {
let mut trigger = message(1, None, "@macro help");
@@ -33,11 +55,13 @@ async fn document_mention_triggers_each_canonical_bot_once_without_classificatio
};
trigger.mentions = vec![mention.clone(), mention];
let classifier = classifier(Ok(false));
+ let admission = Admission::new(Err(ai_billing::AiAdmissionError::Unavailable));
let detector = MentionOrInferredDetector::new(
Arc::new(MockMessageServiceApi::new()),
Arc::new(Access::default()),
classifier.clone(),
- );
+ )
+ .with_admission(admission.clone());
assert_eq!(
detector.detect(&event(&trigger)).await,
vec![BotInvocation {
@@ -46,6 +70,7 @@ async fn document_mention_triggers_each_canonical_bot_once_without_classificatio
}]
);
assert!(classifier.calls.lock().unwrap().is_empty());
+ assert_eq!(admission.calls.load(std::sync::atomic::Ordering::SeqCst), 0);
}
#[tokio::test]
async fn bot_authored_messages_never_trigger_another_response() {
diff --git a/crates/channel_bots/src/inbound/bot_trigger_router.rs b/crates/channel_bots/src/inbound/bot_trigger_router.rs
index 17f59953f7..e86ba3d394 100644
--- a/crates/channel_bots/src/inbound/bot_trigger_router.rs
+++ b/crates/channel_bots/src/inbound/bot_trigger_router.rs
@@ -51,11 +51,34 @@ where
detector: Arc<D>,
time_zones: Arc<Z>,
marks: Arc<dyn CommentMarks>,
+ ) -> Self {
+ Self::new_with_admission(
+ messages,
+ access,
+ responder,
+ detector,
+ time_zones,
+ marks,
+ Arc::new(ai_billing::DisabledAiAdmissionService),
+ )
+ }
+
+ /// Create a router with configured response admission. The detector must
+ /// independently admit any inference it performs.
+ pub fn new_with_admission(
+ messages: Arc<dyn MessageServiceApi>,
+ access: Arc<dyn ConversationAccess>,
+ responder: Arc<R>,
+ detector: Arc<D>,
+ time_zones: Arc<Z>,
+ marks: Arc<dyn CommentMarks>,
+ admission: Arc<dyn ai_billing::AiAdmissionService>,
) -> Self {
Self {
- macro_ai: Arc::new(MacroAiHandler::new(
- messages, access, responder, time_zones, marks,
- )),
+ macro_ai: Arc::new(
+ MacroAiHandler::new(messages, access, responder, time_zones, marks)
+ .with_admission(admission),
+ ),
detector,
}
}
diff --git a/crates/cursor_cloud_agents/src/domain/error.rs b/crates/cursor_cloud_agents/src/domain/error.rs
index 934261560b..46bc32770f 100644
--- a/crates/cursor_cloud_agents/src/domain/error.rs
+++ b/crates/cursor_cloud_agents/src/domain/error.rs
@@ -8,6 +8,10 @@ use thiserror::Error;
/// Why a session operation failed.
#[derive(Debug, Error)]
pub enum SessionError {
+ /// A Macro-funded hosted helper was refused; the owner's Cursor budget is unrelated.
+ #[cfg(feature = "postgres")]
+ #[error(transparent)]
+ Admission(#[from] agent_session::domain::error::AiAdmissionError),
/// The client referenced a session this agent never created.
#[error("unknown session {0}")]
UnknownSession(SessionId),
@@ -32,6 +36,12 @@ pub enum SessionError {
impl From<rootcause::Report> for SessionError {
fn from(report: rootcause::Report) -> Self {
+ #[cfg(feature = "postgres")]
+ if let Some(error) =
+ report.downcast_current_context::<agent_session::domain::error::AiAdmissionError>()
+ {
+ return Self::Admission(*error);
+ }
Self::Cursor(report)
}
}
diff --git a/crates/cursor_cloud_agents/src/domain/service.rs b/crates/cursor_cloud_agents/src/domain/service.rs
index 2df9b6ca9e..14d9b934e6 100644
--- a/crates/cursor_cloud_agents/src/domain/service.rs
+++ b/crates/cursor_cloud_agents/src/domain/service.rs
@@ -338,6 +338,8 @@ fn explain_rejection(error: SessionError) -> SessionError {
fn is_prompt_rejection(error: &SessionError) -> bool {
match error {
SessionError::Rejected(_) => true,
+ #[cfg(feature = "postgres")]
+ SessionError::Admission(_) => true,
SessionError::Cursor(report) => report
.downcast_current_context::<crate::domain::error::PromptRejected>()
.is_some(),
@@ -1152,9 +1154,14 @@ where
// request there, which no later correction undoes.
Err(error) => {
tracing::warn!(error = ?error, "could not choose a repository for this session");
- Err(SessionError::Rejected(PromptRefusal::plain(
- "Couldn't prepare repository access for this session. Please retry; if this persists, check your GitHub connection.",
- )))
+ let error = SessionError::from(error);
+ match error {
+ #[cfg(feature = "postgres")]
+ SessionError::Admission(_) => Err(error),
+ _ => Err(SessionError::Rejected(PromptRefusal::plain(
+ "Couldn't prepare repository access for this session. Please retry; if this persists, check your GitHub connection.",
+ ))),
+ }
}
}
}
@@ -1174,6 +1181,11 @@ where
if cancel.is_cancelled() {
return Ok(StopReason::Cancelled);
}
+ // Quota-refused prompts must not be silently bundled into a later run.
+ #[cfg(feature = "postgres")]
+ if matches!(error, SessionError::Admission(_)) {
+ return Err(error);
+ }
// Only a create's refusal is carried: a follow-up run
// refused on an existing agent is already in a conversation
// the agent can see.
diff --git a/crates/cursor_cloud_agents/src/domain/service/test.rs b/crates/cursor_cloud_agents/src/domain/service/test.rs
index fa0bcdf4fc..d17e2a934a 100644
--- a/crates/cursor_cloud_agents/src/domain/service/test.rs
+++ b/crates/cursor_cloud_agents/src/domain/service/test.rs
@@ -2862,6 +2862,85 @@ async fn a_refused_create_keeps_its_repository_and_carries_the_prompt_forward()
assert_eq!(follow_up, "thanks");
}
+#[cfg(feature = "postgres")]
+struct RefusedChooser;
+
+#[cfg(feature = "postgres")]
+impl RepositoryChooser for RefusedChooser {
+ async fn choose(&self, _: &str, _: &Path) -> Result<SessionIntent, rootcause::Report> {
+ Err(
+ rootcause::report!(agent_session::domain::error::AiAdmissionError::Unavailable)
+ .into_dynamic(),
+ )
+ }
+}
+
+#[cfg(feature = "postgres")]
+#[tokio::test]
+async fn admission_refusal_is_typed_aborted_and_never_sent_to_cursor() {
+ use agent_session::domain::error::AiAdmissionError;
+ let cursor = FakeCursor::new();
+ let service = CursorSessionService::new(
+ cursor.clone(),
+ RecordingNotifier::new(),
+ RefusedChooser,
+ Arc::new(crate::outbound::memory_journal::MemoryJournal::default()),
+ NoArtifactStore,
+ );
+ let id = service.new_session(Path::new(""), vec![]);
+ for _ in 0..2 {
+ let error = service.prompt(&id, "do the thing").await.unwrap_err();
+ assert!(matches!(
+ error,
+ SessionError::Admission(AiAdmissionError::Unavailable)
+ ));
+ assert_eq!(error.to_string(), AiAdmissionError::Unavailable.to_string());
+ }
+ assert!(cursor.calls().is_empty());
+ let session = service.session(&id).unwrap();
+ let state = session.state.lock().unwrap();
+ assert!(
+ state.rejected_prompts.is_empty(),
+ "quota-refused work cannot hitch a ride on a later prompt"
+ );
+ assert!(state.intent.is_none());
+ assert_eq!(
+ state
+ .journal_entries
+ .iter()
+ .filter(|entry| matches!(entry.input, JournalInput::PromptAborted(_)))
+ .count(),
+ 2
+ );
+}
+
+#[cfg(feature = "postgres")]
+#[tokio::test]
+async fn existing_cursor_agent_runs_even_when_macro_helper_admission_would_fail() {
+ let cursor = FakeCursor::new();
+ let service = CursorSessionService::new(
+ cursor.clone(),
+ RecordingNotifier::new(),
+ RefusedChooser,
+ Arc::new(crate::outbound::memory_journal::MemoryJournal::default()),
+ NoArtifactStore,
+ );
+ let id = SessionId::new("existing");
+ service.restore_session(id.clone(), Some(CursorAgentId::new("agent-existing")), None);
+ crate::testing::script_legacy_history(&cursor);
+ service.replay_session(&id).await.unwrap().complete();
+ let events = cursor.script_stream();
+ events.send(finished("run")).unwrap();
+ events.send(CursorEvent::Done).unwrap();
+ service.prompt(&id, "continue").await.unwrap();
+ assert!(
+ cursor
+ .calls()
+ .iter()
+ .any(|call| matches!(call, CursorCall::CreateRun(..)))
+ );
+}
+
#[tokio::test]
async fn repository_setup_failure_is_retryable_and_not_reported_as_prompt_ambiguity() {
struct UnavailableChooser;
diff --git a/crates/cursor_cloud_agents/src/inbound/acp.rs b/crates/cursor_cloud_agents/src/inbound/acp.rs
index ae380f144c..2496593424 100644
--- a/crates/cursor_cloud_agents/src/inbound/acp.rs
+++ b/crates/cursor_cloud_agents/src/inbound/acp.rs
@@ -654,6 +654,11 @@ async fn advertise_slash_commands(notifier: &AcpNotifier, session: &SessionId) {
fn prompt_error(error: &SessionError) -> AcpError {
let acp_error = AcpError::new(-32603, error.to_string());
match error {
+ #[cfg(feature = "postgres")]
+ SessionError::Admission(error) => acp_error.data(Some(serde_json::json!({
+ "code": error.code(),
+ "retryable": error.is_retryable(),
+ }))),
SessionError::Rejected(refusal) => acp_error.data(
refusal
.notice
diff --git a/crates/cursor_cloud_agents/src/inbound/acp/test.rs b/crates/cursor_cloud_agents/src/inbound/acp/test.rs
index cb93e6e5ec..fa329170e5 100644
--- a/crates/cursor_cloud_agents/src/inbound/acp/test.rs
+++ b/crates/cursor_cloud_agents/src/inbound/acp/test.rs
@@ -26,6 +26,19 @@ type Service = CursorSessionService<
crate::domain::ports::NoArtifactStore,
>;
+#[cfg(feature = "postgres")]
+#[test]
+fn admission_error_has_sanitized_retryable_protocol_details() {
+ use agent_session::domain::error::AiAdmissionError;
+ let error = prompt_error(&SessionError::Admission(AiAdmissionError::Unavailable));
+ let value = serde_json::to_value(error).unwrap();
+ assert_eq!(value["message"], AiAdmissionError::Unavailable.to_string());
+ assert_eq!(
+ value["data"],
+ serde_json::json!({"code": "ai_billing_unavailable", "retryable": true})
+ );
+}
+
/// The client's end of a served connection.
struct TestClient {
to_agent: mpsc::UnboundedSender<TransportFrame>,
diff --git a/crates/documents/Cargo.toml b/crates/documents/Cargo.toml
index 3cf44973d8..47cbff8470 100644
--- a/crates/documents/Cargo.toml
+++ b/crates/documents/Cargo.toml
@@ -12,6 +12,7 @@ required-features = ["backfill_binary"]
[features]
purge = ["ports", "outbound", "dep:macro_db_client", "dep:sqs_client", "dep:comms_db_client"]
ai_tools = [
+ "dep:ai_billing",
"dep:ai_toolset",
"dep:ai_usage",
"dep:async-trait",
@@ -163,6 +164,7 @@ sync_service_client = { path = "../sync_service_client" }
task_dedup = { path = "../task_dedup", optional = true }
# AI Tool dependencies
+ai_billing = { path = "../ai_billing", optional = true }
ai_toolset = { path = "../ai_toolset", optional = true }
ai_usage = { path = "../ai_usage", optional = true }
async-trait = { workspace = true, optional = true }
diff --git a/crates/documents/src/domain.rs b/crates/documents/src/domain.rs
index 4b3305b256..b1278c5453 100644
--- a/crates/documents/src/domain.rs
+++ b/crates/documents/src/domain.rs
@@ -2,6 +2,8 @@
/// Event-to-activity mappings for this domain.
pub mod activity;
+#[cfg(feature = "ai_tools")]
+pub mod ai_editing;
pub mod branch_name;
/// A document's comment threads, read through the shared message service.
#[cfg(feature = "ai_tools")]
diff --git a/crates/documents/src/domain/ai_editing.rs b/crates/documents/src/domain/ai_editing.rs
new file mode 100644
index 0000000000..ac233c5133
--- /dev/null
+++ b/crates/documents/src/domain/ai_editing.rs
@@ -0,0 +1,89 @@
+//! Permission-scoped AI editing, admission, and existing per-model metering.
+
+use super::ports::editing::{EditMode, EditResult, EditingWorkerService, EditorName};
+use ai_billing::domain::admission::{AiAdmissionError, AiAdmissionService};
+use ai_usage::{AiFeature, UsageContext, UsageRecorder};
+use entity_access::domain::models::{EditAccessLevel, EntityAccessReceipt};
+use macro_sync_service_jwt::DocumentPermissionToken;
+use macro_user_id::user_id::MacroUserIdStr;
+use std::sync::Arc;
+
+#[cfg(test)]
+mod test;
+
+/// An authorized edit with its boundary-minted, narrowly scoped worker token.
+pub struct AiEditRequest<'a> {
+ /// Permission token for the document named by the receipt.
+ pub document_token: &'a DocumentPermissionToken,
+ /// Requested changes.
+ pub instructions: &'a str,
+ /// Worker pipeline to run.
+ pub mode: EditMode,
+ /// Name displayed on the editing cursor.
+ pub editor: Option<EditorName>,
+}
+
+/// Admission failures never start the worker.
+#[derive(Debug, thiserror::Error)]
+pub enum AiEditError {
+ /// Quota refusal or temporary validation failure.
+ #[error("{0}")]
+ Admission(#[from] AiAdmissionError),
+ /// An admitted worker call failed.
+ #[error(transparent)]
+ Worker(#[from] anyhow::Error),
+}
+
+/// Orchestrates AI editing independently of tool or HTTP transport.
+pub struct AiEditingService<W> {
+ worker: Arc<W>,
+ admission: Arc<dyn AiAdmissionService>,
+ recorder: Arc<dyn UsageRecorder>,
+}
+
+impl<W: EditingWorkerService> AiEditingService<W> {
+ /// Compose the worker with the host's admission and existing usage recorder.
+ pub fn new(
+ worker: Arc<W>,
+ admission: Arc<dyn AiAdmissionService>,
+ recorder: Arc<dyn UsageRecorder>,
+ ) -> Self {
+ Self {
+ worker,
+ admission,
+ recorder,
+ }
+ }
+
+ /// Apply an authorized edit for the trusted caller. Dropping this future
+ /// cancels the worker call; completed calls retain their existing metering.
+ pub async fn edit(
+ &self,
+ receipt: EntityAccessReceipt<EditAccessLevel>,
+ caller: &MacroUserIdStr<'static>,
+ request: AiEditRequest<'_>,
+ ) -> Result<EditResult, AiEditError> {
+ self.admission.admit(caller, AiFeature::AiEditing).await?;
+ let document_id = &receipt.entity().entity_id;
+ let result = self
+ .worker
+ .edit(
+ document_id,
+ request.document_token,
+ request.instructions,
+ request.mode,
+ request.editor,
+ )
+ .await?;
+ let usage = UsageContext::new(AiFeature::AiEditing, caller.clone())
+ .with_entity(macro_uuid::string_to_uuid(document_id).ok());
+ for model in &result.usage {
+ self.recorder.record(usage.clone().into_event(
+ model.model.clone(),
+ u64::from(model.input_tokens),
+ u64::from(model.output_tokens),
+ ));
+ }
+ Ok(result)
+ }
+}
diff --git a/crates/documents/src/domain/ai_editing/test.rs b/crates/documents/src/domain/ai_editing/test.rs
new file mode 100644
index 0000000000..2e1b0a4257
--- /dev/null
+++ b/crates/documents/src/domain/ai_editing/test.rs
@@ -0,0 +1,177 @@
+use super::*;
+use crate::domain::ports::editing::{EditUsage, MockEditingWorkerService};
+use ai_billing::domain::{DenyReason, admission::AdmissionFuture};
+use ai_usage::{UsageAmount, UsageEvent};
+use entity_access::domain::models::{Entity, EntityPermission, EntityType};
+use models_permissions::share_permission::access_level::AccessLevel;
+use std::sync::{
+ Mutex,
+ atomic::{AtomicBool, Ordering},
+};
+
+const DOCUMENT: &str = "019fd3b9-3c6c-7c05-89c2-a27f0121813b";
+fn user() -> MacroUserIdStr<'static> {
+ "macro|[email protected]".to_owned().try_into().unwrap()
+}
+fn receipt() -> EntityAccessReceipt<EditAccessLevel> {
+ EntityAccessReceipt::try_new_authenticated_user(
+ user(),
+ Entity {
+ entity_id: DOCUMENT.into(),
+ entity_type: EntityType::Document,
+ },
+ EntityPermission::AccessLevel {
+ access_level: AccessLevel::Edit,
+ },
+ )
+ .unwrap()
+}
+fn token() -> DocumentPermissionToken {
+ DocumentPermissionToken::from("test-scoped-token".to_owned())
+}
+fn request(token: &DocumentPermissionToken) -> AiEditRequest<'_> {
+ AiEditRequest {
+ document_token: token,
+ instructions: "edit",
+ mode: EditMode::Fast,
+ editor: EditorName::new("Macro"),
+ }
+}
+
+struct Admission(Result<(), AiAdmissionError>);
+impl AiAdmissionService for Admission {
+ fn admit<'a>(
+ &'a self,
+ caller: &'a MacroUserIdStr<'_>,
+ feature: AiFeature,
+ ) -> AdmissionFuture<'a> {
+ Box::pin(async move {
+ assert_eq!(caller, &user());
+ assert_eq!(feature, AiFeature::AiEditing);
+ self.0
+ })
+ }
+}
+#[derive(Default)]
+struct Recorder(Mutex<Vec<UsageEvent>>);
+impl UsageRecorder for Recorder {
+ fn record(&self, event: UsageEvent) {
+ self.0.lock().unwrap().push(event);
+ }
+}
+
+#[tokio::test]
+async fn refusal_never_calls_worker_or_records_usage() {
+ for error in [
+ AiAdmissionError::Denied(DenyReason::AllowanceExhausted),
+ AiAdmissionError::Unavailable,
+ ] {
+ let recorder = Arc::new(Recorder::default());
+ let service = AiEditingService::new(
+ Arc::new(MockEditingWorkerService::new()),
+ Arc::new(Admission(Err(error))),
+ recorder.clone(),
+ );
+ assert!(
+ matches!(service.edit(receipt(), &user(), request(&token())).await, Err(AiEditError::Admission(actual)) if actual == error)
+ );
+ assert!(recorder.0.lock().unwrap().is_empty());
+ }
+}
+
+#[tokio::test]
+async fn admitted_edit_keeps_worker_arguments_and_each_models_usage() {
+ let mut worker = MockEditingWorkerService::new();
+ worker
+ .expect_edit()
+ .times(1)
+ .returning(|id, token, instructions, mode, editor| {
+ assert_eq!(id, DOCUMENT);
+ assert_eq!(token.as_str(), "test-scoped-token");
+ assert_eq!(instructions, "edit");
+ assert_eq!(mode, EditMode::Fast);
+ assert_eq!(editor, EditorName::new("Macro"));
+ Box::pin(async {
+ Ok(EditResult {
+ edits_applied: 0,
+ clarification: Some("Which paragraph?".into()),
+ usage: vec![
+ EditUsage {
+ model: "model-a".into(),
+ input_tokens: 12,
+ output_tokens: 3,
+ },
+ EditUsage {
+ model: "model-b".into(),
+ input_tokens: 14,
+ output_tokens: 5,
+ },
+ ],
+ })
+ })
+ });
+ let recorder = Arc::new(Recorder::default());
+ let service = AiEditingService::new(
+ Arc::new(worker),
+ Arc::new(Admission(Ok(()))),
+ recorder.clone(),
+ );
+ let result = service
+ .edit(receipt(), &user(), request(&token()))
+ .await
+ .unwrap();
+ assert_eq!(result.clarification.as_deref(), Some("Which paragraph?"));
+ let events = recorder.0.lock().unwrap();
+ assert_eq!(events.len(), 2);
+ for event in events.iter() {
+ assert_eq!(event.user, user());
+ assert_eq!(event.feature, AiFeature::AiEditing);
+ assert_eq!(event.entity, Some(DOCUMENT.parse().unwrap()));
+ }
+ assert_eq!(events[0].model, "model-a");
+ assert_eq!(
+ events[0].amount,
+ UsageAmount::Tokens {
+ input: 12,
+ output: 3
+ }
+ );
+ assert_eq!(events[1].model, "model-b");
+}
+
+struct Dropped(Arc<AtomicBool>);
+impl Drop for Dropped {
+ fn drop(&mut self) {
+ self.0.store(true, Ordering::SeqCst);
+ }
+}
+
+#[tokio::test]
+async fn cancelling_edit_drops_in_flight_worker_without_inventing_usage() {
+ let dropped = Arc::new(AtomicBool::new(false));
+ let signal = dropped.clone();
+ let mut worker = MockEditingWorkerService::new();
+ worker
+ .expect_edit()
+ .times(1)
+ .returning(move |_, _, _, _, _| {
+ let guard = Dropped(signal.clone());
+ Box::pin(async move {
+ let _guard = guard;
+ std::future::pending().await
+ })
+ });
+ let recorder = Arc::new(Recorder::default());
+ let service = AiEditingService::new(
+ Arc::new(worker),
+ Arc::new(Admission(Ok(()))),
+ recorder.clone(),
+ );
+ let caller = user();
+ let token = token();
+ let mut edit = Box::pin(service.edit(receipt(), &caller, request(&token)));
+ assert!(futures::poll!(&mut edit).is_pending());
+ drop(edit);
+ assert!(dropped.load(Ordering::SeqCst));
+ assert!(recorder.0.lock().unwrap().is_empty());
+}
diff --git a/crates/documents/src/inbound/toolset.rs b/crates/documents/src/inbound/toolset.rs
index 45fb2013bc..17754e46be 100644
--- a/crates/documents/src/inbound/toolset.rs
+++ b/crates/documents/src/inbound/toolset.rs
@@ -95,6 +95,9 @@ pub struct DocumentToolContext<
/// JWT secret used to mint document permission tokens for the editing worker.
pub document_permission_jwt_secret: String,
+ /// Shared admission used by the domain AI-editing use case.
+ pub admission: Arc<dyn ai_billing::domain::admission::AiAdmissionService>,
+
/// Records the token usage the editing worker reports. Defaults to a no-op;
/// the chat path injects the real (Postgres-backed) recorder per request.
pub recorder: Arc<dyn ai_usage::UsageRecorder>,
@@ -129,6 +132,7 @@ impl<
messages: self.messages.clone(),
spreadsheet: self.spreadsheet.clone(),
document_permission_jwt_secret: self.document_permission_jwt_secret.clone(),
+ admission: self.admission.clone(),
recorder: self.recorder.clone(),
actor: self.actor,
actor_name: self.actor_name.clone(),
@@ -186,12 +190,31 @@ impl<
messages,
spreadsheet,
document_permission_jwt_secret,
+ admission: Arc::new(ai_billing::domain::admission::DisabledAiAdmissionService),
recorder: Arc::new(ai_usage::NoOpUsageRecorder),
actor: bot_id::MACRO_AI_BOT_ID,
actor_name: None,
}
}
+ /// Configure admission for AI edits; deterministic operations do not use it.
+ pub fn with_admission(
+ mut self,
+ admission: Arc<dyn ai_billing::domain::admission::AiAdmissionService>,
+ ) -> Self {
+ self.admission = admission;
+ self
+ }
+
+ /// The AI-editing use case using the currently injected services.
+ pub fn ai_editing(&self) -> crate::domain::ai_editing::AiEditingService<EDSvc> {
+ crate::domain::ai_editing::AiEditingService::new(
+ self.editing.clone(),
+ self.admission.clone(),
+ self.recorder.clone(),
+ )
+ }
+
/// Set the usage recorder the EditDocument tool logs worker token usage to.
pub fn with_recorder(mut self, recorder: Arc<dyn ai_usage::UsageRecorder>) -> Self {
self.recorder = recorder;
diff --git a/crates/documents/src/inbound/toolset/edit_document.rs b/crates/documents/src/inbound/toolset/edit_document.rs
index 76524b614a..8fe565f014 100644
--- a/crates/documents/src/inbound/toolset/edit_document.rs
+++ b/crates/documents/src/inbound/toolset/edit_document.rs
@@ -1,5 +1,6 @@
-//! EditDocument tool — thin wrapper over [`EditingWorkerPort`].
+//! EditDocument tool — permission/token boundary for the domain AI-editing use case.
+use crate::domain::ai_editing::{AiEditError, AiEditRequest};
use crate::domain::permission_token::encode_permission_token;
use crate::domain::ports::{
DocumentService,
@@ -108,7 +109,8 @@ where
ctx: ServiceContext<DocumentToolContext<DSvc, ESvc, EDSvc>>,
request_context: RequestContext,
) -> ToolResult<Self::Output> {
- ctx.entity_access_service
+ let receipt = ctx
+ .entity_access_service
.generate_entity_access_receipt::<EditAccessLevel>(
&request_context.user_id,
None,
@@ -153,36 +155,34 @@ where
// in-flight worker call (closing the HTTP connection so the worker aborts
// its own LLM work) and surface a `cancelled` tool error -- matching how
// the chat stream renders cancellation for tool calls that never returned.
+ let editing = ctx.ai_editing();
+ let edit = AiEditRequest {
+ document_token: &document_token,
+ instructions: &self.instructions,
+ mode: self.mode(),
+ editor,
+ };
let result = tokio::select! {
+ biased;
_ = request_context.cancel.cancelled() => {
return Err(ToolCallError {
description: "cancelled".to_string(),
internal_error: anyhow::anyhow!("edit cancelled by user. document might be left in a partially edited state."),
});
}
- r = ctx.editing.edit(&self.document_id, &document_token, &self.instructions, self.mode(), editor) => r,
+ r = editing.edit(receipt, &request_context.user_id, edit) => r,
}
- .map_err(|e| ToolCallError {
- description: e.to_string(),
- internal_error: e,
+ .map_err(|error| {
+ let description = match &error {
+ AiEditError::Admission(error) => format!("{}: {error}", error.code()),
+ AiEditError::Worker(error) => error.to_string(),
+ };
+ ToolCallError {
+ description,
+ internal_error: error.into(),
+ }
})?;
- // The worker runs several models on the caller's behalf; record each so
- // their tokens land on the usage ledger (attributed to this user).
- let entity = macro_uuid::string_to_uuid(&self.document_id).ok();
- for u in &result.usage {
- let cx = ai_usage::UsageContext::new(
- ai_usage::AiFeature::AiEditing,
- request_context.user_id.clone(),
- )
- .with_entity(entity);
- ctx.recorder.record(cx.into_event(
- u.model.clone(),
- u.input_tokens as u64,
- u.output_tokens as u64,
- ));
- }
-
let summary = if result.clarification.is_some() {
"Paused for clarification; no edits applied.".to_string()
} else {
diff --git a/crates/documents/src/inbound/toolset/edit_document/test.rs b/crates/documents/src/inbound/toolset/edit_document/test.rs
index af9b2269c2..88f94350d7 100644
--- a/crates/documents/src/inbound/toolset/edit_document/test.rs
+++ b/crates/documents/src/inbound/toolset/edit_document/test.rs
@@ -29,6 +29,78 @@ use model_owner::{CreationPrincipal, Owner};
use sync_service_client::SyncServiceClient;
use uuid::Uuid;
+use ai_billing::domain::{
+ DenyReason,
+ admission::{AdmissionFuture, AiAdmissionError, AiAdmissionService},
+};
+
+struct Refuse(AiAdmissionError);
+impl AiAdmissionService for Refuse {
+ fn admit<'a>(
+ &'a self,
+ user: &'a MacroUserIdStr<'_>,
+ feature: ai_usage::AiFeature,
+ ) -> AdmissionFuture<'a> {
+ Box::pin(async move {
+ assert_eq!(user.as_ref(), TEST_USER_ID);
+ assert_eq!(feature, ai_usage::AiFeature::AiEditing);
+ Err(self.0)
+ })
+ }
+}
+
+#[tokio::test]
+async fn direct_edit_tool_surfaces_admission_failure_without_worker_calls() {
+ for error in [
+ AiAdmissionError::Denied(DenyReason::AllowanceExhausted),
+ AiAdmissionError::Unavailable,
+ ] {
+ let (result, worker) = call_edit_document_in("md", false, |context| {
+ context.with_admission(Arc::new(Refuse(error)))
+ })
+ .await;
+ assert_eq!(
+ result.unwrap_err().description,
+ format!("{}: {error}", error.code())
+ );
+ assert!(worker.edit_calls.lock().unwrap().is_empty());
+ }
+}
+
+#[tokio::test]
+async fn permission_errors_still_precede_quota_errors() {
+ let (result, worker) = call_edit_document_in("md", false, |mut context| {
+ context.entity_access_service = Arc::new(FakeEntityAccessService {
+ access_level: AccessLevel::View,
+ });
+ context.with_admission(Arc::new(Refuse(AiAdmissionError::Unavailable)))
+ })
+ .await;
+ assert_eq!(
+ result.unwrap_err().description,
+ "you do not have edit access to this document"
+ );
+ assert!(worker.edit_calls.lock().unwrap().is_empty());
+}
+
+#[tokio::test]
+async fn cancelled_tool_does_not_start_worker() {
+ let worker = FakeEditingWorker::default();
+ let context = tool_context(FakeDocumentService::new("md"), worker.clone());
+ let request = request_context();
+ request.cancel.cancel();
+ let tool = EditDocument {
+ document_id: TEST_DOCUMENT_ID.into(),
+ instructions: "edit".into(),
+ fast: false,
+ };
+ assert_eq!(
+ tool.call(context, request).await.unwrap_err().description,
+ "cancelled"
+ );
+ assert!(worker.edit_calls.lock().unwrap().is_empty());
+}
+
const TEST_USER_ID: &str = "macro|[email protected]";
const TEST_DOCUMENT_ID: &str = "019fd3b9-3c6c-7c05-89c2-a27f0121813b";
diff --git a/crates/import/Cargo.toml b/crates/import/Cargo.toml
index 99ecb67429..774801e2c3 100644
--- a/crates/import/Cargo.toml
+++ b/crates/import/Cargo.toml
@@ -5,6 +5,7 @@ publish = false
version = "0.1.0"
[dependencies]
+ai_billing = { path = "../ai_billing" }
rootcause = { workspace = true }
agent = { path = "../agent" }
ai_toolset = { path = "../ai_toolset" }
diff --git a/crates/import/src/domain/ports.rs b/crates/import/src/domain/ports.rs
index e407286578..7766409be2 100644
--- a/crates/import/src/domain/ports.rs
+++ b/crates/import/src/domain/ports.rs
@@ -8,6 +8,9 @@ use uuid::Uuid;
/// Errors surfaced by the import service and repository.
#[derive(Debug, Error)]
pub enum ImportError {
+ /// AI work was refused or usage validation is temporarily unavailable.
+ #[error(transparent)]
+ Admission(#[from] ai_billing::AiAdmissionError),
/// Database failure.
#[error("database error: {0}")]
Db(rootcause::Report),
diff --git a/crates/import/src/domain/service.rs b/crates/import/src/domain/service.rs
index 9ede8ce3e4..4f600ea7f6 100644
--- a/crates/import/src/domain/service.rs
+++ b/crates/import/src/domain/service.rs
@@ -32,6 +32,7 @@ use std::sync::LazyLock;
use std::time::Duration;
use uuid::Uuid;
+mod admission;
mod prompts;
#[cfg(test)]
@@ -94,7 +95,7 @@ fn notion_import_failure_reason(outcome: &anyhow::Result<()>) -> String {
outcome
.as_ref()
.err()
- .map(ToString::to_string)
+ .map(admission::failure_reason)
.unwrap_or_else(|| "the import job did not finish this item".to_string())
}
@@ -305,6 +306,7 @@ pub struct ImportServiceImpl<R, S, C> {
mcp_tools: Arc<S>,
creator: Arc<C>,
recorder: Arc<dyn ai_usage::UsageRecorder>,
+ admission: Arc<dyn ai_billing::AiAdmissionService>,
notifier: Option<ImportNotify>,
}
@@ -315,6 +317,7 @@ impl<R: Clone, S, C> Clone for ImportServiceImpl<R, S, C> {
mcp_tools: self.mcp_tools.clone(),
creator: self.creator.clone(),
recorder: self.recorder.clone(),
+ admission: self.admission.clone(),
notifier: self.notifier.clone(),
}
}
@@ -333,6 +336,7 @@ impl<R, S, C> ImportServiceImpl<R, S, C> {
mcp_tools,
creator,
recorder,
+ admission: Arc::new(ai_billing::DisabledAiAdmissionService),
notifier: None,
}
}
@@ -378,7 +382,12 @@ where
tracing::warn!(source = source.as_ref(), error = ?e, "gather session failed");
service
.repo
- .finish_run(&user, source, RunStatus::Failed, Some(&e.to_string()))
+ .finish_run(
+ &user,
+ source,
+ RunStatus::Failed,
+ Some(&admission::failure_reason(&e)),
+ )
.await
}
};
@@ -452,14 +461,29 @@ where
user: &MacroUserIdStr<'static>,
source: ImportSource,
) -> anyhow::Result<()> {
+ // The gather may have waited since it was accepted. Refuse before
+ // loading tools; Slack still gets its deterministic attempt first.
+ self.admit_gather(user, source).await?;
let mcp_tools = self.connector_tools(user, source).await?;
+ self.gather_with_tools(user, source, mcp_tools).await
+ }
+
+ async fn gather_with_tools<M>(
+ &self,
+ user: &MacroUserIdStr<'static>,
+ source: ImportSource,
+ mcp_tools: Arc<M>,
+ ) -> anyhow::Result<()>
+ where
+ M: ToolSet<()> + ToolSet<ImportToolContext<Self>> + 'static,
+ {
// Slack discovery is a listing problem, not a language problem:
// enumerate channels through the connector directly and stage the
// strongest. The agent session only runs as a fallback, when the
// connector's tool surface changed under us.
if source == ImportSource::Slack {
- match self.gather_slack_direct(user, &mcp_tools).await {
+ match self.gather_slack_direct(user, &*mcp_tools).await {
Ok(_) => return Ok(()),
Err(e) => {
tracing::warn!(error = ?e, "direct slack gather failed; trying the agent");
@@ -475,6 +499,7 @@ where
.await
{
Ok(()) => Ok(()),
+ Err(e) if e.is::<ai_billing::AiAdmissionError>() => Err(e),
Err(e) => {
tracing::warn!(model = GATHER_MODEL, error = ?e, "gather session failed; retrying on the fallback model");
self.gather_agent_session(user, source, GATHER_FALLBACK_MODEL, mcp_tools)
@@ -485,12 +510,12 @@ where
/// One agent gather session on a specific model.
#[tracing::instrument(skip(self, user, mcp_tools), err)]
- async fn gather_agent_session(
+ async fn gather_agent_session<M: ToolSet<ImportToolContext<Self>> + 'static>(
&self,
user: &MacroUserIdStr<'static>,
source: ImportSource,
model: &str,
- mcp_tools: Arc<UserMcpTools>,
+ mcp_tools: Arc<M>,
) -> anyhow::Result<()> {
let native = gather_toolset::<Self>();
let toolset = NativePlusMcp::new(native, mcp_tools);
@@ -517,10 +542,10 @@ where
/// handle — routing page content through a model means re-emitting the
/// whole page as output tokens, which is an order of magnitude slower.
#[tracing::instrument(skip(self, user, mcp_tools, row), fields(id = %row.id), err)]
- async fn import_notion_page_direct(
+ async fn import_notion_page_direct<M: ToolSet<()>>(
&self,
user: &MacroUserIdStr<'static>,
- mcp_tools: &UserMcpTools,
+ mcp_tools: &M,
row: &ImportEntity,
) -> anyhow::Result<()> {
let fetch_tool = notion_fetch_tool_name(mcp_tools)
@@ -574,10 +599,10 @@ where
/// Call one connector tool and surface both dispatch and tool errors as
/// plain errors.
- async fn connector_tool_call(
+ async fn connector_tool_call<M: ToolSet<()>>(
&self,
user: &MacroUserIdStr<'static>,
- mcp_tools: &UserMcpTools,
+ mcp_tools: &M,
tool_name: &str,
arguments: &serde_json::Value,
) -> anyhow::Result<serde_json::Value> {
@@ -601,10 +626,10 @@ where
/// real error. Staged rows carry no participants — inviting teammates
/// stays best-effort and must never block discovery.
#[tracing::instrument(skip(self, user, mcp_tools), err)]
- async fn gather_slack_direct(
+ async fn gather_slack_direct<M: ToolSet<()>>(
&self,
user: &MacroUserIdStr<'static>,
- mcp_tools: &UserMcpTools,
+ mcp_tools: &M,
) -> anyhow::Result<usize> {
let search_tool = slack_channel_search_tool_name(mcp_tools)
.ok_or_else(|| anyhow::anyhow!("connector exposes no channel-search tool"))?;
@@ -685,11 +710,11 @@ where
/// Fallback: run a single-page Haiku session over the shared connector
/// tools. Rows the agent fails to finalize are handled by the caller.
#[tracing::instrument(skip(self, user, mcp_tools, rows), fields(pages = rows.len()), err)]
- async fn run_notion_import_session(
+ async fn run_notion_import_session<M: ToolSet<ImportToolContext<Self>> + 'static>(
&self,
user: &MacroUserIdStr<'static>,
rows: &[ImportEntity],
- mcp_tools: Arc<UserMcpTools>,
+ mcp_tools: Arc<M>,
) -> anyhow::Result<()> {
let native = notion_import_toolset::<Self>();
let toolset = NativePlusMcp::new(native, mcp_tools);
@@ -731,17 +756,20 @@ where
}
/// Run one bounded agent session to completion, discarding the text.
- #[allow(clippy::too_many_arguments)]
- async fn drive_session(
+ #[expect(clippy::too_many_arguments, reason = "bounded session configuration")]
+ async fn drive_session<M: ToolSet<ImportToolContext<Self>> + 'static>(
&self,
user: &MacroUserIdStr<'static>,
model: impl ToString,
max_turns: usize,
- toolset: NativePlusMcp<ImportToolContext<Self>>,
+ toolset: NativePlusMcp<ImportToolContext<Self>, M>,
context: ImportToolContext<Self>,
system_prompt: &str,
user_prompt: &str,
) -> anyhow::Result<()> {
+ // Covers Slack/Notion fallbacks and pages waiting behind the batch's
+ // concurrency limit. Never gate their preceding deterministic work.
+ self.admit_ai(user).await?;
let usage_ctx = ai_usage::UsageContext::new(ai_usage::AiFeature::Import, user.clone());
let agent_loop = AgentLoop::new(self.recorder.clone())
.with_model(model)
@@ -862,15 +890,18 @@ where
/// Run the canonical single-page Notion pipeline for a row that is
/// already `importing`.
- async fn process_notion_page(
+ async fn process_notion_page<M>(
&self,
user: &MacroUserIdStr<'static>,
- mcp_tools: Arc<UserMcpTools>,
+ mcp_tools: Arc<M>,
row: &ImportEntity,
- ) -> anyhow::Result<()> {
+ ) -> anyhow::Result<()>
+ where
+ M: ToolSet<()> + ToolSet<ImportToolContext<Self>> + 'static,
+ {
let outcome = tokio::time::timeout(NOTION_PAGE_IMPORT_TIMEOUT, async {
match self
- .import_notion_page_direct(user, &mcp_tools, row)
+ .import_notion_page_direct(user, &*mcp_tools, row)
.await
{
Ok(()) => Ok(()),
@@ -1049,8 +1080,10 @@ where
source: ImportSource,
auto_import: bool,
) -> Result<bool> {
- // Wins only when no run row exists — gathers run once per
- // connection; explicit retry is the only re-entry.
+ if !self.prepare_gather(&user, source, &[]).await? {
+ return Ok(false);
+ }
+ // The CAS still decides the winner if another request raced admission.
let won = self.repo.start_run(&user, source, &[], auto_import).await?;
if won {
self.spawn_gather(user.clone(), source);
@@ -1065,6 +1098,12 @@ where
user: MacroUserIdStr<'static>,
source: ImportSource,
) -> Result<bool> {
+ if !self
+ .prepare_gather(&user, source, &[RunStatus::Failed, RunStatus::Dismissed])
+ .await?
+ {
+ return Ok(false);
+ }
let won = self
.repo
.start_run(
@@ -1112,6 +1151,9 @@ where
}
}
+ // Claim deterministic work without quota checks. Even Notion tries a
+ // direct fetch first; only its AI fallback needs admission, and any
+ // refusal releases the row through the usual failure bookkeeping.
let rows = self.repo.mark_importing(&user, &import_ids).await?;
let importing = rows.len() as u64;
self.notify(&user).await;
@@ -1399,6 +1441,11 @@ where
.process_notion_page(user, mcp_tools, &importing_row)
.await;
self.notify(user).await;
+ if let Err(error) = &pipeline_result
+ && let Some(error) = error.downcast_ref::<ai_billing::AiAdmissionError>()
+ {
+ return Err(ImportError::Admission(*error));
+ }
let row = self
.repo
@@ -1501,7 +1548,7 @@ where
/// The mangled name of the connector's Notion fetch tool. Notion exposes this
/// as `notion-fetch` generally and as `fetch` on OpenAI-compatible surfaces.
-fn notion_fetch_tool_name(mcp_tools: &UserMcpTools) -> Option<String> {
+fn notion_fetch_tool_name(mcp_tools: &impl ToolSet<()>) -> Option<String> {
ToolSet::<()>::request_schemas(mcp_tools)?
.into_iter()
.map(|schema| schema.name)
@@ -1518,7 +1565,7 @@ fn is_notion_fetch_tool_name(name: &str) -> bool {
/// The mangled name of the connector's channel-search tool. Slack's hosted
/// MCP has shipped several tool-name spellings, so this matches the shape —
/// a search/list over channels — rather than one literal name.
-fn slack_channel_search_tool_name(mcp_tools: &UserMcpTools) -> Option<String> {
+fn slack_channel_search_tool_name(mcp_tools: &impl ToolSet<()>) -> Option<String> {
ToolSet::<()>::request_schemas(mcp_tools)?
.into_iter()
.map(|schema| schema.name)
@@ -2706,14 +2753,14 @@ impl Drop for AbortOnDrop {
/// A toolset combining an in-process collection with the user's connector
/// MCP tools: native tools win by name, everything else routes to MCP.
-struct NativePlusMcp<Context> {
+struct NativePlusMcp<Context, M> {
native: ai_toolset::AsyncToolCollection<Context>,
native_names: HashSet<String>,
- mcp: Arc<UserMcpTools>,
+ mcp: Arc<M>,
}
-impl<Context: Send + Sync + 'static> NativePlusMcp<Context> {
- fn new(native: ai_toolset::AsyncToolCollection<Context>, mcp: Arc<UserMcpTools>) -> Self {
+impl<Context: Send + Sync + 'static, M> NativePlusMcp<Context, M> {
+ fn new(native: ai_toolset::AsyncToolCollection<Context>, mcp: Arc<M>) -> Self {
let native_names = native
.request_schemas()
.unwrap_or_default()
@@ -2728,9 +2775,10 @@ impl<Context: Send + Sync + 'static> NativePlusMcp<Context> {
}
}
-impl<Context> ToolSet<Context> for NativePlusMcp<Context>
+impl<Context, M> ToolSet<Context> for NativePlusMcp<Context, M>
where
Context: Clone + Send + Sync + 'static,
+ M: ToolSet<Context>,
{
fn dispatch_tool_call<'a>(
&'a self,
diff --git a/crates/import/src/domain/service/admission.rs b/crates/import/src/domain/service/admission.rs
new file mode 100644
index 0000000000..ea6d95e0cf
--- /dev/null
+++ b/crates/import/src/domain/service/admission.rs
@@ -0,0 +1,68 @@
+//! Admission belongs at AI boundaries, not at deterministic import claims.
+
+use super::{ImportServiceImpl, ImportSource, Result, RunStatus};
+use crate::domain::ports::ImportRepo;
+use ai_billing::{AiAdmissionError, AiAdmissionService};
+use ai_usage::AiFeature;
+use macro_user_id::user_id::MacroUserIdStr;
+use std::sync::Arc;
+
+impl<R, S, C> ImportServiceImpl<R, S, C> {
+ /// Attach configured shared admission. Production hosts must supply this;
+ /// the source-compatible constructor defaults to disabled enforcement.
+ pub fn with_admission(mut self, admission: Arc<dyn AiAdmissionService>) -> Self {
+ self.admission = admission;
+ self
+ }
+
+ pub(super) async fn admit_ai(
+ &self,
+ user: &MacroUserIdStr<'static>,
+ ) -> std::result::Result<(), AiAdmissionError> {
+ self.admission.admit(user, AiFeature::Import).await
+ }
+
+ pub(super) async fn admit_gather(
+ &self,
+ user: &MacroUserIdStr<'static>,
+ source: ImportSource,
+ ) -> std::result::Result<(), AiAdmissionError> {
+ match source {
+ ImportSource::Slack => Ok(()),
+ ImportSource::Linear | ImportSource::Notion => self.admit_ai(user).await,
+ }
+ }
+}
+
+impl<R: ImportRepo, S, C> ImportServiceImpl<R, S, C> {
+ /// Preserve no-op retries and settings before checking new AI spending.
+ /// Slack discovery is deterministic until its fallback actually starts.
+ pub(super) async fn prepare_gather(
+ &self,
+ user: &MacroUserIdStr<'static>,
+ source: ImportSource,
+ from: &[RunStatus],
+ ) -> Result<bool> {
+ if let Some(run) = self
+ .repo
+ .list_runs(user)
+ .await?
+ .iter()
+ .find(|run| run.source == source)
+ && !from.contains(&run.status)
+ {
+ return Ok(false);
+ }
+ self.admit_gather(user, source).await?;
+ Ok(true)
+ }
+}
+
+/// Persist stable, sanitized admission codes in existing run/row error fields.
+/// Unavailability is retryable; exhaustion requires a quota/policy change.
+pub(super) fn failure_reason(error: &anyhow::Error) -> String {
+ match error.downcast_ref::<AiAdmissionError>() {
+ Some(error) => format!("{}: {error}", error.code()),
+ None => error.to_string(),
+ }
+}
diff --git a/crates/import/src/domain/service/test.rs b/crates/import/src/domain/service/test.rs
index 3d8a9934eb..b7b7c95d04 100644
--- a/crates/import/src/domain/service/test.rs
+++ b/crates/import/src/domain/service/test.rs
@@ -1,5 +1,7 @@
use super::*;
+mod admission;
+
fn meta(
identifier: Option<&str>,
description: Option<&str>,
diff --git a/crates/import/src/domain/service/test/admission.rs b/crates/import/src/domain/service/test/admission.rs
new file mode 100644
index 0000000000..407451ddbe
--- /dev/null
+++ b/crates/import/src/domain/service/test/admission.rs
@@ -0,0 +1,734 @@
+use super::*;
+use ai_billing::{AiAdmissionError, AiAdmissionService, DenyReason};
+use std::sync::Mutex;
+use std::sync::atomic::{AtomicUsize, Ordering};
+
+fn user() -> MacroUserIdStr<'static> {
+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap()
+}
+
+fn denied() -> AiAdmissionError {
+ AiAdmissionError::Denied(DenyReason::AllowanceExhausted)
+}
+
+struct Admission {
+ error: Mutex<Option<AiAdmissionError>>,
+ calls: AtomicUsize,
+ allow_first: bool,
+}
+
+impl Admission {
+ fn refusing(error: AiAdmissionError) -> Arc<Self> {
+ Arc::new(Self {
+ error: Mutex::new(Some(error)),
+ calls: AtomicUsize::new(0),
+ allow_first: false,
+ })
+ }
+}
+
+impl AiAdmissionService for Admission {
+ fn admit<'a>(
+ &'a self,
+ caller: &'a MacroUserIdStr<'_>,
+ feature: ai_usage::AiFeature,
+ ) -> ai_billing::domain::admission::AdmissionFuture<'a> {
+ assert_eq!(caller, &user());
+ assert_eq!(feature, ai_usage::AiFeature::Import);
+ let call = self.calls.fetch_add(1, Ordering::SeqCst);
+ let error = *self.error.lock().unwrap();
+ Box::pin(async move {
+ if self.allow_first && call == 0 {
+ return Ok(());
+ }
+ error.map_or(Ok(()), Err)
+ })
+ }
+}
+
+#[derive(Default, Clone)]
+struct Repo(Arc<Mutex<Ledger>>);
+
+#[derive(Default)]
+struct Ledger {
+ rows: Vec<ImportEntity>,
+ runs: Vec<ImportRun>,
+}
+
+impl Repo {
+ fn seed(&self, source: ImportSource) -> ImportEntity {
+ let row = ImportEntity {
+ id: Uuid::now_v7(),
+ user_id: user().to_string(),
+ team_id: None,
+ source,
+ foreign_id: Uuid::now_v7().to_string(),
+ status: ImportStatus::Staged,
+ initiator: Initiator::Onboarding,
+ metadata: serde_json::json!({"title": "A page", "name": "general"}),
+ entity_id: None,
+ entity_type: None,
+ last_error: None,
+ created_at: chrono::Utc::now(),
+ updated_at: chrono::Utc::now(),
+ };
+ self.0.lock().unwrap().rows.push(row.clone());
+ row
+ }
+}
+
+impl ImportRepo for Repo {
+ async fn list_runs(&self, caller: &MacroUserIdStr<'static>) -> Result<Vec<ImportRun>> {
+ assert_eq!(caller, &user());
+ Ok(self.0.lock().unwrap().runs.clone())
+ }
+ async fn start_run(
+ &self,
+ _: &MacroUserIdStr<'static>,
+ source: ImportSource,
+ from: &[RunStatus],
+ auto_import: bool,
+ ) -> Result<bool> {
+ let mut ledger = self.0.lock().unwrap();
+ if let Some(run) = ledger.runs.iter_mut().find(|run| run.source == source) {
+ if !from.contains(&run.status) {
+ return Ok(false);
+ }
+ run.status = RunStatus::Running;
+ run.error = None;
+ } else {
+ ledger.runs.push(ImportRun {
+ source,
+ status: RunStatus::Running,
+ auto_import,
+ error: None,
+ updated_at: chrono::Utc::now(),
+ });
+ }
+ Ok(true)
+ }
+ async fn finish_run(
+ &self,
+ _: &MacroUserIdStr<'static>,
+ source: ImportSource,
+ to: RunStatus,
+ error: Option<&str>,
+ ) -> Result<bool> {
+ let mut ledger = self.0.lock().unwrap();
+ let run = ledger
+ .runs
+ .iter_mut()
+ .find(|run| run.source == source)
+ .unwrap();
+ if run.status != RunStatus::Running {
+ return Ok(false);
+ }
+ run.status = to;
+ run.error = error.map(str::to_string);
+ Ok(true)
+ }
+ async fn transition_run(
+ &self,
+ _: &MacroUserIdStr<'static>,
+ source: ImportSource,
+ from: &[RunStatus],
+ to: RunStatus,
+ ) -> Result<bool> {
+ let mut ledger = self.0.lock().unwrap();
+ let run = ledger
+ .runs
+ .iter_mut()
+ .find(|run| run.source == source)
+ .unwrap();
+ if !from.contains(&run.status) {
+ return Ok(false);
+ }
+ run.status = to;
+ Ok(true)
+ }
+ async fn get(
+ &self,
+ caller: &MacroUserIdStr<'static>,
+ id: Uuid,
+ ) -> Result<Option<ImportEntity>> {
+ Ok(self
+ .0
+ .lock()
+ .unwrap()
+ .rows
+ .iter()
+ .find(|row| row.id == id && row.user_id == caller.as_ref())
+ .cloned())
+ }
+ async fn list(
+ &self,
+ _: &MacroUserIdStr<'static>,
+ _: Option<ImportSource>,
+ _: Option<ImportStatus>,
+ ) -> Result<Vec<ImportEntity>> {
+ Ok(self.0.lock().unwrap().rows.clone())
+ }
+ async fn mark_importing(
+ &self,
+ _: &MacroUserIdStr<'static>,
+ ids: &[Uuid],
+ ) -> Result<Vec<ImportEntity>> {
+ let mut ledger = self.0.lock().unwrap();
+ Ok(ledger
+ .rows
+ .iter_mut()
+ .filter(|row| ids.contains(&row.id) && row.status == ImportStatus::Staged)
+ .map(|row| {
+ row.status = ImportStatus::Importing;
+ row.clone()
+ })
+ .collect())
+ }
+ async fn mark_imported(
+ &self,
+ _: &MacroUserIdStr<'static>,
+ id: Uuid,
+ entity_id: &str,
+ entity_type: &str,
+ _: Option<Uuid>,
+ ) -> Result<Option<ImportEntity>> {
+ let mut ledger = self.0.lock().unwrap();
+ let row = ledger.rows.iter_mut().find(|row| row.id == id).unwrap();
+ if row.status != ImportStatus::Importing {
+ return Ok(None);
+ }
+ row.status = ImportStatus::Imported;
+ row.entity_id = Some(entity_id.into());
+ row.entity_type = Some(entity_type.into());
+ Ok(Some(row.clone()))
+ }
+ async fn mark_import_failed(
+ &self,
+ _: &MacroUserIdStr<'static>,
+ id: Uuid,
+ error: &str,
+ ) -> Result<bool> {
+ let mut ledger = self.0.lock().unwrap();
+ let row = ledger.rows.iter_mut().find(|row| row.id == id).unwrap();
+ if row.status != ImportStatus::Importing {
+ return Ok(false);
+ }
+ row.status = ImportStatus::Staged;
+ row.last_error = Some(error.into());
+ Ok(true)
+ }
+ async fn discard(&self, _: &MacroUserIdStr<'static>, id: Uuid) -> Result<bool> {
+ let mut ledger = self.0.lock().unwrap();
+ let row = ledger.rows.iter_mut().find(|row| row.id == id).unwrap();
+ if row.status != ImportStatus::Staged {
+ return Ok(false);
+ }
+ row.status = ImportStatus::Discarded;
+ Ok(true)
+ }
+ async fn user_team_id(&self, _: &MacroUserIdStr<'static>) -> Result<Option<Uuid>> {
+ Ok(None)
+ }
+ async fn fail_stale_importing(&self, _: &MacroUserIdStr<'static>, _: i64) -> Result<u64> {
+ Ok(0)
+ }
+ async fn reconcile_auto_import_runs(&self, _: &MacroUserIdStr<'static>) -> Result<u64> {
+ Ok(0)
+ }
+ async fn touch_importing(&self, _: &MacroUserIdStr<'static>, _: &[Uuid]) -> Result<u64> {
+ Ok(0)
+ }
+ async fn get_own_by_foreign_id(
+ &self,
+ _: &MacroUserIdStr<'static>,
+ source: ImportSource,
+ foreign_id: &str,
+ ) -> Result<Option<ImportEntity>> {
+ Ok(self
+ .0
+ .lock()
+ .unwrap()
+ .rows
+ .iter()
+ .find(|row| row.source == source && row.foreign_id == foreign_id)
+ .cloned())
+ }
+ async fn find_team_imported(
+ &self,
+ _: &MacroUserIdStr<'static>,
+ _: ImportSource,
+ _: &str,
+ ) -> Result<Option<ImportEntity>> {
+ Ok(None)
+ }
+ async fn upsert_staged(
+ &self,
+ _: &MacroUserIdStr<'static>,
+ source: ImportSource,
+ initiator: Initiator,
+ foreign_id: &str,
+ metadata: &serde_json::Value,
+ ) -> Result<Option<ImportEntity>> {
+ let mut row = self.seed(source);
+ row.foreign_id = foreign_id.into();
+ row.initiator = initiator;
+ row.metadata = metadata.clone();
+ *self.0.lock().unwrap().rows.last_mut().unwrap() = row.clone();
+ Ok(Some(row))
+ }
+ async fn upsert_imported(
+ &self,
+ _: &MacroUserIdStr<'static>,
+ _: ImportSource,
+ _: Initiator,
+ _: &str,
+ _: &serde_json::Value,
+ _: &str,
+ _: &str,
+ _: Option<Uuid>,
+ ) -> Result<ImportEntity> {
+ unreachable!()
+ }
+ async fn discard_staged_by_initiator(
+ &self,
+ _: &MacroUserIdStr<'static>,
+ _: Initiator,
+ ) -> Result<u64> {
+ unreachable!()
+ }
+ async fn delete_staged_by_initiator(
+ &self,
+ _: &MacroUserIdStr<'static>,
+ _: Initiator,
+ ) -> Result<u64> {
+ unreachable!()
+ }
+ async fn begin_auto_import(
+ &self,
+ _: &MacroUserIdStr<'static>,
+ _: ImportSource,
+ ) -> Result<Option<Vec<ImportEntity>>> {
+ unreachable!()
+ }
+ async fn finish_auto_import(
+ &self,
+ _: &MacroUserIdStr<'static>,
+ _: ImportSource,
+ _: &[Uuid],
+ ) -> Result<Option<RunStatus>> {
+ unreachable!()
+ }
+}
+
+struct NoConnector;
+impl ConnectorSelect for NoConnector {
+ async fn user_toolset(&self, _: &MacroUserIdStr<'static>) -> UserMcpTools {
+ panic!("unexpected connector call")
+ }
+ async fn connector_toolset(
+ &self,
+ _: &MacroUserIdStr<'static>,
+ _: mcp_select::ConnectorRef<'_>,
+ ) -> anyhow::Result<Option<UserMcpTools>> {
+ panic!("unexpected connector call")
+ }
+ async fn connector_connected(
+ &self,
+ _: &MacroUserIdStr<'static>,
+ _: mcp_select::ConnectorRef<'_>,
+ ) -> anyhow::Result<bool> {
+ panic!("unexpected connector call")
+ }
+}
+
+#[derive(Default)]
+struct Creator(AtomicUsize);
+impl EntityCreator for Creator {
+ async fn create_task(
+ &self,
+ _: &MacroUserIdStr<'static>,
+ _: &str,
+ _: &str,
+ _: &ImportedTaskProperties,
+ ) -> anyhow::Result<String> {
+ self.0.fetch_add(1, Ordering::SeqCst);
+ Ok(Uuid::now_v7().to_string())
+ }
+ async fn create_markdown_doc(
+ &self,
+ _: &MacroUserIdStr<'static>,
+ _: &str,
+ _: &str,
+ _: &ImportedDocumentProperties,
+ ) -> anyhow::Result<String> {
+ self.0.fetch_add(1, Ordering::SeqCst);
+ Ok(Uuid::now_v7().to_string())
+ }
+ async fn create_channel(
+ &self,
+ _: &MacroUserIdStr<'static>,
+ _: &str,
+ _: Option<Uuid>,
+ _: &[String],
+ ) -> anyhow::Result<String> {
+ self.0.fetch_add(1, Ordering::SeqCst);
+ Ok(Uuid::now_v7().to_string())
+ }
+}
+
+type Service = ImportServiceImpl<Repo, NoConnector, Creator>;
+fn service(admission: Arc<Admission>) -> Service {
+ ImportServiceImpl::new(
+ Repo::default(),
+ Arc::new(NoConnector),
+ Arc::new(Creator::default()),
+ Arc::new(ai_usage::NoOpUsageRecorder),
+ )
+ .with_admission(admission)
+}
+
+struct Tools {
+ name: &'static str,
+ result: serde_json::Value,
+ calls: AtomicUsize,
+}
+impl<Context: Send> ToolSet<Context> for Tools {
+ fn dispatch_tool_call<'a>(
+ &'a self,
+ _: Context,
+ caller: RequestContext,
+ _: &'a str,
+ _: &'a serde_json::Value,
+ ) -> Pin<
+ Box<
+ dyn Future<Output = std::result::Result<ToolResult<serde_json::Value>, ToolSetError>>
+ + Send
+ + 'a,
+ >,
+ > {
+ assert_eq!(caller.user_id, user());
+ self.calls.fetch_add(1, Ordering::SeqCst);
+ Box::pin(async { Ok(Ok(self.result.clone())) })
+ }
+ fn request_schemas(&self) -> Option<Vec<ai_toolset::RequestSchema>> {
+ Some(vec![ai_toolset::RequestSchema {
+ name: self.name.into(),
+ schema: schemars::schema_for!(serde_json::Value),
+ }])
+ }
+}
+fn notion_tools(truncated: bool) -> Arc<Tools> {
+ Arc::new(Tools {
+ name: "mcp__Notion__notion-fetch",
+ result: serde_json::json!({"title": "A page", "text": "A complete page", "truncated": truncated}),
+ calls: AtomicUsize::new(0),
+ })
+}
+
+#[tokio::test]
+async fn initial_gather_and_retry_refuse_before_running_or_connector_calls() {
+ for error in [denied(), AiAdmissionError::Unavailable] {
+ let admission = Admission::refusing(error);
+ let service = service(admission.clone());
+ for source in [ImportSource::Linear, ImportSource::Notion] {
+ assert!(
+ matches!(service.start_gather(user(), source, true).await, Err(ImportError::Admission(e)) if e == error)
+ );
+ assert!(service.repo.list_runs(&user()).await.unwrap().is_empty());
+ assert!(
+ matches!(service.retry_gather(user(), source).await, Err(ImportError::Admission(e)) if e == error)
+ );
+ }
+ service
+ .repo
+ .start_run(&user(), ImportSource::Linear, &[], true)
+ .await
+ .unwrap();
+ service
+ .repo
+ .finish_run(
+ &user(),
+ ImportSource::Linear,
+ RunStatus::Failed,
+ Some("old failure"),
+ )
+ .await
+ .unwrap();
+ assert!(
+ matches!(service.retry_gather(user(), ImportSource::Linear).await, Err(ImportError::Admission(e)) if e == error)
+ );
+ let run = service
+ .repo
+ .list_runs(&user())
+ .await
+ .unwrap()
+ .pop()
+ .unwrap();
+ assert_eq!(run.status, RunStatus::Failed);
+ assert!(run.auto_import);
+ assert_eq!(run.error.as_deref(), Some("old failure"));
+ service
+ .dismiss_run(user(), ImportSource::Linear)
+ .await
+ .unwrap();
+ let calls = admission.calls.load(Ordering::SeqCst);
+ assert!(
+ !service
+ .start_gather(user(), ImportSource::Linear, false)
+ .await
+ .unwrap()
+ );
+ assert_eq!(admission.calls.load(Ordering::SeqCst), calls);
+ assert_eq!(
+ service.state(user()).await.unwrap().runs[0].status,
+ RunStatus::Dismissed
+ );
+ }
+}
+
+#[tokio::test]
+async fn queued_gather_rechecks_and_finishes_failed_without_loading_tools() {
+ for error in [denied(), AiAdmissionError::Unavailable] {
+ let admission = Arc::new(Admission {
+ error: Mutex::new(Some(error)),
+ calls: AtomicUsize::new(0),
+ allow_first: true,
+ });
+ let service = service(admission.clone());
+ assert!(
+ service
+ .start_gather(user(), ImportSource::Notion, true)
+ .await
+ .unwrap()
+ );
+ tokio::time::timeout(Duration::from_secs(2), async {
+ loop {
+ let run = service
+ .repo
+ .list_runs(&user())
+ .await
+ .unwrap()
+ .pop()
+ .unwrap();
+ if run.status == RunStatus::Failed {
+ assert!(run.error.unwrap().starts_with(error.code()));
+ assert!(run.auto_import);
+ break;
+ }
+ tokio::task::yield_now().await;
+ }
+ })
+ .await
+ .unwrap();
+ assert_eq!(admission.calls.load(Ordering::SeqCst), 2);
+ }
+}
+
+#[tokio::test]
+async fn active_gather_retries_are_noops_and_failed_retries_preserve_configuration() {
+ let admission = Admission::refusing(AiAdmissionError::Unavailable);
+ let service = service(admission.clone());
+ service
+ .repo
+ .start_run(&user(), ImportSource::Linear, &[], true)
+ .await
+ .unwrap();
+ assert!(
+ !service
+ .retry_gather(user(), ImportSource::Linear)
+ .await
+ .unwrap()
+ );
+ assert_eq!(admission.calls.load(Ordering::SeqCst), 0);
+ service
+ .repo
+ .finish_run(
+ &user(),
+ ImportSource::Linear,
+ RunStatus::Failed,
+ Some("interrupted"),
+ )
+ .await
+ .unwrap();
+
+ // Admission recovers for the retry, then fails again when the task starts.
+ let admission = Arc::new(Admission {
+ error: Mutex::new(Some(AiAdmissionError::Unavailable)),
+ calls: AtomicUsize::new(0),
+ allow_first: true,
+ });
+ let service = service.with_admission(admission);
+ assert!(
+ service
+ .retry_gather(user(), ImportSource::Linear)
+ .await
+ .unwrap()
+ );
+ tokio::time::timeout(Duration::from_secs(2), async {
+ loop {
+ let run = service
+ .repo
+ .list_runs(&user())
+ .await
+ .unwrap()
+ .pop()
+ .unwrap();
+ if run.status == RunStatus::Failed {
+ assert!(run.auto_import);
+ assert!(run.error.unwrap().starts_with("ai_billing_unavailable"));
+ break;
+ }
+ tokio::task::yield_now().await;
+ }
+ })
+ .await
+ .unwrap();
+}
+
+#[tokio::test]
+async fn default_constructor_keeps_admission_disabled() {
+ let service = ImportServiceImpl::new(
+ Repo::default(),
+ Arc::new(NoConnector),
+ Arc::new(Creator::default()),
+ Arc::new(ai_usage::NoOpUsageRecorder),
+ );
+ service.admit_ai(&user()).await.unwrap();
+ assert!(
+ service
+ .prepare_gather(&user(), ImportSource::Notion, &[])
+ .await
+ .unwrap()
+ );
+}
+
+#[tokio::test]
+async fn slack_direct_gather_bypasses_admission_but_fallback_does_not() {
+ let admission = Admission::refusing(denied());
+ let service = service(admission.clone());
+ assert!(
+ service
+ .prepare_gather(&user(), ImportSource::Slack, &[])
+ .await
+ .unwrap()
+ );
+ let tools = Arc::new(Tools {
+ name: "mcp__Slack__search_channels",
+ result: serde_json::json!({"channels": [{"id": "C0123456789", "name": "general"}]}),
+ calls: AtomicUsize::new(0),
+ });
+ service
+ .gather_with_tools(&user(), ImportSource::Slack, tools.clone())
+ .await
+ .unwrap();
+ assert_eq!(tools.calls.load(Ordering::SeqCst), 1);
+ assert_eq!(service.repo.0.lock().unwrap().rows.len(), 1);
+ assert_eq!(admission.calls.load(Ordering::SeqCst), 0);
+ let empty = Arc::new(Tools {
+ name: "mcp__Slack__search_channels",
+ result: serde_json::json!({"channels": []}),
+ calls: AtomicUsize::new(0),
+ });
+ let error = service
+ .gather_with_tools(&user(), ImportSource::Slack, empty)
+ .await
+ .unwrap_err();
+ assert_eq!(error.downcast_ref::<AiAdmissionError>(), Some(&denied()));
+ assert_eq!(
+ admission.calls.load(Ordering::SeqCst),
+ 1,
+ "no alternate model after refusal"
+ );
+}
+
+#[tokio::test]
+async fn notion_direct_import_succeeds_and_denied_fallback_releases_claim() {
+ for error in [denied(), AiAdmissionError::Unavailable] {
+ let admission = Admission::refusing(error);
+ let service = service(admission.clone());
+ let direct = service.repo.seed(ImportSource::Notion);
+ let fallback = service.repo.seed(ImportSource::Notion);
+ let rows = service
+ .repo
+ .mark_importing(&user(), &[direct.id, fallback.id])
+ .await
+ .unwrap();
+ service
+ .process_notion_page(&user(), notion_tools(false), &rows[0])
+ .await
+ .unwrap();
+ assert_eq!(admission.calls.load(Ordering::SeqCst), 0);
+ let result = service
+ .process_notion_page(&user(), notion_tools(true), &rows[1])
+ .await
+ .unwrap_err();
+ assert_eq!(result.downcast_ref::<AiAdmissionError>(), Some(&error));
+ let failed = service
+ .repo
+ .get(&user(), fallback.id)
+ .await
+ .unwrap()
+ .unwrap();
+ assert_eq!(failed.status, ImportStatus::Staged);
+ assert!(failed.last_error.unwrap().starts_with(error.code()));
+ assert_eq!(
+ service
+ .repo
+ .get(&user(), direct.id)
+ .await
+ .unwrap()
+ .unwrap()
+ .status,
+ ImportStatus::Imported
+ );
+ assert_eq!(service.creator.0.load(Ordering::SeqCst), 1);
+ }
+}
+
+#[tokio::test]
+async fn delayed_notion_work_rechecks_current_allowance_and_mixed_work_survives() {
+ let admission = Admission::refusing(denied());
+ *admission.error.lock().unwrap() = None;
+ let service = service(admission.clone());
+ service.admit_ai(&user()).await.unwrap();
+ let notion = service.repo.seed(ImportSource::Notion);
+ let linear = service.repo.seed(ImportSource::Linear);
+ let slack = service.repo.seed(ImportSource::Slack);
+ let discard = service.repo.seed(ImportSource::Notion);
+ // Claim before the quota changes, as when waiting behind a concurrency cap.
+ let rows = service
+ .repo
+ .mark_importing(&user(), &[notion.id])
+ .await
+ .unwrap();
+ *admission.error.lock().unwrap() = Some(denied());
+ let outcome = service
+ .run_import(user(), vec![linear.id, slack.id], vec![discard.id])
+ .await
+ .unwrap();
+ assert_eq!(outcome.importing, 2);
+ assert_eq!(outcome.discarded, 1);
+ let error = service
+ .process_notion_page(&user(), notion_tools(true), &rows[0])
+ .await
+ .unwrap_err();
+ assert_eq!(error.downcast_ref::<AiAdmissionError>(), Some(&denied()));
+ tokio::time::timeout(Duration::from_secs(2), async {
+ while service.creator.0.load(Ordering::SeqCst) < 2 {
+ tokio::task::yield_now().await;
+ }
+ })
+ .await
+ .unwrap();
+ assert_eq!(
+ service
+ .repo
+ .get(&user(), notion.id)
+ .await
+ .unwrap()
+ .unwrap()
+ .status,
+ ImportStatus::Staged
+ );
+ assert_eq!(admission.calls.load(Ordering::SeqCst), 2);
+}
diff --git a/crates/import/src/inbound/axum_router.rs b/crates/import/src/inbound/axum_router.rs
index 658b529c5d..2e8e7f8873 100644
--- a/crates/import/src/inbound/axum_router.rs
+++ b/crates/import/src/inbound/axum_router.rs
@@ -19,6 +19,9 @@ use std::sync::Arc;
use utoipa::ToSchema;
use uuid::Uuid;
+#[cfg(test)]
+mod test;
+
/// Body for accepting/declining staged imports.
#[derive(Debug, Deserialize, ToSchema)]
pub struct RunImportRequest {
@@ -84,6 +87,9 @@ where
}
fn error_response(e: ImportError) -> Response {
+ if let ImportError::Admission(error) = e {
+ return error.into_response();
+ }
tracing::error!(error = ?e, "import request failed");
StatusCode::INTERNAL_SERVER_ERROR.into_response()
}
@@ -156,6 +162,8 @@ pub async fn run_import_handler<T: ImportService, Auth: MacroAuthorizationServic
responses(
(status = 204, description = "Retry accepted (idempotent)"),
(status = 400, description = "Unknown import source"),
+ (status = 402, description = "AI allowance exhausted", body = ai_billing::inbound::admission::AiAdmissionErrorBody),
+ (status = 503, description = "AI usage validation unavailable; retry later", body = ai_billing::inbound::admission::AiAdmissionErrorBody),
(status = 500, description = "Internal server error"),
),
tag = "import"
diff --git a/crates/import/src/inbound/axum_router/test.rs b/crates/import/src/inbound/axum_router/test.rs
new file mode 100644
index 0000000000..d106c68c1c
--- /dev/null
+++ b/crates/import/src/inbound/axum_router/test.rs
@@ -0,0 +1,31 @@
+use super::*;
+use ai_billing::{AiAdmissionError, DenyReason};
+
+#[tokio::test]
+async fn admission_failures_use_shared_http_contract() {
+ for (error, status) in [
+ (
+ AiAdmissionError::Denied(DenyReason::AllowanceExhausted),
+ StatusCode::PAYMENT_REQUIRED,
+ ),
+ (
+ AiAdmissionError::Unavailable,
+ StatusCode::SERVICE_UNAVAILABLE,
+ ),
+ ] {
+ let response = error_response(ImportError::Admission(error));
+ assert_eq!(response.status(), status);
+ let body = axum::body::to_bytes(response.into_body(), 4096)
+ .await
+ .unwrap();
+ let body: serde_json::Value = serde_json::from_slice(&body).unwrap();
+ assert_eq!(body["code"], error.code());
+ assert_eq!(body["error"], error.to_string());
+ }
+}
+
+#[test]
+fn other_errors_remain_internal() {
+ let response = error_response(ImportError::Other(anyhow::anyhow!("private diagnostic")));
+ assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
+}
diff --git a/crates/macro_db_client/migrations/20260930145625_add_ai_usage_count_usage.sql b/crates/macro_db_client/migrations/20260930145625_add_ai_usage_count_usage.sql
new file mode 100644
index 0000000000..b465c181eb
--- /dev/null
+++ b/crates/macro_db_client/migrations/20260930145625_add_ai_usage_count_usage.sql
@@ -0,0 +1,5 @@
+ALTER TABLE ai_usage
+ ADD COLUMN count_usage BOOLEAN NOT NULL DEFAULT FALSE;
+
+COMMENT ON COLUMN ai_usage.count_usage IS
+ 'Prospective quota eligibility: true only for billable, user-owned usage recorded while AI usage enforcement is enabled. Historical rows and writers omitting this column remain false; never backfill them to true.';
diff --git a/crates/macro_db_client/migrations/20260930145626_ai_usage_counted_user_created_at_idx.sql b/crates/macro_db_client/migrations/20260930145626_ai_usage_counted_user_created_at_idx.sql
new file mode 100644
index 0000000000..37e709601c
--- /dev/null
+++ b/crates/macro_db_client/migrations/20260930145626_ai_usage_counted_user_created_at_idx.sql
@@ -0,0 +1,14 @@
+-- no-transaction
+-- Billing sums only counted usage. Keep the full ai_usage_user_id_created_at_idx
+-- for admin analytics and older deployed services that also read uncounted rows.
+-- Before retrying an interrupted build, check validity and definition:
+-- SELECT indisvalid, pg_get_indexdef(indexrelid)
+-- FROM pg_index
+-- WHERE indexrelid = to_regclass('ai_usage_counted_user_created_at_idx');
+-- IF NOT EXISTS does not repair an INVALID index. If present but invalid, run
+-- DROP INDEX CONCURRENTLY ai_usage_counted_user_created_at_idx;
+-- outside a transaction before retrying this migration. If valid, verify that
+-- its definition matches the index below before allowing the retry to skip it.
+CREATE INDEX CONCURRENTLY IF NOT EXISTS ai_usage_counted_user_created_at_idx
+ ON ai_usage (user_id, created_at DESC)
+ WHERE count_usage = TRUE;
diff --git a/crates/memory/src/config.rs b/crates/memory/src/config.rs
index 5a2ffed352..d5e8621230 100644
--- a/crates/memory/src/config.rs
+++ b/crates/memory/src/config.rs
@@ -2,6 +2,7 @@ pub use macro_env::Environment;
use macro_env_var::env_var;
pub struct Config {
+ pub enable_ai_usage_enforcement: ai_usage::AiUsageEnforcement,
pub environment: Environment,
pub database_url: String,
pub user_id: String,
@@ -16,6 +17,8 @@ env_var!(
impl Config {
pub fn from_env() -> anyhow::Result<Self> {
+ let enable_ai_usage_enforcement = ai_usage::config::load_ai_usage_enforcement()
+ .map_err(|error| anyhow::anyhow!("{error}"))?;
let environment = Environment::new_or_prod();
let env_vars = EnvVars::new()?;
@@ -25,6 +28,7 @@ impl Config {
} = env_vars;
Ok(Self {
+ enable_ai_usage_enforcement,
environment,
database_url: database_url.to_string(),
user_id: user_id.to_string(),
diff --git a/crates/memory/src/context.rs b/crates/memory/src/context.rs
index fd78b78900..d1466e70a1 100644
--- a/crates/memory/src/context.rs
+++ b/crates/memory/src/context.rs
@@ -1,280 +1,23 @@
-use ai_tools::{
- NoOpConnectionService, NoOpSnsEndpointManager, ToolImportToolContext, ToolNotificationQueue,
- ToolServiceContext,
-};
-use bots::outbound::pg_bots_repo::PgBotsRepo;
-use channels::{
- domain::list_service::ChannelListServiceImpl, outbound::pg_channels_repo::PgChannelsRepo,
-};
-use documents::domain::models::CloudFrontConfig;
-use documents::inbound::toolset::DocumentToolContext;
-use documents::outbound::pg_document_repo::PgDocumentRepo;
-use documents::outbound::s3_upload_url::S3UploadUrlAdapter;
-use email::domain::ports::ReadonlyEmailPreviewAdapter;
-use email::domain::service::EmailServiceImpl;
-use email::outbound::EmailPgRepo;
-use email_service_client::EmailServiceClientExternal;
-use entity_access::domain::service::EntityAccessServiceImpl;
-use entity_access::outbound::PgAccessRepository;
-use entity_registry::OwnerGrantPolicy;
-use entity_registry_db_utils::OwnedEntityRegistrar;
-use foreign_entity::{
- domain::service::ForeignEntityServiceImpl,
- outbound::pg_foreign_entity_repo::PgForeignEntityRepo,
-};
-use frecency::domain::services::FrecencyQueryServiceImpl;
-use frecency::outbound::postgres::FrecencyPgStorage;
-use lexical_client::LexicalClient;
-use notification::domain::service::{NotificationReaderService, PlatformArnConfig};
-use notification::outbound::repository::DbNotificationRepository;
-use search_service_client::SearchServiceClient;
-use soup::domain::service::SoupImpl;
-use soup::outbound::pg_soup_repo::PgSoupRepo;
-use std::sync::Arc;
-use sync_service_client::SyncServiceClient;
+//! Memory host composition using the shared, configured tool services.
+
+use ai_tools::{ToolServiceContext, build_tool_service_context_from_env};
+use tokio_util::task::TaskTracker;
use crate::config::Config;
-/// Builds a [`ToolServiceContext`] from a database pool and caller-provided config.
-///
-/// This function does not resolve service URLs. The caller must provide a [`Config`]
-/// whose service URL fields have already been resolved, for example with
-/// `macro_service_urls`: `document_storage_service_url`, `sync_service_url`,
-/// `email_service_url`, and `lexical_service_url`.
-///
-/// The provided [`Config`] must also contain values sourced from the required
-/// environment variables: `INTERNAL_API_SECRET_KEY`, `DOCUMENT_STORAGE_BUCKET`,
-/// `DOCX_DOCUMENT_UPLOAD_BUCKET`, `EMAIL_SCHEDULED_QUEUE`,
-/// `DOCUMENT_STORAGE_SERVICE_CLOUDFRONT_DISTRIBUTION_URL`,
-/// `DOCUMENT_STORAGE_SERVICE_CLOUDFRONT_SIGNER_PUBLIC_KEY_ID`, and
-/// `DOCUMENT_STORAGE_SERVICE_CLOUDFRONT_SIGNER_PRIVATE_KEY_SECRET_NAME`.
-///
-/// This function reads the provided [`Config`] and initializes the clients needed to
-/// build the [`ToolServiceContext`].
-#[tracing::instrument(skip(pool, config), err)]
+/// Build memory's tools at startup with the same quota policy as other hosts.
+/// The memory domain binds its exempt `Memory` feature when it starts an operation;
+/// the shared context must not globally exempt independently initiated AI tools.
+#[tracing::instrument(skip_all, err)]
pub async fn build_tool_service_context(
pool: sqlx::PgPool,
config: &Config,
+ event_task_tracker: TaskTracker,
) -> anyhow::Result<ToolServiceContext> {
- let aws_config = macro_aws_config::get_macro_aws_config().await;
- let sqs_client = sqs_client::SQS::new(aws_sdk_sqs::Client::new(&aws_config))
- .email_scheduled_queue(&config.email_scheduled_queue);
-
- // Service clients
- let search_client = Arc::new(SearchServiceClient::new(
- config.internal_api_secret_key.clone(),
- config.document_storage_service_url.clone(),
- ));
- let sync_client = Arc::new(SyncServiceClient::new(
- config.internal_api_secret_key.clone(),
- config.sync_service_url.clone(),
- ));
- let email_ext_client = Arc::new(EmailServiceClientExternal::new(
- config.email_service_url.clone(),
- ));
- let lexical_client = LexicalClient::new(
- config.internal_api_secret_key.clone(),
- config.lexical_service_url.clone(),
- );
-
- // Soup service
- let frecency_storage = FrecencyPgStorage::new(pool.clone());
- let frecency_service = FrecencyQueryServiceImpl::new(frecency_storage.clone());
- let crm_service = crm::domain::service::CrmServiceImpl::new(
- crm::outbound::companies_repo::CompaniesRepositoryImpl::new(pool.clone()),
- crm::outbound::no_op_resolver::NoOpCompanyMetadataResolver,
- );
- let email_service = EmailServiceImpl::new(
- EmailPgRepo::new(pool.clone()),
- frecency_service.clone(),
- email::domain::ports::NoOpEnqueuer,
- crm_service.clone(),
- entity_access_management::domain::service::EntityAccessManagementServiceImpl::new(
- entity_access_management::outbound::PgRepository::new(pool.clone()),
- ),
- 0,
- );
- let channels_service = ChannelListServiceImpl::new(
- PgChannelsRepo::new(pool.clone()),
- PgChannelsRepo::new(pool.clone()),
- frecency_storage,
- );
- let email_service_for_tools: Arc<ai_tools::ToolEmailService> = Arc::new(email_service.clone());
- let foreign_entity_service =
- ForeignEntityServiceImpl::new(PgForeignEntityRepo::new(pool.clone()));
- let soup_service = Arc::new(SoupImpl::new(
- PgSoupRepo::new(readonly_pool::ReadOnlyPool(pool.clone())),
- frecency_service,
- ReadonlyEmailPreviewAdapter(email_service),
- channels_service,
- call::domain::service::CallRecordQueryServiceImpl::new(
- call::outbound::pg_call_repo::PgCallRepo::new(pool.clone()),
- ),
- crm::domain::service::NoOpCrmService,
- foreign_entity_service,
- reminders::domain::service::NoOpRemindersService,
- ));
-
- // Document tool context
- let s3_client = macro_aws_config::s3_client().await;
- let s3_upload_adapter = S3UploadUrlAdapter::new(
- s3_client,
- &config.document_storage_bucket,
- &config.docx_document_upload_bucket,
- );
- let owned_entity_registrar =
- OwnedEntityRegistrar::new(OwnerGrantPolicy::new(PgBotsRepo::new(pool.clone())));
- let document_repo = PgDocumentRepo::new(pool.clone(), owned_entity_registrar.clone());
- let cloudfront_config = CloudFrontConfig {
- distribution_url: config
- .document_storage_service_cloudfront_distribution_url
- .clone(),
- signer_public_key_id: config
- .document_storage_service_cloudfront_signer_public_key_id
- .clone(),
- signer_private_key: config
- .document_storage_service_cloudfront_signer_private_key_secret_name
- .clone(),
- presigned_url_expiry_seconds: 3600,
- browser_cache_expiry_seconds: 86400,
- };
- let entity_access_service = Arc::new(EntityAccessServiceImpl::new(PgAccessRepository::new(
- pool.clone(),
- )));
- let properties_service =
- ai_tools::build_properties_service(pool.clone(), entity_access_service.clone());
- let task_properties_service = ai_tools::build_task_properties_adapter(
- pool.clone(),
- properties_service.clone(),
- entity_access_service.clone(),
- );
- let document_service = documents::domain::service::DocumentServiceImpl::new(
- document_repo,
- cloudfront_config,
- sync_client.as_ref().clone(),
- s3_upload_adapter,
- task_properties_service,
- NoOpConnectionService,
- entity_access_management::domain::service::EntityAccessManagementServiceImpl::new(
- entity_access_management::outbound::PgRepository::new(pool.clone()),
- ),
- ForeignEntityServiceImpl::new(PgForeignEntityRepo::new(pool.clone())),
- );
- let document_tool_context = DocumentToolContext::new(
- document_service,
- (*entity_access_service).clone(),
- lexical_client.clone(),
- sync_client.as_ref().clone(),
- );
-
- // Properties tool context
- let properties_tool_context = ai_tools::build_properties_tool_context(
- properties_service.clone(),
- entity_access_service.clone(),
- );
-
- // Email tool context
- let email_tool_context = email::inbound::toolset::EmailToolContext::new(
- Arc::new(EmailServiceImpl::new(
- EmailPgRepo::new(pool.clone()),
- FrecencyQueryServiceImpl::new(FrecencyPgStorage::new(pool.clone())),
- sqs_client,
- crm_service.clone(),
- entity_access_management::domain::service::EntityAccessManagementServiceImpl::new(
- entity_access_management::outbound::PgRepository::new(pool.clone()),
- ),
- 0,
- )),
- Arc::new(email::domain::ports::NoOpGmailTokenProvider),
- Arc::new(EntityAccessServiceImpl::new(PgAccessRepository::new(
- pool.clone(),
- ))),
- Arc::new(lexical_client.clone()),
- );
-
- let call_service = call::domain::service::CallServiceImpl::new(
- call::outbound::pg_call_repo::PgCallRepo::new(pool.clone()),
- ai_tools::NoOpCallRtcClient,
- ai_tools::NoOpConnectionService,
- (*entity_access_service).clone(),
- ai_tools::NoOpNotificationIngress,
- None::<call::outbound::s3_recording_storage::S3RecordingStorage>,
- String::new(),
- );
- let call_tool_context = call::inbound::toolset::CallToolContext::new(
- call_service,
- (*entity_access_service).clone(),
- );
-
- let notification_reader_service = NotificationReaderService {
- repository: DbNotificationRepository::new(pool.clone()),
- queue: ToolNotificationQueue::NoOp,
- sns_endpoint: NoOpSnsEndpointManager,
- platform_config: PlatformArnConfig {
- apns_platform_arn: String::new(),
- fcm_platform_arn: String::new(),
- apns_voip_platform_arn: String::new(),
- },
- realtime: notification::domain::ports::NoopNotificationRealtimePublisher,
- };
- let notification_tool_context =
- notification::inbound::ai_tool::NotificationToolContext::new(notification_reader_service);
-
- let chat_tool_context = chat::inbound::toolset::ChatToolContext::new(
- chat::domain::service::ChatServiceImpl::new(
- chat::outbound::postgres::PgChatRepo::new(pool.clone(), owned_entity_registrar),
- Arc::new(ai_toolset::AsyncToolCollection::new()),
- (),
- entity_access_management::domain::service::EntityAccessManagementServiceImpl::new(
- entity_access_management::outbound::PgRepository::new(pool.clone()),
- ),
- ),
- (*entity_access_service).clone(),
- );
-
- let skill_tool_context = ai_tools::build_skill_tool_context(
- search_client.clone(),
- soup_service.clone(),
- &document_tool_context,
- );
-
- Ok(ToolServiceContext {
- search_service_client: search_client.clone(),
- email_service_client: email_ext_client,
- soup_service,
- email_service: email_service_for_tools,
- activity_tool_context: ai_tools::build_activity_tool_context(
- pool.clone(),
- properties_service,
- entity_access_service.clone(),
- ),
- document_tool_context,
- properties_tool_context,
- email_tool_context,
- call_tool_context,
- notification_tool_context,
- reminders_tool_context: ai_tools::build_reminders_tool_context(
- pool.clone(),
- entity_access_service.clone(),
- ),
- import_tool_context: ToolImportToolContext::unwired(),
- chat_tool_context,
- channel_tool_context: ai_tools::build_channel_tool_context(
- pool.clone(),
- Arc::new(lexical_client),
- ),
- bot_tool_context: ai_tools::build_bot_tool_context(
- pool.clone(),
- ai_tools::ToolBotEventBroker::NoOp(Default::default()),
- entity_access_service.clone(),
- config.document_storage_service_url.clone(),
- ),
- team_tool_context: ai_tools::build_team_tool_context(pool.clone()),
- crm_tool_context: ai_tools::build_crm_tool_context(pool.clone()),
- skill_tool_context,
- schedule_tool_context: ai_tools::NoOpScheduleContext,
- anthropic_tool_context: ai_tools::build_anthropic_tool_context(),
- recorder: ai_usage::pg_recorder(pool.clone()),
- usage_context: ai_usage::UsageContext::system(ai_usage::AiFeature::Chat),
- })
+ build_tool_service_context_from_env(
+ pool,
+ event_task_tracker,
+ config.enable_ai_usage_enforcement,
+ )
+ .await
}
diff --git a/crates/memory/src/lib.rs b/crates/memory/src/lib.rs
index 3baa171ed8..c2392f0f60 100644
--- a/crates/memory/src/lib.rs
+++ b/crates/memory/src/lib.rs
@@ -1,6 +1,7 @@
#![recursion_limit = "256"]
pub mod config;
+pub mod context;
pub mod domain;
pub mod inbound;
pub mod outbound;
diff --git a/crates/memory/src/main.rs b/crates/memory/src/main.rs
index 60ddff1896..405f2ae476 100644
--- a/crates/memory/src/main.rs
+++ b/crates/memory/src/main.rs
@@ -1,9 +1,10 @@
#![recursion_limit = "256"]
-use ai_tools::{AiHost, build_tool_service_context_from_env, tools_for};
+use ai_tools::{AiHost, tools_for};
use anyhow::Context;
use macro_user_id::user_id::MacroUserIdStr;
use memory::config::Config;
+use memory::context::build_tool_service_context;
use memory::domain::{MemoryService, service::MemoryServiceImpl};
use memory::outbound::pg_memory_repo::PgMemoryRepo;
use sqlx::postgres::PgPoolOptions;
@@ -28,7 +29,7 @@ async fn main() -> anyhow::Result<()> {
let event_broker_tracker = TaskTracker::new();
let tool_context =
- build_tool_service_context_from_env(pool.clone(), event_broker_tracker.clone()).await?;
+ build_tool_service_context(pool.clone(), &config, event_broker_tracker.clone()).await?;
let tools = tools_for(AiHost::Chat);
let memory_repo = PgMemoryRepo::new(pool);
let memory_service = MemoryServiceImpl::new(memory_repo, tool_context, tools);
diff --git a/crates/webhook/src/domain/ingestion.rs b/crates/webhook/src/domain/ingestion.rs
index ab08594fe7..87ff149d80 100644
--- a/crates/webhook/src/domain/ingestion.rs
+++ b/crates/webhook/src/domain/ingestion.rs
@@ -534,6 +534,7 @@ pub(crate) fn lifecycle_audience(event: &AgentSessionLifecycleEvent) -> Lifecycl
AgentSessionLifecycleEvent::Opened(_)
| AgentSessionLifecycleEvent::TurnStarted(_)
| AgentSessionLifecycleEvent::TurnEnded(_)
+ | AgentSessionLifecycleEvent::CommandRejected(_)
| AgentSessionLifecycleEvent::Settled(_)
| AgentSessionLifecycleEvent::WaitingForInput(_)
| AgentSessionLifecycleEvent::InputReceived(_)
diff --git a/docs/AGENT_GUIDE/ai-chat.md b/docs/AGENT_GUIDE/ai-chat.md
index 5eca98cc40..57ed964927 100644
--- a/docs/AGENT_GUIDE/ai-chat.md
+++ b/docs/AGENT_GUIDE/ai-chat.md
@@ -373,14 +373,40 @@ documents:
## AI usage limits
-AI usage billing is enabled only in the dev environment (`dev.macro.com/app`,
-including a local frontend pointed at the dev backend). The backend enforces
-allowances and settles usage only in `Environment::Develop`. In production and
-local-backend environments, requests are not blocked by credits, spending caps,
-or failed-overage-payment state, and usage is recorded without settlement.
+Quota admission uses the backend's default-off `ENABLE_AI_USAGE_ENFORCEMENT`
+policy once configured by the host; it is independent of environment. Settlement
+still runs only in `Environment::Develop`. With admission enabled, cognition chat
+and structured completion return 402 for exhausted allowance or 503 with
+`ai_billing_unavailable` when validation is unavailable. Neither starts AI work;
+chat admission also precedes chat/message creation. Existing model and chat
+permission failures take precedence over quota errors. Retry 503 later rather
+than treating it as approval or repeatedly sending the prompt.
+
+Automatic chat naming is admitted independently. If naming is denied or validation
+is unavailable, the successful chat continues with its existing/default title.
Usage meters, credit controls, out-of-credit dialogs, and model usage multipliers
are hidden outside frontend development mode. Normal paid-model access rules
-still apply everywhere.
+still apply everywhere. Backend enforcement does not depend on those frontend
+controls, and enabling it does not enable production credit collection. There is
+no new upgrade prompt in this rollout.
+
+Session creation and spending controls also return 402/503 for admission failures.
+Waiting prompts are checked again before execution: exhaustion removes rejected
+work from the queue and resolves its announced reply as failed, publishing
+`agent_session.command_rejected` with the action ID and safe failure details.
+Billing unavailability retains waiting work for a later queue-driving event rather
+than retrying continuously. Already-running turns are not retroactively cancelled;
+Stop/cancel and non-spending controls remain usable. Direct ACP requests receive a
+protocol error with a stable `code` and `retryable` flag, not an HTTP status.
+
+A direct AI tool/MCP or AI-edit refusal is a failed tool result even if the outer
+transport succeeds. No worker/provider edit should happen after refusal. Ordinary
+manual editing, deterministic tools/imports, and the exempt Memory, AiProjection,
+CallSummary, and Dictation features are not blocked by quota. Optional naming or
+trigger inference may be skipped without blocking successful primary work; it
+must not make a fallback model call. Managed sessions use their persisted owner
+for quota, not a collaborating sender. Externally funded runtimes skip session
+quota, but Macro-funded tools and helpers still check independently.
In dev, paid plans include a monthly AI allowance (Premium $40, Max $200, at Macro's
usage rates). When it is used up and no credits or usage billing cover the
@@ -394,6 +420,35 @@ or turn on usage billing.
Each team seat has its own allowance; unused allowance never moves between
members. The team owner's prepaid credits and usage-billing cap are shared.
+### Quota manual checks
+
+Use an isolated local backend with local billing fixtures, not real hosted
+accounts. See [quota rollout and coverage](../AI_QUOTA_ENFORCEMENT.md) for setup
+and the full matrix. Record both browser behavior and the Network/protocol result;
+existing UI does not promise a dedicated quota dialog outside development mode.
+
+1. With the flag absent/false across all hosts, send a legacy chat and a managed
+ session prompt. Confirm ordinary behavior and new uncounted usage rows.
+2. With enforcement true and an exhausted paid fixture, select a Macro-funded
+ model and send from Home, a legacy chat, and a doc-scoped chat. Confirm 402 with
+ a stable denial code, no new orphaned session/chat/message/stream, no provider
+ work, and usable retry/cancel controls.
+ Repeat with unavailable billing: expect 503 `ai_billing_unavailable`, not success
+ or repeated automatic sends. Existing permission/model-access errors still win.
+3. Start a managed turn while allowed, queue a follow-up, then exhaust the owner
+ before dispatch. Check queue removal, the failed announced reply (when present),
+ and the matching `agent_session.command_rejected` action ID. Do not expect a
+ completed runtime turn for rejected work. During an outage, check that waiting
+ work remains without a retry loop and that Stop still works.
+4. Invoke AI editing on an editable document and an independent AI tool with the
+ exhausted fixture. Confirm failed results and unchanged document content. Check
+ manual editing and dictation still work. A successful chat whose optional rename
+ is refused keeps its existing/default title rather than failing the chat.
+5. Set false consistently and restart/redeploy all local processes. Retry refused
+ work explicitly and confirm recovery, new uncounted rows, and unchanged counted
+ history. Do not erase history to simulate rollback or claim that rollback is a
+ quota reset. Check cancellation in both flag states.
+
## Start a doc-scoped chat
Open a doc → side panel `Actions` → `Ask Macro`. Opens a chat pane with the document already
diff --git a/docs/AGENT_GUIDE/channels.md b/docs/AGENT_GUIDE/channels.md
index befdb4e00b..7eb84992e6 100644
--- a/docs/AGENT_GUIDE/channels.md
+++ b/docs/AGENT_GUIDE/channels.md
@@ -156,6 +156,18 @@ bot asks before scheduling a specific clock time. Within the rollout, `@Macro`
`@coder` / `@cursor` / `@codex` / `@claude` for everyone — opens
an agent session; follow-up
`@` mentions of that bot in the same thread route to it.
+When the backend is configured with AI usage enforcement, a rejected classic
+`@Macro` request gets a thread reply explaining the allowance failure (for example,
+`ai_allowance_exhausted`) or temporary validation failure (`ai_billing_unavailable`),
+without a lingering thinking placeholder. This also applies in document discussions.
+Optional unmentioned follow-up inference, including attached-image descriptions,
+is skipped when admission fails; silence does not mean the request was approved.
+Explicit mentions and reply-target routing still reach downstream execution checks.
+To verify after backend wiring, test an exhausted account and unavailable billing:
+explicit classic mentions should show the failure, while unmentioned follow-ups
+should not generate responses. Repeat with an attached image. Enforcement is off
+by default; browser verification requires a configured backend.
+
A follow-up sent while that session is still working stops the current turn,
posts a new Magic Chip on the follow-up message, and steers the agent with
that text — the chip appears at the follow-up, not after the cancelled turn
diff --git a/docs/AI_BILLING_ROLLOUT.md b/docs/AI_BILLING_ROLLOUT.md
index 321f1241b0..c6518323e2 100644
--- a/docs/AI_BILLING_ROLLOUT.md
+++ b/docs/AI_BILLING_ROLLOUT.md
@@ -2,12 +2,21 @@
## Current scope: observation, not billing activation
-T07 installs **observational per-provider-attempt tracking** for the Rust paths
-below. It does not activate the new allowance policy, authorization, credit holds,
-credit debits, postpaid liability, or collection. The existing $40 subscription,
-legacy analytics/settlement behavior, feature exclusions, and existing enforcement
-remain unchanged. Observations must never be replayed as financial authorizations
-or converted into historical customer debt.
+The observation rollout installs **observational per-provider-attempt tracking**
+for the Rust paths below. It does not activate financial admission, credit holds,
+credit debits, postpaid liability, or collection. Observations must never be
+replayed as financial authorizations or converted into historical customer debt.
+
+The separate [legacy quota rollout](AI_QUOTA_ENFORCEMENT.md) adds default-off
+`ENABLE_AI_USAGE_ENFORCEMENT`: snapshot-based allowance admission and prospective
+`ai_usage.count_usage` writes by existing aggregate producers. Billing reads only
+persisted counted rows; historical/default-false rows remain uncounted. This is
+not the financial journal's reservation/admission system. Free/unlimited policy,
+feature exclusions, and the existing $40 subscription remain unchanged. Production
+usage-driven credit consumption and Stripe settlement remain dev-gated even when
+legacy quota enforcement is enabled. Follow that document for coordinated Doppler
+registration, rollout, rollback, coverage, and limitations; this observation
+matrix alone is not an enforcement or collection activation checklist.
`UsageRecorder::tracking()` explicitly bridges the existing analytics injection to
an object-safe `UsageTracking` capability. `agent::complete`, history/image and
@@ -17,11 +26,13 @@ Injection alone is **not** coverage: code bypassing those boundaries remains out
this accounting view. `rig_engine` explicitly carries task-local context into its
spawned turn; each session still binds its trusted owner/feature independently.
-Composition roots use `ai_usage::pg_recorder`, which constructs the owning-domain
-observation service and adapter alongside the existing analytics service. DCS wraps
-its existing settling recorder with `with_tracking(..., pg_tracking(...))` instead
-of replacing its legacy behavior. The observation service accepts **no funding or
-rate-authorization capability**. No host selects `FinancialMode::Activated` here;
+Production composition roots use `ai_usage::pg_recorder_with_enforcement`, which
+constructs configured prospective analytics counting alongside the owning-domain
+observation service and adapter. The default-disabled `pg_recorder` remains for
+internal/evaluation callers. DCS wraps its configured settling recorder with
+`with_tracking(..., pg_tracking(...))`; only enabled, counted usage can request
+legacy settlement, and that path remains dev-only. The observation service accepts
+**no funding or rate-authorization capability**. No host selects `FinancialMode::Activated` here;
its strict admission, budget validation, and error propagation remain intact.
### Persistence and failure semantics
@@ -35,7 +46,8 @@ analytics `ai_usage` table, and funding/collection work queues:
identical invocation IDs, timestamps and evidence; new provider executions get
new IDs. Conflicting deliveries fail visibly rather than overwrite facts.
- Request budgets, bodies and headers are unchanged in tracking-only mode. Missing
- provider billing profiles, rates, balances and opt-in do not deny execution.
+ provider billing profiles, rates, balances and opt-in do not deny execution through
+ observations. Enabled legacy quota admission can independently refuse the operation.
- Reported disjoint token dimensions are **unpriced (`MissingRate`)**, not free or
exempt. This path intentionally does not consult mutable analytics rates or claim
that existing financial rate publications qualify all observed request regimes.
@@ -64,8 +76,8 @@ analytics `ai_usage` table, and funding/collection work queues:
Analytics aggregates and per-attempt observations are **different accounting
views**. Do not sum them together. Existing final-success aggregates still feed
-legacy analytics exactly as before; the observational journal never calls analytics
-`record` or the settlement trigger. Independent Anthropic tools add observations,
+legacy analytics, with quota eligibility now stored separately in `count_usage`;
+the observational journal never calls analytics `record` or the settlement trigger. Independent Anthropic tools add observations,
not new legacy aggregate rows or separate tool fees.
## Producer / host matrix
@@ -76,22 +88,22 @@ regressions, not live-provider or deployment verification.
| Producer / host | Trusted attribution and injection site | Attempt vs aggregate coverage / evidence | Tests and remaining gaps |
| --- | --- | --- | --- |
-| DCS chat, dynamic/structured completion, rename | Per-operation `UsageContext` from existing authenticated handlers; `services/document_cognition_service/src/main.rs` wraps its settling recorder | Rig HTTP attempts → journal, including failed parsing/retries; legacy final aggregates unchanged | `agent` metering/structured tests, DCS package tests; billing activation off |
+| DCS chat, dynamic/structured completion, rename | Per-operation `UsageContext` from existing authenticated handlers; `services/document_cognition_service/src/main.rs` wraps its settling recorder | Rig HTTP attempts → journal, including failed parsing/retries; legacy final aggregates unchanged | `agent` metering/structured tests, DCS package tests; financial activation off |
| Subagent in any common-context host | `crates/ai_tools/src/subagent.rs` replaces shared-context user with `RequestContext.user_id`, retains parent feature/entity | `agent::complete` binds a fresh or matching inherited scope → journal; no shared mutable user | `ai_tools` subagent isolation; `agent` scope/independent recorder tests. Shared system identity is not an authenticated payer |
-| MCP native Anthropic tools and subagent | `AuthenticatedToolService` builds `RequestContext` from authenticated HTTP extensions; `services/mcp_service/src/context.rs` injects `pg_recorder`; `ToolServiceContext::FromRef` supplies inherited feature/entity and recorder | Independent Anthropic HTTP attempts and subagent attempts → journal, not merely successful tool aggregates; default feature remains Chat | Anthropic authenticated attribution/malformed-result/failure tests; MCP auth tests. MCP client's own model and remote MCP servers are not covered |
+| MCP native Anthropic tools and subagent | `AuthenticatedToolService` builds `RequestContext` from authenticated HTTP extensions; `services/mcp_service/src/context.rs` injects the configured recorder; `ToolServiceContext::FromRef` supplies inherited feature/entity and recorder | Independent Anthropic HTTP attempts and subagent attempts → journal, not merely successful tool aggregates; default feature remains Chat | Anthropic authenticated attribution/malformed-result/failure tests; MCP auth tests. MCP client's own model and remote MCP servers are not covered |
| Anthropic WebSearch, WebFetch, BashCodeExecution, TextEditorCodeExecution in all common hosts | Manual per-operation `FromRef<ToolServiceContext>` copies recorder + feature/entity; tool call always uses authenticated `RequestContext.user_id` | One journal attempt per independent native Messages HTTP execution. Counters recorded before SDK/result parsing, including non-2xx evidence; cancellation retains execution/evidence task. No separate tool fees | `anthropic --features toolset` tests. Native client has no application retry loop; any future retries must create fresh attempt IDs. Server-tool-specific non-token fees are intentionally not priced |
| In-memory harness sessions | `services/agent_harness_service/src/main.rs` common context → `RigTurnEngine`; trusted `TurnRequest.owner`, AgentSession feature | Captured scope carried into spawned turn; AgentLoop binds immutable owner scope; Rig attempts → journal, final analytics retained | `agent` spawned scope/cancellation tests; `agent_inmem` package tests. Non-user owners remain rejected by existing behavior |
-| Harness session naming | Independent `pg_recorder` supplied to `HaikuAgentSessionNameGenerator` in harness `main.rs`; session owner, ChatRename feature/entity | One-shot model attempts → journal (feature classification unchanged) | Existing name-generator/host tests plus shared completion tests; not covered merely by common-context injection |
-| Harness repository selection | Independent `pg_recorder` passed to `CursorContainerManager` in harness `main.rs`; repository chooser's trusted owner, AgentRepositoryChoice feature | Rust selection completion attempts → journal | Shared completion tests and host tests. Does not cover Cursor's external agent runtime |
-| Harness trigger classifier + image captions | Independent recorder in `services/agent_harness_service/src/trigger.rs` passed to `FastModelTriggerJudge` and `VisionImageCaptioner`; authenticated message sender, Automation feature | Structured/image HTTP attempts → journal before existing errors are handled | `agent_trigger` caption tests + `agent` image-budget/cancellation/evidence tests. Non-user fallback remains system/internal, never an authenticated payer |
-| Standalone trigger classifier + captions | Same explicit injection in `services/agent_trigger_service/src/main.rs` | Same journal attempt boundary, separate from harness and DCS | Standalone service and shared trigger tests. Caption timeout/error-to-None behavior retained; funding-denial propagation deferred |
+| Harness session naming | Independent configured recorder supplied to `HaikuAgentSessionNameGenerator` in harness `main.rs`; session owner, ChatRename feature/entity | One-shot model attempts → journal (feature classification unchanged) | Existing name-generator/host tests plus shared completion tests; not covered merely by common-context injection |
+| Harness repository selection | Independent configured recorder passed to `CursorContainerManager` in harness `main.rs`; repository chooser's trusted owner, AgentRepositoryChoice feature | Rust selection completion attempts → journal | Shared completion tests and host tests. Does not cover Cursor's external agent runtime |
+| Harness trigger classifier + image captions | Independent recorder in `services/agent_harness_service/src/trigger.rs` passed to `FastModelTriggerJudge` and `VisionImageCaptioner`; authenticated message sender, Automation feature | Structured/image HTTP attempts → journal before existing errors are handled | `agent_trigger` caption tests + `agent` image-budget/cancellation/evidence tests. A non-user sender is not replaced with a system billing identity |
+| Standalone trigger classifier + captions | Same explicit injection in `services/agent_trigger_service/src/main.rs` | Same journal attempt boundary, separate from harness and DCS | Standalone service and shared trigger tests. Caption timeout/error-to-None behavior retained; optional inference skips legacy quota refusal without AI fallback |
| DSS channel responder | `services/document_storage_service/src/main.rs` builds common context; responder binds requesting user, ChannelBot feature | AgentLoop HTTP attempts, native tools and subagents → journal; legacy aggregate retained | Shared agent/tool tests, DSS package tests |
-| DSS channel classifier | Separate `pg_recorder` supplied to `FastModelTriggerClassifier` in DSS `main.rs`; requesting user, ChannelBot | One-shot classification attempts → journal | Shared completion/structured tests. This is distinct from the responder's common context |
-| DSS call summarizer, import duplicate judges | Independent `pg_recorder` injections already present in DSS `main.rs`; existing user/feature supplied by each producer | Calls using shared Rust completion APIs now produce journal attempts | Shared agent tests and DSS tests; this change does not change their attribution policy |
+| DSS channel classifier | Separate configured recorder supplied to `FastModelTriggerClassifier` in DSS `main.rs`; requesting user, ChannelBot | One-shot classification attempts → journal | Shared completion/structured tests. This is distinct from the responder's common context |
+| DSS call summarizer, system task duplicate judge | Independent configured recorder injections in DSS `main.rs`; existing user/feature supplied by each producer | Calls using shared Rust completion APIs now produce journal attempts | Shared agent tests and DSS tests; this change does not change their attribution policy |
| Scheduled actions | `services/scheduled_action/src/bins/service.rs` common context; executor binds stored authenticated owner, Automation feature | AgentLoop attempts + native tools/subagents → journal | Scheduled-action package and shared scope tests; remote execution outside this process remains separate |
| DCS imports | DCS `main.rs` passes wrapped recorder to import service; import `drive_session` binds user, Import feature | Rust gather/Notion AgentLoop attempts → journal | Shared agent tests / DCS tests. Remote connector internals are not local model attempts |
-| Memory and AI projections | Common host recorder (DCS; memory's own context also uses `pg_recorder`), with existing user-specific Memory / AiProjection contexts | Shared completion/AgentLoop attempts → journal, including native tool subcalls where available | Shared agent/tool regressions; no claim of new end-to-end producer deployment tests |
-| Managed harness sandboxes (local/Daytona), external Cursor/Codex/Claude agents | Harness passes provider credentials / external account credentials directly to the runtime | **Not covered** by Rust common-context injection; runtime model calls bypass this HTTP adapter. Rust session naming/selection and calls back to authenticated MCP are the only covered portions | Future runtime-owned producer instrumentation must emit trusted per-attempt provider/model/counter/response IDs and immutable authenticated session attribution to an idempotent journal ingress. No credential/proxy redesign or enforcement is introduced here |
+| Memory and AI projections | Common host recorder (DCS; memory's own context uses the configured common-tool builder), with existing user-specific Memory / AiProjection contexts | Shared completion/AgentLoop attempts → journal, including native tool subcalls where available | Shared agent/tool regressions; no claim of new end-to-end producer deployment tests |
+| Managed harness sandboxes (local/Daytona), external Cursor/Codex/Claude agents | Harness passes provider credentials / external account credentials directly to the runtime | **Not covered** by Rust common-context injection; runtime model calls bypass this HTTP adapter. Rust session naming/selection and calls back to authenticated MCP are the only covered portions | Future runtime-owned producer instrumentation must emit trusted per-attempt provider/model/counter/response IDs and immutable authenticated session attribution to an idempotent journal ingress. Legacy admission now gates Macro-funded managed sessions, but adds no runtime metering or credential/proxy redesign; externally funded runtime execution skips that gate |
| AI editing worker, dictation/audio, arbitrary raw-provider callers, remote MCP internals | Separate producer ownership; multipart requests explicitly warn when scoped but unsupported | **Not covered by this token-attempt adapter.** Existing aggregate/audio behavior is not per-attempt evidence | Separate worker/audio integrations and trusted ingress required. Do not enable new-policy charging for these paths based on this matrix |
## Verification and future activation gates
@@ -125,7 +137,8 @@ retention requirements for observations, or cascade-delete financial history.
Schema/application merge and test-environment verification are not evidence that
this deployment gate has passed.
-Before a future **billing/enforcement** release, separately review/implement:
+Before a future **financial admission/collection** release (not the separate
+legacy snapshot-based quota flag), separately review/implement:
1. Verified rates, request-regime support, authenticated payer/seat resolution,
renewal policy activation, and the existing financial admission contract.
@@ -139,8 +152,8 @@ Before a future **billing/enforcement** release, separately review/implement:
5. An authorized, auditable resolution/release transition for unresolved financial
attempts. `FinancialUsage::pending` and funding scans only discover work;
reconciliation stops at missing actual usage, and conflicting finalization
- replays cannot overwrite immutable evidence. Before enabling admission, test
- operator authorization, retained original evidence, idempotent resolution and
+ replays cannot overwrite immutable evidence. Before enabling financial admission,
+ test operator authorization, retained original evidence, idempotent resolution and
recovery of payer ordering/holds. Never treat missing evidence as zero or
release a hold merely because a request timed out. This gap may remain deferred
only while financial admission and policy activation remain unwired.
diff --git a/docs/AI_QUOTA_ENFORCEMENT.md b/docs/AI_QUOTA_ENFORCEMENT.md
new file mode 100644
index 0000000000..1c331182c4
--- /dev/null
+++ b/docs/AI_QUOTA_ENFORCEMENT.md
@@ -0,0 +1,284 @@
+# AI usage quota enforcement
+
+## Scope and policy
+
+`ENABLE_AI_USAGE_ENFORCEMENT` enables **legacy, snapshot-based admission and
+prospective counting of existing `ai_usage` producers**. It is not a provider-spend
+cap, a reservation system, or activation of financial admission. It does not select
+`FinancialMode::Activated`, authorize credit holds, or convert observations into
+customer debt. Production usage-driven credit consumption and Stripe settlement
+remain disabled by the existing `Environment::Develop` safeguard, even with the
+flag true. See [the separate observation/financial rollout](AI_BILLING_ROLLOUT.md).
+
+The [startup loader](../crates/ai_usage/src/config.rs) accepts only raw `true` or
+`false`; absent means false. Empty, quoted, `null`, or otherwise malformed present
+values fail startup. Hosts load the policy once, not per request. Changing it
+requires restarting/redeploying every participating process.
+
+The [shared policy](../crates/ai_usage/src/domain/counting.rs) is identical for
+admission and recording:
+
+| Policy / work | Admission | New `ai_usage.count_usage` |
+| --- | --- | --- |
+| Absent or false | Return before billing I/O | `false` |
+| True, real user, billable feature | Check existing allowance; fail closed on validation error | `true` when existing producer records usage |
+| True, exempt feature | No quota billing I/O | `false` |
+| Genuinely system-owned work | No user quota billing I/O | `false` |
+| Rejected before execution | No provider work | No usage row for work not executed |
+| Historical rows / inserts omitting column | Never retrospectively classified | `false` |
+| Disabled after activation | Stop admission and new counting | Existing booleans unchanged |
+
+**Exempt:** Memory, AiProjection, CallSummary, Dictation. **Billable:** Chat,
+Automation, DynamicCompletionsApi, ChatRename, ChannelBot, AiEditing, Import,
+AgentSession, AgentRepositoryChoice. In particular, AI editing is not exempt.
+The classification is exhaustive and server-selected, not request-controlled.
+
+Free-plan and unlimited-entitlement allowance behavior is unchanged: these users
+are not blocked by this quota policy. Model-access and resource permissions remain
+independent. Counting eligibility is not a claim that a particular user owes money;
+it does not special-case their plan. Existing paid allowance, per-seat usage,
+payer credits, overage opt-in/cap, and denial decisions remain in the legacy ledger.
+
+### Persistence
+
+The [usage service](../crates/ai_usage/src/domain/service.rs) computes the boolean
+for both `record()` and `record_now()`, before the
+[repository insert](../crates/ai_usage/src/outbound/pg_usage_repo.rs). Clients cannot
+supply it. The [billing reader](../crates/ai_billing/src/outbound/pg_usage_reader.rs)
+uses the persisted literal `count_usage = TRUE`, not a mutable feature exclusion
+list. User/team-seat scoping, `[start, end)` periods, list-rate arithmetic, and
+fallback pricing for null totals are retained. Admin analytics still includes
+uncounted rows; repricing can change totals, never eligibility.
+
+[Counting tests](../crates/ai_usage/src/domain/counting/test.rs),
+[recording tests](../crates/ai_usage/src/domain/service/test.rs),
+[persistence/repricing tests](../crates/ai_usage/src/outbound/pg_usage_repo/test.rs),
+and [billing-reader tests](../crates/ai_billing/src/outbound/pg_usage_reader/test.rs)
+cover these distinctions. Historical analytics and observations must never be
+backfilled into counted usage or financial authorizations.
+
+## Public failure contracts
+
+The [shared admission port](../crates/ai_billing/src/domain/admission.rs) returns
+`Denied(DenyReason)` or sanitized `Unavailable`. Authorization runs first; quota
+errors are not permission grants and must not disclose another user's quota.
+
+| Result | HTTP status | Stable `code` | Retry semantics |
+| --- | --- | --- | --- |
+| Allowance exhausted | 402 | `ai_allowance_exhausted` | Policy/allowance must change; no automatic tight retry |
+| Spending cap reached | 402 | `ai_overage_limit_reached` | Policy/allowance must change |
+| Overage payment failed | 402 | `ai_overage_payment_failed` | Billing problem must be resolved |
+| Could not validate billing | 503 | `ai_billing_unavailable` | Retry later with bounded backoff; never execute on uncertainty |
+
+The [common HTTP body](../crates/ai_billing/src/inbound/admission.rs) is
+`{"error":"<public explanation>","code":"<stable code>"}`. The 503 explanation is
+`AI usage validation is temporarily unavailable. Please try again.` Internal
+reports are logged server-side, not serialized. A `Retry-After` header is not
+promised by this mapping.
+
+Cognition chat retains its existing `ChatMessageError` body, including
+`stream_id: null` on admission failure and the optional `code` field. Structured
+completion retains `StructuredCompletionError` (`error`, optional `code`). Both
+return before stream/provider work; chat also checks before creating chat/messages.
+Structured completion's agent and final formatting phases are one admitted
+operation. Imports, session create/control, and manual scheduled execution use
+the shared 402/503 body for synchronous admission errors. Session control also
+retains its unrelated plain-text 503 for a draining replica with `Retry-After: 1`;
+inspect the content type and code rather than assuming every 503 is billing.
+
+### Tools, protocols, queues, and background work
+
+- Subagent, native Anthropic tools, and AI editing return a failed tool result with
+ the stable code and public explanation. These are tool/protocol failures, not
+ necessarily HTTP 402/503 at the outer MCP transport. Do not treat an HTTP-success
+ tool envelope as successful execution. No alternate provider is tried on refusal.
+- Direct in-memory ACP prompts return protocol error `-32603`, the public message,
+ and `data: {"code":"…","retryable":false}` for denial (`true` for unavailability).
+ History and resumable state are preserved; rejected work never starts the engine.
+- Harness admission applies at ingress **and dispatch**, including restored,
+ forwarded, steered, and queued spending commands. A waiting command is not a
+ reservation. On exhaustion, the waiting queue is durably removed before queue
+ updates, failed announced-reply resolution, and
+ `agent_session.command_rejected` lifecycle publication. Its
+ [metadata](../crates/agent_session/src/domain/events.rs) contains `identity`,
+ `action_id`, `actor`, optional `announcement_message_id`, and
+ `failure: {code, message, retryable}`. It does not invent a runtime turn.
+- Queue validation unavailability preserves FIFO work for a later ordinary
+ queue-driving event, without a hot retry loop. Persistence failure retains work
+ rather than announcing a rejection that was not saved. Retrying an already
+ queued/in-flight action ID does not duplicate work or retroactively refuse the
+ original turn. A rejected steering follow-up does not cancel the running turn.
+- AI imports check before running/spawn and again when delayed AI work begins;
+ failures clear running state and remain visible in import status. Deterministic
+ connector fetches/import branches and status/dismiss/discard remain available.
+- Scheduled model work checks the stored owner before resource preparation.
+ Manual, cron, and event runs share the execution boundary; claims and failure
+ bookkeeping are finalized even on refusal. Cron schedules advance; event failures
+ are terminal bookkeeping, not automatic replay. Agent targets delegate funding
+ decisions to the session/harness service. A 503 describes a retryable cause, not
+ a promise that a scheduler or broker will redeliver the same run.
+- Optional chat/session naming is independently admitted as ChatRename; refusal
+ retains the existing/default title without failing successful primary work.
+ Optional bot/trigger inference (including image captions) skips classification
+ on failure, without AI fallback or implied approval. Explicit mentions still
+ route deterministically; downstream execution has its own gate and failures.
+- Repository selection is deterministic for an authorized explicit repository or
+ a single candidate. Ambiguous model selection is AgentRepositoryChoice: refusal
+ propagates instead of choosing a model fallback or silently approving work.
+ Stop/cancel, reads, non-spending controls, and ordinary document operations remain
+ available subject to their existing permissions.
+
+## Trusted attribution and coverage matrix
+
+Authenticated handlers/tool `RequestContext.user_id`, verified document edit
+receipts, persisted scheduled-action owners, and persisted session owners are the
+sources of attribution. Session collaborators are actors, not replacement payers.
+Subagents/native tools replace the shared context's placeholder user with the
+trusted caller and inherit the server's feature/entity. Never accept billing
+identity, feature exemption, or `count_usage` from a client; never substitute
+`SYSTEM_USER_ID` for a missing real caller. Non-user session owners remain rejected.
+
+Macro-funded in-memory and managed sandbox sessions require AgentSession admission.
+Cursor, Codex Cloud, Claude Cloud, and externally paired runtime execution is funded
+externally and skips that gate; independently Macro-funded naming, repository
+selection, and tool calls still have their own gates.
+
+Links below identify the actual boundary, production injection/recorder constructor,
+and local regression suite. They are not evidence of live-provider, browser, or
+deployed coverage. Shared factory [R](../crates/ai_usage/src/lib.rs) means
+`pg_recorder_with_enforcement`: configured analytics plus separate `pg_tracking`.
+Shared tools [T](../crates/ai_tools/src/build_context.rs) construct configured
+admission and R. Admission itself never records usage or calls settlement.
+
+| Surface / feature | Admission boundary | Production recorder / composition | Regression tests |
+| --- | --- | --- | --- |
+| Cognition chat / Chat | [chat handler](../services/document_cognition_service/src/api/stream/chat_message.rs) | [DCS main](../services/document_cognition_service/src/main.rs): configured `UsageServiceImpl` inside `SettlingUsageRecorder`, wrapped with `with_tracking` | [pre-creation refusal and permission precedence](../services/document_cognition_service/src/api/stream/chat_message/test.rs) |
+| Structured completion / DynamicCompletionsApi | [completion handler](../services/document_cognition_service/src/api/structured_completion.rs) | DCS main, same recorder across both phases | [both phases and OpenAPI](../services/document_cognition_service/src/api/structured_completion/test.rs) |
+| Chat naming / ChatRename | [chat renamer](../services/document_cognition_service/src/service/chat_renamer.rs) | DCS main, same recorder | [safe naming skip](../services/document_cognition_service/src/service/chat_renamer/test.rs) |
+| Direct subagent / inherited feature | [operations service](../crates/ai_tools/src/ai_operations.rs), [subagent](../crates/ai_tools/src/subagent.rs) | Host common context: T, DCS main, or [MCP context](../services/mcp_service/src/context.rs) using R | [zero provider calls](../crates/ai_tools/src/ai_operations/test.rs), [concurrent caller isolation](../crates/ai_tools/src/subagent/test.rs) |
+| Native Anthropic WebSearch/WebFetch/code tools / inherited feature | [invoke_server_tool](../crates/anthropic/src/toolset.rs) before both provider branches | Same common contexts via `FromRef`; observation only, **no legacy aggregate producer** | [tool attribution/refusal](../crates/anthropic/src/toolset/test.rs) |
+| AI document editing / AiEditing | [document orchestration](../crates/documents/src/domain/ai_editing.rs) after verified edit receipt | Common context's recorder, existing per-model worker usage | [domain](../crates/documents/src/domain/ai_editing/test.rs), [direct tool and permission precedence](../crates/documents/src/inbound/toolset/edit_document/test.rs) |
+| AI gather/Notion imports / Import | [import admission](../crates/import/src/domain/service/admission.rs), [execution/rechecks](../crates/import/src/domain/service.rs) | DCS main, wrapped recorder | [initial/retry/delayed/deterministic cases](../crates/import/src/domain/service/test/admission.rs), [HTTP](../crates/import/src/inbound/axum_router/test.rs) |
+| Channel responder / ChannelBot | [bot service](../crates/channel_bots/src/domain/service.rs) | [DSS main](../services/document_storage_service/src/main.rs), common context T | [response refusal](../crates/channel_bots/src/domain/service/tests.rs) |
+| Optional channel classification / ChannelBot | [trigger detector](../crates/channel_bots/src/domain/trigger_detector.rs) | DSS main, independent R for classifier | [explicit routing and inference skip](../crates/channel_bots/src/domain/trigger_detector/tests.rs) |
+| Trigger inference and image captions / Automation | [trigger service](../crates/agent_trigger/src/domain/service.rs) | [standalone trigger main](../services/agent_trigger_service/src/main.rs) R; [harness trigger](../services/agent_harness_service/src/trigger.rs) receives R from harness main | [classification/caption refusal](../crates/agent_trigger/src/domain/service/test/admission.rs), [no system fallback](../crates/agent_trigger/src/outbound/fast_model_judge/test.rs) |
+| Managed session ingress/dispatch/queue / AgentSession | [harness admission](../crates/agent_harness/src/domain/service/admission.rs) | [harness main](../services/agent_harness_service/src/main.rs) T for in-memory; managed sandbox inference has **no `ai_usage` producer** | [owner, authorization, runtime funding, restart, queue rejection/outage](../crates/agent_harness/src/domain/service/test/quota.rs), [HTTP](../crates/agent_session/src/inbound/axum_router/test.rs), [event shape](../crates/agent_session/src/domain/events/test.rs) |
+| Direct in-memory ACP/provider commands / AgentSession | [admit_turn](../crates/agent_inmem/src/domain/admission.rs), [agent execution](../crates/agent_inmem/src/domain/agent.rs) | Harness main → manager → `RigTurnEngine`, common-context recorder | [direct ACP, queue, cancel, history](../crates/agent_inmem/src/domain/agent/test.rs), [manager](../crates/agent_inmem/src/outbound/manager/test.rs) |
+| Session naming / ChatRename | [name generator gate](../crates/agent_session/src/domain/name_generation.rs) | Harness main, independent R for `HaikuAgentSessionNameGenerator` | [fallback without provider calls](../crates/agent_session/src/domain/name_generation/test.rs) |
+| Repository chooser / AgentRepositoryChoice | [repository choice service](../crates/agent_harness/src/domain/repository_choice.rs) | Harness main → `CursorContainerManager`, independent R | [deterministic bypass / typed model refusal](../crates/agent_harness/src/domain/repository_choice/test.rs) |
+| Scheduled manual/cron/event model work / Automation | [shared executor](../services/scheduled_action/src/domain/execution.rs) | [scheduled service](../services/scheduled_action/src/bins/service.rs), common context T | [claims, schedules, terminal events](../services/scheduled_action/src/domain/execution/test.rs), [manual HTTP](../services/scheduled_action/src/inbound/axum_router/test.rs) |
+| Scheduled agent targets / session funding policy | [target runner](../services/scheduled_action/src/domain/target_runner.rs) → session/harness admission | Target runtime's recorder, not duplicate scheduler metering | [delegation and typed errors](../services/scheduled_action/src/domain/target_runner/test.rs), [routine error transport](../crates/agent_session/src/inbound/routine_sessions/test.rs) |
+| Memory, projection, call summary, dictation / exempt | [shared admission policy](../crates/ai_billing/src/domain/admission.rs) skips quota; ordinary permissions still apply | DCS/DSS configured recorders; [memory context](../crates/memory/src/context.rs) uses T; DSS independent call-summary/dictation recorders use R | [all exempt features](../crates/ai_usage/src/domain/counting/test.rs), [no billing I/O](../crates/ai_billing/src/domain/admission/test.rs), [configured recording](../crates/ai_billing/src/composition/test.rs) |
+| Existing system task duplicate judge / Automation | [system attribution](../crates/task_dedup/src/outbound/judge.rs), no user quota gate | DSS main, independent R; system events stay uncounted | [system counting](../crates/ai_usage/src/domain/counting/test.rs), [system recorder behavior](../crates/ai_billing/src/outbound/settling_recorder/test.rs) |
+| Billing summary (not execution) | [billing service policy](../crates/ai_billing/src/domain/service.rs) | [authentication main](../services/authentication_service/src/main.rs) configures same flag, no usage producer | [environment/free/unlimited/settlement](../crates/ai_billing/src/domain/service/test.rs), [authentication configuration](../services/authentication_service/src/config/test.rs) |
+
+## Limits and operational risks
+
+- Snapshot checks do not reserve quota. Concurrent calls can all pass the same
+ snapshot and overshoot. Already-started work may finish after exhaustion or a
+ flag change; an admitted operation is not a strict maximum-cost authorization.
+- Existing aggregate recording remains best-effort. Spawned writes, process exit,
+ storage outages, absent provider counters, and paths recording only final success
+ can lose usage. Admission fail-closed does not make metering durable.
+- Managed sandbox inference is gated but is not metered into `ai_usage`. Native
+ Anthropic tools write observations, not aggregate usage. External runtimes,
+ remote MCP internals, and raw provider integrations are not made metered by
+ injecting a common context. AI editing retains existing worker aggregates;
+ dictation retains existing audio aggregates but is exempt. Neither is made
+ complete per-attempt token evidence by this change.
+- `ai_usage_observation` and `ai_financial_invocation` are separate accounting
+ systems, not additional counted aggregates. Never sum them with `ai_usage` or
+ replay observations into debt. Observation retention/erasure approval remains a
+ deployment gate in the [observation rollout](AI_BILLING_ROLLOUT.md).
+- Default-disabled constructors remain for internal/evaluation callers. Production
+ must use configured admission and R (or explicitly configure DCS's inner usage
+ service). A new producer must be audited at both its admission and recorder
+ constructor; protecting its caller alone does not protect direct invocation.
+- **Mixed true/false service configurations undercount usage and permit bypasses.**
+ A false execution host skips admission, a false recorder writes uncounted rows,
+ and a mismatched authentication host reports inconsistent blocking state. The
+ flag is not safe for a staggered per-service activation.
+
+## Safe rollout
+
+No hosted configuration change or collection activation is authorized by this
+procedure. Operators must approve and record each release gate.
+
+1. **Compatible schema first.** Apply
+ [the default-false column migration](../crates/macro_db_client/migrations/20260930145625_add_ai_usage_count_usage.sql)
+ and [the concurrent partial-index migration](../crates/macro_db_client/migrations/20260930145626_ai_usage_counted_user_created_at_idx.sql).
+ Keep the full analytics/old-service index. Verify historical rows and old
+ inserts remain false. Verify `pg_index.indisvalid` and `pg_get_indexdef` for
+ `ai_usage_counted_user_created_at_idx`: `(user_id, created_at DESC) WHERE
+ count_usage = TRUE`. After interrupted concurrent creation, inspect validity;
+ `IF NOT EXISTS` does not repair an invalid index. Follow the migration's
+ operator-reviewed concurrent drop/retry guidance, not a database reset.
+2. **Deploy all application changes with the flag false (or absent).** Include
+ default-off admission, counted readers/writers, protocol/client contracts, and
+ all host wiring before considering activation. Existing historical usage is
+ no longer billed just because its feature is billable.
+3. **Register `ENABLE_AI_USAGE_ENFORCEMENT` as raw `false` in Doppler for every
+ participating service configuration**, including relevant environment variants:
+ authentication, document cognition, document storage, MCP, agent harness,
+ standalone agent trigger, and scheduled action. Include any separately launched
+ memory/common-tool host. Use the existing Doppler-backed application config,
+ not a quoted JSON string, AWS secret indirection, or a second Pulumi flag.
+ Verify the effective startup value for every replica/worker. Registration and
+ hosted access require operator approval; code defaults are not proof of it.
+4. **Validate locally, then in an approved staging environment.** Use the checklist
+ below and review counts, index plans, failure rates, queue cleanup, and known
+ metering gaps. Confirm missing/false/true/invalid parsing and that production
+ settlement is still suppressed. Validate the observation privacy gate too.
+5. **Coordinated, operator-approved enablement only.** Record participating hosts,
+ deployment versions, approved environment/time, monitoring owner, and rollback
+ decision. Coordinate configuration and restart/redeploy so traffic does not
+ rely on mixed-policy replicas; drain/pause affected work if needed. Check actual
+ startup policy, 402/503 behavior, new counted rows, summaries, and background
+ queues before declaring activation complete. This enables legacy quotas, **not
+ production credit collection or Stripe settlement**.
+
+### Rollback
+
+Set the flag to raw `false` **consistently across all participating configurations**
+and restart/redeploy the affected processes. Verify admission bypass and new
+uncounted writes. Do not roll back the additive schema, drop the indexes, erase
+counted history, or rewrite recorded booleans. Never backfill historical rows.
+Previously counted usage remains counted (and will still be present when
+re-enabled in the same period); disabling is not a quota reset. Already-started
+operations can finish using their process's startup policy.
+
+## Validation checklist
+
+Use disposable local fixtures and no hosted customer data. These are release
+checks, not a claim that a particular deployment has passed them.
+
+- Generate only from local Rust binaries:
+ `bun run --cwd apps/web gen-api document-cognition agent-harness scheduled-action cloud-storage`.
+ Repeat with `gen-api --check`. Run `bun run --cwd apps/web check`, `just check`,
+ `just check full`, and `just rust-check`. In a jj-only checkout the current
+ generator freshness/check scripts use Git discovery; a discovery failure is
+ not a passing check. Compare two generated trees for determinism and run direct
+ scoped checks when blocked; record the limitation.
+- Run the matrix's affected Rust packages individually from the repository root
+ with `SQLX_OFFLINE` unset; use [database setup](DATABASE_DEVELOPMENT.md).
+ Include `ai_usage`, `ai_billing`, and composition tests. Test counted/uncounted,
+ historical/default rows, multiple users/seats, period boundaries, null totals,
+ repricing stability, and partial-index eligibility on representative local data.
+- With missing/false configuration, prove zero admission billing-port calls and
+ uncounted writes. With true, use allowed paid, exhausted, free/unlimited, exempt,
+ system, and unavailable-billing fixtures. Refusals must make zero provider calls.
+ Check each matrix boundary, not just chat, and test unauthorized requests first.
+- Enqueue while allowed, exhaust before dispatch, restore after restart, and check
+ durable rejection/reply cleanup. During billing outage preserve queued work
+ without spinning. Retry existing action IDs without duplication. Check import
+ running flags and scheduled claims/finalization, plus cancellation during admission.
+- Start an isolated stack with
+ `nix develop --command just run_local --instance ai-quota`. Use local identities
+ and billing fixtures. Perform the [AI chat manual checks](AGENT_GUIDE/ai-chat.md#quota-manual-checks):
+ no orphaned chat/stream on refusal, direct AI edit failure, observable queue
+ rejection, usable cancellation, and recovery after consistently disabling.
+ A frontend against hosted dev cannot validate these local backend changes.
+- Record actual command results, browser observations, index timing/plans, and
+ environment blockers in the release handoff. Do not infer live Doppler state,
+ provider coverage, privacy approval, or production payment suppression from a
+ generated schema alone. No upgrade-prompt UI is added by this rollout.
diff --git a/packages/sdk/generated/agent-harness/index.ts b/packages/sdk/generated/agent-harness/index.ts
index 3f383faae0..94ee40831e 100644
--- a/packages/sdk/generated/agent-harness/index.ts
+++ b/packages/sdk/generated/agent-harness/index.ts
@@ -1,4 +1,4 @@
// This file is auto-generated by @hey-api/openapi-ts
export { type Options, Sdk } from './sdk.gen';
-export type { AccessLevel, AgentAction, AgentActionId, AgentConfigKindDto, AgentConfigOptionDto, AgentConfigSelectOptionDto, AgentModelDto, AgentModelsStatusDto, AgentPermissionAction, AgentPromptAction, AgentRepositoriesResponse, AgentRepositoryBranchesResponse, AgentRepositoryDto, AgentRespondElicitationAction, AgentSessionChangesPatchResponse, AgentSessionChangesResponse, AgentSessionLogEntryDto, AgentSessionLogResponse, AgentSessionPreviewData, AgentSessionPreviewDto, AgentSessionQueueResponse, AgentSessionResponse, AgentSetConfigOptionAction, AgentSetModelAction, BotId, CapabilityHarnessDto, CaptureAttemptDto, CaptureOutcomeDto, ChangedFileDto, ChangesetDto, ChangesetSourceDto, ChannelSharePermission, ClientOptions, CompleteData, CompleteErrors, CompleteRequest, CompleteResponse, CompleteResponses, ControlAgentSessionData, ControlAgentSessionError, ControlAgentSessionErrors, ControlAgentSessionResponse, ControlAgentSessionResponses, ControlRequest, ControlResponse, ControlStatusDto, CreateAgentSessionData, CreateAgentSessionError, CreateAgentSessionErrors, CreateAgentSessionRequest, CreateAgentSessionResponse, CreateAgentSessionResponse2, CreateAgentSessionResponses, CreateSessionThread, DeleteAgentSessionData, DeleteAgentSessionError, DeleteAgentSessionErrors, DeleteAgentSessionResponses, DisconnectData, DisconnectErrors, DisconnectResponse, DisconnectResponses, DiscoverAgentCapabilitiesHandlerData, DiscoverAgentCapabilitiesHandlerErrors, DiscoverAgentCapabilitiesHandlerResponse, DiscoverAgentCapabilitiesHandlerResponses, DiscoverAgentCapabilitiesRequest, DiscoverAgentCapabilitiesResponse, DocumentId, EditQueuedActionData, EditQueuedActionError, EditQueuedActionErrors, EditQueuedActionRequest, EditQueuedActionResponse, EditQueuedActionResponses, ElicitationAnswer, ElicitationContentValue, ElicitationRequestId, EmptyRequest, ExternalSessionResponse, FileChangeKindDto, GetAgentSandboxSizeData, GetAgentSandboxSizeError, GetAgentSandboxSizeErrors, GetAgentSandboxSizeResponse, GetAgentSandboxSizeResponses, GetAgentSessionChangesData, GetAgentSessionChangesError, GetAgentSessionChangesErrors, GetAgentSessionChangesPatchData, GetAgentSessionChangesPatchError, GetAgentSessionChangesPatchErrors, GetAgentSessionChangesPatchResponse, GetAgentSessionChangesPatchResponses, GetAgentSessionChangesResponse, GetAgentSessionChangesResponses, GetAgentSessionData, GetAgentSessionError, GetAgentSessionErrors, GetAgentSessionLogData, GetAgentSessionLogError, GetAgentSessionLogErrors, GetAgentSessionLogResponse, GetAgentSessionLogResponses, GetAgentSessionPermissionsData, GetAgentSessionPermissionsError, GetAgentSessionPermissionsErrors, GetAgentSessionPermissionsResponse, GetAgentSessionPermissionsResponses, GetAgentSessionQueueData, GetAgentSessionQueueError, GetAgentSessionQueueErrors, GetAgentSessionQueueResponse, GetAgentSessionQueueResponses, GetAgentSessionResponse, GetAgentSessionResponses, GitRefDto, LinkShare, ListAgentRepositoriesData, ListAgentRepositoriesErrors, ListAgentRepositoriesResponse, ListAgentRepositoriesResponses, ListAgentRepositoryBranchesData, ListAgentRepositoryBranchesErrors, ListAgentRepositoryBranchesResponse, ListAgentRepositoryBranchesResponses, LoadAgentModelsHandlerData, LoadAgentModelsHandlerErrors, LoadAgentModelsHandlerResponse, LoadAgentModelsHandlerResponses, LoadAgentModelsRequest, LoadAgentModelsResponse, LogDirectionDto, LogFrameDto, MessageParent, ModelHarnessDto, PermissionAnswer, PreviewAgentSessionsData, PreviewAgentSessionsError, PreviewAgentSessionsErrors, PreviewAgentSessionsRequest, PreviewAgentSessionsResponse, PreviewAgentSessionsResponse2, PreviewAgentSessionsResponses, PromptAttachment, PutAgentSandboxSizeData, PutAgentSandboxSizeError, PutAgentSandboxSizeErrors, PutAgentSandboxSizeResponse, PutAgentSandboxSizeResponses, PutAgentSessionSandboxSizeData, PutAgentSessionSandboxSizeError, PutAgentSessionSandboxSizeErrors, PutAgentSessionSandboxSizeResponse, PutAgentSessionSandboxSizeResponses, QueuedActionDto, RefreshAgentSessionChangesData, RefreshAgentSessionChangesError, RefreshAgentSessionChangesErrors, RefreshAgentSessionChangesResponse, RefreshAgentSessionChangesResponses, RemoveQueuedActionData, RemoveQueuedActionError, RemoveQueuedActionErrors, RemoveQueuedActionResponse, RemoveQueuedActionResponses, RenameAgentSessionData, RenameAgentSessionError, RenameAgentSessionErrors, RenameAgentSessionRequest, RenameAgentSessionResponse, RenameAgentSessionResponses, SandboxSize, SandboxSizeBody, SessionBot, SessionStatusDto, SetAgentSessionArchivedData, SetAgentSessionArchivedError, SetAgentSessionArchivedErrors, SetAgentSessionArchivedRequest, SetAgentSessionArchivedResponse, SetAgentSessionArchivedResponses, SharePermissionV2, StartData, StartErrors, StartResponse, StartResponse2, StartResponses, StatusData, StatusErrors, StatusResponse, StatusResponse2, StatusResponses, UpdateAgentSessionPermissionsData, UpdateAgentSessionPermissionsError, UpdateAgentSessionPermissionsErrors, UpdateAgentSessionPermissionsResponse, UpdateAgentSessionPermissionsResponses, UpdateChannelSharePermission, UpdateOperation, UpdateSharePermissionRequestV2, WithAgentSessionId } from './types.gen';
+export type { AccessLevel, AgentAction, AgentActionId, AgentConfigKindDto, AgentConfigOptionDto, AgentConfigSelectOptionDto, AgentModelDto, AgentModelsStatusDto, AgentPermissionAction, AgentPromptAction, AgentRepositoriesResponse, AgentRepositoryBranchesResponse, AgentRepositoryDto, AgentRespondElicitationAction, AgentSessionChangesPatchResponse, AgentSessionChangesResponse, AgentSessionLogEntryDto, AgentSessionLogResponse, AgentSessionPreviewData, AgentSessionPreviewDto, AgentSessionQueueResponse, AgentSessionResponse, AgentSetConfigOptionAction, AgentSetModelAction, AiAdmissionErrorBody, BotId, CapabilityHarnessDto, CaptureAttemptDto, CaptureOutcomeDto, ChangedFileDto, ChangesetDto, ChangesetSourceDto, ChannelSharePermission, ClientOptions, CompleteData, CompleteErrors, CompleteRequest, CompleteResponse, CompleteResponses, ControlAgentSessionData, ControlAgentSessionError, ControlAgentSessionErrors, ControlAgentSessionResponse, ControlAgentSessionResponses, ControlRequest, ControlResponse, ControlStatusDto, CreateAgentSessionData, CreateAgentSessionError, CreateAgentSessionErrors, CreateAgentSessionRequest, CreateAgentSessionResponse, CreateAgentSessionResponse2, CreateAgentSessionResponses, CreateSessionThread, DeleteAgentSessionData, DeleteAgentSessionError, DeleteAgentSessionErrors, DeleteAgentSessionResponses, DisconnectData, DisconnectErrors, DisconnectResponse, DisconnectResponses, DiscoverAgentCapabilitiesHandlerData, DiscoverAgentCapabilitiesHandlerErrors, DiscoverAgentCapabilitiesHandlerResponse, DiscoverAgentCapabilitiesHandlerResponses, DiscoverAgentCapabilitiesRequest, DiscoverAgentCapabilitiesResponse, DocumentId, EditQueuedActionData, EditQueuedActionError, EditQueuedActionErrors, EditQueuedActionRequest, EditQueuedActionResponse, EditQueuedActionResponses, ElicitationAnswer, ElicitationContentValue, ElicitationRequestId, EmptyRequest, ExternalSessionResponse, FileChangeKindDto, GetAgentSandboxSizeData, GetAgentSandboxSizeError, GetAgentSandboxSizeErrors, GetAgentSandboxSizeResponse, GetAgentSandboxSizeResponses, GetAgentSessionChangesData, GetAgentSessionChangesError, GetAgentSessionChangesErrors, GetAgentSessionChangesPatchData, GetAgentSessionChangesPatchError, GetAgentSessionChangesPatchErrors, GetAgentSessionChangesPatchResponse, GetAgentSessionChangesPatchResponses, GetAgentSessionChangesResponse, GetAgentSessionChangesResponses, GetAgentSessionData, GetAgentSessionError, GetAgentSessionErrors, GetAgentSessionLogData, GetAgentSessionLogError, GetAgentSessionLogErrors, GetAgentSessionLogResponse, GetAgentSessionLogResponses, GetAgentSessionPermissionsData, GetAgentSessionPermissionsError, GetAgentSessionPermissionsErrors, GetAgentSessionPermissionsResponse, GetAgentSessionPermissionsResponses, GetAgentSessionQueueData, GetAgentSessionQueueError, GetAgentSessionQueueErrors, GetAgentSessionQueueResponse, GetAgentSessionQueueResponses, GetAgentSessionResponse, GetAgentSessionResponses, GitRefDto, LinkShare, ListAgentRepositoriesData, ListAgentRepositoriesErrors, ListAgentRepositoriesResponse, ListAgentRepositoriesResponses, ListAgentRepositoryBranchesData, ListAgentRepositoryBranchesErrors, ListAgentRepositoryBranchesResponse, ListAgentRepositoryBranchesResponses, LoadAgentModelsHandlerData, LoadAgentModelsHandlerErrors, LoadAgentModelsHandlerResponse, LoadAgentModelsHandlerResponses, LoadAgentModelsRequest, LoadAgentModelsResponse, LogDirectionDto, LogFrameDto, MessageParent, ModelHarnessDto, PermissionAnswer, PreviewAgentSessionsData, PreviewAgentSessionsError, PreviewAgentSessionsErrors, PreviewAgentSessionsRequest, PreviewAgentSessionsResponse, PreviewAgentSessionsResponse2, PreviewAgentSessionsResponses, PromptAttachment, PutAgentSandboxSizeData, PutAgentSandboxSizeError, PutAgentSandboxSizeErrors, PutAgentSandboxSizeResponse, PutAgentSandboxSizeResponses, PutAgentSessionSandboxSizeData, PutAgentSessionSandboxSizeError, PutAgentSessionSandboxSizeErrors, PutAgentSessionSandboxSizeResponse, PutAgentSessionSandboxSizeResponses, QueuedActionDto, RefreshAgentSessionChangesData, RefreshAgentSessionChangesError, RefreshAgentSessionChangesErrors, RefreshAgentSessionChangesResponse, RefreshAgentSessionChangesResponses, RemoveQueuedActionData, RemoveQueuedActionError, RemoveQueuedActionErrors, RemoveQueuedActionResponse, RemoveQueuedActionResponses, RenameAgentSessionData, RenameAgentSessionError, RenameAgentSessionErrors, RenameAgentSessionRequest, RenameAgentSessionResponse, RenameAgentSessionResponses, SandboxSize, SandboxSizeBody, SessionBot, SessionStatusDto, SetAgentSessionArchivedData, SetAgentSessionArchivedError, SetAgentSessionArchivedErrors, SetAgentSessionArchivedRequest, SetAgentSessionArchivedResponse, SetAgentSessionArchivedResponses, SharePermissionV2, StartData, StartErrors, StartResponse, StartResponse2, StartResponses, StatusData, StatusErrors, StatusResponse, StatusResponse2, StatusResponses, UpdateAgentSessionPermissionsData, UpdateAgentSessionPermissionsError, UpdateAgentSessionPermissionsErrors, UpdateAgentSessionPermissionsResponse, UpdateAgentSessionPermissionsResponses, UpdateChannelSharePermission, UpdateOperation, UpdateSharePermissionRequestV2, WithAgentSessionId } from './types.gen';
diff --git a/packages/sdk/generated/agent-harness/types.gen.ts b/packages/sdk/generated/agent-harness/types.gen.ts
index dfeeca37af..c1693289a8 100644
--- a/packages/sdk/generated/agent-harness/types.gen.ts
+++ b/packages/sdk/generated/agent-harness/types.gen.ts
@@ -496,6 +496,21 @@ export type AgentSetModelAction = {
model: string;
};
+/**
+ * Public admission error payload. Handlers with additional fields can reuse the
+ * domain error's code and message and [`admission_status`].
+ */
+export type AiAdmissionErrorBody = {
+ /**
+ * Stable denial or unavailability code.
+ */
+ code: string;
+ /**
+ * Human-readable explanation, without internal billing diagnostics.
+ */
+ error: string;
+};
+
export type BotId = string;
/**
@@ -1527,10 +1542,18 @@ export type CreateAgentSessionData = {
export type CreateAgentSessionErrors = {
401: string;
+ /**
+ * AI allowance exhausted
+ */
+ 402: AiAdmissionErrorBody;
403: string;
404: string;
422: string;
500: string;
+ /**
+ * AI usage validation unavailable; retry later
+ */
+ 503: AiAdmissionErrorBody;
};
export type CreateAgentSessionError = CreateAgentSessionErrors[keyof CreateAgentSessionErrors];
@@ -1734,9 +1757,17 @@ export type ControlAgentSessionData = {
export type ControlAgentSessionErrors = {
401: string;
+ /**
+ * AI allowance exhausted
+ */
+ 402: AiAdmissionErrorBody;
403: string;
422: string;
500: string;
+ /**
+ * AI usage validation unavailable, or replica draining; retry later
+ */
+ 503: AiAdmissionErrorBody;
};
export type ControlAgentSessionError = ControlAgentSessionErrors[keyof ControlAgentSessionErrors];
diff --git a/packages/sdk/generated/cognition/index.ts b/packages/sdk/generated/cognition/index.ts
index e55b6f99d1..73c344350c 100644
--- a/packages/sdk/generated/cognition/index.ts
+++ b/packages/sdk/generated/cognition/index.ts
@@ -1,4 +1,4 @@
// This file is auto-generated by @hey-api/openapi-ts
export { type Options, Sdk } from './sdk.gen';
-export type { AccessLevel, AddMcpServerData, AddMcpServerError, AddMcpServerErrors, AddMcpServerResponse, AddMcpServerResponses, AddServerRequest, AiFeature, AssistantMessagePart, AttachmentMetadata, AttachmentType, BrowsePipedreamMcpCatalogData, BrowsePipedreamMcpCatalogError, BrowsePipedreamMcpCatalogErrors, BrowsePipedreamMcpCatalogResponse, BrowsePipedreamMcpCatalogResponses, CallToolData, CallToolError, CallToolErrors, CallToolRequest, CallToolResponse, CallToolResponse2, CallToolResponses, ChannelSharePermission, ChannelType, Chat, ChatAttachment, ChatHistory, ChatHistoryBatchMessagesRequest, ChatMessage, ChatMessageContent, ChatMessageError, ChatMessageWithAttachments, ChatPreview, ChatPreviewData, ChatResponse, ChatStream, ClientOptions, CompleteHandlerData, CompleteHandlerErrors, CompleteHandlerResponse, CompleteHandlerResponses, CompleteOnboardingRequest, CompletePipedreamMcpConnectionData, CompletePipedreamMcpConnectionError, CompletePipedreamMcpConnectionErrors, CompletePipedreamMcpConnectionResponse, CompletePipedreamMcpConnectionResponses, CompletionUsage, ConnectedServer, ConversationRecord, CopyChatData, CopyChatError, CopyChatErrors, CopyChatResponse, CopyChatResponses, CreateChatData, CreateChatError, CreateChatErrors, CreateChatRequest, CreateChatResponse, CreateChatResponses, CreatePipedreamMcpTokenData, CreatePipedreamMcpTokenError, CreatePipedreamMcpTokenErrors, CreatePipedreamMcpTokenResponse, CreatePipedreamMcpTokenResponses, DeleteChatData, DeleteChatError, DeleteChatErrors, DeleteChatResponses, DeleteMcpServerData, DeleteMcpServerError, DeleteMcpServerErrors, DeleteMcpServerResponse, DeleteMcpServerResponses, DeletePipedreamMcpConnectionData, DeletePipedreamMcpConnectionError, DeletePipedreamMcpConnectionErrors, DeletePipedreamMcpConnectionResponse, DeletePipedreamMcpConnectionResponses, DismissRunHandlerData, DismissRunHandlerErrors, DismissRunHandlerResponse, DismissRunHandlerResponses, DocumentCognitionServiceApiVersion, DocumentReference, DocumentTextPart, DynamicSchema, Entity, EntityType, ErrorBody, ErrorResponse, Expiry, FeatureUsage, FileType, GenericErrorResponse, GetBatchPreviewData, GetBatchPreviewError, GetBatchPreviewErrors, GetBatchPreviewRequest, GetBatchPreviewResponse, GetBatchPreviewResponse2, GetBatchPreviewResponses, GetChatData, GetChatError, GetChatErrors, GetChatHistoryBatchMessagesHandlerData, GetChatHistoryBatchMessagesHandlerError, GetChatHistoryBatchMessagesHandlerErrors, GetChatHistoryBatchMessagesHandlerResponse, GetChatHistoryBatchMessagesHandlerResponses, GetChatHistoryHandlerData, GetChatHistoryHandlerError, GetChatHistoryHandlerErrors, GetChatHistoryHandlerResponse, GetChatHistoryHandlerResponses, GetChatPermissionsData, GetChatPermissionsError, GetChatPermissionsErrors, GetChatPermissionsResponse, GetChatPermissionsResponse2, GetChatPermissionsResponses, GetChatResponse, GetChatResponse2, GetChatResponses, GetChatsForAttachmentHandlerData, GetChatsForAttachmentHandlerError, GetChatsForAttachmentHandlerErrors, GetChatsForAttachmentHandlerResponse, GetChatsForAttachmentHandlerResponses, GetChatsForAttachmentResponse, GetCitationHandlerData, GetCitationHandlerError, GetCitationHandlerErrors, GetCitationHandlerResponse, GetCitationHandlerResponses, GetMemoryHandlerData, GetMemoryHandlerError, GetMemoryHandlerErrors, GetMemoryHandlerResponse, GetMemoryHandlerResponses, GetStateHandler2Data, GetStateHandler2Errors, GetStateHandler2Response, GetStateHandler2Responses, GetStateHandlerData, GetStateHandlerErrors, GetStateHandlerResponse, GetStateHandlerResponses, GetUsageHandlerData, GetUsageHandlerError, GetUsageHandlerErrors, GetUsageHandlerResponse, GetUsageHandlerResponses, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, HttpSendChatMessageRequest, ImportEntity, ImportRun, ImportSource, ImportState, ImportStatus, Initiator, JwtPayload, LinearIssueMeta, LinkShare, ListMcpServersData, ListMcpServersError, ListMcpServersErrors, ListMcpServersResponse, ListMcpServersResponses, ListPipedreamMcpConnectionsData, ListPipedreamMcpConnectionsError, ListPipedreamMcpConnectionsErrors, ListPipedreamMcpConnectionsResponse, ListPipedreamMcpConnectionsResponses, MacroUserIdStr, McpAuthCallbackData, McpAuthCallbackError, McpAuthCallbackErrors, McpAuthCallbackResponses, McpOauthClientMetadataData, McpOauthClientMetadataResponses, MemoryErrorBody, MemoryResponse, MessageWithAttachments, NewAttachment, NewChatMessage, NewMessageAttachment, NotionDocMeta, OnboardingRow, OnboardingState, OnboardingStatus, PatchChatData, PatchChatError, PatchChatErrors, PatchChatRequest, PatchChatResponses, PermanentlyDeleteChatData, PermanentlyDeleteChatError, PermanentlyDeleteChatErrors, PermanentlyDeleteChatResponses, PipedreamCatalogEntryResponse, PipedreamCatalogResponse, PipedreamCompleteRequest, PipedreamConnectionResponse, PipedreamTokenResponse, PipedreamUpdateRequest, Price, ProjectionStateResponse, ProjectionStatus, RefreshCadence, RejectToolCallData, RejectToolCallError, RejectToolCallErrors, RejectToolCallRequest, RejectToolCallResponses, RetryGatherHandlerData, RetryGatherHandlerErrors, RetryGatherHandlerResponse, RetryGatherHandlerResponses, RevertDeleteChatData, RevertDeleteChatError, RevertDeleteChatErrors, RevertDeleteChatResponses, Role, RunImportHandlerData, RunImportHandlerErrors, RunImportHandlerResponse, RunImportHandlerResponses, RunImportOutcome, RunImportRequest, RunStatus, SendChatMessageData, SendChatMessageError, SendChatMessageErrors, SendChatMessagePayload, SendChatMessageResponse, SendChatMessageResponse2, SendChatMessageResponses, ServerResponse, SetPricingHandlerData, SetPricingHandlerError, SetPricingHandlerErrors, SetPricingHandlerResponses, SetPricingRequest, SharePermissionV2, SlackChannelMeta, SlackParticipant, StartAuthRequest, StartAuthResponse, StartMcpAuthData, StartMcpAuthError, StartMcpAuthErrors, StartMcpAuthResponse, StartMcpAuthResponses, StopChatStreamData, StopChatStreamError, StopChatStreamError2, StopChatStreamErrors, StopChatStreamRequest, StopChatStreamResponse, StopChatStreamResponse2, StopChatStreamResponses, StreamError, StringIdResponse, StructuredCompletionData, StructuredCompletionError, StructuredCompletionError2, StructuredCompletionErrors, StructuredCompletionRequest, StructuredCompletionResponse, StructuredCompletionResponse2, StructuredCompletionResponses, TargetType, ToolSet, UpdateChannelSharePermission, UpdateMcpServerData, UpdateMcpServerError, UpdateMcpServerErrors, UpdateMcpServerResponse, UpdateMcpServerResponses, UpdateOperation, UpdatePipedreamMcpConnectionData, UpdatePipedreamMcpConnectionError, UpdatePipedreamMcpConnectionErrors, UpdatePipedreamMcpConnectionResponse, UpdatePipedreamMcpConnectionResponses, UpdateServerRequest, UpdateSharePermissionRequestV2, UpdateToolCallData, UpdateToolCallError, UpdateToolCallErrors, UpdateToolCallRequest, UpdateToolCallResponses, UpdateToolResponseData, UpdateToolResponseError, UpdateToolResponseErrors, UpdateToolResponseRequest, UpdateToolResponseResponses, UpsertAiProjectionData, UpsertAiProjectionError, UpsertAiProjectionErrors, UpsertAiProjectionResponse, UpsertAiProjectionResponses, UpsertProjectionRequest, Usage, UsageRequest, UsageSummary, UserPdfRect, UserToolResponseValue, WebCitation, WithChatId } from './types.gen';
+export type { AccessLevel, AddMcpServerData, AddMcpServerError, AddMcpServerErrors, AddMcpServerResponse, AddMcpServerResponses, AddServerRequest, AiAdmissionErrorBody, AiFeature, AssistantMessagePart, AttachmentMetadata, AttachmentType, BrowsePipedreamMcpCatalogData, BrowsePipedreamMcpCatalogError, BrowsePipedreamMcpCatalogErrors, BrowsePipedreamMcpCatalogResponse, BrowsePipedreamMcpCatalogResponses, CallToolData, CallToolError, CallToolErrors, CallToolRequest, CallToolResponse, CallToolResponse2, CallToolResponses, ChannelSharePermission, ChannelType, Chat, ChatAttachment, ChatHistory, ChatHistoryBatchMessagesRequest, ChatMessage, ChatMessageContent, ChatMessageError, ChatMessageWithAttachments, ChatPreview, ChatPreviewData, ChatResponse, ChatStream, ClientOptions, CompleteHandlerData, CompleteHandlerErrors, CompleteHandlerResponse, CompleteHandlerResponses, CompleteOnboardingRequest, CompletePipedreamMcpConnectionData, CompletePipedreamMcpConnectionError, CompletePipedreamMcpConnectionErrors, CompletePipedreamMcpConnectionResponse, CompletePipedreamMcpConnectionResponses, CompletionUsage, ConnectedServer, ConversationRecord, CopyChatData, CopyChatError, CopyChatErrors, CopyChatResponse, CopyChatResponses, CreateChatData, CreateChatError, CreateChatErrors, CreateChatRequest, CreateChatResponse, CreateChatResponses, CreatePipedreamMcpTokenData, CreatePipedreamMcpTokenError, CreatePipedreamMcpTokenErrors, CreatePipedreamMcpTokenResponse, CreatePipedreamMcpTokenResponses, DeleteChatData, DeleteChatError, DeleteChatErrors, DeleteChatResponses, DeleteMcpServerData, DeleteMcpServerError, DeleteMcpServerErrors, DeleteMcpServerResponse, DeleteMcpServerResponses, DeletePipedreamMcpConnectionData, DeletePipedreamMcpConnectionError, DeletePipedreamMcpConnectionErrors, DeletePipedreamMcpConnectionResponse, DeletePipedreamMcpConnectionResponses, DismissRunHandlerData, DismissRunHandlerErrors, DismissRunHandlerResponse, DismissRunHandlerResponses, DocumentCognitionServiceApiVersion, DocumentReference, DocumentTextPart, DynamicSchema, Entity, EntityType, ErrorBody, ErrorResponse, Expiry, FeatureUsage, FileType, GenericErrorResponse, GetBatchPreviewData, GetBatchPreviewError, GetBatchPreviewErrors, GetBatchPreviewRequest, GetBatchPreviewResponse, GetBatchPreviewResponse2, GetBatchPreviewResponses, GetChatData, GetChatError, GetChatErrors, GetChatHistoryBatchMessagesHandlerData, GetChatHistoryBatchMessagesHandlerError, GetChatHistoryBatchMessagesHandlerErrors, GetChatHistoryBatchMessagesHandlerResponse, GetChatHistoryBatchMessagesHandlerResponses, GetChatHistoryHandlerData, GetChatHistoryHandlerError, GetChatHistoryHandlerErrors, GetChatHistoryHandlerResponse, GetChatHistoryHandlerResponses, GetChatPermissionsData, GetChatPermissionsError, GetChatPermissionsErrors, GetChatPermissionsResponse, GetChatPermissionsResponse2, GetChatPermissionsResponses, GetChatResponse, GetChatResponse2, GetChatResponses, GetChatsForAttachmentHandlerData, GetChatsForAttachmentHandlerError, GetChatsForAttachmentHandlerErrors, GetChatsForAttachmentHandlerResponse, GetChatsForAttachmentHandlerResponses, GetChatsForAttachmentResponse, GetCitationHandlerData, GetCitationHandlerError, GetCitationHandlerErrors, GetCitationHandlerResponse, GetCitationHandlerResponses, GetMemoryHandlerData, GetMemoryHandlerError, GetMemoryHandlerErrors, GetMemoryHandlerResponse, GetMemoryHandlerResponses, GetStateHandler2Data, GetStateHandler2Errors, GetStateHandler2Response, GetStateHandler2Responses, GetStateHandlerData, GetStateHandlerErrors, GetStateHandlerResponse, GetStateHandlerResponses, GetUsageHandlerData, GetUsageHandlerError, GetUsageHandlerErrors, GetUsageHandlerResponse, GetUsageHandlerResponses, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, HttpSendChatMessageRequest, ImportEntity, ImportRun, ImportSource, ImportState, ImportStatus, Initiator, JwtPayload, LinearIssueMeta, LinkShare, ListMcpServersData, ListMcpServersError, ListMcpServersErrors, ListMcpServersResponse, ListMcpServersResponses, ListPipedreamMcpConnectionsData, ListPipedreamMcpConnectionsError, ListPipedreamMcpConnectionsErrors, ListPipedreamMcpConnectionsResponse, ListPipedreamMcpConnectionsResponses, MacroUserIdStr, McpAuthCallbackData, McpAuthCallbackError, McpAuthCallbackErrors, McpAuthCallbackResponses, McpOauthClientMetadataData, McpOauthClientMetadataResponses, MemoryErrorBody, MemoryResponse, MessageWithAttachments, NewAttachment, NewChatMessage, NewMessageAttachment, NotionDocMeta, OnboardingRow, OnboardingState, OnboardingStatus, PatchChatData, PatchChatError, PatchChatErrors, PatchChatRequest, PatchChatResponses, PermanentlyDeleteChatData, PermanentlyDeleteChatError, PermanentlyDeleteChatErrors, PermanentlyDeleteChatResponses, PipedreamCatalogEntryResponse, PipedreamCatalogResponse, PipedreamCompleteRequest, PipedreamConnectionResponse, PipedreamTokenResponse, PipedreamUpdateRequest, Price, ProjectionStateResponse, ProjectionStatus, RefreshCadence, RejectToolCallData, RejectToolCallError, RejectToolCallErrors, RejectToolCallRequest, RejectToolCallResponses, RetryGatherHandlerData, RetryGatherHandlerError, RetryGatherHandlerErrors, RetryGatherHandlerResponse, RetryGatherHandlerResponses, RevertDeleteChatData, RevertDeleteChatError, RevertDeleteChatErrors, RevertDeleteChatResponses, Role, RunImportHandlerData, RunImportHandlerErrors, RunImportHandlerResponse, RunImportHandlerResponses, RunImportOutcome, RunImportRequest, RunStatus, SendChatMessageData, SendChatMessageError, SendChatMessageErrors, SendChatMessagePayload, SendChatMessageResponse, SendChatMessageResponse2, SendChatMessageResponses, ServerResponse, SetPricingHandlerData, SetPricingHandlerError, SetPricingHandlerErrors, SetPricingHandlerResponses, SetPricingRequest, SharePermissionV2, SlackChannelMeta, SlackParticipant, StartAuthRequest, StartAuthResponse, StartMcpAuthData, StartMcpAuthError, StartMcpAuthErrors, StartMcpAuthResponse, StartMcpAuthResponses, StopChatStreamData, StopChatStreamError, StopChatStreamError2, StopChatStreamErrors, StopChatStreamRequest, StopChatStreamResponse, StopChatStreamResponse2, StopChatStreamResponses, StreamError, StringIdResponse, StructuredCompletionData, StructuredCompletionError, StructuredCompletionError2, StructuredCompletionErrors, StructuredCompletionRequest, StructuredCompletionResponse, StructuredCompletionResponse2, StructuredCompletionResponses, TargetType, ToolSet, UpdateChannelSharePermission, UpdateMcpServerData, UpdateMcpServerError, UpdateMcpServerErrors, UpdateMcpServerResponse, UpdateMcpServerResponses, UpdateOperation, UpdatePipedreamMcpConnectionData, UpdatePipedreamMcpConnectionError, UpdatePipedreamMcpConnectionErrors, UpdatePipedreamMcpConnectionResponse, UpdatePipedreamMcpConnectionResponses, UpdateServerRequest, UpdateSharePermissionRequestV2, UpdateToolCallData, UpdateToolCallError, UpdateToolCallErrors, UpdateToolCallRequest, UpdateToolCallResponses, UpdateToolResponseData, UpdateToolResponseError, UpdateToolResponseErrors, UpdateToolResponseRequest, UpdateToolResponseResponses, UpsertAiProjectionData, UpsertAiProjectionError, UpsertAiProjectionErrors, UpsertAiProjectionResponse, UpsertAiProjectionResponses, UpsertProjectionRequest, Usage, UsageRequest, UsageSummary, UserPdfRect, UserToolResponseValue, WebCitation, WithChatId } from './types.gen';
diff --git a/packages/sdk/generated/cognition/types.gen.ts b/packages/sdk/generated/cognition/types.gen.ts
index 7417b3bae7..1b706e8ab7 100644
--- a/packages/sdk/generated/cognition/types.gen.ts
+++ b/packages/sdk/generated/cognition/types.gen.ts
@@ -23,6 +23,21 @@ export type AddServerRequest = {
url: string;
};
+/**
+ * Public admission error payload. Handlers with additional fields can reuse the
+ * domain error's code and message and [`admission_status`].
+ */
+export type AiAdmissionErrorBody = {
+ /**
+ * Stable denial or unavailability code.
+ */
+ code: string;
+ /**
+ * Human-readable explanation, without internal billing diagnostics.
+ */
+ error: string;
+};
+
/**
* Everything we use AI for. The wire / DB form of each variant is its
* `snake_case` name.
@@ -294,7 +309,7 @@ export type ChatMessageContent = string | Array<AssistantMessagePart>;
*/
export type ChatMessageError = {
/**
- * Stable machine-readable code for payment-required errors.
+ * Stable machine-readable code for admission errors (402 or 503).
*/
code?: string | null;
error: string;
@@ -1415,7 +1430,7 @@ export type StringIdResponse = {
export type StructuredCompletionError = {
/**
- * Stable machine-readable code for payment-required errors.
+ * Stable machine-readable code for admission errors (402 or 503).
*/
code?: string | null;
error: string;
@@ -2289,12 +2304,22 @@ export type RetryGatherHandlerErrors = {
* Unknown import source
*/
400: unknown;
+ /**
+ * AI allowance exhausted
+ */
+ 402: AiAdmissionErrorBody;
/**
* Internal server error
*/
500: unknown;
+ /**
+ * AI usage validation unavailable; retry later
+ */
+ 503: AiAdmissionErrorBody;
};
+export type RetryGatherHandlerError = RetryGatherHandlerErrors[keyof RetryGatherHandlerErrors];
+
export type RetryGatherHandlerResponses = {
/**
* Retry accepted (idempotent)
@@ -2750,6 +2775,10 @@ export type SendChatMessageErrors = {
* Forbidden — user lacks access to the requested model
*/
403: ChatMessageError;
+ /**
+ * AI usage validation unavailable — retry later
+ */
+ 503: ChatMessageError;
};
export type SendChatMessageError = SendChatMessageErrors[keyof SendChatMessageErrors];
@@ -2807,11 +2836,15 @@ export type StructuredCompletionErrors = {
/**
* Payment required
*/
- 402: unknown;
+ 402: StructuredCompletionError;
/**
* Internal error
*/
500: StructuredCompletionError;
+ /**
+ * AI usage validation unavailable — retry later
+ */
+ 503: StructuredCompletionError;
};
export type StructuredCompletionError2 = StructuredCompletionErrors[keyof StructuredCompletionErrors];
diff --git a/packages/sdk/generated/scheduled-action/index.ts b/packages/sdk/generated/scheduled-action/index.ts
index d4151dc70c..b5f5823410 100644
--- a/packages/sdk/generated/scheduled-action/index.ts
+++ b/packages/sdk/generated/scheduled-action/index.ts
@@ -1,4 +1,4 @@
// This file is auto-generated by @hey-api/openapi-ts
export { type Options, Sdk } from './sdk.gen';
-export type { ActionConfiguration, ActionConfigurationUpdate, ActionExecutionRecord, ActionKind, ActionTrigger, AgentTask, AgentTaskAgent, ClientOptions, CreateScheduledAction, CreateScheduledActionData, CreateScheduledActionError, CreateScheduledActionErrors, CreateScheduledActionResponse, CreateScheduledActionResponses, DeleteScheduledActionData, DeleteScheduledActionError, DeleteScheduledActionErrors, DeleteScheduledActionResponse, DeleteScheduledActionResponses, EmptyResponse, EventFilter, EventFilters, EventName, ExecuteScheduledActionNowData, ExecuteScheduledActionNowError, ExecuteScheduledActionNowErrors, ExecuteScheduledActionNowResponse, ExecuteScheduledActionNowResponses, ExecutionResource, ExecutionResourceType, ExecutionResult, InProgressExecution, LegacyActionConfiguration, ListScheduledActionHistoryData, ListScheduledActionHistoryError, ListScheduledActionHistoryErrors, ListScheduledActionHistoryResponse, ListScheduledActionHistoryResponses, ListScheduledActionsData, ListScheduledActionsError, ListScheduledActionsErrors, ListScheduledActionsResponse, ListScheduledActionsResponses, RoutineModelId, Schedule, ScheduledAction, ScheduledActionHealthData, ScheduledActionHealthResponse, ScheduledActionHealthResponses, ScheduledActionResponse, ScheduledActionUpdate, SetScheduledActionEnabled, SetScheduledActionEnabledData, SetScheduledActionEnabledError, SetScheduledActionEnabledErrors, SetScheduledActionEnabledResponse, SetScheduledActionEnabledResponses, UpdateScheduledAction, UpdateScheduledActionData, UpdateScheduledActionError, UpdateScheduledActionErrors, UpdateScheduledActionResponse, UpdateScheduledActionResponses } from './types.gen';
+export type { ActionConfiguration, ActionConfigurationUpdate, ActionExecutionRecord, ActionKind, ActionTrigger, AgentTask, AgentTaskAgent, AiAdmissionErrorBody, ClientOptions, CreateScheduledAction, CreateScheduledActionData, CreateScheduledActionError, CreateScheduledActionErrors, CreateScheduledActionResponse, CreateScheduledActionResponses, DeleteScheduledActionData, DeleteScheduledActionError, DeleteScheduledActionErrors, DeleteScheduledActionResponse, DeleteScheduledActionResponses, EmptyResponse, EventFilter, EventFilters, EventName, ExecuteScheduledActionNowData, ExecuteScheduledActionNowError, ExecuteScheduledActionNowErrors, ExecuteScheduledActionNowResponse, ExecuteScheduledActionNowResponses, ExecutionResource, ExecutionResourceType, ExecutionResult, InProgressExecution, LegacyActionConfiguration, ListScheduledActionHistoryData, ListScheduledActionHistoryError, ListScheduledActionHistoryErrors, ListScheduledActionHistoryResponse, ListScheduledActionHistoryResponses, ListScheduledActionsData, ListScheduledActionsError, ListScheduledActionsErrors, ListScheduledActionsResponse, ListScheduledActionsResponses, RoutineModelId, Schedule, ScheduledAction, ScheduledActionHealthData, ScheduledActionHealthResponse, ScheduledActionHealthResponses, ScheduledActionResponse, ScheduledActionUpdate, SetScheduledActionEnabled, SetScheduledActionEnabledData, SetScheduledActionEnabledError, SetScheduledActionEnabledErrors, SetScheduledActionEnabledResponse, SetScheduledActionEnabledResponses, UpdateScheduledAction, UpdateScheduledActionData, UpdateScheduledActionError, UpdateScheduledActionErrors, UpdateScheduledActionResponse, UpdateScheduledActionResponses } from './types.gen';
diff --git a/packages/sdk/generated/scheduled-action/types.gen.ts b/packages/sdk/generated/scheduled-action/types.gen.ts
index 886bb8971f..5cccba9465 100644
--- a/packages/sdk/generated/scheduled-action/types.gen.ts
+++ b/packages/sdk/generated/scheduled-action/types.gen.ts
@@ -81,6 +81,21 @@ export type AgentTaskAgent = {
bot_id: string;
};
+/**
+ * Public admission error payload. Handlers with additional fields can reuse the
+ * domain error's code and message and [`admission_status`].
+ */
+export type AiAdmissionErrorBody = {
+ /**
+ * Stable denial or unavailability code.
+ */
+ code: string;
+ /**
+ * Human-readable explanation, without internal billing diagnostics.
+ */
+ error: string;
+};
+
/**
* Exactly one representation is accepted, even if mixed fields agree or are null.
*/
@@ -418,12 +433,20 @@ export type ExecuteScheduledActionNowData = {
export type ExecuteScheduledActionNowErrors = {
400: string;
401: string;
+ /**
+ * AI allowance exhausted
+ */
+ 402: AiAdmissionErrorBody;
404: string;
/**
* Action is already running
*/
409: string;
500: string;
+ /**
+ * AI usage validation unavailable; retry later
+ */
+ 503: AiAdmissionErrorBody;
};
export type ExecuteScheduledActionNowError = ExecuteScheduledActionNowErrors[keyof ExecuteScheduledActionNowErrors];
diff --git a/packages/sdk/generated/storage/index.ts b/packages/sdk/generated/storage/index.ts
index 9ecebaa6da..739ed09a25 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-ts
export { type Options, Sdk } from './sdk.gen';
-export type { AccessLevel, ActiveCallsResponse, ActiveCallSummary, ActiveMeeting, ActiveMeetingsResponse, ActivityType, AddFavoriteData, AddFavoriteError, AddFavoriteErrors, AddFavoriteRequest, AddFavoriteResponse, AddFavoriteResponses, AddParticipantsData, AddParticipantsError, AddParticipantsErrors, AddParticipantsRequest, AddParticipantsResponses, AddPinHandlerData, AddPinHandlerError, AddPinHandlerErrors, AddPinHandlerResponse, AddPinHandlerResponses, AddPinRequest, Agent, AgentActionId, AgentChannelScope, AgentMcpServer, AgentMcpServers, AgentPullRequestState, AgentSessionFilters, AgentSessionLifecycleEvent, 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, AssignInitiativeTasksData, AssignInitiativeTasksError, AssignInitiativeTasksErrors, AssignInitiativeTasksResponse, AssignInitiativeTasksResponses, AssignTasksRequest, AssignTasksResponse, AssignTasksResult, AssignTaskStatus, AttachmentChange, AttendeeResponseStatus, BasicDocument, BasicDocumentSubType, BomPart, Bot, BotChannel, BotChannelType, BotId, BotKind, BotOwner, BotOwnerProfile, BotSenderProfile, BotToken, BranchNameResponse, BTreeMap, BulkWakeupRequest, BulkWakeupResponse, BulkWakeupSyncServiceDocumentsData, BulkWakeupSyncServiceDocumentsErrors, BulkWakeupSyncServiceDocumentsResponse, BulkWakeupSyncServiceDocumentsResponses, CalendarAttendee, CalendarEvent, CalendarEventFilters, CalendarEventSourceContent, CalendarMentionEvent, CalendarMentionPreviewItem, CalendarMentionPreviewKind, CalendarMentionPreviewRequest, CalendarMentionPreviewRequestItem, CalendarMentionPreviewResponse, CalendarOccurrence, CalendarOccurrenceItem, CalendarOccurrenceResponse, CalendarSyncStatus, CallActiveResponse, CallFilters, CallRecord, CallRecordGuest, CallRecordParticipant, CallRecordPreview, CallRecordPreviewData, CallRecordTranscriptSegment, CallStatus, CallTokenResponse, CallWebhookData, CallWebhookError, CallWebhookErrors, CallWebhookResponses, Channel, ChannelCreatedMetadata, ChannelDeletedMetadata, ChannelEventAttachment, ChannelFilters, ChannelJoinCodeResponse, ChannelLabel, ChannelLabelRule, ChannelLabelsList, 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, CountedReaction, CreateAgentData, CreateAgentError, CreateAgentErrors, CreateAgentRequest, CreateAgentResponse, CreateAgentResponses, CreateAnchorData, CreateAnchorError, CreateAnchorErrors, CreateAnchorResponse, CreateAnchorResponses, CreateBotRequest, CreateBulkDocumentResponse, CreateBulkDocumentResponseData, CreateChannelData, CreateChannelError, CreateChannelErrors, CreateChannelLabelData, CreateChannelLabelError, CreateChannelLabelErrors, CreateChannelLabelRequest, CreateChannelLabelResponse, CreateChannelLabelResponses, CreateChannelRequest, CreateChannelResponse, CreateChannelResponse2, CreateChannelResponses, CreateChannelScopedBotData, CreateChannelScopedBotError, CreateChannelScopedBotErrors, CreateChannelScopedBotRequest, CreateChannelScopedBotResponse, CreateChannelScopedBotResponse2, CreateChannelScopedBotResponses, CreateCollabSurfaceTokenData, CreateCollabSurfaceTokenError, CreateCollabSurfaceTokenErrors, CreateCollabSurfaceTokenResponse, CreateCollabSurfaceTokenResponses, 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, CreateInitiativeData, CreateInitiativeError, CreateInitiativeErrors, CreateInitiativeRequest, CreateInitiativeResponse, CreateInitiativeResponses, CreateInstructionsDocumentResponse, CreateInstructionsHandlerData, CreateInstructionsHandlerError, CreateInstructionsHandlerErrors, CreateInstructionsHandlerResponse, CreateInstructionsHandlerResponses, CreateMarkdownDocumentRequest, CreateMarkdownDocumentResponse, CreateMarkdownHandlerData, CreateMarkdownHandlerError, CreateMarkdownHandlerErrors, CreateMarkdownHandlerResponse, CreateMarkdownHandlerResponses, CreateMeetingRequest, 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, CrmStageInput, CrmStageResponse, CrmStagesResponse, CrmTeamSettingsResponse, CrmThread, CustomSpeakerAssignment, DataType, DeleteAnchorData, DeleteAnchorError, DeleteAnchorErrors, DeleteAnchorInfo, DeleteAnchorResponse, DeleteAnchorResponses, DeleteCallRecordData, DeleteCallRecordError, DeleteCallRecordErrors, DeleteCallRecordResponse, DeleteCallRecordResponses, DeleteChannelData, DeleteChannelError, DeleteChannelErrors, DeleteChannelLabelData, DeleteChannelLabelError, DeleteChannelLabelErrors, DeleteChannelLabelResponse, DeleteChannelLabelResponses, 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, DeleteInitiativeData, DeleteInitiativeError, DeleteInitiativeErrors, DeleteInitiativeResponse, DeleteInitiativeResponses, DeleteMessageData, DeleteMessageError, DeleteMessageErrors, DeleteMessageQuery, DeleteMessageResponse, DeleteMessageResponses, DeleteProjectHandlerData, DeleteProjectHandlerError, DeleteProjectHandlerErrors, DeleteProjectHandlerResponse, DeleteProjectHandlerResponses, DeleteReminderData, DeleteReminderError, DeleteReminderErrors, DeleteReminderResponse, DeleteReminderResponses, DeleteSelfHarnessData, DeleteSelfHarnessError, DeleteSelfHarnessErrors, DeleteSelfHarnessResponse, DeleteSelfHarnessResponses, DeleteThreadInfo, DeleteUnthreadedAnchorRequest, DeleteUnthreadedAnchorResponse, DeleteUnthreadedPdfAnchorRequest, DeleteUserApiKeyData, DeleteUserApiKeyError, DeleteUserApiKeyErrors, DeleteUserApiKeyResponse, DeleteUserApiKeyResponses, DeleteUserDocumentViewLocationData, DeleteUserDocumentViewLocationError, DeleteUserDocumentViewLocationErrors, DeleteUserDocumentViewLocationResponse, DeleteUserDocumentViewLocationResponses, DeleteViewHandlerData, DeleteViewHandlerError, DeleteViewHandlerErrors, DeleteViewHandlerResponses, DeleteWebhookData, DeleteWebhookError, DeleteWebhookErrors, DeleteWebhookResponse, DeleteWebhookResponses, DescriptionDocumentId, DocumentBasic, DocumentContent, DocumentContentLocation, DocumentContentState, DocumentContentUploadedMetadata, DocumentCopiedMetadata, DocumentCreatedMetadata, DocumentDeletedMetadata, DocumentFilters, DocumentId, DocumentInteractionMetadata, DocumentMetadata, DocumentMetadataWithContent, DocumentPermissionsToken, DocumentPermissionsTokenRequest, DocumentPermissionsTokenResponse, DocumentPreview, DocumentPreviewData, DocumentPreviewDataSubType, DocumentPurgedMetadata, DocumentResponse, DocumentResponseMetadata, DocumentResponseMetadataWithContent, DocumentStorageServiceApiVersion, DocumentSubType, DocumentSyncContentUpdatedMetadata, DocumentSyncEditor, DocumentTeamShareResponse, 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, EntityMessageCreateData, EntityMessageCreateResponse, EntityMessageCreateResponses, EntityMessageDeleteMessageData, EntityMessageDeleteMessageResponse, EntityMessageDeleteMessageResponses, EntityMessageDeleteThreadData, EntityMessageDeleteThreadResponse, EntityMessageDeleteThreadResponses, EntityMessageEditData, EntityMessageEditResponse, EntityMessageEditResponses, EntityMessageGetMessageData, EntityMessageGetMessageResponse, EntityMessageGetMessageResponses, EntityMessageGetThreadData, EntityMessageGetThreadResponse, EntityMessageGetThreadResponses, EntityMessageLegacyData, EntityMessageLegacyResponse, EntityMessageLegacyResponses, EntityMessagePatchThreadData, EntityMessagePatchThreadResponse, EntityMessagePatchThreadResponses, EntityMessageReactData, EntityMessageReactResponse, EntityMessageReactResponses, EntityMessageTypingData, EntityMessageTypingResponse, EntityMessageTypingResponses, EntityPermission, EntityPermissionResponse, 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, GetBotOwnerProfilesData, GetBotOwnerProfilesError, GetBotOwnerProfilesErrors, GetBotOwnerProfilesResponse, GetBotOwnerProfilesResponses, GetCallRecordData, GetCallRecordError, GetCallRecordErrors, GetCallRecordResponse, GetCallRecordResponses, GetChannelAttachmentsData, GetChannelAttachmentsError, GetChannelAttachmentsErrors, GetChannelAttachmentsResponse, GetChannelAttachmentsResponses, GetChannelData, GetChannelError, GetChannelErrors, GetChannelJoinLinkData, GetChannelJoinLinkError, GetChannelJoinLinkErrors, GetChannelJoinLinkResponse, GetChannelJoinLinkResponses, GetChannelMessagesCatchUpData, GetChannelMessagesCatchUpError, GetChannelMessagesCatchUpErrors, GetChannelMessagesCatchUpResponse, GetChannelMessagesCatchUpResponses, 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, GetForeignEntityBySourceData, GetForeignEntityBySourceError, GetForeignEntityBySourceErrors, GetForeignEntityBySourceResponse, GetForeignEntityBySourceResponses, GetForeignEntityData, GetForeignEntityError, GetForeignEntityErrors, GetForeignEntityResponse, GetForeignEntityResponses, GetHarnessPairingData, GetHarnessPairingError, GetHarnessPairingErrors, GetHarnessPairingResponse, GetHarnessPairingResponses, GetHistoryHandlerData, GetHistoryHandlerError, GetHistoryHandlerErrors, GetHistoryHandlerResponse, GetHistoryHandlerResponses, GetInitiativeData, GetInitiativeError, GetInitiativeErrors, GetInitiativeResponse, GetInitiativeResponses, GetInstructionsDocumentResponse, GetInstructionsHandlerData, GetInstructionsHandlerError, GetInstructionsHandlerErrors, GetInstructionsHandlerResponse, GetInstructionsHandlerResponses, GetItemsSoupData, GetItemsSoupError, GetItemsSoupErrors, GetItemsSoupResponse, GetItemsSoupResponses, GetLocationHandlerData, GetLocationHandlerError, GetLocationHandlerErrors, GetLocationHandlerResponse, GetLocationHandlerResponses, 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, GetSelfHarnessData, GetSelfHarnessError, GetSelfHarnessErrors, GetSelfHarnessResponse, GetSelfHarnessResponses, 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, GuestId, GuestJoinRequest, HandlerData, HandlerError, HandlerErrors, HandlerResponse, HandlerResponses, Harness, HarnessAgent, HarnessId, HarnessOwner, HarnessSession, HashMap, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, HighlightType, ImportedAuthor, InFlightTurnSummary, IngestTranscriptData, IngestTranscriptError, IngestTranscriptErrors, IngestTranscriptResponses, InitializeUserDocumentsData, InitializeUserDocumentsError, InitializeUserDocumentsErrors, InitializeUserDocumentsResponse, InitializeUserDocumentsResponses, InitiativeDetail, InitiativeFilters, InitiativeId, InitiativeList, InitiativeSummary, InputReceivedMetadata, InstallSyncData, InstallSyncErrors, InteractionReason, InviteMeetingRequest, InviteMeetingUsersRequest, 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, ListChannelLabelsData, ListChannelLabelsError, ListChannelLabelsErrors, ListChannelLabelsResponse, ListChannelLabelsResponses, 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, ListHarnessSessionsData, ListHarnessSessionsError, ListHarnessSessionsErrors, ListHarnessSessionsResponse, ListHarnessSessionsResponses, ListInitiativesData, ListInitiativesError, ListInitiativesErrors, ListInitiativesResponse, ListInitiativesResponses, ListOccurrencesData, ListOccurrencesErrors, ListOccurrencesResponse, ListOccurrencesResponses, ListRemindersData, ListRemindersError, ListRemindersErrors, ListRemindersResponse, ListRemindersResponses, ListTeamOutOfOfficeData, ListTeamOutOfOfficeErrors, ListTeamOutOfOfficeResponse, ListTeamOutOfOfficeResponses, ListUserApiKeysData, ListUserApiKeysError, ListUserApiKeysErrors, ListUserApiKeysResponse, ListUserApiKeysResponses, ListWebhooksData, ListWebhooksError, ListWebhooksErrors, ListWebhooksResponse, ListWebhooksResponse2, ListWebhooksResponses, LocationResponseData, LocationResponseV3, MacroUserIdStr, Meeting, MeetingCancelData, MeetingCancelError, MeetingCancelErrors, MeetingCancelPreparationData, MeetingCancelPreparationError, MeetingCancelPreparationErrors, MeetingCancelPreparationResponse, MeetingCancelPreparationResponses, MeetingCancelResponse, MeetingCancelResponses, MeetingCreateData, MeetingCreateError, MeetingCreateErrors, MeetingCreateResponse, MeetingCreateResponses, MeetingGuestJoinData, MeetingGuestJoinError, MeetingGuestJoinErrors, MeetingGuestJoinResponse, MeetingGuestJoinResponses, MeetingGuestParticipantsData, MeetingGuestParticipantsError, MeetingGuestParticipantsErrors, MeetingGuestParticipantsResponse, MeetingGuestParticipantsResponses, MeetingInviteData, MeetingInviteError, MeetingInviteErrors, MeetingInvitePermissions, MeetingInvitePermissionsData, MeetingInvitePermissionsError, MeetingInvitePermissionsErrors, MeetingInvitePermissionsResponse, MeetingInvitePermissionsResponses, MeetingInviteResponse, MeetingInviteResponses, MeetingInviteUsersData, MeetingInviteUsersError, MeetingInviteUsersErrors, MeetingInviteUsersResponse, MeetingInviteUsersResponses, MeetingJoinData, MeetingJoinError, MeetingJoinErrors, MeetingJoinResponse, MeetingJoinResponses, MeetingLeaveData, MeetingLeaveError, MeetingLeaveErrors, MeetingLeaveResponse, MeetingLeaveResponses, MeetingListActiveData, MeetingListActiveError, MeetingListActiveErrors, MeetingListActiveResponse, MeetingListActiveResponses, MeetingListData, MeetingListError, MeetingListErrors, MeetingListResponse, MeetingListResponses, MeetingLookupData, MeetingLookupError, MeetingLookupErrors, MeetingLookupResponse, MeetingLookupResponses, MeetingParticipant, MeetingParticipants, MeetingParticipantsData, MeetingParticipantsError, MeetingParticipantsErrors, MeetingParticipantsResponse, MeetingParticipantsResponses, MeetingPreparation, MeetingPrepareData, MeetingPrepareError, MeetingPrepareErrors, MeetingPrepareResponse, MeetingPrepareResponses, MeetingShareData, MeetingShareError, MeetingShareErrors, MeetingShareResponse, MeetingShareResponses, MeetingsResponse, MeetingToken, MeetingUpdateData, MeetingUpdateError, MeetingUpdateErrors, MeetingUpdateResponse, MeetingUpdateResponses, MentionPreviewsData, MentionPreviewsErrors, MentionPreviewsResponse, MentionPreviewsResponses, Mentions, Message, MessageAttachment, MessageChange, MessageCursor, MessageDirection, MessageEvent, MessageListItem, MessagePage, MessageParent, MessagePatch, MessageThread, MessageThreadPreview, MessageTimelineData, MessageTimelineQuery, MessageTimelineResponse, MessageTimelineResponses, NewAttachment, NewChannelAttachment, NewThreadAnchor, NotificationFilters, NotificationState, PairingDetails, Params, ParticipantRole, PatchBotRequest, PatchChannelData, PatchChannelError, PatchChannelErrors, PatchChannelRequest, PatchChannelResponse, PatchChannelResponses, PatchMessageData, PatchMessageError, PatchMessageErrors, PatchMessageNotificationPolicy, 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, PostMessage, PostMessageData, PostMessageError, PostMessageErrors, PostMessageNotificationPolicy, 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, PreviewSmartTagData, PreviewSmartTagError, PreviewSmartTagErrors, PreviewSmartTagResponse, PreviewSmartTagResponses, Project, ProjectDeleteResponseData, ProjectDocumentStatus, ProjectFilters, ProjectPreview, ProjectPreviewData, PropertyDefinition, PropertyFilter, PropertyInput, PropertyOwner, PropertyValue, PutCrmTeamSettingsData, PutCrmTeamSettingsError, PutCrmTeamSettingsErrors, PutCrmTeamSettingsResponse, PutCrmTeamSettingsResponses, PutCrmTeamStagesData, PutCrmTeamStagesError, PutCrmTeamStagesErrors, PutCrmTeamStagesResponse, PutCrmTeamStagesResponses, ReactionAction, ReactionInput, 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, RenameChannelLabelData, RenameChannelLabelError, RenameChannelLabelErrors, RenameChannelLabelRequest, RenameChannelLabelResponse, RenameChannelLabelResponses, ReorderFavoritesData, ReorderFavoritesError, ReorderFavoritesErrors, ReorderFavoritesRequest, ReorderFavoritesResponses, ReorderPinRequest, ReorderPinsHandlerData, ReorderPinsHandlerError, ReorderPinsHandlerErrors, ReorderPinsHandlerResponse, ReorderPinsHandlerResponses, ReplaceCrmStagesRequest, RequestedHarnessScope, ResetCrmTeamStagesData, ResetCrmTeamStagesError, ResetCrmTeamStagesErrors, ResetCrmTeamStagesResponse, ResetCrmTeamStagesResponses, 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, SessionDeletedMetadata, SessionIdentity, SessionMentionedMetadata, SessionOpenedMetadata, SessionRenamedMetadata, SessionSettledMetadata, SessionStoppedMetadata, SetChannelLabelData, SetChannelLabelError, SetChannelLabelErrors, SetChannelLabelRequest, SetChannelLabelResponse, SetChannelLabelResponses, SetChannelPictureData, SetChannelPictureError, SetChannelPictureErrors, SetChannelPictureRequest, SetChannelPictureResponse, SetChannelPictureResponses, SetCompanyHiddenData, SetCompanyHiddenError, SetCompanyHiddenErrors, SetCompanyHiddenRequest, SetCompanyHiddenResponse, SetCompanyHiddenResponses, SetCompanyNameRequest, SetContactHiddenData, SetContactHiddenError, SetContactHiddenErrors, SetContactHiddenRequest, SetContactHiddenResponse, SetContactHiddenResponses, SetContactNameRequest, SetCrmCompanyNameData, SetCrmCompanyNameError, SetCrmCompanyNameErrors, SetCrmCompanyNameResponse, SetCrmCompanyNameResponses, SetCrmContactNameData, SetCrmContactNameError, SetCrmContactNameErrors, SetCrmContactNameResponse, SetCrmContactNameResponses, SetDocumentTeamShareData, SetDocumentTeamShareError, SetDocumentTeamShareErrors, SetDocumentTeamShareRequest, SetDocumentTeamShareResponse, SetDocumentTeamShareResponses, SetEmailSyncData, SetEmailSyncError, SetEmailSyncErrors, SetEmailSyncRequest, SetEmailSyncResponse, SetEmailSyncResponses, SetPropertyValue, SharedEmailFilter, SharePermissionV2, ShortIdResponse, SimpleMention, SimpleSaveData, SimpleSaveError, SimpleSaveErrors, SimpleSaveResponse, SimpleSaveResponses, SmartTagChannelMatch, SmartTagPreview, SoupAgentSessionSoupPropertiesField, SoupApiItem, SoupApiSort, SoupApiSortDirection, SoupAttachment, SoupCalendarEventSoupPropertiesField, SoupCalendarEventTime, SoupCallRecordGuest, SoupCallRecordParticipant, SoupCallRecordSoupPropertiesField, SoupChannel, SoupChannelThread, SoupChatSoupPropertiesField, SoupContact, SoupCountedReaction, SoupCrmCompanySoupPropertiesField, SoupCrmDomain, SoupDocumentSoupPropertiesField, SoupDocumentSubType, SoupEmailThreadPreview, SoupEnrichedEmailThreadPreviewSoupPropertiesField, SoupForeignEntity, SoupInitiativeSoupPropertiesField, SoupItem, SoupLabel, SoupLabelListVisibility, SoupLabelType, SoupMessageAttachment, SoupMessageListVisibility, SoupMessageSender, SoupMessageSenderType, SoupPage, SoupProjectSoupPropertiesField, SoupPropertiesField, SoupProperty, SoupReminderReference, SoupReminderSchedule, SoupReminderSoupPropertiesField, SoupThreadInfo, SoupThreadReply, StarterDocumentsResponse, StreamEventsData, StreamEventsError, StreamEventsErrors, StreamEventsResponse, StreamEventsResponses, String, SuccessResponse, SurfaceState, SyncServiceVersionId, SystemSkillSummary, TagFilterMode, TaskFilters, TeamOutOfOfficeItem, TeamOutOfOfficeResponse, TeamRole, Thread, ThreadAnchor, ThreadOrigin, ThreadPatch, ThreadResponse, ThreadState, ToggleShareWithTeamData, ToggleShareWithTeamError, ToggleShareWithTeamErrors, ToggleShareWithTeamResponse, ToggleShareWithTeamResponses, TranscribeDictationData, TranscribeDictationError, TranscribeDictationErrors, TranscribeDictationResponse, TranscribeDictationResponses, TranscribeResponse, TranscriptSegmentRequest, TurnEndedMetadata, TurnStartedMetadata, TurnSummary, TypedSuccessResponse, TypedSuccessResponseGetDocumentResponseData, TypingAction, TypingInput, UnassignInitiativeTaskData, UnassignInitiativeTaskError, UnassignInitiativeTaskErrors, UnassignInitiativeTaskResponse, UnassignInitiativeTaskResponses, UnthreadedPdfUuidRequest, UpdateAgentData, UpdateAgentError, UpdateAgentErrors, UpdateAgentRequest, UpdateAgentResponse, UpdateAgentResponses, UpdateChannelSharePermission, UpdateCrmTeamSettingsRequest, UpdateInitiativeData, UpdateInitiativeError, UpdateInitiativeErrors, UpdateInitiativeRequest, UpdateInitiativeResponse, UpdateInitiativeResponses, UpdateMeetingRequest, 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, WaitingForInputMetadata, Webhook, WebhookEvent, WebhookFilter, WebhookScope, WebhookStatus, WebhookValidationTestEvent, WithCallId, WithChannelId, WithDocumentId, WithProjectId } from './types.gen';
+export type { AccessLevel, ActiveCallsResponse, ActiveCallSummary, ActiveMeeting, ActiveMeetingsResponse, ActivityType, AddFavoriteData, AddFavoriteError, AddFavoriteErrors, AddFavoriteRequest, AddFavoriteResponse, AddFavoriteResponses, AddParticipantsData, AddParticipantsError, AddParticipantsErrors, AddParticipantsRequest, AddParticipantsResponses, AddPinHandlerData, AddPinHandlerError, AddPinHandlerErrors, AddPinHandlerResponse, AddPinHandlerResponses, AddPinRequest, Agent, AgentActionId, AgentChannelScope, AgentMcpServer, AgentMcpServers, AgentPullRequestState, AgentSessionFilters, AgentSessionLifecycleEvent, 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, AssignInitiativeTasksData, AssignInitiativeTasksError, AssignInitiativeTasksErrors, AssignInitiativeTasksResponse, AssignInitiativeTasksResponses, AssignTasksRequest, AssignTasksResponse, AssignTasksResult, AssignTaskStatus, AttachmentChange, AttendeeResponseStatus, BasicDocument, BasicDocumentSubType, BomPart, Bot, BotChannel, BotChannelType, BotId, BotKind, BotOwner, BotOwnerProfile, BotSenderProfile, BotToken, BranchNameResponse, BTreeMap, BulkWakeupRequest, BulkWakeupResponse, BulkWakeupSyncServiceDocumentsData, BulkWakeupSyncServiceDocumentsErrors, BulkWakeupSyncServiceDocumentsResponse, BulkWakeupSyncServiceDocumentsResponses, CalendarAttendee, CalendarEvent, CalendarEventFilters, CalendarEventSourceContent, CalendarMentionEvent, CalendarMentionPreviewItem, CalendarMentionPreviewKind, CalendarMentionPreviewRequest, CalendarMentionPreviewRequestItem, CalendarMentionPreviewResponse, CalendarOccurrence, CalendarOccurrenceItem, CalendarOccurrenceResponse, CalendarSyncStatus, CallActiveResponse, CallFilters, CallRecord, CallRecordGuest, CallRecordParticipant, CallRecordPreview, CallRecordPreviewData, CallRecordTranscriptSegment, CallStatus, CallTokenResponse, CallWebhookData, CallWebhookError, CallWebhookErrors, CallWebhookResponses, Channel, ChannelCreatedMetadata, ChannelDeletedMetadata, ChannelEventAttachment, ChannelFilters, ChannelJoinCodeResponse, ChannelLabel, ChannelLabelRule, ChannelLabelsList, 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, CommandFailure, CommandRejectedMetadata, Comment, CommentThread, ConferenceProvider, CopyDocumentData, CopyDocumentError, CopyDocumentErrors, CopyDocumentQueryParams, CopyDocumentRequest, CopyDocumentResponse, CopyDocumentResponse2, CopyDocumentResponses, CountedReaction, CreateAgentData, CreateAgentError, CreateAgentErrors, CreateAgentRequest, CreateAgentResponse, CreateAgentResponses, CreateAnchorData, CreateAnchorError, CreateAnchorErrors, CreateAnchorResponse, CreateAnchorResponses, CreateBotRequest, CreateBulkDocumentResponse, CreateBulkDocumentResponseData, CreateChannelData, CreateChannelError, CreateChannelErrors, CreateChannelLabelData, CreateChannelLabelError, CreateChannelLabelErrors, CreateChannelLabelRequest, CreateChannelLabelResponse, CreateChannelLabelResponses, CreateChannelRequest, CreateChannelResponse, CreateChannelResponse2, CreateChannelResponses, CreateChannelScopedBotData, CreateChannelScopedBotError, CreateChannelScopedBotErrors, CreateChannelScopedBotRequest, CreateChannelScopedBotResponse, CreateChannelScopedBotResponse2, CreateChannelScopedBotResponses, CreateCollabSurfaceTokenData, CreateCollabSurfaceTokenError, CreateCollabSurfaceTokenErrors, CreateCollabSurfaceTokenResponse, CreateCollabSurfaceTokenResponses, 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, CreateInitiativeData, CreateInitiativeError, CreateInitiativeErrors, CreateInitiativeRequest, CreateInitiativeResponse, CreateInitiativeResponses, CreateInstructionsDocumentResponse, CreateInstructionsHandlerData, CreateInstructionsHandlerError, CreateInstructionsHandlerErrors, CreateInstructionsHandlerResponse, CreateInstructionsHandlerResponses, CreateMarkdownDocumentRequest, CreateMarkdownDocumentResponse, CreateMarkdownHandlerData, CreateMarkdownHandlerError, CreateMarkdownHandlerErrors, CreateMarkdownHandlerResponse, CreateMarkdownHandlerResponses, CreateMeetingRequest, 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, CrmStageInput, CrmStageResponse, CrmStagesResponse, CrmTeamSettingsResponse, CrmThread, CustomSpeakerAssignment, DataType, DeleteAnchorData, DeleteAnchorError, DeleteAnchorErrors, DeleteAnchorInfo, DeleteAnchorResponse, DeleteAnchorResponses, DeleteCallRecordData, DeleteCallRecordError, DeleteCallRecordErrors, DeleteCallRecordResponse, DeleteCallRecordResponses, DeleteChannelData, DeleteChannelError, DeleteChannelErrors, DeleteChannelLabelData, DeleteChannelLabelError, DeleteChannelLabelErrors, DeleteChannelLabelResponse, DeleteChannelLabelResponses, 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, DeleteInitiativeData, DeleteInitiativeError, DeleteInitiativeErrors, DeleteInitiativeResponse, DeleteInitiativeResponses, DeleteMessageData, DeleteMessageError, DeleteMessageErrors, DeleteMessageQuery, DeleteMessageResponse, DeleteMessageResponses, DeleteProjectHandlerData, DeleteProjectHandlerError, DeleteProjectHandlerErrors, DeleteProjectHandlerResponse, DeleteProjectHandlerResponses, DeleteReminderData, DeleteReminderError, DeleteReminderErrors, DeleteReminderResponse, DeleteReminderResponses, DeleteSelfHarnessData, DeleteSelfHarnessError, DeleteSelfHarnessErrors, DeleteSelfHarnessResponse, DeleteSelfHarnessResponses, DeleteThreadInfo, DeleteUnthreadedAnchorRequest, DeleteUnthreadedAnchorResponse, DeleteUnthreadedPdfAnchorRequest, DeleteUserApiKeyData, DeleteUserApiKeyError, DeleteUserApiKeyErrors, DeleteUserApiKeyResponse, DeleteUserApiKeyResponses, DeleteUserDocumentViewLocationData, DeleteUserDocumentViewLocationError, DeleteUserDocumentViewLocationErrors, DeleteUserDocumentViewLocationResponse, DeleteUserDocumentViewLocationResponses, DeleteViewHandlerData, DeleteViewHandlerError, DeleteViewHandlerErrors, DeleteViewHandlerResponses, DeleteWebhookData, DeleteWebhookError, DeleteWebhookErrors, DeleteWebhookResponse, DeleteWebhookResponses, DescriptionDocumentId, DocumentBasic, DocumentContent, DocumentContentLocation, DocumentContentState, DocumentContentUploadedMetadata, DocumentCopiedMetadata, DocumentCreatedMetadata, DocumentDeletedMetadata, DocumentFilters, DocumentId, DocumentInteractionMetadata, DocumentMetadata, DocumentMetadataWithContent, DocumentPermissionsToken, DocumentPermissionsTokenRequest, DocumentPermissionsTokenResponse, DocumentPreview, DocumentPreviewData, DocumentPreviewDataSubType, DocumentPurgedMetadata, DocumentResponse, DocumentResponseMetadata, DocumentResponseMetadataWithContent, DocumentStorageServiceApiVersion, DocumentSubType, DocumentSyncContentUpdatedMetadata, DocumentSyncEditor, DocumentTeamShareResponse, 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, EntityMessageCreateData, EntityMessageCreateResponse, EntityMessageCreateResponses, EntityMessageDeleteMessageData, EntityMessageDeleteMessageResponse, EntityMessageDeleteMessageResponses, EntityMessageDeleteThreadData, EntityMessageDeleteThreadResponse, EntityMessageDeleteThreadResponses, EntityMessageEditData, EntityMessageEditResponse, EntityMessageEditResponses, EntityMessageGetMessageData, EntityMessageGetMessageResponse, EntityMessageGetMessageResponses, EntityMessageGetThreadData, EntityMessageGetThreadResponse, EntityMessageGetThreadResponses, EntityMessageLegacyData, EntityMessageLegacyResponse, EntityMessageLegacyResponses, EntityMessagePatchThreadData, EntityMessagePatchThreadResponse, EntityMessagePatchThreadResponses, EntityMessageReactData, EntityMessageReactResponse, EntityMessageReactResponses, EntityMessageTypingData, EntityMessageTypingResponse, EntityMessageTypingResponses, EntityPermission, EntityPermissionResponse, 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, GetBotOwnerProfilesData, GetBotOwnerProfilesError, GetBotOwnerProfilesErrors, GetBotOwnerProfilesResponse, GetBotOwnerProfilesResponses, GetCallRecordData, GetCallRecordError, GetCallRecordErrors, GetCallRecordResponse, GetCallRecordResponses, GetChannelAttachmentsData, GetChannelAttachmentsError, GetChannelAttachmentsErrors, GetChannelAttachmentsResponse, GetChannelAttachmentsResponses, GetChannelData, GetChannelError, GetChannelErrors, GetChannelJoinLinkData, GetChannelJoinLinkError, GetChannelJoinLinkErrors, GetChannelJoinLinkResponse, GetChannelJoinLinkResponses, GetChannelMessagesCatchUpData, GetChannelMessagesCatchUpError, GetChannelMessagesCatchUpErrors, GetChannelMessagesCatchUpResponse, GetChannelMessagesCatchUpResponses, 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, GetForeignEntityBySourceData, GetForeignEntityBySourceError, GetForeignEntityBySourceErrors, GetForeignEntityBySourceResponse, GetForeignEntityBySourceResponses, GetForeignEntityData, GetForeignEntityError, GetForeignEntityErrors, GetForeignEntityResponse, GetForeignEntityResponses, GetHarnessPairingData, GetHarnessPairingError, GetHarnessPairingErrors, GetHarnessPairingResponse, GetHarnessPairingResponses, GetHistoryHandlerData, GetHistoryHandlerError, GetHistoryHandlerErrors, GetHistoryHandlerResponse, GetHistoryHandlerResponses, GetInitiativeData, GetInitiativeError, GetInitiativeErrors, GetInitiativeResponse, GetInitiativeResponses, GetInstructionsDocumentResponse, GetInstructionsHandlerData, GetInstructionsHandlerError, GetInstructionsHandlerErrors, GetInstructionsHandlerResponse, GetInstructionsHandlerResponses, GetItemsSoupData, GetItemsSoupError, GetItemsSoupErrors, GetItemsSoupResponse, GetItemsSoupResponses, GetLocationHandlerData, GetLocationHandlerError, GetLocationHandlerErrors, GetLocationHandlerResponse, GetLocationHandlerResponses, 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, GetSelfHarnessData, GetSelfHarnessError, GetSelfHarnessErrors, GetSelfHarnessResponse, GetSelfHarnessResponses, 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, GuestId, GuestJoinRequest, HandlerData, HandlerError, HandlerErrors, HandlerResponse, HandlerResponses, Harness, HarnessAgent, HarnessId, HarnessOwner, HarnessSession, HashMap, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, HighlightType, ImportedAuthor, InFlightTurnSummary, IngestTranscriptData, IngestTranscriptError, IngestTranscriptErrors, IngestTranscriptResponses, InitializeUserDocumentsData, InitializeUserDocumentsError, InitializeUserDocumentsErrors, InitializeUserDocumentsResponse, InitializeUserDocumentsResponses, InitiativeDetail, InitiativeFilters, InitiativeId, InitiativeList, InitiativeSummary, InputReceivedMetadata, InstallSyncData, InstallSyncErrors, InteractionReason, InviteMeetingRequest, InviteMeetingUsersRequest, 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, ListChannelLabelsData, ListChannelLabelsError, ListChannelLabelsErrors, ListChannelLabelsResponse, ListChannelLabelsResponses, 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, ListHarnessSessionsData, ListHarnessSessionsError, ListHarnessSessionsErrors, ListHarnessSessionsResponse, ListHarnessSessionsResponses, ListInitiativesData, ListInitiativesError, ListInitiativesErrors, ListInitiativesResponse, ListInitiativesResponses, ListOccurrencesData, ListOccurrencesErrors, ListOccurrencesResponse, ListOccurrencesResponses, ListRemindersData, ListRemindersError, ListRemindersErrors, ListRemindersResponse, ListRemindersResponses, ListTeamOutOfOfficeData, ListTeamOutOfOfficeErrors, ListTeamOutOfOfficeResponse, ListTeamOutOfOfficeResponses, ListUserApiKeysData, ListUserApiKeysError, ListUserApiKeysErrors, ListUserApiKeysResponse, ListUserApiKeysResponses, ListWebhooksData, ListWebhooksError, ListWebhooksErrors, ListWebhooksResponse, ListWebhooksResponse2, ListWebhooksResponses, LocationResponseData, LocationResponseV3, MacroUserIdStr, Meeting, MeetingCancelData, MeetingCancelError, MeetingCancelErrors, MeetingCancelPreparationData, MeetingCancelPreparationError, MeetingCancelPreparationErrors, MeetingCancelPreparationResponse, MeetingCancelPreparationResponses, MeetingCancelResponse, MeetingCancelResponses, MeetingCreateData, MeetingCreateError, MeetingCreateErrors, MeetingCreateResponse, MeetingCreateResponses, MeetingGuestJoinData, MeetingGuestJoinError, MeetingGuestJoinErrors, MeetingGuestJoinResponse, MeetingGuestJoinResponses, MeetingGuestParticipantsData, MeetingGuestParticipantsError, MeetingGuestParticipantsErrors, MeetingGuestParticipantsResponse, MeetingGuestParticipantsResponses, MeetingInviteData, MeetingInviteError, MeetingInviteErrors, MeetingInvitePermissions, MeetingInvitePermissionsData, MeetingInvitePermissionsError, MeetingInvitePermissionsErrors, MeetingInvitePermissionsResponse, MeetingInvitePermissionsResponses, MeetingInviteResponse, MeetingInviteResponses, MeetingInviteUsersData, MeetingInviteUsersError, MeetingInviteUsersErrors, MeetingInviteUsersResponse, MeetingInviteUsersResponses, MeetingJoinData, MeetingJoinError, MeetingJoinErrors, MeetingJoinResponse, MeetingJoinResponses, MeetingLeaveData, MeetingLeaveError, MeetingLeaveErrors, MeetingLeaveResponse, MeetingLeaveResponses, MeetingListActiveData, MeetingListActiveError, MeetingListActiveErrors, MeetingListActiveResponse, MeetingListActiveResponses, MeetingListData, MeetingListError, MeetingListErrors, MeetingListResponse, MeetingListResponses, MeetingLookupData, MeetingLookupError, MeetingLookupErrors, MeetingLookupResponse, MeetingLookupResponses, MeetingParticipant, MeetingParticipants, MeetingParticipantsData, MeetingParticipantsError, MeetingParticipantsErrors, MeetingParticipantsResponse, MeetingParticipantsResponses, MeetingPreparation, MeetingPrepareData, MeetingPrepareError, MeetingPrepareErrors, MeetingPrepareResponse, MeetingPrepareResponses, MeetingShareData, MeetingShareError, MeetingShareErrors, MeetingShareResponse, MeetingShareResponses, MeetingsResponse, MeetingToken, MeetingUpdateData, MeetingUpdateError, MeetingUpdateErrors, MeetingUpdateResponse, MeetingUpdateResponses, MentionPreviewsData, MentionPreviewsErrors, MentionPreviewsResponse, MentionPreviewsResponses, Mentions, Message, MessageAttachment, MessageChange, MessageCursor, MessageDirection, MessageEvent, MessageListItem, MessagePage, MessageParent, MessagePatch, MessageThread, MessageThreadPreview, MessageTimelineData, MessageTimelineQuery, MessageTimelineResponse, MessageTimelineResponses, NewAttachment, NewChannelAttachment, NewThreadAnchor, NotificationFilters, NotificationState, PairingDetails, Params, ParticipantRole, PatchBotRequest, PatchChannelData, PatchChannelError, PatchChannelErrors, PatchChannelRequest, PatchChannelResponse, PatchChannelResponses, PatchMessageData, PatchMessageError, PatchMessageErrors, PatchMessageNotificationPolicy, 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, PostMessage, PostMessageData, PostMessageError, PostMessageErrors, PostMessageNotificationPolicy, 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, PreviewSmartTagData, PreviewSmartTagError, PreviewSmartTagErrors, PreviewSmartTagResponse, PreviewSmartTagResponses, Project, ProjectDeleteResponseData, ProjectDocumentStatus, ProjectFilters, ProjectPreview, ProjectPreviewData, PropertyDefinition, PropertyFilter, PropertyInput, PropertyOwner, PropertyValue, PutCrmTeamSettingsData, PutCrmTeamSettingsError, PutCrmTeamSettingsErrors, PutCrmTeamSettingsResponse, PutCrmTeamSettingsResponses, PutCrmTeamStagesData, PutCrmTeamStagesError, PutCrmTeamStagesErrors, PutCrmTeamStagesResponse, PutCrmTeamStagesResponses, ReactionAction, ReactionInput, 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, RenameChannelLabelData, RenameChannelLabelError, RenameChannelLabelErrors, RenameChannelLabelRequest, RenameChannelLabelResponse, RenameChannelLabelResponses, ReorderFavoritesData, ReorderFavoritesError, ReorderFavoritesErrors, ReorderFavoritesRequest, ReorderFavoritesResponses, ReorderPinRequest, ReorderPinsHandlerData, ReorderPinsHandlerError, ReorderPinsHandlerErrors, ReorderPinsHandlerResponse, ReorderPinsHandlerResponses, ReplaceCrmStagesRequest, RequestedHarnessScope, ResetCrmTeamStagesData, ResetCrmTeamStagesError, ResetCrmTeamStagesErrors, ResetCrmTeamStagesResponse, ResetCrmTeamStagesResponses, 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, SessionDeletedMetadata, SessionIdentity, SessionMentionedMetadata, SessionOpenedMetadata, SessionRenamedMetadata, SessionSettledMetadata, SessionStoppedMetadata, SetChannelLabelData, SetChannelLabelError, SetChannelLabelErrors, SetChannelLabelRequest, SetChannelLabelResponse, SetChannelLabelResponses, SetChannelPictureData, SetChannelPictureError, SetChannelPictureErrors, SetChannelPictureRequest, SetChannelPictureResponse, SetChannelPictureResponses, SetCompanyHiddenData, SetCompanyHiddenError, SetCompanyHiddenErrors, SetCompanyHiddenRequest, SetCompanyHiddenResponse, SetCompanyHiddenResponses, SetCompanyNameRequest, SetContactHiddenData, SetContactHiddenError, SetContactHiddenErrors, SetContactHiddenRequest, SetContactHiddenResponse, SetContactHiddenResponses, SetContactNameRequest, SetCrmCompanyNameData, SetCrmCompanyNameError, SetCrmCompanyNameErrors, SetCrmCompanyNameResponse, SetCrmCompanyNameResponses, SetCrmContactNameData, SetCrmContactNameError, SetCrmContactNameErrors, SetCrmContactNameResponse, SetCrmContactNameResponses, SetDocumentTeamShareData, SetDocumentTeamShareError, SetDocumentTeamShareErrors, SetDocumentTeamShareRequest, SetDocumentTeamShareResponse, SetDocumentTeamShareResponses, SetEmailSyncData, SetEmailSyncError, SetEmailSyncErrors, SetEmailSyncRequest, SetEmailSyncResponse, SetEmailSyncResponses, SetPropertyValue, SharedEmailFilter, SharePermissionV2, ShortIdResponse, SimpleMention, SimpleSaveData, SimpleSaveError, SimpleSaveErrors, SimpleSaveResponse, SimpleSaveResponses, SmartTagChannelMatch, SmartTagPreview, SoupAgentSessionSoupPropertiesField, SoupApiItem, SoupApiSort, SoupApiSortDirection, SoupAttachment, SoupCalendarEventSoupPropertiesField, SoupCalendarEventTime, SoupCallRecordGuest, SoupCallRecordParticipant, SoupCallRecordSoupPropertiesField, SoupChannel, SoupChannelThread, SoupChatSoupPropertiesField, SoupContact, SoupCountedReaction, SoupCrmCompanySoupPropertiesField, SoupCrmDomain, SoupDocumentSoupPropertiesField, SoupDocumentSubType, SoupEmailThreadPreview, SoupEnrichedEmailThreadPreviewSoupPropertiesField, SoupForeignEntity, SoupInitiativeSoupPropertiesField, SoupItem, SoupLabel, SoupLabelListVisibility, SoupLabelType, SoupMessageAttachment, SoupMessageListVisibility, SoupMessageSender, SoupMessageSenderType, SoupPage, SoupProjectSoupPropertiesField, SoupPropertiesField, SoupProperty, SoupReminderReference, SoupReminderSchedule, SoupReminderSoupPropertiesField, SoupThreadInfo, SoupThreadReply, StarterDocumentsResponse, StreamEventsData, StreamEventsError, StreamEventsErrors, StreamEventsResponse, StreamEventsResponses, String, SuccessResponse, SurfaceState, SyncServiceVersionId, SystemSkillSummary, TagFilterMode, TaskFilters, TeamOutOfOfficeItem, TeamOutOfOfficeResponse, TeamRole, Thread, ThreadAnchor, ThreadOrigin, ThreadPatch, ThreadResponse, ThreadState, ToggleShareWithTeamData, ToggleShareWithTeamError, ToggleShareWithTeamErrors, ToggleShareWithTeamResponse, ToggleShareWithTeamResponses, TranscribeDictationData, TranscribeDictationError, TranscribeDictationErrors, TranscribeDictationResponse, TranscribeDictationResponses, TranscribeResponse, TranscriptSegmentRequest, TurnEndedMetadata, TurnStartedMetadata, TurnSummary, TypedSuccessResponse, TypedSuccessResponseGetDocumentResponseData, TypingAction, TypingInput, UnassignInitiativeTaskData, UnassignInitiativeTaskError, UnassignInitiativeTaskErrors, UnassignInitiativeTaskResponse, UnassignInitiativeTaskResponses, UnthreadedPdfUuidRequest, UpdateAgentData, UpdateAgentError, UpdateAgentErrors, UpdateAgentRequest, UpdateAgentResponse, UpdateAgentResponses, UpdateChannelSharePermission, UpdateCrmTeamSettingsRequest, UpdateInitiativeData, UpdateInitiativeError, UpdateInitiativeErrors, UpdateInitiativeRequest, UpdateInitiativeResponse, UpdateInitiativeResponses, UpdateMeetingRequest, 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, WaitingForInputMetadata, Webhook, WebhookEvent, WebhookFilter, WebhookScope, WebhookStatus, WebhookValidationTestEvent, WithCallId, WithChannelId, WithDocumentId, WithProjectId } from './types.gen';
diff --git a/packages/sdk/generated/storage/types.gen.ts b/packages/sdk/generated/storage/types.gen.ts
index 09d9aef19d..4d90bbee09 100644
--- a/packages/sdk/generated/storage/types.gen.ts
+++ b/packages/sdk/generated/storage/types.gen.ts
@@ -260,6 +260,12 @@ export type AgentSessionLifecycleEvent = {
* The runtime answered a turn.
*/
metadata: TurnEndedMetadata;
+} | {
+ event_type: 'agent_session.command_rejected';
+ /**
+ * An accepted command was refused before runtime execution.
+ */
+ metadata: CommandRejectedMetadata;
} | {
event_type: 'agent_session.settled';
/**
@@ -3176,6 +3182,47 @@ export type CollabSurfaceTokenResponse = {
token: string;
};
+/**
+ * Sanitized public details of a command refused before runtime execution.
+ */
+export type CommandFailure = {
+ /**
+ * Stable public denial or unavailability code.
+ */
+ code: string;
+ /**
+ * Public explanation, never an internal error report.
+ */
+ message: string;
+ /**
+ * Whether retrying later may succeed without a policy change.
+ */
+ retryable: boolean;
+};
+
+/**
+ * An accepted command was refused before it could start a runtime turn.
+ */
+export type CommandRejectedMetadata = {
+ /**
+ * The command that will not execute.
+ */
+ action_id: AgentActionId;
+ actor?: null | MacroUserIdStr;
+ /**
+ * The command's thread announcement, when one was created.
+ */
+ announcement_message_id?: string | null;
+ /**
+ * Safe details for clients and downstream consumers.
+ */
+ failure: CommandFailure;
+ /**
+ * The session.
+ */
+ identity: SessionIdentity;
+};
+
export type Comment = {
commentId: number;
createdAt?: string | null;
diff --git a/packages/sdk/specs/agent-harness.json b/packages/sdk/specs/agent-harness.json
index 2d529594a7..b23e9212d1 100644
--- a/packages/sdk/specs/agent-harness.json
+++ b/packages/sdk/specs/agent-harness.json
@@ -314,6 +314,16 @@
}
}
},
+ "402": {
+ "description": "AI allowance exhausted",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/AiAdmissionErrorBody"
+ }
+ }
+ }
+ },
"403": {
"description": "",
"content": {
@@ -353,6 +363,16 @@
}
}
}
+ },
+ "503": {
+ "description": "AI usage validation unavailable; retry later",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/AiAdmissionErrorBody"
+ }
+ }
+ }
}
}
}
@@ -836,6 +856,16 @@
}
}
},
+ "402": {
+ "description": "AI allowance exhausted",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/AiAdmissionErrorBody"
+ }
+ }
+ }
+ },
"403": {
"description": "",
"content": {
@@ -865,6 +895,21 @@
}
}
}
+ },
+ "503": {
+ "description": "AI usage validation unavailable, or replica draining; retry later",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/AiAdmissionErrorBody"
+ }
+ },
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
}
}
}
@@ -2308,6 +2353,21 @@
}
}
},
+ "AiAdmissionErrorBody": {
+ "type": "object",
+ "description": "Public admission error payload. Handlers with additional fields can reuse the\ndomain error's code and message and [`admission_status`].",
+ "required": ["error", "code"],
+ "properties": {
+ "code": {
+ "type": "string",
+ "description": "Stable denial or unavailability code."
+ },
+ "error": {
+ "type": "string",
+ "description": "Human-readable explanation, without internal billing diagnostics."
+ }
+ }
+ },
"BotId": {
"type": "string"
},
diff --git a/packages/sdk/specs/cognition.json b/packages/sdk/specs/cognition.json
index 0253b8d90c..a97e82efa5 100644
--- a/packages/sdk/specs/cognition.json
+++ b/packages/sdk/specs/cognition.json
@@ -1149,8 +1149,28 @@
"400": {
"description": "Unknown import source"
},
+ "402": {
+ "description": "AI allowance exhausted",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/AiAdmissionErrorBody"
+ }
+ }
+ }
+ },
"500": {
"description": "Internal server error"
+ },
+ "503": {
+ "description": "AI usage validation unavailable; retry later",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/AiAdmissionErrorBody"
+ }
+ }
+ }
}
}
}
@@ -2030,6 +2050,16 @@
}
}
}
+ },
+ "503": {
+ "description": "AI usage validation unavailable — retry later",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ChatMessageError"
+ }
+ }
+ }
}
}
}
@@ -2113,7 +2143,14 @@
"description": "Unauthorized"
},
"402": {
- "description": "Payment required"
+ "description": "Payment required",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/StructuredCompletionError"
+ }
+ }
+ }
},
"500": {
"description": "Internal error",
@@ -2124,6 +2161,16 @@
}
}
}
+ },
+ "503": {
+ "description": "AI usage validation unavailable — retry later",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/StructuredCompletionError"
+ }
+ }
+ }
}
}
}
@@ -2151,6 +2198,21 @@
}
}
},
+ "AiAdmissionErrorBody": {
+ "type": "object",
+ "description": "Public admission error payload. Handlers with additional fields can reuse the\ndomain error's code and message and [`admission_status`].",
+ "required": ["error", "code"],
+ "properties": {
+ "code": {
+ "type": "string",
+ "description": "Stable denial or unavailability code."
+ },
+ "error": {
+ "type": "string",
+ "description": "Human-readable explanation, without internal billing diagnostics."
+ }
+ }
+ },
"AiFeature": {
"type": "string",
"description": "Everything we use AI for. The wire / DB form of each variant is its\n`snake_case` name.",
@@ -2579,7 +2641,7 @@
"properties": {
"code": {
"type": ["string", "null"],
- "description": "Stable machine-readable code for payment-required errors."
+ "description": "Stable machine-readable code for admission errors (402 or 503)."
},
"error": {
"type": "string"
@@ -4598,7 +4660,7 @@
"properties": {
"code": {
"type": ["string", "null"],
- "description": "Stable machine-readable code for payment-required errors."
+ "description": "Stable machine-readable code for admission errors (402 or 503)."
},
"error": {
"type": "string"
diff --git a/packages/sdk/specs/scheduled-action.json b/packages/sdk/specs/scheduled-action.json
index cdc331a606..00b6c827e0 100644
--- a/packages/sdk/specs/scheduled-action.json
+++ b/packages/sdk/specs/scheduled-action.json
@@ -431,6 +431,16 @@
}
}
},
+ "402": {
+ "description": "AI allowance exhausted",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/AiAdmissionErrorBody"
+ }
+ }
+ }
+ },
"404": {
"description": "",
"content": {
@@ -460,6 +470,16 @@
}
}
}
+ },
+ "503": {
+ "description": "AI usage validation unavailable; retry later",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/AiAdmissionErrorBody"
+ }
+ }
+ }
}
}
}
@@ -703,6 +723,21 @@
}
}
},
+ "AiAdmissionErrorBody": {
+ "type": "object",
+ "description": "Public admission error payload. Handlers with additional fields can reuse the\ndomain error's code and message and [`admission_status`].",
+ "required": ["error", "code"],
+ "properties": {
+ "code": {
+ "type": "string",
+ "description": "Stable denial or unavailability code."
+ },
+ "error": {
+ "type": "string",
+ "description": "Human-readable explanation, without internal billing diagnostics."
+ }
+ }
+ },
"CreateScheduledAction": {
"oneOf": [
{
diff --git a/packages/sdk/specs/storage.json b/packages/sdk/specs/storage.json
index a42d94634c..7e0fbcf447 100644
--- a/packages/sdk/specs/storage.json
+++ b/packages/sdk/specs/storage.json
@@ -16023,6 +16023,21 @@
}
}
},
+ {
+ "type": "object",
+ "description": "An accepted command was refused before runtime execution.",
+ "required": ["metadata", "event_type"],
+ "properties": {
+ "event_type": {
+ "type": "string",
+ "enum": ["agent_session.command_rejected"]
+ },
+ "metadata": {
+ "$ref": "#/components/schemas/CommandRejectedMetadata",
+ "description": "An accepted command was refused before runtime execution."
+ }
+ }
+ },
{
"type": "object",
"description": "A turn ended with nothing queued behind it.",
@@ -20250,6 +20265,60 @@
}
}
},
+ "CommandFailure": {
+ "type": "object",
+ "description": "Sanitized public details of a command refused before runtime execution.",
+ "required": ["code", "message", "retryable"],
+ "properties": {
+ "code": {
+ "type": "string",
+ "description": "Stable public denial or unavailability code."
+ },
+ "message": {
+ "type": "string",
+ "description": "Public explanation, never an internal error report."
+ },
+ "retryable": {
+ "type": "boolean",
+ "description": "Whether retrying later may succeed without a policy change."
+ }
+ }
+ },
+ "CommandRejectedMetadata": {
+ "type": "object",
+ "description": "An accepted command was refused before it could start a runtime turn.",
+ "required": ["identity", "action_id", "failure"],
+ "properties": {
+ "action_id": {
+ "$ref": "#/components/schemas/AgentActionId",
+ "description": "The command that will not execute."
+ },
+ "actor": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/MacroUserIdStr",
+ "description": "Who submitted the command, if acting on a user's behalf."
+ }
+ ]
+ },
+ "announcement_message_id": {
+ "type": ["string", "null"],
+ "format": "uuid",
+ "description": "The command's thread announcement, when one was created."
+ },
+ "failure": {
+ "$ref": "#/components/schemas/CommandFailure",
+ "description": "Safe details for clients and downstream consumers."
+ },
+ "identity": {
+ "$ref": "#/components/schemas/SessionIdentity",
+ "description": "The session."
+ }
+ }
+ },
"Comment": {
"type": "object",
"required": ["commentId", "threadId", "owner", "text"],
diff --git a/packages/sdk/src/events/hydrate/agentSession.ts b/packages/sdk/src/events/hydrate/agentSession.ts
index 66475fbc61..6ef2c3ecb4 100644
--- a/packages/sdk/src/events/hydrate/agentSession.ts
+++ b/packages/sdk/src/events/hydrate/agentSession.ts
@@ -95,6 +95,17 @@ export function hydrateAgentSessionEvent(
metadata.announcement_message_id,
),
}))
+ .with({ event_type: 'agent_session.command_rejected' }, ({ metadata }) => ({
+ event_type: 'agent_session.command_rejected' as const,
+ metadata,
+ ...sessionHandles(client, metadata.identity),
+ actor: actorHandle(client, metadata.actor),
+ announcement: announcementHandle(
+ client,
+ metadata.identity,
+ metadata.announcement_message_id,
+ ),
+ }))
.with({ event_type: 'agent_session.settled' }, ({ metadata }) => ({
event_type: 'agent_session.settled' as const,
metadata,
diff --git a/packages/sdk/tests/agent-session-hydrate.test.ts b/packages/sdk/tests/agent-session-hydrate.test.ts
index 93beb661b9..7332c0643a 100644
--- a/packages/sdk/tests/agent-session-hydrate.test.ts
+++ b/packages/sdk/tests/agent-session-hydrate.test.ts
@@ -75,6 +75,59 @@ describe('hydrateAgentSessionEvent', () => {
expect(event.metadata.question).toBe('Tea or coffee?');
});
+ test('command rejection preserves failure details and hydrates session, actor, and chip', () => {
+ const metadata = {
+ identity,
+ action_id: '01a00000-0000-7000-8000-000000000004',
+ actor: 'macro|[email protected]',
+ announcement_message_id: '01a00000-0000-7000-8000-000000000005',
+ failure: {
+ code: 'ai_allowance_exhausted',
+ message: 'AI allowance exhausted',
+ retryable: false,
+ },
+ };
+ const event = hydrateAgentSessionEvent(client, {
+ event_type: 'agent_session.command_rejected',
+ metadata,
+ });
+ if (event.event_type !== 'agent_session.command_rejected')
+ throw new Error(event.event_type);
+
+ expect(event.session.id).toBe(identity.session_id);
+ expect(event.owner.id).toBe(identity.owner_id);
+ expect(event.channel?.id).toBe(identity.origin.channel_id);
+ expect(event.thread).toBeDefined();
+ expect(event.actor?.id).toBe(metadata.actor);
+ expect(event.announcement?.id).toBe(metadata.announcement_message_id);
+ expect(event.metadata).toBe(metadata);
+ });
+
+ test('command rejection tolerates absent optional handles', () => {
+ const event = hydrateAgentSessionEvent(client, {
+ event_type: 'agent_session.command_rejected',
+ metadata: {
+ identity: { ...identity, origin: null },
+ action_id: '01a00000-0000-7000-8000-000000000004',
+ failure: {
+ code: 'ai_billing_unavailable',
+ message: 'AI usage validation unavailable',
+ retryable: true,
+ },
+ },
+ });
+ if (event.event_type !== 'agent_session.command_rejected')
+ throw new Error(event.event_type);
+
+ expect(event.session.id).toBe(identity.session_id);
+ expect(event.owner.id).toBe(identity.owner_id);
+ expect(event.channel).toBeUndefined();
+ expect(event.thread).toBeUndefined();
+ expect(event.actor).toBeUndefined();
+ expect(event.announcement).toBeUndefined();
+ expect(event.metadata.failure.retryable).toBe(true);
+ });
+
test('deleted carries only the identity handles', () => {
const event = hydrateAgentSessionEvent(client, {
event_type: 'agent_session.deleted',
diff --git a/services/agent_harness_service/Cargo.toml b/services/agent_harness_service/Cargo.toml
index 80e35fc8ae..16233e65de 100644
--- a/services/agent_harness_service/Cargo.toml
+++ b/services/agent_harness_service/Cargo.toml
@@ -17,6 +17,9 @@ name = "agent_harness_service_doppler_config"
path = "src/doppler_config.rs"
[dependencies]
+ai_billing = { path = "../../crates/ai_billing", features = ["pg-admission"] }
+roles_and_permissions = { path = "../../crates/roles_and_permissions", default-features = false, features = ["outbound"] }
+teams = { path = "../../crates/teams", default-features = false, features = ["outbound"] }
initiative = { path = "../../crates/initiative", default-features = false, features = ["postgres"] }
crm = { path = "../../crates/crm", default-features = false, features = ["lookup"] }
codex_cloud_agents = { path = "../../crates/codex_cloud_agents" }
diff --git a/services/agent_harness_service/src/config.rs b/services/agent_harness_service/src/config.rs
index af35830e1c..5f0a1bd316 100644
--- a/services/agent_harness_service/src/config.rs
+++ b/services/agent_harness_service/src/config.rs
@@ -62,6 +62,9 @@ fn default_pipedream_environment() -> String {
#[derive(macro_config::MacroConfig)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub struct Config {
+ /// Default-off quota admission and prospective usage counting.
+ #[macro_config_default(ai_usage::AiUsageEnforcement::Disabled)]
+ pub enable_ai_usage_enforcement: ai_usage::AiUsageEnforcement,
/// OAuth encryption key; deployments without a key do not advertise sign-in.
pub claude_oauth_kms_key_id: ClaudeOauthKmsKeyId,
/// The environment we are in.
@@ -239,7 +242,11 @@ impl Config {
/// Load the configuration from the environment.
pub fn from_env() -> anyhow::Result<Self> {
- macro_config::ConfigLoader::load::<Config>()
- .context("failed to load agent harness service config")
+ let enforcement = ai_usage::config::load_ai_usage_enforcement()
+ .map_err(|error| anyhow::anyhow!("{error}"))?;
+ let mut config = macro_config::ConfigLoader::load::<Config>()
+ .context("failed to load agent harness service config")?;
+ config.enable_ai_usage_enforcement = enforcement;
+ Ok(config)
}
}
diff --git a/services/agent_harness_service/src/main.rs b/services/agent_harness_service/src/main.rs
index 65de43789c..003c74cce6 100644
--- a/services/agent_harness_service/src/main.rs
+++ b/services/agent_harness_service/src/main.rs
@@ -288,6 +288,13 @@ async fn run() -> anyhow::Result<()> {
macro_queues::NotificationIngressQueue::new().to_string(),
),
});
+ let admission = ai_billing::composition::pg_admission_service(
+ pool.clone(),
+ config.environment,
+ config.enable_ai_usage_enforcement,
+ );
+ let recorder =
+ ai_usage::pg_recorder_with_enforcement(pool.clone(), config.enable_ai_usage_enforcement);
let lifecycle_publisher = Arc::new(BrokerLifecyclePublisher::new(broker.clone()));
let sessions = AgentSessionServiceImpl::new(
session_repo.clone(),
@@ -296,7 +303,10 @@ async fn run() -> anyhow::Result<()> {
connection_gateway.clone(),
session_audience.clone(),
),
- HaikuAgentSessionNameGenerator::new(ai_usage::pg_recorder(pool.clone())),
+ agent_session::domain::name_generation::AdmittedAgentSessionNameGenerator::new(
+ HaikuAgentSessionNameGenerator::new(recorder.clone()),
+ admission.clone(),
+ ),
turn_observer.clone(),
lifecycle_publisher.clone(),
replica,
@@ -448,10 +458,13 @@ async fn run() -> anyhow::Result<()> {
))));
let sessions = sessions.with_tool_catalog(Arc::clone(&tool_catalog));
- let tool_context =
- ai_tools::build_tool_service_context_from_env(pool.clone(), event_broker_tracker.clone())
- .await
- .context("failed to build the in-memory agent tool context")?;
+ let tool_context = ai_tools::build_tool_service_context_from_env(
+ pool.clone(),
+ event_broker_tracker.clone(),
+ config.enable_ai_usage_enforcement,
+ )
+ .await
+ .context("failed to build the in-memory agent tool context")?;
let inmem_model_engine: Arc<dyn TurnEngine> =
Arc::new(RigTurnEngine::new(pool.clone(), tool_context));
// A model provider cannot fetch images from a private local-stack hostname.
@@ -489,6 +502,7 @@ async fn run() -> anyhow::Result<()> {
&egress_base_url,
))),
)
+ .with_admission(admission.clone())
.with_dev_commands(enable_dev_commands),
};
// The sandbox provider serves every bot but the in-memory one, which the
@@ -571,7 +585,7 @@ async fn run() -> anyhow::Result<()> {
cursor_api_base_url(),
session_repo.clone(),
Arc::clone(&reachable_repositories),
- ai_usage::pg_recorder(pool.clone()),
+ recorder.clone(),
PostgresJournal {
pool: pool.clone(),
replica,
@@ -589,6 +603,7 @@ async fn run() -> anyhow::Result<()> {
),
),
)
+ .with_admission(admission.clone())
.with_pull_requests(session_pull_requests.clone())
.with_working_branches(session_working_branches);
let codex_connections: Option<Arc<dyn codex_connection::domain::ConnectionService>> = config
@@ -929,6 +944,7 @@ async fn run() -> anyhow::Result<()> {
// notification ingress channel messages use.
IngressAgentSessionNotifier::new(Arc::clone(&notifications)),
)
+ .with_admission(admission.clone())
.with_repositories(open_repositories),
);
let model_probe_timeout = std::time::Duration::from_secs(10);
@@ -1183,7 +1199,11 @@ async fn run() -> anyhow::Result<()> {
config.internal_api_key.clone(),
config.document_storage_service_auth_key.clone(),
config.agent_trigger_event_source,
- message_service,
+ trigger::TriggerServices {
+ recorder,
+ admission,
+ messages: message_service,
+ },
));
let egress_port = config.egress_port;
diff --git a/services/agent_harness_service/src/trigger.rs b/services/agent_harness_service/src/trigger.rs
index 3b0e9ad8a8..4c1da7c075 100644
--- a/services/agent_harness_service/src/trigger.rs
+++ b/services/agent_harness_service/src/trigger.rs
@@ -68,6 +68,17 @@ fn commit_message<M: MacroEventCollection + 'static>(
.map_err(|error| anyhow::anyhow!("failed to commit trigger event offset: {error:?}"))
}
+/// Shared domain services retained across trigger-consumer restarts.
+#[derive(Clone)]
+pub struct TriggerServices {
+ /// Recorder configured with the host's quota policy.
+ pub recorder: Arc<dyn ai_usage::UsageRecorder>,
+ /// Admission gate for Macro-funded inference.
+ pub admission: Arc<dyn ai_billing::AiAdmissionService>,
+ /// Message service used to announce task assignments.
+ pub messages: Arc<dyn MessageServiceApi>,
+}
+
/// Keeps the trigger consumer running across transient failures.
pub async fn supervise(
pool: PgPool,
@@ -75,7 +86,7 @@ pub async fn supervise(
internal_api_key: String,
document_storage_service_auth_key: String,
source: TriggerEventSource,
- messages: Arc<dyn MessageServiceApi>,
+ services: TriggerServices,
) {
loop {
if let Err(error) = run(
@@ -84,7 +95,7 @@ pub async fn supervise(
internal_api_key.clone(),
document_storage_service_auth_key.clone(),
source,
- messages.clone(),
+ services.clone(),
)
.await
{
@@ -100,12 +111,14 @@ async fn run(
internal_api_key: String,
document_storage_service_auth_key: String,
source: TriggerEventSource,
- messages: Arc<dyn MessageServiceApi>,
+ services: TriggerServices,
) -> anyhow::Result<()> {
- let lexical = LexicalClient::new(
- internal_api_key.clone(),
- LexicalServiceUrl::new()?.to_string(),
- );
+ let TriggerServices {
+ recorder,
+ admission,
+ messages,
+ } = services;
+ let lexical = LexicalClient::new(internal_api_key, LexicalServiceUrl::new()?.to_string());
let task_context = DssTaskAssignmentContext::new(
DocumentStorageServiceClient::new(
document_storage_service_auth_key,
@@ -113,7 +126,6 @@ async fn run(
),
lexical.clone(),
);
- let recorder = ai_usage::pg_recorder(pool.clone());
let images = VisionImageCaptioner::new(
static_file::outbound::CdnStaticFileRepo::new(StaticFileServiceUrl::new()?.to_string()),
recorder.clone(),
@@ -141,7 +153,8 @@ async fn run(
entity_access::outbound::PgAccessRepository::new(pool.clone()),
),
),
- );
+ )
+ .with_admission(admission);
let channel_types = ChannelRepoTypeLookup::new(PgChannelsRepo::new(pool));
let publisher = MacroEventBrokerService::new(
KafkaEventPublisher::new(&kafka_brokers)?,
diff --git a/services/agent_trigger_service/Cargo.toml b/services/agent_trigger_service/Cargo.toml
index 1af577ba48..242cb33bfb 100644
--- a/services/agent_trigger_service/Cargo.toml
+++ b/services/agent_trigger_service/Cargo.toml
@@ -9,6 +9,10 @@ name = "agent_trigger_service"
path = "src/main.rs"
[dependencies]
+ai_billing = { path = "../../crates/ai_billing", features = ["pg-admission"] }
+macro_env = { path = "../../crates/macro_env" }
+roles_and_permissions = { path = "../../crates/roles_and_permissions", default-features = false, features = ["outbound"] }
+teams = { path = "../../crates/teams", default-features = false, features = ["outbound"] }
initiative = { path = "../../crates/initiative", default-features = false, features = ["postgres"] }
crm = { path = "../../crates/crm", default-features = false, features = ["lookup"] }
agent_session = { path = "../../crates/agent_session" }
diff --git a/services/agent_trigger_service/src/config.rs b/services/agent_trigger_service/src/config.rs
index dfd1a58c87..51717d2a82 100644
--- a/services/agent_trigger_service/src/config.rs
+++ b/services/agent_trigger_service/src/config.rs
@@ -14,6 +14,12 @@ env_vars! {
#[derive(macro_config::MacroConfig)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub struct Config {
+ /// Default-off quota admission and prospective usage counting.
+ #[macro_config_default(ai_usage::AiUsageEnforcement::Disabled)]
+ pub enable_ai_usage_enforcement: ai_usage::AiUsageEnforcement,
+ /// Deployment environment; settlement remains disabled in this worker.
+ #[macro_config_default(macro_env::Environment::new_or_prod())]
+ pub environment: macro_env::Environment,
/// MacroDB connection URL.
pub database_url: DatabaseUrl,
/// Kafka bootstrap servers.
@@ -33,7 +39,11 @@ pub struct Config {
impl Config {
/// Loads configuration from the process environment.
pub fn from_env() -> anyhow::Result<Self> {
- macro_config::ConfigLoader::load::<Self>()
- .context("failed to load agent trigger service config")
+ let enforcement = ai_usage::config::load_ai_usage_enforcement()
+ .map_err(|error| anyhow::anyhow!("{error}"))?;
+ let mut config = macro_config::ConfigLoader::load::<Self>()
+ .context("failed to load agent trigger service config")?;
+ config.enable_ai_usage_enforcement = enforcement;
+ Ok(config)
}
}
diff --git a/services/agent_trigger_service/src/main.rs b/services/agent_trigger_service/src/main.rs
index 5aca9b6fb6..8daac406bc 100644
--- a/services/agent_trigger_service/src/main.rs
+++ b/services/agent_trigger_service/src/main.rs
@@ -111,6 +111,13 @@ async fn run() -> anyhow::Result<()> {
config.internal_api_key.clone(),
LexicalServiceUrl::new()?.to_string(),
);
+ let recorder =
+ ai_usage::pg_recorder_with_enforcement(pool.clone(), config.enable_ai_usage_enforcement);
+ let admission = ai_billing::composition::pg_admission_service(
+ pool.clone(),
+ config.environment,
+ config.enable_ai_usage_enforcement,
+ );
let task_context = DssTaskAssignmentContext::new(
DocumentStorageServiceClient::new(
config.document_storage_service_auth_key.clone(),
@@ -118,7 +125,6 @@ async fn run() -> anyhow::Result<()> {
),
lexical.clone(),
);
- let recorder = ai_usage::pg_recorder(pool.clone());
let images = VisionImageCaptioner::new(
static_file::outbound::CdnStaticFileRepo::new(StaticFileServiceUrl::new()?.to_string()),
recorder.clone(),
@@ -146,7 +152,8 @@ async fn run() -> anyhow::Result<()> {
entity_access::outbound::PgAccessRepository::new(pool.clone()),
),
),
- );
+ )
+ .with_admission(admission);
let channel_types = ChannelRepoTypeLookup::new(PgChannelsRepo::new(pool.clone()));
let publisher = MacroEventBrokerService::new(
KafkaEventPublisher::new(config.kafka_brokers.as_ref())?,
diff --git a/services/authentication_service/Cargo.toml b/services/authentication_service/Cargo.toml
index 744babd389..ff22c3f26b 100644
--- a/services/authentication_service/Cargo.toml
+++ b/services/authentication_service/Cargo.toml
@@ -33,6 +33,7 @@ return_passwordless_code = []
[dependencies]
crm = { path = "../../crates/crm", default-features = false, features = ["lookup"] }
ai_billing = { path = "../../crates/ai_billing" }
+ai_usage = { path = "../../crates/ai_usage" }
initiative = { path = "../../crates/initiative", default-features = false, features = ["postgres"] }
codex_connection = { path = "../../crates/codex_connection" }
codex_cloud_agents = { path = "../../crates/codex_cloud_agents" }
diff --git a/services/authentication_service/src/config.rs b/services/authentication_service/src/config.rs
index 3346319893..2fe43ebc5f 100644
--- a/services/authentication_service/src/config.rs
+++ b/services/authentication_service/src/config.rs
@@ -87,6 +87,9 @@ maybe_env_vars! {
// #[macro_config::from_ref_all]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub struct Config {
+ /// Default-off quota admission and prospective usage counting.
+ #[macro_config_default(ai_billing::AiUsageEnforcement::Disabled)]
+ pub enable_ai_usage_enforcement: ai_billing::AiUsageEnforcement,
#[allow(dead_code)]
pub base_url: BaseUrl,
/// The connection URL for the Postgres database this application should use.
@@ -195,8 +198,12 @@ pub(crate) struct MicrosoftCredentials {
impl Config {
pub fn from_env() -> anyhow::Result<Self> {
- macro_config::ConfigLoader::load::<Config>()
- .context("failed to load authentication service config")
+ let enforcement = ai_usage::config::load_ai_usage_enforcement()
+ .map_err(|error| anyhow::anyhow!("{error}"))?;
+ let mut config = macro_config::ConfigLoader::load::<Config>()
+ .context("failed to load authentication service config")?;
+ config.enable_ai_usage_enforcement = enforcement;
+ Ok(config)
}
/// The KMS key that encrypts Cursor API keys.
diff --git a/services/authentication_service/src/config/test.rs b/services/authentication_service/src/config/test.rs
index fb719683b0..ea7d2707e4 100644
--- a/services/authentication_service/src/config/test.rs
+++ b/services/authentication_service/src/config/test.rs
@@ -2,6 +2,49 @@ use authentication_service::service::signup_policy::SignupPolicyDenial;
use super::*;
+#[test]
+fn billing_enforcement_config_defaults_off_and_requires_a_boolean() {
+ let mut values = serde_json::json!({ "ENVIRONMENT": "local" });
+ for key in [
+ "BASE_URL",
+ "DATABASE_URL",
+ "REDIS_URI",
+ "FUSIONAUTH_API_KEY_SECRET_KEY",
+ "FUSIONAUTH_CLIENT_ID",
+ "FUSIONAUTH_CLIENT_SECRET_KEY",
+ "FUSIONAUTH_BASE_URL",
+ "FUSIONAUTH_OAUTH_REDIRECT_URI",
+ "GOOGLE_CLIENT_ID",
+ "GOOGLE_CLIENT_SECRET_KEY",
+ "MICROSOFT_CLIENT_ID",
+ "MICROSOFT_CLIENT_SECRET",
+ "MICROSOFT_TENANT_ID",
+ "MICROSOFT_TOKEN_KMS_KEY_ID",
+ "STRIPE_SECRET_KEY",
+ "SERVICE_INTERNAL_AUTH_KEY",
+ "GITHUB_CLIENT_ID",
+ "GITHUB_CLIENT_SECRET",
+ "GITHUB_IDP_ID",
+ "STRIPE_PRICE_ID",
+ "INTERNAL_API_KEY",
+ "KAFKA_BROKERS",
+ ] {
+ values[key] = serde_json::json!("test");
+ }
+ let config: Config = serde_json::from_value(values.clone()).unwrap();
+ assert_eq!(
+ config.enable_ai_usage_enforcement,
+ ai_billing::AiUsageEnforcement::Disabled
+ );
+ for enabled in [false, true] {
+ values["ENABLE_AI_USAGE_ENFORCEMENT"] = serde_json::json!(enabled);
+ let config: Config = serde_json::from_value(values.clone()).unwrap();
+ assert_eq!(config.enable_ai_usage_enforcement.is_enabled(), enabled);
+ }
+ values["ENABLE_AI_USAGE_ENFORCEMENT"] = serde_json::json!("invalid");
+ assert!(serde_json::from_value::<Config>(values).is_err());
+}
+
#[test]
fn complete_microsoft_credentials_are_resolved() {
let credentials = resolve(
diff --git a/services/authentication_service/src/main.rs b/services/authentication_service/src/main.rs
index c66a7927c6..627799e16c 100644
--- a/services/authentication_service/src/main.rs
+++ b/services/authentication_service/src/main.rs
@@ -499,16 +499,19 @@ async fn main() -> anyhow::Result<()> {
};
let stripe_client = Arc::new(stripe_client);
- let ai_billing_service = Arc::new(ai_billing::domain::BillingServiceImpl::new(
- ai_billing::outbound::RolesTeamsEntitlementSource::new(
- user_roles_and_permissions_service.clone(),
- teams_repo_impl.clone(),
- ),
- ai_billing::outbound::PgUsageReader::new(db.clone()),
- ai_billing::outbound::PgBillingRepo::new(db.clone()),
- ai_billing::outbound::StripePaymentGateway::new(stripe_client.clone()),
- config.environment,
- ));
+ let ai_billing_service = Arc::new(
+ ai_billing::domain::BillingServiceImpl::new(
+ ai_billing::outbound::RolesTeamsEntitlementSource::new(
+ user_roles_and_permissions_service.clone(),
+ teams_repo_impl.clone(),
+ ),
+ ai_billing::outbound::PgUsageReader::new(db.clone()),
+ ai_billing::outbound::PgBillingRepo::new(db.clone()),
+ ai_billing::outbound::StripePaymentGateway::new(stripe_client.clone()),
+ config.environment,
+ )
+ .with_enforcement(config.enable_ai_usage_enforcement),
+ );
let teams_service_impl = TeamServiceImpl::new_with_analytics(
teams_repo_impl.clone(),
customer_repo_impl,
diff --git a/services/document_cognition_service/src/api/context.rs b/services/document_cognition_service/src/api/context.rs
index 2d60aa90e3..6ae52bab01 100644
--- a/services/document_cognition_service/src/api/context.rs
+++ b/services/document_cognition_service/src/api/context.rs
@@ -85,7 +85,7 @@ pub type DcsMessageService =
MessageServiceImpl<PgChatRepo<PgBotsRepo>, DcsAttachmentProvider, DcsEventBroker>;
#[cfg(test)]
-mod test;
+pub(crate) mod test;
#[cfg(test)]
pub use test::test_api_context;
pub(crate) type NotificationIngressType = SqsNotificationIngress<SqsQueue>;
@@ -152,6 +152,8 @@ pub struct ApiContext {
pub non_user_owners: NonUserOwners,
/// Plan allowance gate for AI requests.
pub ai_billing: Arc<DcsAiBillingService>,
+ /// Shared admission for new AI operations, after authorization.
+ pub ai_admission: Arc<dyn ai_billing::AiAdmissionService>,
pub config: Arc<Config>,
pub internal_api_key: InternalApiKey,
pub notification_ingress_service: Arc<NotificationIngressType>,
diff --git a/services/document_cognition_service/src/api/context/test.rs b/services/document_cognition_service/src/api/context/test.rs
index 8cff205846..03a4f5cef0 100644
--- a/services/document_cognition_service/src/api/context/test.rs
+++ b/services/document_cognition_service/src/api/context/test.rs
@@ -9,6 +9,62 @@ use stream::domain::{
use tokio::sync::broadcast::{self, Receiver};
use tokio_util::task::TaskTracker;
+pub const ADMISSION_TEST_USER: &str = "macro|[email protected]";
+
+pub struct TestAdmission {
+ pub result: Result<(), ai_billing::AiAdmissionError>,
+ pub calls: std::sync::Mutex<Vec<(String, ai_usage::AiFeature)>>,
+}
+
+impl TestAdmission {
+ pub fn rejecting(error: ai_billing::AiAdmissionError) -> Arc<Self> {
+ Arc::new(Self {
+ result: Err(error),
+ calls: Default::default(),
+ })
+ }
+}
+
+impl ai_billing::AiAdmissionService for TestAdmission {
+ fn admit<'a>(
+ &'a self,
+ user: &'a macro_user_id::user_id::MacroUserIdStr<'_>,
+ feature: ai_usage::AiFeature,
+ ) -> ai_billing::domain::admission::AdmissionFuture<'a> {
+ self.calls.lock().unwrap().push((user.to_string(), feature));
+ Box::pin(async { self.result })
+ }
+}
+
+pub fn admission_errors() -> [ai_billing::AiAdmissionError; 4] {
+ use ai_billing::{AiAdmissionError, DenyReason};
+ [
+ AiAdmissionError::Denied(DenyReason::AllowanceExhausted),
+ AiAdmissionError::Denied(DenyReason::OverageLimitReached),
+ AiAdmissionError::Denied(DenyReason::OveragePaymentFailed),
+ AiAdmissionError::Unavailable,
+ ]
+}
+
+pub fn authorized_request(path: &str, body: serde_json::Value) -> axum::extract::Request {
+ axum::http::Request::builder()
+ .method("POST")
+ .uri(path)
+ .header("content-type", "application/json")
+ .header("x-internal-auth-key", "testing")
+ .header("x-internal-macro-user-id", ADMISSION_TEST_USER)
+ .body(axum::body::Body::from(body.to_string()))
+ .unwrap()
+}
+
+pub async fn test_model_access(ctx: &ApiContext) -> DcsChatModelAccess {
+ use axum::extract::FromRequestParts;
+ let (mut parts, _) = authorized_request("/", serde_json::json!({})).into_parts();
+ DcsChatModelAccess::from_request_parts(&mut parts, ctx)
+ .await
+ .unwrap_or_else(|_| panic!("test model access should resolve"))
+}
+
pub struct MockConnectionRepo;
impl MockConnectionRepo {
@@ -108,6 +164,14 @@ impl StreamRepo for MockStreamRepo {
}
pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Arc<ApiContext> {
+ let config = Config::new_empty_for_test();
+ let enforcement = config.enable_ai_usage_enforcement;
+ let admission = ai_billing::composition::pg_admission_service(
+ pool.clone(),
+ config.environment,
+ enforcement,
+ );
+ let recorder = ai_usage::pg_recorder_with_enforcement(pool.clone(), enforcement);
use aws_sdk_sqs;
use channels::{
domain::list_service::ChannelListServiceImpl, outbound::pg_channels_repo::PgChannelsRepo,
@@ -427,7 +491,8 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar
),
schedule_tool_context: ai_tools::no_op_schedule_context(),
anthropic_tool_context: ai_tools::build_anthropic_tool_context_test(),
- recorder: ai_usage::pg_recorder(pool.clone()),
+ admission: admission.clone(),
+ recorder: recorder.clone(),
usage_context: ai_usage::UsageContext::system(ai_usage::AiFeature::Chat),
};
let all_tools = ai_tools::tools_for(ai_tools::AiHost::Chat);
@@ -465,12 +530,15 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar
),
Arc::new(None),
));
- let import_service = Arc::new(import::domain::service::ImportServiceImpl::new(
- import::outbound::pg_import_repo::PgImportRepo::new(pool.clone()),
- mcp_selector.clone(),
- Arc::new(creator),
- ai_usage::pg_recorder(pool.clone()),
- ));
+ let import_service = Arc::new(
+ import::domain::service::ImportServiceImpl::new(
+ import::outbound::pg_import_repo::PgImportRepo::new(pool.clone()),
+ mcp_selector.clone(),
+ Arc::new(creator),
+ recorder.clone(),
+ )
+ .with_admission(admission.clone()),
+ );
let onboarding_service = Arc::new(onboarding::domain::service::OnboardingServiceImpl::new(
onboarding::outbound::pg_onboarding_repo::PgOnboardingRepo::new(pool.clone()),
Arc::new(mcp_repo),
@@ -487,9 +555,12 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar
all_tools,
));
- let usage_service = Arc::new(ai_usage::domain::service::UsageServiceImpl::new(
- ai_usage::outbound::PgUsageRepo::new(pool.clone()),
- ));
+ let usage_service = Arc::new(
+ ai_usage::domain::service::UsageServiceImpl::new(ai_usage::outbound::PgUsageRepo::new(
+ pool.clone(),
+ ))
+ .with_enforcement(enforcement),
+ );
let projection_generator =
ai_projections::outbound::agent_generator::AgentProjectionGenerator::new(
@@ -543,19 +614,23 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar
search_service_client,
email_service_client_external,
authorization_state: authorization_state.clone(),
- ai_billing: Arc::new(ai_billing::domain::BillingServiceImpl::new(
- ai_billing::outbound::RolesTeamsEntitlementSource::new(
- (*user_permissions_service).clone(),
- teams::outbound::team_repo::TeamRepositoryImpl::new(pool.clone()),
- ),
- ai_billing::outbound::PgUsageReader::new(pool.clone()),
- ai_billing::outbound::PgBillingRepo::new(pool.clone()),
- ai_billing::outbound::NoOpPaymentGateway,
- macro_env::Environment::Local,
- )),
+ ai_admission: admission,
+ ai_billing: Arc::new(
+ ai_billing::domain::BillingServiceImpl::new(
+ ai_billing::outbound::RolesTeamsEntitlementSource::new(
+ (*user_permissions_service).clone(),
+ teams::outbound::team_repo::TeamRepositoryImpl::new(pool.clone()),
+ ),
+ ai_billing::outbound::PgUsageReader::new(pool.clone()),
+ ai_billing::outbound::PgBillingRepo::new(pool.clone()),
+ ai_billing::outbound::NoOpPaymentGateway,
+ config.environment,
+ )
+ .with_enforcement(enforcement),
+ ),
user_permissions_service,
non_user_owners: NonUserOwners::Disabled,
- config: Arc::new(Config::new_empty_for_test()),
+ config: Arc::new(config),
internal_api_key: InternalApiKey::Comptime("testing"),
notification_ingress_service,
connection_repo: MockConnectionRepo::new(),
diff --git a/services/document_cognition_service/src/api/stream/chat_message.rs b/services/document_cognition_service/src/api/stream/chat_message.rs
index 0793983f56..7756563038 100644
--- a/services/document_cognition_service/src/api/stream/chat_message.rs
+++ b/services/document_cognition_service/src/api/stream/chat_message.rs
@@ -15,7 +15,7 @@ use crate::service::get_chat::get_chat;
use crate::service::notification::notify;
use agent::types::{AssistantMessagePart, ChatMessage, ChatMessageContent};
use agent::{AgentLoop, StreamAccumulator};
-use ai_billing::BillingService;
+use ai_billing::inbound::admission::admission_status;
use async_stream::stream;
use attachment::FormattedParts;
use axum::Json;
@@ -106,7 +106,7 @@ pub struct ChatMessageError {
pub stream_id: Option<String>,
#[serde(skip)]
pub status: Option<StatusCode>,
- /// Stable machine-readable code for payment-required errors.
+ /// Stable machine-readable code for admission errors (402 or 503).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub code: Option<String>,
}
@@ -138,6 +138,7 @@ impl IntoResponse for ChatMessageError {
(status = 401, description = "Unauthorized"),
(status = 402, description = "Payment required — the user's AI allowance is used up", body = ChatMessageError),
(status = 403, description = "Forbidden — user lacks access to the requested model", body = ChatMessageError),
+ (status = 503, description = "AI usage validation unavailable — retry later", body = ChatMessageError),
)
)]
#[tracing::instrument(skip(state, model_access, user, bearer, request), fields(chat_id=?request.chat_id, user_id = %user.authorization.user.macro_user_id, attachment_ids=?request.attachments.as_ref().map(|a| a.iter().map(|att| att.entity_id.as_ref()).collect::<Vec<_>>()).unwrap_or_default()), ret, err)]
@@ -158,23 +159,6 @@ pub async fn send_chat_message(
.await
}
-/// Why the billing gate refuses this user right now, if it does. A gate
-/// failure (not a refusal) is logged and lets the request through: an outage
-/// in billing must not take AI down with it.
-async fn billing_denial(
- ctx: &ApiContext,
- user_id: &MacroUserIdStr<'_>,
-) -> Option<ai_billing::DenyReason> {
- match ctx.ai_billing.check_allowance(user_id).await {
- Ok(ai_billing::AllowanceDecision::Allow) => None,
- Ok(ai_billing::AllowanceDecision::Deny(reason)) => Some(reason),
- Err(e) => {
- tracing::error!(error = ?e, user_id = %user_id, "ai billing gate failed; allowing request");
- None
- }
- }
-}
-
async fn send_chat_message_inner(
state: ApiContext,
model_access: DcsChatModelAccess,
@@ -205,24 +189,11 @@ async fn send_chat_message_inner(
code: None,
});
}
- // Paid users draw on a monthly AI allowance (then credits, then overage).
- if model_access.professional()
- && let Some(reason) = billing_denial(&ctx, &user_id).await
- {
- return Err(ChatMessageError {
- error: reason.message().to_string(),
- stream_id: Some(stream_id.clone()),
- status: Some(StatusCode::PAYMENT_REQUIRED),
- code: Some(reason.code().to_string()),
- });
- }
let model = request.model.clone();
- // Try to get the chat first - if it doesn't exist or no chat_id provided, create it
- let (chat, actual_chat_id, created_new_chat) = if requested_chat_id.is_empty() {
- // No chat_id provided - create a new chat
- let (chat, chat_id) = create_new_chat(&ctx, &user_id, &model, &stream_id).await?;
- (chat, chat_id, true)
+ // Resolve existing-chat permissions before admission, without creating anything.
+ let existing_chat = if requested_chat_id.is_empty() {
+ None
} else {
match get_chat(&ctx, &requested_chat_id, user_id.0.as_ref()).await {
Ok(chat) => {
@@ -255,19 +226,33 @@ async fn send_chat_message_inner(
_ => (),
},
};
- (chat, requested_chat_id, false)
+ Some(chat)
}
Err(_) => {
- // Chat doesn't exist - create a new one
- tracing::info!(
- requested_chat_id = %requested_chat_id,
- "Chat not found, creating new chat"
- );
- let (chat, chat_id) = create_new_chat(&ctx, &user_id, &model, &stream_id).await?;
- (chat, chat_id, true)
+ // Preserve the missing-chat fallback, but only create after admission.
+ tracing::info!(requested_chat_id = %requested_chat_id, "Chat not found");
+ None
}
}
};
+
+ ctx.ai_admission
+ .admit(&user_id, ai_usage::AiFeature::Chat)
+ .await
+ .map_err(|error| ChatMessageError {
+ error: error.to_string(),
+ stream_id: Some(stream_id.clone()),
+ status: Some(admission_status(error)),
+ code: Some(error.code().to_string()),
+ })?;
+
+ let (chat, actual_chat_id, created_new_chat) = match existing_chat {
+ Some(chat) => (chat, requested_chat_id, false),
+ None => {
+ let (chat, chat_id) = create_new_chat(&ctx, &user_id, &model, &stream_id).await?;
+ (chat, chat_id, true)
+ }
+ };
let should_auto_rename_chat = created_new_chat || chat.messages.is_empty();
// Convert HTTP request to internal payload for existing functions
diff --git a/services/document_cognition_service/src/api/stream/chat_message/test.rs b/services/document_cognition_service/src/api/stream/chat_message/test.rs
index 36219ef578..4208740863 100644
--- a/services/document_cognition_service/src/api/stream/chat_message/test.rs
+++ b/services/document_cognition_service/src/api/stream/chat_message/test.rs
@@ -1,4 +1,132 @@
use super::*;
+use crate::api::context::test::{
+ ADMISSION_TEST_USER, TestAdmission, admission_errors, test_api_context, test_model_access,
+};
+use macro_db_migrator::MACRO_DB_MIGRATIONS;
+
+fn admission_request(chat_id: Option<String>) -> HttpSendChatMessageRequest {
+ HttpSendChatMessageRequest {
+ content: "hello".into(),
+ chat_id,
+ model: chat::domain::models::FREE_MODEL.into(),
+ additional_instructions: None,
+ attachments: None,
+ toolset: ToolSet::None,
+ }
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn admission_rejects_before_chat_creation_or_streaming(pool: sqlx::PgPool) {
+ let ctx = test_api_context(pool.clone()).await;
+ for error in admission_errors() {
+ // Exercise both new-chat paths: omitted ID and a missing chat.
+ for chat_id in [None, Some(uuid::Uuid::now_v7().to_string())] {
+ let admission = TestAdmission::rejecting(error);
+ let mut state = (*ctx).clone();
+ state.ai_admission = admission.clone();
+ let model_access = test_model_access(&state).await;
+ let result = send_chat_message_inner(
+ state,
+ model_access,
+ MacroUserIdStr::parse_from_str(ADMISSION_TEST_USER).unwrap(),
+ BearerToken(String::new()),
+ admission_request(chat_id),
+ )
+ .await
+ .unwrap_err();
+ assert_eq!(result.status, Some(admission_status(error)));
+ assert_eq!(result.code.as_deref(), Some(error.code()));
+ assert_eq!(result.error, error.to_string());
+ assert!(result.stream_id.is_some());
+ assert_eq!(
+ *admission.calls.lock().unwrap(),
+ vec![(ADMISSION_TEST_USER.into(), ai_usage::AiFeature::Chat)]
+ );
+ }
+ }
+ assert_eq!(
+ sqlx::query_scalar!("SELECT count(*) FROM \"Chat\"")
+ .fetch_one(&pool)
+ .await
+ .unwrap(),
+ Some(0)
+ );
+ assert_eq!(
+ sqlx::query_scalar!("SELECT count(*) FROM \"ChatMessage\"")
+ .fetch_one(&pool)
+ .await
+ .unwrap(),
+ Some(0)
+ );
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn permission_failures_precede_admission(pool: sqlx::PgPool) {
+ let ctx = test_api_context(pool.clone()).await;
+ let chat_id = uuid::Uuid::now_v7().to_string();
+ sqlx::query!(
+ r#"INSERT INTO "Chat" (id, "userId", name) VALUES ($1, 'macro|[email protected]', 'Private chat')"#,
+ chat_id
+ ).execute(&pool).await.unwrap();
+
+ for error in admission_errors() {
+ let admission = TestAdmission::rejecting(error);
+ let mut state = (*ctx).clone();
+ state.ai_admission = admission.clone();
+ let result = send_chat_message_inner(
+ state.clone(),
+ test_model_access(&state).await,
+ MacroUserIdStr::parse_from_str(ADMISSION_TEST_USER).unwrap(),
+ BearerToken(String::new()),
+ admission_request(Some(chat_id.clone())),
+ )
+ .await
+ .unwrap_err();
+ assert!(result.error.starts_with("Permission check failed:"));
+ assert!(result.code.is_none());
+ assert_eq!(result.into_response().status(), StatusCode::BAD_REQUEST);
+
+ let mut request = admission_request(None);
+ request.model = "anthropic/claude-opus-5".into();
+ let result = send_chat_message_inner(
+ state.clone(),
+ test_model_access(&state).await,
+ MacroUserIdStr::parse_from_str(ADMISSION_TEST_USER).unwrap(),
+ BearerToken(String::new()),
+ request,
+ )
+ .await
+ .unwrap_err();
+ assert_eq!(result.status, Some(StatusCode::FORBIDDEN));
+ assert!(result.code.is_none());
+ assert!(admission.calls.lock().unwrap().is_empty());
+ }
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn disabled_admission_allows_authorized_request_to_reach_chat_creation(pool: sqlx::PgPool) {
+ let ctx = test_api_context(pool.clone()).await;
+ let model_access = test_model_access(&ctx).await;
+ let mut state = (*ctx).clone();
+ state.ai_admission = Arc::new(ai_billing::BillingAdmissionService::new(
+ ctx.ai_billing.clone(),
+ ai_usage::AiUsageEnforcement::default(),
+ ));
+ // Closed billing storage must not block disabled admission. Execution then
+ // stops at chat creation without starting real AI work.
+ pool.close().await;
+ let error = send_chat_message_inner(
+ state,
+ model_access,
+ MacroUserIdStr::parse_from_str(ADMISSION_TEST_USER).unwrap(),
+ BearerToken(String::new()),
+ admission_request(None),
+ )
+ .await
+ .unwrap_err();
+ assert_eq!(error.error, "Failed to create chat");
+ assert!(error.code.is_none());
+}
#[test]
fn send_chat_message_request_accepts_arbitrary_model_string() {
diff --git a/services/document_cognition_service/src/api/structured_completion.rs b/services/document_cognition_service/src/api/structured_completion.rs
index 772a8fdd50..ca125f7936 100644
--- a/services/document_cognition_service/src/api/structured_completion.rs
+++ b/services/document_cognition_service/src/api/structured_completion.rs
@@ -3,7 +3,7 @@ use crate::model::stream::ToolSet;
use agent::structured_output::DynamicSchema;
use agent::types::{ChatMessage, ChatMessageContent, Role};
use agent::{AgentLoop, StreamAccumulator};
-use ai_billing::BillingService;
+use ai_billing::inbound::admission::admission_status;
use axum::Json;
use axum::extract::State;
use axum::http::StatusCode;
@@ -36,7 +36,7 @@ pub struct StructuredCompletionError {
pub error: String,
#[serde(skip)]
pub status: StatusCode,
- /// Stable machine-readable code for payment-required errors.
+ /// Stable machine-readable code for admission errors (402 or 503).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub code: Option<String>,
}
@@ -61,8 +61,9 @@ impl IntoResponse for StructuredCompletionError {
(status = 200, description = "Structured completion result", body = StructuredCompletionResponse),
(status = 400, description = "Bad request", body = StructuredCompletionError),
(status = 401, description = "Unauthorized"),
- (status = 402, description = "Payment required"),
+ (status = 402, description = "Payment required", body = StructuredCompletionError),
(status = 500, description = "Internal error", body = StructuredCompletionError),
+ (status = 503, description = "AI usage validation unavailable — retry later", body = StructuredCompletionError),
)
)]
#[tracing::instrument(skip(state, model_access, user, request), fields(user_id = %user.authorization.user.macro_user_id), err)]
@@ -77,23 +78,15 @@ pub async fn structured_completion(
let user_id = user.authorization.user.macro_user_id.clone();
- // Paid users draw on a monthly AI allowance (then credits, then overage).
- // A gate failure is logged and lets the request through.
- if model_access.professional() {
- match ctx.ai_billing.check_allowance(&user_id).await {
- Ok(ai_billing::AllowanceDecision::Allow) => {}
- Ok(ai_billing::AllowanceDecision::Deny(reason)) => {
- return Err(StructuredCompletionError {
- error: reason.message().to_string(),
- status: StatusCode::PAYMENT_REQUIRED,
- code: Some(reason.code().to_string()),
- });
- }
- Err(e) => {
- tracing::error!(error = ?e, user_id = %user_id, "ai billing gate failed; allowing request");
- }
- }
- }
+ // One admission covers both the agent and final formatting phases.
+ ctx.ai_admission
+ .admit(&user_id, ai_usage::AiFeature::DynamicCompletionsApi)
+ .await
+ .map_err(|error| StructuredCompletionError {
+ error: error.to_string(),
+ status: admission_status(error),
+ code: Some(error.code().to_string()),
+ })?;
let tools_prompt: &(dyn std::fmt::Display + Sync) = match request.toolset {
ToolSet::All => &ctx.all_tools_prompt,
@@ -198,3 +191,6 @@ pub async fn structured_completion(
Ok(Json(StructuredCompletionResponse { result }))
}
+
+#[cfg(test)]
+mod test;
diff --git a/services/document_cognition_service/src/api/structured_completion/test.rs b/services/document_cognition_service/src/api/structured_completion/test.rs
new file mode 100644
index 0000000000..24c5b919a1
--- /dev/null
+++ b/services/document_cognition_service/src/api/structured_completion/test.rs
@@ -0,0 +1,91 @@
+use super::*;
+use crate::api::context::test::{
+ ADMISSION_TEST_USER, TestAdmission, admission_errors, authorized_request, test_api_context,
+};
+use axum::{Router, routing::post};
+use macro_db_migrator::MACRO_DB_MIGRATIONS;
+use tower::ServiceExt;
+
+fn request_body() -> serde_json::Value {
+ serde_json::json!({
+ "prompt": "hello",
+ "model": "ignored-as-before",
+ "toolset": { "type": "none" },
+ "output_schema": {
+ "name": "Answer",
+ "schema": {
+ "type": "object",
+ "properties": { "answer": { "type": "string" } },
+ "required": ["answer"]
+ }
+ }
+ })
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn admission_rejects_before_tool_discovery_and_both_provider_phases(pool: sqlx::PgPool) {
+ let ctx = test_api_context(pool).await;
+ for error in admission_errors() {
+ let admission = TestAdmission::rejecting(error);
+ let mut state = (*ctx).clone();
+ state.ai_admission = admission.clone();
+ let router = Router::new()
+ .route("/", post(structured_completion))
+ .with_state(state);
+ let response = router
+ .oneshot(authorized_request("/", request_body()))
+ .await
+ .unwrap();
+ assert_eq!(response.status(), admission_status(error));
+ let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
+ .await
+ .unwrap();
+ let body: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
+ assert_eq!(
+ body,
+ serde_json::json!({"error": error.to_string(), "code": error.code()})
+ );
+ assert_eq!(
+ *admission.calls.lock().unwrap(),
+ vec![(
+ ADMISSION_TEST_USER.into(),
+ ai_usage::AiFeature::DynamicCompletionsApi
+ )]
+ );
+ }
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn unauthorized_request_does_not_disclose_quota(pool: sqlx::PgPool) {
+ let mut state = (*test_api_context(pool).await).clone();
+ let admission = TestAdmission::rejecting(ai_billing::AiAdmissionError::Unavailable);
+ state.ai_admission = admission.clone();
+ let router = Router::new()
+ .route("/", post(structured_completion))
+ .with_state(state);
+ let mut request = authorized_request("/", request_body());
+ request
+ .headers_mut()
+ .insert("x-internal-auth-key", "invalid".parse().unwrap());
+ let response = router.oneshot(request).await.unwrap();
+ assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
+ assert!(admission.calls.lock().unwrap().is_empty());
+}
+
+#[test]
+fn openapi_documents_admission_failures_with_existing_payloads() {
+ use utoipa::OpenApi;
+ let doc = serde_json::to_value(crate::api::swagger::ApiDoc::openapi()).unwrap();
+ for (path, schema) in [
+ ("/stream/chat/message", "ChatMessageError"),
+ ("/structured-completion", "StructuredCompletionError"),
+ ] {
+ for status in ["402", "503"] {
+ assert_eq!(
+ doc["paths"][path]["post"]["responses"][status]["content"]["application/json"]["schema"]
+ ["$ref"],
+ format!("#/components/schemas/{schema}")
+ );
+ }
+ }
+}
diff --git a/services/document_cognition_service/src/config.rs b/services/document_cognition_service/src/config.rs
index fffbcfaabf..616e0d796b 100644
--- a/services/document_cognition_service/src/config.rs
+++ b/services/document_cognition_service/src/config.rs
@@ -70,6 +70,9 @@ maybe_env_vars!(
#[derive(macro_config::MacroConfig)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub struct Config {
+ /// Default-off quota admission and prospective usage counting.
+ #[macro_config_default(ai_usage::AiUsageEnforcement::Disabled)]
+ pub enable_ai_usage_enforcement: ai_usage::AiUsageEnforcement,
/// The connection URL for the Postgres database this application should use.
pub database_url: DatabaseUrl,
/// The port to listen for HTTP requests on.
@@ -148,7 +151,12 @@ fn default_mcp_public_url(environment: Environment) -> &'static str {
impl Config {
#[tracing::instrument(err, skip_all)]
pub fn from_env() -> anyhow::Result<Self> {
- macro_config::ConfigLoader::load::<Config>().context("failed to load config")
+ let enforcement = ai_usage::config::load_ai_usage_enforcement()
+ .map_err(|error| anyhow::anyhow!("{error}"))?;
+ let mut config =
+ macro_config::ConfigLoader::load::<Config>().context("failed to load config")?;
+ config.enable_ai_usage_enforcement = enforcement;
+ Ok(config)
}
pub fn non_user_owners(&self) -> anyhow::Result<NonUserOwners> {
@@ -159,6 +167,7 @@ impl Config {
#[cfg(test)]
pub fn new_empty_for_test() -> Self {
Config {
+ enable_ai_usage_enforcement: ai_usage::AiUsageEnforcement::Disabled,
environment: Environment::Local,
database_url: DatabaseUrl::Comptime("DATABASE_URL"),
port: Default::default(),
diff --git a/services/document_cognition_service/src/main.rs b/services/document_cognition_service/src/main.rs
index eb7aae8d61..887c7b33cc 100644
--- a/services/document_cognition_service/src/main.rs
+++ b/services/document_cognition_service/src/main.rs
@@ -475,32 +475,43 @@ async fn main() -> anyhow::Result<()> {
// The AI billing gate reads allowances, credits, and overage state here;
// collection (Stripe) lives in the authentication service, which the
// recorder below asks to settle once a payer runs past their allowance.
- let ai_billing = Arc::new(ai_billing::domain::BillingServiceImpl::new(
- ai_billing::outbound::RolesTeamsEntitlementSource::new(
- (*user_permissions_service).clone(),
- teams::outbound::team_repo::TeamRepositoryImpl::new(db.clone()),
- ),
- ai_billing::outbound::PgUsageReader::new(db.clone()),
- ai_billing::outbound::PgBillingRepo::new(db.clone()),
- ai_billing::outbound::NoOpPaymentGateway,
- config.environment,
- ));
+ let ai_billing = Arc::new(
+ ai_billing::domain::BillingServiceImpl::new(
+ ai_billing::outbound::RolesTeamsEntitlementSource::new(
+ (*user_permissions_service).clone(),
+ teams::outbound::team_repo::TeamRepositoryImpl::new(db.clone()),
+ ),
+ ai_billing::outbound::PgUsageReader::new(db.clone()),
+ ai_billing::outbound::PgBillingRepo::new(db.clone()),
+ ai_billing::outbound::NoOpPaymentGateway,
+ config.environment,
+ )
+ .with_enforcement(config.enable_ai_usage_enforcement),
+ );
+ let admission: Arc<dyn ai_billing::AiAdmissionService> =
+ Arc::new(ai_billing::BillingAdmissionService::new(
+ ai_billing.clone(),
+ config.enable_ai_usage_enforcement,
+ ));
let auth_service_client = Arc::new(authentication_service_client::AuthServiceClient::new(
internal_api_key.clone(),
AuthServiceUrl::new()?.to_string(),
));
let recorder: Arc<dyn ai_usage::UsageRecorder> =
Arc::new(ai_billing::outbound::SettlingUsageRecorder::new(
- Arc::new(ai_usage::domain::service::UsageServiceImpl::new(
- ai_usage::outbound::PgUsageRepo::new(db.clone()),
- )),
+ Arc::new(
+ ai_usage::domain::service::UsageServiceImpl::new(
+ ai_usage::outbound::PgUsageRepo::new(db.clone()),
+ )
+ .with_enforcement(config.enable_ai_usage_enforcement),
+ ),
ai_billing.clone(),
ai_billing::outbound::HttpSettlementTrigger::new(auth_service_client),
config.environment,
));
- // Keep existing analytics/legacy settlement unchanged. Per-attempt observations
- // use a separate journal and never feed this settlement trigger.
+ // Per-attempt observations use a separate journal and never feed the
+ // legacy settlement trigger, which remains counted-usage-only and dev-only.
let recorder = ai_usage::with_tracking(recorder, ai_usage::pg_tracking(db.clone()));
// The import pipeline: staged/imported external items, gather jobs over
@@ -621,6 +632,7 @@ async fn main() -> anyhow::Result<()> {
Arc::new(entity_creator),
recorder.clone(),
)
+ .with_admission(admission.clone())
.with_notifier(import_notify),
);
@@ -697,6 +709,7 @@ async fn main() -> anyhow::Result<()> {
),
schedule_tool_context: ai_tools::NoOpScheduleContext,
anthropic_tool_context: ai_tools::build_anthropic_tool_context(),
+ admission,
recorder,
usage_context: ai_usage::UsageContext::system(ai_usage::AiFeature::Chat),
};
@@ -717,9 +730,12 @@ async fn main() -> anyhow::Result<()> {
// Build the AI cost service. It backs both the admin query/pricing router
// and the usage recorder threaded through the tool service context.
- let usage_service = Arc::new(ai_usage::domain::service::UsageServiceImpl::new(
- ai_usage::outbound::PgUsageRepo::new(db.clone()),
- ));
+ let usage_service = Arc::new(
+ ai_usage::domain::service::UsageServiceImpl::new(ai_usage::outbound::PgUsageRepo::new(
+ db.clone(),
+ ))
+ .with_enforcement(config.enable_ai_usage_enforcement),
+ );
tracing::info!("initialized ai cost service");
@@ -852,6 +868,7 @@ async fn main() -> anyhow::Result<()> {
authorization_state,
user_permissions_service,
non_user_owners,
+ ai_admission: tool_service_context.admission.clone(),
ai_billing,
internal_api_key: config.internal_api_key.clone(),
config: Arc::new(config),
diff --git a/services/document_cognition_service/src/service/chat_renamer.rs b/services/document_cognition_service/src/service/chat_renamer.rs
index b282159296..0da7b0f0bc 100644
--- a/services/document_cognition_service/src/service/chat_renamer.rs
+++ b/services/document_cognition_service/src/service/chat_renamer.rs
@@ -58,6 +58,15 @@ async fn rename_initial_chat(
stream_id: String,
initial_question: String,
) -> anyhow::Result<()> {
+ if let Err(error) = ctx
+ .ai_admission
+ .admit(&user_id, ai_usage::AiFeature::ChatRename)
+ .await
+ {
+ tracing::warn!(code = error.code(), "skipping automatic chat rename");
+ return Ok(());
+ }
+
let name = generate_chat_name(
&initial_question,
user_id.clone(),
@@ -140,20 +149,4 @@ fn clean_chat_name(raw: &str) -> String {
}
#[cfg(test)]
-mod tests {
- use super::clean_chat_name;
-
- #[test]
- fn clean_chat_name_trims_quotes_and_collapses_whitespace() {
- assert_eq!(
- clean_chat_name(" \"Plan Q3\nHiring\" "),
- "Plan Q3 Hiring"
- );
- }
-
- #[test]
- fn clean_chat_name_limits_length() {
- let raw = "a".repeat(120);
- assert_eq!(clean_chat_name(&raw).len(), 100);
- }
-}
+mod test;
diff --git a/services/document_cognition_service/src/service/chat_renamer/test.rs b/services/document_cognition_service/src/service/chat_renamer/test.rs
new file mode 100644
index 0000000000..a4395d6cf8
--- /dev/null
+++ b/services/document_cognition_service/src/service/chat_renamer/test.rs
@@ -0,0 +1,47 @@
+use super::*;
+use crate::api::context::test::{
+ ADMISSION_TEST_USER, TestAdmission, admission_errors, test_api_context,
+};
+
+#[test]
+fn clean_chat_name_trims_quotes_and_collapses_whitespace() {
+ assert_eq!(
+ clean_chat_name(" \"Plan Q3\nHiring\" "),
+ "Plan Q3 Hiring"
+ );
+}
+
+#[test]
+fn clean_chat_name_limits_length() {
+ let raw = "a".repeat(120);
+ assert_eq!(clean_chat_name(&raw).len(), 100);
+}
+
+#[tokio::test]
+async fn rejected_rename_succeeds_without_provider_or_persistence_work() {
+ let pool = sqlx::postgres::PgPoolOptions::new()
+ .connect_lazy("postgres://unused:[email protected]:1/unused")
+ .unwrap();
+ pool.close().await;
+ let ctx = test_api_context(pool).await;
+ for error in admission_errors() {
+ let admission = TestAdmission::rejecting(error);
+ let mut state = (*ctx).clone();
+ state.ai_admission = admission.clone();
+ // No provider is configured and the pool is closed. Returning Ok proves
+ // rejection neither tries a fallback completion nor patches the name.
+ rename_initial_chat(
+ Arc::new(state),
+ MacroUserIdStr::parse_from_str(ADMISSION_TEST_USER).unwrap(),
+ uuid::Uuid::now_v7().to_string(),
+ "stream-id".into(),
+ "Plan Q3 hiring".into(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ *admission.calls.lock().unwrap(),
+ vec![(ADMISSION_TEST_USER.into(), ai_usage::AiFeature::ChatRename)]
+ );
+ }
+}
diff --git a/services/document_storage_service/Cargo.toml b/services/document_storage_service/Cargo.toml
index baf40a00a6..967060b594 100644
--- a/services/document_storage_service/Cargo.toml
+++ b/services/document_storage_service/Cargo.toml
@@ -27,6 +27,9 @@ local_auth = ["macro_authorization/local_auth"]
location_check = []
[dependencies]
+ai_billing = { path = "../../crates/ai_billing" }
+roles_and_permissions = { path = "../../crates/roles_and_permissions", default-features = false, features = ["outbound"] }
+teams = { path = "../../crates/teams", default-features = false, features = ["outbound"] }
agent_changes = { path = "../../crates/agent_changes", default-features = false, features = ["outbound"] }
dictation = { path = "../../crates/dictation", features = ["inbound", "outbound"] }
initiative_documents = { path = "../../crates/initiative_documents" }
diff --git a/services/document_storage_service/src/config.rs b/services/document_storage_service/src/config.rs
index ba988d1e39..36e80a5edb 100644
--- a/services/document_storage_service/src/config.rs
+++ b/services/document_storage_service/src/config.rs
@@ -85,6 +85,9 @@ maybe_env_vars! {
#[derive(macro_config::MacroConfig)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub struct Config {
+ /// Default-off quota admission and prospective usage counting.
+ #[macro_config_default(ai_usage::AiUsageEnforcement::Disabled)]
+ pub enable_ai_usage_enforcement: ai_usage::AiUsageEnforcement,
pub database_url: DatabaseUrl,
pub database_url_readonly: DatabaseUrlReadonly,
pub document_storage_bucket: DocumentStorageBucket,
@@ -196,7 +199,12 @@ pub struct Config {
impl Config {
pub fn from_env() -> anyhow::Result<Self> {
- macro_config::ConfigLoader::load::<Config>().context("failed to load config")
+ let enforcement = ai_usage::config::load_ai_usage_enforcement()
+ .map_err(|error| anyhow::anyhow!("{error}"))?;
+ let mut config =
+ macro_config::ConfigLoader::load::<Config>().context("failed to load config")?;
+ config.enable_ai_usage_enforcement = enforcement;
+ Ok(config)
}
pub fn non_user_owners(&self) -> anyhow::Result<NonUserOwners> {
diff --git a/services/document_storage_service/src/main.rs b/services/document_storage_service/src/main.rs
index 107eb8526c..5d4b58605e 100644
--- a/services/document_storage_service/src/main.rs
+++ b/services/document_storage_service/src/main.rs
@@ -683,7 +683,9 @@ async fn run() -> anyhow::Result<()> {
recording_storage,
config.livekit_server_url.as_ref(),
)
- .with_summarizer(AiCallSummarizer::new(ai_usage::pg_recorder(db.clone())));
+ .with_summarizer(AiCallSummarizer::new(
+ ai_usage::pg_recorder_with_enforcement(db.clone(), config.enable_ai_usage_enforcement),
+ ));
if let Some(secret) = internal_call_secret {
call_service_builder = call_service_builder.with_internal_call_secret(secret);
}
@@ -992,7 +994,7 @@ async fn run() -> anyhow::Result<()> {
dictation::domain::DictationServiceImpl::new(
dictation::outbound::WhisperTranscriber::new(&config.openai_api_key)?,
dictation::outbound::SymphoniaRecordingInspector,
- ai_usage::pg_recorder(db.clone()),
+ ai_usage::pg_recorder_with_enforcement(db.clone(), config.enable_ai_usage_enforcement),
),
RateLimitServiceImpl {
repo: RedisRateLimitAdapter {
@@ -1005,7 +1007,9 @@ async fn run() -> anyhow::Result<()> {
TextEmbedding3Small::new(openai_api_key),
PgTaskVectorDb::new(db.clone()),
CohereReranker::new(cohere_api_key),
- Arc::new(AgentDuplicateJudge::new(ai_usage::pg_recorder(db.clone()))),
+ Arc::new(AgentDuplicateJudge::new(
+ ai_usage::pg_recorder_with_enforcement(db.clone(), config.enable_ai_usage_enforcement),
+ )),
Arc::new(ConnectionGatewayTaskDedupNotifier::new(
conn_gateway_client.clone(),
)),
@@ -1164,10 +1168,13 @@ async fn run() -> anyhow::Result<()> {
// Agent sessions belong to a different bot entirely
// (`bot_id::MACRO_NEW_BOT_ID`, served by the harness), so the two paths
// can never answer the same mention.
- let mut macro_agent_tool_context =
- ai_tools::build_tool_service_context_from_env(db.clone(), event_broker_tracker.clone())
- .await
- .context("failed to build Macro agent tool context")?;
+ let mut macro_agent_tool_context = ai_tools::build_tool_service_context_from_env(
+ db.clone(),
+ event_broker_tracker.clone(),
+ config.enable_ai_usage_enforcement,
+ )
+ .await
+ .context("failed to build Macro agent tool context")?;
// Wire the agent's SendChannelMessage tool to this service's own
// side-effect pipeline so agent-posted messages share the exact instance
// used by the HTTP API, including the in-process bot trigger sender (the
@@ -1185,7 +1192,8 @@ async fn run() -> anyhow::Result<()> {
entity_access_service.clone(),
),
);
- let bot_trigger_router = channel_bots::inbound::BotTriggerRouter::new(
+ let admission = macro_agent_tool_context.admission.clone();
+ let bot_trigger_router = channel_bots::inbound::BotTriggerRouter::new_with_admission(
message_service.clone(),
conversation_access.clone(),
Arc::new(channel_bots::outbound::AgentLoopResponder::new(
@@ -1197,9 +1205,13 @@ async fn run() -> anyhow::Result<()> {
message_service.clone(),
conversation_access,
Arc::new(channel_bots::outbound::FastModelTriggerClassifier::new(
- ai_usage::pg_recorder(db.clone()),
+ ai_usage::pg_recorder_with_enforcement(
+ db.clone(),
+ config.enable_ai_usage_enforcement,
+ ),
)),
- ),
+ )
+ .with_admission(admission.clone()),
),
Arc::new(channel_bots::outbound::PrimaryCalendarTimeZones::new(
Arc::new(calendar_events::domain::service::CalendarService::new(
@@ -1209,6 +1221,7 @@ async fn run() -> anyhow::Result<()> {
Arc::new(channel_bots::outbound::LexicalCommentMarks::new(
(*lexical_client).clone(),
)),
+ admission,
);
bot_trigger_router.spawn(bot_trigger_receiver);
diff --git a/services/mcp_service/Cargo.toml b/services/mcp_service/Cargo.toml
index 80ea229312..07470f7229 100644
--- a/services/mcp_service/Cargo.toml
+++ b/services/mcp_service/Cargo.toml
@@ -14,6 +14,9 @@ name = "mcp_service_doppler_config"
path = "src/doppler_config.rs"
[dependencies]
+ai_billing = { path = "../../crates/ai_billing", features = ["pg-admission"] }
+roles_and_permissions = { path = "../../crates/roles_and_permissions", default-features = false, features = ["outbound"] }
+teams = { path = "../../crates/teams", default-features = false, features = ["outbound"] }
ai_tools = { path = "../../crates/ai_tools" }
ai_toolset = { path = "../../crates/ai_toolset" }
ai_usage = { path = "../../crates/ai_usage" }
diff --git a/services/mcp_service/src/config.rs b/services/mcp_service/src/config.rs
index a9089b457d..6ed0f4aa07 100644
--- a/services/mcp_service/src/config.rs
+++ b/services/mcp_service/src/config.rs
@@ -62,6 +62,9 @@ env_vars! {
#[derive(macro_config::MacroConfig)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub struct Config {
+ /// Default-off quota admission and prospective usage counting.
+ #[macro_config_default(ai_usage::AiUsageEnforcement::Disabled)]
+ pub enable_ai_usage_enforcement: ai_usage::AiUsageEnforcement,
/// The environment we are in.
#[macro_config_default(Environment::new_or_prod())]
pub environment: Environment,
@@ -99,6 +102,11 @@ pub struct Config {
impl Config {
pub fn from_env() -> anyhow::Result<Self> {
- macro_config::ConfigLoader::load::<Config>().context("failed to load mcp server config")
+ let enforcement = ai_usage::config::load_ai_usage_enforcement()
+ .map_err(|error| anyhow::anyhow!("{error}"))?;
+ let mut config = macro_config::ConfigLoader::load::<Config>()
+ .context("failed to load mcp server config")?;
+ config.enable_ai_usage_enforcement = enforcement;
+ Ok(config)
}
}
diff --git a/services/mcp_service/src/context.rs b/services/mcp_service/src/context.rs
index 1f11c82a07..390d9242e7 100644
--- a/services/mcp_service/src/context.rs
+++ b/services/mcp_service/src/context.rs
@@ -440,7 +440,15 @@ async fn build_tool_context(args: ToolContextBuildArgs<'_>) -> anyhow::Result<To
skill_tool_context,
schedule_tool_context: NoOpScheduleContext,
anthropic_tool_context: ai_tools::build_anthropic_tool_context(),
- recorder: ai_usage::pg_recorder(db.clone()),
+ admission: ai_billing::composition::pg_admission_service(
+ db.clone(),
+ config.environment,
+ config.enable_ai_usage_enforcement,
+ ),
+ recorder: ai_usage::pg_recorder_with_enforcement(
+ db.clone(),
+ config.enable_ai_usage_enforcement,
+ ),
usage_context: ai_usage::UsageContext::system(ai_usage::AiFeature::Chat),
};
diff --git a/services/scheduled_action/Cargo.toml b/services/scheduled_action/Cargo.toml
index 3510824562..132d6ed2ec 100644
--- a/services/scheduled_action/Cargo.toml
+++ b/services/scheduled_action/Cargo.toml
@@ -21,9 +21,12 @@ default = []
local_auth = ["macro_authorization/local_auth"]
[dependencies]
+ai_billing = { path = "../../crates/ai_billing" }
+roles_and_permissions = { path = "../../crates/roles_and_permissions", default-features = false, features = ["outbound"] }
+teams = { path = "../../crates/teams", default-features = false, features = ["outbound"] }
activity = { path = "../../crates/activity", default-features = false }
agent_runtime_protocol = { path = "../../crates/agent_runtime_protocol", default-features = false }
-agent_session = { path = "../../crates/agent_session", default-features = false }
+agent_session = { path = "../../crates/agent_session", default-features = false, features = ["admission"] }
bot_id = { path = "../../crates/bot_id" }
bots = { path = "../../crates/bots", default-features = false, features = ["outbound"] }
channel_sender = { path = "../../crates/channel_sender" }
diff --git a/services/scheduled_action/src/bins/service.rs b/services/scheduled_action/src/bins/service.rs
index 9ec6e15688..a274a68ab9 100644
--- a/services/scheduled_action/src/bins/service.rs
+++ b/services/scheduled_action/src/bins/service.rs
@@ -80,9 +80,13 @@ async fn main() -> Result<()> {
.context("failed to connect to macrodb")?;
let lifecycle = ServiceLifecycle::default();
- let tool_context = build_tool_service_context_from_env(db.clone(), lifecycle.publishes.clone())
- .await
- .context("failed to build tool service context")?;
+ let tool_context = build_tool_service_context_from_env(
+ db.clone(),
+ lifecycle.publishes.clone(),
+ config.enable_ai_usage_enforcement,
+ )
+ .await
+ .context("failed to build tool service context")?;
let aws_config = macro_aws_config::get_macro_aws_config().await;
let notification_ingress = Arc::new(SqsNotificationIngress {
@@ -116,6 +120,7 @@ async fn main() -> Result<()> {
tool_context.clone(),
tools_for(AiHost::Chat),
);
+ let ai_admission = tool_context.admission.clone();
let runner = Arc::new(AgentTaskRunner::new(
Arc::clone(&tool_context.chat_tool_context.service),
PgChatRepo::new(db.clone(), registrar),
@@ -134,7 +139,8 @@ async fn main() -> Result<()> {
live_updates,
lifecycle.executions.clone(),
lifecycle.stop_executions.clone(),
- );
+ )
+ .with_admission(ai_admission);
let service_executor = Arc::new(dispatcher_executor.clone());
let jwt_args = JwtValidationArgs::new_with_secret_manager(environment, &secretsmanager_client)
diff --git a/services/scheduled_action/src/config.rs b/services/scheduled_action/src/config.rs
index 3522efca9f..b64df0b1b9 100644
--- a/services/scheduled_action/src/config.rs
+++ b/services/scheduled_action/src/config.rs
@@ -42,6 +42,9 @@ env_vars! {
#[derive(macro_config::MacroConfig)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub struct Config {
+ /// Default-off quota admission and prospective usage counting.
+ #[macro_config_default(ai_usage::AiUsageEnforcement::Disabled)]
+ pub enable_ai_usage_enforcement: ai_usage::AiUsageEnforcement,
/// The environment we are in.
#[macro_config_default(Environment::new_or_prod())]
pub environment: Environment,
@@ -75,7 +78,11 @@ pub struct Config {
impl Config {
pub fn from_env() -> anyhow::Result<Self> {
- macro_config::ConfigLoader::load::<Config>()
- .context("failed to load agent schedule service config")
+ let enforcement = ai_usage::config::load_ai_usage_enforcement()
+ .map_err(|error| anyhow::anyhow!("{error}"))?;
+ let mut config = macro_config::ConfigLoader::load::<Config>()
+ .context("failed to load agent schedule service config")?;
+ config.enable_ai_usage_enforcement = enforcement;
+ Ok(config)
}
}
diff --git a/services/scheduled_action/src/config/test.rs b/services/scheduled_action/src/config/test.rs
index aa4dcd49d8..efb772f0eb 100644
--- a/services/scheduled_action/src/config/test.rs
+++ b/services/scheduled_action/src/config/test.rs
@@ -17,6 +17,29 @@ fn config_values() -> Value {
})
}
+#[test]
+fn ai_usage_enforcement_defaults_off_and_requires_a_boolean() {
+ let config: Config = serde_json::from_value(config_values()).unwrap();
+ assert_eq!(
+ config.enable_ai_usage_enforcement,
+ ai_usage::AiUsageEnforcement::Disabled
+ );
+ for (value, expected) in [
+ (false, ai_usage::AiUsageEnforcement::Disabled),
+ (true, ai_usage::AiUsageEnforcement::Enabled),
+ ] {
+ let mut values = config_values();
+ values["ENABLE_AI_USAGE_ENFORCEMENT"] = json!(value);
+ let config: Config = serde_json::from_value(values).unwrap();
+ assert_eq!(config.enable_ai_usage_enforcement, expected);
+ }
+ for value in [json!("enabled"), json!(1)] {
+ let mut values = config_values();
+ values["ENABLE_AI_USAGE_ENFORCEMENT"] = value;
+ assert!(serde_json::from_value::<Config>(values).is_err());
+ }
+}
+
#[test]
fn event_routines_default_off_and_reuse_existing_brokers() {
let config: Config = serde_json::from_value(config_values()).unwrap();
diff --git a/services/scheduled_action/src/domain/execution.rs b/services/scheduled_action/src/domain/execution.rs
index fc63618fd3..d7d83abfd5 100644
--- a/services/scheduled_action/src/domain/execution.rs
+++ b/services/scheduled_action/src/domain/execution.rs
@@ -3,6 +3,8 @@ mod test;
use std::{sync::Arc, time::Duration};
+use ai_billing::{AiAdmissionError, AiAdmissionService, DisabledAiAdmissionService};
+use ai_usage::AiFeature;
use anyhow::{Context, Result};
use chrono::{DateTime, Utc};
use macro_uuid::{Uuid, generate_uuid_v7};
@@ -12,8 +14,8 @@ use crate::domain::event_runs::{
ClaimedEventRun, EventExecutionResult, EventExecutor, EventRunOutcome,
};
use crate::domain::models::{
- ActionExecutionRecord, ExecutionResource, ExecutionResult, InProgressExecution,
- MAX_ACTION_TIME, ScheduledAction, ScheduledActionUpdate,
+ ActionExecutionRecord, AgentTask, ExecutionResource, ExecutionResult, InProgressExecution,
+ MAX_ACTION_TIME, ResolvedTaskTarget, ScheduledAction, ScheduledActionUpdate,
};
use crate::domain::ports::{
ScheduledActionExecutor, ScheduledActionLiveUpdate, ScheduledActionRepo, ScheduledAgentRunner,
@@ -29,6 +31,8 @@ pub struct ExecutionHandle {
pub action_id: Uuid,
/// Set as soon as resource existence is established, even if preparation later fails.
pub resource: Option<ExecutionResource>,
+ // Cancellation during admission must not contact a runner that never started.
+ preparation_started: bool,
}
impl Default for ExecutionHandle {
@@ -37,6 +41,7 @@ impl Default for ExecutionHandle {
session_id: generate_uuid_v7(),
action_id: generate_uuid_v7(),
resource: None,
+ preparation_started: false,
}
}
}
@@ -47,6 +52,7 @@ pub struct InProcessExecutor<Rpo, Live, Runner> {
repo: Arc<Rpo>,
live_updates: Arc<Live>,
runner: Arc<Runner>,
+ admission: Arc<dyn AiAdmissionService>,
tracker: TaskTracker,
cancellation: CancellationToken,
}
@@ -57,6 +63,7 @@ impl<Rpo, Live, Runner> Clone for InProcessExecutor<Rpo, Live, Runner> {
repo: self.repo.clone(),
live_updates: self.live_updates.clone(),
runner: self.runner.clone(),
+ admission: self.admission.clone(),
tracker: self.tracker.clone(),
cancellation: self.cancellation.clone(),
}
@@ -69,6 +76,8 @@ where
Live: ScheduledActionLiveUpdate,
Runner: ScheduledAgentRunner,
{
+ /// Admission defaults off for compatibility; production must configure it
+ /// with `with_admission` using the shared enforcement policy.
pub fn new(
repo: Arc<Rpo>,
runner: Arc<Runner>,
@@ -80,11 +89,19 @@ where
repo,
runner,
live_updates,
+ admission: Arc::new(DisabledAiAdmissionService),
tracker,
cancellation,
}
}
+ /// Configure model admission. Agent funding and admission belong to the
+ /// session/harness service, not to the scheduler's model policy.
+ pub fn with_admission(mut self, admission: Arc<dyn AiAdmissionService>) -> Self {
+ self.admission = admission;
+ self
+ }
+
async fn prepare(
&self,
action: &ScheduledAction,
@@ -92,6 +109,12 @@ where
) -> Result<ExecutionResource> {
let owner = action.owner_user()?.clone();
let action_id = action.id.context("persisted action required")?;
+ let task: AgentTask =
+ serde_json::from_value(action.task.clone()).context("invalid agent task definition")?;
+ if matches!(task.resolve_target()?, ResolvedTaskTarget::Model { .. }) {
+ self.admission.admit(&owner, AiFeature::Automation).await?;
+ }
+ handle.preparation_started = true;
self.runner.prepare(action, handle).await?;
// Retain the resource even if publishing Started stalls or is cancelled.
let resource = handle
@@ -109,7 +132,17 @@ where
Ok(resource)
}
- async fn cancel(&self, action: &ScheduledAction, handle: &ExecutionHandle) {
+ async fn cancel(
+ &self,
+ action: &ScheduledAction,
+ handle: &ExecutionHandle,
+ error: &anyhow::Error,
+ ) {
+ if !handle.preparation_started
+ || (handle.resource.is_none() && error.is::<AiAdmissionError>())
+ {
+ return;
+ }
match tokio::time::timeout(CANCELLATION_TIMEOUT, self.runner.cancel(action, handle)).await {
Ok(Ok(())) => {}
Ok(Err(error)) => {
@@ -236,8 +269,8 @@ where
executor.runner.run(&action, &handle, None).await
})
.await;
- if result.is_err() {
- executor.cancel(&action, &handle).await;
+ if let Err(error) = &result {
+ executor.cancel(&action, &handle, error).await;
}
let record = execution_record(&action, handle.resource.clone(), start_time, &result);
let end_time = record.end_time;
@@ -309,8 +342,8 @@ where
.await
})
.await;
- if result.is_err() {
- self.cancel(&run.action, &handle).await;
+ if let Err(error) = &result {
+ self.cancel(&run.action, &handle, error).await;
}
let record = execution_record(
&run.action,
diff --git a/services/scheduled_action/src/domain/execution/test.rs b/services/scheduled_action/src/domain/execution/test.rs
index 3f6f0b9813..747860b54f 100644
--- a/services/scheduled_action/src/domain/execution/test.rs
+++ b/services/scheduled_action/src/domain/execution/test.rs
@@ -17,12 +17,144 @@ use std::sync::{
const USER: &str = "macro|[email protected]";
+struct Admission {
+ result: std::result::Result<(), AiAdmissionError>,
+ calls: Mutex<Vec<(String, AiFeature)>>,
+}
+
+impl AiAdmissionService for Admission {
+ fn admit<'a>(
+ &'a self,
+ user: &'a MacroUserIdStr<'_>,
+ feature: AiFeature,
+ ) -> ai_billing::AdmissionFuture<'a> {
+ self.calls.lock().unwrap().push((user.to_string(), feature));
+ Box::pin(async { self.result })
+ }
+}
+
+fn admission(result: std::result::Result<(), AiAdmissionError>) -> Arc<Admission> {
+ Arc::new(Admission {
+ result,
+ calls: Mutex::default(),
+ })
+}
+
+struct StalledAdmission;
+
+impl AiAdmissionService for StalledAdmission {
+ fn admit<'a>(
+ &'a self,
+ _: &'a MacroUserIdStr<'_>,
+ _: AiFeature,
+ ) -> ai_billing::AdmissionFuture<'a> {
+ Box::pin(std::future::pending())
+ }
+}
+
+#[tokio::test]
+async fn shutdown_during_admission_releases_claim_without_contacting_runner() {
+ let executor =
+ executor(Repo::default(), Runner::default()).with_admission(Arc::new(StalledAdmission));
+ let mut request = Box::pin(executor.execute_action(action()));
+ assert!(futures::poll!(&mut request).is_pending());
+ tokio::task::yield_now().await;
+ assert!(executor.repo.claim.lock().unwrap().is_some());
+ executor.cancellation.cancel();
+ assert!(request.await.unwrap_err().is::<ExecutionCancelled>());
+ drain(&executor).await;
+ assert_eq!(executor.repo.releases.load(Ordering::SeqCst), 1);
+ assert_eq!(executor.runner.preparations.load(Ordering::SeqCst), 0);
+ assert!(executor.runner.cancellations.lock().unwrap().is_empty());
+ assert!(executor.live_updates.0.lock().unwrap().is_empty());
+}
+
+fn admission_failures() -> [AiAdmissionError; 2] {
+ [
+ AiAdmissionError::Denied(ai_billing::DenyReason::AllowanceExhausted),
+ AiAdmissionError::Unavailable,
+ ]
+}
+
+#[tokio::test]
+async fn manual_and_cron_refusals_release_claims_and_advance_schedule_without_resources() {
+ for error in admission_failures() {
+ // Both the manual service and cron dispatchers use execute_action.
+ let admission = admission(Err(error));
+ let executor =
+ executor(Repo::default(), Runner::default()).with_admission(admission.clone());
+ let returned = executor.execute_action(action()).await.unwrap_err();
+ assert_eq!(returned.downcast_ref::<AiAdmissionError>(), Some(&error));
+ drain(&executor).await;
+ assert_eq!(
+ *admission.calls.lock().unwrap(),
+ [(USER.into(), AiFeature::Automation)]
+ );
+ assert_eq!(executor.runner.preparations.load(Ordering::SeqCst), 0);
+ assert_eq!(executor.runner.calls.load(Ordering::SeqCst), 0);
+ assert!(executor.runner.cancellations.lock().unwrap().is_empty());
+ assert!(executor.live_updates.0.lock().unwrap().is_empty());
+ assert_eq!(executor.repo.claims.load(Ordering::SeqCst), 1);
+ assert_eq!(executor.repo.releases.load(Ordering::SeqCst), 1);
+ assert_eq!(executor.repo.rescheduled.load(Ordering::SeqCst), 1);
+ assert!(executor.repo.claim.lock().unwrap().is_none());
+ let records = executor.repo.records.lock().unwrap();
+ assert_eq!(records.len(), 1);
+ assert!(!records[0].is_success);
+ assert!(records[0].resource_id.is_none());
+ assert_eq!(records[0].result["error"], error.to_string());
+ }
+}
+
+#[tokio::test]
+async fn event_refusals_return_terminal_bookkeeping_without_replaying_or_releasing_early() {
+ for error in admission_failures() {
+ let admission = admission(Err(error));
+ let executor =
+ executor(Repo::default(), Runner::default()).with_admission(admission.clone());
+ let result = executor.execute(&event_run(), std::future::pending()).await;
+ assert_eq!(result.outcome, EventRunOutcome::Failed);
+ let record = result.record.unwrap();
+ assert!(!record.is_success);
+ assert!(record.resource_id.is_none());
+ assert_eq!(record.result["error"], error.to_string());
+ assert_eq!(
+ *admission.calls.lock().unwrap(),
+ [(USER.into(), AiFeature::Automation)]
+ );
+ assert_eq!(executor.runner.preparations.load(Ordering::SeqCst), 0);
+ assert_eq!(executor.runner.calls.load(Ordering::SeqCst), 0);
+ assert!(executor.live_updates.0.lock().unwrap().is_empty());
+ assert!(executor.runner.cancellations.lock().unwrap().is_empty());
+ // The event worker finalizes this failure and releases run.token atomically.
+ assert_eq!(executor.repo.releases.load(Ordering::SeqCst), 0);
+ assert!(executor.repo.records.lock().unwrap().is_empty());
+ }
+}
+
+#[tokio::test]
+async fn admitted_model_execution_uses_the_persisted_owner_and_automation_feature() {
+ let admission = admission(Ok(()));
+ let executor = executor(Repo::default(), Runner::default()).with_admission(admission.clone());
+ executor.runner.finish.cancel();
+ executor.execute_action(action()).await.unwrap();
+ drain(&executor).await;
+ assert_eq!(
+ *admission.calls.lock().unwrap(),
+ [(USER.into(), AiFeature::Automation)]
+ );
+ assert_eq!(executor.runner.preparations.load(Ordering::SeqCst), 1);
+ assert_eq!(executor.runner.calls.load(Ordering::SeqCst), 1);
+ assert!(executor.repo.records.lock().unwrap()[0].is_success);
+}
+
#[derive(Default)]
struct Repo {
claim: Mutex<Option<ClaimToken>>,
claims: AtomicUsize,
claimed_revisions: Mutex<Vec<i64>>,
releases: AtomicUsize,
+ rescheduled: AtomicUsize,
records: Mutex<Vec<ActionExecutionRecord>>,
fail_persistence: bool,
stall_persistence: bool,
@@ -54,6 +186,7 @@ impl ScheduledActionRepo for Repo {
Ok(())
}
async fn update_next_run_at(&self, _: &Uuid) -> Result<()> {
+ self.rescheduled.fetch_add(1, Ordering::SeqCst);
Ok(())
}
async fn update_last_executed(&self, _: &Uuid, _: DateTime<Utc>) -> Result<()> {
diff --git a/services/scheduled_action/src/domain/service/test.rs b/services/scheduled_action/src/domain/service/test.rs
index 72ba0deb73..50ade7d2af 100644
--- a/services/scheduled_action/src/domain/service/test.rs
+++ b/services/scheduled_action/src/domain/service/test.rs
@@ -1,3 +1,4 @@
+mod admission;
mod user_cleanup;
use super::*;
@@ -121,12 +122,20 @@ impl ScheduledActionRepo for FakeRepo {
#[derive(Default)]
pub(crate) struct FakeExecutor {
calls: Mutex<Vec<ScheduledAction>>,
+ admission_error: Mutex<Option<ai_billing::AiAdmissionError>>,
+}
+
+pub(crate) fn set_admission_error(service: &TestService, error: ai_billing::AiAdmissionError) {
+ *service.executor.admission_error.lock().unwrap() = Some(error);
}
impl ScheduledActionExecutor for FakeExecutor {
async fn execute_action(&self, action: ScheduledAction) -> Result<InProgressExecution> {
let action_id = action.id.unwrap();
self.calls.lock().unwrap().push(action);
+ if let Some(error) = *self.admission_error.lock().unwrap() {
+ return Err(error.into());
+ }
Ok(InProgressExecution {
action_id,
chat_id: Some("manual-chat".into()),
diff --git a/services/scheduled_action/src/domain/service/test/admission.rs b/services/scheduled_action/src/domain/service/test/admission.rs
new file mode 100644
index 0000000000..8af18edd66
--- /dev/null
+++ b/services/scheduled_action/src/domain/service/test/admission.rs
@@ -0,0 +1,47 @@
+use super::*;
+use ai_billing::{AiAdmissionError, DenyReason};
+
+#[tokio::test]
+async fn manual_admission_keeps_error_type_and_uses_stored_owner_without_gating_management() {
+ for error in [
+ AiAdmissionError::Denied(DenyReason::AllowanceExhausted),
+ AiAdmissionError::Unavailable,
+ ] {
+ let service = service(true);
+ set_admission_error(&service, error);
+ let action = service
+ .create_action(
+ &user_principal(),
+ CreateScheduledAction::Canonical(configuration(false)),
+ )
+ .await
+ .unwrap();
+ let id = action.id.unwrap();
+ let stored_owner = MacroUserIdStr::parse_from_str(FOREIGN_USER).unwrap();
+ set_stored_owner(&service, id, Owner::User(stored_owner.clone()));
+ let returned = service
+ .execute_action_now(owner_receipt(id))
+ .await
+ .unwrap_err();
+ assert_eq!(returned.downcast_ref::<AiAdmissionError>(), Some(&error));
+ assert_eq!(
+ service.executor.calls.lock().unwrap()[0]
+ .owner_user()
+ .unwrap(),
+ &stored_owner
+ );
+ assert_eq!(service.get_actions(user(), true).await.unwrap().len(), 1);
+ service
+ .update_action(edit_receipt(id), update(configuration(false)))
+ .await
+ .unwrap();
+ service.set_enabled(edit_receipt(id), false).await.unwrap();
+ service
+ .get_execution_records(view_receipt(id))
+ .await
+ .unwrap();
+ service.delete_action(owner_receipt(id)).await.unwrap();
+ assert!(service.get_actions(user(), true).await.unwrap().is_empty());
+ assert_eq!(service.executor.calls.lock().unwrap().len(), 1);
+ }
+}
diff --git a/services/scheduled_action/src/domain/target_runner.rs b/services/scheduled_action/src/domain/target_runner.rs
index a7cdfced47..2a46ca887c 100644
--- a/services/scheduled_action/src/domain/target_runner.rs
+++ b/services/scheduled_action/src/domain/target_runner.rs
@@ -49,6 +49,9 @@ impl<Model: ScheduledAgentRunner, Sessions: RoutineSessions> ScheduledAgentRunne
let task = task(action)?;
let (bot_id, model) = match task.resolve_target()? {
ResolvedTaskTarget::Model { .. } => return self.model.prepare(action, handle).await,
+ // The session/harness service owns funding classification and gates
+ // managed work before provisioning; external targets are not charged
+ // as scheduler-owned model execution.
ResolvedTaskTarget::Agent { bot_id, model } => (bot_id, model),
};
let identity = session_action(action, handle, bot_id)?;
@@ -69,6 +72,9 @@ impl<Model: ScheduledAgentRunner, Sessions: RoutineSessions> ScheduledAgentRunne
Ok(())
}
Ok(_) => Err(RoutineSessionError::SessionMismatch.into()),
+ // A definitive admission refusal created no session. Preserve the
+ // shared type for HTTP mapping and resource-free executor cleanup.
+ Err(RoutineSessionError::Admission(error)) => Err(error.into()),
Err(error) => {
// ModelMismatch proves the requested owner/session was established.
// Other ambiguous failures may have persisted it too; a safe,
diff --git a/services/scheduled_action/src/domain/target_runner/test.rs b/services/scheduled_action/src/domain/target_runner/test.rs
index ffd43d7665..a03653c58a 100644
--- a/services/scheduled_action/src/domain/target_runner/test.rs
+++ b/services/scheduled_action/src/domain/target_runner/test.rs
@@ -27,6 +27,87 @@ use tokio_util::{sync::CancellationToken, task::TaskTracker};
const USER: &str = "macro|[email protected]";
+struct NoModelAdmission;
+
+impl ai_billing::AiAdmissionService for NoModelAdmission {
+ fn admit<'a>(
+ &'a self,
+ _: &'a MacroUserIdStr<'_>,
+ _: ai_usage::AiFeature,
+ ) -> ai_billing::AdmissionFuture<'a> {
+ panic!("agent funding must be decided by the session/harness service")
+ }
+}
+
+#[tokio::test]
+async fn agent_targets_delegate_admission_and_never_apply_the_model_gate() {
+ use ai_billing::{AiAdmissionError, DenyReason};
+
+ for admission_error in [
+ None,
+ Some(AiAdmissionError::Denied(DenyReason::AllowanceExhausted)),
+ Some(AiAdmissionError::Unavailable),
+ ] {
+ let runner = Arc::new(runner(Sessions {
+ prepare_error: admission_error.map(RoutineSessionError::Admission),
+ statuses: Mutex::new([Ok(RoutineActionStatus::Succeeded)].into()),
+ ..Default::default()
+ }));
+ let live = Arc::new(Live::default());
+ let executor = InProcessExecutor::new(
+ Arc::new(UnusedRepo),
+ runner.clone(),
+ live.clone(),
+ TaskTracker::new(),
+ CancellationToken::new(),
+ )
+ .with_admission(Arc::new(NoModelAdmission));
+ let run = event_run();
+ let result = executor.execute(&run, std::future::pending()).await;
+ let record = result.record.unwrap();
+ let preparations = runner.sessions.preparations.lock().unwrap();
+ assert_eq!(preparations.len(), 1);
+ assert_eq!(
+ &preparations[0].selection.owner,
+ run.action.owner_user().unwrap()
+ );
+ assert!(runner.model.calls.lock().unwrap().is_empty());
+ assert!(runner.sessions.stops.lock().unwrap().is_empty());
+ if let Some(error) = admission_error {
+ assert_eq!(result.outcome, EventRunOutcome::Failed);
+ assert!(!record.is_success);
+ assert!(record.resource_id.is_none());
+ assert_eq!(record.result["error"], error.to_string());
+ assert!(runner.sessions.prompts.lock().unwrap().is_empty());
+ assert!(runner.sessions.reads.lock().unwrap().is_empty());
+ assert!(live.0.lock().unwrap().is_empty());
+ } else {
+ assert_eq!(result.outcome, EventRunOutcome::Succeeded);
+ assert!(record.is_success);
+ assert_eq!(runner.sessions.prompts.lock().unwrap().len(), 1);
+ }
+ }
+}
+
+#[tokio::test]
+async fn agent_preparation_preserves_typed_admission_failures() {
+ use ai_billing::{AiAdmissionError, DenyReason};
+ for error in [
+ AiAdmissionError::Denied(DenyReason::AllowanceExhausted),
+ AiAdmissionError::Unavailable,
+ ] {
+ let runner = runner(Sessions {
+ prepare_error: Some(RoutineSessionError::Admission(error)),
+ ..Default::default()
+ });
+ let mut handle = ExecutionHandle::default();
+ let returned = runner.prepare(&action(), &mut handle).await.unwrap_err();
+ assert_eq!(returned.downcast_ref::<AiAdmissionError>(), Some(&error));
+ assert!(handle.resource.is_none());
+ assert!(runner.sessions.reads.lock().unwrap().is_empty());
+ }
+}
+
#[derive(Default)]
struct Model {
calls: Mutex<Vec<&'static str>>,
@@ -603,26 +684,45 @@ async fn executor_deadline_stops_preallocated_session_even_during_preparation()
#[tokio::test]
async fn executor_failed_prompt_finalizes_agent_history_and_stops_once() {
- let runner = Arc::new(runner(Sessions {
- prompt_error: Some(RoutineSessionError::PromptDeliveryUnknown),
- ..Default::default()
- }));
- let executor = InProcessExecutor::new(
- Arc::new(UnusedRepo),
- runner.clone(),
- Arc::new(Live::default()),
- TaskTracker::new(),
- CancellationToken::new(),
- );
- let result = executor.execute(&event_run(), std::future::pending()).await;
- assert_eq!(result.outcome, EventRunOutcome::Failed);
- let record = result.record.unwrap();
- let metadata: ExecutionResult = serde_json::from_value(record.result).unwrap();
- let resource = metadata.resource.unwrap();
- assert_eq!(resource.resource_type, ExecutionResourceType::Agent);
- assert_eq!(record.resource_id, Some(resource.id));
- assert_eq!(runner.sessions.prompts.lock().unwrap().len(), 1);
- assert_eq!(runner.sessions.stops.lock().unwrap().len(), 1);
+ use ai_billing::{AiAdmissionError, DenyReason};
+ for error in [
+ RoutineSessionError::PromptDeliveryUnknown,
+ RoutineSessionError::Admission(AiAdmissionError::Denied(DenyReason::AllowanceExhausted)),
+ RoutineSessionError::Admission(AiAdmissionError::Unavailable),
+ ] {
+ let runner = Arc::new(runner(Sessions {
+ prompt_error: Some(error),
+ ..Default::default()
+ }));
+ let live = Arc::new(Live::default());
+ let executor = InProcessExecutor::new(
+ Arc::new(UnusedRepo),
+ runner.clone(),
+ live.clone(),
+ TaskTracker::new(),
+ CancellationToken::new(),
+ );
+ let result = executor.execute(&event_run(), std::future::pending()).await;
+ assert_eq!(result.outcome, EventRunOutcome::Failed);
+ let record = result.record.unwrap();
+ let metadata: ExecutionResult = serde_json::from_value(record.result).unwrap();
+ let resource = metadata.resource.unwrap();
+ assert_eq!(resource.resource_type, ExecutionResourceType::Agent);
+ assert_eq!(record.resource_id, Some(resource.id));
+ assert_eq!(metadata.error, Some(error.to_string()));
+ assert_eq!(runner.sessions.prompts.lock().unwrap().len(), 1);
+ assert_eq!(runner.sessions.stops.lock().unwrap().len(), 1);
+ assert!(matches!(
+ live.0.lock().unwrap().as_slice(),
+ [
+ ScheduledActionUpdate::Started { .. },
+ ScheduledActionUpdate::Stopped {
+ is_success: false,
+ ..
+ },
+ ]
+ ));
+ }
}
#[tokio::test]
diff --git a/services/scheduled_action/src/inbound/axum_router.rs b/services/scheduled_action/src/inbound/axum_router.rs
index 434f4f6d0f..a13f0db1ab 100644
--- a/services/scheduled_action/src/inbound/axum_router.rs
+++ b/services/scheduled_action/src/inbound/axum_router.rs
@@ -8,6 +8,7 @@ use crate::domain::models::{
use crate::domain::ports::ScheduledActionService;
use crate::domain::target_validation::TargetValidationError;
use agent_session::domain::routines::RoutineSessionError;
+use ai_billing::{AiAdmissionError, inbound::admission::AiAdmissionErrorBody};
use axum::extract::{FromRef, Path, Query, State, rejection::JsonRejection};
use axum::http::StatusCode;
use axum::response::IntoResponse;
@@ -363,6 +364,8 @@ where
(status = 401, body = String),
(status = 404, body = String),
(status = 409, body = String, description = "Action is already running"),
+ (status = 402, body = AiAdmissionErrorBody, description = "AI allowance exhausted"),
+ (status = 503, body = AiAdmissionErrorBody, description = "AI usage validation unavailable; retry later"),
(status = 500, body = String),
)
)]
@@ -441,6 +444,9 @@ impl IntoResponse for ScheduledActionApiError {
}
Self::Service(error) => error,
};
+ if let Some(admission) = error.downcast_ref::<AiAdmissionError>() {
+ return (*admission).into_response();
+ }
if let Some(policy) = error.downcast_ref::<ActionPolicyError>() {
let status = match policy {
ActionPolicyError::NotFound => StatusCode::NOT_FOUND,
@@ -462,6 +468,7 @@ impl IntoResponse for ScheduledActionApiError {
}
if let Some(session) = error.downcast_ref::<RoutineSessionError>() {
let (status, message) = match session {
+ RoutineSessionError::Admission(error) => return (*error).into_response(),
RoutineSessionError::InvalidCommand | RoutineSessionError::ModelMismatch => {
(StatusCode::BAD_REQUEST, session.to_string())
}
diff --git a/services/scheduled_action/src/inbound/axum_router/test.rs b/services/scheduled_action/src/inbound/axum_router/test.rs
index 3f16b23f62..7ed9d09b86 100644
--- a/services/scheduled_action/src/inbound/axum_router/test.rs
+++ b/services/scheduled_action/src/inbound/axum_router/test.rs
@@ -27,6 +27,79 @@ use std::collections::HashMap;
use tower::ServiceExt;
use utoipa::OpenApi;
+#[tokio::test]
+async fn manual_execution_returns_sanitized_admission_errors_after_authorization() {
+ use crate::domain::service::test::set_admission_error;
+ use ai_billing::{AiAdmissionError, DenyReason};
+
+ for (error, expected_status) in [
+ (
+ AiAdmissionError::Denied(DenyReason::AllowanceExhausted),
+ StatusCode::PAYMENT_REQUIRED,
+ ),
+ (
+ AiAdmissionError::Unavailable,
+ StatusCode::SERVICE_UNAVAILABLE,
+ ),
+ ] {
+ let svc = service(true);
+ set_admission_error(&svc, error);
+ let app = router_with(svc, FakeEntityAccessService::owner_only());
+ let (status, created) =
+ request(&app, "POST", "/scheduled-actions", "owner", legacy()).await;
+ assert_eq!(status, StatusCode::CREATED);
+ let url = format!(
+ "/scheduled-actions/{}/execute",
+ created["id"].as_str().unwrap()
+ );
+ let (status, body) = request(&app, "POST", &url, "owner", Value::Null).await;
+ assert_eq!(status, expected_status);
+ assert_eq!(
+ body,
+ json!({"code": error.code(), "error": error.to_string()})
+ );
+ let (status, body) = request(&app, "POST", &url, "stranger", Value::Null).await;
+ assert_eq!(status, StatusCode::UNAUTHORIZED);
+ assert_ne!(body["code"], error.code());
+ }
+}
+
+#[tokio::test]
+async fn remote_session_admission_uses_the_same_public_http_contract() {
+ use ai_billing::{AiAdmissionError, DenyReason};
+ for error in [
+ AiAdmissionError::Denied(DenyReason::OverageLimitReached),
+ AiAdmissionError::Unavailable,
+ ] {
+ let response = ScheduledActionApiError::from(anyhow::Error::new(
+ RoutineSessionError::Admission(error),
+ ))
+ .into_response();
+ assert_eq!(
+ response.status(),
+ ai_billing::inbound::admission::admission_status(error)
+ );
+ let bytes = to_bytes(response.into_body(), usize::MAX).await.unwrap();
+ let body: Value = serde_json::from_slice(&bytes).unwrap();
+ assert_eq!(
+ body,
+ json!({"code": error.code(), "error": error.to_string()})
+ );
+ }
+}
+
+#[test]
+fn manual_execution_documents_quota_and_retryable_validation_failures() {
+ let schema = serde_json::to_value(crate::swagger::ApiDoc::openapi()).unwrap();
+ let responses = &schema["paths"]["/scheduled-actions/{id}/execute"]["post"]["responses"];
+ for status in ["402", "503"] {
+ assert_eq!(
+ responses[status]["content"]["application/json"]["schema"]["$ref"],
+ "#/components/schemas/AiAdmissionErrorBody"
+ );
+ }
+}
+
const OTHER: &str = "macro|[email protected]";
const VIEWER: &str = "macro|[email protected]";
const BOT_TOKEN: &str = "team-bot-token";
diff --git a/services/scheduled_action/src/outbound/agent_session_client/test.rs b/services/scheduled_action/src/outbound/agent_session_client/test.rs
index 61cf588d4f..e61b314d8b 100644
--- a/services/scheduled_action/src/outbound/agent_session_client/test.rs
+++ b/services/scheduled_action/src/outbound/agent_session_client/test.rs
@@ -197,6 +197,16 @@ async fn all_commands_use_internal_auth_and_domain_wire_contract_at_both_prefixe
#[tokio::test]
async fn typed_sanitized_domain_errors_are_preserved() {
for (status, code) in [
+ (
+ 402,
+ RoutineSessionError::Admission(ai_billing::AiAdmissionError::Denied(
+ ai_billing::DenyReason::AllowanceExhausted,
+ )),
+ ),
+ (
+ 503,
+ RoutineSessionError::Admission(ai_billing::AiAdmissionError::Unavailable),
+ ),
(400, RoutineSessionError::InvalidCommand),
(403, RoutineSessionError::Forbidden),
(404, RoutineSessionError::PersonaUnavailable),
diff --git a/services/scheduled_action/src/swagger.rs b/services/scheduled_action/src/swagger.rs
index cc7c5c57c7..9d0dd12b09 100644
--- a/services/scheduled_action/src/swagger.rs
+++ b/services/scheduled_action/src/swagger.rs
@@ -17,6 +17,7 @@ use crate::domain::models::{
ExecutionResult, InProgressExecution, LegacyActionConfiguration, RoutineModelId, Schedule,
ScheduledAction, ScheduledActionUpdate, UpdateScheduledAction,
};
+use ai_billing::inbound::admission::AiAdmissionErrorBody;
use model::response::EmptyResponse;
#[derive(OpenApi)]
@@ -38,6 +39,7 @@ use model::response::EmptyResponse;
),
components(
schemas(
+ AiAdmissionErrorBody,
ScheduledAction,
ScheduledActionResponse,
ActionConfiguration,