systemprompt_api/routes/messaging/
mod.rs1mod a2a;
21pub mod identity;
22
23use std::sync::LazyLock;
24
25use serde_json::json;
26use systemprompt_identifiers::{AgentName, ContextId, SessionId, TraceId};
27use systemprompt_runtime::AppContext;
28use systemprompt_security::authz::{AuthzContext, AuthzDecision, AuthzRequest, EntityRef};
29
30use a2a::{authenticated_user, build_a2a_request, mint_a2a_token, run_agent};
31use identity::resolve_or_link_user;
32
33static CLIENT: LazyLock<reqwest::Client> = LazyLock::new(reqwest::Client::new);
34
35#[must_use]
36pub fn http_client() -> reqwest::Client {
37 CLIENT.clone()
38}
39
40#[derive(Debug, Clone)]
41pub enum ReplyTarget {
42 Channel { id: String },
43 Url { url: String },
44}
45
46#[derive(Debug, Clone)]
50pub struct MessagingInbound {
51 pub platform: &'static str,
52 pub issuer: String,
53 pub org_id: String,
54 pub channel_id: String,
55 pub external_user_id: String,
56 pub text: String,
57 pub agent_name: AgentName,
58 pub entity: EntityRef,
59 pub reply: ReplyTarget,
60}
61
62#[derive(Debug, Clone)]
63pub enum DispatchOutcome {
64 Replied(String),
65 Denied(String),
66}
67
68#[derive(Debug, thiserror::Error)]
71pub enum MessagingError {
72 #[error("identity resolution failed: {0}")]
73 Identity(String),
74 #[error("token minting failed: {0}")]
75 Token(String),
76 #[error("agent dispatch failed: {0}")]
77 Dispatch(String),
78 #[error("malformed agent response: {0}")]
79 Response(String),
80}
81
82impl MessagingError {
83 #[must_use]
84 pub fn user_message(&self) -> String {
85 let opaque = "Sorry — something went wrong handling that.";
86 if cfg!(feature = "test-api") {
87 format!("{opaque} ({self})")
88 } else {
89 opaque.to_owned()
90 }
91 }
92}
93
94pub async fn dispatch_messaging(
95 ctx: &AppContext,
96 inbound: MessagingInbound,
97) -> Result<DispatchOutcome, MessagingError> {
98 let user = resolve_or_link_user(ctx, &inbound.issuer, &inbound.external_user_id).await?;
99 let authed = authenticated_user(&user)?;
100
101 let context_id =
102 ContextId::derived_from_messaging(inbound.platform, &inbound.org_id, &inbound.channel_id);
103
104 let authz = AuthzRequest {
105 entity: inbound.entity.clone(),
106 user_id: user.id.clone(),
107 roles: user.roles.clone(),
108 attributes: std::collections::BTreeMap::new(),
109 trace_id: TraceId::generate(),
110 session_id: None,
111 context: AuthzContext::extension(
112 format!("{}.message", inbound.platform),
113 json!({ "channel": inbound.channel_id }),
114 ),
115 context_id: Some(context_id.clone()),
116 task_id: None,
117 act_chain: Vec::new(),
118 };
119 if let AuthzDecision::Deny { reason, policy } = ctx.authz_hook().evaluate(authz).await {
120 return Ok(DispatchOutcome::Denied(format!("{policy}: {reason}")));
121 }
122
123 let session_id = SessionId::new(uuid::Uuid::new_v4().to_string());
124 let token = mint_a2a_token(ctx, &authed, &session_id)?;
125
126 let request = build_a2a_request(&inbound, &authed, &session_id, &token, &context_id)?;
127 let reply = run_agent(ctx, inbound.agent_name.as_str(), request).await?;
128 Ok(DispatchOutcome::Replied(reply))
129}
130
131#[cfg(feature = "test-api")]
132pub mod test_api {
133 use systemprompt_agent::models::a2a::Task;
134
135 #[must_use]
136 pub fn reply_text(task: Option<&Task>) -> String {
137 super::a2a::reply_text(task)
138 }
139}