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