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