Skip to main content

systemprompt_api/routes/messaging/
mod.rs

1//! Platform-agnostic dispatch for chat-platform inbound messages.
2//!
3//! Slack and Teams differ only at their edges — request verification, payload
4//! shape, and reply rendering. Everything between (identity, authorization,
5//! deterministic conversation context, per-user A2A token minting, the blocking
6//! `message/send` through the proxy, and reply extraction) is identical and
7//! lives here once. A per-platform route normalizes its wire payload into a
8//! [`MessagingInbound`] and calls [`dispatch_messaging`]; the returned
9//! [`DispatchOutcome`] is rendered back into the platform's UI by the route.
10//!
11//! The pipeline is **synchronous, spawned**: the route acks the platform within
12//! its timeout, then a spawned task runs this blocking dispatch and posts the
13//! reply. There is no responder job and no dispatch-state table — a stable
14//! [`ContextId`] (derived from the conversation) ties multi-turn history
15//! together instead.
16//!
17//! Copyright (c) systemprompt.io — Business Source License 1.1.
18//! See <https://systemprompt.io> for licensing details.
19
20mod 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};
29use systemprompt_traits::SenderIdentity;
30
31use a2a::{authenticated_user, build_a2a_request, mint_a2a_token, run_agent};
32use identity::resolve_or_link_user;
33
34static CLIENT: LazyLock<reqwest::Client> = LazyLock::new(reqwest::Client::new);
35
36#[must_use]
37pub fn http_client() -> reqwest::Client {
38    CLIENT.clone()
39}
40
41#[derive(Debug, Clone)]
42pub enum ReplyTarget {
43    Channel { id: String },
44    Url { url: String },
45}
46
47/// A surface-agnostic inbound message ready for dispatch. Per-platform routes
48/// build this from their normalized payload; the dispatch core never sees a
49/// Slack- or Teams-specific type.
50#[derive(Debug, Clone)]
51pub struct MessagingInbound {
52    pub platform: &'static str,
53    pub issuer: String,
54    pub org_id: String,
55    pub channel_id: String,
56    pub external_user_id: String,
57    pub text: String,
58    pub agent_name: AgentName,
59    pub entity: EntityRef,
60    pub reply: ReplyTarget,
61    pub sender: SenderIdentity,
62}
63
64#[derive(Debug, Clone)]
65pub enum DispatchOutcome {
66    Replied(String),
67    Denied(String),
68}
69
70/// Failures along the dispatch pipeline. This is an internal system surface;
71/// messages are deliberately descriptive for operator debugging.
72#[derive(Debug, thiserror::Error)]
73pub enum MessagingError {
74    #[error("identity resolution failed: {0}")]
75    Identity(String),
76    #[error("token minting failed: {0}")]
77    Token(String),
78    #[error("agent dispatch failed: {0}")]
79    Dispatch(String),
80    #[error("malformed agent response: {0}")]
81    Response(String),
82}
83
84impl MessagingError {
85    #[must_use]
86    pub fn user_message(&self) -> String {
87        let opaque = "Sorry — something went wrong handling that.";
88        if cfg!(feature = "test-api") {
89            format!("{opaque} ({self})")
90        } else {
91            opaque.to_owned()
92        }
93    }
94}
95
96pub async fn dispatch_messaging(
97    ctx: &AppContext,
98    inbound: MessagingInbound,
99) -> Result<DispatchOutcome, MessagingError> {
100    let user = resolve_or_link_user(
101        ctx,
102        &inbound.issuer,
103        &inbound.external_user_id,
104        &inbound.sender.claims(),
105    )
106    .await?;
107    let authed = authenticated_user(&user)?;
108
109    let context_id =
110        ContextId::derived_from_messaging(inbound.platform, &inbound.org_id, &inbound.channel_id);
111
112    let authz = AuthzRequest {
113        entity: inbound.entity.clone(),
114        user_id: user.id.clone(),
115        roles: user.roles.clone(),
116        attributes: std::collections::BTreeMap::new(),
117        trace_id: TraceId::generate(),
118        session_id: None,
119        context: AuthzContext::extension(
120            format!("{}.message", inbound.platform),
121            json!({ "channel": inbound.channel_id }),
122        ),
123        context_id: Some(context_id.clone()),
124        task_id: None,
125        act_chain: Vec::new(),
126    };
127    if let AuthzDecision::Deny { reason, policy } = ctx.authz_hook().evaluate(authz).await {
128        return Ok(DispatchOutcome::Denied(format!("{policy}: {reason}")));
129    }
130
131    let session_id = SessionId::new(uuid::Uuid::new_v4().to_string());
132    let token = mint_a2a_token(ctx, &authed, &session_id)?;
133
134    let request = build_a2a_request(&inbound, &authed, &session_id, &token, &context_id)?;
135    let reply = run_agent(ctx, inbound.agent_name.as_str(), request).await?;
136    Ok(DispatchOutcome::Replied(reply))
137}
138
139#[cfg(feature = "test-api")]
140pub mod test_api {
141    use systemprompt_agent::models::a2a::Task;
142    use systemprompt_models::auth::Permission;
143
144    #[must_use]
145    pub fn reply_text(task: Option<&Task>) -> String {
146        super::a2a::reply_text(task)
147    }
148
149    #[must_use]
150    pub fn permissions_for(roles: &[String]) -> Vec<Permission> {
151        super::a2a::permissions_for(roles)
152    }
153}