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    pub fn is_zero(&self) -> bool {
36        self.total_tokens == 0 && self.prompt_tokens == 0 && self.completion_tokens == 0
37    }
38
39    /// The tokens a budget charges: the total, or prompt and completion when
40    /// the provider reported no total (never wrapping on bogus numbers).
41    pub fn billable_tokens(&self) -> u64 {
42        self.total_tokens.max(self.prompt_tokens.saturating_add(self.completion_tokens))
43    }
44}
45
46/// Why a run or node paused.
47#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
48pub struct PauseReason {
49    /// Frame of the node that requested the pause (empty for external pauses).
50    pub frame: FrameId,
51    /// Node that requested the pause, if any.
52    pub node_id: Option<String>,
53    /// Machine-readable kind, e.g. `human_input`, `external`, `approval`.
54    pub kind: String,
55    /// Free-form details (form definition, message, ...).
56    #[serde(default)]
57    pub data: Value,
58}
59
60/// A run event.
61#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
62#[serde(tag = "type", rename_all = "snake_case")]
63#[non_exhaustive]
64pub enum Event {
65    RunStarted {
66        run_id: String,
67        resumed: bool,
68    },
69    NodeStarted {
70        frame: FrameId,
71        node_id: std::sync::Arc<str>,
72        exec_id: std::sync::Arc<str>,
73        kind: std::sync::Arc<str>,
74        title: std::sync::Arc<str>,
75        attempt: u32,
76    },
77    /// Incremental output, e.g. LLM tokens for output `field`.
78    NodeChunk {
79        frame: FrameId,
80        node_id: std::sync::Arc<str>,
81        exec_id: std::sync::Arc<str>,
82        /// Output field the chunk belongs to. Shared: nodes that stream many
83        /// chunks reuse one allocation (see [`crate::NodeContext::chunk_shared`]).
84        field: std::sync::Arc<str>,
85        chunk: String,
86    },
87    /// Structured progress emitted by a node (agent steps, tool calls, iteration progress...).
88    NodeProgress {
89        frame: FrameId,
90        node_id: std::sync::Arc<str>,
91        exec_id: std::sync::Arc<str>,
92        name: String,
93        data: Value,
94    },
95    NodeRetry {
96        frame: FrameId,
97        node_id: std::sync::Arc<str>,
98        exec_id: std::sync::Arc<str>,
99        attempt: u32,
100        error: String,
101        delay_ms: u64,
102    },
103    NodeSucceeded {
104        frame: FrameId,
105        node_id: std::sync::Arc<str>,
106        exec_id: std::sync::Arc<str>,
107        /// The node's outputs, shared with its pool namespace (cloning is cheap).
108        outputs: Variables,
109        /// Selected branch handle for branch nodes.
110        #[serde(skip_serializing_if = "Option::is_none")]
111        branch: Option<String>,
112        #[serde(skip_serializing_if = "Option::is_none")]
113        usage: Option<Usage>,
114        #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
115        metadata: IndexMap<String, Value>,
116        elapsed_ms: u64,
117    },
118    /// A node failed. `handled` is true when its error strategy kept the run going.
119    NodeFailed {
120        frame: FrameId,
121        node_id: std::sync::Arc<str>,
122        exec_id: std::sync::Arc<str>,
123        error: String,
124        error_type: String,
125        handled: bool,
126        /// Outputs committed by the error strategy (`error_message`, defaults...).
127        #[serde(default, skip_serializing_if = "Variables::is_empty")]
128        outputs: Variables,
129        elapsed_ms: u64,
130    },
131    /// The node will not run because every incoming path was skipped.
132    NodeSkipped {
133        frame: FrameId,
134        node_id: std::sync::Arc<str>,
135    },
136    NodePaused {
137        frame: FrameId,
138        node_id: std::sync::Arc<str>,
139        exec_id: std::sync::Arc<str>,
140        reason: PauseReason,
141    },
142    /// A node wrote a variable outside its own outputs (assigner, conversation variable...).
143    VariableUpdated {
144        frame: FrameId,
145        node_id: std::sync::Arc<str>,
146        selector: Selector,
147        value: Value,
148    },
149    RunSucceeded {
150        outputs: IndexMap<String, Value>,
151        usage: Usage,
152        /// Failures handled by an error strategy (non-zero = partial success).
153        handled_errors: u32,
154        elapsed_ms: u64,
155    },
156    RunFailed {
157        error: String,
158        /// Machine-readable category: `invalid_input` (bad run input or resume
159        /// data), `snapshot_mismatch`, `limit_exceeded` (steps / duration / depth),
160        /// `internal`, or the failing node's own error type (e.g. `timeout`,
161        /// `http`, `model`).
162        #[serde(default)]
163        error_type: String,
164        usage: Usage,
165        elapsed_ms: u64,
166    },
167    RunAborted {
168        reason: String,
169        elapsed_ms: u64,
170    },
171    /// The run paused. Persist `snapshot` and pass it back to resume.
172    RunPaused {
173        reasons: Vec<PauseReason>,
174        snapshot: Box<Snapshot>,
175    },
176}
177
178impl Event {
179    /// Whether this is the final event of a run.
180    pub fn is_terminal(&self) -> bool {
181        matches!(
182            self,
183            Event::RunSucceeded { .. } | Event::RunFailed { .. } | Event::RunAborted { .. } | Event::RunPaused { .. }
184        )
185    }
186
187    /// Frame of node-level events.
188    pub fn frame(&self) -> Option<&FrameId> {
189        match self {
190            Event::NodeStarted { frame, .. }
191            | Event::NodeChunk { frame, .. }
192            | Event::NodeProgress { frame, .. }
193            | Event::NodeRetry { frame, .. }
194            | Event::NodeSucceeded { frame, .. }
195            | Event::NodeFailed { frame, .. }
196            | Event::NodeSkipped { frame, .. }
197            | Event::NodePaused { frame, .. }
198            | Event::VariableUpdated { frame, .. } => Some(frame),
199            _ => None,
200        }
201    }
202}