ag-ui 1.0.0

Rust SDK for AG-UI 1.0 with protocol types, SSE, a server runtime for hosting agents, and a client runtime for consuming them.
Documentation
//! Run outcomes and the human-in-the-loop interrupt protocol.
//!
//! A run does not only end in success or error. It can also *pause*: the agent
//! emits `RUN_FINISHED` with an [`RunOutcome::Interrupt`] outcome listing one or
//! more [`Interrupt`]s, the client collects the answers, and the next request
//! resumes the run by passing [`ResumeEntry`] values in
//! [`RunAgentInput::resume`](crate::input::RunAgentInput::resume).

use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::JsonObject;
use crate::error::{Error, Result};
use crate::ids::{SubagentRunId, ToolCallId};

/// A request for human input that pauses the run.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
pub struct Interrupt {
    /// Correlation id — echoed back as
    /// [`ResumeEntry::interrupt_id`] when the run resumes.
    pub id: String,
    /// Machine-readable reason, for example `"tool_approval"`.
    pub reason: String,
    /// Human-readable prompt to show the user.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub message: Option<String>,
    /// The tool call awaiting approval, when the interrupt is about one.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tool_call_id: Option<ToolCallId>,
    /// JSON Schema the resume payload must satisfy — lets a client render a
    /// form for the answer.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[cfg_attr(
        feature = "schemars",
        schemars(with = "Option<std::collections::BTreeMap<String, serde_json::Value>>")
    )]
    #[cfg_attr(feature = "utoipa", schema(value_type = Option<Object>))]
    pub response_schema: Option<JsonObject>,
    /// When the interrupt stops being answerable, as an ISO-8601 timestamp.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub expires_at: Option<String>,
    /// Integration-specific extras.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[cfg_attr(
        feature = "schemars",
        schemars(with = "Option<std::collections::BTreeMap<String, serde_json::Value>>")
    )]
    #[cfg_attr(feature = "utoipa", schema(value_type = Option<Object>))]
    pub metadata: Option<JsonObject>,
    /// The subagent whose work raised this interrupt, when it was raised
    /// inside one — absent for a root-raised interrupt. Attribution lives on
    /// each interrupt rather than on `RUN_FINISHED` because one run can carry
    /// interrupts from several subagents; a client uses it to render the
    /// approval request inside that subagent's group. A JSON `null` is
    /// rejected — see [`crate::event::subagent`].
    #[serde(
        default,
        deserialize_with = "crate::serde_util::reject_null",
        skip_serializing_if = "Option::is_none"
    )]
    pub subagent_run_id: Option<SubagentRunId>,
}

impl Interrupt {
    /// Builds an interrupt from its two required fields.
    pub fn new(id: impl Into<String>, reason: impl Into<String>) -> Self {
        Self {
            id: id.into(),
            reason: reason.into(),
            ..Default::default()
        }
    }

    /// Sets the prompt to show the user.
    ///
    /// ```
    /// use ag_ui::Interrupt;
    ///
    /// let interrupt = Interrupt::new("i-1", "tool_approval")
    ///     .with_message("Delete the staging database?")
    ///     .with_tool_call_id("call-7");
    /// assert_eq!(interrupt.message.as_deref(), Some("Delete the staging database?"));
    /// assert_eq!(interrupt.tool_call_id.as_ref().map(|id| id.as_str()), Some("call-7"));
    /// ```
    #[must_use]
    pub fn with_message(mut self, message: impl Into<String>) -> Self {
        self.message = Some(message.into());
        self
    }

    /// Names the tool call this interrupt asks to approve.
    #[must_use]
    pub fn with_tool_call_id(mut self, tool_call_id: impl Into<ToolCallId>) -> Self {
        self.tool_call_id = Some(tool_call_id.into());
        self
    }

    /// Sets the JSON Schema the resume payload must satisfy.
    #[must_use]
    pub fn with_response_schema(mut self, schema: JsonObject) -> Self {
        self.response_schema = Some(schema);
        self
    }

    /// Attributes the interrupt to the subagent that raised it.
    #[must_use]
    pub fn with_subagent_run_id(mut self, subagent_run_id: impl Into<SubagentRunId>) -> Self {
        self.subagent_run_id = Some(subagent_run_id.into());
        self
    }
}

/// How a run ended.
///
/// The field is optional on `RUN_FINISHED`: producers that predate the
/// interrupt protocol omit it entirely, which consumers must read as success.
#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(tag = "type", rename_all = "lowercase", deny_unknown_fields)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
pub enum RunOutcome {
    /// The run completed.
    Success,
    /// The run completed with frontend tool calls still awaiting answers.
    ///
    /// This has the same wire discriminator as [`Self::Success`]. The separate
    /// Rust variant keeps existing `RunOutcome::Success` callers working while
    /// preserving the list supplied by an AG-UI 1.0 producer.
    #[serde(rename = "success")]
    SuccessWithPendingToolCalls {
        /// Tool calls to answer in the next run's input, in call order.
        #[serde(rename = "pendingToolCallIds")]
        pending_tool_call_ids: Vec<ToolCallId>,
    },
    /// The run is paused, waiting on the answers to `interrupts`.
    Interrupt {
        /// The pending requests. The protocol requires at least one; see
        /// [`RunOutcome::validate`].
        interrupts: Vec<Interrupt>,
    },
    /// The run was stopped before completion without an execution error.
    Cancelled,
}

// A struct-shaped success variant makes serde enforce unknown-field rejection;
// derive treats an internally tagged unit variant as an ignored payload.
impl<'de> Deserialize<'de> for RunOutcome {
    fn deserialize<D: serde::Deserializer<'de>>(
        deserializer: D,
    ) -> std::result::Result<Self, D::Error> {
        #[derive(Deserialize)]
        #[serde(tag = "type", rename_all = "lowercase", deny_unknown_fields)]
        enum Wire {
            Success {
                #[serde(
                    rename = "pendingToolCallIds",
                    default,
                    deserialize_with = "crate::serde_util::reject_null"
                )]
                pending_tool_call_ids: Option<Vec<ToolCallId>>,
            },
            Interrupt {
                interrupts: Vec<Interrupt>,
            },
            Cancelled {},
        }
        Ok(match Wire::deserialize(deserializer)? {
            Wire::Success {
                pending_tool_call_ids: Some(pending_tool_call_ids),
            } => Self::SuccessWithPendingToolCalls {
                pending_tool_call_ids,
            },
            Wire::Success {
                pending_tool_call_ids: None,
            } => Self::Success,
            Wire::Interrupt { interrupts } => Self::Interrupt { interrupts },
            Wire::Cancelled {} => Self::Cancelled,
        })
    }
}

impl RunOutcome {
    /// A successful run with frontend tool calls to answer in the next input.
    pub fn success_with_pending_tool_calls(
        ids: impl IntoIterator<Item = impl Into<ToolCallId>>,
    ) -> Self {
        Self::SuccessWithPendingToolCalls {
            pending_tool_call_ids: ids.into_iter().map(Into::into).collect(),
        }
    }

    /// Builds an interrupt outcome.
    pub fn interrupt(interrupts: impl Into<Vec<Interrupt>>) -> Self {
        Self::Interrupt {
            interrupts: interrupts.into(),
        }
    }

    /// Whether the run is paused rather than finished.
    pub const fn is_interrupt(&self) -> bool {
        matches!(self, Self::Interrupt { .. })
    }

    /// Whether execution stopped without completing or failing.
    pub const fn is_cancelled(&self) -> bool {
        matches!(self, Self::Cancelled)
    }

    /// Frontend tool calls still awaiting answers, in call order.
    pub fn pending_tool_call_ids(&self) -> &[ToolCallId] {
        match self {
            Self::SuccessWithPendingToolCalls {
                pending_tool_call_ids,
            } => pending_tool_call_ids,
            _ => &[],
        }
    }

    /// The pending interrupts, or an empty slice for a success outcome.
    pub fn interrupts(&self) -> &[Interrupt] {
        match self {
            Self::Interrupt { interrupts } => interrupts,
            _ => &[],
        }
    }

    /// Checks that an interrupt outcome carries at least one interrupt and each ID is unique.
    ///
    /// Deserializing does not enforce this, so that a stray empty array from a
    /// buggy producer surfaces as a protocol error you can log rather than as
    /// an unparseable event that kills the stream.
    pub fn validate(&self) -> Result<()> {
        match self.interrupt_error() {
            Some(reason) => Err(Error::Protocol(reason)),
            None => Ok(()),
        }
    }

    pub(crate) fn interrupt_error(&self) -> Option<String> {
        let Self::Interrupt { interrupts } = self else {
            return None;
        };
        if interrupts.is_empty() {
            return Some("RUN_FINISHED outcome `interrupt` requires at least one interrupt".into());
        }
        let mut seen = std::collections::HashSet::new();
        let repeated = interrupts.iter().find(|entry| !seen.insert(&entry.id))?;
        Some(format!(
            "RUN_FINISHED carries interrupt id \"{}\" more than once: an interrupt's id is unique within its run",
            crate::serde_util::excerpt(&repeated.id, false)
        ))
    }
}

/// How the client answered one interrupt.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
pub enum ResumeStatus {
    /// The user answered; `payload` carries the answer.
    Resolved,
    /// The user declined or the request timed out.
    Cancelled,
}

impl ResumeStatus {
    /// The status string as it appears on the wire.
    pub const fn as_str(&self) -> &'static str {
        match self {
            Self::Resolved => "resolved",
            Self::Cancelled => "cancelled",
        }
    }
}

/// One answer to one [`Interrupt`], sent on the resuming request.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
pub struct ResumeEntry {
    /// The [`Interrupt::id`] being answered.
    pub interrupt_id: String,
    /// Whether the user answered or declined.
    pub status: ResumeStatus,
    /// The answer. Shape is up to the agent; when the interrupt supplied a
    /// `responseSchema`, this should satisfy it. For a tool approval that was
    /// edited before approval, agents that advertise `approveWithEdits` expect
    /// `{"editedArgs": …}` here. `Some(Value::Null)` is written as an
    /// omitted field, which is how AG-UI 1.0 spells no answer.
    #[serde(default, skip_serializing_if = "crate::serde_util::is_none_or_null")]
    pub payload: Option<Value>,
    /// Envelope data about the answer — signatures, routing keys — as opposed
    /// to `payload`, which is the answer the agent asked for and will act on.
    /// A request field, so nothing merges into it. Absent or an object — a
    /// JSON `null` is rejected. See [`crate::metadata`].
    #[serde(
        default,
        deserialize_with = "crate::serde_util::reject_null",
        skip_serializing_if = "Option::is_none"
    )]
    #[cfg_attr(
        feature = "schemars",
        schemars(with = "Option<std::collections::BTreeMap<String, serde_json::Value>>")
    )]
    #[cfg_attr(feature = "utoipa", schema(value_type = Option<Object>))]
    pub metadata: Option<JsonObject>,
}

impl ResumeEntry {
    /// Answers an interrupt with a payload.
    pub fn resolved(interrupt_id: impl Into<String>, payload: impl Into<Value>) -> Self {
        Self {
            interrupt_id: interrupt_id.into(),
            status: ResumeStatus::Resolved,
            payload: Some(payload.into()),
            metadata: None,
        }
    }

    /// Declines an interrupt.
    pub fn cancelled(interrupt_id: impl Into<String>) -> Self {
        Self {
            interrupt_id: interrupt_id.into(),
            status: ResumeStatus::Cancelled,
            payload: None,
            metadata: None,
        }
    }

    /// Attaches envelope metadata to the answer.
    #[must_use]
    pub fn with_metadata(mut self, metadata: JsonObject) -> Self {
        self.metadata = Some(metadata);
        self
    }
}