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
20pub mod a2a;
21pub mod identity;
22
23use std::sync::LazyLock;
24
25use serde_json::json;
26use systemprompt_identifiers::{Actor, 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    #[expect(
87        clippy::unused_self,
88        reason = "opaque by contract: no part of the error may reach the caller"
89    )]
90    pub fn user_message(&self) -> String {
91        "Sorry — something went wrong handling that.".to_owned()
92    }
93}
94
95pub async fn dispatch_messaging(
96    ctx: &AppContext,
97    inbound: MessagingInbound,
98) -> Result<DispatchOutcome, MessagingError> {
99    let user = resolve_or_link_user(
100        ctx,
101        &inbound.issuer,
102        &inbound.external_user_id,
103        &inbound.sender.claims(),
104    )
105    .await?;
106    let authed = authenticated_user(&user)?;
107
108    let context_id =
109        ContextId::derived_from_messaging(inbound.platform, &inbound.org_id, &inbound.channel_id);
110
111    let authz = AuthzRequest {
112        entity: inbound.entity.clone(),
113        user_id: user.id.clone(),
114        actor: Some(Actor::user(user.id.clone())),
115        client_id: None,
116        access_scope: None,
117        roles: user.roles.clone(),
118        attributes: std::collections::BTreeMap::new(),
119        trace_id: TraceId::generate(),
120        session_id: None,
121        context: AuthzContext::extension(
122            format!("{}.message", inbound.platform),
123            json!({ "channel": inbound.channel_id }),
124        ),
125        context_id: Some(context_id.clone()),
126        task_id: None,
127        act_chain: Vec::new(),
128    };
129    if let AuthzDecision::Deny { reason, policy } = ctx.authz_hook().evaluate(authz).await {
130        return Ok(DispatchOutcome::Denied(format!("{policy}: {reason}")));
131    }
132
133    let session_id = SessionId::new(uuid::Uuid::new_v4().to_string());
134    let token = mint_a2a_token(ctx, &authed, &session_id)?;
135
136    let request = build_a2a_request(&inbound, &authed, &session_id, &token, &context_id)?;
137    let reply = run_agent(ctx, inbound.agent_name.as_str(), request).await?;
138    Ok(DispatchOutcome::Replied(reply))
139}