Skip to main content

graphrt_core/
event.rs

1//! Events emitted by a run.
2//!
3//! Events are plain serializable data (tagged by `type`), so they can be
4//! streamed over SSE / websockets as-is. Secrets inside values are masked by
5//! [`crate::value::Value`]'s serializer.
6
7use indexmap::IndexMap;
8use serde::{Deserialize, Serialize};
9
10use crate::pool::Selector;
11use crate::snapshot::Snapshot;
12use crate::value::Value;
13use crate::variables::Variables;
14
15/// Identifies an execution frame. The root frame is the empty string; child
16/// frames are `"<container_node>[<index>]"` segments joined by `/`, e.g.
17/// `"iter[2]/loop[0]"`.
18pub type FrameId = std::sync::Arc<str>;
19
20/// Token usage reported by model-calling nodes.
21#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
22pub struct Usage {
23    pub prompt_tokens: u64,
24    pub completion_tokens: u64,
25    pub total_tokens: u64,
26}
27
28impl Usage {
29    pub fn add(&mut self, other: &Usage) {
30        self.prompt_tokens = self.prompt_tokens.saturating_add(other.prompt_tokens);
31        self.completion_tokens = self.completion_tokens.saturating_add(other.completion_tokens);
32        self.total_tokens = self.total_tokens.saturating_add(other.total_tokens);
33    }
34
35    /// Each count less `other`'s, not below zero.
36    #[must_use]
37    pub fn saturating_sub(&self, other: &Usage) -> Usage {
38        Usage {
39            prompt_tokens: self.prompt_tokens.saturating_sub(other.prompt_tokens),
40            completion_tokens: self.completion_tokens.saturating_sub(other.completion_tokens),
41            total_tokens: self.total_tokens.saturating_sub(other.total_tokens),
42        }
43    }
44
45    /// Each count the larger of this and `other`'s.
46    #[must_use]
47    pub fn at_least(&self, other: &Usage) -> Usage {
48        Usage {
49            prompt_tokens: self.prompt_tokens.max(other.prompt_tokens),
50            completion_tokens: self.completion_tokens.max(other.completion_tokens),
51            total_tokens: self.total_tokens.max(other.total_tokens),
52        }
53    }
54
55    pub fn is_zero(&self) -> bool {
56        self.total_tokens == 0 && self.prompt_tokens == 0 && self.completion_tokens == 0
57    }
58
59    /// The tokens a budget charges: the total, or prompt and completion when
60    /// the provider reported no total (never wrapping on bogus numbers).
61    pub fn billable_tokens(&self) -> u64 {
62        self.total_tokens.max(self.prompt_tokens.saturating_add(self.completion_tokens))
63    }
64}
65
66/// Why a run or node paused.
67#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
68pub struct PauseReason {
69    /// Frame of the node that requested the pause (empty for external pauses).
70    pub frame: FrameId,
71    /// Node that requested the pause, if any.
72    pub node_id: Option<String>,
73    /// Machine-readable kind, e.g. `human_input`, `external`, `approval`.
74    pub kind: String,
75    /// Free-form details (form definition, message, ...).
76    #[serde(default)]
77    pub data: Value,
78}
79
80/// A run event.
81#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
82#[serde(tag = "type", rename_all = "snake_case")]
83#[non_exhaustive]
84pub enum Event {
85    RunStarted {
86        run_id: String,
87        resumed: bool,
88    },
89    NodeStarted {
90        frame: FrameId,
91        node_id: std::sync::Arc<str>,
92        exec_id: std::sync::Arc<str>,
93        kind: std::sync::Arc<str>,
94        title: std::sync::Arc<str>,
95        attempt: u32,
96    },
97    /// Incremental output, e.g. LLM tokens for output `field`.
98    NodeChunk {
99        frame: FrameId,
100        node_id: std::sync::Arc<str>,
101        exec_id: std::sync::Arc<str>,
102        /// Output field the chunk belongs to. Shared: nodes that stream many
103        /// chunks reuse one allocation (see [`crate::NodeContext::chunk_shared`]).
104        field: std::sync::Arc<str>,
105        chunk: String,
106    },
107    /// Structured progress emitted by a node (agent steps, tool calls, iteration progress...).
108    NodeProgress {
109        frame: FrameId,
110        node_id: std::sync::Arc<str>,
111        exec_id: std::sync::Arc<str>,
112        name: String,
113        data: Value,
114    },
115    NodeRetry {
116        frame: FrameId,
117        node_id: std::sync::Arc<str>,
118        exec_id: std::sync::Arc<str>,
119        attempt: u32,
120        error: String,
121        delay_ms: u64,
122    },
123    NodeSucceeded {
124        frame: FrameId,
125        node_id: std::sync::Arc<str>,
126        exec_id: std::sync::Arc<str>,
127        /// The node's outputs, shared with its pool namespace (cloning is cheap).
128        outputs: Variables,
129        /// Selected branch handle for branch nodes.
130        #[serde(skip_serializing_if = "Option::is_none")]
131        branch: Option<String>,
132        #[serde(skip_serializing_if = "Option::is_none")]
133        usage: Option<Usage>,
134        #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
135        metadata: IndexMap<String, Value>,
136        elapsed_ms: u64,
137    },
138    /// A node failed. `handled` is true when its error strategy kept the run going.
139    NodeFailed {
140        frame: FrameId,
141        node_id: std::sync::Arc<str>,
142        exec_id: std::sync::Arc<str>,
143        error: String,
144        error_type: String,
145        handled: bool,
146        /// Outputs committed by the error strategy (`error_message`, defaults...).
147        #[serde(default, skip_serializing_if = "Variables::is_empty")]
148        outputs: Variables,
149        elapsed_ms: u64,
150    },
151    /// The node will not run because every incoming path was skipped.
152    NodeSkipped {
153        frame: FrameId,
154        node_id: std::sync::Arc<str>,
155    },
156    NodePaused {
157        frame: FrameId,
158        node_id: std::sync::Arc<str>,
159        exec_id: std::sync::Arc<str>,
160        reason: PauseReason,
161    },
162    /// A node wrote a variable outside its own outputs (assigner, conversation variable...).
163    VariableUpdated {
164        frame: FrameId,
165        node_id: std::sync::Arc<str>,
166        selector: Selector,
167        value: Value,
168    },
169    RunSucceeded {
170        outputs: IndexMap<String, Value>,
171        usage: Usage,
172        /// Failures handled by an error strategy (non-zero = partial success).
173        handled_errors: u32,
174        elapsed_ms: u64,
175    },
176    RunFailed {
177        error: String,
178        /// Machine-readable category: `invalid_input` (bad run input or resume
179        /// data), `snapshot_mismatch`, `limit_exceeded` (steps / duration / depth),
180        /// `internal`, or the failing node's own error type (e.g. `timeout`,
181        /// `http`, `model`).
182        #[serde(default)]
183        error_type: String,
184        usage: Usage,
185        elapsed_ms: u64,
186    },
187    RunAborted {
188        reason: String,
189        elapsed_ms: u64,
190    },
191    /// The run paused. Persist `snapshot` and pass it back to resume.
192    RunPaused {
193        reasons: Vec<PauseReason>,
194        snapshot: Box<Snapshot>,
195    },
196}
197
198impl Event {
199    /// Whether this is the final event of a run.
200    pub fn is_terminal(&self) -> bool {
201        matches!(
202            self,
203            Event::RunSucceeded { .. } | Event::RunFailed { .. } | Event::RunAborted { .. } | Event::RunPaused { .. }
204        )
205    }
206
207    /// Frame of node-level events.
208    pub fn frame(&self) -> Option<&FrameId> {
209        match self {
210            Event::NodeStarted { frame, .. }
211            | Event::NodeChunk { frame, .. }
212            | Event::NodeProgress { frame, .. }
213            | Event::NodeRetry { frame, .. }
214            | Event::NodeSucceeded { frame, .. }
215            | Event::NodeFailed { frame, .. }
216            | Event::NodeSkipped { frame, .. }
217            | Event::NodePaused { frame, .. }
218            | Event::VariableUpdated { frame, .. } => Some(frame),
219            _ => None,
220        }
221    }
222}