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): structured trigger context for agent prompts (#7803)

Wolf Mermelstein52f0bc2596ce
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.json
index 3bf7e1f83e..a67b7d8be6 100644
--- a/.github/workspace-dep-closures.json
+++ b/.github/workspace-dep-closures.json
@@ -148,6 +148,7 @@
"crates/static_file_service_client",
"crates/system_properties",
"crates/teams",
+ "crates/trigger_context",
"crates/unfurl",
"crates/workspace-hack"
],
@@ -277,6 +278,7 @@
"crates/system_skills",
"crates/task_dedup",
"crates/teams",
+ "crates/trigger_context",
"crates/unfurl",
"crates/user_quota",
"crates/workspace-hack"
@@ -424,6 +426,7 @@
"crates/system_skills",
"crates/task_dedup",
"crates/teams",
+ "crates/trigger_context",
"crates/unfurl",
"crates/user_quota",
"crates/workspace-hack"
@@ -601,6 +604,7 @@
"crates/system_skills",
"crates/task_dedup",
"crates/teams",
+ "crates/trigger_context",
"crates/unfurl",
"crates/user_quota",
"crates/workspace-hack",
@@ -767,6 +771,7 @@
"crates/system_skills",
"crates/task_dedup",
"crates/teams",
+ "crates/trigger_context",
"crates/unfurl",
"crates/user_quota",
"crates/workspace-hack"
@@ -913,6 +918,7 @@
"crates/static_file_service_client",
"crates/system_properties",
"crates/teams",
+ "crates/trigger_context",
"crates/unfurl",
"crates/workspace-hack"
],
@@ -1016,6 +1022,7 @@
"crates/static_file_service_client",
"crates/system_properties",
"crates/teams",
+ "crates/trigger_context",
"crates/unfurl",
"crates/workspace-hack"
],
@@ -1121,6 +1128,7 @@
"crates/static_file_service_client",
"crates/system_properties",
"crates/teams",
+ "crates/trigger_context",
"crates/unfurl",
"crates/workspace-hack"
],
@@ -1228,6 +1236,7 @@
"crates/static_file_service_client",
"crates/system_properties",
"crates/teams",
+ "crates/trigger_context",
"crates/unfurl",
"crates/workspace-hack",
"services/agent_trigger_service"
@@ -1327,6 +1336,7 @@
"crates/static_file_service_client",
"crates/system_properties",
"crates/teams",
+ "crates/trigger_context",
"crates/unfurl",
"crates/workspace-hack"
],
@@ -1490,6 +1500,7 @@
"crates/system_skills",
"crates/task_dedup",
"crates/teams",
+ "crates/trigger_context",
"crates/unfurl",
"crates/user_quota",
"crates/workspace-hack"
@@ -1586,6 +1597,7 @@
"crates/sqs_worker",
"crates/static_file_service_client",
"crates/system_properties",
+ "crates/trigger_context",
"crates/unfurl",
"crates/workspace-hack",
"services/ai_projections_refresh_handler"
@@ -1745,6 +1757,7 @@
"crates/system_skills",
"crates/task_dedup",
"crates/teams",
+ "crates/trigger_context",
"crates/unfurl",
"crates/user_quota",
"crates/workspace-hack"
@@ -1875,6 +1888,7 @@
"crates/static_file_service_client",
"crates/system_properties",
"crates/teams",
+ "crates/trigger_context",
"crates/unfurl",
"crates/workspace-hack"
],
@@ -2039,6 +2053,7 @@
"crates/system_skills",
"crates/task_dedup",
"crates/teams",
+ "crates/trigger_context",
"crates/unfurl",
"crates/user_quota",
"crates/workspace-hack",
@@ -2292,6 +2307,7 @@
"crates/static_file_service_client",
"crates/system_properties",
"crates/teams",
+ "crates/trigger_context",
"crates/unfurl",
"crates/workspace-hack"
],
@@ -2433,6 +2449,7 @@
"crates/static_file_service_client",
"crates/system_properties",
"crates/teams",
+ "crates/trigger_context",
"crates/unfurl",
"crates/workspace-hack"
],
@@ -2538,6 +2555,7 @@
"crates/static_file_service_client",
"crates/system_properties",
"crates/teams",
+ "crates/trigger_context",
"crates/unfurl",
"crates/workspace-hack",
"services/calendar_service"
@@ -2779,6 +2797,7 @@
"crates/system_skills",
"crates/task_dedup",
"crates/teams",
+ "crates/trigger_context",
"crates/unfurl",
"crates/user_quota",
"crates/workspace-hack"
@@ -3078,6 +3097,7 @@
"crates/static_file_service_client",
"crates/system_properties",
"crates/teams",
+ "crates/trigger_context",
"crates/unfurl",
"crates/workspace-hack"
],
@@ -3182,6 +3202,7 @@
"crates/static_file_service_client",
"crates/system_properties",
"crates/teams",
+ "crates/trigger_context",
"crates/unfurl",
"crates/workspace-hack"
],
@@ -3322,6 +3343,7 @@
"crates/system_skills",
"crates/task_dedup",
"crates/teams",
+ "crates/trigger_context",
"crates/unfurl",
"crates/user_quota",
"crates/webhook",
@@ -3400,6 +3422,7 @@
"crates/sync_service",
"crates/sync_service_client",
"crates/system_properties",
+ "crates/trigger_context",
"crates/user_quota",
"crates/workspace-hack"
],
@@ -3628,6 +3651,7 @@
"crates/system_skills",
"crates/task_dedup",
"crates/teams",
+ "crates/trigger_context",
"crates/unfurl",
"crates/user_quota",
"crates/work_feed",
@@ -3904,6 +3928,7 @@
"crates/sqs_worker",
"crates/static_file_service_client",
"crates/system_properties",
+ "crates/trigger_context",
"crates/unfurl",
"crates/user_quota",
"crates/workspace-hack",
@@ -4095,6 +4120,7 @@
"crates/static_file_service_client",
"crates/system_properties",
"crates/teams",
+ "crates/trigger_context",
"crates/unfurl",
"crates/workspace-hack"
],
@@ -4292,6 +4318,7 @@
"crates/static_file_service_client",
"crates/system_properties",
"crates/teams",
+ "crates/trigger_context",
"crates/unfurl",
"crates/workspace-hack"
],
@@ -4467,6 +4494,7 @@
"crates/system_skills",
"crates/task_dedup",
"crates/teams",
+ "crates/trigger_context",
"crates/unfurl",
"crates/user_quota",
"crates/workspace-hack",
@@ -4658,6 +4686,7 @@
"crates/system_skills",
"crates/task_dedup",
"crates/teams",
+ "crates/trigger_context",
"crates/unfurl",
"crates/user_quota",
"crates/workspace-hack",
@@ -4863,6 +4892,7 @@
"crates/system_skills",
"crates/task_dedup",
"crates/teams",
+ "crates/trigger_context",
"crates/unfurl",
"crates/user_api_key",
"crates/user_quota",
@@ -5066,6 +5096,7 @@
"crates/system_skills",
"crates/task_dedup",
"crates/teams",
+ "crates/trigger_context",
"crates/unfurl",
"crates/user_quota",
"crates/workspace-hack",
@@ -5189,6 +5220,7 @@
"crates/system_skills",
"crates/task_dedup",
"crates/teams",
+ "crates/trigger_context",
"crates/unfurl",
"crates/user_quota",
"crates/workspace-hack"
@@ -5297,6 +5329,7 @@
"crates/sqs_worker",
"crates/static_file_service_client",
"crates/system_properties",
+ "crates/trigger_context",
"crates/unfurl",
"crates/user_quota",
"crates/workspace-hack",
@@ -5399,6 +5432,7 @@
"crates/sqs_worker",
"crates/static_file_service_client",
"crates/system_properties",
+ "crates/trigger_context",
"crates/unfurl",
"crates/workspace-hack"
],
@@ -5550,6 +5584,7 @@
"crates/sqs_worker",
"crates/static_file_service_client",
"crates/system_properties",
+ "crates/trigger_context",
"crates/unfurl",
"crates/workspace-hack",
"services/email_refresh_handler"
@@ -5644,6 +5679,7 @@
"crates/sqs_worker",
"crates/static_file_service_client",
"crates/system_properties",
+ "crates/trigger_context",
"crates/unfurl",
"crates/workspace-hack",
"services/email_scheduled_handler"
@@ -5755,6 +5791,7 @@
"crates/sqs_worker",
"crates/static_file_service_client",
"crates/system_properties",
+ "crates/trigger_context",
"crates/unfurl",
"crates/user_quota",
"crates/workspace-hack",
@@ -5847,6 +5884,7 @@
"crates/sqs_worker",
"crates/static_file_service_client",
"crates/system_properties",
+ "crates/trigger_context",
"crates/unfurl",
"crates/workspace-hack"
],
@@ -5940,6 +5978,7 @@
"crates/sqs_worker",
"crates/static_file_service_client",
"crates/system_properties",
+ "crates/trigger_context",
"crates/unfurl",
"crates/workspace-hack",
"services/email_sfs_delete_handler"
@@ -6366,6 +6405,7 @@
"crates/sync_service_client",
"crates/system_properties",
"crates/teams",
+ "crates/trigger_context",
"crates/unfurl",
"crates/user_quota",
"crates/workspace-hack"
@@ -6522,6 +6562,7 @@
"crates/system_skills",
"crates/task_dedup",
"crates/teams",
+ "crates/trigger_context",
"crates/unfurl",
"crates/user_quota",
"crates/workspace-hack"
@@ -6893,6 +6934,7 @@
"crates/sqs_worker",
"crates/static_file_service_client",
"crates/system_properties",
+ "crates/trigger_context",
"crates/unfurl",
"crates/workspace-hack"
],
@@ -7035,6 +7077,7 @@
"crates/system_skills",
"crates/task_dedup",
"crates/teams",
+ "crates/trigger_context",
"crates/unfurl",
"crates/user_quota",
"crates/workspace-hack"
@@ -7179,6 +7222,7 @@
"crates/system_skills",
"crates/task_dedup",
"crates/teams",
+ "crates/trigger_context",
"crates/unfurl",
"crates/user_quota",
"crates/workspace-hack"
@@ -7323,6 +7367,7 @@
"crates/system_skills",
"crates/task_dedup",
"crates/teams",
+ "crates/trigger_context",
"crates/unfurl",
"crates/user_quota",
"crates/workspace-hack"
@@ -7590,6 +7635,7 @@
"crates/system_skills",
"crates/task_dedup",
"crates/teams",
+ "crates/trigger_context",
"crates/unfurl",
"crates/user_quota",
"crates/workspace-hack",
@@ -7733,6 +7779,7 @@
"crates/system_skills",
"crates/task_dedup",
"crates/teams",
+ "crates/trigger_context",
"crates/unfurl",
"crates/user_quota",
"crates/workspace-hack"
@@ -7904,6 +7951,7 @@
"crates/system_skills",
"crates/task_dedup",
"crates/teams",
+ "crates/trigger_context",
"crates/unfurl",
"crates/user_quota",
"crates/work_feed",
@@ -8019,6 +8067,7 @@
"crates/share_permission_db_utils",
"crates/static_file_service_client",
"crates/system_properties",
+ "crates/trigger_context",
"crates/workspace-hack"
],
"image_optimizer": [
@@ -8205,6 +8254,7 @@
"crates/static_file_service_client",
"crates/system_properties",
"crates/teams",
+ "crates/trigger_context",
"crates/unfurl",
"crates/workspace-hack"
],
@@ -8337,6 +8387,7 @@
"crates/sync_service",
"crates/sync_service_client",
"crates/system_properties",
+ "crates/trigger_context",
"crates/user_quota",
"crates/workspace-hack"
],
@@ -8497,6 +8548,7 @@
"crates/remote_env_var",
"crates/share_permission_db_utils",
"crates/system_properties",
+ "crates/trigger_context",
"crates/workspace-hack"
],
"lexical_mention_extractor": [
@@ -8561,6 +8613,7 @@
"crates/remote_env_var",
"crates/share_permission_db_utils",
"crates/system_properties",
+ "crates/trigger_context",
"crates/workspace-hack"
],
"load-test": [
@@ -9103,6 +9156,7 @@
"crates/system_skills",
"crates/task_dedup",
"crates/teams",
+ "crates/trigger_context",
"crates/unfurl",
"crates/user_quota",
"crates/workspace-hack",
@@ -9275,6 +9329,7 @@
"crates/system_skills",
"crates/task_dedup",
"crates/teams",
+ "crates/trigger_context",
"crates/unfurl",
"crates/user_quota",
"crates/workspace-hack"
@@ -9604,6 +9659,7 @@
"crates/sqs_worker",
"crates/static_file_service_client",
"crates/system_properties",
+ "crates/trigger_context",
"crates/unfurl",
"crates/workspace-hack"
],
@@ -9701,6 +9757,7 @@
"crates/sqs_worker",
"crates/static_file_service_client",
"crates/system_properties",
+ "crates/trigger_context",
"crates/unfurl",
"crates/workspace-hack"
],
@@ -10083,6 +10140,7 @@
"crates/static_file_service_client",
"crates/system_properties",
"crates/teams",
+ "crates/trigger_context",
"crates/unfurl",
"crates/workspace-hack"
],
@@ -10187,6 +10245,7 @@
"crates/sqs_worker",
"crates/static_file_service_client",
"crates/system_properties",
+ "crates/trigger_context",
"crates/unfurl",
"crates/workspace-hack",
"services/organization_retention_handler"
@@ -10281,6 +10340,7 @@
"crates/sqs_worker",
"crates/static_file_service_client",
"crates/system_properties",
+ "crates/trigger_context",
"crates/unfurl",
"crates/workspace-hack",
"services/organization_retention_trigger"
@@ -10441,6 +10501,7 @@
"crates/system_skills",
"crates/task_dedup",
"crates/teams",
+ "crates/trigger_context",
"crates/unfurl",
"crates/user_quota",
"crates/workspace-hack",
@@ -10566,6 +10627,7 @@
"crates/system_skills",
"crates/task_dedup",
"crates/teams",
+ "crates/trigger_context",
"crates/unfurl",
"crates/user_quota",
"crates/workspace-hack"
@@ -10814,6 +10876,7 @@
"crates/sqs_worker",
"crates/static_file_service_client",
"crates/system_properties",
+ "crates/trigger_context",
"crates/unfurl",
"crates/workspace-hack"
],
@@ -10990,6 +11053,7 @@
"crates/system_skills",
"crates/task_dedup",
"crates/teams",
+ "crates/trigger_context",
"crates/unfurl",
"crates/user_quota",
"crates/workspace-hack",
@@ -11131,6 +11195,7 @@
"crates/system_skills",
"crates/task_dedup",
"crates/teams",
+ "crates/trigger_context",
"crates/unfurl",
"crates/user_quota",
"crates/workspace-hack",
@@ -11250,6 +11315,7 @@
"crates/static_file_service_client",
"crates/system_properties",
"crates/teams",
+ "crates/trigger_context",
"crates/unfurl",
"crates/user_quota",
"crates/workspace-hack"
@@ -11346,6 +11412,7 @@
"crates/sqs_worker",
"crates/static_file_service_client",
"crates/system_properties",
+ "crates/trigger_context",
"crates/unfurl",
"crates/workspace-hack"
],
@@ -11482,6 +11549,7 @@
"crates/sync_service",
"crates/sync_service_client",
"crates/system_properties",
+ "crates/trigger_context",
"crates/user_quota",
"crates/workspace-hack",
"tooling/seed_cli"
@@ -11658,6 +11726,7 @@
"crates/system_skills",
"crates/task_dedup",
"crates/teams",
+ "crates/trigger_context",
"crates/unfurl",
"crates/user_quota",
"crates/workspace-hack"
@@ -11766,6 +11835,7 @@
"crates/static_file_service_client",
"crates/system_properties",
"crates/teams",
+ "crates/trigger_context",
"crates/unfurl",
"crates/workspace-hack",
"services/slack_import_worker"
@@ -11872,6 +11942,7 @@
"crates/static_file_service_client",
"crates/system_properties",
"crates/teams",
+ "crates/trigger_context",
"crates/unfurl",
"crates/workspace-hack"
],
@@ -11987,6 +12058,7 @@
"crates/static_file_service_client",
"crates/system_properties",
"crates/teams",
+ "crates/trigger_context",
"crates/unfurl",
"crates/workspace-hack"
],
@@ -12105,6 +12177,7 @@
"crates/static_file_service_client",
"crates/system_properties",
"crates/teams",
+ "crates/trigger_context",
"crates/unfurl",
"crates/workspace-hack"
],
@@ -12219,6 +12292,7 @@
"crates/static_file_service_client",
"crates/system_properties",
"crates/teams",
+ "crates/trigger_context",
"crates/unfurl",
"crates/workspace-hack"
],
@@ -12346,6 +12420,7 @@
"crates/system_skills",
"crates/task_dedup",
"crates/teams",
+ "crates/trigger_context",
"crates/unfurl",
"crates/user_quota",
"crates/workspace-hack"
@@ -12439,6 +12514,7 @@
"crates/sqs_worker",
"crates/static_file_service_client",
"crates/system_properties",
+ "crates/trigger_context",
"crates/unfurl",
"crates/workspace-hack"
],
@@ -12652,6 +12728,7 @@
"crates/share_permission_db_utils",
"crates/system_properties",
"crates/task_dedup",
+ "crates/trigger_context",
"crates/workspace-hack"
],
"teams": [
@@ -12748,9 +12825,16 @@
"crates/static_file_service_client",
"crates/system_properties",
"crates/teams",
+ "crates/trigger_context",
"crates/unfurl",
"crates/workspace-hack"
],
+ "trigger_context": [
+ "crates/bot_id",
+ "crates/cowlike",
+ "crates/trigger_context",
+ "crates/workspace-hack"
+ ],
"turso-opfs": [
"crates/client/turso-opfs"
],
@@ -12862,6 +12946,7 @@
"crates/sqs_worker",
"crates/static_file_service_client",
"crates/system_properties",
+ "crates/trigger_context",
"crates/unfurl",
"crates/workspace-hack",
"services/upload_extractor_lambda_handler"
@@ -12957,6 +13042,7 @@
"crates/sqs_worker",
"crates/static_file_service_client",
"crates/system_properties",
+ "crates/trigger_context",
"crates/unfurl",
"crates/workspace-hack",
"services/upload_extractor_lambda_trigger"
@@ -13174,6 +13260,7 @@
"crates/system_skills",
"crates/task_dedup",
"crates/teams",
+ "crates/trigger_context",
"crates/unfurl",
"crates/user_quota",
"crates/webhook",
@@ -13314,6 +13401,7 @@
"crates/system_skills",
"crates/task_dedup",
"crates/teams",
+ "crates/trigger_context",
"crates/unfurl",
"crates/user_quota",
"crates/work_feed",
diff --git a/Cargo.lock b/Cargo.lock
index f63e31556d..8b3d2095f6 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -393,6 +393,7 @@ dependencies = [
"tracing",
"tracing-opentelemetry",
"tracing-subscriber",
+ "trigger_context",
"url",
"utoipa",
"uuid",
@@ -426,6 +427,7 @@ dependencies = [
"axum-extra",
"bot_id",
"bots",
+ "call",
"channels",
"claude_cloud_agents",
"codex_cloud_agents",
@@ -667,6 +669,7 @@ dependencies = [
"tracing",
"tracing-opentelemetry",
"tracing-subscriber",
+ "trigger_context",
"utoipa",
"uuid",
"workspace-hack",
@@ -704,6 +707,7 @@ dependencies = [
"async-trait",
"bot_id",
"bots",
+ "call",
"channel_sender",
"channels",
"chrono",
@@ -712,6 +716,7 @@ dependencies = [
"entity_access",
"initiative",
"lexical_client",
+ "macro_db_migrator",
"macro_event_broker",
"macro_event_topics",
"macro_user_id",
@@ -733,6 +738,7 @@ dependencies = [
"thiserror 2.0.18",
"tokio",
"tracing",
+ "trigger_context",
"workspace-hack",
]
@@ -746,6 +752,7 @@ dependencies = [
"ai_usage",
"anyhow",
"bots",
+ "call",
"channels",
"connection_gateway_client",
"crm",
@@ -4356,6 +4363,7 @@ dependencies = [
"toml_edit 0.22.27",
"tracing",
"tracing-subscriber",
+ "trigger_context",
"tui-input",
"uuid",
"webbrowser",
@@ -10872,6 +10880,7 @@ dependencies = [
"serde_json",
"tokio",
"tracing",
+ "trigger_context",
"workspace-hack",
]
@@ -16640,6 +16649,7 @@ dependencies = [
"tokio-util",
"tower 0.5.3",
"tracing",
+ "trigger_context",
"utoipa",
"utoipa-swagger-ui",
"workspace-hack",
@@ -19825,6 +19835,18 @@ dependencies = [
"petgraph 0.8.3",
]
+[[package]]
+name = "trigger_context"
+version = "0.1.0"
+dependencies = [
+ "bot_id",
+ "chrono",
+ "serde",
+ "serde_json",
+ "uuid",
+ "workspace-hack",
+]
+
[[package]]
name = "triomphe"
version = "0.1.15"
diff --git a/Cargo.toml b/Cargo.toml
index 91bd98e84d..41f123e093 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -6,6 +6,7 @@ members = [
"crates/activity",
"crates/agent", "crates/agent_changes", "crates/agent_egress", "crates/folds/agent_fold", "crates/folds/claude_fold", "crates/folds/codex_fold",
"crates/agent_harness",
+ "crates/trigger_context",
"crates/agent_preview",
"crates/agent_inmem",
"crates/agent_runtime_protocol", "crates/agent_session", "crates/agent_session_realtime",
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/AgentContext.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/AgentContext.tsx
index cdd8179ebc..b553aef9ed 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/AgentContext.tsx
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/AgentContext.tsx
@@ -1,14 +1,64 @@
+import { Popover } from '@kobalte/core/popover';
import type { AgentContextDecoratorProps } from '@macro-inc/lexical-core';
-import type { Component } from 'solid-js';
+import Eye from '@phosphor/eye.svg';
+import { type Component, createMemo, createSignal, For, Show } from 'solid-js';
+import { AgentContextElement } from './AgentContextElement';
+import { parseContext, summaryOf } from './agent-context-tree';
-/** A quiet disclosure for the channel context supplied to an agent. */
-export const AgentContext: Component<AgentContextDecoratorProps> = (props) => (
- <details class="my-1 text-xs text-ink-muted">
- <summary class="w-fit select-none rounded-full border border-edge-muted bg-hover px-2 py-0.5">
- Context
- </summary>
- <pre class="mt-1 max-h-64 overflow-auto whitespace-pre-wrap rounded-md border border-edge-muted bg-hover p-2 font-sans text-xs text-ink-muted">
- {props.text}
- </pre>
- </details>
-);
+/** A small eye in the message's corner, opening what the agent was given. */
+export const AgentContext: Component<AgentContextDecoratorProps> = (props) => {
+ const [raw, setRaw] = createSignal(false);
+ const elements = createMemo(() => parseContext(props.text));
+ const label = () => {
+ const parsed = elements();
+ return parsed ? summaryOf(parsed) : 'Context';
+ };
+
+ return (
+ // Zero height so the message keeps its own spacing: the next block is
+ // styled as the first one, and the eye sits in the corner over it.
+ <div class="relative h-0 [&+*]:!mt-1.5">
+ <Popover placement="bottom-end" gutter={4}>
+ <Popover.Trigger
+ aria-label={`What the agent saw: ${label()}`}
+ title={label()}
+ class="absolute -top-3 -right-3 rounded p-0.5 text-ink-extra-muted hover:bg-hover hover:text-ink"
+ >
+ <Eye class="size-3.5" />
+ </Popover.Trigger>
+ <Popover.Portal>
+ <Popover.Content class="z-action-menu flex max-h-[60vh] w-[28rem] max-w-[90vw] flex-col gap-2 overflow-auto rounded-xl border border-edge-muted bg-menu p-3 text-xs text-ink-muted shadow-lg">
+ <div class="flex items-center justify-between gap-2">
+ <span class="font-medium text-ink">
+ Context shared with the agent
+ </span>
+ <button
+ type="button"
+ onClick={() => setRaw(!raw())}
+ class="text-[11px] text-ink-extra-muted hover:text-ink"
+ >
+ {raw() ? 'Structured' : 'Raw'}
+ </button>
+ </div>
+ <Show
+ when={!raw() && elements()}
+ fallback={
+ <pre class="whitespace-pre-wrap font-mono text-[11px]">
+ {props.text}
+ </pre>
+ }
+ >
+ {(parsed) => (
+ <div class="flex flex-col gap-3">
+ <For each={parsed()}>
+ {(element) => <AgentContextElement element={element} />}
+ </For>
+ </div>
+ )}
+ </Show>
+ </Popover.Content>
+ </Popover.Portal>
+ </Popover>
+ </div>
+ );
+};
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/AgentContextElement.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/AgentContextElement.tsx
new file mode 100644
index 0000000000..24b5d6967b
--- /dev/null
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/AgentContextElement.tsx
@@ -0,0 +1,47 @@
+import { type Component, For, Show } from 'solid-js';
+import { type ContextElement, displayValue } from './agent-context-tree';
+
+/** An attribute that names the agent itself, such as `mentioned_you`. */
+function isAboutTheAgent(name: string, value: string): boolean {
+ return value === 'true' && name.endsWith('_you');
+}
+
+/** One element of the context: its tag, its attributes, its text, and what it holds. */
+export const AgentContextElement: Component<{ element: ContextElement }> = (
+ props
+) => (
+ <div class="flex min-w-0 flex-col gap-1">
+ <div class="flex flex-wrap items-baseline gap-1">
+ <span class="font-mono text-[11px] text-ink-extra-muted">
+ {props.element.tag}
+ </span>
+ <For each={props.element.attributes}>
+ {([name, value]) => (
+ <span
+ class="rounded px-1.5 py-px text-[11px]"
+ classList={{
+ 'bg-accent/10 text-accent': isAboutTheAgent(name, value),
+ 'bg-hover text-ink-muted': !isAboutTheAgent(name, value),
+ }}
+ >
+ <span class="opacity-70">{name.replaceAll('_', ' ')}</span>{' '}
+ {displayValue(name, value)}
+ </span>
+ )}
+ </For>
+ </div>
+ <For each={props.element.notes}>
+ {(note) => <p class="text-xs italic text-ink-extra-muted">{note}</p>}
+ </For>
+ <Show when={props.element.text}>
+ {(text) => <p class="whitespace-pre-wrap text-sm text-ink">{text()}</p>}
+ </Show>
+ <Show when={props.element.children.length > 0}>
+ <div class="flex flex-col gap-2 border-l border-edge-muted pl-3">
+ <For each={props.element.children}>
+ {(child) => <AgentContextElement element={child} />}
+ </For>
+ </div>
+ </Show>
+ </div>
+);
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/agent-context-tree.test.ts b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/agent-context-tree.test.ts
new file mode 100644
index 0000000000..397f17d7e5
--- /dev/null
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/agent-context-tree.test.ts
@@ -0,0 +1,82 @@
+import { describe, expect, it } from 'vitest';
+import { parseContext, summaryOf } from './agent-context-tree';
+
+describe('parseContext', () => {
+ it('reads elements, attributes, notes and text', () => {
+ expect(
+ parseContext(
+ '<trigger kind="mentioned"><note>Opened the session.</note><channel id="c1" name="eng" type="public"/><thread root="m1"><message id="m1" author="Julia">hello</message></thread></trigger>'
+ )
+ ).toEqual([
+ {
+ tag: 'trigger',
+ attributes: [['kind', 'mentioned']],
+ notes: ['Opened the session.'],
+ text: undefined,
+ children: [
+ {
+ tag: 'channel',
+ attributes: [
+ ['id', 'c1'],
+ ['name', 'eng'],
+ ['type', 'public'],
+ ],
+ notes: [],
+ text: undefined,
+ children: [],
+ },
+ {
+ tag: 'thread',
+ attributes: [['root', 'm1']],
+ notes: [],
+ text: undefined,
+ children: [
+ {
+ tag: 'message',
+ attributes: [
+ ['id', 'm1'],
+ ['author', 'Julia'],
+ ],
+ notes: [],
+ text: 'hello',
+ children: [],
+ },
+ ],
+ },
+ ],
+ },
+ ]);
+ });
+
+ it('gives up on text that is not XML', () => {
+ expect(parseContext('Prior message 1: <unclosed')).toBeUndefined();
+ });
+});
+
+describe('summaryOf', () => {
+ it('names the kind and the channel', () => {
+ expect(
+ summaryOf(
+ parseContext(
+ '<session owner="Wolf"/><trigger kind="follow_up"><discussion><channel name="eng"/></discussion></trigger>'
+ ) ?? []
+ )
+ ).toBe('Follow-up · #eng');
+ });
+
+ it('names a task by its title', () => {
+ expect(
+ summaryOf(
+ parseContext(
+ '<trigger kind="task_assigned"><task id="t1" title="Fix scroll"/></trigger>'
+ ) ?? []
+ )
+ ).toBe('Task assigned · Fix scroll');
+ });
+
+ it('falls back to Context without a trigger', () => {
+ expect(
+ summaryOf(parseContext('<instructions>Be brief.</instructions>') ?? [])
+ ).toBe('Context');
+ });
+});
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/agent-context-tree.ts b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/agent-context-tree.ts
new file mode 100644
index 0000000000..9a5bdfd450
--- /dev/null
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/agent-context-tree.ts
@@ -0,0 +1,100 @@
+import { match } from 'ts-pattern';
+
+/** One element of an agent's context, as the XML has it. */
+export type ContextElement = {
+ tag: string;
+ attributes: [name: string, value: string][];
+ /** Guidance the agent was given about this element. */
+ notes: string[];
+ /** Text of an element without element children. */
+ text: string | undefined;
+ children: ContextElement[];
+};
+
+function toElement(element: Element): ContextElement {
+ const children = [...element.children];
+ return {
+ tag: element.tagName,
+ attributes: [...element.attributes].map((item) => [item.name, item.value]),
+ notes: children
+ .filter((child) => child.tagName === 'note')
+ .map((child) => child.textContent ?? ''),
+ text:
+ children.length === 0
+ ? element.textContent?.trim() || undefined
+ : undefined,
+ children: children
+ .filter((child) => child.tagName !== 'note')
+ .map(toElement),
+ };
+}
+
+/** Top-level elements, or `undefined` when the text is not XML. */
+export function parseContext(text: string): ContextElement[] | undefined {
+ const parsed = new DOMParser().parseFromString(
+ `<context>${text}</context>`,
+ 'application/xml'
+ );
+ if (parsed.getElementsByTagName('parsererror').length > 0) return undefined;
+ return [...parsed.documentElement.children].map(toElement);
+}
+
+export function attributeOf(
+ element: ContextElement,
+ name: string
+): string | undefined {
+ return element.attributes.find(([key]) => key === name)?.[1];
+}
+
+function findFirst(
+ elements: ContextElement[],
+ tags: string[]
+): ContextElement | undefined {
+ for (const element of elements) {
+ if (tags.includes(element.tag)) return element;
+ const found = findFirst(element.children, tags);
+ if (found) return found;
+ }
+ return undefined;
+}
+
+const PLACE_TAGS = [
+ 'channel',
+ 'document',
+ 'task',
+ 'routine',
+ 'project',
+ 'call',
+];
+
+/** Where the trigger happened, as a reader names it: `#eng`, a document's name. */
+export function placeOf(trigger: ContextElement): string | undefined {
+ const place = findFirst([trigger], PLACE_TAGS);
+ if (!place) return undefined;
+ const name = attributeOf(place, 'name') ?? attributeOf(place, 'title');
+ if (!name) return undefined;
+ return place.tag === 'channel' ? `#${name}` : name;
+}
+
+/** The chip's label: what called the agent, and where. */
+export function summaryOf(elements: ContextElement[]): string {
+ const trigger = elements.find((element) => element.tag === 'trigger');
+ if (!trigger) return 'Context';
+ const kind = match(attributeOf(trigger, 'kind'))
+ .with('mentioned', () => 'Mentioned')
+ .with('follow_up', () => 'Follow-up')
+ .with('task_assigned', () => 'Task assigned')
+ .with('requested', () => 'Requested')
+ .with('dispatched', () => 'Dispatched')
+ .with('routine', () => 'Routine')
+ .otherwise(() => 'Context');
+ const place = placeOf(trigger);
+ return place ? `${kind} · ${place}` : kind;
+}
+
+/** Times in the context are RFC 3339; show them the way the app does. */
+export function displayValue(name: string, value: string): string {
+ if (name !== 'at' && name !== 'due' && !name.endsWith('_at')) return value;
+ const time = new Date(value);
+ return Number.isNaN(time.getTime()) ? value : time.toLocaleString();
+}
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/controlRequestAllOf.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/controlRequestAllOf.ts
index 1543ba9463..aea26f5b76 100644
--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/controlRequestAllOf.ts
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/controlRequestAllOf.ts
@@ -5,7 +5,11 @@
* OpenAPI spec version: 0.1.0
*/
import type { ControlRequestAllOfActionId } from './controlRequestAllOfActionId';
+import type { ControlRequestAllOfContext } from './controlRequestAllOfContext';
export type ControlRequestAllOf = {
actionId?: ControlRequestAllOfActionId;
+ /** Why the agent is being asked. Only a runtime forwarding a triggered
+prompt may send it; a user's request carrying it is refused. */
+ context?: ControlRequestAllOfContext;
};
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/controlRequestAllOfContext.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/controlRequestAllOfContext.ts
new file mode 100644
index 0000000000..12cdd0bf98
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/controlRequestAllOfContext.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 { ControlRequestAllOfContextAnyOf } from './controlRequestAllOfContextAnyOf';
+
+/**
+ * Why the agent is being asked. Only a runtime forwarding a triggered
+prompt may send it; a user's request carrying it is refused.
+ */
+export type ControlRequestAllOfContext = ControlRequestAllOfContextAnyOf | null;
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/controlRequestAllOfContextAnyOf.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/controlRequestAllOfContextAnyOf.ts
new file mode 100644
index 0000000000..ce289a97b3
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/controlRequestAllOfContextAnyOf.ts
@@ -0,0 +1,12 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Why the agent is being asked. Only a runtime forwarding a triggered
+prompt may send it; a user's request carrying it is refused.
+ */
+export type ControlRequestAllOfContextAnyOf = { [key: string]: unknown };
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 f857e2ca47..1dd01ed668 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
@@ -107,6 +107,8 @@ export * from './completeRequest';
export * from './controlRequest';
export * from './controlRequestAllOf';
export * from './controlRequestAllOfActionId';
+export * from './controlRequestAllOfContext';
+export * from './controlRequestAllOfContextAnyOf';
export * from './controlResponse';
export * from './controlStatusDto';
export * from './createAgentSessionRequest';
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 929013f7dc..08de27bd58 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
@@ -3265,6 +3265,10 @@
"description": "The id the caller already speculated this action under, when it has\none. Adopted as the accepted id, so a client that renders the action\noptimistically promotes that entry in place instead of retracting it\nand re-speculating under a server id. Re-sending the same id is not a\nsecond action: see [`ControlResponse`].\n\nNamed rather than flattened so it cannot collide with the action's own\nfields, which are tagged under `type`."
}
]
+ },
+ "context": {
+ "type": ["object", "null"],
+ "description": "Why the agent is being asked. Only a runtime forwarding a triggered\nprompt may send it; a user's request carrying it is refused."
}
}
}
diff --git a/crates/agent_harness/Cargo.toml b/crates/agent_harness/Cargo.toml
index ed467936d3..6334db88a9 100644
--- a/crates/agent_harness/Cargo.toml
+++ b/crates/agent_harness/Cargo.toml
@@ -32,6 +32,7 @@ anyhow = { workspace = true }
axum = { workspace = true, features = ["ws"] }
base64 = { workspace = true }
bot_id = { path = "../bot_id" }
+trigger_context = { path = "../trigger_context" }
harness_id = { path = "../harness_id" }
channel_sender = { path = "../channel_sender" }
chrono = { workspace = true }
diff --git a/crates/agent_harness/src/domain/model.rs b/crates/agent_harness/src/domain/model.rs
index 06afd9908b..8788bae923 100644
--- a/crates/agent_harness/src/domain/model.rs
+++ b/crates/agent_harness/src/domain/model.rs
@@ -16,6 +16,7 @@ use bot_id::BotId;
use macro_user_id::user_id::MacroUserIdStr;
use macro_uuid::Uuid;
use messages::domain::events::MessageEventAttachment;
+use trigger_context::TriggerContext;
mod session_origin;
pub use session_origin::{MentionOrigin, SessionOrigin, TaskAssignmentOrigin};
mod coding_preferences;
@@ -359,109 +360,6 @@ pub struct AnnounceOrigin {
pub message_id: Uuid,
}
-/// One message supplied as untrusted prompt context.
-#[derive(Debug, Clone, PartialEq, Eq)]
-pub struct ContextMessage {
- /// Message id.
- pub id: Uuid,
- /// Sender identifier as the message service represents it.
- pub sender_id: String,
- /// Readable name of the sender.
- pub author: String,
- /// Message body.
- pub content: String,
- /// When the message was posted.
- pub posted_at: chrono::DateTime<chrono::Utc>,
-}
-
-/// Messages of one discussion, oldest first.
-#[derive(Debug, Clone, PartialEq, Eq)]
-pub struct ContextThread {
- /// Root message of the discussion.
- pub root_id: Uuid,
- /// Live messages, the root first when it is included.
- pub messages: Vec<ContextMessage>,
- /// Whether some messages of the discussion were left out.
- pub messages_omitted: bool,
-}
-
-/// What a prompt answers. Without this the agent has to guess which of the
-/// surrounding messages "fix this" means.
-#[derive(Debug, Clone, PartialEq, Eq)]
-pub enum ReplyTarget {
- /// The author quote-replied to one message.
- Quote {
- /// The quoted message.
- message_id: Uuid,
- /// The discussion holding the quoted message.
- thread_id: Uuid,
- /// The one-line preview the quote renders.
- preview: String,
- /// The quoted message in full. Absent when it lives in another
- /// conversation or could not be read.
- message: Option<ContextMessage>,
- },
- /// The prompt was posted as a reply in a discussion.
- Thread {
- /// Root of that discussion.
- root_id: Uuid,
- },
- /// The prompt was posted at the top level of a channel and replies to
- /// no particular message.
- None,
-}
-
-/// Where in a document a comment thread sits. An annotation id alone names a
-/// location the agent has no way to resolve: the document body it can read
-/// carries no marks or highlights, so the text the comment covers travels
-/// with the id.
-#[derive(Debug, Clone, PartialEq, Eq)]
-pub enum CommentAnchor {
- /// A cell or rectangular range in a native spreadsheet.
- Spreadsheet {
- /// Stable sheet identity within the workbook.
- sheet_id: String,
- /// Sheet name when the discussion was created.
- sheet_name: String,
- /// A1 cell or range, such as B4 or B4:C9.
- range: String,
- },
-
- /// A comment mark in a markdown document.
- Mark {
- /// Lexical mark the thread is attached to.
- mark_id: String,
- /// The marked text as it read when the comment was posted. Absent on
- /// threads anchored before snapshots were captured.
- marked_text: Option<String>,
- /// The mark as the document reads now. Absent when the document no longer
- /// carries it or the lookup failed, leaving the snapshot as the fallback.
- current: Option<MarkedPassage>,
- },
- /// A highlight on a PDF.
- PdfHighlight {
- /// Highlight annotation the thread is attached to.
- anchor_id: String,
- /// The text the highlight covers, read from the highlight. Absent when
- /// the highlight carries none.
- marked_text: Option<String>,
- },
- /// A point pinned on a PDF page, which covers no text.
- PdfPin {
- /// Pin annotation the thread is attached to.
- anchor_id: String,
- },
-}
-
-/// A comment mark resolved against the live document, both fields bounded.
-#[derive(Debug, Clone, PartialEq, Eq)]
-pub struct MarkedPassage {
- /// The text the mark covers.
- pub marked_text: String,
- /// The block or blocks containing the mark, windowed around it.
- pub surrounding_text: String,
-}
-
/// Whose access a session runs with, and who sent the prompt being composed.
///
/// Named to the agent on every prompt so it can tell the session's owner
@@ -474,24 +372,6 @@ pub struct PromptPeople {
pub sender: Option<MacroUserIdStr<'static>>,
}
-/// What the conversation an agent was summoned from contributes to its prompt.
-#[derive(Debug, Clone, Default, PartialEq, Eq)]
-pub struct ConversationContext {
- /// The document location, when the prompt came from an anchored comment.
- pub anchor: Option<CommentAnchor>,
- /// What the prompt answers.
- pub reply_target: Option<ReplyTarget>,
- /// The prompting message, marked where it appears in the context.
- pub prompt_message_id: Option<Uuid>,
- /// The discussion the prompt was posted in, through the prompt itself.
- /// Absent for a top-level channel message.
- pub thread: Option<ContextThread>,
- /// Other recent channel activity, grouped by discussion, oldest first.
- /// For a top-level channel prompt this is the primary context and ends
- /// with the prompt.
- pub channel: Vec<ContextThread>,
-}
-
/// Do something in a session that already exists.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct DeliverAction {
@@ -510,6 +390,10 @@ pub struct DeliverAction {
/// channel passes `Some`, and is still suppressed - the harness only
/// learns the session's channel when it runs.
pub announce: Option<AnnounceOrigin>,
+ /// Why the agent is being asked, rendered ahead of a prompt. Absent for
+ /// prompts driven from the session itself.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub context: Option<TriggerContext>,
}
/// One operation executed by the harness for an agent session.
@@ -600,6 +484,7 @@ impl DeliverAction {
action,
actor,
announce,
+ context: None,
}
}
@@ -615,6 +500,7 @@ impl DeliverAction {
action: event.action,
actor: event.actor,
announce: None,
+ context: event.context,
}
}
}
diff --git a/crates/agent_harness/src/domain/model/session_origin.rs b/crates/agent_harness/src/domain/model/session_origin.rs
index c77afd6a0d..a77e1b295d 100644
--- a/crates/agent_harness/src/domain/model/session_origin.rs
+++ b/crates/agent_harness/src/domain/model/session_origin.rs
@@ -3,6 +3,7 @@
use agent_runtime_protocol::domain::action::{AgentAction, PromptAttachment};
use macro_user_id::user_id::MacroUserIdStr;
use macro_uuid::Uuid;
+use trigger_context::TriggerContext;
use super::AnnounceOrigin;
@@ -25,6 +26,9 @@ pub struct MentionOrigin {
/// Files attached to the message, as the prompt will refer to them.
#[serde(default)]
pub attachments: Vec<PromptAttachment>,
+ /// Why the agent was called, as the trigger read it.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub context: Option<TriggerContext>,
}
/// A task assignment that starts a session without a user-authored mention.
@@ -38,6 +42,9 @@ pub struct TaskAssignmentOrigin {
pub actor: MacroUserIdStr<'static>,
/// Task instructions supplied privately to the session.
pub prompt: String,
+ /// The task, who assigned it, and how, as the trigger read it.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub context: Option<TriggerContext>,
}
/// The event that opens a managed session.
@@ -76,6 +83,13 @@ impl SessionOrigin {
}
}
+ pub(crate) fn context(&self) -> Option<&TriggerContext> {
+ match self {
+ Self::Mention(origin) => origin.context.as_ref(),
+ Self::TaskAssignment(origin) => origin.context.as_ref(),
+ }
+ }
+
pub(crate) fn kind(&self) -> &'static str {
match self {
Self::Mention(_) => "mention",
diff --git a/crates/agent_harness/src/domain/model/session_origin/test.rs b/crates/agent_harness/src/domain/model/session_origin/test.rs
index e57dc2d8d1..5cfbdfca6b 100644
--- a/crates/agent_harness/src/domain/model/session_origin/test.rs
+++ b/crates/agent_harness/src/domain/model/session_origin/test.rs
@@ -14,6 +14,7 @@ fn existing_mention_commands_keep_their_wire_shape_and_reply_behavior() {
sender: actor(),
content: "Please review this".to_owned(),
attachments: vec![PromptAttachment::new("https://example.com/file", "image")],
+ context: None,
};
let wire = serde_json::to_value(&mention).unwrap();
let origin: SessionOrigin = serde_json::from_value(wire.clone()).unwrap();
@@ -36,6 +37,7 @@ fn assignments_remain_distinct_after_command_serialization() {
discussion_id: Uuid::from_u128(4),
actor: actor(),
prompt: "Private task brief".to_owned(),
+ context: None,
});
let wire = serde_json::to_value(&origin).unwrap();
assert!(wire.get("content").is_none());
diff --git a/crates/agent_harness/src/domain/ports.rs b/crates/agent_harness/src/domain/ports.rs
index d876153fe1..a06b4b54a5 100644
--- a/crates/agent_harness/src/domain/ports.rs
+++ b/crates/agent_harness/src/domain/ports.rs
@@ -15,9 +15,9 @@ use macro_user_id::user_id::MacroUserIdStr;
use super::error::{HarnessError, Result};
use super::model::{
- AgentKind, AgentRuntimeConfig, AnnouncedMessage, CommandOutcome, ConversationContext,
- DeclinedMention, HarnessCommand, ProvisionedEgress, ReachableRepository, ResolvedReply,
- SandboxEgress, SessionAnnouncement, SessionBlocker, SpawnContainer, ToolApprovalChange,
+ AgentKind, AgentRuntimeConfig, AnnouncedMessage, CommandOutcome, DeclinedMention,
+ HarnessCommand, ProvisionedEgress, ReachableRepository, ResolvedReply, SandboxEgress,
+ SessionAnnouncement, SessionBlocker, SpawnContainer, ToolApprovalChange,
};
use super::notifications::PlannedNotification;
use super::sandbox::SandboxResizeEffect;
@@ -160,7 +160,7 @@ pub trait AgentRuntimeDirectory: Send + Sync + 'static {
) -> impl Future<Output = Result<Option<AgentRuntimeConfig>>> + Send;
}
-/// Authorizes message origins and loads conversation context for agent prompts.
+/// Authorizes the message origins agent prompts answer into.
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.
@@ -169,29 +169,19 @@ pub trait MessagePromptContext: Send + Sync + 'static {
actor: &MacroUserIdStr<'static>,
origin: &super::model::AnnounceOrigin,
) -> impl Future<Output = Result<()>> + Send;
-
- /// Read the prompt's discussion, the channel activity around it, what the
- /// prompt replies to, and the comment anchor it sits on, with a fresh
- /// access check.
- fn conversation_context(
- &self,
- actor: &MacroUserIdStr<'static>,
- origin: &super::model::AnnounceOrigin,
- ) -> impl Future<Output = Result<ConversationContext>> + Send;
}
/// Composes an agent prompt from raw markdown and trusted session context.
pub trait AgentPromptComposer: Send + Sync + 'static {
/// Return the markdown that should be delivered to the agent runtime.
- /// With no instructions, people, or context, the prompt is sanitized
+ /// With no instructions, people, or trigger, the prompt is sanitized
/// without adding a private context node.
fn compose(
&self,
prompt_markdown: &str,
instructions: Option<&str>,
- parent: Option<&messages::domain::models::MessageParent>,
people: Option<&super::model::PromptPeople>,
- context: Option<&ConversationContext>,
+ trigger: Option<&trigger_context::TriggerContext>,
) -> impl Future<Output = Result<String>> + Send;
}
diff --git a/crates/agent_harness/src/domain/queue.rs b/crates/agent_harness/src/domain/queue.rs
index b6d86fa731..daca23ec30 100644
--- a/crates/agent_harness/src/domain/queue.rs
+++ b/crates/agent_harness/src/domain/queue.rs
@@ -32,6 +32,7 @@ use chrono::{DateTime, Utc};
use dashmap::DashMap;
use macro_user_id::user_id::MacroUserIdStr;
use macro_uuid::Uuid;
+use trigger_context::TriggerContext;
use super::model::{AnnounceOrigin, HeldToolCall};
@@ -56,6 +57,8 @@ pub struct QueuedEntry {
/// Where to announce the prompt at dispatch, when it came from somewhere
/// the session should answer back into.
pub announce: Option<AnnounceOrigin>,
+ /// Why the agent is being asked, composed into the prompt at dispatch.
+ pub context: Option<TriggerContext>,
/// The chip message, once posted. Set by the dispatch that posts it and
/// carried through a requeue, so a dispatch that fails *after*
/// announcing retries without posting a second chip.
@@ -156,6 +159,7 @@ impl QueuedEntry {
.map(serde_json::to_value)
.transpose()?,
announced_message_id: self.announced,
+ context: self.context.clone(),
})
}
@@ -167,6 +171,7 @@ impl QueuedEntry {
actor: stored.actor,
announce: stored.announce.map(serde_json::from_value).transpose()?,
announced: stored.announced_message_id,
+ context: stored.context,
created_at: stored.created_at,
})
}
diff --git a/crates/agent_harness/src/domain/queue/test.rs b/crates/agent_harness/src/domain/queue/test.rs
index 7735ab415a..b7be069acd 100644
--- a/crates/agent_harness/src/domain/queue/test.rs
+++ b/crates/agent_harness/src/domain/queue/test.rs
@@ -11,6 +11,7 @@ fn prompt_entry(text: &str) -> QueuedEntry {
announce: None,
announced: None,
created_at: Utc::now(),
+ context: None,
}
}
@@ -132,6 +133,7 @@ fn only_prompts_are_editable() {
announce: None,
announced: None,
created_at: Utc::now(),
+ context: None,
};
queues.enqueue(session, compact.clone()).unwrap();
diff --git a/crates/agent_harness/src/domain/service.rs b/crates/agent_harness/src/domain/service.rs
index b497915652..21c1182ce0 100644
--- a/crates/agent_harness/src/domain/service.rs
+++ b/crates/agent_harness/src/domain/service.rs
@@ -48,6 +48,7 @@ use macro_user_id::user_id::MacroUserIdStr;
use tokio::sync::{mpsc, oneshot};
use tracing::Instrument as _;
use tracing::instrument::WithSubscriber as _;
+use trigger_context::TriggerContext;
use crate::domain::error::{HarnessError, Result};
use crate::domain::model::{
diff --git a/crates/agent_harness/src/domain/service/deliver.rs b/crates/agent_harness/src/domain/service/deliver.rs
index 25536a6349..8bc0cb95e0 100644
--- a/crates/agent_harness/src/domain/service/deliver.rs
+++ b/crates/agent_harness/src/domain/service/deliver.rs
@@ -56,6 +56,7 @@ where
action,
actor,
announce: _,
+ context: _,
} = command;
if action.occupies_turn() {
@@ -155,18 +156,18 @@ where
/// Compose a prompt in place. Compact and other actions are left as-is.
///
- /// 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. The prompt that opens a session's first turn
- /// also carries the session's instructions, unless its runtime already
- /// reads them as a system prompt.
+ /// A prompt that names an origin is only composed while the actor may
+ /// still write there. Why the agent was called arrives with the prompt,
+ /// read by whatever triggered it; nothing here reads the conversation. The
+ /// prompt that opens a session's first turn also carries the session's
+ /// instructions, unless its runtime already reads them as a system prompt.
pub(super) async fn compose_action(
&self,
session_id: AgentSessionId,
action: &mut AgentAction,
actor: Option<&MacroUserIdStr<'static>>,
announce: Option<&AnnounceOrigin>,
+ context: Option<&TriggerContext>,
first_turn: bool,
) -> Result<()> {
let AgentAction::Prompt(prompt) = action else {
@@ -188,61 +189,31 @@ where
})
.and_then(|session| session.instructions.as_deref())
.filter(|instructions| !instructions.trim().is_empty());
- let context = if let Some(origin) = announce {
- Some(self.load_prompt_context(origin, actor).await?)
- } else {
- None
- };
+ if let Some(origin) = announce {
+ self.authorize_prompt_origin(origin, actor).await?;
+ }
prompt.prompt = self
.prompt_composer
- .compose(
- &raw_prompt,
- instructions,
- announce
- .filter(|origin| !origin.reuse_origin_message)
- .map(|origin| &origin.parent),
- people.as_ref(),
- context.as_ref(),
- )
+ .compose(&raw_prompt, instructions, people.as_ref(), context)
.await?;
prompt.set_name_source(raw_prompt);
Ok(())
}
- /// Recheck the actor's access to the origin, then read the conversation
- /// around 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(
+ /// Recheck the actor's access to the origin. 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 authorize_prompt_origin(
&self,
origin: &AnnounceOrigin,
actor: Option<&MacroUserIdStr<'static>>,
- ) -> Result<crate::domain::model::ConversationContext> {
+ ) -> Result<()> {
let actor = actor.ok_or_else(|| {
HarnessError::PromptContext(rootcause::report!(
"message prompts require an acting user"
))
})?;
- self.prompt_context.authorize_origin(actor, origin).await?;
- // Assignment context is supplied privately. It was not a user message
- // in the discussion, so do not add history or thread-reply instructions.
- if origin.reuse_origin_message {
- return Ok(Default::default());
- }
- Ok(self
- .prompt_context
- .conversation_context(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())
+ self.prompt_context.authorize_origin(actor, origin).await
}
/// Who, if anyone, should be told that this landed.
diff --git a/crates/agent_harness/src/domain/service/open.rs b/crates/agent_harness/src/domain/service/open.rs
index 32c0586dad..9b90634ce4 100644
--- a/crates/agent_harness/src/domain/service/open.rs
+++ b/crates/agent_harness/src/domain/service/open.rs
@@ -427,6 +427,7 @@ where
session_id,
DeliverAction {
id: AgentActionId::mint(),
+ context: origin.context().cloned(),
action: origin.into_action(),
actor: Some(actor),
announce: Some(announcement),
diff --git a/crates/agent_harness/src/domain/service/queue.rs b/crates/agent_harness/src/domain/service/queue.rs
index a1fadef109..4bbd6b5702 100644
--- a/crates/agent_harness/src/domain/service/queue.rs
+++ b/crates/agent_harness/src/domain/service/queue.rs
@@ -638,6 +638,7 @@ where
action: command.action,
actor: command.actor,
announce: command.announce,
+ context: command.context,
announced: None,
created_at: chrono::Utc::now(),
};
@@ -770,6 +771,7 @@ where
action: AgentAction::Stop,
actor,
announce: None,
+ context: None,
},
)
.await
@@ -811,6 +813,7 @@ where
action: AgentAction::Stop,
actor: actor.cloned(),
announce: None,
+ context: None,
},
)
.await
@@ -999,6 +1002,7 @@ where
&mut composed,
entry.actor.as_ref(),
entry.announce.as_ref(),
+ entry.context.as_ref(),
prompted_message_id.turn == TurnId(0),
)
.await
@@ -1064,6 +1068,8 @@ where
action: composed,
actor: entry.actor.clone(),
announce: entry.announce.clone(),
+ // Already composed into the action above.
+ context: None,
};
match self.deliver(session_id, command).await {
Ok(()) => {
diff --git a/crates/agent_harness/src/domain/service/test.rs b/crates/agent_harness/src/domain/service/test.rs
index 3163be5b35..fab75831e2 100644
--- a/crates/agent_harness/src/domain/service/test.rs
+++ b/crates/agent_harness/src/domain/service/test.rs
@@ -45,15 +45,17 @@ use bot_id::BotId;
use macro_user_id::user_id::MacroUserIdStr;
use macro_uuid::Uuid;
use tokio::sync::mpsc;
+use trigger_context::{
+ ChannelType, ContextPerson, DiscussionContext, DiscussionSurface, ReplyTarget, TriggerContext,
+};
use super::AgentHarnessService;
use super::into_session_error;
use crate::domain::error::HarnessError;
use crate::domain::model::{
- AgentKind, AgentRuntimeConfig, AnnounceOrigin, CommandOutcome, CommentAnchor, ContextMessage,
- ContextThread, ConversationContext, DeclinedMention, DeliverAction, HarnessCommand,
- HarnessDefaults, MentionOrigin, OpenSession, PromptPeople, SessionBlocker, SessionDefaults,
- SessionOrigin, SessionRepository, SpawnContainer,
+ AgentKind, AgentRuntimeConfig, AnnounceOrigin, CommandOutcome, DeclinedMention, DeliverAction,
+ HarnessCommand, HarnessDefaults, MentionOrigin, OpenSession, PromptPeople, SessionBlocker,
+ SessionDefaults, SessionOrigin, SessionRepository, SpawnContainer,
};
use crate::domain::ports::{
AgentPromptComposer, ContainerManager as _, MessagePromptContext, NoPeers,
@@ -108,10 +110,31 @@ fn open_command() -> OpenSession {
sender: sender(),
content: "@claude fix the failing test".to_owned(),
attachments: vec![],
+ context: Some(trigger()),
}),
}
}
+/// Why the agent was called, as a trigger event carries it.
+fn trigger() -> TriggerContext {
+ TriggerContext::Mentioned(DiscussionContext {
+ surface: DiscussionSurface::Channel {
+ id: Uuid::from_u128(0xf0),
+ name: Some("eng".to_owned()),
+ channel_type: ChannelType::Public,
+ },
+ prompt_message_id: Uuid::from_u128(0xf2),
+ sender: ContextPerson {
+ id: "macro|[email protected]".to_owned(),
+ name: "[email protected]".to_owned(),
+ email: Some("[email protected]".to_owned()),
+ },
+ reply_target: ReplyTarget::None,
+ thread: None,
+ channel: Vec::new(),
+ })
+}
+
fn mention_origin(command: &OpenSession) -> &MentionOrigin {
let SessionOrigin::Mention(origin) = &command.origin else {
panic!("expected a mention");
@@ -131,41 +154,28 @@ fn mention_origin_mut(command: &mut OpenSession) -> &mut MentionOrigin {
fn forward_message(content: &str) -> DeliverAction {
// Staff: `disconnected_session` is a Daytona coder bot, and the
// execute() gate admits only macro.com actors onto those.
- DeliverAction::prompt(
- AgentAction::prompt(content),
- Some(staff_sender()),
- Some(AnnounceOrigin {
- reuse_origin_message: false,
- 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),
- }),
- )
+ DeliverAction {
+ context: Some(trigger()),
+ ..DeliverAction::prompt(
+ AgentAction::prompt(content),
+ Some(staff_sender()),
+ Some(AnnounceOrigin {
+ reuse_origin_message: false,
+ 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),
+ }),
+ )
+ }
}
#[derive(Clone, Default)]
struct PromptContextMock {
- context: Arc<Mutex<ConversationContext>>,
- failure: Arc<Mutex<Option<String>>>,
unauthorized: Arc<Mutex<Option<String>>>,
authorized: Arc<Mutex<Vec<(MacroUserIdStr<'static>, AnnounceOrigin)>>>,
}
impl PromptContextMock {
- fn with_context(context: ConversationContext) -> Self {
- Self {
- context: Arc::new(Mutex::new(context)),
- ..Self::default()
- }
- }
-
- fn failing(message: &str) -> Self {
- Self {
- 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()))),
@@ -193,25 +203,13 @@ impl MessagePromptContext for PromptContextMock {
.push((actor.clone(), origin.clone()));
Ok(())
}
-
- async fn conversation_context(
- &self,
- _actor: &MacroUserIdStr<'static>,
- _origin: &AnnounceOrigin,
- ) -> crate::domain::error::Result<ConversationContext> {
- if let Some(message) = self.failure.lock().unwrap().clone() {
- return Err(HarnessError::PromptContext(rootcause::report!("{message}")));
- }
- Ok(self.context.lock().unwrap().clone())
- }
}
-type PromptCompositionCall = (String, Option<String>, Option<ConversationContext>);
+type PromptCompositionCall = (String, Option<String>, Option<TriggerContext>);
#[derive(Clone, Default)]
struct PromptComposerMock {
calls: Arc<Mutex<Vec<PromptCompositionCall>>>,
- parents: Arc<Mutex<Vec<Option<MessageParent>>>>,
people: Arc<Mutex<Vec<Option<PromptPeople>>>>,
failure: Arc<Mutex<Option<String>>>,
}
@@ -238,11 +236,9 @@ impl AgentPromptComposer for PromptComposerMock {
&self,
prompt_markdown: &str,
instructions: Option<&str>,
- parent: Option<&MessageParent>,
people: Option<&PromptPeople>,
- context: Option<&ConversationContext>,
+ context: Option<&TriggerContext>,
) -> crate::domain::error::Result<String> {
- self.parents.lock().unwrap().push(parent.cloned());
self.people.lock().unwrap().push(people.cloned());
self.calls.lock().unwrap().push((
prompt_markdown.to_owned(),
@@ -793,6 +789,7 @@ async fn claude_cloud_only_accepts_control_from_the_subscription_owner() {
action: AgentAction::prompt("spend another user's subscription"),
action_id: None,
actor,
+ context: None,
},
)
.await
@@ -806,6 +803,7 @@ async fn claude_cloud_only_accepts_control_from_the_subscription_owner() {
action: AgentAction::prompt("owner follow-up"),
action_id: None,
actor: Some(owner),
+ context: None,
},
);
let drive = async {
@@ -898,49 +896,6 @@ async fn revoked_origin_access_blocks_the_connect_cursor_reply() {
assert!(announcer.declined().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 {
- if containers.spawned() == 1 {
- break;
- }
- tokio::task::yield_now().await;
- }
- let container = containers.container(id).unwrap();
- complete_handshake(&container).await;
- container
- };
- let (result, container) = tokio::join!(open, drive);
-
- result.expect("context lookup is best-effort after Kafka admission");
- // Access precedes provisioning and queue admission, and is rechecked at
- // dispatch so a revocation while queued still stops the prompt.
- assert_eq!(context.authorized().len(), 3);
- assert_eq!(announcer.announced().len(), 1);
- assert_eq!(
- composer.calls(),
- [(
- "@claude fix the failing test".to_owned(),
- None,
- Some(ConversationContext::default())
- )]
- );
- assert_eq!(
- prompts(&container.agent()),
- [vec![ContentBlock::from(context_prompt(
- "@claude fix the failing test"
- ))]]
- );
-}
-
#[tokio::test]
async fn composer_failure_stops_open_delivery_and_keeps_the_prompt_queued() {
let composer = PromptComposerMock::failing("lexical unavailable");
@@ -975,28 +930,12 @@ async fn composer_failure_stops_open_delivery_and_keeps_the_prompt_queued() {
/// A mention snapshots the agent's instructions onto the session row, the
/// same as the create menu does, and a runtime without a system prompt gets
-/// them in its first prompt's hidden context, beside the conversation.
+/// them in its first prompt's hidden context, beside the trigger.
#[tokio::test]
async fn open_sends_context_and_agent_instructions_in_the_first_prompt() {
- let context = ConversationContext {
- channel: vec![ContextThread {
- root_id: Uuid::from_u128(40),
- messages: vec![ContextMessage {
- id: Uuid::from_u128(40),
- sender_id: "macro|[email protected]".to_owned(),
- author: "[email protected]".to_owned(),
- content: "previous channel message".to_owned(),
- posted_at: chrono::DateTime::UNIX_EPOCH,
- }],
- messages_omitted: false,
- }],
- ..ConversationContext::default()
- };
let composer = PromptComposerMock::default();
- let (service, repo, containers, announcer, _runtimes) = harness_with_edges(
- PromptContextMock::with_context(context.clone()),
- composer.clone(),
- );
+ let (service, repo, containers, announcer, _runtimes) =
+ harness_with_edges(PromptContextMock::default(), composer.clone());
let mut command = open_command();
command.runtime.instructions = "Diagnose first.".to_owned();
let raw = mention_origin(&command).content.clone();
@@ -1023,7 +962,7 @@ async fn open_sends_context_and_agent_instructions_in_the_first_prompt() {
[(
raw.clone(),
Some("Diagnose first.".to_owned()),
- Some(context)
+ Some(trigger())
)]
);
assert_eq!(
@@ -1061,46 +1000,6 @@ async fn open_stores_no_instructions_when_the_agent_has_only_blank_ones() {
assert_eq!(session.instructions, None);
}
-/// A mention in a document comment: the agent is told which mark the comment
-/// sits on and what that mark covered, so it can find the words the comment is
-/// about instead of guessing from the comment body.
-#[tokio::test]
-async fn open_sends_the_comment_anchor_the_prompt_was_posted_on() {
- let context = ConversationContext {
- anchor: Some(CommentAnchor::Mark {
- mark_id: "0199f3d4-0000-7000-8000-00000000000a".to_owned(),
- marked_text: Some("the marked phrase".to_owned()),
- current: None,
- }),
- ..ConversationContext::default()
- };
- let composer = PromptComposerMock::default();
- let (service, _repo, containers, _announcer, _runtimes) = harness_with_edges(
- PromptContextMock::with_context(context.clone()),
- composer.clone(),
- );
- let command = open_command();
- let raw = mention_origin(&command).content.clone();
- let id = AgentSessionId::new();
-
- let open = service.execute(id, HarnessCommand::Open(command));
- let drive = async {
- loop {
- if containers.spawned() == 1 {
- break;
- }
- tokio::task::yield_now().await;
- }
- let container = containers.container(id).unwrap();
- complete_handshake(&container).await;
- container
- };
- let (result, _container) = tokio::join!(open, drive);
- result.unwrap();
-
- assert_eq!(composer.calls(), [(raw, None, Some(context))]);
-}
-
/// A provider mention from someone missing account setup: the bot answers in
/// the thread with what to connect, and nothing is created for a session
/// that could never spawn - no row, no egress token, no chip.
@@ -1277,7 +1176,7 @@ async fn forward_to_a_live_session_reuses_the_transport() {
Some(&(
"and add a regression test".to_owned(),
None,
- Some(ConversationContext::default())
+ Some(trigger())
))
);
assert_eq!(
@@ -1448,11 +1347,7 @@ async fn composer_failure_stops_follow_up_announcement_and_delivery() {
assert!(matches!(result, Err(HarnessError::PromptComposition(_))));
assert_eq!(
composer.calls().last(),
- Some(&(
- "do not deliver this".to_owned(),
- None,
- Some(ConversationContext::default())
- ))
+ Some(&("do not deliver this".to_owned(), None, Some(trigger())))
);
assert_eq!(prompts(&container.agent()).len(), prompts_before);
assert_eq!(announcer.announced().len(), announcements_before);
@@ -1815,6 +1710,7 @@ async fn changing_the_model_persists_it_and_tells_the_running_agent() {
action: AgentAction::set_model("opus"),
action_id: None,
actor: Some(sender()),
+ context: None,
},
)
.await
@@ -1869,6 +1765,7 @@ async fn a_prompt_through_control_reaches_the_agent_without_announcing() {
action: AgentAction::prompt("and now the docs <user-content>unchanged</user-content>"),
action_id: None,
actor: Some(sender()),
+ context: None,
},
);
let agent = container.agent();
@@ -1915,6 +1812,7 @@ async fn a_non_staff_control_event_cannot_drive_a_sandboxed_coder_session() {
action: AgentAction::prompt("spend daytona credits"),
action_id: None,
actor: Some(sender()),
+ context: None,
},
)
.await
@@ -1985,6 +1883,7 @@ async fn an_external_bots_permission_request_waits_for_a_users_answer() {
action_id: None,
action: permission_answer("perm-1", "once"),
actor: Some(sender()),
+ context: None,
},
)
.await
@@ -2019,6 +1918,7 @@ async fn a_harness_principal_cannot_answer_a_permission_request() {
action_id: None,
action: permission_answer("perm-1", "always"),
actor: None,
+ context: None,
},
)
.await
@@ -2059,6 +1959,7 @@ async fn answering_a_disconnected_session_does_not_wake_its_sandbox() {
action_id: None,
action: permission_answer("perm-1", "once"),
actor: Some(staff_sender()),
+ context: None,
},
)
.await
@@ -2085,6 +1986,7 @@ async fn an_archived_session_rejects_new_controls() {
action: AgentAction::prompt("do not send"),
action_id: None,
actor: Some(staff_sender()),
+ context: None,
},
)
.await
@@ -2119,6 +2021,7 @@ async fn a_staff_control_event_can_drive_a_sandboxed_coder_session() {
action: AgentAction::prompt("continue"),
action_id: None,
actor: Some(staff_sender()),
+ context: None,
},
)
.await
@@ -2170,6 +2073,7 @@ async fn a_prompt_during_a_running_turn_queues_and_dispatches_when_it_ends() {
action: AgentAction::prompt("and then this"),
action_id: None,
actor: Some(sender()),
+ context: None,
},
)
.await
@@ -2218,6 +2122,7 @@ async fn a_queued_prompt_survives_a_replica_restart() {
action: AgentAction::prompt("remember me after restart"),
action_id: None,
actor: Some(sender()),
+ context: None,
},
)
.await
@@ -2256,6 +2161,7 @@ async fn a_resume_restores_the_persisted_queue() {
created_at: chrono::Utc::now(),
announce: None,
announced_message_id: None,
+ context: None,
}],
)
.await
@@ -2267,6 +2173,7 @@ async fn a_resume_restores_the_persisted_queue() {
action: AgentAction::prompt("wake up"),
action_id: None,
actor: Some(staff_sender()),
+ context: None,
},
);
let drive_resume = async {
@@ -2315,6 +2222,7 @@ async fn archiving_drops_prompts_queued_behind_a_running_turn() {
action: AgentAction::prompt("do not dispatch"),
action_id: None,
actor: Some(sender()),
+ context: None,
},
)
.await
@@ -2349,6 +2257,7 @@ async fn a_stop_cancels_the_turn_and_the_queue_keeps_draining() {
action: AgentAction::prompt("still wanted after the stop"),
action_id: None,
actor: Some(sender()),
+ context: None,
},
)
.await
@@ -2366,6 +2275,7 @@ async fn a_stop_cancels_the_turn_and_the_queue_keeps_draining() {
action: AgentAction::Stop,
action_id: None,
actor: Some(sender()),
+ context: None,
},
)
.await
@@ -2421,6 +2331,7 @@ async fn a_channel_follow_up_stops_the_running_turn_announces_and_flushes() {
action: AgentAction::prompt("queued earlier from the session page"),
action_id: None,
actor: Some(staff_sender()),
+ context: None,
},
)
.await
@@ -2544,6 +2455,7 @@ async fn queued_prompts_are_editable_and_removable_until_dispatch() {
action: AgentAction::prompt(text),
action_id: None,
actor: Some(sender()),
+ context: None,
};
let second = service.control_event(id, prompt("second")).await.unwrap();
let third = service.control_event(id, prompt("third")).await.unwrap();
@@ -2605,6 +2517,7 @@ async fn steering_a_later_queued_prompt_runs_it_ahead_of_earlier_ones() {
action: AgentAction::prompt(text),
action_id: None,
actor: Some(sender()),
+ context: None,
};
let first = service
.control_event(id, prompt("first waiting"))
@@ -2666,6 +2579,7 @@ async fn a_model_change_bypasses_the_running_turn() {
action: AgentAction::set_model("opus"),
action_id: None,
actor: Some(sender()),
+ context: None,
},
)
.await
@@ -2701,6 +2615,7 @@ async fn a_control_event_is_accepted_under_the_callers_own_action_id() {
action: AgentAction::prompt("speculated by the caller"),
action_id: Some(action_id),
actor: Some(sender()),
+ context: None,
},
)
.await
@@ -2736,6 +2651,7 @@ async fn a_control_event_without_an_action_id_is_given_a_fresh_one() {
action: AgentAction::prompt(text),
action_id: None,
actor: Some(sender()),
+ context: None,
};
let first = service.control_event(id, unnamed("first")).await.unwrap();
let second = service.control_event(id, unnamed("second")).await.unwrap();
@@ -2770,6 +2686,7 @@ async fn re_sending_a_waiting_action_id_does_not_queue_it_twice() {
action: AgentAction::prompt("said once"),
action_id: Some(action_id),
actor: Some(sender()),
+ context: None,
};
let first = service.control_event(id, retried()).await.unwrap();
let again = service.control_event(id, retried()).await.unwrap();
@@ -2799,6 +2716,7 @@ async fn compact_through_control_reaches_opencode_as_a_slash_command() {
action: AgentAction::Compact,
action_id: None,
actor: Some(sender()),
+ context: None,
},
);
let agent = container.agent();
@@ -2829,6 +2747,7 @@ async fn a_prompt_through_control_resumes_a_disconnected_session() {
action: AgentAction::prompt("wake up"),
action_id: None,
actor: Some(staff_sender()),
+ context: None,
},
);
let drive_resume = async {
@@ -3001,6 +2920,7 @@ async fn an_external_open_provisions_nothing_and_prompts_nobody() {
action: AgentAction::prompt("@claude fix the failing test"),
action_id: None,
actor: Some(sender()),
+ context: None,
},
);
let (result, ()) = tokio::join!(prompted, complete_bound_handshake(&runtime));
@@ -3287,6 +3207,7 @@ async fn a_managed_session_resumes_its_sandbox_rather_than_a_dialed_in_runtime()
action: AgentAction::prompt("wake up"),
action_id: None,
actor: Some(staff_sender()),
+ context: None,
},
);
let drive_resume = async {
@@ -4173,6 +4094,7 @@ mod lifecycle_events {
action: AgentAction::prompt(text),
action_id: None,
actor: Some(staff_sender()),
+ context: None,
};
service
.control_event(id, prompt("first"))
@@ -4260,6 +4182,7 @@ mod lifecycle_events {
),
action_id: None,
actor: Some(staff_sender()),
+ context: None,
})),
)
.await
@@ -4791,6 +4714,7 @@ async fn a_non_staff_session_editor_can_approve_a_managed_session_request() {
action_id: None,
action: permission_answer("editor-approval", "once"),
actor: Some(sender()),
+ context: None,
},
)
.await
diff --git a/crates/agent_harness/src/domain/service/test/chat_reply.rs b/crates/agent_harness/src/domain/service/test/chat_reply.rs
index a754afb35d..0f671f19e9 100644
--- a/crates/agent_harness/src/domain/service/test/chat_reply.rs
+++ b/crates/agent_harness/src/domain/service/test/chat_reply.rs
@@ -24,6 +24,7 @@ fn assignment_open_command() -> OpenSession {
discussion_id: macro_uuid::generate_uuid_v7(),
actor: sender(),
prompt: "Private assignment instructions".to_owned(),
+ context: None,
});
command
}
@@ -53,8 +54,7 @@ async fn assignment_instructions_reach_system_and_prompt_only_runtimes() {
calls[0].1.as_deref(),
kind.folds_instructions().then_some(instructions.as_str())
);
- assert_eq!(calls[0].2, Some(ConversationContext::default()));
- assert_eq!(*composer.parents.lock().unwrap(), vec![None]);
+ assert_eq!(calls[0].2, None);
assert!(!context.authorized().is_empty());
}
}
@@ -461,6 +461,7 @@ mod elicitation {
),
action_id: None,
actor: Some(sender()),
+ context: None,
})),
)
.await
diff --git a/crates/agent_harness/src/domain/service/test/coding_preferences.rs b/crates/agent_harness/src/domain/service/test/coding_preferences.rs
index 2e105fa844..cd782db946 100644
--- a/crates/agent_harness/src/domain/service/test/coding_preferences.rs
+++ b/crates/agent_harness/src/domain/service/test/coding_preferences.rs
@@ -38,6 +38,7 @@ fn assignment_command(kind: AgentKind, harness: &str) -> OpenSession {
discussion_id: macro_uuid::generate_uuid_v7(),
actor: sender(),
prompt: "Private assignment instructions".to_owned(),
+ context: None,
});
command
}
diff --git a/crates/agent_harness/src/domain/service/test/quota.rs b/crates/agent_harness/src/domain/service/test/quota.rs
index 934099e554..a296d54553 100644
--- a/crates/agent_harness/src/domain/service/test/quota.rs
+++ b/crates/agent_harness/src/domain/service/test/quota.rs
@@ -81,6 +81,7 @@ fn action(action: AgentAction) -> DeliverAction {
action,
actor: Some(staff_sender()),
announce: None,
+ context: None,
}
}
@@ -123,6 +124,7 @@ async fn denied_or_unavailable_trigger_open_has_no_side_effects() {
discussion_id: macro_uuid::generate_uuid_v7(),
actor: staff_sender(),
prompt: "Work on this task".to_owned(),
+ context: None,
}),
] {
admission.calls.lock().unwrap().clear();
@@ -714,6 +716,7 @@ async fn rejection_persistence_failure_keeps_work_and_defers_reply_resolution()
announce: command.announce,
announced: Some(macro_uuid::generate_uuid_v7()),
created_at: chrono::Utc::now(),
+ context: None,
};
let stored = entry.to_stored().unwrap();
let mut sessions = MockAgentSessionService::new();
diff --git a/crates/agent_harness/src/domain/service/warm.rs b/crates/agent_harness/src/domain/service/warm.rs
index a1bdf12217..5caa581bfa 100644
--- a/crates/agent_harness/src/domain/service/warm.rs
+++ b/crates/agent_harness/src/domain/service/warm.rs
@@ -198,6 +198,7 @@ where
action: AgentAction::prompt(prompt),
actor: Some(owner_user),
announce: None,
+ context: None,
}),
)
.await
@@ -352,6 +353,7 @@ where
action: AgentAction::prompt(raw_prompt),
actor: Some(owner_user),
announce: None,
+ context: None,
}),
)
.await
diff --git a/crates/agent_harness/src/domain/trigger_router.rs b/crates/agent_harness/src/domain/trigger_router.rs
index 534368a44c..a093de5600 100644
--- a/crates/agent_harness/src/domain/trigger_router.rs
+++ b/crates/agent_harness/src/domain/trigger_router.rs
@@ -4,6 +4,7 @@ use agent_session::domain::model::AgentSessionId;
use agent_trigger::domain::broker_events::{
AgentTriggerTopicEvent, NewAgentSessionEvent, OpeningMention, SessionMessage,
};
+use agent_trigger::domain::task_assignment::assignment_instructions;
use bot_id::BotId;
use agent_runtime_protocol::domain::action::AgentAction;
@@ -15,6 +16,10 @@ use super::model::{
/// What one trigger event asks this deployment to do.
#[derive(Debug, Clone)]
+#[allow(
+ clippy::large_enum_variant,
+ reason = "a command carries its prompt's context; boxing would only move the size"
+)]
pub enum RoutedTrigger {
/// Run a harness command for the managed bot's session.
Command(AgentSessionId, HarnessCommand),
@@ -67,16 +72,28 @@ pub fn route_agent_trigger(
bot_id: assigned.bot_id,
runtime,
origin: SessionOrigin::TaskAssignment(TaskAssignmentOrigin {
+ // The task travels in the context; the prompt is only
+ // what to do with it. Events from producers that
+ // predate the context carry the whole brief instead.
+ prompt: match &assigned.context {
+ Some(_) => assignment_instructions(&assigned.parent),
+ None => assigned.prompt,
+ },
parent: assigned.parent,
discussion_id: assigned.discussion_id,
actor: assigned.actor,
- prompt: assigned.prompt,
+ context: assigned.context,
}),
}),
))
}
AgentTriggerTopicEvent::New(event) => {
- let Some(OpeningMention { bot_id, message }) = event.mention() else {
+ let Some(OpeningMention {
+ bot_id,
+ message,
+ context,
+ }) = event.mention()
+ else {
return Err(Skipped::Unrecognized);
};
let Some(runtime) = runtime.filter(|runtime| runtime.kind.is_managed()) else {
@@ -101,6 +118,7 @@ pub fn route_agent_trigger(
sender,
content: message.content,
attachments: links.prompt_attachments(&message.attachments),
+ context,
}),
}),
))
@@ -111,6 +129,7 @@ pub fn route_agent_trigger(
session_id,
kind: _,
message,
+ context,
}) = event.session_message()
else {
return Err(Skipped::Unrecognized);
@@ -127,14 +146,17 @@ pub fn route_agent_trigger(
if kind.is_managed() {
return Ok(RoutedTrigger::Command(
session_id,
- HarnessCommand::Deliver(DeliverAction::prompt(
- AgentAction::prompt_with_attachments(
- message.content,
- links.prompt_attachments(&message.attachments),
- ),
- message.sender.as_user().cloned(),
- Some(origin),
- )),
+ HarnessCommand::Deliver(DeliverAction {
+ context,
+ ..DeliverAction::prompt(
+ AgentAction::prompt_with_attachments(
+ message.content,
+ links.prompt_attachments(&message.attachments),
+ ),
+ message.sender.as_user().cloned(),
+ Some(origin),
+ )
+ }),
));
}
let sender = message
diff --git a/crates/agent_harness/src/inbound/kafka/test.rs b/crates/agent_harness/src/inbound/kafka/test.rs
index baa0f47d44..672cb27b3f 100644
--- a/crates/agent_harness/src/inbound/kafka/test.rs
+++ b/crates/agent_harness/src/inbound/kafka/test.rs
@@ -14,6 +14,10 @@ use macro_user_id::user_id::MacroUserIdStr;
use macro_uuid::Uuid;
use messages::domain::events::MessagePostedMetadata;
use messages::domain::models::MessageParent;
+use trigger_context::{
+ AddressedBy, ContextPerson, DiscussionContext, DiscussionSurface, FollowUpContext, ReplyTarget,
+ TaskAssignedContext, TaskSnapshot, TriggerContext,
+};
use super::*;
use crate::domain::model::{
@@ -97,6 +101,7 @@ fn mentioned(bot: BotId, sender: ChannelSender<'static>) -> AgentTriggerTopicEve
AgentBotMentionedEvent {
bot_id: bot,
message: message(sender),
+ context: None,
},
))
}
@@ -107,6 +112,7 @@ fn channel_message(bot: BotId) -> AgentTriggerTopicEvent {
session_id: AgentSessionId::TEST_A,
kind: ThreadMessageKind::MentionThread,
message: message(ChannelSender::new_from_user(user())),
+ context: None,
}))
}
@@ -142,6 +148,7 @@ fn a_threaded_mention_answers_into_its_thread() {
AgentBotMentionedEvent {
bot_id: BotId::TEST_A,
message: event,
+ context: None,
},
));
@@ -265,6 +272,7 @@ fn a_bot_authored_external_channel_message_is_skipped() {
session_id: AgentSessionId::TEST_A,
kind: ThreadMessageKind::MentionThread,
message: message(ChannelSender::new_from_bot(BotId::TEST_B)),
+ context: None,
},
));
assert_eq!(
@@ -279,6 +287,7 @@ fn channel_message_from(bot: BotId, sender: ChannelSender<'static>) -> AgentTrig
session_id: AgentSessionId::TEST_A,
kind: ThreadMessageKind::MentionThread,
message: message(sender),
+ context: None,
}))
}
@@ -290,6 +299,7 @@ fn a_document_mention_opens_and_follows_up_on_its_document() {
AgentTriggerTopicEvent::New(NewAgentSessionEvent::Mentioned(AgentMentionedEvent {
bot_id: BotId::TEST_A,
message: document_message(ChannelSender::new_from_user(user())),
+ context: None,
}));
let RoutedTrigger::Command(_, HarnessCommand::Open(open)) =
route_agent_trigger(opened, runtime(AgentKind::InMemory), &links())
@@ -306,6 +316,7 @@ fn a_document_mention_opens_and_follows_up_on_its_document() {
session_id: AgentSessionId::TEST_A,
kind: ThreadMessageKind::MentionThread,
message: document_message(ChannelSender::new_from_user(user())),
+ context: None,
}));
let RoutedTrigger::Announce(session_id, prompt) =
route_agent_trigger(followed, None, &links()).expect("an external follow-up announces")
@@ -324,6 +335,7 @@ fn assigned_to_task() -> AgentTriggerTopicEvent {
discussion_id: Uuid::from_u128(2),
actor: user(),
prompt: "Complete the assigned task".to_owned(),
+ context: None,
},
))
}
@@ -348,6 +360,95 @@ fn assigning_a_managed_agent_opens_on_the_task_discussion() {
assert_eq!(origin.prompt, "Complete the assigned task");
}
+/// With the task in the context, the prompt is only what to do with it, so
+/// the task body is not sent to the agent twice.
+#[test]
+fn an_assignment_with_context_prompts_with_instructions_and_carries_the_task() {
+ let context = TriggerContext::TaskAssigned(TaskAssignedContext {
+ task: TaskSnapshot {
+ id: "doc".to_owned(),
+ title: "Fix the scroll".to_owned(),
+ markdown: "The popover scrolls the page.".to_owned(),
+ status: None,
+ priority: None,
+ due: None,
+ assignees: Vec::new(),
+ project: None,
+ },
+ assigned_by: ContextPerson {
+ id: "macro|[email protected]".to_owned(),
+ name: "[email protected]".to_owned(),
+ email: Some("[email protected]".to_owned()),
+ },
+ assigned_at: chrono::DateTime::UNIX_EPOCH,
+ discussion_id: Uuid::from_u128(2),
+ });
+ let AgentTriggerTopicEvent::New(NewAgentSessionEvent::AssignedToTask(mut assigned)) =
+ assigned_to_task()
+ else {
+ unreachable!();
+ };
+ assigned.context = Some(context.clone());
+ let event = AgentTriggerTopicEvent::New(NewAgentSessionEvent::AssignedToTask(assigned));
+
+ let RoutedTrigger::Command(_, HarnessCommand::Open(open)) =
+ route_agent_trigger(event, runtime(AgentKind::InMemory), &links())
+ .expect("a managed assignment opens a session")
+ else {
+ panic!("an assignment should open a session");
+ };
+ let SessionOrigin::TaskAssignment(origin) = open.origin else {
+ panic!("an assignment must retain its own origin");
+ };
+ assert_eq!(
+ origin.prompt,
+ agent_trigger::domain::task_assignment::assignment_instructions(&document())
+ );
+ assert_eq!(origin.context, Some(context));
+}
+
+/// A follow-up's context rides on the delivery, to be composed at dispatch.
+#[test]
+fn a_managed_follow_up_carries_its_context_to_delivery() {
+ let context = TriggerContext::FollowUp(FollowUpContext {
+ addressed_by: AddressedBy::Inferred,
+ discussion: DiscussionContext {
+ surface: DiscussionSurface::DocumentComment {
+ id: "doc".to_owned(),
+ name: "Spec".to_owned(),
+ anchor: None,
+ },
+ prompt_message_id: Uuid::from_u128(2),
+ sender: ContextPerson {
+ id: "macro|[email protected]".to_owned(),
+ name: "[email protected]".to_owned(),
+ email: Some("[email protected]".to_owned()),
+ },
+ reply_target: ReplyTarget::Thread {
+ root_id: Uuid::from_u128(2),
+ },
+ thread: None,
+ channel: Vec::new(),
+ },
+ });
+ let followed =
+ AgentTriggerTopicEvent::Existing(ExistingAgentSessionEvent::Thread(ThreadEventMetadata {
+ bot_id: BotId::TEST_A,
+ session_id: AgentSessionId::TEST_A,
+ kind: ThreadMessageKind::Inferred,
+ message: document_message(ChannelSender::new_from_user(user())),
+ context: Some(context.clone()),
+ }));
+
+ let RoutedTrigger::Command(_, HarnessCommand::Deliver(deliver)) =
+ route_agent_trigger(followed, runtime(AgentKind::InMemory), &links())
+ .expect("a managed follow-up delivers")
+ else {
+ panic!("a managed follow-up should deliver");
+ };
+ assert_eq!(deliver.context, Some(context));
+}
+
#[test]
fn assigning_an_external_agent_leaves_session_creation_to_its_runtime() {
assert_eq!(
@@ -373,6 +474,7 @@ fn task_discussion_followups_keep_the_managed_and_external_session_origin() {
content: "Include a regression test".to_owned(),
..document_message(ChannelSender::new_from_user(user()))
},
+ context: None,
}));
let RoutedTrigger::Command(session_id, HarnessCommand::Deliver(deliver)) =
route_agent_trigger(followed.clone(), runtime(AgentKind::InMemory), &links())
@@ -478,6 +580,7 @@ fn a_mention_with_attached_files_opens_with_them_as_prompt_attachments() {
AgentBotMentionedEvent {
bot_id: BotId::TEST_A,
message: message_with_files(ChannelSender::new_from_user(user())),
+ context: None,
},
));
let routed = route_agent_trigger(event, runtime(AgentKind::InMemory), &links()).unwrap();
@@ -509,6 +612,7 @@ fn a_managed_channel_message_with_files_delivers_them_as_prompt_attachments() {
session_id: AgentSessionId::TEST_A,
kind: ThreadMessageKind::MentionThread,
message: message_with_files(ChannelSender::new_from_user(user())),
+ context: None,
},
));
let routed = route_agent_trigger(event, runtime(AgentKind::SandboxedCoder), &links()).unwrap();
diff --git a/crates/agent_harness/src/outbound/agent_prompt_composer.rs b/crates/agent_harness/src/outbound/agent_prompt_composer.rs
index 55f630f1b2..4070874332 100644
--- a/crates/agent_harness/src/outbound/agent_prompt_composer.rs
+++ b/crates/agent_harness/src/outbound/agent_prompt_composer.rs
@@ -1,16 +1,12 @@
-//! Compose channel context for every harness.
+//! Compose trigger context for every harness.
use lexical_client::LexicalClient;
-use lexical_client::parse_markdown::{
- AgentContext, AgentContextAnchor, AgentContextMessage, AgentContextPeople, AgentContextPerson,
- AgentContextReplyTarget, AgentContextThread,
-};
+use lexical_client::parse_markdown::{AgentContextPeople, AgentContextPerson};
use macro_user_id::user_id::MacroUserIdStr;
+use trigger_context::TriggerContext;
use crate::domain::error::{HarnessError, Result};
-use crate::domain::model::{
- CommentAnchor, ContextMessage, ContextThread, ConversationContext, PromptPeople, ReplyTarget,
-};
+use crate::domain::model::PromptPeople;
use crate::domain::ports::AgentPromptComposer;
/// Lexical-service-backed agent prompt composer.
@@ -30,30 +26,15 @@ impl AgentPromptComposer for LexicalAgentPromptComposer {
&self,
prompt_markdown: &str,
instructions: Option<&str>,
- parent: Option<&messages::domain::models::MessageParent>,
people: Option<&PromptPeople>,
- context: Option<&ConversationContext>,
+ trigger: Option<&TriggerContext>,
) -> Result<String> {
let people = people.map(|people| AgentContextPeople {
owner: person(&people.owner),
sender: people.sender.as_ref().map(person),
});
- let context = context.map(|context| AgentContext {
- anchor: context.anchor.as_ref().map(anchor),
- reply_target: context.reply_target.as_ref().map(reply_target),
- prompt_message_id: context.prompt_message_id.map(|id| id.to_string()),
- thread: context.thread.as_ref().map(thread),
- channel: context.channel.iter().map(thread).collect(),
- });
-
self.lexical
- .compose_agent_context(
- prompt_markdown,
- instructions,
- parent,
- people.as_ref(),
- context.as_ref(),
- )
+ .compose_agent_context(prompt_markdown, instructions, people.as_ref(), trigger)
.await
.map_err(|error| HarnessError::PromptComposition(rootcause::report!(error).into()))
}
@@ -67,77 +48,5 @@ fn person<'a>(user: &'a MacroUserIdStr<'static>) -> AgentContextPerson<'a> {
}
}
-fn anchor(anchor: &CommentAnchor) -> AgentContextAnchor<'_> {
- match anchor {
- CommentAnchor::Spreadsheet {
- sheet_id,
- sheet_name,
- range,
- } => AgentContextAnchor::Spreadsheet {
- sheet_id,
- sheet_name,
- range,
- },
- CommentAnchor::Mark {
- mark_id,
- marked_text,
- current,
- } => AgentContextAnchor::Markdown {
- mark_id,
- marked_text: marked_text.as_deref(),
- current_marked_text: current.as_ref().map(|c| c.marked_text.as_str()),
- surrounding_text: current.as_ref().map(|c| c.surrounding_text.as_str()),
- },
- CommentAnchor::PdfHighlight {
- anchor_id,
- marked_text,
- } => AgentContextAnchor::PdfHighlight {
- anchor_id,
- marked_text: marked_text.as_deref(),
- },
- CommentAnchor::PdfPin { anchor_id } => AgentContextAnchor::PdfPin { anchor_id },
- }
-}
-
-fn reply_target(target: &ReplyTarget) -> AgentContextReplyTarget<'_> {
- match target {
- ReplyTarget::Quote {
- message_id,
- thread_id,
- preview,
- message: quoted,
- } => AgentContextReplyTarget::Quote {
- message_id: message_id.to_string(),
- thread_id: thread_id.to_string(),
- preview,
- message: quoted.as_ref().map(message),
- },
- ReplyTarget::Thread { root_id } => AgentContextReplyTarget::Thread {
- thread_id: root_id.to_string(),
- },
- ReplyTarget::None => AgentContextReplyTarget::None,
- }
-}
-
-fn thread(thread: &ContextThread) -> AgentContextThread<'_> {
- AgentContextThread {
- root_id: thread.root_id.to_string(),
- messages: thread.messages.iter().map(message).collect(),
- messages_omitted: thread.messages_omitted,
- }
-}
-
-fn message(message: &ContextMessage) -> AgentContextMessage<'_> {
- AgentContextMessage {
- id: message.id.to_string(),
- sender_id: &message.sender_id,
- author: &message.author,
- content: &message.content,
- posted_at: message
- .posted_at
- .to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
- }
-}
-
#[cfg(test)]
mod test;
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 151f6b6568..eb9675aded 100644
--- a/crates/agent_harness/src/outbound/agent_prompt_composer/test.rs
+++ b/crates/agent_harness/src/outbound/agent_prompt_composer/test.rs
@@ -1,40 +1,14 @@
use super::*;
-use crate::domain::model::{
- CommentAnchor, ContextMessage, ContextThread, MarkedPassage, PromptPeople, ReplyTarget,
-};
use axum::{Json, Router, routing::post};
-use macro_uuid::Uuid;
+use chrono::{TimeZone, Utc};
use std::sync::{Arc, Mutex};
+use trigger_context::{ContextPerson, ProjectRef, TaskAssignedContext, TaskSnapshot};
+use uuid::Uuid;
+/// The trigger crosses a service boundary, so the body the lexical service
+/// validates is asserted here rather than only in its own types.
#[tokio::test]
-async fn composition_preserves_lexical_output_without_tool_instructions() {
- let app = Router::new().route(
- "/agent-context",
- post(|| async { Json(serde_json::json!({ "markdown": "Sanitized prompt and context" })) }),
- );
- let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
- let address = listener.local_addr().unwrap();
- let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
- let composer = LexicalAgentPromptComposer::new(LexicalClient::new(
- "test".into(),
- format!("http://{address}"),
- ));
-
- for context in [None, Some(&ConversationContext::default())] {
- let prompt = composer
- .compose("Raw prompt", None, None, None, context)
- .await
- .unwrap();
- assert_eq!(prompt, "Sanitized prompt and context");
- assert!(!prompt.contains("set_pull_request"));
- }
- server.abort();
-}
-
-/// The comment anchor crosses a service boundary, so the shape the lexical
-/// service validates is asserted here rather than only in its own types.
-#[tokio::test]
-async fn the_comment_anchor_reaches_the_lexical_service_beside_the_history() {
+async fn the_trigger_reaches_the_lexical_service_beside_the_people() {
let received: Arc<Mutex<Option<serde_json::Value>>> = Arc::default();
let seen = received.clone();
let app = Router::new().route(
@@ -54,225 +28,78 @@ async fn the_comment_anchor_reaches_the_lexical_service_beside_the_history() {
"test".into(),
format!("http://{address}"),
));
-
- composer
- .compose(
- "Raw prompt",
- Some("Never force-push."),
- None,
- None,
- Some(&ConversationContext {
- anchor: Some(CommentAnchor::Mark {
- mark_id: "mark-1".to_owned(),
- marked_text: Some("the marked phrase".to_owned()),
- current: Some(MarkedPassage {
- marked_text: "the edited phrase".to_owned(),
- surrounding_text: "Around the edited phrase.".to_owned(),
- }),
- }),
- ..ConversationContext::default()
+ let owner = MacroUserIdStr::try_from_email("[email protected]").unwrap();
+ let trigger = TriggerContext::TaskAssigned(TaskAssignedContext {
+ task: TaskSnapshot {
+ id: "task-1".to_owned(),
+ title: "Fix calendar popover scroll".to_owned(),
+ markdown: "The popover scrolls the page behind it.".to_owned(),
+ status: Some("Todo".to_owned()),
+ priority: None,
+ due: None,
+ assignees: Vec::new(),
+ project: Some(ProjectRef {
+ id: Uuid::from_u128(0xA1),
+ name: "Calendar polish".to_owned(),
}),
- )
- .await
- .unwrap();
- let body = received.lock().unwrap().clone().unwrap();
- assert_eq!(body["anchor"]["type"], "markdown");
- assert_eq!(body["anchor"]["markId"], "mark-1");
- assert_eq!(body["anchor"]["markedText"], "the marked phrase");
- assert_eq!(body["anchor"]["currentMarkedText"], "the edited phrase");
- assert_eq!(
- body["anchor"]["surroundingText"],
- "Around the edited phrase."
- );
- assert_eq!(body["instructions"], "Never force-push.");
+ },
+ assigned_by: ContextPerson {
+ id: "macro|[email protected]".to_owned(),
+ name: "Julia".to_owned(),
+ email: Some("[email protected]".to_owned()),
+ },
+ assigned_at: Utc.with_ymd_and_hms(2026, 10, 8, 14, 2, 0).unwrap(),
+ discussion_id: Uuid::from_u128(0xD1),
+ });
- // A thread anchored before snapshots existed still names its mark.
- composer
+ let composed = composer
.compose(
- "Raw prompt",
- None,
- None,
- None,
- Some(&ConversationContext {
- anchor: Some(CommentAnchor::Mark {
- mark_id: "mark-2".to_owned(),
- marked_text: None,
- current: None,
- }),
- ..ConversationContext::default()
+ "Work on the task",
+ Some("Be brief."),
+ Some(&PromptPeople {
+ owner: owner.clone(),
+ sender: Some(owner),
}),
+ Some(&trigger),
)
.await
.unwrap();
- let body = received.lock().unwrap().clone().unwrap();
- assert_eq!(body["anchor"]["markId"], "mark-2");
- assert!(body["anchor"].get("markedText").is_none());
- assert!(body["anchor"].get("currentMarkedText").is_none());
- let sent = |anchor: CommentAnchor| {
- let composer = &composer;
- let received = received.clone();
- async move {
- composer
- .compose(
- "Raw prompt",
- None,
- None,
- None,
- Some(&ConversationContext {
- anchor: Some(anchor),
- ..ConversationContext::default()
- }),
- )
- .await
- .unwrap();
- received.lock().unwrap().clone().unwrap()["anchor"].clone()
- }
- };
+ assert_eq!(composed, "composed");
assert_eq!(
- sent(CommentAnchor::PdfHighlight {
- anchor_id: "highlight-1".to_owned(),
- marked_text: Some("the highlighted words".to_owned()),
- })
- .await,
+ received.lock().unwrap().take().unwrap(),
serde_json::json!({
- "type": "pdfHighlight",
- "anchorId": "highlight-1",
- "markedText": "the highlighted words"
- })
- );
- assert_eq!(
- sent(CommentAnchor::PdfHighlight {
- anchor_id: "highlight-2".to_owned(),
- marked_text: None,
- })
- .await,
- serde_json::json!({ "type": "pdfHighlight", "anchorId": "highlight-2" })
- );
- assert_eq!(
- sent(CommentAnchor::PdfPin {
- anchor_id: "pin-1".to_owned(),
- })
- .await,
- serde_json::json!({ "type": "pdfPin", "anchorId": "pin-1" })
- );
- assert_eq!(
- sent(CommentAnchor::Spreadsheet {
- sheet_id: "sheet-1".into(),
- sheet_name: "Budget".into(),
- range: "B4:C9".into(),
- })
- .await,
- serde_json::json!({"type": "spreadsheet", "sheetId": "sheet-1", "sheetName": "Budget", "range": "B4:C9"})
- );
- server.abort();
-}
-
-fn context_message(id: u128, content: &str) -> ContextMessage {
- ContextMessage {
- id: Uuid::from_u128(id),
- sender_id: "macro|[email protected]".to_owned(),
- author: "[email protected]".to_owned(),
- content: content.to_owned(),
- posted_at: chrono::DateTime::from_timestamp(1_758_800_000, 0).unwrap(),
- }
-}
-
-/// The discussion, the channel around it, and the reply target cross a
-/// service boundary; the shape the lexical service validates is pinned here.
-#[tokio::test]
-async fn the_thread_channel_and_reply_target_reach_the_lexical_service() {
- let received: Arc<Mutex<Option<serde_json::Value>>> = Arc::default();
- let seen = received.clone();
- let app = Router::new().route(
- "/agent-context",
- post(move |Json(body): Json<serde_json::Value>| {
- let seen = seen.clone();
- async move {
- *seen.lock().unwrap() = Some(body);
- Json(serde_json::json!({ "markdown": "composed" }))
+ "promptMarkdown": "Work on the task",
+ "instructions": "Be brief.",
+ "owner": { "id": "macro|[email protected]", "name": "[email protected]" },
+ "sender": { "id": "macro|[email protected]", "name": "[email protected]" },
+ "trigger": {
+ "kind": "task_assigned",
+ "task": {
+ "id": "task-1",
+ "title": "Fix calendar popover scroll",
+ "markdown": "The popover scrolls the page behind it.",
+ "status": "Todo",
+ "project": {
+ "id": "00000000-0000-0000-0000-0000000000a1",
+ "name": "Calendar polish"
+ }
+ },
+ "assigned_by": {
+ "id": "macro|[email protected]",
+ "name": "Julia",
+ "email": "[email protected]"
+ },
+ "assigned_at": "2026-10-08T14:02:00Z",
+ "discussion_id": "00000000-0000-0000-0000-0000000000d1"
}
- }),
- );
- let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
- let address = listener.local_addr().unwrap();
- let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
- let composer = LexicalAgentPromptComposer::new(LexicalClient::new(
- "test".into(),
- format!("http://{address}"),
- ));
-
- let context = |reply_target| ConversationContext {
- reply_target: Some(reply_target),
- prompt_message_id: Some(Uuid::from_u128(3)),
- thread: Some(ContextThread {
- root_id: Uuid::from_u128(1),
- messages: vec![context_message(1, "the bug"), context_message(3, "fix it")],
- messages_omitted: false,
- }),
- channel: vec![ContextThread {
- root_id: Uuid::from_u128(5),
- messages: vec![context_message(6, "a reply elsewhere")],
- messages_omitted: true,
- }],
- ..ConversationContext::default()
- };
- let sent = |target| {
- let composer = &composer;
- let received = received.clone();
- let context = context(target);
- async move {
- composer
- .compose("Raw prompt", None, None, None, Some(&context))
- .await
- .unwrap();
- received.lock().unwrap().clone().unwrap()
- }
- };
-
- let body = sent(ReplyTarget::Thread {
- root_id: Uuid::from_u128(1),
- })
- .await;
- assert_eq!(
- body["replyTarget"],
- serde_json::json!({ "kind": "thread", "threadId": Uuid::from_u128(1).to_string() })
- );
- assert_eq!(body["promptMessageId"], Uuid::from_u128(3).to_string());
- assert_eq!(
- body["thread"]["messages"][0],
- serde_json::json!({
- "id": Uuid::from_u128(1).to_string(),
- "senderId": "macro|[email protected]",
- "author": "[email protected]",
- "content": "the bug",
- "postedAt": "2025-09-25T11:33:20Z",
})
);
- assert_eq!(body["thread"]["messagesOmitted"], false);
- assert_eq!(body["channel"][0]["rootId"], Uuid::from_u128(5).to_string());
- assert_eq!(body["channel"][0]["messagesOmitted"], true);
-
- let body = sent(ReplyTarget::Quote {
- message_id: Uuid::from_u128(1),
- thread_id: Uuid::from_u128(1),
- preview: "the bug".to_owned(),
- message: Some(context_message(1, "the bug")),
- })
- .await;
- assert_eq!(body["replyTarget"]["kind"], "quote");
- assert_eq!(body["replyTarget"]["preview"], "the bug");
- assert_eq!(body["replyTarget"]["message"]["content"], "the bug");
-
- let body = sent(ReplyTarget::None).await;
- assert_eq!(body["replyTarget"], serde_json::json!({ "kind": "none" }));
server.abort();
}
-/// Owner and sender cross the same boundary and are named by email, like
-/// message authors; a prompt with no person behind it sends no sender.
#[tokio::test]
-async fn the_owner_and_sender_reach_the_lexical_service() {
+async fn a_prompt_without_a_trigger_sends_none() {
let received: Arc<Mutex<Option<serde_json::Value>>> = Arc::default();
let seen = received.clone();
let app = Router::new().route(
@@ -281,7 +108,7 @@ async fn the_owner_and_sender_reach_the_lexical_service() {
let seen = seen.clone();
async move {
*seen.lock().unwrap() = Some(body);
- Json(serde_json::json!({ "markdown": "composed" }))
+ Json(serde_json::json!({ "markdown": "Sanitized prompt" }))
}
}),
);
@@ -292,46 +119,16 @@ async fn the_owner_and_sender_reach_the_lexical_service() {
"test".into(),
format!("http://{address}"),
));
- let owner = MacroUserIdStr::try_from_email("[email protected]").unwrap();
- let sender = MacroUserIdStr::try_from_email("[email protected]").unwrap();
- composer
- .compose(
- "Raw prompt",
- None,
- None,
- Some(&PromptPeople {
- owner: owner.clone(),
- sender: Some(sender),
- }),
- None,
- )
+ let composed = composer
+ .compose("Raw prompt", None, None, None)
.await
.unwrap();
- let body = received.lock().unwrap().clone().unwrap();
- assert_eq!(
- body["owner"],
- serde_json::json!({ "id": "macro|[email protected]", "name": "[email protected]" })
- );
+
+ assert_eq!(composed, "Sanitized prompt");
assert_eq!(
- body["sender"],
- serde_json::json!({ "id": "macro|[email protected]", "name": "[email protected]" })
+ received.lock().unwrap().take().unwrap(),
+ serde_json::json!({ "promptMarkdown": "Raw prompt" })
);
-
- composer
- .compose(
- "Raw prompt",
- None,
- None,
- Some(&PromptPeople {
- owner,
- sender: None,
- }),
- None,
- )
- .await
- .unwrap();
- let body = received.lock().unwrap().clone().unwrap();
- assert!(body.get("sender").is_none());
server.abort();
}
diff --git a/crates/agent_harness/src/outbound/channel_prompt_context.rs b/crates/agent_harness/src/outbound/channel_prompt_context.rs
index 2bf528fbe6..127b40a514 100644
--- a/crates/agent_harness/src/outbound/channel_prompt_context.rs
+++ b/crates/agent_harness/src/outbound/channel_prompt_context.rs
@@ -1,38 +1,22 @@
-//! Authorized conversation context through the common message application port.
+//! Authorize the origins agent prompts answer into, through the common
+//! message application port.
#[cfg(test)]
mod test;
use crate::domain::{
error::{HarnessError, Result},
- model::{
- AnnounceOrigin, CommentAnchor, ContextMessage, ContextThread, ConversationContext,
- MarkedPassage, ReplyTarget,
- },
+ model::AnnounceOrigin,
ports::MessagePromptContext,
};
use entity_access::domain::{
models::{EntityAccessReceipt, EntityType},
ports::EntityAccessService,
};
-use lexical_client::LexicalClient;
-use lexical_client::parse_markdown::ExtractedExplicitReply;
use macro_user_id::user_id::MacroUserIdStr;
-use macro_uuid::Uuid;
-use messages::domain::{
- api::MessageReader,
- models::{Message, MessageParent, MessageThread, ThreadAnchor},
- service::{MessageView, MessageWrite},
-};
+use messages::domain::{api::MessageReader, models::MessageParent, service::MessageWrite};
use std::sync::Arc;
-/// Channel messages before the prompt read as the surrounding activity.
-const CHANNEL_MESSAGES: u16 = 10;
-
-/// Most messages of the prompt's own discussion carried. The root is always
-/// kept, so a long thread loses its middle rather than its subject.
-const THREAD_MESSAGES: usize = 50;
-
trait ContextAuthorizer: Send + Sync + 'static {
fn capability(
&self,
@@ -65,78 +49,20 @@ impl<Access: EntityAccessService> ContextAuthorizer for Access {
}
}
-/// Reads what a comment mark covers in the live document. It checks no access
-/// of its own: it is only asked after the thread was read under the actor's
-/// capability on that document.
-trait MarkReader: Send + Sync + 'static {
- fn resolve(
- &self,
- document_id: &str,
- mark_id: &str,
- ) -> impl Future<Output = anyhow::Result<Option<MarkedPassage>>> + Send;
-}
-
-impl MarkReader for LexicalClient {
- async fn resolve(
- &self,
- document_id: &str,
- mark_id: &str,
- ) -> anyhow::Result<Option<MarkedPassage>> {
- Ok(self
- .resolve_comment_mark(document_id, mark_id)
- .await?
- .map(|mark| MarkedPassage {
- marked_text: mark.marked_text,
- surrounding_text: mark.surrounding_text,
- }))
- }
-}
-
-/// Reads the message a prompt quote-replies to out of the prompt's markdown.
-/// The quoted message itself is read separately, under the actor's access.
-trait QuoteReader: Send + Sync + 'static {
- fn quoted(
- &self,
- markdown: &str,
- ) -> impl Future<Output = anyhow::Result<Option<ExtractedExplicitReply>>> + Send;
-}
-
-impl QuoteReader for LexicalClient {
- async fn quoted(&self, markdown: &str) -> anyhow::Result<Option<ExtractedExplicitReply>> {
- self.extract_explicit_reply(markdown).await
- }
-}
-
-/// Reads channel and document conversation history with the same access boundary.
-pub struct MessagePromptContextAdapter<Access, Lexical = LexicalClient> {
+/// Checks prompt origins with the actor's current access.
+pub struct MessagePromptContextAdapter<Access> {
messages: Arc<dyn MessageReader>,
access: Arc<Access>,
- lexical: Arc<Lexical>,
}
-impl<Access, Lexical> MessagePromptContextAdapter<Access, Lexical> {
- /// Compose with the shared message service, current entity permissions,
- /// and the lexical service that resolves comment marks and quotes.
- pub fn new(
- messages: Arc<dyn MessageReader>,
- access: Arc<Access>,
- lexical: Arc<Lexical>,
- ) -> Self {
- Self {
- messages,
- access,
- lexical,
- }
+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 }
}
}
-fn context_error(error: impl std::fmt::Display) -> HarnessError {
- HarnessError::PromptContext(rootcause::report!(error.to_string()).into())
-}
-
-impl<Access: ContextAuthorizer, Lexical: MarkReader + QuoteReader> MessagePromptContext
- for MessagePromptContextAdapter<Access, Lexical>
-{
+impl<Access: ContextAuthorizer> MessagePromptContext for MessagePromptContextAdapter<Access> {
async fn authorize_origin(
&self,
actor: &MacroUserIdStr<'static>,
@@ -163,297 +89,4 @@ impl<Access: ContextAuthorizer, Lexical: MarkReader + QuoteReader> MessagePrompt
}
Ok(())
}
-
- /// The prompt's own discussion is read whole, because that is what the
- /// prompt is about. Nearby channel messages are grouped by the discussion
- /// they belong to so the agent can tell them apart from it.
- async fn conversation_context(
- &self,
- actor: &MacroUserIdStr<'static>,
- origin: &AnnounceOrigin,
- ) -> Result<ConversationContext> {
- let access: EntityAccessReceipt<MessageView> = self
- .access
- .capability(actor, &origin.parent)
- .await?
- .try_into_requirement()
- .map_err(|error| HarnessError::PromptContext(rootcause::report!(error).into()))?;
- let prompt = self
- .messages
- .get(access.clone(), origin.message_id)
- .await
- .map_err(context_error)?;
- let is_channel = matches!(origin.parent, MessageParent::Channel(_));
- let top_level = is_channel && origin.thread_id == origin.message_id;
-
- let discussion = if top_level {
- None
- } else {
- Some(
- self.messages
- .get_thread(access.clone(), origin.thread_id)
- .await
- .map_err(context_error)?,
- )
- };
- let recent = if is_channel {
- self.messages
- .preceding(access.clone(), origin.message_id, CHANNEL_MESSAGES)
- .await
- .map_err(context_error)?
- } else {
- Vec::new()
- };
-
- let anchor = match (&origin.parent, &discussion) {
- (MessageParent::Document(_), Some(discussion)) => {
- anchor(
- self.lexical.as_ref(),
- origin,
- discussion.state.anchor.clone(),
- )
- .await
- }
- _ => None,
- };
- let reply_target = match quote(
- self.messages.as_ref(),
- self.lexical.as_ref(),
- origin,
- &prompt,
- access,
- )
- .await
- {
- Some(quote) => quote,
- None if top_level => ReplyTarget::None,
- None => ReplyTarget::Thread {
- root_id: origin.thread_id,
- },
- };
-
- let mut channel = channel_threads(&recent, origin.thread_id);
- if top_level {
- channel.push(ContextThread {
- root_id: prompt.id,
- messages: context_message(&prompt).into_iter().collect(),
- messages_omitted: false,
- });
- }
-
- Ok(ConversationContext {
- anchor,
- reply_target: Some(reply_target),
- prompt_message_id: Some(prompt.id),
- thread: discussion.map(|discussion| prompt_thread(discussion, &prompt)),
- channel,
- })
- }
-}
-
-/// Where a document discussion sits, and what that anchor covers now. A PDF
-/// highlight's text arrives with the thread; a markdown mark is resolved
-/// against the live document, and a failed lookup leaves the stored
-/// snapshot to stand in rather than failing the prompt.
-async fn anchor(
- lexical: &impl MarkReader,
- origin: &AnnounceOrigin,
- anchor: Option<ThreadAnchor>,
-) -> Option<CommentAnchor> {
- let (mark_id, marked_text) = match anchor? {
- ThreadAnchor::Spreadsheet {
- sheet_id,
- sheet_name,
- range,
- } => {
- return Some(CommentAnchor::Spreadsheet {
- sheet_id,
- sheet_name,
- range,
- });
- }
- ThreadAnchor::PdfHighlight {
- anchor_id,
- marked_text,
- } => {
- return Some(CommentAnchor::PdfHighlight {
- anchor_id: anchor_id.to_string(),
- marked_text,
- });
- }
- ThreadAnchor::PdfPlaceable { anchor_id } => {
- return Some(CommentAnchor::PdfPin {
- anchor_id: anchor_id.to_string(),
- });
- }
- // The lexical prompt composer has no design anchor kind yet, so a
- // design pin reaches the agent as an unanchored thread on the design.
- ThreadAnchor::Fig { .. } => return None,
- ThreadAnchor::Markdown {
- mark_id,
- marked_text,
- } => (mark_id.to_string(), marked_text),
- };
- let current = lexical
- .resolve(&origin.parent.entity_id(), &mark_id)
- .await
- .inspect_err(|error| {
- tracing::warn!(
- error = ?error,
- parent = ?origin.parent,
- %mark_id,
- "sending comment anchor without the live marked text"
- );
- })
- .ok()
- .flatten();
- Some(CommentAnchor::Mark {
- mark_id,
- marked_text,
- current,
- })
-}
-
-/// The message the prompt quote-replies to, when it is one. The quoted
-/// message is only read when it sits in the prompt's own conversation,
-/// which the actor's access already covers; a quote from elsewhere
-/// travels as its preview.
-async fn quote(
- messages: &dyn MessageReader,
- lexical: &impl QuoteReader,
- origin: &AnnounceOrigin,
- prompt: &Message,
- access: EntityAccessReceipt<MessageView>,
-) -> Option<ReplyTarget> {
- let quoted = lexical
- .quoted(&prompt.content)
- .await
- .inspect_err(|error| {
- tracing::warn!(
- error = ?error,
- message_id = %origin.message_id,
- "sending agent prompt without its quote-reply target"
- );
- })
- .ok()
- .flatten()?;
- let (Ok(message_id), Ok(thread_id)) = (
- Uuid::parse_str(&quoted.target_message_id),
- Uuid::parse_str(&quoted.target_thread_id),
- ) else {
- tracing::warn!(
- target_message_id = %quoted.target_message_id,
- target_thread_id = %quoted.target_thread_id,
- "quote-reply target is not a message id"
- );
- return None;
- };
- let message = if quoted.parent == origin.parent {
- messages
- .get(access, message_id)
- .await
- .inspect_err(|error| {
- tracing::warn!(error = ?error, %message_id, "quoted message is unreadable");
- })
- .ok()
- .filter(|message| message.deleted_at.is_none() && message.parent == origin.parent)
- .and_then(|message| context_message(&message))
- } else {
- None
- };
- Some(ReplyTarget::Quote {
- message_id,
- thread_id,
- preview: quoted.display_text,
- message,
- })
-}
-
-/// The prompt's discussion from its root through the prompt. Replies posted
-/// after the prompt belong to later turns and are left out.
-fn prompt_thread(discussion: MessageThread, prompt: &Message) -> ContextThread {
- let root_id = discussion.state.root_id;
- let mut messages = Vec::new();
- let mut reached_prompt = false;
- for message in std::iter::once(discussion.root).chain(discussion.replies) {
- let is_prompt = message.id == prompt.id;
- if message.deleted_at.is_none()
- && let Some(message) = context_message(&message)
- {
- messages.push(message);
- }
- if is_prompt {
- reached_prompt = true;
- break;
- }
- }
- if !reached_prompt && let Some(message) = context_message(prompt) {
- messages.push(message);
- }
-
- let messages_omitted = messages.len() > THREAD_MESSAGES;
- if messages_omitted {
- let keep_root = messages
- .first()
- .is_some_and(|message| message.id == root_id);
- let tail = messages.split_off(messages.len() - (THREAD_MESSAGES - usize::from(keep_root)));
- messages.truncate(usize::from(keep_root));
- messages.extend(tail);
- }
- ContextThread {
- root_id,
- messages,
- messages_omitted,
- }
-}
-
-/// Channel messages outside the prompt's discussion, grouped by the
-/// discussion each belongs to, in the order the discussions first appear.
-fn channel_threads(recent: &[Message], prompt_root: Uuid) -> Vec<ContextThread> {
- let mut threads: Vec<ContextThread> = Vec::new();
- for message in recent {
- let root_id = message.root_id();
- if message.deleted_at.is_some() || root_id == prompt_root {
- continue;
- }
- let Some(entry) = context_message(message) else {
- continue;
- };
- match threads.iter_mut().find(|thread| thread.root_id == root_id) {
- Some(thread) => thread.messages.push(entry),
- None => threads.push(ContextThread {
- root_id,
- // A reply whose root fell outside the window.
- messages_omitted: message.id != root_id,
- messages: vec![entry],
- }),
- }
- }
- threads
-}
-
-/// A live message as context; `None` when its body is blank.
-fn context_message(message: &Message) -> Option<ContextMessage> {
- let content = message.content.trim();
- (!content.is_empty()).then(|| ContextMessage {
- id: message.id,
- sender_id: message.sender_id.as_ref().to_owned(),
- author: author(message),
- content: content.to_owned(),
- posted_at: message.created_at,
- })
-}
-
-/// Who wrote a message, as a reader would name them.
-fn author(message: &Message) -> String {
- if let Some(imported) = &message.imported_author {
- return imported.name.clone();
- }
- if let Some(bot) = &message.bot_profile {
- return bot.name.clone();
- }
- message.sender_id.as_user().map_or_else(
- || message.sender_id.as_ref().to_owned(),
- |user| user.email_str().to_owned(),
- )
}
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 9728172cb1..9513ee70b1 100644
--- a/crates/agent_harness/src/outbound/channel_prompt_context/test.rs
+++ b/crates/agent_harness/src/outbound/channel_prompt_context/test.rs
@@ -2,45 +2,7 @@ use super::*;
use chrono::{DateTime, Utc};
use entity_access::domain::models::{AccessLevel, Entity, EntityPermission};
use macro_uuid::Uuid;
-use messages::domain::{
- api::MockMessageReader,
- models::{Message, MessageThread, ThreadState},
-};
-
-/// The lexical service's lookups, each answering one fixed result.
-struct Lexical {
- mark: std::result::Result<Option<MarkedPassage>, &'static str>,
- quote: std::result::Result<Option<ExtractedExplicitReply>, &'static str>,
-}
-impl Lexical {
- fn none() -> Self {
- Self {
- mark: Ok(None),
- quote: Ok(None),
- }
- }
- fn mark(mark: std::result::Result<Option<MarkedPassage>, &'static str>) -> Self {
- Self {
- mark,
- ..Self::none()
- }
- }
-}
-impl MarkReader for Lexical {
- async fn resolve(
- &self,
- document_id: &str,
- _mark_id: &str,
- ) -> anyhow::Result<Option<MarkedPassage>> {
- assert_eq!(document_id, "doc");
- self.mark.clone().map_err(|error| anyhow::anyhow!(error))
- }
-}
-impl QuoteReader for Lexical {
- async fn quoted(&self, _markdown: &str) -> anyhow::Result<Option<ExtractedExplicitReply>> {
- self.quote.clone().map_err(|error| anyhow::anyhow!(error))
- }
-}
+use messages::domain::{api::MockMessageReader, models::Message};
struct Authorizer {
allowed: bool,
@@ -81,9 +43,6 @@ fn origin() -> AnnounceOrigin {
message_id: Uuid::from_u128(2),
}
}
-fn channel() -> MessageParent {
- MessageParent::Channel(Uuid::from_u128(3))
-}
fn at(minute: i64) -> DateTime<Utc> {
DateTime::from_timestamp(1_758_800_000 + minute * 60, 0).unwrap()
}
@@ -127,9 +86,6 @@ fn message() -> Message {
5,
)
}
-fn context_of(message: &Message) -> ContextMessage {
- context_message(message).unwrap()
-}
#[tokio::test]
async fn document_origin_checks_its_parent_capability_and_root() {
@@ -143,11 +99,8 @@ async fn document_origin_checks_its_parent_capability_and_root() {
&& *id == origin().message_id
})
.return_once(|_, _| Ok(message()));
- let adapter = MessagePromptContextAdapter::new(
- Arc::new(source),
- Arc::new(Authorizer { allowed: true }),
- Arc::new(Lexical::none()),
- );
+ let adapter =
+ MessagePromptContextAdapter::new(Arc::new(source), Arc::new(Authorizer { allowed: true }));
adapter.authorize_origin(&actor(), &origin()).await.unwrap();
}
@@ -173,24 +126,14 @@ async fn initiative_origin_mints_parent_capability_and_rechecks_revocation() {
..message()
})
});
- let adapter = MessagePromptContextAdapter::new(
- Arc::new(source),
- Arc::new(Authorizer { allowed: true }),
- Arc::new(Lexical::none()),
- );
+ let adapter =
+ MessagePromptContextAdapter::new(Arc::new(source), Arc::new(Authorizer { allowed: true }));
adapter.authorize_origin(&actor(), &origin).await.unwrap();
let revoked = MessagePromptContextAdapter::new(
Arc::new(MockMessageReader::new()),
Arc::new(Authorizer { allowed: false }),
- Arc::new(Lexical::none()),
);
assert!(revoked.authorize_origin(&actor(), &origin).await.is_err());
- assert!(
- revoked
- .conversation_context(&actor(), &origin)
- .await
- .is_err()
- );
}
#[tokio::test]
@@ -198,15 +141,8 @@ async fn revoked_access_never_reads_message_content() {
let adapter = MessagePromptContextAdapter::new(
Arc::new(MockMessageReader::new()),
Arc::new(Authorizer { allowed: false }),
- Arc::new(Lexical::none()),
);
assert!(adapter.authorize_origin(&actor(), &origin()).await.is_err());
- assert!(
- adapter
- .conversation_context(&actor(), &origin())
- .await
- .is_err()
- );
}
#[tokio::test]
@@ -227,655 +163,7 @@ async fn a_claimed_root_or_parent_cannot_link_an_unrelated_session() {
let adapter = MessagePromptContextAdapter::new(
Arc::new(source),
Arc::new(Authorizer { allowed: true }),
- Arc::new(Lexical::none()),
);
assert!(adapter.authorize_origin(&actor(), &origin()).await.is_err());
}
}
-
-fn discussion(root: Message, replies: Vec<Message>, anchor: Option<ThreadAnchor>) -> MessageThread {
- MessageThread {
- state: ThreadState {
- root_id: root.id,
- user_id: actor().as_ref().to_owned(),
- resolved: false,
- anchor,
- created_at: root.created_at,
- updated_at: root.created_at,
- deleted_at: None,
- },
- root,
- replies,
- }
-}
-
-/// A document comment thread: the root and the prompting reply.
-fn reader(anchor: Option<ThreadAnchor>) -> MockMessageReader {
- let root = posted(
- &origin().parent,
- 1,
- None,
- "is this right?",
- 0,
- );
- let mut source = MockMessageReader::new();
- source
- .expect_get()
- .withf(|_, id| *id == origin().message_id)
- .returning(|_, _| Ok(message()));
- // A document discussion is its own thread; nothing outside it is read.
- source.expect_preceding().never();
- source
- .expect_get_thread()
- .once()
- .withf(|access, root| access.entity().entity_id == "doc" && *root == origin().thread_id)
- .return_once(move |_, _| Ok(discussion(root, vec![message()], anchor)));
- source
-}
-
-async fn context_from(
- source: MockMessageReader,
- lexical: Lexical,
- origin: &AnnounceOrigin,
-) -> ConversationContext {
- MessagePromptContextAdapter::new(
- Arc::new(source),
- Arc::new(Authorizer { allowed: true }),
- Arc::new(lexical),
- )
- .conversation_context(&actor(), origin)
- .await
- .unwrap()
-}
-
-#[tokio::test]
-async fn a_document_comment_carries_its_whole_thread_through_the_prompt() {
- let context = context_from(reader(None), Lexical::none(), &origin()).await;
- let thread = context.thread.unwrap();
- assert_eq!(thread.root_id, origin().thread_id);
- assert_eq!(
- thread
- .messages
- .iter()
- .map(|message| (message.author.as_str(), message.content.as_str()))
- .collect::<Vec<_>>(),
- [
- ("[email protected]", "is this right?"),
- ("[email protected]", "@agent explain this paragraph"),
- ]
- );
- assert!(!thread.messages_omitted);
- assert_eq!(context.prompt_message_id, Some(origin().message_id));
- assert_eq!(
- context.reply_target,
- Some(ReplyTarget::Thread {
- root_id: origin().thread_id
- })
- );
- assert!(context.channel.is_empty());
- // An unanchored discussion names no place in the document.
- assert_eq!(context.anchor, None);
-}
-
-/// The reported failure: "please fix" in thread A, posted while another
-/// thread was busier. The agent must get thread A whole and be told the rest
-/// is background, not a flat list whose last entry is someone else's bug.
-#[tokio::test]
-async fn a_channel_thread_reply_is_about_its_thread_not_the_latest_message() {
- let parent = channel();
- let calendar = posted(
- &parent,
- 10,
- None,
- "calendar popover scrolls the page",
- 0,
- );
- let spinner = posted(
- &parent,
- 20,
- None,
- "sidebar spinner never stops",
- 5,
- );
- let repro = posted(
- &parent,
- 11,
- Some(10),
- "repro: open it and scroll",
- 6,
- );
- let lunch = posted(&parent, 30, None, "[email protected]", "lunch?", 10);
- let mobile = posted(
- &parent,
- 21,
- Some(20),
- "same on mobile",
- 12,
- );
- let prompt = posted(
- &parent,
- 12,
- Some(10),
- "@Cursor please fix",
- 15,
- );
- let later = posted(
- &parent,
- 13,
- Some(10),
- "posted after the prompt",
- 20,
- );
- let origin = AnnounceOrigin {
- reuse_origin_message: false,
- parent: parent.clone(),
- thread_id: calendar.id,
- message_id: prompt.id,
- };
-
- let mut source = MockMessageReader::new();
- let prompt_message = prompt.clone();
- source
- .expect_get()
- .withf(move |_, id| *id == Uuid::from_u128(12))
- .returning(move |_, _| Ok(prompt_message.clone()));
- let thread = discussion(
- calendar.clone(),
- vec![repro.clone(), prompt.clone(), later],
- None,
- );
- source
- .expect_get_thread()
- .once()
- .withf(|_, root| *root == Uuid::from_u128(10))
- .return_once(move |_, _| Ok(thread));
- // The window starts after the thread's root, as it does in a busy channel.
- let recent = vec![
- spinner.clone(),
- repro.clone(),
- lunch.clone(),
- mobile.clone(),
- ];
- source
- .expect_preceding()
- .once()
- .withf(|_, id, limit| *id == Uuid::from_u128(12) && *limit == 10)
- .return_once(move |_, _, _| Ok(recent));
-
- let context = context_from(source, Lexical::none(), &origin).await;
-
- assert_eq!(
- context.thread,
- Some(ContextThread {
- root_id: calendar.id,
- messages: vec![
- context_of(&calendar),
- context_of(&repro),
- context_of(&prompt)
- ],
- messages_omitted: false,
- })
- );
- assert_eq!(
- context.channel,
- [
- ContextThread {
- root_id: spinner.id,
- messages: vec![context_of(&spinner), context_of(&mobile)],
- messages_omitted: false,
- },
- ContextThread {
- root_id: lunch.id,
- messages: vec![context_of(&lunch)],
- messages_omitted: false,
- },
- ]
- );
- assert_eq!(
- context.reply_target,
- Some(ReplyTarget::Thread {
- root_id: calendar.id
- })
- );
- assert_eq!(context.prompt_message_id, Some(prompt.id));
-}
-
-#[tokio::test]
-async fn a_top_level_channel_prompt_replies_to_nothing_and_ends_the_channel() {
- let parent = channel();
- let root = posted(&parent, 20, None, "[email protected]", "spinner bug", 0);
- let reply = posted(
- &parent,
- 21,
- Some(20),
- "same on mobile",
- 1,
- );
- let orphan = posted(
- &parent,
- 41,
- Some(40),
- "reply to an old thread",
- 2,
- );
- let prompt = posted(
- &parent,
- 50,
- None,
- "@Cursor what's broken?",
- 3,
- );
- let origin = AnnounceOrigin {
- reuse_origin_message: false,
- parent: parent.clone(),
- thread_id: prompt.id,
- message_id: prompt.id,
- };
-
- let mut source = MockMessageReader::new();
- let prompt_message = prompt.clone();
- source
- .expect_get()
- .returning(move |_, _| Ok(prompt_message.clone()));
- source.expect_get_thread().never();
- let recent = vec![root.clone(), reply.clone(), orphan.clone()];
- source
- .expect_preceding()
- .once()
- .return_once(move |_, _, _| Ok(recent));
-
- let context = context_from(source, Lexical::none(), &origin).await;
-
- assert_eq!(context.thread, None);
- assert_eq!(context.anchor, None);
- assert_eq!(context.reply_target, Some(ReplyTarget::None));
- assert_eq!(
- context.channel,
- [
- ContextThread {
- root_id: root.id,
- messages: vec![context_of(&root), context_of(&reply)],
- messages_omitted: false,
- },
- ContextThread {
- root_id: Uuid::from_u128(40),
- messages: vec![context_of(&orphan)],
- // Its root fell outside the window.
- messages_omitted: true,
- },
- ContextThread {
- root_id: prompt.id,
- messages: vec![context_of(&prompt)],
- messages_omitted: false,
- },
- ]
- );
-}
-
-#[tokio::test]
-async fn a_quote_reply_carries_the_quoted_message_even_outside_the_window() {
- let parent = channel();
- let quoted = posted(
- &parent,
- 60,
- None,
- "the spinner never stops",
- 0,
- );
- let prompt = posted(
- &parent,
- 70,
- None,
- "<m-reply-target>…</m-reply-target>\n\n@Cursor fix this",
- 30,
- );
- let origin = AnnounceOrigin {
- reuse_origin_message: false,
- parent: parent.clone(),
- thread_id: prompt.id,
- message_id: prompt.id,
- };
-
- let mut source = MockMessageReader::new();
- let prompt_message = prompt.clone();
- source
- .expect_get()
- .withf(|_, id| *id == Uuid::from_u128(70))
- .returning(move |_, _| Ok(prompt_message.clone()));
- let quoted_message = quoted.clone();
- source
- .expect_get()
- .once()
- .withf(|access, id| {
- access.entity().entity_id == channel().entity_id() && *id == Uuid::from_u128(60)
- })
- .return_once(move |_, _| Ok(quoted_message));
- source
- .expect_preceding()
- .once()
- .return_once(|_, _, _| Ok(vec![]));
-
- let lexical = Lexical {
- quote: Ok(Some(ExtractedExplicitReply {
- parent: parent.clone(),
- target_message_id: quoted.id.to_string(),
- target_thread_id: quoted.id.to_string(),
- display_text: "the spinner never stops".to_owned(),
- sender_id: quoted.sender_id.as_ref().to_owned(),
- })),
- ..Lexical::none()
- };
- let context = context_from(source, lexical, &origin).await;
-
- assert_eq!(
- context.reply_target,
- Some(ReplyTarget::Quote {
- message_id: quoted.id,
- thread_id: quoted.id,
- preview: "the spinner never stops".to_owned(),
- message: Some(context_of(&quoted)),
- })
- );
-}
-
-#[tokio::test]
-async fn a_quote_from_another_conversation_travels_as_its_preview() {
- let parent = channel();
- let prompt = posted(
- &parent,
- 70,
- None,
- "@Cursor fix this",
- 30,
- );
- let origin = AnnounceOrigin {
- reuse_origin_message: false,
- parent: parent.clone(),
- thread_id: prompt.id,
- message_id: prompt.id,
- };
- let mut source = MockMessageReader::new();
- let prompt_message = prompt.clone();
- // Only the prompt is read: the quoted message is on a parent the actor's
- // capability does not cover.
- source
- .expect_get()
- .once()
- .withf(|_, id| *id == Uuid::from_u128(70))
- .return_once(move |_, _| Ok(prompt_message));
- source
- .expect_preceding()
- .once()
- .return_once(|_, _, _| Ok(vec![]));
- let lexical = Lexical {
- quote: Ok(Some(ExtractedExplicitReply {
- parent: MessageParent::Channel(Uuid::from_u128(99)),
- target_message_id: Uuid::from_u128(61).to_string(),
- target_thread_id: Uuid::from_u128(61).to_string(),
- display_text: "elsewhere".to_owned(),
- sender_id: "macro|[email protected]".to_owned(),
- })),
- ..Lexical::none()
- };
- let context = context_from(source, lexical, &origin).await;
- assert_eq!(
- context.reply_target,
- Some(ReplyTarget::Quote {
- message_id: Uuid::from_u128(61),
- thread_id: Uuid::from_u128(61),
- preview: "elsewhere".to_owned(),
- message: None,
- })
- );
-}
-
-#[tokio::test]
-async fn a_failed_quote_lookup_still_names_the_thread() {
- let context = context_from(
- reader(None),
- Lexical {
- quote: Err("lexical unavailable"),
- ..Lexical::none()
- },
- &origin(),
- )
- .await;
- assert_eq!(
- context.reply_target,
- Some(ReplyTarget::Thread {
- root_id: origin().thread_id
- })
- );
-}
-
-#[tokio::test]
-async fn a_long_thread_keeps_its_root_and_the_messages_nearest_the_prompt() {
- let parent = channel();
- let root = posted(&parent, 1, None, "[email protected]", "the bug", 0);
- let replies: Vec<Message> = (0..60)
- .map(|index| {
- posted(
- &parent,
- 100 + index,
- Some(1),
- &format!("reply {index}"),
- 1 + i64::try_from(index).unwrap(),
- )
- })
- .collect();
- let prompt = replies.last().unwrap().clone();
- let origin = AnnounceOrigin {
- reuse_origin_message: false,
- parent: parent.clone(),
- thread_id: root.id,
- message_id: prompt.id,
- };
- let mut source = MockMessageReader::new();
- let prompt_message = prompt.clone();
- source
- .expect_get()
- .returning(move |_, _| Ok(prompt_message.clone()));
- let thread = discussion(root.clone(), replies, None);
- source
- .expect_get_thread()
- .once()
- .return_once(move |_, _| Ok(thread));
- source
- .expect_preceding()
- .once()
- .return_once(|_, _, _| Ok(vec![]));
-
- let thread = context_from(source, Lexical::none(), &origin)
- .await
- .thread
- .unwrap();
- assert!(thread.messages_omitted);
- assert_eq!(thread.messages.len(), THREAD_MESSAGES);
- assert_eq!(thread.messages[0].content, "the bug");
- assert_eq!(thread.messages[1].content, "reply 11");
- assert_eq!(thread.messages.last().unwrap().id, prompt.id);
-}
-
-#[tokio::test]
-async fn a_marked_discussion_names_its_mark_and_the_text_it_covers() {
- let mark_id = Uuid::from_u128(7);
- let context = context_from(
- reader(Some(ThreadAnchor::Markdown {
- mark_id,
- marked_text: Some("the marked phrase".to_owned()),
- })),
- Lexical::none(),
- &origin(),
- )
- .await;
- assert_eq!(
- context.anchor,
- Some(CommentAnchor::Mark {
- mark_id: mark_id.to_string(),
- marked_text: Some("the marked phrase".to_owned()),
- current: None,
- })
- );
-}
-
-#[tokio::test]
-async fn a_discussion_anchored_before_snapshots_still_names_its_mark() {
- let mark_id = Uuid::from_u128(8);
- let context = context_from(
- reader(Some(ThreadAnchor::Markdown {
- mark_id,
- marked_text: None,
- })),
- Lexical::none(),
- &origin(),
- )
- .await;
- assert_eq!(
- context.anchor,
- Some(CommentAnchor::Mark {
- mark_id: mark_id.to_string(),
- marked_text: None,
- current: None,
- })
- );
-}
-
-#[tokio::test]
-async fn a_marked_discussion_reads_the_mark_as_the_document_has_it_now() {
- let mark_id = Uuid::from_u128(9);
- let current = MarkedPassage {
- marked_text: "the edited phrase".to_owned(),
- surrounding_text: "Before the edited phrase after.".to_owned(),
- };
- let context = context_from(
- reader(Some(ThreadAnchor::Markdown {
- mark_id,
- marked_text: Some("the original phrase".to_owned()),
- })),
- Lexical::mark(Ok(Some(current.clone()))),
- &origin(),
- )
- .await;
- assert_eq!(
- context.anchor,
- Some(CommentAnchor::Mark {
- mark_id: mark_id.to_string(),
- marked_text: Some("the original phrase".to_owned()),
- current: Some(current),
- })
- );
-}
-
-#[tokio::test]
-async fn a_failed_live_lookup_falls_back_to_the_snapshot() {
- let mark_id = Uuid::from_u128(10);
- let context = context_from(
- reader(Some(ThreadAnchor::Markdown {
- mark_id,
- marked_text: Some("the original phrase".to_owned()),
- })),
- Lexical::mark(Err("lexical unavailable")),
- &origin(),
- )
- .await;
- assert_eq!(
- context.anchor,
- Some(CommentAnchor::Mark {
- mark_id: mark_id.to_string(),
- marked_text: Some("the original phrase".to_owned()),
- current: None,
- })
- );
-}
-
-#[tokio::test]
-async fn a_pdf_highlight_discussion_names_the_text_the_highlight_covers() {
- let anchor_id = Uuid::from_u128(11);
- let context = context_from(
- reader(Some(ThreadAnchor::PdfHighlight {
- anchor_id,
- marked_text: Some("indemnifies the lessor".to_owned()),
- })),
- // The highlight's text arrives with the thread; no document lookup.
- Lexical::mark(Err("never asked")),
- &origin(),
- )
- .await;
- assert_eq!(
- context.anchor,
- Some(CommentAnchor::PdfHighlight {
- anchor_id: anchor_id.to_string(),
- marked_text: Some("indemnifies the lessor".to_owned()),
- })
- );
-}
-
-#[tokio::test]
-async fn a_pdf_pin_discussion_names_its_pin() {
- let anchor_id = Uuid::from_u128(12);
- let context = context_from(
- reader(Some(ThreadAnchor::PdfPlaceable { anchor_id })),
- Lexical::none(),
- &origin(),
- )
- .await;
- assert_eq!(
- context.anchor,
- Some(CommentAnchor::PdfPin {
- anchor_id: anchor_id.to_string(),
- })
- );
-}
-
-#[tokio::test]
-async fn spreadsheet_discussions_carry_the_range_without_resolving_a_mark() {
- let context = context_from(
- reader(Some(ThreadAnchor::Spreadsheet {
- sheet_id: "sheet-1".into(),
- sheet_name: "Budget".into(),
- range: "B4:C9".into(),
- })),
- Lexical::mark(Err("never asked")),
- &origin(),
- )
- .await;
- assert_eq!(
- context.anchor,
- Some(CommentAnchor::Spreadsheet {
- sheet_id: "sheet-1".into(),
- sheet_name: "Budget".into(),
- range: "B4:C9".into()
- })
- );
-}
-
-#[tokio::test]
-async fn design_discussions_reach_the_agent_unanchored() {
- let context = context_from(
- reader(Some(ThreadAnchor::Fig {
- page_id: "0:1".into(),
- node_id: Some("12:34".into()),
- x: 18.5,
- y: -4.0,
- })),
- Lexical::mark(Err("never asked")),
- &origin(),
- )
- .await;
- assert_eq!(context.anchor, None);
- assert!(context.thread.is_some());
-}
diff --git a/crates/agent_session/Cargo.toml b/crates/agent_session/Cargo.toml
index 69fa298d24..b16c765a75 100644
--- a/crates/agent_session/Cargo.toml
+++ b/crates/agent_session/Cargo.toml
@@ -94,6 +94,7 @@ chrono = { workspace = true }
thiserror = { workspace = true }
anyhow = { workspace = true }
bot_id = { path = "../bot_id" }
+trigger_context = { path = "../trigger_context" }
serde = { workspace = true }
serde_json = { workspace = true }
strum = { workspace = true }
diff --git a/crates/agent_session/src/domain/coding_agents.rs b/crates/agent_session/src/domain/coding_agents.rs
index dd21288c2c..2e322660e7 100644
--- a/crates/agent_session/src/domain/coding_agents.rs
+++ b/crates/agent_session/src/domain/coding_agents.rs
@@ -213,6 +213,9 @@ where
action_id,
},
prompt: command.prompt,
+ // Dispatch moves onto the trigger topic separately, and
+ // takes its context from there.
+ context: None,
})
.await
.map_err(failed)?;
diff --git a/crates/agent_session/src/domain/control.rs b/crates/agent_session/src/domain/control.rs
index dc1786cd9e..69398d816a 100644
--- a/crates/agent_session/src/domain/control.rs
+++ b/crates/agent_session/src/domain/control.rs
@@ -3,6 +3,7 @@
use agent_runtime_protocol::domain::action::{AgentAction, AgentActionId};
use entity_access::domain::models::{EditAccessLevel, EntityAccessReceipt};
use macro_user_id::user_id::MacroUserIdStr;
+use trigger_context::TriggerContext;
use super::error::{AgentSessionError, Result};
use super::ports::ControlEvent;
@@ -19,13 +20,21 @@ impl ControlEvent {
/// Only an authenticated user with edit access may answer an interaction.
/// Runtime principals may forward ordinary controls, but cannot use their
/// acting-user identity to approve their own permission or elicitation.
+ ///
+ /// Trigger context is only accepted from a runtime forwarding a prompt it
+ /// was triggered with. A user could otherwise tell an owner's agent that
+ /// the owner asked for something.
pub fn authorized(
action: AgentAction,
action_id: Option<AgentActionId>,
+ context: Option<TriggerContext>,
principal: ControlPrincipal,
access: EntityAccessReceipt<EditAccessLevel>,
) -> Result<Self> {
let actor = match principal {
+ ControlPrincipal::User if context.is_some() => {
+ return Err(AgentSessionError::Forbidden);
+ }
ControlPrincipal::User => Some(
access
.get_authenticated_user()
@@ -46,6 +55,7 @@ impl ControlEvent {
action,
action_id,
actor,
+ context,
})
}
}
diff --git a/crates/agent_session/src/domain/control/test.rs b/crates/agent_session/src/domain/control/test.rs
index 55316de3ed..4bd2f6a024 100644
--- a/crates/agent_session/src/domain/control/test.rs
+++ b/crates/agent_session/src/domain/control/test.rs
@@ -38,7 +38,7 @@ fn editors_and_owners_can_answer_both_interaction_kinds() {
for level in [AccessLevel::Edit, AccessLevel::Owner] {
for action in answers() {
let event =
- ControlEvent::authorized(action, None, ControlPrincipal::User, access(level))
+ ControlEvent::authorized(action, None, None, ControlPrincipal::User, access(level))
.unwrap();
assert_eq!(event.actor, Some(user()));
}
@@ -54,6 +54,7 @@ fn runtimes_cannot_answer_even_when_forwarding_an_owner_or_editor() {
ControlEvent::authorized(
action,
None,
+ None,
ControlPrincipal::Runtime(actor.clone()),
access(level)
),
@@ -63,6 +64,7 @@ fn runtimes_cannot_answer_even_when_forwarding_an_owner_or_editor() {
let event = ControlEvent::authorized(
AgentAction::prompt("hello"),
None,
+ None,
ControlPrincipal::Runtime(actor.clone()),
access(level),
)
@@ -71,3 +73,45 @@ fn runtimes_cannot_answer_even_when_forwarding_an_owner_or_editor() {
}
}
}
+
+fn trigger() -> trigger_context::TriggerContext {
+ trigger_context::TriggerContext::Requested(trigger_context::RequestedContext {
+ requested_by: trigger_context::ContextPerson {
+ id: "macro|[email protected]".to_owned(),
+ name: "Owner".to_owned(),
+ email: Some("[email protected]".to_owned()),
+ },
+ requested_at: chrono::DateTime::UNIX_EPOCH,
+ repo_url: None,
+ })
+}
+
+/// A runtime forwards the context it was triggered with.
+#[test]
+fn a_runtime_forwards_trigger_context_with_a_prompt() {
+ let event = ControlEvent::authorized(
+ AgentAction::prompt("hello"),
+ None,
+ Some(trigger()),
+ ControlPrincipal::Runtime(Some(user())),
+ access(AccessLevel::Edit),
+ )
+ .unwrap();
+ assert_eq!(event.context, Some(trigger()));
+}
+
+/// A user could otherwise tell an owner's agent that the owner asked for
+/// something.
+#[test]
+fn a_user_cannot_supply_trigger_context() {
+ assert!(matches!(
+ ControlEvent::authorized(
+ AgentAction::prompt("hello"),
+ None,
+ Some(trigger()),
+ ControlPrincipal::User,
+ access(AccessLevel::Owner),
+ ),
+ Err(AgentSessionError::Forbidden)
+ ));
+}
diff --git a/crates/agent_session/src/domain/model.rs b/crates/agent_session/src/domain/model.rs
index 9dbcb31da0..b41d7b78ef 100644
--- a/crates/agent_session/src/domain/model.rs
+++ b/crates/agent_session/src/domain/model.rs
@@ -409,6 +409,9 @@ pub struct StoredQueuedAction {
/// Chip message id, once posted, so a retry does not announce twice.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub announced_message_id: Option<Uuid>,
+ /// Why the agent is being asked, composed into the prompt at dispatch.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub context: Option<trigger_context::TriggerContext>,
}
impl From<&StoredQueuedAction> for super::ports::QueuedControl {
diff --git a/crates/agent_session/src/domain/ports.rs b/crates/agent_session/src/domain/ports.rs
index fb67d46d19..e5a08279fb 100644
--- a/crates/agent_session/src/domain/ports.rs
+++ b/crates/agent_session/src/domain/ports.rs
@@ -1115,6 +1115,9 @@ pub struct ControlEvent {
/// `None` means "no user is responsible", not "unknown" - a bot's own
/// actions are attributed to the bot, which this field does not carry.
pub actor: Option<MacroUserIdStr<'static>>,
+ /// Why the agent is being asked, when a runtime forwards a triggered
+ /// prompt. Users driving a session directly supply none.
+ pub context: Option<trigger_context::TriggerContext>,
}
/// What accepting a control operation did with it.
diff --git a/crates/agent_session/src/domain/routines/models.rs b/crates/agent_session/src/domain/routines/models.rs
index bc168ebbf1..fc63f298f7 100644
--- a/crates/agent_session/src/domain/routines/models.rs
+++ b/crates/agent_session/src/domain/routines/models.rs
@@ -61,6 +61,9 @@ pub struct PromptRoutineSession {
pub action: RoutineSessionAction,
/// Routine guidance, instructions, and context; not persona system settings.
pub prompt: String,
+ /// What made the routine fire, rendered ahead of the prompt.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub context: Option<trigger_context::TriggerContext>,
}
/// Prompt admission is not completion.
diff --git a/crates/agent_session/src/domain/routines/service.rs b/crates/agent_session/src/domain/routines/service.rs
index 578247b612..7a9b2e2093 100644
--- a/crates/agent_session/src/domain/routines/service.rs
+++ b/crates/agent_session/src/domain/routines/service.rs
@@ -217,6 +217,7 @@ where
action: AgentAction::prompt(command.prompt),
action_id: Some(action.action_id),
actor: Some(action.owner),
+ context: command.context,
},
)
.await
@@ -257,6 +258,7 @@ where
action: AgentAction::Stop,
action_id: Some(AgentActionId::mint()),
actor: Some(command.owner),
+ context: None,
},
)
.await
diff --git a/crates/agent_session/src/domain/routines/service/test.rs b/crates/agent_session/src/domain/routines/service/test.rs
index 7aa107ff35..31d1140722 100644
--- a/crates/agent_session/src/domain/routines/service/test.rs
+++ b/crates/agent_session/src/domain/routines/service/test.rs
@@ -440,7 +440,8 @@ async fn every_subsequent_operation_checks_owner_and_persona_before_controls_or_
fx.service
.prompt(PromptRoutineSession {
action,
- prompt: "task".into()
+ prompt: "task".into(),
+ context: None,
})
.await
.unwrap_err(),
@@ -460,6 +461,7 @@ async fn prompt_and_cancel_only_emit_attributed_prompt_and_stop_controls() {
.prompt(PromptRoutineSession {
action: action.clone(),
prompt: "routine guidance and task".into(),
+ context: None,
})
.await
.unwrap();
@@ -487,7 +489,8 @@ async fn ambiguous_prompt_failure_is_not_replayed() {
fx.service
.prompt(PromptRoutineSession {
action: fx.action(),
- prompt: "task".into()
+ prompt: "task".into(),
+ context: None,
})
.await
.unwrap_err(),
@@ -530,7 +533,8 @@ async fn refuses_known_prompt_replays_even_after_completion() {
fx.service
.prompt(PromptRoutineSession {
action,
- prompt: "retry".into()
+ prompt: "retry".into(),
+ context: None,
})
.await
.unwrap_err(),
@@ -553,7 +557,8 @@ async fn queued_prompt_prevents_second_submission() {
fx.service
.prompt(PromptRoutineSession {
action,
- prompt: "retry".into()
+ prompt: "retry".into(),
+ context: None,
})
.await
.unwrap_err(),
diff --git a/crates/agent_session/src/inbound/axum_router.rs b/crates/agent_session/src/inbound/axum_router.rs
index 0c2c28d390..8ef78c5a89 100644
--- a/crates/agent_session/src/inbound/axum_router.rs
+++ b/crates/agent_session/src/inbound/axum_router.rs
@@ -508,6 +508,11 @@ pub struct ControlRequest {
/// fields, which are tagged under `type`.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub action_id: Option<AgentActionId>,
+ /// Why the agent is being asked. Only a runtime forwarding a triggered
+ /// prompt may send it; a user's request carrying it is refused.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schema(value_type = Option<Object>)]
+ pub context: Option<trigger_context::TriggerContext>,
/// The operation to perform.
#[serde(flatten)]
pub action: AgentAction,
@@ -1065,6 +1070,7 @@ pub async fn control_agent_session_handler<
ControlEvent::authorized(
req.action,
req.action_id,
+ req.context,
principal,
access.entity_access_receipt,
)?,
diff --git a/crates/agent_session/src/inbound/axum_router/test.rs b/crates/agent_session/src/inbound/axum_router/test.rs
index 78e292ba58..84bbc609bc 100644
--- a/crates/agent_session/src/inbound/axum_router/test.rs
+++ b/crates/agent_session/src/inbound/axum_router/test.rs
@@ -1366,6 +1366,7 @@ fn an_unnamed_control_request_omits_the_field() {
let body = serde_json::to_value(ControlRequest {
action_id: None,
action: AgentAction::Stop,
+ context: None,
})
.expect("a control request serializes");
diff --git a/crates/agent_session/src/outbound/postgres/test/queue.rs b/crates/agent_session/src/outbound/postgres/test/queue.rs
index 9dbe4db311..5a736924ea 100644
--- a/crates/agent_session/src/outbound/postgres/test/queue.rs
+++ b/crates/agent_session/src/outbound/postgres/test/queue.rs
@@ -16,6 +16,7 @@ fn stored_prompt(text: &str) -> StoredQueuedAction {
"messageId": "00000000-0000-0000-0000-0000000000f2"
})),
announced_message_id: None,
+ context: None,
}
}
diff --git a/crates/agent_trigger/Cargo.toml b/crates/agent_trigger/Cargo.toml
index 1c74452a20..67fee882dc 100644
--- a/crates/agent_trigger/Cargo.toml
+++ b/crates/agent_trigger/Cargo.toml
@@ -11,7 +11,7 @@ admission = ["dep:ai_billing"]
# 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 = ["admission", "dep:agent", "dep:ai_usage", "dep:async-trait", "dep:document_storage_service_client", "dep:document_sub_type", "dep:lexical_client", "dep:sqlx", "dep:static_file", "channels/ports"]
+outbound = ["admission", "dep:agent", "dep:ai_usage", "dep:async-trait", "dep:call", "dep:document_storage_service_client", "dep:document_sub_type", "dep:lexical_client", "dep:sqlx", "dep:static_file", "channels/ports"]
[dependencies]
ai_billing = { path = "../ai_billing", optional = true }
@@ -27,6 +27,7 @@ bots = { path = "../bots", default-features = false, features = ["ports"] }
lexical_client = { path = "../lexical_client", optional = true }
static_file = { path = "../static_file", optional = true, default-features = false }
chrono = { workspace = true }
+trigger_context = { path = "../trigger_context" }
# Only the domain vocabulary (`Event`, `MacroEvent`, `TopicEvent`). Asking for
# `outbound` here would pull rdkafka — and so librdkafka and openssl — into
# every consumer of this crate, including the self-hosted daemon, which
@@ -54,9 +55,11 @@ thiserror = { workspace = true }
tracing = { workspace = true }
tokio = { workspace = true, features = ["rt", "time"] }
async-trait = { workspace = true, optional = true }
+call = { path = "../call", default-features = false, features = ["ports"], optional = true }
workspace-hack = { version = "0.1", path = "../workspace-hack" }
[dev-dependencies]
+macro_db_migrator = { path = "../macro_db_migrator" }
messages = { path = "../messages", features = ["test-utils"] }
agent_session = { path = "../agent_session", features = ["test-utils"] }
bot_id = { path = "../bot_id", features = ["test-utils"] }
diff --git a/crates/agent_trigger/src/domain/broker_events.rs b/crates/agent_trigger/src/domain/broker_events.rs
index 10c29295f6..73131b8fd7 100644
--- a/crates/agent_trigger/src/domain/broker_events.rs
+++ b/crates/agent_trigger/src/domain/broker_events.rs
@@ -19,6 +19,8 @@ use messages::domain::events::{MessageEventAttachment, MessagePostedMetadata};
use messages::domain::models::MessageParent;
use serde::{Deserialize, Serialize};
+use trigger_context::TriggerContext;
+
#[cfg(test)]
mod test;
@@ -44,6 +46,10 @@ pub struct AgentBotMentionedEvent {
pub bot_id: BotId,
/// The message that triggered this, verbatim.
pub message: ChannelMessagePostedMetadata,
+ /// Why the agent was called, for whoever composes its prompt. Absent on
+ /// events from producers that predate it.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub context: Option<TriggerContext>,
}
/// A session opened by a mention on a message parent. Today only document
@@ -56,6 +62,10 @@ pub struct AgentMentionedEvent {
pub bot_id: BotId,
/// The message that triggered this, verbatim, with its parent.
pub message: MessagePostedMetadata,
+ /// Why the agent was called, for whoever composes its prompt. Absent on
+ /// events from producers that predate it.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub context: Option<TriggerContext>,
}
/// A session opened when a task is assigned to an agent.
@@ -71,6 +81,10 @@ pub struct AgentAssignedToTaskEvent {
pub actor: macro_user_id::user_id::MacroUserIdStr<'static>,
/// Private startup prompt, never posted as a discussion message.
pub prompt: String,
+ /// Why the agent was called, for whoever composes its prompt. Absent on
+ /// events from producers that predate it.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub context: Option<TriggerContext>,
}
/// A session somebody asked for from Macro itself - the composer - rather
@@ -92,6 +106,10 @@ pub struct AgentSessionRequestedEvent {
/// Repository selected by the requester, absent on older producers.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub repo_url: Option<String>,
+ /// Why the agent was called, for whoever composes its prompt. Absent on
+ /// events from producers that predate it.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub context: Option<TriggerContext>,
}
/// Events that open a new session.
@@ -117,6 +135,8 @@ pub struct OpeningMention {
pub bot_id: BotId,
/// The opening message, with its parent.
pub message: MessagePostedMetadata,
+ /// Why the agent was called.
+ pub context: Option<TriggerContext>,
}
impl NewAgentSessionEvent {
@@ -128,10 +148,12 @@ impl NewAgentSessionEvent {
Self::TopLevelMentioned(mentioned) => Some(OpeningMention {
bot_id: mentioned.bot_id,
message: posted_from_channel_event(&mentioned.message),
+ context: mentioned.context.clone(),
}),
Self::Mentioned(mentioned) => Some(OpeningMention {
bot_id: mentioned.bot_id,
message: mentioned.message.clone(),
+ context: mentioned.context.clone(),
}),
Self::AssignedToTask(_) | Self::Requested(_) => None,
}
@@ -159,6 +181,10 @@ pub struct ChannelEventMetadata {
pub kind: ThreadMessageKind,
/// The message, verbatim.
pub message: ChannelMessagePostedMetadata,
+ /// Why the agent was called, for whoever composes its prompt. Absent on
+ /// events from producers that predate it.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub context: Option<TriggerContext>,
}
/// A message for a session that already exists, with its parent. Today only
@@ -175,6 +201,10 @@ pub struct ThreadEventMetadata {
pub kind: ThreadMessageKind,
/// The message, verbatim, with its parent.
pub message: MessagePostedMetadata,
+ /// Why the agent was called, for whoever composes its prompt. Absent on
+ /// events from producers that predate it.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub context: Option<TriggerContext>,
}
/// Events for a session that already exists.
@@ -199,6 +229,8 @@ pub struct SessionMessage {
pub kind: ThreadMessageKind,
/// The message, with its parent.
pub message: MessagePostedMetadata,
+ /// Why the agent was called.
+ pub context: Option<TriggerContext>,
}
impl ExistingAgentSessionEvent {
@@ -212,12 +244,14 @@ impl ExistingAgentSessionEvent {
session_id: metadata.session_id,
kind: metadata.kind,
message: posted_from_channel_event(&metadata.message),
+ context: metadata.context.clone(),
}),
Self::Thread(metadata) => Some(SessionMessage {
bot_id: metadata.bot_id,
session_id: metadata.session_id,
kind: metadata.kind,
message: metadata.message.clone(),
+ context: metadata.context.clone(),
}),
}
}
@@ -346,6 +380,7 @@ impl AgentSessionMacroEvent {
pub fn from_decision(
decision: TriggerDecision,
channel_type: Option<ChannelType>,
+ context: Option<TriggerContext>,
) -> Result<Self, MissingChannelType> {
let channel = match &decision.message().parent {
MessageParent::Channel(channel_id) => Some(
@@ -367,11 +402,13 @@ impl AgentSessionMacroEvent {
NewAgentSessionEvent::TopLevelMentioned(AgentBotMentionedEvent {
bot_id,
message: channel_event_from_posted(&message, channel_id, channel_type),
+ context,
}),
),
None => Self::new_session(NewAgentSessionEvent::Mentioned(AgentMentionedEvent {
bot_id,
message,
+ context,
})),
},
TriggerDecision::Existing {
@@ -386,6 +423,7 @@ impl AgentSessionMacroEvent {
session_id,
kind,
message: channel_event_from_posted(&message, channel_id, channel_type),
+ context,
}),
bot_id,
),
@@ -395,6 +433,7 @@ impl AgentSessionMacroEvent {
session_id,
kind,
message,
+ context,
}),
bot_id,
),
diff --git a/crates/agent_trigger/src/domain/broker_events/test.rs b/crates/agent_trigger/src/domain/broker_events/test.rs
index 35f27f9d94..a237518343 100644
--- a/crates/agent_trigger/src/domain/broker_events/test.rs
+++ b/crates/agent_trigger/src/domain/broker_events/test.rs
@@ -59,6 +59,7 @@ fn serializes_a_new_top_level_mention() {
AgentBotMentionedEvent {
bot_id: BotId::TEST_A,
message: channel_message(),
+ context: None,
},
));
@@ -77,6 +78,7 @@ fn serializes_an_existing_channel_event() {
session_id: AgentSessionId::TEST_A,
kind: ThreadMessageKind::MentionThread,
message: channel_message(),
+ context: None,
},
));
@@ -102,6 +104,7 @@ fn channel_events_keep_the_first_schema_versions_shape() {
session_id: AgentSessionId::TEST_A,
kind: ThreadMessageKind::MentionThread,
message: channel_message(),
+ context: None,
},
));
let value = serde_json::to_value(&event).expect("serialize event");
@@ -126,6 +129,7 @@ fn parent_aware_events_name_their_parent_and_are_new_variants() {
session_id: AgentSessionId::TEST_A,
kind: ThreadMessageKind::MentionThread,
message: posted(document(), None),
+ context: None,
}));
let value = serde_json::to_value(&event).expect("serialize event");
assert_eq!(value["metadata"]["source"], "thread");
@@ -135,6 +139,7 @@ fn parent_aware_events_name_their_parent_and_are_new_variants() {
AgentTriggerTopicEvent::New(NewAgentSessionEvent::Mentioned(AgentMentionedEvent {
bot_id: BotId::TEST_A,
message: posted(document(), None),
+ context: None,
}));
let value = serde_json::to_value(&opened).expect("serialize event");
assert_eq!(value["metadata"]["source"], "mentioned");
@@ -152,6 +157,7 @@ fn task_assignment_round_trips_and_opens_on_its_discussion() {
discussion_id: message.message_id,
actor: message.sender.as_user().unwrap().clone(),
prompt: message.content.clone(),
+ context: None,
});
let published = AgentSessionMacroEvent::new_session(assigned.clone());
assert_eq!(published.key(), BotId::TEST_A.to_string());
@@ -175,6 +181,7 @@ fn accessors_present_both_shapes_as_parent_aware_messages() {
let from_channel = NewAgentSessionEvent::TopLevelMentioned(AgentBotMentionedEvent {
bot_id: BotId::TEST_A,
message: channel_message(),
+ context: None,
})
.mention()
.expect("a recognised shape");
@@ -194,6 +201,7 @@ fn accessors_present_both_shapes_as_parent_aware_messages() {
session_id: AgentSessionId::TEST_B,
kind: ThreadMessageKind::Inferred,
message: posted(document(), Some(Uuid::from_u128(7))),
+ context: None,
})
.session_message()
.expect("a recognised shape");
@@ -207,6 +215,7 @@ fn accessors_present_both_shapes_as_parent_aware_messages() {
session_id: AgentSessionId::TEST_A,
kind: ThreadMessageKind::ExplicitReply,
message: channel_message(),
+ context: None,
},
));
assert_eq!(topic.bot_id(), Some(BotId::TEST_A));
@@ -223,6 +232,7 @@ fn decisions_take_the_wire_shape_their_parent_needs() {
message: posted(channel.clone(), None),
},
Some(ChannelType::Team),
+ None,
)
.expect("a channel type was supplied");
assert_eq!(opened.key(), BotId::TEST_A.to_string());
@@ -243,6 +253,7 @@ fn decisions_take_the_wire_shape_their_parent_needs() {
message: posted(channel.clone(), Some(Uuid::from_u128(7))),
},
Some(ChannelType::Public),
+ None,
)
.expect("a channel type was supplied");
let AgentTriggerTopicEvent::Existing(ExistingAgentSessionEvent::Channel(metadata)) =
@@ -259,6 +270,7 @@ fn decisions_take_the_wire_shape_their_parent_needs() {
message: posted(document(), None),
},
None,
+ None,
)
.expect("documents need no channel type");
assert!(matches!(
@@ -274,6 +286,7 @@ fn decisions_take_the_wire_shape_their_parent_needs() {
message: posted(document(), Some(Uuid::from_u128(7))),
},
Some(ChannelType::Public),
+ None,
)
.expect("a stray channel type is ignored for documents");
assert!(matches!(
@@ -289,6 +302,7 @@ fn decisions_take_the_wire_shape_their_parent_needs() {
message: posted(channel, None),
},
None,
+ None,
)
.unwrap_err(),
MissingChannelType {
@@ -317,6 +331,7 @@ fn event_names_match_the_wire() {
AgentBotMentionedEvent {
bot_id: BotId::TEST_A,
message: channel_message(),
+ context: None,
},
)),
AgentTriggerTopicEvent::Existing(ExistingAgentSessionEvent::Channel(
@@ -325,6 +340,7 @@ fn event_names_match_the_wire() {
session_id: AgentSessionId::TEST_A,
kind: ThreadMessageKind::MentionThread,
message: channel_message(),
+ context: None,
},
)),
]
diff --git a/crates/agent_trigger/src/domain/context.rs b/crates/agent_trigger/src/domain/context.rs
new file mode 100644
index 0000000000..5cec10caee
--- /dev/null
+++ b/crates/agent_trigger/src/domain/context.rs
@@ -0,0 +1,52 @@
+//! Reading why an agent was called, for the trigger events that call it.
+
+use agent_session::domain::error::Result;
+use messages::domain::events::MessagePostedMetadata;
+use trigger_context::{
+ AddressedBy, ContextPerson, DiscussionContext, FollowUpContext, TriggerContext,
+};
+
+use crate::domain::broker_events::{ThreadMessageKind, TriggerDecision};
+use crate::domain::service::AuthorizedInvocation;
+
+/// Reads the discussion a message was posted in, under the poster's verified
+/// capability on its parent.
+#[cfg_attr(test, mockall::automock)]
+pub trait DiscussionReader: Send + Sync + 'static {
+ /// The message's surface, its own thread through the message, nearby
+ /// channel activity, what it replies to, and where a comment thread is
+ /// anchored.
+ fn discussion(
+ &self,
+ invocation: &AuthorizedInvocation,
+ posted: &MessagePostedMetadata,
+ ) -> impl Future<Output = Result<DiscussionContext>> + Send;
+}
+
+/// Names people and bots the way a reader would.
+#[cfg_attr(test, mockall::automock)]
+pub trait PeopleDirectory: Send + Sync + 'static {
+ /// One entry per id, in order. An id with no name on record is named by
+ /// its email, or by the id itself for a bot without a profile.
+ fn people(&self, ids: Vec<String>) -> impl Future<Output = Result<Vec<ContextPerson>>> + Send;
+}
+
+/// Why a decision calls its agent: a mention opens a session, anything else
+/// follows up in one that is running.
+#[must_use]
+pub fn discussion_trigger(
+ decision: &TriggerDecision,
+ discussion: DiscussionContext,
+) -> TriggerContext {
+ match decision {
+ TriggerDecision::Open { .. } => TriggerContext::Mentioned(discussion),
+ TriggerDecision::Existing { kind, .. } => TriggerContext::FollowUp(FollowUpContext {
+ addressed_by: match kind {
+ ThreadMessageKind::MentionThread => AddressedBy::Mention,
+ ThreadMessageKind::ExplicitReply => AddressedBy::ExplicitReply,
+ ThreadMessageKind::Inferred => AddressedBy::Inferred,
+ },
+ discussion,
+ }),
+ }
+}
diff --git a/crates/agent_trigger/src/domain/mod.rs b/crates/agent_trigger/src/domain/mod.rs
index 4781a6edaf..1e48fc305a 100644
--- a/crates/agent_trigger/src/domain/mod.rs
+++ b/crates/agent_trigger/src/domain/mod.rs
@@ -1,4 +1,5 @@
pub mod broker_events;
+pub mod context;
pub mod processing;
pub mod project_assignment;
pub mod service;
diff --git a/crates/agent_trigger/src/domain/processing.rs b/crates/agent_trigger/src/domain/processing.rs
index c30e12ca83..c38cd9f545 100644
--- a/crates/agent_trigger/src/domain/processing.rs
+++ b/crates/agent_trigger/src/domain/processing.rs
@@ -9,6 +9,7 @@ use messages::domain::events::MessagePostedMetadata;
use messages::domain::models::MessageParent;
use super::broker_events::{AgentSessionMacroEvent, AgentTriggerEventName};
+use super::context::{DiscussionReader, discussion_trigger};
use super::service::{
AgentBotLookup, AgentTriggerService, ChannelParticipationLookup, ExplicitReplyExtractor,
ImplicitTriggerJudge, TeamMembershipLookup, ThreadHistory,
@@ -72,11 +73,13 @@ pub async fn process_message_event<
Judge,
History,
Kinds,
+ Discussions,
Broker,
>(
trigger: &AgentTriggerService<Repo, Bots, Teams, Channels, Replies, Judge, History>,
publisher: &Broker,
kinds: &Kinds,
+ discussions: &Discussions,
input: &TriggerInput,
) -> Result<(), ProcessMessageEventError>
where
@@ -88,6 +91,7 @@ where
Judge: ImplicitTriggerJudge,
History: ThreadHistory,
Kinds: ChannelTypeLookup,
+ Discussions: DiscussionReader,
Broker: MacroEventBroker,
{
tracing::Span::current().record("macro.event.type", "message.posted");
@@ -134,8 +138,29 @@ where
) => None,
};
+ // Read once for every agent the message calls. Trigger events are
+ // admitted at most once, so a failed read publishes the events without
+ // context rather than dropping the prompts.
+ let discussion = match trigger.invocation(posted).await? {
+ Some(invocation) => discussions
+ .discussion(&invocation, posted)
+ .await
+ .inspect_err(|error| {
+ tracing::warn!(
+ error = ?error,
+ message_id = %posted.message_id,
+ "publishing agent triggers without their discussion"
+ );
+ })
+ .ok(),
+ None => None,
+ };
+
for decision in decisions {
- let yielded = AgentSessionMacroEvent::from_decision(decision, channel_type)
+ let context = discussion
+ .clone()
+ .map(|discussion| discussion_trigger(&decision, discussion));
+ let yielded = AgentSessionMacroEvent::from_decision(decision, channel_type, context)
.map_err(|error| AgentSessionError::Unknown(error.into()))?;
let event_type: &'static str = AgentTriggerEventName::from(&yielded.event().event).into();
tracing::info!(
diff --git a/crates/agent_trigger/src/domain/service.rs b/crates/agent_trigger/src/domain/service.rs
index d2fc6713fe..75dcccf5e0 100644
--- a/crates/agent_trigger/src/domain/service.rs
+++ b/crates/agent_trigger/src/domain/service.rs
@@ -344,6 +344,21 @@ where
}
}
+ /// The poster's current capability on the message's conversation, for
+ /// reading it as context. `None` when the poster is no user or may no
+ /// longer write there.
+ pub async fn invocation(
+ &self,
+ posted: &MessagePostedMetadata,
+ ) -> Result<Option<AuthorizedInvocation>> {
+ let Some(user) = posted.sender.as_user().cloned().map(CowLike::into_owned) else {
+ return Ok(None);
+ };
+ self.history
+ .authorize_invocation(&user, &posted.parent, posted.root_id())
+ .await
+ }
+
/// Evaluates a posted message for every mentioned bot.
#[tracing::instrument(err, skip(self, posted), fields(
parent = ?posted.parent,
diff --git a/crates/agent_trigger/src/domain/task_assignment.rs b/crates/agent_trigger/src/domain/task_assignment.rs
index 0439f5a18e..faee741a9e 100644
--- a/crates/agent_trigger/src/domain/task_assignment.rs
+++ b/crates/agent_trigger/src/domain/task_assignment.rs
@@ -2,7 +2,11 @@
use std::collections::HashSet;
-use agent_session::domain::error::Result as AgentResult;
+use agent_session::domain::error::{AgentSessionError, Result as AgentResult};
+use chrono::{DateTime, Utc};
+use trigger_context::{TaskAssignedContext, TaskSnapshot, TriggerContext};
+
+use crate::domain::context::PeopleDirectory;
use agent_session::domain::ports::AgentSessionRepo;
use bot_id::{BotId, BotIdStr};
use macro_event_broker::MacroEventBroker;
@@ -39,8 +43,16 @@ pub struct TaskBrief {
pub title: String,
/// Current task description in Markdown.
pub markdown: String,
+ /// Current Status option name.
+ pub status: Option<String>,
+ /// Current Priority option name.
+ pub priority: Option<String>,
+ /// Current due date.
+ pub due: Option<chrono::DateTime<chrono::Utc>>,
+ /// User and bot ids in the Assignees property, people and agents alike.
+ pub assignee_ids: Vec<String>,
/// Current project, only when the assigning principal can view it.
- pub project_id: Option<initiative::domain::models::InitiativeId>,
+ pub project: Option<trigger_context::ProjectRef>,
}
/// Reads the task through its owning service under a verified document capability.
@@ -119,11 +131,13 @@ pub async fn process_task_assignment<
History,
Broker,
Context,
+ People,
>(
trigger: &AgentTriggerService<Repo, Bots, Teams, Channels, Replies, Judge, History>,
publisher: &Broker,
messages: &dyn MessageCommands,
context: &Context,
+ people: &People,
assignment: &TaskAssignment,
) -> Result<(), ProcessMessageEventError>
where
@@ -136,6 +150,7 @@ where
History: ThreadHistory,
Broker: MacroEventBroker,
Context: TaskAssignmentContext,
+ People: PeopleDirectory,
{
for &bot_id in &assignment.bots {
let Some(invocation) = trigger
@@ -170,6 +185,7 @@ where
else {
continue;
};
+ let context = assigned_context(assignment, &brief, message.id, people).await?;
let event = AgentSessionMacroEvent::new_session(NewAgentSessionEvent::AssignedToTask(
AgentAssignedToTaskEvent {
bot_id,
@@ -177,6 +193,7 @@ where
discussion_id: message.id,
actor: assignment.actor.clone(),
prompt: assignment_prompt(assignment, &brief),
+ context: Some(context),
},
));
publisher
@@ -187,6 +204,57 @@ where
Ok(())
}
+/// The task as the agent should see it, with everyone named.
+async fn assigned_context(
+ assignment: &TaskAssignment,
+ brief: &TaskBrief,
+ discussion_id: Uuid,
+ people: &impl PeopleDirectory,
+) -> AgentResult<TriggerContext> {
+ let mut named = people
+ .people(
+ std::iter::once(assignment.actor.as_ref().to_owned())
+ .chain(brief.assignee_ids.iter().cloned())
+ .collect(),
+ )
+ .await?
+ .into_iter();
+ let assigned_by = named.next().ok_or_else(|| {
+ AgentSessionError::Unknown(anyhow::anyhow!("the people directory named nobody"))
+ })?;
+ Ok(TriggerContext::TaskAssigned(TaskAssignedContext {
+ task: TaskSnapshot {
+ id: assignment.parent.entity_id(),
+ title: brief.title.clone(),
+ markdown: brief.markdown.clone(),
+ status: brief.status.clone(),
+ priority: brief.priority.clone(),
+ due: brief.due,
+ assignees: named.collect(),
+ project: brief.project.clone(),
+ },
+ assigned_by,
+ assigned_at: assigned_at(assignment.event_id)?,
+ discussion_id,
+ }))
+}
+
+/// When the assignment was made: its source event id is a UUIDv7, which
+/// carries the moment the event was minted.
+fn assigned_at(event_id: Uuid) -> AgentResult<DateTime<Utc>> {
+ event_id
+ .get_timestamp()
+ .and_then(|timestamp| {
+ let (seconds, nanos) = timestamp.to_unix();
+ DateTime::from_timestamp(i64::try_from(seconds).ok()?, nanos)
+ })
+ .ok_or_else(|| {
+ AgentSessionError::Unknown(anyhow::anyhow!(
+ "assignment event {event_id} is not a UUIDv7"
+ ))
+ })
+}
+
/// Derive one replay-stable UUIDv7 per assigned bot, retaining the event timestamp.
/// The hashed random bits keep simultaneous agents in separate discussion threads.
fn discussion_id(event_id: Uuid, bot_id: BotId) -> Uuid {
@@ -208,7 +276,7 @@ fn assignment_prompt(assignment: &TaskAssignment, brief: &TaskBrief) -> String {
include_str!("task_assignment/prompt.md").trim(),
task_reference(&assignment.parent, &brief.title),
);
- if let Some(project_id) = brief.project_id {
+ if let Some(project_id) = brief.project.as_ref().map(|project| project.id) {
let project_reference = serde_json::json!({
"documentId": project_id,
"documentName": "Task project",
diff --git a/crates/agent_trigger/src/domain/task_assignment/project_context.rs b/crates/agent_trigger/src/domain/task_assignment/project_context.rs
index fa560bb8d1..214a829a72 100644
--- a/crates/agent_trigger/src/domain/task_assignment/project_context.rs
+++ b/crates/agent_trigger/src/domain/task_assignment/project_context.rs
@@ -3,8 +3,9 @@
use agent_session::domain::error::{AgentSessionError, Result};
use channel_sender::ChannelSender;
use entity_access::domain::models::{EntityAccessAuth, EntityAccessReceipt};
-use initiative::domain::events::InitiativeEventActor;
+use initiative::domain::{events::InitiativeEventActor, lookup::InitiativeReader};
use messages::domain::service::MessageWrite;
+use trigger_context::ProjectRef;
use crate::domain::project_assignment::{ProjectAssignmentAccess, ProjectMemberships};
@@ -14,28 +15,35 @@ use super::{TaskAssignmentContext, TaskBrief};
mod test;
/// Enriches task briefs with the current project only when the same actor can view it.
-pub struct ProjectTaskAssignmentContext<C, M, A> {
- tasks: C,
- memberships: M,
- access: A,
+pub struct ProjectTaskAssignmentContext<Tasks, Memberships, Access, Projects> {
+ tasks: Tasks,
+ memberships: Memberships,
+ access: Access,
+ projects: Projects,
}
-impl<C, M, A> ProjectTaskAssignmentContext<C, M, A> {
- /// Compose task content, current memberships, and project authorization ports.
- pub fn new(tasks: C, memberships: M, access: A) -> Self {
+impl<Tasks, Memberships, Access, Projects>
+ ProjectTaskAssignmentContext<Tasks, Memberships, Access, Projects>
+{
+ /// Compose task content, current memberships, project authorization, and
+ /// project identity ports.
+ pub fn new(tasks: Tasks, memberships: Memberships, access: Access, projects: Projects) -> Self {
Self {
tasks,
memberships,
access,
+ projects,
}
}
}
-impl<C, M, A> TaskAssignmentContext for ProjectTaskAssignmentContext<C, M, A>
+impl<Tasks, Memberships, Access, Projects> TaskAssignmentContext
+ for ProjectTaskAssignmentContext<Tasks, Memberships, Access, Projects>
where
- C: TaskAssignmentContext,
- M: ProjectMemberships + 'static,
- A: ProjectAssignmentAccess + 'static,
+ Tasks: TaskAssignmentContext,
+ Memberships: ProjectMemberships + 'static,
+ Access: ProjectAssignmentAccess + 'static,
+ Projects: InitiativeReader,
{
async fn task_brief(
&self,
@@ -45,7 +53,7 @@ where
return Ok(None);
};
// Membership may have changed since another source built the brief.
- brief.project_id = None;
+ brief.project = None;
let actor = match access.auth() {
EntityAccessAuth::Authenticated(user) => InitiativeEventActor {
actor: ChannelSender::new_from_user(user.clone()),
@@ -78,10 +86,20 @@ where
.receipts(&actor, project, task)
.await
.map_err(|error| AgentSessionError::Unknown(error.into()))?
- .is_some()
+ .is_none()
{
- brief.project_id = Some(project);
+ return Ok(Some(brief));
}
+ // A project deleted since the membership read is not named.
+ brief.project = self
+ .projects
+ .read_basic(project)
+ .await
+ .map_err(|error| AgentSessionError::Unknown(error.into()))?
+ .map(|project| ProjectRef {
+ id: project.id.as_uuid(),
+ name: project.name,
+ });
Ok(Some(brief))
}
}
diff --git a/crates/agent_trigger/src/domain/task_assignment/project_context/test.rs b/crates/agent_trigger/src/domain/task_assignment/project_context/test.rs
index 044cdaea6b..f573606775 100644
--- a/crates/agent_trigger/src/domain/task_assignment/project_context/test.rs
+++ b/crates/agent_trigger/src/domain/task_assignment/project_context/test.rs
@@ -8,10 +8,21 @@ use entity_access::domain::models::{
AccessError, AccessLevel, BotReceiptScope, Entity, EntityPermission, EntityType,
RequiredPermission,
};
-use initiative::domain::models::{InitiativeError, InitiativeId};
+use initiative::domain::models::{InitiativeBasic, InitiativeError, InitiativeId};
use macro_user_id::user_id::MacroUserIdStr;
use properties::{EditReceipt, ViewReceipt};
-use std::collections::HashMap;
+use std::{collections::HashMap, pin::Pin};
+use trigger_context::ProjectRef;
+
+mockall::mock! {
+ Projects {}
+ impl InitiativeReader for Projects {
+ fn read_basic<'a>(
+ &'a self,
+ id: InitiativeId,
+ ) -> Pin<Box<dyn Future<Output = std::result::Result<Option<InitiativeBasic>, InitiativeError>> + Send + 'a>>;
+ }
+}
fn user() -> MacroUserIdStr<'static> {
MacroUserIdStr::try_from_email("[email protected]").unwrap()
@@ -54,7 +65,14 @@ fn brief() -> TaskBrief {
TaskBrief {
title: "Fix export".to_owned(),
markdown: "Include archived rows.".to_owned(),
- project_id: Some(InitiativeId::generate()),
+ status: Some("In Progress".to_owned()),
+ priority: None,
+ due: None,
+ assignee_ids: vec![BotId::TEST_A.to_string()],
+ project: Some(ProjectRef {
+ id: InitiativeId::generate().as_uuid(),
+ name: "Stale project".to_owned(),
+ }),
}
}
@@ -101,6 +119,24 @@ fn allowed(
Box::pin(async move { Ok(Some(result)) })
}
+fn named(project: InitiativeId, name: &'static str) -> MockProjects {
+ let mut projects = MockProjects::new();
+ projects
+ .expect_read_basic()
+ .once()
+ .withf(move |id| *id == project)
+ .return_once(move |id| {
+ Box::pin(async move {
+ Ok(Some(InitiativeBasic {
+ id,
+ name: name.to_owned(),
+ owner_id: user(),
+ }))
+ })
+ });
+ projects
+}
+
#[tokio::test]
async fn current_project_replaces_stale_context_after_authorizing_the_same_user() {
let project = InitiativeId::generate();
@@ -117,17 +153,29 @@ async fn current_project_replaces_stale_context_after_authorizing_the_same_user(
})
.returning(allowed);
let result = ProjectTaskAssignmentContext::new(
- tasks(Some(original.clone())),
+ tasks(Some(original)),
membership(Some(project)),
access,
+ named(project, "Exports"),
)
.task_brief(task_access())
.await
- .unwrap()
.unwrap();
- assert_eq!(result.project_id, Some(project));
- assert_eq!(result.title, original.title);
- assert_eq!(result.markdown, original.markdown);
+ assert_eq!(
+ result,
+ Some(TaskBrief {
+ title: "Fix export".to_owned(),
+ markdown: "Include archived rows.".to_owned(),
+ status: Some("In Progress".to_owned()),
+ priority: None,
+ due: None,
+ assignee_ids: vec![BotId::TEST_A.to_string()],
+ project: Some(ProjectRef {
+ id: project.as_uuid(),
+ name: "Exports".to_owned(),
+ }),
+ })
+ );
}
#[tokio::test]
@@ -142,15 +190,25 @@ async fn delegated_bot_keeps_its_identity_and_acting_user_for_project_access() {
&& actor.on_behalf_of.as_ref() == Some(&user())
})
.returning(allowed);
- let result =
- ProjectTaskAssignmentContext::new(tasks(Some(brief())), membership(Some(project)), access)
- .task_brief(bot_access(BotReceiptScope::User {
- acting_user: user(),
- }))
- .await
- .unwrap()
- .unwrap();
- assert_eq!(result.project_id, Some(project));
+ let result = ProjectTaskAssignmentContext::new(
+ tasks(Some(brief())),
+ membership(Some(project)),
+ access,
+ named(project, "Exports"),
+ )
+ .task_brief(bot_access(BotReceiptScope::User {
+ acting_user: user(),
+ }))
+ .await
+ .unwrap()
+ .unwrap();
+ assert_eq!(
+ result.project,
+ Some(ProjectRef {
+ id: project.as_uuid(),
+ name: "Exports".to_owned(),
+ })
+ );
}
#[tokio::test]
@@ -163,13 +221,17 @@ async fn no_project_or_revoked_access_removes_stale_project_context() {
.once()
.returning(|_, _, _| Box::pin(async { Ok(None) }));
}
- let result =
- ProjectTaskAssignmentContext::new(tasks(Some(brief())), membership(project), access)
- .task_brief(task_access())
- .await
- .unwrap()
- .unwrap();
- assert_eq!(result.project_id, None);
+ let result = ProjectTaskAssignmentContext::new(
+ tasks(Some(brief())),
+ membership(project),
+ access,
+ MockProjects::new(),
+ )
+ .task_brief(task_access())
+ .await
+ .unwrap()
+ .unwrap();
+ assert_eq!(result.project, None);
}
}
@@ -179,6 +241,7 @@ async fn missing_tasks_do_not_read_project_membership() {
tasks(None),
MockProjectMemberships::new(),
MockProjectAssignmentAccess::new(),
+ MockProjects::new(),
)
.task_brief(task_access())
.await
@@ -198,12 +261,13 @@ async fn receipts_without_an_acting_user_do_not_expose_project_context() {
tasks(Some(brief())),
MockProjectMemberships::new(),
MockProjectAssignmentAccess::new(),
+ MockProjects::new(),
)
.task_brief(receipt)
.await
.unwrap()
.unwrap();
- assert_eq!(result.project_id, None);
+ assert_eq!(result.project, None);
}
}
@@ -221,6 +285,7 @@ async fn project_membership_and_access_failures_are_retried() {
tasks(Some(brief())),
memberships,
MockProjectAssignmentAccess::new(),
+ MockProjects::new(),
)
.task_brief(task_access())
.await;
@@ -238,8 +303,54 @@ async fn project_membership_and_access_failures_are_retried() {
tasks(Some(brief())),
membership(Some(InitiativeId::generate())),
access,
+ MockProjects::new(),
+ )
+ .task_brief(task_access())
+ .await;
+ assert!(matches!(result, Err(AgentSessionError::Unknown(_))));
+
+ let project = InitiativeId::generate();
+ let mut access = MockProjectAssignmentAccess::new();
+ access.expect_receipts().once().returning(allowed);
+ let mut projects = MockProjects::new();
+ projects.expect_read_basic().once().return_once(|_| {
+ Box::pin(async {
+ Err(InitiativeError::Internal(
+ std::io::Error::other("database unavailable").into(),
+ ))
+ })
+ });
+ let result = ProjectTaskAssignmentContext::new(
+ tasks(Some(brief())),
+ membership(Some(project)),
+ access,
+ projects,
)
.task_brief(task_access())
.await;
assert!(matches!(result, Err(AgentSessionError::Unknown(_))));
}
+
+#[tokio::test]
+async fn a_deleted_project_is_not_named() {
+ let project = InitiativeId::generate();
+ let mut access = MockProjectAssignmentAccess::new();
+ access.expect_receipts().once().returning(allowed);
+ let mut projects = MockProjects::new();
+ projects
+ .expect_read_basic()
+ .once()
+ .withf(move |id| *id == project)
+ .return_once(|_| Box::pin(async { Ok(None) }));
+ let result = ProjectTaskAssignmentContext::new(
+ tasks(Some(brief())),
+ membership(Some(project)),
+ access,
+ projects,
+ )
+ .task_brief(task_access())
+ .await
+ .unwrap()
+ .unwrap();
+ assert_eq!(result.project, None);
+}
diff --git a/crates/agent_trigger/src/domain/task_assignment/test.rs b/crates/agent_trigger/src/domain/task_assignment/test.rs
index 20976bac58..ef1b3e2b2f 100644
--- a/crates/agent_trigger/src/domain/task_assignment/test.rs
+++ b/crates/agent_trigger/src/domain/task_assignment/test.rs
@@ -10,7 +10,11 @@ fn brief() -> TaskBrief {
TaskBrief {
title: "Fix export".to_owned(),
markdown: "Include archived rows in CSV exports.".to_owned(),
- project_id: None,
+ status: None,
+ priority: None,
+ due: None,
+ assignee_ids: Vec::new(),
+ project: None,
}
}
@@ -381,7 +385,10 @@ async fn authorized_assignment_publishes_the_task_brief_for_toolless_runtimes()
.returning(move |_| {
Box::pin(async move {
Ok(Some(TaskBrief {
- project_id: Some(project_id),
+ project: Some(trigger_context::ProjectRef {
+ id: project_id.as_uuid(),
+ name: "Exports".to_owned(),
+ }),
..brief()
}))
})
@@ -397,13 +404,36 @@ async fn authorized_assignment_publishes_the_task_brief_for_toolless_runtimes()
message.content = input.content;
Ok(message)
});
+ let mut people = crate::domain::context::MockPeopleDirectory::new();
+ people.expect_people().once().returning(|ids| {
+ Box::pin(async move {
+ Ok(ids
+ .into_iter()
+ .map(|id| trigger_context::ContextPerson {
+ name: format!("name of {id}"),
+ email: None,
+ id,
+ })
+ .collect())
+ })
+ });
let broker = RecordedEvents::default();
- process_task_assignment(&trigger, &broker, &commands, &context, &assignment)
+ process_task_assignment(&trigger, &broker, &commands, &context, &people, &assignment)
.await
.unwrap();
let events = broker.0.lock().unwrap();
assert_eq!(events.len(), 1);
let metadata = &events[0]["metadata"];
+ let context = &metadata["context"];
+ assert_eq!(context["kind"], "task_assigned");
+ assert_eq!(context["task"]["id"], "task-1");
+ assert_eq!(context["task"]["title"], "Fix export");
+ assert_eq!(
+ context["task"]["project"],
+ serde_json::json!({ "id": project_id.to_string(), "name": "Exports" })
+ );
+ assert_eq!(context["assigned_by"]["id"], assignment.actor.as_ref());
+ assert_eq!(context["discussion_id"], event_id.to_string());
assert_eq!(metadata["source"], "assigned_to_task");
assert_eq!(metadata["bot_id"], bot_id::CODEX_BOT_ID.to_string());
let prompt = metadata["prompt"].as_str().unwrap();
diff --git a/crates/agent_trigger/src/outbound/discussion_context.rs b/crates/agent_trigger/src/outbound/discussion_context.rs
new file mode 100644
index 0000000000..7066803d22
--- /dev/null
+++ b/crates/agent_trigger/src/outbound/discussion_context.rs
@@ -0,0 +1,682 @@
+//! The discussion a message was posted in, read through the common message
+//! read port under the poster's verified capability on its parent.
+
+#[cfg(test)]
+mod test;
+
+use std::collections::HashMap;
+use std::sync::Arc;
+
+use agent_session::domain::error::{AgentSessionError, Result};
+use call::domain::{models::CallRecordPreview, ports::CallRepository};
+use channels::domain::{models::ChannelType as StoredChannelType, ports::ChannelRepo};
+use document_storage_service_client::DocumentStorageServiceClient;
+use entity_access::domain::models::EntityAccessReceipt;
+use initiative::domain::{lookup::InitiativeReader, models::InitiativeId};
+use lexical_client::LexicalClient;
+use lexical_client::parse_markdown::ExtractedExplicitReply;
+use macro_uuid::Uuid;
+use messages::domain::{
+ api::MessageReader,
+ events::MessagePostedMetadata,
+ models::{Message, MessageParent, MessageThread, ThreadAnchor},
+ ports::CrmParentReader,
+ service::MessageView,
+};
+use trigger_context::{
+ ChannelType, CommentAnchor, ContextMessage, ContextPerson, ContextThread, DiscussionContext,
+ DiscussionSurface, MarkedPassage, ReplyTarget,
+};
+
+use crate::domain::{
+ context::{DiscussionReader, PeopleDirectory},
+ service::AuthorizedInvocation,
+};
+
+/// Channel messages before the prompt read as the surrounding activity.
+const CHANNEL_MESSAGES: u16 = 10;
+
+/// Most messages of the prompt's own discussion carried. The root is always
+/// kept, so a long thread loses its middle rather than its subject.
+const THREAD_MESSAGES: usize = 50;
+
+/// What a message's parent is called.
+#[derive(Debug, Clone, PartialEq, Eq)]
+enum ParentName {
+ /// A channel's stored name, absent for direct messages, and its type.
+ Channel {
+ name: Option<String>,
+ channel_type: ChannelType,
+ },
+ /// Any other parent's display name.
+ Named(String),
+}
+
+/// Reads what a message's parent is called. It checks no access of its own:
+/// it is only asked under the actor's capability on that parent.
+trait ParentNames: Send + Sync + 'static {
+ fn name(
+ &self,
+ access: &EntityAccessReceipt<MessageView>,
+ parent: &MessageParent,
+ ) -> impl Future<Output = Result<ParentName>> + Send;
+}
+
+/// Reads what a comment mark covers in the live document. It checks no access
+/// of its own: it is only asked after the thread was read under the actor's
+/// capability on that document.
+trait MarkReader: Send + Sync + 'static {
+ fn resolve(
+ &self,
+ document_id: &str,
+ mark_id: &str,
+ ) -> impl Future<Output = anyhow::Result<Option<MarkedPassage>>> + Send;
+}
+
+impl MarkReader for LexicalClient {
+ async fn resolve(
+ &self,
+ document_id: &str,
+ mark_id: &str,
+ ) -> anyhow::Result<Option<MarkedPassage>> {
+ Ok(self
+ .resolve_comment_mark(document_id, mark_id)
+ .await?
+ .map(|mark| MarkedPassage {
+ marked_text: mark.marked_text,
+ surrounding_text: mark.surrounding_text,
+ }))
+ }
+}
+
+/// Reads the message a prompt quote-replies to out of the prompt's markdown.
+/// The quoted message itself is read separately, under the actor's access.
+trait QuoteReader: Send + Sync + 'static {
+ fn quoted(
+ &self,
+ markdown: &str,
+ ) -> impl Future<Output = anyhow::Result<Option<ExtractedExplicitReply>>> + Send;
+}
+
+impl QuoteReader for LexicalClient {
+ async fn quoted(&self, markdown: &str) -> anyhow::Result<Option<ExtractedExplicitReply>> {
+ self.extract_explicit_reply(markdown).await
+ }
+}
+
+/// Names every kind of message parent through the domain that owns it.
+pub struct ParentNameReader<Channels, Calls> {
+ channels: Channels,
+ documents: DocumentStorageServiceClient,
+ initiatives: Arc<dyn InitiativeReader>,
+ crm: Arc<dyn CrmParentReader>,
+ calls: Calls,
+}
+
+impl<Channels, Calls> ParentNameReader<Channels, Calls> {
+ /// Compose the owning readers of channels, documents, projects, CRM
+ /// records and calls.
+ pub fn new(
+ channels: Channels,
+ documents: DocumentStorageServiceClient,
+ initiatives: impl InitiativeReader,
+ crm: impl CrmParentReader,
+ calls: Calls,
+ ) -> Self {
+ Self {
+ channels,
+ documents,
+ initiatives: Arc::new(initiatives),
+ crm: Arc::new(crm),
+ calls,
+ }
+ }
+}
+
+fn unknown(error: impl Into<anyhow::Error>) -> AgentSessionError {
+ AgentSessionError::Unknown(error.into())
+}
+
+fn unnamed(parent: &MessageParent, why: &str) -> AgentSessionError {
+ AgentSessionError::Unknown(anyhow::anyhow!("{why}: {parent:?}"))
+}
+
+impl<Channels: ChannelRepo, Calls: CallRepository> ParentNames
+ for ParentNameReader<Channels, Calls>
+{
+ async fn name(
+ &self,
+ access: &EntityAccessReceipt<MessageView>,
+ parent: &MessageParent,
+ ) -> Result<ParentName> {
+ let name = match parent {
+ MessageParent::Channel(id) => {
+ let info = self.channels.get_channel_info(*id).await.map_err(unknown)?;
+ let channel_type = match info.channel_type {
+ StoredChannelType::Public => ChannelType::Public,
+ StoredChannelType::Private => ChannelType::Private,
+ StoredChannelType::DirectMessage => ChannelType::DirectMessage,
+ StoredChannelType::Team => ChannelType::Team,
+ };
+ // Direct messages and unnamed group conversations are named
+ // after their members, per viewer; only they lack a name.
+ if info.name.is_none()
+ && matches!(channel_type, ChannelType::Public | ChannelType::Team)
+ {
+ return Err(unnamed(parent, "channel has no name"));
+ }
+ return Ok(ParentName::Channel {
+ name: info.name,
+ channel_type,
+ });
+ }
+ MessageParent::Document(_) => self
+ .documents
+ .get_document_basic(&parent.entity_id())
+ .await
+ .map_err(unknown)?
+ .filter(|document| document.deleted_at.is_none())
+ .map(|document| document.document_name),
+ MessageParent::Initiative(id) => self
+ .initiatives
+ .read_basic(InitiativeId::from_uuid(*id))
+ .await
+ .map_err(unknown)?
+ .map(|initiative| initiative.name),
+ MessageParent::CrmCompany(_) | MessageParent::CrmContact(_) => self
+ .crm
+ .read_crm_parent(parent)
+ .await
+ .map_err(|error| unknown(anyhow::anyhow!("{error:?}")))?
+ .map(|record| record.name),
+ MessageParent::Call(id) => {
+ // A call is named by its own title, else by its channel as
+ // the viewer sees it.
+ let viewer = access.get_authenticated_user().map_err(unknown)?.clone();
+ let previews = self
+ .calls
+ .batch_get_call_record_previews(&[*id], viewer)
+ .await
+ .map_err(unknown)?;
+ match previews.into_iter().next() {
+ Some(CallRecordPreview::Exists(call)) => call.custom_name.or(call.channel_name),
+ Some(CallRecordPreview::DoesNotExist(_)) | None => None,
+ }
+ }
+ };
+ name.filter(|name| !name.trim().is_empty())
+ .map(ParentName::Named)
+ .ok_or_else(|| unnamed(parent, "discussion parent has no name"))
+ }
+}
+
+/// Reads a message's discussion under the capability its invocation verified.
+pub struct MessageDiscussionReader<People, Names, Lexical = LexicalClient> {
+ messages: Arc<dyn MessageReader>,
+ people: People,
+ names: Names,
+ lexical: Lexical,
+}
+
+impl<People, Names, Lexical> MessageDiscussionReader<People, Names, Lexical> {
+ /// Compose the shared message read port, the people directory, the
+ /// parent names, and the lexical service that resolves comment marks and
+ /// quotes.
+ pub fn new(
+ messages: Arc<dyn MessageReader>,
+ people: People,
+ names: Names,
+ lexical: Lexical,
+ ) -> Self {
+ Self {
+ messages,
+ people,
+ names,
+ lexical,
+ }
+ }
+}
+
+impl<People, Names, Lexical> DiscussionReader for MessageDiscussionReader<People, Names, Lexical>
+where
+ People: PeopleDirectory,
+ Names: ParentNames,
+ Lexical: MarkReader + QuoteReader,
+{
+ /// The prompt's own discussion is read whole, because that is what the
+ /// prompt is about. Nearby channel messages are grouped by the discussion
+ /// they belong to so the agent can tell them apart from it.
+ async fn discussion(
+ &self,
+ invocation: &AuthorizedInvocation,
+ posted: &MessagePostedMetadata,
+ ) -> Result<DiscussionContext> {
+ let access: EntityAccessReceipt<MessageView> = invocation
+ .access()
+ .clone()
+ .try_into_requirement()
+ .map_err(unknown)?;
+ // The capability covers one parent and one discussion; a post claiming
+ // another is never read with it.
+ if access.entity().entity_type != posted.parent.access_entity_type()
+ || access.entity().entity_id != posted.parent.entity_id()
+ || invocation.root_id() != posted.root_id
+ {
+ return Err(AgentSessionError::Forbidden);
+ }
+ let parent = &posted.parent;
+ let root_id = posted.root_id;
+ let prompt = self
+ .messages
+ .get(access.clone(), posted.message_id)
+ .await
+ .map_err(unknown)?;
+ let is_channel = matches!(parent, MessageParent::Channel(_));
+ let top_level = is_channel && root_id == prompt.id;
+
+ let discussion = if top_level {
+ None
+ } else {
+ Some(
+ self.messages
+ .get_thread(access.clone(), root_id)
+ .await
+ .map_err(unknown)?,
+ )
+ };
+ let recent = if is_channel {
+ self.messages
+ .preceding(access.clone(), prompt.id, CHANNEL_MESSAGES)
+ .await
+ .map_err(unknown)?
+ } else {
+ Vec::new()
+ };
+ let quote = quote(
+ self.messages.as_ref(),
+ &self.lexical,
+ parent,
+ &prompt,
+ access.clone(),
+ )
+ .await;
+ let name = self.names.name(&access, parent).await?;
+ let anchor = match (parent, &discussion) {
+ (MessageParent::Document(_), Some(discussion)) => {
+ anchor(&self.lexical, parent, discussion.state.anchor.clone()).await
+ }
+ _ => None,
+ };
+
+ let thread = discussion
+ .as_ref()
+ .map(|discussion| prompt_thread(discussion, &prompt));
+ let mut channel = channel_threads(&recent, root_id);
+ if top_level {
+ channel.push(Selection {
+ root_id: prompt.id,
+ messages: std::iter::once(&prompt).filter(|m| readable(m)).collect(),
+ messages_omitted: false,
+ });
+ }
+ let quoted = quote.as_ref().and_then(|quote| quote.message.as_ref());
+
+ let authors: Vec<&Message> = std::iter::once(&prompt)
+ .chain(
+ thread
+ .iter()
+ .flat_map(|thread| thread.messages.iter().copied()),
+ )
+ .chain(
+ channel
+ .iter()
+ .flat_map(|thread| thread.messages.iter().copied()),
+ )
+ .chain(quoted)
+ .collect();
+ let people = self.people_of(&authors).await?;
+
+ let reply_target = match quote {
+ Some(quote) => ReplyTarget::Quote {
+ message_id: quote.message_id,
+ thread_id: quote.thread_id,
+ preview: quote.preview,
+ message: quote
+ .message
+ .as_ref()
+ .map(|message| people.message(message)),
+ },
+ None if top_level => ReplyTarget::None,
+ None => ReplyTarget::Thread { root_id },
+ };
+ Ok(DiscussionContext {
+ surface: surface(parent, name, anchor)?,
+ prompt_message_id: prompt.id,
+ sender: people.author(&prompt),
+ reply_target,
+ thread: thread.map(|thread| people.thread(thread)),
+ channel: channel
+ .into_iter()
+ .map(|thread| people.thread(thread))
+ .collect(),
+ })
+ }
+}
+
+impl<People: PeopleDirectory, Names, Lexical> MessageDiscussionReader<People, Names, Lexical> {
+ /// Everyone who wrote one of `messages`, named once each.
+ async fn people_of(&self, messages: &[&Message]) -> Result<Authors> {
+ let mut ids: Vec<String> = Vec::new();
+ for message in messages {
+ if let Some(id) = directory_id(message)
+ && !ids.contains(&id)
+ {
+ ids.push(id);
+ }
+ }
+ let people = self.people.people(ids.clone()).await?;
+ if people.len() != ids.len() {
+ return Err(AgentSessionError::Unknown(anyhow::anyhow!(
+ "people directory named {} of {} authors",
+ people.len(),
+ ids.len()
+ )));
+ }
+ Ok(Authors(ids.into_iter().zip(people).collect()))
+ }
+}
+
+/// Where the discussion lives, by name.
+fn surface(
+ parent: &MessageParent,
+ name: ParentName,
+ anchor: Option<CommentAnchor>,
+) -> Result<DiscussionSurface> {
+ Ok(match (parent, name) {
+ (MessageParent::Channel(id), ParentName::Channel { name, channel_type }) => {
+ DiscussionSurface::Channel {
+ id: *id,
+ name,
+ channel_type,
+ }
+ }
+ (MessageParent::Document(_), ParentName::Named(name)) => {
+ DiscussionSurface::DocumentComment {
+ id: parent.entity_id(),
+ name,
+ anchor,
+ }
+ }
+ (MessageParent::Initiative(id), ParentName::Named(name)) => {
+ DiscussionSurface::ProjectComment { id: *id, name }
+ }
+ (MessageParent::CrmCompany(id), ParentName::Named(name)) => {
+ DiscussionSurface::CrmCompanyComment { id: *id, name }
+ }
+ (MessageParent::CrmContact(id), ParentName::Named(name)) => {
+ DiscussionSurface::CrmContactComment { id: *id, name }
+ }
+ (MessageParent::Call(id), ParentName::Named(title)) => {
+ DiscussionSurface::CallChat { id: *id, title }
+ }
+ (parent, name) => {
+ return Err(AgentSessionError::Unknown(anyhow::anyhow!(
+ "{parent:?} was named as {name:?}"
+ )));
+ }
+ })
+}
+
+/// Where a document discussion sits, and what that anchor covers now. A PDF
+/// highlight's text arrives with the thread; a markdown mark is resolved
+/// against the live document, and a failed lookup leaves the stored
+/// snapshot to stand in rather than failing the prompt.
+async fn anchor(
+ lexical: &impl MarkReader,
+ parent: &MessageParent,
+ anchor: Option<ThreadAnchor>,
+) -> Option<CommentAnchor> {
+ let (mark_id, marked_text) = match anchor? {
+ ThreadAnchor::Spreadsheet {
+ sheet_id,
+ sheet_name,
+ range,
+ } => {
+ return Some(CommentAnchor::Spreadsheet {
+ sheet_id,
+ sheet_name,
+ range,
+ });
+ }
+ ThreadAnchor::PdfHighlight {
+ anchor_id,
+ marked_text,
+ } => {
+ return Some(CommentAnchor::PdfHighlight {
+ anchor_id: anchor_id.to_string(),
+ marked_text,
+ });
+ }
+ ThreadAnchor::PdfPlaceable { anchor_id } => {
+ return Some(CommentAnchor::PdfPin {
+ anchor_id: anchor_id.to_string(),
+ });
+ }
+ // The lexical prompt composer has no design anchor kind yet, so a
+ // design pin reaches the agent as an unanchored thread on the design.
+ ThreadAnchor::Fig { .. } => return None,
+ ThreadAnchor::Markdown {
+ mark_id,
+ marked_text,
+ } => (mark_id.to_string(), marked_text),
+ };
+ let current = lexical
+ .resolve(&parent.entity_id(), &mark_id)
+ .await
+ .inspect_err(|error| {
+ tracing::warn!(
+ error = ?error,
+ ?parent,
+ %mark_id,
+ "sending comment anchor without the live marked text"
+ );
+ })
+ .ok()
+ .flatten();
+ Some(CommentAnchor::Mark {
+ mark_id,
+ marked_text,
+ current,
+ })
+}
+
+/// A quote-reply target, with the quoted message when it could be read.
+struct Quote {
+ message_id: Uuid,
+ thread_id: Uuid,
+ preview: String,
+ message: Option<Message>,
+}
+
+/// The message the prompt quote-replies to, when it is one. The quoted
+/// message is only read when it sits in the prompt's own conversation,
+/// which the actor's access already covers; a quote from elsewhere
+/// travels as its preview.
+async fn quote(
+ messages: &dyn MessageReader,
+ lexical: &impl QuoteReader,
+ parent: &MessageParent,
+ prompt: &Message,
+ access: EntityAccessReceipt<MessageView>,
+) -> Option<Quote> {
+ let quoted = lexical
+ .quoted(&prompt.content)
+ .await
+ .inspect_err(|error| {
+ tracing::warn!(
+ error = ?error,
+ message_id = %prompt.id,
+ "sending agent prompt without its quote-reply target"
+ );
+ })
+ .ok()
+ .flatten()?;
+ let (Ok(message_id), Ok(thread_id)) = (
+ Uuid::parse_str(&quoted.target_message_id),
+ Uuid::parse_str(&quoted.target_thread_id),
+ ) else {
+ tracing::warn!(
+ target_message_id = %quoted.target_message_id,
+ target_thread_id = %quoted.target_thread_id,
+ "quote-reply target is not a message id"
+ );
+ return None;
+ };
+ let message = if quoted.parent == *parent {
+ messages
+ .get(access, message_id)
+ .await
+ .inspect_err(|error| {
+ tracing::warn!(error = ?error, %message_id, "quoted message is unreadable");
+ })
+ .ok()
+ .filter(|message| message.parent == *parent && readable(message))
+ } else {
+ None
+ };
+ Some(Quote {
+ message_id,
+ thread_id,
+ preview: quoted.display_text,
+ message,
+ })
+}
+
+/// Messages of one discussion chosen for the context, before their authors
+/// are named.
+struct Selection<'a> {
+ root_id: Uuid,
+ messages: Vec<&'a Message>,
+ messages_omitted: bool,
+}
+
+/// Whether a message is live and says something.
+fn readable(message: &Message) -> bool {
+ message.deleted_at.is_none() && !message.content.trim().is_empty()
+}
+
+/// The prompt's discussion from its root through the prompt. Replies posted
+/// after the prompt belong to later turns and are left out.
+fn prompt_thread<'a>(discussion: &'a MessageThread, prompt: &'a Message) -> Selection<'a> {
+ let root_id = discussion.state.root_id;
+ let mut messages = Vec::new();
+ let mut reached_prompt = false;
+ for message in std::iter::once(&discussion.root).chain(&discussion.replies) {
+ if readable(message) {
+ messages.push(message);
+ }
+ if message.id == prompt.id {
+ reached_prompt = true;
+ break;
+ }
+ }
+ if !reached_prompt && !prompt.content.trim().is_empty() {
+ messages.push(prompt);
+ }
+
+ let messages_omitted = messages.len() > THREAD_MESSAGES;
+ if messages_omitted {
+ let keep_root = messages
+ .first()
+ .is_some_and(|message| message.id == root_id);
+ let tail = messages.split_off(messages.len() - (THREAD_MESSAGES - usize::from(keep_root)));
+ messages.truncate(usize::from(keep_root));
+ messages.extend(tail);
+ }
+ Selection {
+ root_id,
+ messages,
+ messages_omitted,
+ }
+}
+
+/// Channel messages outside the prompt's discussion, grouped by the
+/// discussion each belongs to, in the order the discussions first appear.
+fn channel_threads(recent: &[Message], prompt_root: Uuid) -> Vec<Selection<'_>> {
+ let mut threads: Vec<Selection<'_>> = Vec::new();
+ for message in recent {
+ let root_id = message.root_id();
+ if root_id == prompt_root || !readable(message) {
+ continue;
+ }
+ match threads.iter_mut().find(|thread| thread.root_id == root_id) {
+ Some(thread) => thread.messages.push(message),
+ None => threads.push(Selection {
+ root_id,
+ // A reply whose root fell outside the window.
+ messages_omitted: message.id != root_id,
+ messages: vec![message],
+ }),
+ }
+ }
+ threads
+}
+
+/// The directory id of a message's author, when the message does not name
+/// its author itself.
+fn directory_id(message: &Message) -> Option<String> {
+ (message.imported_author.is_none() && message.bot_profile.is_none())
+ .then(|| message.sender_id.as_ref().to_owned())
+}
+
+/// Authors named by the people directory, by directory id.
+struct Authors(HashMap<String, ContextPerson>);
+
+impl Authors {
+ /// Who wrote a message, as a reader would name them. Imported messages
+ /// and bot posts carry their own names.
+ fn author(&self, message: &Message) -> ContextPerson {
+ let id = message.sender_id.as_ref().to_owned();
+ if let Some(imported) = &message.imported_author {
+ return ContextPerson {
+ id,
+ name: imported.name.clone(),
+ email: None,
+ };
+ }
+ if let Some(bot) = &message.bot_profile {
+ return ContextPerson {
+ id,
+ name: bot.name.clone(),
+ email: None,
+ };
+ }
+ // Every author was named before any message is built.
+ self.0.get(&id).cloned().unwrap_or(ContextPerson {
+ name: id.clone(),
+ id,
+ email: None,
+ })
+ }
+
+ fn message(&self, message: &Message) -> ContextMessage {
+ ContextMessage {
+ id: message.id,
+ author: self.author(message),
+ content: message.content.trim().to_owned(),
+ posted_at: message.created_at,
+ }
+ }
+
+ fn thread(&self, selection: Selection<'_>) -> ContextThread {
+ ContextThread {
+ root_id: selection.root_id,
+ messages: selection
+ .messages
+ .into_iter()
+ .map(|message| self.message(message))
+ .collect(),
+ messages_omitted: selection.messages_omitted,
+ }
+ }
+}
diff --git a/crates/agent_trigger/src/outbound/discussion_context/test.rs b/crates/agent_trigger/src/outbound/discussion_context/test.rs
new file mode 100644
index 0000000000..7bf6594a8f
--- /dev/null
+++ b/crates/agent_trigger/src/outbound/discussion_context/test.rs
@@ -0,0 +1,1123 @@
+use super::*;
+use chrono::{DateTime, Utc};
+use entity_access::domain::models::{AccessLevel, Entity, EntityPermission};
+use macro_user_id::user_id::MacroUserIdStr;
+use messages::domain::{
+ api::MockMessageReader,
+ models::{BotSenderProfile, ImportedAuthor, MessageThread, ThreadState},
+};
+
+/// The lexical service's lookups, each answering one fixed result.
+struct Lexical {
+ mark: std::result::Result<Option<MarkedPassage>, &'static str>,
+ quote: std::result::Result<Option<ExtractedExplicitReply>, &'static str>,
+}
+impl Lexical {
+ fn none() -> Self {
+ Self {
+ mark: Ok(None),
+ quote: Ok(None),
+ }
+ }
+ fn mark(mark: std::result::Result<Option<MarkedPassage>, &'static str>) -> Self {
+ Self {
+ mark,
+ ..Self::none()
+ }
+ }
+}
+impl MarkReader for Lexical {
+ async fn resolve(
+ &self,
+ document_id: &str,
+ _mark_id: &str,
+ ) -> anyhow::Result<Option<MarkedPassage>> {
+ assert_eq!(document_id, "doc");
+ self.mark.clone().map_err(|error| anyhow::anyhow!(error))
+ }
+}
+impl QuoteReader for Lexical {
+ async fn quoted(&self, _markdown: &str) -> anyhow::Result<Option<ExtractedExplicitReply>> {
+ self.quote.clone().map_err(|error| anyhow::anyhow!(error))
+ }
+}
+
+/// Names one expected parent.
+struct Names {
+ parent: MessageParent,
+ name: ParentName,
+}
+impl ParentNames for Names {
+ async fn name(
+ &self,
+ access: &EntityAccessReceipt<MessageView>,
+ parent: &MessageParent,
+ ) -> Result<ParentName> {
+ assert_eq!(*parent, self.parent);
+ assert_eq!(access.entity().entity_id, parent.entity_id());
+ Ok(self.name.clone())
+ }
+}
+fn document_names() -> Names {
+ Names {
+ parent: document(),
+ name: ParentName::Named("Launch plan".to_owned()),
+ }
+}
+fn channel_names() -> Names {
+ Names {
+ parent: channel(),
+ name: ParentName::Channel {
+ name: Some("eng".to_owned()),
+ channel_type: ChannelType::Public,
+ },
+ }
+}
+
+/// Names each user after their email's local part.
+struct Directory;
+impl PeopleDirectory for Directory {
+ async fn people(&self, ids: Vec<String>) -> Result<Vec<ContextPerson>> {
+ Ok(ids
+ .into_iter()
+ .map(|id| {
+ let email = id.strip_prefix("macro|").unwrap().to_owned();
+ ContextPerson {
+ name: email.split('@').next().unwrap().to_owned(),
+ id,
+ email: Some(email),
+ }
+ })
+ .collect())
+ }
+}
+fn person(email: &str) -> ContextPerson {
+ ContextPerson {
+ id: format!("macro|{email}"),
+ name: email.split('@').next().unwrap().to_owned(),
+ email: Some(email.to_owned()),
+ }
+}
+
+fn actor() -> MacroUserIdStr<'static> {
+ MacroUserIdStr::try_from_email("[email protected]").unwrap()
+}
+fn document() -> MessageParent {
+ MessageParent::parse("document", "doc").unwrap()
+}
+fn channel() -> MessageParent {
+ MessageParent::Channel(Uuid::from_u128(3))
+}
+fn at(minute: i64) -> DateTime<Utc> {
+ DateTime::from_timestamp(1_758_800_000 + minute * 60, 0).unwrap()
+}
+
+/// A live message by `email` on `parent`, posted `minute` minutes in.
+fn posted(
+ parent: &MessageParent,
+ id: u128,
+ thread: Option<u128>,
+ email: &str,
+ content: &str,
+ minute: i64,
+) -> Message {
+ Message {
+ id: Uuid::from_u128(id),
+ parent: parent.clone(),
+ thread_id: thread.map(Uuid::from_u128),
+ sender_id: channel_sender::ChannelSender::new_from_user(
+ MacroUserIdStr::try_from_email(email).unwrap(),
+ ),
+ triggered_by: None,
+ bot_profile: None,
+ mentions: vec![],
+ imported_author: None,
+ content: content.into(),
+ created_at: at(minute),
+ updated_at: at(minute),
+ edited_at: None,
+ deleted_at: None,
+ attachments: vec![],
+ reactions: vec![],
+ }
+}
+/// The context entry for a message by a user the directory names.
+fn entry(message: &Message) -> ContextMessage {
+ ContextMessage {
+ id: message.id,
+ author: person(message.sender_id.as_user().unwrap().email_str()),
+ content: message.content.clone(),
+ posted_at: message.created_at,
+ }
+}
+
+fn discussion(root: Message, replies: Vec<Message>, anchor: Option<ThreadAnchor>) -> MessageThread {
+ MessageThread {
+ state: ThreadState {
+ root_id: root.id,
+ user_id: actor().as_ref().to_owned(),
+ resolved: false,
+ anchor,
+ created_at: root.created_at,
+ updated_at: root.created_at,
+ deleted_at: None,
+ },
+ root,
+ replies,
+ }
+}
+
+/// The actor's verified capability on `prompt`'s parent and discussion.
+fn invocation(prompt: &Message) -> AuthorizedInvocation {
+ AuthorizedInvocation::new(
+ EntityAccessReceipt::try_new_authenticated_user(
+ actor(),
+ Entity {
+ entity_type: prompt.parent.access_entity_type(),
+ entity_id: prompt.parent.entity_id(),
+ },
+ EntityPermission::AccessLevel {
+ access_level: AccessLevel::Comment,
+ },
+ )
+ .unwrap(),
+ prompt.root_id(),
+ )
+}
+
+async fn context_from(
+ source: MockMessageReader,
+ names: Names,
+ lexical: Lexical,
+ prompt: &Message,
+) -> DiscussionContext {
+ MessageDiscussionReader::new(Arc::new(source), Directory, names, lexical)
+ .discussion(
+ &invocation(prompt),
+ &MessagePostedMetadata::from_message(prompt, vec![]),
+ )
+ .await
+ .unwrap()
+}
+
+/// The prompting reply in a comment thread on `parent`.
+fn comment(parent: &MessageParent) -> Message {
+ posted(
+ parent,
+ 2,
+ Some(1),
+ "@agent explain this paragraph",
+ 5,
+ )
+}
+
+/// A comment thread on `parent`: the root and the prompting reply.
+fn reader(parent: &MessageParent, anchor: Option<ThreadAnchor>) -> MockMessageReader {
+ let root = posted(parent, 1, None, "[email protected]", "is this right?", 0);
+ let prompt = comment(parent);
+ let mut source = MockMessageReader::new();
+ let prompt_message = prompt.clone();
+ source
+ .expect_get()
+ .withf(|_, id| *id == Uuid::from_u128(2))
+ .returning(move |_, _| Ok(prompt_message.clone()));
+ // A comment discussion is its own thread; nothing outside it is read.
+ source.expect_preceding().never();
+ let expected = parent.entity_id();
+ source
+ .expect_get_thread()
+ .once()
+ .withf(move |access, root| {
+ access.entity().entity_id == expected && *root == Uuid::from_u128(1)
+ })
+ .return_once(move |_, _| Ok(discussion(root, vec![prompt], anchor)));
+ source
+}
+
+#[tokio::test]
+async fn a_document_comment_carries_its_whole_thread_through_the_prompt() {
+ let prompt = comment(&document());
+ let context = context_from(
+ reader(&document(), None),
+ document_names(),
+ Lexical::none(),
+ &prompt,
+ )
+ .await;
+ assert_eq!(
+ context,
+ DiscussionContext {
+ // An unanchored discussion names no place in the document.
+ surface: DiscussionSurface::DocumentComment {
+ id: "doc".to_owned(),
+ name: "Launch plan".to_owned(),
+ anchor: None,
+ },
+ prompt_message_id: Uuid::from_u128(2),
+ sender: ContextPerson {
+ id: "macro|[email protected]".to_owned(),
+ name: "actor".to_owned(),
+ email: Some("[email protected]".to_owned()),
+ },
+ reply_target: ReplyTarget::Thread {
+ root_id: Uuid::from_u128(1)
+ },
+ thread: Some(ContextThread {
+ root_id: Uuid::from_u128(1),
+ messages: vec![
+ ContextMessage {
+ id: Uuid::from_u128(1),
+ author: ContextPerson {
+ id: "macro|[email protected]".to_owned(),
+ name: "alice".to_owned(),
+ email: Some("[email protected]".to_owned()),
+ },
+ content: "is this right?".to_owned(),
+ posted_at: at(0),
+ },
+ ContextMessage {
+ id: Uuid::from_u128(2),
+ author: ContextPerson {
+ id: "macro|[email protected]".to_owned(),
+ name: "actor".to_owned(),
+ email: Some("[email protected]".to_owned()),
+ },
+ content: "@agent explain this paragraph".to_owned(),
+ posted_at: at(5),
+ },
+ ],
+ messages_omitted: false,
+ }),
+ channel: vec![],
+ }
+ );
+}
+
+/// "please fix" in thread A, posted while another thread was busier. The
+/// agent must get thread A whole and be told the rest is background, not a
+/// flat list whose last entry is someone else's bug.
+#[tokio::test]
+async fn a_channel_thread_reply_is_about_its_thread_not_the_latest_message() {
+ let parent = channel();
+ let calendar = posted(
+ &parent,
+ 10,
+ None,
+ "calendar popover scrolls the page",
+ 0,
+ );
+ let spinner = posted(
+ &parent,
+ 20,
+ None,
+ "sidebar spinner never stops",
+ 5,
+ );
+ let repro = posted(
+ &parent,
+ 11,
+ Some(10),
+ "repro: open it and scroll",
+ 6,
+ );
+ let lunch = posted(&parent, 30, None, "[email protected]", "lunch?", 10);
+ let mobile = posted(
+ &parent,
+ 21,
+ Some(20),
+ "same on mobile",
+ 12,
+ );
+ let prompt = posted(
+ &parent,
+ 12,
+ Some(10),
+ "@Cursor please fix",
+ 15,
+ );
+ let later = posted(
+ &parent,
+ 13,
+ Some(10),
+ "posted after the prompt",
+ 20,
+ );
+
+ let mut source = MockMessageReader::new();
+ let prompt_message = prompt.clone();
+ source
+ .expect_get()
+ .withf(move |_, id| *id == Uuid::from_u128(12))
+ .returning(move |_, _| Ok(prompt_message.clone()));
+ let thread = discussion(
+ calendar.clone(),
+ vec![repro.clone(), prompt.clone(), later],
+ None,
+ );
+ source
+ .expect_get_thread()
+ .once()
+ .withf(|_, root| *root == Uuid::from_u128(10))
+ .return_once(move |_, _| Ok(thread));
+ // The window starts after the thread's root, as it does in a busy channel.
+ let recent = vec![
+ spinner.clone(),
+ repro.clone(),
+ lunch.clone(),
+ mobile.clone(),
+ ];
+ source
+ .expect_preceding()
+ .once()
+ .withf(|_, id, limit| *id == Uuid::from_u128(12) && *limit == 10)
+ .return_once(move |_, _, _| Ok(recent));
+
+ let context = context_from(source, channel_names(), Lexical::none(), &prompt).await;
+
+ assert_eq!(
+ context,
+ DiscussionContext {
+ surface: DiscussionSurface::Channel {
+ id: Uuid::from_u128(3),
+ name: Some("eng".to_owned()),
+ channel_type: ChannelType::Public,
+ },
+ prompt_message_id: prompt.id,
+ sender: person("[email protected]"),
+ reply_target: ReplyTarget::Thread {
+ root_id: calendar.id
+ },
+ thread: Some(ContextThread {
+ root_id: calendar.id,
+ messages: vec![entry(&calendar), entry(&repro), entry(&prompt)],
+ messages_omitted: false,
+ }),
+ channel: vec![
+ ContextThread {
+ root_id: spinner.id,
+ messages: vec![entry(&spinner), entry(&mobile)],
+ messages_omitted: false,
+ },
+ ContextThread {
+ root_id: lunch.id,
+ messages: vec![entry(&lunch)],
+ messages_omitted: false,
+ },
+ ],
+ }
+ );
+}
+
+#[tokio::test]
+async fn a_top_level_channel_prompt_replies_to_nothing_and_ends_the_channel() {
+ let parent = channel();
+ let root = posted(&parent, 20, None, "[email protected]", "spinner bug", 0);
+ let reply = posted(
+ &parent,
+ 21,
+ Some(20),
+ "same on mobile",
+ 1,
+ );
+ let orphan = posted(
+ &parent,
+ 41,
+ Some(40),
+ "reply to an old thread",
+ 2,
+ );
+ let prompt = posted(
+ &parent,
+ 50,
+ None,
+ "@Cursor what's broken?",
+ 3,
+ );
+
+ let mut source = MockMessageReader::new();
+ let prompt_message = prompt.clone();
+ source
+ .expect_get()
+ .returning(move |_, _| Ok(prompt_message.clone()));
+ source.expect_get_thread().never();
+ let recent = vec![root.clone(), reply.clone(), orphan.clone()];
+ source
+ .expect_preceding()
+ .once()
+ .return_once(move |_, _, _| Ok(recent));
+
+ let context = context_from(source, channel_names(), Lexical::none(), &prompt).await;
+
+ assert_eq!(context.thread, None);
+ assert_eq!(context.reply_target, ReplyTarget::None);
+ assert_eq!(
+ context.channel,
+ [
+ ContextThread {
+ root_id: root.id,
+ messages: vec![entry(&root), entry(&reply)],
+ messages_omitted: false,
+ },
+ ContextThread {
+ root_id: Uuid::from_u128(40),
+ messages: vec![entry(&orphan)],
+ // Its root fell outside the window.
+ messages_omitted: true,
+ },
+ ContextThread {
+ root_id: prompt.id,
+ messages: vec![entry(&prompt)],
+ messages_omitted: false,
+ },
+ ]
+ );
+}
+
+#[tokio::test]
+async fn deleted_blank_imported_and_bot_messages_read_as_their_authors_wrote_them() {
+ let parent = channel();
+ let deleted = Message {
+ deleted_at: Some(at(1)),
+ ..posted(&parent, 20, None, "[email protected]", "retracted", 0)
+ };
+ let blank = posted(&parent, 21, None, "[email protected]", " \n ", 1);
+ let imported = Message {
+ imported_author: Some(ImportedAuthor {
+ name: "Dana (Slack)".to_owned(),
+ }),
+ ..posted(&parent, 22, None, "[email protected]", "from slack", 2)
+ };
+ let bot = Message {
+ sender_id: channel_sender::ChannelSender::new_from_bot(bot_id::BotId::new_from_uuid(
+ Uuid::from_u128(99),
+ )),
+ bot_profile: Some(BotSenderProfile {
+ name: "Deploy Bot".to_owned(),
+ avatar_url: None,
+ }),
+ ..posted(&parent, 23, None, "[email protected]", "deployed v2", 3)
+ };
+ let prompt = posted(&parent, 50, None, "[email protected]", "@Cursor status?", 4);
+
+ let mut source = MockMessageReader::new();
+ let prompt_message = prompt.clone();
+ source
+ .expect_get()
+ .returning(move |_, _| Ok(prompt_message.clone()));
+ let recent = vec![deleted, blank, imported, bot];
+ source
+ .expect_preceding()
+ .once()
+ .return_once(move |_, _, _| Ok(recent));
+
+ let context = context_from(source, channel_names(), Lexical::none(), &prompt).await;
+
+ assert_eq!(
+ context.channel,
+ [
+ ContextThread {
+ root_id: Uuid::from_u128(22),
+ messages: vec![ContextMessage {
+ id: Uuid::from_u128(22),
+ author: ContextPerson {
+ id: "macro|[email protected]".to_owned(),
+ name: "Dana (Slack)".to_owned(),
+ email: None,
+ },
+ content: "from slack".to_owned(),
+ posted_at: at(2),
+ }],
+ messages_omitted: false,
+ },
+ ContextThread {
+ root_id: Uuid::from_u128(23),
+ messages: vec![ContextMessage {
+ id: Uuid::from_u128(23),
+ author: ContextPerson {
+ id: "bot|00000000-0000-0000-0000-000000000063".to_owned(),
+ name: "Deploy Bot".to_owned(),
+ email: None,
+ },
+ content: "deployed v2".to_owned(),
+ posted_at: at(3),
+ }],
+ messages_omitted: false,
+ },
+ ContextThread {
+ root_id: prompt.id,
+ messages: vec![entry(&prompt)],
+ messages_omitted: false,
+ },
+ ]
+ );
+}
+
+#[tokio::test]
+async fn a_quote_reply_carries_the_quoted_message_even_outside_the_window() {
+ let parent = channel();
+ let quoted = posted(
+ &parent,
+ 60,
+ None,
+ "the spinner never stops",
+ 0,
+ );
+ let prompt = posted(
+ &parent,
+ 70,
+ None,
+ "<m-reply-target>…</m-reply-target>\n\n@Cursor fix this",
+ 30,
+ );
+
+ let mut source = MockMessageReader::new();
+ let prompt_message = prompt.clone();
+ source
+ .expect_get()
+ .withf(|_, id| *id == Uuid::from_u128(70))
+ .returning(move |_, _| Ok(prompt_message.clone()));
+ let quoted_message = quoted.clone();
+ source
+ .expect_get()
+ .once()
+ .withf(|access, id| {
+ access.entity().entity_id == channel().entity_id() && *id == Uuid::from_u128(60)
+ })
+ .return_once(move |_, _| Ok(quoted_message));
+ source
+ .expect_preceding()
+ .once()
+ .return_once(|_, _, _| Ok(vec![]));
+
+ let lexical = Lexical {
+ quote: Ok(Some(ExtractedExplicitReply {
+ parent: parent.clone(),
+ target_message_id: quoted.id.to_string(),
+ target_thread_id: quoted.id.to_string(),
+ display_text: "the spinner never stops".to_owned(),
+ sender_id: quoted.sender_id.as_ref().to_owned(),
+ })),
+ ..Lexical::none()
+ };
+ let context = context_from(source, channel_names(), lexical, &prompt).await;
+
+ assert_eq!(
+ context.reply_target,
+ ReplyTarget::Quote {
+ message_id: quoted.id,
+ thread_id: quoted.id,
+ preview: "the spinner never stops".to_owned(),
+ message: Some(ContextMessage {
+ id: quoted.id,
+ author: ContextPerson {
+ id: "macro|[email protected]".to_owned(),
+ name: "teo".to_owned(),
+ email: Some("[email protected]".to_owned()),
+ },
+ content: "the spinner never stops".to_owned(),
+ posted_at: at(0),
+ }),
+ }
+ );
+}
+
+#[tokio::test]
+async fn a_quote_from_another_conversation_travels_as_its_preview() {
+ let parent = channel();
+ let prompt = posted(
+ &parent,
+ 70,
+ None,
+ "@Cursor fix this",
+ 30,
+ );
+ let mut source = MockMessageReader::new();
+ let prompt_message = prompt.clone();
+ // Only the prompt is read: the quoted message is on a parent the actor's
+ // capability does not cover.
+ source
+ .expect_get()
+ .once()
+ .withf(|_, id| *id == Uuid::from_u128(70))
+ .return_once(move |_, _| Ok(prompt_message));
+ source
+ .expect_preceding()
+ .once()
+ .return_once(|_, _, _| Ok(vec![]));
+ let lexical = Lexical {
+ quote: Ok(Some(ExtractedExplicitReply {
+ parent: MessageParent::Channel(Uuid::from_u128(99)),
+ target_message_id: Uuid::from_u128(61).to_string(),
+ target_thread_id: Uuid::from_u128(61).to_string(),
+ display_text: "elsewhere".to_owned(),
+ sender_id: "macro|[email protected]".to_owned(),
+ })),
+ ..Lexical::none()
+ };
+ let context = context_from(source, channel_names(), lexical, &prompt).await;
+ assert_eq!(
+ context.reply_target,
+ ReplyTarget::Quote {
+ message_id: Uuid::from_u128(61),
+ thread_id: Uuid::from_u128(61),
+ preview: "elsewhere".to_owned(),
+ message: None,
+ }
+ );
+}
+
+#[tokio::test]
+async fn a_failed_quote_lookup_still_names_the_thread() {
+ let context = context_from(
+ reader(&document(), None),
+ document_names(),
+ Lexical {
+ quote: Err("lexical unavailable"),
+ ..Lexical::none()
+ },
+ &comment(&document()),
+ )
+ .await;
+ assert_eq!(
+ context.reply_target,
+ ReplyTarget::Thread {
+ root_id: Uuid::from_u128(1)
+ }
+ );
+}
+
+#[tokio::test]
+async fn a_long_thread_keeps_its_root_and_the_messages_nearest_the_prompt() {
+ let parent = channel();
+ let root = posted(&parent, 1, None, "[email protected]", "the bug", 0);
+ let replies: Vec<Message> = (0..60)
+ .map(|index| {
+ posted(
+ &parent,
+ 100 + index,
+ Some(1),
+ &format!("reply {index}"),
+ 1 + i64::try_from(index).unwrap(),
+ )
+ })
+ .collect();
+ let prompt = replies.last().unwrap().clone();
+ let mut source = MockMessageReader::new();
+ let prompt_message = prompt.clone();
+ source
+ .expect_get()
+ .returning(move |_, _| Ok(prompt_message.clone()));
+ let thread = discussion(root.clone(), replies, None);
+ source
+ .expect_get_thread()
+ .once()
+ .return_once(move |_, _| Ok(thread));
+ source
+ .expect_preceding()
+ .once()
+ .return_once(|_, _, _| Ok(vec![]));
+
+ let thread = context_from(source, channel_names(), Lexical::none(), &prompt)
+ .await
+ .thread
+ .unwrap();
+ assert!(thread.messages_omitted);
+ assert_eq!(thread.messages.len(), THREAD_MESSAGES);
+ assert_eq!(thread.messages[0].content, "the bug");
+ assert_eq!(thread.messages[1].content, "reply 11");
+ assert_eq!(thread.messages.last().unwrap().id, prompt.id);
+}
+
+#[tokio::test]
+async fn a_post_outside_the_invoked_discussion_is_never_read() {
+ let prompt = comment(&document());
+ let elsewhere = Message {
+ thread_id: Some(Uuid::from_u128(77)),
+ ..prompt.clone()
+ };
+ let error = MessageDiscussionReader::new(
+ Arc::new(MockMessageReader::new()),
+ Directory,
+ document_names(),
+ Lexical::none(),
+ )
+ .discussion(
+ &invocation(&prompt),
+ &MessagePostedMetadata::from_message(&elsewhere, vec![]),
+ )
+ .await
+ .unwrap_err();
+ assert!(matches!(error, AgentSessionError::Forbidden));
+}
+
+#[tokio::test]
+async fn a_direct_message_channel_has_no_name() {
+ let prompt = posted(&channel(), 50, None, "[email protected]", "@Cursor hi", 0);
+ let mut source = MockMessageReader::new();
+ let prompt_message = prompt.clone();
+ source
+ .expect_get()
+ .returning(move |_, _| Ok(prompt_message.clone()));
+ source
+ .expect_preceding()
+ .once()
+ .return_once(|_, _, _| Ok(vec![]));
+ let names = Names {
+ parent: channel(),
+ name: ParentName::Channel {
+ name: None,
+ channel_type: ChannelType::DirectMessage,
+ },
+ };
+ let context = context_from(source, names, Lexical::none(), &prompt).await;
+ assert_eq!(
+ context.surface,
+ DiscussionSurface::Channel {
+ id: Uuid::from_u128(3),
+ name: None,
+ channel_type: ChannelType::DirectMessage,
+ }
+ );
+}
+
+#[tokio::test]
+async fn a_project_comment_names_its_project() {
+ let parent = MessageParent::Initiative(Uuid::from_u128(901));
+ let names = Names {
+ parent: parent.clone(),
+ name: ParentName::Named("Q4 launch".to_owned()),
+ };
+ let context = context_from(
+ reader(&parent, None),
+ names,
+ Lexical::none(),
+ &comment(&parent),
+ )
+ .await;
+ assert_eq!(
+ context.surface,
+ DiscussionSurface::ProjectComment {
+ id: Uuid::from_u128(901),
+ name: "Q4 launch".to_owned(),
+ }
+ );
+}
+
+#[tokio::test]
+async fn a_crm_company_comment_names_its_company() {
+ let parent = MessageParent::CrmCompany(Uuid::from_u128(902));
+ let names = Names {
+ parent: parent.clone(),
+ name: ParentName::Named("Acme".to_owned()),
+ };
+ let context = context_from(
+ reader(&parent, None),
+ names,
+ Lexical::none(),
+ &comment(&parent),
+ )
+ .await;
+ assert_eq!(
+ context.surface,
+ DiscussionSurface::CrmCompanyComment {
+ id: Uuid::from_u128(902),
+ name: "Acme".to_owned(),
+ }
+ );
+}
+
+#[tokio::test]
+async fn a_crm_contact_comment_names_its_contact() {
+ let parent = MessageParent::CrmContact(Uuid::from_u128(903));
+ let names = Names {
+ parent: parent.clone(),
+ name: ParentName::Named("Dana Lee".to_owned()),
+ };
+ let context = context_from(
+ reader(&parent, None),
+ names,
+ Lexical::none(),
+ &comment(&parent),
+ )
+ .await;
+ assert_eq!(
+ context.surface,
+ DiscussionSurface::CrmContactComment {
+ id: Uuid::from_u128(903),
+ name: "Dana Lee".to_owned(),
+ }
+ );
+}
+
+#[tokio::test]
+async fn a_call_chat_names_its_call() {
+ let parent = MessageParent::Call(Uuid::from_u128(904));
+ let names = Names {
+ parent: parent.clone(),
+ name: ParentName::Named("Weekly sync".to_owned()),
+ };
+ let context = context_from(
+ reader(&parent, None),
+ names,
+ Lexical::none(),
+ &comment(&parent),
+ )
+ .await;
+ assert_eq!(
+ context.surface,
+ DiscussionSurface::CallChat {
+ id: Uuid::from_u128(904),
+ title: "Weekly sync".to_owned(),
+ }
+ );
+}
+
+#[tokio::test]
+async fn a_marked_discussion_names_its_mark_and_the_text_it_covers() {
+ let mark_id = Uuid::from_u128(7);
+ let context = context_from(
+ reader(
+ &document(),
+ Some(ThreadAnchor::Markdown {
+ mark_id,
+ marked_text: Some("the marked phrase".to_owned()),
+ }),
+ ),
+ document_names(),
+ Lexical::none(),
+ &comment(&document()),
+ )
+ .await;
+ assert_eq!(
+ context.surface,
+ DiscussionSurface::DocumentComment {
+ id: "doc".to_owned(),
+ name: "Launch plan".to_owned(),
+ anchor: Some(CommentAnchor::Mark {
+ mark_id: mark_id.to_string(),
+ marked_text: Some("the marked phrase".to_owned()),
+ current: None,
+ }),
+ }
+ );
+}
+
+#[tokio::test]
+async fn a_discussion_anchored_before_snapshots_still_names_its_mark() {
+ let mark_id = Uuid::from_u128(8);
+ let context = context_from(
+ reader(
+ &document(),
+ Some(ThreadAnchor::Markdown {
+ mark_id,
+ marked_text: None,
+ }),
+ ),
+ document_names(),
+ Lexical::none(),
+ &comment(&document()),
+ )
+ .await;
+ assert_eq!(
+ context.surface,
+ DiscussionSurface::DocumentComment {
+ id: "doc".to_owned(),
+ name: "Launch plan".to_owned(),
+ anchor: Some(CommentAnchor::Mark {
+ mark_id: mark_id.to_string(),
+ marked_text: None,
+ current: None,
+ }),
+ }
+ );
+}
+
+#[tokio::test]
+async fn a_marked_discussion_reads_the_mark_as_the_document_has_it_now() {
+ let mark_id = Uuid::from_u128(9);
+ let context = context_from(
+ reader(
+ &document(),
+ Some(ThreadAnchor::Markdown {
+ mark_id,
+ marked_text: Some("the original phrase".to_owned()),
+ }),
+ ),
+ document_names(),
+ Lexical::mark(Ok(Some(MarkedPassage {
+ marked_text: "the edited phrase".to_owned(),
+ surrounding_text: "Before the edited phrase after.".to_owned(),
+ }))),
+ &comment(&document()),
+ )
+ .await;
+ assert_eq!(
+ context.surface,
+ DiscussionSurface::DocumentComment {
+ id: "doc".to_owned(),
+ name: "Launch plan".to_owned(),
+ anchor: Some(CommentAnchor::Mark {
+ mark_id: mark_id.to_string(),
+ marked_text: Some("the original phrase".to_owned()),
+ current: Some(MarkedPassage {
+ marked_text: "the edited phrase".to_owned(),
+ surrounding_text: "Before the edited phrase after.".to_owned(),
+ }),
+ }),
+ }
+ );
+}
+
+#[tokio::test]
+async fn a_failed_live_lookup_falls_back_to_the_snapshot() {
+ let mark_id = Uuid::from_u128(10);
+ let context = context_from(
+ reader(
+ &document(),
+ Some(ThreadAnchor::Markdown {
+ mark_id,
+ marked_text: Some("the original phrase".to_owned()),
+ }),
+ ),
+ document_names(),
+ Lexical::mark(Err("lexical unavailable")),
+ &comment(&document()),
+ )
+ .await;
+ assert_eq!(
+ context.surface,
+ DiscussionSurface::DocumentComment {
+ id: "doc".to_owned(),
+ name: "Launch plan".to_owned(),
+ anchor: Some(CommentAnchor::Mark {
+ mark_id: mark_id.to_string(),
+ marked_text: Some("the original phrase".to_owned()),
+ current: None,
+ }),
+ }
+ );
+}
+
+#[tokio::test]
+async fn a_pdf_highlight_discussion_names_the_text_the_highlight_covers() {
+ let anchor_id = Uuid::from_u128(11);
+ let context = context_from(
+ reader(
+ &document(),
+ Some(ThreadAnchor::PdfHighlight {
+ anchor_id,
+ marked_text: Some("indemnifies the lessor".to_owned()),
+ }),
+ ),
+ document_names(),
+ // The highlight's text arrives with the thread; no document lookup.
+ Lexical::mark(Err("never asked")),
+ &comment(&document()),
+ )
+ .await;
+ assert_eq!(
+ context.surface,
+ DiscussionSurface::DocumentComment {
+ id: "doc".to_owned(),
+ name: "Launch plan".to_owned(),
+ anchor: Some(CommentAnchor::PdfHighlight {
+ anchor_id: anchor_id.to_string(),
+ marked_text: Some("indemnifies the lessor".to_owned()),
+ }),
+ }
+ );
+}
+
+#[tokio::test]
+async fn a_pdf_pin_discussion_names_its_pin() {
+ let anchor_id = Uuid::from_u128(12);
+ let context = context_from(
+ reader(&document(), Some(ThreadAnchor::PdfPlaceable { anchor_id })),
+ document_names(),
+ Lexical::none(),
+ &comment(&document()),
+ )
+ .await;
+ assert_eq!(
+ context.surface,
+ DiscussionSurface::DocumentComment {
+ id: "doc".to_owned(),
+ name: "Launch plan".to_owned(),
+ anchor: Some(CommentAnchor::PdfPin {
+ anchor_id: anchor_id.to_string(),
+ }),
+ }
+ );
+}
+
+#[tokio::test]
+async fn spreadsheet_discussions_carry_the_range_without_resolving_a_mark() {
+ let context = context_from(
+ reader(
+ &document(),
+ Some(ThreadAnchor::Spreadsheet {
+ sheet_id: "sheet-1".into(),
+ sheet_name: "Budget".into(),
+ range: "B4:C9".into(),
+ }),
+ ),
+ document_names(),
+ Lexical::mark(Err("never asked")),
+ &comment(&document()),
+ )
+ .await;
+ assert_eq!(
+ context.surface,
+ DiscussionSurface::DocumentComment {
+ id: "doc".to_owned(),
+ name: "Launch plan".to_owned(),
+ anchor: Some(CommentAnchor::Spreadsheet {
+ sheet_id: "sheet-1".into(),
+ sheet_name: "Budget".into(),
+ range: "B4:C9".into(),
+ }),
+ }
+ );
+}
+
+#[tokio::test]
+async fn design_discussions_reach_the_agent_unanchored() {
+ let context = context_from(
+ reader(
+ &document(),
+ Some(ThreadAnchor::Fig {
+ page_id: "0:1".into(),
+ node_id: Some("12:34".into()),
+ x: 18.5,
+ y: -4.0,
+ }),
+ ),
+ document_names(),
+ Lexical::mark(Err("never asked")),
+ &comment(&document()),
+ )
+ .await;
+ assert_eq!(
+ context.surface,
+ DiscussionSurface::DocumentComment {
+ id: "doc".to_owned(),
+ name: "Launch plan".to_owned(),
+ anchor: None,
+ }
+ );
+ assert!(context.thread.is_some());
+}
diff --git a/crates/agent_trigger/src/outbound/dss_task_assignment_context.rs b/crates/agent_trigger/src/outbound/dss_task_assignment_context.rs
index 6b96bb4de9..8eb53ee1fb 100644
--- a/crates/agent_trigger/src/outbound/dss_task_assignment_context.rs
+++ b/crates/agent_trigger/src/outbound/dss_task_assignment_context.rs
@@ -1,31 +1,67 @@
//! Task briefs from the document service and its live Markdown renderer.
use agent_session::domain::error::{AgentSessionError, Result};
+use chrono::{DateTime, Utc};
use document_storage_service_client::DocumentStorageServiceClient;
use document_sub_type::DocumentSubType;
-use entity_access::domain::models::{EntityAccessReceipt, EntityType};
+use entity_access::domain::models::{EntityAccessReceipt, EntityType, ViewAccessLevel};
use lexical_client::{LexicalClient, parse_markdown::MarkdownTarget};
use messages::domain::service::MessageWrite;
+use models_properties::{
+ EntityType as PropertyEntityType,
+ service::{property_option::PropertyOptionValue, property_value::PropertyValue},
+};
+use properties::{EntityPropertyInfo, PropertiesErr, PropertiesService, ViewReceipt};
+use system_properties::SystemPropertyKey;
use crate::domain::task_assignment::{TaskAssignmentContext, TaskBrief};
#[cfg(test)]
mod test;
-/// Loads the current title and Markdown for an already-authorized task.
-pub struct DssTaskAssignmentContext {
+/// The property domain's read of an authorized task's current properties.
+#[cfg_attr(test, mockall::automock)]
+pub trait TaskProperties: Send + Sync + 'static {
+ /// Every property on the task, with option definitions to name select values.
+ fn task_properties(
+ &self,
+ task: &ViewReceipt,
+ ) -> impl Future<Output = std::result::Result<Vec<EntityPropertyInfo>, PropertiesErr>> + Send;
+}
+
+impl<P: PropertiesService> TaskProperties for P {
+ async fn task_properties(
+ &self,
+ task: &ViewReceipt,
+ ) -> std::result::Result<Vec<EntityPropertyInfo>, PropertiesErr> {
+ self.get_entity_properties(task).await
+ }
+}
+
+/// Loads the current title, Markdown, and properties for an already-authorized task.
+pub struct DssTaskAssignmentContext<Properties> {
documents: DocumentStorageServiceClient,
lexical: LexicalClient,
+ properties: Properties,
}
-impl DssTaskAssignmentContext {
- /// Compose the owning document service client and live Markdown renderer.
- pub fn new(documents: DocumentStorageServiceClient, lexical: LexicalClient) -> Self {
- Self { documents, lexical }
+impl<Properties: TaskProperties> DssTaskAssignmentContext<Properties> {
+ /// Compose the owning document service client, live Markdown renderer, and
+ /// property service.
+ pub fn new(
+ documents: DocumentStorageServiceClient,
+ lexical: LexicalClient,
+ properties: Properties,
+ ) -> Self {
+ Self {
+ documents,
+ lexical,
+ properties,
+ }
}
}
-impl TaskAssignmentContext for DssTaskAssignmentContext {
+impl<Properties: TaskProperties> TaskAssignmentContext for DssTaskAssignmentContext<Properties> {
async fn task_brief(
&self,
access: EntityAccessReceipt<MessageWrite>,
@@ -33,7 +69,12 @@ impl TaskAssignmentContext for DssTaskAssignmentContext {
if access.entity().entity_type != EntityType::Document {
return Err(AgentSessionError::Forbidden);
}
- let document_id = &access.entity().entity_id;
+ // Commenting on a task implies viewing it, so its properties are
+ // read under the same access.
+ let task: ViewReceipt = access
+ .try_into_requirement::<ViewAccessLevel>()
+ .map_err(|_| AgentSessionError::Forbidden)?;
+ let document_id = &task.entity().entity_id;
let Some(document) = self
.documents
.get_document_basic(document_id)
@@ -55,10 +96,58 @@ impl TaskAssignmentContext for DssTaskAssignmentContext {
.get_markdown(document_id, MarkdownTarget::External)
.await
.map_err(AgentSessionError::Unknown)?;
+ let properties = self
+ .properties
+ .task_properties(&task)
+ .await
+ .map_err(|error| AgentSessionError::Unknown(error.into()))?;
+ let property = |key: SystemPropertyKey| {
+ properties
+ .iter()
+ .find(|property| property.property_definition_id == key.uuid())
+ };
Ok(Some(TaskBrief {
title: document.document_name,
markdown,
- project_id: None,
+ status: property(SystemPropertyKey::Status).and_then(selected_option),
+ priority: property(SystemPropertyKey::Priority).and_then(selected_option),
+ due: property(SystemPropertyKey::DueDate).and_then(date),
+ assignee_ids: property(SystemPropertyKey::Assignees)
+ .map(users)
+ .unwrap_or_default(),
+ project: None,
}))
}
}
+
+/// The selected option's label; single-select properties hold at most one.
+fn selected_option(property: &EntityPropertyInfo) -> Option<String> {
+ let Some(PropertyValue::SelectOption(ids)) = &property.value else {
+ return None;
+ };
+ ids.iter()
+ .find_map(|id| property.options.iter().find(|option| option.id == *id))
+ .map(|option| match &option.value {
+ PropertyOptionValue::String(label) => label.clone(),
+ PropertyOptionValue::Number(number) => number.to_string(),
+ })
+}
+
+fn date(property: &EntityPropertyInfo) -> Option<DateTime<Utc>> {
+ match property.value {
+ Some(PropertyValue::Date(date)) => Some(date),
+ _ => None,
+ }
+}
+
+/// User and bot ids; both are stored as user references.
+fn users(property: &EntityPropertyInfo) -> Vec<String> {
+ let Some(PropertyValue::EntityRef(references)) = &property.value else {
+ return Vec::new();
+ };
+ references
+ .iter()
+ .filter(|reference| reference.entity_type == PropertyEntityType::User)
+ .map(|reference| reference.entity_id.clone())
+ .collect()
+}
diff --git a/crates/agent_trigger/src/outbound/dss_task_assignment_context/test.rs b/crates/agent_trigger/src/outbound/dss_task_assignment_context/test.rs
index fbea029151..1edf5c6557 100644
--- a/crates/agent_trigger/src/outbound/dss_task_assignment_context/test.rs
+++ b/crates/agent_trigger/src/outbound/dss_task_assignment_context/test.rs
@@ -1,9 +1,19 @@
use super::*;
+use chrono::{TimeZone, Utc};
use entity_access::domain::models::{AccessLevel, Entity, EntityPermission};
use macro_user_id::user_id::MacroUserIdStr;
+use macro_uuid::Uuid;
+use models_properties::service::{
+ property_option::PropertyOptionValue, property_value::PropertyValue,
+};
+use models_properties::{
+ DataType, EntityReference, EntityType as PropertyEntityType, PropertyOwner,
+};
+use properties::PropertyOptionInfo;
use serde_json::{Value, json};
use std::io::{BufRead, BufReader, Write};
use std::net::TcpListener;
+use system_properties::SystemPropertyKey;
fn access() -> EntityAccessReceipt<MessageWrite> {
EntityAccessReceipt::try_new_authenticated_user(
@@ -32,7 +42,11 @@ fn task() -> Value {
fn server(
responses: Vec<(&'static str, u16, Value)>,
-) -> (DssTaskAssignmentContext, std::thread::JoinHandle<()>) {
+ properties: MockTaskProperties,
+) -> (
+ DssTaskAssignmentContext<MockTaskProperties>,
+ std::thread::JoinHandle<()>,
+) {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let address = listener.local_addr().unwrap();
let handle = std::thread::spawn(move || {
@@ -58,26 +72,134 @@ fn server(
DssTaskAssignmentContext::new(
DocumentStorageServiceClient::new("test-key".to_owned(), url.clone()),
LexicalClient::new("test-key".to_owned(), url),
+ properties,
),
handle,
)
}
#[tokio::test]
-async fn a_task_brief_contains_the_title_and_current_markdown() {
- let (context, server) = server(vec![
- ("/internal/documents/task-1/basic", 200, task()),
- (
- "/markdown/task-1?target=external",
- 200,
- json!({"data": "Reproduce the race, then add a regression test."}),
- ),
- ]);
- let brief = context.task_brief(access()).await.unwrap().unwrap();
- assert_eq!(brief.title, "Fix the flaky test");
+async fn a_task_brief_names_the_current_status_priority_due_date_and_assignees() {
+ let in_progress = Uuid::from_u128(0x10);
+ let high = Uuid::from_u128(0x20);
+ let mut properties = MockTaskProperties::new();
+ properties
+ .expect_task_properties()
+ .once()
+ .withf(|task| {
+ task.entity().entity_id == "task-1" && task.entity().entity_type == EntityType::Document
+ })
+ .return_once(move |_| {
+ Box::pin(async move {
+ Ok(vec![
+ EntityPropertyInfo {
+ property_definition_id: SystemPropertyKey::Status.uuid(),
+ owner: PropertyOwner::System,
+ display_name: "Status".to_owned(),
+ data_type: DataType::SelectString,
+ is_multi_select: false,
+ is_system: true,
+ value: Some(PropertyValue::SelectOption(vec![in_progress])),
+ options: vec![
+ PropertyOptionInfo {
+ id: Uuid::from_u128(0x11),
+ display_order: 0,
+ value: PropertyOptionValue::String("Not Started".to_owned()),
+ },
+ PropertyOptionInfo {
+ id: in_progress,
+ display_order: 1,
+ value: PropertyOptionValue::String("In Progress".to_owned()),
+ },
+ ],
+ },
+ EntityPropertyInfo {
+ property_definition_id: SystemPropertyKey::Priority.uuid(),
+ owner: PropertyOwner::System,
+ display_name: "Priority".to_owned(),
+ data_type: DataType::SelectString,
+ is_multi_select: false,
+ is_system: true,
+ value: Some(PropertyValue::SelectOption(vec![high])),
+ options: vec![PropertyOptionInfo {
+ id: high,
+ display_order: 0,
+ value: PropertyOptionValue::String("High".to_owned()),
+ }],
+ },
+ EntityPropertyInfo {
+ property_definition_id: SystemPropertyKey::DueDate.uuid(),
+ owner: PropertyOwner::System,
+ display_name: "Due Date".to_owned(),
+ data_type: DataType::Date,
+ is_multi_select: false,
+ is_system: true,
+ value: Some(PropertyValue::Date(
+ Utc.with_ymd_and_hms(2026, 10, 15, 17, 0, 0).unwrap(),
+ )),
+ options: Vec::new(),
+ },
+ EntityPropertyInfo {
+ property_definition_id: SystemPropertyKey::Assignees.uuid(),
+ owner: PropertyOwner::System,
+ display_name: "Assignees".to_owned(),
+ data_type: DataType::Entity,
+ is_multi_select: true,
+ is_system: true,
+ value: Some(PropertyValue::EntityRef(vec![
+ EntityReference {
+ entity_id: "macro|[email protected]".to_owned(),
+ entity_type: PropertyEntityType::User,
+ specific_message_id: None,
+ },
+ EntityReference {
+ entity_id: bot_id::CODEX_BOT_ID.to_string(),
+ entity_type: PropertyEntityType::User,
+ specific_message_id: None,
+ },
+ ])),
+ options: Vec::new(),
+ },
+ EntityPropertyInfo {
+ property_definition_id: Uuid::from_u128(0x30),
+ owner: PropertyOwner::User {
+ user_id: "macro|[email protected]".to_owned(),
+ },
+ display_name: "Estimate".to_owned(),
+ data_type: DataType::Number,
+ is_multi_select: false,
+ is_system: false,
+ value: Some(PropertyValue::Num(3.0)),
+ options: Vec::new(),
+ },
+ ])
+ })
+ });
+ let (context, server) = server(
+ vec![
+ ("/internal/documents/task-1/basic", 200, task()),
+ (
+ "/markdown/task-1?target=external",
+ 200,
+ json!({"data": "Reproduce the race, then add a regression test."}),
+ ),
+ ],
+ properties,
+ );
assert_eq!(
- brief.markdown,
- "Reproduce the race, then add a regression test."
+ context.task_brief(access()).await.unwrap(),
+ Some(TaskBrief {
+ title: "Fix the flaky test".to_owned(),
+ markdown: "Reproduce the race, then add a regression test.".to_owned(),
+ status: Some("In Progress".to_owned()),
+ priority: Some("High".to_owned()),
+ due: Some(Utc.with_ymd_and_hms(2026, 10, 15, 17, 0, 0).unwrap()),
+ assignee_ids: vec![
+ "macro|[email protected]".to_owned(),
+ bot_id::CODEX_BOT_ID.to_string(),
+ ],
+ project: None,
+ })
);
server.join().unwrap();
}
@@ -89,8 +211,10 @@ async fn missing_deleted_and_non_task_documents_do_not_load_content() {
let mut ordinary = task();
ordinary["subType"] = Value::Null;
for (status, metadata) in [(404, json!({})), (200, deleted), (200, ordinary)] {
- let (context, server) =
- server(vec![("/internal/documents/task-1/basic", status, metadata)]);
+ let (context, server) = server(
+ vec![("/internal/documents/task-1/basic", status, metadata)],
+ MockTaskProperties::new(),
+ );
assert!(context.task_brief(access()).await.unwrap().is_none());
server.join().unwrap();
}
@@ -100,7 +224,10 @@ async fn missing_deleted_and_non_task_documents_do_not_load_content() {
async fn a_response_for_a_different_document_cannot_supply_the_brief() {
let mut metadata = task();
metadata["documentId"] = json!("other-task");
- let (context, server) = server(vec![("/internal/documents/task-1/basic", 200, metadata)]);
+ let (context, server) = server(
+ vec![("/internal/documents/task-1/basic", 200, metadata)],
+ MockTaskProperties::new(),
+ );
assert!(matches!(
context.task_brief(access()).await,
Err(AgentSessionError::Forbidden)
@@ -110,14 +237,41 @@ async fn a_response_for_a_different_document_cannot_supply_the_brief() {
#[tokio::test]
async fn unavailable_live_content_is_retried_instead_of_starting_without_a_description() {
- let (context, server) = server(vec![
- ("/internal/documents/task-1/basic", 200, task()),
- (
- "/markdown/task-1?target=external",
- 503,
- json!({"error": "temporarily unavailable"}),
- ),
- ]);
+ let (context, server) = server(
+ vec![
+ ("/internal/documents/task-1/basic", 200, task()),
+ (
+ "/markdown/task-1?target=external",
+ 503,
+ json!({"error": "temporarily unavailable"}),
+ ),
+ ],
+ MockTaskProperties::new(),
+ );
assert!(context.task_brief(access()).await.is_err());
server.join().unwrap();
}
+
+#[tokio::test]
+async fn unavailable_properties_are_retried_instead_of_starting_without_them() {
+ let mut properties = MockTaskProperties::new();
+ properties.expect_task_properties().once().return_once(|_| {
+ Box::pin(async { Err(PropertiesErr::Repo(anyhow::anyhow!("database unavailable"))) })
+ });
+ let (context, server) = server(
+ vec![
+ ("/internal/documents/task-1/basic", 200, task()),
+ (
+ "/markdown/task-1?target=external",
+ 200,
+ json!({"data": "Reproduce the race, then add a regression test."}),
+ ),
+ ],
+ properties,
+ );
+ assert!(matches!(
+ context.task_brief(access()).await,
+ Err(AgentSessionError::Unknown(_))
+ ));
+ server.join().unwrap();
+}
diff --git a/crates/agent_trigger/src/outbound/mod.rs b/crates/agent_trigger/src/outbound/mod.rs
index 87efbac504..06376e2ef7 100644
--- a/crates/agent_trigger/src/outbound/mod.rs
+++ b/crates/agent_trigger/src/outbound/mod.rs
@@ -2,16 +2,20 @@
mod bot_repo_agent_lookup;
mod channel_type_lookup;
+mod discussion_context;
mod dss_task_assignment_context;
mod fast_model_judge;
mod image_caption;
mod lexical_explicit_reply_extractor;
mod message_thread_history;
+mod people_directory;
pub use bot_repo_agent_lookup::BotRepoAgentLookup;
pub use channel_type_lookup::ChannelRepoTypeLookup;
+pub use discussion_context::{MessageDiscussionReader, ParentNameReader};
pub use dss_task_assignment_context::DssTaskAssignmentContext;
pub use fast_model_judge::FastModelTriggerJudge;
pub use image_caption::{ImageCaptioner, VisionImageCaptioner};
pub use lexical_explicit_reply_extractor::LexicalExplicitReplyExtractor;
pub use message_thread_history::MessageThreadHistory;
+pub use people_directory::PgPeopleDirectory;
diff --git a/crates/agent_trigger/src/outbound/people_directory.rs b/crates/agent_trigger/src/outbound/people_directory.rs
new file mode 100644
index 0000000000..16642daf13
--- /dev/null
+++ b/crates/agent_trigger/src/outbound/people_directory.rs
@@ -0,0 +1,162 @@
+//! Names people from MacroDB profiles and bots from the bots repository.
+
+#[cfg(test)]
+mod test;
+
+use std::collections::HashMap;
+
+use agent_session::domain::error::{AgentSessionError, Result};
+use bot_id::BotId;
+use bots::domain::ports::BotRepo;
+use channel_sender::ChannelSender;
+use sqlx::PgPool;
+use trigger_context::ContextPerson;
+
+use crate::domain::context::PeopleDirectory;
+
+/// Stands in for a name part a user never filled in.
+const UNSET_NAME: &str = "N/A";
+
+/// Reads the names bots carry. A seam so the directory can be tested without
+/// the bots table.
+trait BotNames: Send + Sync + 'static {
+ /// Names of the requested bots that have a profile, soft-deleted ones included.
+ fn bot_names(
+ &self,
+ bot_ids: &[BotId],
+ ) -> impl Future<Output = Result<HashMap<BotId, String>>> + Send;
+}
+
+impl<Repo: BotRepo> BotNames for Repo {
+ async fn bot_names(&self, bot_ids: &[BotId]) -> Result<HashMap<BotId, String>> {
+ let mut names: HashMap<BotId, String> = bot_ids
+ .iter()
+ .filter_map(|bot_id| {
+ bot_id::system_bot(*bot_id).map(|bot| (*bot_id, bot.name.to_owned()))
+ })
+ .collect();
+ let stored: Vec<BotId> = bot_ids
+ .iter()
+ .copied()
+ .filter(|bot_id| !names.contains_key(bot_id))
+ .collect();
+ if !stored.is_empty() {
+ let profiles = self
+ .get_bot_profiles(&stored)
+ .await
+ .map_err(|error| AgentSessionError::Unknown(error.into()))?;
+ names.extend(
+ profiles
+ .into_iter()
+ .map(|(bot_id, profile)| (bot_id, profile.name)),
+ );
+ }
+ Ok(names)
+ }
+}
+
+/// Names users by their profile name and bots by their profile.
+pub struct PgPeopleDirectory<Bots> {
+ pool: PgPool,
+ bots: Bots,
+}
+
+impl<Bots> PgPeopleDirectory<Bots> {
+ /// Compose MacroDB, for user names, with the bots repository.
+ pub fn new(pool: PgPool, bots: Bots) -> Self {
+ Self { pool, bots }
+ }
+
+ async fn user_names(&self, user_ids: Vec<String>) -> Result<HashMap<String, String>> {
+ if user_ids.is_empty() {
+ return Ok(HashMap::new());
+ }
+ let rows = sqlx::query!(
+ r#"
+ SELECT u.id as user_profile_id, mui.first_name, mui.last_name
+ FROM macro_user_info mui
+ JOIN "User" u ON mui.macro_user_id = u.macro_user_id
+ WHERE u.id = ANY($1)
+ "#,
+ &user_ids
+ )
+ .fetch_all(&self.pool)
+ .await
+ .map_err(|error| AgentSessionError::Unknown(error.into()))?;
+ Ok(rows
+ .into_iter()
+ .filter_map(|row| {
+ display_name(row.first_name.as_deref(), row.last_name.as_deref())
+ .map(|name| (row.user_profile_id, name))
+ })
+ .collect())
+ }
+}
+
+impl<Bots: BotNames> PeopleDirectory for PgPeopleDirectory<Bots> {
+ async fn people(&self, ids: Vec<String>) -> Result<Vec<ContextPerson>> {
+ let senders: Vec<Option<ChannelSender<'_>>> = ids
+ .iter()
+ .map(|id| ChannelSender::parse_from_str(id).ok())
+ .collect();
+ let user_ids = senders
+ .iter()
+ .flatten()
+ .filter_map(|sender| sender.as_user().map(|user| user.as_ref().to_owned()))
+ .collect();
+ let bot_ids: Vec<BotId> = senders
+ .iter()
+ .flatten()
+ .filter_map(|sender| sender.as_bot().map(|bot| bot.bot_id()))
+ .collect();
+ let user_names = self.user_names(user_ids).await?;
+ let bot_names = self.bots.bot_names(&bot_ids).await?;
+
+ Ok(ids
+ .iter()
+ .zip(&senders)
+ .map(|(id, sender)| {
+ let user = sender.as_ref().and_then(ChannelSender::as_user);
+ let bot = sender.as_ref().and_then(ChannelSender::as_bot);
+ match (user, bot) {
+ (Some(user), _) => ContextPerson {
+ id: id.clone(),
+ name: user_names
+ .get(id)
+ .cloned()
+ .unwrap_or_else(|| user.email_str().to_owned()),
+ email: Some(user.email_str().to_owned()),
+ },
+ (None, Some(bot)) => ContextPerson {
+ id: id.clone(),
+ name: bot_names
+ .get(&bot.bot_id())
+ .cloned()
+ .unwrap_or_else(|| id.clone()),
+ email: None,
+ },
+ (None, None) => ContextPerson {
+ id: id.clone(),
+ name: id.clone(),
+ email: None,
+ },
+ }
+ })
+ .collect())
+ }
+}
+
+/// "First Last" from whichever parts the user set.
+fn display_name(first: Option<&str>, last: Option<&str>) -> Option<String> {
+ match (name_part(first), name_part(last)) {
+ (None, None) => None,
+ (Some(only), None) | (None, Some(only)) => Some(only.to_owned()),
+ (Some(first), Some(last)) => Some(format!("{first} {last}")),
+ }
+}
+
+/// A name part the user actually set.
+fn name_part(part: Option<&str>) -> Option<&str> {
+ part.map(str::trim)
+ .filter(|part| !part.is_empty() && *part != UNSET_NAME)
+}
diff --git a/crates/agent_trigger/src/outbound/people_directory/fixtures/people.sql b/crates/agent_trigger/src/outbound/people_directory/fixtures/people.sql
new file mode 100644
index 0000000000..298bb85c7c
--- /dev/null
+++ b/crates/agent_trigger/src/outbound/people_directory/fixtures/people.sql
@@ -0,0 +1,14 @@
+INSERT INTO macro_user (id, username, email, stripe_customer_id) VALUES
+ ('00000000-0000-7000-8000-000000000001', '[email protected]', '[email protected]', 'stripe_julia'),
+ ('00000000-0000-7000-8000-000000000002', '[email protected]', '[email protected]', 'stripe_teo'),
+ ('00000000-0000-7000-8000-000000000003', '[email protected]', '[email protected]', 'stripe_nameless');
+
+INSERT INTO "User" (id, email, macro_user_id) VALUES
+ ('macro|[email protected]', '[email protected]', '00000000-0000-7000-8000-000000000001'),
+ ('macro|[email protected]', '[email protected]', '00000000-0000-7000-8000-000000000002'),
+ ('macro|[email protected]', '[email protected]', '00000000-0000-7000-8000-000000000003');
+
+-- Teo never set a last name; the nameless user never set either.
+INSERT INTO macro_user_info (macro_user_id, first_name, last_name) VALUES
+ ('00000000-0000-7000-8000-000000000001', 'Julia', 'Rivera'),
+ ('00000000-0000-7000-8000-000000000002', 'Teo', 'N/A');
diff --git a/crates/agent_trigger/src/outbound/people_directory/test.rs b/crates/agent_trigger/src/outbound/people_directory/test.rs
new file mode 100644
index 0000000000..ade5864b01
--- /dev/null
+++ b/crates/agent_trigger/src/outbound/people_directory/test.rs
@@ -0,0 +1,71 @@
+use super::*;
+use macro_db_migrator::MACRO_DB_MIGRATIONS;
+use macro_uuid::Uuid;
+
+/// One stored bot with a profile; every other bot has none.
+struct ProfiledBot;
+impl BotNames for ProfiledBot {
+ async fn bot_names(&self, bot_ids: &[BotId]) -> Result<HashMap<BotId, String>> {
+ Ok(bot_ids
+ .iter()
+ .filter(|bot_id| **bot_id == BotId::new_from_uuid(Uuid::from_u128(1)))
+ .map(|bot_id| (*bot_id, "Release Bot".to_owned()))
+ .collect())
+ }
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "fixtures", scripts("people"))
+)]
+async fn names_each_id_in_order(pool: PgPool) {
+ let directory = PgPeopleDirectory::new(pool, ProfiledBot);
+
+ let people = directory
+ .people(vec![
+ "macro|[email protected]".to_owned(),
+ "bot|00000000-0000-0000-0000-000000000001".to_owned(),
+ "macro|[email protected]".to_owned(),
+ "macro|[email protected]".to_owned(),
+ "bot|00000000-0000-0000-0000-000000000002".to_owned(),
+ "macro|[email protected]".to_owned(),
+ ])
+ .await
+ .unwrap();
+
+ assert_eq!(
+ people,
+ [
+ ContextPerson {
+ id: "macro|[email protected]".to_owned(),
+ name: "Julia Rivera".to_owned(),
+ email: Some("[email protected]".to_owned()),
+ },
+ ContextPerson {
+ id: "bot|00000000-0000-0000-0000-000000000001".to_owned(),
+ name: "Release Bot".to_owned(),
+ email: None,
+ },
+ ContextPerson {
+ id: "macro|[email protected]".to_owned(),
+ name: "Teo".to_owned(),
+ email: Some("[email protected]".to_owned()),
+ },
+ ContextPerson {
+ id: "macro|[email protected]".to_owned(),
+ name: "[email protected]".to_owned(),
+ email: Some("[email protected]".to_owned()),
+ },
+ ContextPerson {
+ id: "bot|00000000-0000-0000-0000-000000000002".to_owned(),
+ name: "bot|00000000-0000-0000-0000-000000000002".to_owned(),
+ email: None,
+ },
+ ContextPerson {
+ id: "macro|[email protected]".to_owned(),
+ name: "Julia Rivera".to_owned(),
+ email: Some("[email protected]".to_owned()),
+ },
+ ]
+ );
+}
diff --git a/crates/coding_agent_worker/Cargo.toml b/crates/coding_agent_worker/Cargo.toml
index 93fb29e5cf..b92da95f97 100644
--- a/crates/coding_agent_worker/Cargo.toml
+++ b/crates/coding_agent_worker/Cargo.toml
@@ -22,6 +22,7 @@ agent_session = { path = "../agent_session" }
agent_trigger = { path = "../agent_trigger" }
arboard = { workspace = true }
bot_id = { path = "../bot_id" }
+trigger_context = { path = "../trigger_context" }
chrono = { workspace = true }
clap = { workspace = true }
crossterm = { workspace = true }
diff --git a/crates/coding_agent_worker/src/dispatch.rs b/crates/coding_agent_worker/src/dispatch.rs
index bc2d27b94e..146944d4aa 100644
--- a/crates/coding_agent_worker/src/dispatch.rs
+++ b/crates/coding_agent_worker/src/dispatch.rs
@@ -135,6 +135,7 @@ impl WorkExecutor for Dispatcher {
thread_id,
message_id,
content,
+ context,
} => {
let session = AgentSessionId::new_from_uuid(uuid::Uuid::new_v5(
&bot.as_uuid(),
@@ -201,7 +202,7 @@ impl WorkExecutor for Dispatcher {
.ensure_connected()
.await
.map_err(DispatchError::Dial)?;
- self.api.prompt(session, &sender, &content).await?;
+ self.api.prompt(session, &sender, &content, context).await?;
return Ok(());
}
Err(ApiError::ThreadSessionExists { session: None }) => {
@@ -224,7 +225,7 @@ impl WorkExecutor for Dispatcher {
// answer. SSE has no redelivery; a later `agent_trigger.existing`
// or a 409 on a repeat create (session already exists) is how
// a follow-up lands on the same session.
- self.api.prompt(session, &sender, &content).await?;
+ self.api.prompt(session, &sender, &content, context).await?;
Ok(())
}
TriggerWork::OpenRequested {
@@ -264,13 +265,14 @@ impl WorkExecutor for Dispatcher {
session,
sender,
content,
+ context,
} => {
self.prompted(session, &sender);
self.runtime
.ensure_connected()
.await
.map_err(DispatchError::Dial)?;
- self.api.prompt(session, &sender, &content).await?;
+ self.api.prompt(session, &sender, &content, context).await?;
Ok(())
}
}
diff --git a/crates/coding_agent_worker/src/herdr/hub.rs b/crates/coding_agent_worker/src/herdr/hub.rs
index 05ad2250ba..8208e24893 100644
--- a/crates/coding_agent_worker/src/herdr/hub.rs
+++ b/crates/coding_agent_worker/src/herdr/hub.rs
@@ -537,7 +537,7 @@ async fn steer(inner: &Inner, session: &str, request: FromPane) -> Result<(), St
};
inner
.api
- .control(macro_session, &owner, action)
+ .control(macro_session, &owner, action, None)
.await
.map_err(|error| format!("Macro refused: {error}"))
}
diff --git a/crates/coding_agent_worker/src/outbound/agent_session.rs b/crates/coding_agent_worker/src/outbound/agent_session.rs
index 2838558094..327fbddd87 100644
--- a/crates/coding_agent_worker/src/outbound/agent_session.rs
+++ b/crates/coding_agent_worker/src/outbound/agent_session.rs
@@ -10,6 +10,7 @@ use agent_session::inbound::axum_router::{
};
use macro_user_id::user_id::MacroUserIdStr;
use reqwest::StatusCode;
+use trigger_context::TriggerContext;
use crate::config::{HarnessCredentials, MacroApi};
@@ -100,6 +101,7 @@ impl HarnessApi {
session: AgentSessionId,
actor: &MacroUserIdStr<'static>,
action: AgentAction,
+ context: Option<TriggerContext>,
) -> Result<(), ApiError> {
let response = self
.http
@@ -108,6 +110,7 @@ impl HarnessApi {
.header(HARNESS_ACTING_USER_HEADER, actor.as_ref())
.json(&ControlRequest {
action_id: None,
+ context,
action,
})
.send()
@@ -116,14 +119,16 @@ impl HarnessApi {
Ok(())
}
- /// Deliver a prompt to a session, acting for the user who sent it.
+ /// Deliver a prompt to a session, acting for the user who sent it, with
+ /// why the agent was called as the trigger read it.
pub async fn prompt(
&self,
session: AgentSessionId,
sender: &MacroUserIdStr<'static>,
text: &str,
+ context: Option<TriggerContext>,
) -> Result<(), ApiError> {
- self.control(session, sender, AgentAction::prompt(text))
+ self.control(session, sender, AgentAction::prompt(text), context)
.await
}
}
diff --git a/crates/coding_agent_worker/src/trigger.rs b/crates/coding_agent_worker/src/trigger.rs
index 625191014a..2d1ed4e527 100644
--- a/crates/coding_agent_worker/src/trigger.rs
+++ b/crates/coding_agent_worker/src/trigger.rs
@@ -8,11 +8,13 @@ use agent_trigger::domain::broker_events::{
AgentSessionRequestedEvent, AgentTriggerEventName, AgentTriggerTopicEvent,
NewAgentSessionEvent, OpeningMention, SessionMessage,
};
+use agent_trigger::domain::task_assignment::assignment_instructions;
use bot_id::BotId;
use macro_event_broker::Event;
use macro_user_id::user_id::MacroUserIdStr;
use macro_uuid::Uuid;
use strum::IntoEnumIterator as _;
+use trigger_context::TriggerContext;
use webhook::domain::models::WebhookFilter;
#[cfg(test)]
@@ -43,6 +45,8 @@ pub enum TriggerWork {
message_id: Uuid,
/// The mention's text: the first prompt, and the announcement quote.
content: String,
+ /// Why the agent was called, forwarded with the prompt.
+ context: Option<TriggerContext>,
},
/// Open a session somebody asked for from the composer, under the id
/// they are waiting on. No thread, so nothing is announced anywhere;
@@ -69,6 +73,8 @@ pub enum TriggerWork {
sender: MacroUserIdStr<'static>,
/// The message's text.
content: String,
+ /// Why the agent was called, forwarded with the prompt.
+ context: Option<TriggerContext>,
},
}
@@ -92,6 +98,7 @@ pub fn trigger_to_work(event: AgentTriggerTopicEvent) -> Result<TriggerWork, Ski
bot_id,
session_id,
owner,
+ context: _,
},
)) => {
let sender = MacroUserIdStr::try_from(owner).map_err(|_| Skipped::NotFromUser)?;
@@ -107,14 +114,26 @@ pub fn trigger_to_work(event: AgentTriggerTopicEvent) -> Result<TriggerWork, Ski
reuse_origin_message: true,
bot: assigned.bot_id,
sender: assigned.actor,
+ // The task travels in the context; the prompt is only what to
+ // do with it. Events from producers that predate the context
+ // carry the whole brief instead.
+ content: match &assigned.context {
+ Some(_) => assignment_instructions(&assigned.parent),
+ None => assigned.prompt,
+ },
parent: assigned.parent,
thread_id: assigned.discussion_id,
message_id: assigned.discussion_id,
- content: assigned.prompt,
+ context: assigned.context,
})
}
AgentTriggerTopicEvent::New(event) => {
- let Some(OpeningMention { bot_id, message }) = event.mention() else {
+ let Some(OpeningMention {
+ bot_id,
+ message,
+ context,
+ }) = event.mention()
+ else {
return Err(Skipped::Unrecognized);
};
let sender = message
@@ -132,12 +151,14 @@ pub fn trigger_to_work(event: AgentTriggerTopicEvent) -> Result<TriggerWork, Ski
thread_id: message.thread_id.unwrap_or(message.message_id),
message_id: message.message_id,
content: message.content,
+ context,
})
}
AgentTriggerTopicEvent::Existing(event) => {
let Some(SessionMessage {
session_id,
message,
+ context,
..
}) = event.session_message()
else {
@@ -152,6 +173,7 @@ pub fn trigger_to_work(event: AgentTriggerTopicEvent) -> Result<TriggerWork, Ski
session: session_id,
sender,
content: message.content,
+ context,
})
}
}
diff --git a/crates/coding_agent_worker/src/trigger/test.rs b/crates/coding_agent_worker/src/trigger/test.rs
index 98ce07f764..67a7b07c76 100644
--- a/crates/coding_agent_worker/src/trigger/test.rs
+++ b/crates/coding_agent_worker/src/trigger/test.rs
@@ -75,6 +75,7 @@ fn mention(content: &str) -> AgentTriggerTopicEvent {
AgentBotMentionedEvent {
bot_id: bot_id::BotId::TEST_A,
message: message(content, None),
+ context: None,
},
))
}
@@ -85,6 +86,7 @@ fn follow_up(content: &str) -> AgentTriggerTopicEvent {
session_id: test_session(),
kind: ThreadMessageKind::MentionThread,
message: message(content, Some(Uuid::from_u128(7))),
+ context: None,
}))
}
@@ -96,6 +98,7 @@ fn document_triggers_become_work_on_the_document() {
AgentTriggerTopicEvent::New(NewAgentSessionEvent::Mentioned(AgentMentionedEvent {
bot_id: bot_id::BotId::TEST_A,
message: document_message("summarize this", None),
+ context: None,
}));
assert_eq!(
trigger_to_work(opened).expect("a document mention is work"),
@@ -107,6 +110,7 @@ fn document_triggers_become_work_on_the_document() {
thread_id: Uuid::from_u128(2),
message_id: Uuid::from_u128(2),
content: "summarize this".to_owned(),
+ context: None,
}
);
let followed =
@@ -115,6 +119,7 @@ fn document_triggers_become_work_on_the_document() {
session_id: test_session(),
kind: ThreadMessageKind::Inferred,
message: document_message("and this", Some(Uuid::from_u128(7))),
+ context: None,
}));
assert_eq!(
trigger_to_work(followed).expect("a document follow-up is work"),
@@ -122,6 +127,7 @@ fn document_triggers_become_work_on_the_document() {
session: test_session(),
sender: sender(),
content: "and this".to_owned(),
+ context: None,
}
);
}
@@ -135,6 +141,7 @@ fn a_task_assignment_opens_and_prompts_in_the_task_discussion() {
discussion_id: Uuid::from_u128(2),
actor: sender(),
prompt: "Complete the assigned task".to_owned(),
+ context: None,
},
));
assert_eq!(
@@ -147,6 +154,7 @@ fn a_task_assignment_opens_and_prompts_in_the_task_discussion() {
thread_id: Uuid::from_u128(2),
message_id: Uuid::from_u128(2),
content: "Complete the assigned task".to_owned(),
+ context: None,
}
);
}
@@ -164,6 +172,7 @@ fn a_mention_becomes_open_and_prompt_rooting_its_own_thread() {
thread_id: Uuid::from_u128(2),
message_id: Uuid::from_u128(2),
content: "fix the test".to_owned(),
+ context: None,
}
);
}
@@ -177,6 +186,7 @@ fn a_follow_up_becomes_prompt_existing() {
session: test_session(),
sender: sender(),
content: "keep going".to_owned(),
+ context: None,
}
);
}
diff --git a/crates/lexical_client/Cargo.toml b/crates/lexical_client/Cargo.toml
index f9aea5106b..41a033d780 100644
--- a/crates/lexical_client/Cargo.toml
+++ b/crates/lexical_client/Cargo.toml
@@ -8,6 +8,7 @@ version = "0.1.0"
agent_fold = { path = "../folds/agent_fold", default-features = false }
anyhow = { workspace = true }
messages = { path = "../messages" }
+trigger_context = { path = "../trigger_context" }
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 e8b3bd834c..8f286d522e 100644
--- a/crates/lexical_client/src/parse_markdown.rs
+++ b/crates/lexical_client/src/parse_markdown.rs
@@ -4,6 +4,7 @@ mod test;
use super::LexicalClient;
use crate::types::{CognitionResponseData, CognitionV2ResponseData};
use messages::domain::models::MessageParent;
+use trigger_context::TriggerContext;
use crate::types::MarkdownParseResult;
use agent_fold::domain::model::MessageId;
@@ -255,63 +256,6 @@ struct AgentChatReplyRequest<'a> {
chat_reply: &'a AgentChatReply,
}
-/// A message included as context for an agent prompt.
-#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct AgentContextMessage<'a> {
- /// Message id.
- pub id: String,
- /// Sender identifier as the message service represents it.
- pub sender_id: &'a str,
- /// Readable name of the sender.
- pub author: &'a str,
- /// Markdown content of the message.
- pub content: &'a str,
- /// RFC 3339 time the message was posted.
- pub posted_at: String,
-}
-
-/// Messages of one discussion included as context, oldest first.
-#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct AgentContextThread<'a> {
- /// Root message of the discussion.
- pub root_id: String,
- /// Live messages, the root first when it is included.
- pub messages: Vec<AgentContextMessage<'a>>,
- /// Whether some messages of the discussion were left out.
- pub messages_omitted: bool,
-}
-
-/// What an agent prompt answers.
-#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
-#[serde(
- tag = "kind",
- rename_all = "camelCase",
- rename_all_fields = "camelCase"
-)]
-pub enum AgentContextReplyTarget<'a> {
- /// The author quote-replied to one message.
- Quote {
- /// The quoted message.
- message_id: String,
- /// The discussion holding the quoted message.
- thread_id: String,
- /// The one-line preview the quote renders.
- preview: &'a str,
- /// The quoted message in full, when it could be read.
- #[serde(skip_serializing_if = "Option::is_none")]
- message: Option<AgentContextMessage<'a>>,
- },
- /// The prompt was posted as a reply in a discussion.
- Thread {
- /// Root of that discussion.
- thread_id: String,
- },
- /// The prompt was posted at the top level of a channel.
- None,
-}
-
/// A person an agent session acts for or hears from.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
pub struct AgentContextPerson<'a> {
@@ -331,86 +275,16 @@ pub struct AgentContextPeople<'a> {
pub sender: Option<AgentContextPerson<'a>>,
}
-/// The conversation an agent prompt was posted in.
-#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct AgentContext<'a> {
- /// The document location of the comment thread, when it has one.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub anchor: Option<AgentContextAnchor<'a>>,
- /// What the prompt answers.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub reply_target: Option<AgentContextReplyTarget<'a>>,
- /// The prompting message, marked where it appears in the context.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub prompt_message_id: Option<String>,
- /// The discussion the prompt was posted in, through the prompt.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub thread: Option<AgentContextThread<'a>>,
- /// Other channel activity, grouped by discussion, oldest first.
- #[serde(skip_serializing_if = "Vec::is_empty")]
- pub channel: Vec<AgentContextThread<'a>>,
-}
-
-/// The document location of the comment thread an agent prompt was posted in.
-#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
-#[serde(
- tag = "type",
- rename_all = "camelCase",
- rename_all_fields = "camelCase"
-)]
-pub enum AgentContextAnchor<'a> {
- /// A cell or rectangular range in a native spreadsheet.
- Spreadsheet {
- /// Stable sheet identity within the workbook.
- sheet_id: &'a str,
- /// Sheet name when the discussion was created.
- sheet_name: &'a str,
- /// A1 cell or range, such as B4 or B4:C9.
- range: &'a str,
- },
-
- /// A comment mark in a markdown document.
- Markdown {
- /// Lexical mark the comment is attached to.
- mark_id: &'a str,
- /// The marked text when the comment was posted, when it was captured.
- #[serde(skip_serializing_if = "Option::is_none")]
- marked_text: Option<&'a str>,
- /// The text the mark covers in the document now, when it was resolved.
- #[serde(skip_serializing_if = "Option::is_none")]
- current_marked_text: Option<&'a str>,
- /// The passage around the mark now, when it was resolved.
- #[serde(skip_serializing_if = "Option::is_none")]
- surrounding_text: Option<&'a str>,
- },
- /// A highlight on a PDF.
- PdfHighlight {
- /// Highlight annotation the comment is attached to.
- anchor_id: &'a str,
- /// The text the highlight covers, when it carries any.
- #[serde(skip_serializing_if = "Option::is_none")]
- marked_text: Option<&'a str>,
- },
- /// A point pinned on a PDF page, which covers no text.
- PdfPin {
- /// Pin annotation the comment is attached to.
- anchor_id: &'a str,
- },
-}
-
#[derive(Debug, serde::Serialize)]
#[serde(rename_all = "camelCase")]
struct AgentContextRequest<'a> {
prompt_markdown: &'a str,
#[serde(skip_serializing_if = "Option::is_none")]
instructions: Option<&'a str>,
- #[serde(skip_serializing_if = "Option::is_none")]
- parent: Option<&'a MessageParent>,
#[serde(flatten, skip_serializing_if = "Option::is_none")]
people: Option<&'a AgentContextPeople<'a>>,
- #[serde(flatten, skip_serializing_if = "Option::is_none")]
- context: Option<&'a AgentContext<'a>>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ trigger: Option<&'a TriggerContext>,
}
#[derive(Debug, Clone, serde::Deserialize)]
@@ -730,17 +604,16 @@ impl LexicalClient {
Ok(data.markdown)
}
- /// Sanitizes an agent prompt and optionally composes it with the
- /// conversation it was posted in via the lexical service, so internal
- /// nodes and escaping are handled by Lexical rather than by the caller.
- #[tracing::instrument(skip(self, prompt_markdown, context), err)]
+ /// Sanitizes an agent prompt and optionally composes it with why the
+ /// agent was called via the lexical service, so internal nodes and
+ /// escaping are handled by Lexical rather than by the caller.
+ #[tracing::instrument(skip(self, prompt_markdown, trigger), err)]
pub async fn compose_agent_context(
&self,
prompt_markdown: &str,
instructions: Option<&str>,
- parent: Option<&MessageParent>,
people: Option<&AgentContextPeople<'_>>,
- context: Option<&AgentContext<'_>>,
+ trigger: Option<&TriggerContext>,
) -> Result<String> {
let url = format!("{}/agent-context", self.url);
let response = check_response(
@@ -749,9 +622,8 @@ impl LexicalClient {
.json(&AgentContextRequest {
prompt_markdown,
instructions,
- parent,
people,
- context,
+ trigger,
})
.send()
.await?,
diff --git a/crates/trigger_context/Cargo.toml b/crates/trigger_context/Cargo.toml
new file mode 100644
index 0000000000..793e35ac75
--- /dev/null
+++ b/crates/trigger_context/Cargo.toml
@@ -0,0 +1,18 @@
+[package]
+edition = "2024"
+name = "trigger_context"
+publish = false
+version = "0.1.0"
+
+# Why an agent was called, as it travels from whatever called it to whoever
+# composes the agent's prompt. Plain data, so the self-hosted daemon and the
+# session control API can carry it without the producers' dependencies.
+[dependencies]
+bot_id = { path = "../bot_id" }
+chrono = { workspace = true, features = ["serde"] }
+serde = { workspace = true }
+uuid = { workspace = true, features = ["serde"] }
+workspace-hack = { version = "0.1", path = "../workspace-hack" }
+
+[dev-dependencies]
+serde_json = { workspace = true }
diff --git a/crates/trigger_context/src/lib.rs b/crates/trigger_context/src/lib.rs
new file mode 100644
index 0000000000..2c1521f980
--- /dev/null
+++ b/crates/trigger_context/src/lib.rs
@@ -0,0 +1,519 @@
+//! Why an agent was called, and what about.
+//!
+//! One [`TriggerContext`] travels on each trigger event. Whoever delivers the
+//! prompt has lexical-service render it as XML ahead of the user's text, so
+//! every runtime sees the same account of the trigger. Everything here is
+//! untrusted context read under the triggering user's access: it describes the
+//! request, and grants nothing.
+
+use bot_id::BotId;
+use chrono::{DateTime, Utc};
+use serde::{Deserialize, Serialize};
+use uuid::Uuid;
+
+#[cfg(test)]
+mod test;
+
+/// What happened to call the agent, and everything it needs to know about it.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(tag = "kind", rename_all = "snake_case")]
+pub enum TriggerContext {
+ /// A mention opened the session.
+ Mentioned(DiscussionContext),
+ /// A further message in the discussion of a session that is already running.
+ FollowUp(FollowUpContext),
+ /// The agent was assigned a task.
+ TaskAssigned(TaskAssignedContext),
+ /// Someone opened the session from the composer. Their prompt arrives
+ /// separately, through the session itself.
+ Requested(RequestedContext),
+ /// Another agent handed this one a task.
+ Dispatched(DispatchedContext),
+ /// A routine fired.
+ Routine(RoutineContext),
+}
+
+/// What kind of channel a discussion is in.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum ChannelType {
+ /// Anyone in the organization can join.
+ Public,
+ /// Invited members only.
+ Private,
+ /// A conversation between two people.
+ DirectMessage,
+ /// A team's channel.
+ Team,
+}
+
+/// A person or bot, as a reader would name them.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct ContextPerson {
+ /// Stable identity: a Macro user id or a bot id.
+ pub id: String,
+ /// Display name, or the email when the user set none.
+ pub name: String,
+ /// Absent for bots and imported authors.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub email: Option<String>,
+}
+
+/// A message the agent may read.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct ContextMessage {
+ /// Message id.
+ pub id: Uuid,
+ /// Who wrote it.
+ pub author: ContextPerson,
+ /// Body, in internal markdown.
+ pub content: String,
+ /// When it was posted.
+ pub posted_at: DateTime<Utc>,
+}
+
+/// Messages of one discussion, oldest first.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct ContextThread {
+ /// Root message of the discussion.
+ pub root_id: Uuid,
+ /// Live messages, the root first when it is included.
+ pub messages: Vec<ContextMessage>,
+ /// Whether some messages of the discussion were left out.
+ pub messages_omitted: bool,
+}
+
+/// The discussion a message was posted in.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct DiscussionContext {
+ /// Where the discussion lives.
+ pub surface: DiscussionSurface,
+ /// The message that called the agent.
+ pub prompt_message_id: Uuid,
+ /// Who posted it.
+ pub sender: ContextPerson,
+ /// What the message answers.
+ pub reply_target: ReplyTarget,
+ /// The message's own discussion, from its root through the message.
+ /// Absent for a top-level channel message.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub thread: Option<ContextThread>,
+ /// Other recent channel activity, grouped by discussion, oldest first.
+ /// For a top-level channel message this is the primary context and ends
+ /// with the message. Empty off channels.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub channel: Vec<ContextThread>,
+}
+
+/// Where a discussion lives. Each carries its name, so the agent is never
+/// handed a bare id.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(tag = "type", rename_all = "snake_case")]
+pub enum DiscussionSurface {
+ /// A channel.
+ Channel {
+ /// Channel id.
+ id: Uuid,
+ /// Channel name; direct messages have none.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ name: Option<String>,
+ /// Public, private, direct message, or team.
+ channel_type: ChannelType,
+ },
+ /// A comment thread on a document.
+ DocumentComment {
+ /// Document id.
+ id: String,
+ /// Document name.
+ name: String,
+ /// Where in the document the thread sits, when it is anchored.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ anchor: Option<CommentAnchor>,
+ },
+ /// A comment thread on a project.
+ ProjectComment {
+ /// Project id.
+ id: Uuid,
+ /// Project name.
+ name: String,
+ },
+ /// A comment thread on a CRM company.
+ CrmCompanyComment {
+ /// Company id.
+ id: Uuid,
+ /// Company name.
+ name: String,
+ },
+ /// A comment thread on a CRM contact.
+ CrmContactComment {
+ /// Contact id.
+ id: Uuid,
+ /// Contact name.
+ name: String,
+ },
+ /// The chat of a call.
+ CallChat {
+ /// Call id.
+ id: Uuid,
+ /// Call title.
+ title: String,
+ },
+}
+
+/// What a message answers. Without this the agent has to guess which of the
+/// surrounding messages "fix this" means.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(tag = "kind", rename_all = "snake_case")]
+pub enum ReplyTarget {
+ /// The author quote-replied to one message.
+ Quote {
+ /// The quoted message.
+ message_id: Uuid,
+ /// The discussion holding the quoted message.
+ thread_id: Uuid,
+ /// The one-line preview the quote renders.
+ preview: String,
+ /// The quoted message in full. Absent when it lives in another
+ /// conversation or could not be read.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ message: Option<ContextMessage>,
+ },
+ /// The message was posted as a reply in a discussion.
+ Thread {
+ /// Root of that discussion.
+ root_id: Uuid,
+ },
+ /// The message was posted at the top level of a channel and replies to
+ /// no particular message.
+ None,
+}
+
+/// Where in a document a comment thread sits. An annotation id alone names a
+/// location the agent has no way to resolve, so the text it covers travels
+/// with it.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(tag = "type", rename_all = "snake_case")]
+pub enum CommentAnchor {
+ /// A cell or rectangular range in a native spreadsheet.
+ Spreadsheet {
+ /// Stable sheet identity within the workbook.
+ sheet_id: String,
+ /// Sheet name when the discussion was created.
+ sheet_name: String,
+ /// A1 cell or range, such as B4 or B4:C9.
+ range: String,
+ },
+ /// A comment mark in a markdown document.
+ Mark {
+ /// Lexical mark the thread is attached to.
+ mark_id: String,
+ /// The marked text as it read when the comment was posted. Absent on
+ /// threads anchored before snapshots were captured.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ marked_text: Option<String>,
+ /// The mark as the document reads now. Absent when the document no
+ /// longer carries it or the lookup failed.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ current: Option<MarkedPassage>,
+ },
+ /// A highlight on a PDF.
+ PdfHighlight {
+ /// Highlight annotation the thread is attached to.
+ anchor_id: String,
+ /// The text the highlight covers. Absent when the highlight carries none.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ marked_text: Option<String>,
+ },
+ /// A point pinned on a PDF page, which covers no text.
+ PdfPin {
+ /// Pin annotation the thread is attached to.
+ anchor_id: String,
+ },
+}
+
+/// A comment mark resolved against the live document.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct MarkedPassage {
+ /// The text the mark covers.
+ pub marked_text: String,
+ /// The block or blocks containing the mark, windowed around it.
+ pub surrounding_text: String,
+}
+
+/// A message for a session that is already running.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct FollowUpContext {
+ /// How the message reached this agent.
+ pub addressed_by: AddressedBy,
+ /// The discussion it was posted in.
+ pub discussion: DiscussionContext,
+}
+
+/// How a follow-up was attributed to the agent.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum AddressedBy {
+ /// The message mentions the agent.
+ Mention,
+ /// The message quote-replies to the agent, without a mention.
+ ExplicitReply,
+ /// A model judged the message was meant for the agent.
+ Inferred,
+}
+
+/// A task handed to the agent.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct TaskAssignedContext {
+ /// The task as it reads now.
+ pub task: TaskSnapshot,
+ /// Who assigned it.
+ pub assigned_by: ContextPerson,
+ /// When.
+ pub assigned_at: DateTime<Utc>,
+ /// The agent's own discussion on the task, where it answers.
+ pub discussion_id: Uuid,
+}
+
+/// A task, read under the assigner's access.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct TaskSnapshot {
+ /// Task id.
+ pub id: String,
+ /// Title.
+ pub title: String,
+ /// Description, in internal markdown.
+ pub markdown: String,
+ /// Status option name.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub status: Option<String>,
+ /// Priority option name.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub priority: Option<String>,
+ /// Due date.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub due: Option<DateTime<Utc>>,
+ /// Everyone assigned, people and agents.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub assignees: Vec<ContextPerson>,
+ /// The task's project, only when the assigner can see it.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub project: Option<ProjectRef>,
+}
+
+/// A project, by name.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct ProjectRef {
+ /// Project id.
+ pub id: Uuid,
+ /// Project name.
+ pub name: String,
+}
+
+/// A session opened from the composer.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct RequestedContext {
+ /// Who opened it.
+ pub requested_by: ContextPerson,
+ /// When.
+ pub requested_at: DateTime<Utc>,
+ /// Repository the requester picked.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub repo_url: Option<String>,
+}
+
+/// A task handed over by another agent.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct DispatchedContext {
+ /// The user whose authority the work runs under.
+ pub dispatched_by: ContextPerson,
+ /// When.
+ pub dispatched_at: DateTime<Utc>,
+ /// The agent that handed it over.
+ pub from_bot: Option<BotId>,
+ /// The session that handed it over, when it was one.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub from_session: Option<Uuid>,
+ /// Repository chosen for the work.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub repo_url: Option<String>,
+}
+
+/// A routine run.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct RoutineContext {
+ /// The routine's id.
+ pub routine_id: Uuid,
+ /// The routine's name.
+ pub name: String,
+ /// Whose routine it is.
+ pub owner: ContextPerson,
+ /// What the routine asks for, as its owner wrote it.
+ pub instructions: String,
+ /// Everything that makes it run.
+ pub triggers: Vec<RoutineTrigger>,
+ /// What made it fire this time.
+ pub firing: RoutineFiring,
+}
+
+/// One of the ways a routine runs.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(tag = "type", rename_all = "snake_case")]
+pub enum RoutineTrigger {
+ /// A cron schedule.
+ Schedule {
+ /// The cron expression.
+ cron: String,
+ /// The timezone it is read in.
+ timezone: String,
+ },
+ /// Events it watches.
+ Events {
+ /// The event names, such as `email.message_received`.
+ events: Vec<String>,
+ /// Only these entities, when the routine narrows to some.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ entity_ids: Vec<Uuid>,
+ /// A yes/no question the event's content must answer yes to.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ condition: Option<String>,
+ },
+}
+
+/// What made a routine fire.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(tag = "type", rename_all = "snake_case")]
+pub enum RoutineFiring {
+ /// Its schedule came due.
+ Scheduled {
+ /// When the run was due.
+ scheduled_for: DateTime<Utc>,
+ /// The schedule, as the routine states it.
+ schedule: String,
+ },
+ /// Its owner started it by hand.
+ Manual {
+ /// When they started it.
+ requested_at: DateTime<Utc>,
+ },
+ /// An event it watches happened.
+ Event {
+ /// The event. Boxed: it carries whole discussions and documents.
+ event: Box<RoutineEvent>,
+ /// The routine's yes/no questions this event was checked against;
+ /// it answered yes to at least one. Empty when the routine asks none.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ conditions: Vec<String>,
+ },
+}
+
+/// The event a routine fired on, one variant per event it can watch.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(tag = "event", rename_all = "snake_case")]
+pub enum RoutineEvent {
+ /// A document was created.
+ DocumentCreated {
+ /// The document.
+ document: DocumentSnapshot,
+ },
+ /// A document was edited.
+ DocumentUpdated {
+ /// The document as it reads now.
+ document: DocumentSnapshot,
+ },
+ /// A document was deleted.
+ DocumentDeleted {
+ /// Document id.
+ id: String,
+ /// Its name.
+ name: String,
+ },
+ /// A task was created.
+ TaskCreated {
+ /// The task.
+ task: TaskSnapshot,
+ },
+ /// A task's status changed.
+ TaskStatusChanged {
+ /// The task as it reads now.
+ task: TaskSnapshot,
+ },
+ /// A task's priority changed.
+ TaskPriorityChanged {
+ /// The task as it reads now.
+ task: TaskSnapshot,
+ },
+ /// Another of a task's properties changed. The event does not record
+ /// which one.
+ TaskPropertyChanged {
+ /// The task as it reads now.
+ task: TaskSnapshot,
+ },
+ /// An email arrived.
+ EmailReceived {
+ /// The email.
+ email: EmailSnapshot,
+ },
+ /// A channel was created.
+ ChannelCreated {
+ /// Channel id.
+ id: Uuid,
+ /// Channel name.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ name: Option<String>,
+ },
+ /// A message was posted in a channel.
+ ChannelMessagePosted {
+ /// The discussion it was posted in.
+ discussion: DiscussionContext,
+ },
+ /// Someone was mentioned in a channel.
+ ChannelMentioned {
+ /// The discussion the mention was posted in.
+ discussion: DiscussionContext,
+ },
+ /// A channel message was edited.
+ ChannelMessagePatched {
+ /// The discussion, with the message as it reads now.
+ discussion: DiscussionContext,
+ },
+ /// Something was attached to a channel message.
+ ChannelMessageAttachmentCreated {
+ /// The discussion holding the message.
+ discussion: DiscussionContext,
+ /// What was attached, such as a document.
+ entity_type: String,
+ /// Its id.
+ entity_id: String,
+ },
+}
+
+/// A document, read under the routine owner's access.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct DocumentSnapshot {
+ /// Document id.
+ pub id: String,
+ /// Name.
+ pub name: String,
+ /// File type, such as md or pdf.
+ pub file_type: String,
+ /// Text content, bounded. Absent for documents with no readable text.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub text: Option<String>,
+}
+
+/// An email, read under the routine owner's access.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct EmailSnapshot {
+ /// Thread id.
+ pub thread_id: Uuid,
+ /// Subject line.
+ pub subject: String,
+ /// Sender, as the email names them.
+ pub from: String,
+ /// Recipients.
+ pub to: Vec<String>,
+ /// When it arrived.
+ pub received_at: DateTime<Utc>,
+ /// Body as plain text, bounded.
+ pub body: String,
+}
diff --git a/crates/trigger_context/src/test.rs b/crates/trigger_context/src/test.rs
new file mode 100644
index 0000000000..ea01c8813e
--- /dev/null
+++ b/crates/trigger_context/src/test.rs
@@ -0,0 +1,153 @@
+use chrono::{TimeZone, Utc};
+use serde_json::json;
+
+use super::*;
+
+#[test]
+fn a_channel_follow_up_has_a_stable_wire_shape() {
+ let context = TriggerContext::FollowUp(FollowUpContext {
+ addressed_by: AddressedBy::ExplicitReply,
+ discussion: DiscussionContext {
+ surface: DiscussionSurface::Channel {
+ id: Uuid::parse_str("00000000-0000-0000-0000-0000000000c1").unwrap(),
+ name: Some("eng".to_owned()),
+ channel_type: ChannelType::Public,
+ },
+ prompt_message_id: Uuid::parse_str("00000000-0000-0000-0000-000000000003").unwrap(),
+ sender: ContextPerson {
+ id: "macro|[email protected]".to_owned(),
+ name: "Julia".to_owned(),
+ email: Some("[email protected]".to_owned()),
+ },
+ reply_target: ReplyTarget::Quote {
+ message_id: Uuid::parse_str("00000000-0000-0000-0000-000000000002").unwrap(),
+ thread_id: Uuid::parse_str("00000000-0000-0000-0000-000000000001").unwrap(),
+ preview: "The popover scrolls the page".to_owned(),
+ message: None,
+ },
+ thread: Some(ContextThread {
+ root_id: Uuid::parse_str("00000000-0000-0000-0000-000000000001").unwrap(),
+ messages: vec![ContextMessage {
+ id: Uuid::parse_str("00000000-0000-0000-0000-000000000003").unwrap(),
+ author: ContextPerson {
+ id: "macro|[email protected]".to_owned(),
+ name: "Julia".to_owned(),
+ email: Some("[email protected]".to_owned()),
+ },
+ content: "please fix".to_owned(),
+ posted_at: Utc.with_ymd_and_hms(2026, 10, 8, 14, 2, 0).unwrap(),
+ }],
+ messages_omitted: false,
+ }),
+ channel: Vec::new(),
+ },
+ });
+
+ let wire = json!({
+ "kind": "follow_up",
+ "addressed_by": "explicit_reply",
+ "discussion": {
+ "surface": {
+ "type": "channel",
+ "id": "00000000-0000-0000-0000-0000000000c1",
+ "name": "eng",
+ "channel_type": "public"
+ },
+ "prompt_message_id": "00000000-0000-0000-0000-000000000003",
+ "sender": {
+ "id": "macro|[email protected]",
+ "name": "Julia",
+ "email": "[email protected]"
+ },
+ "reply_target": {
+ "kind": "quote",
+ "message_id": "00000000-0000-0000-0000-000000000002",
+ "thread_id": "00000000-0000-0000-0000-000000000001",
+ "preview": "The popover scrolls the page"
+ },
+ "thread": {
+ "root_id": "00000000-0000-0000-0000-000000000001",
+ "messages": [{
+ "id": "00000000-0000-0000-0000-000000000003",
+ "author": {
+ "id": "macro|[email protected]",
+ "name": "Julia",
+ "email": "[email protected]"
+ },
+ "content": "please fix",
+ "posted_at": "2026-10-08T14:02:00Z"
+ }],
+ "messages_omitted": false
+ }
+ }
+ });
+
+ assert_eq!(serde_json::to_value(&context).unwrap(), wire);
+ assert_eq!(
+ serde_json::from_value::<TriggerContext>(wire).unwrap(),
+ context
+ );
+}
+
+#[test]
+fn a_task_assignment_has_a_stable_wire_shape() {
+ let context = TriggerContext::TaskAssigned(TaskAssignedContext {
+ task: TaskSnapshot {
+ id: "task-1".to_owned(),
+ title: "Fix calendar popover scroll".to_owned(),
+ markdown: "The popover scrolls the page behind it.".to_owned(),
+ status: Some("Todo".to_owned()),
+ priority: Some("High".to_owned()),
+ due: Some(Utc.with_ymd_and_hms(2026, 10, 10, 0, 0, 0).unwrap()),
+ assignees: vec![ContextPerson {
+ id: "bot|00000000-0000-0000-0000-00000000c5c5".to_owned(),
+ name: "Cursor".to_owned(),
+ email: None,
+ }],
+ project: Some(ProjectRef {
+ id: Uuid::parse_str("00000000-0000-0000-0000-0000000000a1").unwrap(),
+ name: "Calendar polish".to_owned(),
+ }),
+ },
+ assigned_by: ContextPerson {
+ id: "macro|[email protected]".to_owned(),
+ name: "Julia".to_owned(),
+ email: Some("[email protected]".to_owned()),
+ },
+ assigned_at: Utc.with_ymd_and_hms(2026, 10, 8, 14, 2, 0).unwrap(),
+ discussion_id: Uuid::parse_str("00000000-0000-0000-0000-0000000000d1").unwrap(),
+ });
+
+ let wire = json!({
+ "kind": "task_assigned",
+ "task": {
+ "id": "task-1",
+ "title": "Fix calendar popover scroll",
+ "markdown": "The popover scrolls the page behind it.",
+ "status": "Todo",
+ "priority": "High",
+ "due": "2026-10-10T00:00:00Z",
+ "assignees": [{
+ "id": "bot|00000000-0000-0000-0000-00000000c5c5",
+ "name": "Cursor"
+ }],
+ "project": {
+ "id": "00000000-0000-0000-0000-0000000000a1",
+ "name": "Calendar polish"
+ }
+ },
+ "assigned_by": {
+ "id": "macro|[email protected]",
+ "name": "Julia",
+ "email": "[email protected]"
+ },
+ "assigned_at": "2026-10-08T14:02:00Z",
+ "discussion_id": "00000000-0000-0000-0000-0000000000d1"
+ });
+
+ assert_eq!(serde_json::to_value(&context).unwrap(), wire);
+ assert_eq!(
+ serde_json::from_value::<TriggerContext>(wire).unwrap(),
+ context
+ );
+}
diff --git a/crates/webhook/src/domain/ingestion/test.rs b/crates/webhook/src/domain/ingestion/test.rs
index 9784dc229c..31de5a329b 100644
--- a/crates/webhook/src/domain/ingestion/test.rs
+++ b/crates/webhook/src/domain/ingestion/test.rs
@@ -1382,6 +1382,7 @@ fn agent_trigger_new_event() -> Event<agent_trigger::domain::broker_events::Agen
attachments: vec![],
created_at: timestamp(),
},
+ context: None,
}),
))
}
@@ -1400,6 +1401,7 @@ fn agent_trigger_requested_event()
uuid::Uuid::from_u128(0x5E55),
),
owner: "macro|[email protected]".to_owned(),
+ context: None,
}),
))
}
@@ -1426,6 +1428,7 @@ fn agent_trigger_document_event()
attachments: vec![],
created_at: timestamp(),
},
+ context: None,
}),
))
}
@@ -1453,6 +1456,7 @@ fn agent_trigger_existing_event()
attachments: vec![],
created_at: timestamp(),
},
+ context: None,
}),
))
}
@@ -1489,6 +1493,7 @@ fn agent_trigger_task_assignment_event() -> Event<AgentTriggerTopicEvent> {
discussion_id: uuid::Uuid::from_u128(2),
actor: user_id("macro|[email protected]"),
prompt: "Complete the assigned task".to_owned(),
+ context: None,
}),
))
}
diff --git a/packages/lexical-core/tests/agent-trigger-context.test.ts b/packages/lexical-core/tests/agent-trigger-context.test.ts
new file mode 100644
index 0000000000..660dbbaa04
--- /dev/null
+++ b/packages/lexical-core/tests/agent-trigger-context.test.ts
@@ -0,0 +1,566 @@
+import { describe, expect, it } from 'vitest';
+import type { SerializedAgentContextNode } from '../nodes/AgentContextNode';
+import { composeAgentContextPrompt } from '../utils/agent-context';
+import { markdownToSerializedEditorStateWithIds } from '../utils/markdown-state';
+
+function hiddenContext(markdown: string): string | undefined {
+ const [first] =
+ markdownToSerializedEditorStateWithIds(markdown).root.children;
+ if (first?.type !== 'agent-context') return undefined;
+ return (first as SerializedAgentContextNode).text;
+}
+
+describe('composeAgentContextPrompt with a trigger', () => {
+ it('renders a mention that opened the session with its document comment discussion', () => {
+ const markdown = composeAgentContextPrompt({
+ promptMarkdown: 'can you check the QA calendar?',
+ trigger: {
+ kind: 'mentioned',
+ surface: {
+ type: 'document_comment',
+ id: 'doc-1',
+ name: 'Launch plan',
+ anchor: {
+ type: 'mark',
+ mark_id: 'mark-1',
+ marked_text: 'ship Friday',
+ current: {
+ marked_text: 'ship Monday',
+ surrounding_text: 'We ship Monday after QA.',
+ },
+ },
+ },
+ prompt_message_id: 'm2',
+ sender: {
+ id: 'macro|[email protected]',
+ name: 'Julia',
+ email: '[email protected]',
+ },
+ reply_target: { kind: 'thread', root_id: 'm1' },
+ thread: {
+ root_id: 'm1',
+ messages: [
+ {
+ id: 'm1',
+ author: {
+ id: 'macro|[email protected]',
+ name: 'Teo',
+ email: '[email protected]',
+ },
+ content: 'Is Monday realistic?',
+ posted_at: '2026-10-08T14:00:00Z',
+ },
+ {
+ id: 'm2',
+ author: {
+ id: 'macro|[email protected]',
+ name: 'Julia',
+ email: '[email protected]',
+ },
+ content:
+ '<m-user-mention>{"userId":"bot|00000000-0000-0000-0000-00000000c5c5","displayName":"Cursor"}</m-user-mention> can you check the QA calendar?',
+ posted_at: '2026-10-08T14:02:00Z',
+ },
+ ],
+ messages_omitted: false,
+ },
+ },
+ });
+
+ expect(hiddenContext(markdown)).toBe(
+ [
+ '<trigger kind="mentioned">',
+ ' <note>Julia mentioned you, and that mention opened this session. Their message is the prompt.</note>',
+ ' <discussion>',
+ ' <document id="doc-1" name="Launch plan">',
+ ' <anchor type="mark" mark="mark-1">',
+ ' <note>marked_text is what the mark covers in the document now and surrounding_text the passage around it.</note>',
+ ' <marked_text>ship Monday</marked_text>',
+ ' <surrounding_text>We ship Monday after QA.</surrounding_text>',
+ ' <marked_text_when_posted>ship Friday</marked_text_when_posted>',
+ ' </anchor>',
+ ' </document>',
+ ' <origin>This prompt was posted in a document comment thread, not the agent session view. Your reply is posted back into that thread, and it is where the user will answer anything you ask.</origin>',
+ ' <sender name="Julia" email="[email protected]" id="macro|[email protected]"/>',
+ ' <reply_target kind="thread" thread="m1">',
+ ' <note>The prompt was posted as a reply in the thread below. It is about that thread.</note>',
+ ' </reply_target>',
+ ' <thread root="m1">',
+ ' <message id="m1" author="Teo" author_email="[email protected]" author_id="macro|[email protected]" at="2026-10-08T14:00:00Z">Is Monday realistic?</message>',
+ ' <message id="m2" author="Julia" author_email="[email protected]" author_id="macro|[email protected]" at="2026-10-08T14:02:00Z" mentioned_you="true">Cursor can you check the QA calendar?</message>',
+ ' </thread>',
+ ' </discussion>',
+ '</trigger>',
+ ].join('\n')
+ );
+ });
+
+ it('renders an inferred follow-up after the session block and warns the inference can be wrong', () => {
+ const markdown = composeAgentContextPrompt({
+ promptMarkdown: 'and the popover one too',
+ owner: { id: 'macro|[email protected]', name: 'Julia' },
+ sender: { id: 'macro|[email protected]', name: 'Julia' },
+ trigger: {
+ kind: 'follow_up',
+ addressed_by: 'inferred',
+ discussion: {
+ surface: {
+ type: 'channel',
+ id: 'c1',
+ name: 'eng',
+ channel_type: 'public',
+ },
+ prompt_message_id: 'p',
+ sender: {
+ id: 'macro|[email protected]',
+ name: 'Julia',
+ email: '[email protected]',
+ },
+ reply_target: { kind: 'none' },
+ channel: [
+ {
+ root_id: 'old',
+ messages: [
+ {
+ id: 'old',
+ author: {
+ id: 'macro|[email protected]',
+ name: 'Teo',
+ email: '[email protected]',
+ },
+ content: 'spinner never stops',
+ posted_at: '2026-10-08T13:00:00Z',
+ },
+ {
+ id: 'old2',
+ author: {
+ id: 'bot|00000000-0000-0000-0000-00000000c5c5',
+ name: 'Cursor',
+ },
+ content: 'Fixed in #12.',
+ posted_at: '2026-10-08T13:30:00Z',
+ },
+ ],
+ messages_omitted: false,
+ },
+ {
+ root_id: 'p',
+ messages: [
+ {
+ id: 'p',
+ author: {
+ id: 'macro|[email protected]',
+ name: 'Julia',
+ email: '[email protected]',
+ },
+ content: 'and the popover one too',
+ posted_at: '2026-10-08T14:02:00Z',
+ },
+ ],
+ messages_omitted: false,
+ },
+ ],
+ },
+ },
+ });
+
+ expect(hiddenContext(markdown)).toBe(
+ [
+ '<session owner="Julia" owner_id="macro|[email protected]">',
+ ' <prompted_by name="Julia" id="macro|[email protected]" is_owner="true"/>',
+ ' <note>Julia owns this session and sent this prompt.</note>',
+ '</session>',
+ '<trigger kind="follow_up" addressed_by="inferred">',
+ ' <note>This session was already running when Julia posted this message in its discussion. It neither mentions you nor quote-replies to you: a model judged from the discussion that it was meant for you. That judgment can be wrong, so if the message reads as meant for someone else, say so briefly instead of acting on it. The message is the prompt.</note>',
+ ' <discussion>',
+ ' <channel id="c1" name="eng" type="public"/>',
+ ' <origin>This prompt was posted in a channel thread, not the agent session view. Your reply is posted back into that thread, and it is where the user will answer anything you ask.</origin>',
+ ' <sender name="Julia" email="[email protected]" id="macro|[email protected]"/>',
+ ' <reply_target kind="none">',
+ ' <note>The prompt was posted at the top level of the channel and replies to no particular message.</note>',
+ ' </reply_target>',
+ ' <channel_recent>',
+ ' <note>Recent messages in this channel, grouped by thread, oldest first.</note>',
+ ' <thread root="old">',
+ ' <message id="old" author="Teo" author_email="[email protected]" author_id="macro|[email protected]" at="2026-10-08T13:00:00Z">spinner never stops</message>',
+ ' <message id="old2" author="Cursor" author_id="bot|00000000-0000-0000-0000-00000000c5c5" at="2026-10-08T13:30:00Z">Fixed in #12.</message>',
+ ' </thread>',
+ ' <message id="p" author="Julia" author_email="[email protected]" author_id="macro|[email protected]" at="2026-10-08T14:02:00Z" addressed_to_you="true">and the popover one too</message>',
+ ' </channel_recent>',
+ ' </discussion>',
+ '</trigger>',
+ ].join('\n')
+ );
+ });
+
+ it('renders a task assignment with the task, how the agent came to own it, and where it answers', () => {
+ const markdown = composeAgentContextPrompt({
+ promptMarkdown: 'Work on the assigned task.',
+ trigger: {
+ kind: 'task_assigned',
+ task: {
+ id: 'task-1',
+ title: 'Fix calendar popover scroll',
+ markdown:
+ 'The popover scrolls the page behind it. Ask <m-user-mention>{"userId":"macro|[email protected]","displayName":"Teo"}</m-user-mention> for repro steps.',
+ status: 'Todo',
+ priority: 'High',
+ due: '2026-10-10T00:00:00Z',
+ assignees: [
+ { id: 'bot|00000000-0000-0000-0000-00000000c5c5', name: 'Cursor' },
+ ],
+ project: { id: 'p-a1', name: 'Calendar polish' },
+ },
+ assigned_by: {
+ id: 'macro|[email protected]',
+ name: 'Julia',
+ email: '[email protected]',
+ },
+ assigned_at: '2026-10-08T14:02:00Z',
+ discussion_id: 'd1',
+ },
+ });
+
+ expect(hiddenContext(markdown)).toBe(
+ [
+ '<trigger kind="task_assigned" discussion="d1">',
+ ' <note>Julia assigned you this task. Your replies are posted to your own discussion on the task, where Julia and others on the task read them.</note>',
+ ' <assigned by="Julia" by_email="[email protected]" by_id="macro|[email protected]" at="2026-10-08T14:02:00Z"/>',
+ ' <task id="task-1" title="Fix calendar popover scroll" status="Todo" priority="High" due="2026-10-10T00:00:00Z">',
+ ' <project id="p-a1" name="Calendar polish"/>',
+ ' <assignees>',
+ ' <assignee name="Cursor" id="bot|00000000-0000-0000-0000-00000000c5c5"/>',
+ ' </assignees>',
+ ' <description>The popover scrolls the page behind it. Ask Teo for repro steps.</description>',
+ ' </task>',
+ '</trigger>',
+ ].join('\n')
+ );
+ });
+
+ it('renders a composer request and says the prompt follows', () => {
+ const markdown = composeAgentContextPrompt({
+ promptMarkdown: 'Upgrade the lexical packages.',
+ trigger: {
+ kind: 'requested',
+ requested_by: {
+ id: 'macro|[email protected]',
+ name: 'Julia',
+ email: '[email protected]',
+ },
+ requested_at: '2026-10-08T14:02:00Z',
+ repo_url: 'https://github.com/macro-inc/macro',
+ },
+ });
+
+ expect(hiddenContext(markdown)).toBe(
+ [
+ '<trigger kind="requested">',
+ ' <note>Julia opened this session from the composer. Their prompt follows.</note>',
+ ' <requested by="Julia" by_email="[email protected]" by_id="macro|[email protected]" at="2026-10-08T14:02:00Z" repo="https://github.com/macro-inc/macro"/>',
+ '</trigger>',
+ ].join('\n')
+ );
+ });
+
+ it('renders a dispatch from another agent', () => {
+ const markdown = composeAgentContextPrompt({
+ promptMarkdown: 'Fix the flaky sync test.',
+ trigger: {
+ kind: 'dispatched',
+ dispatched_by: {
+ id: 'macro|[email protected]',
+ name: 'Julia',
+ email: '[email protected]',
+ },
+ dispatched_at: '2026-10-08T14:02:00Z',
+ from_bot: '00000000-0000-0000-0000-00000000a2a2',
+ from_session: 's-1',
+ repo_url: 'https://github.com/macro-inc/macro',
+ },
+ });
+
+ expect(hiddenContext(markdown)).toBe(
+ [
+ '<trigger kind="dispatched">',
+ ' <note>Another agent handed you this task on behalf of Julia. The prompt is the task it handed over.</note>',
+ ' <dispatched by="Julia" by_email="[email protected]" by_id="macro|[email protected]" at="2026-10-08T14:02:00Z" from_bot="00000000-0000-0000-0000-00000000a2a2" from_session="s-1" repo="https://github.com/macro-inc/macro"/>',
+ '</trigger>',
+ ].join('\n')
+ );
+ });
+
+ it('renders a scheduled routine run', () => {
+ const markdown = composeAgentContextPrompt({
+ promptMarkdown: 'Triage the inbox.',
+ trigger: {
+ kind: 'routine',
+ routine_id: 'r-1',
+ name: 'Morning triage',
+ owner: {
+ id: 'macro|[email protected]',
+ name: 'Julia',
+ email: '[email protected]',
+ },
+ instructions: 'Sort new email into Finance and Support.',
+ triggers: [
+ {
+ type: 'schedule',
+ cron: '0 0 9 * * MON-FRI',
+ timezone: 'America/New_York',
+ },
+ ],
+ firing: {
+ type: 'scheduled',
+ scheduled_for: '2026-10-08T09:00:00Z',
+ schedule: 'Every weekday at 9:00',
+ },
+ },
+ });
+
+ expect(hiddenContext(markdown)).toBe(
+ [
+ '<trigger kind="routine">',
+ ' <note>The routine Morning triage, owned by Julia, fired. The prompt is what the routine asks you to do.</note>',
+ ' <routine id="r-1" name="Morning triage" owner="Julia" owner_email="[email protected]" owner_id="macro|[email protected]"/>',
+ ' <instructions>Sort new email into Finance and Support.</instructions>',
+ ' <triggers>',
+ ' <schedule cron="0 0 9 * * MON-FRI" timezone="America/New_York"/>',
+ ' </triggers>',
+ ' <scheduled for="2026-10-08T09:00:00Z" schedule="Every weekday at 9:00">',
+ ' <note>The routine ran because its schedule came due.</note>',
+ ' </scheduled>',
+ '</trigger>',
+ ].join('\n')
+ );
+ });
+
+ it('renders a routine fired by a task status change, with the change and the condition', () => {
+ const markdown = composeAgentContextPrompt({
+ promptMarkdown: 'Escalate the blocker.',
+ trigger: {
+ kind: 'routine',
+ routine_id: 'r-2',
+ name: 'Escalate blockers',
+ owner: {
+ id: 'macro|[email protected]',
+ name: 'Julia',
+ email: '[email protected]',
+ },
+ instructions: 'Tell the team when a task gets blocked.',
+ triggers: [
+ {
+ type: 'events',
+ events: ['task.status_changed'],
+ condition: 'Did the task move to Blocked?',
+ },
+ ],
+ firing: {
+ type: 'event',
+ event: {
+ event: 'task_status_changed',
+ task: {
+ id: 'task-2',
+ title: 'Renew SSL cert',
+ markdown: 'Expires Friday.',
+ status: 'Blocked',
+ },
+ },
+ conditions: ['Did the task move to Blocked?'],
+ },
+ },
+ });
+
+ expect(hiddenContext(markdown)).toBe(
+ [
+ '<trigger kind="routine">',
+ ' <note>The routine Escalate blockers, owned by Julia, fired. The prompt is what the routine asks you to do.</note>',
+ ' <routine id="r-2" name="Escalate blockers" owner="Julia" owner_email="[email protected]" owner_id="macro|[email protected]"/>',
+ ' <instructions>Tell the team when a task gets blocked.</instructions>',
+ ' <triggers>',
+ ' <events names="task.status_changed">',
+ ' <condition>Did the task move to Blocked?</condition>',
+ ' </events>',
+ ' </triggers>',
+ ' <event type="task_status_changed">',
+ ' <change property="status" to="Blocked"/>',
+ ' <task id="task-2" title="Renew SSL cert" status="Blocked">',
+ ' <description>Expires Friday.</description>',
+ ' </task>',
+ ' </event>',
+ ' <conditions>',
+ ' <note>The event answered yes to at least one of these.</note>',
+ ' <condition>Did the task move to Blocked?</condition>',
+ ' </conditions>',
+ '</trigger>',
+ ].join('\n')
+ );
+ });
+
+ it('renders a routine fired by an email', () => {
+ const markdown = composeAgentContextPrompt({
+ promptMarkdown: 'File the invoice.',
+ trigger: {
+ kind: 'routine',
+ routine_id: 'r-3',
+ name: 'Invoice intake',
+ owner: {
+ id: 'macro|[email protected]',
+ name: 'Julia',
+ email: '[email protected]',
+ },
+ instructions: 'File invoices into the Finance folder.',
+ triggers: [{ type: 'events', events: ['email.message_received'] }],
+ firing: {
+ type: 'event',
+ event: {
+ event: 'email_received',
+ email: {
+ thread_id: 'e-1',
+ subject: 'Invoice #42',
+ from: 'Acme Billing <[email protected]>',
+ received_at: '2026-10-08T08:15:00Z',
+ body: 'Please find invoice #42 attached.',
+ },
+ },
+ },
+ },
+ });
+
+ expect(hiddenContext(markdown)).toBe(
+ [
+ '<trigger kind="routine">',
+ ' <note>The routine Invoice intake, owned by Julia, fired. The prompt is what the routine asks you to do.</note>',
+ ' <routine id="r-3" name="Invoice intake" owner="Julia" owner_email="[email protected]" owner_id="macro|[email protected]"/>',
+ ' <instructions>File invoices into the Finance folder.</instructions>',
+ ' <triggers>',
+ ' <events names="email.message_received"/>',
+ ' </triggers>',
+ ' <event type="email_received">',
+ ' <email thread="e-1" subject="Invoice #42" from="Acme Billing &lt;[email protected]&gt;" to="[email protected], [email protected]" received_at="2026-10-08T08:15:00Z">',
+ ' <body>Please find invoice #42 attached.</body>',
+ ' </email>',
+ ' </event>',
+ '</trigger>',
+ ].join('\n')
+ );
+ });
+
+ it('renders a routine fired by a channel attachment without claiming the reply goes there', () => {
+ const markdown = composeAgentContextPrompt({
+ promptMarkdown: 'File the attachment.',
+ trigger: {
+ kind: 'routine',
+ routine_id: 'r-4',
+ name: 'File intake',
+ owner: {
+ id: 'macro|[email protected]',
+ name: 'Julia',
+ email: '[email protected]',
+ },
+ instructions: 'Summarise attached reports.',
+ triggers: [
+ { type: 'events', events: ['channel.message_attachment_created'] },
+ ],
+ firing: {
+ type: 'event',
+ event: {
+ event: 'channel_message_attachment_created',
+ entity_type: 'document',
+ entity_id: 'doc-q3',
+ discussion: {
+ surface: {
+ type: 'channel',
+ id: 'c2',
+ channel_type: 'direct_message',
+ },
+ prompt_message_id: 'f1',
+ sender: {
+ id: 'macro|[email protected]',
+ name: 'Teo',
+ email: '[email protected]',
+ },
+ reply_target: {
+ kind: 'quote',
+ message_id: 'q',
+ thread_id: 'q',
+ preview: 'send the numbers',
+ message: {
+ id: 'q',
+ author: {
+ id: 'macro|[email protected]',
+ name: 'Julia',
+ email: '[email protected]',
+ },
+ content: 'send the numbers',
+ posted_at: '2026-10-08T10:00:00Z',
+ },
+ },
+ thread: {
+ root_id: 'q',
+ messages: [
+ {
+ id: 'f1',
+ author: {
+ id: 'macro|[email protected]',
+ name: 'Teo',
+ email: '[email protected]',
+ },
+ content: 'here you go',
+ posted_at: '2026-10-08T10:05:00Z',
+ },
+ ],
+ messages_omitted: true,
+ },
+ },
+ },
+ },
+ },
+ });
+
+ expect(hiddenContext(markdown)).toBe(
+ [
+ '<trigger kind="routine">',
+ ' <note>The routine File intake, owned by Julia, fired. The prompt is what the routine asks you to do.</note>',
+ ' <routine id="r-4" name="File intake" owner="Julia" owner_email="[email protected]" owner_id="macro|[email protected]"/>',
+ ' <instructions>Summarise attached reports.</instructions>',
+ ' <triggers>',
+ ' <events names="channel.message_attachment_created"/>',
+ ' </triggers>',
+ ' <event type="channel_message_attachment_created">',
+ ' <attachment entity_type="document" entity_id="doc-q3"/>',
+ ' <discussion>',
+ ' <channel id="c2" type="direct_message"/>',
+ ' <sender name="Teo" email="[email protected]" id="macro|[email protected]"/>',
+ ' <reply_target kind="quote" message="q" thread="q">',
+ ' <note>The triggering message quote-replies to this message. It is what the triggering message is about.</note>',
+ ' <message id="q" author="Julia" author_email="[email protected]" author_id="macro|[email protected]" at="2026-10-08T10:00:00Z">send the numbers</message>',
+ ' </reply_target>',
+ ' <thread root="q" messages_omitted="true">',
+ ' <note>Some messages of this thread are not shown.</note>',
+ ' <message id="f1" author="Teo" author_email="[email protected]" author_id="macro|[email protected]" at="2026-10-08T10:05:00Z" fired_routine="true">here you go</message>',
+ ' </thread>',
+ ' </discussion>',
+ ' </event>',
+ '</trigger>',
+ ].join('\n')
+ );
+ });
+
+ it('refuses a trigger beside the legacy conversation fields', () => {
+ expect(() =>
+ composeAgentContextPrompt({
+ promptMarkdown: 'please fix',
+ parent: { type: 'channel', id: 'c1' },
+ trigger: {
+ kind: 'requested',
+ requested_by: { id: 'macro|[email protected]', name: 'Julia' },
+ requested_at: '2026-10-08T14:02:00Z',
+ },
+ })
+ ).toThrow(
+ 'trigger cannot be combined with legacy conversation fields: parent'
+ );
+ });
+});
diff --git a/packages/lexical-core/utils/agent-context.ts b/packages/lexical-core/utils/agent-context.ts
index dd6731d994..e8cfe162a6 100644
--- a/packages/lexical-core/utils/agent-context.ts
+++ b/packages/lexical-core/utils/agent-context.ts
@@ -10,6 +10,241 @@ import { $createAgentContextNode } from '../nodes/AgentContextNode';
import { ALL_TRANSFORMERS } from '../transformers';
import { buildXml } from '../transformers/xml';
import { el, type FxpNode } from '../transformers/xml/codecs';
+import { markdownToEmbeddingText } from './parsers';
+
+/**
+ * Why an agent was called, and what about. Mirrors the Rust `TriggerContext`
+ * in `crates/trigger_context/src/lib.rs` exactly as it arrives on the
+ * wire: snake_case fields, optional fields absent rather than null.
+ */
+export type TriggerContext =
+ | ({ kind: 'mentioned' } & DiscussionContext)
+ | ({ kind: 'follow_up' } & FollowUpContext)
+ | ({ kind: 'task_assigned' } & TaskAssignedContext)
+ | ({ kind: 'requested' } & RequestedContext)
+ | ({ kind: 'dispatched' } & DispatchedContext)
+ | ({ kind: 'routine' } & RoutineContext);
+
+/** A person or bot, as a reader would name them. */
+export type ContextPerson = {
+ /** A Macro user id or a bot id. */
+ id: string;
+ name: string;
+ /** Absent for bots and imported authors. */
+ email?: string;
+};
+
+/** A message the agent may read. */
+export type ContextMessage = {
+ id: string;
+ author: ContextPerson;
+ /** Internal markdown. */
+ content: string;
+ posted_at: string;
+};
+
+/** Messages of one discussion, oldest first. */
+export type ContextThread = {
+ root_id: string;
+ messages: ContextMessage[];
+ messages_omitted: boolean;
+};
+
+/** The discussion a message was posted in. */
+export type DiscussionContext = {
+ surface: DiscussionSurface;
+ prompt_message_id: string;
+ sender: ContextPerson;
+ reply_target: ReplyTarget;
+ /** Absent for a top-level channel message. */
+ thread?: ContextThread;
+ /** Absent when empty. */
+ channel?: ContextThread[];
+};
+
+export type ChannelType = 'public' | 'private' | 'direct_message' | 'team';
+
+/** Where a discussion lives. */
+export type DiscussionSurface =
+ | {
+ type: 'channel';
+ id: string;
+ /** Direct messages have none. */
+ name?: string;
+ channel_type: ChannelType;
+ }
+ | {
+ type: 'document_comment';
+ id: string;
+ name: string;
+ anchor?: CommentAnchor;
+ }
+ | { type: 'project_comment'; id: string; name: string }
+ | { type: 'crm_company_comment'; id: string; name: string }
+ | { type: 'crm_contact_comment'; id: string; name: string }
+ | { type: 'call_chat'; id: string; title: string };
+
+/** What a message answers. */
+export type ReplyTarget =
+ | {
+ kind: 'quote';
+ message_id: string;
+ thread_id: string;
+ preview: string;
+ /** Absent when the quoted message is elsewhere or unreadable. */
+ message?: ContextMessage;
+ }
+ | { kind: 'thread'; root_id: string }
+ | { kind: 'none' };
+
+/** Where in a document a comment thread sits. */
+export type CommentAnchor =
+ | { type: 'spreadsheet'; sheet_id: string; sheet_name: string; range: string }
+ | {
+ type: 'mark';
+ mark_id: string;
+ /** The marked text when the comment was posted. */
+ marked_text?: string;
+ /** The mark as the document reads now. */
+ current?: MarkedPassage;
+ }
+ | { type: 'pdf_highlight'; anchor_id: string; marked_text?: string }
+ | { type: 'pdf_pin'; anchor_id: string };
+
+/** A comment mark resolved against the live document. */
+export type MarkedPassage = { marked_text: string; surrounding_text: string };
+
+/** How a follow-up was attributed to the agent. */
+export type AddressedBy = 'mention' | 'explicit_reply' | 'inferred';
+
+/** A message for a session that is already running. */
+export type FollowUpContext = {
+ addressed_by: AddressedBy;
+ discussion: DiscussionContext;
+};
+
+/** A task handed to the agent. */
+export type TaskAssignedContext = {
+ task: TaskSnapshot;
+ assigned_by: ContextPerson;
+ assigned_at: string;
+ /** The agent's own discussion on the task, where it answers. */
+ discussion_id: string;
+};
+
+/** A task, read under the assigner's access. */
+export type TaskSnapshot = {
+ id: string;
+ title: string;
+ /** Description, in internal markdown. */
+ markdown: string;
+ status?: string;
+ priority?: string;
+ due?: string;
+ /** Absent when empty. */
+ assignees?: ContextPerson[];
+ project?: ProjectRef;
+};
+
+/** A project, by name. */
+export type ProjectRef = { id: string; name: string };
+
+/** A session opened from the composer. */
+export type RequestedContext = {
+ requested_by: ContextPerson;
+ requested_at: string;
+ repo_url?: string;
+};
+
+/** A task handed over by another agent. */
+export type DispatchedContext = {
+ /** The user whose authority the work runs under. */
+ dispatched_by: ContextPerson;
+ dispatched_at: string;
+ /** Rust sends null when absent. */
+ from_bot?: string | null;
+ from_session?: string;
+ repo_url?: string;
+};
+
+/** A routine run. */
+export type RoutineContext = {
+ routine_id: string;
+ name: string;
+ owner: ContextPerson;
+ /** What the routine asks for, as its owner wrote it. */
+ instructions: string;
+ triggers: RoutineTrigger[];
+ firing: RoutineFiring;
+};
+
+/** One of the ways a routine runs. */
+export type RoutineTrigger =
+ | { type: 'schedule'; cron: string; timezone: string }
+ | {
+ type: 'events';
+ events: string[];
+ /** Absent when the routine watches every entity. */
+ entity_ids?: string[];
+ condition?: string;
+ };
+
+/** What made a routine fire. */
+export type RoutineFiring =
+ | { type: 'scheduled'; scheduled_for: string; schedule: string }
+ | { type: 'manual'; requested_at: string }
+ | {
+ type: 'event';
+ event: RoutineEvent;
+ /** Questions the event was checked against; it answered yes to at least one. */
+ conditions?: string[];
+ };
+
+/** The event a routine fired on. */
+export type RoutineEvent =
+ | { event: 'document_created'; document: DocumentSnapshot }
+ | { event: 'document_updated'; document: DocumentSnapshot }
+ | { event: 'document_deleted'; id: string; name: string }
+ | { event: 'task_created'; task: TaskSnapshot }
+ | { event: 'task_status_changed'; task: TaskSnapshot }
+ | { event: 'task_priority_changed'; task: TaskSnapshot }
+ /** The event does not record which property changed. */
+ | { event: 'task_property_changed'; task: TaskSnapshot }
+ | { event: 'email_received'; email: EmailSnapshot }
+ | { event: 'channel_created'; id: string; name?: string }
+ | { event: 'channel_message_posted'; discussion: DiscussionContext }
+ | { event: 'channel_mentioned'; discussion: DiscussionContext }
+ | { event: 'channel_message_patched'; discussion: DiscussionContext }
+ | {
+ event: 'channel_message_attachment_created';
+ discussion: DiscussionContext;
+ entity_type: string;
+ entity_id: string;
+ };
+
+/** A document, read under the routine owner's access. */
+export type DocumentSnapshot = {
+ id: string;
+ name: string;
+ file_type: string;
+ /** Absent for documents with no readable text. */
+ text?: string;
+};
+
+/** An email, read under the routine owner's access. */
+export type EmailSnapshot = {
+ thread_id: string;
+ subject: string;
+ from: string;
+ to: string[];
+ received_at: string;
+ /** Plain text. */
+ body: string;
+};
+
+// LEGACY conversation fields. Remove these types, their renderer
+// (`renderConversation` and helpers), and the matching AgentContextPrompt
+// fields once every caller sends `trigger` instead.
/** A message supplied as untrusted agent context. */
export type AgentContextMessage = {
@@ -104,7 +339,12 @@ export type AgentContextPrompt = {
owner?: AgentContextPerson;
/** Who sent the prompt; absent when a bot sent it on nobody's behalf. */
sender?: AgentContextPerson;
- /** Supplied by the message service, never by the prompt's author. */
+ /**
+ * Why the agent was called. Supplied by the trigger pipeline, never by the
+ * prompt's author. Cannot be combined with the legacy fields below.
+ */
+ trigger?: TriggerContext;
+ /** LEGACY. Supplied by the message service, never by the prompt's author. */
parent?: AgentContextParent;
anchor?: AgentContextAnchor;
replyTarget?: AgentContextReplyTarget;
@@ -130,6 +370,19 @@ function present(
);
}
+/** Legacy conversation fields; none may travel beside `trigger`. */
+export const LEGACY_CONVERSATION_FIELDS = [
+ 'parent',
+ 'anchor',
+ 'replyTarget',
+ 'promptMessageId',
+ 'thread',
+ 'channel',
+] as const satisfies readonly (keyof AgentContextPrompt)[];
+
+// LEGACY renderer, from here through `renderConversation`. Remove once every
+// caller sends `trigger`.
+
function messageNode(
message: AgentContextMessage,
promptMessageId: string | undefined
@@ -379,6 +632,604 @@ function renderConversation(input: AgentContextPrompt): FxpNode | undefined {
);
}
+// End of the LEGACY renderer.
+
+/** Message bodies as the model should read them: names, not mention JSON. */
+const readable = (markdown: string): string =>
+ markdownToEmbeddingText(markdown);
+
+function personAttributes(
+ person: ContextPerson,
+ prefix: string
+): Record<string, string | undefined> {
+ return {
+ [prefix]: person.name,
+ [`${prefix}_email`]: person.email,
+ [`${prefix}_id`]: person.id,
+ };
+}
+
+function personNode(tag: string, person: ContextPerson): FxpNode {
+ return el(
+ tag,
+ [],
+ present({ name: person.name, email: person.email, id: person.id })
+ );
+}
+
+/** How a discussion relates to the session reading it. */
+type DiscussionReading = {
+ /** Attribute marking the message that called the agent. */
+ marker: string;
+ /** What the notes call that message. */
+ subject: 'prompt' | 'triggering message';
+ /** Whether the agent's reply is posted back into the discussion. */
+ repliesHere: boolean;
+};
+
+type MessageMarker = { attribute: string; messageId: string };
+
+function contextMessageNode(
+ message: ContextMessage,
+ marker: MessageMarker
+): FxpNode {
+ return el(
+ 'message',
+ [text(readable(message.content))],
+ present({
+ id: message.id,
+ ...personAttributes(message.author, 'author'),
+ at: message.posted_at,
+ [marker.attribute]: message.id === marker.messageId ? 'true' : undefined,
+ })
+ );
+}
+
+function contextThreadNode(
+ thread: ContextThread,
+ marker: MessageMarker
+): FxpNode {
+ return el(
+ 'thread',
+ [
+ ...(thread.messages_omitted
+ ? [note('Some messages of this thread are not shown.')]
+ : []),
+ ...thread.messages.map((message) => contextMessageNode(message, marker)),
+ ],
+ present({
+ root: thread.root_id,
+ messages_omitted: thread.messages_omitted ? 'true' : undefined,
+ })
+ );
+}
+
+function surfaceDescription(surface: DiscussionSurface): string {
+ return match(surface)
+ .with({ type: 'channel' }, () => 'a channel thread')
+ .with({ type: 'document_comment' }, () => 'a document comment thread')
+ .with({ type: 'project_comment' }, () => 'a project comment thread')
+ .with({ type: 'crm_company_comment' }, () => 'a CRM company comment thread')
+ .with({ type: 'crm_contact_comment' }, () => 'a CRM contact comment thread')
+ .with({ type: 'call_chat' }, () => 'a call chat thread')
+ .exhaustive();
+}
+
+/** Same building blocks as the legacy `anchorNode`, over the wire types. */
+function commentAnchorNode(anchor: CommentAnchor): FxpNode {
+ return match(anchor)
+ .with({ type: 'spreadsheet' }, ({ sheet_id, sheet_name, range }) =>
+ el(
+ 'anchor',
+ [note('Use ReadSpreadsheet to read the live cells in this range.')],
+ { type: 'spreadsheet', sheet_id, sheet_name, range }
+ )
+ )
+ .with({ type: 'pdf_pin' }, ({ anchor_id }) =>
+ el(
+ 'anchor',
+ [
+ note(
+ 'The comment is pinned to a point on a PDF page rather than to text, so it covers no words.'
+ ),
+ ],
+ { type: 'pdf_pin', pin: anchor_id }
+ )
+ )
+ .with({ type: 'pdf_highlight' }, ({ anchor_id, marked_text }) =>
+ el(
+ 'anchor',
+ [
+ marked_text === undefined
+ ? note(
+ 'The PDF highlight carries no text, so which words it covers is not known.'
+ )
+ : el('marked_text', [text(marked_text)]),
+ ],
+ { type: 'pdf_highlight', highlight: anchor_id }
+ )
+ )
+ .with({ type: 'mark' }, (mark) =>
+ el('anchor', markPassageChildren(mark), {
+ type: 'mark',
+ mark: mark.mark_id,
+ })
+ )
+ .exhaustive();
+}
+
+function markPassageChildren(
+ mark: Extract<CommentAnchor, { type: 'mark' }>
+): FxpNode[] {
+ return match(mark)
+ .with({ current: P.nonNullable }, ({ current, marked_text }) => [
+ note(
+ 'marked_text is what the mark covers in the document now and surrounding_text the passage around it.'
+ ),
+ el('marked_text', [text(current.marked_text)]),
+ el('surrounding_text', [text(current.surrounding_text)]),
+ ...(marked_text === undefined || marked_text === current.marked_text
+ ? []
+ : [el('marked_text_when_posted', [text(marked_text)])]),
+ ])
+ .with({ marked_text: P.string }, ({ marked_text }) => [
+ note(
+ 'marked_text_when_posted is what the mark covered when the comment was posted; the document may have changed since.'
+ ),
+ el('marked_text_when_posted', [text(marked_text)]),
+ ])
+ .otherwise(() => []);
+}
+
+/** Where a discussion lives, named; a document carries its comment anchor. */
+function surfaceNode(surface: DiscussionSurface): FxpNode {
+ return match(surface)
+ .with({ type: 'channel' }, ({ id, name, channel_type }) =>
+ el('channel', [], present({ id, name, type: channel_type }))
+ )
+ .with({ type: 'document_comment' }, ({ id, name, anchor }) =>
+ el('document', anchor ? [commentAnchorNode(anchor)] : [], { id, name })
+ )
+ .with({ type: 'project_comment' }, ({ id, name }) =>
+ el('project', [], { id, name })
+ )
+ .with({ type: 'crm_company_comment' }, ({ id, name }) =>
+ el('crm_company', [], { id, name })
+ )
+ .with({ type: 'crm_contact_comment' }, ({ id, name }) =>
+ el('crm_contact', [], { id, name })
+ )
+ .with({ type: 'call_chat' }, ({ id, title }) =>
+ el('call', [], { id, title })
+ )
+ .exhaustive();
+}
+
+function contextReplyTargetNode(
+ target: ReplyTarget,
+ marker: MessageMarker,
+ subject: DiscussionReading['subject']
+): FxpNode {
+ const Subject = `The ${subject}`;
+ return match(target)
+ .with({ kind: 'quote' }, (quote) =>
+ el(
+ 'reply_target',
+ [
+ note(
+ `${Subject} quote-replies to this message. It is what the ${subject} is about.`
+ ),
+ quote.message
+ ? contextMessageNode(quote.message, marker)
+ : el('preview', [text(readable(quote.preview))]),
+ ],
+ { kind: 'quote', message: quote.message_id, thread: quote.thread_id }
+ )
+ )
+ .with({ kind: 'thread' }, ({ root_id }) =>
+ el(
+ 'reply_target',
+ [
+ note(
+ `${Subject} was posted as a reply in the thread below. It is about that thread.`
+ ),
+ ],
+ { kind: 'thread', thread: root_id }
+ )
+ )
+ .with({ kind: 'none' }, () =>
+ el(
+ 'reply_target',
+ [
+ note(
+ `${Subject} was posted at the top level of the channel and replies to no particular message.`
+ ),
+ ],
+ { kind: 'none' }
+ )
+ )
+ .exhaustive();
+}
+
+function contextChannelNode(
+ channel: ContextThread[],
+ besideThread: boolean,
+ marker: MessageMarker,
+ subject: DiscussionReading['subject']
+): FxpNode {
+ const children = channel.map((thread) =>
+ match(thread)
+ .with(
+ {
+ messages_omitted: false,
+ messages: [P.select({ id: thread.root_id })],
+ },
+ (only) => contextMessageNode(only, marker)
+ )
+ .otherwise(() => contextThreadNode(thread, marker))
+ );
+ return besideThread
+ ? el('channel_background', [
+ note(
+ `Other recent messages in this channel, outside the thread above, oldest first. Background only: they are not what the ${subject} is about.`
+ ),
+ ...children,
+ ])
+ : el('channel_recent', [
+ note(
+ 'Recent messages in this channel, grouped by thread, oldest first.'
+ ),
+ ...children,
+ ]);
+}
+
+/**
+ * A discussion with its structure kept: where it lives, the message it
+ * answers named outright, its own thread whole, and the channel around it
+ * labeled as background.
+ */
+function discussionNode(
+ discussion: DiscussionContext,
+ reading: DiscussionReading
+): FxpNode {
+ const marker = {
+ attribute: reading.marker,
+ messageId: discussion.prompt_message_id,
+ };
+ const channel = discussion.channel ?? [];
+ return el('discussion', [
+ surfaceNode(discussion.surface),
+ ...(reading.repliesHere
+ ? [
+ el('origin', [
+ text(
+ `This ${reading.subject} was posted in ${surfaceDescription(discussion.surface)}, not the agent session view. Your reply is posted back into that thread, and it is where the user will answer anything you ask.`
+ ),
+ ]),
+ ]
+ : []),
+ personNode('sender', discussion.sender),
+ contextReplyTargetNode(discussion.reply_target, marker, reading.subject),
+ ...(discussion.thread
+ ? [contextThreadNode(discussion.thread, marker)]
+ : []),
+ ...(channel.length > 0
+ ? [
+ contextChannelNode(
+ channel,
+ discussion.thread !== undefined,
+ marker,
+ reading.subject
+ ),
+ ]
+ : []),
+ ]);
+}
+
+function taskNode(task: TaskSnapshot): FxpNode {
+ const assignees = task.assignees ?? [];
+ const description = readable(task.markdown);
+ return el(
+ 'task',
+ [
+ ...(task.project
+ ? [el('project', [], { id: task.project.id, name: task.project.name })]
+ : []),
+ ...(assignees.length > 0
+ ? [
+ el(
+ 'assignees',
+ assignees.map((assignee) => personNode('assignee', assignee))
+ ),
+ ]
+ : []),
+ ...(description.trim() ? [el('description', [text(description)])] : []),
+ ],
+ present({
+ id: task.id,
+ title: task.title,
+ status: task.status,
+ priority: task.priority,
+ due: task.due,
+ })
+ );
+}
+
+function documentNode(document: DocumentSnapshot): FxpNode {
+ return el(
+ 'document',
+ document.text === undefined ? [] : [text(readable(document.text))],
+ { id: document.id, name: document.name, file_type: document.file_type }
+ );
+}
+
+function mentionedNode(discussion: DiscussionContext): FxpNode {
+ return el(
+ 'trigger',
+ [
+ note(
+ `${discussion.sender.name} mentioned you, and that mention opened this session. Their message is the prompt.`
+ ),
+ discussionNode(discussion, {
+ marker: 'mentioned_you',
+ subject: 'prompt',
+ repliesHere: true,
+ }),
+ ],
+ { kind: 'mentioned' }
+ );
+}
+
+function followUpNode({ addressed_by, discussion }: FollowUpContext): FxpNode {
+ const { marker, explanation } = match(addressed_by)
+ .with('mention', () => ({
+ marker: 'mentioned_you',
+ explanation: 'It mentions you.',
+ }))
+ .with('explicit_reply', () => ({
+ marker: 'replied_to_you',
+ explanation:
+ 'It quote-replies to one of your messages without mentioning you.',
+ }))
+ .with('inferred', () => ({
+ marker: 'addressed_to_you',
+ explanation:
+ 'It neither mentions you nor quote-replies to you: a model judged from the discussion that it was meant for you. That judgment can be wrong, so if the message reads as meant for someone else, say so briefly instead of acting on it.',
+ }))
+ .exhaustive();
+ return el(
+ 'trigger',
+ [
+ note(
+ `This session was already running when ${discussion.sender.name} posted this message in its discussion. ${explanation} The message is the prompt.`
+ ),
+ discussionNode(discussion, {
+ marker,
+ subject: 'prompt',
+ repliesHere: true,
+ }),
+ ],
+ { kind: 'follow_up', addressed_by }
+ );
+}
+
+function taskAssignedNode(context: TaskAssignedContext): FxpNode {
+ const assigner = context.assigned_by.name;
+ return el(
+ 'trigger',
+ [
+ note(
+ `${assigner} assigned you this task. Your replies are posted to your own discussion on the task, where ${assigner} and others on the task read them.`
+ ),
+ el(
+ 'assigned',
+ [],
+ present({
+ ...personAttributes(context.assigned_by, 'by'),
+ at: context.assigned_at,
+ })
+ ),
+ taskNode(context.task),
+ ],
+ { kind: 'task_assigned', discussion: context.discussion_id }
+ );
+}
+
+function requestedNode(context: RequestedContext): FxpNode {
+ return el(
+ 'trigger',
+ [
+ note(
+ `${context.requested_by.name} opened this session from the composer. Their prompt follows.`
+ ),
+ el(
+ 'requested',
+ [],
+ present({
+ ...personAttributes(context.requested_by, 'by'),
+ at: context.requested_at,
+ repo: context.repo_url,
+ })
+ ),
+ ],
+ { kind: 'requested' }
+ );
+}
+
+function dispatchedNode(context: DispatchedContext): FxpNode {
+ return el(
+ 'trigger',
+ [
+ note(
+ `Another agent handed you this task on behalf of ${context.dispatched_by.name}. The prompt is the task it handed over.`
+ ),
+ el(
+ 'dispatched',
+ [],
+ present({
+ ...personAttributes(context.dispatched_by, 'by'),
+ at: context.dispatched_at,
+ from_bot: context.from_bot ?? undefined,
+ from_session: context.from_session,
+ repo: context.repo_url,
+ })
+ ),
+ ],
+ { kind: 'dispatched' }
+ );
+}
+
+const routineDiscussion: DiscussionReading = {
+ marker: 'fired_routine',
+ subject: 'triggering message',
+ repliesHere: false,
+};
+
+function routineEventChildren(event: RoutineEvent): FxpNode[] {
+ return match(event)
+ .with(
+ { event: P.union('document_created', 'document_updated') },
+ ({ document }) => [documentNode(document)]
+ )
+ .with({ event: 'document_deleted' }, ({ id, name }) => [
+ el('document', [], { id, name }),
+ ])
+ .with({ event: 'task_created' }, ({ task }) => [taskNode(task)])
+ .with({ event: 'task_status_changed' }, ({ task }) => [
+ el('change', [], present({ property: 'status', to: task.status })),
+ taskNode(task),
+ ])
+ .with({ event: 'task_priority_changed' }, ({ task }) => [
+ el('change', [], present({ property: 'priority', to: task.priority })),
+ taskNode(task),
+ ])
+ .with({ event: 'task_property_changed' }, ({ task }) => [
+ el('change', [
+ note(
+ "One of the task's properties changed; which one is not recorded."
+ ),
+ ]),
+ taskNode(task),
+ ])
+ .with({ event: 'email_received' }, ({ email }) => [
+ el('email', [el('body', [text(email.body)])], {
+ thread: email.thread_id,
+ subject: email.subject,
+ from: email.from,
+ to: email.to.join(', '),
+ received_at: email.received_at,
+ }),
+ ])
+ .with({ event: 'channel_created' }, ({ id, name }) => [
+ el('channel', [], present({ id, name })),
+ ])
+ .with(
+ {
+ event: P.union(
+ 'channel_message_posted',
+ 'channel_mentioned',
+ 'channel_message_patched'
+ ),
+ },
+ ({ discussion }) => [discussionNode(discussion, routineDiscussion)]
+ )
+ .with(
+ { event: 'channel_message_attachment_created' },
+ ({ discussion, entity_type, entity_id }) => [
+ el('attachment', [], { entity_type, entity_id }),
+ discussionNode(discussion, routineDiscussion),
+ ]
+ )
+ .exhaustive();
+}
+
+function routineFiringNodes(firing: RoutineFiring): FxpNode[] {
+ return match(firing)
+ .with({ type: 'scheduled' }, ({ scheduled_for, schedule }) => [
+ el(
+ 'scheduled',
+ [note('The routine ran because its schedule came due.')],
+ {
+ for: scheduled_for,
+ schedule,
+ }
+ ),
+ ])
+ .with({ type: 'manual' }, ({ requested_at }) => [
+ el('manual', [note("The routine's owner started this run by hand.")], {
+ requested_at,
+ }),
+ ])
+ .with({ type: 'event' }, ({ event, conditions }) => [
+ el('event', routineEventChildren(event), { type: event.event }),
+ ...(conditions === undefined || conditions.length === 0
+ ? []
+ : [
+ el('conditions', [
+ note('The event answered yes to at least one of these.'),
+ ...conditions.map((condition) =>
+ el('condition', [text(condition)])
+ ),
+ ]),
+ ]),
+ ])
+ .exhaustive();
+}
+
+function routineTriggerNode(trigger: RoutineTrigger): FxpNode {
+ return match(trigger)
+ .with({ type: 'schedule' }, ({ cron, timezone }) =>
+ el('schedule', [], { cron, timezone })
+ )
+ .with({ type: 'events' }, ({ events, entity_ids, condition }) =>
+ el(
+ 'events',
+ condition === undefined ? [] : [el('condition', [text(condition)])],
+ present({
+ names: events.join(', '),
+ only: entity_ids?.join(', '),
+ })
+ )
+ )
+ .exhaustive();
+}
+
+function routineNode(context: RoutineContext): FxpNode {
+ return el(
+ 'trigger',
+ [
+ note(
+ `The routine ${context.name}, owned by ${context.owner.name}, fired. The prompt is what the routine asks you to do.`
+ ),
+ el(
+ 'routine',
+ [],
+ present({
+ id: context.routine_id,
+ name: context.name,
+ ...personAttributes(context.owner, 'owner'),
+ })
+ ),
+ el('instructions', [text(context.instructions)]),
+ el('triggers', context.triggers.map(routineTriggerNode)),
+ ...routineFiringNodes(context.firing),
+ ],
+ { kind: 'routine' }
+ );
+}
+
+/** Why the agent was called, one renderer per kind. */
+function triggerNode(trigger: TriggerContext): FxpNode {
+ return match(trigger)
+ .with({ kind: 'mentioned' }, mentionedNode)
+ .with({ kind: 'follow_up' }, followUpNode)
+ .with({ kind: 'task_assigned' }, taskAssignedNode)
+ .with({ kind: 'requested' }, requestedNode)
+ .with({ kind: 'dispatched' }, dispatchedNode)
+ .with({ kind: 'routine' }, routineNode)
+ .exhaustive();
+}
+
/**
* Name who the session acts for and who is asking. The agent runs with the
* owner's access, so a prompt from anyone else must not be able to spend it
@@ -411,11 +1262,22 @@ function sessionNode(
);
}
+/** Legacy conversation fields the input sets. */
+export function legacyConversationFieldsIn(
+ input: Partial<Record<(typeof LEGACY_CONVERSATION_FIELDS)[number], unknown>>
+): (typeof LEGACY_CONVERSATION_FIELDS)[number][] {
+ return LEGACY_CONVERSATION_FIELDS.filter(
+ (field) => input[field] !== undefined
+ );
+}
+
function renderContext(input: AgentContextPrompt): string | undefined {
- const conversation = renderConversation(input);
+ const body = input.trigger
+ ? triggerNode(input.trigger)
+ : renderConversation(input);
const nodes = [
...(input.owner ? [sessionNode(input.owner, input.sender)] : []),
- ...(conversation ? [conversation] : []),
+ ...(body ? [body] : []),
];
if (nodes.length === 0) return undefined;
// The builder opens with a newline when formatting.
@@ -443,6 +1305,13 @@ function escapeAgentContextTags(markdown: string): string {
* it came from. The internal markdown transformer owns envelope encoding.
*/
export function composeAgentContextPrompt(input: AgentContextPrompt): string {
+ const legacy = legacyConversationFieldsIn(input);
+ if (input.trigger && legacy.length > 0) {
+ throw new Error(
+ `trigger cannot be combined with legacy conversation fields: ${legacy.join(', ')}`
+ );
+ }
+
const editor = createHeadlessEditor({
nodes: [...SupportedNodeTypes, ...NodeReplacements],
});
diff --git a/packages/sdk/generated/agent-harness/types.gen.ts b/packages/sdk/generated/agent-harness/types.gen.ts
index 4eeaf4c7f0..49b2a9f832 100644
--- a/packages/sdk/generated/agent-harness/types.gen.ts
+++ b/packages/sdk/generated/agent-harness/types.gen.ts
@@ -720,6 +720,13 @@ export type CompleteRequest = {
*/
export type ControlRequest = AgentAction & {
actionId?: null | AgentActionId;
+ /**
+ * Why the agent is being asked. Only a runtime forwarding a triggered
+ * prompt may send it; a user's request carrying it is refused.
+ */
+ context?: {
+ [key: string]: unknown;
+ } | null;
};
/**
diff --git a/packages/sdk/specs/agent-harness.json b/packages/sdk/specs/agent-harness.json
index 929013f7dc..08de27bd58 100644
--- a/packages/sdk/specs/agent-harness.json
+++ b/packages/sdk/specs/agent-harness.json
@@ -3265,6 +3265,10 @@
"description": "The id the caller already speculated this action under, when it has\none. Adopted as the accepted id, so a client that renders the action\noptimistically promotes that entry in place instead of retracting it\nand re-speculating under a server id. Re-sending the same id is not a\nsecond action: see [`ControlResponse`].\n\nNamed rather than flattened so it cannot collide with the action's own\nfields, which are tagged under `type`."
}
]
+ },
+ "context": {
+ "type": ["object", "null"],
+ "description": "Why the agent is being asked. Only a runtime forwarding a triggered\nprompt may send it; a user's request carrying it is refused."
}
}
}
diff --git a/services/agent_harness_service/Cargo.toml b/services/agent_harness_service/Cargo.toml
index 4d0d13ba72..7d70a7e5a3 100644
--- a/services/agent_harness_service/Cargo.toml
+++ b/services/agent_harness_service/Cargo.toml
@@ -23,6 +23,7 @@ roles_and_permissions = { path = "../../crates/roles_and_permissions", default-f
teams = { path = "../../crates/teams", default-features = false, features = ["outbound"] }
initiative = { path = "../../crates/initiative", default-features = false, features = ["postgres"] }
crm = { path = "../../crates/crm", default-features = false, features = ["lookup"] }
+call = { path = "../../crates/call", default-features = false, features = ["outbound"] }
codex_cloud_agents = { path = "../../crates/codex_cloud_agents" }
codex_connection = { path = "../../crates/codex_connection" }
agent_changes = { path = "../../crates/agent_changes" }
diff --git a/services/agent_harness_service/src/external_session_requests.rs b/services/agent_harness_service/src/external_session_requests.rs
index 2541f6920b..22b64061e1 100644
--- a/services/agent_harness_service/src/external_session_requests.rs
+++ b/services/agent_harness_service/src/external_session_requests.rs
@@ -49,6 +49,9 @@ where
repo_url: request.repo_url,
session_id,
owner: request.owner.as_ref().to_owned(),
+ // The requester's prompt follows through the session's control
+ // endpoint, from the app; nothing composes it with this event.
+ context: None,
});
self.broker
.send_event(&event)
diff --git a/services/agent_harness_service/src/main.rs b/services/agent_harness_service/src/main.rs
index de8f99c25d..00e99c3314 100644
--- a/services/agent_harness_service/src/main.rs
+++ b/services/agent_harness_service/src/main.rs
@@ -946,11 +946,8 @@ async fn run() -> anyhow::Result<()> {
);
let prompt_mentions =
LexicalPromptMentions::new(lexical.clone(), PgSessionAccess::new(pool.clone()));
- let prompt_context = MessagePromptContextAdapter::new(
- message_service.clone(),
- Arc::clone(&entity_access),
- Arc::new(lexical.clone()),
- );
+ let prompt_context =
+ MessagePromptContextAdapter::new(message_service.clone(), Arc::clone(&entity_access));
let prompt_composer = LexicalAgentPromptComposer::new(lexical);
// One connection per harness, shared by every session of every agent
diff --git a/services/agent_harness_service/src/trigger.rs b/services/agent_harness_service/src/trigger.rs
index feeefd06a2..04e73e6881 100644
--- a/services/agent_harness_service/src/trigger.rs
+++ b/services/agent_harness_service/src/trigger.rs
@@ -1,6 +1,7 @@
//! Committed-post consumer that emits agent-session trigger events.
use agent_session::outbound::postgres::PgAgentSessionRepo;
+use agent_trigger::domain::context::{DiscussionReader, PeopleDirectory};
use agent_trigger::domain::processing::process_message_event;
use agent_trigger::domain::project_assignment::ProjectAssignmentService;
use agent_trigger::domain::service::AgentTriggerService;
@@ -10,7 +11,8 @@ use agent_trigger::domain::task_assignment::{
};
use agent_trigger::outbound::{
BotRepoAgentLookup, ChannelRepoTypeLookup, DssTaskAssignmentContext, FastModelTriggerJudge,
- LexicalExplicitReplyExtractor, MessageThreadHistory, VisionImageCaptioner,
+ LexicalExplicitReplyExtractor, MessageDiscussionReader, MessageThreadHistory, ParentNameReader,
+ PgPeopleDirectory, VisionImageCaptioner,
};
use bots::outbound::pg_bots_repo::PgBotsRepo;
use channels::outbound::pg_channels_repo::PgChannelsRepo;
@@ -142,16 +144,53 @@ async fn run(
messages,
} = services;
let lexical = LexicalClient::new(internal_api_key, LexicalServiceUrl::new()?.to_string());
+ let documents = DocumentStorageServiceClient::new(
+ document_storage_service_auth_key,
+ DocumentStorageServiceUrl::new()?.to_string(),
+ );
let task_context = ProjectTaskAssignmentContext::new(
DssTaskAssignmentContext::new(
- DocumentStorageServiceClient::new(
- document_storage_service_auth_key,
- DocumentStorageServiceUrl::new()?.to_string(),
- ),
+ documents.clone(),
lexical.clone(),
+ PropertiesServiceImpl::new(
+ PropertiesPgRepo::new(pool.clone()),
+ Some(PermissionServiceImpl::new(
+ pool.clone(),
+ Arc::new(EntityAccessServiceImpl::new(PgAccessRepository::new(
+ pool.clone(),
+ ))),
+ )),
+ None::<SilentAssignmentNotifications>,
+ ),
),
SystemPropertiesServiceImpl::new(PgSystemPropertiesRepository::new(pool.clone())),
EntityAccessServiceImpl::new(PgAccessRepository::new(pool.clone())),
+ initiative::domain::lookup::InitiativeLookup::new(
+ initiative::outbound::PgInitiativeRepo::new(pool.clone()),
+ ),
+ );
+ let message_reader = Arc::new(messages::domain::service::MessageService::new(
+ PgMessageRepository::new(pool.clone())
+ .with_initiatives(initiative::domain::lookup::InitiativeLookup::new(
+ initiative::outbound::PgInitiativeRepo::new(pool.clone()),
+ ))
+ .with_crm(crm::outbound::lookup::PgCrmParentReader::new(pool.clone())),
+ messages::domain::ports::NoMessageEventPublisher,
+ ));
+ let people = PgPeopleDirectory::new(pool.clone(), PgBotsRepo::new(pool.clone()));
+ let discussions = MessageDiscussionReader::new(
+ message_reader.clone(),
+ PgPeopleDirectory::new(pool.clone(), PgBotsRepo::new(pool.clone())),
+ ParentNameReader::new(
+ PgChannelsRepo::new(pool.clone()),
+ documents,
+ initiative::domain::lookup::InitiativeLookup::new(
+ initiative::outbound::PgInitiativeRepo::new(pool.clone()),
+ ),
+ crm::outbound::lookup::PgCrmParentReader::new(pool.clone()),
+ call::outbound::pg_call_repo::PgCallRepo::new(pool.clone()),
+ ),
+ lexical.clone(),
);
let images = VisionImageCaptioner::new(
static_file::outbound::CdnStaticFileRepo::new(StaticFileServiceUrl::new()?.to_string()),
@@ -168,14 +207,7 @@ async fn run(
LexicalExplicitReplyExtractor::new(lexical),
FastModelTriggerJudge::new(recorder, images),
MessageThreadHistory::new(
- std::sync::Arc::new(messages::domain::service::MessageService::new(
- PgMessageRepository::new(pool.clone())
- .with_initiatives(initiative::domain::lookup::InitiativeLookup::new(
- initiative::outbound::PgInitiativeRepo::new(pool.clone()),
- ))
- .with_crm(crm::outbound::lookup::PgCrmParentReader::new(pool.clone())),
- messages::domain::ports::NoMessageEventPublisher,
- )),
+ message_reader,
entity_access::domain::service::EntityAccessServiceImpl::new(
entity_access::outbound::PgAccessRepository::new(pool.clone()),
),
@@ -208,7 +240,11 @@ async fn run(
consumer,
&trigger,
&publisher,
- &channel_types,
+ &ContextReaders {
+ channel_types,
+ discussions,
+ people,
+ },
messages.as_ref(),
&task_context,
&project_assignments,
@@ -216,12 +252,19 @@ async fn run(
.await
}
+/// What the trigger reads beside the post to describe the agents it calls.
+struct ContextReaders<Discussions, People> {
+ channel_types: ChannelTypes,
+ discussions: Discussions,
+ people: People,
+}
+
/// Read the trigger topic until it fails, evaluating every committed post.
async fn consume<Events: TriggerEvents>(
consumer: KafkaConsumerAdapter<AgentTriggerConsumerGroup, ()>,
trigger: &Trigger,
publisher: &Publisher,
- channel_types: &ChannelTypes,
+ readers: &ContextReaders<impl DiscussionReader, impl PeopleDirectory>,
messages: &dyn MessageServiceApi,
task_context: &impl TaskAssignmentContext,
project_assignments: &ProjectAssignmentService<
@@ -272,11 +315,25 @@ async fn consume<Events: TriggerEvents>(
tracing::Span::current().record("macro.event.type", decoded.event_type);
if let Some(posted) = &decoded.posted {
- process_message_event(trigger, publisher, channel_types, posted).await?;
+ process_message_event(
+ trigger,
+ publisher,
+ &readers.channel_types,
+ &readers.discussions,
+ posted,
+ )
+ .await?;
}
if let Some(assignment) = &decoded.assignment {
- process_task_assignment(trigger, publisher, messages, task_context, assignment)
- .await?;
+ process_task_assignment(
+ trigger,
+ publisher,
+ messages,
+ task_context,
+ &readers.people,
+ assignment,
+ )
+ .await?;
}
if let Some(added) = &decoded.project_task {
project_assignments.process(added).await?;
diff --git a/services/agent_trigger_service/Cargo.toml b/services/agent_trigger_service/Cargo.toml
index 6c5736333c..1f4958e1f2 100644
--- a/services/agent_trigger_service/Cargo.toml
+++ b/services/agent_trigger_service/Cargo.toml
@@ -14,6 +14,7 @@ roles_and_permissions = { path = "../../crates/roles_and_permissions", default-f
teams = { path = "../../crates/teams", default-features = false, features = ["outbound"] }
initiative = { path = "../../crates/initiative", default-features = false, features = ["postgres"] }
crm = { path = "../../crates/crm", default-features = false, features = ["lookup"] }
+call = { path = "../../crates/call", default-features = false, features = ["outbound"] }
agent_session = { path = "../../crates/agent_session" }
agent_trigger = { path = "../../crates/agent_trigger", features = ["outbound"] }
ai_usage = { path = "../../crates/ai_usage" }
diff --git a/services/agent_trigger_service/src/main.rs b/services/agent_trigger_service/src/main.rs
index d21eccf178..1200a88a35 100644
--- a/services/agent_trigger_service/src/main.rs
+++ b/services/agent_trigger_service/src/main.rs
@@ -7,6 +7,7 @@
mod config;
use agent_session::outbound::postgres::PgAgentSessionRepo;
+use agent_trigger::domain::context::{DiscussionReader, PeopleDirectory};
use agent_trigger::domain::processing::process_message_event;
use agent_trigger::domain::project_assignment::ProjectAssignmentService;
use agent_trigger::domain::service::AgentTriggerService;
@@ -16,7 +17,8 @@ use agent_trigger::domain::task_assignment::{
};
use agent_trigger::outbound::{
BotRepoAgentLookup, ChannelRepoTypeLookup, DssTaskAssignmentContext, FastModelTriggerJudge,
- LexicalExplicitReplyExtractor, MessageThreadHistory, VisionImageCaptioner,
+ LexicalExplicitReplyExtractor, MessageDiscussionReader, MessageThreadHistory, ParentNameReader,
+ PgPeopleDirectory, VisionImageCaptioner,
};
use anyhow::Context as _;
use bots::outbound::pg_bots_repo::PgBotsRepo;
@@ -143,16 +145,53 @@ async fn run() -> anyhow::Result<()> {
config.enable_ai_usage_enforcement,
config.ai_pricing(),
);
+ let documents = DocumentStorageServiceClient::new(
+ config.document_storage_service_auth_key.clone(),
+ DocumentStorageServiceUrl::new()?.to_string(),
+ );
let task_context = ProjectTaskAssignmentContext::new(
DssTaskAssignmentContext::new(
- DocumentStorageServiceClient::new(
- config.document_storage_service_auth_key.clone(),
- DocumentStorageServiceUrl::new()?.to_string(),
- ),
+ documents.clone(),
lexical.clone(),
+ PropertiesServiceImpl::new(
+ PropertiesPgRepo::new(pool.clone()),
+ Some(PermissionServiceImpl::new(
+ pool.clone(),
+ Arc::new(EntityAccessServiceImpl::new(PgAccessRepository::new(
+ pool.clone(),
+ ))),
+ )),
+ None::<SilentAssignmentNotifications>,
+ ),
),
SystemPropertiesServiceImpl::new(PgSystemPropertiesRepository::new(pool.clone())),
EntityAccessServiceImpl::new(PgAccessRepository::new(pool.clone())),
+ initiative::domain::lookup::InitiativeLookup::new(
+ initiative::outbound::PgInitiativeRepo::new(pool.clone()),
+ ),
+ );
+ let message_reader = Arc::new(messages::domain::service::MessageService::new(
+ PgMessageRepository::new(pool.clone())
+ .with_initiatives(initiative::domain::lookup::InitiativeLookup::new(
+ initiative::outbound::PgInitiativeRepo::new(pool.clone()),
+ ))
+ .with_crm(crm::outbound::lookup::PgCrmParentReader::new(pool.clone())),
+ messages::domain::ports::NoMessageEventPublisher,
+ ));
+ let people = PgPeopleDirectory::new(pool.clone(), PgBotsRepo::new(pool.clone()));
+ let discussions = MessageDiscussionReader::new(
+ message_reader.clone(),
+ PgPeopleDirectory::new(pool.clone(), PgBotsRepo::new(pool.clone())),
+ ParentNameReader::new(
+ PgChannelsRepo::new(pool.clone()),
+ documents,
+ initiative::domain::lookup::InitiativeLookup::new(
+ initiative::outbound::PgInitiativeRepo::new(pool.clone()),
+ ),
+ crm::outbound::lookup::PgCrmParentReader::new(pool.clone()),
+ call::outbound::pg_call_repo::PgCallRepo::new(pool.clone()),
+ ),
+ lexical.clone(),
);
let images = VisionImageCaptioner::new(
static_file::outbound::CdnStaticFileRepo::new(StaticFileServiceUrl::new()?.to_string()),
@@ -169,14 +208,7 @@ async fn run() -> anyhow::Result<()> {
LexicalExplicitReplyExtractor::new(lexical),
FastModelTriggerJudge::new(recorder, images),
MessageThreadHistory::new(
- std::sync::Arc::new(messages::domain::service::MessageService::new(
- PgMessageRepository::new(pool.clone())
- .with_initiatives(initiative::domain::lookup::InitiativeLookup::new(
- initiative::outbound::PgInitiativeRepo::new(pool.clone()),
- ))
- .with_crm(crm::outbound::lookup::PgCrmParentReader::new(pool.clone())),
- messages::domain::ports::NoMessageEventPublisher,
- )),
+ message_reader,
entity_access::domain::service::EntityAccessServiceImpl::new(
entity_access::outbound::PgAccessRepository::new(pool.clone()),
),
@@ -234,7 +266,11 @@ async fn run() -> anyhow::Result<()> {
consumer,
&trigger,
&publisher,
- &channel_types,
+ &ContextReaders {
+ channel_types,
+ discussions,
+ people,
+ },
&messages,
&task_context,
&project_assignments,
@@ -242,12 +278,19 @@ async fn run() -> anyhow::Result<()> {
.await
}
+/// What the trigger reads beside the post to describe the agents it calls.
+struct ContextReaders<Discussions, People> {
+ channel_types: ChannelTypes,
+ discussions: Discussions,
+ people: People,
+}
+
/// Read the trigger topic until shutdown, evaluating every committed post.
async fn consume<Events: TriggerEvents>(
consumer: KafkaConsumerAdapter<AgentTriggerConsumerGroup, ()>,
trigger: &Trigger,
publisher: &Publisher,
- channel_types: &ChannelTypes,
+ readers: &ContextReaders<impl DiscussionReader, impl PeopleDirectory>,
messages: &dyn MessageCommands,
task_context: &impl TaskAssignmentContext,
project_assignments: &ProjectAssignmentService<
@@ -304,10 +347,10 @@ async fn consume<Events: TriggerEvents>(
tracing::Span::current().record("macro.event.type", decoded.event_type);
if let Some(posted) = &decoded.posted {
- process_message_event(trigger, publisher, channel_types, posted).await?;
+ process_message_event(trigger, publisher, &readers.channel_types, &readers.discussions, posted).await?;
}
if let Some(assignment) = &decoded.assignment {
- process_task_assignment(trigger, publisher, messages, task_context, assignment).await?;
+ process_task_assignment(trigger, publisher, messages, task_context, &readers.people, assignment).await?;
}
if let Some(added) = &decoded.project_task {
project_assignments.process(added).await?;
diff --git a/services/lexical-service/src/endpoints/agent-context.ts b/services/lexical-service/src/endpoints/agent-context.ts
index 69392e0a84..ce94da5fdc 100644
--- a/services/lexical-service/src/endpoints/agent-context.ts
+++ b/services/lexical-service/src/endpoints/agent-context.ts
@@ -1,10 +1,17 @@
-import { composeAgentContextPrompt } from '@macro-inc/lexical-core/utils/agent-context';
+import {
+ composeAgentContextPrompt,
+ legacyConversationFieldsIn,
+ type TriggerContext,
+} 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';
+// LEGACY conversation schemas, through `replyTarget`. Remove once every caller
+// sends `trigger`.
+
const messageParent = z.object({
type: z.enum([
'channel',
@@ -73,24 +80,294 @@ const replyTarget = z.discriminatedUnion('kind', [
}),
]);
-const person = z.object({
+// End of the LEGACY conversation schemas.
+
+// The trigger: mirrors the Rust `TriggerContext` wire shape in
+// crates/trigger_context/src/lib.rs.
+
+const triggerPerson = z.object({
id: z.string().min(1),
name: z.string(),
+ email: z.string().optional(),
+});
+
+const triggerMessage = z.object({
+ id: z.string().min(1),
+ author: triggerPerson,
+ content: z.string(),
+ posted_at: z.string().min(1),
+});
+
+const triggerThread = z.object({
+ root_id: z.string().min(1),
+ messages: z.array(triggerMessage),
+ messages_omitted: z.boolean(),
});
-const agentContextRequest = z.object({
- promptMarkdown: z.string(),
- instructions: z.string().optional(),
- owner: person.optional(),
- sender: person.optional(),
- parent: messageParent.optional(),
- anchor: commentAnchor.optional(),
- replyTarget: replyTarget.optional(),
- promptMessageId: z.string().min(1).optional(),
- thread: contextThread.optional(),
- channel: z.array(contextThread).optional(),
+const triggerCommentAnchor = z.discriminatedUnion('type', [
+ z.object({
+ type: z.literal('spreadsheet'),
+ sheet_id: z.string().min(1),
+ sheet_name: z.string(),
+ range: z.string().min(1),
+ }),
+ z.object({
+ type: z.literal('mark'),
+ mark_id: z.string().min(1),
+ marked_text: z.string().optional(),
+ current: z
+ .object({ marked_text: z.string(), surrounding_text: z.string() })
+ .optional(),
+ }),
+ z.object({
+ type: z.literal('pdf_highlight'),
+ anchor_id: z.string().min(1),
+ marked_text: z.string().optional(),
+ }),
+ z.object({
+ type: z.literal('pdf_pin'),
+ anchor_id: z.string().min(1),
+ }),
+]);
+
+const namedSurface = <Type extends string>(type: Type) =>
+ z.object({ type: z.literal(type), id: z.string().min(1), name: z.string() });
+
+const discussionSurface = z.discriminatedUnion('type', [
+ z.object({
+ type: z.literal('channel'),
+ id: z.string().min(1),
+ name: z.string().optional(),
+ channel_type: z.enum(['public', 'private', 'direct_message', 'team']),
+ }),
+ z.object({
+ type: z.literal('document_comment'),
+ id: z.string().min(1),
+ name: z.string(),
+ anchor: triggerCommentAnchor.optional(),
+ }),
+ namedSurface('project_comment'),
+ namedSurface('crm_company_comment'),
+ namedSurface('crm_contact_comment'),
+ z.object({
+ type: z.literal('call_chat'),
+ id: z.string().min(1),
+ title: z.string(),
+ }),
+]);
+
+const triggerReplyTarget = z.discriminatedUnion('kind', [
+ z.object({
+ kind: z.literal('quote'),
+ message_id: z.string().min(1),
+ thread_id: z.string().min(1),
+ preview: z.string(),
+ message: triggerMessage.optional(),
+ }),
+ z.object({
+ kind: z.literal('thread'),
+ root_id: z.string().min(1),
+ }),
+ z.object({
+ kind: z.literal('none'),
+ }),
+]);
+
+const discussionContext = z.object({
+ surface: discussionSurface,
+ prompt_message_id: z.string().min(1),
+ sender: triggerPerson,
+ reply_target: triggerReplyTarget,
+ thread: triggerThread.optional(),
+ channel: z.array(triggerThread).optional(),
+});
+
+const projectRef = z.object({
+ id: z.string().min(1),
+ name: z.string(),
+});
+
+const taskSnapshot = z.object({
+ id: z.string().min(1),
+ title: z.string(),
+ markdown: z.string(),
+ status: z.string().optional(),
+ priority: z.string().optional(),
+ due: z.string().optional(),
+ assignees: z.array(triggerPerson).optional(),
+ project: projectRef.optional(),
+});
+
+const documentSnapshot = z.object({
+ id: z.string().min(1),
+ name: z.string(),
+ file_type: z.string(),
+ text: z.string().optional(),
});
+const emailSnapshot = z.object({
+ thread_id: z.string().min(1),
+ subject: z.string(),
+ from: z.string(),
+ to: z.array(z.string()),
+ received_at: z.string().min(1),
+ body: z.string(),
+});
+
+const routineEvent = z.discriminatedUnion('event', [
+ z.object({
+ event: z.literal('document_created'),
+ document: documentSnapshot,
+ }),
+ z.object({
+ event: z.literal('document_updated'),
+ document: documentSnapshot,
+ }),
+ z.object({
+ event: z.literal('document_deleted'),
+ id: z.string().min(1),
+ name: z.string(),
+ }),
+ z.object({ event: z.literal('task_created'), task: taskSnapshot }),
+ z.object({ event: z.literal('task_status_changed'), task: taskSnapshot }),
+ z.object({ event: z.literal('task_priority_changed'), task: taskSnapshot }),
+ z.object({ event: z.literal('task_property_changed'), task: taskSnapshot }),
+ z.object({ event: z.literal('email_received'), email: emailSnapshot }),
+ z.object({
+ event: z.literal('channel_created'),
+ id: z.string().min(1),
+ name: z.string().optional(),
+ }),
+ z.object({
+ event: z.literal('channel_message_posted'),
+ discussion: discussionContext,
+ }),
+ z.object({
+ event: z.literal('channel_mentioned'),
+ discussion: discussionContext,
+ }),
+ z.object({
+ event: z.literal('channel_message_patched'),
+ discussion: discussionContext,
+ }),
+ z.object({
+ event: z.literal('channel_message_attachment_created'),
+ discussion: discussionContext,
+ entity_type: z.string().min(1),
+ entity_id: z.string().min(1),
+ }),
+]);
+
+const routineFiring = z.discriminatedUnion('type', [
+ z.object({
+ type: z.literal('scheduled'),
+ scheduled_for: z.string().min(1),
+ schedule: z.string(),
+ }),
+ z.object({
+ type: z.literal('manual'),
+ requested_at: z.string().min(1),
+ }),
+ z.object({
+ type: z.literal('event'),
+ event: routineEvent,
+ conditions: z.array(z.string()).optional(),
+ }),
+]);
+
+const routineTrigger = z.discriminatedUnion('type', [
+ z.object({
+ type: z.literal('schedule'),
+ cron: z.string().min(1),
+ timezone: z.string().min(1),
+ }),
+ z.object({
+ type: z.literal('events'),
+ events: z.array(z.string().min(1)),
+ entity_ids: z.array(z.string().min(1)).optional(),
+ condition: z.string().optional(),
+ }),
+]);
+
+const triggerContextSchema = z.discriminatedUnion('kind', [
+ discussionContext.extend({ kind: z.literal('mentioned') }),
+ z.object({
+ kind: z.literal('follow_up'),
+ addressed_by: z.enum(['mention', 'explicit_reply', 'inferred']),
+ discussion: discussionContext,
+ }),
+ z.object({
+ kind: z.literal('task_assigned'),
+ task: taskSnapshot,
+ assigned_by: triggerPerson,
+ assigned_at: z.string().min(1),
+ discussion_id: z.string().min(1),
+ }),
+ z.object({
+ kind: z.literal('requested'),
+ requested_by: triggerPerson,
+ requested_at: z.string().min(1),
+ repo_url: z.string().optional(),
+ }),
+ z.object({
+ kind: z.literal('dispatched'),
+ dispatched_by: triggerPerson,
+ dispatched_at: z.string().min(1),
+ // Rust serializes an absent bot as null.
+ from_bot: z.string().nullish(),
+ from_session: z.string().optional(),
+ repo_url: z.string().optional(),
+ }),
+ z.object({
+ kind: z.literal('routine'),
+ routine_id: z.string().min(1),
+ name: z.string(),
+ owner: triggerPerson,
+ instructions: z.string(),
+ triggers: z.array(routineTrigger),
+ firing: routineFiring,
+ }),
+]);
+
+/**
+ * The trigger schema, typed as the lexical-core contract. This service builds
+ * without strictNullChecks, under which zod infers every required union field
+ * (surface, reply_target, firing, event) as optional; the runtime schema
+ * still requires them.
+ */
+export const triggerContext: z.ZodType<TriggerContext> =
+ triggerContextSchema as z.ZodType<TriggerContext>;
+
+const person = z.object({
+ id: z.string().min(1),
+ name: z.string(),
+});
+
+export const agentContextRequest = z
+ .object({
+ promptMarkdown: z.string(),
+ instructions: z.string().optional(),
+ owner: person.optional(),
+ sender: person.optional(),
+ trigger: triggerContext.optional(),
+ // LEGACY conversation fields; remove once every caller sends `trigger`.
+ parent: messageParent.optional(),
+ anchor: commentAnchor.optional(),
+ replyTarget: replyTarget.optional(),
+ promptMessageId: z.string().min(1).optional(),
+ thread: contextThread.optional(),
+ channel: z.array(contextThread).optional(),
+ })
+ .refine(
+ (request) =>
+ request.trigger === undefined ||
+ legacyConversationFieldsIn(request).length === 0,
+ {
+ message:
+ 'trigger cannot be combined with parent, anchor, replyTarget, promptMessageId, thread, or channel',
+ }
+ );
+
const agentContextResponse = z.object({
markdown: z.string(),
});
@@ -99,7 +376,7 @@ export class AgentContextEndpoint extends OpenAPIRoute {
schema = {
summary: 'Compose an agent prompt with conversation context',
description:
- 'Builds internal markdown naming the session owner and the prompt sender, and containing trusted session instructions and the conversation the prompt was posted in - its thread, the channel around it, what it replies to, and the comment anchor it sits on - followed by the user prompt.',
+ 'Builds internal markdown naming the session owner and the prompt sender, and containing trusted session instructions and the trigger that called the agent - a mention or follow-up with its discussion, a task assignment, a composer request, a dispatch, or a routine firing - followed by the user prompt. The legacy conversation fields (parent, anchor, replyTarget, promptMessageId, thread, channel) are still accepted, but not together with trigger.',
request: {
body: {
content: {
@@ -123,8 +400,10 @@ export class AgentContextEndpoint extends OpenAPIRoute {
};
async handle(c: Context) {
+ // Outside the try: chanfana answers a request that fails the schema with
+ // 400, where handleEndpointError would turn it into a 500.
+ const { body } = await this.getValidatedData<typeof this.schema>();
try {
- const { body } = await this.getValidatedData<typeof this.schema>();
const markdown = composeAgentContextPrompt(body);
return c.json({ markdown });
} catch (error) {
diff --git a/services/lexical-service/test/agent-context.test.ts b/services/lexical-service/test/agent-context.test.ts
new file mode 100644
index 0000000000..28c2e629ed
--- /dev/null
+++ b/services/lexical-service/test/agent-context.test.ts
@@ -0,0 +1,160 @@
+import { describe, expect, it } from 'bun:test';
+import { fromHono } from 'chanfana';
+import { Hono } from 'hono';
+import {
+ AgentContextEndpoint,
+ agentContextRequest,
+} from '../src/endpoints/agent-context';
+
+// The wire examples in crates/trigger_context/src/test.rs.
+const followUpWire = {
+ kind: 'follow_up',
+ addressed_by: 'explicit_reply',
+ discussion: {
+ surface: {
+ type: 'channel',
+ id: '00000000-0000-0000-0000-0000000000c1',
+ name: 'eng',
+ channel_type: 'public',
+ },
+ prompt_message_id: '00000000-0000-0000-0000-000000000003',
+ sender: {
+ id: 'macro|[email protected]',
+ name: 'Julia',
+ email: '[email protected]',
+ },
+ reply_target: {
+ kind: 'quote',
+ message_id: '00000000-0000-0000-0000-000000000002',
+ thread_id: '00000000-0000-0000-0000-000000000001',
+ preview: 'The popover scrolls the page',
+ },
+ thread: {
+ root_id: '00000000-0000-0000-0000-000000000001',
+ messages: [
+ {
+ id: '00000000-0000-0000-0000-000000000003',
+ author: {
+ id: 'macro|[email protected]',
+ name: 'Julia',
+ email: '[email protected]',
+ },
+ content: 'please fix',
+ posted_at: '2026-10-08T14:02:00Z',
+ },
+ ],
+ messages_omitted: false,
+ },
+ },
+};
+
+const taskAssignedWire = {
+ kind: 'task_assigned',
+ task: {
+ id: 'task-1',
+ title: 'Fix calendar popover scroll',
+ markdown: 'The popover scrolls the page behind it.',
+ status: 'Todo',
+ priority: 'High',
+ due: '2026-10-10T00:00:00Z',
+ assignees: [
+ {
+ id: 'bot|00000000-0000-0000-0000-00000000c5c5',
+ name: 'Cursor',
+ },
+ ],
+ project: {
+ id: '00000000-0000-0000-0000-0000000000a1',
+ name: 'Calendar polish',
+ },
+ },
+ assigned_by: {
+ id: 'macro|[email protected]',
+ name: 'Julia',
+ email: '[email protected]',
+ },
+ assigned_at: '2026-10-08T14:02:00Z',
+ discussion_id: '00000000-0000-0000-0000-0000000000d1',
+};
+
+// Rust serializes DispatchedContext.from_bot as null when absent.
+const dispatchedWire = {
+ kind: 'dispatched',
+ dispatched_by: { id: 'macro|[email protected]', name: 'Julia' },
+ dispatched_at: '2026-10-08T14:02:00Z',
+ from_bot: null,
+};
+
+function endpoint() {
+ const app = new Hono();
+ fromHono(app).post('/agent-context', AgentContextEndpoint);
+ return (body: unknown) =>
+ app.request('/agent-context', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify(body),
+ });
+}
+
+describe('agent-context request schema', () => {
+ it('accepts each Rust wire example as the trigger, unchanged', () => {
+ for (const trigger of [followUpWire, taskAssignedWire, dispatchedWire]) {
+ const parsed = agentContextRequest.safeParse({
+ promptMarkdown: 'please fix',
+ trigger,
+ });
+ expect(parsed.success).toBe(true);
+ expect(parsed.data?.trigger).toEqual(trigger);
+ }
+ });
+
+ it('still accepts the legacy conversation fields on their own', () => {
+ const parsed = agentContextRequest.safeParse({
+ promptMarkdown: 'please fix',
+ parent: { type: 'channel', id: 'c1' },
+ replyTarget: { kind: 'none' },
+ promptMessageId: 'p',
+ });
+ expect(parsed.success).toBe(true);
+ });
+
+ it('rejects a trigger beside any legacy conversation field', () => {
+ for (const legacy of [
+ { parent: { type: 'channel', id: 'c1' } },
+ { promptMessageId: 'p' },
+ { replyTarget: { kind: 'none' } },
+ { anchor: { markId: 'mark-1' } },
+ { thread: { rootId: 'a', messages: [], messagesOmitted: false } },
+ { channel: [] },
+ ]) {
+ const parsed = agentContextRequest.safeParse({
+ promptMarkdown: 'please fix',
+ trigger: followUpWire,
+ ...legacy,
+ });
+ expect(parsed.success).toBe(false);
+ }
+ });
+});
+
+describe('POST /agent-context', () => {
+ it('composes a prompt from each Rust wire example', async () => {
+ const post = endpoint();
+ for (const trigger of [followUpWire, taskAssignedWire, dispatchedWire]) {
+ const response = await post({ promptMarkdown: 'please fix', trigger });
+ expect(response.status).toBe(200);
+ const { markdown } = (await response.json()) as { markdown: string };
+ expect(markdown).toStartWith('<m-agent-context>');
+ expect(markdown).toContain(`trigger kind=\\"${trigger.kind}\\"`);
+ }
+ });
+
+ it('answers 400 to a trigger mixed with legacy fields', async () => {
+ const response = await endpoint()({
+ promptMarkdown: 'please fix',
+ trigger: taskAssignedWire,
+ parent: { type: 'channel', id: 'c1' },
+ });
+ expect(response.status).toBe(400);
+ });
+});
diff --git a/services/scheduled_action/Cargo.toml b/services/scheduled_action/Cargo.toml
index cbe2f1088e..47af6b0abb 100644
--- a/services/scheduled_action/Cargo.toml
+++ b/services/scheduled_action/Cargo.toml
@@ -51,6 +51,7 @@ messages = { path = "../../crates/messages", features = ["broker", "outbound"] }
models_properties = { path = "../../crates/models_properties" }
properties = { path = "../../crates/properties", default-features = false, features = ["outbound"] }
system_properties = { path = "../../crates/system_properties" }
+trigger_context = { path = "../../crates/trigger_context" }
rdkafka = { workspace = true }
reqwest = { workspace = true }
rootcause = { workspace = true }
diff --git a/services/scheduled_action/src/bins/service.rs b/services/scheduled_action/src/bins/service.rs
index 4cd89d70a8..1864223d31 100644
--- a/services/scheduled_action/src/bins/service.rs
+++ b/services/scheduled_action/src/bins/service.rs
@@ -104,7 +104,16 @@ async fn main() -> Result<()> {
AgentHarnessServiceUrl::new()?.as_ref(),
&config.internal_api_key,
)?);
- let runner = Arc::new(TargetRunner::new(Arc::clone(&sessions)));
+ let event_content = Arc::new(event_content(
+ &db,
+ &registrar,
+ Arc::clone(&access),
+ &config,
+ )?);
+ let runner = Arc::new(TargetRunner::new(
+ Arc::clone(&sessions),
+ Arc::clone(&event_content),
+ ));
let dispatcher_executor = InProcessExecutor::new(
Arc::clone(&repo),
runner,
@@ -155,12 +164,7 @@ async fn main() -> Result<()> {
let conditions_enabled = typesafe.is_some();
let conditions = match typesafe {
Some(provider) => Some(ConditionGate::new(
- Arc::new(event_content(
- &db,
- &registrar,
- Arc::clone(&access),
- &config,
- )?),
+ event_content,
// Condition evaluation is the only model work this process meters
// (agent targets are funded by the harness). Counted usage asks the
// authentication service to settle the payer, as every other host does.
@@ -261,13 +265,18 @@ async fn main() -> Result<()> {
}
/// Read-only views of the domains whose events can trigger a routine, for
-/// condition checks. None of these reads notify, publish or enqueue.
+/// condition checks and the agent's account of the event. None of these reads
+/// notify, publish or enqueue.
fn event_content(
db: &sqlx::PgPool,
registrar: &OwnedEntityRegistrar<PgBotsRepo>,
access: Arc<EntityAccessServiceImpl<PgAccessRepository>>,
config: &Config,
-) -> Result<impl scheduled_action::domain::event_runs::condition::EventContentReader + use<>> {
+) -> Result<
+ impl scheduled_action::domain::event_runs::condition::EventContentReader
+ + scheduled_action::domain::ports::RoutineEventReader
+ + use<>,
+> {
Ok(EventContentAdapter::new(
email::domain::service::EmailServiceImpl::new(
email::outbound::EmailPgRepo::new(db.clone()),
@@ -301,7 +310,7 @@ fn event_content(
))
}
-/// Condition checks only read properties; they never assign tasks.
+/// Event content only reads properties; it never assigns tasks.
struct NoTaskNotifications;
impl properties::NotificationService for NoTaskNotifications {
diff --git a/services/scheduled_action/src/domain/execution.rs b/services/scheduled_action/src/domain/execution.rs
index 4a4a40739c..e42b7fdba3 100644
--- a/services/scheduled_action/src/domain/execution.rs
+++ b/services/scheduled_action/src/domain/execution.rs
@@ -18,7 +18,8 @@ use crate::domain::models::{
MAX_ACTION_TIME, ResolvedTaskTarget, ScheduledAction, ScheduledActionUpdate,
};
use crate::domain::ports::{
- ScheduledActionExecutor, ScheduledActionLiveUpdate, ScheduledActionRepo, ScheduledAgentRunner,
+ RoutineRun, ScheduledActionExecutor, ScheduledActionLiveUpdate, ScheduledActionRepo,
+ ScheduledAgentRunner,
};
/// Run identity allocated before any awaited preparation. Runners can cancel
@@ -234,6 +235,16 @@ where
let id = action.id.context("persisted action required")?;
let start_time = Utc::now();
let deadline = start_time + MAX_ACTION_TIME;
+ // The claim is fenced to `next_run_at`, so a run started once it is
+ // due consumes that firing, whoever started it.
+ let firing = match action.next_run_at {
+ Some(scheduled_for) if scheduled_for <= start_time => {
+ RoutineRun::Scheduled { scheduled_for }
+ }
+ _ => RoutineRun::Manual {
+ requested_at: start_time,
+ },
+ };
// Track preparation too: cancellation of an HTTP request must not leak
// a claim or abandon a run after creating its resource.
@@ -266,7 +277,7 @@ where
resource: Some(resource),
}));
}
- executor.runner.run(&action, &handle, None).await
+ executor.runner.run(&action, &handle, firing).await
})
.await;
if let Err(error) = &result {
@@ -338,7 +349,7 @@ where
let result = bounded(deadline, shutdown, async {
self.prepare(&run.action, &mut handle).await?;
self.runner
- .run(&run.action, &handle, Some(&run.run.pending.event))
+ .run(&run.action, &handle, RoutineRun::Event(&run.run))
.await
})
.await;
diff --git a/services/scheduled_action/src/domain/execution/test.rs b/services/scheduled_action/src/domain/execution/test.rs
index 91a8f7a52f..9d7535f6e1 100644
--- a/services/scheduled_action/src/domain/execution/test.rs
+++ b/services/scheduled_action/src/domain/execution/test.rs
@@ -291,11 +291,11 @@ impl ScheduledAgentRunner for Runner {
&self,
_: &ScheduledAction,
_: &ExecutionHandle,
- event: Option<&EventReference>,
+ firing: RoutineRun<'_>,
) -> Result<()> {
let _guard = self.dropped.clone().drop_guard();
self.calls.fetch_add(1, Ordering::SeqCst);
- self.contexts.lock().unwrap().push(event.cloned());
+ self.contexts.lock().unwrap().push(firing.event().cloned());
self.finish.cancelled().await;
anyhow::ensure!(!self.fail_run, "agent stream failed");
Ok(())
diff --git a/services/scheduled_action/src/domain/ports.rs b/services/scheduled_action/src/domain/ports.rs
index 9339ee1a8f..c2eb03ae90 100644
--- a/services/scheduled_action/src/domain/ports.rs
+++ b/services/scheduled_action/src/domain/ports.rs
@@ -1,4 +1,4 @@
-use super::event_runs::{ClaimToken, ConfigurationRevision};
+use super::event_runs::{AuthorizedEventRun, ClaimToken, ConfigurationRevision};
use super::event_trigger::EventReference;
use super::execution::ExecutionHandle;
use super::models::{
@@ -16,6 +16,7 @@ use macro_uuid::Uuid;
use model_owner::{CreationPrincipal, Owner};
use rootcause::Report;
use tokio::sync::mpsc::{Receiver, Sender};
+use trigger_context::RoutineEvent;
/// Validate configuration syntax and authorize its target before persistence.
pub trait TaskTargetValidator: Send + Sync + 'static {
@@ -200,6 +201,36 @@ pub trait ScheduledActionExecutor {
) -> impl Future<Output = Result<InProgressExecution>> + Send;
}
+/// What started a routine run.
+#[derive(Clone, Copy)]
+pub enum RoutineRun<'a> {
+ /// One of its schedules came due.
+ Scheduled { scheduled_for: DateTime<Utc> },
+ /// Its owner started it by hand.
+ Manual { requested_at: DateTime<Utc> },
+ /// An event it watches happened, and its owner may read it.
+ Event(&'a AuthorizedEventRun),
+}
+
+impl RoutineRun<'_> {
+ pub fn event(&self) -> Option<&EventReference> {
+ match self {
+ Self::Event(run) => Some(&run.pending.event),
+ Self::Scheduled { .. } | Self::Manual { .. } => None,
+ }
+ }
+}
+
+/// Reads the event a routine fired on, as the routine owner, through the
+/// run's access receipt. Content that is gone or unreadable is `Err`.
+pub trait RoutineEventReader: Send + Sync + 'static {
+ fn read_event(
+ &self,
+ owner: &MacroUserIdStr<'static>,
+ run: &AuthorizedEventRun,
+ ) -> impl Future<Output = Result<RoutineEvent, Report>> + Send;
+}
+
/// Execution dependencies, separate from claim/history orchestration.
pub trait ScheduledAgentRunner: Send + Sync + 'static {
/// Prepare without starting the task. Remote runners must use the handle's
@@ -217,7 +248,7 @@ pub trait ScheduledAgentRunner: Send + Sync + 'static {
&self,
action: &ScheduledAction,
handle: &ExecutionHandle,
- event: Option<&EventReference>,
+ firing: RoutineRun<'_>,
) -> impl Future<Output = Result<()>> + Send;
/// Best-effort cleanup, including partially prepared sessions. Must be safe
diff --git a/services/scheduled_action/src/domain/service/test.rs b/services/scheduled_action/src/domain/service/test.rs
index 4b4c77ff76..c84147c581 100644
--- a/services/scheduled_action/src/domain/service/test.rs
+++ b/services/scheduled_action/src/domain/service/test.rs
@@ -519,7 +519,7 @@ async fn preparation_reauthorizes_previously_saved_selection_after_deletion_or_r
.unwrap();
assert!(sessions.preparations.lock().unwrap().is_empty());
*sessions.error.lock().unwrap() = Some(denial);
- let runner = TargetRunner::new(sessions.clone());
+ let runner = TargetRunner::new(sessions.clone(), Arc::new(UnreadEvents));
let mut handle = ExecutionHandle::default();
let error = runner.prepare(&created, &mut handle).await.unwrap_err();
assert_eq!(error.downcast_ref(), Some(&denial));
@@ -528,6 +528,19 @@ async fn preparation_reauthorizes_previously_saved_selection_after_deletion_or_r
}
}
+/// Preparation never reads the triggering event.
+struct UnreadEvents;
+
+impl crate::domain::ports::RoutineEventReader for UnreadEvents {
+ async fn read_event(
+ &self,
+ _: &MacroUserIdStr<'static>,
+ _: &crate::domain::event_runs::AuthorizedEventRun,
+ ) -> std::result::Result<trigger_context::RoutineEvent, rootcause::Report> {
+ panic!("preparation must not read the triggering event")
+ }
+}
+
fn assert_policy<T: std::fmt::Debug>(result: Result<T>, expected: ActionPolicyError) {
assert_eq!(
result
diff --git a/services/scheduled_action/src/domain/target_runner.rs b/services/scheduled_action/src/domain/target_runner.rs
index b0af52acda..315f5aa06c 100644
--- a/services/scheduled_action/src/domain/target_runner.rs
+++ b/services/scheduled_action/src/domain/target_runner.rs
@@ -12,12 +12,19 @@ use agent_session::domain::{
};
use anyhow::{Context, Result};
use bot_id::BotId;
+use chrono_tz::Tz;
+use macro_user_id::user_id::MacroUserIdStr;
+use trigger_context::{
+ ContextPerson, RoutineContext, RoutineFiring, RoutineTrigger as ContextTrigger, TriggerContext,
+};
use super::{
- event_trigger::EventReference,
+ event_trigger::{
+ ActionTrigger, ConditionRequirement, EventFilters, EventReference, RoutineTrigger,
+ },
execution::ExecutionHandle,
- models::{AgentTask, ExecutionResource, ExecutionResourceType, ScheduledAction},
- ports::ScheduledAgentRunner,
+ models::{AgentTask, ExecutionResource, ExecutionResourceType, Schedule, ScheduledAction},
+ ports::{RoutineEventReader, RoutineRun, ScheduledAgentRunner},
};
const INITIAL_POLL_DELAY: Duration = Duration::from_secs(1);
@@ -29,17 +36,20 @@ const SCHEDULED_GUIDANCE: &str = "You are executing a user routine that has alre
/// Executes every routine through the agent-session domain.
/// The shared executor bounds preparation and polling by its original deadline,
/// drops in-flight reads on timeout/shutdown, and invokes `cancel` separately.
-pub struct TargetRunner<Sessions> {
+pub struct TargetRunner<Sessions, Events> {
sessions: Arc<Sessions>,
+ events: Arc<Events>,
}
-impl<Sessions> TargetRunner<Sessions> {
- pub fn new(sessions: Arc<Sessions>) -> Self {
- Self { sessions }
+impl<Sessions, Events> TargetRunner<Sessions, Events> {
+ pub fn new(sessions: Arc<Sessions>, events: Arc<Events>) -> Self {
+ Self { sessions, events }
}
}
-impl<Sessions: RoutineSessions> ScheduledAgentRunner for TargetRunner<Sessions> {
+impl<Sessions: RoutineSessions, Events: RoutineEventReader> ScheduledAgentRunner
+ for TargetRunner<Sessions, Events>
+{
async fn prepare(&self, action: &ScheduledAction, handle: &mut ExecutionHandle) -> Result<()> {
let task = task(action)?;
let (bot_id, model) = task.resolve_target()?.session_target();
@@ -93,7 +103,7 @@ impl<Sessions: RoutineSessions> ScheduledAgentRunner for TargetRunner<Sessions>
&self,
action: &ScheduledAction,
handle: &ExecutionHandle,
- event: Option<&EventReference>,
+ firing: RoutineRun<'_>,
) -> Result<()> {
let task = task(action)?;
let (bot_id, _) = task.resolve_target()?.session_target();
@@ -107,11 +117,13 @@ impl<Sessions: RoutineSessions> ScheduledAgentRunner for TargetRunner<Sessions>
"expected prepared agent session"
);
let identity = session_action(action, handle, bot_id)?;
+ let context = self.context(action, &task, &identity.owner, firing).await?;
let accepted = self
.sessions
.prompt(PromptRoutineSession {
action: identity.clone(),
- prompt: first_prompt(&task, event)?,
+ prompt: first_prompt(&task, context.as_ref(), firing.event())?,
+ context,
})
.await?;
if accepted.action_id != identity.action_id {
@@ -130,7 +142,51 @@ impl<Sessions: RoutineSessions> ScheduledAgentRunner for TargetRunner<Sessions>
}
}
-impl<Sessions: RoutineSessions> TargetRunner<Sessions> {
+impl<Sessions: RoutineSessions, Events: RoutineEventReader> TargetRunner<Sessions, Events> {
+ /// None when the triggering event could not be read; the run goes ahead
+ /// with the event's ids in the prompt instead.
+ async fn context(
+ &self,
+ action: &ScheduledAction,
+ task: &AgentTask,
+ owner: &MacroUserIdStr<'static>,
+ firing: RoutineRun<'_>,
+ ) -> Result<Option<TriggerContext>> {
+ let firing = match firing {
+ RoutineRun::Scheduled { scheduled_for } => RoutineFiring::Scheduled {
+ scheduled_for,
+ schedule: schedule(&action.trigger),
+ },
+ RoutineRun::Manual { requested_at } => RoutineFiring::Manual { requested_at },
+ RoutineRun::Event(run) => match self.events.read_event(owner, run).await {
+ Ok(event) => RoutineFiring::Event {
+ event: Box::new(event),
+ conditions: conditions(&action.trigger, &run.pending.event),
+ },
+ Err(error) => {
+ tracing::warn!(
+ error = ?error,
+ action_id = ?action.id,
+ "routine event unreadable; prompting with its ids"
+ );
+ return Ok(None);
+ }
+ },
+ };
+ Ok(Some(TriggerContext::Routine(RoutineContext {
+ routine_id: action.id.context("persisted action required")?,
+ name: action.name.clone(),
+ owner: ContextPerson {
+ id: owner.as_ref().to_owned(),
+ name: owner.email_str().to_owned(),
+ email: Some(owner.email_str().to_owned()),
+ },
+ instructions: task.prompt.clone(),
+ triggers: triggers(&action.trigger),
+ firing,
+ })))
+ }
+
async fn await_completion(&self, identity: RoutineSessionAction) -> Result<()> {
let mut delay = INITIAL_POLL_DELAY;
let mut failures = 0;
@@ -190,7 +246,96 @@ fn retain_resource(handle: &mut ExecutionHandle) {
});
}
-fn first_prompt(task: &AgentTask, event: Option<&EventReference>) -> Result<String> {
+/// Every schedule the routine states, since any of them may have come due.
+fn schedule(trigger: &ActionTrigger) -> String {
+ let cron =
+ |schedule: &Schedule, timezone: &Tz| format!("cron `{}` in {timezone}", schedule.as_str());
+ match trigger {
+ ActionTrigger::Cron { schedule, timezone } => cron(schedule, timezone),
+ ActionTrigger::Multiple { triggers } => triggers
+ .as_slice()
+ .iter()
+ .filter_map(|trigger| match trigger {
+ RoutineTrigger::Cron { schedule, timezone } => Some(cron(schedule, timezone)),
+ RoutineTrigger::Events { .. } => None,
+ })
+ .collect::<Vec<_>>()
+ .join("; "),
+ ActionTrigger::Events { .. } => String::new(),
+ }
+}
+
+/// The routine's triggers as the agent reads them: one entry per schedule and
+/// per event filter.
+fn triggers(trigger: &ActionTrigger) -> Vec<ContextTrigger> {
+ let schedule = |schedule: &Schedule, timezone: &Tz| ContextTrigger::Schedule {
+ cron: schedule.as_str().to_owned(),
+ timezone: timezone.name().to_owned(),
+ };
+ let mut triggers: Vec<ContextTrigger> = match trigger {
+ ActionTrigger::Cron {
+ schedule: cron,
+ timezone,
+ } => vec![schedule(cron, timezone)],
+ ActionTrigger::Multiple { triggers } => triggers
+ .as_slice()
+ .iter()
+ .filter_map(|trigger| match trigger {
+ RoutineTrigger::Cron {
+ schedule: cron,
+ timezone,
+ } => Some(schedule(cron, timezone)),
+ RoutineTrigger::Events { .. } => None,
+ })
+ .collect(),
+ ActionTrigger::Events { .. } => Vec::new(),
+ };
+ triggers.extend(
+ trigger
+ .event_filters()
+ .into_iter()
+ .flat_map(EventFilters::as_slice)
+ .map(|filter| ContextTrigger::Events {
+ events: filter
+ .events()
+ .iter()
+ .map(|event| event.as_str().to_owned())
+ .collect(),
+ entity_ids: filter.ids().map(<[_]>::to_vec).unwrap_or_default(),
+ condition: filter
+ .condition()
+ .map(|condition| condition.as_str().to_owned()),
+ }),
+ );
+ triggers
+}
+
+/// The questions the event was checked against before the run started.
+fn conditions(trigger: &ActionTrigger, event: &EventReference) -> Vec<String> {
+ match trigger
+ .event_filters()
+ .map(|filters| filters.condition_requirement(event))
+ {
+ Some(ConditionRequirement::AnyOf(conditions)) => conditions
+ .iter()
+ .map(|condition| condition.as_str().to_owned())
+ .collect(),
+ Some(ConditionRequirement::Unconditional) | None => Vec::new(),
+ }
+}
+
+/// The routine's instructions travel in the context when there is one.
+fn first_prompt(
+ task: &AgentTask,
+ context: Option<&TriggerContext>,
+ event: Option<&EventReference>,
+) -> Result<String> {
+ if context.is_some() {
+ return Ok(format!(
+ "{SCHEDULED_GUIDANCE}\n\nUser task:\n{}",
+ task.user_prompt
+ ));
+ }
let mut prompt = format!(
"{SCHEDULED_GUIDANCE}\n\nRoutine instructions:\n{}\n\nUser task:\n{}",
task.prompt, task.user_prompt
diff --git a/services/scheduled_action/src/domain/target_runner/test.rs b/services/scheduled_action/src/domain/target_runner/test.rs
index 4f8340b342..4fac214eae 100644
--- a/services/scheduled_action/src/domain/target_runner/test.rs
+++ b/services/scheduled_action/src/domain/target_runner/test.rs
@@ -3,7 +3,7 @@ use agent_session::domain::routines::{
PreparedRoutineSession, RoutineFailureReason, RoutinePendingReason, RoutinePromptAccepted,
ValidatedRoutineSession,
};
-use chrono::Utc;
+use chrono::{TimeZone, Utc};
use macro_user_id::user_id::MacroUserIdStr;
use macro_uuid::generate_uuid_v7;
use model_owner::Owner;
@@ -20,10 +20,15 @@ use crate::domain::{
models::{ActionExecutionRecord, ActionKind, ExecutionResult, ScheduledActionUpdate},
ports::{ScheduledActionLiveUpdate, ScheduledActionRepo},
};
-use entity_access::domain::models::{EntityAccessReceipt, ViewAccessLevel};
+use entity_access::domain::models::{EntityAccessReceipt, ViewAccessLevel, ViewOnly};
use macro_uuid::Uuid;
use model_entity::EntityType;
+use rootcause::Report;
use tokio_util::{sync::CancellationToken, task::TaskTracker};
+use trigger_context::{
+ ContextPerson, RoutineContext, RoutineEvent, RoutineFiring,
+ RoutineTrigger as ContextRoutineTrigger, TaskSnapshot, TriggerContext,
+};
const USER: &str = "macro|[email protected]";
@@ -211,16 +216,52 @@ fn action() -> ScheduledAction {
}
}
-fn event() -> EventReference {
- serde_json::from_value(json!({
+fn event() -> AuthorizedEventRun {
+ let event: EventReference = serde_json::from_value(json!({
"event_id":generate_uuid_v7(), "event_name":"channel.message_posted",
"entity_id":generate_uuid_v7(), "message_id":generate_uuid_v7(),
}))
- .unwrap()
+ .unwrap();
+ AuthorizedEventRun {
+ access: EventAccessCapability::Channel(
+ EntityAccessReceipt::<ViewOnly>::dangerously_assert_authenticated_user(
+ MacroUserIdStr::parse_from_str(USER).unwrap(),
+ &event.entity_id().to_string(),
+ EntityType::Channel,
+ ),
+ ),
+ pending: PendingEventRun {
+ action_id: generate_uuid_v7(),
+ revision: ConfigurationRevision::INITIAL,
+ event,
+ admitted_at: Utc::now(),
+ },
+ }
}
-fn runner(sessions: Sessions) -> TargetRunner<Sessions> {
- TargetRunner::new(Arc::new(sessions))
+fn manual() -> RoutineRun<'static> {
+ RoutineRun::Manual {
+ requested_at: Utc::now(),
+ }
+}
+
+/// Supplies one event, or finds every event unreadable.
+struct Events(Option<RoutineEvent>);
+
+impl RoutineEventReader for Events {
+ async fn read_event(
+ &self,
+ _: &MacroUserIdStr<'static>,
+ _: &AuthorizedEventRun,
+ ) -> std::result::Result<RoutineEvent, Report> {
+ self.0
+ .clone()
+ .ok_or_else(|| rootcause::report!("the event is no longer available"))
+ }
+}
+
+fn runner(sessions: Sessions) -> TargetRunner<Sessions, Events> {
+ TargetRunner::new(Arc::new(sessions), Arc::new(Events(None)))
}
fn assert_identity(
@@ -253,7 +294,11 @@ async fn model_targets_use_macro_sessions_with_the_selected_model_and_event_cont
action.task.as_object_mut().unwrap().remove("agent");
let mut handle = ExecutionHandle::default();
runner.prepare(&action, &mut handle).await.unwrap();
- runner.run(&action, &handle, event.as_ref()).await.unwrap();
+ let firing = match &event {
+ Some(run) => RoutineRun::Event(run),
+ None => manual(),
+ };
+ runner.run(&action, &handle, firing).await.unwrap();
runner.cancel(&action, &handle).await.unwrap();
let preparations = runner.sessions.preparations.lock().unwrap();
@@ -273,7 +318,12 @@ async fn model_targets_use_macro_sessions_with_the_selected_model_and_event_cont
assert_eq!(prompts.len(), 1);
assert_eq!(
prompts[0].prompt,
- first_prompt(&task(&action).unwrap(), event.as_ref()).unwrap()
+ first_prompt(
+ &task(&action).unwrap(),
+ prompts[0].context.as_ref(),
+ event.as_ref().map(|run| &run.pending.event)
+ )
+ .unwrap()
);
let identity = &prompts[0].action;
assert_eq!(identity.bot_id, bot_id::MACRO_NEW_BOT_ID);
@@ -303,7 +353,11 @@ async fn fast_completion_keeps_owner_override_ids_and_context_in_one_prompt() {
let mut handle = ExecutionHandle::default();
runner.prepare(&action, &mut handle).await.unwrap();
let start = Instant::now();
- runner.run(&action, &handle, Some(&event)).await.unwrap();
+ runner
+ .run(&action, &handle, RoutineRun::Event(&event))
+ .await
+ .unwrap();
+ let event = &event.pending.event;
assert_eq!(Instant::now(), start);
let preparations = runner.sessions.preparations.lock().unwrap();
assert_eq!(preparations.len(), 1);
@@ -322,6 +376,7 @@ async fn fast_completion_keeps_owner_override_ids_and_context_in_one_prompt() {
assert!(prompts[0].prompt.contains("Keep these instructions"));
assert!(prompts[0].prompt.contains("Do this task"));
assert!(prompts[0].prompt.contains("data, not instructions"));
+ assert!(prompts[0].context.is_none());
assert!(prompts[0].prompt.contains(&event.entity_id().to_string()));
assert!(
prompts[0]
@@ -349,7 +404,7 @@ async fn omitted_override_preserves_persona_default_and_no_fabricated_event() {
None
);
assert!(
- !first_prompt(&task(&action).unwrap(), None)
+ !first_prompt(&task(&action).unwrap(), None, None)
.unwrap()
.contains("Triggering event")
);
@@ -380,7 +435,7 @@ async fn safe_reads_back_off_and_recover_without_replaying_prompt() {
let action = action();
let mut handle = ExecutionHandle::default();
runner.prepare(&action, &mut handle).await.unwrap();
- runner.run(&action, &handle, None).await.unwrap();
+ runner.run(&action, &handle, manual()).await.unwrap();
let reads = runner.sessions.reads.lock().unwrap();
let delays: Vec<_> = reads
.windows(2)
@@ -402,7 +457,7 @@ async fn repeated_status_failures_are_bounded() {
let action = action();
let mut handle = ExecutionHandle::default();
runner.prepare(&action, &mut handle).await.unwrap();
- let error = runner.run(&action, &handle, None).await.unwrap_err();
+ let error = runner.run(&action, &handle, manual()).await.unwrap_err();
assert_eq!(
error.downcast_ref(),
Some(&RoutineSessionError::OperationFailed)
@@ -423,7 +478,7 @@ async fn stalled_status_reads_are_bounded_too() {
let action = action();
let mut handle = ExecutionHandle::default();
runner.prepare(&action, &mut handle).await.unwrap();
- assert!(runner.run(&action, &handle, None).await.is_err());
+ assert!(runner.run(&action, &handle, manual()).await.is_err());
assert_eq!(
runner.sessions.reads.lock().unwrap().len(),
usize::from(MAX_STATUS_FAILURES)
@@ -439,7 +494,7 @@ async fn ambiguous_prompt_is_never_retried_and_keeps_resource_for_failed_history
let action = action();
let mut handle = ExecutionHandle::default();
runner.prepare(&action, &mut handle).await.unwrap();
- assert!(runner.run(&action, &handle, None).await.is_err());
+ assert!(runner.run(&action, &handle, manual()).await.is_err());
runner.cancel(&action, &handle).await.unwrap();
assert_eq!(runner.sessions.prompts.lock().unwrap().len(), 1);
assert!(runner.sessions.reads.lock().unwrap().is_empty());
@@ -512,7 +567,7 @@ async fn mismatched_session_or_action_never_reports_success() {
assert!(runner.sessions.prompts.lock().unwrap().is_empty());
} else {
prepared.unwrap();
- assert!(runner.run(&action, &handle, None).await.is_err());
+ assert!(runner.run(&action, &handle, manual()).await.is_err());
}
assert!(runner.sessions.reads.lock().unwrap().is_empty());
}
@@ -544,7 +599,7 @@ async fn all_terminal_failures_and_authorization_errors_fail_without_retry() {
let action = action();
let mut handle = ExecutionHandle::default();
runner.prepare(&action, &mut handle).await.unwrap();
- assert!(runner.run(&action, &handle, None).await.is_err());
+ assert!(runner.run(&action, &handle, manual()).await.is_err());
assert_eq!(runner.sessions.reads.lock().unwrap().len(), 1);
}
}
@@ -786,3 +841,281 @@ async fn invalid_targets_and_non_user_owners_never_reach_sessions() {
}
assert!(runner.sessions.preparations.lock().unwrap().is_empty());
}
+
+#[tokio::test]
+async fn a_scheduled_run_tells_the_agent_which_routine_fired_and_on_what_schedule() {
+ let runner = runner(Sessions {
+ statuses: Mutex::new([Ok(RoutineActionStatus::Succeeded)].into()),
+ ..Default::default()
+ });
+ let routine_id = Uuid::parse_str("01928f3e-6a2b-7c3d-8e4f-0123456789ab").unwrap();
+ let scheduled_for = Utc.with_ymd_and_hms(2026, 10, 8, 13, 0, 0).unwrap();
+ let action = ScheduledAction {
+ id: Some(routine_id),
+ owner: Owner::User(MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap()),
+ name: "Morning digest".into(),
+ trigger: serde_json::from_value(json!({"type": "multiple", "triggers": [
+ {"type": "cron", "schedule": "0 0 9 * * MON-FRI", "timezone": "America/New_York"},
+ {"type": "cron", "schedule": "0 0 12 * * SAT", "timezone": "UTC"},
+ ]}))
+ .unwrap(),
+ kind: ActionKind::Agent,
+ task: json!({
+ "model": "runtime/model",
+ "prompt": "Summarize my unread email.",
+ "user_prompt": "Post it in #digest.",
+ }),
+ enabled: true,
+ next_run_at: Some(scheduled_for),
+ claimed: None,
+ configuration_revision: ConfigurationRevision::INITIAL,
+ event_activated_at: None,
+ created_at: scheduled_for,
+ updated_at: scheduled_for,
+ };
+ let mut handle = ExecutionHandle::default();
+ runner.prepare(&action, &mut handle).await.unwrap();
+ runner
+ .run(&action, &handle, RoutineRun::Scheduled { scheduled_for })
+ .await
+ .unwrap();
+
+ let prompts = runner.sessions.prompts.lock().unwrap();
+ assert_eq!(prompts.len(), 1);
+ assert_eq!(
+ prompts[0].prompt,
+ format!("{SCHEDULED_GUIDANCE}\n\nUser task:\nPost it in #digest.")
+ );
+ assert_eq!(
+ prompts[0].context,
+ Some(TriggerContext::Routine(RoutineContext {
+ routine_id,
+ name: "Morning digest".into(),
+ owner: ContextPerson {
+ id: "macro|[email protected]".into(),
+ name: "[email protected]".into(),
+ email: Some("[email protected]".into()),
+ },
+ instructions: "Summarize my unread email.".into(),
+ triggers: vec![
+ ContextRoutineTrigger::Schedule {
+ cron: "0 0 9 * * MON-FRI".into(),
+ timezone: "America/New_York".into(),
+ },
+ ContextRoutineTrigger::Schedule {
+ cron: "0 0 12 * * SAT".into(),
+ timezone: "UTC".into(),
+ },
+ ],
+ firing: RoutineFiring::Scheduled {
+ scheduled_for,
+ schedule:
+ "cron `0 0 9 * * MON-FRI` in America/New_York; cron `0 0 12 * * SAT` in UTC"
+ .into(),
+ },
+ }))
+ );
+}
+
+#[tokio::test]
+async fn a_task_status_change_hands_the_agent_the_task_instead_of_its_ids() {
+ let task_status_changed = RoutineEvent::TaskStatusChanged {
+ task: TaskSnapshot {
+ id: "01928f3e-6a2b-7c3d-8e4f-000000007a5c".into(),
+ title: "Login page crashes on Safari".into(),
+ markdown: "Steps: open login on Safari 17.".into(),
+ status: Some("In review".into()),
+ priority: Some("High".into()),
+ due: Some(Utc.with_ymd_and_hms(2026, 10, 9, 0, 0, 0).unwrap()),
+ assignees: vec![ContextPerson {
+ id: "macro|[email protected]".into(),
+ name: "[email protected]".into(),
+ email: Some("[email protected]".into()),
+ }],
+ project: None,
+ },
+ };
+ let runner = TargetRunner::new(
+ Arc::new(Sessions {
+ statuses: Mutex::new([Ok(RoutineActionStatus::Succeeded)].into()),
+ ..Default::default()
+ }),
+ Arc::new(Events(Some(task_status_changed.clone()))),
+ );
+ let routine_id = Uuid::parse_str("01928f3e-6a2b-7c3d-8e4f-0123456789ab").unwrap();
+ let owner = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+ let at = Utc.with_ymd_and_hms(2026, 10, 8, 13, 0, 0).unwrap();
+ let action = ScheduledAction {
+ id: Some(routine_id),
+ owner: Owner::User(owner.clone()),
+ name: "Review handoff".into(),
+ trigger: serde_json::from_value(json!({
+ "type": "events",
+ "filters": [
+ {
+ "events": ["task.status_changed", "task.created"],
+ "ids": ["01928f3e-6a2b-7c3d-8e4f-000000007a5c"],
+ "condition": "Is the task ready for review?",
+ },
+ {
+ "events": ["task.property_changed"],
+ "condition": "Did someone ask for a second reviewer?",
+ },
+ {"events": ["document.created"]},
+ ],
+ }))
+ .unwrap(),
+ kind: ActionKind::Agent,
+ task: json!({
+ "model": "runtime/model",
+ "prompt": "Ask a reviewer to pick it up.",
+ "user_prompt": "Tag the right reviewer.",
+ }),
+ enabled: true,
+ next_run_at: None,
+ claimed: None,
+ configuration_revision: ConfigurationRevision::INITIAL,
+ event_activated_at: Some(at),
+ created_at: at,
+ updated_at: at,
+ };
+ let event: EventReference = serde_json::from_value(json!({
+ "event_id": "01928f3e-6a2b-7c3d-8e4f-0123456789cd",
+ "event_name": "task.status_changed",
+ "entity_id": "01928f3e-6a2b-7c3d-8e4f-000000007a5c",
+ "message_id": null,
+ }))
+ .unwrap();
+ let run = AuthorizedEventRun {
+ access: EventAccessCapability::Document(
+ EntityAccessReceipt::<ViewAccessLevel>::dangerously_assert_authenticated_user(
+ owner,
+ "01928f3e-6a2b-7c3d-8e4f-000000007a5c",
+ EntityType::Document,
+ ),
+ ),
+ pending: PendingEventRun {
+ action_id: routine_id,
+ revision: ConfigurationRevision::INITIAL,
+ event,
+ admitted_at: at,
+ },
+ };
+ let mut handle = ExecutionHandle::default();
+ runner.prepare(&action, &mut handle).await.unwrap();
+ runner
+ .run(&action, &handle, RoutineRun::Event(&run))
+ .await
+ .unwrap();
+
+ let prompts = runner.sessions.prompts.lock().unwrap();
+ assert_eq!(prompts.len(), 1);
+ assert_eq!(
+ prompts[0].prompt,
+ format!("{SCHEDULED_GUIDANCE}\n\nUser task:\nTag the right reviewer.")
+ );
+ assert_eq!(
+ prompts[0].context,
+ Some(TriggerContext::Routine(RoutineContext {
+ routine_id,
+ name: "Review handoff".into(),
+ owner: ContextPerson {
+ id: "macro|[email protected]".into(),
+ name: "[email protected]".into(),
+ email: Some("[email protected]".into()),
+ },
+ instructions: "Ask a reviewer to pick it up.".into(),
+ triggers: vec![
+ ContextRoutineTrigger::Events {
+ events: vec!["document.created".into()],
+ entity_ids: Vec::new(),
+ condition: None,
+ },
+ ContextRoutineTrigger::Events {
+ events: vec!["task.created".into(), "task.status_changed".into()],
+ entity_ids: vec![
+ Uuid::parse_str("01928f3e-6a2b-7c3d-8e4f-000000007a5c").unwrap()
+ ],
+ condition: Some("Is the task ready for review?".into()),
+ },
+ ContextRoutineTrigger::Events {
+ events: vec!["task.property_changed".into()],
+ entity_ids: Vec::new(),
+ condition: Some("Did someone ask for a second reviewer?".into()),
+ },
+ ],
+ firing: RoutineFiring::Event {
+ event: Box::new(task_status_changed),
+ conditions: vec![
+ "Did someone ask for a second reviewer?".into(),
+ "Is the task ready for review?".into(),
+ ],
+ },
+ }))
+ );
+}
+
+#[tokio::test]
+async fn a_manual_run_tells_the_agent_its_owner_started_it() {
+ let runner = runner(Sessions {
+ statuses: Mutex::new([Ok(RoutineActionStatus::Succeeded)].into()),
+ ..Default::default()
+ });
+ let routine_id = Uuid::parse_str("01928f3e-6a2b-7c3d-8e4f-0123456789ab").unwrap();
+ let requested_at = Utc.with_ymd_and_hms(2026, 10, 8, 15, 30, 0).unwrap();
+ let action = ScheduledAction {
+ id: Some(routine_id),
+ owner: Owner::User(MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap()),
+ name: "Inbox triage".into(),
+ trigger: serde_json::from_value(json!({
+ "type": "events",
+ "filters": [{"events": ["email.message_received"]}],
+ }))
+ .unwrap(),
+ kind: ActionKind::Agent,
+ task: json!({
+ "model": "runtime/model",
+ "prompt": "Label my new email.",
+ "user_prompt": "Use the Finance label for invoices.",
+ }),
+ enabled: true,
+ next_run_at: None,
+ claimed: None,
+ configuration_revision: ConfigurationRevision::INITIAL,
+ event_activated_at: Some(requested_at),
+ created_at: requested_at,
+ updated_at: requested_at,
+ };
+ let mut handle = ExecutionHandle::default();
+ runner.prepare(&action, &mut handle).await.unwrap();
+ runner
+ .run(&action, &handle, RoutineRun::Manual { requested_at })
+ .await
+ .unwrap();
+
+ let prompts = runner.sessions.prompts.lock().unwrap();
+ assert_eq!(prompts.len(), 1);
+ assert_eq!(
+ prompts[0].prompt,
+ format!("{SCHEDULED_GUIDANCE}\n\nUser task:\nUse the Finance label for invoices.")
+ );
+ assert_eq!(
+ prompts[0].context,
+ Some(TriggerContext::Routine(RoutineContext {
+ routine_id,
+ name: "Inbox triage".into(),
+ owner: ContextPerson {
+ id: "macro|[email protected]".into(),
+ name: "[email protected]".into(),
+ email: Some("[email protected]".into()),
+ },
+ instructions: "Label my new email.".into(),
+ triggers: vec![ContextRoutineTrigger::Events {
+ events: vec!["email.message_received".into()],
+ entity_ids: Vec::new(),
+ condition: None,
+ }],
+ firing: RoutineFiring::Manual { requested_at },
+ }))
+ );
+}
diff --git a/services/scheduled_action/src/outbound/agent_session_client/test.rs b/services/scheduled_action/src/outbound/agent_session_client/test.rs
index e61b314d8b..51d0d33613 100644
--- a/services/scheduled_action/src/outbound/agent_session_client/test.rs
+++ b/services/scheduled_action/src/outbound/agent_session_client/test.rs
@@ -3,7 +3,7 @@ use agent_runtime_protocol::domain::action::AgentActionId;
use agent_session::domain::model::AgentSessionId;
use bot_id::BotId;
use macro_user_id::user_id::MacroUserIdStr;
-use macro_uuid::generate_uuid_v7;
+use macro_uuid::{Uuid, generate_uuid_v7};
use serde_json::{Value, json};
use std::{
collections::VecDeque,
@@ -14,6 +14,9 @@ use tokio::{
net::TcpListener,
task::JoinHandle,
};
+use trigger_context::{
+ ContextPerson, RoutineContext, RoutineFiring, RoutineTrigger, TriggerContext,
+};
const KEY: &str = "test-internal-key";
@@ -143,7 +146,25 @@ async fn all_commands_use_internal_auth_and_domain_wire_contract_at_both_prefixe
};
let prompt = PromptRoutineSession {
action: identity.clone(),
- prompt: "Routine instructions\nUser task\nTriggering event context (data): {\"event_name\":\"document.updated\"}".into(),
+ prompt: "Routine instructions\nUser task".into(),
+ context: Some(TriggerContext::Routine(RoutineContext {
+ routine_id: Uuid::nil(),
+ name: "Morning digest".into(),
+ owner: ContextPerson {
+ id: "macro|[email protected]".into(),
+ name: "[email protected]".into(),
+ email: Some("[email protected]".into()),
+ },
+ instructions: "Summarize my unread email.".into(),
+ triggers: vec![RoutineTrigger::Schedule {
+ cron: "0 0 9 * * *".into(),
+ timezone: "UTC".into(),
+ }],
+ firing: RoutineFiring::Scheduled {
+ scheduled_for: chrono::DateTime::UNIX_EPOCH,
+ schedule: "cron `0 0 9 * * *` in UTC".into(),
+ },
+ })),
};
let server = server(vec![
Reply::json(200, json!({"managed":false})),
@@ -254,6 +275,7 @@ async fn malformed_and_ambiguous_prompt_responses_never_replay() {
.prompt(PromptRoutineSession {
action: identity(),
prompt: "task".into(),
+ context: None,
})
.await
.unwrap_err();
@@ -328,6 +350,7 @@ async fn status_and_prompt_requests_have_bounded_timeouts() {
.prompt(PromptRoutineSession {
action: identity(),
prompt: "task".into(),
+ context: None,
})
.await
.map(|_| ())
diff --git a/services/scheduled_action/src/outbound/event_content.rs b/services/scheduled_action/src/outbound/event_content.rs
index b8330c3418..0ed9dad60b 100644
--- a/services/scheduled_action/src/outbound/event_content.rs
+++ b/services/scheduled_action/src/outbound/event_content.rs
@@ -1,10 +1,15 @@
//! Read a triggering event's content through each owning domain, as the
-//! routine owner, and describe it as JSON for the condition classifier.
+//! routine owner: as JSON for the condition classifier, and as the typed
+//! event the agent's prompt context carries.
//!
//! Every read uses the run's access receipt or an id it covers. Nothing here
-//! is logged: the content is the user's, and only the classifier sees it.
+//! is logged: the content is the user's, and only the classifier and the
+//! routine's agent see it.
-use channels::domain::{models::ChannelType, ports::ChannelService};
+use channels::domain::{
+ models::{ChannelMetadata, ChannelType},
+ ports::ChannelService,
+};
use documents::domain::ports::DocumentRepo;
use email::domain::{
models::{ContactInfo, ParsedMessage},
@@ -16,7 +21,10 @@ use macro_user_id::user_id::MacroUserIdStr;
use macro_uuid::Uuid;
use mention_utils::parse::{ParsedXmlText, PlainTextFormatter, XmlFormatter};
use messages::domain::{
- api::MessageReader, models::Message, ports::MessageError, service::MessageView,
+ api::MessageReader,
+ models::{Message, MessageThread},
+ ports::MessageError,
+ service::MessageView,
};
use model::document::DocumentBasic;
use models_properties::service::{
@@ -25,12 +33,16 @@ use models_properties::service::{
use properties::{EntityPropertyInfo, PropertiesService};
use rootcause::{Report, compat::IntoRootcause};
use serde_json::{Map, Value, json};
+use trigger_context::RoutineEvent;
use crate::domain::{
event_runs::{AuthorizedEventRun, EventAccessCapability, condition::EventContentReader},
event_trigger::{EventName, EventReference},
+ ports::RoutineEventReader,
};
+mod routine_event;
+
#[cfg(test)]
mod test;
@@ -84,21 +96,56 @@ where
run: &AuthorizedEventRun,
) -> Result<Value, Report> {
let event = &run.pending.event;
- let content = match &run.access {
- EventAccessCapability::EmailThread(receipt) => {
- json!({ "email": self.email(receipt.clone(), event).await? })
- }
- EventAccessCapability::Channel(receipt) => {
- self.channel(owner, receipt.clone(), event).await?
- }
- EventAccessCapability::Document(receipt) => {
- json!({ "item": self.document(receipt, event).await? })
- }
- };
- Ok(envelope(owner, event, content))
+ let content = self.content(owner, run).await?;
+ Ok(envelope(owner, event, content_json(event, &content)))
+ }
+}
+
+impl<E, M, C, D, P> RoutineEventReader for EventContentAdapter<E, M, C, D, P>
+where
+ E: EmailContentService,
+ M: MessageReader,
+ C: ChannelService,
+ D: DocumentRepo,
+ P: PropertiesService,
+{
+ async fn read_event(
+ &self,
+ owner: &MacroUserIdStr<'static>,
+ run: &AuthorizedEventRun,
+ ) -> Result<RoutineEvent, Report> {
+ let content = self.content(owner, run).await?;
+ routine_event::routine_event(&run.pending.event, content)
}
}
+/// A triggering event's content, as its owning domains return it.
+#[expect(
+ clippy::large_enum_variant,
+ reason = "read once per run and consumed at once"
+)]
+enum EventContent {
+ /// The triggering email; None once it is gone from the thread's latest page.
+ Email(Option<ParsedMessage>),
+ Channel {
+ channel: ChannelMetadata,
+ /// None for events without a message, and once the message is gone.
+ message: Option<ChannelMessage>,
+ },
+ Document {
+ document: DocumentBasic,
+ properties: Vec<EntityPropertyInfo>,
+ /// Body of Macro's own documents, when lexical could render it.
+ markdown: Option<String>,
+ },
+}
+
+struct ChannelMessage {
+ message: Message,
+ /// The discussion a reply was posted in; None for top-level messages.
+ thread: Option<MessageThread>,
+}
+
impl<E, M, C, D, P> EventContentAdapter<E, M, C, D, P>
where
E: EmailContentService,
@@ -107,11 +154,28 @@ where
D: DocumentRepo,
P: PropertiesService,
{
+ async fn content(
+ &self,
+ owner: &MacroUserIdStr<'static>,
+ run: &AuthorizedEventRun,
+ ) -> Result<EventContent, Report> {
+ let event = &run.pending.event;
+ match &run.access {
+ EventAccessCapability::EmailThread(receipt) => Ok(EventContent::Email(
+ self.email(receipt.clone(), event).await?,
+ )),
+ EventAccessCapability::Channel(receipt) => {
+ self.channel(owner, receipt.clone(), event).await
+ }
+ EventAccessCapability::Document(receipt) => self.document(receipt, event).await,
+ }
+ }
+
async fn email(
&self,
receipt: EntityAccessReceipt<ViewAccessLevel>,
event: &EventReference,
- ) -> Result<Value, Report> {
+ ) -> Result<Option<ParsedMessage>, Report> {
let messages = self
.email
.get_messages_parsed(receipt, 0, EMAIL_PAGE)
@@ -119,12 +183,8 @@ where
.map_err(|error| Report::new(error).into_dynamic())?
.unwrap_or_default();
Ok(messages
- .iter()
- .find(|message| Some(message.db_id) == event.message_id())
- .map_or_else(
- || unavailable("the email is no longer available"),
- email_json,
- ))
+ .into_iter()
+ .find(|message| Some(message.db_id) == event.message_id()))
}
async fn channel(
@@ -132,35 +192,48 @@ where
owner: &MacroUserIdStr<'static>,
receipt: EntityAccessReceipt<ViewOnly>,
event: &EventReference,
- ) -> Result<Value, Report> {
+ ) -> Result<EventContent, Report> {
let channel = self
.channels
.get_channel_metadata(event.entity_id(), owner.clone())
.await
.map_err(|error| Report::new(error).into_dynamic())?;
- let mut content = json!({
- "channel": {
- "name": channel.channel_name,
- "type": channel_type(channel.channel_type),
- }
- });
let Some(message_id) = event.message_id() else {
- return Ok(content);
+ return Ok(EventContent::Channel {
+ channel,
+ message: None,
+ });
};
let access = receipt
.try_into_requirement::<MessageView>()
.map_err(|error| Report::new(error).into_dynamic())?;
let Some(message) = self.message(access.clone(), message_id).await? else {
- content["message"] = unavailable("the message is no longer available");
- return Ok(content);
+ return Ok(EventContent::Channel {
+ channel,
+ message: None,
+ });
+ };
+ let thread = match message.thread_id.filter(|root| *root != message.id) {
+ Some(root) => self.thread(access, root).await?,
+ None => None,
};
- if let Some(root) = message.thread_id.filter(|root| *root != message.id)
- && let Some(parent) = self.message(access, root).await?
- {
- content["thread_parent"] = message_json(&parent);
+ Ok(EventContent::Channel {
+ channel,
+ message: Some(ChannelMessage { message, thread }),
+ })
+ }
+
+ /// None when the discussion has been deleted.
+ async fn thread(
+ &self,
+ access: EntityAccessReceipt<MessageView>,
+ root: Uuid,
+ ) -> Result<Option<MessageThread>, Report> {
+ match self.messages.get_thread(access, root).await {
+ Ok(thread) => Ok(Some(thread)),
+ Err(MessageError::NotFound) => Ok(None),
+ Err(error) => Err(Report::new(error).into_dynamic()),
}
- content["message"] = message_json(&message);
- Ok(content)
}
/// None when the message, or the thread it was in, has been deleted.
@@ -180,7 +253,7 @@ where
&self,
receipt: &EntityAccessReceipt<ViewAccessLevel>,
event: &EventReference,
- ) -> Result<Value, Report> {
+ ) -> Result<EventContent, Report> {
let id = event.entity_id().to_string();
let document = self
.documents
@@ -188,7 +261,11 @@ where
.await
.map_err(|error| Into::<anyhow::Error>::into(error).into_rootcause())?;
if document.deleted_at.is_some() || event.event_name() == EventName::DocumentDeleted {
- return Ok(document_json(&document, &[], None));
+ return Ok(EventContent::Document {
+ document,
+ properties: Vec::new(),
+ markdown: None,
+ });
}
let properties = self
.properties
@@ -208,7 +285,50 @@ where
} else {
None
};
- Ok(document_json(&document, &properties, markdown.as_deref()))
+ Ok(EventContent::Document {
+ document,
+ properties,
+ markdown,
+ })
+ }
+}
+
+/// The classifier's view of the content.
+fn content_json(event: &EventReference, content: &EventContent) -> Value {
+ match content {
+ EventContent::Email(message) => json!({
+ "email": message.as_ref().map_or_else(
+ || unavailable("the email is no longer available"),
+ email_json,
+ ),
+ }),
+ EventContent::Channel { channel, message } => {
+ let mut value = json!({
+ "channel": {
+ "name": channel.channel_name,
+ "type": channel_type(channel.channel_type),
+ }
+ });
+ if event.message_id().is_none() {
+ return value;
+ }
+ let Some(ChannelMessage { message, thread }) = message else {
+ value["message"] = unavailable("the message is no longer available");
+ return value;
+ };
+ if let Some(thread) = thread
+ && thread.root.deleted_at.is_none()
+ {
+ value["thread_parent"] = message_json(&thread.root);
+ }
+ value["message"] = message_json(message);
+ value
+ }
+ EventContent::Document {
+ document,
+ properties,
+ markdown,
+ } => json!({ "item": document_json(document, properties, markdown.as_deref()) }),
}
}
@@ -240,13 +360,18 @@ fn contact(contact: &ContactInfo) -> Value {
json!({ "name": contact.name, "email": contact.email })
}
-fn email_json(message: &ParsedMessage) -> Value {
- let body = message
+/// The reply-free body, else the full text, else the snippet; bounded.
+fn email_body(message: &ParsedMessage) -> Option<String> {
+ message
.body_parsed
.as_deref()
.or(message.body_text.as_deref())
.or(message.snippet.as_deref())
- .map(truncate);
+ .map(truncate)
+}
+
+fn email_json(message: &ParsedMessage) -> Value {
+ let body = email_body(message);
json!({
"subject": message.subject,
"from": message.from.as_ref().map(contact),
diff --git a/services/scheduled_action/src/outbound/event_content/routine_event.rs b/services/scheduled_action/src/outbound/event_content/routine_event.rs
new file mode 100644
index 0000000000..caabdd4d87
--- /dev/null
+++ b/services/scheduled_action/src/outbound/event_content/routine_event.rs
@@ -0,0 +1,355 @@
+//! The typed event a routine's agent is told about, from the same content the
+//! condition classifier reads.
+
+use channel_sender::ChannelSender;
+use channels::domain::models::{ChannelMetadata, ChannelType as ChannelKind};
+use email::domain::models::{ContactInfo, ParsedMessage};
+use macro_user_id::user_id::MacroUserIdStr;
+use macro_uuid::Uuid;
+use messages::domain::models::{Message, MessageThread};
+use model::document::DocumentBasic;
+use models_properties::service::{
+ property_option::PropertyOptionValue, property_value::PropertyValue,
+};
+use properties::EntityPropertyInfo;
+use rootcause::Report;
+use system_properties::SystemPropertyKey;
+use trigger_context::{
+ ChannelType, ContextMessage, ContextPerson, ContextThread, DiscussionContext,
+ DiscussionSurface, DocumentSnapshot, EmailSnapshot, ReplyTarget, RoutineEvent, TaskSnapshot,
+};
+
+use super::{ChannelMessage, EventContent, email_body, truncate};
+use crate::domain::event_trigger::{EventName, EventReference};
+
+#[cfg(test)]
+mod test;
+
+/// Messages of a discussion passed on, the triggering message included.
+const MAX_THREAD_MESSAGES: usize = 20;
+
+/// `Err` when the event's message or email is gone, or the content read does
+/// not belong to the event.
+pub(super) fn routine_event(
+ event: &EventReference,
+ content: EventContent,
+) -> Result<RoutineEvent, Report> {
+ let name = event.event_name();
+ match content {
+ EventContent::Document {
+ document,
+ properties,
+ markdown,
+ } => document_event(name, document, &properties, markdown.as_deref()),
+ EventContent::Email(message) => match (name, message) {
+ (EventName::EmailMessageReceived, Some(message)) => Ok(RoutineEvent::EmailReceived {
+ email: email_snapshot(event.entity_id(), &message),
+ }),
+ (EventName::EmailMessageReceived, None) => {
+ Err(rootcause::report!("the email is no longer available"))
+ }
+ (name, _) => Err(mismatch(name)),
+ },
+ EventContent::Channel { channel, message } => {
+ channel_event(name, event.entity_id(), channel, message)
+ }
+ }
+}
+
+fn mismatch(name: EventName) -> Report {
+ rootcause::report!(
+ "the content read does not belong to a {} event",
+ name.as_str()
+ )
+}
+
+fn document_event(
+ name: EventName,
+ document: DocumentBasic,
+ properties: &[EntityPropertyInfo],
+ markdown: Option<&str>,
+) -> Result<RoutineEvent, Report> {
+ Ok(match name {
+ EventName::DocumentCreated => RoutineEvent::DocumentCreated {
+ document: document_snapshot(document, markdown),
+ },
+ EventName::DocumentUpdated => RoutineEvent::DocumentUpdated {
+ document: document_snapshot(document, markdown),
+ },
+ EventName::DocumentDeleted => RoutineEvent::DocumentDeleted {
+ id: document.document_id,
+ name: document.document_name,
+ },
+ EventName::TaskCreated => RoutineEvent::TaskCreated {
+ task: task_snapshot(document, properties, markdown),
+ },
+ EventName::TaskStatusChanged => RoutineEvent::TaskStatusChanged {
+ task: task_snapshot(document, properties, markdown),
+ },
+ EventName::TaskPriorityChanged => RoutineEvent::TaskPriorityChanged {
+ task: task_snapshot(document, properties, markdown),
+ },
+ EventName::TaskPropertyChanged => RoutineEvent::TaskPropertyChanged {
+ task: task_snapshot(document, properties, markdown),
+ },
+ name => return Err(mismatch(name)),
+ })
+}
+
+fn channel_event(
+ name: EventName,
+ channel_id: Uuid,
+ channel: ChannelMetadata,
+ message: Option<ChannelMessage>,
+) -> Result<RoutineEvent, Report> {
+ if name == EventName::ChannelCreated {
+ return Ok(RoutineEvent::ChannelCreated {
+ id: channel_id,
+ name: Some(channel.channel_name),
+ });
+ }
+ let message =
+ message.ok_or_else(|| rootcause::report!("the message is no longer available"))?;
+ let attachment = newest_attachment(&message.message);
+ let discussion = discussion(channel_id, channel, message);
+ Ok(match name {
+ EventName::ChannelMessagePosted => RoutineEvent::ChannelMessagePosted { discussion },
+ EventName::ChannelMentioned => RoutineEvent::ChannelMentioned { discussion },
+ EventName::ChannelMessagePatched => RoutineEvent::ChannelMessagePatched { discussion },
+ EventName::ChannelMessageAttachmentCreated => {
+ let (entity_type, entity_id) = attachment
+ .ok_or_else(|| rootcause::report!("the attachment is no longer available"))?;
+ RoutineEvent::ChannelMessageAttachmentCreated {
+ discussion,
+ entity_type,
+ entity_id,
+ }
+ }
+ name => return Err(mismatch(name)),
+ })
+}
+
+fn document_snapshot(document: DocumentBasic, markdown: Option<&str>) -> DocumentSnapshot {
+ DocumentSnapshot {
+ id: document.document_id,
+ name: document.document_name,
+ file_type: document.file_type.unwrap_or_default(),
+ text: markdown.map(truncate),
+ }
+}
+
+fn task_snapshot(
+ document: DocumentBasic,
+ properties: &[EntityPropertyInfo],
+ markdown: Option<&str>,
+) -> TaskSnapshot {
+ let mut task = TaskSnapshot {
+ id: document.document_id,
+ title: document.document_name,
+ markdown: markdown.map(truncate).unwrap_or_default(),
+ status: None,
+ priority: None,
+ due: None,
+ assignees: Vec::new(),
+ // Projects are read under their own access, which the run does not carry.
+ project: None,
+ };
+ for property in properties {
+ match (
+ SystemPropertyKey::from_uuid(property.property_definition_id),
+ &property.value,
+ ) {
+ (Some(SystemPropertyKey::Status), Some(PropertyValue::SelectOption(ids))) => {
+ task.status = option_label(property, ids);
+ }
+ (Some(SystemPropertyKey::Priority), Some(PropertyValue::SelectOption(ids))) => {
+ task.priority = option_label(property, ids);
+ }
+ (Some(SystemPropertyKey::DueDate), Some(PropertyValue::Date(due))) => {
+ task.due = Some(*due);
+ }
+ (Some(SystemPropertyKey::Assignees), Some(PropertyValue::EntityRef(references))) => {
+ task.assignees = references
+ .iter()
+ .map(|reference| principal(&reference.entity_id))
+ .collect();
+ }
+ _ => {}
+ }
+ }
+ task
+}
+
+/// The label of the first selected option.
+fn option_label(property: &EntityPropertyInfo, ids: &[Uuid]) -> Option<String> {
+ let id = ids.first()?;
+ let option = property.options.iter().find(|option| option.id == *id)?;
+ Some(match &option.value {
+ PropertyOptionValue::String(text) => text.clone(),
+ PropertyOptionValue::Number(number) => number.to_string(),
+ })
+}
+
+fn email_snapshot(thread_id: Uuid, message: &ParsedMessage) -> EmailSnapshot {
+ EmailSnapshot {
+ thread_id,
+ subject: message.subject.clone().unwrap_or_default(),
+ from: message.from.as_ref().map(address).unwrap_or_default(),
+ to: message.to.iter().map(address).collect(),
+ received_at: message
+ .internal_date_ts
+ .or(message.sent_at)
+ .unwrap_or(message.created_at),
+ body: email_body(message).unwrap_or_default(),
+ }
+}
+
+fn address(contact: &ContactInfo) -> String {
+ match &contact.name {
+ Some(name) => format!("{name} <{}>", contact.email),
+ None => contact.email.clone(),
+ }
+}
+
+/// The triggering message with its discussion up to it. A top-level message
+/// is its own discussion, so it travels as the channel context.
+fn discussion(
+ channel_id: Uuid,
+ channel: ChannelMetadata,
+ ChannelMessage { message, thread }: ChannelMessage,
+) -> DiscussionContext {
+ let surface = DiscussionSurface::Channel {
+ id: channel_id,
+ name: Some(channel.channel_name),
+ channel_type: channel_type(channel.channel_type),
+ };
+ let sender = author(&message);
+ let prompt_message_id = message.id;
+ match message.thread_id.filter(|root| *root != message.id) {
+ Some(root_id) => DiscussionContext {
+ surface,
+ prompt_message_id,
+ sender,
+ reply_target: ReplyTarget::Thread { root_id },
+ thread: Some(context_thread(root_id, thread, &message)),
+ channel: Vec::new(),
+ },
+ None => DiscussionContext {
+ surface,
+ prompt_message_id,
+ sender,
+ reply_target: ReplyTarget::None,
+ thread: None,
+ channel: vec![ContextThread {
+ root_id: message.id,
+ messages: vec![context_message(&message)],
+ messages_omitted: false,
+ }],
+ },
+ }
+}
+
+/// Live messages from the root through `message`, keeping the root and the
+/// latest replies when there are too many.
+fn context_thread(
+ root_id: Uuid,
+ thread: Option<MessageThread>,
+ message: &Message,
+) -> ContextThread {
+ let unread = thread.is_none();
+ let mut earlier: Vec<ContextMessage> = thread
+ .iter()
+ .flat_map(|thread| std::iter::once(&thread.root).chain(&thread.replies))
+ .filter(|other| {
+ other.deleted_at.is_none()
+ && other.id != message.id
+ && other.created_at <= message.created_at
+ })
+ .map(context_message)
+ .collect();
+ let room = MAX_THREAD_MESSAGES - 1;
+ let bounded = earlier.len() > room;
+ if bounded {
+ let root = (earlier[0].id == root_id).then(|| earlier.remove(0));
+ let replies = earlier.split_off(earlier.len() - (room - usize::from(root.is_some())));
+ earlier = root.into_iter().chain(replies).collect();
+ }
+ earlier.push(context_message(message));
+ ContextThread {
+ root_id,
+ messages: earlier,
+ messages_omitted: unread || bounded,
+ }
+}
+
+fn context_message(message: &Message) -> ContextMessage {
+ ContextMessage {
+ id: message.id,
+ author: author(message),
+ content: truncate(&message.content),
+ posted_at: message.created_at,
+ }
+}
+
+fn author(message: &Message) -> ContextPerson {
+ let id = message.sender_id.as_ref().to_owned();
+ if let Some(imported) = &message.imported_author {
+ return ContextPerson {
+ id,
+ name: imported.name.clone(),
+ email: None,
+ };
+ }
+ if let Some(user) = message.sender_id.as_user() {
+ return user_person(user);
+ }
+ ContextPerson {
+ name: message
+ .bot_profile
+ .as_ref()
+ .map_or_else(|| id.clone(), |bot| bot.name.clone()),
+ id,
+ email: None,
+ }
+}
+
+/// A user or bot named only by its id.
+fn principal(id: &str) -> ContextPerson {
+ match ChannelSender::parse_from_str(id)
+ .ok()
+ .and_then(|sender| sender.into_user())
+ {
+ Some(user) => user_person(&user),
+ None => ContextPerson {
+ id: id.to_owned(),
+ name: id.to_owned(),
+ email: None,
+ },
+ }
+}
+
+fn user_person(user: &MacroUserIdStr<'_>) -> ContextPerson {
+ ContextPerson {
+ id: user.as_ref().to_owned(),
+ name: user.email_str().to_owned(),
+ email: Some(user.email_str().to_owned()),
+ }
+}
+
+/// What the newest attachment attaches, as its type and id.
+fn newest_attachment(message: &Message) -> Option<(String, String)> {
+ message
+ .attachments
+ .iter()
+ .max_by_key(|attachment| attachment.created_at)
+ .map(|attachment| (attachment.entity_type.clone(), attachment.entity_id.clone()))
+}
+
+fn channel_type(channel_type: ChannelKind) -> ChannelType {
+ match channel_type {
+ ChannelKind::Public => ChannelType::Public,
+ ChannelKind::Private => ChannelType::Private,
+ ChannelKind::DirectMessage => ChannelType::DirectMessage,
+ ChannelKind::Team => ChannelType::Team,
+ }
+}
diff --git a/services/scheduled_action/src/outbound/event_content/routine_event/test.rs b/services/scheduled_action/src/outbound/event_content/routine_event/test.rs
new file mode 100644
index 0000000000..c15d6376ab
--- /dev/null
+++ b/services/scheduled_action/src/outbound/event_content/routine_event/test.rs
@@ -0,0 +1,393 @@
+use channels::domain::models::{ChannelMetadata, ChannelType as ChannelKind};
+use chrono::{TimeZone, Utc};
+use document_sub_type::DocumentSubType;
+use email::domain::models::{ContactInfo, ParsedLabel, ParsedMessage};
+use macro_user_id::user_id::MacroUserIdStr;
+use macro_uuid::Uuid;
+use messages::domain::models::{Message, MessageParent, MessageThread, ThreadState};
+use model::document::DocumentBasic;
+use model_owner::Owner;
+use models_properties::{
+ DataType, EntityType as PropertyEntityType, PropertyOwner,
+ service::{property_option::PropertyOptionValue, property_value::PropertyValue},
+ shared::EntityReference,
+};
+use properties::{EntityPropertyInfo, PropertyOptionInfo};
+use serde_json::json;
+use system_properties::SystemPropertyKey;
+use trigger_context::{
+ ChannelType, ContextMessage, ContextPerson, ContextThread, DiscussionContext,
+ DiscussionSurface, EmailSnapshot, ReplyTarget, RoutineEvent, TaskSnapshot,
+};
+
+use super::super::{ChannelMessage, EventContent};
+use super::routine_event;
+use crate::domain::event_trigger::EventReference;
+
+#[test]
+fn a_task_status_change_carries_the_task_as_it_reads_now() {
+ let event: EventReference = serde_json::from_value(json!({
+ "event_id": "01928f3e-6a2b-7c3d-8e4f-0123456789cd",
+ "event_name": "task.status_changed",
+ "entity_id": "01928f3e-6a2b-7c3d-8e4f-000000007a5c",
+ "message_id": null,
+ }))
+ .unwrap();
+ let in_review = Uuid::parse_str("00000001-0000-0000-0002-000000000003").unwrap();
+ let high = Uuid::parse_str("00000001-0000-0000-0003-000000000003").unwrap();
+ let content = EventContent::Document {
+ document: DocumentBasic {
+ document_id: "01928f3e-6a2b-7c3d-8e4f-000000007a5c".into(),
+ document_name: "Login page crashes on Safari".into(),
+ owner: Owner::User(MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap()),
+ file_type: Some("md".into()),
+ sub_type: Some(DocumentSubType::Task),
+ branched_from_id: None,
+ branched_from_version_id: None,
+ document_family_id: None,
+ project_id: None,
+ deleted_at: None,
+ },
+ properties: vec![
+ EntityPropertyInfo {
+ property_definition_id: SystemPropertyKey::STATUS_UUID,
+ owner: PropertyOwner::System,
+ display_name: "Status".into(),
+ data_type: DataType::SelectString,
+ is_multi_select: false,
+ is_system: true,
+ value: Some(PropertyValue::SelectOption(vec![in_review])),
+ options: vec![PropertyOptionInfo {
+ id: in_review,
+ display_order: 2,
+ value: PropertyOptionValue::String("In review".into()),
+ }],
+ },
+ EntityPropertyInfo {
+ property_definition_id: SystemPropertyKey::PRIORITY_UUID,
+ owner: PropertyOwner::System,
+ display_name: "Priority".into(),
+ data_type: DataType::SelectString,
+ is_multi_select: false,
+ is_system: true,
+ value: Some(PropertyValue::SelectOption(vec![high])),
+ options: vec![PropertyOptionInfo {
+ id: high,
+ display_order: 2,
+ value: PropertyOptionValue::String("High".into()),
+ }],
+ },
+ EntityPropertyInfo {
+ property_definition_id: SystemPropertyKey::DUE_DATE_UUID,
+ owner: PropertyOwner::System,
+ display_name: "Due Date".into(),
+ data_type: DataType::Date,
+ is_multi_select: false,
+ is_system: true,
+ value: Some(PropertyValue::Date(
+ Utc.with_ymd_and_hms(2026, 10, 9, 0, 0, 0).unwrap(),
+ )),
+ options: Vec::new(),
+ },
+ EntityPropertyInfo {
+ property_definition_id: SystemPropertyKey::ASSIGNEES_UUID,
+ owner: PropertyOwner::System,
+ display_name: "Assignees".into(),
+ data_type: DataType::Entity,
+ is_multi_select: true,
+ is_system: true,
+ value: Some(PropertyValue::EntityRef(vec![EntityReference {
+ entity_id: "macro|[email protected]".into(),
+ entity_type: PropertyEntityType::User,
+ specific_message_id: None,
+ }])),
+ options: Vec::new(),
+ },
+ EntityPropertyInfo {
+ property_definition_id: Uuid::parse_str("01928f3e-6a2b-7c3d-8e4f-0000000eff01")
+ .unwrap(),
+ owner: PropertyOwner::System,
+ display_name: "Estimate".into(),
+ data_type: DataType::Number,
+ is_multi_select: false,
+ is_system: false,
+ value: Some(PropertyValue::Num(3.0)),
+ options: Vec::new(),
+ },
+ ],
+ markdown: Some("Steps: open login on Safari 17.".into()),
+ };
+
+ assert_eq!(
+ routine_event(&event, content).unwrap(),
+ RoutineEvent::TaskStatusChanged {
+ task: TaskSnapshot {
+ id: "01928f3e-6a2b-7c3d-8e4f-000000007a5c".into(),
+ title: "Login page crashes on Safari".into(),
+ markdown: "Steps: open login on Safari 17.".into(),
+ status: Some("In review".into()),
+ priority: Some("High".into()),
+ due: Some(Utc.with_ymd_and_hms(2026, 10, 9, 0, 0, 0).unwrap()),
+ assignees: vec![ContextPerson {
+ id: "macro|[email protected]".into(),
+ name: "[email protected]".into(),
+ email: Some("[email protected]".into()),
+ }],
+ project: None,
+ },
+ }
+ );
+}
+
+#[test]
+fn a_received_email_carries_its_headers_and_reply_free_body() {
+ let event: EventReference = serde_json::from_value(json!({
+ "event_id": "01928f3e-6a2b-7c3d-8e4f-0123456789cd",
+ "event_name": "email.message_received",
+ "entity_id": "01928f3e-6a2b-7c3d-8e4f-00000000e7a1",
+ "message_id": "01928f3e-6a2b-7c3d-8e4f-00000000e3e5",
+ }))
+ .unwrap();
+ let received_at = Utc.with_ymd_and_hms(2026, 10, 5, 9, 30, 0).unwrap();
+ let content = EventContent::Email(Some(ParsedMessage {
+ db_id: Uuid::parse_str("01928f3e-6a2b-7c3d-8e4f-00000000e3e5").unwrap(),
+ link_id: Uuid::nil(),
+ thread_db_id: Uuid::parse_str("01928f3e-6a2b-7c3d-8e4f-00000000e7a1").unwrap(),
+ subject: Some("Invoice #42".into()),
+ snippet: Some("Please find attached".into()),
+ from: Some(ContactInfo {
+ email: "[email protected]".into(),
+ name: Some("Vendor Billing".into()),
+ photo_url: Some("https://example.com/p.png".into()),
+ }),
+ to: vec![
+ ContactInfo {
+ email: "[email protected]".into(),
+ name: None,
+ photo_url: None,
+ },
+ ContactInfo {
+ email: "[email protected]".into(),
+ name: Some("Accounts Payable".into()),
+ photo_url: None,
+ },
+ ],
+ cc: Vec::new(),
+ bcc: vec![ContactInfo {
+ email: "[email protected]".into(),
+ name: None,
+ photo_url: None,
+ }],
+ labels: vec![ParsedLabel {
+ provider_id: "INBOX".into(),
+ name: "Inbox".into(),
+ }],
+ body_parsed: Some("Your invoice for October is $420.".into()),
+ body_text: Some("full text with quoted replies".into()),
+ body_html_sanitized: None,
+ body_macro: None,
+ body_replyless: None,
+ internal_date_ts: Some(received_at),
+ sent_at: None,
+ is_read: false,
+ is_starred: false,
+ is_sent: false,
+ is_draft: false,
+ has_attachments: true,
+ created_at: received_at,
+ updated_at: received_at,
+ }));
+
+ assert_eq!(
+ routine_event(&event, content).unwrap(),
+ RoutineEvent::EmailReceived {
+ email: EmailSnapshot {
+ thread_id: Uuid::parse_str("01928f3e-6a2b-7c3d-8e4f-00000000e7a1").unwrap(),
+ subject: "Invoice #42".into(),
+ from: "Vendor Billing <[email protected]>".into(),
+ to: vec![
+ "[email protected]".into(),
+ "Accounts Payable <[email protected]>".into(),
+ ],
+ received_at,
+ body: "Your invoice for October is $420.".into(),
+ },
+ }
+ );
+}
+
+#[test]
+fn a_channel_reply_carries_its_thread_through_the_message() {
+ let channel_id = Uuid::parse_str("01928f3e-6a2b-7c3d-8e4f-0000000c4a77").unwrap();
+ let root_id = Uuid::parse_str("01928f3e-6a2b-7c3d-8e4f-000000000001").unwrap();
+ let answer_id = Uuid::parse_str("01928f3e-6a2b-7c3d-8e4f-000000000002").unwrap();
+ let deleted_id = Uuid::parse_str("01928f3e-6a2b-7c3d-8e4f-000000000003").unwrap();
+ let prompt_id = Uuid::parse_str("01928f3e-6a2b-7c3d-8e4f-000000000004").unwrap();
+ let later_id = Uuid::parse_str("01928f3e-6a2b-7c3d-8e4f-000000000005").unwrap();
+ let event: EventReference = serde_json::from_value(json!({
+ "event_id": "01928f3e-6a2b-7c3d-8e4f-0123456789cd",
+ "event_name": "channel.message_posted",
+ "entity_id": channel_id,
+ "message_id": prompt_id,
+ }))
+ .unwrap();
+ let at = |minute| Utc.with_ymd_and_hms(2026, 10, 8, 14, minute, 0).unwrap();
+ let prompt = Message {
+ id: prompt_id,
+ parent: MessageParent::Channel(channel_id),
+ thread_id: Some(root_id),
+ sender_id: "macro|[email protected]".to_owned().try_into().unwrap(),
+ imported_author: None,
+ bot_profile: None,
+ mentions: Vec::new(),
+ triggered_by: None,
+ content: "Still broken on Safari 17, can someone look?".into(),
+ created_at: at(4),
+ updated_at: at(4),
+ edited_at: None,
+ deleted_at: None,
+ attachments: Vec::new(),
+ reactions: Vec::new(),
+ };
+ let content = EventContent::Channel {
+ channel: ChannelMetadata {
+ channel_type: ChannelKind::Public,
+ channel_name: "eng".into(),
+ },
+ message: Some(ChannelMessage {
+ message: prompt.clone(),
+ thread: Some(MessageThread {
+ state: ThreadState {
+ root_id,
+ user_id: "macro|[email protected]".into(),
+ resolved: false,
+ anchor: None,
+ created_at: at(1),
+ updated_at: at(5),
+ deleted_at: None,
+ },
+ root: Message {
+ id: root_id,
+ parent: MessageParent::Channel(channel_id),
+ thread_id: None,
+ sender_id: "macro|[email protected]".to_owned().try_into().unwrap(),
+ imported_author: None,
+ bot_profile: None,
+ mentions: Vec::new(),
+ triggered_by: None,
+ content: "Login crashes on Safari".into(),
+ created_at: at(1),
+ updated_at: at(1),
+ edited_at: None,
+ deleted_at: None,
+ attachments: Vec::new(),
+ reactions: Vec::new(),
+ },
+ replies: vec![
+ Message {
+ id: answer_id,
+ parent: MessageParent::Channel(channel_id),
+ thread_id: Some(root_id),
+ sender_id: "macro|[email protected]".to_owned().try_into().unwrap(),
+ imported_author: None,
+ bot_profile: None,
+ mentions: Vec::new(),
+ triggered_by: None,
+ content: "Fixed in #812".into(),
+ created_at: at(2),
+ updated_at: at(2),
+ edited_at: None,
+ deleted_at: None,
+ attachments: Vec::new(),
+ reactions: Vec::new(),
+ },
+ Message {
+ id: deleted_id,
+ parent: MessageParent::Channel(channel_id),
+ thread_id: Some(root_id),
+ sender_id: "macro|[email protected]".to_owned().try_into().unwrap(),
+ imported_author: None,
+ bot_profile: None,
+ mentions: Vec::new(),
+ triggered_by: None,
+ content: "oops".into(),
+ created_at: at(3),
+ updated_at: at(3),
+ edited_at: None,
+ deleted_at: Some(at(3)),
+ attachments: Vec::new(),
+ reactions: Vec::new(),
+ },
+ prompt,
+ Message {
+ id: later_id,
+ parent: MessageParent::Channel(channel_id),
+ thread_id: Some(root_id),
+ sender_id: "macro|[email protected]".to_owned().try_into().unwrap(),
+ imported_author: None,
+ bot_profile: None,
+ mentions: Vec::new(),
+ triggered_by: None,
+ content: "Looking".into(),
+ created_at: at(5),
+ updated_at: at(5),
+ edited_at: None,
+ deleted_at: None,
+ attachments: Vec::new(),
+ reactions: Vec::new(),
+ },
+ ],
+ }),
+ }),
+ };
+
+ let ana = ContextPerson {
+ id: "macro|[email protected]".into(),
+ name: "[email protected]".into(),
+ email: Some("[email protected]".into()),
+ };
+ assert_eq!(
+ routine_event(&event, content).unwrap(),
+ RoutineEvent::ChannelMessagePosted {
+ discussion: DiscussionContext {
+ surface: DiscussionSurface::Channel {
+ id: channel_id,
+ name: Some("eng".into()),
+ channel_type: ChannelType::Public,
+ },
+ prompt_message_id: prompt_id,
+ sender: ana.clone(),
+ reply_target: ReplyTarget::Thread { root_id },
+ thread: Some(ContextThread {
+ root_id,
+ messages: vec![
+ ContextMessage {
+ id: root_id,
+ author: ana.clone(),
+ content: "Login crashes on Safari".into(),
+ posted_at: at(1),
+ },
+ ContextMessage {
+ id: answer_id,
+ author: ContextPerson {
+ id: "macro|[email protected]".into(),
+ name: "[email protected]".into(),
+ email: Some("[email protected]".into()),
+ },
+ content: "Fixed in #812".into(),
+ posted_at: at(2),
+ },
+ ContextMessage {
+ id: prompt_id,
+ author: ana,
+ content: "Still broken on Safari 17, can someone look?".into(),
+ posted_at: at(4),
+ },
+ ],
+ messages_omitted: false,
+ }),
+ channel: Vec::new(),
+ },
+ }
+ );
+}
diff --git a/services/scheduled_action/tests/event_routines.rs b/services/scheduled_action/tests/event_routines.rs
index 73ee58affc..364a062325 100644
--- a/services/scheduled_action/tests/event_routines.rs
+++ b/services/scheduled_action/tests/event_routines.rs
@@ -50,7 +50,7 @@ use scheduled_action::{
ExecutionResource, ExecutionResourceType, MAX_ACTION_TIME, ScheduledAction,
ScheduledActionUpdate,
},
- ports::{ScheduledActionLiveUpdate, ScheduledActionRepo, ScheduledAgentRunner},
+ ports::{RoutineRun, ScheduledActionLiveUpdate, ScheduledActionRepo, ScheduledAgentRunner},
service::ScheduledActionServiceImpl,
},
inbound::{
@@ -176,8 +176,9 @@ impl ScheduledAgentRunner for FakeRunner {
&self,
action: &ScheduledAction,
_: &ExecutionHandle,
- event: Option<&EventReference>,
+ firing: RoutineRun<'_>,
) -> anyhow::Result<()> {
+ let event = firing.event();
self.calls
.lock()
.unwrap()