Skip to main content

ag_ui/event/
lifecycle.rs

1//! Run and step lifecycle: `RUN_*` and `STEP_*`.
2
3use serde::{Deserialize, Serialize};
4use serde_json::Value;
5
6use crate::event::BaseEvent;
7use crate::ids::{RunId, StepName, SubagentRunId, ThreadId};
8use crate::input::PROTOCOL_VERSION;
9use crate::input::RunAgentInput;
10use crate::outcome::RunOutcome;
11use crate::token_usage::TokenUsage;
12
13/// The first event of every run.
14#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
15#[serde(rename_all = "camelCase")]
16#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
17#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
18pub struct RunStartedEvent {
19    /// Timestamp and raw provider event.
20    #[serde(flatten)]
21    pub base: BaseEvent,
22    /// The conversation this run belongs to.
23    pub thread_id: ThreadId,
24    /// The run that is starting.
25    pub run_id: RunId,
26    /// The protocol version this producer speaks, independent of the input's
27    /// declaration. Absent only when reading a legacy stream.
28    #[serde(default, skip_serializing_if = "Option::is_none")]
29    pub protocol_version: Option<String>,
30    /// The run that spawned this one, for nested / delegated agents.
31    #[serde(default, skip_serializing_if = "Option::is_none")]
32    pub parent_run_id: Option<RunId>,
33    /// The request that started the run, echoed so a recorded stream replays
34    /// without the original HTTP body.
35    ///
36    /// Boxed: it is the largest payload in the protocol and is usually absent,
37    /// so inlining it would bloat every [`Event`](crate::event::Event).
38    #[serde(default, skip_serializing_if = "Option::is_none")]
39    pub input: Option<Box<RunAgentInput>>,
40}
41
42impl RunStartedEvent {
43    /// Starts a run.
44    pub fn new(thread_id: impl Into<ThreadId>, run_id: impl Into<RunId>) -> Self {
45        Self {
46            base: BaseEvent::default(),
47            thread_id: thread_id.into(),
48            run_id: run_id.into(),
49            protocol_version: Some(PROTOCOL_VERSION.to_owned()),
50            parent_run_id: None,
51            input: None,
52        }
53    }
54}
55
56/// The last event of a run that did not error.
57///
58/// "Finished" includes *paused*: an [`RunOutcome::Interrupt`] outcome means the
59/// agent is waiting on human input and the run continues on the next request.
60#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
61#[serde(rename_all = "camelCase")]
62#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
63#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
64pub struct RunFinishedEvent {
65    /// Timestamp and raw provider event.
66    #[serde(flatten)]
67    pub base: BaseEvent,
68    /// The conversation this run belongs to.
69    pub thread_id: ThreadId,
70    /// The run that finished.
71    pub run_id: RunId,
72    /// Agent-defined return value.
73    #[serde(default, skip_serializing_if = "crate::serde_util::is_none_or_null")]
74    pub result: Option<Value>,
75    /// How the run ended. Absent from producers that predate the interrupt
76    /// protocol, which consumers read as success. A JSON `null` also reads as
77    /// absent, for producers that serialize `None` rather than omitting it.
78    #[serde(default, skip_serializing_if = "Option::is_none")]
79    pub outcome: Option<RunOutcome>,
80    /// Token usage, one entry per `(provider, model)` the run invoked.
81    #[serde(default, skip_serializing_if = "Option::is_none")]
82    pub usage: Option<Vec<TokenUsage>>,
83}
84
85impl RunFinishedEvent {
86    /// Finishes a run without declaring an outcome (legacy shape).
87    pub fn new(thread_id: impl Into<ThreadId>, run_id: impl Into<RunId>) -> Self {
88        Self {
89            base: BaseEvent::default(),
90            thread_id: thread_id.into(),
91            run_id: run_id.into(),
92            result: None,
93            outcome: None,
94            usage: None,
95        }
96    }
97
98    /// Sets the outcome.
99    #[must_use]
100    pub fn with_outcome(mut self, outcome: RunOutcome) -> Self {
101        self.outcome = Some(outcome);
102        self
103    }
104
105    /// Sets the return value.
106    #[must_use]
107    pub fn with_result(mut self, result: impl Into<Value>) -> Self {
108        let result = result.into();
109        self.result = (!result.is_null()).then_some(result);
110        self
111    }
112
113    /// Sets the token usage.
114    #[must_use]
115    pub fn with_usage(mut self, usage: impl Into<Vec<TokenUsage>>) -> Self {
116        self.usage = Some(usage.into());
117        self
118    }
119}
120
121/// The run failed. No further events follow.
122#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
123#[serde(rename_all = "camelCase")]
124#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
125#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
126pub struct RunErrorEvent {
127    /// Timestamp and raw provider event.
128    #[serde(flatten)]
129    pub base: BaseEvent,
130    /// What went wrong, for a human.
131    pub message: String,
132    /// Machine-readable error code.
133    #[serde(default, skip_serializing_if = "Option::is_none")]
134    pub code: Option<String>,
135    /// Partial usage for a run that failed after some model calls completed.
136    #[serde(default, skip_serializing_if = "Option::is_none")]
137    pub usage: Option<Vec<TokenUsage>>,
138}
139
140impl RunErrorEvent {
141    /// Fails the run with a message.
142    pub fn new(message: impl Into<String>) -> Self {
143        Self {
144            base: BaseEvent::default(),
145            message: message.into(),
146            code: None,
147            usage: None,
148        }
149    }
150
151    /// Sets the error code.
152    #[must_use]
153    pub fn with_code(mut self, code: impl Into<String>) -> Self {
154        self.code = Some(code.into());
155        self
156    }
157}
158
159/// Opens a named step within a run.
160#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
161#[serde(rename_all = "camelCase")]
162#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
163#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
164pub struct StepStartedEvent {
165    /// Timestamp and raw provider event.
166    #[serde(flatten)]
167    pub base: BaseEvent,
168    /// The step that is starting.
169    pub step_name: StepName,
170    /// The subagent that opened the step; absent means the parent agent. A
171    /// JSON `null` is rejected — see [`crate::event::subagent`]. Steps are
172    /// scoped to the agent that opened them: a subagent cannot close the
173    /// parent's step, or a sibling's, so the same name may be open under two
174    /// owners at once.
175    #[serde(
176        default,
177        deserialize_with = "crate::serde_util::reject_null",
178        skip_serializing_if = "Option::is_none"
179    )]
180    pub subagent_run_id: Option<SubagentRunId>,
181}
182
183impl StepStartedEvent {
184    /// Starts a step.
185    pub fn new(step_name: impl Into<StepName>) -> Self {
186        Self {
187            base: BaseEvent::default(),
188            step_name: step_name.into(),
189            subagent_run_id: None,
190        }
191    }
192}
193
194/// Closes a named step.
195#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
196#[serde(rename_all = "camelCase")]
197#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
198#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
199pub struct StepFinishedEvent {
200    /// Timestamp and raw provider event.
201    #[serde(flatten)]
202    pub base: BaseEvent,
203    /// The step that finished.
204    pub step_name: StepName,
205    /// The subagent that closes the step; absent means the parent agent. A
206    /// JSON `null` is rejected — see [`crate::event::subagent`]. Must match
207    /// the owner that opened it, as on [`StepStartedEvent`].
208    #[serde(
209        default,
210        deserialize_with = "crate::serde_util::reject_null",
211        skip_serializing_if = "Option::is_none"
212    )]
213    pub subagent_run_id: Option<SubagentRunId>,
214}
215
216impl StepFinishedEvent {
217    /// Finishes a step.
218    pub fn new(step_name: impl Into<StepName>) -> Self {
219        Self {
220            base: BaseEvent::default(),
221            step_name: step_name.into(),
222            subagent_run_id: None,
223        }
224    }
225}