weavegraph 0.7.0

Graph-driven, concurrent agent workflow framework with versioned state, deterministic barrier merges, and rich diagnostics.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
//! Event types emitted by workflow nodes and the framework.
use std::fmt;

use chrono::{DateTime, Utc};
use rustc_hash::FxHashMap;
use serde::{Deserialize, Serialize};
use serde_json::Value;

/// Emitted when the event stream closes, signalling clean stream termination.
pub const STREAM_END_SCOPE: &str = "__weavegraph_stream_end__";

/// Emitted after each [`AppRunner::invoke_next`](crate::runtimes::AppRunner::invoke_next) call
/// so subscribers can separate logical inputs without treating the bus as closed.
pub const INVOCATION_END_SCOPE: &str = "__weavegraph_invocation_end__";

/// Scope for internal framework diagnostics; filter on this to separate telemetry
/// from user-emitted node events.
pub const DIAGNOSTIC_SCOPE: &str = "__weavegraph_diagnostic__";

/// An event that can be emitted by a workflow node or by the framework itself.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub enum Event {
    /// A structured event from a workflow node.
    Node(NodeEvent),
    /// A framework-internal diagnostic.
    Diagnostic(DiagnosticEvent),
    /// An LLM streaming chunk, final marker, or error.
    LLM(LLMStreamingEvent),
}

impl Event {
    /// Construct a node event with only a scope and message.
    pub fn node_message(scope: impl Into<String>, message: impl Into<String>) -> Self {
        Event::Node(NodeEvent::new(None, None, scope.into(), message.into()))
    }

    /// Construct a node event with node ID, step, scope, and message.
    pub fn node_message_with_meta(
        node_id: impl Into<String>,
        step: u64,
        scope: impl Into<String>,
        message: impl Into<String>,
    ) -> Self {
        Event::Node(NodeEvent::new(
            Some(node_id.into()),
            Some(step),
            scope.into(),
            message.into(),
        ))
    }

    /// Construct a node event with full metadata including runtime labels.
    pub fn node_message_with_metadata(
        node_id: impl Into<String>,
        step: u64,
        scope: impl Into<String>,
        message: impl Into<String>,
        metadata: FxHashMap<String, Value>,
    ) -> Self {
        Event::Node(
            NodeEvent::new(
                Some(node_id.into()),
                Some(step),
                scope.into(),
                message.into(),
            )
            .with_metadata(metadata),
        )
    }

    /// Construct a diagnostic event.
    pub fn diagnostic(scope: impl Into<String>, message: impl Into<String>) -> Self {
        Event::Diagnostic(DiagnosticEvent {
            scope: scope.into(),
            message: message.into(),
        })
    }

    /// Returns the scope label for this event.
    pub fn scope_label(&self) -> Option<&str> {
        match self {
            Event::Node(n) => Some(n.scope()),
            Event::Diagnostic(d) => Some(d.scope()),
            Event::LLM(l) => Some(l.scope().as_ref()),
        }
    }

    /// Returns the primary message text.
    pub fn message(&self) -> &str {
        match self {
            Event::Node(n) => n.message(),
            Event::Diagnostic(d) => d.message(),
            Event::LLM(l) => l.chunk(),
        }
    }

    /// Serialises the event to a normalised JSON value.
    ///
    /// The returned object has the shape:
    /// ```json
    /// {
    ///   "type": "node" | "diagnostic" | "llm",
    ///   "scope": "<scope>",
    ///   "message": "<text>",
    ///   "timestamp": "<rfc3339>",
    ///   "metadata": { ... }
    /// }
    /// ```
    ///
    /// # Example
    ///
    /// ```
    /// use weavegraph::event_bus::Event;
    ///
    /// let event = Event::node_message_with_meta("router", 5, "routing", "Processing request");
    /// let json = event.to_json_value();
    ///
    /// assert_eq!(json["type"], "node");
    /// assert_eq!(json["scope"], "routing");
    /// assert_eq!(json["message"], "Processing request");
    /// assert_eq!(json["metadata"]["node_id"], "router");
    /// assert_eq!(json["metadata"]["step"], 5);
    /// ```
    pub fn to_json_value(&self) -> serde_json::Value {
        use serde_json::json;

        let (event_type, metadata, timestamp) = match self {
            Event::Node(n) => {
                let mut meta: serde_json::Map<String, Value> = n
                    .metadata()
                    .iter()
                    .map(|(k, v)| (k.clone(), v.clone()))
                    .collect();
                if let Some(id) = n.node_id() {
                    meta.insert("node_id".to_owned(), json!(id));
                }
                if let Some(step) = n.step() {
                    meta.insert("step".to_owned(), json!(step));
                }
                ("node", Value::Object(meta), Utc::now())
            }
            Event::Diagnostic(_) => ("diagnostic", json!({}), Utc::now()),
            Event::LLM(l) => {
                let mut meta: serde_json::Map<String, Value> = l
                    .metadata()
                    .iter()
                    .map(|(k, v)| (k.clone(), v.clone()))
                    .collect();
                if let Some(id) = l.session_id() {
                    meta.insert("session_id".to_owned(), json!(id));
                }
                if let Some(id) = l.node_id() {
                    meta.insert("node_id".to_owned(), json!(id));
                }
                if let Some(id) = l.stream_id() {
                    meta.insert("stream_id".to_owned(), json!(id));
                }
                meta.insert("is_final".to_owned(), json!(l.is_final()));
                ("llm", Value::Object(meta), l.timestamp())
            }
        };

        json!({
            "type": event_type,
            "scope": self.scope_label(),
            "message": self.message(),
            "timestamp": timestamp.to_rfc3339(),
            "metadata": metadata,
        })
    }

    /// Serialises the event to a compact JSON string.
    ///
    /// # Example
    ///
    /// ```
    /// use weavegraph::event_bus::Event;
    ///
    /// let event = Event::diagnostic("test", "message");
    /// let json_str = event.to_json_string().unwrap();
    /// assert!(json_str.contains("\"type\":\"diagnostic\""));
    /// ```
    pub fn to_json_string(&self) -> Result<String, serde_json::Error> {
        serde_json::to_string(&self.to_json_value())
    }

    /// Serialises the event to an indented JSON string.
    ///
    /// # Example
    ///
    /// ```
    /// use weavegraph::event_bus::Event;
    ///
    /// let event = Event::node_message("test", "hello");
    /// let json_str = event.to_json_pretty().unwrap();
    /// assert!(json_str.contains("  \"type\": \"node\""));
    /// ```
    pub fn to_json_pretty(&self) -> Result<String, serde_json::Error> {
        serde_json::to_string_pretty(&self.to_json_value())
    }
}

impl fmt::Display for Event {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Event::Node(n) => match (n.node_id(), n.step()) {
                (Some(id), Some(step)) => write!(f, "[{id}@{step}] {}", n.message()),
                (Some(id), None) => write!(f, "[{id}] {}", n.message()),
                (None, Some(step)) => write!(f, "[step {step}] {}", n.message()),
                (None, None) => write!(f, "{}", n.message()),
            },
            Event::Diagnostic(d) => write!(f, "{}", d.message()),
            Event::LLM(l) => {
                if let Some(id) = l.stream_id() {
                    write!(f, "[LLM {id}] {}", l.chunk())
                } else if let Some(id) = l.node_id() {
                    write!(f, "[LLM {id}] {}", l.chunk())
                } else {
                    write!(f, "{}", l.chunk())
                }
            }
        }
    }
}

/// A structured event emitted by a workflow node during execution.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub struct NodeEvent {
    node_id: Option<String>,
    step: Option<u64>,
    scope: String,
    message: String,
    #[serde(default)]
    metadata: FxHashMap<String, Value>,
}

impl NodeEvent {
    /// Create a new node event.
    pub fn new(node_id: Option<String>, step: Option<u64>, scope: String, message: String) -> Self {
        Self {
            node_id,
            step,
            scope,
            message,
            metadata: FxHashMap::default(),
        }
    }

    /// Returns the node ID, if set.
    pub fn node_id(&self) -> Option<&str> {
        self.node_id.as_deref()
    }

    /// Returns the step number at which this event was emitted, if set.
    pub fn step(&self) -> Option<u64> {
        self.step
    }

    /// Returns the scope label.
    pub fn scope(&self) -> &str {
        &self.scope
    }

    /// Returns the message text.
    pub fn message(&self) -> &str {
        &self.message
    }

    /// Returns the metadata map.
    pub fn metadata(&self) -> &FxHashMap<String, Value> {
        &self.metadata
    }

    /// Replace the metadata map and return `self`.
    pub fn with_metadata(mut self, metadata: FxHashMap<String, Value>) -> Self {
        self.metadata = metadata;
        self
    }
}

/// A framework-internal diagnostic event, emitted outside normal node execution.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub struct DiagnosticEvent {
    scope: String,
    message: String,
}

impl DiagnosticEvent {
    /// Returns the scope label.
    pub fn scope(&self) -> &str {
        &self.scope
    }

    /// Returns the diagnostic message text.
    pub fn message(&self) -> &str {
        &self.message
    }
}

/// Scope discriminant for LLM streaming events.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub enum LLMStreamingEventScope {
    /// An in-progress streaming session (default).
    Streaming,
    /// A single text chunk within a streaming response.
    Chunk,
    /// The final chunk, marking end-of-stream.
    Final,
    /// An error event that terminates the stream.
    Error,
}

impl AsRef<str> for LLMStreamingEventScope {
    fn as_ref(&self) -> &str {
        match self {
            Self::Streaming => "stream",
            Self::Chunk => "chunk",
            Self::Final => STREAM_END_SCOPE,
            Self::Error => "error",
        }
    }
}

/// An LLM event carrying a response chunk, a final marker, or an error.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub struct LLMStreamingEvent {
    session_id: Option<String>,
    node_id: Option<String>,
    stream_id: Option<String>,
    chunk: String,
    is_final: bool,
    scope: LLMStreamingEventScope,
    metadata: FxHashMap<String, Value>,
    timestamp: DateTime<Utc>,
}

impl LLMStreamingEvent {
    /// Return a builder for constructing a new event; `chunk` is the only required field.
    pub fn builder(chunk: impl Into<String>) -> LLMStreamingEventBuilder {
        LLMStreamingEventBuilder::new(chunk)
    }

    /// Create a partial-chunk event.
    pub fn chunk_event(
        session_id: Option<String>,
        node_id: Option<String>,
        stream_id: Option<String>,
        chunk: impl Into<String>,
        metadata: FxHashMap<String, Value>,
    ) -> Self {
        Self {
            session_id,
            node_id,
            stream_id,
            chunk: chunk.into(),
            is_final: false,
            scope: LLMStreamingEventScope::Chunk,
            metadata,
            timestamp: Utc::now(),
        }
    }

    /// Create a final-chunk event marking the end of the stream.
    pub fn final_event(
        session_id: Option<String>,
        node_id: Option<String>,
        stream_id: Option<String>,
        chunk: impl Into<String>,
        metadata: FxHashMap<String, Value>,
    ) -> Self {
        Self {
            session_id,
            node_id,
            stream_id,
            chunk: chunk.into(),
            is_final: true,
            scope: LLMStreamingEventScope::Final,
            metadata,
            timestamp: Utc::now(),
        }
    }

    /// Create an error event marking a failed streaming session.
    pub fn error_event(
        session_id: Option<String>,
        node_id: Option<String>,
        stream_id: Option<String>,
        error_message: impl Into<String>,
    ) -> Self {
        let metadata = [("severity".to_owned(), Value::String("error".to_owned()))]
            .into_iter()
            .collect();
        Self {
            session_id,
            node_id,
            stream_id,
            chunk: error_message.into(),
            is_final: true,
            scope: LLMStreamingEventScope::Error,
            metadata,
            timestamp: Utc::now(),
        }
    }

    /// Returns the session ID, if set.
    pub fn session_id(&self) -> Option<&str> {
        self.session_id.as_deref()
    }

    /// Returns the node ID, if set.
    pub fn node_id(&self) -> Option<&str> {
        self.node_id.as_deref()
    }

    /// Returns the stream ID, if set.
    pub fn stream_id(&self) -> Option<&str> {
        self.stream_id.as_deref()
    }

    /// Returns the text chunk.
    pub fn chunk(&self) -> &str {
        &self.chunk
    }

    /// Returns `true` if this is the final event in the stream.
    pub fn is_final(&self) -> bool {
        self.is_final
    }

    /// Returns the scope discriminant.
    pub fn scope(&self) -> &LLMStreamingEventScope {
        &self.scope
    }

    /// Returns the metadata map.
    pub fn metadata(&self) -> &FxHashMap<String, Value> {
        &self.metadata
    }

    /// Returns the event creation timestamp.
    pub fn timestamp(&self) -> DateTime<Utc> {
        self.timestamp
    }

    /// Replace the metadata map and return `self`.
    pub fn with_metadata(mut self, metadata: FxHashMap<String, Value>) -> Self {
        self.metadata = metadata;
        self
    }

    /// Replace the timestamp and return `self`.
    pub fn with_timestamp(mut self, timestamp: DateTime<Utc>) -> Self {
        self.timestamp = timestamp;
        self
    }
}

/// Builder for [`LLMStreamingEvent`].
///
/// Obtain one via [`LLMStreamingEvent::builder`]. All fields except `chunk` are optional;
/// `timestamp` defaults to [`Utc::now`] when [`build`](Self::build) is called.
pub struct LLMStreamingEventBuilder {
    session_id: Option<String>,
    node_id: Option<String>,
    stream_id: Option<String>,
    chunk: String,
    is_final: bool,
    scope: LLMStreamingEventScope,
    metadata: FxHashMap<String, Value>,
    timestamp: Option<DateTime<Utc>>,
}

impl LLMStreamingEventBuilder {
    fn new(chunk: impl Into<String>) -> Self {
        Self {
            session_id: None,
            node_id: None,
            stream_id: None,
            chunk: chunk.into(),
            is_final: false,
            scope: LLMStreamingEventScope::Streaming,
            metadata: FxHashMap::default(),
            timestamp: None,
        }
    }

    /// Set the session ID.
    pub fn session_id(mut self, id: impl Into<String>) -> Self {
        self.session_id = Some(id.into());
        self
    }

    /// Set the node ID.
    pub fn node_id(mut self, id: impl Into<String>) -> Self {
        self.node_id = Some(id.into());
        self
    }

    /// Set the stream ID.
    pub fn stream_id(mut self, id: impl Into<String>) -> Self {
        self.stream_id = Some(id.into());
        self
    }

    /// Mark the event as final.
    pub fn is_final(mut self, v: bool) -> Self {
        self.is_final = v;
        self
    }

    /// Set the scope discriminant (defaults to [`LLMStreamingEventScope::Streaming`]).
    pub fn scope(mut self, s: LLMStreamingEventScope) -> Self {
        self.scope = s;
        self
    }

    /// Set the metadata map.
    pub fn metadata(mut self, m: FxHashMap<String, Value>) -> Self {
        self.metadata = m;
        self
    }

    /// Fix the creation timestamp; defaults to [`Utc::now`] if omitted.
    pub fn timestamp(mut self, ts: DateTime<Utc>) -> Self {
        self.timestamp = Some(ts);
        self
    }

    /// Consume the builder and return the event.
    pub fn build(self) -> LLMStreamingEvent {
        LLMStreamingEvent {
            session_id: self.session_id,
            node_id: self.node_id,
            stream_id: self.stream_id,
            chunk: self.chunk,
            is_final: self.is_final,
            scope: self.scope,
            metadata: self.metadata,
            timestamp: self.timestamp.unwrap_or_else(Utc::now),
        }
    }
}