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(agents): parent-aware invocation, sessions, and reply delivery for messages (#6441)

gbirmana21712ca28ea
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.json
index 25e5a992d9..84c04024ff 100644
--- a/.github/workspace-dep-closures.json
+++ b/.github/workspace-dep-closures.json
@@ -921,6 +921,8 @@
"crates/bot_token",
"crates/broadcast",
"crates/channel_sender",
+ "crates/connection_gateway_client",
+ "crates/connection_gateway_models",
"crates/cowlike",
"crates/crm",
"crates/database_env_vars",
@@ -953,9 +955,11 @@
"crates/macro_event_topics",
"crates/macro_queues",
"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",
@@ -2180,7 +2184,11 @@
"crates/attachment",
"crates/bot_id",
"crates/bot_token",
+ "crates/broadcast",
+ "crates/channel_sender",
"crates/collab_surface",
+ "crates/connection_gateway_client",
+ "crates/connection_gateway_models",
"crates/cowlike",
"crates/database_env_vars",
"crates/document_sub_type",
@@ -2188,29 +2196,44 @@
"crates/genai_telemetry",
"crates/harness_id",
"crates/harness_token",
+ "crates/invite_email",
+ "crates/kafka_util",
+ "crates/last_online_tracker",
"crates/lexical_client",
"crates/macro_auth",
"crates/macro_authorization",
"crates/macro_entrypoint",
"crates/macro_env",
"crates/macro_env_var",
+ "crates/macro_event_broker",
+ "crates/macro_event_topics",
+ "crates/macro_service_urls",
"crates/macro_sync_service_jwt",
+ "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_user",
"crates/models_bulk_upload",
"crates/models_entity_access_management",
"crates/models_pagination",
"crates/models_permissions",
+ "crates/models_properties",
"crates/non_empty",
+ "crates/notification",
+ "crates/notification_state",
"crates/prompt",
+ "crates/rate_limit",
"crates/remote_env_var",
"crates/sync_service",
"crates/sync_service_client",
+ "crates/system_properties",
"crates/workspace-hack"
],
"comms_db_client": [
@@ -2582,6 +2605,8 @@
"crates/bot_token",
"crates/broadcast",
"crates/channel_sender",
+ "crates/connection_gateway_client",
+ "crates/connection_gateway_models",
"crates/cowlike",
"crates/crm",
"crates/database_env_vars",
@@ -2621,9 +2646,11 @@
"crates/macro_middleware",
"crates/macro_queues",
"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",
@@ -3522,6 +3549,8 @@
"crates/bot_token",
"crates/broadcast",
"crates/channel_sender",
+ "crates/connection_gateway_client",
+ "crates/connection_gateway_models",
"crates/cowlike",
"crates/crm",
"crates/database_env_vars",
@@ -3557,9 +3586,11 @@
"crates/macro_queues",
"crates/macro_service_urls",
"crates/macro_sha_count_client",
+ "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",
@@ -3614,6 +3645,8 @@
"crates/bot_token",
"crates/broadcast",
"crates/channel_sender",
+ "crates/connection_gateway_client",
+ "crates/connection_gateway_models",
"crates/cowlike",
"crates/crm",
"crates/database_env_vars",
@@ -3642,9 +3675,11 @@
"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",
@@ -3738,6 +3773,8 @@
"crates/bot_token",
"crates/broadcast",
"crates/channel_sender",
+ "crates/connection_gateway_client",
+ "crates/connection_gateway_models",
"crates/cowlike",
"crates/crm",
"crates/database_env_vars",
@@ -3768,9 +3805,11 @@
"crates/macro_event_topics",
"crates/macro_queues",
"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",
@@ -3812,6 +3851,8 @@
"crates/bot_token",
"crates/broadcast",
"crates/channel_sender",
+ "crates/connection_gateway_client",
+ "crates/connection_gateway_models",
"crates/cowlike",
"crates/crm",
"crates/database_env_vars",
@@ -3842,9 +3883,11 @@
"crates/macro_event_topics",
"crates/macro_queues",
"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",
@@ -3936,6 +3979,7 @@
"crates/macro_user_id",
"crates/macro_uuid",
"crates/mention_utils",
+ "crates/messages",
"crates/model",
"crates/model-entity",
"crates/model-error-response",
@@ -3986,6 +4030,8 @@
"crates/bot_token",
"crates/broadcast",
"crates/channel_sender",
+ "crates/connection_gateway_client",
+ "crates/connection_gateway_models",
"crates/cowlike",
"crates/crm",
"crates/database_env_vars",
@@ -4015,9 +4061,11 @@
"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",
@@ -4055,6 +4103,8 @@
"crates/bot_token",
"crates/broadcast",
"crates/channel_sender",
+ "crates/connection_gateway_client",
+ "crates/connection_gateway_models",
"crates/cowlike",
"crates/crm",
"crates/database_env_vars",
@@ -4085,9 +4135,11 @@
"crates/macro_event_topics",
"crates/macro_queues",
"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",
@@ -4639,6 +4691,8 @@
"crates/bot_token",
"crates/broadcast",
"crates/channel_sender",
+ "crates/connection_gateway_client",
+ "crates/connection_gateway_models",
"crates/cowlike",
"crates/crm",
"crates/database_env_vars",
@@ -4669,9 +4723,11 @@
"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",
@@ -5486,13 +5542,60 @@
"crates/workspace-hack"
],
"lexical_client": [
+ "crates/agent",
"crates/agent_fold",
"crates/agent_runtime_protocol",
+ "crates/ai_toolset",
+ "crates/ai_usage",
+ "crates/attachment",
+ "crates/bot_id",
+ "crates/bot_token",
+ "crates/broadcast",
+ "crates/channel_sender",
+ "crates/connection_gateway_client",
+ "crates/connection_gateway_models",
"crates/cowlike",
+ "crates/database_env_vars",
+ "crates/document_sub_type",
+ "crates/entity_access",
+ "crates/genai_telemetry",
+ "crates/harness_id",
+ "crates/harness_token",
+ "crates/invite_email",
+ "crates/kafka_util",
+ "crates/last_online_tracker",
"crates/lexical_client",
+ "crates/macro_auth",
+ "crates/macro_authorization",
+ "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_user",
+ "crates/models_bulk_upload",
+ "crates/models_entity_access_management",
+ "crates/models_pagination",
+ "crates/models_permissions",
+ "crates/models_properties",
"crates/non_empty",
+ "crates/notification",
+ "crates/notification_state",
+ "crates/prompt",
+ "crates/rate_limit",
+ "crates/remote_env_var",
+ "crates/system_properties",
"crates/workspace-hack"
],
"lexical_mention_extractor": [
@@ -6923,6 +7026,8 @@
"crates/bot_token",
"crates/broadcast",
"crates/channel_sender",
+ "crates/connection_gateway_client",
+ "crates/connection_gateway_models",
"crates/cowlike",
"crates/crm",
"crates/database_env_vars",
@@ -6953,9 +7058,11 @@
"crates/macro_event_topics",
"crates/macro_queues",
"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",
@@ -6997,6 +7104,8 @@
"crates/bot_token",
"crates/broadcast",
"crates/channel_sender",
+ "crates/connection_gateway_client",
+ "crates/connection_gateway_models",
"crates/cowlike",
"crates/crm",
"crates/database_env_vars",
@@ -7027,9 +7136,11 @@
"crates/macro_event_topics",
"crates/macro_queues",
"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",
@@ -8513,6 +8624,8 @@
"crates/bot_token",
"crates/broadcast",
"crates/channel_sender",
+ "crates/connection_gateway_client",
+ "crates/connection_gateway_models",
"crates/cowlike",
"crates/crm",
"crates/database_env_vars",
@@ -8541,9 +8654,11 @@
"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",
@@ -8722,14 +8837,21 @@
"crates/attachment",
"crates/bot_id",
"crates/bot_token",
+ "crates/broadcast",
+ "crates/channel_sender",
"crates/connection_gateway_client",
"crates/connection_gateway_models",
"crates/cowlike",
+ "crates/database_env_vars",
"crates/document_sub_type",
"crates/embedding",
+ "crates/entity_access",
"crates/genai_telemetry",
"crates/harness_id",
"crates/harness_token",
+ "crates/invite_email",
+ "crates/kafka_util",
+ "crates/last_online_tracker",
"crates/lexical_client",
"crates/macro_auth",
"crates/macro_authorization",
@@ -8737,17 +8859,30 @@
"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_user",
+ "crates/models_bulk_upload",
+ "crates/models_entity_access_management",
+ "crates/models_pagination",
+ "crates/models_permissions",
"crates/models_properties",
"crates/non_empty",
+ "crates/notification",
+ "crates/notification_state",
"crates/prompt",
+ "crates/rate_limit",
"crates/remote_env_var",
"crates/secretsmanager_client",
"crates/system_properties",
@@ -8909,6 +9044,7 @@
"crates/macro_user_id",
"crates/macro_uuid",
"crates/mention_utils",
+ "crates/messages",
"crates/model",
"crates/model-entity",
"crates/model-error-response",
@@ -8950,6 +9086,8 @@
"crates/bot_token",
"crates/broadcast",
"crates/channel_sender",
+ "crates/connection_gateway_client",
+ "crates/connection_gateway_models",
"crates/cowlike",
"crates/crm",
"crates/database_env_vars",
@@ -8981,9 +9119,11 @@
"crates/macro_event_topics",
"crates/macro_queues",
"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",
diff --git a/.sqlx/query-25a11c79c03cc2c700b6ffbeb460daa7ce462e3b28cd04e0ab90018239051df4.json b/.sqlx/query-0953c73b72345668f2cfb7fbe14339fc4f48e11fae0349c0b60ffc477af81e65.json
similarity index 81%
rename from .sqlx/query-25a11c79c03cc2c700b6ffbeb460daa7ce462e3b28cd04e0ab90018239051df4.json
rename to .sqlx/query-0953c73b72345668f2cfb7fbe14339fc4f48e11fae0349c0b60ffc477af81e65.json
index a859cfcccd..6e37534ca9 100644
--- a/.sqlx/query-25a11c79c03cc2c700b6ffbeb460daa7ce462e3b28cd04e0ab90018239051df4.json
+++ b/.sqlx/query-0953c73b72345668f2cfb7fbe14339fc4f48e11fae0349c0b60ffc477af81e65.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT\n id, name, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, repo_branch, pull_request_url, workspace, sandbox_size, instructions,\n mcp_scope, mcp_servers, acp_session_id, status,\n status_event_name, agent_session.created_at, modified_at,\n (SELECT channel_id FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_channel_id?\",\n ext.provider AS \"external_provider?\", ext.external_id AS \"external_id?\",\n ext.external_name AS \"external_name?\", ext.external_url AS \"external_url?\",\n ext.last_run_id AS \"external_last_run_id?\"\n FROM agent_session\n LEFT JOIN external_agent_session AS ext ON ext.agent_session_id = agent_session.id\n WHERE thread_id = $1\n ORDER BY agent_session.created_at DESC\n ",
+ "query": "\n SELECT\n id, name, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, repo_branch, pull_request_url, workspace, sandbox_size, instructions,\n mcp_scope, mcp_servers, acp_session_id, status,\n status_event_name, agent_session.created_at, modified_at,\n (SELECT jsonb_build_object('type', parent_entity_type, 'id', parent_entity_id)\n FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_parent?: Json<MessageParent>\",\n ext.provider AS \"external_provider?\", ext.external_id AS \"external_id?\",\n ext.external_name AS \"external_name?\", ext.external_url AS \"external_url?\",\n ext.last_run_id AS \"external_last_run_id?\"\n FROM agent_session\n LEFT JOIN external_agent_session AS ext ON ext.agent_session_id = agent_session.id\n WHERE id = $1\n ",
"describe": {
"columns": [
{
@@ -110,8 +110,8 @@
},
{
"ordinal": 21,
- "name": "thread_channel_id?",
- "type_info": "Uuid"
+ "name": "thread_parent?: Json<MessageParent>",
+ "type_info": "Jsonb"
},
{
"ordinal": 22,
@@ -174,5 +174,5 @@
true
]
},
- "hash": "25a11c79c03cc2c700b6ffbeb460daa7ce462e3b28cd04e0ab90018239051df4"
+ "hash": "0953c73b72345668f2cfb7fbe14339fc4f48e11fae0349c0b60ffc477af81e65"
}
diff --git a/.sqlx/query-09d165c95c65c1c557077270a3ae8337815d014b73097e578c5b5bd43e8b6ce4.json b/.sqlx/query-09d165c95c65c1c557077270a3ae8337815d014b73097e578c5b5bd43e8b6ce4.json
deleted file mode 100644
index e8ca3df16d..0000000000
--- a/.sqlx/query-09d165c95c65c1c557077270a3ae8337815d014b73097e578c5b5bd43e8b6ce4.json
+++ /dev/null
@@ -1,16 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "WITH u AS (INSERT INTO macro_user (id, username, email, stripe_customer_id) VALUES ($1,$2,$2,$2) RETURNING id) INSERT INTO \"User\" (\"id\", \"email\", \"macro_user_id\") SELECT $3,$2,u.id FROM u",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Uuid",
- "Text",
- "Text"
- ]
- },
- "nullable": []
- },
- "hash": "09d165c95c65c1c557077270a3ae8337815d014b73097e578c5b5bd43e8b6ce4"
-}
diff --git a/.sqlx/query-15caf267eba0d6ffee5e4b14d19d57a3f252dcbd4103166571cdfef584be1e9c.json b/.sqlx/query-15caf267eba0d6ffee5e4b14d19d57a3f252dcbd4103166571cdfef584be1e9c.json
deleted file mode 100644
index 728f954b68..0000000000
--- a/.sqlx/query-15caf267eba0d6ffee5e4b14d19d57a3f252dcbd4103166571cdfef584be1e9c.json
+++ /dev/null
@@ -1,22 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "SELECT channel_id FROM comms_messages WHERE id = $1",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "channel_id",
- "type_info": "Uuid"
- }
- ],
- "parameters": {
- "Left": [
- "Uuid"
- ]
- },
- "nullable": [
- true
- ]
- },
- "hash": "15caf267eba0d6ffee5e4b14d19d57a3f252dcbd4103166571cdfef584be1e9c"
-}
diff --git a/.sqlx/query-9c81dc959ddc96e6d9bcd928bb4827184e90f2ece1838299f3d67dda72485836.json b/.sqlx/query-349c3a9085f7a4d136fea60c95d2a5da45a619527c60d1a5f743f4d81abc43f1.json
similarity index 84%
rename from .sqlx/query-9c81dc959ddc96e6d9bcd928bb4827184e90f2ece1838299f3d67dda72485836.json
rename to .sqlx/query-349c3a9085f7a4d136fea60c95d2a5da45a619527c60d1a5f743f4d81abc43f1.json
index cd816ecd69..9bc07d9f0b 100644
--- a/.sqlx/query-9c81dc959ddc96e6d9bcd928bb4827184e90f2ece1838299f3d67dda72485836.json
+++ b/.sqlx/query-349c3a9085f7a4d136fea60c95d2a5da45a619527c60d1a5f743f4d81abc43f1.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n INSERT INTO agent_session (\n id, owner_id, thread_id, originating_message_id, bot_id, model,\n harness, repo_url, workspace, sandbox_size, instructions,\n acp_session_id, status, status_event_name, egress_token_hash,\n mcp_scope, mcp_servers, repo_branch\n )\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18)\n RETURNING\n id, name, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, repo_branch, pull_request_url, workspace, sandbox_size, instructions,\n mcp_scope, mcp_servers, acp_session_id, status,\n status_event_name, created_at, modified_at,\n (SELECT channel_id FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_channel_id?\",\n -- A row being created cannot have an external identity yet.\n NULL::TEXT AS \"external_provider?\", NULL::TEXT AS \"external_id?\",\n NULL::TEXT AS \"external_name?\", NULL::TEXT AS \"external_url?\",\n NULL::TEXT AS \"external_last_run_id?\"\n ",
+ "query": "\n INSERT INTO agent_session (\n id, owner_id, thread_id, originating_message_id, bot_id, model,\n harness, repo_url, workspace, sandbox_size, instructions,\n acp_session_id, status, status_event_name, egress_token_hash,\n mcp_scope, mcp_servers, repo_branch\n )\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18)\n RETURNING\n id, name, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, repo_branch, pull_request_url, workspace, sandbox_size, instructions,\n mcp_scope, mcp_servers, acp_session_id, status,\n status_event_name, created_at, modified_at,\n (SELECT jsonb_build_object('type', parent_entity_type, 'id', parent_entity_id)\n FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_parent?: Json<MessageParent>\",\n -- A row being created cannot have an external identity yet.\n NULL::TEXT AS \"external_provider?\", NULL::TEXT AS \"external_id?\",\n NULL::TEXT AS \"external_name?\", NULL::TEXT AS \"external_url?\",\n NULL::TEXT AS \"external_last_run_id?\"\n ",
"describe": {
"columns": [
{
@@ -110,8 +110,8 @@
},
{
"ordinal": 21,
- "name": "thread_channel_id?",
- "type_info": "Uuid"
+ "name": "thread_parent?: Json<MessageParent>",
+ "type_info": "Jsonb"
},
{
"ordinal": 22,
@@ -191,5 +191,5 @@
null
]
},
- "hash": "9c81dc959ddc96e6d9bcd928bb4827184e90f2ece1838299f3d67dda72485836"
+ "hash": "349c3a9085f7a4d136fea60c95d2a5da45a619527c60d1a5f743f4d81abc43f1"
}
diff --git a/.sqlx/query-7101ea0a8cc97511d2c071783abcc6d0e841215c5ebddc2e3bc8b98ac203e47c.json b/.sqlx/query-5b4956ff23c99caf7019749ed49d21d3a2be86ea38194ca3472711d880420b39.json
similarity index 78%
rename from .sqlx/query-7101ea0a8cc97511d2c071783abcc6d0e841215c5ebddc2e3bc8b98ac203e47c.json
rename to .sqlx/query-5b4956ff23c99caf7019749ed49d21d3a2be86ea38194ca3472711d880420b39.json
index a2336c3044..fe8b913263 100644
--- a/.sqlx/query-7101ea0a8cc97511d2c071783abcc6d0e841215c5ebddc2e3bc8b98ac203e47c.json
+++ b/.sqlx/query-5b4956ff23c99caf7019749ed49d21d3a2be86ea38194ca3472711d880420b39.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n WITH viewer_source_ids AS (\n SELECT cp.channel_id::text AS source_id\n FROM comms_channel_participants cp\n WHERE cp.user_id = $2 AND cp.left_at IS NULL\n UNION ALL\n SELECT t.team_id::text FROM team_user t WHERE t.user_id = $2\n UNION ALL\n SELECT $2\n )\n SELECT\n s.id,\n s.name,\n s.owner_id,\n s.bot_id,\n s.status,\n s.status_event_name,\n s.created_at,\n s.modified_at,\n EXISTS (\n SELECT 1 FROM entity_access ea\n WHERE ea.entity_id = s.id\n AND ea.entity_type = 'agent_session'\n AND ea.source_id IN (SELECT source_id FROM viewer_source_ids)\n ) AS \"has_access!\"\n FROM agent_session s\n WHERE s.id = ANY($1)\n ",
+ "query": "\n WITH viewer_source_ids AS (\n SELECT cp.channel_id::text AS source_id\n FROM comms_channel_participants cp\n WHERE cp.user_id = $2 AND cp.left_at IS NULL\n UNION ALL\n SELECT t.team_id::text FROM team_user t WHERE t.user_id = $2\n UNION ALL\n SELECT $2\n )\n SELECT\n s.id,\n s.name,\n s.owner_id,\n s.bot_id,\n s.status,\n s.status_event_name,\n s.created_at,\n s.modified_at,\n EXISTS (\n SELECT 1 FROM entity_access ea\n WHERE ea.entity_id = s.id\n AND ea.entity_type = 'agent_session'\n AND ea.source_id IN (SELECT source_id FROM viewer_source_ids)\n ) AS \"has_access!\",\n (SELECT jsonb_build_object('type', parent_entity_type, 'id', parent_entity_id)\n FROM comms_messages WHERE id = s.thread_id)\n AS \"thread_parent?: Json<MessageParent>\"\n FROM agent_session s\n WHERE s.id = ANY($1)\n ",
"describe": {
"columns": [
{
@@ -47,6 +47,11 @@
"ordinal": 8,
"name": "has_access!",
"type_info": "Bool"
+ },
+ {
+ "ordinal": 9,
+ "name": "thread_parent?: Json<MessageParent>",
+ "type_info": "Jsonb"
}
],
"parameters": {
@@ -64,8 +69,9 @@
true,
false,
false,
+ null,
null
]
},
- "hash": "7101ea0a8cc97511d2c071783abcc6d0e841215c5ebddc2e3bc8b98ac203e47c"
+ "hash": "5b4956ff23c99caf7019749ed49d21d3a2be86ea38194ca3472711d880420b39"
}
diff --git a/.sqlx/query-dacaf399371a115436903c7a02db483923b64b662f6d6671f8775ee737aca657.json b/.sqlx/query-5c5bb5665c2f17e43ed18d2229651c5ddef91721ff24d669ac7b6ce26298e26e.json
similarity index 79%
rename from .sqlx/query-dacaf399371a115436903c7a02db483923b64b662f6d6671f8775ee737aca657.json
rename to .sqlx/query-5c5bb5665c2f17e43ed18d2229651c5ddef91721ff24d669ac7b6ce26298e26e.json
index cd8a82b181..2e92aa5da6 100644
--- a/.sqlx/query-dacaf399371a115436903c7a02db483923b64b662f6d6671f8775ee737aca657.json
+++ b/.sqlx/query-5c5bb5665c2f17e43ed18d2229651c5ddef91721ff24d669ac7b6ce26298e26e.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT\n id, name, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, repo_branch, pull_request_url, workspace, sandbox_size, instructions,\n mcp_scope, mcp_servers, acp_session_id, status,\n status_event_name, agent_session.created_at, modified_at,\n (SELECT channel_id FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_channel_id?\",\n ext.provider AS \"external_provider?\", ext.external_id AS \"external_id?\",\n ext.external_name AS \"external_name?\", ext.external_url AS \"external_url?\",\n ext.last_run_id AS \"external_last_run_id?\"\n FROM agent_session\n LEFT JOIN external_agent_session AS ext ON ext.agent_session_id = agent_session.id\n WHERE owner_id = $1\n ORDER BY agent_session.created_at DESC, id DESC\n LIMIT $2\n ",
+ "query": "\n SELECT\n id, name, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, repo_branch, pull_request_url, workspace, sandbox_size, instructions,\n mcp_scope, mcp_servers, acp_session_id, status,\n status_event_name, agent_session.created_at, modified_at,\n (SELECT jsonb_build_object('type', parent_entity_type, 'id', parent_entity_id)\n FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_parent?: Json<MessageParent>\",\n ext.provider AS \"external_provider?\", ext.external_id AS \"external_id?\",\n ext.external_name AS \"external_name?\", ext.external_url AS \"external_url?\",\n ext.last_run_id AS \"external_last_run_id?\"\n FROM agent_session\n LEFT JOIN external_agent_session AS ext ON ext.agent_session_id = agent_session.id\n WHERE owner_id = $1\n ORDER BY agent_session.created_at DESC, id DESC\n LIMIT $2\n ",
"describe": {
"columns": [
{
@@ -110,8 +110,8 @@
},
{
"ordinal": 21,
- "name": "thread_channel_id?",
- "type_info": "Uuid"
+ "name": "thread_parent?: Json<MessageParent>",
+ "type_info": "Jsonb"
},
{
"ordinal": 22,
@@ -175,5 +175,5 @@
true
]
},
- "hash": "dacaf399371a115436903c7a02db483923b64b662f6d6671f8775ee737aca657"
+ "hash": "5c5bb5665c2f17e43ed18d2229651c5ddef91721ff24d669ac7b6ce26298e26e"
}
diff --git a/.sqlx/query-65715e1ea022117872fa028427720c27b87a1da078ff2e114083e4cf7a176129.json b/.sqlx/query-65715e1ea022117872fa028427720c27b87a1da078ff2e114083e4cf7a176129.json
new file mode 100644
index 0000000000..c304074bf5
--- /dev/null
+++ b/.sqlx/query-65715e1ea022117872fa028427720c27b87a1da078ff2e114083e4cf7a176129.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT m.parent_entity_id FROM agent_session s\n JOIN comms_messages m ON m.id = s.thread_id\n JOIN comms_message_threads t ON t.root_id = m.id\n WHERE s.id = $1 AND m.parent_entity_type = 'document' AND t.deleted_at IS NULL",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "parent_entity_id",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "65715e1ea022117872fa028427720c27b87a1da078ff2e114083e4cf7a176129"
+}
diff --git a/.sqlx/query-788d94f60798cda89ec1d1b859f12b82a2157bf3207a71af91c796b6145f17d9.json b/.sqlx/query-788d94f60798cda89ec1d1b859f12b82a2157bf3207a71af91c796b6145f17d9.json
deleted file mode 100644
index cc01125cb2..0000000000
--- a/.sqlx/query-788d94f60798cda89ec1d1b859f12b82a2157bf3207a71af91c796b6145f17d9.json
+++ /dev/null
@@ -1,12 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "INSERT INTO claude_oauth_grants (user_id, grant_ciphertext, kms_key_id, encryption_version) SELECT 'bob', grant_ciphertext, kms_key_id, encryption_version FROM claude_oauth_grants WHERE user_id = 'alice'",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": []
- },
- "nullable": []
- },
- "hash": "788d94f60798cda89ec1d1b859f12b82a2157bf3207a71af91c796b6145f17d9"
-}
diff --git a/.sqlx/query-97ef237eb6866b33fe847279d4751ade9631b5b1c1e87a059dccbe72cdc57132.json b/.sqlx/query-7ced61e34ca50f6f3f002e9fa0609cb1c143e37ad838a39d0cee671283347a2b.json
similarity index 80%
rename from .sqlx/query-97ef237eb6866b33fe847279d4751ade9631b5b1c1e87a059dccbe72cdc57132.json
rename to .sqlx/query-7ced61e34ca50f6f3f002e9fa0609cb1c143e37ad838a39d0cee671283347a2b.json
index 84af580196..7e372e8019 100644
--- a/.sqlx/query-97ef237eb6866b33fe847279d4751ade9631b5b1c1e87a059dccbe72cdc57132.json
+++ b/.sqlx/query-7ced61e34ca50f6f3f002e9fa0609cb1c143e37ad838a39d0cee671283347a2b.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT\n id, name, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, repo_branch, pull_request_url, workspace, sandbox_size, instructions,\n mcp_scope, mcp_servers, acp_session_id, status,\n status_event_name, agent_session.created_at, modified_at,\n (SELECT channel_id FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_channel_id?\",\n ext.provider AS \"external_provider?\", ext.external_id AS \"external_id?\",\n ext.external_name AS \"external_name?\", ext.external_url AS \"external_url?\",\n ext.last_run_id AS \"external_last_run_id?\"\n FROM agent_session\n LEFT JOIN external_agent_session AS ext ON ext.agent_session_id = agent_session.id\n WHERE id = $1\n ",
+ "query": "\n SELECT\n id, name, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, repo_branch, pull_request_url, workspace, sandbox_size, instructions,\n mcp_scope, mcp_servers, acp_session_id, status,\n status_event_name, agent_session.created_at, modified_at,\n (SELECT jsonb_build_object('type', parent_entity_type, 'id', parent_entity_id)\n FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_parent?: Json<MessageParent>\",\n ext.provider AS \"external_provider?\", ext.external_id AS \"external_id?\",\n ext.external_name AS \"external_name?\", ext.external_url AS \"external_url?\",\n ext.last_run_id AS \"external_last_run_id?\"\n FROM agent_session\n LEFT JOIN external_agent_session AS ext ON ext.agent_session_id = agent_session.id\n WHERE thread_id = $1\n ORDER BY agent_session.created_at DESC\n ",
"describe": {
"columns": [
{
@@ -110,8 +110,8 @@
},
{
"ordinal": 21,
- "name": "thread_channel_id?",
- "type_info": "Uuid"
+ "name": "thread_parent?: Json<MessageParent>",
+ "type_info": "Jsonb"
},
{
"ordinal": 22,
@@ -174,5 +174,5 @@
true
]
},
- "hash": "97ef237eb6866b33fe847279d4751ade9631b5b1c1e87a059dccbe72cdc57132"
+ "hash": "7ced61e34ca50f6f3f002e9fa0609cb1c143e37ad838a39d0cee671283347a2b"
}
diff --git a/.sqlx/query-23628bbbc5c35de5511a1473dceaa2f6f3ac861a56a9292f8b728ea544d46a2a.json b/.sqlx/query-9a14ff2c21c4f16bfa2e06ac2decf57426e53bc0f44ff99c47e253a1d6919eec.json
similarity index 79%
rename from .sqlx/query-23628bbbc5c35de5511a1473dceaa2f6f3ac861a56a9292f8b728ea544d46a2a.json
rename to .sqlx/query-9a14ff2c21c4f16bfa2e06ac2decf57426e53bc0f44ff99c47e253a1d6919eec.json
index 35eece51ae..ac88b2d45d 100644
--- a/.sqlx/query-23628bbbc5c35de5511a1473dceaa2f6f3ac861a56a9292f8b728ea544d46a2a.json
+++ b/.sqlx/query-9a14ff2c21c4f16bfa2e06ac2decf57426e53bc0f44ff99c47e253a1d6919eec.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT\n id, name, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, repo_branch, pull_request_url, workspace, sandbox_size, instructions,\n mcp_scope, mcp_servers, acp_session_id, status,\n status_event_name, agent_session.created_at, modified_at,\n (SELECT channel_id FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_channel_id?\",\n ext.provider AS \"external_provider?\", ext.external_id AS \"external_id?\",\n ext.external_name AS \"external_name?\", ext.external_url AS \"external_url?\",\n ext.last_run_id AS \"external_last_run_id?\"\n FROM agent_session\n LEFT JOIN external_agent_session AS ext ON ext.agent_session_id = agent_session.id\n WHERE thread_id = $1 AND bot_id = $2\n ORDER BY agent_session.created_at DESC\n LIMIT 1\n ",
+ "query": "\n SELECT\n id, name, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, repo_branch, pull_request_url, workspace, sandbox_size, instructions,\n mcp_scope, mcp_servers, acp_session_id, status,\n status_event_name, agent_session.created_at, modified_at,\n (SELECT jsonb_build_object('type', parent_entity_type, 'id', parent_entity_id)\n FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_parent?: Json<MessageParent>\",\n ext.provider AS \"external_provider?\", ext.external_id AS \"external_id?\",\n ext.external_name AS \"external_name?\", ext.external_url AS \"external_url?\",\n ext.last_run_id AS \"external_last_run_id?\"\n FROM agent_session\n LEFT JOIN external_agent_session AS ext ON ext.agent_session_id = agent_session.id\n WHERE thread_id = $1 AND bot_id = $2\n ORDER BY agent_session.created_at DESC\n LIMIT 1\n ",
"describe": {
"columns": [
{
@@ -110,8 +110,8 @@
},
{
"ordinal": 21,
- "name": "thread_channel_id?",
- "type_info": "Uuid"
+ "name": "thread_parent?: Json<MessageParent>",
+ "type_info": "Jsonb"
},
{
"ordinal": 22,
@@ -175,5 +175,5 @@
true
]
},
- "hash": "23628bbbc5c35de5511a1473dceaa2f6f3ac861a56a9292f8b728ea544d46a2a"
+ "hash": "9a14ff2c21c4f16bfa2e06ac2decf57426e53bc0f44ff99c47e253a1d6919eec"
}
diff --git a/.sqlx/query-b16931ecba057b16bf4028b613bf9f85761fe643ceb64b3185db814f1ea1a5d7.json b/.sqlx/query-b16931ecba057b16bf4028b613bf9f85761fe643ceb64b3185db814f1ea1a5d7.json
deleted file mode 100644
index ac476c9a0b..0000000000
--- a/.sqlx/query-b16931ecba057b16bf4028b613bf9f85761fe643ceb64b3185db814f1ea1a5d7.json
+++ /dev/null
@@ -1,22 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "SELECT history_start_log_id FROM agent_session WHERE id = $1",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "history_start_log_id",
- "type_info": "Uuid"
- }
- ],
- "parameters": {
- "Left": [
- "Uuid"
- ]
- },
- "nullable": [
- true
- ]
- },
- "hash": "b16931ecba057b16bf4028b613bf9f85761fe643ceb64b3185db814f1ea1a5d7"
-}
diff --git a/.sqlx/query-b99f44b3083e803ed923c27da5de9a9331238e347a15ef0fe95514c7308e8435.json b/.sqlx/query-b99f44b3083e803ed923c27da5de9a9331238e347a15ef0fe95514c7308e8435.json
deleted file mode 100644
index 6b7201a84d..0000000000
--- a/.sqlx/query-b99f44b3083e803ed923c27da5de9a9331238e347a15ef0fe95514c7308e8435.json
+++ /dev/null
@@ -1,20 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "SELECT grant_ciphertext FROM claude_oauth_grants WHERE user_id = 'alice'",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "grant_ciphertext",
- "type_info": "Bytea"
- }
- ],
- "parameters": {
- "Left": []
- },
- "nullable": [
- false
- ]
- },
- "hash": "b99f44b3083e803ed923c27da5de9a9331238e347a15ef0fe95514c7308e8435"
-}
diff --git a/.sqlx/query-c9fba3bb2e323d8f5090ff805cb673f0e79e98567c08ec6893e1fd1c0a805b1d.json b/.sqlx/query-c9fba3bb2e323d8f5090ff805cb673f0e79e98567c08ec6893e1fd1c0a805b1d.json
new file mode 100644
index 0000000000..9d9e83ee59
--- /dev/null
+++ b/.sqlx/query-c9fba3bb2e323d8f5090ff805cb673f0e79e98567c08ec6893e1fd1c0a805b1d.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT parent_entity_id::uuid AS \"channel_id!\" FROM comms_messages WHERE parent_entity_type = 'channel' AND id = $1",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "channel_id!",
+ "type_info": "Uuid"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "c9fba3bb2e323d8f5090ff805cb673f0e79e98567c08ec6893e1fd1c0a805b1d"
+}
diff --git a/.sqlx/query-205a1accf8b5e0a08a8e46c7eb2911cdbd3ccc849309f9c2db63b6e6502d3dba.json b/.sqlx/query-fb43d363a3386eb501d8eb29cb073930b41b5823eea316366dc6d28cba2008fd.json
similarity index 81%
rename from .sqlx/query-205a1accf8b5e0a08a8e46c7eb2911cdbd3ccc849309f9c2db63b6e6502d3dba.json
rename to .sqlx/query-fb43d363a3386eb501d8eb29cb073930b41b5823eea316366dc6d28cba2008fd.json
index 8526744dea..06b13b8772 100644
--- a/.sqlx/query-205a1accf8b5e0a08a8e46c7eb2911cdbd3ccc849309f9c2db63b6e6502d3dba.json
+++ b/.sqlx/query-fb43d363a3386eb501d8eb29cb073930b41b5823eea316366dc6d28cba2008fd.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT\n id, name, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, repo_branch, pull_request_url, workspace, sandbox_size, instructions,\n mcp_scope, mcp_servers, acp_session_id, status,\n status_event_name, agent_session.created_at, modified_at,\n (SELECT channel_id FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_channel_id?\",\n ext.provider AS \"external_provider?\", ext.external_id AS \"external_id?\",\n ext.external_name AS \"external_name?\", ext.external_url AS \"external_url?\",\n ext.last_run_id AS \"external_last_run_id?\"\n FROM agent_session\n LEFT JOIN external_agent_session AS ext ON ext.agent_session_id = agent_session.id\n WHERE egress_token_hash = $1\n ",
+ "query": "\n SELECT\n id, name, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, repo_branch, pull_request_url, workspace, sandbox_size, instructions,\n mcp_scope, mcp_servers, acp_session_id, status,\n status_event_name, agent_session.created_at, modified_at,\n (SELECT jsonb_build_object('type', parent_entity_type, 'id', parent_entity_id)\n FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_parent?: Json<MessageParent>\",\n ext.provider AS \"external_provider?\", ext.external_id AS \"external_id?\",\n ext.external_name AS \"external_name?\", ext.external_url AS \"external_url?\",\n ext.last_run_id AS \"external_last_run_id?\"\n FROM agent_session\n LEFT JOIN external_agent_session AS ext ON ext.agent_session_id = agent_session.id\n WHERE egress_token_hash = $1\n ",
"describe": {
"columns": [
{
@@ -110,8 +110,8 @@
},
{
"ordinal": 21,
- "name": "thread_channel_id?",
- "type_info": "Uuid"
+ "name": "thread_parent?: Json<MessageParent>",
+ "type_info": "Jsonb"
},
{
"ordinal": 22,
@@ -174,5 +174,5 @@
true
]
},
- "hash": "205a1accf8b5e0a08a8e46c7eb2911cdbd3ccc849309f9c2db63b6e6502d3dba"
+ "hash": "fb43d363a3386eb501d8eb29cb073930b41b5823eea316366dc6d28cba2008fd"
}
diff --git a/.sqlx/query-fdf3802d910ed6101aa3235af774581ebb1bc17fadf3cebeafbffff412804997.json b/.sqlx/query-fdf3802d910ed6101aa3235af774581ebb1bc17fadf3cebeafbffff412804997.json
deleted file mode 100644
index 14da440a98..0000000000
--- a/.sqlx/query-fdf3802d910ed6101aa3235af774581ebb1bc17fadf3cebeafbffff412804997.json
+++ /dev/null
@@ -1,16 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "INSERT INTO claude_oauth_grants (user_id, grant_ciphertext, kms_key_id, encryption_version) VALUES ($1, $2, $3, 1) ON CONFLICT (user_id) DO UPDATE SET grant_ciphertext = EXCLUDED.grant_ciphertext, kms_key_id = EXCLUDED.kms_key_id, encryption_version = 1, updated_at = now()",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Text",
- "Bytea",
- "Text"
- ]
- },
- "nullable": []
- },
- "hash": "fdf3802d910ed6101aa3235af774581ebb1bc17fadf3cebeafbffff412804997"
-}
diff --git a/Cargo.lock b/Cargo.lock
index e53cb6ac5e..9c437bb688 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -343,6 +343,7 @@ dependencies = [
"harnesses",
"kafka_util",
"lexical_client",
+ "lexical_mention_extractor",
"macro_auth",
"macro_authorization",
"macro_aws_config",
@@ -357,6 +358,7 @@ dependencies = [
"macro_tower_layers",
"macro_user_id",
"macro_uuid",
+ "messages",
"notification",
"pipedream_mcp",
"rdkafka",
@@ -479,6 +481,7 @@ dependencies = [
"macro_event_topics",
"macro_user_id",
"macro_uuid",
+ "messages",
"mockall",
"model-entity",
"model_owner",
@@ -518,6 +521,7 @@ dependencies = [
"channel_sender",
"channels",
"chrono",
+ "entity_access",
"lexical_client",
"macro_event_broker",
"macro_event_topics",
@@ -527,6 +531,7 @@ dependencies = [
"mockall",
"serde",
"serde_json",
+ "sqlx",
"strum 0.27.2",
"thiserror 2.0.18",
"tokio",
@@ -545,6 +550,7 @@ dependencies = [
"bots",
"channels",
"database_env_vars",
+ "entity_access",
"kafka_util",
"lexical_client",
"macro_config",
@@ -552,6 +558,7 @@ dependencies = [
"macro_env_var",
"macro_event_broker",
"macro_service_urls",
+ "messages",
"rdkafka",
"serde_json",
"sqlx",
@@ -3393,14 +3400,13 @@ dependencies = [
"async-trait",
"bot_id",
"calendar_events",
- "channels",
+ "channel_sender",
"chrono",
"chrono-tz",
"entity_access",
"futures",
"macro_user_id",
"messages",
- "models_pagination",
"prompt",
"rootcause",
"serde",
@@ -3779,6 +3785,7 @@ dependencies = [
"macro_event_broker",
"macro_user_id",
"macro_uuid",
+ "messages",
"ratatui",
"reqwest 0.13.4",
"rootcause",
@@ -9461,6 +9468,7 @@ version = "0.1.0"
dependencies = [
"agent_fold",
"anyhow",
+ "messages",
"reqwest 0.13.4",
"serde",
"serde_json",
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentSessionResponse.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentSessionResponse.ts
index 7a7c111e5f..2a1479c24e 100644
--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentSessionResponse.ts
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentSessionResponse.ts
@@ -12,6 +12,7 @@ import type { AgentSessionResponsePullRequestUrl } from './agentSessionResponseP
import type { AgentSessionResponseRepoUrl } from './agentSessionResponseRepoUrl';
import type { AgentSessionResponseThreadChannelId } from './agentSessionResponseThreadChannelId';
import type { AgentSessionResponseThreadId } from './agentSessionResponseThreadId';
+import type { AgentSessionResponseThreadParent } from './agentSessionResponseThreadParent';
import type { SandboxSize } from './sandboxSize';
import type { SessionStatusDto } from './sessionStatusDto';
@@ -58,10 +59,11 @@ at creation. Absent otherwise, so existing payloads are unchanged. */
/** The session's status. */
status: SessionStatusDto;
/** The channel `thread_id` lives in, when the session was spawned from a
-thread. */
+channel thread. Derived from `thread_parent`. */
threadChannelId?: AgentSessionResponseThreadChannelId;
/** The root message of the thread the session was created from, if any. */
threadId?: AgentSessionResponseThreadId;
+ threadParent?: AgentSessionResponseThreadParent;
/** The directory the session's harness runs in on its runtime. */
workspace: string;
}
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentSessionResponseThreadChannelId.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentSessionResponseThreadChannelId.ts
index 7ba59613b0..97c0c5ffd9 100644
--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentSessionResponseThreadChannelId.ts
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentSessionResponseThreadChannelId.ts
@@ -7,6 +7,6 @@
/**
* The channel `thread_id` lives in, when the session was spawned from a
-thread.
+channel thread. Derived from `thread_parent`.
*/
export type AgentSessionResponseThreadChannelId = string | null;
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentSessionResponseThreadParent.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentSessionResponseThreadParent.ts
new file mode 100644
index 0000000000..81e3343a60
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentSessionResponseThreadParent.ts
@@ -0,0 +1,9 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { MessageParent } from './messageParent';
+
+export type AgentSessionResponseThreadParent = null | MessageParent;
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createSessionThread.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createSessionThread.ts
index 3c6528efff..38f66df0f4 100644
--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createSessionThread.ts
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createSessionThread.ts
@@ -4,6 +4,8 @@
* agent_harness_service
* OpenAPI spec version: 0.1.0
*/
+import type { CreateSessionThreadChannelId } from './createSessionThreadChannelId';
+import type { CreateSessionThreadParent } from './createSessionThreadParent';
import type { CreateSessionThreadThreadId } from './createSessionThreadThreadId';
/**
@@ -12,12 +14,14 @@ import type { CreateSessionThreadThreadId } from './createSessionThreadThreadId'
Clients serialize this, so both derives are used.
*/
export interface CreateSessionThread {
- /** Channel the mentioning message was posted in. */
- channelId: string;
+ /** Channel the mentioning message was posted in. Runtimes built before
+message parents send this instead of `parent`. */
+ channelId?: CreateSessionThreadChannelId;
/** The mention's text, quoted in the session's announcement. */
content?: string;
/** The mentioning message. */
messageId: string;
+ parent?: CreateSessionThreadParent;
/** Thread the session belongs to; defaults to the message itself, which
is how a top-level mention roots its own thread. */
threadId?: CreateSessionThreadThreadId;
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createSessionThreadChannelId.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createSessionThreadChannelId.ts
new file mode 100644
index 0000000000..9308d0208d
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createSessionThreadChannelId.ts
@@ -0,0 +1,12 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Channel the mentioning message was posted in. Runtimes built before
+message parents send this instead of `parent`.
+ */
+export type CreateSessionThreadChannelId = string | null;
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createSessionThreadParent.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createSessionThreadParent.ts
new file mode 100644
index 0000000000..541abc0e3d
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createSessionThreadParent.ts
@@ -0,0 +1,9 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { MessageParent } from './messageParent';
+
+export type CreateSessionThreadParent = null | MessageParent;
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/documentId.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/documentId.ts
new file mode 100644
index 0000000000..2ebf9a9f18
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/documentId.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * A validated document identifier. Historical document ids need not be UUIDs.
+ */
+export type DocumentId = 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 f6e3cd8f57..ae14bba680 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
@@ -53,6 +53,7 @@ export * from './agentSessionResponsePullRequestUrl';
export * from './agentSessionResponseRepoUrl';
export * from './agentSessionResponseThreadChannelId';
export * from './agentSessionResponseThreadId';
+export * from './agentSessionResponseThreadParent';
export * from './agentSetModelAction';
export * from './botId';
export * from './completeRequest';
@@ -70,7 +71,10 @@ export * from './createAgentSessionRequestThread';
export * from './createAgentSessionRequestWorkspace';
export * from './createAgentSessionResponse';
export * from './createSessionThread';
+export * from './createSessionThreadChannelId';
+export * from './createSessionThreadParent';
export * from './createSessionThreadThreadId';
+export * from './documentId';
export * from './editQueuedActionRequest';
export * from './elicitationAnswer';
export * from './elicitationAnswerOneOf';
@@ -94,6 +98,11 @@ export * from './loadAgentModelsResponseCurrentModel';
export * from './logDirectionDto';
export * from './logFrameDto';
export * from './logFrameDtoContent';
+export * from './messageParent';
+export * from './messageParentOneOf';
+export * from './messageParentOneOfThree';
+export * from './messageParentOneOfThreeType';
+export * from './messageParentOneOfType';
export * from './modelHarnessDto';
export * from './previewAgentSessionsRequest';
export * from './previewAgentSessionsResponse';
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/messageParent.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/messageParent.ts
new file mode 100644
index 0000000000..6e6b8ab697
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/messageParent.ts
@@ -0,0 +1,13 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { MessageParentOneOf } from './messageParentOneOf';
+import type { MessageParentOneOfThree } from './messageParentOneOfThree';
+
+/**
+ * The entity whose permissions and lifecycle govern a message.
+ */
+export type MessageParent = MessageParentOneOf | MessageParentOneOfThree;
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/messageParentOneOf.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/messageParentOneOf.ts
new file mode 100644
index 0000000000..63a979f2c0
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/messageParentOneOf.ts
@@ -0,0 +1,16 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { MessageParentOneOfType } from './messageParentOneOfType';
+
+/**
+ * A channel, including direct messages.
+ */
+export type MessageParentOneOf = {
+ /** A channel, including direct messages. */
+ id: string;
+ type: MessageParentOneOfType;
+};
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/messageParentOneOfThree.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/messageParentOneOfThree.ts
new file mode 100644
index 0000000000..e83b3f8eb1
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/messageParentOneOfThree.ts
@@ -0,0 +1,17 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { DocumentId } from './documentId';
+import type { MessageParentOneOfThreeType } from './messageParentOneOfThreeType';
+
+/**
+ * A document, including tasks and PDFs.
+ */
+export type MessageParentOneOfThree = {
+ /** A document, including tasks and PDFs. */
+ id: DocumentId;
+ type: MessageParentOneOfThreeType;
+};
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/messageParentOneOfThreeType.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/messageParentOneOfThreeType.ts
new file mode 100644
index 0000000000..f16b4326b7
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/messageParentOneOfThreeType.ts
@@ -0,0 +1,14 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type MessageParentOneOfThreeType =
+ (typeof MessageParentOneOfThreeType)[keyof typeof MessageParentOneOfThreeType];
+
+// eslint-disable-next-line @typescript-eslint/no-redeclare
+export const MessageParentOneOfThreeType = {
+ document: 'document',
+} as const;
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/messageParentOneOfType.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/messageParentOneOfType.ts
new file mode 100644
index 0000000000..3d101193c5
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/messageParentOneOfType.ts
@@ -0,0 +1,14 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type MessageParentOneOfType =
+ (typeof MessageParentOneOfType)[keyof typeof MessageParentOneOfType];
+
+// eslint-disable-next-line @typescript-eslint/no-redeclare
+export const MessageParentOneOfType = {
+ channel: 'channel',
+} as const;
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 87e7d3e5ed..8d16a0e071 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
@@ -1480,13 +1480,24 @@
"threadChannelId": {
"type": ["string", "null"],
"format": "uuid",
- "description": "The channel `thread_id` lives in, when the session was spawned from a\nthread."
+ "description": "The channel `thread_id` lives in, when the session was spawned from a\nchannel thread. Derived from `thread_parent`."
},
"threadId": {
"type": ["string", "null"],
"format": "uuid",
"description": "The root message of the thread the session was created from, if any."
},
+ "threadParent": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/MessageParent",
+ "description": "The channel or document `thread_id` lives in, when the session was\nspawned from a thread."
+ }
+ ]
+ },
"workspace": {
"type": "string",
"description": "The directory the session's harness runs in on its runtime."
@@ -1612,12 +1623,12 @@
"CreateSessionThread": {
"type": "object",
"description": "The triggering mention on a create request.\n\nClients serialize this, so both derives are used.",
- "required": ["channelId", "messageId"],
+ "required": ["messageId"],
"properties": {
"channelId": {
- "type": "string",
+ "type": ["string", "null"],
"format": "uuid",
- "description": "Channel the mentioning message was posted in."
+ "description": "Channel the mentioning message was posted in. Runtimes built before\nmessage parents send this instead of `parent`."
},
"content": {
"type": "string",
@@ -1628,6 +1639,17 @@
"format": "uuid",
"description": "The mentioning message."
},
+ "parent": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/MessageParent",
+ "description": "Entity the mentioning message was posted in."
+ }
+ ]
+ },
"threadId": {
"type": ["string", "null"],
"format": "uuid",
@@ -1635,6 +1657,10 @@
}
}
},
+ "DocumentId": {
+ "type": "string",
+ "description": "A validated document identifier. Historical document ids need not be UUIDs."
+ },
"EditQueuedActionRequest": {
"type": "object",
"description": "Request body for editing a queued prompt.",
@@ -1821,6 +1847,42 @@
}
}
},
+ "MessageParent": {
+ "oneOf": [
+ {
+ "type": "object",
+ "description": "A channel, including direct messages.",
+ "required": ["id", "type"],
+ "properties": {
+ "id": {
+ "type": "string",
+ "format": "uuid",
+ "description": "A channel, including direct messages."
+ },
+ "type": {
+ "type": "string",
+ "enum": ["channel"]
+ }
+ }
+ },
+ {
+ "type": "object",
+ "description": "A document, including tasks and PDFs.",
+ "required": ["id", "type"],
+ "properties": {
+ "id": {
+ "$ref": "#/components/schemas/DocumentId",
+ "description": "A document, including tasks and PDFs."
+ },
+ "type": {
+ "type": "string",
+ "enum": ["document"]
+ }
+ }
+ }
+ ],
+ "description": "The entity whose permissions and lifecycle govern a message."
+ },
"ModelHarnessDto": {
"type": "string",
"description": "Harness names accepted by the model discovery endpoint.",
diff --git a/apps/web/src/lib/service-clients/service-notification/generated/schemas/agentSessionNotificationRef.ts b/apps/web/src/lib/service-clients/service-notification/generated/schemas/agentSessionNotificationRef.ts
index 637dda50e7..78f72ded16 100644
--- a/apps/web/src/lib/service-clients/service-notification/generated/schemas/agentSessionNotificationRef.ts
+++ b/apps/web/src/lib/service-clients/service-notification/generated/schemas/agentSessionNotificationRef.ts
@@ -6,13 +6,11 @@
*/
import type { AgentSessionNotificationRefAnnouncementMessageId } from './agentSessionNotificationRefAnnouncementMessageId';
import type { AgentSessionNotificationRefChannelId } from './agentSessionNotificationRefChannelId';
+import type { AgentSessionNotificationRefParent } from './agentSessionNotificationRefParent';
import type { AgentSessionNotificationRefThreadId } from './agentSessionNotificationRefThreadId';
/**
- * The session an agent-session notification is about, and where its magic
-chip lives when it was opened from a thread.
-
-Flattened into each agent-session kind so the wire keeps these keys at the
+ * Flattened into each agent-session kind so the wire keeps these keys at the
top level of the metadata, the way [`CommonChannelMetadata`] does.
*/
export interface AgentSessionNotificationRef {
@@ -25,8 +23,10 @@ RFC 4122 uuids and fail a `format: uuid` check on the client. */
/** The bot's display name; agent notifications have no user sender, so
this is who they read as being from. */
botName: string;
- /** The channel the session was opened from, when it was. */
+ /** The channel the session was opened from, when it was opened from a
+channel thread. */
channelId?: AgentSessionNotificationRefChannelId;
+ parent?: AgentSessionNotificationRefParent;
/** The session; what a click opens. */
sessionId: string;
/** The session's name at the time of the event. */
diff --git a/apps/web/src/lib/service-clients/service-notification/generated/schemas/agentSessionNotificationRefChannelId.ts b/apps/web/src/lib/service-clients/service-notification/generated/schemas/agentSessionNotificationRefChannelId.ts
index 6746c86122..83c4d0b16a 100644
--- a/apps/web/src/lib/service-clients/service-notification/generated/schemas/agentSessionNotificationRefChannelId.ts
+++ b/apps/web/src/lib/service-clients/service-notification/generated/schemas/agentSessionNotificationRefChannelId.ts
@@ -6,6 +6,7 @@
*/
/**
- * The channel the session was opened from, when it was.
+ * The channel the session was opened from, when it was opened from a
+channel thread.
*/
export type AgentSessionNotificationRefChannelId = string | null;
diff --git a/apps/web/src/lib/service-clients/service-notification/generated/schemas/agentSessionNotificationRefParent.ts b/apps/web/src/lib/service-clients/service-notification/generated/schemas/agentSessionNotificationRefParent.ts
new file mode 100644
index 0000000000..445d9cba4f
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-notification/generated/schemas/agentSessionNotificationRefParent.ts
@@ -0,0 +1,9 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * notification_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { AgentSessionOriginParent } from './agentSessionOriginParent';
+
+export type AgentSessionNotificationRefParent = null | AgentSessionOriginParent;
diff --git a/apps/web/src/lib/service-clients/service-notification/generated/schemas/agentSessionOriginParent.ts b/apps/web/src/lib/service-clients/service-notification/generated/schemas/agentSessionOriginParent.ts
new file mode 100644
index 0000000000..3168c687e5
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-notification/generated/schemas/agentSessionOriginParent.ts
@@ -0,0 +1,21 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * notification_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * The session an agent-session notification is about, and where its magic
+chip lives when it was opened from a thread.
+
+The conversation an agent session was opened from: a channel or a
+document discussion. Spelled like the message API's parent so a client can
+route to either surface.
+ */
+export interface AgentSessionOriginParent {
+ /** The channel or document id. */
+ id: string;
+ /** `channel` or `document`. */
+ type: string;
+}
diff --git a/apps/web/src/lib/service-clients/service-notification/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-notification/generated/schemas/index.ts
index 1478e7f77d..4e896590f7 100644
--- a/apps/web/src/lib/service-clients/service-notification/generated/schemas/index.ts
+++ b/apps/web/src/lib/service-clients/service-notification/generated/schemas/index.ts
@@ -11,7 +11,9 @@ export * from './agentSessionMentionedMetadataAllOfMentionedBy';
export * from './agentSessionNotificationRef';
export * from './agentSessionNotificationRefAnnouncementMessageId';
export * from './agentSessionNotificationRefChannelId';
+export * from './agentSessionNotificationRefParent';
export * from './agentSessionNotificationRefThreadId';
+export * from './agentSessionOriginParent';
export * from './agentSessionSettledMetadata';
export * from './agentSessionSettledMetadataAllOf';
export * from './agentSessionSettledMetadataAllOfActor';
diff --git a/apps/web/src/lib/service-clients/service-notification/generated/zod.ts b/apps/web/src/lib/service-clients/service-notification/generated/zod.ts
index 814c6466cf..4bebd46b0d 100644
--- a/apps/web/src/lib/service-clients/service-notification/generated/zod.ts
+++ b/apps/web/src/lib/service-clients/service-notification/generated/zod.ts
@@ -1537,8 +1537,25 @@ export const listTypedNotificationsResponse = zod
.uuid()
.nullish()
.describe(
- 'The channel the session was opened from, when it was.'
+ 'The channel the session was opened from, when it was opened from a\nchannel thread.'
),
+ parent: zod
+ .union([
+ zod.null(),
+ zod
+ .object({
+ id: zod
+ .string()
+ .describe('The channel or document id.'),
+ type: zod
+ .string()
+ .describe('`channel` or `document`.'),
+ })
+ .describe(
+ "The session an agent-session notification is about, and where its magic\nchip lives when it was opened from a thread.\n\nThe conversation an agent session was opened from: a channel or a\ndocument discussion. Spelled like the message API's parent so a client can\nroute to either surface."
+ ),
+ ])
+ .optional(),
sessionId: zod
.uuid()
.describe('The session; what a click opens.'),
@@ -1555,7 +1572,7 @@ export const listTypedNotificationsResponse = zod
),
})
.describe(
- 'The session an agent-session notification is about, and where its magic\nchip lives when it was opened from a thread.\n\nFlattened into each agent-session kind so the wire keeps these keys at the\ntop level of the metadata, the way [`CommonChannelMetadata`] does.'
+ 'Flattened into each agent-session kind so the wire keeps these keys at the\ntop level of the metadata, the way [`CommonChannelMetadata`] does.'
)
.and(
zod.object({
@@ -1614,8 +1631,25 @@ export const listTypedNotificationsResponse = zod
.uuid()
.nullish()
.describe(
- 'The channel the session was opened from, when it was.'
+ 'The channel the session was opened from, when it was opened from a\nchannel thread.'
),
+ parent: zod
+ .union([
+ zod.null(),
+ zod
+ .object({
+ id: zod
+ .string()
+ .describe('The channel or document id.'),
+ type: zod
+ .string()
+ .describe('`channel` or `document`.'),
+ })
+ .describe(
+ "The session an agent-session notification is about, and where its magic\nchip lives when it was opened from a thread.\n\nThe conversation an agent session was opened from: a channel or a\ndocument discussion. Spelled like the message API's parent so a client can\nroute to either surface."
+ ),
+ ])
+ .optional(),
sessionId: zod
.uuid()
.describe('The session; what a click opens.'),
@@ -1632,7 +1666,7 @@ export const listTypedNotificationsResponse = zod
),
})
.describe(
- 'The session an agent-session notification is about, and where its magic\nchip lives when it was opened from a thread.\n\nFlattened into each agent-session kind so the wire keeps these keys at the\ntop level of the metadata, the way [`CommonChannelMetadata`] does.'
+ 'Flattened into each agent-session kind so the wire keeps these keys at the\ntop level of the metadata, the way [`CommonChannelMetadata`] does.'
)
.and(
zod.object({
@@ -1681,8 +1715,25 @@ export const listTypedNotificationsResponse = zod
.uuid()
.nullish()
.describe(
- 'The channel the session was opened from, when it was.'
+ 'The channel the session was opened from, when it was opened from a\nchannel thread.'
),
+ parent: zod
+ .union([
+ zod.null(),
+ zod
+ .object({
+ id: zod
+ .string()
+ .describe('The channel or document id.'),
+ type: zod
+ .string()
+ .describe('`channel` or `document`.'),
+ })
+ .describe(
+ "The session an agent-session notification is about, and where its magic\nchip lives when it was opened from a thread.\n\nThe conversation an agent session was opened from: a channel or a\ndocument discussion. Spelled like the message API's parent so a client can\nroute to either surface."
+ ),
+ ])
+ .optional(),
sessionId: zod
.uuid()
.describe('The session; what a click opens.'),
@@ -1699,7 +1750,7 @@ export const listTypedNotificationsResponse = zod
),
})
.describe(
- 'The session an agent-session notification is about, and where its magic\nchip lives when it was opened from a thread.\n\nFlattened into each agent-session kind so the wire keeps these keys at the\ntop level of the metadata, the way [`CommonChannelMetadata`] does.'
+ 'Flattened into each agent-session kind so the wire keeps these keys at the\ntop level of the metadata, the way [`CommonChannelMetadata`] does.'
)
.and(
zod.object({
@@ -3224,8 +3275,25 @@ export const bulkGetTypedNotificationsByEventItemIdsResponse = zod
.uuid()
.nullish()
.describe(
- 'The channel the session was opened from, when it was.'
+ 'The channel the session was opened from, when it was opened from a\nchannel thread.'
),
+ parent: zod
+ .union([
+ zod.null(),
+ zod
+ .object({
+ id: zod
+ .string()
+ .describe('The channel or document id.'),
+ type: zod
+ .string()
+ .describe('`channel` or `document`.'),
+ })
+ .describe(
+ "The session an agent-session notification is about, and where its magic\nchip lives when it was opened from a thread.\n\nThe conversation an agent session was opened from: a channel or a\ndocument discussion. Spelled like the message API's parent so a client can\nroute to either surface."
+ ),
+ ])
+ .optional(),
sessionId: zod
.uuid()
.describe('The session; what a click opens.'),
@@ -3242,7 +3310,7 @@ export const bulkGetTypedNotificationsByEventItemIdsResponse = zod
),
})
.describe(
- 'The session an agent-session notification is about, and where its magic\nchip lives when it was opened from a thread.\n\nFlattened into each agent-session kind so the wire keeps these keys at the\ntop level of the metadata, the way [`CommonChannelMetadata`] does.'
+ 'Flattened into each agent-session kind so the wire keeps these keys at the\ntop level of the metadata, the way [`CommonChannelMetadata`] does.'
)
.and(
zod.object({
@@ -3301,8 +3369,25 @@ export const bulkGetTypedNotificationsByEventItemIdsResponse = zod
.uuid()
.nullish()
.describe(
- 'The channel the session was opened from, when it was.'
+ 'The channel the session was opened from, when it was opened from a\nchannel thread.'
),
+ parent: zod
+ .union([
+ zod.null(),
+ zod
+ .object({
+ id: zod
+ .string()
+ .describe('The channel or document id.'),
+ type: zod
+ .string()
+ .describe('`channel` or `document`.'),
+ })
+ .describe(
+ "The session an agent-session notification is about, and where its magic\nchip lives when it was opened from a thread.\n\nThe conversation an agent session was opened from: a channel or a\ndocument discussion. Spelled like the message API's parent so a client can\nroute to either surface."
+ ),
+ ])
+ .optional(),
sessionId: zod
.uuid()
.describe('The session; what a click opens.'),
@@ -3319,7 +3404,7 @@ export const bulkGetTypedNotificationsByEventItemIdsResponse = zod
),
})
.describe(
- 'The session an agent-session notification is about, and where its magic\nchip lives when it was opened from a thread.\n\nFlattened into each agent-session kind so the wire keeps these keys at the\ntop level of the metadata, the way [`CommonChannelMetadata`] does.'
+ 'Flattened into each agent-session kind so the wire keeps these keys at the\ntop level of the metadata, the way [`CommonChannelMetadata`] does.'
)
.and(
zod.object({
@@ -3368,8 +3453,25 @@ export const bulkGetTypedNotificationsByEventItemIdsResponse = zod
.uuid()
.nullish()
.describe(
- 'The channel the session was opened from, when it was.'
+ 'The channel the session was opened from, when it was opened from a\nchannel thread.'
),
+ parent: zod
+ .union([
+ zod.null(),
+ zod
+ .object({
+ id: zod
+ .string()
+ .describe('The channel or document id.'),
+ type: zod
+ .string()
+ .describe('`channel` or `document`.'),
+ })
+ .describe(
+ "The session an agent-session notification is about, and where its magic\nchip lives when it was opened from a thread.\n\nThe conversation an agent session was opened from: a channel or a\ndocument discussion. Spelled like the message API's parent so a client can\nroute to either surface."
+ ),
+ ])
+ .optional(),
sessionId: zod
.uuid()
.describe('The session; what a click opens.'),
@@ -3386,7 +3488,7 @@ export const bulkGetTypedNotificationsByEventItemIdsResponse = zod
),
})
.describe(
- 'The session an agent-session notification is about, and where its magic\nchip lives when it was opened from a thread.\n\nFlattened into each agent-session kind so the wire keeps these keys at the\ntop level of the metadata, the way [`CommonChannelMetadata`] does.'
+ 'Flattened into each agent-session kind so the wire keeps these keys at the\ntop level of the metadata, the way [`CommonChannelMetadata`] does.'
)
.and(
zod.object({
@@ -4905,8 +5007,25 @@ export const getTypedNotificationsByEventItemIdResponse = zod
.uuid()
.nullish()
.describe(
- 'The channel the session was opened from, when it was.'
+ 'The channel the session was opened from, when it was opened from a\nchannel thread.'
),
+ parent: zod
+ .union([
+ zod.null(),
+ zod
+ .object({
+ id: zod
+ .string()
+ .describe('The channel or document id.'),
+ type: zod
+ .string()
+ .describe('`channel` or `document`.'),
+ })
+ .describe(
+ "The session an agent-session notification is about, and where its magic\nchip lives when it was opened from a thread.\n\nThe conversation an agent session was opened from: a channel or a\ndocument discussion. Spelled like the message API's parent so a client can\nroute to either surface."
+ ),
+ ])
+ .optional(),
sessionId: zod
.uuid()
.describe('The session; what a click opens.'),
@@ -4923,7 +5042,7 @@ export const getTypedNotificationsByEventItemIdResponse = zod
),
})
.describe(
- 'The session an agent-session notification is about, and where its magic\nchip lives when it was opened from a thread.\n\nFlattened into each agent-session kind so the wire keeps these keys at the\ntop level of the metadata, the way [`CommonChannelMetadata`] does.'
+ 'Flattened into each agent-session kind so the wire keeps these keys at the\ntop level of the metadata, the way [`CommonChannelMetadata`] does.'
)
.and(
zod.object({
@@ -4982,8 +5101,25 @@ export const getTypedNotificationsByEventItemIdResponse = zod
.uuid()
.nullish()
.describe(
- 'The channel the session was opened from, when it was.'
+ 'The channel the session was opened from, when it was opened from a\nchannel thread.'
),
+ parent: zod
+ .union([
+ zod.null(),
+ zod
+ .object({
+ id: zod
+ .string()
+ .describe('The channel or document id.'),
+ type: zod
+ .string()
+ .describe('`channel` or `document`.'),
+ })
+ .describe(
+ "The session an agent-session notification is about, and where its magic\nchip lives when it was opened from a thread.\n\nThe conversation an agent session was opened from: a channel or a\ndocument discussion. Spelled like the message API's parent so a client can\nroute to either surface."
+ ),
+ ])
+ .optional(),
sessionId: zod
.uuid()
.describe('The session; what a click opens.'),
@@ -5000,7 +5136,7 @@ export const getTypedNotificationsByEventItemIdResponse = zod
),
})
.describe(
- 'The session an agent-session notification is about, and where its magic\nchip lives when it was opened from a thread.\n\nFlattened into each agent-session kind so the wire keeps these keys at the\ntop level of the metadata, the way [`CommonChannelMetadata`] does.'
+ 'Flattened into each agent-session kind so the wire keeps these keys at the\ntop level of the metadata, the way [`CommonChannelMetadata`] does.'
)
.and(
zod.object({
@@ -5049,8 +5185,25 @@ export const getTypedNotificationsByEventItemIdResponse = zod
.uuid()
.nullish()
.describe(
- 'The channel the session was opened from, when it was.'
+ 'The channel the session was opened from, when it was opened from a\nchannel thread.'
),
+ parent: zod
+ .union([
+ zod.null(),
+ zod
+ .object({
+ id: zod
+ .string()
+ .describe('The channel or document id.'),
+ type: zod
+ .string()
+ .describe('`channel` or `document`.'),
+ })
+ .describe(
+ "The session an agent-session notification is about, and where its magic\nchip lives when it was opened from a thread.\n\nThe conversation an agent session was opened from: a channel or a\ndocument discussion. Spelled like the message API's parent so a client can\nroute to either surface."
+ ),
+ ])
+ .optional(),
sessionId: zod
.uuid()
.describe('The session; what a click opens.'),
@@ -5067,7 +5220,7 @@ export const getTypedNotificationsByEventItemIdResponse = zod
),
})
.describe(
- 'The session an agent-session notification is about, and where its magic\nchip lives when it was opened from a thread.\n\nFlattened into each agent-session kind so the wire keeps these keys at the\ntop level of the metadata, the way [`CommonChannelMetadata`] does.'
+ 'Flattened into each agent-session kind so the wire keeps these keys at the\ntop level of the metadata, the way [`CommonChannelMetadata`] does.'
)
.and(
zod.object({
@@ -6484,8 +6637,25 @@ export const getTypedNotificationByIdResponse = zod
.uuid()
.nullish()
.describe(
- 'The channel the session was opened from, when it was.'
+ 'The channel the session was opened from, when it was opened from a\nchannel thread.'
),
+ parent: zod
+ .union([
+ zod.null(),
+ zod
+ .object({
+ id: zod
+ .string()
+ .describe('The channel or document id.'),
+ type: zod
+ .string()
+ .describe('`channel` or `document`.'),
+ })
+ .describe(
+ "The session an agent-session notification is about, and where its magic\nchip lives when it was opened from a thread.\n\nThe conversation an agent session was opened from: a channel or a\ndocument discussion. Spelled like the message API's parent so a client can\nroute to either surface."
+ ),
+ ])
+ .optional(),
sessionId: zod
.uuid()
.describe('The session; what a click opens.'),
@@ -6500,7 +6670,7 @@ export const getTypedNotificationByIdResponse = zod
),
})
.describe(
- 'The session an agent-session notification is about, and where its magic\nchip lives when it was opened from a thread.\n\nFlattened into each agent-session kind so the wire keeps these keys at the\ntop level of the metadata, the way [`CommonChannelMetadata`] does.'
+ 'Flattened into each agent-session kind so the wire keeps these keys at the\ntop level of the metadata, the way [`CommonChannelMetadata`] does.'
)
.and(
zod.object({
@@ -6559,8 +6729,25 @@ export const getTypedNotificationByIdResponse = zod
.uuid()
.nullish()
.describe(
- 'The channel the session was opened from, when it was.'
+ 'The channel the session was opened from, when it was opened from a\nchannel thread.'
),
+ parent: zod
+ .union([
+ zod.null(),
+ zod
+ .object({
+ id: zod
+ .string()
+ .describe('The channel or document id.'),
+ type: zod
+ .string()
+ .describe('`channel` or `document`.'),
+ })
+ .describe(
+ "The session an agent-session notification is about, and where its magic\nchip lives when it was opened from a thread.\n\nThe conversation an agent session was opened from: a channel or a\ndocument discussion. Spelled like the message API's parent so a client can\nroute to either surface."
+ ),
+ ])
+ .optional(),
sessionId: zod
.uuid()
.describe('The session; what a click opens.'),
@@ -6575,7 +6762,7 @@ export const getTypedNotificationByIdResponse = zod
),
})
.describe(
- 'The session an agent-session notification is about, and where its magic\nchip lives when it was opened from a thread.\n\nFlattened into each agent-session kind so the wire keeps these keys at the\ntop level of the metadata, the way [`CommonChannelMetadata`] does.'
+ 'Flattened into each agent-session kind so the wire keeps these keys at the\ntop level of the metadata, the way [`CommonChannelMetadata`] does.'
)
.and(
zod.object({
@@ -6622,8 +6809,25 @@ export const getTypedNotificationByIdResponse = zod
.uuid()
.nullish()
.describe(
- 'The channel the session was opened from, when it was.'
+ 'The channel the session was opened from, when it was opened from a\nchannel thread.'
),
+ parent: zod
+ .union([
+ zod.null(),
+ zod
+ .object({
+ id: zod
+ .string()
+ .describe('The channel or document id.'),
+ type: zod
+ .string()
+ .describe('`channel` or `document`.'),
+ })
+ .describe(
+ "The session an agent-session notification is about, and where its magic\nchip lives when it was opened from a thread.\n\nThe conversation an agent session was opened from: a channel or a\ndocument discussion. Spelled like the message API's parent so a client can\nroute to either surface."
+ ),
+ ])
+ .optional(),
sessionId: zod
.uuid()
.describe('The session; what a click opens.'),
@@ -6638,7 +6842,7 @@ export const getTypedNotificationByIdResponse = zod
),
})
.describe(
- 'The session an agent-session notification is about, and where its magic\nchip lives when it was opened from a thread.\n\nFlattened into each agent-session kind so the wire keeps these keys at the\ntop level of the metadata, the way [`CommonChannelMetadata`] does.'
+ 'Flattened into each agent-session kind so the wire keeps these keys at the\ntop level of the metadata, the way [`CommonChannelMetadata`] does.'
)
.and(
zod.object({
diff --git a/apps/web/src/lib/service-clients/service-notification/openapi.json b/apps/web/src/lib/service-clients/service-notification/openapi.json
index e07be1f0ab..62040128af 100644
--- a/apps/web/src/lib/service-clients/service-notification/openapi.json
+++ b/apps/web/src/lib/service-clients/service-notification/openapi.json
@@ -1056,7 +1056,7 @@
},
"AgentSessionNotificationRef": {
"type": "object",
- "description": "The session an agent-session notification is about, and where its magic\nchip lives when it was opened from a thread.\n\nFlattened into each agent-session kind so the wire keeps these keys at the\ntop level of the metadata, the way [`CommonChannelMetadata`] does.",
+ "description": "Flattened into each agent-session kind so the wire keeps these keys at the\ntop level of the metadata, the way [`CommonChannelMetadata`] does.",
"required": ["sessionId", "sessionName", "botId", "botName"],
"properties": {
"announcementMessageId": {
@@ -1075,7 +1075,18 @@
"channelId": {
"type": ["string", "null"],
"format": "uuid",
- "description": "The channel the session was opened from, when it was."
+ "description": "The channel the session was opened from, when it was opened from a\nchannel thread."
+ },
+ "parent": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/AgentSessionOriginParent",
+ "description": "The channel or document the session was opened from, when it was."
+ }
+ ]
},
"sessionId": {
"type": "string",
@@ -1093,6 +1104,21 @@
}
}
},
+ "AgentSessionOriginParent": {
+ "type": "object",
+ "description": "The session an agent-session notification is about, and where its magic\nchip lives when it was opened from a thread.\n\nThe conversation an agent session was opened from: a channel or a\ndocument discussion. Spelled like the message API's parent so a client can\nroute to either surface.",
+ "required": ["type", "id"],
+ "properties": {
+ "id": {
+ "type": "string",
+ "description": "The channel or document id."
+ },
+ "type": {
+ "type": "string",
+ "description": "`channel` or `document`."
+ }
+ }
+ },
"AgentSessionSettledMetadata": {
"allOf": [
{
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 2a7a2b4706..d0b2379796 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
@@ -1392,6 +1392,7 @@ export * from './threadAnchorOneOfType';
export * from './threadCreatedAt';
export * from './threadDeletedAt';
export * from './threadOrigin';
+export * from './threadOriginChannelId';
export * from './threadPatch';
export * from './threadPatchNonce';
export * from './threadPatchResolved';
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/threadOrigin.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/threadOrigin.ts
index f50c717834..16590e64a1 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/threadOrigin.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/threadOrigin.ts
@@ -5,14 +5,20 @@
* OpenAPI spec version: 0.1.0
*/
+import type { MessageParent } from './messageParent';
+import type { ThreadOriginChannelId } from './threadOriginChannelId';
+
/**
- * The channel thread a session was opened from, when it was.
+ * The thread a session was opened from, when it was.
*/
export interface ThreadOrigin {
- /** Channel the thread lives in. */
- channel_id: string;
+ /** Channel the thread lives in, for channel parents only. Kept beside
+`parent` for consumers written when every origin was a channel. */
+ channel_id?: ThreadOriginChannelId;
/** The message whose mention opened the session. */
originating_message_id: string;
+ /** Entity owning the thread: the channel or document it was posted in. */
+ parent: MessageParent;
/** Root message of the thread. */
thread_id: string;
}
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/threadOriginChannelId.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/threadOriginChannelId.ts
new file mode 100644
index 0000000000..c041b96685
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/threadOriginChannelId.ts
@@ -0,0 +1,12 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Channel the thread lives in, for channel parents only. Kept beside
+`parent` for consumers written when every origin was a channel.
+ */
+export type ThreadOriginChannelId = string | null;
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 2400f6d0ba..666555e87a 100644
--- a/apps/web/src/lib/service-clients/service-storage/openapi.json
+++ b/apps/web/src/lib/service-clients/service-storage/openapi.json
@@ -29589,19 +29589,23 @@
},
"ThreadOrigin": {
"type": "object",
- "description": "The channel thread a session was opened from, when it was.",
- "required": ["channel_id", "thread_id", "originating_message_id"],
+ "description": "The thread a session was opened from, when it was.",
+ "required": ["parent", "thread_id", "originating_message_id"],
"properties": {
"channel_id": {
- "type": "string",
+ "type": ["string", "null"],
"format": "uuid",
- "description": "Channel the thread lives in."
+ "description": "Channel the thread lives in, for channel parents only. Kept beside\n`parent` for consumers written when every origin was a channel."
},
"originating_message_id": {
"type": "string",
"format": "uuid",
"description": "The message whose mention opened the session."
},
+ "parent": {
+ "$ref": "#/components/schemas/MessageParent",
+ "description": "Entity owning the thread: the channel or document it was posted in."
+ },
"thread_id": {
"type": "string",
"format": "uuid",
diff --git a/crates/agent_harness/Cargo.toml b/crates/agent_harness/Cargo.toml
index 27770a538f..482686461a 100644
--- a/crates/agent_harness/Cargo.toml
+++ b/crates/agent_harness/Cargo.toml
@@ -30,7 +30,6 @@ bot_id = { path = "../bot_id" }
harness_id = { path = "../harness_id" }
channel_sender = { path = "../channel_sender" }
chrono = { workspace = true }
-channels = { path = "../channels", features = ["ports"] }
lexical_client = { path = "../lexical_client" }
dashmap = { workspace = true }
futures = { workspace = true }
@@ -49,10 +48,10 @@ macro_authorization = { path = "../macro_authorization", features = ["axum"] }
macro_tower_layers = { path = "../macro_tower_layers" }
macro_user_id = { path = "../macro_user_id" }
macro_uuid = { path = "../macro_uuid" }
-messages = { path = "../messages" }
model-entity = { path = "../model-entity" }
model_notifications = { path = "../model_notifications" }
notification = { path = "../notification" }
+messages = { path = "../messages", features = ["broker", "ports"] }
opentelemetry = { workspace = true, features = ["trace"] }
reqwest = { workspace = true }
redis = { workspace = true, features = ["aio", "tokio-comp"] }
@@ -78,6 +77,8 @@ utoipa = { workspace = true }
workspace-hack = { version = "0.1", path = "../workspace-hack" }
[dev-dependencies]
+channels = { path = "../channels", default-features = false }
+messages = { path = "../messages", features = ["test-utils"] }
uuid = { workspace = true }
agent_fold = { path = "../agent_fold", features = ["test-utils"] }
agent_session = { path = "../agent_session", features = ["test-utils"] }
diff --git a/crates/agent_harness/src/domain/model.rs b/crates/agent_harness/src/domain/model.rs
index fe44237e84..63e223e039 100644
--- a/crates/agent_harness/src/domain/model.rs
+++ b/crates/agent_harness/src/domain/model.rs
@@ -12,8 +12,8 @@ use macro_uuid::Uuid;
/// Where a mention happened.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct MentionOrigin {
- /// Channel the mentioning message was posted in.
- pub channel_id: Uuid,
+ /// Channel or document the mentioning message was posted in.
+ pub parent: messages::domain::models::MessageParent,
/// Thread the announcement replies into: the mention's thread root.
pub thread_id: Uuid,
/// The mentioning message itself.
@@ -152,18 +152,18 @@ pub(crate) use agent_egress::domain::model::is_macro_staff;
/// answer back into.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct AnnounceOrigin {
- /// Channel the prompt was posted in.
- pub channel_id: Uuid,
+ /// Channel or document the prompt was posted in.
+ pub parent: messages::domain::models::MessageParent,
/// Thread the announcement replies into.
pub thread_id: Uuid,
- /// The channel message that triggered the prompt.
+ /// The message that triggered the prompt.
pub message_id: Uuid,
}
-/// One channel message supplied as untrusted prompt context.
+/// One prior message supplied as untrusted prompt context.
#[derive(Debug, Clone, PartialEq, Eq)]
-pub struct PriorChannelMessage {
- /// Sender identifier as represented by the channels service.
+pub struct PriorMessage {
+ /// Sender identifier as the message service represents it.
pub sender: String,
/// Message body.
pub content: String,
@@ -285,7 +285,7 @@ impl DeliverAction {
/// the control endpoint, and this posts the magic-chip message the replies
/// render into. Split that way because each side is the only one that can
/// do its half honestly: only the runtime can reach its harness, and only
-/// the observed trigger event can vouch for the channel context.
+/// the observed trigger event can vouch for the conversation context.
#[derive(Debug, Clone)]
pub struct AnnouncePrompt {
/// The bot the trigger named; must match the session row before posting.
@@ -305,8 +305,8 @@ pub struct SessionAnnouncement {
pub session_id: AgentSessionId,
/// The bot the session runs for; the announcement posts as it.
pub bot_id: BotId,
- /// Channel containing the mention that opened the session.
- pub origin_channel_id: Uuid,
+ /// Channel or document containing the mention that opened the session.
+ pub origin_parent: messages::domain::models::MessageParent,
/// Thread where the announcement should be posted.
pub origin_thread_id: Uuid,
/// Channel message targeted by the announcement.
@@ -319,7 +319,7 @@ pub struct SessionAnnouncement {
pub triggered_by: MacroUserIdStr<'static>,
}
-/// The channel message an announcement became.
+/// The message an announcement became.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AnnouncedMessage {
/// The posted message: the magic chip its turn renders into.
diff --git a/crates/agent_harness/src/domain/notifications.rs b/crates/agent_harness/src/domain/notifications.rs
index 465c91a230..81e8dd548e 100644
--- a/crates/agent_harness/src/domain/notifications.rs
+++ b/crates/agent_harness/src/domain/notifications.rs
@@ -41,8 +41,8 @@ use macro_user_id::user_id::MacroUserIdStr;
use macro_uuid::Uuid;
use model_entity::{Entity, EntityType};
use model_notifications::{
- AgentSessionMentionedMetadata, AgentSessionNotificationRef, AgentSessionSettledMetadata,
- AgentSessionWaitingForInputMetadata,
+ AgentSessionMentionedMetadata, AgentSessionNotificationRef, AgentSessionOriginParent,
+ AgentSessionSettledMetadata, AgentSessionWaitingForInputMetadata,
};
use notification::domain::models::apple::PushNotificationData;
use notification::domain::models::request::SendNotificationRequestBuilder;
@@ -216,7 +216,17 @@ fn session_ref(
session_name: identity.session_name.clone(),
bot_id: identity.bot_id.as_uuid(),
bot_name: identity.bot_name.clone(),
- channel_id: identity.origin.as_ref().map(|origin| origin.channel_id),
+ parent: identity
+ .origin
+ .as_ref()
+ .map(|origin| AgentSessionOriginParent {
+ kind: origin.parent.entity_type().to_owned(),
+ id: origin.parent.entity_id(),
+ }),
+ channel_id: identity
+ .origin
+ .as_ref()
+ .and_then(|origin| origin.channel_id),
thread_id: identity.origin.as_ref().map(|origin| origin.thread_id),
announcement_message_id,
}
diff --git a/crates/agent_harness/src/domain/notifications/test.rs b/crates/agent_harness/src/domain/notifications/test.rs
index 59c345472a..c0542cb9f5 100644
--- a/crates/agent_harness/src/domain/notifications/test.rs
+++ b/crates/agent_harness/src/domain/notifications/test.rs
@@ -29,11 +29,11 @@ fn identity() -> SessionIdentity {
bot_id: BotId::new_from_uuid(Uuid::from_u128(0xB07)),
bot_name: "Macro Coder".to_owned(),
owner_id: owner(),
- origin: Some(ThreadOrigin {
- channel_id: Uuid::from_u128(1),
- thread_id: Uuid::from_u128(2),
- originating_message_id: Uuid::from_u128(3),
- }),
+ origin: Some(ThreadOrigin::new(
+ messages::domain::models::MessageParent::Channel(Uuid::from_u128(1)),
+ Uuid::from_u128(2),
+ Uuid::from_u128(3),
+ )),
audience: vec![owner(), user("[email protected]"), user("[email protected]")],
}
}
diff --git a/crates/agent_harness/src/domain/ports.rs b/crates/agent_harness/src/domain/ports.rs
index 9358f407c7..43ed3664ae 100644
--- a/crates/agent_harness/src/domain/ports.rs
+++ b/crates/agent_harness/src/domain/ports.rs
@@ -14,7 +14,7 @@ use macro_user_id::user_id::MacroUserIdStr;
use super::error::{HarnessError, Result};
use super::model::{
- AgentRuntimeConfig, AnnouncedMessage, CommandOutcome, HarnessCommand, PriorChannelMessage,
+ AgentRuntimeConfig, AnnouncedMessage, CommandOutcome, HarnessCommand, PriorMessage,
ProvisionedEgress, SandboxEgress, SessionAnnouncement, SpawnContainer,
};
use super::notifications::PlannedNotification;
@@ -112,22 +112,22 @@ pub trait AgentRuntimeDirectory: Send + Sync + 'static {
) -> impl Future<Output = Result<Option<AgentRuntimeConfig>>> + Send;
}
-/// Loads messages preceding a channel-originated agent prompt.
-pub trait ChannelPromptContext: Send + Sync + 'static {
- /// Verify that a user who triggered a prompt remains a channel member.
- fn authorize_member(
+/// Authorizes message origins and loads conversation context for agent prompts.
+pub trait MessagePromptContext: Send + Sync + 'static {
+ /// Recheck the actor's posting permission and verify the live message belongs
+ /// to exactly this parent and root before provisioning or dispatching work.
+ fn authorize_origin(
&self,
- actor: &macro_user_id::user_id::MacroUserIdStr<'static>,
- channel_id: macro_uuid::Uuid,
+ actor: &MacroUserIdStr<'static>,
+ origin: &super::model::AnnounceOrigin,
) -> impl Future<Output = Result<()>> + Send;
- /// Return up to ten non-deleted messages immediately before `message_id`
- /// in chronological order.
+ /// Read up to ten preceding live messages with a fresh access check.
fn preceding_messages(
&self,
- channel_id: macro_uuid::Uuid,
- message_id: macro_uuid::Uuid,
- ) -> impl Future<Output = Result<Vec<PriorChannelMessage>>> + Send;
+ actor: &MacroUserIdStr<'static>,
+ origin: &super::model::AnnounceOrigin,
+ ) -> impl Future<Output = Result<Vec<PriorMessage>>> + Send;
}
/// Composes an agent prompt from raw markdown and optional channel history.
@@ -137,7 +137,8 @@ pub trait AgentPromptComposer: Send + Sync + 'static {
fn compose(
&self,
prompt_markdown: &str,
- messages: Option<&[PriorChannelMessage]>,
+ parent: Option<&messages::domain::models::MessageParent>,
+ messages: Option<&[PriorMessage]>,
) -> impl Future<Output = Result<String>> + Send;
}
diff --git a/crates/agent_harness/src/domain/service.rs b/crates/agent_harness/src/domain/service.rs
index 0f52e5e31f..4c39048bd8 100644
--- a/crates/agent_harness/src/domain/service.rs
+++ b/crates/agent_harness/src/domain/service.rs
@@ -51,8 +51,8 @@ use crate::domain::model::{
};
use crate::domain::pending::PendingCommands;
use crate::domain::ports::{
- AgentPromptComposer, AgentSessionNotifier, ChannelPromptContext, CommandForwarder,
- ContainerManager, PromptMentions, RuntimeConnections, SandboxEgressProvisioner,
+ AgentPromptComposer, AgentSessionNotifier, CommandForwarder, ContainerManager,
+ MessagePromptContext, PromptMentions, RuntimeConnections, SandboxEgressProvisioner,
SessionAnnouncer,
};
use crate::domain::queue::{InFlightTurn, QueueError, QueuedEntry, SessionQueues};
@@ -229,7 +229,7 @@ where
Containers: ContainerManager,
Announcer: SessionAnnouncer,
Runtimes: RuntimeConnections,
- PromptContext: ChannelPromptContext,
+ PromptContext: MessagePromptContext,
PromptComposer: AgentPromptComposer,
Egress: SandboxEgressProvisioner,
Lifecycle: AgentSessionLifecyclePublisher,
@@ -330,6 +330,10 @@ where
session_id: AgentSessionId,
prompt: AnnouncePrompt,
) -> Result<()> {
+ self.inner
+ .prompt_context
+ .authorize_origin(&prompt.sender, &prompt.origin)
+ .await?;
// Re-read rather than trusted: the row is what vouches that the
// trigger's session and bot actually belong together.
let session = self.inner.sessions.get_session(session_id).await?;
@@ -348,7 +352,7 @@ where
.announce(SessionAnnouncement {
session_id,
bot_id: session.bot_id,
- origin_channel_id: prompt.origin.channel_id,
+ origin_parent: prompt.origin.parent,
origin_thread_id: prompt.origin.thread_id,
origin_message_id: prompt.origin.message_id,
prompted_message_id: self
@@ -406,7 +410,7 @@ where
Containers: ContainerManager,
Announcer: SessionAnnouncer,
Runtimes: RuntimeConnections,
- PromptContext: ChannelPromptContext,
+ PromptContext: MessagePromptContext,
PromptComposer: AgentPromptComposer,
Egress: SandboxEgressProvisioner,
Lifecycle: AgentSessionLifecyclePublisher,
diff --git a/crates/agent_harness/src/domain/service/deliver.rs b/crates/agent_harness/src/domain/service/deliver.rs
index ae39ce16da..9a269ed59b 100644
--- a/crates/agent_harness/src/domain/service/deliver.rs
+++ b/crates/agent_harness/src/domain/service/deliver.rs
@@ -32,7 +32,7 @@ where
Containers: ContainerManager,
Announcer: SessionAnnouncer,
Runtimes: RuntimeConnections,
- PromptContext: ChannelPromptContext,
+ PromptContext: MessagePromptContext,
PromptComposer: AgentPromptComposer,
Egress: SandboxEgressProvisioner,
Lifecycle: AgentSessionLifecyclePublisher,
@@ -123,9 +123,10 @@ where
/// Compose a prompt in place. Compact and other actions are left as-is.
///
- /// Channel context is loaded when the prompt named an origin; a lookup
- /// failure still composes, with empty history, so a transient context
- /// outage cannot eat the prompt.
+ /// Message context is loaded when the prompt named an origin. The actor's
+ /// current access to that origin gates composition; a failed history read
+ /// still composes, with empty history, so a transient context outage
+ /// cannot eat the prompt.
pub(super) async fn compose_action(
&self,
action: &mut AgentAction,
@@ -137,49 +138,51 @@ where
};
let raw_prompt = prompt.prompt.clone();
let prior_messages = if let Some(origin) = announce {
- Some(
- self.load_prompt_context(origin.channel_id, origin.message_id, actor)
- .await,
- )
+ Some(self.load_prompt_context(origin, actor).await?)
} else {
None
};
prompt.prompt = self
.prompt_composer
- .compose(&raw_prompt, prior_messages.as_deref())
+ .compose(
+ &raw_prompt,
+ announce.map(|origin| &origin.parent),
+ prior_messages.as_deref(),
+ )
.await?;
prompt.set_name_source(raw_prompt);
Ok(())
}
+ /// Recheck the actor's access to the origin, then read the history before
+ /// it. Authorization is not optional: a prompt that names an origin was
+ /// posted by a user, and one who may no longer write there sends nothing.
pub(super) async fn load_prompt_context(
&self,
- channel_id: macro_uuid::Uuid,
- message_id: macro_uuid::Uuid,
+ origin: &AnnounceOrigin,
actor: Option<&MacroUserIdStr<'static>>,
- ) -> Vec<crate::domain::model::PriorChannelMessage> {
- async {
- if let Some(actor) = actor {
- self.prompt_context
- .authorize_member(actor, channel_id)
- .await?;
- }
- self.prompt_context
- .preceding_messages(channel_id, message_id)
- .await
- }
- .await
- .inspect_err(|error| {
- // Trigger events are admitted at-most-once. Context is useful,
- // but a transient lookup failure must not discard the prompt.
- tracing::warn!(
- error = ?error,
- %channel_id,
- %message_id,
- "sending agent prompt without channel history"
- );
- })
- .unwrap_or_default()
+ ) -> Result<Vec<crate::domain::model::PriorMessage>> {
+ let actor = actor.ok_or_else(|| {
+ HarnessError::PromptContext(rootcause::report!(
+ "message prompts require an acting user"
+ ))
+ })?;
+ self.prompt_context.authorize_origin(actor, origin).await?;
+ Ok(self
+ .prompt_context
+ .preceding_messages(actor, origin)
+ .await
+ .inspect_err(|error| {
+ // Trigger events are admitted at-most-once. Context is useful,
+ // but a transient lookup failure must not discard the prompt.
+ tracing::warn!(
+ error = ?error,
+ parent = ?origin.parent,
+ message_id = %origin.message_id,
+ "sending agent prompt without conversation history"
+ );
+ })
+ .unwrap_or_default())
}
/// Who, if anyone, should be told that this landed.
@@ -208,7 +211,7 @@ where
Ok(Some(SessionAnnouncement {
session_id,
bot_id: session.bot_id,
- origin_channel_id: origin.channel_id,
+ origin_parent: origin.parent,
origin_thread_id: origin.thread_id,
origin_message_id: origin.message_id,
prompted_message_id,
diff --git a/crates/agent_harness/src/domain/service/lifecycle.rs b/crates/agent_harness/src/domain/service/lifecycle.rs
index 7742bd1f96..7a534dcee5 100644
--- a/crates/agent_harness/src/domain/service/lifecycle.rs
+++ b/crates/agent_harness/src/domain/service/lifecycle.rs
@@ -39,7 +39,7 @@ where
Containers: ContainerManager,
Announcer: SessionAnnouncer,
Runtimes: RuntimeConnections,
- PromptContext: ChannelPromptContext,
+ PromptContext: MessagePromptContext,
PromptComposer: AgentPromptComposer,
Egress: SandboxEgressProvisioner,
Lifecycle: AgentSessionLifecyclePublisher,
@@ -180,7 +180,7 @@ where
Containers: ContainerManager,
Announcer: SessionAnnouncer,
Runtimes: RuntimeConnections,
- PromptContext: ChannelPromptContext,
+ PromptContext: MessagePromptContext,
PromptComposer: AgentPromptComposer,
Egress: SandboxEgressProvisioner,
Lifecycle: AgentSessionLifecyclePublisher,
@@ -230,7 +230,7 @@ where
Containers: ContainerManager,
Announcer: SessionAnnouncer,
Runtimes: RuntimeConnections,
- PromptContext: ChannelPromptContext,
+ PromptContext: MessagePromptContext,
PromptComposer: AgentPromptComposer,
Egress: SandboxEgressProvisioner,
Lifecycle: AgentSessionLifecyclePublisher,
diff --git a/crates/agent_harness/src/domain/service/lifecycle_events.rs b/crates/agent_harness/src/domain/service/lifecycle_events.rs
index f9bad265ef..76c1ca686a 100644
--- a/crates/agent_harness/src/domain/service/lifecycle_events.rs
+++ b/crates/agent_harness/src/domain/service/lifecycle_events.rs
@@ -40,7 +40,7 @@ where
Containers: ContainerManager,
Announcer: SessionAnnouncer,
Runtimes: RuntimeConnections,
- PromptContext: ChannelPromptContext,
+ PromptContext: MessagePromptContext,
PromptComposer: AgentPromptComposer,
Egress: SandboxEgressProvisioner,
Lifecycle: AgentSessionLifecyclePublisher,
diff --git a/crates/agent_harness/src/domain/service/open.rs b/crates/agent_harness/src/domain/service/open.rs
index df06c7b760..adad74ba44 100644
--- a/crates/agent_harness/src/domain/service/open.rs
+++ b/crates/agent_harness/src/domain/service/open.rs
@@ -43,7 +43,7 @@ where
Containers: ContainerManager,
Announcer: SessionAnnouncer,
Runtimes: RuntimeConnections,
- PromptContext: ChannelPromptContext,
+ PromptContext: MessagePromptContext,
PromptComposer: AgentPromptComposer,
Egress: SandboxEgressProvisioner,
Lifecycle: AgentSessionLifecyclePublisher,
@@ -54,6 +54,29 @@ where
&self,
request: agent_session::domain::ports::OpenExternalAgentSession,
) -> agent_session::domain::error::Result<AgentSession> {
+ // The thread linkage is the caller's claim: it is honoured only when
+ // the owner can write to that parent and the message sits in it.
+ if let Some(thread) = &request.thread {
+ self.inner
+ .prompt_context
+ .authorize_origin(
+ &request.owner,
+ &AnnounceOrigin {
+ parent: thread.parent.clone(),
+ thread_id: thread.thread_id,
+ message_id: thread.message_id,
+ },
+ )
+ .await
+ .map_err(|error| {
+ tracing::warn!(
+ error = ?error,
+ owner = %request.owner,
+ "rejecting an external session whose claimed thread its owner may not post in"
+ );
+ AgentSessionError::Forbidden
+ })?;
+ }
let defaults = self.inner.defaults.for_bot(request.bot_id);
let session = self
.inner
@@ -86,7 +109,7 @@ where
let announcement = SessionAnnouncement {
session_id: session.id,
bot_id: request.bot_id,
- origin_channel_id: thread.channel_id,
+ origin_parent: thread.parent,
origin_thread_id: thread.thread_id,
origin_message_id: thread.message_id,
prompted_message_id: MessageId::first(AuthorKind::User),
@@ -318,13 +341,13 @@ where
match self
.inner
.sessions
- .find_for_channel(Some(thread_id), Some(bot_id))
+ .find_for_thread(Some(thread_id), Some(bot_id))
.await?
{
- agent_session::domain::model::ChannelSession::CreatedFromThread(session) => {
+ agent_session::domain::model::ThreadSession::CreatedFromThread(session) => {
Ok(Some(session.id))
}
- agent_session::domain::model::ChannelSession::None => Ok(None),
+ agent_session::domain::model::ThreadSession::None => Ok(None),
}
}
}
@@ -358,7 +381,7 @@ where
Containers: ContainerManager,
Announcer: SessionAnnouncer,
Runtimes: RuntimeConnections,
- PromptContext: ChannelPromptContext,
+ PromptContext: MessagePromptContext,
PromptComposer: AgentPromptComposer,
Egress: SandboxEgressProvisioner,
Lifecycle: AgentSessionLifecyclePublisher,
@@ -369,7 +392,7 @@ where
%session_id,
bot_id = %command.bot_id,
message_id = %command.origin.message_id,
- channel_id = %command.origin.channel_id,
+ parent = ?command.origin.parent,
thread_id = %command.origin.thread_id,
agent.trigger.kind = "mention",
agent.session.id = tracing::field::Empty,
@@ -385,6 +408,18 @@ where
origin,
} = command;
tracing::Span::current().record("agent.session.id", tracing::field::display(session_id));
+ // The mention was observed, but the sender's access is checked now:
+ // a user removed from the parent since posting opens nothing.
+ self.prompt_context
+ .authorize_origin(
+ &origin.sender,
+ &AnnounceOrigin {
+ parent: origin.parent.clone(),
+ thread_id: origin.thread_id,
+ message_id: origin.message_id,
+ },
+ )
+ .await?;
let defaults = self.defaults.for_bot(bot_id);
let sandbox_size = self.sessions.user_sandbox_size(&origin.sender).await?;
@@ -475,7 +510,7 @@ where
action: AgentAction::prompt(origin.content),
actor: Some(origin.sender),
announce: Some(AnnounceOrigin {
- channel_id: origin.channel_id,
+ parent: origin.parent,
thread_id: origin.thread_id,
message_id: origin.message_id,
}),
diff --git a/crates/agent_harness/src/domain/service/queue.rs b/crates/agent_harness/src/domain/service/queue.rs
index 00c798ec1e..3538c41e6e 100644
--- a/crates/agent_harness/src/domain/service/queue.rs
+++ b/crates/agent_harness/src/domain/service/queue.rs
@@ -89,7 +89,7 @@ where
Containers: ContainerManager,
Announcer: SessionAnnouncer,
Runtimes: RuntimeConnections,
- PromptContext: ChannelPromptContext,
+ PromptContext: MessagePromptContext,
PromptComposer: AgentPromptComposer,
Egress: SandboxEgressProvisioner,
Lifecycle: AgentSessionLifecyclePublisher,
@@ -186,7 +186,7 @@ where
Containers: ContainerManager,
Announcer: SessionAnnouncer,
Runtimes: RuntimeConnections,
- PromptContext: ChannelPromptContext,
+ PromptContext: MessagePromptContext,
PromptComposer: AgentPromptComposer,
Egress: SandboxEgressProvisioner,
Lifecycle: AgentSessionLifecyclePublisher,
@@ -809,7 +809,7 @@ pub(super) async fn run_session_worker<
Containers: ContainerManager,
Announcer: SessionAnnouncer,
Runtimes: RuntimeConnections,
- PromptContext: ChannelPromptContext,
+ PromptContext: MessagePromptContext,
PromptComposer: AgentPromptComposer,
Egress: SandboxEgressProvisioner,
Lifecycle: AgentSessionLifecyclePublisher,
diff --git a/crates/agent_harness/src/domain/service/test.rs b/crates/agent_harness/src/domain/service/test.rs
index df1d6e186b..bfbdf7f430 100644
--- a/crates/agent_harness/src/domain/service/test.rs
+++ b/crates/agent_harness/src/domain/service/test.rs
@@ -2,6 +2,7 @@
//! with in-memory persistence, mock containers, a fake agent, and a
//! recording announcer. Only the edges are doubles.
+use messages::domain::models::MessageParent;
use std::sync::{Arc, Mutex};
use agent_client_protocol::RawJsonRpcMessage;
@@ -39,11 +40,11 @@ use super::into_session_error;
use crate::domain::error::HarnessError;
use crate::domain::model::{
AgentKind, AgentRuntimeConfig, AnnounceOrigin, CommandOutcome, DeliverAction, HarnessCommand,
- HarnessDefaults, MentionOrigin, OpenSession, PriorChannelMessage, SessionDefaults,
- SessionRepository, SpawnContainer,
+ HarnessDefaults, MentionOrigin, OpenSession, PriorMessage, SessionDefaults, SessionRepository,
+ SpawnContainer,
};
use crate::domain::ports::{
- AgentPromptComposer, ChannelPromptContext, ContainerManager as _, NoPeers,
+ AgentPromptComposer, ContainerManager as _, MessagePromptContext, NoPeers,
};
use crate::outbound::runtime_registry::RuntimeRegistry;
use crate::testing::helpers::agent::FakeAgent;
@@ -89,7 +90,7 @@ fn open_command() -> OpenSession {
mcp_servers: AgentMcpServers::OwnerConnections,
},
origin: MentionOrigin {
- channel_id: macro_uuid::generate_uuid_v7(),
+ parent: MessageParent::Channel(macro_uuid::generate_uuid_v7()),
thread_id,
message_id: thread_id,
sender: sender(),
@@ -107,7 +108,7 @@ fn forward_message(content: &str) -> DeliverAction {
content,
Some(staff_sender()),
Some(AnnounceOrigin {
- channel_id: macro_uuid::Uuid::from_u128(0xf0),
+ parent: MessageParent::Channel(macro_uuid::Uuid::from_u128(0xf0)),
thread_id: macro_uuid::Uuid::from_u128(0xf1),
message_id: macro_uuid::Uuid::from_u128(0xf2),
}),
@@ -116,40 +117,60 @@ fn forward_message(content: &str) -> DeliverAction {
#[derive(Clone, Default)]
struct PromptContextMock {
- messages: Arc<Mutex<Vec<PriorChannelMessage>>>,
+ messages: Arc<Mutex<Vec<PriorMessage>>>,
failure: Arc<Mutex<Option<String>>>,
+ unauthorized: Arc<Mutex<Option<String>>>,
+ authorized: Arc<Mutex<Vec<(MacroUserIdStr<'static>, AnnounceOrigin)>>>,
}
impl PromptContextMock {
- fn with_messages(messages: Vec<PriorChannelMessage>) -> Self {
+ fn with_messages(messages: Vec<PriorMessage>) -> Self {
Self {
messages: Arc::new(Mutex::new(messages)),
- failure: Arc::default(),
+ ..Self::default()
}
}
fn failing(message: &str) -> Self {
Self {
- messages: Arc::default(),
failure: Arc::new(Mutex::new(Some(message.to_owned()))),
+ ..Self::default()
}
}
+
+ fn unauthorized(message: &str) -> Self {
+ Self {
+ unauthorized: Arc::new(Mutex::new(Some(message.to_owned()))),
+ ..Self::default()
+ }
+ }
+
+ fn authorized(&self) -> Vec<(MacroUserIdStr<'static>, AnnounceOrigin)> {
+ self.authorized.lock().unwrap().clone()
+ }
}
-impl ChannelPromptContext for PromptContextMock {
- async fn authorize_member(
+impl MessagePromptContext for PromptContextMock {
+ async fn authorize_origin(
&self,
- _actor: &MacroUserIdStr<'static>,
- _channel_id: Uuid,
+ actor: &MacroUserIdStr<'static>,
+ origin: &AnnounceOrigin,
) -> crate::domain::error::Result<()> {
+ if let Some(message) = self.unauthorized.lock().unwrap().clone() {
+ return Err(HarnessError::PromptContext(rootcause::report!("{message}")));
+ }
+ self.authorized
+ .lock()
+ .unwrap()
+ .push((actor.clone(), origin.clone()));
Ok(())
}
async fn preceding_messages(
&self,
- _channel_id: Uuid,
- _message_id: Uuid,
- ) -> crate::domain::error::Result<Vec<PriorChannelMessage>> {
+ _actor: &MacroUserIdStr<'static>,
+ _origin: &AnnounceOrigin,
+ ) -> crate::domain::error::Result<Vec<PriorMessage>> {
if let Some(message) = self.failure.lock().unwrap().clone() {
return Err(HarnessError::PromptContext(rootcause::report!("{message}")));
}
@@ -157,7 +178,7 @@ impl ChannelPromptContext for PromptContextMock {
}
}
-type PromptCompositionCall = (String, Option<Vec<PriorChannelMessage>>);
+type PromptCompositionCall = (String, Option<Vec<PriorMessage>>);
#[derive(Clone, Default)]
struct PromptComposerMock {
@@ -182,7 +203,8 @@ impl AgentPromptComposer for PromptComposerMock {
async fn compose(
&self,
prompt_markdown: &str,
- messages: Option<&[PriorChannelMessage]>,
+ _parent: Option<&MessageParent>,
+ messages: Option<&[PriorMessage]>,
) -> crate::domain::error::Result<String> {
self.calls.lock().unwrap().push((
prompt_markdown.to_owned(),
@@ -538,7 +560,7 @@ async fn open_creates_announces_and_delivers_the_mention() {
assert_eq!(session.harness, "opencode");
let announced = announcer.announced();
assert_eq!(announced.len(), 1);
- assert_eq!(announced[0].origin_channel_id, origin.channel_id);
+ assert_eq!(announced[0].origin_parent, origin.parent);
assert_eq!(announced[0].origin_thread_id, origin.thread_id);
assert_eq!(announced[0].triggered_by, origin.sender);
assert_eq!(
@@ -641,14 +663,36 @@ async fn open_snapshots_the_agents_mcp_selection_onto_the_session() {
}
#[tokio::test]
-async fn context_failure_still_calls_composer_with_empty_messages_and_delivers() {
+async fn revoked_origin_access_blocks_open_before_anything_is_provisioned() {
let composer = PromptComposerMock::default();
- let (service, _repo, containers, announcer, _runtimes) = harness_with_edges(
- PromptContextMock::failing("channels unavailable"),
+ let (service, repo, containers, announcer, _runtimes) = harness_with_edges(
+ PromptContextMock::unauthorized("removed from the channel"),
composer.clone(),
);
let id = AgentSessionId::new();
+ let result = service
+ .execute(id, HarnessCommand::Open(open_command()))
+ .await;
+
+ assert!(
+ matches!(result, Err(HarnessError::PromptContext(_))),
+ "a sender who may not write to the origin opens nothing: {result:?}"
+ );
+ assert!(repo.get(id).await.is_err());
+ assert_eq!(containers.spawned(), 0);
+ assert!(announcer.announced().is_empty());
+ assert!(composer.calls().is_empty());
+}
+
+#[tokio::test]
+async fn context_failure_still_calls_composer_with_empty_messages_and_delivers() {
+ let composer = PromptComposerMock::default();
+ let context = PromptContextMock::failing("messages unavailable");
+ let (service, _repo, containers, announcer, _runtimes) =
+ harness_with_edges(context.clone(), composer.clone());
+ let id = AgentSessionId::new();
+
let open = service.execute(id, HarnessCommand::Open(open_command()));
let drive = async {
loop {
@@ -664,6 +708,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);
assert_eq!(announcer.announced().len(), 1);
assert_eq!(
composer.calls(),
@@ -711,7 +758,7 @@ async fn composer_failure_stops_open_delivery_and_keeps_the_prompt_queued() {
#[tokio::test]
async fn open_sends_context_but_not_agent_instructions_to_the_agent_prompt() {
- let context = vec![PriorChannelMessage {
+ let context = vec![PriorMessage {
sender: "[email protected]".to_owned(),
content: "previous channel message".to_owned(),
}];
@@ -856,7 +903,10 @@ async fn forward_to_a_live_session_reuses_the_transport() {
author: AuthorKind::User,
}
);
- assert_eq!(announced[1].origin_channel_id, Uuid::from_u128(0xf0));
+ assert_eq!(
+ announced[1].origin_parent,
+ MessageParent::Channel(Uuid::from_u128(0xf0))
+ );
assert_eq!(announced[1].origin_thread_id, Uuid::from_u128(0xf1));
}
@@ -2177,7 +2227,7 @@ async fn an_external_open_with_a_mention_announces_as_the_sessions_bot() {
let mut request = open_external_request("/srv/agent");
let bot = request.bot_id;
request.thread = Some(agent_session::domain::ports::SessionThread {
- channel_id: macro_uuid::Uuid::from_u128(0xC1),
+ parent: MessageParent::Channel(macro_uuid::Uuid::from_u128(0xC1)),
thread_id: macro_uuid::Uuid::from_u128(0xC2),
message_id: macro_uuid::Uuid::from_u128(0xC2),
content: "@opencode fix the flaky test".to_owned(),
@@ -2195,8 +2245,8 @@ async fn an_external_open_with_a_mention_announces_as_the_sessions_bot() {
assert_eq!(announced.len(), 1);
assert_eq!(announced[0].bot_id, bot);
assert_eq!(
- announced[0].origin_channel_id,
- macro_uuid::Uuid::from_u128(0xC1)
+ announced[0].origin_parent,
+ MessageParent::Channel(macro_uuid::Uuid::from_u128(0xC1))
);
assert_eq!(
announced[0].prompted_content,
@@ -2222,7 +2272,7 @@ async fn an_external_prompt_announce_posts_into_the_observed_origin() {
crate::domain::model::AnnouncePrompt {
bot_id: bot,
origin: AnnounceOrigin {
- channel_id: macro_uuid::Uuid::from_u128(0xAA),
+ parent: MessageParent::Channel(macro_uuid::Uuid::from_u128(0xAA)),
thread_id: macro_uuid::Uuid::from_u128(0xAB),
message_id: macro_uuid::Uuid::from_u128(0xAC),
},
@@ -2238,8 +2288,8 @@ async fn an_external_prompt_announce_posts_into_the_observed_origin() {
assert_eq!(announced.len(), 1, "threadless open posts no chip");
assert_eq!(announced[0].bot_id, bot);
assert_eq!(
- announced[0].origin_channel_id,
- macro_uuid::Uuid::from_u128(0xAA)
+ announced[0].origin_parent,
+ MessageParent::Channel(macro_uuid::Uuid::from_u128(0xAA))
);
assert_eq!(
announced[0].origin_thread_id,
@@ -2262,7 +2312,7 @@ async fn an_announce_whose_bot_does_not_own_the_session_is_dropped() {
crate::domain::model::AnnouncePrompt {
bot_id: BotId::new_from_uuid(macro_uuid::generate_uuid_v7()),
origin: AnnounceOrigin {
- channel_id: macro_uuid::Uuid::from_u128(0xAA),
+ parent: MessageParent::Channel(macro_uuid::Uuid::from_u128(0xAA)),
thread_id: macro_uuid::Uuid::from_u128(0xAB),
message_id: macro_uuid::Uuid::from_u128(0xAC),
},
diff --git a/crates/agent_harness/src/domain/trigger_router.rs b/crates/agent_harness/src/domain/trigger_router.rs
index 32e9488ff8..4b791ba8a2 100644
--- a/crates/agent_harness/src/domain/trigger_router.rs
+++ b/crates/agent_harness/src/domain/trigger_router.rs
@@ -2,7 +2,7 @@
use agent_session::domain::model::AgentSessionId;
use agent_trigger::domain::broker_events::{
- AgentTriggerTopicEvent, ChannelEventMetadata, ExistingAgentSessionEvent, NewAgentSessionEvent,
+ AgentTriggerTopicEvent, OpeningMention, SessionMessage,
};
use bot_id::BotId;
@@ -38,15 +38,7 @@ pub enum Skipped {
/// Bot targeted by a recognized trigger event shape.
#[must_use]
pub fn agent_trigger_bot_id(event: &AgentTriggerTopicEvent) -> Option<BotId> {
- match event {
- AgentTriggerTopicEvent::New(NewAgentSessionEvent::TopLevelMentioned(mentioned)) => {
- Some(mentioned.bot_id)
- }
- AgentTriggerTopicEvent::Existing(ExistingAgentSessionEvent::Channel(metadata)) => {
- Some(metadata.bot_id)
- }
- _ => None,
- }
+ event.bot_id()
}
/// Route one trigger event: work for this deployment, or a reason it was
@@ -62,11 +54,13 @@ pub fn route_agent_trigger(
runtime: Option<AgentRuntimeConfig>,
) -> Result<RoutedTrigger, Skipped> {
match event {
- AgentTriggerTopicEvent::New(NewAgentSessionEvent::TopLevelMentioned(mentioned)) => {
+ AgentTriggerTopicEvent::New(event) => {
+ let Some(OpeningMention { bot_id, message }) = event.mention() else {
+ return Err(Skipped::Unrecognized);
+ };
let Some(runtime) = runtime.filter(|runtime| runtime.kind.is_managed()) else {
return Err(Skipped::ForeignBot);
};
- let message = mentioned.message;
let sender = message
.sender
.as_user()
@@ -75,10 +69,10 @@ pub fn route_agent_trigger(
Ok(RoutedTrigger::Command(
AgentSessionId::new(),
HarnessCommand::Open(OpenSession {
- bot_id: mentioned.bot_id,
+ bot_id,
runtime,
origin: MentionOrigin {
- channel_id: message.channel_id,
+ parent: message.parent,
// A top-level mention roots its own thread; a mention
// inside a thread answers into that thread.
thread_id: message.thread_id.unwrap_or(message.message_id),
@@ -89,16 +83,18 @@ pub fn route_agent_trigger(
}),
))
}
- AgentTriggerTopicEvent::Existing(ExistingAgentSessionEvent::Channel(
- ChannelEventMetadata {
+ AgentTriggerTopicEvent::Existing(event) => {
+ let Some(SessionMessage {
bot_id,
session_id,
kind: _,
message,
- },
- )) => {
+ }) = event.session_message()
+ else {
+ return Err(Skipped::Unrecognized);
+ };
let origin = AnnounceOrigin {
- channel_id: message.channel_id,
+ parent: message.parent,
thread_id: message.thread_id.unwrap_or(message.message_id),
message_id: message.message_id,
};
@@ -130,6 +126,5 @@ pub fn route_agent_trigger(
},
))
}
- _ => Err(Skipped::Unrecognized),
}
}
diff --git a/crates/agent_harness/src/inbound/kafka/test.rs b/crates/agent_harness/src/inbound/kafka/test.rs
index 985a9297f8..e32a2bed06 100644
--- a/crates/agent_harness/src/inbound/kafka/test.rs
+++ b/crates/agent_harness/src/inbound/kafka/test.rs
@@ -1,8 +1,8 @@
use agent_runtime_protocol::domain::action::AgentAction;
use agent_session::domain::model::{AgentMcpServers, AgentSessionId};
use agent_trigger::domain::broker_events::{
- AgentBotMentionedEvent, AgentTriggerTopicEvent, ChannelEventMetadata, ChannelKind,
- ExistingAgentSessionEvent, NewAgentSessionEvent,
+ AgentBotMentionedEvent, AgentMentionedEvent, AgentTriggerTopicEvent, ChannelEventMetadata,
+ ExistingAgentSessionEvent, NewAgentSessionEvent, ThreadEventMetadata, ThreadMessageKind,
};
use bot_id::{BotId, MACRO_CODER_BOT_ID};
use channel_sender::ChannelSender;
@@ -11,6 +11,8 @@ use channels::domain::models::ChannelType;
use chrono::Utc;
use macro_user_id::user_id::MacroUserIdStr;
use macro_uuid::Uuid;
+use messages::domain::events::MessagePostedMetadata;
+use messages::domain::models::MessageParent;
use super::*;
use crate::domain::model::{AgentKind, AgentRuntimeConfig, HarnessCommand};
@@ -37,6 +39,7 @@ fn user() -> MacroUserIdStr<'static> {
MacroUserIdStr::try_from_email("[email protected]").expect("a valid user id")
}
+/// A channel post in the channel-only shape channel triggers travel in.
fn message(sender: ChannelSender<'static>) -> ChannelMessagePostedMetadata {
ChannelMessagePostedMetadata {
channel_id: Uuid::from_u128(1),
@@ -52,6 +55,26 @@ fn message(sender: ChannelSender<'static>) -> ChannelMessagePostedMetadata {
}
}
+fn document() -> MessageParent {
+ MessageParent::parse("document", "doc-1").unwrap()
+}
+
+/// A document discussion post, which only the parent-aware shape carries.
+fn document_message(sender: ChannelSender<'static>) -> MessagePostedMetadata {
+ MessagePostedMetadata {
+ parent: document(),
+ message_id: Uuid::from_u128(2),
+ thread_id: None,
+ root_id: Uuid::from_u128(2),
+ sender,
+ triggered_by: None,
+ content: "@claude fix the tests".to_owned(),
+ mentions: vec![],
+ attachments: vec![],
+ created_at: Utc::now(),
+ }
+}
+
fn mentioned(bot: BotId, sender: ChannelSender<'static>) -> AgentTriggerTopicEvent {
AgentTriggerTopicEvent::New(NewAgentSessionEvent::TopLevelMentioned(
AgentBotMentionedEvent {
@@ -65,7 +88,7 @@ fn channel_message(bot: BotId) -> AgentTriggerTopicEvent {
AgentTriggerTopicEvent::Existing(ExistingAgentSessionEvent::Channel(ChannelEventMetadata {
bot_id: bot,
session_id: AgentSessionId::TEST_A,
- kind: ChannelKind::MentionThread,
+ kind: ThreadMessageKind::MentionThread,
message: message(ChannelSender::new_from_user(user())),
}))
}
@@ -179,7 +202,10 @@ fn a_managed_channel_message_forwards_to_its_session() {
// Offered rather than decided here: whether this is the session's own
// channel is not knowable from the event alone.
let announce = deliver.announce.expect("a channel prompt offers an origin");
- assert_eq!(announce.channel_id, Uuid::from_u128(1));
+ assert_eq!(
+ announce.parent,
+ messages::domain::models::MessageParent::Channel(Uuid::from_u128(1))
+ );
assert_eq!(announce.thread_id, Uuid::from_u128(2));
assert_eq!(announce.message_id, Uuid::from_u128(2));
}
@@ -198,7 +224,10 @@ fn an_external_channel_message_announces_only() {
assert_eq!(prompt.bot_id, BotId::TEST_A);
assert_eq!(prompt.sender, user());
assert_eq!(prompt.content, "@claude fix the tests");
- assert_eq!(prompt.origin.channel_id, Uuid::from_u128(1));
+ assert_eq!(
+ prompt.origin.parent,
+ messages::domain::models::MessageParent::Channel(Uuid::from_u128(1))
+ );
assert_eq!(prompt.origin.thread_id, Uuid::from_u128(2));
}
@@ -208,7 +237,7 @@ fn a_bot_authored_external_channel_message_is_skipped() {
ChannelEventMetadata {
bot_id: BotId::TEST_A,
session_id: AgentSessionId::TEST_A,
- kind: ChannelKind::MentionThread,
+ kind: ThreadMessageKind::MentionThread,
message: message(ChannelSender::new_from_bot(BotId::TEST_B)),
},
));
@@ -222,11 +251,45 @@ fn channel_message_from(bot: BotId, sender: ChannelSender<'static>) -> AgentTrig
AgentTriggerTopicEvent::Existing(ExistingAgentSessionEvent::Channel(ChannelEventMetadata {
bot_id: bot,
session_id: AgentSessionId::TEST_A,
- kind: ChannelKind::MentionThread,
+ kind: ThreadMessageKind::MentionThread,
message: message(sender),
}))
}
+/// Document triggers arrive in the parent-aware shape and route on their
+/// document parent, opening and announcing like a channel mention would.
+#[test]
+fn a_document_mention_opens_and_follows_up_on_its_document() {
+ let opened =
+ AgentTriggerTopicEvent::New(NewAgentSessionEvent::Mentioned(AgentMentionedEvent {
+ bot_id: BotId::TEST_A,
+ message: document_message(ChannelSender::new_from_user(user())),
+ }));
+ let RoutedTrigger::Command(_, HarnessCommand::Open(open)) =
+ route_agent_trigger(opened, runtime(AgentKind::InMemory))
+ .expect("a document mention for our bot should open")
+ else {
+ panic!("a new-session event should open");
+ };
+ assert_eq!(open.origin.parent, document());
+ assert_eq!(open.origin.thread_id, Uuid::from_u128(2));
+
+ let followed =
+ AgentTriggerTopicEvent::Existing(ExistingAgentSessionEvent::Thread(ThreadEventMetadata {
+ bot_id: MACRO_CODER_BOT_ID,
+ session_id: AgentSessionId::TEST_A,
+ kind: ThreadMessageKind::MentionThread,
+ message: document_message(ChannelSender::new_from_user(user())),
+ }));
+ let RoutedTrigger::Announce(session_id, prompt) =
+ route_agent_trigger(followed, None).expect("an external follow-up announces")
+ else {
+ panic!("an external existing-session event should announce");
+ };
+ assert_eq!(session_id, AgentSessionId::TEST_A);
+ assert_eq!(prompt.origin.parent, document());
+}
+
#[test]
fn any_user_can_follow_up_to_their_cursor_session() {
let user = MacroUserIdStr::try_from_email("[email protected]").expect("a valid user id");
diff --git a/crates/agent_harness/src/outbound/agent_prompt_composer.rs b/crates/agent_harness/src/outbound/agent_prompt_composer.rs
index cfc8916c00..218def7132 100644
--- a/crates/agent_harness/src/outbound/agent_prompt_composer.rs
+++ b/crates/agent_harness/src/outbound/agent_prompt_composer.rs
@@ -4,7 +4,7 @@ use lexical_client::LexicalClient;
use lexical_client::parse_markdown::AgentContextMessage;
use crate::domain::error::{HarnessError, Result};
-use crate::domain::model::PriorChannelMessage;
+use crate::domain::model::PriorMessage;
use crate::domain::ports::AgentPromptComposer;
/// Lexical-service-backed agent prompt composer.
@@ -23,7 +23,8 @@ impl AgentPromptComposer for LexicalAgentPromptComposer {
async fn compose(
&self,
prompt_markdown: &str,
- messages: Option<&[PriorChannelMessage]>,
+ parent: Option<&messages::domain::models::MessageParent>,
+ messages: Option<&[PriorMessage]>,
) -> Result<String> {
let messages = messages.map(|messages| {
messages
@@ -36,7 +37,7 @@ impl AgentPromptComposer for LexicalAgentPromptComposer {
});
self.lexical
- .compose_agent_context(prompt_markdown, messages.as_deref())
+ .compose_agent_context(prompt_markdown, parent, messages.as_deref())
.await
.map_err(|error| HarnessError::PromptComposition(rootcause::report!(error).into()))
}
diff --git a/crates/agent_harness/src/outbound/agent_prompt_composer/test.rs b/crates/agent_harness/src/outbound/agent_prompt_composer/test.rs
index f43162ffb7..3b68c0776d 100644
--- a/crates/agent_harness/src/outbound/agent_prompt_composer/test.rs
+++ b/crates/agent_harness/src/outbound/agent_prompt_composer/test.rs
@@ -16,7 +16,10 @@ async fn composition_preserves_lexical_output_without_tool_instructions() {
));
for messages in [None, Some([].as_slice())] {
- let prompt = composer.compose("Raw prompt", messages).await.unwrap();
+ let prompt = composer
+ .compose("Raw prompt", None, messages)
+ .await
+ .unwrap();
assert_eq!(prompt, "Sanitized prompt and context");
assert!(!prompt.contains("set_pull_request"));
}
diff --git a/crates/agent_harness/src/outbound/channel_announcer.rs b/crates/agent_harness/src/outbound/channel_announcer.rs
index 757023ec8a..3463a17fa3 100644
--- a/crates/agent_harness/src/outbound/channel_announcer.rs
+++ b/crates/agent_harness/src/outbound/channel_announcer.rs
@@ -1,32 +1,22 @@
-//! Announce sessions by posting into the mention's thread as the bot.
-//!
-//! Implements [`SessionAnnouncer`] over the channels domain's own
-//! [`ChannelService`] port, so the post gets the full side-effect fan-out -
-//! persistence, realtime, notifications, broker - exactly as if it came
-//! through the channel API. The composition root decides which
-//! `ChannelService` implementation (and side-effect stack) this wraps.
-//!
-//! The announcement places a structured reply target above the session's
-//! magic chip. The content is composed by the lexical service — the one place
-//! that builds message markdown from real Lexical nodes — so this adapter
-//! never formats markdown itself.
+//! Announce agent responses in their originating message thread through the shared service.
#[cfg(test)]
mod test;
use std::sync::Arc;
-use channel_sender::ChannelSender;
-use channels::domain::models::PostMessageRequest;
-use channels::domain::ports::ChannelService;
+use entity_access::domain::{models::BotAccessScope, ports::EntityAccessService};
use lexical_client::LexicalClient;
use lexical_client::parse_markdown::{AgentAnnouncementChip, AgentAnnouncementReplyTarget};
-use messages::domain::models::PostMessageNotificationPolicy;
+use messages::domain::{
+ api::MessageCommands,
+ models::{MessageAttribution, MessageParent, PostMessage, PostMessageNotificationPolicy},
+ service::MessageWrite,
+};
use crate::domain::error::{HarnessError, Result};
use crate::domain::model::{AnnouncedMessage, SessionAnnouncement};
use crate::domain::ports::SessionAnnouncer;
-use macro_uuid::Uuid;
fn announcement_chip(announcement: &SessionAnnouncement) -> AgentAnnouncementChip {
AgentAnnouncementChip {
@@ -39,7 +29,11 @@ fn announcement_chip(announcement: &SessionAnnouncement) -> AgentAnnouncementChi
fn announcement_reply_target(announcement: &SessionAnnouncement) -> AgentAnnouncementReplyTarget {
AgentAnnouncementReplyTarget {
- channel_id: announcement.origin_channel_id.to_string(),
+ parent: announcement.origin_parent.clone(),
+ channel_id: match &announcement.origin_parent {
+ MessageParent::Channel(channel_id) => Some(channel_id.to_string()),
+ MessageParent::Document(_) => None,
+ },
target_message_id: announcement.origin_message_id.to_string(),
target_thread_id: announcement.origin_thread_id.to_string(),
display_text: announcement.prompted_content.clone(),
@@ -47,69 +41,72 @@ fn announcement_reply_target(announcement: &SessionAnnouncement) -> AgentAnnounc
}
}
-/// Posts session announcements as their session's bot through a
-/// [`ChannelService`].
-pub struct ChannelAnnouncer<Channels> {
- channels: Arc<Channels>,
+/// Posts as the session bot with the invoking user's current parent capability.
+pub struct MessageAnnouncer<Access> {
+ messages: Arc<dyn MessageCommands>,
+ access: Arc<Access>,
lexical: LexicalClient,
}
-impl<Channels> ChannelAnnouncer<Channels> {
- /// Post through `channels`, with content composed by `lexical`. The
- /// sender is per-announcement: whichever bot the session runs for.
- pub fn new(channels: Arc<Channels>, lexical: LexicalClient) -> Self {
- Self { channels, lexical }
+impl<Access> MessageAnnouncer<Access> {
+ /// Compose the common message service, authorization service, and Markdown composer.
+ pub fn new(
+ messages: Arc<dyn MessageCommands>,
+ access: Arc<Access>,
+ lexical: LexicalClient,
+ ) -> Self {
+ Self {
+ messages,
+ access,
+ lexical,
+ }
}
}
-impl<Channels> SessionAnnouncer for ChannelAnnouncer<Channels>
-where
- Channels: ChannelService + Send + Sync + 'static,
-{
+impl<Access: EntityAccessService> SessionAnnouncer for MessageAnnouncer<Access> {
async fn announce(&self, announcement: SessionAnnouncement) -> Result<AnnouncedMessage> {
- let reply_target = announcement_reply_target(&announcement);
- let chip = announcement_chip(&announcement);
+ // Minted on the invoking user's current capability: an author who
+ // may no longer write to the parent gets no chip posted for them.
+ let access = self
+ .access
+ .generate_bot_entity_access_receipt::<MessageWrite>(
+ announcement.bot_id,
+ BotAccessScope::user(announcement.triggered_by.clone()),
+ &announcement.origin_parent.entity_id(),
+ announcement.origin_parent.access_entity_type(),
+ )
+ .await
+ .map_err(|error| HarnessError::Announce(rootcause::report!(error).into()))?;
let content = self
.lexical
- .compose_agent_announcement(&reply_target, &chip)
+ .compose_agent_announcement(
+ &announcement_reply_target(&announcement),
+ &announcement_chip(&announcement),
+ )
.await
.map_err(|error| HarnessError::Announce(rootcause::report!(error).into()))?;
-
let posted = self
- .channels
- .post_message(
- ChannelSender::new_from_bot(announcement.bot_id),
- announcement.origin_channel_id,
- PostMessageRequest {
- content,
- mentions: Vec::new(),
- thread_id: Some(announcement.origin_thread_id),
- attachments: Vec::new(),
- nonce: None,
+ .messages
+ .post(
+ access,
+ PostMessage {
+ attribution: MessageAttribution::ActingUser,
// The chip is a pointer, not news: the thread hears
// about the session when it finishes or asks, through
// the lifecycle notifications, not when it boots.
notification_policy: PostMessageNotificationPolicy::Silent,
- // Attributed to whoever mentioned the bot, so the reply
- // reads as their agent answering.
- triggered_by: Some(announcement.triggered_by.as_ref().to_owned()),
+ content,
+ thread_id: Some(announcement.origin_thread_id),
+ anchor: None,
+ mentions: Vec::new(),
+ attachments: Vec::new(),
+ nonce: None,
},
)
.await
.map_err(|error| HarnessError::Announce(rootcause::report!(error).into()))?;
-
- // Message ids are uuids everywhere in the channels domain; anything
- // else here is a bug in the poster, not a shape to tolerate.
- let message_id = Uuid::parse_str(&posted.id).map_err(|error| {
- HarnessError::Announce(
- rootcause::report!(error)
- .context(format!(
- "announcement posted a non-uuid message id {}",
- posted.id
- ))
- .into(),
- )
- })?;
- Ok(AnnouncedMessage { message_id })
+ Ok(AnnouncedMessage {
+ message_id: posted.id,
+ })
}
}
diff --git a/crates/agent_harness/src/outbound/channel_announcer/test.rs b/crates/agent_harness/src/outbound/channel_announcer/test.rs
index f135e2ee06..d74432e6d2 100644
--- a/crates/agent_harness/src/outbound/channel_announcer/test.rs
+++ b/crates/agent_harness/src/outbound/channel_announcer/test.rs
@@ -8,7 +8,7 @@ fn announcement() -> SessionAnnouncement {
SessionAnnouncement {
bot_id: BotId::TEST_A,
session_id: agent_session::domain::model::AgentSessionId::TEST_A,
- origin_channel_id: Uuid::from_u128(1),
+ origin_parent: MessageParent::Channel(Uuid::from_u128(1)),
origin_thread_id: Uuid::from_u128(2),
origin_message_id: Uuid::from_u128(3),
prompted_message_id: agent_session::domain::model::MessageId::first(
@@ -41,7 +41,8 @@ fn reply_target_carries_the_originating_channel_message() {
assert_eq!(
announcement_reply_target(&announcement()),
AgentAnnouncementReplyTarget {
- channel_id: "00000000-0000-0000-0000-000000000001".to_owned(),
+ parent: MessageParent::Channel(Uuid::from_u128(1)),
+ channel_id: Some("00000000-0000-0000-0000-000000000001".to_owned()),
target_message_id: "00000000-0000-0000-0000-000000000003".to_owned(),
target_thread_id: "00000000-0000-0000-0000-000000000002".to_owned(),
display_text: "@claude fix the failing test".to_owned(),
diff --git a/crates/agent_harness/src/outbound/channel_prompt_context.rs b/crates/agent_harness/src/outbound/channel_prompt_context.rs
index 261068bd08..9c699ed19c 100644
--- a/crates/agent_harness/src/outbound/channel_prompt_context.rs
+++ b/crates/agent_harness/src/outbound/channel_prompt_context.rs
@@ -1,131 +1,113 @@
-//! Loads authorized channel history for managed agent prompts.
+//! Authorized conversation context through the common message application port.
#[cfg(test)]
mod test;
-use std::sync::Arc;
-
-use channels::domain::models::ChannelContextMessage;
-use channels::domain::ports::ChannelService;
-use entity_access::domain::models::{EntityType, MemberParticipantRole};
-use entity_access::domain::ports::EntityAccessService;
+use crate::domain::{
+ error::{HarnessError, Result},
+ model::{AnnounceOrigin, PriorMessage},
+ ports::MessagePromptContext,
+};
+use entity_access::domain::{
+ models::{EntityAccessReceipt, EntityType},
+ ports::EntityAccessService,
+};
use macro_user_id::user_id::MacroUserIdStr;
-use macro_uuid::Uuid;
-
-use crate::domain::error::{HarnessError, Result};
-use crate::domain::model::PriorChannelMessage;
-use crate::domain::ports::ChannelPromptContext;
-
-const CONTEXT_MESSAGE_LIMIT: usize = 10;
-
-trait ChannelContextSource: Send + Sync + 'static {
- fn message_context(
- &self,
- channel_id: Uuid,
- message_id: Uuid,
- before: i64,
- ) -> impl Future<Output = Result<Vec<ChannelContextMessage>>> + Send;
-}
-
-impl<Channels> ChannelContextSource for Channels
-where
- Channels: ChannelService + Send + Sync + 'static,
-{
- async fn message_context(
- &self,
- channel_id: Uuid,
- message_id: Uuid,
- before: i64,
- ) -> Result<Vec<ChannelContextMessage>> {
- self.get_message_context(channel_id, message_id, before, 0)
- .await
- .map_err(|error| HarnessError::PromptContext(rootcause::report!(error).into()))
- }
-}
+use messages::domain::{api::MessageReader, models::MessageParent, service::MessageWrite};
+use std::sync::Arc;
-trait ChannelContextAuthorizer: Send + Sync + 'static {
- fn authorize_member(
+trait ContextAuthorizer: Send + Sync + 'static {
+ fn capability(
&self,
actor: &MacroUserIdStr<'static>,
- channel_id: Uuid,
- ) -> impl Future<Output = Result<()>> + Send;
+ parent: &MessageParent,
+ ) -> impl Future<Output = Result<EntityAccessReceipt<MessageWrite>>> + Send;
}
-impl<Access> ChannelContextAuthorizer for Access
-where
- Access: EntityAccessService,
-{
- async fn authorize_member(
+impl<Access: EntityAccessService> ContextAuthorizer for Access {
+ async fn capability(
&self,
actor: &MacroUserIdStr<'static>,
- channel_id: Uuid,
- ) -> Result<()> {
- self.generate_entity_access_receipt::<MemberParticipantRole>(
+ parent: &MessageParent,
+ ) -> Result<EntityAccessReceipt<MessageWrite>> {
+ self.generate_entity_access_receipt::<MessageWrite>(
actor,
None,
- &channel_id.to_string(),
- EntityType::Channel,
+ &parent.entity_id(),
+ match parent {
+ MessageParent::Channel(_) => EntityType::Channel,
+ MessageParent::Document(_) => EntityType::Document,
+ },
)
.await
- .map(|_| ())
.map_err(|error| HarnessError::PromptContext(rootcause::report!(error).into()))
}
}
-/// Channel context adapter that rechecks the triggering user's membership.
-pub struct ChannelPromptContextAdapter<Channels, Access> {
- channels: Arc<Channels>,
+/// Reads channel and document conversation history with the same access boundary.
+pub struct MessagePromptContextAdapter<Access> {
+ messages: Arc<dyn MessageReader>,
access: Arc<Access>,
}
-impl<Channels, Access> ChannelPromptContextAdapter<Channels, Access> {
- /// Build an adapter from the channels and entity-access services.
- pub fn new(channels: Arc<Channels>, access: Arc<Access>) -> Self {
- Self { channels, access }
+impl<Access> MessagePromptContextAdapter<Access> {
+ /// Compose with the shared message service and current entity permissions.
+ pub fn new(messages: Arc<dyn MessageReader>, access: Arc<Access>) -> Self {
+ Self { messages, access }
}
}
-impl<Channels, Access> ChannelPromptContext for ChannelPromptContextAdapter<Channels, Access>
-where
- Channels: ChannelContextSource,
- Access: ChannelContextAuthorizer,
-{
- async fn authorize_member(
+impl<Access: ContextAuthorizer> MessagePromptContext for MessagePromptContextAdapter<Access> {
+ async fn authorize_origin(
&self,
actor: &MacroUserIdStr<'static>,
- channel_id: Uuid,
+ origin: &AnnounceOrigin,
) -> Result<()> {
- self.access.authorize_member(actor, channel_id).await
+ let access = self
+ .access
+ .capability(actor, &origin.parent)
+ .await?
+ .try_into_requirement()
+ .map_err(|error| HarnessError::PromptContext(rootcause::report!(error).into()))?;
+ let message = self
+ .messages
+ .get(access, origin.message_id)
+ .await
+ .map_err(|error| HarnessError::PromptContext(rootcause::report!(error).into()))?;
+ if message.root_id() != origin.thread_id
+ || message.parent != origin.parent
+ || message.deleted_at.is_some()
+ {
+ return Err(HarnessError::PromptContext(rootcause::report!(
+ "invalid agent message origin"
+ )));
+ }
+ Ok(())
}
async fn preceding_messages(
&self,
- channel_id: Uuid,
- message_id: Uuid,
- ) -> Result<Vec<PriorChannelMessage>> {
- let mut before = CONTEXT_MESSAGE_LIMIT;
- loop {
- let messages = self
- .channels
- .message_context(channel_id, message_id, before as i64)
- .await?;
- let reached_channel_start = messages.len() < before + 1;
- let mut live = messages
- .into_iter()
- .filter(|message| message.id != message_id && message.deleted_at.is_none())
- .map(|message| PriorChannelMessage {
- sender: message.sender_id,
- content: message.content,
- })
- .collect::<Vec<_>>();
-
- if live.len() >= CONTEXT_MESSAGE_LIMIT {
- return Ok(live.split_off(live.len() - CONTEXT_MESSAGE_LIMIT));
- }
- if reached_channel_start {
- return Ok(live);
- }
- before = before.saturating_mul(2).min(i64::MAX as usize);
- }
+ actor: &MacroUserIdStr<'static>,
+ origin: &AnnounceOrigin,
+ ) -> Result<Vec<PriorMessage>> {
+ let access = self
+ .access
+ .capability(actor, &origin.parent)
+ .await?
+ .try_into_requirement()
+ .map_err(|error| HarnessError::PromptContext(rootcause::report!(error).into()))?;
+ self.messages
+ .preceding(access, origin.message_id, 10)
+ .await
+ .map(|messages| {
+ messages
+ .into_iter()
+ .map(|m| PriorMessage {
+ sender: m.sender_id.as_ref().to_owned(),
+ content: m.content,
+ })
+ .collect()
+ })
+ .map_err(|error| HarnessError::PromptContext(rootcause::report!(error).into()))
}
}
diff --git a/crates/agent_harness/src/outbound/channel_prompt_context/test.rs b/crates/agent_harness/src/outbound/channel_prompt_context/test.rs
index adc2eeec11..42abcf6ac8 100644
--- a/crates/agent_harness/src/outbound/channel_prompt_context/test.rs
+++ b/crates/agent_harness/src/outbound/channel_prompt_context/test.rs
@@ -1,200 +1,142 @@
-use std::sync::{Arc, Mutex};
-
-use chrono::{TimeDelta, Utc};
-
use super::*;
+use chrono::Utc;
+use entity_access::domain::models::{AccessLevel, Entity, EntityPermission};
+use macro_uuid::Uuid;
+use messages::domain::{api::MockMessageReader, models::Message};
-#[derive(Default)]
struct Authorizer {
- calls: Mutex<Vec<(MacroUserIdStr<'static>, Uuid)>>,
- fail: bool,
+ allowed: bool,
}
-
-impl ChannelContextAuthorizer for Authorizer {
- async fn authorize_member(
+impl ContextAuthorizer for Authorizer {
+ async fn capability(
&self,
actor: &MacroUserIdStr<'static>,
- channel_id: Uuid,
- ) -> Result<()> {
- self.calls.lock().unwrap().push((actor.clone(), channel_id));
- if self.fail {
+ parent: &MessageParent,
+ ) -> Result<EntityAccessReceipt<MessageWrite>> {
+ if !self.allowed {
return Err(HarnessError::PromptContext(rootcause::report!(
- "not a channel member"
+ "access revoked"
)));
}
- Ok(())
+ Ok(EntityAccessReceipt::try_new_authenticated_user(
+ actor.clone(),
+ Entity {
+ entity_type: match parent {
+ MessageParent::Document(_) => EntityType::Document,
+ MessageParent::Channel(_) => EntityType::Channel,
+ },
+ entity_id: parent.entity_id(),
+ },
+ EntityPermission::AccessLevel {
+ access_level: AccessLevel::Comment,
+ },
+ )
+ .unwrap())
}
}
-#[derive(Default)]
-struct Source {
- messages: Vec<ChannelContextMessage>,
- calls: Mutex<Vec<(Uuid, Uuid, i64)>>,
+fn actor() -> MacroUserIdStr<'static> {
+ MacroUserIdStr::try_from_email("[email protected]").unwrap()
}
-
-impl ChannelContextSource for Source {
- async fn message_context(
- &self,
- channel_id: Uuid,
- message_id: Uuid,
- before: i64,
- ) -> Result<Vec<ChannelContextMessage>> {
- self.calls
- .lock()
- .unwrap()
- .push((channel_id, message_id, before));
- let Some(target) = self
- .messages
- .iter()
- .position(|message| message.id == message_id)
- else {
- return Ok(Vec::new());
- };
- let start = target.saturating_sub(before as usize);
- Ok(self.messages[start..=target].to_vec())
+fn origin() -> AnnounceOrigin {
+ AnnounceOrigin {
+ parent: MessageParent::parse("document", "doc").unwrap(),
+ thread_id: Uuid::from_u128(1),
+ message_id: Uuid::from_u128(2),
}
}
-
-fn message(id: u128, sender: &str, content: &str, deleted: bool) -> ChannelContextMessage {
- let created_at = Utc::now() + TimeDelta::seconds(id as i64);
- ChannelContextMessage {
- id: Uuid::from_u128(id),
- channel_id: Uuid::from_u128(1),
- thread_id: None,
- sender_id: sender.to_owned(),
+fn message() -> Message {
+ Message {
+ id: origin().message_id,
+ parent: origin().parent,
+ thread_id: Some(origin().thread_id),
+ sender_id: channel_sender::ChannelSender::new_from_user(actor()),
triggered_by: None,
bot_profile: None,
- content: content.to_owned(),
- created_at,
- updated_at: created_at,
+ mentions: vec![],
+ imported_author: None,
+ content: "@agent explain this paragraph".into(),
+ created_at: Utc::now(),
+ updated_at: Utc::now(),
edited_at: None,
- deleted_at: deleted.then_some(created_at),
+ deleted_at: None,
+ attachments: vec![],
+ reactions: vec![],
}
}
-fn actor() -> MacroUserIdStr<'static> {
- MacroUserIdStr::try_from_email("[email protected]").unwrap()
-}
-
#[tokio::test]
-async fn adapter_authorizes_and_returns_only_live_preceding_messages_in_order() {
- let channel_id = Uuid::from_u128(1);
- let trigger_id = Uuid::from_u128(4);
- let source = Arc::new(Source {
- messages: vec![
- message(1, "first", "one", false),
- message(2, "deleted", "two", true),
- message(3, "third", "three", false),
- message(4, "actor", "trigger", false),
- ],
- calls: Mutex::default(),
- });
- let authorizer = Arc::new(Authorizer::default());
- let adapter = ChannelPromptContextAdapter::new(source.clone(), authorizer.clone());
-
- adapter
- .authorize_member(&actor(), channel_id)
- .await
- .unwrap();
- let messages = adapter
- .preceding_messages(channel_id, trigger_id)
- .await
- .unwrap();
-
- assert_eq!(
- messages,
- vec![
- PriorChannelMessage {
- sender: "first".to_owned(),
- content: "one".to_owned(),
- },
- PriorChannelMessage {
- sender: "third".to_owned(),
- content: "three".to_owned(),
- },
- ]
- );
- assert_eq!(
- source.calls.lock().unwrap().as_slice(),
- &[(channel_id, trigger_id, 10)]
- );
- assert_eq!(
- authorizer.calls.lock().unwrap().as_slice(),
- &[(actor(), channel_id)]
- );
+async fn document_origin_checks_its_parent_capability_and_root() {
+ let mut source = MockMessageReader::new();
+ source
+ .expect_get()
+ .once()
+ .withf(|access, id| {
+ access.entity().entity_type == EntityType::Document
+ && access.entity().entity_id == "doc"
+ && *id == origin().message_id
+ })
+ .return_once(|_, _| Ok(message()));
+ let adapter =
+ MessagePromptContextAdapter::new(Arc::new(source), Arc::new(Authorizer { allowed: true }));
+ adapter.authorize_origin(&actor(), &origin()).await.unwrap();
}
#[tokio::test]
-async fn deleted_rows_do_not_consume_the_ten_message_limit() {
- let channel_id = Uuid::from_u128(1);
- let trigger_id = Uuid::from_u128(13);
- let source = Arc::new(Source {
- messages: (1..=13)
- .map(|id| {
- message(
- id,
- &format!("sender-{id}"),
- &format!("message-{id}"),
- id == 10,
- )
- })
- .collect(),
- calls: Mutex::default(),
- });
- let adapter = ChannelPromptContextAdapter::new(source.clone(), Arc::new(Authorizer::default()));
-
- adapter
- .authorize_member(&actor(), channel_id)
- .await
- .unwrap();
- let messages = adapter
- .preceding_messages(channel_id, trigger_id)
- .await
- .unwrap();
-
- assert_eq!(messages.len(), 10);
- assert_eq!(messages.first().unwrap().content, "message-2");
- assert_eq!(messages.last().unwrap().content, "message-12");
- assert_eq!(
- source.calls.lock().unwrap().as_slice(),
- &[(channel_id, trigger_id, 10), (channel_id, trigger_id, 20)]
+async fn revoked_access_never_reads_message_content() {
+ let adapter = MessagePromptContextAdapter::new(
+ Arc::new(MockMessageReader::new()),
+ Arc::new(Authorizer { allowed: false }),
+ );
+ assert!(adapter.authorize_origin(&actor(), &origin()).await.is_err());
+ assert!(
+ adapter
+ .preceding_messages(&actor(), &origin())
+ .await
+ .is_err()
);
}
#[tokio::test]
-async fn denied_membership_prevents_the_channel_fetch() {
- let source = Arc::new(Source::default());
- let authorizer = Arc::new(Authorizer {
- fail: true,
- ..Default::default()
- });
- let adapter = ChannelPromptContextAdapter::new(source.clone(), authorizer);
-
- let result = adapter.authorize_member(&actor(), Uuid::from_u128(1)).await;
-
- assert!(matches!(result, Err(HarnessError::PromptContext(_))));
- assert!(source.calls.lock().unwrap().is_empty());
+async fn a_claimed_root_or_parent_cannot_link_an_unrelated_session() {
+ for (wrong_parent, deleted) in [(false, false), (true, false), (false, true)] {
+ let mut source = MockMessageReader::new();
+ source.expect_get().once().return_once(move |_, _| {
+ let mut message = message();
+ if wrong_parent {
+ message.parent = MessageParent::parse("document", "other-document").unwrap();
+ } else if deleted {
+ message.deleted_at = Some(Utc::now());
+ } else {
+ message.thread_id = Some(Uuid::from_u128(99));
+ }
+ Ok(message)
+ });
+ let adapter = MessagePromptContextAdapter::new(
+ Arc::new(source),
+ Arc::new(Authorizer { allowed: true }),
+ );
+ assert!(adapter.authorize_origin(&actor(), &origin()).await.is_err());
+ }
}
#[tokio::test]
-async fn bot_authored_prompts_use_the_observed_channel_without_user_authorization() {
- let channel_id = Uuid::from_u128(1);
- let trigger_id = Uuid::from_u128(2);
- let source = Arc::new(Source {
- messages: vec![
- message(1, "user", "context", false),
- message(2, "bot", "trigger", false),
- ],
- calls: Mutex::default(),
- });
- let authorizer = Arc::new(Authorizer::default());
- let adapter = ChannelPromptContextAdapter::new(source, authorizer.clone());
-
- let messages = adapter
- .preceding_messages(channel_id, trigger_id)
+async fn history_uses_the_shared_authorized_message_reader() {
+ let mut source = MockMessageReader::new();
+ source
+ .expect_preceding()
+ .once()
+ .withf(|access, id, limit| {
+ access.entity().entity_id == "doc" && *id == origin().message_id && *limit == 10
+ })
+ .return_once(|_, _, _| Ok(vec![message()]));
+ let adapter =
+ MessagePromptContextAdapter::new(Arc::new(source), Arc::new(Authorizer { allowed: true }));
+ let history = adapter
+ .preceding_messages(&actor(), &origin())
.await
.unwrap();
-
- assert_eq!(messages.len(), 1);
- assert!(authorizer.calls.lock().unwrap().is_empty());
+ assert_eq!(history.len(), 1);
+ assert_eq!(history[0].sender, actor().as_ref());
+ assert_eq!(history[0].content, message().content);
}
diff --git a/crates/agent_harness/src/outbound/cursor/manager/test.rs b/crates/agent_harness/src/outbound/cursor/manager/test.rs
index e27c98cad4..0e72bc2766 100644
--- a/crates/agent_harness/src/outbound/cursor/manager/test.rs
+++ b/crates/agent_harness/src/outbound/cursor/manager/test.rs
@@ -9,8 +9,8 @@ use agent_runtime_protocol::domain::schema::v0::{
};
use agent_session::domain::error::Result as SessionResult;
use agent_session::domain::model::{
- AgentSession, AgentSessionPreview, ChannelSession, CreateAgentSessionParams,
- DEFAULT_AGENT_SESSION_NAME, SandboxSize, SessionBot, SessionStatus,
+ AgentSession, CreateAgentSessionParams, DEFAULT_AGENT_SESSION_NAME, SandboxSize, SessionBot,
+ SessionStatus, ThreadSession,
};
use bot_id::BotId;
use cursor_api_key::cipher::CursorApiKey;
@@ -72,7 +72,7 @@ impl AgentSessionRepo for StubSessions {
&self,
_viewer: &MacroUserIdStr<'static>,
_ids: &[AgentSessionId],
- ) -> SessionResult<Vec<AgentSessionPreview>> {
+ ) -> SessionResult<Vec<agent_session::domain::model::SessionPreviewCandidate>> {
unimplemented!("the manager never previews sessions")
}
@@ -83,7 +83,7 @@ impl AgentSessionRepo for StubSessions {
owner_id: MacroUserIdStr::try_from("macro|[email protected]".to_owned())
.expect("valid user id"),
thread_id: None,
- thread_channel_id: None,
+ thread_parent: None,
originating_message_id: None,
bot_id: BotId::new_from_uuid(macro_uuid::generate_uuid_v7()),
model: "auto".to_owned(),
@@ -111,11 +111,11 @@ impl AgentSessionRepo for StubSessions {
})
}
- async fn find_for_channel(
+ async fn find_for_thread(
&self,
_thread_id: Option<macro_uuid::Uuid>,
_bot_id: Option<BotId>,
- ) -> SessionResult<ChannelSession> {
+ ) -> SessionResult<ThreadSession> {
unimplemented!("the manager never routes channel events")
}
diff --git a/crates/agent_harness/src/outbound/routing/test.rs b/crates/agent_harness/src/outbound/routing/test.rs
index 52cd0d82d3..128d6777ff 100644
--- a/crates/agent_harness/src/outbound/routing/test.rs
+++ b/crates/agent_harness/src/outbound/routing/test.rs
@@ -4,8 +4,8 @@ use crate::testing::helpers::egress::test_egress;
use agent_runtime_protocol::domain::schema::v0::{ToRuntimeMessage, ToServerMessage};
use agent_session::domain::error::Result as SessionResult;
use agent_session::domain::model::{
- AgentSession, AgentSessionPreview, ChannelSession, CreateAgentSessionParams,
- DEFAULT_AGENT_SESSION_NAME, SandboxSize, SessionBot, SessionStatus,
+ AgentSession, CreateAgentSessionParams, DEFAULT_AGENT_SESSION_NAME, SandboxSize, SessionBot,
+ SessionStatus, ThreadSession,
};
use bot_id::BotId;
use macro_user_id::user_id::MacroUserIdStr;
@@ -117,7 +117,7 @@ impl AgentSessionRepo for FixedBotSessions {
&self,
_viewer: &MacroUserIdStr<'static>,
_ids: &[AgentSessionId],
- ) -> SessionResult<Vec<AgentSessionPreview>> {
+ ) -> SessionResult<Vec<agent_session::domain::model::SessionPreviewCandidate>> {
unimplemented!("the router never previews sessions")
}
@@ -129,7 +129,7 @@ impl AgentSessionRepo for FixedBotSessions {
owner_id: MacroUserIdStr::try_from("macro|[email protected]".to_owned())
.expect("valid user id"),
thread_id: None,
- thread_channel_id: None,
+ thread_parent: None,
originating_message_id: None,
bot_id: self.0,
model: "auto".to_owned(),
@@ -153,11 +153,11 @@ impl AgentSessionRepo for FixedBotSessions {
})
}
- async fn find_for_channel(
+ async fn find_for_thread(
&self,
_thread_id: Option<macro_uuid::Uuid>,
_bot_id: Option<BotId>,
- ) -> SessionResult<ChannelSession> {
+ ) -> SessionResult<ThreadSession> {
unimplemented!("the router never routes channel events")
}
diff --git a/crates/agent_session/Cargo.toml b/crates/agent_session/Cargo.toml
index 8ac255d1a6..07d7952297 100644
--- a/crates/agent_session/Cargo.toml
+++ b/crates/agent_session/Cargo.toml
@@ -49,6 +49,7 @@ agent = { path = "../agent", optional = true }
ai_usage = { path = "../ai_usage", optional = true }
dashmap = { workspace = true }
macro_uuid = { path = "../macro_uuid" }
+messages = { path = "../messages", features = ["ports", "schema"] }
mockall = { workspace = true, optional = true }
agent_fold = { path = "../agent_fold" }
# Only the domain vocabulary; `outbound` would pull rdkafka into every
@@ -91,6 +92,8 @@ path = "src/bin/seed_jsonl.rs"
required-features = ["cli"]
[dev-dependencies]
+messages = { path = "../messages", features = ["outbound"] }
+entity_access = { path = "../entity_access", features = ["outbound"] }
agent-client-protocol = { workspace = true }
bot_id = { path = "../bot_id", features = ["test-utils"] }
harness_id = { path = "../harness_id", features = ["test-utils"] }
diff --git a/crates/agent_session/src/domain/audience.rs b/crates/agent_session/src/domain/audience.rs
new file mode 100644
index 0000000000..70dbf2094b
--- /dev/null
+++ b/crates/agent_session/src/domain/audience.rs
@@ -0,0 +1,137 @@
+//! Select stream recipients using current session access, including document inheritance.
+
+use super::{
+ model::AgentSessionId,
+ ports::{AgentSessionRepo, SessionViewAccess},
+};
+use entity_access::domain::{
+ models::{AccessError, EntityType, ViewAccessLevel},
+ ports::EntityAccessService,
+};
+use macro_user_id::user_id::MacroUserIdStr;
+use messages::domain::models::MessageParent;
+use std::collections::HashSet;
+
+/// Users tracking a session or a parent that renders its response chip.
+pub trait SessionSubscriptions: Send + Sync + 'static {
+ /// Subscription candidates are never authorization evidence.
+ fn candidates(
+ &self,
+ id: AgentSessionId,
+ parent: Option<&MessageParent>,
+ ) -> impl Future<Output = Result<HashSet<String>, rootcause::Report>> + Send;
+}
+
+/// Authorized users who may receive session frames.
+pub trait SessionAudience: Send + Sync + 'static {
+ /// Select current viewers of a session.
+ fn viewers(
+ &self,
+ id: AgentSessionId,
+ ) -> impl Future<Output = Result<Vec<MacroUserIdStr<'static>>, rootcause::Report>> + Send;
+}
+
+/// Includes the owner and currently authorized viewers watching either surface.
+#[derive(Clone)]
+pub struct AuthorizedSessionAudience<Repo, Access, Subscriptions> {
+ repo: Repo,
+ access: Access,
+ subscriptions: Subscriptions,
+}
+impl<Repo, Access, Subscriptions> AuthorizedSessionAudience<Repo, Access, Subscriptions> {
+ /// Compose persisted session facts, access capabilities, and subscriptions.
+ pub fn new(repo: Repo, access: Access, subscriptions: Subscriptions) -> Self {
+ Self {
+ repo,
+ access,
+ subscriptions,
+ }
+ }
+}
+impl<Repo: AgentSessionRepo, Access: EntityAccessService, Subscriptions: SessionSubscriptions>
+ SessionAudience for AuthorizedSessionAudience<Repo, Access, Subscriptions>
+{
+ async fn viewers(
+ &self,
+ id: AgentSessionId,
+ ) -> Result<Vec<MacroUserIdStr<'static>>, rootcause::Report> {
+ let session = self
+ .repo
+ .get(id)
+ .await
+ .map_err(|error| rootcause::report!(error))?;
+ let mut candidates = self
+ .subscriptions
+ .candidates(id, session.thread_parent.as_ref())
+ .await?;
+ candidates.insert(session.owner_id.to_string());
+ let mut viewers = Vec::new();
+ for candidate in candidates {
+ let Ok(user) = MacroUserIdStr::try_from(candidate) else {
+ continue;
+ };
+ match self
+ .access
+ .generate_entity_access_receipt::<ViewAccessLevel>(
+ &user,
+ None,
+ &id.to_string(),
+ EntityType::AgentSession,
+ )
+ .await
+ {
+ Ok(_) => viewers.push(user),
+ Err(
+ AccessError::Unauthorized
+ | AccessError::NotFound(_)
+ | AccessError::BadRequest(_),
+ ) => {}
+ Err(error) => return Err(rootcause::report!(error).into()),
+ }
+ }
+ Ok(viewers)
+ }
+}
+
+/// Answers session view access through the entity access service, so a
+/// preview sees the same inherited document access a read route does.
+#[derive(Clone)]
+pub struct EntityAccessSessionView<Access> {
+ access: Access,
+}
+
+impl<Access> EntityAccessSessionView<Access> {
+ /// Resolve view access with `access`.
+ pub fn new(access: Access) -> Self {
+ Self { access }
+ }
+}
+
+impl<Access: EntityAccessService> SessionViewAccess for EntityAccessSessionView<Access> {
+ fn can_view<'a>(
+ &'a self,
+ viewer: &'a MacroUserIdStr<'static>,
+ session: AgentSessionId,
+ ) -> std::pin::Pin<Box<dyn Future<Output = super::error::Result<bool>> + Send + 'a>> {
+ Box::pin(async move {
+ match self
+ .access
+ .generate_entity_access_receipt::<ViewAccessLevel>(
+ viewer,
+ None,
+ &session.to_string(),
+ EntityType::AgentSession,
+ )
+ .await
+ {
+ Ok(_) => Ok(true),
+ Err(
+ AccessError::Unauthorized
+ | AccessError::NotFound(_)
+ | AccessError::BadRequest(_),
+ ) => Ok(false),
+ Err(error) => Err(super::error::AgentSessionError::Unknown(error.into())),
+ }
+ })
+ }
+}
diff --git a/crates/agent_session/src/domain/events.rs b/crates/agent_session/src/domain/events.rs
index f325f4ad5d..fc13a749f8 100644
--- a/crates/agent_session/src/domain/events.rs
+++ b/crates/agent_session/src/domain/events.rs
@@ -19,22 +19,71 @@ use macro_event_broker::{Event, MacroEvent, TopicEvent};
use macro_event_topics::MacroAgentSessionLifecycleTopic;
use macro_user_id::user_id::MacroUserIdStr;
use macro_uuid::Uuid;
+use messages::domain::models::MessageParent;
use serde::{Deserialize, Serialize};
use super::model::{AgentSessionId, TurnId};
-/// The channel thread a session was opened from, when it was.
-#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+/// The thread a session was opened from, when it was.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
pub struct ThreadOrigin {
- /// Channel the thread lives in.
- pub channel_id: Uuid,
+ /// Entity owning the thread: the channel or document it was posted in.
+ pub parent: MessageParent,
+ /// Channel the thread lives in, for channel parents only. Kept beside
+ /// `parent` for consumers written when every origin was a channel.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub channel_id: Option<Uuid>,
/// Root message of the thread.
pub thread_id: Uuid,
/// The message whose mention opened the session.
pub originating_message_id: Uuid,
}
+impl ThreadOrigin {
+ /// An origin on `parent`, with `channel_id` derived from it.
+ #[must_use]
+ pub fn new(parent: MessageParent, thread_id: Uuid, originating_message_id: Uuid) -> Self {
+ let channel_id = match &parent {
+ MessageParent::Channel(channel_id) => Some(*channel_id),
+ MessageParent::Document(_) => None,
+ };
+ Self {
+ parent,
+ channel_id,
+ thread_id,
+ originating_message_id,
+ }
+ }
+}
+
+/// Wire shape of [`ThreadOrigin`]: events published before parents existed
+/// carry only `channel_id`, and still decode as channel origins.
+#[derive(Deserialize)]
+struct ThreadOriginWire {
+ #[serde(default)]
+ parent: Option<MessageParent>,
+ #[serde(default)]
+ channel_id: Option<Uuid>,
+ thread_id: Uuid,
+ originating_message_id: Uuid,
+}
+
+impl<'de> Deserialize<'de> for ThreadOrigin {
+ fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
+ let wire = ThreadOriginWire::deserialize(deserializer)?;
+ let parent = wire
+ .parent
+ .or(wire.channel_id.map(MessageParent::Channel))
+ .ok_or_else(|| serde::de::Error::missing_field("parent"))?;
+ Ok(Self::new(
+ parent,
+ wire.thread_id,
+ wire.originating_message_id,
+ ))
+ }
+}
+
/// Who and what a session is; carried by every lifecycle event so a
/// consumer never has to look the session up.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
diff --git a/crates/agent_session/src/domain/events/test.rs b/crates/agent_session/src/domain/events/test.rs
index 5683b4bbaa..ebed9b3170 100644
--- a/crates/agent_session/src/domain/events/test.rs
+++ b/crates/agent_session/src/domain/events/test.rs
@@ -17,11 +17,11 @@ fn identity() -> SessionIdentity {
bot_id: BotId::TEST_A,
bot_name: "Macro Coder".to_owned(),
owner_id: owner(),
- origin: Some(ThreadOrigin {
- channel_id: Uuid::from_u128(1),
- thread_id: Uuid::from_u128(2),
- originating_message_id: Uuid::from_u128(3),
- }),
+ origin: Some(ThreadOrigin::new(
+ messages::domain::models::MessageParent::Channel(Uuid::from_u128(1)),
+ Uuid::from_u128(2),
+ Uuid::from_u128(3),
+ )),
audience: vec![owner()],
}
}
diff --git a/crates/agent_session/src/domain/lifecycle.rs b/crates/agent_session/src/domain/lifecycle.rs
index c6a5b93998..c672b4df7e 100644
--- a/crates/agent_session/src/domain/lifecycle.rs
+++ b/crates/agent_session/src/domain/lifecycle.rs
@@ -26,28 +26,27 @@ pub fn session_identity(
if !audience.contains(&session.owner_id) {
audience.push(session.owner_id.clone());
}
- let origin = match (
- session.thread_channel_id,
- session.thread_id,
- session.originating_message_id,
- ) {
- (Some(channel_id), Some(thread_id), Some(originating_message_id)) => Some(ThreadOrigin {
- channel_id,
- thread_id,
- originating_message_id,
- }),
- (None, None, None) => None,
- (channel_id, thread_id, originating_message_id) => {
- tracing::warn!(
- session_id = %session.id,
- ?channel_id,
- ?thread_id,
- ?originating_message_id,
- "agent session has a partial thread origin; reporting none"
- );
- None
- }
- };
+ let origin =
+ match (
+ session.thread_parent.as_ref(),
+ session.thread_id,
+ session.originating_message_id,
+ ) {
+ (Some(parent), Some(thread_id), Some(originating_message_id)) => Some(
+ ThreadOrigin::new(parent.clone(), thread_id, originating_message_id),
+ ),
+ (None, None, None) => None,
+ (parent, thread_id, originating_message_id) => {
+ tracing::warn!(
+ session_id = %session.id,
+ ?parent,
+ ?thread_id,
+ ?originating_message_id,
+ "agent session has a partial thread origin; reporting none"
+ );
+ None
+ }
+ };
SessionIdentity {
session_id: session.id,
session_name: session.name.clone(),
diff --git a/crates/agent_session/src/domain/mod.rs b/crates/agent_session/src/domain/mod.rs
index 48c59f8429..9bed6ea05f 100644
--- a/crates/agent_session/src/domain/mod.rs
+++ b/crates/agent_session/src/domain/mod.rs
@@ -1,3 +1,5 @@
+/// Current authorization for agent session streams.
+pub mod audience;
pub mod connection;
pub mod error;
pub mod events;
diff --git a/crates/agent_session/src/domain/model.rs b/crates/agent_session/src/domain/model.rs
index a8ef9ba959..ea800afa69 100644
--- a/crates/agent_session/src/domain/model.rs
+++ b/crates/agent_session/src/domain/model.rs
@@ -212,10 +212,9 @@ pub struct AgentSession {
pub owner_id: MacroUserIdStr<'static>,
/// The root message where the bot was originally invoked, if any.
pub thread_id: Option<Uuid>,
- /// The channel `thread_id` lives in, when the session was spawned from a
- /// thread. Derived from the thread root's message row rather than
- /// stored — the message's channel is authoritative.
- pub thread_channel_id: Option<Uuid>,
+ /// Entity owning the originating thread, derived from its root message.
+ /// The persisted message parent is authoritative for routing and access.
+ pub thread_parent: Option<messages::domain::models::MessageParent>,
/// The exact message that originally invoked the bot, if any.
pub originating_message_id: Option<Uuid>,
/// the bot id of the bot running the agent
@@ -428,8 +427,8 @@ pub struct SessionLog {
clippy::large_enum_variant,
reason = "one data variant against None; boxing would only move the size"
)]
-pub enum ChannelSession {
- /// No session matched the channel context.
+pub enum ThreadSession {
+ /// No session matched the thread context.
None,
/// The bot's session was created from the incoming thread.
CreatedFromThread(AgentSession),
@@ -472,6 +471,21 @@ impl AgentSessionPreview {
}
}
+/// One session found by [`AgentSessionRepo::preview`](super::ports::AgentSessionRepo::preview),
+/// before access policy: what a chip would show, whether an access row grants
+/// the viewer at least view access, and where the session came from, so the
+/// service can resolve inherited access that no row materializes.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct SessionPreviewCandidate {
+ /// What a chip renders once access is settled.
+ pub data: AgentSessionPreviewData,
+ /// Whether a materialized grant - the viewer, a channel they are in, or a
+ /// team they belong to - gives them at least view access.
+ pub has_grant: bool,
+ /// Parent of the thread the session was opened from, when it was.
+ pub thread_parent: Option<messages::domain::models::MessageParent>,
+}
+
/// The subset of an [`AgentSession`] a chip or mention renders.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AgentSessionPreviewData {
diff --git a/crates/agent_session/src/domain/ports.rs b/crates/agent_session/src/domain/ports.rs
index 455dec0555..0a2427e3b4 100644
--- a/crates/agent_session/src/domain/ports.rs
+++ b/crates/agent_session/src/domain/ports.rs
@@ -179,8 +179,8 @@ pub async fn managed_persona_for_user<Bots: BotDirectory>(
/// where the bot can already post.
#[derive(Debug, Clone)]
pub struct SessionThread {
- /// Channel the mentioning message was posted in.
- pub channel_id: Uuid,
+ /// Channel or document the mentioning message was posted in.
+ pub parent: messages::domain::models::MessageParent,
/// Thread the session belongs to.
pub thread_id: Uuid,
/// The mentioning message itself.
@@ -282,19 +282,18 @@ pub trait AgentSessionRepo: Send + Sync + 'static {
/// Get an agent session by id.
fn get(&self, id: AgentSessionId) -> impl Future<Output = Result<AgentSession>> + Send;
- /// Resolve each of `ids` to what `viewer` may see of it, for chips.
- ///
- /// One [`AgentSessionPreview`] per id in `ids`, in no particular order.
- /// Access is the session's own `entity_access` grants resolved against
- /// the viewer - as themselves, through the channels they are still in,
- /// and through their teams - the same predicate the read routes' access
- /// extractor applies, so a preview says `Access` exactly when
- /// `GET /agent-sessions/{id}` would answer.
+ /// The sessions among `ids` that exist, each with what a chip shows and
+ /// whether a materialized grant lets `viewer` see it: their own grant,
+ /// one through a channel they are still in, or one through their teams -
+ /// the same three the read routes' access extractor resolves. Inherited
+ /// access that no row materializes (a document collaborator's) is the
+ /// service's to resolve from the returned thread parent. Ids with no
+ /// session are simply absent.
fn preview(
&self,
viewer: &MacroUserIdStr<'static>,
ids: &[AgentSessionId],
- ) -> impl Future<Output = Result<Vec<AgentSessionPreview>>> + Send;
+ ) -> impl Future<Output = Result<Vec<SessionPreviewCandidate>>> + Send;
/// Replace the session credential when attaching an external runtime.
fn set_egress_token_hash(
@@ -327,15 +326,15 @@ pub trait AgentSessionRepo: Send + Sync + 'static {
/// otherwise `None`. There is nothing else to match: a session does not
/// own a channel, and messages sent directly to a session arrive through
/// their own topic rather than as channel events.
- fn find_for_channel(
+ fn find_for_thread(
&self,
thread_id: Option<Uuid>,
bot_id: Option<BotId>,
- ) -> impl Future<Output = Result<ChannelSession>> + Send;
+ ) -> impl Future<Output = Result<ThreadSession>> + Send;
/// Every session rooted at this thread, newest first, regardless of bot.
///
- /// [`find_for_channel`](Self::find_for_channel) answers for one known bot;
+ /// [`find_for_thread`](Self::find_for_thread) answers for one known bot;
/// this answers when no bot was named - a message in the thread may still
/// be meant for whichever agent lives there.
fn find_all_for_thread(
@@ -981,3 +980,32 @@ pub trait AgentSessionNotificationRecipient: Send + Sync + 'static {
#[cfg(test)]
mod test;
+
+/// Current view access to a session, resolved the way a read route resolves
+/// it - including access inherited from the document a session was opened
+/// from, which no access row materializes.
+///
+/// Object-safe so the service holds it erased, like its turn observer.
+pub trait SessionViewAccess: Send + Sync + 'static {
+ /// Whether `viewer` may currently view `session`.
+ fn can_view<'a>(
+ &'a self,
+ viewer: &'a MacroUserIdStr<'static>,
+ session: AgentSessionId,
+ ) -> Pin<Box<dyn Future<Output = Result<bool>> + Send + 'a>>;
+}
+
+/// Only materialized grants count: a process with no entity-access service,
+/// or a test, never discovers inherited access.
+#[derive(Debug, Clone, Copy, Default)]
+pub struct NoInheritedSessionAccess;
+
+impl SessionViewAccess for NoInheritedSessionAccess {
+ fn can_view<'a>(
+ &'a self,
+ _viewer: &'a MacroUserIdStr<'static>,
+ _session: AgentSessionId,
+ ) -> Pin<Box<dyn Future<Output = Result<bool>> + Send + 'a>> {
+ Box::pin(async { Ok(false) })
+ }
+}
diff --git a/crates/agent_session/src/domain/service.rs b/crates/agent_session/src/domain/service.rs
index 7965f6cdef..71a495bd25 100644
--- a/crates/agent_session/src/domain/service.rs
+++ b/crates/agent_session/src/domain/service.rs
@@ -51,15 +51,15 @@ use super::lifecycle::session_identity;
use super::model::SessionBot;
use super::model::{
AgentSession, AgentSessionId, AgentSessionLog, AgentSessionPreview, AgentSessionRenamed,
- AuthorKind, ChannelSession, ClaimOutcome, CreateAgentSessionParams, LogAppended,
- MAX_AGENT_SESSION_NAME_CHARS, MAX_PREVIEW_SESSION_IDS, Message, MessageId, ReplicaId,
- SandboxSize, SessionClaim, SessionLog, SessionManagement, StoredAgentSessionLog,
+ AuthorKind, ClaimOutcome, CreateAgentSessionParams, LogAppended, MAX_AGENT_SESSION_NAME_CHARS,
+ MAX_PREVIEW_SESSION_IDS, Message, MessageId, ReplicaId, SandboxSize, SessionClaim, SessionLog,
+ SessionManagement, SessionPreviewCandidate, StoredAgentSessionLog, ThreadSession,
};
use super::ports::{
AgentConnector, AgentSessionLifecyclePublisher, AgentSessionLogRepo, AgentSessionLogWriter,
AgentSessionNameGenerator, AgentSessionQueueChanged, AgentSessionRealtime, AgentSessionRepo,
- Appended, NoOpAgentSessionNameGenerator, NoOpToolCatalog, SessionOwnership, SessionToolCatalog,
- SessionTurnObserver,
+ Appended, NoInheritedSessionAccess, NoOpAgentSessionNameGenerator, NoOpToolCatalog,
+ SessionOwnership, SessionToolCatalog, SessionTurnObserver, SessionViewAccess,
};
use super::session::actors::{SessionActor, SessionCommand, Stepped};
use super::session::{CloseReason, Input};
@@ -212,11 +212,11 @@ pub trait AgentSessionService: Send + Sync + 'static {
) -> impl Future<Output = Result<()>> + Send;
/// The session an incoming channel context routes to, if any.
- fn find_for_channel(
+ fn find_for_thread(
&self,
thread_id: Option<Uuid>,
bot_id: Option<BotId>,
- ) -> impl Future<Output = Result<ChannelSession>> + Send;
+ ) -> impl Future<Output = Result<ThreadSession>> + Send;
/// The bot a session runs for, as viewers see it.
fn session_bot(&self, id: BotId) -> impl Future<Output = Result<SessionBot>> + Send;
@@ -296,6 +296,10 @@ pub struct AgentSessionServiceImpl<R, Folds, Rt, Namer = NoOpAgentSessionNameGen
/// Lists a session's MCP tools for its telemetry. Erased like the
/// observer, for the same reason.
tool_catalog: Arc<dyn SessionToolCatalog>,
+ /// Answers whether a viewer may see a session when no access row says
+ /// so: a document collaborator's inherited access. Erased like the
+ /// observer, for the same reason.
+ view_access: Arc<dyn SessionViewAccess>,
/// Where lifecycle facts go - renames, from here; everything else from
/// the harness. Erased for the same reason as the observer.
lifecycle_publisher: Arc<dyn AgentSessionLifecyclePublisher>,
@@ -344,6 +348,7 @@ impl<R, Folds, Rt, Namer> AgentSessionServiceImpl<R, Folds, Rt, Namer> {
turn_observer,
lifecycle_publisher,
tool_catalog: Arc::new(NoOpToolCatalog),
+ view_access: Arc::new(NoInheritedSessionAccess),
active: Arc::new(DashMap::new()),
replica,
tasks: TaskTracker::new(),
@@ -360,6 +365,16 @@ impl<R, Folds, Rt, Namer> AgentSessionServiceImpl<R, Folds, Rt, Namer> {
self
}
+ /// Resolve inherited session access when previewing, so a document
+ /// collaborator's chips render like their reads succeed. Only a process
+ /// with an entity-access service can answer, hence a builder rather than
+ /// a constructor argument.
+ #[must_use]
+ pub fn with_view_access(mut self, view_access: Arc<dyn SessionViewAccess>) -> Self {
+ self.view_access = view_access;
+ self
+ }
+
/// This service's identity in the session-management lease, for the
/// composition root to heartbeat while the process lives.
#[must_use]
@@ -675,7 +690,33 @@ where
if ids.is_empty() {
return Ok(Vec::new());
}
- let mut previews = self.repo.preview(viewer, &ids).await?;
+ let mut candidates: std::collections::HashMap<AgentSessionId, SessionPreviewCandidate> =
+ self.repo
+ .preview(viewer, &ids)
+ .await?
+ .into_iter()
+ .map(|candidate| (candidate.data.id, candidate))
+ .collect();
+ let mut previews = Vec::with_capacity(ids.len());
+ for id in ids {
+ let Some(candidate) = candidates.remove(&id) else {
+ previews.push(AgentSessionPreview::DoesNotExist(id));
+ continue;
+ };
+ // A grant row settles it. Without one, a session opened from a
+ // document discussion may still be visible through the document
+ // itself, which only the access service knows.
+ let visible = candidate.has_grant
+ || (matches!(
+ candidate.thread_parent,
+ Some(messages::domain::models::MessageParent::Document(_))
+ ) && self.view_access.can_view(viewer, id).await?);
+ previews.push(if visible {
+ AgentSessionPreview::Access(Box::new(candidate.data))
+ } else {
+ AgentSessionPreview::NoAccess(id)
+ });
+ }
let mut profiles = std::collections::HashMap::new();
for preview in &mut previews {
let AgentSessionPreview::Access(data) = preview else {
@@ -692,12 +733,12 @@ where
Ok(previews)
}
- async fn find_for_channel(
+ async fn find_for_thread(
&self,
thread_id: Option<Uuid>,
bot_id: Option<BotId>,
- ) -> Result<ChannelSession> {
- self.repo.find_for_channel(thread_id, bot_id).await
+ ) -> Result<ThreadSession> {
+ self.repo.find_for_thread(thread_id, bot_id).await
}
async fn delete_session(&self, id: AgentSessionId) -> Result<()> {
@@ -1198,7 +1239,7 @@ where
&self,
viewer: &MacroUserIdStr<'static>,
ids: &[AgentSessionId],
- ) -> Result<Vec<AgentSessionPreview>> {
+ ) -> Result<Vec<SessionPreviewCandidate>> {
self.repo.preview(viewer, ids).await
}
@@ -1228,12 +1269,12 @@ where
self.repo.recent_for_owner(owner, limit).await
}
- async fn find_for_channel(
+ async fn find_for_thread(
&self,
thread_id: Option<Uuid>,
bot_id: Option<bots::domain::models::BotId>,
- ) -> Result<super::model::ChannelSession> {
- self.repo.find_for_channel(thread_id, bot_id).await
+ ) -> Result<super::model::ThreadSession> {
+ self.repo.find_for_thread(thread_id, bot_id).await
}
async fn find_all_for_thread(&self, thread_id: Uuid) -> Result<Vec<AgentSession>> {
diff --git a/crates/agent_session/src/domain/service/test.rs b/crates/agent_session/src/domain/service/test.rs
index 2bcdf3ca9d..df688ab8e6 100644
--- a/crates/agent_session/src/domain/service/test.rs
+++ b/crates/agent_session/src/domain/service/test.rs
@@ -80,6 +80,76 @@ async fn previews_hydrate_bot_identity_only_for_accessible_sessions() {
);
}
+/// A viewer answers for one document-born session.
+struct GrantingViewAccess(AgentSessionId);
+
+impl crate::domain::ports::SessionViewAccess for GrantingViewAccess {
+ fn can_view<'a>(
+ &'a self,
+ _viewer: &'a macro_user_id::user_id::MacroUserIdStr<'static>,
+ session: AgentSessionId,
+ ) -> std::pin::Pin<Box<dyn Future<Output = Result<bool>> + Send + 'a>> {
+ Box::pin(async move { Ok(session == self.0) })
+ }
+}
+
+#[tokio::test]
+async fn previews_resolve_inherited_document_access_through_the_view_port() {
+ let fx = fixture();
+ let mut document_session = test_agent_session(AgentSessionId::new());
+ document_session.thread_parent =
+ Some(messages::domain::models::MessageParent::parse("document", "doc-1").unwrap());
+ let mut channel_session = test_agent_session(AgentSessionId::new());
+ channel_session.thread_parent = Some(messages::domain::models::MessageParent::Channel(
+ Uuid::from_u128(9),
+ ));
+ fx.repo.insert_session(document_session.clone());
+ fx.repo.insert_session(channel_session.clone());
+ let collaborator =
+ macro_user_id::user_id::MacroUserIdStr::try_from_email("[email protected]").unwrap();
+ let ids = vec![document_session.id, channel_session.id, fx.session];
+
+ // Without a view port, only materialized grants count.
+ let mut previews = fx
+ .service
+ .preview_sessions(&collaborator, ids.clone())
+ .await
+ .unwrap();
+ previews.sort_by_key(|preview| preview.id().as_uuid());
+ assert!(
+ previews
+ .iter()
+ .all(|preview| matches!(preview, AgentSessionPreview::NoAccess(_)))
+ );
+
+ // With one, the document-born session is asked about and the rest are not.
+ let service = fx
+ .service
+ .clone()
+ .with_view_access(Arc::new(GrantingViewAccess(document_session.id)));
+ let previews = service.preview_sessions(&collaborator, ids).await.unwrap();
+ let access: Vec<_> = previews
+ .iter()
+ .filter_map(|preview| match preview {
+ AgentSessionPreview::Access(data) => Some(data.id),
+ _ => None,
+ })
+ .collect();
+ assert_eq!(access, vec![document_session.id]);
+ let channel_service = fx
+ .service
+ .clone()
+ .with_view_access(Arc::new(GrantingViewAccess(channel_session.id)));
+ assert_eq!(
+ channel_service
+ .preview_sessions(&collaborator, vec![channel_session.id])
+ .await
+ .unwrap(),
+ vec![AgentSessionPreview::NoAccess(channel_session.id)],
+ "channel grants are rows; the view port is never consulted for them"
+ );
+}
+
#[tokio::test]
async fn only_the_first_prompt_is_selected_for_automatic_naming() {
let repo = InMemoryAgentSessionRepo::new();
@@ -420,7 +490,7 @@ impl AgentSessionRepo for BlockingPromptLogs {
&self,
viewer: &MacroUserIdStr<'static>,
ids: &[AgentSessionId],
- ) -> Result<Vec<AgentSessionPreview>> {
+ ) -> Result<Vec<crate::domain::model::SessionPreviewCandidate>> {
self.repo.preview(viewer, ids).await
}
@@ -443,12 +513,12 @@ impl AgentSessionRepo for BlockingPromptLogs {
self.repo.find_by_egress_token_hash(egress_token_hash).await
}
- async fn find_for_channel(
+ async fn find_for_thread(
&self,
thread_id: Option<Uuid>,
bot_id: Option<BotId>,
- ) -> Result<ChannelSession> {
- self.repo.find_for_channel(thread_id, bot_id).await
+ ) -> Result<ThreadSession> {
+ self.repo.find_for_thread(thread_id, bot_id).await
}
async fn find_all_for_thread(&self, thread_id: Uuid) -> Result<Vec<AgentSession>> {
diff --git a/crates/agent_session/src/inbound/axum_router.rs b/crates/agent_session/src/inbound/axum_router.rs
index 1e64ad2ea2..974869c4b0 100644
--- a/crates/agent_session/src/inbound/axum_router.rs
+++ b/crates/agent_session/src/inbound/axum_router.rs
@@ -459,8 +459,11 @@ pub struct AgentSessionResponse {
pub can_edit: bool,
/// The root message of the thread the session was created from, if any.
pub thread_id: Option<Uuid>,
+ /// The channel or document `thread_id` lives in, when the session was
+ /// spawned from a thread.
+ pub thread_parent: Option<messages::domain::models::MessageParent>,
/// The channel `thread_id` lives in, when the session was spawned from a
- /// thread.
+ /// channel thread. Derived from `thread_parent`.
pub thread_channel_id: Option<Uuid>,
/// The exact message that invoked the bot, if any.
pub originating_message_id: Option<Uuid>,
@@ -525,13 +528,18 @@ impl From<ExternalSession> for ExternalSessionResponse {
impl AgentSessionResponse {
/// Describe `session` to a caller whose edit access is `can_edit`.
pub fn new(session: AgentSession, can_edit: bool) -> Self {
+ let thread_channel_id = match &session.thread_parent {
+ Some(messages::domain::models::MessageParent::Channel(channel_id)) => Some(*channel_id),
+ Some(messages::domain::models::MessageParent::Document(_)) | None => None,
+ };
Self {
id: session.id.as_uuid(),
name: session.name,
owner_id: session.owner_id.to_string(),
can_edit,
thread_id: session.thread_id,
- thread_channel_id: session.thread_channel_id,
+ thread_parent: session.thread_parent,
+ thread_channel_id,
originating_message_id: session.originating_message_id,
bot_id: session.bot_id.as_uuid(),
model: session.model,
@@ -1416,8 +1424,13 @@ pub struct CreateAgentSessionRequest {
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct CreateSessionThread {
- /// Channel the mentioning message was posted in.
- pub channel_id: Uuid,
+ /// Entity the mentioning message was posted in.
+ #[serde(default)]
+ pub parent: Option<messages::domain::models::MessageParent>,
+ /// Channel the mentioning message was posted in. Runtimes built before
+ /// message parents send this instead of `parent`.
+ #[serde(default)]
+ pub channel_id: Option<Uuid>,
/// Thread the session belongs to; defaults to the message itself, which
/// is how a top-level mention roots its own thread.
pub thread_id: Option<Uuid>,
@@ -1480,6 +1493,8 @@ pub enum CreateSessionApiError {
InvalidWorkspace(&'static str),
/// The request mixed the managed and external shapes.
MixedSessionShape,
+ /// The thread named neither a parent nor a channel.
+ ThreadParentRequired,
/// The thread already routes to a session; carries it for recovery.
ThreadSessionExists {
/// The existing session, when it could be resolved.
@@ -1534,6 +1549,10 @@ impl IntoResponse for CreateSessionApiError {
workspace, owner or thread asks for an external one"
.to_owned(),
),
+ Self::ThreadParentRequired => (
+ StatusCode::UNPROCESSABLE_ENTITY,
+ "thread.parent is required".to_owned(),
+ ),
Self::ThreadSessionExists { session_id } => {
let body = ThreadSessionExistsResponse {
message: THREAD_SESSION_EXISTS_MESSAGE.to_owned(),
@@ -1767,12 +1786,23 @@ pub async fn create_agent_session_handler<
validate_workspace(&workspace)?;
let owner = resolve_owner(&caller.authorization, request.owner)?;
- let thread = request.thread.map(|thread| SessionThread {
- channel_id: thread.channel_id,
- thread_id: thread.thread_id.unwrap_or(thread.message_id),
- message_id: thread.message_id,
- content: thread.content,
- });
+ let thread = request
+ .thread
+ .map(|thread| {
+ let parent = thread
+ .parent
+ .or(thread
+ .channel_id
+ .map(messages::domain::models::MessageParent::Channel))
+ .ok_or(CreateSessionApiError::ThreadParentRequired)?;
+ Ok::<_, CreateSessionApiError>(SessionThread {
+ parent,
+ thread_id: thread.thread_id.unwrap_or(thread.message_id),
+ message_id: thread.message_id,
+ content: thread.content,
+ })
+ })
+ .transpose()?;
let session = match state
.opener
.open_external_session(OpenExternalAgentSession {
diff --git a/crates/agent_session/src/inbound/axum_router/test.rs b/crates/agent_session/src/inbound/axum_router/test.rs
index 73b3d87a04..5a0491cf14 100644
--- a/crates/agent_session/src/inbound/axum_router/test.rs
+++ b/crates/agent_session/src/inbound/axum_router/test.rs
@@ -113,7 +113,7 @@ impl SessionOpener for RecordingOpener {
name: crate::domain::model::DEFAULT_AGENT_SESSION_NAME.to_owned(),
owner_id: request.owner.clone(),
thread_id: request.thread.as_ref().map(|thread| thread.thread_id),
- thread_channel_id: request.thread.as_ref().map(|thread| thread.channel_id),
+ thread_parent: request.thread.as_ref().map(|thread| thread.parent.clone()),
originating_message_id: request.thread.as_ref().map(|thread| thread.message_id),
bot_id: request.bot_id,
model: "claude".to_owned(),
@@ -148,7 +148,7 @@ impl SessionOpener for RecordingOpener {
name: crate::domain::model::DEFAULT_AGENT_SESSION_NAME.to_owned(),
owner_id: request.owner.clone(),
thread_id: None,
- thread_channel_id: None,
+ thread_parent: None,
originating_message_id: None,
bot_id,
model: "claude".to_owned(),
@@ -328,7 +328,7 @@ fn body(bot_id: Option<Uuid>, workspace: &str, owner: Option<&str>) -> String {
"workspace": workspace,
"owner": owner,
"thread": {
- "channelId": "00000000-0000-0000-0000-000000000001",
+ "parent": {"type": "channel", "id": "00000000-0000-0000-0000-000000000001"},
"messageId": "00000000-0000-0000-0000-000000000002",
"content": "fix the flaky test",
},
diff --git a/crates/agent_session/src/outbound/connection_gateway_realtime.rs b/crates/agent_session/src/outbound/connection_gateway_realtime.rs
index 74df9b740a..2c1bc04b60 100644
--- a/crates/agent_session/src/outbound/connection_gateway_realtime.rs
+++ b/crates/agent_session/src/outbound/connection_gateway_realtime.rs
@@ -40,7 +40,6 @@ use crate::domain::model::{
};
use crate::domain::ports::{AgentSessionQueueChanged, AgentSessionRealtime};
use connection_gateway_client::ConnectionGatewayClient;
-use macro_user_id::user_id::MacroUserIdStr;
use macro_uuid::Uuid;
use model_entity::EntityType as GatewayEntityType;
use serde::Serialize;
@@ -179,22 +178,40 @@ impl<Participants> ConnectionGatewayAgentSessionRealtime<Participants> {
}
}
-/// Who should receive a session's frames.
-///
-/// The gateway addresses users, so publishing needs a list of them. Named as
-/// its own capability rather than reaching for a repository, because this is
-/// the only thing the adapter wants from one.
-///
-/// Asked by session rather than by channel: a session created since they
-/// stopped owning a channel has no membership list to consult. The answer is
-/// the same either way for older sessions, whose channel only ever had one
-/// participant - the owner, written by `create`.
-pub trait SessionAudience: Send + Sync + 'static {
- /// The users who should see this session's frames.
- fn viewers(
+pub use crate::domain::audience::SessionAudience;
+
+/// Reads subscriptions without treating a tracked entity as a permission grant.
+#[derive(Clone)]
+pub struct ConnectionGatewaySessionSubscriptions(pub Arc<ConnectionGatewayClient>);
+
+impl crate::domain::audience::SessionSubscriptions for ConnectionGatewaySessionSubscriptions {
+ async fn candidates(
&self,
- agent_session_id: AgentSessionId,
- ) -> impl Future<Output = Result<Vec<MacroUserIdStr<'static>>, rootcause::Report>> + Send;
+ id: AgentSessionId,
+ parent: Option<&messages::domain::models::MessageParent>,
+ ) -> Result<std::collections::HashSet<String>, rootcause::Report> {
+ let mut users: std::collections::HashSet<_> = self
+ .0
+ .track_entity_users(GatewayEntityType::AgentSession.with_entity_string(id.to_string()))
+ .await
+ .map_err(|error| rootcause::report!(error))?
+ .into_iter()
+ .collect();
+ if let Some(parent) = parent {
+ let kind = if parent.is_discussion() {
+ GatewayEntityType::Document
+ } else {
+ GatewayEntityType::Channel
+ };
+ users.extend(
+ self.0
+ .track_entity_users(kind.with_entity_string(parent.entity_id()))
+ .await
+ .map_err(|error| rootcause::report!(error))?,
+ );
+ }
+ Ok(users)
+ }
}
impl<Participants> AgentSessionRealtime for ConnectionGatewayAgentSessionRealtime<Participants>
diff --git a/crates/agent_session/src/outbound/postgres.rs b/crates/agent_session/src/outbound/postgres.rs
index 89791d4988..19debcdc97 100644
--- a/crates/agent_session/src/outbound/postgres.rs
+++ b/crates/agent_session/src/outbound/postgres.rs
@@ -3,6 +3,9 @@
//! addressed to.
pub mod search;
+
+use messages::domain::models::MessageParent;
+use sqlx::types::Json;
#[cfg(test)]
mod test;
@@ -10,10 +13,10 @@ mod pull_request;
use crate::domain::error::{AgentSessionError, Result};
use crate::domain::model::{
- AgentMcpServers, AgentSession, AgentSessionId, AgentSessionLog, AgentSessionPreview,
- AgentSessionPreviewData, ChannelSession, ClaimOutcome, CreateAgentSessionParams,
- ExternalSession, ManagerFence, Message, ReplicaAddress, ReplicaId, SandboxSize, SessionBot,
- SessionClaim, SessionManager, SessionStatus, StoredAgentSessionLog,
+ AgentMcpServers, AgentSession, AgentSessionId, AgentSessionLog, AgentSessionPreviewData,
+ ClaimOutcome, CreateAgentSessionParams, ExternalSession, ManagerFence, Message, ReplicaAddress,
+ ReplicaId, SandboxSize, SessionBot, SessionClaim, SessionManager, SessionPreviewCandidate,
+ SessionStatus, StoredAgentSessionLog, ThreadSession,
};
use crate::domain::ports::{
AgentSessionLogRepo, AgentSessionRepo, ExternalSessionRepo, REPLICA_STALE_AFTER,
@@ -187,7 +190,7 @@ struct AgentSessionRow {
name: String,
owner_id: String,
thread_id: Option<Uuid>,
- thread_channel_id: Option<Uuid>,
+ thread_parent: Option<Json<MessageParent>>,
originating_message_id: Option<Uuid>,
bot_id: Uuid,
model: String,
@@ -223,7 +226,7 @@ impl TryFrom<AgentSessionRow> for AgentSession {
owner_id: MacroUserIdStr::try_from(row.owner_id)
.context("agent session has an unparseable owner")?,
thread_id: row.thread_id,
- thread_channel_id: row.thread_channel_id,
+ thread_parent: row.thread_parent.map(|parent| parent.0),
originating_message_id: row.originating_message_id,
bot_id: BotId::new_from_uuid(row.bot_id),
model: row.model,
@@ -307,8 +310,9 @@ impl AgentSessionRepo for PgAgentSessionRepo {
model, harness, repo_url, repo_branch, pull_request_url, workspace, sandbox_size, instructions,
mcp_scope, mcp_servers, acp_session_id, status,
status_event_name, created_at, modified_at,
- (SELECT channel_id FROM comms_messages WHERE id = agent_session.thread_id)
- AS "thread_channel_id?",
+ (SELECT jsonb_build_object('type', parent_entity_type, 'id', parent_entity_id)
+ FROM comms_messages WHERE id = agent_session.thread_id)
+ AS "thread_parent?: Json<MessageParent>",
-- A row being created cannot have an external identity yet.
NULL::TEXT AS "external_provider?", NULL::TEXT AS "external_id?",
NULL::TEXT AS "external_name?", NULL::TEXT AS "external_url?",
@@ -374,13 +378,12 @@ impl AgentSessionRepo for PgAgentSessionRepo {
// message - directly, rather than from a channel - is its owner's alone.
let origin_channel_id = match originating_message_id {
Some(message_id) => sqlx::query_scalar!(
- "SELECT channel_id FROM comms_messages WHERE id = $1",
+ r#"SELECT parent_entity_id::uuid AS "channel_id!" FROM comms_messages WHERE parent_entity_type = 'channel' AND id = $1"#,
message_id,
)
.fetch_optional(&mut *transaction)
.await
- .context("failed to read the originating message's channel")?
- .flatten(),
+ .context("failed to read the originating message's channel")?,
None => None,
};
@@ -422,8 +425,9 @@ impl AgentSessionRepo for PgAgentSessionRepo {
model, harness, repo_url, repo_branch, pull_request_url, workspace, sandbox_size, instructions,
mcp_scope, mcp_servers, acp_session_id, status,
status_event_name, agent_session.created_at, modified_at,
- (SELECT channel_id FROM comms_messages WHERE id = agent_session.thread_id)
- AS "thread_channel_id?",
+ (SELECT jsonb_build_object('type', parent_entity_type, 'id', parent_entity_id)
+ FROM comms_messages WHERE id = agent_session.thread_id)
+ AS "thread_parent?: Json<MessageParent>",
ext.provider AS "external_provider?", ext.external_id AS "external_id?",
ext.external_name AS "external_name?", ext.external_url AS "external_url?",
ext.last_run_id AS "external_last_run_id?"
@@ -445,11 +449,13 @@ impl AgentSessionRepo for PgAgentSessionRepo {
&self,
viewer: &MacroUserIdStr<'static>,
ids: &[AgentSessionId],
- ) -> Result<Vec<AgentSessionPreview>> {
+ ) -> Result<Vec<SessionPreviewCandidate>> {
let uuids: Vec<Uuid> = ids.iter().map(AgentSessionId::as_uuid).collect();
// The viewer's grant sources - themselves, the channels they are still
// in, their teams - are the same three the Soup leg and the access
// extractor resolve, so a preview agrees with what a read would do.
+ // Access inherited from an originating document has no row; the
+ // thread parent is returned so the service can ask for it.
let rows = sqlx::query!(
r#"
WITH viewer_source_ids AS (
@@ -475,7 +481,10 @@ impl AgentSessionRepo for PgAgentSessionRepo {
WHERE ea.entity_id = s.id
AND ea.entity_type = 'agent_session'
AND ea.source_id IN (SELECT source_id FROM viewer_source_ids)
- ) AS "has_access!"
+ ) AS "has_access!",
+ (SELECT jsonb_build_object('type', parent_entity_type, 'id', parent_entity_id)
+ FROM comms_messages WHERE id = s.thread_id)
+ AS "thread_parent?: Json<MessageParent>"
FROM agent_session s
WHERE s.id = ANY($1)
"#,
@@ -486,35 +495,27 @@ impl AgentSessionRepo for PgAgentSessionRepo {
.await
.context("failed to preview agent sessions")?;
- let mut found = std::collections::HashSet::with_capacity(rows.len());
- let mut previews = Vec::with_capacity(ids.len());
- for row in rows {
- let id = AgentSessionId::new_from_uuid(row.id);
- found.insert(id);
- if !row.has_access {
- previews.push(AgentSessionPreview::NoAccess(id));
- continue;
- }
- previews.push(AgentSessionPreview::Access(Box::new(
- AgentSessionPreviewData {
- bot: None,
- id,
- name: row.name,
- owner_id: MacroUserIdStr::try_from(row.owner_id)
- .context("agent session has an unparseable owner")?,
- bot_id: BotId::new_from_uuid(row.bot_id),
- status: parse_status(&row.status, row.status_event_name)?,
- created_at: row.created_at,
- modified_at: row.modified_at,
- },
- )));
- }
- previews.extend(
- ids.iter()
- .filter(|id| !found.contains(id))
- .map(|id| AgentSessionPreview::DoesNotExist(*id)),
- );
- Ok(previews)
+ rows.into_iter()
+ .map(|row| {
+ let id = AgentSessionId::new_from_uuid(row.id);
+ Ok(SessionPreviewCandidate {
+ data: AgentSessionPreviewData {
+ bot: None,
+ id,
+ name: row.name,
+ owner_id: MacroUserIdStr::try_from(row.owner_id)
+ .context("agent session has an unparseable owner")?,
+ bot_id: BotId::new_from_uuid(row.bot_id),
+ status: parse_status(&row.status, row.status_event_name)?,
+ created_at: row.created_at,
+ modified_at: row.modified_at,
+ },
+ has_grant: row.has_access,
+ thread_parent: row.thread_parent.map(|parent| parent.0),
+ })
+ })
+ .collect::<anyhow::Result<Vec<_>>>()
+ .map_err(Into::into)
}
async fn find_by_egress_token_hash(
@@ -532,8 +533,9 @@ impl AgentSessionRepo for PgAgentSessionRepo {
model, harness, repo_url, repo_branch, pull_request_url, workspace, sandbox_size, instructions,
mcp_scope, mcp_servers, acp_session_id, status,
status_event_name, agent_session.created_at, modified_at,
- (SELECT channel_id FROM comms_messages WHERE id = agent_session.thread_id)
- AS "thread_channel_id?",
+ (SELECT jsonb_build_object('type', parent_entity_type, 'id', parent_entity_id)
+ FROM comms_messages WHERE id = agent_session.thread_id)
+ AS "thread_parent?: Json<MessageParent>",
ext.provider AS "external_provider?", ext.external_id AS "external_id?",
ext.external_name AS "external_name?", ext.external_url AS "external_url?",
ext.last_run_id AS "external_last_run_id?"
@@ -553,16 +555,16 @@ impl AgentSessionRepo for PgAgentSessionRepo {
})
}
- async fn find_for_channel(
+ async fn find_for_thread(
&self,
thread_id: Option<Uuid>,
bot_id: Option<BotId>,
- ) -> Result<ChannelSession> {
+ ) -> Result<ThreadSession> {
// Both are required to match: a session is only reachable from the
// thread it was created from, by the bot that runs it. NULL params
// match nothing rather than everything.
let (Some(thread_id), Some(bot_id)) = (thread_id, bot_id) else {
- return Ok(ChannelSession::None);
+ return Ok(ThreadSession::None);
};
let row = sqlx::query_as!(
AgentSessionRow,
@@ -572,8 +574,9 @@ impl AgentSessionRepo for PgAgentSessionRepo {
model, harness, repo_url, repo_branch, pull_request_url, workspace, sandbox_size, instructions,
mcp_scope, mcp_servers, acp_session_id, status,
status_event_name, agent_session.created_at, modified_at,
- (SELECT channel_id FROM comms_messages WHERE id = agent_session.thread_id)
- AS "thread_channel_id?",
+ (SELECT jsonb_build_object('type', parent_entity_type, 'id', parent_entity_id)
+ FROM comms_messages WHERE id = agent_session.thread_id)
+ AS "thread_parent?: Json<MessageParent>",
ext.provider AS "external_provider?", ext.external_id AS "external_id?",
ext.external_name AS "external_name?", ext.external_url AS "external_url?",
ext.last_run_id AS "external_last_run_id?"
@@ -591,8 +594,8 @@ impl AgentSessionRepo for PgAgentSessionRepo {
.context("failed to find agent session for channel context")?;
Ok(match row {
- Some(row) => ChannelSession::CreatedFromThread(row.try_into()?),
- None => ChannelSession::None,
+ Some(row) => ThreadSession::CreatedFromThread(row.try_into()?),
+ None => ThreadSession::None,
})
}
@@ -605,8 +608,9 @@ impl AgentSessionRepo for PgAgentSessionRepo {
model, harness, repo_url, repo_branch, pull_request_url, workspace, sandbox_size, instructions,
mcp_scope, mcp_servers, acp_session_id, status,
status_event_name, agent_session.created_at, modified_at,
- (SELECT channel_id FROM comms_messages WHERE id = agent_session.thread_id)
- AS "thread_channel_id?",
+ (SELECT jsonb_build_object('type', parent_entity_type, 'id', parent_entity_id)
+ FROM comms_messages WHERE id = agent_session.thread_id)
+ AS "thread_parent?: Json<MessageParent>",
ext.provider AS "external_provider?", ext.external_id AS "external_id?",
ext.external_name AS "external_name?", ext.external_url AS "external_url?",
ext.last_run_id AS "external_last_run_id?"
@@ -640,8 +644,9 @@ impl AgentSessionRepo for PgAgentSessionRepo {
model, harness, repo_url, repo_branch, pull_request_url, workspace, sandbox_size, instructions,
mcp_scope, mcp_servers, acp_session_id, status,
status_event_name, agent_session.created_at, modified_at,
- (SELECT channel_id FROM comms_messages WHERE id = agent_session.thread_id)
- AS "thread_channel_id?",
+ (SELECT jsonb_build_object('type', parent_entity_type, 'id', parent_entity_id)
+ FROM comms_messages WHERE id = agent_session.thread_id)
+ AS "thread_parent?: Json<MessageParent>",
ext.provider AS "external_provider?", ext.external_id AS "external_id?",
ext.external_name AS "external_name?", ext.external_url AS "external_url?",
ext.last_run_id AS "external_last_run_id?"
diff --git a/crates/agent_session/src/outbound/postgres/test.rs b/crates/agent_session/src/outbound/postgres/test.rs
index 93a78df424..f41661d595 100644
--- a/crates/agent_session/src/outbound/postgres/test.rs
+++ b/crates/agent_session/src/outbound/postgres/test.rs
@@ -143,7 +143,7 @@ async fn insert_originating_thread_fixture(pool: &PgPool) -> (Uuid, Uuid, Uuid)
.await
.expect("create originating channel");
sqlx::query!(
- "INSERT INTO comms_messages (id, channel_id, sender_id, content) VALUES ($1, $2, $3, '')",
+ "INSERT INTO comms_messages (id, parent_entity_type, parent_entity_id, sender_id, content) VALUES ($1, 'channel', $2::uuid::text, $3, '')",
thread_id,
channel_id,
owner_id,
@@ -152,7 +152,7 @@ async fn insert_originating_thread_fixture(pool: &PgPool) -> (Uuid, Uuid, Uuid)
.await
.expect("create originating thread");
sqlx::query!(
- "INSERT INTO comms_messages (id, channel_id, thread_id, sender_id, content) VALUES ($1, $2, $3, $4, '')",
+ "INSERT INTO comms_messages (id, parent_entity_type, parent_entity_id, thread_id, sender_id, content) VALUES ($1, 'channel', $2::uuid::text, $3, $4, '')",
originating_message_id,
channel_id,
thread_id,
@@ -722,7 +722,7 @@ async fn log_create_and_list_by_session_orders_chronologically(pool: PgPool) {
}
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
-async fn find_for_channel_matches_the_originating_thread_and_bot(pool: PgPool) {
+async fn find_for_thread_matches_the_originating_thread_and_bot(pool: PgPool) {
let repo = PgAgentSessionRepo::new(pool.clone());
let bot_a = create_test_bot(&pool).await;
let bot_b = create_test_bot(&pool).await;
@@ -736,32 +736,42 @@ async fn find_for_channel_matches_the_originating_thread_and_bot(pool: PgPool) {
.await;
// The create response must already resolve the thread's channel: linked
// -thread navigation renders from this row without a second lookup.
- assert_eq!(session.thread_channel_id, Some(originating_channel));
+ assert_eq!(
+ session.thread_parent,
+ Some(messages::domain::models::MessageParent::Channel(
+ originating_channel
+ ))
+ );
// A session from some other context must not shadow the lookup.
create_session(&repo, new_session(bot_a, None, None)).await;
let found = repo
- .find_for_channel(Some(thread), Some(bot_b))
+ .find_for_thread(Some(thread), Some(bot_b))
.await
.expect("find bot B's session by originating thread");
- let ChannelSession::CreatedFromThread(matched) = found else {
+ let ThreadSession::CreatedFromThread(matched) = found else {
panic!("expected the originating-thread session, got {found:?}");
};
assert_eq!(matched.id, session.id);
assert_eq!(matched.originating_message_id, Some(originating_message));
- assert_eq!(matched.thread_channel_id, Some(originating_channel));
+ assert_eq!(
+ matched.thread_parent,
+ Some(messages::domain::models::MessageParent::Channel(
+ originating_channel
+ ))
+ );
let wrong_bot = repo
- .find_for_channel(Some(thread), Some(bot_a))
+ .find_for_thread(Some(thread), Some(bot_a))
.await
.expect("look up the wrong bot");
- assert!(matches!(wrong_bot, ChannelSession::None));
+ assert!(matches!(wrong_bot, ThreadSession::None));
let wrong_thread = repo
- .find_for_channel(Some(macro_uuid::generate_uuid_v7()), Some(bot_b))
+ .find_for_thread(Some(macro_uuid::generate_uuid_v7()), Some(bot_b))
.await
.expect("look up an unrelated thread");
- assert!(matches!(wrong_thread, ChannelSession::None));
+ assert!(matches!(wrong_thread, ThreadSession::None));
}
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
@@ -862,7 +872,7 @@ async fn recent_for_owner_returns_the_owners_newest_sessions(pool: PgPool) {
}
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
-async fn find_for_channel_requires_thread_and_bot_for_originating_match(pool: PgPool) {
+async fn find_for_thread_requires_thread_and_bot_for_originating_match(pool: PgPool) {
let repo = PgAgentSessionRepo::new(pool.clone());
let bot = create_test_bot(&pool).await;
let (_channel, thread, originating_message) = insert_originating_thread_fixture(&pool).await;
@@ -873,16 +883,16 @@ async fn find_for_channel_requires_thread_and_bot_for_originating_match(pool: Pg
.await;
let without_bot = repo
- .find_for_channel(Some(thread), None)
+ .find_for_thread(Some(thread), None)
.await
.expect("look up without a bot");
- assert!(matches!(without_bot, ChannelSession::None));
+ assert!(matches!(without_bot, ThreadSession::None));
let without_thread = repo
- .find_for_channel(None, Some(bot))
+ .find_for_thread(None, Some(bot))
.await
.expect("look up without a thread");
- assert!(matches!(without_thread, ChannelSession::None));
+ assert!(matches!(without_thread, ThreadSession::None));
}
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
@@ -1044,11 +1054,11 @@ async fn create_records_the_session_in_the_owners_history(pool: PgPool) {
assert_eq!(history[0].item_type, "agent_session");
}
-/// A preview answers every requested id one way or another: the owner sees
-/// the session's fields, a channel member sees them through the channel's
-/// grant, a stranger learns only that it exists, and an unknown id is
-/// reported as such. Duplicates in the request are the caller's problem
-/// (the service collapses them); the repo answers what it is asked.
+/// A preview reports every existing id with whether the viewer holds a grant:
+/// the owner through their own row, a channel member through the channel's,
+/// a stranger through none, and an unknown id not at all. Duplicates in the
+/// request are the caller's problem (the service collapses them); the repo
+/// answers what it is asked.
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn preview_answers_per_id_by_the_viewers_grants(pool: PgPool) {
let repo = PgAgentSessionRepo::new(pool.clone());
@@ -1082,67 +1092,63 @@ async fn preview_answers_per_id_by_the_viewers_grants(pool: PgPool) {
.preview(&user_id(OWNER), &ids)
.await
.expect("owner preview");
- owner_view.sort_by_key(|preview| preview.id().as_uuid());
+ owner_view.sort_by_key(|candidate| candidate.data.id.as_uuid());
let mut expected = vec![
- AgentSessionPreview::Access(Box::new(AgentSessionPreviewData {
- id: from_channel.id,
- bot: None,
- name: DEFAULT_AGENT_SESSION_NAME.to_string(),
- owner_id: user_id(OWNER),
- bot_id,
- status: SessionStatus::NoMessages,
- created_at: from_channel.created_at,
- modified_at: from_channel.modified_at,
- })),
- AgentSessionPreview::Access(Box::new(AgentSessionPreviewData {
- id: private.id,
- bot: None,
- name: DEFAULT_AGENT_SESSION_NAME.to_string(),
- owner_id: user_id(OWNER),
- bot_id,
- status: SessionStatus::Event(SystemEvent::AcpReady),
- created_at: private.created_at,
- // Bumped by the status event, so read back rather than assumed.
- modified_at: AgentSessionRepo::get(&repo, private.id)
- .await
- .expect("reload")
- .modified_at,
- })),
- AgentSessionPreview::DoesNotExist(missing),
+ SessionPreviewCandidate {
+ data: AgentSessionPreviewData {
+ id: from_channel.id,
+ bot: None,
+ name: DEFAULT_AGENT_SESSION_NAME.to_string(),
+ owner_id: user_id(OWNER),
+ bot_id,
+ status: SessionStatus::NoMessages,
+ created_at: from_channel.created_at,
+ modified_at: from_channel.modified_at,
+ },
+ has_grant: true,
+ thread_parent: Some(MessageParent::Channel(channel_id)),
+ },
+ SessionPreviewCandidate {
+ data: AgentSessionPreviewData {
+ id: private.id,
+ bot: None,
+ name: DEFAULT_AGENT_SESSION_NAME.to_string(),
+ owner_id: user_id(OWNER),
+ bot_id,
+ status: SessionStatus::Event(SystemEvent::AcpReady),
+ created_at: private.created_at,
+ // Bumped by the status event, so read back rather than assumed.
+ modified_at: AgentSessionRepo::get(&repo, private.id)
+ .await
+ .expect("reload")
+ .modified_at,
+ },
+ has_grant: true,
+ thread_parent: None,
+ },
];
- expected.sort_by_key(|preview| preview.id().as_uuid());
+ expected.sort_by_key(|candidate| candidate.data.id.as_uuid());
assert_eq!(owner_view, expected);
+ let grant = |view: &[SessionPreviewCandidate], id: AgentSessionId| {
+ view.iter()
+ .find(|candidate| candidate.data.id == id)
+ .map(|candidate| candidate.has_grant)
+ };
let member_view = repo
.preview(&user_id(member), &ids)
.await
.expect("member preview");
- assert_eq!(member_view.len(), 3);
- assert!(matches!(
- member_view.iter().find(|p| p.id() == from_channel.id),
- Some(AgentSessionPreview::Access(_))
- ));
- assert_eq!(
- member_view.iter().find(|p| p.id() == private.id),
- Some(&AgentSessionPreview::NoAccess(private.id))
- );
- assert_eq!(
- member_view.iter().find(|p| p.id() == missing),
- Some(&AgentSessionPreview::DoesNotExist(missing))
- );
+ assert_eq!(member_view.len(), 2, "the missing id is absent");
+ assert_eq!(grant(&member_view, from_channel.id), Some(true));
+ assert_eq!(grant(&member_view, private.id), Some(false));
let stranger_view = repo
.preview(&user_id(stranger), &ids)
.await
.expect("stranger preview");
- assert_eq!(
- stranger_view.iter().find(|p| p.id() == from_channel.id),
- Some(&AgentSessionPreview::NoAccess(from_channel.id))
- );
- assert_eq!(
- stranger_view.iter().find(|p| p.id() == private.id),
- Some(&AgentSessionPreview::NoAccess(private.id))
- );
+ assert_eq!(grant(&stranger_view, from_channel.id), Some(false));
+ assert_eq!(grant(&stranger_view, private.id), Some(false));
// A member who has left the channel loses the channel's grant with it.
sqlx::query!(
@@ -1157,10 +1163,7 @@ async fn preview_answers_per_id_by_the_viewers_grants(pool: PgPool) {
.preview(&user_id(member), &[from_channel.id])
.await
.expect("former member preview");
- assert_eq!(
- left_view,
- vec![AgentSessionPreview::NoAccess(from_channel.id)]
- );
+ assert_eq!(grant(&left_view, from_channel.id), Some(false));
}
/// `entity_access.entity_id` carries no foreign key, so deleting a session
@@ -2119,3 +2122,177 @@ async fn pull_request_waiting_on_takeover_cannot_overwrite_successor(pool: PgPoo
Err(AgentSessionError::FencedOut(_))
));
}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn a_document_session_preserves_its_origin_and_inherits_live_document_access(pool: PgPool) {
+ use entity_access::domain::ports::EntityAccessService as _;
+ use messages::domain::{
+ models::PostMessage,
+ ports::{CreateMessage, MessageRepository},
+ };
+ let bot = create_test_bot(&pool).await;
+ let document = macro_uuid::generate_uuid_v7();
+ let document_id = document.to_string();
+ sqlx::query!(r#"INSERT INTO "Document" (id, name, owner, "fileType") VALUES ($1, 'Agent document', $2, 'md')"#, document_id, OWNER)
+ .execute(&pool).await.unwrap();
+ let messages = messages::outbound::pg_message_repo::PgMessageRepository::new(pool.clone());
+ let parent = MessageParent::parse("document", &document_id).unwrap();
+ let root = messages
+ .create(CreateMessage {
+ parent: parent.clone(),
+ actor: OWNER.to_owned().try_into().unwrap(),
+ triggered_by: None,
+ input: PostMessage {
+ attribution: Default::default(),
+ notification_policy: Default::default(),
+ content: "@agent investigate".into(),
+ thread_id: None,
+ anchor: None,
+ mentions: vec![],
+ attachments: vec![],
+ nonce: None,
+ },
+ })
+ .await
+ .unwrap();
+ let repo = PgAgentSessionRepo::new(pool.clone());
+ let session = create_session(&repo, new_session(bot, Some(root.id), Some(root.id))).await;
+ assert_eq!(session.thread_parent, Some(parent.clone()));
+ assert_eq!(
+ AgentSessionRepo::get(&repo, session.id)
+ .await
+ .unwrap()
+ .thread_parent,
+ Some(parent.clone())
+ );
+ assert_eq!(
+ repo.find_all_for_thread(root.id).await.unwrap()[0].thread_parent,
+ Some(parent.clone())
+ );
+
+ let collaborator = "macro|[email protected]";
+ insert_user(&pool, collaborator).await;
+ let mut transaction = pool.begin().await.unwrap();
+ insert_entity_access_row(
+ &mut transaction,
+ &document,
+ EntityType::Document,
+ collaborator,
+ EntityAccessSourceType::User,
+ AccessLevel::Comment,
+ )
+ .await
+ .unwrap();
+ transaction.commit().await.unwrap();
+ let access = entity_access::domain::service::EntityAccessServiceImpl::new(
+ entity_access::outbound::PgAccessRepository::new(pool.clone()),
+ );
+ use crate::domain::audience::{AuthorizedSessionAudience, SessionAudience};
+ let audience = AuthorizedSessionAudience::new(
+ repo.clone(),
+ access.clone(),
+ DocumentSubscriptions {
+ document: document_id.clone(),
+ candidates: [
+ collaborator.to_string(),
+ "macro|[email protected]".to_string(),
+ ]
+ .into_iter()
+ .collect(),
+ },
+ );
+ let viewers = audience.viewers(session.id).await.unwrap();
+ assert!(viewers.contains(&user_id(OWNER)));
+ assert!(viewers.contains(&user_id(collaborator)));
+ assert_eq!(viewers.len(), 2);
+ // Bind owned values across the async lookup.
+ let collaborator_id = user_id(collaborator);
+ let session_id = session.id.to_string();
+ assert_eq!(
+ access
+ .get_access_level(
+ Some(&collaborator_id),
+ &session_id,
+ EntityType::AgentSession
+ )
+ .await
+ .unwrap(),
+ Some(AccessLevel::Edit)
+ );
+ sqlx::query!(
+ "DELETE FROM entity_access WHERE entity_id = $1 AND source_id = $2",
+ document,
+ collaborator
+ )
+ .execute(&pool)
+ .await
+ .unwrap();
+ assert_eq!(
+ access
+ .get_access_level(
+ Some(&collaborator_id),
+ &session_id,
+ EntityType::AgentSession
+ )
+ .await
+ .unwrap(),
+ None
+ );
+ assert_eq!(
+ audience.viewers(session.id).await.unwrap(),
+ vec![user_id(OWNER)]
+ );
+
+ // A preview never sees the inherited grant as a row: the candidate names
+ // the document so the service can ask, and the view adapter answers with
+ // the document's current permission.
+ use crate::domain::audience::EntityAccessSessionView;
+ use crate::domain::ports::SessionViewAccess as _;
+ let view = EntityAccessSessionView::new(access.clone());
+ let candidates = repo.preview(&collaborator_id, &[session.id]).await.unwrap();
+ assert_eq!(candidates.len(), 1);
+ assert!(!candidates[0].has_grant);
+ assert_eq!(candidates[0].thread_parent, Some(parent.clone()));
+ assert!(!view.can_view(&collaborator_id, session.id).await.unwrap());
+ let mut transaction = pool.begin().await.unwrap();
+ insert_entity_access_row(
+ &mut transaction,
+ &document,
+ EntityType::Document,
+ collaborator,
+ EntityAccessSourceType::User,
+ AccessLevel::View,
+ )
+ .await
+ .unwrap();
+ transaction.commit().await.unwrap();
+ assert!(view.can_view(&collaborator_id, session.id).await.unwrap());
+ assert!(
+ !repo.preview(&collaborator_id, &[session.id]).await.unwrap()[0].has_grant,
+ "inherited access is resolved at check time, never materialized"
+ );
+ assert!(
+ !view
+ .can_view(&user_id("macro|[email protected]"), session.id)
+ .await
+ .unwrap()
+ );
+}
+
+struct DocumentSubscriptions {
+ document: String,
+ candidates: std::collections::HashSet<String>,
+}
+impl crate::domain::audience::SessionSubscriptions for DocumentSubscriptions {
+ async fn candidates(
+ &self,
+ _: AgentSessionId,
+ parent: Option<&MessageParent>,
+ ) -> Result<std::collections::HashSet<String>, rootcause::Report> {
+ assert_eq!(
+ parent,
+ Some(&MessageParent::parse("document", &self.document).unwrap())
+ );
+ Ok(self.candidates.clone())
+ }
+}
diff --git a/crates/agent_session/src/testing.rs b/crates/agent_session/src/testing.rs
index af7d3888ac..d73b598d8b 100644
--- a/crates/agent_session/src/testing.rs
+++ b/crates/agent_session/src/testing.rs
@@ -7,10 +7,10 @@
use crate::domain::error::{AgentSessionError, Result};
use crate::domain::events::AgentSessionLifecycleEvent;
use crate::domain::model::{
- AgentMcpServers, AgentSession, AgentSessionId, AgentSessionLog, AgentSessionPreview,
- AgentSessionPreviewData, ChannelSession, ClaimOutcome, CreateAgentSessionParams,
- DEFAULT_AGENT_SESSION_NAME, LogAppended, ManagerFence, ReplicaAddress, ReplicaId, SandboxSize,
- SessionBot, SessionClaim, SessionManager, SessionStatus, StoredAgentSessionLog,
+ AgentMcpServers, AgentSession, AgentSessionId, AgentSessionLog, AgentSessionPreviewData,
+ ClaimOutcome, CreateAgentSessionParams, DEFAULT_AGENT_SESSION_NAME, LogAppended, ManagerFence,
+ ReplicaAddress, ReplicaId, SandboxSize, SessionBot, SessionClaim, SessionManager,
+ SessionPreviewCandidate, SessionStatus, StoredAgentSessionLog, ThreadSession,
};
use crate::domain::ports::{
AgentSessionLifecyclePublisher, AgentSessionLogRepo, AgentSessionRealtime, AgentSessionRepo,
@@ -136,7 +136,7 @@ impl AgentSessionRepo for InMemoryAgentSessionRepo {
owner_id: params.owner_id,
thread_id: params.thread_id,
// The in-memory repo has no comms rows to derive a channel from.
- thread_channel_id: None,
+ thread_parent: None,
originating_message_id: params.originating_message_id,
bot_id: params.bot_id,
model: params.model,
@@ -166,28 +166,29 @@ impl AgentSessionRepo for InMemoryAgentSessionRepo {
&self,
viewer: &MacroUserIdStr<'static>,
ids: &[AgentSessionId],
- ) -> Result<Vec<AgentSessionPreview>> {
+ ) -> Result<Vec<SessionPreviewCandidate>> {
// No `entity_access` rows to consult here: the owner is the one grant
- // `create` always writes, so ownership stands in for access.
+ // `create` always writes, so ownership stands in for a grant.
let sessions = self
.sessions
.lock()
.expect("in-memory session store is not poisoned");
Ok(ids
.iter()
- .map(|id| match sessions.get(id) {
- None => AgentSessionPreview::DoesNotExist(*id),
- Some(session) if session.owner_id != *viewer => AgentSessionPreview::NoAccess(*id),
- Some(session) => AgentSessionPreview::Access(Box::new(AgentSessionPreviewData {
+ .filter_map(|id| sessions.get(id))
+ .map(|session| SessionPreviewCandidate {
+ data: AgentSessionPreviewData {
bot: None,
- id: *id,
+ id: session.id,
name: session.name.clone(),
owner_id: session.owner_id.clone(),
bot_id: session.bot_id,
status: session.status.clone(),
created_at: session.created_at,
modified_at: session.modified_at,
- })),
+ },
+ has_grant: session.owner_id == *viewer,
+ thread_parent: session.thread_parent.clone(),
})
.collect())
}
@@ -236,11 +237,11 @@ impl AgentSessionRepo for InMemoryAgentSessionRepo {
Ok(found)
}
- async fn find_for_channel(
+ async fn find_for_thread(
&self,
thread_id: Option<Uuid>,
bot_id: Option<BotId>,
- ) -> Result<ChannelSession> {
+ ) -> Result<ThreadSession> {
let sessions = self
.sessions
.lock()
@@ -252,8 +253,8 @@ impl AgentSessionRepo for InMemoryAgentSessionRepo {
&& Some(session.bot_id) == bot_id
});
Ok(match matched {
- Some(session) => ChannelSession::CreatedFromThread(session.clone()),
- None => ChannelSession::None,
+ Some(session) => ThreadSession::CreatedFromThread(session.clone()),
+ None => ThreadSession::None,
})
}
@@ -698,7 +699,7 @@ pub fn test_agent_session(id: AgentSessionId) -> AgentSession {
owner_id: macro_user_id::user_id::MacroUserIdStr::try_from_email("[email protected]")
.expect("valid macro user id"),
thread_id: None,
- thread_channel_id: None,
+ thread_parent: None,
originating_message_id: None,
bot_id: BotId::new_from_uuid(Uuid::from_u128(0xb07)),
model: "claude-sonnet-5".to_string(),
diff --git a/crates/agent_trigger/Cargo.toml b/crates/agent_trigger/Cargo.toml
index 686af9418c..140cf62e8f 100644
--- a/crates/agent_trigger/Cargo.toml
+++ b/crates/agent_trigger/Cargo.toml
@@ -9,7 +9,7 @@ version = "0.1.0"
# 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:lexical_client"]
+outbound = ["dep:agent", "dep:ai_usage", "dep:lexical_client", "dep:sqlx", "channels/ports"]
[dependencies]
agent = { path = "../agent", optional = true }
@@ -17,9 +17,9 @@ agent_session = { path = "../agent_session", default-features = false }
ai_usage = { path = "../ai_usage", optional = true }
anyhow = { workspace = true }
bot_id = { path = "../bot_id" }
+entity_access = { path = "../entity_access", default-features = false, features = ["ports"] }
bots = { path = "../bots", default-features = false, features = ["ports"] }
lexical_client = { path = "../lexical_client", optional = true }
-channels = { path = "../channels", features = ["ports"] }
chrono = { workspace = true }
# Only the domain vocabulary (`Event`, `MacroEvent`, `TopicEvent`). Asking for
# `outbound` here would pull rdkafka — and so librdkafka and openssl — into
@@ -30,7 +30,12 @@ macro_event_topics = { path = "../macro_event_topics" }
macro_user_id = { path = "../macro_user_id" }
channel_sender = { path = "../channel_sender" }
macro_uuid = { path = "../macro_uuid" }
+messages = { path = "../messages", features = ["broker", "ports"] }
+# Domain vocabulary: channel-parent trigger events keep the channel-only post
+# shape, and the channel topic's `message_posted` can still feed the trigger.
+channels = { path = "../channels", default-features = false }
serde = { workspace = true }
+sqlx = { workspace = true, optional = true }
strum = { workspace = true }
serde_json = { workspace = true }
thiserror = { workspace = true }
@@ -39,8 +44,8 @@ tokio = { workspace = true, features = ["rt"] }
workspace-hack = { version = "0.1", path = "../workspace-hack" }
[dev-dependencies]
+messages = { path = "../messages", features = ["test-utils"] }
agent_session = { path = "../agent_session", features = ["test-utils"] }
bot_id = { path = "../bot_id", features = ["test-utils"] }
-messages = { path = "../messages" }
mockall = { workspace = true }
tokio = { workspace = true, features = ["macros", "rt-multi-thread"] }
diff --git a/crates/agent_trigger/src/domain/broker_events.rs b/crates/agent_trigger/src/domain/broker_events.rs
index 86a4fe38de..5a77d09146 100644
--- a/crates/agent_trigger/src/domain/broker_events.rs
+++ b/crates/agent_trigger/src/domain/broker_events.rs
@@ -1,10 +1,22 @@
//! Signals published to [`MacroAgentSessionsTopic`].
+//!
+//! The topic stays at its first schema version. Channel parents keep the
+//! shapes every consumer already decodes - [`NewAgentSessionEvent::TopLevelMentioned`]
+//! and [`ExistingAgentSessionEvent::Channel`], each embedding the channel-only
+//! post - because some consumers are user-run daemons that cannot be rolled
+//! with a deploy. Other parents travel in the parent-aware variants added
+//! beside them, which those consumers drop as unknown: only the new surface
+//! waits for them to roll, never a channel mention.
use agent_session::domain::model::AgentSessionId;
use bot_id::BotId;
-use channels::domain::broker_events::ChannelMessagePostedMetadata;
+use channels::domain::broker_events::{ChannelEventAttachment, ChannelMessagePostedMetadata};
+use channels::domain::models::ChannelType;
use macro_event_broker::{Event, MacroEvent, TopicEvent};
use macro_event_topics::MacroAgentSessionsTopic;
+use macro_uuid::Uuid;
+use messages::domain::events::{MessageEventAttachment, MessagePostedMetadata};
+use messages::domain::models::MessageParent;
use serde::{Deserialize, Serialize};
#[cfg(test)]
@@ -13,7 +25,7 @@ mod test;
/// How a message was attributed to the session it feeds.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
-pub enum ChannelKind {
+pub enum ThreadMessageKind {
/// The thread the session was created from, where the bot was pinged.
MentionThread,
/// The session's thread, where the message explicitly targeted another
@@ -24,7 +36,8 @@ pub enum ChannelKind {
Inferred,
}
-/// A session opened by a mention in a channel.
+/// A session opened by a mention in a top-level channel message, in the
+/// channel-only shape consumers built before message parents decode.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AgentBotMentionedEvent {
/// The bot that was mentioned.
@@ -33,6 +46,18 @@ pub struct AgentBotMentionedEvent {
pub message: ChannelMessagePostedMetadata,
}
+/// A session opened by a mention on a message parent. Today only document
+/// discussions produce it; channel mentions stay on
+/// [`NewAgentSessionEvent::TopLevelMentioned`] until every consumer that
+/// predates parents has rolled.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct AgentMentionedEvent {
+ /// The bot that was mentioned.
+ pub bot_id: BotId,
+ /// The message that triggered this, verbatim, with its parent.
+ pub message: MessagePostedMetadata,
+}
+
/// Events that open a new session.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
@@ -40,9 +65,39 @@ pub struct AgentBotMentionedEvent {
pub enum NewAgentSessionEvent {
/// Opened by a bot mention in a top-level channel message.
TopLevelMentioned(AgentBotMentionedEvent),
+ /// Opened by a bot mention on a message parent other than a channel.
+ Mentioned(AgentMentionedEvent),
+}
+
+/// The mention a new-session event carries, whichever parent it was on.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct OpeningMention {
+ /// The bot that was mentioned.
+ pub bot_id: BotId,
+ /// The mentioning message, with its parent.
+ pub message: MessagePostedMetadata,
}
-/// A message for a session that already exists.
+impl NewAgentSessionEvent {
+ /// The mention this event carries; `None` for a shape this build does
+ /// not recognise, which a consumer skips rather than routes.
+ #[must_use]
+ pub fn mention(&self) -> Option<OpeningMention> {
+ match self {
+ Self::TopLevelMentioned(mentioned) => Some(OpeningMention {
+ bot_id: mentioned.bot_id,
+ message: posted_from_channel_event(&mentioned.message),
+ }),
+ Self::Mentioned(mentioned) => Some(OpeningMention {
+ bot_id: mentioned.bot_id,
+ message: mentioned.message.clone(),
+ }),
+ }
+ }
+}
+
+/// A channel message for a session that already exists, in the channel-only
+/// shape consumers built before message parents decode.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ChannelEventMetadata {
/// Whose session this is, so foreign traffic is dropped before any read.
@@ -50,18 +105,71 @@ pub struct ChannelEventMetadata {
/// The session to feed.
pub session_id: AgentSessionId,
/// How the message was attributed to the session.
- pub kind: ChannelKind,
+ pub kind: ThreadMessageKind,
/// The message, verbatim.
pub message: ChannelMessagePostedMetadata,
}
+/// A message for a session that already exists, with its parent. Today only
+/// document discussions produce it; channel messages stay on
+/// [`ExistingAgentSessionEvent::Channel`] until every consumer that predates
+/// parents has rolled.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct ThreadEventMetadata {
+ /// Whose session this is, so foreign traffic is dropped before any read.
+ pub bot_id: BotId,
+ /// The session to feed.
+ pub session_id: AgentSessionId,
+ /// How the message was attributed to the session.
+ pub kind: ThreadMessageKind,
+ /// The message, verbatim, with its parent.
+ pub message: MessagePostedMetadata,
+}
+
/// Events for a session that already exists.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "source", rename_all = "snake_case")]
pub enum ExistingAgentSessionEvent {
- /// A mentioned message arrived in the session's originating thread.
+ /// A message arrived in the session's originating channel thread.
Channel(ChannelEventMetadata),
+ /// A message arrived in the session's originating thread on another parent.
+ Thread(ThreadEventMetadata),
+}
+
+/// The message an existing-session event feeds, whichever parent it was on.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct SessionMessage {
+ /// Whose session this is.
+ pub bot_id: BotId,
+ /// The session to feed.
+ pub session_id: AgentSessionId,
+ /// How the message was attributed to the session.
+ pub kind: ThreadMessageKind,
+ /// The message, with its parent.
+ pub message: MessagePostedMetadata,
+}
+
+impl ExistingAgentSessionEvent {
+ /// The message this event feeds; `None` for a shape this build does not
+ /// recognise, which a consumer skips rather than routes.
+ #[must_use]
+ pub fn session_message(&self) -> Option<SessionMessage> {
+ match self {
+ Self::Channel(metadata) => Some(SessionMessage {
+ bot_id: metadata.bot_id,
+ session_id: metadata.session_id,
+ kind: metadata.kind,
+ message: posted_from_channel_event(&metadata.message),
+ }),
+ Self::Thread(metadata) => Some(SessionMessage {
+ bot_id: metadata.bot_id,
+ session_id: metadata.session_id,
+ kind: metadata.kind,
+ message: metadata.message.clone(),
+ }),
+ }
+ }
}
/// Events publishable to [`MacroAgentSessionsTopic`].
@@ -87,12 +195,81 @@ pub enum AgentTriggerTopicEvent {
Existing(ExistingAgentSessionEvent),
}
+impl AgentTriggerTopicEvent {
+ /// The bot the event is for, when its shape is recognised.
+ #[must_use]
+ pub fn bot_id(&self) -> Option<BotId> {
+ match self {
+ Self::New(event) => event.mention().map(|mention| mention.bot_id),
+ Self::Existing(event) => event.session_message().map(|message| message.bot_id),
+ }
+ }
+}
+
impl TopicEvent for AgentTriggerTopicEvent {
type Topic = MacroAgentSessionsTopic;
const SCHEMA_VERSION: u8 = 1;
}
+/// What the trigger decided for one bot, before the wire shape is chosen.
+///
+/// The decision is parent-aware; [`AgentSessionMacroEvent::from_decision`]
+/// picks the channel-only shape for channel parents and the parent-aware one
+/// for the rest.
+#[derive(Debug, Clone, PartialEq, Eq)]
+#[allow(
+ clippy::large_enum_variant,
+ reason = "both variants carry a whole message; boxing would only move the size"
+)]
+pub enum TriggerDecision {
+ /// Open a session for a mentioned bot.
+ Open {
+ /// The bot that was mentioned.
+ bot_id: BotId,
+ /// The mentioning message.
+ message: MessagePostedMetadata,
+ },
+ /// Feed a session that already exists.
+ Existing {
+ /// Whose session this is.
+ bot_id: BotId,
+ /// The session to feed.
+ session_id: AgentSessionId,
+ /// How the message was attributed to the session.
+ kind: ThreadMessageKind,
+ /// The message.
+ message: MessagePostedMetadata,
+ },
+}
+
+impl TriggerDecision {
+ /// The bot the decision is for.
+ #[must_use]
+ pub fn bot_id(&self) -> BotId {
+ match self {
+ Self::Open { bot_id, .. } | Self::Existing { bot_id, .. } => *bot_id,
+ }
+ }
+
+ /// The message the decision was made about.
+ #[must_use]
+ pub fn message(&self) -> &MessagePostedMetadata {
+ match self {
+ Self::Open { message, .. } | Self::Existing { message, .. } => message,
+ }
+ }
+}
+
+/// A channel-parent decision needs the channel's type to take the channel-only
+/// wire shape, and the caller supplied none.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
+#[error("a channel trigger event needs the channel type of channel {channel_id}")]
+pub struct MissingChannelType {
+ /// The channel whose type was not supplied.
+ pub channel_id: Uuid,
+}
+
/// Publishable event for [`MacroAgentSessionsTopic`].
///
/// Keyed by bot id: a session belongs to one bot, so one bot's partition
@@ -106,22 +283,76 @@ pub struct AgentSessionMacroEvent {
}
impl AgentSessionMacroEvent {
+ /// The wire event for a decision.
+ ///
+ /// A channel parent takes the channel-only shape, which carries the
+ /// channel's type; any other parent takes the parent-aware shape and
+ /// ignores `channel_type`.
+ pub fn from_decision(
+ decision: TriggerDecision,
+ channel_type: Option<ChannelType>,
+ ) -> Result<Self, MissingChannelType> {
+ let channel = match &decision.message().parent {
+ MessageParent::Channel(channel_id) => Some(
+ channel_type
+ .map(|channel_type| (*channel_id, channel_type))
+ .ok_or(MissingChannelType {
+ channel_id: *channel_id,
+ })?,
+ ),
+ MessageParent::Document(_) => None,
+ };
+ Ok(match decision {
+ TriggerDecision::Open { bot_id, message } => match channel {
+ Some((channel_id, channel_type)) => Self::new_session(
+ NewAgentSessionEvent::TopLevelMentioned(AgentBotMentionedEvent {
+ bot_id,
+ message: channel_event_from_posted(&message, channel_id, channel_type),
+ }),
+ ),
+ None => Self::new_session(NewAgentSessionEvent::Mentioned(AgentMentionedEvent {
+ bot_id,
+ message,
+ })),
+ },
+ TriggerDecision::Existing {
+ bot_id,
+ session_id,
+ kind,
+ message,
+ } => match channel {
+ Some((channel_id, channel_type)) => Self::existing_event(
+ ExistingAgentSessionEvent::Channel(ChannelEventMetadata {
+ bot_id,
+ session_id,
+ kind,
+ message: channel_event_from_posted(&message, channel_id, channel_type),
+ }),
+ bot_id,
+ ),
+ None => Self::existing_event(
+ ExistingAgentSessionEvent::Thread(ThreadEventMetadata {
+ bot_id,
+ session_id,
+ kind,
+ message,
+ }),
+ bot_id,
+ ),
+ },
+ })
+ }
+
/// Open a session for a bot.
#[must_use]
pub fn new_session(event: NewAgentSessionEvent) -> Self {
let bot_id = match &event {
NewAgentSessionEvent::TopLevelMentioned(mentioned) => mentioned.bot_id,
+ NewAgentSessionEvent::Mentioned(mentioned) => mentioned.bot_id,
};
Self::new(bot_id, AgentTriggerTopicEvent::New(event))
}
- /// Feed one of a bot's existing sessions.
- #[must_use]
- pub fn channel_event(metadata: ChannelEventMetadata) -> Self {
- let bot_id = metadata.bot_id;
- Self::existing_event(ExistingAgentSessionEvent::Channel(metadata), bot_id)
- }
-
/// Feed one of a bot's existing sessions, however the message arrived.
#[must_use]
pub fn existing_event(event: ExistingAgentSessionEvent, bot_id: BotId) -> Self {
@@ -155,3 +386,65 @@ impl MacroEvent for AgentSessionMacroEvent {
Self::with_event(key, event)
}
}
+
+/// The parent-aware shape of a channel post carried in the channel-only shape.
+///
+/// A channel event names its channel and, for a reply, its thread; the root
+/// is the thread when there is one and the message itself otherwise, exactly
+/// as the message service derives it.
+#[must_use]
+pub fn posted_from_channel_event(posted: &ChannelMessagePostedMetadata) -> MessagePostedMetadata {
+ MessagePostedMetadata {
+ parent: MessageParent::Channel(posted.channel_id),
+ message_id: posted.message_id,
+ thread_id: posted.thread_id,
+ root_id: posted.thread_id.unwrap_or(posted.message_id),
+ sender: posted.sender.clone(),
+ triggered_by: posted.triggered_by.clone(),
+ content: posted.content.clone(),
+ mentions: posted.mentions.clone(),
+ attachments: posted
+ .attachments
+ .iter()
+ .map(|attachment| MessageEventAttachment {
+ attachment_id: attachment.attachment_id,
+ entity_type: attachment.entity_type.clone(),
+ entity_id: attachment.entity_id.clone(),
+ created_at: attachment.created_at,
+ })
+ .collect(),
+ created_at: posted.created_at,
+ }
+}
+
+/// The channel-only shape of a channel-parent post, for consumers built before
+/// message parents. The parent is dropped and the channel's type, which the
+/// parent-aware post does not carry, is supplied by the caller.
+#[must_use]
+pub fn channel_event_from_posted(
+ posted: &MessagePostedMetadata,
+ channel_id: Uuid,
+ channel_type: ChannelType,
+) -> ChannelMessagePostedMetadata {
+ ChannelMessagePostedMetadata {
+ channel_id,
+ message_id: posted.message_id,
+ thread_id: posted.thread_id,
+ sender: posted.sender.clone(),
+ triggered_by: posted.triggered_by.clone(),
+ channel_type,
+ content: posted.content.clone(),
+ mentions: posted.mentions.clone(),
+ attachments: posted
+ .attachments
+ .iter()
+ .map(|attachment| ChannelEventAttachment {
+ attachment_id: attachment.attachment_id,
+ entity_type: attachment.entity_type.clone(),
+ entity_id: attachment.entity_id.clone(),
+ created_at: attachment.created_at,
+ })
+ .collect(),
+ created_at: posted.created_at,
+ }
+}
diff --git a/crates/agent_trigger/src/domain/broker_events/test.rs b/crates/agent_trigger/src/domain/broker_events/test.rs
index f3f04d86fc..2d22732cf4 100644
--- a/crates/agent_trigger/src/domain/broker_events/test.rs
+++ b/crates/agent_trigger/src/domain/broker_events/test.rs
@@ -1,25 +1,47 @@
use super::*;
use channel_sender::ChannelSender;
-use channels::domain::models::ChannelType;
use chrono::Utc;
use macro_user_id::cowlike::CowLike;
use macro_user_id::user_id::MacroUserIdStr;
-use macro_uuid::Uuid;
use serde_json::json;
-fn message() -> ChannelMessagePostedMetadata {
+fn sender() -> ChannelSender<'static> {
+ ChannelSender::new_from_user(
+ MacroUserIdStr::parse_from_str("macro|[email protected]")
+ .expect("valid user id")
+ .into_owned(),
+ )
+}
+
+fn channel_message() -> ChannelMessagePostedMetadata {
ChannelMessagePostedMetadata {
channel_id: Uuid::from_u128(1),
message_id: Uuid::from_u128(2),
thread_id: None,
- sender: ChannelSender::new_from_user(
- MacroUserIdStr::parse_from_str("macro|[email protected]")
- .expect("valid user id")
- .into_owned(),
- ),
+ sender: sender(),
+ triggered_by: None,
+ channel_type: ChannelType::Private,
+ content: "hello".to_owned(),
+ mentions: vec![],
+ attachments: vec![ChannelEventAttachment {
+ attachment_id: Uuid::from_u128(9),
+ entity_type: "document".to_owned(),
+ entity_id: "doc".to_owned(),
+ created_at: Utc::now(),
+ }],
+ created_at: Utc::now(),
+ }
+}
+
+fn posted(parent: MessageParent, thread_id: Option<Uuid>) -> MessagePostedMetadata {
+ MessagePostedMetadata {
+ parent,
+ message_id: Uuid::from_u128(2),
+ thread_id,
+ root_id: thread_id.unwrap_or(Uuid::from_u128(2)),
+ sender: sender(),
triggered_by: None,
- channel_type: ChannelType::Public,
content: "hello".to_owned(),
mentions: vec![],
attachments: vec![],
@@ -27,12 +49,16 @@ fn message() -> ChannelMessagePostedMetadata {
}
}
+fn document() -> MessageParent {
+ MessageParent::parse("document", "doc-1").unwrap()
+}
+
#[test]
fn serializes_a_new_top_level_mention() {
let event = AgentTriggerTopicEvent::New(NewAgentSessionEvent::TopLevelMentioned(
AgentBotMentionedEvent {
bot_id: BotId::TEST_A,
- message: message(),
+ message: channel_message(),
},
));
@@ -49,8 +75,8 @@ fn serializes_an_existing_channel_event() {
ChannelEventMetadata {
bot_id: BotId::TEST_A,
session_id: AgentSessionId::TEST_A,
- kind: ChannelKind::MentionThread,
- message: message(),
+ kind: ThreadMessageKind::MentionThread,
+ message: channel_message(),
},
));
@@ -64,6 +90,194 @@ fn serializes_an_existing_channel_event() {
);
}
+/// The channel-only variants are the first schema version's wire shape; a
+/// consumer built against it must keep decoding what the trigger publishes
+/// for channel parents, so the topic never bumps its version for them.
+#[test]
+fn channel_events_keep_the_first_schema_versions_shape() {
+ assert_eq!(AgentTriggerTopicEvent::SCHEMA_VERSION, 1);
+ let event = AgentTriggerTopicEvent::Existing(ExistingAgentSessionEvent::Channel(
+ ChannelEventMetadata {
+ bot_id: BotId::TEST_A,
+ session_id: AgentSessionId::TEST_A,
+ kind: ThreadMessageKind::MentionThread,
+ message: channel_message(),
+ },
+ ));
+ let value = serde_json::to_value(&event).expect("serialize event");
+ let message = &value["metadata"]["message"];
+ assert_eq!(message["channel_id"], json!(Uuid::from_u128(1)));
+ assert_eq!(message["channel_type"], "private");
+ assert!(
+ message.get("parent").is_none(),
+ "the channel shape names no parent"
+ );
+ assert!(message.get("root_id").is_none());
+
+ let decoded: AgentTriggerTopicEvent = serde_json::from_value(value).expect("decode");
+ assert_eq!(decoded, event);
+}
+
+#[test]
+fn parent_aware_events_name_their_parent_and_are_new_variants() {
+ let event =
+ AgentTriggerTopicEvent::Existing(ExistingAgentSessionEvent::Thread(ThreadEventMetadata {
+ bot_id: BotId::TEST_A,
+ session_id: AgentSessionId::TEST_A,
+ kind: ThreadMessageKind::MentionThread,
+ message: posted(document(), None),
+ }));
+ let value = serde_json::to_value(&event).expect("serialize event");
+ assert_eq!(value["metadata"]["source"], "thread");
+ assert_eq!(value["metadata"]["message"]["parent"]["type"], "document");
+
+ let opened =
+ AgentTriggerTopicEvent::New(NewAgentSessionEvent::Mentioned(AgentMentionedEvent {
+ bot_id: BotId::TEST_A,
+ message: posted(document(), None),
+ }));
+ let value = serde_json::to_value(&opened).expect("serialize event");
+ assert_eq!(value["metadata"]["source"], "mentioned");
+}
+
+/// Consumers read both shapes through one view: the channel shape converts
+/// to a channel parent, the parent-aware shape passes through.
+#[test]
+fn accessors_present_both_shapes_as_parent_aware_messages() {
+ let from_channel = NewAgentSessionEvent::TopLevelMentioned(AgentBotMentionedEvent {
+ bot_id: BotId::TEST_A,
+ message: channel_message(),
+ })
+ .mention()
+ .expect("a recognised shape");
+ assert_eq!(from_channel.bot_id, BotId::TEST_A);
+ assert_eq!(
+ from_channel.message.parent,
+ MessageParent::Channel(Uuid::from_u128(1))
+ );
+ assert_eq!(from_channel.message.root_id, Uuid::from_u128(2));
+ assert_eq!(
+ from_channel.message.attachments[0].attachment_id,
+ Uuid::from_u128(9)
+ );
+
+ let from_document = ExistingAgentSessionEvent::Thread(ThreadEventMetadata {
+ bot_id: BotId::TEST_B,
+ session_id: AgentSessionId::TEST_B,
+ kind: ThreadMessageKind::Inferred,
+ message: posted(document(), Some(Uuid::from_u128(7))),
+ })
+ .session_message()
+ .expect("a recognised shape");
+ assert_eq!(from_document.session_id, AgentSessionId::TEST_B);
+ assert_eq!(from_document.kind, ThreadMessageKind::Inferred);
+ assert_eq!(from_document.message.parent, document());
+
+ let topic = AgentTriggerTopicEvent::Existing(ExistingAgentSessionEvent::Channel(
+ ChannelEventMetadata {
+ bot_id: BotId::TEST_A,
+ session_id: AgentSessionId::TEST_A,
+ kind: ThreadMessageKind::ExplicitReply,
+ message: channel_message(),
+ },
+ ));
+ assert_eq!(topic.bot_id(), Some(BotId::TEST_A));
+}
+
+/// A decision on a channel parent takes the channel-only shape, carrying the
+/// channel's type; one on a document takes the parent-aware shape.
+#[test]
+fn decisions_take_the_wire_shape_their_parent_needs() {
+ let channel = MessageParent::Channel(Uuid::from_u128(1));
+ let opened = AgentSessionMacroEvent::from_decision(
+ TriggerDecision::Open {
+ bot_id: BotId::TEST_A,
+ message: posted(channel.clone(), None),
+ },
+ Some(ChannelType::Team),
+ )
+ .expect("a channel type was supplied");
+ assert_eq!(opened.key(), BotId::TEST_A.to_string());
+ let AgentTriggerTopicEvent::New(NewAgentSessionEvent::TopLevelMentioned(mentioned)) =
+ &opened.event().event
+ else {
+ panic!("a channel mention takes the channel-only shape: {opened:?}");
+ };
+ assert_eq!(mentioned.message.channel_id, Uuid::from_u128(1));
+ assert_eq!(mentioned.message.channel_type, ChannelType::Team);
+ assert_eq!(mentioned.message.thread_id, None);
+
+ let followed = AgentSessionMacroEvent::from_decision(
+ TriggerDecision::Existing {
+ bot_id: BotId::TEST_A,
+ session_id: AgentSessionId::TEST_A,
+ kind: ThreadMessageKind::Inferred,
+ message: posted(channel.clone(), Some(Uuid::from_u128(7))),
+ },
+ Some(ChannelType::Public),
+ )
+ .expect("a channel type was supplied");
+ let AgentTriggerTopicEvent::Existing(ExistingAgentSessionEvent::Channel(metadata)) =
+ &followed.event().event
+ else {
+ panic!("a channel follow-up takes the channel-only shape: {followed:?}");
+ };
+ assert_eq!(metadata.kind, ThreadMessageKind::Inferred);
+ assert_eq!(metadata.message.thread_id, Some(Uuid::from_u128(7)));
+
+ let document_opened = AgentSessionMacroEvent::from_decision(
+ TriggerDecision::Open {
+ bot_id: BotId::TEST_B,
+ message: posted(document(), None),
+ },
+ None,
+ )
+ .expect("documents need no channel type");
+ assert!(matches!(
+ &document_opened.event().event,
+ AgentTriggerTopicEvent::New(NewAgentSessionEvent::Mentioned(mentioned))
+ if mentioned.message.parent == document()
+ ));
+ let document_followed = AgentSessionMacroEvent::from_decision(
+ TriggerDecision::Existing {
+ bot_id: BotId::TEST_B,
+ session_id: AgentSessionId::TEST_B,
+ kind: ThreadMessageKind::ExplicitReply,
+ message: posted(document(), Some(Uuid::from_u128(7))),
+ },
+ Some(ChannelType::Public),
+ )
+ .expect("a stray channel type is ignored for documents");
+ assert!(matches!(
+ &document_followed.event().event,
+ AgentTriggerTopicEvent::Existing(ExistingAgentSessionEvent::Thread(metadata))
+ if metadata.session_id == AgentSessionId::TEST_B
+ ));
+
+ assert_eq!(
+ AgentSessionMacroEvent::from_decision(
+ TriggerDecision::Open {
+ bot_id: BotId::TEST_A,
+ message: posted(channel, None),
+ },
+ None,
+ )
+ .unwrap_err(),
+ MissingChannelType {
+ channel_id: Uuid::from_u128(1)
+ }
+ );
+}
+
+#[test]
+fn channel_shape_round_trips_through_the_parent_aware_post() {
+ let original = channel_message();
+ let parent_aware = posted_from_channel_event(&original);
+ assert_eq!(parent_aware.root_id, original.message_id);
+ let back = channel_event_from_posted(&parent_aware, Uuid::from_u128(1), ChannelType::Private);
+ assert_eq!(back, original);
+}
+
#[test]
fn event_names_match_the_wire() {
use strum::IntoEnumIterator as _;
@@ -74,15 +288,15 @@ fn event_names_match_the_wire() {
AgentTriggerTopicEvent::New(NewAgentSessionEvent::TopLevelMentioned(
AgentBotMentionedEvent {
bot_id: BotId::TEST_A,
- message: message(),
+ message: channel_message(),
},
)),
AgentTriggerTopicEvent::Existing(ExistingAgentSessionEvent::Channel(
ChannelEventMetadata {
bot_id: BotId::TEST_A,
session_id: AgentSessionId::TEST_A,
- kind: ChannelKind::MentionThread,
- message: message(),
+ kind: ThreadMessageKind::MentionThread,
+ message: channel_message(),
},
)),
]
@@ -99,13 +313,13 @@ fn event_names_match_the_wire() {
#[test]
fn channel_kinds_round_trip_in_snake_case() {
for (kind, wire) in [
- (ChannelKind::MentionThread, "mention_thread"),
- (ChannelKind::ExplicitReply, "explicit_reply"),
- (ChannelKind::Inferred, "inferred"),
+ (ThreadMessageKind::MentionThread, "mention_thread"),
+ (ThreadMessageKind::ExplicitReply, "explicit_reply"),
+ (ThreadMessageKind::Inferred, "inferred"),
] {
let value = serde_json::to_value(kind).expect("serialize kind");
assert_eq!(value, json!(wire));
- let parsed: ChannelKind = serde_json::from_value(value).expect("deserialize kind");
+ let parsed: ThreadMessageKind = serde_json::from_value(value).expect("deserialize kind");
assert_eq!(parsed, kind);
}
}
diff --git a/crates/agent_trigger/src/domain/mod.rs b/crates/agent_trigger/src/domain/mod.rs
index 6c98e84cd0..5e1e13131d 100644
--- a/crates/agent_trigger/src/domain/mod.rs
+++ b/crates/agent_trigger/src/domain/mod.rs
@@ -1,5 +1,6 @@
pub mod broker_events;
pub mod processing;
pub mod service;
+pub mod sources;
pub mod thread_window;
pub mod yield_event;
diff --git a/crates/agent_trigger/src/domain/processing.rs b/crates/agent_trigger/src/domain/processing.rs
index aa19d2f689..d485be1d4b 100644
--- a/crates/agent_trigger/src/domain/processing.rs
+++ b/crates/agent_trigger/src/domain/processing.rs
@@ -1,22 +1,51 @@
-//! Shared channel-event processing for agent trigger consumers.
+//! Shared committed-post processing for agent trigger consumers.
use agent_session::domain::error::AgentSessionError;
use agent_session::domain::ports::AgentSessionRepo;
-use channels::domain::broker_events::{ChannelMacroEvent, ChannelTopicEvent};
+use channels::domain::models::ChannelType;
use macro_event_broker::{EventBrokerError, MacroEvent as _, MacroEventBroker};
+use macro_uuid::Uuid;
+use messages::domain::events::MessagePostedMetadata;
+use messages::domain::models::MessageParent;
-use super::broker_events::AgentTriggerEventName;
+use super::broker_events::{AgentSessionMacroEvent, AgentTriggerEventName};
use super::service::{
AgentBotLookup, AgentTriggerService, ChannelParticipationLookup, ExplicitReplyExtractor,
ImplicitTriggerJudge, TeamMembershipLookup, ThreadHistory,
};
-/// Failure while evaluating or publishing one channel event.
+/// One committed post to evaluate, with the channel's type when the source
+/// already carried it. A channel-parent trigger event keeps the channel-only
+/// wire shape, which names the channel's type; the parent-aware post does not,
+/// so it is looked up when absent.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct TriggerInput {
+ /// The committed post.
+ pub posted: MessagePostedMetadata,
+ /// The channel's type, when the source event carried it.
+ pub channel_type: Option<ChannelType>,
+}
+
+/// Channel facts a channel-parent trigger event still carries for consumers
+/// built before message parents.
+#[cfg_attr(test, mockall::automock)]
+pub trait ChannelTypeLookup: Send + Sync + 'static {
+ /// The channel's type, or `None` when no such channel exists.
+ fn channel_type(
+ &self,
+ channel_id: Uuid,
+ ) -> impl Future<Output = agent_session::domain::error::Result<Option<ChannelType>>> + Send;
+}
+
+/// Failure while evaluating or publishing one message event.
#[derive(Debug, thiserror::Error)]
-pub enum ProcessChannelEventError {
+pub enum ProcessMessageEventError {
/// Trigger evaluation could not read its session or bot context.
#[error(transparent)]
Evaluate(#[from] AgentSessionError),
+ /// The channel's type could not be read for a channel-parent event.
+ #[error("failed to read the channel type for a trigger event: {0}")]
+ ChannelType(#[source] AgentSessionError),
/// A yielded event could not be queued for publication.
#[error(transparent)]
Publish(#[from] EventBrokerError),
@@ -25,15 +54,28 @@ pub enum ProcessChannelEventError {
PublishTask(#[source] tokio::task::JoinError),
}
-/// Evaluate and publish all agent triggers yielded by one channel event.
+/// Evaluate and publish all agent triggers yielded by one committed post.
///
/// Transport adapters retain ownership of decode and offset commit so their
-/// `kafka.process` span can cover the complete record lifecycle.
-pub async fn process_channel_event<Repo, Bots, Teams, Channels, Replies, Judge, History, Broker>(
+/// `kafka.process` span can cover the complete record lifecycle. A channel
+/// whose row is gone yields nothing rather than an error: nothing downstream
+/// could act on it, and an error would only wedge the partition.
+pub async fn process_message_event<
+ Repo,
+ Bots,
+ Teams,
+ Channels,
+ Replies,
+ Judge,
+ History,
+ Kinds,
+ Broker,
+>(
trigger: &AgentTriggerService<Repo, Bots, Teams, Channels, Replies, Judge, History>,
publisher: &Broker,
- event: &ChannelMacroEvent,
-) -> Result<(), ProcessChannelEventError>
+ kinds: &Kinds,
+ input: &TriggerInput,
+) -> Result<(), ProcessMessageEventError>
where
Repo: AgentSessionRepo,
Bots: AgentBotLookup,
@@ -42,23 +84,49 @@ where
Replies: ExplicitReplyExtractor,
Judge: ImplicitTriggerJudge,
History: ThreadHistory,
+ Kinds: ChannelTypeLookup,
Broker: MacroEventBroker,
{
- let ChannelTopicEvent::MessagePosted(posted) = &event.event().event else {
- return Ok(());
- };
- tracing::Span::current().record("macro.event.type", "channel.message_posted");
+ tracing::Span::current().record("macro.event.type", "message.posted");
+ let posted = &input.posted;
- let yielded_events = trigger.evaluate(posted).await?;
+ let decisions = trigger.evaluate(posted).await?;
tracing::info!(
message_id = %posted.message_id,
- yielded_count = yielded_events.len(),
- "agent trigger evaluated channel message"
+ yielded_count = decisions.len(),
+ "agent trigger evaluated message"
);
- if yielded_events.is_empty() {
+ if decisions.is_empty() {
tracing::debug!(message_id = %posted.message_id, "agent trigger yielded no event");
+ return Ok(());
}
- for yielded in yielded_events {
+
+ let channel_type = match (&posted.parent, input.channel_type) {
+ (MessageParent::Channel(_), Some(channel_type)) => Some(channel_type),
+ (MessageParent::Channel(channel_id), None) => {
+ match kinds
+ .channel_type(*channel_id)
+ .await
+ .map_err(ProcessMessageEventError::ChannelType)?
+ {
+ Some(channel_type) => Some(channel_type),
+ None => {
+ tracing::warn!(
+ message_id = %posted.message_id,
+ %channel_id,
+ dropped = decisions.len(),
+ "channel of a triggering message no longer exists; dropping its agent events"
+ );
+ return Ok(());
+ }
+ }
+ }
+ (MessageParent::Document(_), _) => None,
+ };
+
+ for decision in decisions {
+ let yielded = AgentSessionMacroEvent::from_decision(decision, channel_type)
+ .map_err(|error| AgentSessionError::Unknown(error.into()))?;
let event_type: &'static str = AgentTriggerEventName::from(&yielded.event().event).into();
tracing::info!(
macro.event.id = %yielded.event().event_id,
@@ -68,7 +136,7 @@ where
publisher
.send_event(&yielded)?
.await
- .map_err(ProcessChannelEventError::PublishTask)??;
+ .map_err(ProcessMessageEventError::PublishTask)??;
}
Ok(())
diff --git a/crates/agent_trigger/src/domain/service.rs b/crates/agent_trigger/src/domain/service.rs
index a5a12b610d..1953b24421 100644
--- a/crates/agent_trigger/src/domain/service.rs
+++ b/crates/agent_trigger/src/domain/service.rs
@@ -1,4 +1,4 @@
-//! Orchestration for evaluating one posted channel message.
+//! Orchestration for evaluating one posted message.
use std::collections::HashSet;
@@ -6,19 +6,21 @@ use std::collections::HashSet;
mod test;
use agent_session::domain::error::Result;
-use agent_session::domain::model::{AgentSession, AgentSessionId, ChannelSession};
+use agent_session::domain::model::{AgentSession, AgentSessionId, ThreadSession};
use agent_session::domain::ports::AgentSessionRepo;
use bot_id::BotId;
use bots::domain::models::{Agent, AgentChannelScope, Bot, BotKind, BotOwner};
-use channels::domain::broker_events::ChannelMessagePostedMetadata;
-use channels::domain::side_effects::bot_mention_ids;
+use entity_access::domain::models::EntityAccessReceipt;
+use messages::domain::mentions::bot_mention_ids;
+use messages::domain::service::MessageWrite;
+use messages::domain::{events::MessagePostedMetadata, models::MessageParent};
use channel_sender::ChannelSender;
use macro_user_id::cowlike::CowLike;
use macro_user_id::user_id::MacroUserIdStr;
use macro_uuid::Uuid;
-use crate::domain::broker_events::{AgentSessionMacroEvent, ChannelEventMetadata, ChannelKind};
+use crate::domain::broker_events::{ThreadMessageKind, TriggerDecision};
use crate::domain::thread_window::{ThreadMessage, render_transcript, thread_window};
use crate::domain::yield_event::{
AgentSessionEventDecision, NoEventReason, PotentialTriggerEvent, yield_event,
@@ -76,9 +78,9 @@ pub trait ChannelParticipationLookup: Send + Sync + 'static {
/// and which message they pointed at.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ExtractedExplicitReply {
- /// Channel containing the targeted message.
- pub channel_id: String,
- /// Targeted channel message.
+ /// Entity containing the targeted message.
+ pub parent: MessageParent,
+ /// Targeted message.
pub target_message_id: String,
/// Thread containing the targeted message.
pub target_thread_id: String,
@@ -99,15 +101,49 @@ pub trait ExplicitReplyExtractor: Send + Sync + 'static {
) -> impl Future<Output = Result<Option<ExtractedExplicitReply>>> + Send;
}
+/// A current invocation capability binding the actor, parent, and thread root.
+/// It is minted again when evaluating queued work, rather than persisted in events.
+#[derive(Debug, Clone)]
+pub struct AuthorizedInvocation {
+ access: EntityAccessReceipt<MessageWrite>,
+ root_id: Uuid,
+}
+
+impl AuthorizedInvocation {
+ /// Bind a verified posting capability on the parent to the thread it invokes in.
+ #[must_use]
+ pub fn new(access: EntityAccessReceipt<MessageWrite>, root_id: Uuid) -> Self {
+ Self { access, root_id }
+ }
+
+ /// The actor's verified capability on the parent.
+ #[must_use]
+ pub fn access(&self) -> &EntityAccessReceipt<MessageWrite> {
+ &self.access
+ }
+
+ /// The thread root the invocation is bound to.
+ #[must_use]
+ pub fn root_id(&self) -> Uuid {
+ self.root_id
+ }
+}
+
/// Reads whole threads, so an unmentioned message can be judged against the
/// conversation it landed in.
#[cfg_attr(test, mockall::automock)]
pub trait ThreadHistory: Send + Sync + 'static {
- /// Every message of the thread rooted at `thread_id`, oldest first.
+ /// Recheck that the invoking user may still write to this conversation.
+ fn authorize_invocation(
+ &self,
+ user: &MacroUserIdStr<'static>,
+ parent: &MessageParent,
+ root_id: Uuid,
+ ) -> impl Future<Output = Result<Option<AuthorizedInvocation>>> + Send;
+ /// Live history from the exact origin covered by the invocation capability.
fn thread_messages(
&self,
- channel_id: Uuid,
- thread_id: Uuid,
+ invocation: &AuthorizedInvocation,
) -> impl Future<Output = Result<Vec<ThreadMessage>>> + Send;
}
@@ -120,12 +156,12 @@ pub trait ImplicitTriggerJudge: Send + Sync + 'static {
/// it, empty when the thread could not be read.
fn is_addressed_to_agent(
&self,
- posted: &ChannelMessagePostedMetadata,
+ posted: &MessagePostedMetadata,
transcript: &str,
) -> impl Future<Output = Result<bool>> + Send;
}
-/// Looks up the session context for a channel message and evaluates its trigger rule.
+/// Looks up the session context for a message and evaluates its trigger rule.
pub struct AgentTriggerService<Repo, Bots, Teams, Channels, Replies, Judge, History> {
sessions: Repo,
bots: Bots,
@@ -176,7 +212,7 @@ where
/// legacy agent-backed bots use explicit channel participation.
async fn agent_is_available(
&self,
- posted: &ChannelMessagePostedMetadata,
+ posted: &MessagePostedMetadata,
bot_id: BotId,
) -> Result<bool> {
let Some(caller) = posted.sender.as_user().cloned().map(CowLike::into_owned) else {
@@ -187,6 +223,15 @@ where
if !agent.bot.has_agent {
return Ok(false);
}
+ // Channel selection restricts channel placement. Document invocation
+ // requires ownership or team membership and is independently bounded
+ // by the invoking user's document access at execution time.
+ if matches!(posted.parent, MessageParent::Document(_)) {
+ return self.owner_allows(&caller, agent.bot.owner.as_ref()).await;
+ }
+ let MessageParent::Channel(channel_id) = posted.parent else {
+ unreachable!()
+ };
return match agent.channel_scope {
AgentChannelScope::All => match agent.bot.owner {
Some(BotOwner::User { user_id }) => Ok(user_id == caller.as_ref()),
@@ -197,7 +242,7 @@ where
},
AgentChannelScope::Selected => {
self.channels
- .bot_active_in_channel(posted.channel_id, bot_id)
+ .bot_active_in_channel(channel_id, bot_id)
.await
}
};
@@ -211,34 +256,58 @@ where
}
match bot.kind {
BotKind::System => Ok(true),
- BotKind::Owned => {
- self.channels
- .bot_active_in_channel(posted.channel_id, bot_id)
- .await
+ BotKind::Owned => match &posted.parent {
+ MessageParent::Channel(channel_id) => {
+ self.channels
+ .bot_active_in_channel(*channel_id, bot_id)
+ .await
+ }
+ MessageParent::Document(_) => self.owner_allows(&caller, bot.owner.as_ref()).await,
+ },
+ }
+ }
+
+ async fn owner_allows(
+ &self,
+ caller: &MacroUserIdStr<'static>,
+ owner: Option<&BotOwner>,
+ ) -> Result<bool> {
+ match owner {
+ Some(BotOwner::User { user_id }) => Ok(user_id == caller.as_ref()),
+ Some(BotOwner::Team { team_id }) => {
+ self.teams.user_has_team(caller.clone(), *team_id).await
}
+ None => Ok(false),
}
}
- /// Evaluates one channel message for every mentioned bot.
+ /// Evaluates a posted message for every mentioned bot.
#[tracing::instrument(err, skip(self, posted), fields(
- channel_id = %posted.channel_id,
+ parent = ?posted.parent,
message_id = %posted.message_id,
thread_id = ?posted.thread_id,
- channel.message.scope = tracing::field::Empty,
+ message.scope = tracing::field::Empty,
agent.mention.bot_count = tracing::field::Empty,
))]
- pub async fn evaluate(
- &self,
- posted: &ChannelMessagePostedMetadata,
- ) -> Result<Vec<AgentSessionMacroEvent>> {
+ pub async fn evaluate(&self, posted: &MessagePostedMetadata) -> Result<Vec<TriggerDecision>> {
+ let Some(user) = posted.sender.as_user().cloned().map(CowLike::into_owned) else {
+ return Ok(Vec::new());
+ };
+ let Some(invocation) = self
+ .history
+ .authorize_invocation(&user, &posted.parent, posted.root_id())
+ .await?
+ else {
+ return Ok(Vec::new());
+ };
let mut mentioned = bot_mention_ids(&posted.mentions);
mentioned.sort_by_key(ToString::to_string);
tracing::Span::current().record(
- "channel.message.scope",
+ "message.scope",
if posted.thread_id.is_some() {
"thread"
} else {
- "channel_top_level"
+ "root"
},
);
tracing::Span::current().record("agent.mention.bot_count", mentioned.len());
@@ -248,7 +317,7 @@ where
if mentioned.is_empty() {
if let Some(event) = self.evaluate_bot(posted, None, &mut seen_sessions).await? {
events.push(event);
- } else if let Some(event) = self.evaluate_implicit(posted).await? {
+ } else if let Some(event) = self.evaluate_implicit(posted, &invocation).await? {
events.push(event);
}
return Ok(events);
@@ -270,7 +339,7 @@ where
err,
skip(self, posted, seen_sessions),
fields(
- channel_id = %posted.channel_id,
+ parent = ?posted.parent,
message_id = %posted.message_id,
bot_id = ?mentioned_bot,
agent.trigger.outcome = tracing::field::Empty,
@@ -278,14 +347,20 @@ where
)]
async fn evaluate_bot(
&self,
- posted: &ChannelMessagePostedMetadata,
+ posted: &MessagePostedMetadata,
mentioned_bot: Option<BotId>,
seen_sessions: &mut HashSet<AgentSessionId>,
- ) -> Result<Option<AgentSessionMacroEvent>> {
+ ) -> Result<Option<TriggerDecision>> {
let existing = self
.sessions
- .find_for_channel(posted.thread_id, mentioned_bot)
+ .find_for_thread(posted.thread_id, mentioned_bot)
.await?;
+ if let ThreadSession::CreatedFromThread(session) = &existing
+ && (session.thread_parent.as_ref() != Some(&posted.parent)
+ || session.thread_id != posted.thread_id)
+ {
+ return Ok(None);
+ }
if let Some(session_id) = session_id(&existing)
&& !seen_sessions.insert(session_id)
{
@@ -295,15 +370,15 @@ where
return Ok(None);
}
let bot = match &existing {
- ChannelSession::CreatedFromThread(session) => Some(session.bot_id),
- ChannelSession::None => mentioned_bot,
+ ThreadSession::CreatedFromThread(session) => Some(session.bot_id),
+ ThreadSession::None => mentioned_bot,
};
let available = match bot {
Some(bot_id) => self.agent_is_available(posted, bot_id).await?,
None => false,
};
- let message = PotentialTriggerEvent::Channel {
+ let message = PotentialTriggerEvent::Thread {
posted,
existing: &existing,
mentioned_bot,
@@ -311,8 +386,8 @@ where
match yield_event(&message, available) {
AgentSessionEventDecision::Event(event) => {
let outcome = match existing {
- ChannelSession::None => "top_level_mentioned",
- ChannelSession::CreatedFromThread(_) => "mention_thread",
+ ThreadSession::None => "top_level_mentioned",
+ ThreadSession::CreatedFromThread(_) => "mention_thread",
};
tracing::Span::current().record("agent.trigger.outcome", outcome);
Ok(Some(event))
@@ -337,11 +412,12 @@ where
///
/// Extractor and judge failures are treated as "no" rather than propagated:
/// implicit triggering is best-effort, and an outage must not wedge the
- /// channel firehose or fabricate forwards.
+ /// message stream or fabricate forwards.
async fn evaluate_implicit(
&self,
- posted: &ChannelMessagePostedMetadata,
- ) -> Result<Option<AgentSessionMacroEvent>> {
+ posted: &MessagePostedMetadata,
+ invocation: &AuthorizedInvocation,
+ ) -> Result<Option<TriggerDecision>> {
let Some(thread_id) = posted.thread_id else {
return Ok(None);
};
@@ -352,7 +428,10 @@ where
}
let mut candidates = Vec::new();
for session in self.sessions.find_all_for_thread(thread_id).await? {
- if self.agent_is_available(posted, session.bot_id).await? {
+ if session.thread_parent.as_ref() == Some(&posted.parent)
+ && session.thread_id == Some(thread_id)
+ && self.agent_is_available(posted, session.bot_id).await?
+ {
candidates.push(session);
}
}
@@ -362,9 +441,9 @@ where
{
// The reply-target says who it answers on its face, so it needs no
// thread read at all.
- return Ok(Some(channel_event(
+ return Ok(Some(thread_event(
session,
- ChannelKind::ExplicitReply,
+ ThreadMessageKind::ExplicitReply,
posted,
)));
}
@@ -385,10 +464,14 @@ where
};
if self
- .is_addressed_to_agent(posted, &self.transcript(posted, thread_id, &session).await)
+ .is_addressed_to_agent(posted, &self.transcript(posted, invocation, &session).await)
.await
{
- return Ok(Some(channel_event(session, ChannelKind::Inferred, posted)));
+ return Ok(Some(thread_event(
+ session,
+ ThreadMessageKind::Inferred,
+ posted,
+ )));
}
log_no_event(
@@ -405,7 +488,7 @@ where
/// uniquely its originating message.
async fn explicit_reply_session(
&self,
- posted: &ChannelMessagePostedMetadata,
+ posted: &MessagePostedMetadata,
candidates: &[AgentSession],
) -> Option<AgentSession> {
let reply = self
@@ -420,6 +503,9 @@ where
})
.ok()
.flatten()?;
+ if reply.parent != posted.parent || reply.target_thread_id != posted.root_id().to_string() {
+ return None;
+ }
session_targeted_by_reply(candidates, &reply).cloned()
}
@@ -432,15 +518,11 @@ where
/// wedging on a thread read.
async fn transcript(
&self,
- posted: &ChannelMessagePostedMetadata,
- thread_id: Uuid,
+ posted: &MessagePostedMetadata,
+ invocation: &AuthorizedInvocation,
session: &AgentSession,
) -> String {
- let messages = match self
- .history
- .thread_messages(posted.channel_id, thread_id)
- .await
- {
+ let messages = match self.history.thread_messages(invocation).await {
Ok(messages) => messages,
Err(error) => {
tracing::warn!(error = ?error, "thread read failed; judging without thread context");
@@ -468,7 +550,7 @@ where
async fn is_addressed_to_agent(
&self,
- posted: &ChannelMessagePostedMetadata,
+ posted: &MessagePostedMetadata,
transcript: &str,
) -> bool {
self.judge
@@ -482,7 +564,7 @@ where
}
fn log_no_event(
- posted: &ChannelMessagePostedMetadata,
+ posted: &MessagePostedMetadata,
mentioned_bot: Option<BotId>,
reason: NoEventReason,
) {
@@ -494,24 +576,24 @@ fn log_no_event(
);
}
-fn session_id(session: &ChannelSession) -> Option<AgentSessionId> {
+fn session_id(session: &ThreadSession) -> Option<AgentSessionId> {
match session {
- ChannelSession::CreatedFromThread(session) => Some(session.id),
- ChannelSession::None => None,
+ ThreadSession::CreatedFromThread(session) => Some(session.id),
+ ThreadSession::None => None,
}
}
-fn channel_event(
+fn thread_event(
session: AgentSession,
- kind: ChannelKind,
- posted: &ChannelMessagePostedMetadata,
-) -> AgentSessionMacroEvent {
- AgentSessionMacroEvent::channel_event(ChannelEventMetadata {
+ kind: ThreadMessageKind,
+ posted: &MessagePostedMetadata,
+) -> TriggerDecision {
+ TriggerDecision::Existing {
bot_id: session.bot_id,
session_id: session.id,
kind,
message: posted.clone(),
- })
+ }
}
/// The live session the reply-target names: its bot as addressee, or uniquely
diff --git a/crates/agent_trigger/src/domain/service/test.rs b/crates/agent_trigger/src/domain/service/test.rs
index 92cd48e805..d841b7fb53 100644
--- a/crates/agent_trigger/src/domain/service/test.rs
+++ b/crates/agent_trigger/src/domain/service/test.rs
@@ -1,21 +1,17 @@
use super::*;
use agent_session::domain::error::AgentSessionError;
-use agent_session::domain::model::{AgentSession, AgentSessionId, ChannelSession, SessionStatus};
+use agent_session::domain::model::{AgentSession, AgentSessionId, SessionStatus, ThreadSession};
use agent_session::domain::ports::MockAgentSessionRepo;
use bots::domain::models::{Agent, AgentChannelScope, AgentMcpServers, Bot, BotKind, BotOwner};
use channel_sender::ChannelSender;
-use channels::domain::models::ChannelType;
use chrono::Utc;
-use macro_event_broker::MacroEvent;
use macro_user_id::cowlike::CowLike;
use macro_user_id::user_id::MacroUserIdStr;
use macro_uuid::Uuid;
use messages::domain::models::SimpleMention;
-use crate::domain::broker_events::{
- AgentTriggerTopicEvent, ExistingAgentSessionEvent, NewAgentSessionEvent,
-};
+use crate::domain::broker_events::TriggerDecision;
fn user() -> MacroUserIdStr<'static> {
MacroUserIdStr::parse_from_str("macro|[email protected]")
@@ -87,14 +83,14 @@ fn system_bot(bot_id: BotId) -> Bot {
}
}
-fn message(mentions: Vec<SimpleMention>) -> ChannelMessagePostedMetadata {
- ChannelMessagePostedMetadata {
- channel_id: Uuid::from_u128(1),
+fn message(mentions: Vec<SimpleMention>) -> MessagePostedMetadata {
+ MessagePostedMetadata {
+ parent: messages::domain::models::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: ChannelSender::new_from_user(user()),
triggered_by: None,
- channel_type: ChannelType::Public,
content: "hello".to_owned(),
mentions,
attachments: vec![],
@@ -109,8 +105,8 @@ fn session(id: AgentSessionId, bot_id: BotId) -> AgentSession {
id,
name: agent_session::domain::model::DEFAULT_AGENT_SESSION_NAME.to_owned(),
owner_id: MacroUserIdStr::try_from_email("[email protected]").expect("valid macro user id"),
- thread_id: None,
- thread_channel_id: None,
+ thread_id: Some(Uuid::from_u128(3)),
+ thread_parent: Some(MessageParent::Channel(Uuid::from_u128(1))),
originating_message_id: None,
bot_id,
model: "model".to_owned(),
@@ -195,10 +191,43 @@ fn service_reading(
)
}
+fn allow_invocation(
+ user: &MacroUserIdStr<'static>,
+ parent: &MessageParent,
+ root_id: Uuid,
+) -> std::pin::Pin<Box<dyn Future<Output = Result<Option<AuthorizedInvocation>>> + Send>> {
+ use entity_access::domain::models::{
+ AccessLevel, Entity, EntityPermission, EntityType, ParticipantRole,
+ };
+ let access = EntityAccessReceipt::try_new_authenticated_user(
+ user.clone(),
+ Entity {
+ entity_type: match parent {
+ MessageParent::Channel(_) => EntityType::Channel,
+ MessageParent::Document(_) => EntityType::Document,
+ },
+ entity_id: parent.entity_id(),
+ },
+ match parent {
+ MessageParent::Channel(_) => EntityPermission::ChannelRole {
+ role: ParticipantRole::Member,
+ },
+ MessageParent::Document(_) => EntityPermission::AccessLevel {
+ access_level: AccessLevel::Comment,
+ },
+ },
+ )
+ .unwrap();
+ Box::pin(async move { Ok(Some(AuthorizedInvocation { access, root_id })) })
+}
+
/// A history that reads the given messages for any thread.
fn thread_of(messages: Vec<ThreadMessage>) -> MockThreadHistory {
let mut history = MockThreadHistory::new();
- history.expect_thread_messages().returning(move |_, _| {
+ history
+ .expect_authorize_invocation()
+ .returning(allow_invocation);
+ history.expect_thread_messages().returning(move |_| {
let messages = messages.clone();
Box::pin(async move { Ok(messages) })
});
@@ -214,31 +243,43 @@ fn no_implicit() -> (MockExplicitReplyExtractor, MockImplicitTriggerJudge) {
)
}
-fn existing_channel_metadata(
- events: &[AgentSessionMacroEvent],
-) -> &crate::domain::broker_events::ChannelEventMetadata {
+/// The one existing-session decision an evaluation yielded.
+struct ExistingDecision {
+ bot_id: BotId,
+ session_id: AgentSessionId,
+ kind: ThreadMessageKind,
+ message: MessagePostedMetadata,
+}
+
+fn existing_channel_metadata(events: &[TriggerDecision]) -> ExistingDecision {
assert_eq!(events.len(), 1);
- let AgentTriggerTopicEvent::Existing(ExistingAgentSessionEvent::Channel(metadata)) =
- &events[0].event().event
+ let TriggerDecision::Existing {
+ bot_id,
+ session_id,
+ kind,
+ message,
+ } = &events[0]
else {
- panic!("expected a channel event");
+ panic!("expected an existing-session decision, got {:?}", events[0]);
};
- metadata
+ ExistingDecision {
+ bot_id: *bot_id,
+ session_id: *session_id,
+ kind: *kind,
+ message: message.clone(),
+ }
}
fn sessions_without_existing() -> MockAgentSessionRepo {
let mut sessions = MockAgentSessionRepo::new();
sessions
- .expect_find_for_channel()
+ .expect_find_for_thread()
.once()
- .return_once(|_, _| Box::pin(async { Ok(ChannelSession::None) }));
+ .return_once(|_, _| Box::pin(async { Ok(ThreadSession::None) }));
sessions
}
-async fn mention_yields_event(
- posted: &ChannelMessagePostedMetadata,
- facts: impl Into<FactMocks>,
-) -> bool {
+async fn mention_yields_event(posted: &MessagePostedMetadata, facts: impl Into<FactMocks>) -> bool {
let (replies, judge) = no_implicit();
!service(sessions_without_existing(), facts, replies, judge)
.evaluate(posted)
@@ -265,9 +306,14 @@ async fn a_private_global_agent_is_unavailable_to_another_user() {
async fn a_bot_authored_mention_cannot_trigger_an_agent() {
let mut posted = message(vec![mention_of(BotId::TEST_A)]);
posted.sender = ChannelSender::new_from_bot(BotId::TEST_B);
- let bots = MockAgentBotLookup::new();
-
- assert!(!mention_yields_event(&posted, bots).await);
+ let (replies, judge) = no_implicit();
+ let service = service(
+ MockAgentSessionRepo::new(),
+ MockAgentBotLookup::new(),
+ replies,
+ judge,
+ );
+ assert!(service.evaluate(&posted).await.unwrap().is_empty());
}
#[tokio::test]
@@ -342,7 +388,7 @@ async fn a_selected_agent_requires_active_channel_membership() {
.channels
.expect_bot_active_in_channel()
.with(
- mockall::predicate::eq(posted.channel_id),
+ mockall::predicate::eq(Uuid::from_u128(1)),
mockall::predicate::eq(BotId::TEST_A),
)
.once()
@@ -371,7 +417,7 @@ async fn an_active_selected_agent_is_available_to_channel_members() {
.channels
.expect_bot_active_in_channel()
.with(
- mockall::predicate::eq(posted.channel_id),
+ mockall::predicate::eq(Uuid::from_u128(1)),
mockall::predicate::eq(BotId::TEST_A),
)
.once()
@@ -399,7 +445,7 @@ async fn forwards_a_mentioned_thread_reply_to_its_session() {
let posted = message(vec![mention_of(BotId::TEST_A)]);
let mut sessions = MockAgentSessionRepo::new();
sessions
- .expect_find_for_channel()
+ .expect_find_for_thread()
.with(
mockall::predicate::eq(posted.thread_id),
mockall::predicate::eq(Some(BotId::TEST_A)),
@@ -407,7 +453,7 @@ async fn forwards_a_mentioned_thread_reply_to_its_session() {
.once()
.return_once(|_, _| {
Box::pin(async {
- Ok(ChannelSession::CreatedFromThread(session(
+ Ok(ThreadSession::CreatedFromThread(session(
AgentSessionId::TEST_A,
BotId::TEST_A,
)))
@@ -451,10 +497,10 @@ async fn evaluates_every_mentioned_agent_bot() {
let thread_id = posted.thread_id;
let mut sessions = MockAgentSessionRepo::new();
sessions
- .expect_find_for_channel()
+ .expect_find_for_thread()
.withf(move |actual_thread_id, bot_id| *actual_thread_id == thread_id && bot_id.is_some())
.times(2)
- .returning(|_, _| Box::pin(async { Ok(ChannelSession::None) }));
+ .returning(|_, _| Box::pin(async { Ok(ThreadSession::None) }));
let mut bots = MockAgentBotLookup::new();
bots.expect_get_agent()
.times(2)
@@ -466,11 +512,9 @@ async fn evaluates_every_mentioned_agent_bot() {
assert_eq!(events.len(), 2);
let mut event_bots: Vec<_> = events
.iter()
- .map(|event| match &event.event().event {
- AgentTriggerTopicEvent::New(NewAgentSessionEvent::TopLevelMentioned(mentioned)) => {
- mentioned.bot_id
- }
- other => panic!("expected a new-session event, got {other:?}"),
+ .map(|event| match event {
+ TriggerDecision::Open { bot_id, .. } => *bot_id,
+ other => panic!("expected a new-session decision, got {other:?}"),
})
.collect();
event_bots.sort_by_key(ToString::to_string);
@@ -482,13 +526,13 @@ async fn evaluates_a_repeated_bot_mention_once() {
let posted = message(vec![mention_of(BotId::TEST_A), mention_of(BotId::TEST_A)]);
let mut sessions = MockAgentSessionRepo::new();
sessions
- .expect_find_for_channel()
+ .expect_find_for_thread()
.with(
mockall::predicate::eq(posted.thread_id),
mockall::predicate::eq(Some(BotId::TEST_A)),
)
.once()
- .return_once(|_, _| Box::pin(async { Ok(ChannelSession::None) }));
+ .return_once(|_, _| Box::pin(async { Ok(ThreadSession::None) }));
let mut bots = MockAgentBotLookup::new();
bots.expect_get_agent()
.with(mockall::predicate::eq(BotId::TEST_A))
@@ -499,12 +543,10 @@ async fn evaluates_a_repeated_bot_mention_once() {
let events = service.evaluate(&posted).await.expect("evaluate message");
assert_eq!(events.len(), 1);
- let AgentTriggerTopicEvent::New(NewAgentSessionEvent::TopLevelMentioned(mentioned)) =
- &events[0].event().event
- else {
- panic!("expected a new-session event");
+ let TriggerDecision::Open { bot_id, .. } = &events[0] else {
+ panic!("expected a new-session decision");
};
- assert_eq!(mentioned.bot_id, BotId::TEST_A);
+ assert_eq!(*bot_id, BotId::TEST_A);
}
#[tokio::test]
@@ -512,9 +554,9 @@ async fn ignores_a_mentioned_bot_without_an_agent() {
let posted = message(vec![mention_of(BotId::TEST_A)]);
let mut sessions = MockAgentSessionRepo::new();
sessions
- .expect_find_for_channel()
+ .expect_find_for_thread()
.once()
- .return_once(|_, _| Box::pin(async { Ok(ChannelSession::None) }));
+ .return_once(|_, _| Box::pin(async { Ok(ThreadSession::None) }));
let mut bots = MockAgentBotLookup::new();
bots.expect_get_agent()
.with(mockall::predicate::eq(BotId::TEST_A))
@@ -541,11 +583,11 @@ async fn deduplicates_a_session_found_for_multiple_mentions() {
let posted = message(vec![mention_of(BotId::TEST_A), mention_of(BotId::TEST_B)]);
let mut sessions = MockAgentSessionRepo::new();
sessions
- .expect_find_for_channel()
+ .expect_find_for_thread()
.times(2)
.returning(|_, _| {
Box::pin(async {
- Ok(ChannelSession::CreatedFromThread(session(
+ Ok(ThreadSession::CreatedFromThread(session(
AgentSessionId::TEST_A,
BotId::TEST_A,
)))
@@ -569,9 +611,9 @@ async fn deduplicates_a_session_found_for_multiple_mentions() {
fn implicit_sessions(found: Vec<AgentSession>) -> MockAgentSessionRepo {
let mut sessions = MockAgentSessionRepo::new();
sessions
- .expect_find_for_channel()
+ .expect_find_for_thread()
.once()
- .return_once(|_, _| Box::pin(async { Ok(ChannelSession::None) }));
+ .return_once(|_, _| Box::pin(async { Ok(ThreadSession::None) }));
sessions
.expect_find_all_for_thread()
.with(mockall::predicate::eq(Uuid::from_u128(3)))
@@ -598,7 +640,7 @@ fn extractor(result: Result<Option<ExtractedExplicitReply>>) -> MockExplicitRepl
fn reply_to_bot(bot_id: BotId) -> ExtractedExplicitReply {
ExtractedExplicitReply {
- channel_id: Uuid::from_u128(1).to_string(),
+ parent: MessageParent::Channel(Uuid::from_u128(1)),
target_message_id: Uuid::from_u128(10).to_string(),
target_thread_id: Uuid::from_u128(3).to_string(),
display_text: "please fix this".to_owned(),
@@ -612,7 +654,7 @@ fn reply_to_user() -> ExtractedExplicitReply {
fn reply_to_user_message(target_message_id: Uuid) -> ExtractedExplicitReply {
ExtractedExplicitReply {
- channel_id: Uuid::from_u128(1).to_string(),
+ parent: MessageParent::Channel(Uuid::from_u128(1)),
target_message_id: target_message_id.to_string(),
target_thread_id: Uuid::from_u128(3).to_string(),
display_text: "please fix this".to_owned(),
@@ -666,7 +708,7 @@ async fn an_explicit_reply_in_a_session_thread_triggers_without_a_mention() {
let metadata = existing_channel_metadata(&events);
assert_eq!(metadata.session_id, AgentSessionId::TEST_A);
assert_eq!(metadata.bot_id, BotId::TEST_A);
- assert_eq!(metadata.kind, ChannelKind::ExplicitReply);
+ assert_eq!(metadata.kind, ThreadMessageKind::ExplicitReply);
}
#[tokio::test]
@@ -682,7 +724,7 @@ async fn a_message_the_judge_reads_as_addressed_triggers_as_inferred() {
let events = service.evaluate(&posted).await.expect("evaluate message");
let metadata = existing_channel_metadata(&events);
- assert_eq!(metadata.kind, ChannelKind::Inferred);
+ assert_eq!(metadata.kind, ThreadMessageKind::Inferred);
}
#[tokio::test]
@@ -725,11 +767,7 @@ async fn a_thread_without_sessions_never_consults_the_judge() {
async fn a_bot_sender_never_triggers_implicitly() {
let mut posted = message(vec![]);
posted.sender = ChannelSender::new_from_bot(BotId::TEST_B);
- let mut sessions = MockAgentSessionRepo::new();
- sessions
- .expect_find_for_channel()
- .once()
- .return_once(|_, _| Box::pin(async { Ok(ChannelSession::None) }));
+ let sessions = MockAgentSessionRepo::new();
let (replies, judge) = no_implicit();
let service = service(sessions, MockAgentBotLookup::new(), replies, judge);
@@ -814,7 +852,7 @@ async fn a_failing_extractor_falls_through_to_the_judge() {
let events = service.evaluate(&posted).await.expect("evaluate message");
assert_eq!(
existing_channel_metadata(&events).kind,
- ChannelKind::Inferred
+ ThreadMessageKind::Inferred
);
}
@@ -866,7 +904,7 @@ async fn the_judge_reads_the_thread_around_the_agent() {
let events = service.evaluate(&posted).await.expect("evaluate message");
assert_eq!(
existing_channel_metadata(&events).kind,
- ChannelKind::Inferred
+ ThreadMessageKind::Inferred
);
}
@@ -875,6 +913,9 @@ async fn an_explicit_reply_never_reads_the_thread() {
let posted = message(vec![]);
let sessions = implicit_sessions(vec![thread_session(AgentSessionId::TEST_A, BotId::TEST_A)]);
let mut history = MockThreadHistory::new();
+ history
+ .expect_authorize_invocation()
+ .returning(allow_invocation);
history.expect_thread_messages().never();
let service = service_reading(
sessions,
@@ -887,7 +928,7 @@ async fn an_explicit_reply_never_reads_the_thread() {
let events = service.evaluate(&posted).await.expect("evaluate message");
assert_eq!(
existing_channel_metadata(&events).kind,
- ChannelKind::ExplicitReply
+ ThreadMessageKind::ExplicitReply
);
}
@@ -896,7 +937,10 @@ async fn an_unreadable_thread_still_judges_the_message_alone() {
let posted = message(vec![]);
let sessions = implicit_sessions(vec![thread_session(AgentSessionId::TEST_A, BotId::TEST_A)]);
let mut history = MockThreadHistory::new();
- history.expect_thread_messages().once().return_once(|_, _| {
+ history
+ .expect_authorize_invocation()
+ .returning(allow_invocation);
+ history.expect_thread_messages().once().return_once(|_| {
Box::pin(async {
Err(AgentSessionError::Unknown(anyhow::anyhow!(
"channels database unavailable"
@@ -914,7 +958,7 @@ async fn an_unreadable_thread_still_judges_the_message_alone() {
let events = service.evaluate(&posted).await.expect("evaluate message");
assert_eq!(
existing_channel_metadata(&events).kind,
- ChannelKind::Inferred
+ ThreadMessageKind::Inferred
);
}
@@ -933,7 +977,7 @@ async fn an_explicit_reply_to_the_originating_message_triggers_without_a_mention
let metadata = existing_channel_metadata(&events);
assert_eq!(metadata.session_id, AgentSessionId::TEST_A);
assert_eq!(metadata.bot_id, BotId::TEST_A);
- assert_eq!(metadata.kind, ChannelKind::ExplicitReply);
+ assert_eq!(metadata.kind, ThreadMessageKind::ExplicitReply);
}
#[tokio::test]
@@ -950,7 +994,7 @@ async fn an_explicit_reply_to_another_user_falls_through_to_the_judge() {
let events = service.evaluate(&posted).await.expect("evaluate message");
assert_eq!(
existing_channel_metadata(&events).kind,
- ChannelKind::Inferred
+ ThreadMessageKind::Inferred
);
}
@@ -972,7 +1016,7 @@ async fn an_explicit_reply_to_one_of_two_live_agents_routes_to_that_agent() {
let metadata = existing_channel_metadata(&events);
assert_eq!(metadata.session_id, AgentSessionId::TEST_B);
assert_eq!(metadata.bot_id, BotId::TEST_B);
- assert_eq!(metadata.kind, ChannelKind::ExplicitReply);
+ assert_eq!(metadata.kind, ThreadMessageKind::ExplicitReply);
}
#[tokio::test]
@@ -1020,3 +1064,145 @@ async fn an_explicit_reply_to_a_shared_originating_message_yields_nothing() {
.is_empty()
);
}
+
+#[tokio::test]
+async fn document_mentions_use_owned_agents_without_channel_participation() {
+ for scope in [AgentChannelScope::All, AgentChannelScope::Selected] {
+ let mut posted = message(vec![mention_of(BotId::TEST_A)]);
+ posted.parent = MessageParent::parse("document", "doc").unwrap();
+ let mut bots = MockAgentBotLookup::new();
+ bots.expect_get_agent().once().return_once(move |id| {
+ Box::pin(async move {
+ let mut agent = private_agent(id);
+ agent.channel_scope = scope;
+ Ok(Some(agent))
+ })
+ });
+ assert!(mention_yields_event(&posted, bots).await);
+ }
+}
+
+#[tokio::test]
+async fn document_agents_respect_team_membership() {
+ for allowed in [true, false] {
+ let mut posted = message(vec![mention_of(BotId::TEST_A)]);
+ posted.parent = MessageParent::parse("document", "doc").unwrap();
+ let team_id = Uuid::from_u128(99);
+ let mut facts = FactMocks::from(MockAgentBotLookup::new());
+ facts.bots.expect_get_agent().once().return_once(move |id| {
+ Box::pin(async move {
+ Ok(Some(agent_with(
+ id,
+ BotOwner::Team { team_id },
+ AgentChannelScope::Selected,
+ )))
+ })
+ });
+ facts
+ .teams
+ .expect_user_has_team()
+ .once()
+ .return_once(move |_, _| Box::pin(async move { Ok(allowed) }));
+ assert_eq!(mention_yields_event(&posted, facts).await, allowed);
+ }
+}
+
+#[tokio::test]
+async fn a_document_cannot_invoke_another_users_private_agent() {
+ let mut posted = message(vec![mention_of(BotId::TEST_A)]);
+ posted.parent = MessageParent::parse("document", "doc").unwrap();
+ posted.sender =
+ ChannelSender::new_from_user(MacroUserIdStr::try_from_email("[email protected]").unwrap());
+ let mut bots = MockAgentBotLookup::new();
+ bots.expect_get_agent()
+ .once()
+ .return_once(|id| Box::pin(async move { Ok(Some(private_agent(id))) }));
+ assert!(!mention_yields_event(&posted, bots).await);
+}
+
+#[tokio::test]
+async fn a_queued_document_mention_cannot_invoke_after_access_is_revoked() {
+ let mut posted = message(vec![mention_of(BotId::TEST_A)]);
+ posted.parent = MessageParent::parse("document", "doc").unwrap();
+ let mut history = MockThreadHistory::new();
+ history
+ .expect_authorize_invocation()
+ .once()
+ .return_once(|_, _, _| Box::pin(async { Ok(None) }));
+ let (replies, judge) = no_implicit();
+ let service = service_reading(
+ MockAgentSessionRepo::new(),
+ MockAgentBotLookup::new(),
+ replies,
+ judge,
+ history,
+ );
+ assert!(service.evaluate(&posted).await.unwrap().is_empty());
+}
+
+#[tokio::test]
+async fn document_explicit_followups_route_to_the_existing_agent() {
+ let mut posted = message(vec![]);
+ posted.parent = MessageParent::parse("document", "doc").unwrap();
+ let mut reply = reply_to_bot(BotId::TEST_A);
+ reply.parent = posted.parent.clone();
+ let mut session = thread_session(AgentSessionId::TEST_A, BotId::TEST_A);
+ session.thread_parent = Some(posted.parent.clone());
+ let sessions = implicit_sessions(vec![session]);
+ let mut bots = MockAgentBotLookup::new();
+ bots.expect_get_agent()
+ .returning(|id| Box::pin(async move { Ok(Some(private_agent(id))) }));
+ let service = service(
+ sessions,
+ bots,
+ extractor(Ok(Some(reply))),
+ MockImplicitTriggerJudge::new(),
+ );
+ let events = service.evaluate(&posted).await.unwrap();
+ assert_eq!(
+ existing_channel_metadata(&events).message.parent,
+ posted.parent
+ );
+}
+
+#[tokio::test]
+async fn explicit_reply_cannot_select_a_session_from_a_different_parent_or_root() {
+ for wrong_parent in [true, false] {
+ let posted = message(vec![]);
+ let mut reply = reply_to_bot(BotId::TEST_A);
+ if wrong_parent {
+ reply.parent = MessageParent::parse("document", "another-document").unwrap();
+ } else {
+ reply.target_thread_id = Uuid::from_u128(999).to_string();
+ }
+ let service = service(
+ MockAgentSessionRepo::new(),
+ MockAgentBotLookup::new(),
+ extractor(Ok(Some(reply))),
+ MockImplicitTriggerJudge::new(),
+ );
+ assert!(
+ service
+ .explicit_reply_session(
+ &posted,
+ &[thread_session(AgentSessionId::TEST_A, BotId::TEST_A)]
+ )
+ .await
+ .is_none()
+ );
+ }
+}
+
+#[tokio::test]
+async fn a_session_from_another_parent_cannot_receive_a_document_followup() {
+ let mut posted = message(vec![]);
+ posted.parent = MessageParent::parse("document", "doc").unwrap();
+ let sessions = implicit_sessions(vec![thread_session(AgentSessionId::TEST_A, BotId::TEST_A)]);
+ let service = service(
+ sessions,
+ MockAgentBotLookup::new(),
+ MockExplicitReplyExtractor::new(),
+ MockImplicitTriggerJudge::new(),
+ );
+ assert!(service.evaluate(&posted).await.unwrap().is_empty());
+}
diff --git a/crates/agent_trigger/src/domain/sources.rs b/crates/agent_trigger/src/domain/sources.rs
new file mode 100644
index 0000000000..7b1b8c9614
--- /dev/null
+++ b/crates/agent_trigger/src/domain/sources.rs
@@ -0,0 +1,137 @@
+//! The committed-post events a trigger consumer may read, and how each
+//! becomes the one shape the trigger evaluates.
+//!
+//! `message.posted` on `macro.messages` is the source of record: it carries the
+//! persisted parent, so a mention in a document discussion routes like one in a
+//! channel. `channel.message_posted` on `macro.channels` is the event the
+//! trigger read before parents existed; it decodes into the same shape with a
+//! channel parent, so a deployment can switch back to it with a config change
+//! until the producer retires it. Only one source is read at a time: every
+//! channel post is published on both topics, so reading both would evaluate
+//! every channel mention twice.
+
+#[cfg(test)]
+mod test;
+
+use super::broker_events::posted_from_channel_event;
+use super::processing::TriggerInput;
+use channels::domain::broker_events::{ChannelMacroEvent, ChannelTopicEvent};
+use macro_event_broker::{MacroEvent as _, MacroEventCollection};
+use macro_uuid::Uuid;
+use messages::outbound::broker::{MessageMacroEvent, MessageTopicEvent};
+use serde::Deserialize;
+
+/// Which topic a trigger consumer subscribes to.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum TriggerEventSource {
+ /// `message.posted` on `macro.messages`: channel and document posts alike.
+ #[default]
+ Messages,
+ /// `channel.message_posted` on `macro.channels`: channel posts only.
+ Channels,
+}
+
+impl std::str::FromStr for TriggerEventSource {
+ type Err = String;
+
+ fn from_str(value: &str) -> Result<Self, Self::Err> {
+ match value.trim().to_ascii_lowercase().as_str() {
+ "messages" => Ok(Self::Messages),
+ "channels" => Ok(Self::Channels),
+ other => Err(format!(
+ "unknown agent trigger event source {other:?}; expected `messages` or `channels`"
+ )),
+ }
+ }
+}
+
+macro_event_broker::declare_topics!(MessageTriggerEvents: MessageMacroEvent);
+macro_event_broker::declare_topics!(ChannelTriggerEvents: ChannelMacroEvent);
+
+/// A decoded broker record from one trigger source.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct DecodedTrigger {
+ /// Broker event id, for tracing.
+ pub event_id: Uuid,
+ /// Wire name of the decoded event.
+ pub event_type: &'static str,
+ /// The committed post, when the record was one; other facts on the topic
+ /// carry no trigger.
+ pub posted: Option<TriggerInput>,
+}
+
+/// A topic collection whose records may carry a committed post.
+pub trait TriggerEvents: MacroEventCollection + Send + 'static {
+ /// The source this collection reads.
+ const SOURCE: TriggerEventSource;
+
+ /// Reduce a decoded record to the post it carries, if any.
+ fn into_trigger(self) -> DecodedTrigger;
+}
+
+impl TriggerEvents for MessageTriggerEvents {
+ const SOURCE: TriggerEventSource = TriggerEventSource::Messages;
+
+ fn into_trigger(self) -> DecodedTrigger {
+ let Self::MessageMacroEvent(event) = self;
+ let envelope = event.event();
+ let (event_type, posted) = match &envelope.event {
+ MessageTopicEvent::Posted(posted) => (
+ "message.posted",
+ Some(TriggerInput {
+ posted: posted.clone(),
+ channel_type: None,
+ }),
+ ),
+ MessageTopicEvent::Patched(_) => ("message.patched", None),
+ MessageTopicEvent::Deleted(_) => ("message.deleted", None),
+ MessageTopicEvent::Mentioned(_) => ("message.mentioned", None),
+ MessageTopicEvent::AttachmentCreated(_) => ("message.attachment_created", None),
+ MessageTopicEvent::AttachmentRemoved(_) => ("message.attachment_removed", None),
+ };
+ DecodedTrigger {
+ event_id: envelope.event_id,
+ event_type,
+ posted,
+ }
+ }
+}
+
+impl TriggerEvents for ChannelTriggerEvents {
+ const SOURCE: TriggerEventSource = TriggerEventSource::Channels;
+
+ fn into_trigger(self) -> DecodedTrigger {
+ let Self::ChannelMacroEvent(event) = self;
+ let envelope = event.event();
+ let posted = match &envelope.event {
+ ChannelTopicEvent::MessagePosted(posted) => Some(TriggerInput {
+ posted: posted_from_channel_event(posted),
+ channel_type: Some(posted.channel_type),
+ }),
+ _ => None,
+ };
+ DecodedTrigger {
+ event_id: envelope.event_id,
+ event_type: channel_event_type(&envelope.event),
+ posted,
+ }
+ }
+}
+
+/// The wire name of a channel topic event, as its serde tag spells it.
+fn channel_event_type(event: &ChannelTopicEvent) -> &'static str {
+ match event {
+ ChannelTopicEvent::Created(_) => "channel.created",
+ ChannelTopicEvent::Updated(_) => "channel.updated",
+ ChannelTopicEvent::Deleted(_) => "channel.deleted",
+ ChannelTopicEvent::MessagePosted(_) => "channel.message_posted",
+ ChannelTopicEvent::Mentioned(_) => "channel.mentioned",
+ ChannelTopicEvent::MessagePatched(_) => "channel.message_patched",
+ ChannelTopicEvent::MessageDeleted(_) => "channel.message_deleted",
+ ChannelTopicEvent::MessageAttachmentCreated(_) => "channel.message_attachment_created",
+ ChannelTopicEvent::MessageAttachmentRemoved(_) => "channel.message_attachment_removed",
+ ChannelTopicEvent::ParticipantAdded(_) => "channel.participant_added",
+ ChannelTopicEvent::ParticipantRemoved(_) => "channel.participant_removed",
+ }
+}
diff --git a/crates/agent_trigger/src/domain/sources/test.rs b/crates/agent_trigger/src/domain/sources/test.rs
new file mode 100644
index 0000000000..4ad14d61ee
--- /dev/null
+++ b/crates/agent_trigger/src/domain/sources/test.rs
@@ -0,0 +1,175 @@
+use super::*;
+use channel_sender::ChannelSender;
+use channels::domain::broker_events::{ChannelEventAttachment, ChannelMessagePostedMetadata};
+use channels::domain::models::ChannelType;
+use chrono::Utc;
+use macro_event_broker::{Event, MacroEvent as _, MessageParts};
+use macro_user_id::user_id::MacroUserIdStr;
+use messages::domain::events::MessagePostedMetadata;
+use messages::domain::models::{MessageParent, SimpleMention};
+
+struct Record {
+ topic: &'static str,
+ key: String,
+ payload: Vec<u8>,
+}
+
+impl MessageParts for Record {
+ fn key(&self) -> Option<&str> {
+ Some(&self.key)
+ }
+ fn payload(&self) -> Option<&[u8]> {
+ Some(&self.payload)
+ }
+ fn topic(&self) -> &str {
+ self.topic
+ }
+}
+
+fn record<E: macro_event_broker::MacroEvent>(event: &E) -> Record
+where
+ E::EventPayload: serde::Serialize,
+{
+ Record {
+ topic: <<E::EventPayload as macro_event_broker::TopicEvent>::Topic as macro_event_broker::Topic>::TOPIC_STR,
+ key: event.key().to_owned(),
+ payload: serde_json::to_vec(event.event()).unwrap(),
+ }
+}
+
+fn sender() -> ChannelSender<'static> {
+ ChannelSender::new_from_user(MacroUserIdStr::try_from_email("[email protected]").unwrap())
+}
+
+fn channel_post(thread_id: Option<Uuid>) -> ChannelMessagePostedMetadata {
+ ChannelMessagePostedMetadata {
+ channel_id: Uuid::from_u128(1),
+ message_id: Uuid::from_u128(2),
+ thread_id,
+ sender: sender(),
+ triggered_by: None,
+ channel_type: ChannelType::Public,
+ content: "@claude fix it".to_owned(),
+ mentions: vec![SimpleMention {
+ entity_type: "bot".to_owned(),
+ entity_id: "bot|00000000-0000-0000-0000-00000000b07a".to_owned(),
+ }],
+ attachments: vec![ChannelEventAttachment {
+ attachment_id: Uuid::from_u128(9),
+ entity_type: "document".to_owned(),
+ entity_id: "doc".to_owned(),
+ created_at: Utc::now(),
+ }],
+ created_at: Utc::now(),
+ }
+}
+
+#[test]
+fn a_channel_post_decodes_as_a_channel_parent_rooted_like_the_message_service() {
+ let top_level = posted_from_channel_event(&channel_post(None));
+ assert_eq!(top_level.parent, MessageParent::Channel(Uuid::from_u128(1)));
+ assert_eq!(top_level.root_id, top_level.message_id);
+ assert_eq!(top_level.mentions.len(), 1);
+ assert_eq!(top_level.attachments[0].attachment_id, Uuid::from_u128(9));
+
+ let reply = posted_from_channel_event(&channel_post(Some(Uuid::from_u128(7))));
+ assert_eq!(reply.root_id, Uuid::from_u128(7));
+ assert_eq!(reply.thread_id, Some(Uuid::from_u128(7)));
+}
+
+/// The channel source already knows the channel's type, so the trigger need
+/// not look it up to publish the channel-only wire shape.
+#[test]
+fn the_channel_source_only_triggers_on_posts() {
+ let posted = ChannelMacroEvent::from_event(
+ "1".to_owned(),
+ Event::new(ChannelTopicEvent::MessagePosted(channel_post(None))),
+ );
+ let decoded = ChannelTriggerEvents::decode(&record(&posted)).unwrap();
+ let trigger = decoded.into_trigger();
+ assert_eq!(trigger.event_type, "channel.message_posted");
+ let input = trigger.posted.unwrap();
+ assert_eq!(
+ input.posted.parent,
+ MessageParent::Channel(Uuid::from_u128(1))
+ );
+ assert_eq!(input.channel_type, Some(ChannelType::Public));
+
+ let deleted = ChannelMacroEvent::from_event(
+ "1".to_owned(),
+ Event::new(ChannelTopicEvent::MessageDeleted(
+ channels::domain::broker_events::ChannelMessageDeletedMetadata {
+ channel_id: Uuid::from_u128(1),
+ message_id: Uuid::from_u128(2),
+ thread_id: None,
+ actor: sender(),
+ deleted_at: None,
+ },
+ )),
+ );
+ let trigger = ChannelTriggerEvents::decode(&record(&deleted))
+ .unwrap()
+ .into_trigger();
+ assert_eq!(trigger.event_type, "channel.message_deleted");
+ assert!(trigger.posted.is_none());
+}
+
+#[test]
+fn the_message_source_carries_the_persisted_parent_through() {
+ let posted = MessagePostedMetadata {
+ parent: MessageParent::parse("document", "doc-1").unwrap(),
+ message_id: Uuid::from_u128(2),
+ thread_id: None,
+ root_id: Uuid::from_u128(2),
+ sender: sender(),
+ triggered_by: None,
+ content: "@claude explain".to_owned(),
+ mentions: vec![],
+ attachments: vec![],
+ created_at: Utc::now(),
+ };
+ let event = MessageMacroEvent::posted(posted.clone());
+ let trigger = MessageTriggerEvents::decode(&record(&event))
+ .unwrap()
+ .into_trigger();
+ assert_eq!(trigger.event_type, "message.posted");
+ assert_eq!(
+ trigger.posted,
+ Some(TriggerInput {
+ posted,
+ channel_type: None,
+ })
+ );
+
+ let patched = MessageMacroEvent::patched(messages::domain::events::MessagePatchedMetadata {
+ parent: MessageParent::parse("document", "doc-1").unwrap(),
+ message_id: Uuid::from_u128(2),
+ thread_id: None,
+ root_id: Uuid::from_u128(2),
+ actor: sender(),
+ content: "edited".to_owned(),
+ edited_at: None,
+ updated_at: Utc::now(),
+ });
+ let trigger = MessageTriggerEvents::decode(&record(&patched))
+ .unwrap()
+ .into_trigger();
+ assert_eq!(trigger.event_type, "message.patched");
+ assert!(trigger.posted.is_none());
+}
+
+#[test]
+fn each_source_reads_exactly_one_topic() {
+ assert_eq!(MessageTriggerEvents::topics(), ["macro.messages"]);
+ assert_eq!(ChannelTriggerEvents::topics(), ["macro.channels"]);
+ assert_eq!(
+ "channels".parse::<TriggerEventSource>().unwrap(),
+ TriggerEventSource::Channels
+ );
+ assert_eq!(
+ "MESSAGES".parse::<TriggerEventSource>().unwrap(),
+ TriggerEventSource::Messages
+ );
+ assert!("both".parse::<TriggerEventSource>().is_err());
+ assert_eq!(TriggerEventSource::default(), TriggerEventSource::Messages);
+}
diff --git a/crates/agent_trigger/src/domain/yield_event.rs b/crates/agent_trigger/src/domain/yield_event.rs
index d3e2582004..cde9c62a71 100644
--- a/crates/agent_trigger/src/domain/yield_event.rs
+++ b/crates/agent_trigger/src/domain/yield_event.rs
@@ -1,15 +1,12 @@
//! What one incoming message means for one bot.
-use agent_session::domain::model::{AgentSessionId, ChannelSession};
+use agent_session::domain::model::{AgentSessionId, ThreadSession};
use bot_id::BotId;
use channel_sender::ChannelSender;
-use channels::domain::broker_events::ChannelMessagePostedMetadata;
-use channels::domain::side_effects::bot_mention_ids;
+use messages::domain::events::MessagePostedMetadata;
+use messages::domain::mentions::bot_mention_ids;
-use crate::domain::broker_events::{
- AgentBotMentionedEvent, AgentSessionMacroEvent, ChannelEventMetadata, ChannelKind,
- NewAgentSessionEvent,
-};
+use crate::domain::broker_events::{ThreadMessageKind, TriggerDecision};
/// Why evaluating a message did not produce an agent-session event.
#[derive(Debug, Clone, Copy, PartialEq, Eq, strum::AsRefStr)]
@@ -57,19 +54,19 @@ pub enum NoEventReason {
#[derive(Debug)]
#[allow(
clippy::large_enum_variant,
- reason = "the event carries a whole message; boxing would only move the size"
+ reason = "the decision carries a whole message; boxing would only move the size"
)]
pub enum AgentSessionEventDecision {
- /// Publish this event.
- Event(AgentSessionMacroEvent),
+ /// Publish this decision.
+ Event(TriggerDecision),
/// Do not publish, for some reason the agent harness was not triggered.
NoEvent(NoEventReason),
}
impl AgentSessionEventDecision {
- /// Returns the event when this decision emits one.
+ /// Returns the decision when this one emits an event.
#[must_use]
- pub fn into_event(self) -> Option<AgentSessionMacroEvent> {
+ pub fn into_event(self) -> Option<TriggerDecision> {
match self {
Self::Event(event) => Some(event),
Self::NoEvent(_) => None,
@@ -91,11 +88,11 @@ pub fn is_own_message(bot: BotId, sender: &ChannelSender<'_>) -> bool {
pub enum PotentialTriggerEvent<'a> {
/// A message posted in a comms channel, with the session lookup it
/// required and the bot being evaluated for it.
- Channel {
- /// The message, as the channel topic carried it.
- posted: &'a ChannelMessagePostedMetadata,
+ Thread {
+ /// The message, as the topic carried it.
+ posted: &'a MessagePostedMetadata,
/// The session lookup for the message's thread context.
- existing: &'a ChannelSession,
+ existing: &'a ThreadSession,
/// The bot being evaluated when no session exists.
mentioned_bot: Option<BotId>,
},
@@ -111,7 +108,7 @@ pub fn yield_event(
available: bool,
) -> AgentSessionEventDecision {
match message {
- PotentialTriggerEvent::Channel {
+ PotentialTriggerEvent::Thread {
posted,
existing,
mentioned_bot,
@@ -120,14 +117,14 @@ pub fn yield_event(
}
fn yield_channel_event(
- posted: &ChannelMessagePostedMetadata,
- existing: &ChannelSession,
+ posted: &MessagePostedMetadata,
+ existing: &ThreadSession,
mentioned_bot: Option<BotId>,
available: bool,
) -> AgentSessionEventDecision {
let session_bot = match existing {
- ChannelSession::CreatedFromThread(session) => session.bot_id,
- ChannelSession::None => match mentioned_bot {
+ ThreadSession::CreatedFromThread(session) => session.bot_id,
+ ThreadSession::None => match mentioned_bot {
Some(bot_id) => bot_id,
None => {
return AgentSessionEventDecision::NoEvent(NoEventReason::MissingBotContext);
@@ -150,29 +147,25 @@ fn yield_channel_event(
let mentioned = bot_mention_ids(&posted.mentions).contains(&session_bot);
match (existing, mentioned) {
- (ChannelSession::CreatedFromThread(session), true) => AgentSessionEventDecision::Event(
- AgentSessionMacroEvent::channel_event(ChannelEventMetadata {
+ (ThreadSession::CreatedFromThread(session), true) => {
+ AgentSessionEventDecision::Event(TriggerDecision::Existing {
bot_id: session_bot,
session_id: session.id,
- kind: ChannelKind::MentionThread,
+ kind: ThreadMessageKind::MentionThread,
message: posted.clone(),
- }),
- ),
- (ChannelSession::None, true) => {
- AgentSessionEventDecision::Event(AgentSessionMacroEvent::new_session(
- NewAgentSessionEvent::TopLevelMentioned(AgentBotMentionedEvent {
- bot_id: session_bot,
- message: posted.clone(),
- }),
- ))
+ })
}
- (ChannelSession::CreatedFromThread(session), false) => {
+ (ThreadSession::None, true) => AgentSessionEventDecision::Event(TriggerDecision::Open {
+ bot_id: session_bot,
+ message: posted.clone(),
+ }),
+ (ThreadSession::CreatedFromThread(session), false) => {
AgentSessionEventDecision::NoEvent(NoEventReason::MentionRequired {
bot_id: session_bot,
session_id: Some(session.id),
})
}
- (ChannelSession::None, false) => {
+ (ThreadSession::None, false) => {
AgentSessionEventDecision::NoEvent(NoEventReason::MentionRequired {
bot_id: session_bot,
session_id: None,
diff --git a/crates/agent_trigger/src/outbound/channel_thread_history.rs b/crates/agent_trigger/src/outbound/channel_thread_history.rs
deleted file mode 100644
index 32cf338c65..0000000000
--- a/crates/agent_trigger/src/outbound/channel_thread_history.rs
+++ /dev/null
@@ -1,78 +0,0 @@
-//! Thread history assembled from the channels repository.
-
-use agent_session::domain::error::{AgentSessionError, Result};
-use channel_sender::ChannelSender;
-use channels::domain::ports::ChannelRepo;
-use macro_uuid::Uuid;
-
-use crate::domain::service::ThreadHistory;
-use crate::domain::thread_window::ThreadMessage;
-
-/// Reads a thread as its root message followed by its replies.
-pub struct ChannelThreadHistory<Repo> {
- repo: Repo,
-}
-
-impl<Repo> ChannelThreadHistory<Repo> {
- /// Creates a reader over the given channels repository.
- pub const fn new(repo: Repo) -> Self {
- Self { repo }
- }
-}
-
-/// A sender that will not parse drops its message rather than failing the
-/// read: one unreadable row must not blind the judge to the whole thread.
-fn thread_message(
- id: Uuid,
- sender_id: String,
- content: String,
- created_at: chrono::DateTime<chrono::Utc>,
-) -> Option<ThreadMessage> {
- let sender = ChannelSender::try_from(sender_id)
- .inspect_err(|error| {
- tracing::warn!(error = ?error, message_id = %id, "skipping thread message with an unparseable sender");
- })
- .ok()?;
- Some(ThreadMessage {
- id,
- sender,
- content,
- created_at,
- })
-}
-
-impl<Repo> ThreadHistory for ChannelThreadHistory<Repo>
-where
- Repo: ChannelRepo,
-{
- async fn thread_messages(
- &self,
- channel_id: Uuid,
- thread_id: Uuid,
- ) -> Result<Vec<ThreadMessage>> {
- // The root is not one of its own replies, and it is where the mention
- // that opened the session lives.
- let root = self
- .repo
- .resolve_top_level_parent(channel_id, thread_id)
- .await
- .map_err(|error| AgentSessionError::Unknown(error.into()))?
- .filter(|root| root.deleted_at.is_none())
- .and_then(|root| {
- thread_message(root.id, root.sender_id, root.content, root.created_at)
- });
-
- let replies = self
- .repo
- .get_thread_replies(thread_id)
- .await
- .map_err(|error| AgentSessionError::Unknown(error.into()))?;
-
- Ok(root
- .into_iter()
- .chain(replies.into_iter().filter_map(|reply| {
- thread_message(reply.id, reply.sender_id, reply.content, reply.created_at)
- }))
- .collect())
- }
-}
diff --git a/crates/agent_trigger/src/outbound/channel_type_lookup.rs b/crates/agent_trigger/src/outbound/channel_type_lookup.rs
new file mode 100644
index 0000000000..70c0d4c9ae
--- /dev/null
+++ b/crates/agent_trigger/src/outbound/channel_type_lookup.rs
@@ -0,0 +1,44 @@
+//! Channel type facts from the channels repository.
+
+use agent_session::domain::error::{AgentSessionError, Result};
+use channels::domain::models::ChannelType;
+use channels::domain::ports::ChannelRepo;
+use macro_uuid::Uuid;
+
+use crate::domain::processing::ChannelTypeLookup;
+
+/// Reads a channel's type from the channels repository.
+pub struct ChannelRepoTypeLookup<Repo> {
+ repo: Repo,
+}
+
+impl<Repo> ChannelRepoTypeLookup<Repo> {
+ /// Creates a lookup over the given channels repository.
+ pub const fn new(repo: Repo) -> Self {
+ Self { repo }
+ }
+}
+
+impl<Repo> ChannelTypeLookup for ChannelRepoTypeLookup<Repo>
+where
+ Repo: ChannelRepo,
+{
+ async fn channel_type(&self, channel_id: Uuid) -> Result<Option<ChannelType>> {
+ match self.repo.get_channel_info(channel_id).await {
+ Ok(info) => Ok(Some(info.channel_type)),
+ Err(error) => {
+ let error: anyhow::Error = error.into();
+ // The repository reads one row and reports a missing channel
+ // as the driver's not-found, which is the one failure a
+ // consumer should skip rather than retry.
+ if matches!(
+ error.downcast_ref::<sqlx::Error>(),
+ Some(sqlx::Error::RowNotFound)
+ ) {
+ return Ok(None);
+ }
+ Err(AgentSessionError::Unknown(error))
+ }
+ }
+ }
+}
diff --git a/crates/agent_trigger/src/outbound/fast_model_judge.rs b/crates/agent_trigger/src/outbound/fast_model_judge.rs
index ee3b341e16..29d4474743 100644
--- a/crates/agent_trigger/src/outbound/fast_model_judge.rs
+++ b/crates/agent_trigger/src/outbound/fast_model_judge.rs
@@ -6,7 +6,7 @@ use agent::structured_output::{DynamicSchema, dynamic_structured_completion};
use agent::{Message, PredefinedModel};
use agent_session::domain::error::Result;
use ai_usage::{AiFeature, UsageContext, UsageRecorder};
-use channels::domain::broker_events::ChannelMessagePostedMetadata;
+use messages::domain::events::MessagePostedMetadata;
use serde::Deserialize;
use serde_json::json;
@@ -57,7 +57,7 @@ impl FastModelTriggerJudge {
impl ImplicitTriggerJudge for FastModelTriggerJudge {
async fn is_addressed_to_agent(
&self,
- posted: &ChannelMessagePostedMetadata,
+ posted: &MessagePostedMetadata,
transcript: &str,
) -> Result<bool> {
let schema = DynamicSchema {
diff --git a/crates/agent_trigger/src/outbound/lexical_explicit_reply_extractor.rs b/crates/agent_trigger/src/outbound/lexical_explicit_reply_extractor.rs
index 88de7fed3c..dfce790240 100644
--- a/crates/agent_trigger/src/outbound/lexical_explicit_reply_extractor.rs
+++ b/crates/agent_trigger/src/outbound/lexical_explicit_reply_extractor.rs
@@ -28,7 +28,7 @@ impl ExplicitReplyExtractor for LexicalExplicitReplyExtractor {
.extract_explicit_reply(markdown)
.await?
.map(|reply| ExtractedExplicitReply {
- channel_id: reply.channel_id,
+ parent: reply.parent,
target_message_id: reply.target_message_id,
target_thread_id: reply.target_thread_id,
display_text: reply.display_text,
diff --git a/crates/agent_trigger/src/outbound/message_thread_history.rs b/crates/agent_trigger/src/outbound/message_thread_history.rs
new file mode 100644
index 0000000000..59ef63cce3
--- /dev/null
+++ b/crates/agent_trigger/src/outbound/message_thread_history.rs
@@ -0,0 +1,103 @@
+//! Authorized conversation history through the common read application boundary.
+
+#[cfg(test)]
+mod test;
+
+use crate::domain::{
+ service::{AuthorizedInvocation, ThreadHistory},
+ thread_window::ThreadMessage,
+};
+use agent_session::domain::error::{AgentSessionError, Result};
+use entity_access::domain::{
+ models::{AccessError, EntityAccessReceipt, EntityType},
+ ports::EntityAccessService,
+};
+use macro_user_id::user_id::MacroUserIdStr;
+use macro_uuid::Uuid;
+use messages::domain::{
+ api::MessageReader, models::MessageParent, ports::MessageError, service::MessageWrite,
+};
+use std::sync::Arc;
+
+trait InvocationAuthorizer: Send + Sync + 'static {
+ fn capability(
+ &self,
+ user: &MacroUserIdStr<'static>,
+ parent: &MessageParent,
+ ) -> impl Future<Output = std::result::Result<EntityAccessReceipt<MessageWrite>, AccessError>> + Send;
+}
+
+impl<Access: EntityAccessService> InvocationAuthorizer for Access {
+ async fn capability(
+ &self,
+ user: &MacroUserIdStr<'static>,
+ parent: &MessageParent,
+ ) -> std::result::Result<EntityAccessReceipt<MessageWrite>, AccessError> {
+ self.generate_entity_access_receipt::<MessageWrite>(
+ user,
+ None,
+ &parent.entity_id(),
+ match parent {
+ MessageParent::Channel(_) => EntityType::Channel,
+ MessageParent::Document(_) => EntityType::Document,
+ },
+ )
+ .await
+ }
+}
+
+/// Reads common message history with the invoking user's current capability.
+pub struct MessageThreadHistory<Access> {
+ messages: Arc<dyn MessageReader>,
+ access: Access,
+}
+
+impl<Access> MessageThreadHistory<Access> {
+ /// Compose the read application port and current parent authorization.
+ pub fn new(messages: Arc<dyn MessageReader>, access: Access) -> Self {
+ Self { messages, access }
+ }
+}
+
+impl<Access: InvocationAuthorizer> ThreadHistory for MessageThreadHistory<Access> {
+ async fn authorize_invocation(
+ &self,
+ user: &MacroUserIdStr<'static>,
+ parent: &MessageParent,
+ root_id: Uuid,
+ ) -> Result<Option<AuthorizedInvocation>> {
+ match self.access.capability(user, parent).await {
+ Ok(access) => Ok(Some(AuthorizedInvocation::new(access, root_id))),
+ Err(AccessError::Unavailable(error) | AccessError::Internal(error)) => {
+ Err(AgentSessionError::Unknown(error.into()))
+ }
+ Err(_) => Ok(None),
+ }
+ }
+
+ async fn thread_messages(
+ &self,
+ invocation: &AuthorizedInvocation,
+ ) -> Result<Vec<ThreadMessage>> {
+ let access = invocation
+ .access()
+ .clone()
+ .try_into_requirement()
+ .map_err(|error| AgentSessionError::Unknown(error.into()))?;
+ let thread = match self.messages.get_thread(access, invocation.root_id()).await {
+ Ok(thread) => thread,
+ Err(MessageError::NotFound) => return Ok(Vec::new()),
+ Err(error) => return Err(AgentSessionError::Unknown(error.into())),
+ };
+ Ok(std::iter::once(thread.root)
+ .chain(thread.replies)
+ .filter(|message| message.deleted_at.is_none())
+ .map(|message| ThreadMessage {
+ id: message.id,
+ sender: message.sender_id,
+ content: message.content,
+ created_at: message.created_at,
+ })
+ .collect())
+ }
+}
diff --git a/crates/agent_trigger/src/outbound/message_thread_history/test.rs b/crates/agent_trigger/src/outbound/message_thread_history/test.rs
new file mode 100644
index 0000000000..a55e990066
--- /dev/null
+++ b/crates/agent_trigger/src/outbound/message_thread_history/test.rs
@@ -0,0 +1,138 @@
+use super::*;
+use entity_access::domain::models::{AccessLevel, Entity, EntityPermission};
+use messages::domain::{
+ api::MockMessageReader,
+ models::{Message, MessageThread, ThreadState},
+};
+
+struct Authorizer {
+ allowed: bool,
+}
+impl InvocationAuthorizer for Authorizer {
+ async fn capability(
+ &self,
+ user: &MacroUserIdStr<'static>,
+ parent: &MessageParent,
+ ) -> std::result::Result<EntityAccessReceipt<MessageWrite>, AccessError> {
+ if !self.allowed {
+ return Err(AccessError::Unauthorized);
+ }
+ EntityAccessReceipt::try_new_authenticated_user(
+ user.clone(),
+ Entity {
+ entity_type: EntityType::Document,
+ entity_id: parent.entity_id(),
+ },
+ EntityPermission::AccessLevel {
+ access_level: AccessLevel::Comment,
+ },
+ )
+ }
+}
+fn user() -> MacroUserIdStr<'static> {
+ MacroUserIdStr::try_from_email("[email protected]").unwrap()
+}
+fn parent() -> MessageParent {
+ MessageParent::parse("document", "origin").unwrap()
+}
+fn root() -> Uuid {
+ Uuid::from_u128(1)
+}
+fn message(id: Uuid, deleted: bool) -> Message {
+ let now = chrono::Utc::now();
+ Message {
+ id,
+ parent: parent(),
+ thread_id: (id != root()).then_some(root()),
+ sender_id: channel_sender::ChannelSender::new_from_user(user()),
+ triggered_by: None,
+ bot_profile: None,
+ mentions: vec![],
+ imported_author: None,
+ content: "history".into(),
+ created_at: now,
+ updated_at: now,
+ edited_at: None,
+ deleted_at: deleted.then_some(now),
+ attachments: vec![],
+ reactions: vec![],
+ }
+}
+
+#[tokio::test]
+async fn reads_the_bound_actor_parent_and_root_and_omits_tombstones() {
+ let mut reader = MockMessageReader::new();
+ reader
+ .expect_get_thread()
+ .once()
+ .withf(|access, id| {
+ access.entity().entity_id == parent().entity_id()
+ && access.entity().entity_type == EntityType::Document
+ && access.get_authenticated_user().unwrap() == &user()
+ && *id == root()
+ })
+ .return_once(|_, _| {
+ Ok(MessageThread {
+ state: ThreadState {
+ root_id: root(),
+ user_id: user().to_string(),
+ created_at: chrono::Utc::now(),
+ updated_at: chrono::Utc::now(),
+ resolved: false,
+ deleted_at: None,
+ anchor: None,
+ },
+ root: message(root(), true),
+ replies: vec![
+ message(Uuid::from_u128(2), false),
+ message(Uuid::from_u128(3), true),
+ ],
+ })
+ });
+ let history = MessageThreadHistory::new(Arc::new(reader), Authorizer { allowed: true });
+ let invocation = history
+ .authorize_invocation(&user(), &parent(), root())
+ .await
+ .unwrap()
+ .unwrap();
+ let messages = history.thread_messages(&invocation).await.unwrap();
+ assert_eq!(messages.len(), 1);
+ assert_eq!(messages[0].id, Uuid::from_u128(2));
+}
+
+#[tokio::test]
+async fn revoked_write_permission_yields_no_invocation_or_read() {
+ let history = MessageThreadHistory::new(
+ Arc::new(MockMessageReader::new()),
+ Authorizer { allowed: false },
+ );
+ assert!(
+ history
+ .authorize_invocation(&user(), &parent(), root())
+ .await
+ .unwrap()
+ .is_none()
+ );
+}
+
+#[tokio::test]
+async fn deleted_thread_uses_the_application_lifecycle_rule() {
+ let mut reader = MockMessageReader::new();
+ reader
+ .expect_get_thread()
+ .once()
+ .return_once(|_, _| Err(MessageError::NotFound));
+ let history = MessageThreadHistory::new(Arc::new(reader), Authorizer { allowed: true });
+ let invocation = history
+ .authorize_invocation(&user(), &parent(), root())
+ .await
+ .unwrap()
+ .unwrap();
+ assert!(
+ history
+ .thread_messages(&invocation)
+ .await
+ .unwrap()
+ .is_empty()
+ );
+}
diff --git a/crates/agent_trigger/src/outbound/mod.rs b/crates/agent_trigger/src/outbound/mod.rs
index 088ca9b3f4..c2b198e12b 100644
--- a/crates/agent_trigger/src/outbound/mod.rs
+++ b/crates/agent_trigger/src/outbound/mod.rs
@@ -1,11 +1,13 @@
//! Adapters implementing the trigger's implicit-evaluation ports.
mod bot_repo_agent_lookup;
-mod channel_thread_history;
+mod channel_type_lookup;
mod fast_model_judge;
mod lexical_explicit_reply_extractor;
+mod message_thread_history;
pub use bot_repo_agent_lookup::BotRepoAgentLookup;
-pub use channel_thread_history::ChannelThreadHistory;
+pub use channel_type_lookup::ChannelRepoTypeLookup;
pub use fast_model_judge::FastModelTriggerJudge;
pub use lexical_explicit_reply_extractor::LexicalExplicitReplyExtractor;
+pub use message_thread_history::MessageThreadHistory;
diff --git a/crates/channel_bots/Cargo.toml b/crates/channel_bots/Cargo.toml
index b5a4ac5cab..cdec5f7728 100644
--- a/crates/channel_bots/Cargo.toml
+++ b/crates/channel_bots/Cargo.toml
@@ -13,7 +13,7 @@ anyhow = { workspace = true }
async-trait = { workspace = true }
bot_id = { path = "../bot_id" }
calendar_events = { path = "../calendar_events" }
-channels = { path = "../channels", features = ["inbound", "outbound"] }
+channel_sender = { path = "../channel_sender" }
entity_access = { path = "../entity_access", default-features = false, features = ["ports"] }
chrono = { workspace = true }
chrono-tz = { workspace = true }
@@ -30,4 +30,4 @@ uuid = { workspace = true }
workspace-hack = { version = "0.1", path = "../workspace-hack" }
[dev-dependencies]
-models_pagination = { path = "../models_pagination" }
+messages = { path = "../messages", features = ["test-utils"] }
diff --git a/crates/channel_bots/src/domain.rs b/crates/channel_bots/src/domain.rs
index dbcc2378e8..943e292229 100644
--- a/crates/channel_bots/src/domain.rs
+++ b/crates/channel_bots/src/domain.rs
@@ -24,3 +24,6 @@ pub(crate) fn sender_label(sender_id: &str) -> String {
.unwrap_or(sender_id)
.to_string()
}
+
+#[cfg(test)]
+pub(crate) mod test;
diff --git a/crates/channel_bots/src/domain/models.rs b/crates/channel_bots/src/domain/models.rs
index c66b41e09a..d1d4728c40 100644
--- a/crates/channel_bots/src/domain/models.rs
+++ b/crates/channel_bots/src/domain/models.rs
@@ -1,14 +1,14 @@
//! Domain models for channel bot triggers.
use bot_id::BotId;
-use channels::domain::models::MutatedMessage;
use macro_user_id::user_id::MacroUserIdStr;
+use messages::domain::events::MessagePostedMetadata;
use uuid::Uuid;
/// The kind of event that triggered a bot.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BotTrigger {
- /// The bot was `@`-mentioned in a channel message.
+ /// The bot was `@`-mentioned in a message.
Mention,
/// A classifier inferred that a thread message expects the bot to respond
/// even though it was not `@`-mentioned.
@@ -29,10 +29,8 @@ pub struct BotInvocation {
pub struct BotEvent {
/// What triggered the bot.
pub trigger: BotTrigger,
- /// Channel the trigger occurred in.
- pub channel_id: Uuid,
/// The user-authored message that triggered the bot.
- pub message: MutatedMessage,
+ pub message: MessagePostedMetadata,
/// Thread the bot should reply in. For a top-level message this is the
/// message id; for a reply it is the existing thread id.
pub reply_thread_id: Uuid,
diff --git a/crates/channel_bots/src/domain/ports.rs b/crates/channel_bots/src/domain/ports.rs
index 31efe1837d..429a0b0eee 100644
--- a/crates/channel_bots/src/domain/ports.rs
+++ b/crates/channel_bots/src/domain/ports.rs
@@ -1,14 +1,15 @@
-//! Port definitions for channel bot domain dependencies.
+//! Port definitions for built-in message agent dependencies.
use async_trait::async_trait;
-use channels::domain::side_effects::ChannelBotTrigger;
use entity_access::domain::models::EntityAccessReceipt;
use macro_user_id::user_id::MacroUserIdStr;
-use messages::domain::{models::MessageParent, service::MessageWrite};
+use messages::domain::{
+ events::MessagePostedMetadata, models::MessageParent, service::MessageWrite,
+};
use super::models::{BotInvocation, TranscriptMessage};
-/// Produces an assistant response for a channel message.
+/// Produces an assistant response for a posted message.
#[async_trait]
pub trait AgentResponder: Send + Sync {
/// Run the agent on behalf of `user_id` with `prompt`, returning the reply.
@@ -23,12 +24,12 @@ pub trait UserTimeZones: Send + Sync {
async fn primary_time_zone(&self, user_id: &str) -> Option<String>;
}
-/// Decides whether a candidate channel message should invoke any bots.
+/// Decides whether a committed post should invoke any bots.
#[async_trait]
pub trait TriggerDetector: Send + Sync {
/// Resolve the bot invocations for a candidate message. An empty result
/// means the message triggers nothing.
- async fn detect(&self, candidate: &ChannelBotTrigger) -> Vec<BotInvocation>;
+ async fn detect(&self, candidate: &MessagePostedMetadata) -> Vec<BotInvocation>;
}
/// Classifies whether a thread message expects an agent response without an
@@ -44,9 +45,18 @@ pub trait InferredTriggerClassifier: Send + Sync {
) -> anyhow::Result<bool>;
}
-/// Current parent capabilities for built-in agent replies.
+/// Current parent capabilities for built-in agent reads and replies.
#[async_trait]
pub trait ConversationAccess: Send + Sync {
+ /// Verify the invoking user can still post to the parent. Context reads
+ /// downgrade this to view access, so a user who may no longer write there
+ /// gets no history read on their behalf either.
+ async fn user_write(
+ &self,
+ user: &MacroUserIdStr<'static>,
+ parent: &MessageParent,
+ ) -> Result<EntityAccessReceipt<MessageWrite>, rootcause::Report>;
+
/// Mint Macro AI's write capability on behalf of the invoking user, immediately
/// before a reply is persisted, so a revoked membership stops the reply.
async fn bot_write(
diff --git a/crates/channel_bots/src/domain/service.rs b/crates/channel_bots/src/domain/service.rs
index 7471a572d0..94648636f6 100644
--- a/crates/channel_bots/src/domain/service.rs
+++ b/crates/channel_bots/src/domain/service.rs
@@ -1,17 +1,18 @@
-//! Domain service for built-in channel bots.
+//! Domain service for the built-in Macro AI agent on channels and documents.
use std::collections::HashSet;
use std::fmt::Write as _;
use std::sync::Arc;
-use channels::domain::ports::ChannelService;
+use entity_access::domain::models::EntityAccessReceipt;
use messages::domain::{
- api::MessageCommands,
+ api::MessageServiceApi,
models::{
MessageAttribution, MessageParent, PatchMessageNotificationPolicy, PostMessage,
PostMessageNotificationPolicy,
},
ports::{MessageError, MessagePatch},
+ service::MessageView,
};
use uuid::Uuid;
@@ -19,12 +20,11 @@ use super::models::{BotEvent, BotTrigger};
use super::ports::{AgentResponder, ConversationAccess, UserTimeZones};
use super::sender_label;
-/// How many channel messages to include around the trigger.
+/// How many channel messages preceding the trigger to include as local context.
///
/// Together with the trigger message itself, this yields a bounded nine-message
/// local context window.
-const CONTEXT_MESSAGES_BEFORE: i64 = 4;
-const CONTEXT_MESSAGES_AFTER: i64 = 4;
+const CONTEXT_MESSAGES_BEFORE: u16 = 8;
/// Inline marker appended to the sender label of the triggering message so the
/// model can tell it apart from surrounding context.
@@ -131,32 +131,29 @@ fn current_time_block(now: chrono::DateTime<chrono::Utc>, time_zone: Option<&str
/// In-process handler for the Macro AI system bot.
///
/// Posts an immediate "thinking" reply in a thread, runs the agent loop, then
-/// edits that same message with the final answer.
-pub struct MacroAiHandler<C, R, Z> {
- channels: Arc<C>,
- messages: Arc<dyn MessageCommands>,
+/// edits that same message with the final answer. Reads and writes go through
+/// the shared message service under the invoking user's current capability,
+/// so channels and document discussions behave the same way.
+pub struct MacroAiHandler<R, Z> {
+ messages: Arc<dyn MessageServiceApi>,
access: Arc<dyn ConversationAccess>,
responder: Arc<R>,
time_zones: Arc<Z>,
}
-impl<C, R, Z> MacroAiHandler<C, R, Z>
+impl<R, Z> MacroAiHandler<R, Z>
where
- C: ChannelService,
R: AgentResponder,
Z: UserTimeZones,
{
- /// Create a Macro AI handler that reads channel context through `channels`
- /// and replies through the shared message commands.
+ /// Create a Macro AI handler over the shared message service.
pub fn new(
- channels: Arc<C>,
- messages: Arc<dyn MessageCommands>,
+ messages: Arc<dyn MessageServiceApi>,
access: Arc<dyn ConversationAccess>,
responder: Arc<R>,
time_zones: Arc<Z>,
) -> Self {
Self {
- channels,
messages,
access,
responder,
@@ -164,101 +161,106 @@ where
}
}
- /// Load the thread the mention belongs to as prompt lines: the top-level
- /// parent followed by all replies in order, with the triggering message
- /// marked inline. Also returns the ids of every message known to belong to
- /// the thread so they can be excluded from the channel background.
+ /// Load the thread the mention belongs to as prompt lines: the root
+ /// followed by all replies in order, with the triggering message marked
+ /// inline. Also returns the ids of every message known to belong to the
+ /// thread so they can be excluded from the channel background.
async fn thread_lines(
&self,
event: &BotEvent,
- parent_id: Uuid,
- ) -> (Vec<PromptLine>, HashSet<Uuid>) {
- let mut thread_ids = HashSet::from([parent_id, event.message.id]);
+ access: EntityAccessReceipt<MessageView>,
+ root_id: Uuid,
+ ) -> anyhow::Result<(Vec<PromptLine>, HashSet<Uuid>)> {
+ let thread = self.messages.get_thread(access, root_id).await?;
+ let mut thread_ids = HashSet::new();
let mut lines = Vec::new();
-
- let parent = self
- .channels
- .get_message_context(event.channel_id, parent_id, 0, 0)
- .await
- .inspect_err(|err| tracing::warn!(error=?err, "failed to load thread parent"))
- .unwrap_or_default()
- .into_iter()
- .find(|message| message.id == parent_id);
- if let Some(parent) = parent
- && parent.deleted_at.is_none()
- && let Some(content) = trimmed_content(&parent.content)
- {
- lines.push(PromptLine {
- sender: sender_label(&parent.sender_id),
- content,
- is_trigger: false,
- });
- }
-
- let replies = self
- .channels
- .get_thread_replies(event.channel_id, parent_id)
- .await
- .inspect_err(|err| tracing::warn!(error=?err, "failed to load thread replies"))
- .unwrap_or_default();
- for reply in replies {
- thread_ids.insert(reply.id);
- let Some(content) = trimmed_content(&reply.content) else {
+ for message in std::iter::once(thread.root).chain(thread.replies) {
+ thread_ids.insert(message.id);
+ if message.deleted_at.is_some() {
+ continue;
+ }
+ let Some(content) = trimmed_content(&message.content) else {
continue;
};
lines.push(PromptLine {
- sender: sender_label(&reply.sender_id),
+ sender: sender_label(message.sender_id.as_ref()),
content,
- is_trigger: reply.id == event.message.id,
+ is_trigger: message.id == event.message.message_id,
});
}
if !lines.iter().any(|line| line.is_trigger) {
lines.push(trigger_line(event));
}
- (lines, thread_ids)
+ Ok((lines, thread_ids))
}
/// Build the prompt for a mention.
///
- /// When the mention is a thread reply, the thread (parent + replies) is the
- /// primary context and nearby channel messages are demoted to a clearly
- /// labeled background block. For a top-level mention, the chronological
- /// channel slice is the primary context. In both cases the triggering
- /// message is marked inline rather than repeated at the end.
- async fn build_prompt(&self, event: &BotEvent) -> String {
+ /// The invoking user's current access to the parent gates every read, and
+ /// the live trigger must still sit in the thread the event claims. When
+ /// the mention is a thread reply or a document discussion, the thread is
+ /// the primary context and nearby channel messages are demoted to a
+ /// clearly labeled background block. For a top-level channel mention, the
+ /// chronological channel slice is the primary context. In both cases the
+ /// triggering message is marked inline rather than repeated at the end.
+ async fn build_prompt(&self, event: &BotEvent) -> anyhow::Result<String> {
let mentioner = sender_label(event.requesting_user.as_ref());
- let trigger_id = event.message.id;
+ let trigger_id = event.message.message_id;
+ let parent = &event.message.parent;
+ let access = self
+ .access
+ .user_write(&event.requesting_user, parent)
+ .await
+ .map_err(|error| anyhow::anyhow!(error.to_string()))?;
+ let view = access.try_into_requirement::<MessageView>()?;
+ let current = self.messages.get(view.clone(), trigger_id).await?;
+ if current.deleted_at.is_some()
+ || current.root_id() != event.reply_thread_id
+ || current.sender_id.as_user() != Some(&event.requesting_user)
+ {
+ anyhow::bail!("trigger no longer belongs to this conversation");
+ }
let (nearby, time_zone) = futures::join!(
async {
- self.channels
- .get_message_context(
- event.channel_id,
- trigger_id,
- CONTEXT_MESSAGES_BEFORE,
- CONTEXT_MESSAGES_AFTER,
- )
- .await
- .inspect_err(
- |err| tracing::warn!(error=?err, "failed to load local channel context"),
- )
- .unwrap_or_default()
+ if matches!(parent, MessageParent::Channel(_)) {
+ self.messages
+ .preceding(view.clone(), trigger_id, CONTEXT_MESSAGES_BEFORE)
+ .await
+ .inspect_err(|err| {
+ tracing::warn!(error=?err, "failed to load local channel context")
+ })
+ .unwrap_or_default()
+ } else {
+ Vec::new()
+ }
},
self.time_zones
.primary_time_zone(event.requesting_user.as_ref()),
);
- let mut prompt = String::new();
- if let Some(parent_id) = event.message.thread_id {
+ let mut prompt = format!("Conversation parent: {}\n", serde_json::to_string(parent)?);
+ // A document discussion is a thread from its root; a top-level channel
+ // message is the channel's own timeline.
+ let thread_root = event
+ .message
+ .thread_id
+ .or_else(|| parent.is_discussion().then_some(trigger_id));
+ if let Some(root_id) = thread_root {
+ let place = if parent.is_discussion() {
+ "a document discussion"
+ } else {
+ "a channel thread"
+ };
let (intro, thread_instruction, marker) = match event.trigger {
BotTrigger::Mention => (
- format!("{mentioner} mentioned you (@macro) in a channel thread."),
+ format!("{mentioner} mentioned you (@macro) in {place}."),
MENTION_THREAD_INSTRUCTION,
MENTION_TRIGGER_MARKER,
),
BotTrigger::Inferred => (
format!(
- "{mentioner} replied in a channel thread you are part of. They did not \
+ "{mentioner} replied in {place} you are part of. They did not \
@-mention you, but their message appears to be addressed to you."
),
INFERRED_THREAD_INSTRUCTION,
@@ -266,7 +268,7 @@ where
),
};
let _ = writeln!(prompt, "{intro}");
- let (thread, thread_ids) = self.thread_lines(event, parent_id).await;
+ let (thread, thread_ids) = self.thread_lines(event, view, root_id).await?;
append_block(&mut prompt, "thread", thread_instruction, marker, &thread);
let background: Vec<PromptLine> = nearby
@@ -274,11 +276,11 @@ where
.filter(|message| {
message.deleted_at.is_none()
&& !thread_ids.contains(&message.id)
- && message.thread_id != Some(parent_id)
+ && message.thread_id != Some(root_id)
})
.filter_map(|message| {
Some(PromptLine {
- sender: sender_label(&message.sender_id),
+ sender: sender_label(message.sender_id.as_ref()),
content: trimmed_content(&message.content)?,
is_trigger: false,
})
@@ -298,7 +300,7 @@ where
.filter(|message| message.deleted_at.is_none())
.filter_map(|message| {
Some(PromptLine {
- sender: sender_label(&message.sender_id),
+ sender: sender_label(message.sender_id.as_ref()),
content: trimmed_content(&message.content)?,
is_trigger: message.id == trigger_id,
})
@@ -322,23 +324,24 @@ where
));
let _ = write!(prompt, "\nReply to {mentioner}.");
- prompt
+ Ok(prompt)
}
/// React to a Macro AI mention.
- #[tracing::instrument(skip(self, event), fields(channel_id = %event.channel_id), err)]
+ #[tracing::instrument(skip(self, event), fields(parent = ?event.message.parent), err)]
pub(crate) async fn handle(&self, event: &BotEvent) -> anyhow::Result<()> {
- let parent = MessageParent::Channel(event.channel_id);
+ let parent = &event.message.parent;
// 1. Gather conversational context (before posting, so our own
- // "thinking" message is not included).
- let prompt = self.build_prompt(event).await;
+ // "thinking" message is not included). An unreadable or revoked
+ // 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 access = self
.access
- .bot_write(&event.requesting_user, &parent)
+ .bot_write(&event.requesting_user, parent)
.await
.map_err(|error| anyhow::anyhow!(error.to_string()))?;
let thinking = self
@@ -378,7 +381,7 @@ where
// ran — treat that as the user not wanting a response.
let access = self
.access
- .bot_write(&event.requesting_user, &parent)
+ .bot_write(&event.requesting_user, parent)
.await
.map_err(|error| anyhow::anyhow!(error.to_string()))?;
match self
diff --git a/crates/channel_bots/src/domain/service/tests.rs b/crates/channel_bots/src/domain/service/tests.rs
index 7922e9e2ba..efa55c5d4a 100644
--- a/crates/channel_bots/src/domain/service/tests.rs
+++ b/crates/channel_bots/src/domain/service/tests.rs
@@ -1,197 +1,39 @@
-use std::sync::{Arc, Mutex};
-
+use super::super::test::*;
+use super::*;
use async_trait::async_trait;
-use channels::domain::models::{
- AttachmentEntityReference, ChannelAttachmentType, ChannelContextMessage, ChannelMessageFilters,
- ChannelParticipant, MessagePageDirection, MutatedMessage, PatchMessageRequest,
- PostMessageRequest, PostMessageResponse, ResolvedChannelMessage, Sender, ThreadReply,
-};
-use channels::domain::ports::{
- ChannelAttachmentsPage, ChannelMessagesErr, ChannelMessagesQueryResult, ChannelMutationErr,
- ChannelService,
-};
use chrono::{TimeZone as _, Utc};
-use entity_access::domain::models::{
- BotReceiptScope, Entity, EntityAccessReceipt, EntityPermission, EntityType, ParticipantRole,
-};
-use macro_user_id::user_id::MacroUserIdStr;
-use messages::domain::models::{PatchMessageNotificationPolicy, PostMessageNotificationPolicy};
-use messages::domain::{
- models::{Message, MessageParent, ThreadPatch, ThreadState},
- ports::{MessageError, MessagePatch},
- service::MessageWrite,
-};
-use models_pagination::{CreatedAt, Query};
-use uuid::Uuid;
-
-use super::*;
-use crate::domain::{
- models::{BotEvent, BotTrigger},
- ports::{AgentResponder, ConversationAccess, UserTimeZones},
-};
-
-/// Mints Macro AI write capabilities for whichever user asked.
-struct GrantingAccess;
+use messages::domain::api::MockMessageServiceApi;
+use std::sync::Mutex;
-#[async_trait]
-impl ConversationAccess for GrantingAccess {
- async fn bot_write(
- &self,
- user: &MacroUserIdStr<'static>,
- parent: &MessageParent,
- ) -> Result<EntityAccessReceipt<MessageWrite>, rootcause::Report> {
- Ok(EntityAccessReceipt::try_new_bot(
- bot_id::MACRO_AI_BOT_ID.into_storage_id(),
- BotReceiptScope::User {
- acting_user: user.clone(),
- },
- Entity {
- entity_id: parent.entity_id(),
- entity_type: EntityType::Channel,
- },
- EntityPermission::ChannelRole {
- role: ParticipantRole::Member,
- },
- )?)
- }
-}
-
-/// Records the shared message writes the handler makes.
-struct RecordingMessages {
- thinking_deleted: bool,
- posted: Mutex<Vec<(EntityAccessReceipt<MessageWrite>, PostMessage)>>,
- patched: Mutex<Vec<(EntityAccessReceipt<MessageWrite>, Uuid, MessagePatch)>>,
+struct Responder {
+ prompts: Mutex<Vec<String>>,
+ revoke: Option<Arc<Access>>,
+ result: &'static str,
}
-impl RecordingMessages {
- fn new(thinking_deleted: bool) -> Self {
- Self {
- thinking_deleted,
- posted: Mutex::new(Vec::new()),
- patched: Mutex::new(Vec::new()),
+#[async_trait]
+impl AgentResponder for Responder {
+ async fn respond(&self, user_id: &str, prompt: String) -> anyhow::Result<String> {
+ assert_eq!(user_id, user().as_ref());
+ self.prompts.lock().unwrap().push(prompt);
+ if let Some(access) = &self.revoke {
+ access.revoke();
}
- }
-
- fn posted_policies(&self) -> Vec<PostMessageNotificationPolicy> {
- self.posted
- .lock()
- .unwrap()
- .iter()
- .map(|(_, input)| input.notification_policy)
- .collect()
- }
-
- fn patched_contents(&self) -> Vec<String> {
- self.patched
- .lock()
- .unwrap()
- .iter()
- .filter_map(|(_, _, patch)| patch.content.clone())
- .collect()
- }
-
- fn patched_policies(&self) -> Vec<PatchMessageNotificationPolicy> {
- self.patched
- .lock()
- .unwrap()
- .iter()
- .map(|(_, _, patch)| patch.notification_policy)
- .collect()
+ if self.result == "error" {
+ anyhow::bail!("model error");
+ }
+ Ok(self.result.into())
}
}
-fn shared_message(access: &EntityAccessReceipt<MessageWrite>, content: &str) -> Message {
- Message {
- id: Uuid::new_v4(),
- parent: MessageParent::parse("channel", &access.entity().entity_id).unwrap(),
- thread_id: None,
- sender_id: Sender::new_from_bot(bot_id::MACRO_AI_BOT_ID),
- imported_author: None,
- bot_profile: None,
- mentions: Vec::new(),
- triggered_by: access
- .acting_user_id()
- .map(|user| user.as_ref().to_string()),
- content: content.to_string(),
- created_at: Utc::now(),
- updated_at: Utc::now(),
- edited_at: None,
- deleted_at: None,
- attachments: Vec::new(),
- reactions: Vec::new(),
- }
+fn responder(result: &'static str) -> Arc<Responder> {
+ Arc::new(Responder {
+ prompts: Mutex::new(vec![]),
+ revoke: None,
+ result,
+ })
}
-#[async_trait]
-impl MessageCommands for RecordingMessages {
- async fn post(
- &self,
- access: EntityAccessReceipt<MessageWrite>,
- input: PostMessage,
- ) -> Result<Message, MessageError> {
- let message = shared_message(&access, &input.content);
- self.posted.lock().unwrap().push((access, input));
- Ok(message)
- }
- async fn patch(
- &self,
- access: EntityAccessReceipt<MessageWrite>,
- id: Uuid,
- input: MessagePatch,
- ) -> Result<Message, MessageError> {
- if self.thinking_deleted {
- return Err(MessageError::NotFound);
- }
- let message = shared_message(&access, input.content.as_deref().unwrap_or_default());
- self.patched.lock().unwrap().push((access, id, input));
- Ok(message)
- }
- async fn delete(
- &self,
- _: EntityAccessReceipt<MessageWrite>,
- _: Uuid,
- _: Option<String>,
- ) -> Result<Message, MessageError> {
- unimplemented!()
- }
- async fn react(
- &self,
- _: EntityAccessReceipt<MessageWrite>,
- _: Uuid,
- _: String,
- _: bool,
- _: Option<String>,
- ) -> Result<Message, MessageError> {
- unimplemented!()
- }
- async fn typing(
- &self,
- _: EntityAccessReceipt<MessageWrite>,
- _: Option<Uuid>,
- _: bool,
- _: Option<String>,
- ) -> Result<(), MessageError> {
- unimplemented!()
- }
- async fn patch_thread(
- &self,
- _: EntityAccessReceipt<MessageWrite>,
- _: Uuid,
- _: ThreadPatch,
- ) -> Result<ThreadState, MessageError> {
- unimplemented!()
- }
- async fn delete_thread(
- &self,
- _: EntityAccessReceipt<MessageWrite>,
- _: Uuid,
- _: Option<String>,
- ) -> Result<ThreadState, MessageError> {
- unimplemented!()
- }
-}
-
-/// Time zone fake with a fixed answer.
struct FixedTimeZones(Option<&'static str>);
#[async_trait]
@@ -205,680 +47,298 @@ fn eastern_time_zones() -> Arc<FixedTimeZones> {
Arc::new(FixedTimeZones(Some("America/New_York")))
}
-struct TestChannelService {
- around_args: Mutex<Option<(Uuid, Uuid, i64, i64)>>,
- around_messages: Vec<ChannelContextMessage>,
- thread_replies: Vec<ThreadReply>,
+fn handler(
+ api: MockMessageServiceApi,
+ access: Arc<Access>,
+ responder: Arc<Responder>,
+) -> MacroAiHandler<Responder, FixedTimeZones> {
+ MacroAiHandler::new(Arc::new(api), access, responder, eastern_time_zones())
}
-impl ChannelService for TestChannelService {
- async fn set_channel_picture(
- &self,
- _access: channels::domain::ports::ChannelPictureAccess,
- _picture_id: Option<uuid::Uuid>,
- ) -> Result<(), channels::domain::ports::ChannelMutationErr> {
- unimplemented!("picture mutation is not used by this fixture")
- }
-
- fn get_channel_messages(
- &self,
- _channel_id: Uuid,
- _query: Query<Uuid, CreatedAt, ()>,
- _direction: MessagePageDirection,
- _limit: u16,
- _filters: &ChannelMessageFilters,
- _notification_user_id: Option<MacroUserIdStr<'static>>,
- ) -> impl Future<Output = Result<ChannelMessagesQueryResult, ChannelMessagesErr>> + Send {
- async move { unimplemented!("not needed for prompt tests") }
- }
-
- fn get_channel_attachments(
- &self,
- _channel_id: Uuid,
- _query: Query<Uuid, CreatedAt, ()>,
- _limit: u16,
- _attachment_type: Option<ChannelAttachmentType>,
- ) -> impl Future<Output = Result<ChannelAttachmentsPage, ChannelMessagesErr>> + Send {
- async move { unimplemented!("not needed for prompt tests") }
- }
-
- fn get_channel_participants(
- &self,
- _channel_id: Uuid,
- ) -> impl Future<Output = Result<Vec<ChannelParticipant>, ChannelMessagesErr>> + Send {
- async move { unimplemented!("not needed for prompt tests") }
- }
-
- fn get_message_context(
- &self,
- channel_id: Uuid,
- message_id: Uuid,
- before: i64,
- after: i64,
- ) -> impl Future<Output = Result<Vec<ChannelContextMessage>, ChannelMessagesErr>> + Send {
- // Record only the wide context fetch; the thread-parent lookup uses
- // a zero-width window.
- if before > 0 || after > 0 {
- *self.around_args.lock().unwrap() = Some((channel_id, message_id, before, after));
- }
- let messages = self.around_messages.clone();
- async move { Ok(messages) }
- }
-
- fn get_attachment_references(
- &self,
- _entity_type: String,
- _entity_id: String,
- _user_id: String,
- ) -> impl Future<Output = Result<Vec<AttachmentEntityReference>, ChannelMessagesErr>> + Send
- {
- async move { unimplemented!("not needed for prompt tests") }
- }
-
- fn get_channel_messages_around(
- &self,
- _channel_id: Uuid,
- _message_id: Uuid,
- _limit: u16,
- ) -> impl Future<Output = Result<ChannelMessagesQueryResult, ChannelMessagesErr>> + Send {
- async move { unimplemented!("not needed for prompt tests") }
- }
-
- fn get_thread_replies(
- &self,
- _channel_id: Uuid,
- _message_id: Uuid,
- ) -> impl Future<Output = Result<Vec<ThreadReply>, ChannelMessagesErr>> + Send {
- let replies = self.thread_replies.clone();
- async move { Ok(replies) }
- }
-
- fn resolve_message(
- &self,
- _channel_id: Uuid,
- _message_id: Uuid,
- ) -> impl Future<Output = Result<ResolvedChannelMessage, ChannelMessagesErr>> + Send {
- async move { unimplemented!("not needed for prompt tests") }
- }
-}
-
-struct TestResponder;
-
-#[async_trait]
-impl AgentResponder for TestResponder {
- async fn respond(&self, _user_id: &str, _prompt: String) -> anyhow::Result<String> {
- unimplemented!("not needed for prompt tests")
- }
-}
-
-/// Channel service fake for the post-thinking-then-patch flow: reads return no
-/// context and the legacy write methods are never reached.
-struct MutationChannelService;
-
-impl ChannelService for MutationChannelService {
- async fn set_channel_picture(
- &self,
- _access: channels::domain::ports::ChannelPictureAccess,
- _picture_id: Option<uuid::Uuid>,
- ) -> Result<(), channels::domain::ports::ChannelMutationErr> {
- unimplemented!("picture mutation is not used by this fixture")
- }
-
- fn get_channel_messages(
- &self,
- _channel_id: Uuid,
- _query: Query<Uuid, CreatedAt, ()>,
- _direction: MessagePageDirection,
- _limit: u16,
- _filters: &ChannelMessageFilters,
- _notification_user_id: Option<MacroUserIdStr<'static>>,
- ) -> impl Future<Output = Result<ChannelMessagesQueryResult, ChannelMessagesErr>> + Send {
- async move { unimplemented!("not needed for mutation tests") }
- }
-
- fn get_channel_attachments(
- &self,
- _channel_id: Uuid,
- _query: Query<Uuid, CreatedAt, ()>,
- _limit: u16,
- _attachment_type: Option<ChannelAttachmentType>,
- ) -> impl Future<Output = Result<ChannelAttachmentsPage, ChannelMessagesErr>> + Send {
- async move { unimplemented!("not needed for mutation tests") }
- }
-
- fn get_channel_participants(
- &self,
- _channel_id: Uuid,
- ) -> impl Future<Output = Result<Vec<ChannelParticipant>, ChannelMessagesErr>> + Send {
- async move { unimplemented!("not needed for mutation tests") }
- }
-
- fn get_message_context(
- &self,
- _channel_id: Uuid,
- _message_id: Uuid,
- _before: i64,
- _after: i64,
- ) -> impl Future<Output = Result<Vec<ChannelContextMessage>, ChannelMessagesErr>> + Send {
- async move { Ok(Vec::new()) }
- }
-
- fn get_attachment_references(
- &self,
- _entity_type: String,
- _entity_id: String,
- _user_id: String,
- ) -> impl Future<Output = Result<Vec<AttachmentEntityReference>, ChannelMessagesErr>> + Send
- {
- async move { unimplemented!("not needed for mutation tests") }
- }
-
- fn get_channel_messages_around(
- &self,
- _channel_id: Uuid,
- _message_id: Uuid,
- _limit: u16,
- ) -> impl Future<Output = Result<ChannelMessagesQueryResult, ChannelMessagesErr>> + Send {
- async move { unimplemented!("not needed for mutation tests") }
- }
-
- fn get_thread_replies(
- &self,
- _channel_id: Uuid,
- _message_id: Uuid,
- ) -> impl Future<Output = Result<Vec<ThreadReply>, ChannelMessagesErr>> + Send {
- async move { unimplemented!("not needed for mutation tests") }
- }
-
- fn resolve_message(
- &self,
- _channel_id: Uuid,
- _message_id: Uuid,
- ) -> impl Future<Output = Result<ResolvedChannelMessage, ChannelMessagesErr>> + Send {
- async move { unimplemented!("not needed for mutation tests") }
- }
-
- fn post_message(
- &self,
- _actor: Sender,
- _channel_id: Uuid,
- _req: PostMessageRequest,
- ) -> impl Future<Output = Result<PostMessageResponse, ChannelMutationErr>> + Send {
- async move { unimplemented!("replies go through the shared message commands") }
- }
-
- fn patch_message(
- &self,
- _actor: Sender,
- _actor_role: channels::domain::models::ParticipantRole,
- _channel_id: Uuid,
- _message_id: Uuid,
- _req: PatchMessageRequest,
- ) -> impl Future<Output = Result<(), ChannelMutationErr>> + Send {
- async move { unimplemented!("replies go through the shared message commands") }
+fn invocation(trigger: &messages::domain::models::Message) -> BotEvent {
+ BotEvent {
+ trigger: BotTrigger::Mention,
+ message: event(trigger),
+ reply_thread_id: trigger.root_id(),
+ requesting_user: user(),
}
}
-struct FixedResponder(&'static str);
-
-#[async_trait]
-impl AgentResponder for FixedResponder {
- async fn respond(&self, _user_id: &str, _prompt: String) -> anyhow::Result<String> {
- Ok(self.0.to_string())
- }
+fn expect_placeholder(api: &mut MockMessageServiceApi) {
+ api.expect_post().once().returning(|access, input| {
+ assert_eq!(
+ access.get_authenticated_bot_auth().unwrap().bot_id(),
+ bot_id::MACRO_AI_BOT_ID
+ );
+ assert_eq!(access.acting_user_id(), Some(&user()));
+ assert_eq!(input.attribution, MessageAttribution::ActingUser);
+ assert_eq!(input.thread_id, Some(Uuid::from_u128(1)));
+ assert_eq!(
+ input.notification_policy,
+ PostMessageNotificationPolicy::Silent
+ );
+ assert_eq!(input.content, THINKING_MESSAGE);
+ Ok(message(3, input.thread_id, &input.content))
+ });
}
-fn user_id(email: &str) -> MacroUserIdStr<'static> {
- MacroUserIdStr::try_from(format!("macro|{email}")).unwrap()
+#[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");
+ let trigger = message(2, Some(root.id), "@macro explain this");
+ let mut api = MockMessageServiceApi::new();
+ configure_reads(&mut api, &trigger, thread(root, vec![trigger.clone()]));
+ expect_placeholder(&mut api);
+ api.expect_patch().once().returning(|access, id, input| {
+ assert_eq!(access.entity().entity_id, parent().entity_id());
+ assert_eq!(id, Uuid::from_u128(3));
+ assert_eq!(input.content.as_deref(), Some("the answer"));
+ assert_eq!(
+ input.notification_policy,
+ PatchMessageNotificationPolicy::NotifyAsPostedMessage
+ );
+ Ok(message(
+ 3,
+ Some(Uuid::from_u128(1)),
+ input.content.as_deref().unwrap(),
+ ))
+ });
+ let responder = responder("the answer");
+ handler(api, Arc::new(Access::default()), responder.clone())
+ .handle(&invocation(&trigger))
+ .await
+ .unwrap();
+ let prompts = responder.prompts.lock().unwrap();
+ assert!(prompts[0].contains("discussion-document"));
+ assert!(prompts[0].contains("mentioned you (@macro) in a document discussion."));
+ assert!(prompts[0].contains("Selected paragraph discussion"));
+ assert!(prompts[0].contains(MENTION_TRIGGER_MARKER));
+ assert!(!prompts[0].contains("<channel_background>"));
+ assert!(prompts[0].ends_with("Reply to person."));
}
-fn context_message(
- channel_id: Uuid,
- id: Uuid,
- sender_id: &str,
- content: &str,
-) -> ChannelContextMessage {
- let now = Utc::now();
- ChannelContextMessage {
- id,
- channel_id,
- thread_id: None,
- sender_id: sender_id.to_string(),
- content: content.to_string(),
- created_at: now,
- updated_at: now,
- edited_at: None,
- deleted_at: None,
- bot_profile: None,
- triggered_by: None,
- }
+#[tokio::test]
+async fn root_comment_is_valid_agent_context_before_any_replies_exist() {
+ let trigger = message(1, None, "@macro help with this document");
+ let mut api = MockMessageServiceApi::new();
+ configure_reads(&mut api, &trigger, thread(trigger.clone(), vec![]));
+ let prompt = handler(api, Arc::new(Access::default()), responder("reply"))
+ .build_prompt(&invocation(&trigger))
+ .await
+ .unwrap();
+ assert_eq!(prompt.matches("@macro help with this document").count(), 1);
+ assert!(prompt.contains("<thread>"));
}
-fn thread_reply(id: Uuid, sender_id: &str, content: &str) -> ThreadReply {
- let now = Utc::now();
- ThreadReply {
- id,
- sender_id: sender_id.to_string(),
- bot_profile: None,
- content: content.to_string(),
- created_at: now,
- updated_at: now,
- edited_at: None,
- triggered_by: None,
- reactions: Vec::new(),
- attachments: Vec::new(),
- }
+#[tokio::test]
+async fn revoked_document_access_prevents_context_reads_and_agent_work() {
+ let trigger = message(1, None, "@macro help");
+ let access = Arc::new(Access::default());
+ access.revoke();
+ let responder = responder("reply");
+ let handler = handler(MockMessageServiceApi::new(), access, responder.clone());
+ assert!(handler.handle(&invocation(&trigger)).await.is_err());
+ assert!(responder.prompts.lock().unwrap().is_empty());
}
-fn mention_event(
- channel_id: Uuid,
- trigger_id: Uuid,
- thread_id: Option<Uuid>,
- sender_email: &str,
- content: &str,
-) -> BotEvent {
- bot_event(
- BotTrigger::Mention,
- channel_id,
- trigger_id,
- thread_id,
- sender_email,
- content,
- )
+#[tokio::test]
+async fn revocation_while_model_runs_prevents_answer_delivery() {
+ let trigger = message(1, None, "@macro help");
+ let mut api = MockMessageServiceApi::new();
+ configure_reads(&mut api, &trigger, thread(trigger.clone(), vec![]));
+ expect_placeholder(&mut api);
+ let access = Arc::new(Access::default());
+ let responder = Arc::new(Responder {
+ prompts: Mutex::new(vec![]),
+ revoke: Some(access.clone()),
+ result: "private answer",
+ });
+ assert!(
+ handler(api, access, responder)
+ .handle(&invocation(&trigger))
+ .await
+ .is_err()
+ );
}
-fn bot_event(
- trigger: BotTrigger,
- channel_id: Uuid,
- trigger_id: Uuid,
- thread_id: Option<Uuid>,
- sender_email: &str,
- content: &str,
-) -> BotEvent {
- BotEvent {
- trigger,
- channel_id,
- message: MutatedMessage {
- id: trigger_id,
- channel_id,
- thread_id,
- sender_id: Sender::new_from_user(user_id(sender_email)),
- content: content.to_string(),
- created_at: Utc::now(),
- updated_at: Utc::now(),
- edited_at: None,
- deleted_at: None,
- triggered_by: None,
- },
- reply_thread_id: thread_id.unwrap_or(trigger_id),
- requesting_user: user_id(sender_email),
- }
+#[tokio::test]
+async fn deleted_placeholder_does_not_recreate_a_response() {
+ let trigger = message(1, None, "@macro help");
+ let mut api = MockMessageServiceApi::new();
+ configure_reads(&mut api, &trigger, thread(trigger.clone(), vec![]));
+ expect_placeholder(&mut api);
+ api.expect_patch()
+ .once()
+ .returning(|_, _, _| Err(MessageError::NotFound));
+ handler(api, Arc::new(Access::default()), responder("answer"))
+ .handle(&invocation(&trigger))
+ .await
+ .unwrap();
}
#[tokio::test]
-async fn handle_patches_thinking_message_with_reply() {
- let channel_id = Uuid::new_v4();
- let channels = Arc::new(MutationChannelService);
- let messages = Arc::new(RecordingMessages::new(false));
- let handler = MacroAiHandler::new(
- channels.clone(),
- messages.clone(),
- Arc::new(GrantingAccess),
- Arc::new(FixedResponder("the answer")),
- eastern_time_zones(),
- );
-
- handler
- .handle(&mention_event(
- channel_id,
- Uuid::new_v4(),
- None,
- "@macro help",
+async fn responder_failure_still_replaces_the_placeholder_with_a_fallback() {
+ let trigger = message(1, None, "@macro help");
+ let mut api = MockMessageServiceApi::new();
+ configure_reads(&mut api, &trigger, thread(trigger.clone(), vec![]));
+ expect_placeholder(&mut api);
+ api.expect_patch().once().returning(|_, id, input| {
+ assert_eq!(input.content.as_deref(), Some(ERROR_FALLBACK));
+ Ok(message(
+ 3,
+ Some(Uuid::from_u128(1)),
+ &input.content.unwrap(),
))
+ .map(|mut m| {
+ m.id = id;
+ m
+ })
+ });
+ handler(api, Arc::new(Access::default()), responder("error"))
+ .handle(&invocation(&trigger))
.await
.unwrap();
-
- assert_eq!(
- messages.posted_policies(),
- vec![PostMessageNotificationPolicy::Silent]
- );
- let posted = messages.posted.lock().unwrap();
- assert_eq!(
- posted[0].0.acting_user_id().map(|user| user.as_ref()),
- Some("macro|[email protected]")
- );
- assert_eq!(posted[0].0.entity().entity_id, channel_id.to_string());
- assert_eq!(
- posted[0].1.attribution,
- messages::domain::models::MessageAttribution::ActingUser
- );
- drop(posted);
- assert_eq!(messages.patched_contents(), vec!["the answer".to_string()]);
- assert_eq!(
- messages.patched_policies(),
- vec![PatchMessageNotificationPolicy::NotifyAsPostedMessage]
- );
}
#[tokio::test]
-async fn handle_drops_reply_when_thinking_message_was_deleted() {
- let channel_id = Uuid::new_v4();
- let channels = Arc::new(MutationChannelService);
- let messages = Arc::new(RecordingMessages::new(true));
- let handler = MacroAiHandler::new(
- channels.clone(),
- messages.clone(),
- Arc::new(GrantingAccess),
- Arc::new(FixedResponder("the answer")),
- eastern_time_zones(),
- );
-
- handler
- .handle(&mention_event(
- channel_id,
- Uuid::new_v4(),
- None,
- "@macro help",
- ))
+async fn inference_prompt_describes_a_follow_up_without_claiming_a_mention() {
+ let root = message(1, None, "initial question");
+ let trigger = message(2, Some(root.id), "what about tomorrow?");
+ let mut api = MockMessageServiceApi::new();
+ configure_reads(&mut api, &trigger, thread(root, vec![trigger.clone()]));
+ let mut event = invocation(&trigger);
+ event.trigger = BotTrigger::Inferred;
+ let prompt = handler(api, Arc::new(Access::default()), responder("reply"))
+ .build_prompt(&event)
.await
.unwrap();
-
- assert!(messages.patched.lock().unwrap().is_empty());
- assert_eq!(messages.posted.lock().unwrap().len(), 1);
+ assert!(prompt.contains("replied in a document discussion you are part of."));
+ assert!(prompt.contains(INFERRED_TRIGGER_MARKER));
+ assert!(!prompt.contains(MENTION_TRIGGER_MARKER));
}
#[tokio::test]
-async fn top_level_prompt_marks_trigger_inline_in_channel_context() {
- let channel_id = Uuid::new_v4();
- let trigger_id = Uuid::new_v4();
- let before_id = Uuid::new_v4();
- let after_id = Uuid::new_v4();
- let channels = Arc::new(TestChannelService {
- around_args: Mutex::new(None),
- around_messages: vec![
- context_message(channel_id, before_id, "macro|[email protected]", "before"),
- context_message(
- channel_id,
- trigger_id,
- "@macro help",
- ),
- context_message(channel_id, after_id, "macro|[email protected]", "after"),
- ],
- thread_replies: Vec::new(),
- });
- let messages = Arc::new(RecordingMessages::new(false));
- let handler = MacroAiHandler::new(
- channels.clone(),
- messages.clone(),
- Arc::new(GrantingAccess),
- Arc::new(TestResponder),
- eastern_time_zones(),
- );
- let event = mention_event(
- channel_id,
- trigger_id,
- None,
- "@macro help",
+async fn channel_context_keeps_other_threads_as_background() {
+ let parent = MessageParent::Channel(Uuid::from_u128(900));
+ let mut root = message(1, None, "thread subject");
+ root.parent = parent.clone();
+ let mut trigger = message(2, Some(root.id), "@macro explain this");
+ trigger.parent = parent.clone();
+ let mut nearby = message(4, None, "unrelated channel background");
+ nearby.parent = parent;
+ let mut api = MockMessageServiceApi::new();
+ configure_reads(&mut api, &trigger, thread(root, vec![trigger.clone()]));
+ api.expect_preceding()
+ .once()
+ .returning(move |_, _, _| Ok(vec![nearby.clone()]));
+ let prompt = handler(api, Arc::new(Access::default()), responder("reply"))
+ .build_prompt(&invocation(&trigger))
+ .await
+ .unwrap();
+ assert!(prompt.contains("mentioned you (@macro) in a channel thread."));
+ assert!(
+ prompt.find("thread subject").unwrap()
+ < prompt.find("unrelated channel background").unwrap()
);
+ assert!(prompt.contains("<channel_background>"));
+}
- let prompt = handler.build_prompt(&event).await;
-
- assert_eq!(
- *channels.around_args.lock().unwrap(),
- Some((
- channel_id,
- trigger_id,
- CONTEXT_MESSAGES_BEFORE,
- CONTEXT_MESSAGES_AFTER
- ))
+#[tokio::test]
+async fn top_level_channel_mention_marks_the_trigger_inline_in_channel_context() {
+ let parent = MessageParent::Channel(Uuid::from_u128(900));
+ let mut trigger = message(2, None, "@macro help");
+ trigger.parent = parent.clone();
+ let mut before = message(1, None, "before");
+ before.parent = parent;
+ before.sender_id = channel_sender::ChannelSender::new_from_user(
+ "macro|[email protected]".to_string().try_into().unwrap(),
);
+ let mut api = MockMessageServiceApi::new();
+ configure_reads(&mut api, &trigger, thread(trigger.clone(), vec![]));
+ api.expect_preceding()
+ .once()
+ .returning(move |_, id, limit| {
+ assert_eq!(id, Uuid::from_u128(2));
+ assert_eq!(limit, CONTEXT_MESSAGES_BEFORE);
+ Ok(vec![before.clone()])
+ });
+ let prompt = handler(api, Arc::new(Access::default()), responder("reply"))
+ .build_prompt(&invocation(&trigger))
+ .await
+ .unwrap();
+
assert!(prompt.contains("mentioned you (@macro) in a channel."));
assert!(prompt.contains("<channel_context>"));
- assert!(prompt.contains("</channel_context>"));
assert!(prompt.contains("alice: before"));
- assert!(prompt.contains("bob: after"));
- assert!(prompt.contains("teo [this message mentioned you]: @macro help"));
+ assert!(prompt.contains("person [this message mentioned you]: @macro help"));
// The trigger appears once, inline, not repeated at the end.
assert_eq!(prompt.matches("@macro help").count(), 1);
assert!(!prompt.contains("<thread>"));
- assert!(prompt.ends_with("Reply to teo."));
+ assert!(prompt.ends_with("Reply to person."));
}
#[tokio::test]
-async fn thread_prompt_puts_thread_first_and_demotes_channel_noise() {
- let channel_id = Uuid::new_v4();
- let parent_id = Uuid::new_v4();
- let trigger_id = Uuid::new_v4();
- let unrelated_id = Uuid::new_v4();
-
- let mut trigger_context = context_message(
- channel_id,
- trigger_id,
- "@macro can you make a task out of this?",
- );
- trigger_context.thread_id = Some(parent_id);
-
- let channels = Arc::new(TestChannelService {
- around_args: Mutex::new(None),
- around_messages: vec![
- context_message(
- channel_id,
- parent_id,
- "We stopped persisting filter/sort across refresh",
- ),
- context_message(
- channel_id,
- unrelated_id,
- "unrelated tasks view chatter",
- ),
- trigger_context,
- ],
- thread_replies: vec![thread_reply(
- trigger_id,
- "@macro can you make a task out of this?",
- )],
- });
- let messages = Arc::new(RecordingMessages::new(false));
- let handler = MacroAiHandler::new(
- channels.clone(),
- messages.clone(),
- Arc::new(GrantingAccess),
- Arc::new(TestResponder),
- eastern_time_zones(),
- );
- let event = mention_event(
- channel_id,
- trigger_id,
- Some(parent_id),
- "@macro can you make a task out of this?",
- );
-
- let prompt = handler.build_prompt(&event).await;
-
- assert!(prompt.contains("austin mentioned you (@macro) in a channel thread."));
-
- // Thread block comes first and contains parent + marked trigger.
- let thread_start = prompt.find("<thread>").expect("thread block");
- let thread_end = prompt.find("</thread>").expect("thread block end");
- let thread_block = &prompt[thread_start..thread_end];
- assert!(thread_block.contains("peter: We stopped persisting filter/sort across refresh"));
- assert!(
- thread_block.contains(
- "austin [this message mentioned you]: @macro can you make a task out of this?"
- )
- );
- assert!(!thread_block.contains("carol"));
-
- // Channel noise is demoted to the background block, with thread messages excluded.
- let background_start = prompt
- .find("<channel_background>")
- .expect("background block");
- assert!(background_start > thread_end);
- let background_end = prompt
- .find("</channel_background>")
- .expect("background end");
- let background_block = &prompt[background_start..background_end];
- assert!(background_block.contains("carol: unrelated tasks view chatter"));
- assert!(!background_block.contains("peter:"));
- assert!(!background_block.contains("austin"));
-
- // The trigger appears exactly once across the whole prompt.
- assert_eq!(
- prompt
- .matches("@macro can you make a task out of this?")
- .count(),
- 1
- );
- assert!(prompt.ends_with("Reply to austin."));
-}
-
-#[tokio::test]
-async fn inferred_thread_prompt_does_not_claim_a_mention() {
- let channel_id = Uuid::new_v4();
- let parent_id = Uuid::new_v4();
- let trigger_id = Uuid::new_v4();
- let macro_ai = bot_id::MACRO_AI_BOT_ID.into_storage_id().to_string();
-
- let channels = Arc::new(TestChannelService {
- around_args: Mutex::new(None),
- around_messages: vec![context_message(
- channel_id,
- parent_id,
- "notifications are broken",
- )],
- thread_replies: vec![
- thread_reply(Uuid::new_v4(), &macro_ai, "what is broken exactly?"),
- thread_reply(trigger_id, "macro|[email protected]", "it fires twice"),
- ],
- });
- let messages = Arc::new(RecordingMessages::new(false));
- let handler = MacroAiHandler::new(
- channels.clone(),
- messages.clone(),
- Arc::new(GrantingAccess),
- Arc::new(TestResponder),
- eastern_time_zones(),
- );
- let event = bot_event(
- BotTrigger::Inferred,
- channel_id,
- trigger_id,
- Some(parent_id),
- "it fires twice",
- );
-
- let prompt = handler.build_prompt(&event).await;
-
- assert!(prompt.contains("alice replied in a channel thread you are part of."));
- assert!(!prompt.contains("mentioned you (@macro)"));
- assert!(prompt.contains("alice [respond to this message]: it fires twice"));
- assert!(!prompt.contains("[this message mentioned you]"));
- assert!(prompt.ends_with("Reply to alice."));
+async fn unavailable_context_blocks_instead_of_prompting_from_an_unverified_event() {
+ let trigger = message(1, None, "@macro help");
+ let mut api = MockMessageServiceApi::new();
+ api.expect_get()
+ .once()
+ .returning(|_, _| Err(MessageError::NotFound));
+ let responder = responder("reply");
+ let handler = handler(api, Arc::new(Access::default()), responder.clone());
+ assert!(handler.handle(&invocation(&trigger)).await.is_err());
+ assert!(responder.prompts.lock().unwrap().is_empty());
}
#[tokio::test]
-async fn thread_prompt_includes_trigger_when_reply_fetch_fails_to_return_it() {
- let channel_id = Uuid::new_v4();
- let parent_id = Uuid::new_v4();
- let trigger_id = Uuid::new_v4();
-
- let channels = Arc::new(TestChannelService {
- around_args: Mutex::new(None),
- around_messages: vec![context_message(
- channel_id,
- parent_id,
- "parent message",
- )],
- thread_replies: Vec::new(),
- });
- let messages = Arc::new(RecordingMessages::new(false));
- let handler = MacroAiHandler::new(
- channels.clone(),
- messages.clone(),
- Arc::new(GrantingAccess),
- Arc::new(TestResponder),
- eastern_time_zones(),
- );
- let event = mention_event(
- channel_id,
- trigger_id,
- Some(parent_id),
- "@macro help with this",
+async fn a_trigger_that_moved_threads_or_changed_author_is_not_prompted() {
+ let trigger = message(1, None, "@macro help");
+ let mut relocated = trigger.clone();
+ relocated.sender_id = channel_sender::ChannelSender::new_from_user(
+ .to_string()
+ .try_into()
+ .unwrap(),
);
-
- let prompt = handler.build_prompt(&event).await;
-
- assert!(prompt.contains("peter: parent message"));
- assert!(prompt.contains("austin [this message mentioned you]: @macro help with this"));
+ let mut api = MockMessageServiceApi::new();
+ api.expect_get()
+ .once()
+ .returning(move |_, _| Ok(relocated.clone()));
+ let responder = responder("reply");
+ let handler = handler(api, Arc::new(Access::default()), responder.clone());
+ assert!(handler.handle(&invocation(&trigger)).await.is_err());
+ assert!(responder.prompts.lock().unwrap().is_empty());
}
#[tokio::test]
async fn prompt_carries_the_current_time_in_the_users_zone() {
- let channels = Arc::new(TestChannelService {
- around_args: Mutex::new(None),
- around_messages: Vec::new(),
- thread_replies: Vec::new(),
- });
- let messages = Arc::new(RecordingMessages::new(false));
- let handler = MacroAiHandler::new(
- channels,
- messages.clone(),
- Arc::new(GrantingAccess),
- Arc::new(TestResponder),
- eastern_time_zones(),
- );
- let event = mention_event(
- Uuid::new_v4(),
- Uuid::new_v4(),
- None,
- "@macro help",
- );
-
- let prompt = handler.build_prompt(&event).await;
+ let trigger = message(1, None, "@macro help");
+ let mut api = MockMessageServiceApi::new();
+ configure_reads(&mut api, &trigger, thread(trigger.clone(), vec![]));
+ let prompt = handler(api, Arc::new(Access::default()), responder("reply"))
+ .build_prompt(&invocation(&trigger))
+ .await
+ .unwrap();
assert!(prompt.contains("<current_time>"));
assert!(prompt.contains("America/New_York, the time zone of the user's primary calendar"));
- assert!(prompt.ends_with("Reply to teo."));
+ assert!(prompt.ends_with("Reply to person."));
}
#[tokio::test]
async fn prompt_says_the_time_zone_is_unknown_without_a_calendar() {
- let channels = Arc::new(TestChannelService {
- around_args: Mutex::new(None),
- around_messages: Vec::new(),
- thread_replies: Vec::new(),
- });
- let messages = Arc::new(RecordingMessages::new(false));
- let handler = MacroAiHandler::new(
- channels,
- messages.clone(),
- Arc::new(GrantingAccess),
- Arc::new(TestResponder),
+ let trigger = message(1, None, "@macro help");
+ let mut api = MockMessageServiceApi::new();
+ configure_reads(&mut api, &trigger, thread(trigger.clone(), vec![]));
+ let prompt = MacroAiHandler::new(
+ Arc::new(api),
+ Arc::new(Access::default()),
+ responder("reply"),
Arc::new(FixedTimeZones(None)),
- );
- let event = mention_event(
- Uuid::new_v4(),
- Uuid::new_v4(),
- None,
- "@macro help",
- );
-
- let prompt = handler.build_prompt(&event).await;
+ )
+ .build_prompt(&invocation(&trigger))
+ .await
+ .unwrap();
assert!(prompt.contains("UTC; the user's own time zone is unknown"));
}
diff --git a/crates/channel_bots/src/domain/test.rs b/crates/channel_bots/src/domain/test.rs
new file mode 100644
index 0000000000..b1f2b8dccf
--- /dev/null
+++ b/crates/channel_bots/src/domain/test.rs
@@ -0,0 +1,146 @@
+use super::ports::ConversationAccess;
+use async_trait::async_trait;
+use entity_access::domain::models::{
+ AccessLevel, BotReceiptScope, EntityAccessReceipt, EntityPermission, EntityType,
+ ParticipantRole,
+};
+use macro_user_id::user_id::MacroUserIdStr;
+use messages::domain::{
+ api::MockMessageServiceApi,
+ events::MessagePostedMetadata,
+ models::{Message, MessageParent, MessageThread, ThreadState},
+ service::MessageWrite,
+};
+use std::sync::{
+ Arc,
+ atomic::{AtomicBool, Ordering},
+};
+use uuid::Uuid;
+
+pub(super) fn user() -> MacroUserIdStr<'static> {
+ "macro|[email protected]".to_string().try_into().unwrap()
+}
+pub(super) fn parent() -> MessageParent {
+ MessageParent::parse("document", "discussion-document").unwrap()
+}
+pub(crate) fn message(id: u128, thread: Option<Uuid>, body: &str) -> Message {
+ Message {
+ id: Uuid::from_u128(id),
+ parent: parent(),
+ thread_id: thread,
+ sender_id: channel_sender::ChannelSender::new_from_user(user()),
+ bot_profile: None,
+ mentions: vec![],
+ imported_author: None,
+ triggered_by: None,
+ content: body.into(),
+ created_at: chrono::Utc::now(),
+ updated_at: chrono::Utc::now(),
+ edited_at: None,
+ deleted_at: None,
+ attachments: vec![],
+ reactions: vec![],
+ }
+}
+pub(super) fn event(message: &Message) -> MessagePostedMetadata {
+ MessagePostedMetadata::from_message(message, message.mentions.clone())
+}
+pub(super) fn thread(root: Message, replies: Vec<Message>) -> MessageThread {
+ MessageThread {
+ state: ThreadState {
+ root_id: root.id,
+ user_id: user().to_string(),
+ anchor: None,
+ resolved: false,
+ created_at: root.created_at,
+ updated_at: root.updated_at,
+ deleted_at: None,
+ },
+ root,
+ replies,
+ }
+}
+pub(super) fn configure_reads(
+ api: &mut MockMessageServiceApi,
+ trigger: &Message,
+ history: MessageThread,
+) {
+ let current = trigger.clone();
+ api.expect_get().returning(move |receipt, id| {
+ assert_eq!(receipt.entity().entity_id, current.parent.entity_id());
+ assert_eq!(id, current.id);
+ Ok(current.clone())
+ });
+ api.expect_get_thread().returning(move |receipt, id| {
+ assert_eq!(receipt.entity().entity_id, history.root.parent.entity_id());
+ assert_eq!(id, history.root.id);
+ Ok(history.clone())
+ });
+}
+#[derive(Default)]
+pub(super) struct Access {
+ pub revoked: Arc<AtomicBool>,
+}
+impl Access {
+ pub fn revoke(&self) {
+ self.revoked.store(true, Ordering::SeqCst);
+ }
+ fn permission(
+ &self,
+ parent: &MessageParent,
+ ) -> Result<(entity_access::domain::models::Entity, EntityPermission), rootcause::Report> {
+ if self.revoked.load(Ordering::SeqCst) {
+ return Err(rootcause::report!("document access revoked"));
+ }
+ Ok(match parent {
+ MessageParent::Document(_) => (
+ entity_access::domain::models::Entity {
+ entity_type: EntityType::Document,
+ entity_id: parent.entity_id(),
+ },
+ EntityPermission::AccessLevel {
+ access_level: AccessLevel::Comment,
+ },
+ ),
+ MessageParent::Channel(_) => (
+ entity_access::domain::models::Entity {
+ entity_type: EntityType::Channel,
+ entity_id: parent.entity_id(),
+ },
+ EntityPermission::ChannelRole {
+ role: ParticipantRole::Member,
+ },
+ ),
+ })
+ }
+}
+#[async_trait]
+impl ConversationAccess for Access {
+ async fn user_write(
+ &self,
+ user: &MacroUserIdStr<'static>,
+ parent: &MessageParent,
+ ) -> Result<EntityAccessReceipt<MessageWrite>, rootcause::Report> {
+ let (entity, permission) = self.permission(parent)?;
+ Ok(EntityAccessReceipt::try_new_authenticated_user(
+ user.clone(),
+ entity,
+ permission,
+ )?)
+ }
+ async fn bot_write(
+ &self,
+ user: &MacroUserIdStr<'static>,
+ parent: &MessageParent,
+ ) -> Result<EntityAccessReceipt<MessageWrite>, rootcause::Report> {
+ let (entity, permission) = self.permission(parent)?;
+ Ok(EntityAccessReceipt::try_new_bot(
+ bot_id::MACRO_AI_BOT_ID.into_storage_id(),
+ BotReceiptScope::User {
+ acting_user: user.clone(),
+ },
+ entity,
+ permission,
+ )?)
+ }
+}
diff --git a/crates/channel_bots/src/domain/trigger_detector.rs b/crates/channel_bots/src/domain/trigger_detector.rs
index 3d3d6cc799..cff4066b56 100644
--- a/crates/channel_bots/src/domain/trigger_detector.rs
+++ b/crates/channel_bots/src/domain/trigger_detector.rs
@@ -3,12 +3,11 @@
use std::sync::Arc;
use async_trait::async_trait;
-use channels::domain::ports::ChannelService;
-use channels::domain::side_effects::ChannelBotTrigger;
+use messages::domain::{api::MessageReader, events::MessagePostedMetadata};
use uuid::Uuid;
use super::models::{BotInvocation, BotTrigger, TranscriptMessage};
-use super::ports::{InferredTriggerClassifier, TriggerDetector};
+use super::ports::{ConversationAccess, InferredTriggerClassifier, TriggerDetector};
use super::sender_label;
/// Detects both explicit `@`-mention triggers and inferred triggers.
@@ -23,20 +22,25 @@ use super::sender_label;
///
/// Bot-authored messages never trigger anything; classifier failures resolve
/// to no trigger.
-pub struct MentionOrInferredDetector<C, I> {
- channels: Arc<C>,
+pub struct MentionOrInferredDetector<I> {
+ messages: Arc<dyn MessageReader>,
+ access: Arc<dyn ConversationAccess>,
classifier: Arc<I>,
}
-impl<C, I> MentionOrInferredDetector<C, I>
+impl<I> MentionOrInferredDetector<I>
where
- C: ChannelService,
I: InferredTriggerClassifier,
{
/// Create a detector from the channel read service and a classifier.
- pub fn new(channels: Arc<C>, classifier: Arc<I>) -> Self {
+ pub fn new(
+ messages: Arc<dyn MessageReader>,
+ access: Arc<dyn ConversationAccess>,
+ classifier: Arc<I>,
+ ) -> Self {
Self {
- channels,
+ messages,
+ access,
classifier,
}
}
@@ -46,54 +50,51 @@ where
/// yet.
async fn thread_transcript(
&self,
- candidate: &ChannelBotTrigger,
+ candidate: &MessagePostedMetadata,
parent_id: Uuid,
- ) -> Vec<TranscriptMessage> {
- let mut transcript = Vec::new();
-
- let parent = self
- .channels
- .get_message_context(candidate.channel_id, parent_id, 0, 0)
+ ) -> anyhow::Result<Vec<TranscriptMessage>> {
+ let user = candidate
+ .sender
+ .as_user()
+ .ok_or_else(|| anyhow::anyhow!("only users invoke agents"))?;
+ let access = self
+ .access
+ .user_write(user, &candidate.parent)
.await
- .inspect_err(|err| tracing::warn!(error=?err, "failed to load thread parent"))
- .unwrap_or_default()
- .into_iter()
- .find(|message| message.id == parent_id);
- if let Some(parent) = parent
- && parent.deleted_at.is_none()
- && !parent.content.trim().is_empty()
+ .map_err(|e| anyhow::anyhow!(e.to_string()))?;
+ let view = access.try_into_requirement()?;
+ let current = self
+ .messages
+ .get(view.clone(), candidate.message_id)
+ .await?;
+ if current.deleted_at.is_some()
+ || current.root_id() != parent_id
+ || current.sender_id != candidate.sender
{
- transcript.push(transcript_message(&parent.sender_id, &parent.content));
+ anyhow::bail!("invalid trigger origin");
}
-
- let replies = self
- .channels
- .get_thread_replies(candidate.channel_id, parent_id)
- .await
- .inspect_err(|err| tracing::warn!(error=?err, "failed to load thread replies"))
- .unwrap_or_default();
- let mut candidate_included = false;
- for reply in replies {
- if reply.content.trim().is_empty() {
- continue;
+ let thread = self.messages.get_thread(view, parent_id).await?;
+ let mut transcript = Vec::new();
+ for message in std::iter::once(thread.root).chain(thread.replies) {
+ if message.deleted_at.is_none() && !message.content.trim().is_empty() {
+ transcript.push(transcript_message(
+ message.sender_id.as_ref(),
+ &message.content,
+ ));
}
- candidate_included |= reply.id == candidate.message.id;
- transcript.push(transcript_message(&reply.sender_id, &reply.content));
- }
- if !candidate_included {
- transcript.push(transcript_message(
- candidate.message.sender_id.as_ref(),
- &candidate.message.content,
- ));
}
- transcript
+ Ok(transcript)
}
- async fn infer(&self, candidate: &ChannelBotTrigger) -> Option<BotInvocation> {
- let requesting_user = candidate.message.sender_id.as_user()?;
- let parent_id = candidate.message.thread_id?;
+ async fn infer(&self, candidate: &MessagePostedMetadata) -> Option<BotInvocation> {
+ let requesting_user = candidate.sender.as_user()?;
+ let parent_id = candidate.thread_id?;
- let transcript = self.thread_transcript(candidate, parent_id).await;
+ let transcript = self
+ .thread_transcript(candidate, parent_id)
+ .await
+ .inspect_err(|err| tracing::warn!(error=?err, "unable to load authorized bot thread"))
+ .ok()?;
if !transcript.iter().any(|message| message.from_agent) {
return None;
}
@@ -127,21 +128,31 @@ fn transcript_message(sender_id: &str, content: &str) -> TranscriptMessage {
}
#[async_trait]
-impl<C, I> TriggerDetector for MentionOrInferredDetector<C, I>
+impl<I> TriggerDetector for MentionOrInferredDetector<I>
where
- C: ChannelService,
I: InferredTriggerClassifier,
{
- async fn detect(&self, candidate: &ChannelBotTrigger) -> Vec<BotInvocation> {
- if candidate.message.sender_id.as_user().is_none() {
+ async fn detect(&self, candidate: &MessagePostedMetadata) -> Vec<BotInvocation> {
+ if candidate.sender.as_user().is_none() {
+ return Vec::new();
+ }
+ let Some(user) = candidate.sender.as_user() else {
+ return Vec::new();
+ };
+ if self
+ .access
+ .user_write(user, &candidate.parent)
+ .await
+ .is_err()
+ {
return Vec::new();
}
- if !candidate.mentioned_bot_ids.is_empty() {
- return candidate
- .mentioned_bot_ids
- .iter()
+ let mentioned = messages::domain::mentions::bot_mention_ids(&candidate.mentions);
+ if !mentioned.is_empty() {
+ return mentioned
+ .into_iter()
.map(|bot_id| BotInvocation {
- bot_id: *bot_id,
+ bot_id,
trigger: BotTrigger::Mention,
})
.collect();
diff --git a/crates/channel_bots/src/domain/trigger_detector/tests.rs b/crates/channel_bots/src/domain/trigger_detector/tests.rs
index 825dc7aca1..ba100defd7 100644
--- a/crates/channel_bots/src/domain/trigger_detector/tests.rs
+++ b/crates/channel_bots/src/domain/trigger_detector/tests.rs
@@ -1,476 +1,158 @@
-use std::sync::{Arc, Mutex};
-
-use async_trait::async_trait;
-use channels::domain::models::{
- AttachmentEntityReference, ChannelAttachmentType, ChannelContextMessage, ChannelMessageFilters,
- ChannelParticipant, MessagePageDirection, MutatedMessage, ResolvedChannelMessage, Sender,
- ThreadReply,
-};
-use channels::domain::ports::{
- ChannelAttachmentsPage, ChannelMessagesErr, ChannelMessagesQueryResult, ChannelService,
-};
-use chrono::Utc;
-use macro_user_id::user_id::MacroUserIdStr;
-use models_pagination::{CreatedAt, Query};
-
+use super::super::test::*;
use super::*;
+use messages::domain::{api::MockMessageServiceApi, models::SimpleMention};
+use std::sync::Mutex;
-struct TestChannelService {
- parent: Option<ChannelContextMessage>,
- thread_replies: Vec<ThreadReply>,
-}
-
-impl ChannelService for TestChannelService {
- async fn set_channel_picture(
- &self,
- _access: channels::domain::ports::ChannelPictureAccess,
- _picture_id: Option<uuid::Uuid>,
- ) -> Result<(), channels::domain::ports::ChannelMutationErr> {
- unimplemented!("picture mutation is not used by this fixture")
- }
-
- fn get_channel_messages(
- &self,
- _channel_id: Uuid,
- _query: Query<Uuid, CreatedAt, ()>,
- _direction: MessagePageDirection,
- _limit: u16,
- _filters: &ChannelMessageFilters,
- _notification_user_id: Option<MacroUserIdStr<'static>>,
- ) -> impl Future<Output = Result<ChannelMessagesQueryResult, ChannelMessagesErr>> + Send {
- async move { unimplemented!("not needed for detector tests") }
- }
-
- fn get_channel_attachments(
- &self,
- _channel_id: Uuid,
- _query: Query<Uuid, CreatedAt, ()>,
- _limit: u16,
- _attachment_type: Option<ChannelAttachmentType>,
- ) -> impl Future<Output = Result<ChannelAttachmentsPage, ChannelMessagesErr>> + Send {
- async move { unimplemented!("not needed for detector tests") }
- }
-
- fn get_channel_participants(
- &self,
- _channel_id: Uuid,
- ) -> impl Future<Output = Result<Vec<ChannelParticipant>, ChannelMessagesErr>> + Send {
- async move { unimplemented!("not needed for detector tests") }
- }
-
- fn get_message_context(
- &self,
- _channel_id: Uuid,
- _message_id: Uuid,
- _before: i64,
- _after: i64,
- ) -> impl Future<Output = Result<Vec<ChannelContextMessage>, ChannelMessagesErr>> + Send {
- let messages = self.parent.clone().into_iter().collect::<Vec<_>>();
- async move { Ok(messages) }
- }
-
- fn get_attachment_references(
- &self,
- _entity_type: String,
- _entity_id: String,
- _user_id: String,
- ) -> impl Future<Output = Result<Vec<AttachmentEntityReference>, ChannelMessagesErr>> + Send
- {
- async move { unimplemented!("not needed for detector tests") }
- }
-
- fn get_channel_messages_around(
- &self,
- _channel_id: Uuid,
- _message_id: Uuid,
- _limit: u16,
- ) -> impl Future<Output = Result<ChannelMessagesQueryResult, ChannelMessagesErr>> + Send {
- async move { unimplemented!("not needed for detector tests") }
- }
-
- fn get_thread_replies(
- &self,
- _channel_id: Uuid,
- _message_id: Uuid,
- ) -> impl Future<Output = Result<Vec<ThreadReply>, ChannelMessagesErr>> + Send {
- let replies = self.thread_replies.clone();
- async move { Ok(replies) }
- }
-
- fn resolve_message(
- &self,
- _channel_id: Uuid,
- _message_id: Uuid,
- ) -> impl Future<Output = Result<ResolvedChannelMessage, ChannelMessagesErr>> + Send {
- async move { unimplemented!("not needed for detector tests") }
- }
+struct Classifier {
+ answer: Result<bool, &'static str>,
+ calls: Mutex<Vec<Vec<TranscriptMessage>>>,
}
-
-struct TestClassifier {
- result: anyhow::Result<bool>,
- received: Mutex<Option<Vec<TranscriptMessage>>>,
-}
-
-impl TestClassifier {
- fn returning(result: anyhow::Result<bool>) -> Self {
- Self {
- result,
- received: Mutex::new(None),
- }
- }
-
- fn received_thread(&self) -> Option<Vec<TranscriptMessage>> {
- self.received.lock().unwrap().clone()
- }
-}
-
#[async_trait]
-impl InferredTriggerClassifier for TestClassifier {
+impl InferredTriggerClassifier for Classifier {
async fn expects_response(
&self,
- _requesting_user: &MacroUserIdStr<'static>,
+ _: &macro_user_id::user_id::MacroUserIdStr<'static>,
thread: &[TranscriptMessage],
) -> anyhow::Result<bool> {
- *self.received.lock().unwrap() = Some(thread.to_vec());
- match &self.result {
- Ok(value) => Ok(*value),
- Err(err) => anyhow::bail!("{err}"),
- }
+ self.calls.lock().unwrap().push(thread.to_vec());
+ self.answer.map_err(|error| anyhow::anyhow!(error))
}
}
-
-fn user_id(email: &str) -> MacroUserIdStr<'static> {
- MacroUserIdStr::try_from(format!("macro|{email}")).unwrap()
-}
-
-fn macro_ai_sender_id() -> String {
- bot_id::MACRO_AI_BOT_ID.into_storage_id().to_string()
-}
-
-fn candidate(
- channel_id: Uuid,
- thread_id: Option<Uuid>,
- sender: Sender,
- content: &str,
- mentioned_bot_ids: Vec<bot_id::BotId>,
-) -> ChannelBotTrigger {
- let now = Utc::now();
- ChannelBotTrigger {
- channel_id,
- message: MutatedMessage {
- id: Uuid::new_v4(),
- channel_id,
- thread_id,
- sender_id: sender,
- triggered_by: None,
- content: content.to_string(),
- created_at: now,
- updated_at: now,
- edited_at: None,
- deleted_at: None,
- },
- mentioned_bot_ids,
- span: tracing::Span::none(),
- }
-}
-
-fn parent_message(
- channel_id: Uuid,
- id: Uuid,
- sender_id: &str,
- content: &str,
-) -> ChannelContextMessage {
- let now = Utc::now();
- ChannelContextMessage {
- id,
- channel_id,
- thread_id: None,
- sender_id: sender_id.to_string(),
- triggered_by: None,
- bot_profile: None,
- content: content.to_string(),
- created_at: now,
- updated_at: now,
- edited_at: None,
- deleted_at: None,
- }
-}
-
-fn thread_reply(sender_id: &str, content: &str) -> ThreadReply {
- let now = Utc::now();
- ThreadReply {
- id: Uuid::new_v4(),
- sender_id: sender_id.to_string(),
- triggered_by: None,
- bot_profile: None,
- content: content.to_string(),
- created_at: now,
- updated_at: now,
- edited_at: None,
- reactions: Vec::new(),
- attachments: Vec::new(),
- }
+fn classifier(answer: Result<bool, &'static str>) -> Arc<Classifier> {
+ Arc::new(Classifier {
+ answer,
+ calls: Mutex::new(vec![]),
+ })
}
-
-fn detector(
- channels: TestChannelService,
- classifier: Arc<TestClassifier>,
-) -> MentionOrInferredDetector<TestChannelService, TestClassifier> {
- MentionOrInferredDetector::new(Arc::new(channels), classifier)
-}
-
-fn thread_with_agent_reply(channel_id: Uuid, parent_id: Uuid) -> TestChannelService {
- TestChannelService {
- parent: Some(parent_message(
- channel_id,
- parent_id,
- "notifications are broken",
- )),
- thread_replies: vec![thread_reply(
- &macro_ai_sender_id(),
- "what is broken exactly?",
- )],
- }
-}
-
#[tokio::test]
-async fn mention_triggers_each_mentioned_bot_without_classification() {
- let channel_id = Uuid::new_v4();
- let other_bot = bot_id::BotId::new_from_uuid(Uuid::new_v4());
- let classifier = Arc::new(TestClassifier::returning(Ok(true)));
- let detector = detector(
- TestChannelService {
- parent: None,
- thread_replies: Vec::new(),
- },
+async fn document_mention_triggers_each_canonical_bot_once_without_classification() {
+ let mut trigger = message(1, None, "@macro help");
+ let mention = SimpleMention {
+ entity_type: "user".into(),
+ entity_id: bot_id::MACRO_AI_BOT_ID.into_storage_id().to_string(),
+ };
+ trigger.mentions = vec![mention.clone(), mention];
+ let classifier = classifier(Ok(false));
+ let detector = MentionOrInferredDetector::new(
+ Arc::new(MockMessageServiceApi::new()),
+ Arc::new(Access::default()),
classifier.clone(),
);
-
- let invocations = detector
- .detect(&candidate(
- channel_id,
- None,
- Sender::new_from_user(user_id("[email protected]")),
- "@macro help",
- vec![bot_id::MACRO_AI_BOT_ID, other_bot],
- ))
- .await;
-
assert_eq!(
- invocations,
- vec![
- BotInvocation {
- bot_id: bot_id::MACRO_AI_BOT_ID,
- trigger: BotTrigger::Mention,
- },
- BotInvocation {
- bot_id: other_bot,
- trigger: BotTrigger::Mention,
- },
- ]
+ detector.detect(&event(&trigger)).await,
+ vec![BotInvocation {
+ bot_id: bot_id::MACRO_AI_BOT_ID,
+ trigger: BotTrigger::Mention
+ }]
);
- assert!(classifier.received_thread().is_none());
+ assert!(classifier.calls.lock().unwrap().is_empty());
}
-
#[tokio::test]
-async fn bot_authored_message_never_triggers() {
- let channel_id = Uuid::new_v4();
- let parent_id = Uuid::new_v4();
- let classifier = Arc::new(TestClassifier::returning(Ok(true)));
- let detector = detector(
- thread_with_agent_reply(channel_id, parent_id),
+async fn bot_authored_messages_never_trigger_another_response() {
+ let mut trigger = message(1, None, "@macro help");
+ trigger.sender_id = channel_sender::ChannelSender::new_from_bot(bot_id::MACRO_AI_BOT_ID);
+ trigger.mentions = vec![SimpleMention {
+ entity_type: "bot".into(),
+ entity_id: bot_id::MACRO_AI_BOT_ID.into_storage_id().to_string(),
+ }];
+ let access = Arc::new(Access::default());
+ access.revoke();
+ let classifier = classifier(Ok(true));
+ let detector = MentionOrInferredDetector::new(
+ Arc::new(MockMessageServiceApi::new()),
+ access,
classifier.clone(),
);
-
- let invocations = detector
- .detect(&candidate(
- channel_id,
- Some(parent_id),
- Sender::new_from_bot(bot_id::MACRO_AI_BOT_ID),
- "I fixed it",
- Vec::new(),
- ))
- .await;
-
- assert!(invocations.is_empty());
- assert!(classifier.received_thread().is_none());
+ assert!(detector.detect(&event(&trigger)).await.is_empty());
+ assert!(classifier.calls.lock().unwrap().is_empty());
}
-
#[tokio::test]
-async fn top_level_message_is_never_inferred() {
- let channel_id = Uuid::new_v4();
- let classifier = Arc::new(TestClassifier::returning(Ok(true)));
- let detector = detector(
- TestChannelService {
- parent: None,
- thread_replies: Vec::new(),
- },
+async fn root_without_mention_is_never_inferred() {
+ let classifier = classifier(Ok(true));
+ let detector = MentionOrInferredDetector::new(
+ Arc::new(MockMessageServiceApi::new()),
+ Arc::new(Access::default()),
classifier.clone(),
);
-
- let invocations = detector
- .detect(&candidate(
- channel_id,
- None,
- Sender::new_from_user(user_id("[email protected]")),
- "macro agent respond",
- Vec::new(),
- ))
- .await;
-
- assert!(invocations.is_empty());
- assert!(classifier.received_thread().is_none());
+ assert!(
+ detector
+ .detect(&event(&message(1, None, "hello")))
+ .await
+ .is_empty()
+ );
+ assert!(classifier.calls.lock().unwrap().is_empty());
}
-
#[tokio::test]
-async fn thread_without_agent_message_is_never_inferred() {
- let channel_id = Uuid::new_v4();
- let parent_id = Uuid::new_v4();
- let classifier = Arc::new(TestClassifier::returning(Ok(true)));
- let detector = detector(
- TestChannelService {
- parent: Some(parent_message(
- channel_id,
- parent_id,
- "anyone looked at this?",
- )),
- thread_replies: vec![thread_reply("macro|[email protected]", "not yet")],
- },
- classifier.clone(),
- );
-
- let invocations = detector
- .detect(&candidate(
- channel_id,
- Some(parent_id),
- Sender::new_from_user(user_id("[email protected]")),
- "can someone respond",
- Vec::new(),
- ))
- .await;
-
- assert!(invocations.is_empty());
- assert!(classifier.received_thread().is_none());
+async fn inferred_document_follow_up_requires_prior_agent_participation_and_classifier_agreement() {
+ for (prior_agent, answer, expected) in [
+ (true, Ok(true), true),
+ (false, Ok(true), false),
+ (true, Ok(false), false),
+ (true, Err("provider failed"), false),
+ ] {
+ let root = message(1, None, "question");
+ let mut previous = message(2, Some(root.id), "previous answer");
+ if prior_agent {
+ previous.sender_id =
+ channel_sender::ChannelSender::new_from_bot(bot_id::MACRO_AI_BOT_ID);
+ }
+ let trigger = message(3, Some(root.id), "can you expand on that?");
+ let mut api = MockMessageServiceApi::new();
+ configure_reads(
+ &mut api,
+ &trigger,
+ thread(root, vec![previous, trigger.clone()]),
+ );
+ let classifier = classifier(answer);
+ let detector = MentionOrInferredDetector::new(
+ Arc::new(api),
+ Arc::new(Access::default()),
+ classifier.clone(),
+ );
+ let result = detector.detect(&event(&trigger)).await;
+ assert_eq!(!result.is_empty(), expected);
+ if expected {
+ assert_eq!(result[0].trigger, BotTrigger::Inferred);
+ }
+ assert_eq!(!classifier.calls.lock().unwrap().is_empty(), prior_agent);
+ }
}
-
#[tokio::test]
-async fn thread_reply_after_agent_message_infers_when_classifier_agrees() {
- let channel_id = Uuid::new_v4();
- let parent_id = Uuid::new_v4();
- let classifier = Arc::new(TestClassifier::returning(Ok(true)));
- let detector = detector(
- thread_with_agent_reply(channel_id, parent_id),
+async fn access_revocation_suppresses_explicit_and_inferred_document_triggers() {
+ let access = Arc::new(Access::default());
+ access.revoke();
+ let classifier = classifier(Ok(true));
+ let detector = MentionOrInferredDetector::new(
+ Arc::new(MockMessageServiceApi::new()),
+ access,
classifier.clone(),
);
-
- let invocations = detector
- .detect(&candidate(
- channel_id,
- Some(parent_id),
- Sender::new_from_user(user_id("[email protected]")),
- "it fires twice per message",
- Vec::new(),
- ))
- .await;
-
- assert_eq!(
- invocations,
- vec![BotInvocation {
- bot_id: bot_id::MACRO_AI_BOT_ID,
- trigger: BotTrigger::Inferred,
- }]
- );
-
- let thread = classifier.received_thread().expect("classifier called");
- assert_eq!(
- thread,
- vec![
- TranscriptMessage {
- from_agent: false,
- sender: "alice".to_string(),
- content: "notifications are broken".to_string(),
- },
- TranscriptMessage {
- from_agent: true,
- sender: bot_id::MACRO_AI_NAME.to_string(),
- content: "what is broken exactly?".to_string(),
- },
- TranscriptMessage {
- from_agent: false,
- sender: "alice".to_string(),
- content: "it fires twice per message".to_string(),
- },
- ]
- );
+ let mut trigger = message(2, Some(Uuid::from_u128(1)), "please continue");
+ assert!(detector.detect(&event(&trigger)).await.is_empty());
+ trigger.mentions.push(SimpleMention {
+ entity_type: "bot".into(),
+ entity_id: bot_id::MACRO_AI_BOT_ID.into_storage_id().to_string(),
+ });
+ assert!(detector.detect(&event(&trigger)).await.is_empty());
+ assert!(classifier.calls.lock().unwrap().is_empty());
}
-
#[tokio::test]
-async fn classifier_rejection_yields_no_trigger() {
- let channel_id = Uuid::new_v4();
- let parent_id = Uuid::new_v4();
- let classifier = Arc::new(TestClassifier::returning(Ok(false)));
- let detector = detector(thread_with_agent_reply(channel_id, parent_id), classifier);
-
- let invocations = detector
- .detect(&candidate(
- channel_id,
- Some(parent_id),
- Sender::new_from_user(user_id("[email protected]")),
- "thanks, I'll take it from here",
- Vec::new(),
- ))
- .await;
-
- assert!(invocations.is_empty());
-}
-
-#[tokio::test]
-async fn classifier_failure_yields_no_trigger() {
- let channel_id = Uuid::new_v4();
- let parent_id = Uuid::new_v4();
- let classifier = Arc::new(TestClassifier::returning(Err(anyhow::anyhow!(
- "model down"
- ))));
- let detector = detector(thread_with_agent_reply(channel_id, parent_id), classifier);
-
- let invocations = detector
- .detect(&candidate(
- channel_id,
- Some(parent_id),
- Sender::new_from_user(user_id("[email protected]")),
- "it fires twice per message",
- Vec::new(),
- ))
- .await;
-
- assert!(invocations.is_empty());
-}
-
-#[tokio::test]
-async fn candidate_message_is_appended_when_missing_from_replies() {
- let channel_id = Uuid::new_v4();
- let parent_id = Uuid::new_v4();
- let classifier = Arc::new(TestClassifier::returning(Ok(true)));
- let detector = detector(
- thread_with_agent_reply(channel_id, parent_id),
+async fn unavailable_history_cannot_be_replaced_by_an_unverified_event_transcript() {
+ let mut api = MockMessageServiceApi::new();
+ api.expect_get()
+ .once()
+ .returning(|_, _| Err(messages::domain::ports::MessageError::NotFound));
+ let classifier = classifier(Ok(true));
+ let detector = MentionOrInferredDetector::new(
+ Arc::new(api),
+ Arc::new(Access::default()),
classifier.clone(),
);
-
- detector
- .detect(&candidate(
- channel_id,
- Some(parent_id),
- Sender::new_from_user(user_id("[email protected]")),
- "u so dumb",
- Vec::new(),
- ))
- .await;
-
- let thread = classifier.received_thread().expect("classifier called");
- let last = thread.last().expect("non-empty transcript");
- assert_eq!(last.sender, "bob");
- assert_eq!(last.content, "u so dumb");
- assert!(!last.from_agent);
+ assert!(
+ detector
+ .detect(&event(&message(2, Some(Uuid::from_u128(1)), "continue")))
+ .await
+ .is_empty()
+ );
+ assert!(classifier.calls.lock().unwrap().is_empty());
}
diff --git a/crates/channel_bots/src/inbound/bot_trigger_router.rs b/crates/channel_bots/src/inbound/bot_trigger_router.rs
index 26970634de..8dbf2badde 100644
--- a/crates/channel_bots/src/inbound/bot_trigger_router.rs
+++ b/crates/channel_bots/src/inbound/bot_trigger_router.rs
@@ -1,9 +1,8 @@
-//! Routes channel bot triggers to the appropriate handler.
+//! Routes committed posts to the built-in bot handlers.
use std::sync::Arc;
-use channels::domain::ports::ChannelService;
-use channels::domain::side_effects::ChannelBotTrigger;
+use messages::domain::{api::MessageServiceApi, events::MessagePostedMetadata};
use tokio::sync::mpsc::UnboundedReceiver;
use tracing::Instrument as _;
@@ -12,26 +11,24 @@ use crate::domain::{
ports::{AgentResponder, ConversationAccess, TriggerDetector, UserTimeZones},
service::MacroAiHandler,
};
-use messages::domain::api::MessageCommands;
-/// Resolves the bot invocations for a candidate channel message and runs their
-/// handlers.
+/// Resolves the bot invocations for a committed post and runs their handlers.
///
-/// Receives trigger candidates derived by the channel side-effect service. A
-/// [`TriggerDetector`] decides which bots each candidate invokes — explicit
-/// `@`-mentions or an inferred invocation. Dispatch is fire-and-forget: each
-/// candidate is handled on a spawned task.
+/// Receives every human-authored post the shared message service commits, on
+/// a channel or a document. A [`TriggerDetector`] decides which bots each
+/// candidate invokes — explicit `@`-mentions or an inferred invocation.
+/// Dispatch is fire-and-forget: each candidate is handled on a spawned task.
///
/// System bots are defined in code and require no database row. Unknown bot ids
/// are ignored here; only Macro AI is handled by this branch. Non-system bots
-/// are notified of mentions out of process via the `channel.mentioned`
-/// webhook event instead (see the `webhook` crate).
-pub struct BotTriggerRouter<C, R, D, Z> {
- macro_ai: Arc<MacroAiHandler<C, R, Z>>,
+/// are notified of mentions out of process via the trigger topic and webhooks
+/// instead (see the `agent_trigger` and `webhook` crates).
+pub struct BotTriggerRouter<R, D, Z> {
+ macro_ai: Arc<MacroAiHandler<R, Z>>,
detector: Arc<D>,
}
-impl<C, R, D, Z> Clone for BotTriggerRouter<C, R, D, Z> {
+impl<R, D, Z> Clone for BotTriggerRouter<R, D, Z> {
fn clone(&self) -> Self {
Self {
macro_ai: self.macro_ai.clone(),
@@ -40,32 +37,28 @@ impl<C, R, D, Z> Clone for BotTriggerRouter<C, R, D, Z> {
}
}
-impl<C, R, D, Z> BotTriggerRouter<C, R, D, Z>
+impl<R, D, Z> BotTriggerRouter<R, D, Z>
where
- C: ChannelService,
R: AgentResponder,
D: TriggerDetector,
Z: UserTimeZones,
{
/// Create a router with the built-in system bots registered.
pub fn new(
- channels: Arc<C>,
- messages: Arc<dyn MessageCommands>,
+ messages: Arc<dyn MessageServiceApi>,
access: Arc<dyn ConversationAccess>,
responder: Arc<R>,
detector: Arc<D>,
time_zones: Arc<Z>,
) -> Self {
Self {
- macro_ai: Arc::new(MacroAiHandler::new(
- channels, messages, access, responder, time_zones,
- )),
+ macro_ai: Arc::new(MacroAiHandler::new(messages, access, responder, time_zones)),
detector,
}
}
- /// Start consuming channel bot trigger candidates.
- pub fn spawn(self, mut candidates: UnboundedReceiver<ChannelBotTrigger>)
+ /// Start consuming bot trigger candidates.
+ pub fn spawn(self, mut candidates: UnboundedReceiver<MessagePostedMetadata>)
where
R: 'static,
D: 'static,
@@ -74,7 +67,11 @@ where
tokio::spawn(async move {
while let Some(candidate) = candidates.recv().await {
let router = self.clone();
- let span = candidate.span.clone();
+ let span = tracing::info_span!(
+ "message.bot_trigger",
+ parent = ?candidate.parent,
+ message.id = %candidate.message_id,
+ );
tokio::spawn(async move {
router.run(candidate).instrument(span).await;
});
@@ -82,18 +79,17 @@ where
});
}
- async fn run(&self, candidate: ChannelBotTrigger) {
+ async fn run(&self, candidate: MessagePostedMetadata) {
// Guarded upstream, but double-check: only user messages trigger bots.
- let Some(requesting_user) = candidate.message.sender_id.as_user().cloned() else {
+ let Some(requesting_user) = candidate.sender.as_user().cloned() else {
return;
};
- let reply_thread_id = candidate.message.thread_id.unwrap_or(candidate.message.id);
+ let reply_thread_id = candidate.root_id();
for invocation in self.detector.detect(&candidate).await {
let event = BotEvent {
trigger: invocation.trigger,
- channel_id: candidate.channel_id,
- message: candidate.message.clone(),
+ message: candidate.clone(),
reply_thread_id,
requesting_user: requesting_user.clone(),
};
diff --git a/crates/channel_bots/src/lib.rs b/crates/channel_bots/src/lib.rs
index e14a266046..b0f4359f41 100644
--- a/crates/channel_bots/src/lib.rs
+++ b/crates/channel_bots/src/lib.rs
@@ -1,24 +1,10 @@
#![deny(missing_docs)]
-//! Channel bots: trigger built-in bot behavior from channel events.
+//! Built-in agents for document comments and channel messages.
//!
-//! Channels emit a [`ChannelBotTrigger`](channels::domain::side_effects::ChannelBotTrigger)
-//! candidate for every user-authored message. The inbound
-//! [`BotTriggerRouter`](inbound::BotTriggerRouter) resolves each candidate
-//! through a [`TriggerDetector`](domain::ports::TriggerDetector) — an explicit
-//! `@`-mention triggers the mentioned bots, and a thread reply with no mention
-//! may trigger an *inferred* Macro AI invocation when the thread already
-//! contains an agent message and a fast-model classifier judges that the
-//! message expects an agent response — and runs the appropriate domain
-//! service:
-//!
-//! * **System bots** (defined inside Macro) run in-process. The only one today
-//! is Macro AI, handled by
-//! [`MacroAiHandler`](domain::service::MacroAiHandler), which posts an
-//! immediate "thinking" message, runs the agent loop, then edits the message
-//! with the answer.
+//! The common message service emits committed posts for both channels and documents.
+//! Built-in agents read, authorize, and deliver through the same message boundary.
-/// Domain layer: bot trigger models, ports, and service implementation.
pub mod domain;
/// Inbound adapters for channel bot triggers.
pub mod inbound;
diff --git a/crates/channel_bots/src/outbound/conversation.rs b/crates/channel_bots/src/outbound/conversation.rs
index ddfb530fa9..ceb98ecbc5 100644
--- a/crates/channel_bots/src/outbound/conversation.rs
+++ b/crates/channel_bots/src/outbound/conversation.rs
@@ -1,26 +1,40 @@
-//! Current parent capabilities for built-in agent replies.
+//! Current parent capabilities and local delivery for built-in message agents.
use crate::domain::ports::ConversationAccess;
use async_trait::async_trait;
use entity_access::domain::{
- models::{BotAccessScope, EntityAccessReceipt, EntityType},
+ models::{BotAccessScope, EntityAccessReceipt},
ports::EntityAccessService,
};
use macro_user_id::user_id::MacroUserIdStr;
-use messages::domain::{models::MessageParent, service::MessageWrite};
+use messages::domain::{
+ events::MessagePostedMetadata,
+ models::MessageParent,
+ ports::{MessageChange, MessageEvent, MessageEventPublisher},
+ service::MessageWrite,
+};
use std::sync::Arc;
/// Mint current parent capabilities through the standard access service.
pub struct EntityAccessConversation<A>(pub Arc<A>);
-fn entity_type(parent: &MessageParent) -> EntityType {
- match parent {
- MessageParent::Channel(_) => EntityType::Channel,
- MessageParent::Document(_) => EntityType::Document,
- }
-}
-
#[async_trait]
impl<A: EntityAccessService> ConversationAccess for EntityAccessConversation<A> {
+ async fn user_write(
+ &self,
+ user: &MacroUserIdStr<'static>,
+ parent: &MessageParent,
+ ) -> Result<EntityAccessReceipt<MessageWrite>, rootcause::Report> {
+ Ok(self
+ .0
+ .generate_entity_access_receipt(
+ user,
+ None,
+ &parent.entity_id(),
+ parent.access_entity_type(),
+ )
+ .await?)
+ }
+
async fn bot_write(
&self,
user: &MacroUserIdStr<'static>,
@@ -32,8 +46,48 @@ impl<A: EntityAccessService> ConversationAccess for EntityAccessConversation<A>
bot_id::MACRO_AI_BOT_ID,
BotAccessScope::user(user.clone()),
&parent.entity_id(),
- entity_type(parent),
+ parent.access_entity_type(),
)
.await?)
}
}
+
+/// Feeds the built-in responder from the same committed message stream hosted
+/// and external agents consume, for channel and document posts alike.
+///
+/// Only human posts enter the queue: a bot's own reply, including Macro AI's,
+/// never triggers another bot, which is what keeps bots from relaying each
+/// other forever.
+#[derive(Clone)]
+pub struct LocalBotPublisher {
+ triggers: tokio::sync::mpsc::UnboundedSender<MessagePostedMetadata>,
+}
+
+impl LocalBotPublisher {
+ /// Attach the built-in responder to common message delivery.
+ pub fn new(triggers: tokio::sync::mpsc::UnboundedSender<MessagePostedMetadata>) -> Self {
+ Self { triggers }
+ }
+}
+
+impl MessageEventPublisher for LocalBotPublisher {
+ async fn publish(&self, event: MessageEvent) -> Result<(), rootcause::Report> {
+ if let MessageChange::Posted {
+ message, mentions, ..
+ } = &event.change
+ && message.sender_id.as_user().is_some()
+ {
+ self.triggers
+ .send(MessagePostedMetadata::from_message(
+ message,
+ mentions.clone(),
+ ))
+ .map_err(|error| rootcause::report!(error).into())
+ } else {
+ Ok(())
+ }
+ }
+}
+
+#[cfg(test)]
+mod test;
diff --git a/crates/channel_bots/src/outbound/conversation/test.rs b/crates/channel_bots/src/outbound/conversation/test.rs
new file mode 100644
index 0000000000..6b637e0989
--- /dev/null
+++ b/crates/channel_bots/src/outbound/conversation/test.rs
@@ -0,0 +1,74 @@
+use super::*;
+use crate::domain::test::message;
+use std::sync::Mutex;
+
+#[derive(Clone, Default)]
+struct Delivery(Arc<Mutex<Vec<MessageEvent>>>);
+impl MessageEventPublisher for Delivery {
+ async fn publish(&self, event: MessageEvent) -> Result<(), rootcause::Report> {
+ self.0.lock().unwrap().push(event);
+ Ok(())
+ }
+}
+fn posted(parent: MessageParent, bot: bool) -> MessageEvent {
+ let mut message = message(1, None, "@macro explain this");
+ message.parent = parent.clone();
+ if bot {
+ message.sender_id = channel_sender::ChannelSender::new_from_bot(bot_id::MACRO_AI_BOT_ID);
+ }
+ MessageEvent {
+ parent,
+ actor: message.sender_id.as_ref().to_owned(),
+ nonce: None,
+ change: MessageChange::Posted {
+ notification_policy: Default::default(),
+ message,
+ mentions: vec![],
+ },
+ }
+}
+#[tokio::test]
+async fn user_posts_from_both_parents_dispatch_once_and_bot_responses_never_reenter() {
+ let (sender, mut receiver) = tokio::sync::mpsc::unbounded_channel();
+ let delivery = Delivery::default();
+ let publisher = messages::domain::effects::MessageEffects::new(
+ messages::domain::ports::NoMessageEventPublisher,
+ LocalBotPublisher::new(sender),
+ delivery.clone(),
+ );
+ for parent in [
+ MessageParent::Channel(uuid::Uuid::from_u128(900)),
+ MessageParent::parse("document", "doc").unwrap(),
+ ] {
+ publisher
+ .publish(posted(parent.clone(), false))
+ .await
+ .unwrap();
+ assert_eq!(receiver.try_recv().unwrap().parent, parent);
+ assert!(receiver.try_recv().is_err());
+ publisher.publish(posted(parent, true)).await.unwrap();
+ assert!(receiver.try_recv().is_err());
+ }
+ assert_eq!(delivery.0.lock().unwrap().len(), 4);
+}
+#[tokio::test]
+async fn closed_agent_receiver_does_not_suppress_realtime_and_notification_delivery() {
+ let (sender, receiver) = tokio::sync::mpsc::unbounded_channel();
+ drop(receiver);
+ let delivery = Delivery::default();
+ let publisher = messages::domain::effects::MessageEffects::new(
+ messages::domain::ports::NoMessageEventPublisher,
+ LocalBotPublisher::new(sender),
+ delivery.clone(),
+ );
+ assert!(
+ publisher
+ .publish(posted(
+ MessageParent::parse("document", "doc").unwrap(),
+ false
+ ))
+ .await
+ .is_err()
+ );
+ assert_eq!(delivery.0.lock().unwrap().len(), 1);
+}
diff --git a/crates/coding_agent_worker/Cargo.toml b/crates/coding_agent_worker/Cargo.toml
index e1ae4869af..fd0fafc629 100644
--- a/crates/coding_agent_worker/Cargo.toml
+++ b/crates/coding_agent_worker/Cargo.toml
@@ -9,6 +9,7 @@ name = "macrod"
path = "src/main.rs"
[dependencies]
+messages = { path = "../messages", features = ["broker"] }
# Direct crate imports are the whole typegen story: the protocol envelope,
# the trigger event vocabulary, and the delivery signature all come from the
# owning crates, compiler-checked.
diff --git a/crates/coding_agent_worker/src/dispatch.rs b/crates/coding_agent_worker/src/dispatch.rs
index c55ce7f9fc..f28c8033d9 100644
--- a/crates/coding_agent_worker/src/dispatch.rs
+++ b/crates/coding_agent_worker/src/dispatch.rs
@@ -43,7 +43,7 @@ impl WorkExecutor for Dispatcher {
TriggerWork::OpenAndPrompt {
bot,
sender,
- channel_id,
+ parent,
thread_id,
message_id,
content,
@@ -62,7 +62,17 @@ impl WorkExecutor for Dispatcher {
repo_branch: None,
owner: Some(sender.as_ref().to_owned()),
thread: Some(CreateSessionThread {
- channel_id,
+ // Keep `channel_id` populated for channel parents so a
+ // pre-parent harness, which ignores `parent` and reads
+ // `channel_id` as a required UUID, still deserializes
+ // the request. Document parents have no channel id.
+ channel_id: match &parent {
+ messages::domain::models::MessageParent::Channel(channel_id) => {
+ Some(*channel_id)
+ }
+ messages::domain::models::MessageParent::Document(_) => None,
+ },
+ parent: Some(parent),
thread_id: Some(thread_id),
message_id,
content: content.clone(),
diff --git a/crates/coding_agent_worker/src/trigger.rs b/crates/coding_agent_worker/src/trigger.rs
index 5055c39cdc..af0afeed1d 100644
--- a/crates/coding_agent_worker/src/trigger.rs
+++ b/crates/coding_agent_worker/src/trigger.rs
@@ -5,7 +5,7 @@
use agent_session::domain::model::AgentSessionId;
use agent_trigger::domain::broker_events::{
- AgentTriggerEventName, AgentTriggerTopicEvent, ExistingAgentSessionEvent, NewAgentSessionEvent,
+ AgentTriggerEventName, AgentTriggerTopicEvent, OpeningMention, SessionMessage,
};
use bot_id::BotId;
use macro_event_broker::Event;
@@ -32,8 +32,8 @@ pub enum TriggerWork {
bot: BotId,
/// Who asked; owns the session and authors the prompt.
sender: MacroUserIdStr<'static>,
- /// Channel the mention was posted in.
- channel_id: Uuid,
+ /// Channel or document the mention was posted in.
+ parent: messages::domain::models::MessageParent,
/// Thread the mention roots.
thread_id: Uuid,
/// The mentioning message.
@@ -69,17 +69,19 @@ pub enum Skipped {
/// Translate one trigger event into this daemon's work, or a reason to skip.
pub fn trigger_to_work(event: AgentTriggerTopicEvent) -> Result<TriggerWork, Skipped> {
match event {
- AgentTriggerTopicEvent::New(NewAgentSessionEvent::TopLevelMentioned(mentioned)) => {
- let message = mentioned.message;
+ AgentTriggerTopicEvent::New(event) => {
+ let Some(OpeningMention { bot_id, message }) = event.mention() else {
+ return Err(Skipped::Unrecognized);
+ };
let sender = message
.sender
.as_user()
.cloned()
.ok_or(Skipped::NotFromUser)?;
Ok(TriggerWork::OpenAndPrompt {
- bot: mentioned.bot_id,
+ bot: bot_id,
sender,
- channel_id: message.channel_id,
+ parent: message.parent,
// A top-level mention roots its own thread; a mention inside
// a thread answers into that thread.
thread_id: message.thread_id.unwrap_or(message.message_id),
@@ -87,20 +89,26 @@ pub fn trigger_to_work(event: AgentTriggerTopicEvent) -> Result<TriggerWork, Ski
content: message.content,
})
}
- AgentTriggerTopicEvent::Existing(ExistingAgentSessionEvent::Channel(metadata)) => {
- let sender = metadata
- .message
+ AgentTriggerTopicEvent::Existing(event) => {
+ let Some(SessionMessage {
+ session_id,
+ message,
+ ..
+ }) = event.session_message()
+ else {
+ return Err(Skipped::Unrecognized);
+ };
+ let sender = message
.sender
.as_user()
.cloned()
.ok_or(Skipped::NotFromUser)?;
Ok(TriggerWork::PromptExisting {
- session: metadata.session_id,
+ session: session_id,
sender,
- content: metadata.message.content,
+ content: message.content,
})
}
- _ => Err(Skipped::Unrecognized),
}
}
diff --git a/crates/coding_agent_worker/src/trigger/test.rs b/crates/coding_agent_worker/src/trigger/test.rs
index bc3b126aa5..9ac9099b5d 100644
--- a/crates/coding_agent_worker/src/trigger/test.rs
+++ b/crates/coding_agent_worker/src/trigger/test.rs
@@ -1,9 +1,14 @@
use super::*;
-use agent_trigger::domain::broker_events::AgentBotMentionedEvent;
+use agent_trigger::domain::broker_events::{
+ AgentBotMentionedEvent, AgentMentionedEvent, ChannelEventMetadata, ExistingAgentSessionEvent,
+ NewAgentSessionEvent, ThreadEventMetadata, ThreadMessageKind,
+};
use channel_sender::ChannelSender;
use channels::domain::broker_events::ChannelMessagePostedMetadata;
use channels::domain::models::ChannelType;
use chrono::Utc;
+use messages::domain::events::MessagePostedMetadata;
+use messages::domain::models::MessageParent;
use std::sync::Mutex;
fn test_session() -> AgentSessionId {
@@ -14,6 +19,7 @@ fn sender() -> MacroUserIdStr<'static> {
MacroUserIdStr::try_from_email("[email protected]").unwrap()
}
+/// A channel post in the channel-only shape channel triggers travel in.
fn message(content: &str, thread_id: Option<Uuid>) -> ChannelMessagePostedMetadata {
ChannelMessagePostedMetadata {
channel_id: Uuid::from_u128(1),
@@ -29,6 +35,25 @@ fn message(content: &str, thread_id: Option<Uuid>) -> ChannelMessagePostedMetada
}
}
+fn document() -> MessageParent {
+ MessageParent::parse("document", "doc-1").unwrap()
+}
+
+fn document_message(content: &str, thread_id: Option<Uuid>) -> MessagePostedMetadata {
+ MessagePostedMetadata {
+ parent: document(),
+ message_id: Uuid::from_u128(2),
+ thread_id,
+ root_id: thread_id.unwrap_or(Uuid::from_u128(2)),
+ sender: ChannelSender::new_from_user(sender()),
+ triggered_by: None,
+ content: content.to_owned(),
+ mentions: vec![],
+ attachments: vec![],
+ created_at: Utc::now(),
+ }
+}
+
fn mention(content: &str) -> AgentTriggerTopicEvent {
AgentTriggerTopicEvent::New(NewAgentSessionEvent::TopLevelMentioned(
AgentBotMentionedEvent {
@@ -39,14 +64,49 @@ fn mention(content: &str) -> AgentTriggerTopicEvent {
}
fn follow_up(content: &str) -> AgentTriggerTopicEvent {
- AgentTriggerTopicEvent::Existing(ExistingAgentSessionEvent::Channel(
- agent_trigger::domain::broker_events::ChannelEventMetadata {
+ AgentTriggerTopicEvent::Existing(ExistingAgentSessionEvent::Channel(ChannelEventMetadata {
+ bot_id: bot_id::BotId::TEST_A,
+ session_id: test_session(),
+ kind: ThreadMessageKind::MentionThread,
+ message: message(content, Some(Uuid::from_u128(7))),
+ }))
+}
+
+/// Document triggers arrive in the parent-aware shape and become the same
+/// work as channel ones, addressed to the document.
+#[test]
+fn document_triggers_become_work_on_the_document() {
+ let opened =
+ AgentTriggerTopicEvent::New(NewAgentSessionEvent::Mentioned(AgentMentionedEvent {
+ bot_id: bot_id::BotId::TEST_A,
+ message: document_message("summarize this", None),
+ }));
+ assert_eq!(
+ trigger_to_work(opened).expect("a document mention is work"),
+ TriggerWork::OpenAndPrompt {
+ bot: bot_id::BotId::TEST_A,
+ sender: sender(),
+ parent: document(),
+ thread_id: Uuid::from_u128(2),
+ message_id: Uuid::from_u128(2),
+ content: "summarize this".to_owned(),
+ }
+ );
+ let followed =
+ AgentTriggerTopicEvent::Existing(ExistingAgentSessionEvent::Thread(ThreadEventMetadata {
bot_id: bot_id::BotId::TEST_A,
session_id: test_session(),
- kind: agent_trigger::domain::broker_events::ChannelKind::MentionThread,
- message: message(content, Some(Uuid::from_u128(7))),
- },
- ))
+ kind: ThreadMessageKind::Inferred,
+ message: document_message("and this", Some(Uuid::from_u128(7))),
+ }));
+ assert_eq!(
+ trigger_to_work(followed).expect("a document follow-up is work"),
+ TriggerWork::PromptExisting {
+ session: test_session(),
+ sender: sender(),
+ content: "and this".to_owned(),
+ }
+ );
}
#[test]
@@ -57,7 +117,7 @@ fn a_mention_becomes_open_and_prompt_rooting_its_own_thread() {
TriggerWork::OpenAndPrompt {
bot: bot_id::BotId::TEST_A,
sender: sender(),
- channel_id: Uuid::from_u128(1),
+ parent: messages::domain::models::MessageParent::Channel(Uuid::from_u128(1)),
thread_id: Uuid::from_u128(2),
message_id: Uuid::from_u128(2),
content: "fix the test".to_owned(),
diff --git a/crates/entity_access/src/domain/ports.rs b/crates/entity_access/src/domain/ports.rs
index 1ee55ddbec..52be6a8bb2 100644
--- a/crates/entity_access/src/domain/ports.rs
+++ b/crates/entity_access/src/domain/ports.rs
@@ -81,6 +81,12 @@ pub trait AccessRepository: Clone + Send + Sync + 'static {
initiative_id: &str,
user_id: Option<&MacroUserId<Lowercase<'_>>>,
) -> impl Future<Output = Result<Option<AccessLevel>, AccessError>> + Send;
+ /// Document owning an agent session's still-live originating message thread.
+ /// This is a persisted relationship, not a caller-supplied grant.
+ fn get_agent_session_document(
+ &self,
+ agent_session_id: &str,
+ ) -> impl Future<Output = Result<Option<String>, AccessError>> + Send;
/// Get the access level a user has for a reminder.
///
diff --git a/crates/entity_access/src/domain/service.rs b/crates/entity_access/src/domain/service.rs
index 57463810d8..d2d009805d 100644
--- a/crates/entity_access/src/domain/service.rs
+++ b/crates/entity_access/src/domain/service.rs
@@ -51,7 +51,21 @@ where
EntityType::EmailThread => self.repo.get_thread_access(entity_id, user_id).await,
EntityType::Call => self.repo.get_call_access(entity_id, user_id).await,
EntityType::AgentSession => {
- self.repo.get_agent_session_access(entity_id, user_id).await
+ let direct = self
+ .repo
+ .get_agent_session_access(entity_id, user_id)
+ .await?;
+ let inherited = if let Some(document) =
+ self.repo.get_agent_session_document(entity_id).await?
+ {
+ self.repo
+ .get_document_access(&document, user_id)
+ .await?
+ .map(session_permission_from_document)
+ } else {
+ None
+ };
+ Ok(direct.max(inherited))
}
EntityType::Initiative => self.repo.get_initiative_access(entity_id, user_id).await,
EntityType::CalendarEvent => {
@@ -182,7 +196,6 @@ where
| EntityType::Project
| EntityType::EmailThread
| EntityType::Call
- | EntityType::AgentSession
| EntityType::Initiative => {
let access_level = self
.repo
@@ -191,6 +204,13 @@ where
.ok_or(AccessError::Unauthorized)?;
Ok(EntityPermission::AccessLevel { access_level })
}
+ EntityType::AgentSession => {
+ let direct = self.repo.get_team_entity_access(bot_id, team_id, entity_id, entity_type).await?;
+ let inherited = if let Some(document) = self.repo.get_agent_session_document(entity_id).await? {
+ self.repo.get_team_entity_access(bot_id, team_id, &document, EntityType::Document).await?.map(session_permission_from_document)
+ } else { None };
+ Ok(EntityPermission::AccessLevel { access_level: direct.max(inherited).ok_or(AccessError::Unauthorized)? })
+ }
EntityType::Channel => {
let channel_id = Uuid::parse_str(entity_id)
.map_err(|_| AccessError::BadRequest("Invalid channel ID format"))?;
@@ -667,3 +687,13 @@ fn channel_role_result_to_permission(
#[cfg(test)]
mod test;
+
+// Commenters can prompt the agent; viewers can inspect the response. Parent
+// ownership never confers session ownership or permission to delete it.
+fn session_permission_from_document(level: AccessLevel) -> AccessLevel {
+ if level >= AccessLevel::Comment {
+ AccessLevel::Edit
+ } else {
+ AccessLevel::View
+ }
+}
diff --git a/crates/entity_access/src/domain/service/test.rs b/crates/entity_access/src/domain/service/test.rs
index b5f631e901..0273e86344 100644
--- a/crates/entity_access/src/domain/service/test.rs
+++ b/crates/entity_access/src/domain/service/test.rs
@@ -29,6 +29,7 @@ struct MockRepo {
call_access: Arc<Mutex<Option<AccessLevel>>>,
agent_session_access: Arc<Mutex<Option<AccessLevel>>>,
initiative_access: Arc<Mutex<Option<AccessLevel>>>,
+ agent_session_document: Arc<Mutex<Option<String>>>,
reminder_access: Arc<Mutex<Option<AccessLevel>>>,
team_entity_access: Arc<Mutex<Option<AccessLevel>>>,
team_entity_access_calls: Arc<AtomicUsize>,
@@ -66,6 +67,7 @@ impl MockRepo {
call_access: Arc::new(Mutex::new(None)),
agent_session_access: Arc::new(Mutex::new(None)),
initiative_access: Arc::new(Mutex::new(None)),
+ agent_session_document: Arc::default(),
reminder_access: Arc::new(Mutex::new(None)),
team_entity_access: Arc::new(Mutex::new(None)),
team_entity_access_calls: Arc::new(AtomicUsize::new(0)),
@@ -221,6 +223,10 @@ impl MockRepo {
}
impl AccessRepository for MockRepo {
+ async fn get_agent_session_document(&self, _: &str) -> Result<Option<String>, AccessError> {
+ Ok(self.agent_session_document.lock().await.clone())
+ }
+
async fn get_document_access(
&self,
_document_id: &str,
@@ -2151,3 +2157,33 @@ async fn test_get_users_by_entity_project_with_many_users() {
assert_eq!(u.to_string(), format!("macro|user{}@test.com", i));
}
}
+
+#[tokio::test]
+async fn document_session_access_tracks_current_document_permission() {
+ let repo = MockRepo::new();
+ *repo.agent_session_document.lock().await = Some("doc".into());
+ let service = EntityAccessServiceImpl::new(repo.clone());
+ for (permission, expected) in [
+ (Some(AccessLevel::View), Some(AccessLevel::View)),
+ (Some(AccessLevel::Comment), Some(AccessLevel::Edit)),
+ (Some(AccessLevel::Owner), Some(AccessLevel::Edit)),
+ (None, None),
+ ] {
+ *repo.document_access.lock().await = permission;
+ assert_eq!(
+ service
+ .get_access_level(None, "session", EntityType::AgentSession)
+ .await
+ .unwrap(),
+ expected
+ );
+ }
+ *repo.agent_session_access.lock().await = Some(AccessLevel::Owner);
+ assert_eq!(
+ service
+ .get_access_level(None, "session", EntityType::AgentSession)
+ .await
+ .unwrap(),
+ Some(AccessLevel::Owner)
+ );
+}
diff --git a/crates/entity_access/src/outbound/pg_access_repo.rs b/crates/entity_access/src/outbound/pg_access_repo.rs
index fb5aa2cd1c..d735047aca 100644
--- a/crates/entity_access/src/outbound/pg_access_repo.rs
+++ b/crates/entity_access/src/outbound/pg_access_repo.rs
@@ -212,6 +212,24 @@ impl AccessRepository for PgAccessRepository {
Ok(queries::call_access::get_call_access(&self.pool, &call_uuid, &source_ids).await?)
}
+ async fn get_agent_session_document(
+ &self,
+ agent_session_id: &str,
+ ) -> Result<Option<String>, AccessError> {
+ let session = agent_session_id
+ .parse::<Uuid>()
+ .map_err(|_| AccessError::BadRequest("Invalid agent session ID format"))?;
+ Ok(sqlx::query_scalar!(
+ r#"SELECT m.parent_entity_id FROM agent_session s
+ JOIN comms_messages m ON m.id = s.thread_id
+ JOIN comms_message_threads t ON t.root_id = m.id
+ WHERE s.id = $1 AND m.parent_entity_type = 'document' AND t.deleted_at IS NULL"#,
+ session,
+ )
+ .fetch_optional(&self.pool)
+ .await?)
+ }
+
async fn get_agent_session_access(
&self,
agent_session_id: &str,
diff --git a/crates/lexical_client/Cargo.toml b/crates/lexical_client/Cargo.toml
index 4ea95152e1..308c33557b 100644
--- a/crates/lexical_client/Cargo.toml
+++ b/crates/lexical_client/Cargo.toml
@@ -7,6 +7,7 @@ version = "0.1.0"
[dependencies]
agent_fold = { path = "../agent_fold", default-features = false }
anyhow = { workspace = true }
+messages = { path = "../messages" }
reqwest = { workspace = true }
serde = { workspace = true }
tracing = { workspace = true }
diff --git a/crates/lexical_client/src/parse_markdown.rs b/crates/lexical_client/src/parse_markdown.rs
index 6bab6834f2..500b8b3a60 100644
--- a/crates/lexical_client/src/parse_markdown.rs
+++ b/crates/lexical_client/src/parse_markdown.rs
@@ -1,5 +1,6 @@
use super::LexicalClient;
use crate::types::{CognitionResponseData, CognitionV2ResponseData};
+use messages::domain::models::MessageParent;
use crate::types::MarkdownParseResult;
use agent_fold::domain::model::MessageId;
@@ -55,12 +56,12 @@ struct ExtractReplyRequest<'a> {
/// The leading `ReplyTargetNode` extracted from markdown by the lexical
/// service `/extract-reply` endpoint, when the markdown is an explicit reply.
-#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
+#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ExtractedExplicitReply {
- /// Channel containing the targeted message.
- pub channel_id: String,
- /// Targeted channel message.
+ /// Entity containing the targeted message.
+ pub parent: MessageParent,
+ /// Targeted message.
pub target_message_id: String,
/// Thread containing the targeted message.
pub target_thread_id: String,
@@ -70,6 +71,40 @@ pub struct ExtractedExplicitReply {
pub sender_id: String,
}
+/// Wire shape of an extracted reply target. Reply targets serialized before
+/// message parents existed name only a `channelId`; both shapes decode.
+#[derive(serde::Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct ExtractedExplicitReplyWire {
+ #[serde(default)]
+ parent: Option<MessageParent>,
+ #[serde(default)]
+ channel_id: Option<String>,
+ target_message_id: String,
+ target_thread_id: String,
+ display_text: String,
+ sender_id: String,
+}
+
+impl<'de> serde::Deserialize<'de> for ExtractedExplicitReply {
+ fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
+ let wire = ExtractedExplicitReplyWire::deserialize(deserializer)?;
+ let parent = match (wire.parent, wire.channel_id) {
+ (Some(parent), _) => parent,
+ (None, Some(channel_id)) => MessageParent::parse("channel", &channel_id)
+ .map_err(|_| serde::de::Error::custom("reply target channelId is not a uuid"))?,
+ (None, None) => return Err(serde::de::Error::missing_field("parent")),
+ };
+ Ok(Self {
+ parent,
+ target_message_id: wire.target_message_id,
+ target_thread_id: wire.target_thread_id,
+ display_text: wire.display_text,
+ sender_id: wire.sender_id,
+ })
+ }
+}
+
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
struct ExtractReplyResponse {
@@ -109,14 +144,18 @@ pub struct AgentAnnouncementChip {
pub status: String,
}
-/// The channel message targeted by an agent-session announcement, in the
-/// shape the lexical service's `ReplyTargetNode` validates.
+/// The message targeted by an agent-session announcement, in the shape the
+/// lexical service's `ReplyTargetNode` validates.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AgentAnnouncementReplyTarget {
- /// Channel containing the targeted message.
- pub channel_id: String,
- /// Targeted channel message.
+ /// Entity containing the targeted message.
+ pub parent: MessageParent,
+ /// Channel containing the targeted message, for channel parents. Sent
+ /// beside `parent` for the reply-target shape that predates parents.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub channel_id: Option<String>,
+ /// Targeted message.
pub target_message_id: String,
/// Thread containing the targeted message.
pub target_thread_id: String,
@@ -152,6 +191,8 @@ pub struct AgentContextMessage<'a> {
struct AgentContextRequest<'a> {
prompt_markdown: &'a str,
#[serde(skip_serializing_if = "Option::is_none")]
+ parent: Option<&'a MessageParent>,
+ #[serde(skip_serializing_if = "Option::is_none")]
messages: Option<&'a [AgentContextMessage<'a>]>,
}
@@ -393,6 +434,7 @@ impl LexicalClient {
pub async fn compose_agent_context(
&self,
prompt_markdown: &str,
+ parent: Option<&MessageParent>,
messages: Option<&[AgentContextMessage<'_>]>,
) -> Result<String> {
let url = format!("{}/agent-context", self.url);
@@ -401,6 +443,7 @@ impl LexicalClient {
.post(&url)
.json(&AgentContextRequest {
prompt_markdown,
+ parent,
messages,
})
.send()
@@ -541,7 +584,7 @@ mod tests {
fn extract_reply_response_deserializes_a_target() {
let json = r#"{
"reply": {
- "channelId": "channel-1",
+ "parent": {"type": "document", "id": "doc-1"},
"targetMessageId": "message-1",
"targetThreadId": "thread-1",
"displayText": "please fix this",
@@ -551,11 +594,59 @@ mod tests {
let response: ExtractReplyResponse = serde_json::from_str(json).unwrap();
let reply = response.reply.expect("reply");
- assert_eq!(reply.channel_id, "channel-1");
+ assert_eq!(
+ reply.parent,
+ MessageParent::parse("document", "doc-1").unwrap()
+ );
assert_eq!(reply.target_message_id, "message-1");
assert_eq!(reply.sender_id, "bot|00000000-0000-0000-0000-00000000b07a");
}
+ #[test]
+ fn extract_reply_response_reads_a_channel_only_target_as_a_channel_parent() {
+ let json = r#"{
+ "reply": {
+ "channelId": "00000000-0000-0000-0000-000000000001",
+ "targetMessageId": "message-1",
+ "targetThreadId": "thread-1",
+ "displayText": "please fix this",
+ "senderId": "macro|[email protected]"
+ }
+ }"#;
+
+ let response: ExtractReplyResponse = serde_json::from_str(json).unwrap();
+ let reply = response.reply.expect("reply");
+ assert_eq!(
+ reply.parent,
+ MessageParent::parse("channel", "00000000-0000-0000-0000-000000000001").unwrap()
+ );
+ }
+
+ #[test]
+ fn announcement_reply_target_names_the_channel_beside_its_parent() {
+ let target = AgentAnnouncementReplyTarget {
+ parent: MessageParent::parse("channel", "00000000-0000-0000-0000-000000000001")
+ .unwrap(),
+ channel_id: Some("00000000-0000-0000-0000-000000000001".to_owned()),
+ target_message_id: "message-1".to_owned(),
+ target_thread_id: "thread-1".to_owned(),
+ display_text: "please fix this".to_owned(),
+ sender_id: "macro|[email protected]".to_owned(),
+ };
+ let value = serde_json::to_value(&target).unwrap();
+ assert_eq!(value["parent"]["type"], "channel");
+ assert_eq!(value["channelId"], "00000000-0000-0000-0000-000000000001");
+
+ let document = AgentAnnouncementReplyTarget {
+ parent: MessageParent::parse("document", "doc-1").unwrap(),
+ channel_id: None,
+ ..target
+ };
+ let value = serde_json::to_value(&document).unwrap();
+ assert!(value.get("channelId").is_none());
+ assert_eq!(value["parent"]["id"], "doc-1");
+ }
+
#[test]
fn extract_reply_response_deserializes_null() {
let response: ExtractReplyResponse = serde_json::from_str(r#"{ "reply": null }"#).unwrap();
diff --git a/crates/messages/src/domain/models.rs b/crates/messages/src/domain/models.rs
index 516f52a22a..ca9b15737a 100644
--- a/crates/messages/src/domain/models.rs
+++ b/crates/messages/src/domain/models.rs
@@ -77,6 +77,15 @@ impl MessageParent {
pub fn is_discussion(&self) -> bool {
!matches!(self, Self::Channel(_))
}
+
+ /// Entity type whose permissions govern messages on this parent.
+ #[cfg(feature = "ports")]
+ pub fn access_entity_type(&self) -> entity_access::domain::models::EntityType {
+ match self {
+ Self::Channel(_) => entity_access::domain::models::EntityType::Channel,
+ Self::Document(_) => entity_access::domain::models::EntityType::Document,
+ }
+ }
}
/// A thread's location within its document. Geometry remains annotation-owned.
diff --git a/crates/model_notifications/src/lib.rs b/crates/model_notifications/src/lib.rs
index 616ced1da4..ddd832dfb4 100644
--- a/crates/model_notifications/src/lib.rs
+++ b/crates/model_notifications/src/lib.rs
@@ -10,17 +10,18 @@ mod metadata;
mod unsubscribe;
pub use device::DeviceType;
pub use metadata::{
- AgentSessionMentionedMetadata, AgentSessionNotificationRef, AgentSessionSettledMetadata,
- AgentSessionWaitingForInputMetadata, AiResponseMetadata, CalendarEventReminderMetadata,
- CallStartedMetadata, ChannelInviteMetadata, ChannelMentionMetadata, ChannelMessageSendMetadata,
- ChannelReplyMetadata, ChannelType, CommentedOnDocumentMetadata, CommonChannelMetadata,
- DocumentMentionMetadata, GithubPrCheckRun, GithubPrCheckRunState, GithubPrComment,
- GithubPrCommentKind, GithubPrEventAction, GithubPrEventStatus, GithubPrMention,
- GithubPrMentionLocation, GithubPrNotificationCommon, GithubPrReview, GithubPrReviewState,
- GithubPrStatusChanged, GithubReviewRequested, InboxReauthRequiredMetadata,
- InviteToTeamMetadata, ItemSharedMetadata, MentionedInDocumentCommentMetadata, NewEmailMetadata,
- NotificationDocumentSubType, NotificationTitle, ReminderMetadata,
- RepliedToDocumentCommentThreadMetadata, TaskAssignedMetadata,
+ AgentSessionMentionedMetadata, AgentSessionNotificationRef, AgentSessionOriginParent,
+ AgentSessionSettledMetadata, AgentSessionWaitingForInputMetadata, AiResponseMetadata,
+ CalendarEventReminderMetadata, CallStartedMetadata, ChannelInviteMetadata,
+ ChannelMentionMetadata, ChannelMessageSendMetadata, ChannelReplyMetadata, ChannelType,
+ CommentedOnDocumentMetadata, CommonChannelMetadata, DocumentMentionMetadata, GithubPrCheckRun,
+ GithubPrCheckRunState, GithubPrComment, GithubPrCommentKind, GithubPrEventAction,
+ GithubPrEventStatus, GithubPrMention, GithubPrMentionLocation, GithubPrNotificationCommon,
+ GithubPrReview, GithubPrReviewState, GithubPrStatusChanged, GithubReviewRequested,
+ InboxReauthRequiredMetadata, InviteToTeamMetadata, ItemSharedMetadata,
+ MentionedInDocumentCommentMetadata, NewEmailMetadata, NotificationDocumentSubType,
+ NotificationTitle, ReminderMetadata, RepliedToDocumentCommentThreadMetadata,
+ TaskAssignedMetadata,
};
pub use unsubscribe::UserUnsubscribe;
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
diff --git a/crates/model_notifications/src/metadata.rs b/crates/model_notifications/src/metadata.rs
index 8045ffa2e3..e48a069059 100644
--- a/crates/model_notifications/src/metadata.rs
+++ b/crates/model_notifications/src/metadata.rs
@@ -1625,6 +1625,18 @@ const AGENT_EXCERPT_MAX_CHARS: usize = 280;
/// The session an agent-session notification is about, and where its magic
/// chip lives when it was opened from a thread.
///
+/// The conversation an agent session was opened from: a channel or a
+/// document discussion. Spelled like the message API's parent so a client can
+/// route to either surface.
+#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, ToSchema)]
+pub struct AgentSessionOriginParent {
+ /// `channel` or `document`.
+ #[serde(rename = "type")]
+ pub kind: String,
+ /// The channel or document id.
+ pub id: String,
+}
+
/// Flattened into each agent-session kind so the wire keeps these keys at the
/// top level of the metadata, the way [`CommonChannelMetadata`] does.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, ToSchema)]
@@ -1642,7 +1654,11 @@ pub struct AgentSessionNotificationRef {
/// The bot's display name; agent notifications have no user sender, so
/// this is who they read as being from.
pub bot_name: String,
- /// The channel the session was opened from, when it was.
+ /// The channel or document the session was opened from, when it was.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub parent: Option<AgentSessionOriginParent>,
+ /// The channel the session was opened from, when it was opened from a
+ /// channel thread.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub channel_id: Option<Uuid>,
/// The thread the session was opened from, when it was.
diff --git a/crates/model_notifications/src/metadata/test.rs b/crates/model_notifications/src/metadata/test.rs
index fc5124096e..ef2d51f022 100644
--- a/crates/model_notifications/src/metadata/test.rs
+++ b/crates/model_notifications/src/metadata/test.rs
@@ -986,6 +986,10 @@ fn agent_session_ref() -> AgentSessionNotificationRef {
session_name: "Fix the flaky test".to_string(),
bot_id: Uuid::parse_str("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb").unwrap(),
bot_name: "Macro Coder".to_string(),
+ parent: Some(AgentSessionOriginParent {
+ kind: "channel".to_string(),
+ id: "cccccccc-cccc-4ccc-8ccc-cccccccccccc".to_string(),
+ }),
channel_id: Some(Uuid::parse_str("cccccccc-cccc-4ccc-8ccc-cccccccccccc").unwrap()),
thread_id: Some(Uuid::parse_str("dddddddd-dddd-4ddd-8ddd-dddddddddddd").unwrap()),
announcement_message_id: None,
diff --git a/crates/webhook/Cargo.toml b/crates/webhook/Cargo.toml
index 7f50d523d8..38cbd34449 100644
--- a/crates/webhook/Cargo.toml
+++ b/crates/webhook/Cargo.toml
@@ -64,6 +64,7 @@ stream = [
worker = ["dep:tokio", "ports"]
[dependencies]
+messages = { path = "../messages", features = ["broker"] }
anyhow = { workspace = true }
axum = { workspace = true, optional = true }
axum-extra = { workspace = true, optional = true }
diff --git a/crates/webhook/src/domain/ingestion.rs b/crates/webhook/src/domain/ingestion.rs
index 94d797472a..67b4ce5356 100644
--- a/crates/webhook/src/domain/ingestion.rs
+++ b/crates/webhook/src/domain/ingestion.rs
@@ -25,6 +25,7 @@ use entity_access::domain::ports::EntityAccessService;
use futures::future::join_all;
use macro_event_broker::Event;
use macro_user_id::user_id::MacroUserIdStr;
+use messages::domain::models::MessageParent;
use std::future::Future;
use std::sync::Arc;
use tracing::Instrument as _;
@@ -396,48 +397,44 @@ pub(crate) struct TriggerAudience {
pub(crate) entity_type: EntityType,
}
+impl TriggerAudience {
+ /// Whoever may currently read the conversation's parent.
+ fn parent(parent: &MessageParent) -> Self {
+ Self {
+ entity_id: parent.entity_id(),
+ entity_type: parent.access_entity_type(),
+ }
+ }
+}
+
/// Normalize one agent-trigger event.
///
/// The entity - and the ordering key, mirroring the broker's partitioning -
/// is the bot: a subscriber consumes a bot's whole trigger stream, in order.
/// Returned alongside is whose access gates it, which differs by shape.
///
-/// A mention that opens a session has no session yet, so the channel it was
-/// posted in is the only thing to ask. Once a session exists it carries its
-/// own grants - its owner, and the channel it came from - so the session is
-/// the authoritative audience, and whatever channel a later message happened
-/// to land in is incidental to it.
+/// Every message trigger includes parent content, so delivery rechecks access to
+/// that parent, including follow-ups to a session with independently shared access.
pub(crate) fn normalized_agent_trigger_event(
event: &Event<AgentTriggerTopicEvent>,
) -> Result<(NormalizedWebhookEvent, TriggerAudience), WebhookEventIngestionError> {
- use agent_trigger::domain::broker_events::{
- AgentTriggerEventName, ExistingAgentSessionEvent, NewAgentSessionEvent,
- };
-
- let (bot_id, audience) = match &event.event {
- AgentTriggerTopicEvent::New(NewAgentSessionEvent::TopLevelMentioned(mentioned)) => (
- mentioned.bot_id,
- TriggerAudience {
- entity_id: mentioned.message.channel_id.to_string(),
- entity_type: EntityType::Channel,
- },
- ),
- AgentTriggerTopicEvent::Existing(ExistingAgentSessionEvent::Channel(metadata)) => (
- metadata.bot_id,
- TriggerAudience {
- entity_id: metadata.session_id.to_string(),
- entity_type: EntityType::AgentSession,
- },
- ),
- // Both trigger enums are non-exhaustive on purpose; an unknown shape
- // has no bot to route to. Permanent, so the consumer skips it.
- _ => {
- return Err(WebhookEventIngestionError::InvalidEntityId {
- entity_type: "bot",
- entity_id: "unrecognized agent-trigger event shape".to_owned(),
- });
- }
- };
+ use agent_trigger::domain::broker_events::AgentTriggerEventName;
+
+ let (bot_id, parent) = match &event.event {
+ AgentTriggerTopicEvent::New(new) => new
+ .mention()
+ .map(|mention| (mention.bot_id, mention.message.parent)),
+ AgentTriggerTopicEvent::Existing(existing) => existing
+ .session_message()
+ .map(|message| (message.bot_id, message.message.parent)),
+ }
+ // Both trigger enums are non-exhaustive on purpose; an unknown shape
+ // has no bot to route to. Permanent, so the consumer skips it.
+ .ok_or_else(|| WebhookEventIngestionError::InvalidEntityId {
+ entity_type: "bot",
+ entity_id: "unrecognized agent-trigger event shape".to_owned(),
+ })?;
+ let audience = TriggerAudience::parent(&parent);
let event_name: &'static str = AgentTriggerEventName::from(&event.event).into();
let broker_envelope = serde_json::to_value(event)?;
let bot_id = bot_id.to_string();
@@ -485,10 +482,11 @@ pub(crate) fn normalized_agent_session_lifecycle_event(
pub(crate) enum LifecycleAudience {
/// Everyone with access to the session.
Session,
- /// The session is gone: its owner, plus the channel it was opened from.
+ /// The session is gone: its owner, plus the channel or document it was
+ /// opened from.
Departed {
owner: MacroUserIdStr<'static>,
- origin_channel_id: Option<Uuid>,
+ origin_parent: Option<MessageParent>,
},
}
@@ -496,11 +494,11 @@ pub(crate) fn lifecycle_audience(event: &AgentSessionLifecycleEvent) -> Lifecycl
match event {
AgentSessionLifecycleEvent::Deleted(deleted) => LifecycleAudience::Departed {
owner: deleted.identity.owner_id.clone(),
- origin_channel_id: deleted
+ origin_parent: deleted
.identity
.origin
.as_ref()
- .map(|origin| origin.channel_id),
+ .map(|origin| origin.parent.clone()),
},
AgentSessionLifecycleEvent::Opened(_)
| AgentSessionLifecycleEvent::TurnStarted(_)
@@ -581,12 +579,13 @@ where
}
LifecycleAudience::Departed {
owner,
- origin_channel_id,
+ origin_parent,
} => {
let mut accessors = vec![owner];
- if let Some(channel_id) = origin_channel_id {
+ if let Some(parent) = origin_parent {
+ let audience = TriggerAudience::parent(&parent);
accessors.extend(
- self.users_with_access(&channel_id.to_string(), EntityType::Channel)
+ self.users_with_access(&audience.entity_id, audience.entity_type)
.await?,
);
}
diff --git a/crates/webhook/src/domain/ingestion/stream.rs b/crates/webhook/src/domain/ingestion/stream.rs
index 9fe54162e3..279e7678fb 100644
--- a/crates/webhook/src/domain/ingestion/stream.rs
+++ b/crates/webhook/src/domain/ingestion/stream.rs
@@ -75,22 +75,25 @@ pub(crate) fn agent_session_lifecycle_stream_candidate(
entity_id: normalized.entity_id.clone(),
entity_type: EntityType::AgentSession,
},
- // The session's grants are gone with it; the channel it came from
- // still knows its audience, and a session without one was its
- // owner's alone.
+ // The session's grants are gone with it. The owner keeps ownership, so
+ // they must still receive the departure even after losing access to the
+ // parent; the channel or document it came from also still knows its
+ // audience. Deliver to the union of the two.
LifecycleAudience::Departed {
owner,
- origin_channel_id: Some(channel_id),
- } => {
- drop(owner);
+ origin_parent: Some(parent),
+ } => StreamAudience::Any(vec![
+ StreamAudience::Workspace {
+ workspace_id: owner.to_string(),
+ },
StreamAudience::Entity {
- entity_id: channel_id.to_string(),
- entity_type: EntityType::Channel,
- }
- }
+ entity_id: parent.entity_id(),
+ entity_type: parent.access_entity_type(),
+ },
+ ]),
LifecycleAudience::Departed {
owner,
- origin_channel_id: None,
+ origin_parent: None,
} => StreamAudience::Workspace {
workspace_id: owner.to_string(),
},
diff --git a/crates/webhook/src/domain/ingestion/test.rs b/crates/webhook/src/domain/ingestion/test.rs
index bbf5400d08..ded1fb5d38 100644
--- a/crates/webhook/src/domain/ingestion/test.rs
+++ b/crates/webhook/src/domain/ingestion/test.rs
@@ -1328,8 +1328,6 @@ fn agent_trigger_new_event() -> Event<agent_trigger::domain::broker_events::Agen
use agent_trigger::domain::broker_events::{
AgentBotMentionedEvent, AgentTriggerTopicEvent, NewAgentSessionEvent,
};
- use channels::domain::broker_events::ChannelMessagePostedMetadata;
- use channels::domain::models::ChannelType;
Event::new(AgentTriggerTopicEvent::New(
NewAgentSessionEvent::TopLevelMentioned(AgentBotMentionedEvent {
@@ -1350,19 +1348,43 @@ fn agent_trigger_new_event() -> Event<agent_trigger::domain::broker_events::Agen
))
}
+fn agent_trigger_document_event()
+-> Event<agent_trigger::domain::broker_events::AgentTriggerTopicEvent> {
+ use agent_trigger::domain::broker_events::{
+ AgentMentionedEvent, AgentTriggerTopicEvent, NewAgentSessionEvent,
+ };
+
+ Event::new(AgentTriggerTopicEvent::New(
+ NewAgentSessionEvent::Mentioned(AgentMentionedEvent {
+ bot_id: bot_id::BotId::new_from_uuid(uuid::Uuid::from_u128(0xB07)),
+ message: messages::domain::events::MessagePostedMetadata {
+ parent: messages::domain::models::MessageParent::parse("document", "doc-1")
+ .unwrap(),
+ message_id: uuid::Uuid::from_u128(2),
+ thread_id: None,
+ root_id: uuid::Uuid::from_u128(2),
+ sender: sender("macro|[email protected]"),
+ triggered_by: None,
+ content: "summarize this".to_owned(),
+ mentions: vec![],
+ attachments: vec![],
+ created_at: timestamp(),
+ },
+ }),
+ ))
+}
+
fn agent_trigger_existing_event()
-> Event<agent_trigger::domain::broker_events::AgentTriggerTopicEvent> {
use agent_trigger::domain::broker_events::{
AgentTriggerTopicEvent, ChannelEventMetadata, ExistingAgentSessionEvent,
};
- use channels::domain::broker_events::ChannelMessagePostedMetadata;
- use channels::domain::models::ChannelType;
Event::new(AgentTriggerTopicEvent::Existing(
ExistingAgentSessionEvent::Channel(ChannelEventMetadata {
bot_id: bot_id::BotId::new_from_uuid(uuid::Uuid::from_u128(0xB07)),
session_id: agent_session::domain::model::AgentSessionId::TEST_A,
- kind: agent_trigger::domain::broker_events::ChannelKind::MentionThread,
+ kind: agent_trigger::domain::broker_events::ThreadMessageKind::MentionThread,
message: ChannelMessagePostedMetadata {
channel_id: uuid::Uuid::from_u128(1),
message_id: uuid::Uuid::from_u128(2),
@@ -1379,11 +1401,30 @@ fn agent_trigger_existing_event()
))
}
-/// A follow-up on a session that exists asks the session, not the channel:
-/// the session carries its own grants, so whatever channel a later message
-/// landed in is incidental.
+/// A document trigger is gated by who may read the document.
+#[tokio::test]
+async fn a_document_trigger_is_gated_by_its_document() {
+ let access = MockAccessService::with_users(vec![user_id(PERSONAL_WORKSPACE_ID)]);
+ let repository = MockRepository::new(
+ vec![PERSONAL_WORKSPACE_ID.to_string()],
+ vec![webhook("wh_agent_feed", PERSONAL_WORKSPACE_ID)],
+ );
+ let service = service(access.clone(), repository.clone(), MockEnqueuer::default());
+
+ service
+ .ingest_agent_trigger_event(agent_trigger_document_event())
+ .await
+ .expect("document agent trigger events are ingested");
+
+ assert_eq!(
+ lock(&access.calls).as_slice(),
+ &[("doc-1".to_owned(), EntityType::Document)],
+ );
+}
+
+/// An existing session does not grant a webhook access to a new message parent.
#[tokio::test]
-async fn an_existing_session_trigger_is_gated_by_the_session() {
+async fn an_existing_session_trigger_is_gated_by_its_message_parent() {
let access = MockAccessService::with_users(vec![user_id(PERSONAL_WORKSPACE_ID)]);
let repository = MockRepository::new(
vec![PERSONAL_WORKSPACE_ID.to_string()],
@@ -1398,10 +1439,7 @@ async fn an_existing_session_trigger_is_gated_by_the_session() {
assert_eq!(
lock(&access.calls).as_slice(),
- &[(
- agent_session::domain::model::AgentSessionId::TEST_A.to_string(),
- EntityType::AgentSession
- )],
+ &[(uuid::Uuid::from_u128(1).to_string(), EntityType::Channel)],
);
}
@@ -1474,11 +1512,11 @@ fn agent_session_lifecycle_event(
owner_id: macro_user_id::user_id::MacroUserIdStr::parse_from_str("macro|[email protected]")
.expect("valid user id")
.into_owned(),
- origin: Some(ThreadOrigin {
- channel_id: uuid::Uuid::from_u128(1),
- thread_id: uuid::Uuid::from_u128(2),
- originating_message_id: uuid::Uuid::from_u128(3),
- }),
+ origin: Some(ThreadOrigin::new(
+ messages::domain::models::MessageParent::Channel(uuid::Uuid::from_u128(1)),
+ uuid::Uuid::from_u128(2),
+ uuid::Uuid::from_u128(3),
+ )),
audience: Vec::new(),
}))
}
@@ -1655,3 +1693,33 @@ async fn a_deleted_session_without_an_origin_is_its_owners_alone() {
Some(1)
);
}
+
+/// The live stream mirrors the persisted fan-out: a departed session's owner
+/// keeps ownership, so the stream audience is the union of the owner's
+/// workspace and the origin parent, not the parent alone.
+#[test]
+fn a_deleted_session_streams_to_both_its_owner_and_origin_parent() {
+ use crate::domain::ingestion::stream::agent_session_lifecycle_stream_candidate;
+ use crate::domain::stream::StreamAudience;
+ use agent_session::domain::events::{AgentSessionLifecycleEvent, SessionDeletedMetadata};
+
+ let event = agent_session_lifecycle_event(|identity| {
+ AgentSessionLifecycleEvent::Deleted(SessionDeletedMetadata { identity })
+ });
+
+ let candidate =
+ agent_session_lifecycle_stream_candidate(&event).expect("a deleted session streams");
+
+ assert_eq!(
+ candidate.audience,
+ StreamAudience::Any(vec![
+ StreamAudience::Workspace {
+ workspace_id: "macro|[email protected]".to_owned(),
+ },
+ StreamAudience::Entity {
+ entity_id: uuid::Uuid::from_u128(1).to_string(),
+ entity_type: EntityType::Channel,
+ },
+ ]),
+ );
+}
diff --git a/crates/webhook/src/domain/stream.rs b/crates/webhook/src/domain/stream.rs
index d17c20d62f..8724b22205 100644
--- a/crates/webhook/src/domain/stream.rs
+++ b/crates/webhook/src/domain/stream.rs
@@ -46,6 +46,10 @@ pub enum StreamAudience {
/// Owning workspace id.
workspace_id: String,
},
+ /// Anyone in any of these audiences. Used when an event belongs to more
+ /// than one grant at once, such as a departed session whose owner keeps
+ /// ownership even after losing access to the parent it came from.
+ Any(Vec<StreamAudience>),
}
/// One normalized broker event plus whose access gates it.
@@ -161,6 +165,14 @@ where
audience: &StreamAudience,
) -> Result<bool, rootcause::Report> {
match audience {
+ StreamAudience::Any(audiences) => {
+ for audience in audiences {
+ if Box::pin(self.subscriber_in_audience(audience)).await? {
+ return Ok(true);
+ }
+ }
+ Ok(false)
+ }
StreamAudience::Workspace { workspace_id } => {
let current = self.scoped_workspace_id().await?;
if self.scope == WebhookScope::Team && current.is_none() {
diff --git a/docs/design/entity-messages.md b/docs/design/entity-messages.md
index 414c082940..18628fd787 100644
--- a/docs/design/entity-messages.md
+++ b/docs/design/entity-messages.md
@@ -88,9 +88,9 @@ and never turns the committed write into an error:
`message.attachment_removed`, keyed by root id. Reactions and typing stay off the
topic. Payloads carry the parent, message and root ids, sender, and the same
fields as the channel-only events, minus `channel_type`.
-- The local built-in agent queue. In this stage the Macro AI trigger still arrives
- through the channel side effects below, so this sink is a no-op until the agent PR
- moves detection onto the message facts.
+- The local built-in agent queue: every human-authored post, on either parent, is
+ handed to the in-process Macro AI detector (see Agents below). Bot posts never
+ enter it, so bots cannot trigger each other.
- Parent delivery. For channels, `ChannelMessageDelivery` dispatches the same
`ChannelEvent`s the old writer dispatched, so notifications, activity, sharing of
referenced items, contact sync, search indexing, bot triggers, and the
@@ -103,14 +103,73 @@ and never turns the committed write into an error:
Comment notifications now identify the comment by message id, so the metadata's
`commentId` / `threadId` accept either a legacy number or a message UUID.
+## Agents
+
+Every committed post publishes `message.posted` with the persisted parent, the message
+and root ids, the sender, mentions and attachments, and the verified triggering user.
+Agent invocation reads that fact and never requires a channel id.
+
+Hosted and external agents:
+
+1. The trigger consumer verifies the sender's current ability to write to the parent
+ (channel membership or document comment access) and mints an invocation capability
+ bound to that parent and root. Agent availability is checked next: system agents
+ are global; a document permits the caller's own private or team agents; a channel
+ keeps its installation rules for selected agents and legacy agent bots.
+2. An existing session is resumed only when it was opened from the same parent and
+ root. Explicit reply references and follow-up mentions cannot select another
+ conversation's session. Otherwise a session is created for this root, and its
+ `thread_parent` is derived from the root message rather than stored.
+3. History is read through the message service under the invocation capability,
+ downgraded to view access. Document history stays inside its discussion; channel
+ history may include the preceding channel messages. The composed prompt names the
+ parent so document tools can address the enclosing document.
+4. The harness rechecks the sender's access before provisioning and again at
+ dispatch, then announces the session as the bot into the same thread through the
+ message service with a capability minted on the invoking user. Session origins,
+ queued prompts, external webhook payloads, and coding-worker origins carry the
+ parent.
+
+A document collaborator inherits session viewing from document viewing, and session
+editing from document commenting or editing; the session owner keeps explicit
+ownership, and other collaborators lose inherited access when the document grant is
+revoked. Realtime session frames are addressed through the same current access.
+
+Classic `@Macro` runs in the storage service on the local agent queue for both
+parents. It rechecks the invoking user's write access before reading context, posts a
+silent thinking message as the bot on that user's capability, and patches it into the
+answer with normal notification delivery. A deleted placeholder or revoked access
+prevents publishing the answer.
+
+### Trigger event transition
+
+The trigger consumers can read either `message.posted` on `macro.messages` (the
+default) or the pre-parent `channel.message_posted` on `macro.channels`, selected by
+`AGENT_TRIGGER_EVENT_SOURCE`. Only one source is read at a time: the storage service
+publishes every channel post on both topics, so reading both would evaluate each
+channel mention twice. The channel source stays available as a rollback until PR 7
+retires the `channel.message_*` events, at which point it is removed.
+
+Agent-session trigger events on `macro.agent_sessions` stay at schema version 1. A
+channel-parent trigger keeps the shapes every consumer already decodes
+(`top_level_mentioned` and `channel`, embedding the channel-only post with its
+`channel_type`, which the trigger reads from the channel when `message.posted` did not
+carry it). A document-parent trigger travels in the new `mentioned` and `thread`
+variants, which consumers built before message parents drop as undecodable. Old
+replicas and user-run macrod daemons therefore keep serving channel mentions through a
+deploy; only document mentions wait for them to roll. Lifecycle events keep their
+schema too: `ThreadOrigin` gains `parent` and its `channel_id` becomes optional, and
+older origins without a parent decode as channel origins.
+
## What each remaining PR adds
1. Comment import: an online, idempotent copy of `Comment` / `Thread` rows into the
shared store, filling the legacy-id mapping tables and the PDF anchors' `root_id`.
2. Frontend: the shared message queries, cache, and thread components mounted on both
surfaces behind a flag, consuming `message_update` and the new routes.
-3. Parent-aware agents: trigger detection, session origins, history, and reply
- delivery on `message.posted`; the local agent sink replaces the channel trigger.
+3. Parent-aware agents (this document's Agents section): trigger detection, session
+ origins, history, and reply delivery on `message.posted`; the local agent sink
+ replaces the channel trigger.
4. References: documents list the channel threads that mention them.
5. Contract: drop the legacy comment tables and handlers, `channel_id`, the shim
triggers, the old channel message routes, and the `channel.message_*` broker
diff --git a/packages/lexical-core/tests/agent-announcement.test.ts b/packages/lexical-core/tests/agent-announcement.test.ts
index 4aabb97da1..8825bbd316 100644
--- a/packages/lexical-core/tests/agent-announcement.test.ts
+++ b/packages/lexical-core/tests/agent-announcement.test.ts
@@ -58,6 +58,10 @@ describe('composeAgentSessionAnnouncement', () => {
expect(markdown).toBe(`${replyTargetMarkdown}\n\n${chipMarkdown}`);
});
+ it('announces with the chip alone when there is no reply target', () => {
+ expect(composeAgentSessionAnnouncement({ chip })).toBe(chipMarkdown);
+ });
+
it('emits only the chip for a blank reply-target preview', () => {
expect(
composeAgentSessionAnnouncement({
diff --git a/packages/lexical-core/tests/agent-context.test.ts b/packages/lexical-core/tests/agent-context.test.ts
index 874cc0ed6e..3de40271f1 100644
--- a/packages/lexical-core/tests/agent-context.test.ts
+++ b/packages/lexical-core/tests/agent-context.test.ts
@@ -149,6 +149,31 @@ describe('composeAgentContextPrompt', () => {
).toBe('original');
});
+ it('names the conversation parent before any history', () => {
+ expect(
+ composeAgentContextPrompt({
+ promptMarkdown: 'original request',
+ parent: { type: 'document', id: 'doc-1' },
+ messages: [{ sender: 'alice', content: 'earlier message' }],
+ })
+ ).toBe(
+ '<m-agent-context>{"version":1,"text":"Conversation parent: {\\"type\\":\\"document\\",\\"id\\":\\"doc-1\\"}\\n\\nPrior message 1:\\nSender: alice\\nContent: earlier message"}</m-agent-context>\n\noriginal request'
+ );
+ });
+
+ it('names the conversation parent even without history', () => {
+ const composed = composeAgentContextPrompt({
+ promptMarkdown: 'original',
+ parent: { type: 'channel', id: 'channel-1' },
+ });
+ const state = markdownToSerializedEditorStateWithIds(composed);
+
+ expect(state.root.children[0]).toMatchObject({
+ type: 'agent-context',
+ text: 'Conversation parent: {"type":"channel","id":"channel-1"}',
+ });
+ });
+
it('cannot close the context envelope from message content', () => {
const composed = composeAgentContextPrompt({
promptMarkdown: 'original',
diff --git a/packages/lexical-core/utils/agent-announcement.ts b/packages/lexical-core/utils/agent-announcement.ts
index 41c74308f8..fea95f9347 100644
--- a/packages/lexical-core/utils/agent-announcement.ts
+++ b/packages/lexical-core/utils/agent-announcement.ts
@@ -8,29 +8,33 @@ import {
} from '../nodes/MagicChipNode';
import {
$createReplyTargetNode,
- stripLeadingReplyTargetMarkdown,
type ReplyTargetData,
+ stripLeadingReplyTargetMarkdown,
} from '../nodes/ReplyTargetNode';
import { ALL_TRANSFORMERS } from '../transformers';
/** Everything the announcement for one agent-session prompt is built from. */
export type AgentSessionAnnouncement = {
- /** Message the agent announcement explicitly replies to. */
- replyTarget: ReplyTargetData;
+ /**
+ * Message the agent announcement explicitly replies to. Absent when the
+ * conversation cannot be referenced by a reply target yet, in which case
+ * the announcement is the chip alone.
+ */
+ replyTarget?: ReplyTargetData;
/** The Magic Chip anchoring the session's live response. */
chip: MagicChipData;
};
/**
- * Compose the channel message that announces an agent session: a structured
- * reply target followed by the session's Magic Chip. Built headlessly from
- * real Lexical nodes so the serialized markdown always matches what the
- * editor itself produces.
+ * Compose the message that announces an agent session: a structured reply
+ * target followed by the session's Magic Chip. Built headlessly from real
+ * Lexical nodes so the serialized markdown always matches what the editor
+ * itself produces.
*/
export function composeAgentSessionAnnouncement(
announcement: AgentSessionAnnouncement
): string {
- const replyTarget = {
+ const replyTarget = announcement.replyTarget && {
...announcement.replyTarget,
displayText: stripLeadingReplyTargetMarkdown(
announcement.replyTarget.displayText
@@ -44,7 +48,7 @@ export function composeAgentSessionAnnouncement(
editor.update(
() => {
- if (replyTarget.displayText) {
+ if (replyTarget?.displayText) {
$getRoot().append($createReplyTargetNode(replyTarget));
}
$getRoot().append($createMagicChipNode(announcement.chip));
diff --git a/packages/lexical-core/utils/agent-context.ts b/packages/lexical-core/utils/agent-context.ts
index f3a5d2d544..55471cc410 100644
--- a/packages/lexical-core/utils/agent-context.ts
+++ b/packages/lexical-core/utils/agent-context.ts
@@ -14,9 +14,17 @@ export type AgentContextMessage = {
content: string;
};
-/** Input used to compose an agent prompt with private channel context. */
+/** The authorized conversation a prompt was posted in. */
+export type AgentContextParent = {
+ type: 'channel' | 'document';
+ id: string;
+};
+
+/** Input used to compose an agent prompt with private conversation context. */
export type AgentContextPrompt = {
promptMarkdown: string;
+ /** Supplied by the message service, never by the prompt's author. */
+ parent?: AgentContextParent;
messages?: AgentContextMessage[];
};
@@ -29,8 +37,9 @@ function escapeAgentContextTags(markdown: string): string {
}
/**
- * Prefix a prompt with a private AgentContext node containing chronological
- * channel history. The internal markdown transformer owns envelope encoding.
+ * Prefix a prompt with a private AgentContext node naming the conversation it
+ * came from and containing its chronological history. The internal markdown
+ * transformer owns envelope encoding.
*/
export function composeAgentContextPrompt(input: AgentContextPrompt): string {
const editor = createHeadlessEditor({
@@ -49,17 +58,20 @@ export function composeAgentContextPrompt(input: AgentContextPrompt): string {
editor.update(
() => {
- if (!input.messages?.length) return;
+ if (!input.messages?.length && !input.parent) return;
- const contextText = input.messages
+ const history = (input.messages ?? [])
.map(
(message, index) =>
`Prior message ${index + 1}:\nSender: ${message.sender}\nContent: ${message.content}`
)
.join('\n\n');
+ const location = input.parent
+ ? `Conversation parent: ${JSON.stringify(input.parent)}`
+ : '';
const context = $createAgentContextNode({
version: 1,
- text: contextText,
+ text: [location, history].filter(Boolean).join('\n\n'),
});
const firstChild = $getRoot().getFirstChild();
if (firstChild) firstChild.insertBefore(context);
diff --git a/packages/sdk/generated/agent-harness/index.ts b/packages/sdk/generated/agent-harness/index.ts
index a38a367292..d6a4b61923 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 { AgentAction, AgentActionId, AgentModelDto, AgentModelsStatusDto, AgentPromptAction, AgentRespondElicitationAction, AgentSessionLogEntryDto, AgentSessionLogResponse, AgentSessionPreviewData, AgentSessionPreviewDto, AgentSessionQueueResponse, AgentSessionResponse, AgentSetModelAction, BotId, 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, EditQueuedActionData, EditQueuedActionError, EditQueuedActionErrors, EditQueuedActionRequest, EditQueuedActionResponse, EditQueuedActionResponses, ElicitationAnswer, ElicitationContentValue, ElicitationRequestId, EmptyRequest, ExternalSessionResponse, GetAgentSandboxSizeData, GetAgentSandboxSizeError, GetAgentSandboxSizeErrors, GetAgentSandboxSizeResponse, GetAgentSandboxSizeResponses, GetAgentSessionData, GetAgentSessionError, GetAgentSessionErrors, GetAgentSessionLogData, GetAgentSessionLogError, GetAgentSessionLogErrors, GetAgentSessionLogResponse, GetAgentSessionLogResponses, GetAgentSessionQueueData, GetAgentSessionQueueError, GetAgentSessionQueueErrors, GetAgentSessionQueueResponse, GetAgentSessionQueueResponses, GetAgentSessionResponse, GetAgentSessionResponses, LoadAgentModelsHandlerData, LoadAgentModelsHandlerErrors, LoadAgentModelsHandlerResponse, LoadAgentModelsHandlerResponses, LoadAgentModelsRequest, LoadAgentModelsResponse, LogDirectionDto, LogFrameDto, ModelHarnessDto, PreviewAgentSessionsData, PreviewAgentSessionsError, PreviewAgentSessionsErrors, PreviewAgentSessionsRequest, PreviewAgentSessionsResponse, PreviewAgentSessionsResponse2, PreviewAgentSessionsResponses, PutAgentSandboxSizeData, PutAgentSandboxSizeError, PutAgentSandboxSizeErrors, PutAgentSandboxSizeResponse, PutAgentSandboxSizeResponses, PutAgentSessionSandboxSizeData, PutAgentSessionSandboxSizeError, PutAgentSessionSandboxSizeErrors, PutAgentSessionSandboxSizeResponse, PutAgentSessionSandboxSizeResponses, QueuedActionDto, RemoveQueuedActionData, RemoveQueuedActionError, RemoveQueuedActionErrors, RemoveQueuedActionResponse, RemoveQueuedActionResponses, RenameAgentSessionData, RenameAgentSessionError, RenameAgentSessionErrors, RenameAgentSessionRequest, RenameAgentSessionResponse, RenameAgentSessionResponses, SandboxSize, SandboxSizeBody, SessionBot, SessionStatusDto, StartData, StartErrors, StartResponse, StartResponse2, StartResponses, StatusData, StatusErrors, StatusResponse, StatusResponse2, StatusResponses, WithAgentSessionId } from './types.gen';
+export type { AgentAction, AgentActionId, AgentModelDto, AgentModelsStatusDto, AgentPromptAction, AgentRespondElicitationAction, AgentSessionLogEntryDto, AgentSessionLogResponse, AgentSessionPreviewData, AgentSessionPreviewDto, AgentSessionQueueResponse, AgentSessionResponse, AgentSetModelAction, BotId, 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, DocumentId, EditQueuedActionData, EditQueuedActionError, EditQueuedActionErrors, EditQueuedActionRequest, EditQueuedActionResponse, EditQueuedActionResponses, ElicitationAnswer, ElicitationContentValue, ElicitationRequestId, EmptyRequest, ExternalSessionResponse, GetAgentSandboxSizeData, GetAgentSandboxSizeError, GetAgentSandboxSizeErrors, GetAgentSandboxSizeResponse, GetAgentSandboxSizeResponses, GetAgentSessionData, GetAgentSessionError, GetAgentSessionErrors, GetAgentSessionLogData, GetAgentSessionLogError, GetAgentSessionLogErrors, GetAgentSessionLogResponse, GetAgentSessionLogResponses, GetAgentSessionQueueData, GetAgentSessionQueueError, GetAgentSessionQueueErrors, GetAgentSessionQueueResponse, GetAgentSessionQueueResponses, GetAgentSessionResponse, GetAgentSessionResponses, LoadAgentModelsHandlerData, LoadAgentModelsHandlerErrors, LoadAgentModelsHandlerResponse, LoadAgentModelsHandlerResponses, LoadAgentModelsRequest, LoadAgentModelsResponse, LogDirectionDto, LogFrameDto, MessageParent, ModelHarnessDto, PreviewAgentSessionsData, PreviewAgentSessionsError, PreviewAgentSessionsErrors, PreviewAgentSessionsRequest, PreviewAgentSessionsResponse, PreviewAgentSessionsResponse2, PreviewAgentSessionsResponses, PutAgentSandboxSizeData, PutAgentSandboxSizeError, PutAgentSandboxSizeErrors, PutAgentSandboxSizeResponse, PutAgentSandboxSizeResponses, PutAgentSessionSandboxSizeData, PutAgentSessionSandboxSizeError, PutAgentSessionSandboxSizeErrors, PutAgentSessionSandboxSizeResponse, PutAgentSessionSandboxSizeResponses, QueuedActionDto, RemoveQueuedActionData, RemoveQueuedActionError, RemoveQueuedActionErrors, RemoveQueuedActionResponse, RemoveQueuedActionResponses, RenameAgentSessionData, RenameAgentSessionError, RenameAgentSessionErrors, RenameAgentSessionRequest, RenameAgentSessionResponse, RenameAgentSessionResponses, SandboxSize, SandboxSizeBody, SessionBot, SessionStatusDto, StartData, StartErrors, StartResponse, StartResponse2, StartResponses, StatusData, StatusErrors, StatusResponse, StatusResponse2, StatusResponses, 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 7b34ff64e1..5e9d75d813 100644
--- a/packages/sdk/generated/agent-harness/types.gen.ts
+++ b/packages/sdk/generated/agent-harness/types.gen.ts
@@ -288,13 +288,14 @@ export type AgentSessionResponse = {
status: SessionStatusDto;
/**
* The channel `thread_id` lives in, when the session was spawned from a
- * thread.
+ * channel thread. Derived from `thread_parent`.
*/
threadChannelId?: string | null;
/**
* The root message of the thread the session was created from, if any.
*/
threadId?: string | null;
+ threadParent?: null | MessageParent;
/**
* The directory the session's harness runs in on its runtime.
*/
@@ -441,9 +442,10 @@ export type CreateAgentSessionResponse = {
*/
export type CreateSessionThread = {
/**
- * Channel the mentioning message was posted in.
+ * Channel the mentioning message was posted in. Runtimes built before
+ * message parents send this instead of `parent`.
*/
- channelId: string;
+ channelId?: string | null;
/**
* The mention's text, quoted in the session's announcement.
*/
@@ -452,6 +454,7 @@ export type CreateSessionThread = {
* The mentioning message.
*/
messageId: string;
+ parent?: null | MessageParent;
/**
* Thread the session belongs to; defaults to the message itself, which
* is how a top-level mention roots its own thread.
@@ -459,6 +462,11 @@ export type CreateSessionThread = {
threadId?: string | null;
};
+/**
+ * A validated document identifier. Historical document ids need not be UUIDs.
+ */
+export type DocumentId = string;
+
/**
* Request body for editing a queued prompt.
*/
@@ -596,6 +604,23 @@ export type LogFrameDto = {
direction: LogDirectionDto;
};
+/**
+ * The entity whose permissions and lifecycle govern a message.
+ */
+export type MessageParent = {
+ /**
+ * A channel, including direct messages.
+ */
+ id: string;
+ type: 'channel';
+} | {
+ /**
+ * A document, including tasks and PDFs.
+ */
+ id: DocumentId;
+ type: 'document';
+};
+
/**
* Harness names accepted by the model discovery endpoint.
*/
diff --git a/packages/sdk/generated/notification/index.ts b/packages/sdk/generated/notification/index.ts
index f3694c86f8..2e683c3803 100644
--- a/packages/sdk/generated/notification/index.ts
+++ b/packages/sdk/generated/notification/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 { AgentSessionMentionedMetadata, AgentSessionNotificationRef, AgentSessionSettledMetadata, AgentSessionWaitingForInputMetadata, AiResponseMetadata, ApiUserNotification, BulkDeleteUserNotificationsV2Data, BulkDeleteUserNotificationsV2Error, BulkDeleteUserNotificationsV2Errors, BulkDeleteUserNotificationsV2Responses, BulkGetByEventItemIdsRequest, BulkGetTypedNotificationsByEventItemIdsData, BulkGetTypedNotificationsByEventItemIdsError, BulkGetTypedNotificationsByEventItemIdsErrors, BulkGetTypedNotificationsByEventItemIdsResponse, BulkGetTypedNotificationsByEventItemIdsResponses, BulkMarkNotificationsDoneData, BulkMarkNotificationsDoneError, BulkMarkNotificationsDoneErrors, BulkMarkNotificationsDoneResponses, BulkMarkNotificationsSeenData, BulkMarkNotificationsSeenError, BulkMarkNotificationsSeenErrors, BulkMarkNotificationsSeenResponses, BulkMarkNotificationsUndoneData, BulkMarkNotificationsUndoneError, BulkMarkNotificationsUndoneErrors, BulkMarkNotificationsUndoneResponses, CalendarEventReminderMetadata, CallStartedMetadata, ChannelInviteMetadata, ChannelMentionMetadata, ChannelMessageSendMetadata, ChannelReplyMetadata, ChannelType, ClientOptions, CommentedOnDocumentMetadata, CommentRef, CommonChannelMetadata, ConnGatewayNotificationPayload, CreateNotification, DeleteUserNotificationV2Data, DeleteUserNotificationV2Error, DeleteUserNotificationV2Errors, DeleteUserNotificationV2Responses, DeviceRequest, DeviceType, DisableNotificationTypeData, DisableNotificationTypeError, DisableNotificationTypeErrors, DisableNotificationTypeResponses, DocumentMentionMetadata, EmptyResponse, EnableNotificationTypeData, EnableNotificationTypeError, EnableNotificationTypeErrors, EnableNotificationTypeResponses, Entity, EntityType, ErrorResponse, GetAllUserNotificationsResponse, GetNotificationTypePreferencesData, GetNotificationTypePreferencesError, GetNotificationTypePreferencesErrors, GetNotificationTypePreferencesResponse, GetNotificationTypePreferencesResponse2, GetNotificationTypePreferencesResponses, GetTypedNotificationByIdData, GetTypedNotificationByIdError, GetTypedNotificationByIdErrors, GetTypedNotificationByIdResponse, GetTypedNotificationByIdResponses, GetTypedNotificationsByEventItemIdData, GetTypedNotificationsByEventItemIdError, GetTypedNotificationsByEventItemIdErrors, GetTypedNotificationsByEventItemIdResponse, GetTypedNotificationsByEventItemIdResponses, GetUnsubscribesData, GetUnsubscribesError, GetUnsubscribesErrors, GetUnsubscribesResponse, GetUnsubscribesResponses, GithubPrCheckRun, GithubPrCheckRunState, GithubPrComment, GithubPrCommentKind, GithubPrEventAction, GithubPrEventStatus, GithubPrMention, GithubPrMentionLocation, GithubPrNotificationCommon, GithubPrReview, GithubPrReviewState, GithubPrStatusChanged, GithubReviewRequested, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, InboxReauthRequiredMetadata, InviteToTeamMetadata, ItemSharedMetadata, ListTypedNotificationsData, ListTypedNotificationsError, ListTypedNotificationsErrors, ListTypedNotificationsResponse, ListTypedNotificationsResponses, MacroUserIdStr, MentionedInDocumentCommentMetadata, NewEmailMetadata, NotifEvent, NotificationBulkRequest, NotificationDocumentSubType, NotificationServiceApiVersion, NotificationState, NotificationTypeName, PushNotificationData, RealtimeNotifTaggedContentValue, ReminderMetadata, RemoveUnsubscribeAllData, RemoveUnsubscribeAllError, RemoveUnsubscribeAllErrors, RemoveUnsubscribeAllResponse, RemoveUnsubscribeAllResponses, RemoveUnsubscribeItemData, RemoveUnsubscribeItemError, RemoveUnsubscribeItemErrors, RemoveUnsubscribeItemResponse, RemoveUnsubscribeItemResponses, RepliedToDocumentCommentThreadMetadata, TaskAssignedMetadata, UnsubscribeAllData, UnsubscribeAllError, UnsubscribeAllErrors, UnsubscribeAllResponse, UnsubscribeAllResponses, UnsubscribeEmailData, UnsubscribeEmailError, UnsubscribeEmailErrors, UnsubscribeEmailResponse, UnsubscribeEmailResponses, UnsubscribeItemData, UnsubscribeItemError, UnsubscribeItemErrors, UnsubscribeItemPathParams, UnsubscribeItemResponse, UnsubscribeItemResponses, UserUnsubscribe } from './types.gen';
+export type { AgentSessionMentionedMetadata, AgentSessionNotificationRef, AgentSessionOriginParent, AgentSessionSettledMetadata, AgentSessionWaitingForInputMetadata, AiResponseMetadata, ApiUserNotification, BulkDeleteUserNotificationsV2Data, BulkDeleteUserNotificationsV2Error, BulkDeleteUserNotificationsV2Errors, BulkDeleteUserNotificationsV2Responses, BulkGetByEventItemIdsRequest, BulkGetTypedNotificationsByEventItemIdsData, BulkGetTypedNotificationsByEventItemIdsError, BulkGetTypedNotificationsByEventItemIdsErrors, BulkGetTypedNotificationsByEventItemIdsResponse, BulkGetTypedNotificationsByEventItemIdsResponses, BulkMarkNotificationsDoneData, BulkMarkNotificationsDoneError, BulkMarkNotificationsDoneErrors, BulkMarkNotificationsDoneResponses, BulkMarkNotificationsSeenData, BulkMarkNotificationsSeenError, BulkMarkNotificationsSeenErrors, BulkMarkNotificationsSeenResponses, BulkMarkNotificationsUndoneData, BulkMarkNotificationsUndoneError, BulkMarkNotificationsUndoneErrors, BulkMarkNotificationsUndoneResponses, CalendarEventReminderMetadata, CallStartedMetadata, ChannelInviteMetadata, ChannelMentionMetadata, ChannelMessageSendMetadata, ChannelReplyMetadata, ChannelType, ClientOptions, CommentedOnDocumentMetadata, CommentRef, CommonChannelMetadata, ConnGatewayNotificationPayload, CreateNotification, DeleteUserNotificationV2Data, DeleteUserNotificationV2Error, DeleteUserNotificationV2Errors, DeleteUserNotificationV2Responses, DeviceRequest, DeviceType, DisableNotificationTypeData, DisableNotificationTypeError, DisableNotificationTypeErrors, DisableNotificationTypeResponses, DocumentMentionMetadata, EmptyResponse, EnableNotificationTypeData, EnableNotificationTypeError, EnableNotificationTypeErrors, EnableNotificationTypeResponses, Entity, EntityType, ErrorResponse, GetAllUserNotificationsResponse, GetNotificationTypePreferencesData, GetNotificationTypePreferencesError, GetNotificationTypePreferencesErrors, GetNotificationTypePreferencesResponse, GetNotificationTypePreferencesResponse2, GetNotificationTypePreferencesResponses, GetTypedNotificationByIdData, GetTypedNotificationByIdError, GetTypedNotificationByIdErrors, GetTypedNotificationByIdResponse, GetTypedNotificationByIdResponses, GetTypedNotificationsByEventItemIdData, GetTypedNotificationsByEventItemIdError, GetTypedNotificationsByEventItemIdErrors, GetTypedNotificationsByEventItemIdResponse, GetTypedNotificationsByEventItemIdResponses, GetUnsubscribesData, GetUnsubscribesError, GetUnsubscribesErrors, GetUnsubscribesResponse, GetUnsubscribesResponses, GithubPrCheckRun, GithubPrCheckRunState, GithubPrComment, GithubPrCommentKind, GithubPrEventAction, GithubPrEventStatus, GithubPrMention, GithubPrMentionLocation, GithubPrNotificationCommon, GithubPrReview, GithubPrReviewState, GithubPrStatusChanged, GithubReviewRequested, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, InboxReauthRequiredMetadata, InviteToTeamMetadata, ItemSharedMetadata, ListTypedNotificationsData, ListTypedNotificationsError, ListTypedNotificationsErrors, ListTypedNotificationsResponse, ListTypedNotificationsResponses, MacroUserIdStr, MentionedInDocumentCommentMetadata, NewEmailMetadata, NotifEvent, NotificationBulkRequest, NotificationDocumentSubType, NotificationServiceApiVersion, NotificationState, NotificationTypeName, PushNotificationData, RealtimeNotifTaggedContentValue, ReminderMetadata, RemoveUnsubscribeAllData, RemoveUnsubscribeAllError, RemoveUnsubscribeAllErrors, RemoveUnsubscribeAllResponse, RemoveUnsubscribeAllResponses, RemoveUnsubscribeItemData, RemoveUnsubscribeItemError, RemoveUnsubscribeItemErrors, RemoveUnsubscribeItemResponse, RemoveUnsubscribeItemResponses, RepliedToDocumentCommentThreadMetadata, TaskAssignedMetadata, UnsubscribeAllData, UnsubscribeAllError, UnsubscribeAllErrors, UnsubscribeAllResponse, UnsubscribeAllResponses, UnsubscribeEmailData, UnsubscribeEmailError, UnsubscribeEmailErrors, UnsubscribeEmailResponse, UnsubscribeEmailResponses, UnsubscribeItemData, UnsubscribeItemError, UnsubscribeItemErrors, UnsubscribeItemPathParams, UnsubscribeItemResponse, UnsubscribeItemResponses, UserUnsubscribe } from './types.gen';
diff --git a/packages/sdk/generated/notification/types.gen.ts b/packages/sdk/generated/notification/types.gen.ts
index d1258176e0..d02b56cfad 100644
--- a/packages/sdk/generated/notification/types.gen.ts
+++ b/packages/sdk/generated/notification/types.gen.ts
@@ -19,9 +19,6 @@ export type AgentSessionMentionedMetadata = AgentSessionNotificationRef & {
};
/**
- * The session an agent-session notification is about, and where its magic
- * chip lives when it was opened from a thread.
- *
* Flattened into each agent-session kind so the wire keeps these keys at the
* top level of the metadata, the way [`CommonChannelMetadata`] does.
*/
@@ -42,9 +39,11 @@ export type AgentSessionNotificationRef = {
*/
botName: string;
/**
- * The channel the session was opened from, when it was.
+ * The channel the session was opened from, when it was opened from a
+ * channel thread.
*/
channelId?: string | null;
+ parent?: null | AgentSessionOriginParent;
/**
* The session; what a click opens.
*/
@@ -59,6 +58,25 @@ export type AgentSessionNotificationRef = {
threadId?: string | null;
};
+/**
+ * The session an agent-session notification is about, and where its magic
+ * chip lives when it was opened from a thread.
+ *
+ * The conversation an agent session was opened from: a channel or a
+ * document discussion. Spelled like the message API's parent so a client can
+ * route to either surface.
+ */
+export type AgentSessionOriginParent = {
+ /**
+ * The channel or document id.
+ */
+ id: string;
+ /**
+ * `channel` or `document`.
+ */
+ type: string;
+};
+
/**
* An agent finished a turn with nothing queued behind it.
*/
diff --git a/packages/sdk/generated/storage/types.gen.ts b/packages/sdk/generated/storage/types.gen.ts
index a1da34ad78..697726eca6 100644
--- a/packages/sdk/generated/storage/types.gen.ts
+++ b/packages/sdk/generated/storage/types.gen.ts
@@ -9794,17 +9794,22 @@ export type ThreadAnchor = {
};
/**
- * The channel thread a session was opened from, when it was.
+ * The thread a session was opened from, when it was.
*/
export type ThreadOrigin = {
/**
- * Channel the thread lives in.
+ * Channel the thread lives in, for channel parents only. Kept beside
+ * `parent` for consumers written when every origin was a channel.
*/
- channel_id: string;
+ channel_id?: string | null;
/**
* The message whose mention opened the session.
*/
originating_message_id: string;
+ /**
+ * Entity owning the thread: the channel or document it was posted in.
+ */
+ parent: MessageParent;
/**
* Root message of the thread.
*/
diff --git a/packages/sdk/specs/agent-harness.json b/packages/sdk/specs/agent-harness.json
index 87e7d3e5ed..8d16a0e071 100644
--- a/packages/sdk/specs/agent-harness.json
+++ b/packages/sdk/specs/agent-harness.json
@@ -1480,13 +1480,24 @@
"threadChannelId": {
"type": ["string", "null"],
"format": "uuid",
- "description": "The channel `thread_id` lives in, when the session was spawned from a\nthread."
+ "description": "The channel `thread_id` lives in, when the session was spawned from a\nchannel thread. Derived from `thread_parent`."
},
"threadId": {
"type": ["string", "null"],
"format": "uuid",
"description": "The root message of the thread the session was created from, if any."
},
+ "threadParent": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/MessageParent",
+ "description": "The channel or document `thread_id` lives in, when the session was\nspawned from a thread."
+ }
+ ]
+ },
"workspace": {
"type": "string",
"description": "The directory the session's harness runs in on its runtime."
@@ -1612,12 +1623,12 @@
"CreateSessionThread": {
"type": "object",
"description": "The triggering mention on a create request.\n\nClients serialize this, so both derives are used.",
- "required": ["channelId", "messageId"],
+ "required": ["messageId"],
"properties": {
"channelId": {
- "type": "string",
+ "type": ["string", "null"],
"format": "uuid",
- "description": "Channel the mentioning message was posted in."
+ "description": "Channel the mentioning message was posted in. Runtimes built before\nmessage parents send this instead of `parent`."
},
"content": {
"type": "string",
@@ -1628,6 +1639,17 @@
"format": "uuid",
"description": "The mentioning message."
},
+ "parent": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/MessageParent",
+ "description": "Entity the mentioning message was posted in."
+ }
+ ]
+ },
"threadId": {
"type": ["string", "null"],
"format": "uuid",
@@ -1635,6 +1657,10 @@
}
}
},
+ "DocumentId": {
+ "type": "string",
+ "description": "A validated document identifier. Historical document ids need not be UUIDs."
+ },
"EditQueuedActionRequest": {
"type": "object",
"description": "Request body for editing a queued prompt.",
@@ -1821,6 +1847,42 @@
}
}
},
+ "MessageParent": {
+ "oneOf": [
+ {
+ "type": "object",
+ "description": "A channel, including direct messages.",
+ "required": ["id", "type"],
+ "properties": {
+ "id": {
+ "type": "string",
+ "format": "uuid",
+ "description": "A channel, including direct messages."
+ },
+ "type": {
+ "type": "string",
+ "enum": ["channel"]
+ }
+ }
+ },
+ {
+ "type": "object",
+ "description": "A document, including tasks and PDFs.",
+ "required": ["id", "type"],
+ "properties": {
+ "id": {
+ "$ref": "#/components/schemas/DocumentId",
+ "description": "A document, including tasks and PDFs."
+ },
+ "type": {
+ "type": "string",
+ "enum": ["document"]
+ }
+ }
+ }
+ ],
+ "description": "The entity whose permissions and lifecycle govern a message."
+ },
"ModelHarnessDto": {
"type": "string",
"description": "Harness names accepted by the model discovery endpoint.",
diff --git a/packages/sdk/specs/notification.json b/packages/sdk/specs/notification.json
index e07be1f0ab..62040128af 100644
--- a/packages/sdk/specs/notification.json
+++ b/packages/sdk/specs/notification.json
@@ -1056,7 +1056,7 @@
},
"AgentSessionNotificationRef": {
"type": "object",
- "description": "The session an agent-session notification is about, and where its magic\nchip lives when it was opened from a thread.\n\nFlattened into each agent-session kind so the wire keeps these keys at the\ntop level of the metadata, the way [`CommonChannelMetadata`] does.",
+ "description": "Flattened into each agent-session kind so the wire keeps these keys at the\ntop level of the metadata, the way [`CommonChannelMetadata`] does.",
"required": ["sessionId", "sessionName", "botId", "botName"],
"properties": {
"announcementMessageId": {
@@ -1075,7 +1075,18 @@
"channelId": {
"type": ["string", "null"],
"format": "uuid",
- "description": "The channel the session was opened from, when it was."
+ "description": "The channel the session was opened from, when it was opened from a\nchannel thread."
+ },
+ "parent": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/AgentSessionOriginParent",
+ "description": "The channel or document the session was opened from, when it was."
+ }
+ ]
},
"sessionId": {
"type": "string",
@@ -1093,6 +1104,21 @@
}
}
},
+ "AgentSessionOriginParent": {
+ "type": "object",
+ "description": "The session an agent-session notification is about, and where its magic\nchip lives when it was opened from a thread.\n\nThe conversation an agent session was opened from: a channel or a\ndocument discussion. Spelled like the message API's parent so a client can\nroute to either surface.",
+ "required": ["type", "id"],
+ "properties": {
+ "id": {
+ "type": "string",
+ "description": "The channel or document id."
+ },
+ "type": {
+ "type": "string",
+ "description": "`channel` or `document`."
+ }
+ }
+ },
"AgentSessionSettledMetadata": {
"allOf": [
{
diff --git a/packages/sdk/specs/storage.json b/packages/sdk/specs/storage.json
index 2400f6d0ba..666555e87a 100644
--- a/packages/sdk/specs/storage.json
+++ b/packages/sdk/specs/storage.json
@@ -29589,19 +29589,23 @@
},
"ThreadOrigin": {
"type": "object",
- "description": "The channel thread a session was opened from, when it was.",
- "required": ["channel_id", "thread_id", "originating_message_id"],
+ "description": "The thread a session was opened from, when it was.",
+ "required": ["parent", "thread_id", "originating_message_id"],
"properties": {
"channel_id": {
- "type": "string",
+ "type": ["string", "null"],
"format": "uuid",
- "description": "Channel the thread lives in."
+ "description": "Channel the thread lives in, for channel parents only. Kept beside\n`parent` for consumers written when every origin was a channel."
},
"originating_message_id": {
"type": "string",
"format": "uuid",
"description": "The message whose mention opened the session."
},
+ "parent": {
+ "$ref": "#/components/schemas/MessageParent",
+ "description": "Entity owning the thread: the channel or document it was posted in."
+ },
"thread_id": {
"type": "string",
"format": "uuid",
diff --git a/packages/sdk/src/events/hydrate/agentSession.ts b/packages/sdk/src/events/hydrate/agentSession.ts
index e6f1d15779..66475fbc61 100644
--- a/packages/sdk/src/events/hydrate/agentSession.ts
+++ b/packages/sdk/src/events/hydrate/agentSession.ts
@@ -16,15 +16,20 @@ export type AgentSessionEvent = Extract<
{ event_type: `agent_session.${string}` }
>;
-/** The channel thread a session was opened from, when it was. */
+/**
+ * The channel thread a session was opened from, when it was. A session
+ * opened from a document discussion has an origin but no channel handles:
+ * the SDK's message entities are channel-scoped for now.
+ */
function originHandles(
client: MacroClient,
origin: ThreadOrigin | null | undefined,
) {
- return origin
+ const channelId = origin?.channel_id;
+ return origin && channelId
? {
- channel: Channel.byId(client, origin.channel_id),
- thread: new Thread(client, origin.channel_id, origin.thread_id),
+ channel: Channel.byId(client, channelId),
+ thread: new Thread(client, channelId, origin.thread_id),
}
: { channel: undefined, thread: undefined };
}
@@ -47,8 +52,9 @@ function announcementHandle(
identity: SessionIdentity,
announcementMessageId: string | null | undefined,
) {
- return identity.origin && announcementMessageId
- ? Message.byId(client, identity.origin.channel_id, announcementMessageId)
+ const channelId = identity.origin?.channel_id;
+ return channelId && announcementMessageId
+ ? Message.byId(client, channelId, announcementMessageId)
: undefined;
}
diff --git a/packages/sdk/tests/agent-session-hydrate.test.ts b/packages/sdk/tests/agent-session-hydrate.test.ts
index ed3895ea9e..93beb661b9 100644
--- a/packages/sdk/tests/agent-session-hydrate.test.ts
+++ b/packages/sdk/tests/agent-session-hydrate.test.ts
@@ -13,6 +13,10 @@ const identity = {
bot_name: 'Macro Coder',
owner_id: 'macro|[email protected]',
origin: {
+ parent: {
+ type: 'channel' as const,
+ id: '01a00000-0000-7000-8000-000000000001',
+ },
channel_id: '01a00000-0000-7000-8000-000000000001',
thread_id: '01a00000-0000-7000-8000-000000000002',
originating_message_id: '01a00000-0000-7000-8000-000000000003',
diff --git a/services/agent_harness_service/Cargo.toml b/services/agent_harness_service/Cargo.toml
index 3ad395d2e8..d6cdd05b18 100644
--- a/services/agent_harness_service/Cargo.toml
+++ b/services/agent_harness_service/Cargo.toml
@@ -55,7 +55,9 @@ macro_aws_config = { path = "../../crates/macro_aws_config" }
macro_event_broker = { path = "../../crates/macro_event_broker", features = ["outbound"] }
macro_queues = { path = "../../crates/macro_queues" }
lexical_client = { path = "../../crates/lexical_client" }
+lexical_mention_extractor = { path = "../../crates/lexical_mention_extractor" }
macro_service_urls = { path = "../../crates/macro_service_urls" }
+messages = { path = "../../crates/messages", features = ["broker", "delivery"] }
static_file_service_client = { path = "../../crates/static_file_service_client" }
macro_tower_layers = { path = "../../crates/macro_tower_layers" }
notification = { path = "../../crates/notification" }
diff --git a/services/agent_harness_service/src/config.rs b/services/agent_harness_service/src/config.rs
index 9102dffd5c..722592d990 100644
--- a/services/agent_harness_service/src/config.rs
+++ b/services/agent_harness_service/src/config.rs
@@ -64,6 +64,13 @@ pub struct Config {
pub codex_oauth_kms_key_id: CodexOauthKmsKeyId,
/// Comma-separated Kafka bootstrap servers.
pub kafka_brokers: KafkaBrokers,
+ /// Which committed-post topic feeds the in-process trigger: `messages`
+ /// (the default, channel and document posts) or `channels` (the
+ /// pre-parent channel event, kept until its producer retires it). Never
+ /// both: every channel post is on both topics, so both would evaluate
+ /// each mention twice.
+ #[macro_config_default(agent_trigger::domain::sources::TriggerEventSource::default())]
+ pub agent_trigger_event_source: agent_trigger::domain::sources::TriggerEventSource,
/// MacroDB connection string; `agent_sessions` lives here.
pub database_url: DatabaseUrl,
/// Shared Redis used for cross-replica command forwarding.
diff --git a/services/agent_harness_service/src/main.rs b/services/agent_harness_service/src/main.rs
index a95d101505..86abae3a5d 100644
--- a/services/agent_harness_service/src/main.rs
+++ b/services/agent_harness_service/src/main.rs
@@ -43,8 +43,8 @@ use agent_harness::domain::trigger_router::{
use agent_harness::inbound::model_load::AgentModelsRouterState;
use agent_harness::inbound::runtime_gateway::RuntimeGatewayState;
use agent_harness::outbound::agent_prompt_composer::LexicalAgentPromptComposer;
-use agent_harness::outbound::channel_announcer::ChannelAnnouncer;
-use agent_harness::outbound::channel_prompt_context::ChannelPromptContextAdapter;
+use agent_harness::outbound::channel_announcer::MessageAnnouncer;
+use agent_harness::outbound::channel_prompt_context::MessagePromptContextAdapter;
use agent_harness::outbound::containers::HarnessContainers;
use agent_harness::outbound::cursor::{CursorContainerManager, PgCursorApiKeys, PostgresJournal};
use agent_harness::outbound::daytona::{
@@ -82,7 +82,6 @@ use anyhow::Context as _;
use bot_id::BotId;
use bots::outbound::pg_bots_repo::PgBotsRepo;
use bots_directory::PgBotDirectory;
-use channels::domain::service::ChannelServiceImpl;
use channels::domain::side_effects::{ChannelSideEffectService, SpawnedChannelEventDispatcher};
use channels::outbound::connection_gateway_realtime::ConnectionGatewayChannelRealtimePublisher;
use channels::outbound::contacts_dispatcher::ContactsChannelDispatcher;
@@ -233,6 +232,20 @@ async fn run() -> anyhow::Result<()> {
// log and pushes each frame at the channel's participants so a viewer sees
// it happen.
let session_repo = PgAgentSessionRepo::new(pool.clone());
+ let entity_access = Arc::new(
+ entity_access::domain::service::EntityAccessServiceImpl::new(
+ entity_access::outbound::PgAccessRepository::new(pool.clone()),
+ ),
+ );
+ // Frames reach the owner plus whoever currently holds session access,
+ // which for a document-born session follows the document's own grants.
+ let session_audience = agent_session::domain::audience::AuthorizedSessionAudience::new(
+ session_repo.clone(),
+ (*entity_access).clone(),
+ agent_session::outbound::connection_gateway_realtime::ConnectionGatewaySessionSubscriptions(
+ connection_gateway.clone(),
+ ),
+ );
// One ownership identity for the whole process. Both attach-capable
// service instances below live here, so they share it.
let replica = ReplicaId::mint();
@@ -260,7 +273,7 @@ async fn run() -> anyhow::Result<()> {
FoldedMessageService::new(session_repo.clone()),
ConnectionGatewayAgentSessionRealtime::new(
connection_gateway.clone(),
- session_repo.clone(),
+ session_audience.clone(),
),
HaikuAgentSessionNameGenerator::new(ai_usage::pg_recorder(pool.clone())),
turn_observer.clone(),
@@ -462,7 +475,7 @@ async fn run() -> anyhow::Result<()> {
session_repo.clone(),
ConnectionGatewayAgentSessionRealtime::new(
connection_gateway.clone(),
- session_repo.clone(),
+ session_audience.clone(),
),
),
);
@@ -638,33 +651,74 @@ async fn run() -> anyhow::Result<()> {
macro_queues::ContactsQueue::new().to_string(),
),
});
+ // The same message service the storage API composes, so an announcement
+ // posted here fans out exactly like a post through the API: channel side
+ // effects for channel threads, document comment notifications for
+ // discussions, and the common realtime and broker facts for both.
let side_effects = ChannelSideEffectService::new(
PgChannelSideEffectContext::new(pool.clone()),
ConnectionGatewayChannelRealtimePublisher::new(connection_gateway.clone()),
NotificationChannelSender::new(Arc::clone(&notifications)),
ContactsChannelDispatcher::new(contacts_ingress),
)
- .with_macro_event_broker(broker);
- let channel_service = Arc::new(ChannelServiceImpl::with_dependencies(
- PgChannelsRepo::new(pool.clone()),
- SpawnedChannelEventDispatcher::new(side_effects),
- channels::domain::service::NoopChannelReferenceSharePermissions,
- ));
- let entity_access = Arc::new(
- entity_access::domain::service::EntityAccessServiceImpl::new(
- entity_access::outbound::PgAccessRepository::new(pool.clone()),
- ),
- );
+ .with_macro_event_broker(broker.clone());
let lexical = LexicalClient::new(
config.internal_api_key.clone(),
LexicalServiceUrl::new()?.to_string(),
);
- let announcer = ChannelAnnouncer::new(Arc::clone(&channel_service), lexical.clone());
+ let message_realtime = messages::outbound::connection_gateway::ConnectionGatewayMessages(
+ connection_gateway.clone(),
+ );
+ let message_delivery = messages::domain::delivery::ParentMessagePublisher::new(
+ channels::domain::message_delivery::ChannelMessageDelivery::new(
+ PgChannelsRepo::new(pool.clone()),
+ SpawnedChannelEventDispatcher::new(side_effects),
+ channels::domain::service::NoopChannelReferenceSharePermissions,
+ message_realtime.clone(),
+ ),
+ messages::domain::delivery::DiscussionDelivery::new(
+ messages::outbound::pg_discussion_context::PgDiscussionContext(pool.clone()),
+ messages::outbound::entity_access_audience::EntityAccessMessageAudience(
+ (*entity_access).clone(),
+ ),
+ message_realtime,
+ messages::outbound::notification_sender::MessageNotificationSender(Arc::clone(
+ &notifications,
+ )),
+ )
+ .with_sharing(messages::outbound::pg_discussion_context::PgDiscussionContext(pool.clone())),
+ );
+ let message_service: Arc<dyn messages::domain::api::MessageServiceApi> = Arc::new(
+ messages::domain::service::MessageService::new(
+ messages::outbound::pg_message_repo::PgMessageRepository::new(pool.clone()),
+ messages::domain::effects::MessageEffects::new(
+ messages::outbound::broker::BrokerMessagePublisher::new(broker),
+ messages::domain::ports::NoMessageEventPublisher,
+ message_delivery,
+ ),
+ )
+ .with_group_recipients(channels::domain::group_mentions::ChannelGroupRecipients(
+ PgChannelsRepo::new(pool.clone()),
+ ))
+ .with_mention_extractor(lexical_mention_extractor::LexicalMentionExtractor::new(
+ Arc::new(lexical.clone()),
+ ))
+ .with_references(
+ messages::outbound::entity_access_audience::EntityAccessMessageReferences(
+ (*entity_access).clone(),
+ ),
+ ),
+ );
+ let announcer = MessageAnnouncer::new(
+ message_service.clone(),
+ Arc::clone(&entity_access),
+ lexical.clone(),
+ );
let prompt_mentions =
LexicalPromptMentions::new(lexical.clone(), PgSessionAccess::new(pool.clone()));
let prompt_composer = LexicalAgentPromptComposer::new(lexical);
let prompt_context =
- ChannelPromptContextAdapter::new(channel_service, Arc::clone(&entity_access));
+ MessagePromptContextAdapter::new(message_service, Arc::clone(&entity_access));
// One connection per harness, shared by every session of every agent
// bound to it. Held here because the gateway puts dialed-in sockets into
@@ -824,12 +878,15 @@ async fn run() -> anyhow::Result<()> {
AgentSessionServiceImpl::new(
session_repo.clone(),
FoldedMessageService::new(session_repo.clone()),
- ConnectionGatewayAgentSessionRealtime::new(connection_gateway, session_repo.clone()),
+ ConnectionGatewayAgentSessionRealtime::new(connection_gateway, session_audience),
NoOpAgentSessionNameGenerator,
Arc::new(NoOpTurnObserver),
lifecycle_publisher,
ReplicaId::mint(),
- ),
+ )
+ .with_view_access(Arc::new(
+ agent_session::domain::audience::EntityAccessSessionView::new((*entity_access).clone()),
+ )),
entity_access.clone(),
MacroAuthorizationState::new(Arc::new(authorization_service.clone())),
);
@@ -907,6 +964,7 @@ async fn run() -> anyhow::Result<()> {
pool.clone(),
config.kafka_brokers.as_ref().to_owned(),
config.internal_api_key.clone(),
+ config.agent_trigger_event_source,
));
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 34402f7b06..dc058eb749 100644
--- a/services/agent_harness_service/src/trigger.rs
+++ b/services/agent_harness_service/src/trigger.rs
@@ -1,21 +1,25 @@
-//! Channel-message consumer that emits agent-session trigger events.
+//! Committed-post consumer that emits agent-session trigger events.
use agent_session::outbound::postgres::PgAgentSessionRepo;
-use agent_trigger::domain::processing::process_channel_event;
+use agent_trigger::domain::processing::process_message_event;
use agent_trigger::domain::service::AgentTriggerService;
+use agent_trigger::domain::sources::{
+ ChannelTriggerEvents, MessageTriggerEvents, TriggerEventSource, TriggerEvents,
+};
use agent_trigger::outbound::{
- BotRepoAgentLookup, ChannelThreadHistory, FastModelTriggerJudge, LexicalExplicitReplyExtractor,
+ BotRepoAgentLookup, ChannelRepoTypeLookup, FastModelTriggerJudge,
+ LexicalExplicitReplyExtractor, MessageThreadHistory,
};
use bots::outbound::pg_bots_repo::PgBotsRepo;
-use channels::domain::broker_events::ChannelMacroEvent;
use channels::outbound::pg_channels_repo::PgChannelsRepo;
use kafka_util::{GroupName, KafkaEventConsumer, consumer_span, record_span_error};
use lexical_client::LexicalClient;
use macro_event_broker::{
- KafkaConsumerAdapter, KafkaEventPublisher, MacroEvent as _, MacroEventBrokerService,
- MacroEventCollection as _, MacroEventConsumerService,
+ KafkaConsumerAdapter, KafkaEventPublisher, MacroEventBrokerService, MacroEventCollection,
+ MacroEventConsumerService,
};
use macro_service_urls::LexicalServiceUrl;
+use messages::outbound::pg_message_repo::PgMessageRepository;
use rdkafka::consumer::CommitMode;
use rdkafka::message::{BorrowedMessage, Message as _};
use sqlx::PgPool;
@@ -28,25 +32,49 @@ impl GroupName for AgentTriggerConsumerGroup {
const GROUP_NAME: &'static str = "agent-trigger-service";
}
-macro_event_broker::declare_topics!(DeclaredChannelEvent: ChannelMacroEvent);
+/// The concrete trigger service this binary composes.
+type Trigger = AgentTriggerService<
+ PgAgentSessionRepo,
+ BotRepoAgentLookup<PgBotsRepo>,
+ BotRepoAgentLookup<PgBotsRepo>,
+ BotRepoAgentLookup<PgBotsRepo>,
+ LexicalExplicitReplyExtractor,
+ FastModelTriggerJudge,
+ MessageThreadHistory<
+ entity_access::domain::service::EntityAccessServiceImpl<
+ entity_access::outbound::PgAccessRepository,
+ >,
+ >,
+>;
+type Publisher = MacroEventBrokerService<KafkaEventPublisher, macro_event_broker::GlobalSpawner>;
+type ChannelTypes = ChannelRepoTypeLookup<PgChannelsRepo>;
-type TriggerKafkaAdapter = KafkaConsumerAdapter<AgentTriggerConsumerGroup, DeclaredChannelEvent>;
-type TriggerConsumer = MacroEventConsumerService<DeclaredChannelEvent, TriggerKafkaAdapter>;
+type TriggerKafkaAdapter<M> = KafkaConsumerAdapter<AgentTriggerConsumerGroup, M>;
+type TriggerConsumer<M> = MacroEventConsumerService<M, TriggerKafkaAdapter<M>>;
-fn commit_message(consumer: &TriggerConsumer, message: &BorrowedMessage<'_>) -> anyhow::Result<()> {
+fn commit_message<M: MacroEventCollection + 'static>(
+ consumer: &TriggerConsumer<M>,
+ message: &BorrowedMessage<'_>,
+) -> anyhow::Result<()> {
consumer
.inner()
.commit_message(message, CommitMode::Sync)
- .map_err(|error| anyhow::anyhow!("failed to commit channel event offset: {error:?}"))
+ .map_err(|error| anyhow::anyhow!("failed to commit trigger event offset: {error:?}"))
}
-/// Keeps the channel trigger consumer running across transient failures.
-pub async fn supervise(pool: PgPool, kafka_brokers: String, internal_api_key: String) {
+/// Keeps the trigger consumer running across transient failures.
+pub async fn supervise(
+ pool: PgPool,
+ kafka_brokers: String,
+ internal_api_key: String,
+ source: TriggerEventSource,
+) {
loop {
if let Err(error) = run(
pool.clone(),
kafka_brokers.clone(),
internal_api_key.clone(),
+ source,
)
.await
{
@@ -56,7 +84,12 @@ pub async fn supervise(pool: PgPool, kafka_brokers: String, internal_api_key: St
}
}
-async fn run(pool: PgPool, kafka_brokers: String, internal_api_key: String) -> anyhow::Result<()> {
+async fn run(
+ pool: PgPool,
+ kafka_brokers: String,
+ internal_api_key: String,
+ source: TriggerEventSource,
+) -> anyhow::Result<()> {
let lexical = LexicalClient::new(internal_api_key, LexicalServiceUrl::new()?.to_string());
let trigger = AgentTriggerService::new(
PgAgentSessionRepo::new(pool.clone()),
@@ -65,20 +98,48 @@ async fn run(pool: PgPool, kafka_brokers: String, internal_api_key: String) -> a
BotRepoAgentLookup::new(PgBotsRepo::new(pool.clone())),
LexicalExplicitReplyExtractor::new(lexical),
FastModelTriggerJudge::new(ai_usage::pg_recorder(pool.clone())),
- ChannelThreadHistory::new(PgChannelsRepo::new(pool)),
+ MessageThreadHistory::new(
+ std::sync::Arc::new(messages::domain::service::MessageService::new(
+ PgMessageRepository::new(pool.clone()),
+ messages::domain::ports::NoMessageEventPublisher,
+ )),
+ entity_access::domain::service::EntityAccessServiceImpl::new(
+ entity_access::outbound::PgAccessRepository::new(pool.clone()),
+ ),
+ ),
);
+ let channel_types = ChannelRepoTypeLookup::new(PgChannelsRepo::new(pool));
let publisher = MacroEventBrokerService::new(
KafkaEventPublisher::new(&kafka_brokers)?,
macro_event_broker::GlobalSpawner,
);
let consumer = KafkaEventConsumer::<AgentTriggerConsumerGroup>::from_env(&kafka_brokers)?;
- let consumer = KafkaConsumerAdapter::<AgentTriggerConsumerGroup, ()>::new(consumer)
- .subscribe::<DeclaredChannelEvent>()
- .map_err(|error| anyhow::anyhow!("failed to subscribe to channel events: {error:?}"))?;
- let consumer = TriggerConsumer::new(consumer);
+ let consumer = KafkaConsumerAdapter::<AgentTriggerConsumerGroup, ()>::new(consumer);
+ match source {
+ TriggerEventSource::Messages => {
+ consume::<MessageTriggerEvents>(consumer, &trigger, &publisher, &channel_types).await
+ }
+ TriggerEventSource::Channels => {
+ consume::<ChannelTriggerEvents>(consumer, &trigger, &publisher, &channel_types).await
+ }
+ }
+}
+
+/// Read one trigger source until it fails, evaluating every committed post.
+async fn consume<Events: TriggerEvents>(
+ consumer: KafkaConsumerAdapter<AgentTriggerConsumerGroup, ()>,
+ trigger: &Trigger,
+ publisher: &Publisher,
+ channel_types: &ChannelTypes,
+) -> anyhow::Result<()> {
+ let consumer = consumer
+ .subscribe::<Events>()
+ .map_err(|error| anyhow::anyhow!("failed to subscribe to trigger events: {error:?}"))?;
+ let consumer = TriggerConsumer::<Events>::new(consumer);
tracing::info!(
- topics = ?DeclaredChannelEvent::topics(),
+ topics = ?Events::topics(),
+ source = ?Events::SOURCE,
group = AgentTriggerConsumerGroup::GROUP_NAME,
"agent trigger listening"
);
@@ -87,7 +148,7 @@ async fn run(pool: PgPool, kafka_brokers: String, internal_api_key: String) -> a
let message = match consumer.recv().await {
Ok(message) => message,
Err(error) => {
- tracing::error!(error = ?error, "failed to receive channel event");
+ tracing::error!(error = ?error, "failed to receive trigger event");
sleep(Duration::from_secs(1)).await;
continue;
}
@@ -95,26 +156,27 @@ async fn run(pool: PgPool, kafka_brokers: String, internal_api_key: String) -> a
let span = consumer_span(message.inner(), AgentTriggerConsumerGroup::GROUP_NAME);
let result = async {
let kafka_message = message.inner();
- let event = match message.decode_payload() {
- Ok(DeclaredChannelEvent::ChannelMacroEvent(event)) => event,
+ let decoded = match message.decode_payload() {
+ Ok(decoded) => decoded.into_trigger(),
Err(error) => {
record_span_error(&tracing::Span::current(), &error);
tracing::error!(
error = ?error,
partition = kafka_message.partition(),
offset = kafka_message.offset(),
- "dropping undecodable channel event"
+ "dropping undecodable trigger event"
);
commit_message(&consumer, kafka_message)?;
return Ok::<(), anyhow::Error>(());
}
};
- tracing::Span::current().record(
- "macro.event.id",
- tracing::field::display(event.event().event_id),
- );
+ tracing::Span::current()
+ .record("macro.event.id", tracing::field::display(decoded.event_id));
+ tracing::Span::current().record("macro.event.type", decoded.event_type);
- process_channel_event(&trigger, &publisher, &event).await?;
+ if let Some(posted) = &decoded.posted {
+ process_message_event(trigger, publisher, channel_types, posted).await?;
+ }
commit_message(&consumer, kafka_message)?;
Ok(())
}
diff --git a/services/agent_trigger_service/Cargo.toml b/services/agent_trigger_service/Cargo.toml
index 7bd7a8a6c3..92c694a9d4 100644
--- a/services/agent_trigger_service/Cargo.toml
+++ b/services/agent_trigger_service/Cargo.toml
@@ -16,6 +16,7 @@ anyhow = { workspace = true }
bots = { path = "../../crates/bots", default-features = false, features = ["outbound", "ports"] }
channels = { path = "../../crates/channels", default-features = false, features = ["outbound", "ports"] }
database_env_vars = { path = "../../crates/database_env_vars" }
+entity_access = { path = "../../crates/entity_access" }
kafka_util = { path = "../../crates/kafka_util" }
lexical_client = { path = "../../crates/lexical_client" }
macro_config = { path = "../../crates/macro_config" }
@@ -23,6 +24,7 @@ macro_entrypoint = { path = "../../crates/macro_entrypoint" }
macro_env_var = { path = "../../crates/macro_env_var" }
macro_event_broker = { path = "../../crates/macro_event_broker", features = ["outbound"] }
macro_service_urls = { path = "../../crates/macro_service_urls" }
+messages = { path = "../../crates/messages", features = ["broker", "outbound"] }
rdkafka = { workspace = true }
serde_json = { workspace = true }
sqlx = { workspace = true }
diff --git a/services/agent_trigger_service/src/config.rs b/services/agent_trigger_service/src/config.rs
index 7aaa4f7b16..9de1eeefed 100644
--- a/services/agent_trigger_service/src/config.rs
+++ b/services/agent_trigger_service/src/config.rs
@@ -1,5 +1,6 @@
//! Environment-backed service configuration.
+use agent_trigger::domain::sources::TriggerEventSource;
use anyhow::Context as _;
use database_env_vars::DatabaseUrl;
use macro_env_var::env_vars;
@@ -19,6 +20,12 @@ pub struct Config {
pub kafka_brokers: KafkaBrokers,
/// Key for internal service-to-service calls (the lexical service).
pub internal_api_key: String,
+ /// Which committed-post topic feeds the trigger: `messages` (the default,
+ /// channel and document posts) or `channels` (the pre-parent channel
+ /// event, kept until its producer retires it). Never both: every channel
+ /// post is on both topics, so both would evaluate each mention twice.
+ #[macro_config_default(TriggerEventSource::default())]
+ pub agent_trigger_event_source: TriggerEventSource,
}
impl Config {
diff --git a/services/agent_trigger_service/src/main.rs b/services/agent_trigger_service/src/main.rs
index eb04667516..ffd2eced65 100644
--- a/services/agent_trigger_service/src/main.rs
+++ b/services/agent_trigger_service/src/main.rs
@@ -1,26 +1,32 @@
-//! Kafka worker that turns posted channel messages into agent-session events.
+//! Kafka worker that turns committed posts into agent-session events.
+
+// The consumer loop is generic over the trigger source, and the select! it
+// awaits in nests the concrete service types past the default query depth.
+#![recursion_limit = "256"]
mod config;
use agent_session::outbound::postgres::PgAgentSessionRepo;
-use agent_trigger::domain::processing::process_channel_event;
+use agent_trigger::domain::processing::process_message_event;
use agent_trigger::domain::service::AgentTriggerService;
+use agent_trigger::domain::sources::{ChannelTriggerEvents, MessageTriggerEvents, TriggerEvents};
use agent_trigger::outbound::{
- BotRepoAgentLookup, ChannelThreadHistory, FastModelTriggerJudge, LexicalExplicitReplyExtractor,
+ BotRepoAgentLookup, ChannelRepoTypeLookup, FastModelTriggerJudge,
+ LexicalExplicitReplyExtractor, MessageThreadHistory,
};
use anyhow::Context as _;
use bots::outbound::pg_bots_repo::PgBotsRepo;
-use channels::domain::broker_events::ChannelMacroEvent;
use channels::outbound::pg_channels_repo::PgChannelsRepo;
use config::Config;
use kafka_util::{GroupName, KafkaEventConsumer, consumer_span, record_span_error};
use lexical_client::LexicalClient;
use macro_entrypoint::{MacroEntrypoint, shutdown_signal};
use macro_event_broker::{
- KafkaConsumerAdapter, KafkaEventPublisher, MacroEvent as _, MacroEventBrokerService,
- MacroEventCollection as _, MacroEventConsumerService,
+ KafkaConsumerAdapter, KafkaEventPublisher, MacroEventBrokerService, MacroEventCollection,
+ MacroEventConsumerService,
};
use macro_service_urls::LexicalServiceUrl;
+use messages::outbound::pg_message_repo::PgMessageRepository;
use rdkafka::consumer::CommitMode;
use rdkafka::message::{BorrowedMessage, Message as _};
use sqlx::postgres::PgPoolOptions;
@@ -32,16 +38,34 @@ impl GroupName for AgentTriggerConsumerGroup {
const GROUP_NAME: &'static str = "agent-trigger-service";
}
-macro_event_broker::declare_topics!(DeclaredMacroEvent: ChannelMacroEvent);
+/// The concrete trigger service this binary composes.
+type Trigger = AgentTriggerService<
+ PgAgentSessionRepo,
+ BotRepoAgentLookup<PgBotsRepo>,
+ BotRepoAgentLookup<PgBotsRepo>,
+ BotRepoAgentLookup<PgBotsRepo>,
+ LexicalExplicitReplyExtractor,
+ FastModelTriggerJudge,
+ MessageThreadHistory<
+ entity_access::domain::service::EntityAccessServiceImpl<
+ entity_access::outbound::PgAccessRepository,
+ >,
+ >,
+>;
+type Publisher = MacroEventBrokerService<KafkaEventPublisher, macro_event_broker::GlobalSpawner>;
+type ChannelTypes = ChannelRepoTypeLookup<PgChannelsRepo>;
-type TriggerKafkaAdapter = KafkaConsumerAdapter<AgentTriggerConsumerGroup, DeclaredMacroEvent>;
-type TriggerConsumer = MacroEventConsumerService<DeclaredMacroEvent, TriggerKafkaAdapter>;
+type TriggerKafkaAdapter<M> = KafkaConsumerAdapter<AgentTriggerConsumerGroup, M>;
+type TriggerConsumer<M> = MacroEventConsumerService<M, TriggerKafkaAdapter<M>>;
-fn commit_message(consumer: &TriggerConsumer, message: &BorrowedMessage<'_>) -> anyhow::Result<()> {
+fn commit_message<M: MacroEventCollection + 'static>(
+ consumer: &TriggerConsumer<M>,
+ message: &BorrowedMessage<'_>,
+) -> anyhow::Result<()> {
consumer
.inner()
.commit_message(message, CommitMode::Sync)
- .map_err(|error| anyhow::anyhow!("failed to commit channel event offset: {error:?}"))
+ .map_err(|error| anyhow::anyhow!("failed to commit trigger event offset: {error:?}"))
}
#[tokio::main]
@@ -72,21 +96,50 @@ async fn run() -> anyhow::Result<()> {
BotRepoAgentLookup::new(PgBotsRepo::new(pool.clone())),
LexicalExplicitReplyExtractor::new(lexical),
FastModelTriggerJudge::new(ai_usage::pg_recorder(pool.clone())),
- ChannelThreadHistory::new(PgChannelsRepo::new(pool)),
+ MessageThreadHistory::new(
+ std::sync::Arc::new(messages::domain::service::MessageService::new(
+ PgMessageRepository::new(pool.clone()),
+ messages::domain::ports::NoMessageEventPublisher,
+ )),
+ entity_access::domain::service::EntityAccessServiceImpl::new(
+ entity_access::outbound::PgAccessRepository::new(pool.clone()),
+ ),
+ ),
);
+ let channel_types = ChannelRepoTypeLookup::new(PgChannelsRepo::new(pool));
let publisher = MacroEventBrokerService::new(
KafkaEventPublisher::new(config.kafka_brokers.as_ref())?,
macro_event_broker::GlobalSpawner,
);
let consumer =
KafkaEventConsumer::<AgentTriggerConsumerGroup>::from_env(config.kafka_brokers.as_ref())?;
- let consumer = KafkaConsumerAdapter::<AgentTriggerConsumerGroup, ()>::new(consumer)
- .subscribe::<DeclaredMacroEvent>()
- .map_err(|error| anyhow::anyhow!("failed to subscribe to channel events: {error:?}"))?;
- let consumer = TriggerConsumer::new(consumer);
+ let consumer = KafkaConsumerAdapter::<AgentTriggerConsumerGroup, ()>::new(consumer);
+
+ match config.agent_trigger_event_source {
+ agent_trigger::domain::sources::TriggerEventSource::Messages => {
+ consume::<MessageTriggerEvents>(consumer, &trigger, &publisher, &channel_types).await
+ }
+ agent_trigger::domain::sources::TriggerEventSource::Channels => {
+ consume::<ChannelTriggerEvents>(consumer, &trigger, &publisher, &channel_types).await
+ }
+ }
+}
+
+/// Read one trigger source until shutdown, evaluating every committed post.
+async fn consume<Events: TriggerEvents>(
+ consumer: KafkaConsumerAdapter<AgentTriggerConsumerGroup, ()>,
+ trigger: &Trigger,
+ publisher: &Publisher,
+ channel_types: &ChannelTypes,
+) -> anyhow::Result<()> {
+ let consumer = consumer
+ .subscribe::<Events>()
+ .map_err(|error| anyhow::anyhow!("failed to subscribe to trigger events: {error:?}"))?;
+ let consumer = TriggerConsumer::<Events>::new(consumer);
tracing::info!(
- topics = ?DeclaredMacroEvent::topics(),
+ topics = ?Events::topics(),
+ source = ?Events::SOURCE,
group = AgentTriggerConsumerGroup::GROUP_NAME,
"agent trigger service listening"
);
@@ -103,30 +156,33 @@ async fn run() -> anyhow::Result<()> {
let message = match result {
Ok(message) => message,
Err(error) => {
- tracing::error!(error = ?error, "failed to receive channel event");
+ tracing::error!(error = ?error, "failed to receive trigger event");
continue;
}
};
let span = consumer_span(message.inner(), AgentTriggerConsumerGroup::GROUP_NAME);
let result = async {
let kafka_message = message.inner();
- let event = match message.decode_payload() {
- Ok(DeclaredMacroEvent::ChannelMacroEvent(event)) => event,
+ let decoded = match message.decode_payload() {
+ Ok(decoded) => decoded.into_trigger(),
Err(error) => {
record_span_error(&tracing::Span::current(), &error);
tracing::error!(
error = ?error,
partition = kafka_message.partition(),
offset = kafka_message.offset(),
- "dropping undecodable channel event"
+ "dropping undecodable trigger event"
);
commit_message(&consumer, kafka_message)?;
return Ok::<(), anyhow::Error>(());
}
};
- tracing::Span::current().record("macro.event.id", tracing::field::display(event.event().event_id));
+ tracing::Span::current().record("macro.event.id", tracing::field::display(decoded.event_id));
+ tracing::Span::current().record("macro.event.type", decoded.event_type);
- process_channel_event(&trigger, &publisher, &event).await?;
+ if let Some(posted) = &decoded.posted {
+ process_message_event(trigger, publisher, channel_types, posted).await?;
+ }
commit_message(&consumer, kafka_message)?;
Ok(())
}
diff --git a/services/document_storage_service/src/main.rs b/services/document_storage_service/src/main.rs
index 091609720d..426a269a84 100644
--- a/services/document_storage_service/src/main.rs
+++ b/services/document_storage_service/src/main.rs
@@ -957,6 +957,9 @@ async fn run() -> anyhow::Result<()> {
Arc::new(PgTaskMatchRepo::new(db.clone())),
));
let channels_repo = PgChannelsRepo::new(db.clone());
+ // Built-in agents read the same committed-post stream as hosted and
+ // external agents, for channel and document posts alike, so the channel
+ // side effects no longer carry their own trigger queue.
let (bot_trigger_sender, bot_trigger_receiver) = tokio::sync::mpsc::unbounded_channel();
let channel_side_effects = ChannelSideEffectService::new(
@@ -965,7 +968,6 @@ async fn run() -> anyhow::Result<()> {
NotificationChannelSender::new(notification_ingress_service.clone()),
ContactsChannelDispatcher::new(contacts_ingress.clone()),
)
- .with_bot_trigger_sender(bot_trigger_sender)
.with_macro_event_broker(macro_event_broker.clone());
let channels_service = Arc::new(
@@ -1018,7 +1020,7 @@ async fn run() -> anyhow::Result<()> {
messages::outbound::pg_message_repo::PgMessageRepository::new(db.clone()),
messages::domain::effects::MessageEffects::new(
messages::outbound::broker::BrokerMessagePublisher::new(macro_event_broker.clone()),
- messages::domain::ports::NoMessageEventPublisher,
+ channel_bots::outbound::conversation::LocalBotPublisher::new(bot_trigger_sender),
messages::domain::delivery::ParentMessagePublisher::new(
channel_delivery,
discussion_delivery,
@@ -1112,21 +1114,22 @@ async fn run() -> anyhow::Result<()> {
message_commands.clone(),
);
let macro_agent_tools = ai_tools::tools_for(ai_tools::AiHost::ChannelBot);
- let bot_trigger_router = channel_bots::inbound::BotTriggerRouter::new(
- channels_service.clone(),
- message_commands.clone(),
- Arc::new(
- channel_bots::outbound::conversation::EntityAccessConversation(
- entity_access_service.clone(),
- ),
+ let conversation_access = Arc::new(
+ channel_bots::outbound::conversation::EntityAccessConversation(
+ entity_access_service.clone(),
),
+ );
+ let bot_trigger_router = channel_bots::inbound::BotTriggerRouter::new(
+ message_service.clone(),
+ conversation_access.clone(),
Arc::new(channel_bots::outbound::AgentLoopResponder::new(
macro_agent_tool_context,
macro_agent_tools,
)),
Arc::new(
channel_bots::domain::trigger_detector::MentionOrInferredDetector::new(
- channels_service.clone(),
+ message_service.clone(),
+ conversation_access,
Arc::new(channel_bots::outbound::FastModelTriggerClassifier::new(
ai_usage::pg_recorder(db.clone()),
)),
diff --git a/services/lexical-service/src/endpoints/agent-announcement.ts b/services/lexical-service/src/endpoints/agent-announcement.ts
index 5f3177de29..180802ff94 100644
--- a/services/lexical-service/src/endpoints/agent-announcement.ts
+++ b/services/lexical-service/src/endpoints/agent-announcement.ts
@@ -1,71 +1,95 @@
import {
- MAGIC_CHIP_AUTHORS,
- MAGIC_CHIP_STATUSES,
-} from "@macro-inc/lexical-core/nodes/MagicChipNode";
-import { composeAgentSessionAnnouncement } from "@macro-inc/lexical-core/utils/agent-announcement";
-import { OpenAPIRoute } from "chanfana";
-import type { Context } from "hono";
-import { z } from "zod";
-import { handleEndpointError } from "../lib/error-handler";
-import { standardErrorResponses } from "../lib/schemas";
+ MAGIC_CHIP_AUTHORS,
+ MAGIC_CHIP_STATUSES,
+} from '@macro-inc/lexical-core/nodes/MagicChipNode';
+import { composeAgentSessionAnnouncement } from '@macro-inc/lexical-core/utils/agent-announcement';
+import { OpenAPIRoute } from 'chanfana';
+import type { Context } from 'hono';
+import { z } from 'zod';
+import { handleEndpointError } from '../lib/error-handler';
+import { standardErrorResponses } from '../lib/schemas';
+
+const messageParent = z.object({
+ type: z.enum(['channel', 'document']),
+ id: z.string().min(1),
+});
+
+const replyTargetRequest = z
+ .object({
+ parent: messageParent.optional(),
+ channelId: z.string().optional(),
+ targetMessageId: z.string(),
+ targetThreadId: z.string(),
+ displayText: z.string(),
+ senderId: z.string(),
+ })
+ .refine(
+ (target) => target.parent !== undefined || target.channelId !== undefined,
+ {
+ message: 'replyTarget needs a parent or a channelId',
+ }
+ );
const agentAnnouncementRequest = z.object({
- replyTarget: z.object({
- channelId: z.string(),
- targetMessageId: z.string(),
- targetThreadId: z.string(),
- displayText: z.string(),
- senderId: z.string(),
- }),
- chip: z.object({
- agentSessionId: z.string(),
- channelId: z.string().optional(),
- promptedMessage: z.object({
- turn: z.number().int().nonnegative(),
- author: z.enum(MAGIC_CHIP_AUTHORS),
- }),
- status: z.enum(MAGIC_CHIP_STATUSES),
- }),
+ replyTarget: replyTargetRequest,
+ chip: z.object({
+ agentSessionId: z.string(),
+ channelId: z.string().optional(),
+ promptedMessage: z.object({
+ turn: z.number().int().nonnegative(),
+ author: z.enum(MAGIC_CHIP_AUTHORS),
+ }),
+ status: z.enum(MAGIC_CHIP_STATUSES),
+ }),
});
const agentAnnouncementResponse = z.object({
- markdown: z.string(),
+ markdown: z.string(),
});
export class AgentAnnouncementEndpoint extends OpenAPIRoute {
- schema = {
- summary: "Compose an agent-harness bot response",
- description:
- "Builds an agent-harness announcement from a structured reply target and magic chip.",
- request: {
- body: {
- content: {
- "application/json": {
- schema: agentAnnouncementRequest,
- },
- },
- },
- },
- responses: {
- 200: {
- description: "Successfully composed the announcement markdown",
- content: {
- "application/json": {
- schema: agentAnnouncementResponse,
- },
- },
- },
- ...standardErrorResponses,
- },
- };
+ schema = {
+ summary: 'Compose an agent-harness bot response',
+ description:
+ 'Builds an agent-harness announcement from a structured reply target and magic chip.',
+ request: {
+ body: {
+ content: {
+ 'application/json': {
+ schema: agentAnnouncementRequest,
+ },
+ },
+ },
+ },
+ responses: {
+ 200: {
+ description: 'Successfully composed the announcement markdown',
+ content: {
+ 'application/json': {
+ schema: agentAnnouncementResponse,
+ },
+ },
+ },
+ ...standardErrorResponses,
+ },
+ };
- async handle(c: Context) {
- try {
- const { body } = await this.getValidatedData<typeof this.schema>();
- const markdown = composeAgentSessionAnnouncement(body);
- return c.json({ markdown });
- } catch (error) {
- return handleEndpointError(error, c);
- }
- }
+ async handle(c: Context) {
+ try {
+ const { body } = await this.getValidatedData<typeof this.schema>();
+ const { parent, channelId, ...target } = body.replyTarget;
+ // The reply-target node still references channels only; a document
+ // discussion announces with the chip alone until the node learns
+ // message parents.
+ const channel =
+ channelId ?? (parent?.type === 'channel' ? parent.id : undefined);
+ const markdown = composeAgentSessionAnnouncement({
+ replyTarget: channel ? { ...target, channelId: channel } : undefined,
+ chip: body.chip,
+ });
+ return c.json({ markdown });
+ } catch (error) {
+ return handleEndpointError(error, c);
+ }
+ }
}
diff --git a/services/lexical-service/src/endpoints/agent-context.ts b/services/lexical-service/src/endpoints/agent-context.ts
index d6d7d3240e..b62901556e 100644
--- a/services/lexical-service/src/endpoints/agent-context.ts
+++ b/services/lexical-service/src/endpoints/agent-context.ts
@@ -1,60 +1,66 @@
-import { composeAgentContextPrompt } from "@macro-inc/lexical-core/utils/agent-context";
-import { OpenAPIRoute } from "chanfana";
-import type { Context } from "hono";
-import { z } from "zod";
-import { handleEndpointError } from "../lib/error-handler";
-import { standardErrorResponses } from "../lib/schemas";
+import { composeAgentContextPrompt } from '@macro-inc/lexical-core/utils/agent-context';
+import { OpenAPIRoute } from 'chanfana';
+import type { Context } from 'hono';
+import { z } from 'zod';
+import { handleEndpointError } from '../lib/error-handler';
+import { standardErrorResponses } from '../lib/schemas';
+
+const messageParent = z.object({
+ type: z.enum(['channel', 'document']),
+ id: z.string().min(1),
+});
const agentContextRequest = z.object({
- promptMarkdown: z.string(),
- messages: z
- .array(
- z.object({
- sender: z.string(),
- content: z.string(),
- }),
- )
- .optional(),
+ promptMarkdown: z.string(),
+ parent: messageParent.optional(),
+ messages: z
+ .array(
+ z.object({
+ sender: z.string(),
+ content: z.string(),
+ })
+ )
+ .optional(),
});
const agentContextResponse = z.object({
- markdown: z.string(),
+ markdown: z.string(),
});
export class AgentContextEndpoint extends OpenAPIRoute {
- schema = {
- summary: "Compose an agent prompt with channel context",
- description:
- "Builds internal markdown containing optional untrusted prior channel messages and the user prompt.",
- request: {
- body: {
- content: {
- "application/json": {
- schema: agentContextRequest,
- },
- },
- },
- },
- responses: {
- 200: {
- description: "Successfully composed the agent context markdown",
- content: {
- "application/json": {
- schema: agentContextResponse,
- },
- },
- },
- ...standardErrorResponses,
- },
- };
+ schema = {
+ summary: 'Compose an agent prompt with conversation context',
+ description:
+ 'Builds internal markdown containing the conversation parent, optional untrusted prior messages, and the user prompt.',
+ request: {
+ body: {
+ content: {
+ 'application/json': {
+ schema: agentContextRequest,
+ },
+ },
+ },
+ },
+ responses: {
+ 200: {
+ description: 'Successfully composed the agent context markdown',
+ content: {
+ 'application/json': {
+ schema: agentContextResponse,
+ },
+ },
+ },
+ ...standardErrorResponses,
+ },
+ };
- async handle(c: Context) {
- try {
- const { body } = await this.getValidatedData<typeof this.schema>();
- const markdown = composeAgentContextPrompt(body);
- return c.json({ markdown });
- } catch (error) {
- return handleEndpointError(error, c);
- }
- }
+ async handle(c: Context) {
+ try {
+ const { body } = await this.getValidatedData<typeof this.schema>();
+ const markdown = composeAgentContextPrompt(body);
+ return c.json({ markdown });
+ } catch (error) {
+ return handleEndpointError(error, c);
+ }
+ }
}