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);
37
38#[must_use]
39pub fn http_client() -> reqwest::Client {
40 CLIENT.clone()
41}
42
43#[derive(Debug, Clone)]
44pub enum ReplyTarget {
45 Channel { id: String },
46 Url { url: String },
47}
48
49#[derive(Debug, Clone)]
53pub struct MessagingInbound {
54 pub platform: &'static str,
57 pub issuer: String,
58 pub org_id: String,
59 pub channel_id: String,
60 pub external_user_id: String,
61 pub text: String,
62 pub agent_name: AgentName,
63 pub entity: EntityRef,
66 pub reply: ReplyTarget,
67}
68
69#[derive(Debug, Clone)]
70pub enum DispatchOutcome {
71 Replied(String),
74 Denied(String),
76}
77
78#[derive(Debug, thiserror::Error)]
81pub enum MessagingError {
82 #[error("identity resolution failed: {0}")]
83 Identity(String),
84 #[error("token minting failed: {0}")]
85 Token(String),
86 #[error("agent dispatch failed: {0}")]
87 Dispatch(String),
88 #[error("malformed agent response: {0}")]
89 Response(String),
90}
91
92pub async fn dispatch_messaging(
98 ctx: &AppContext,
99 inbound: MessagingInbound,
100) -> Result<DispatchOutcome, MessagingError> {
101 let user = resolve_or_link_user(ctx, &inbound.issuer, &inbound.external_user_id).await?;
102 let authed = authenticated_user(&user)?;
103
104 let context_id =
105 ContextId::derived_from_messaging(inbound.platform, &inbound.org_id, &inbound.channel_id);
106
107 let authz = AuthzRequest {
108 entity: inbound.entity.clone(),
109 user_id: user.id.clone(),
110 roles: user.roles.clone(),
111 attributes: std::collections::BTreeMap::new(),
112 trace_id: TraceId::generate(),
113 session_id: None,
114 context: AuthzContext::extension(
115 format!("{}.message", inbound.platform),
116 json!({ "channel": inbound.channel_id }),
117 ),
118 context_id: Some(context_id.clone()),
119 task_id: None,
120 act_chain: Vec::new(),
121 };
122 if let AuthzDecision::Deny { reason, policy } = ctx.authz_hook().evaluate(authz).await {
123 return Ok(DispatchOutcome::Denied(format!("{policy}: {reason}")));
124 }
125
126 let session_id = SessionId::new(uuid::Uuid::new_v4().to_string());
127 let token = mint_a2a_token(ctx, &authed, &session_id)?;
128
129 let request = build_a2a_request(&inbound, &authed, &session_id, &token, &context_id)?;
130 let reply = run_agent(ctx, inbound.agent_name.as_str(), request).await?;
131 Ok(DispatchOutcome::Replied(reply))
132}
133
134#[cfg(feature = "test-api")]
135pub mod test_api {
136 use systemprompt_agent::models::a2a::Task;
137
138 #[must_use]
139 pub fn reply_text(task: Option<&Task>) -> String {
140 super::a2a::reply_text(task)
141 }
142}