systemprompt-api 0.43.0

Axum-based HTTP server and API gateway for systemprompt.io AI governance infrastructure. Exposes governed agents, MCP, A2A, and admin endpoints with rate limiting and RBAC.
Documentation
//! Persistence of gateway request lifecycle to the AI-request audit trail.
//!
//! [`GatewayAudit`] opens a record when a request arrives (see the `open`
//! submodule), records the canonical messages and request payload, then closes
//! it on completion with token usage, resolved cost, latency, captured tool
//! calls, and the response payload (see the `complete` submodule) — or marks it
//! failed. [`GatewayRequestContext`] carries the identifiers and routing
//! metadata bound to a single request.
//!
//! Copyright (c) systemprompt.io — Business Source License 1.1.
//! See <https://systemprompt.io> for licensing details.

mod complete;
mod message_text;
mod open;
pub mod payload;

#[cfg(feature = "test-api")]
pub mod test_api {
    pub use super::message_text::flatten_message_content;
}

use std::sync::{Arc, Mutex};
use std::time::Instant;

use anyhow::Result;
use systemprompt_ai::models::RequestStatus;
use systemprompt_ai::repository::{AiRequestPayloadRepository, AiRequestRepository};
use systemprompt_identifiers::{
    AiRequestId, ClientId, ContextId, GatewayConversationId, SessionId, TraceId, UserId,
};
use systemprompt_security::policy::types::AccessScope;

#[derive(Debug, Clone)]
pub struct GatewayRequestContext {
    pub ai_request_id: AiRequestId,
    pub user_id: UserId,
    pub session_id: Option<SessionId>,
    pub context_id: ContextId,
    pub gateway_conversation_id: Option<GatewayConversationId>,
    pub trace_id: Option<TraceId>,
    // Why: governance policies read the caller's tier; an API key carries no
    // roles and is therefore `Unknown`.
    pub access_scope: AccessScope,
    pub client_id: Option<ClientId>,
    pub provider: String,
    pub model: String,
    pub requested_model: Option<String>,
    pub max_tokens: Option<u32>,
    pub is_streaming: bool,
    pub wire_protocol: String,
}

#[expect(
    missing_debug_implementations,
    reason = "service type holds repository clients that intentionally do not implement Debug"
)]
pub struct GatewayAudit {
    requests: Arc<AiRequestRepository>,
    payloads: Arc<AiRequestPayloadRepository>,
    context_materializer: systemprompt_traits::DynContextMaterializer,
    pub ctx: GatewayRequestContext,
    served_model: Mutex<Option<String>>,
    started_at: Instant,
}

impl GatewayAudit {
    pub fn new(repos: &super::GatewayRepositories, ctx: GatewayRequestContext) -> Self {
        Self {
            requests: Arc::clone(&repos.requests),
            payloads: Arc::clone(&repos.payloads),
            context_materializer: Arc::clone(&repos.context_materializer),
            ctx,
            served_model: Mutex::new(None),
            started_at: Instant::now(),
        }
    }

    pub async fn set_served_model(&self, model: &str) {
        if model.is_empty() || model == self.ctx.model {
            return;
        }
        if let Ok(mut slot) = self.served_model.lock() {
            *slot = Some(model.to_owned());
        }
        if let Err(e) = self
            .requests
            .update_model(&self.ctx.ai_request_id, model)
            .await
        {
            tracing::warn!(error = %e, "update_model failed");
        }
    }

    pub async fn set_prepared_body_digest(&self, body: &[u8]) {
        let sha256 = payload::digest_hex(body);
        if let Err(e) = self
            .payloads
            .upsert_prepared_sha256(&self.ctx.ai_request_id, &sha256)
            .await
        {
            tracing::warn!(error = %e, ai_request_id = %self.ctx.ai_request_id, "prepared body digest write failed");
        }
    }

    pub async fn set_system_prompt_override(&self, descriptor: &str) {
        if let Err(e) = self
            .requests
            .update_system_prompt_override(&self.ctx.ai_request_id, descriptor)
            .await
        {
            tracing::warn!(error = %e, "update_system_prompt_override failed");
        }
    }

    pub async fn set_route_match(&self, descriptor: &str) {
        if let Err(e) = self
            .requests
            .update_route_match(&self.ctx.ai_request_id, descriptor)
            .await
        {
            tracing::warn!(error = %e, "update_route_match failed");
        }
    }

    pub async fn fail(&self, error: &str) -> Result<()> {
        if let Err(e) = self
            .requests
            .update_error(&self.ctx.ai_request_id, RequestStatus::Failed, error)
            .await
        {
            tracing::warn!(error = %e, "audit fail update failed");
        }
        tracing::info!(
            ai_request_id = %self.ctx.ai_request_id,
            user_id = %self.ctx.user_id,
            provider = %self.ctx.provider,
            model = %self.ctx.model,
            error,
            "Gateway audit: request failed"
        );
        Ok(())
    }
}