graphrt-core 0.2.0

Executor-agnostic graph runtime for agentic AI workflows: graph model, variable pool, scheduler, events, snapshots and built-in control nodes.
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
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
//! Ordered response streaming.
//!
//! The engine emits raw events as soon as they happen: tokens from parallel
//! LLM nodes interleave, and nodes finish in any order. A chat-style consumer
//! wants something different: the text of each response node (`answer`, and
//! optionally `end`) rendered in template order, with model tokens streamed
//! through as early as it is safe to do so.
//!
//! [`ResponseAssembler`] is a consumer-side transducer that does exactly that:
//!
//! ```ignore
//! let mut assembler = ResponseAssembler::new(engine.graph());
//! while let Some(event) = run.next().await {
//!     for chunk in assembler.push(&event) {
//!         print!("{}", chunk.text);
//!     }
//! }
//! ```
//!
//! ## Rules
//!
//! - Only response nodes of the **root scope** are assembled. Events from child
//!   frames (iteration / loop bodies) are ignored, unless
//!   [`ResponseAssembler::pass_through_unreferenced`] is enabled, in which case
//!   their chunks are forwarded verbatim.
//! - At most one response is *active* at a time. Responses are activated in the
//!   order they become **certain** to execute (ties broken by topological
//!   order). Certainty is a linear-time fixpoint over the graph — never a path
//!   enumeration:
//!   - a node that started or finished is certain, and so is the root entry;
//!   - a node is certain when one incoming edge comes from a certain source and
//!     that edge will be taken if the source succeeds: every edge of a
//!     non-branching node (except `fail-branch` edges), or the edge matching the
//!     handle a finished branch node selected. Node failures are not anticipated,
//!     except that an unfinished node with the `fail-branch` strategy makes none
//!     of its edges certain (either side may be taken).
//! - While a response is active, its template is drained left to right:
//!   literal text is emitted immediately; a variable produced by a graph node
//!   emits that node's buffered stream chunks for the variable's field as they
//!   arrive; once the node finishes, a variable that never streamed is emitted
//!   whole (`Value::to_text`). Variables of skipped or failed nodes render as
//!   nothing. Variables outside graph nodes (`sys.*`, `conversation.*`, ...)
//!   are resolved from values given via [`ResponseAssembler::with_value`] /
//!   [`ResponseAssembler::with_pool`], or render as nothing.
//! - `end` nodes do not stream by default (their outputs are structured data,
//!   delivered in `RunSucceeded`). Enable [`ResponseAssembler::include_end`] to
//!   render them as their output values joined by newlines.
//! - **Retries and handled failures never mix attempts.** A source node whose
//!   policy allows retries (`retry.max_retries > 0`) or handles errors
//!   (`on_error` other than `fail`) is *not* streamed live: its chunks are
//!   buffered and emitted only once the node finishes. A `node_retry` event
//!   discards the buffered chunks of the failed attempt. On success the final
//!   attempt's text is emitted; after a handled `default-value` failure the
//!   default output is emitted instead of any partial text; after a
//!   `fail-branch` failure (or an unhandled one) nothing is emitted for the
//!   variable. The trade-off: such nodes lose token-by-token streaming in
//!   exchange for an answer that always matches the node's final output.
//! - Ordering after handled failures follows the engine: a non-branch node with
//!   `default-value` continues along its regular edges, a `fail-branch` node
//!   along its `fail-branch` edges, and a branch node with `default-value`
//!   along the handle named by its `branch` default value (no edge if absent).
//! - A terminal run event (`RunSucceeded`, `RunFailed`, `RunAborted`) flushes
//!   everything that can still be rendered, as does [`ResponseAssembler::finish`].

use std::collections::{HashMap, HashSet, VecDeque};
use std::sync::Arc;

use serde::Deserialize;

use crate::dsl::ErrorStrategy;
use crate::event::Event;
use crate::graph::{FAIL_BRANCH, Graph, NodeIx};
use crate::node::NodeRole;
use crate::pool::{Selector, VariablePool};
use crate::snapshot::{EdgeStatus, FrameSnapshot, NodeStatus};
use crate::template::{Part, Template};
use crate::value::Value;

/// A piece of ordered response text.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ResponseChunk {
    /// Response node the text belongs to (or, for passed-through chunks, the
    /// node that produced them).
    pub node_id: String,
    pub text: String,
    /// `true` exactly once per response node, on an empty chunk marking that
    /// its template is fully rendered.
    pub is_final: bool,
}

impl ResponseChunk {
    fn text(node_id: &str, text: String) -> Self {
        Self { node_id: node_id.to_owned(), text, is_final: false }
    }

    fn done(node_id: &str) -> Self {
        Self { node_id: node_id.to_owned(), text: String::new(), is_final: true }
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Status {
    Unknown,
    Started,
    Succeeded,
    /// Failed but kept going through its error strategy.
    Handled,
    /// Failed without an error strategy: outputs never appear.
    Failed,
    Skipped,
}

impl Status {
    fn finished(self) -> bool {
        matches!(self, Status::Succeeded | Status::Handled | Status::Failed | Status::Skipped)
    }
}

#[derive(Debug)]
struct Response {
    node: NodeIx,
    id: Arc<str>,
    parts: Vec<Part>,
    queued: bool,
    done: bool,
}

#[derive(Debug, Default)]
struct StreamBuf {
    text: String,
}

#[derive(Debug)]
struct Active {
    response: usize,
    part: usize,
    /// Byte offset already emitted from the current variable's stream buffer.
    offset: usize,
}

#[derive(Deserialize)]
struct EndOutput {
    value_selector: Selector,
}

/// Turns raw run events into ordered response text. See the module docs.
#[derive(Debug)]
pub struct ResponseAssembler {
    graph: Arc<Graph>,
    responses: Vec<Response>,
    status: Vec<Status>,
    branch: Vec<Option<String>>,
    /// Nodes whose streams are buffered until they finish (retry / handled-error policy).
    deferred: Vec<bool>,
    /// Edge states restored from a snapshot (indexed like `Graph::edges`).
    edge_state: Vec<Option<EdgeStatus>>,
    /// Response nodes fully rendered before a pause (restored via `resume_from`).
    rendered: Vec<bool>,
    /// Stream buffers keyed by `(node id, field)`, only for referenced selectors.
    streams: HashMap<(Arc<str>, Arc<str>), StreamBuf>,
    referenced: HashSet<(Arc<str>, Arc<str>)>,
    pool: VariablePool,
    queue: VecDeque<usize>,
    active: Option<Active>,
    emitted: String,
    pass_through: bool,
    include_end: bool,
    finished: bool,
    /// Certainty of each node, maintained incrementally between events.
    certain: Vec<bool>,
    /// Whether `certain` reflects the current state (false after construction / resume).
    certain_valid: bool,
    /// Root nodes whose status changed since the last certainty refresh.
    changed: Vec<NodeIx>,
}

impl ResponseAssembler {
    /// Build an assembler for runs of `graph`.
    pub fn new(graph: &Arc<Graph>) -> Self {
        let mut this = Self {
            graph: Arc::clone(graph),
            responses: Vec::new(),
            status: vec![Status::Unknown; graph.nodes().len()],
            branch: vec![None; graph.nodes().len()],
            deferred: graph
                .nodes()
                .iter()
                .map(|n| n.policy.retry.max_retries > 0 || !matches!(n.policy.on_error, ErrorStrategy::Fail))
                .collect(),
            edge_state: vec![None; graph.edges().len()],
            rendered: vec![false; graph.nodes().len()],
            streams: HashMap::new(),
            referenced: HashSet::new(),
            pool: VariablePool::new(),
            queue: VecDeque::new(),
            active: None,
            emitted: String::new(),
            pass_through: false,
            include_end: false,
            finished: false,
            certain: vec![false; graph.nodes().len()],
            certain_valid: false,
            changed: Vec::new(),
        };
        this.rebuild_responses();
        this
    }

    /// Forward chunks that no template references (and child-frame chunks) verbatim.
    pub fn pass_through_unreferenced(mut self, enabled: bool) -> Self {
        self.pass_through = enabled;
        self
    }

    /// Also render `end` nodes (their outputs joined by newlines).
    pub fn include_end(mut self, enabled: bool) -> Self {
        self.include_end = enabled;
        self.rebuild_responses();
        self
    }

    /// Provide a value for a non-node variable such as `sys.query`.
    pub fn with_value(mut self, selector: &Selector, value: Value) -> Self {
        self.pool.set(selector, value);
        self
    }

    /// Provide non-node variables in bulk (e.g. the run's `sys` / `conversation` values).
    pub fn with_pool(mut self, pool: VariablePool) -> Self {
        for (ns, name, value) in pool.iter() {
            self.pool.insert(ns, name, value.clone());
        }
        self
    }

    /// Continue assembling a resumed run from the root frame snapshot carried by
    /// `RunPaused` (`snapshot.root`).
    ///
    /// Restores every variable value of the snapshot (node outputs included, so
    /// templates can reference nodes that will not run again), node and edge
    /// states (for correct ordering), and marks response nodes that already
    /// succeeded before the pause as rendered, so they are not emitted twice.
    /// A response that was only partially rendered when the run paused is
    /// rendered again from the start.
    pub fn resume_from(mut self, snapshot: &FrameSnapshot) -> Self {
        let restored = VariablePool::from_snapshot(snapshot.pool.clone());
        for (ns, name, value) in restored.iter() {
            self.pool.insert(ns, name, value.clone());
        }
        for (ix, edge) in self.graph.edges().iter().enumerate() {
            if let (Some(state), Some(slot)) = (snapshot.edges.get(edge.id.as_ref()), self.edge_state.get_mut(ix)) {
                *slot = Some(*state);
            }
        }
        for (node_id, node) in &snapshot.nodes {
            let Some(ix) = self.root_node(node_id) else { continue };
            let status = match node.status {
                NodeStatus::Succeeded => Status::Succeeded,
                NodeStatus::Skipped => Status::Skipped,
                NodeStatus::Failed if self.has_taken_outgoing(ix) => Status::Handled,
                NodeStatus::Failed => Status::Failed,
                NodeStatus::Paused => Status::Started,
                NodeStatus::Pending => Status::Unknown,
            };
            if let Some(slot) = self.status.get_mut(ix) {
                *slot = status;
            }
            if let Some(slot) = self.rendered.get_mut(ix) {
                *slot = status == Status::Succeeded;
            }
        }
        self.certain_valid = false;
        self.rebuild_responses();
        self
    }

    fn has_taken_outgoing(&self, ix: NodeIx) -> bool {
        self.graph.outgoing(ix).iter().any(|&ex| self.edge_state.get(ex).copied().flatten() == Some(EdgeStatus::Taken))
    }

    /// All response text emitted so far, concatenated.
    pub fn text_so_far(&self) -> &str {
        &self.emitted
    }

    /// Feed one event; returns the response chunks it unlocks.
    pub fn push(&mut self, event: &Event) -> Vec<ResponseChunk> {
        let mut out = Vec::new();
        if self.finished {
            return out;
        }
        match event {
            Event::NodeStarted { frame, node_id, .. } if frame.is_empty() => {
                self.set_status(node_id, Status::Started);
            }
            Event::NodeChunk { frame, node_id, field, chunk, .. } => {
                let key: (Arc<str>, Arc<str>) = (Arc::clone(node_id), Arc::from(field.as_str()));
                if frame.is_empty() && self.referenced.contains(&key) {
                    self.streams.entry(key).or_default().text.push_str(chunk);
                } else if self.pass_through && !chunk.is_empty() {
                    out.push(ResponseChunk::text(node_id, chunk.clone()));
                }
            }
            Event::NodeSucceeded { frame, node_id, outputs, branch, .. } if frame.is_empty() => {
                self.pool.set_outputs(node_id, outputs);
                if let Some(ix) = self.root_node(node_id) {
                    if let Some(b) = self.branch.get_mut(ix) {
                        b.clone_from(branch);
                    }
                }
                self.set_status(node_id, Status::Succeeded);
            }
            Event::NodeFailed { frame, node_id, handled, outputs, .. } if frame.is_empty() => {
                if *handled {
                    self.pool.set_outputs(node_id, outputs);
                }
                self.set_status(node_id, if *handled { Status::Handled } else { Status::Failed });
            }
            Event::NodeSkipped { frame, node_id } if frame.is_empty() => {
                self.set_status(node_id, Status::Skipped);
            }
            Event::NodeRetry { frame, node_id, .. } if frame.is_empty() => {
                // The failed attempt's partial output must never reach the answer.
                self.streams.retain(|(node, _), _| node.as_ref() != node_id.as_ref());
                return out;
            }
            Event::RunSucceeded { .. } | Event::RunFailed { .. } | Event::RunAborted { .. } => {
                out.extend(self.finish());
                return out;
            }
            _ => return out,
        }
        self.refresh_certainty();
        self.drain(false, &mut out);
        out
    }

    /// Flush: treat every pending variable as resolved and render what is
    /// available. Idempotent.
    pub fn finish(&mut self) -> Vec<ResponseChunk> {
        let mut out = Vec::new();
        if self.finished {
            return out;
        }
        self.refresh_certainty();
        self.drain(true, &mut out);
        self.finished = true;
        out
    }

    fn rebuild_responses(&mut self) {
        let Some(scope) = self.graph.root_scope() else {
            return;
        };
        let mut responses = Vec::new();
        for &ix in &scope.nodes {
            let Some(node) = self.graph.node(ix) else { continue };
            if node.role != NodeRole::Response {
                continue;
            }
            let parts = match &*node.kind {
                "answer" => node
                    .doc
                    .config
                    .get("answer")
                    .and_then(serde_json::Value::as_str)
                    .map(|s| Template::parse(s).parts().to_vec())
                    .unwrap_or_default(),
                "end" if self.include_end => end_parts(&node.doc.config),
                _ => continue,
            };
            let rendered = self.rendered.get(ix).copied().unwrap_or(false);
            responses.push(Response { node: ix, id: node.id.clone(), parts, queued: rendered, done: rendered });
        }
        self.referenced = responses
            .iter()
            .flat_map(|r| r.parts.iter())
            .filter_map(|p| match p {
                Part::Var(sel) if sel.path().is_empty() => Some((Arc::from(sel.namespace()), Arc::from(sel.name()))),
                _ => None,
            })
            .collect();
        self.responses = responses;
    }

    fn root_node(&self, id: &str) -> Option<NodeIx> {
        self.graph.index_of(id).filter(|&ix| self.graph.node(ix).is_some_and(|n| n.parent.is_none()))
    }

    fn set_status(&mut self, node_id: &str, status: Status) {
        if let Some(ix) = self.root_node(node_id) {
            if let Some(s) = self.status.get_mut(ix) {
                // Never downgrade a finished node back to "started" (retries reuse the id).
                if !(s.finished() && status == Status::Started) {
                    if *s != status {
                        self.changed.push(ix);
                    }
                    *s = status;
                }
            }
        }
    }

    fn status_of(&self, ix: NodeIx) -> Status {
        self.status.get(ix).copied().unwrap_or(Status::Unknown)
    }

    /// Whether `ix` is certain to run, given the certainty of its predecessors.
    fn compute_certain(&self, ix: NodeIx, entry: NodeIx, certain: &[bool]) -> bool {
        match self.status_of(ix) {
            Status::Skipped => false,
            Status::Unknown => ix == entry || self.has_certain_edge(ix, certain),
            _ => true,
        }
    }

    /// Bring the certain set up to date and enqueue newly certain responses.
    ///
    /// Certainty only grows as a run progresses, so after one full pass each
    /// status change is propagated forward from the changed node: O(affected
    /// nodes) per event instead of O(graph). A node losing certainty (not
    /// expected in practice) falls back to a full recomputation.
    fn refresh_certainty(&mut self) {
        let Some(scope) = self.graph.root_scope() else {
            return;
        };
        let entry = scope.entry;
        let mut certain = std::mem::take(&mut self.certain);
        certain.resize(self.graph.nodes().len(), false);
        let changed = std::mem::take(&mut self.changed);
        let mut full = !self.certain_valid;
        if !full {
            let mut work: Vec<NodeIx> = changed;
            while let Some(ix) = work.pop() {
                let now = self.compute_certain(ix, entry, &certain);
                let before = certain.get(ix).copied().unwrap_or(false);
                if before && !now {
                    full = true;
                    break;
                }
                if now != before {
                    if let Some(c) = certain.get_mut(ix) {
                        *c = now;
                    }
                }
                // Even when `ix` itself was already certain, its outgoing edges may
                // have become certain (e.g. a branch picked its handle).
                if now {
                    for &ex in self.graph.outgoing(ix) {
                        if let Some(edge) = self.graph.edge(ex) {
                            if !certain.get(edge.target).copied().unwrap_or(false)
                                && self.compute_certain(edge.target, entry, &certain)
                            {
                                if let Some(c) = certain.get_mut(edge.target) {
                                    *c = true;
                                }
                                work.push(edge.target);
                            }
                        }
                    }
                }
            }
        }
        if full {
            certain.iter_mut().for_each(|c| *c = false);
            for &ix in &scope.nodes {
                let is_certain = self.compute_certain(ix, entry, &certain);
                if let Some(c) = certain.get_mut(ix) {
                    *c = is_certain;
                }
            }
        }
        for (i, r) in self.responses.iter_mut().enumerate() {
            if !r.queued && certain.get(r.node).copied().unwrap_or(false) {
                r.queued = true;
                self.queue.push_back(i);
            }
        }
        self.certain = certain;
        self.certain_valid = true;
    }

    /// Whether an incoming edge of `ix` will be taken given its (certain) source.
    fn has_certain_edge(&self, ix: NodeIx, certain: &[bool]) -> bool {
        self.graph.incoming(ix).iter().filter_map(|&ex| self.graph.edge(ex).map(|e| (ex, e))).any(|(ex, edge)| {
            if !certain.get(edge.source).copied().unwrap_or(false) {
                return false;
            }
            // States restored from a snapshot are authoritative.
            match self.edge_state.get(ex).copied().flatten() {
                Some(EdgeStatus::Taken) => return true,
                Some(EdgeStatus::Skipped) => return false,
                Some(EdgeStatus::Unknown) | None => {}
            }
            let Some(src) = self.graph.node(edge.source) else { return false };
            let status = self.status_of(edge.source);
            let fail_branch = matches!(src.policy.on_error, ErrorStrategy::FailBranch);
            match status {
                Status::Failed | Status::Skipped => false,
                Status::Handled if fail_branch => edge.handle.as_ref() == FAIL_BRANCH,
                Status::Handled if src.role == NodeRole::Branch => {
                    default_branch(&src.policy.on_error).as_deref() == Some(edge.handle.as_ref())
                }
                Status::Handled => edge.handle.as_ref() != FAIL_BRANCH,
                Status::Succeeded if src.role == NodeRole::Branch => {
                    self.branch.get(edge.source).and_then(Option::as_deref) == Some(edge.handle.as_ref())
                }
                _ if src.role == NodeRole::Branch => false,
                // Unfinished fail-branch node: which side it takes is not known yet.
                _ if fail_branch => false,
                _ => edge.handle.as_ref() != FAIL_BRANCH,
            }
        })
    }

    /// Render as much as possible. With `flush`, pending variables are treated as resolved.
    fn drain(&mut self, flush: bool, out: &mut Vec<ResponseChunk>) {
        loop {
            if self.active.is_none() {
                match self.queue.pop_front() {
                    Some(response) => self.active = Some(Active { response, part: 0, offset: 0 }),
                    None => return,
                }
            }
            let Some(active) = self.active.as_mut() else { return };
            let Some(response) = self.responses.get(active.response) else {
                self.active = None;
                continue;
            };
            // A response node that ended up skipped renders nothing.
            if self.status.get(response.node).copied() == Some(Status::Skipped) {
                self.finish_active(None, out);
                continue;
            }
            let id = Arc::clone(&response.id);
            match response.parts.get(active.part).cloned() {
                None => self.finish_active(Some(&id), out),
                Some(Part::Text(text)) => {
                    emit(&mut self.emitted, out, &id, text);
                    active.part += 1;
                    active.offset = 0;
                }
                Some(Part::Var(sel)) => {
                    let sources = Sources {
                        graph: &self.graph,
                        status: &self.status,
                        deferred: &self.deferred,
                        streams: &self.streams,
                        pool: &self.pool,
                    };
                    let step = resolve_var(&sources, &sel, active.offset, flush);
                    if !step.text.is_empty() {
                        emit(&mut self.emitted, out, &id, step.text);
                    }
                    active.offset = step.offset;
                    if step.complete {
                        active.part += 1;
                        active.offset = 0;
                    } else {
                        return;
                    }
                }
            }
        }
    }

    fn finish_active(&mut self, id: Option<&Arc<str>>, out: &mut Vec<ResponseChunk>) {
        if let Some(active) = self.active.take() {
            if let Some(r) = self.responses.get_mut(active.response) {
                r.done = true;
            }
            if let Some(id) = id {
                out.push(ResponseChunk::done(id));
            }
        }
    }
}

struct Step {
    text: String,
    offset: usize,
    complete: bool,
}

/// Read-only view of the state a template variable is resolved from.
struct Sources<'a> {
    graph: &'a Graph,
    status: &'a [Status],
    deferred: &'a [bool],
    streams: &'a HashMap<(Arc<str>, Arc<str>), StreamBuf>,
    pool: &'a VariablePool,
}

fn resolve_var(sources: &Sources<'_>, sel: &Selector, offset: usize, flush: bool) -> Step {
    let Sources { graph, status, deferred, streams, pool } = *sources;
    let node_ix = graph.index_of(sel.namespace()).filter(|&ix| graph.node(ix).is_some_and(|n| n.parent.is_none()));
    let Some(ix) = node_ix else {
        // Not produced by a root graph node: host-provided value (or nothing).
        return Step { text: pool.get(sel).map(|v| v.to_text()).unwrap_or_default(), offset: 0, complete: true };
    };
    let node_status = status.get(ix).copied().unwrap_or(Status::Unknown);

    let is_deferred = deferred.get(ix).copied().unwrap_or(false);
    let key = (Arc::from(sel.namespace()), Arc::from(sel.name()));
    let buffered = if sel.path().is_empty() { streams.get(&key).filter(|b| !b.text.is_empty()) } else { None };

    if is_deferred {
        // Emitted only once the node has finished, from its final attempt.
        let text = match node_status {
            Status::Succeeded => match buffered {
                Some(buf) => buf.text.clone(),
                None => pool.get(sel).map(|v| v.to_text()).unwrap_or_default(),
            },
            // Default-value outputs (or nothing on fail-branch, whose outputs are only error fields).
            Status::Handled => pool.get(sel).map(|v| v.to_text()).unwrap_or_default(),
            _ => String::new(),
        };
        return Step { text, offset: 0, complete: node_status.finished() || flush };
    }

    // Live streaming: emit whatever was buffered beyond `offset`.
    let mut text = String::new();
    let mut new_offset = offset;
    let streamed = buffered.is_some();
    if let Some(buf) = buffered {
        if let Some(rest) = buf.text.get(offset..) {
            text.push_str(rest);
            new_offset = buf.text.len();
        }
    }

    let complete = match node_status {
        Status::Skipped | Status::Failed => true,
        Status::Succeeded | Status::Handled => {
            if !streamed {
                if let Some(v) = pool.get(sel) {
                    text.push_str(&v.to_text());
                }
            }
            true
        }
        Status::Unknown | Status::Started => {
            if flush && !streamed {
                if let Some(v) = pool.get(sel) {
                    text.push_str(&v.to_text());
                }
            }
            flush
        }
    };
    Step { text, offset: new_offset, complete }
}

/// Handle named by a `branch` entry of a `default-value` strategy.
fn default_branch(strategy: &ErrorStrategy) -> Option<String> {
    match strategy {
        ErrorStrategy::DefaultValue { values } => values.get("branch").and_then(Value::as_str).map(str::to_owned),
        _ => None,
    }
}

fn emit(emitted: &mut String, out: &mut Vec<ResponseChunk>, id: &str, text: String) {
    if text.is_empty() {
        return;
    }
    emitted.push_str(&text);
    out.push(ResponseChunk::text(id, text));
}

fn end_parts(config: &serde_json::Map<String, serde_json::Value>) -> Vec<Part> {
    let outputs: Vec<EndOutput> = config
        .get("outputs")
        .cloned()
        .and_then(|v| serde_json::from_value::<Vec<serde_json::Value>>(v).ok())
        .unwrap_or_default()
        .into_iter()
        .filter_map(|v| serde_json::from_value(v).ok())
        .collect();
    let mut parts = Vec::with_capacity(outputs.len() * 2);
    for (i, o) in outputs.into_iter().enumerate() {
        if i > 0 {
            parts.push(Part::Text("\n".to_owned()));
        }
        parts.push(Part::Var(o.value_selector));
    }
    parts
}