Skip to main content

graphrt_core/
node.rs

1//! The node contract.
2//!
3//! A node is an immutable, pre-validated object built once from its
4//! [`NodeDoc`] by a factory in the [`Registry`]. At run time the engine calls
5//! [`Node::run`] with an owned [`NodeContext`]; the node reads inputs from the
6//! context's pool snapshot and returns a [`NodeOutcome`]. Nodes never mutate
7//! shared state directly: outputs and variable writes are returned and
8//! committed by the engine.
9
10use std::any::{Any, TypeId};
11use std::collections::HashMap;
12use std::fmt;
13use std::sync::{Arc, OnceLock};
14use std::time::Duration;
15
16use futures::future::BoxFuture;
17use indexmap::IndexMap;
18
19use crate::dsl::NodeDoc;
20use crate::event::{Event, FrameId, PauseReason, Usage};
21use crate::pool::{Selector, VariablePool};
22use crate::redact::SecretSet;
23use crate::snapshot::FrameSnapshot;
24use crate::value::Value;
25use crate::variables::{VarName, Variables};
26
27/// How the scheduler treats a node.
28#[derive(Clone, Copy, Debug, PartialEq, Eq)]
29#[non_exhaustive]
30pub enum NodeRole {
31    /// Entry point of the root graph.
32    Root,
33    /// Entry point of a container body (iteration-start / loop-start).
34    ScopeStart,
35    /// Regular node: on success every outgoing edge is taken.
36    Executable,
37    /// Selects exactly one outgoing handle via [`NodeOutput::branch`].
38    Branch,
39    /// Produces user-facing output (answer / end). Outputs are merged into the frame outputs.
40    Response,
41    /// Owns a child scope executed through [`NodeContext::subgraph`].
42    Container,
43}
44
45/// Error produced by a node.
46#[derive(Clone, Debug, PartialEq, thiserror::Error)]
47#[error("{kind}: {message}")]
48pub struct NodeError {
49    /// Machine-readable category, e.g. `timeout`, `http`, `invalid_input`, `model`.
50    pub kind: String,
51    pub message: String,
52    /// Whether a retry may succeed. Non-retryable errors skip the retry policy.
53    pub retryable: bool,
54    /// Minimum delay before a retry, as requested by the remote side (e.g. an
55    /// HTTP `Retry-After` header or a provider rate limit). The engine waits for
56    /// the larger of this and the node's retry policy delay.
57    pub retry_after_ms: Option<u64>,
58}
59
60impl NodeError {
61    pub fn new(kind: impl Into<String>, message: impl Into<String>) -> Self {
62        Self { kind: kind.into(), message: message.into(), retryable: true, retry_after_ms: None }
63    }
64
65    /// Error that retrying cannot fix (bad configuration, invalid input).
66    pub fn fatal(kind: impl Into<String>, message: impl Into<String>) -> Self {
67        Self { kind: kind.into(), message: message.into(), retryable: false, retry_after_ms: None }
68    }
69
70    /// Attach a server-requested retry delay.
71    pub fn with_retry_after(mut self, retry_after_ms: Option<u64>) -> Self {
72        self.retry_after_ms = retry_after_ms;
73        self
74    }
75
76    /// Replace the message, keeping kind, retryability and retry delay.
77    pub fn with_message(mut self, message: impl Into<String>) -> Self {
78        self.message = message.into();
79        self
80    }
81
82    pub fn invalid_input(message: impl Into<String>) -> Self {
83        Self::fatal("invalid_input", message)
84    }
85
86    pub fn timeout(after: Duration) -> Self {
87        Self::new("timeout", format!("node timed out after {} ms", after.as_millis()))
88    }
89}
90
91/// Error raised when a node's configuration is invalid (at graph build time).
92#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
93#[error("node `{node_id}` ({kind}): {}{message}", field_prefix(.field))]
94pub struct ConfigError {
95    pub node_id: String,
96    pub kind: String,
97    pub message: String,
98    /// Config field the error is about, as a path below the node such as
99    /// `variables[0].value_selector`, when known.
100    pub field: Option<String>,
101}
102
103fn field_prefix(field: &Option<String>) -> String {
104    field.as_ref().map(|f| format!("{f}: ")).unwrap_or_default()
105}
106
107impl ConfigError {
108    pub fn new(doc: &NodeDoc, message: impl Into<String>) -> Self {
109        Self { node_id: doc.id.clone(), kind: doc.kind.clone(), message: message.into(), field: None }
110    }
111
112    /// Attach the config field the error is about.
113    #[must_use]
114    pub fn at_field(mut self, field: impl Into<String>) -> Self {
115        self.field = Some(field.into());
116        self
117    }
118}
119
120/// Successful node result.
121#[derive(Clone, Debug, Default, PartialEq)]
122pub struct NodeOutput {
123    /// Outputs stored under the node's namespace (`<node_id>.<key>`). The
124    /// engine stores this map as the namespace and emits it in
125    /// [`Event::NodeSucceeded`] without copying it.
126    pub outputs: Variables,
127    /// Selected handle for branch nodes.
128    pub branch: Option<String>,
129    /// Writes to other namespaces (conversation variables, loop variables, ...), applied in order.
130    pub writes: Vec<(Selector, Value)>,
131    pub usage: Option<Usage>,
132    /// Observability data (resolved inputs, request details...). Not stored in the pool.
133    pub metadata: IndexMap<String, Value>,
134}
135
136impl NodeOutput {
137    pub fn new() -> Self {
138        Self::default()
139    }
140
141    /// Add an output. A string-literal name costs no allocation.
142    pub fn with(mut self, key: impl Into<VarName>, value: impl Into<Value>) -> Self {
143        self.outputs.insert(key.into(), value.into());
144        self
145    }
146
147    pub fn branch(mut self, handle: impl Into<String>) -> Self {
148        self.branch = Some(handle.into());
149        self
150    }
151
152    pub fn write(mut self, selector: Selector, value: Value) -> Self {
153        self.writes.push((selector, value));
154        self
155    }
156
157    pub fn usage(mut self, usage: Usage) -> Self {
158        self.usage = Some(usage);
159        self
160    }
161
162    pub fn meta(mut self, key: impl Into<String>, value: impl Into<Value>) -> Self {
163        self.metadata.insert(key.into(), value.into());
164        self
165    }
166}
167
168/// A request from a node to pause the run (e.g. waiting for a human).
169#[derive(Clone, Debug, PartialEq)]
170pub struct PauseRequest {
171    /// Machine-readable kind, e.g. `human_input`.
172    pub kind: String,
173    /// Details shown to the host (form schema, prompt...).
174    pub data: Value,
175    /// State handed back to the node in [`Resume::state`].
176    pub state: serde_json::Value,
177}
178
179/// What a node run produced.
180#[derive(Clone, Debug, PartialEq)]
181pub enum NodeOutcome {
182    Completed(NodeOutput),
183    Paused(PauseRequest),
184}
185
186impl From<NodeOutput> for NodeOutcome {
187    fn from(o: NodeOutput) -> Self {
188        NodeOutcome::Completed(o)
189    }
190}
191
192/// Data given to a node that previously paused.
193#[derive(Clone, Debug, PartialEq)]
194pub struct Resume {
195    /// The node's own saved state ([`PauseRequest::state`]).
196    pub state: serde_json::Value,
197    /// Host-supplied input for this node (e.g. a submitted human-input form), if any.
198    pub input: Option<Value>,
199}
200
201/// Result type of [`Node::run`].
202pub type NodeResult = Result<NodeOutcome, NodeError>;
203
204/// An executable node.
205pub trait Node: Send + Sync + fmt::Debug {
206    /// Scheduling role. Must be constant for a given instance.
207    fn role(&self) -> NodeRole {
208        NodeRole::Executable
209    }
210
211    /// Execute the node. Dropping the returned future cancels the node.
212    fn run(&self, ctx: NodeContext) -> BoxFuture<'_, NodeResult>;
213
214    /// Selectors this node reads. [`crate::graph::Graph::build`] rejects selectors
215    /// whose namespace is neither a node id nor `sys` / `env` / `conversation`
216    /// (catching typos at load time) and warns about references into other
217    /// container bodies. Return every selector the node may read, including
218    /// placeholders inside templates.
219    fn inputs(&self) -> Vec<Selector> {
220        Vec::new()
221    }
222
223    /// Every handle a [`NodeRole::Branch`] node may select, when known from its
224    /// configuration (if-else case ids, classifier class ids...). Graph building
225    /// rejects edges with other handles. `None` (the default) falls back to the
226    /// kind's catalog descriptor: `Fixed` handles are checked, `Dynamic` ones are
227    /// not, and non-branch nodes have the single handle `source`.
228    fn branch_handles(&self) -> Option<Vec<String>> {
229        None
230    }
231
232    /// Whether the node charges the run's budget itself after each model
233    /// response, with its cost, and may keep checkpoints
234    /// ([`NodeContext::charge`], [`NodeContext::checkpoint`]). The engine then
235    /// charges it nothing when it completes, and gives it a checkpoint that
236    /// lasts across its attempts. Other nodes are charged the tokens of their
237    /// usage when they complete.
238    fn tracks_turns(&self) -> bool {
239        false
240    }
241}
242
243/// Append `new` writes to `acc`, keeping only the latest write per exact selector.
244///
245/// An earlier write to the same selector is removed and the new one is appended
246/// at the end, so replaying `acc` in order still yields the same final state
247/// while its length stays bounded by the number of distinct selectors (no
248/// quadratic growth across loop rounds or iteration items).
249pub fn merge_writes(acc: &mut Vec<(Selector, Value)>, new: impl IntoIterator<Item = (Selector, Value)>) {
250    for (selector, value) in new {
251        if let Some(pos) = acc.iter().position(|(s, _)| *s == selector) {
252            acc.remove(pos);
253        }
254        acc.push((selector, value));
255    }
256}
257
258/// Request to execute a container's body once.
259#[derive(Debug)]
260pub struct SubgraphRequest {
261    /// Iteration index / loop round. Used for the child frame id.
262    pub index: usize,
263    /// Variables visible to the body. Usually a cheap clone of the context pool plus
264    /// the container's per-round values.
265    pub pool: VariablePool,
266    /// Resume a previously paused body run.
267    pub resume: Option<FrameSnapshot>,
268}
269
270/// Outcome of a container body run.
271///
272/// Produced once per body run and moved straight into the container node, so
273/// the size difference between variants does not matter.
274#[derive(Debug)]
275#[allow(clippy::large_enum_variant)]
276pub enum SubgraphResult {
277    Completed {
278        /// Final pool of the body run.
279        pool: VariablePool,
280        /// Response outputs accumulated in the body (answer text...).
281        outputs: IndexMap<String, Value>,
282        /// Writes to namespaces outside the body (container variables, conversation...),
283        /// in commit order. The container should forward them via [`NodeOutput::writes`].
284        writes: Vec<(Selector, Value)>,
285        usage: Usage,
286        /// Whether a `loop-end` (break) node completed in this body run.
287        broke: bool,
288    },
289    Failed {
290        error: NodeError,
291        usage: Usage,
292    },
293    Paused {
294        snapshot: FrameSnapshot,
295        reasons: Vec<PauseReason>,
296    },
297}
298
299/// Executes a container's child scope. Provided to container nodes by the engine.
300pub trait Subgraph: Send + Sync + fmt::Debug {
301    fn run(&self, request: SubgraphRequest) -> BoxFuture<'_, SubgraphResult>;
302}
303
304/// The pause kind of a node whose pause only passes on the pauses of child
305/// runs it started ([`ChildRuns`]): the nodes inside them reported their
306/// reasons already, so the engine adds none for this node.
307#[cfg(feature = "subagents")]
308pub const CHILD_PAUSE: &str = "child_runs";
309
310/// One child run: workflow `workflow` started by the current node as call
311/// `index` (stable across attempts and resumes, it names the child's frame).
312/// Built with [`ChildRequest::start`] or [`ChildRequest::resume`].
313#[cfg(feature = "subagents")]
314#[derive(Debug, Clone)]
315pub struct ChildRequest {
316    pub(crate) workflow: String,
317    pub(crate) index: usize,
318    /// Values for the start variables of the child workflow (a start only).
319    pub(crate) inputs: IndexMap<String, Value>,
320    /// `sys` values the child sees (a start only). It sees nothing else of the parent.
321    pub(crate) sys: IndexMap<String, Value>,
322    /// The snapshot of a child that paused, to resume it.
323    pub(crate) resume: Option<FrameSnapshot>,
324}
325
326#[cfg(feature = "subagents")]
327impl ChildRequest {
328    /// Start `workflow` as call `index` with `inputs` for its start variables.
329    pub fn start(workflow: impl Into<String>, index: usize, inputs: IndexMap<String, Value>) -> Self {
330        Self { workflow: workflow.into(), index, inputs, sys: IndexMap::new(), resume: None }
331    }
332
333    /// The `sys` values a started child sees.
334    pub fn with_sys(mut self, sys: IndexMap<String, Value>) -> Self {
335        self.sys = sys;
336        self
337    }
338
339    /// Resume call `index` of `workflow` from the snapshot its pause gave.
340    /// The child keeps the inputs and `sys` values it started with.
341    pub fn resume(workflow: impl Into<String>, index: usize, snapshot: FrameSnapshot) -> Self {
342        Self { workflow: workflow.into(), index, inputs: IndexMap::new(), sys: IndexMap::new(), resume: Some(snapshot) }
343    }
344}
345
346#[cfg(feature = "subagents")]
347pub(crate) mod sealed {
348    /// Only the engine implements [`super::ChildRuns`].
349    pub trait Sealed {}
350}
351
352/// Workflows linked to the run that a node may start as child runs. A child
353/// runs inside the same run: it shares the step budget, the deadline, the
354/// depth limit, the secrets that are scrubbed, the control signals and the
355/// event stream, and its pauses reach the root with frame qualified keys. It
356/// uses the services its host gave its own workflow.
357///
358/// Implemented by the engine only.
359#[cfg(feature = "subagents")]
360pub trait ChildRuns: sealed::Sealed + Send + Sync + fmt::Debug {
361    /// The names of the linked workflows.
362    fn workflows(&self) -> Vec<String>;
363    /// The JSON schema of the start variables of `workflow`.
364    ///
365    /// @throws NodeError - `unknown_workflow` when it is not linked,
366    ///   `unusable_workflow` when a model cannot supply a required variable.
367    fn inputs_schema(&self, workflow: &str) -> Result<serde_json::Value, NodeError>;
368    /// Run, or resume, one child.
369    fn run(&self, request: ChildRequest) -> BoxFuture<'_, SubgraphResult>;
370    /// Child runs a node may have at once (the run's concurrency).
371    fn max_concurrency(&self) -> usize;
372    /// Whether the run stops (aborted, or a limit of the run): a child that
373    /// failed then failed for that reason, not for one of its own.
374    fn run_stopped(&self) -> bool;
375}
376
377/// Time source used by the engine and nodes (retries, timeouts, elapsed time).
378pub trait Clock: Send + Sync + fmt::Debug {
379    /// Milliseconds since an arbitrary fixed origin.
380    fn now_ms(&self) -> u64;
381    /// Wait for `duration`.
382    fn sleep(&self, duration: Duration) -> BoxFuture<'static, ()>;
383    /// Whether [`Clock::sleep`] actually waits. Timeouts are only enforced when true.
384    fn supports_timers(&self) -> bool {
385        true
386    }
387}
388
389/// A clock without timers: sleeps complete immediately and timeouts are not enforced.
390/// Useful for tests and for executors without a timer facility.
391#[derive(Debug, Default, Clone, Copy)]
392pub struct NoTimerClock;
393
394impl Clock for NoTimerClock {
395    fn now_ms(&self) -> u64 {
396        system_now_ms()
397    }
398    fn sleep(&self, _duration: Duration) -> BoxFuture<'static, ()> {
399        Box::pin(futures::future::ready(()))
400    }
401    fn supports_timers(&self) -> bool {
402        false
403    }
404}
405
406/// Wall-clock milliseconds since the Unix epoch.
407///
408/// `wasm32-unknown-unknown` has no system clock (`SystemTime::now` panics there),
409/// so that target returns a monotonically increasing counter instead. Hosts on
410/// that target should supply their own [`Clock`] for meaningful timestamps.
411#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
412fn system_now_ms() -> u64 {
413    std::time::SystemTime::now()
414        .duration_since(std::time::UNIX_EPOCH)
415        .map(|d| u64::try_from(d.as_millis()).unwrap_or(u64::MAX))
416        .unwrap_or(0)
417}
418
419#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
420fn system_now_ms() -> u64 {
421    use std::sync::atomic::{AtomicU64, Ordering};
422    static COUNTER: AtomicU64 = AtomicU64::new(0);
423    COUNTER.fetch_add(1, Ordering::Relaxed)
424}
425
426/// Tokio-backed clock.
427#[cfg(feature = "tokio")]
428#[derive(Debug, Default, Clone, Copy)]
429pub struct TokioClock;
430
431#[cfg(feature = "tokio")]
432impl Clock for TokioClock {
433    fn now_ms(&self) -> u64 {
434        NoTimerClock.now_ms()
435    }
436    /// Outside a Tokio runtime this completes immediately instead of panicking
437    /// (and [`Clock::supports_timers`] reports `false`, so timeouts are not
438    /// enforced). Inside a runtime, the runtime must have its time driver enabled
439    /// (`enable_time()` / `enable_all()`).
440    fn sleep(&self, duration: Duration) -> BoxFuture<'static, ()> {
441        if tokio::runtime::Handle::try_current().is_ok() {
442            Box::pin(tokio::time::sleep(duration))
443        } else {
444            Box::pin(futures::future::ready(()))
445        }
446    }
447
448    /// `true` only when called from inside a Tokio runtime.
449    fn supports_timers(&self) -> bool {
450        tokio::runtime::Handle::try_current().is_ok()
451    }
452}
453
454/// The default clock for this build: [`TokioClock`] with the `tokio` feature, else [`NoTimerClock`].
455pub fn default_clock() -> Arc<dyn Clock> {
456    #[cfg(feature = "tokio")]
457    {
458        Arc::new(TokioClock)
459    }
460    #[cfg(not(feature = "tokio"))]
461    {
462        Arc::new(NoTimerClock)
463    }
464}
465
466/// Type-indexed registry of host services (LLM providers, HTTP clients, tool
467/// runtimes, file resolvers...). Nodes look services up at run time, so node
468/// factories stay pure and graphs can be built without any integration.
469#[derive(Default, Clone)]
470pub struct Services {
471    map: HashMap<TypeId, Arc<dyn Any + Send + Sync>>,
472}
473
474impl fmt::Debug for Services {
475    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
476        write!(f, "Services({} entries)", self.map.len())
477    }
478}
479
480impl Services {
481    pub fn new() -> Self {
482        Self::default()
483    }
484
485    /// Register a service. `T` is usually an `Arc<dyn Trait>` or a concrete struct.
486    pub fn insert<T: Any + Send + Sync>(&mut self, service: T) -> &mut Self {
487        self.map.insert(TypeId::of::<T>(), Arc::new(service));
488        self
489    }
490
491    /// Builder-style [`Services::insert`].
492    pub fn with<T: Any + Send + Sync>(mut self, service: T) -> Self {
493        self.insert(service);
494        self
495    }
496
497    pub fn get<T: Any + Send + Sync>(&self) -> Option<&T> {
498        self.map.get(&TypeId::of::<T>()).and_then(|s| s.downcast_ref::<T>())
499    }
500}
501
502/// Marker service: the host records message content (rendered prompts, tool
503/// results, retrieval queries), so nodes should also report it as progress.
504///
505/// Hosts register it only when content capture is on (for example
506/// `OTEL_INSTRUMENTATION_GENAI_CAPTURE_CONTENT=SPAN_ONLY`). Without it, nodes
507/// skip building that progress entirely, so capture costs nothing when off.
508/// Content progress carries the same masked values as node outputs (secret
509/// values serialize as `******`).
510///
511/// ```
512/// let services = graphrt_core::Services::new().with(graphrt_core::node::CaptureContent);
513/// let ctx = graphrt_core::NodeContext::for_test("n", graphrt_core::VariablePool::new())
514///     .with_services(std::sync::Arc::new(services));
515/// assert!(ctx.captures_content());
516/// ```
517#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
518pub struct CaptureContent;
519
520/// Callback receiving events from nodes.
521pub type EventSink = Arc<dyn Fn(Event) + Send + Sync>;
522
523/// Everything a node may use while running. Cheap to clone.
524#[derive(Clone)]
525pub struct NodeContext {
526    pub node_id: Arc<str>,
527    pub exec_id: Arc<str>,
528    pub frame: FrameId,
529    /// 1-based attempt number (increments on retries).
530    pub attempt: u32,
531    /// How many times the engine retries this node after a retryable error
532    /// (its `retry.max_retries`). See [`NodeContext::is_last_attempt`].
533    pub max_retries: u32,
534    /// Snapshot of the frame's variables at the time the node started.
535    pub pool: VariablePool,
536    pub services: Arc<Services>,
537    pub clock: Arc<dyn Clock>,
538    /// Present when the node is resumed after pausing.
539    pub resume: Option<Resume>,
540    /// Present for container nodes.
541    pub subgraph: Option<Arc<dyn Subgraph>>,
542    /// Present when the run has linked workflows: the child runs a node may start.
543    #[cfg(feature = "subagents")]
544    pub children: Option<Arc<dyn ChildRuns>>,
545    /// Absolute deadline of the current attempt in [`Clock::now_ms`] time, when
546    /// the node has an effective timeout. See [`NodeContext::remaining`].
547    pub deadline_ms: Option<u64>,
548    sink: EventSink,
549    /// The run's secret registry, when the engine provides one.
550    secret_values: Option<Arc<SecretSet>>,
551    /// The run's token and cost budget, when the engine provides one.
552    budget: Option<Arc<crate::budget::RunBudget>>,
553    /// The checkpoint of this execution (nodes that track their turns).
554    progress: Option<Arc<crate::budget::NodeProgress>>,
555}
556
557impl fmt::Debug for NodeContext {
558    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
559        f.debug_struct("NodeContext")
560            .field("node_id", &self.node_id)
561            .field("exec_id", &self.exec_id)
562            .field("frame", &self.frame)
563            .field("attempt", &self.attempt)
564            .finish_non_exhaustive()
565    }
566}
567
568impl NodeContext {
569    /// The idempotency key of this node execution's side effects:
570    /// `<run_id>:<exec_id>` (just `exec_id` when the run has no `sys.run_id`).
571    ///
572    /// Execution is at-least-once per node: a node can run again after a retry,
573    /// or after its run was preempted and resumed (the snapshot keeps the
574    /// `exec_id`). The key is the same in all those cases and different for
575    /// every other execution (another run, another loop iteration), so a
576    /// downstream service that dedupes on it applies the effect once. Hosts send
577    /// it as `Idempotency-Key` (the `http-request` node) or hand it to plugins.
578    ///
579    /// @example
580    /// // "run-1a2b:1a20151eb86-997f9542-0"
581    /// let key = ctx.idempotency_key();
582    pub fn idempotency_key(&self) -> String {
583        match self.pool.get(&Selector::of(crate::pool::SYS, "run_id")) {
584            Some(Value::String(run_id)) if !run_id.is_empty() => format!("{run_id}:{}", self.exec_id),
585            _ => self.exec_id.to_string(),
586        }
587    }
588
589    /// Construct a context. Used by the engine and by node unit tests.
590    #[allow(clippy::too_many_arguments)]
591    pub fn new(
592        node_id: impl Into<Arc<str>>,
593        exec_id: impl Into<Arc<str>>,
594        frame: FrameId,
595        attempt: u32,
596        pool: VariablePool,
597        services: Arc<Services>,
598        clock: Arc<dyn Clock>,
599        sink: EventSink,
600    ) -> Self {
601        Self {
602            node_id: node_id.into(),
603            exec_id: exec_id.into(),
604            frame,
605            attempt,
606            max_retries: 0,
607            pool,
608            services,
609            clock,
610            resume: None,
611            subgraph: None,
612            #[cfg(feature = "subagents")]
613            children: None,
614            deadline_ms: None,
615            sink,
616            secret_values: None,
617            budget: None,
618            progress: None,
619        }
620    }
621
622    /// Hand the node the run's budget and, for a node that tracks its turns,
623    /// the progress of this execution.
624    pub fn with_budget(
625        mut self,
626        budget: Arc<crate::budget::RunBudget>,
627        progress: Option<Arc<crate::budget::NodeProgress>>,
628    ) -> Self {
629        self.budget = Some(budget);
630        self.progress = progress;
631        self
632    }
633
634    /// The run's token and cost budget, `None` outside the engine.
635    pub fn budget(&self) -> Option<&crate::budget::RunBudget> {
636        self.budget.as_deref()
637    }
638
639    /// Charge one model response to the run's budget: `usage` and its cost in
640    /// micro units. For a node that tracks its turns ([`Node::tracks_turns`]):
641    /// the engine charges any other node's usage itself when it completes, so
642    /// such a node must not call this (its usage would count twice).
643    ///
644    /// @throws NodeError - `limit_exceeded` when a limit is passed: the run stops.
645    pub fn charge(&self, usage: &crate::event::Usage, cost_micros: u64) -> Result<(), NodeError> {
646        // Spent whatever the budget says: a node that fails still counts it in the run.
647        if let Some(progress) = &self.progress {
648            progress.add_charged(usage);
649        }
650        match &self.budget {
651            Some(budget) => budget.charge(usage, cost_micros),
652            None => Ok(()),
653        }
654    }
655
656    /// Before a model call: stop the run when its budget is spent.
657    ///
658    /// @throws NodeError - `limit_exceeded`: nothing is left, the run stops.
659    pub fn check_budget(&self) -> Result<(), NodeError> {
660        match &self.budget {
661            Some(budget) => budget.stop_if_spent(),
662            None => Ok(()),
663        }
664    }
665
666    /// Charge the final answer a node made because its budget ran low: it is
667    /// counted, and may pass the limit by this one answer instead of failing it.
668    pub fn charge_final(&self, usage: &crate::event::Usage, cost_micros: u64) {
669        if let Some(progress) = &self.progress {
670            progress.add_charged(usage);
671        }
672        if let Some(budget) = &self.budget {
673            budget.record(usage, cost_micros);
674        }
675    }
676
677    /// Keep `state` as this execution's progress. Its next attempt (a retry,
678    /// or the attempt after the run was preempted and resumed) gets it from
679    /// [`NodeContext::checkpointed`]. Does nothing for a node that does not
680    /// track its turns.
681    pub fn checkpoint(&self, state: serde_json::Value) {
682        if let Some(progress) = &self.progress {
683            progress.set(state);
684        }
685    }
686
687    /// Whether checkpoints are kept for this node (it tracks its turns and runs in an engine).
688    pub fn keeps_checkpoints(&self) -> bool {
689        self.progress.is_some()
690    }
691
692    /// The checkpoint an earlier attempt of this execution kept.
693    pub fn checkpointed(&self) -> Option<serde_json::Value> {
694        self.progress.as_ref().and_then(|progress| progress.get())
695    }
696
697    /// A context with an empty pool and a no-op sink, for unit tests.
698    pub fn for_test(node_id: &str, pool: VariablePool) -> Self {
699        Self::new(
700            node_id,
701            format!("{node_id}-exec"),
702            Arc::from(""),
703            1,
704            pool,
705            Arc::new(Services::new()),
706            Arc::new(NoTimerClock),
707            Arc::new(|_| {}),
708        )
709    }
710
711    pub fn with_services(mut self, services: Arc<Services>) -> Self {
712        self.services = services;
713        self
714    }
715
716    pub fn with_sink(mut self, sink: EventSink) -> Self {
717        self.sink = sink;
718        self
719    }
720
721    pub fn with_resume(mut self, resume: Option<Resume>) -> Self {
722        self.resume = resume;
723        self
724    }
725
726    pub fn with_subgraph(mut self, subgraph: Option<Arc<dyn Subgraph>>) -> Self {
727        self.subgraph = subgraph;
728        self
729    }
730
731    /// The child runs this node may start (see [`ChildRuns`]).
732    #[cfg(feature = "subagents")]
733    pub fn with_children(mut self, children: Option<Arc<dyn ChildRuns>>) -> Self {
734        self.children = children;
735        self
736    }
737
738    /// Set how many times the engine retries this node (`retry.max_retries`).
739    pub fn with_max_retries(mut self, max_retries: u32) -> Self {
740        self.max_retries = max_retries;
741        self
742    }
743
744    /// Whether the engine will not retry this node after this attempt fails
745    /// (a model node then fails over to a fallback model on a rate limit
746    /// instead of leaving the wait to the retry).
747    pub fn is_last_attempt(&self) -> bool {
748        self.attempt > self.max_retries
749    }
750
751    pub fn with_deadline(mut self, deadline_ms: Option<u64>) -> Self {
752        self.deadline_ms = deadline_ms;
753        self
754    }
755
756    /// Attach the run's secret registry (see [`NodeContext::observe_secret`]).
757    pub fn with_secret_values(mut self, secret_values: Arc<SecretSet>) -> Self {
758        self.secret_values = Some(secret_values);
759        self
760    }
761
762    /// Register plaintext this node handles as a secret, so the engine scrubs it
763    /// from every later node error message of the run. A no-op outside the engine.
764    pub fn observe_secret(&self, plaintext: &str) {
765        if let Some(secret_values) = &self.secret_values {
766            secret_values.observe_plaintext(plaintext);
767        }
768    }
769
770    /// The run's secret registry, for a node that keeps text beyond the run
771    /// (a saved note, for example) and must mask the secrets in it first. It
772    /// only masks: the values themselves cannot be read from it. `None`
773    /// outside the engine.
774    pub fn secret_values(&self) -> Option<Arc<SecretSet>> {
775        self.secret_values.clone()
776    }
777
778    /// Time left before the current attempt times out, if it has a deadline.
779    /// Nodes that block synchronously (e.g. an embedded interpreter) should
780    /// cap their own work by this.
781    pub fn remaining(&self) -> Option<Duration> {
782        self.deadline_ms.map(|deadline| Duration::from_millis(deadline.saturating_sub(self.clock.now_ms())))
783    }
784
785    /// Look up a host service.
786    pub fn service<T: Any + Send + Sync>(&self) -> Option<&T> {
787        self.services.get::<T>()
788    }
789
790    /// Look up a host service or fail with a descriptive error.
791    pub fn require_service<T: Any + Send + Sync>(&self, what: &str) -> Result<&T, NodeError> {
792        self.services.get::<T>().ok_or_else(|| NodeError::fatal("missing_service", format!("no {what} configured")))
793    }
794
795    /// Resolve a selector against the pool snapshot.
796    pub fn get(&self, selector: &Selector) -> Option<Value> {
797        self.pool.get(selector)
798    }
799
800    /// Stream an incremental chunk for output `field`.
801    ///
802    /// Allocates the field name for every chunk; nodes that stream many chunks
803    /// should keep the name in an `Arc<str>` and use [`NodeContext::chunk_shared`].
804    pub fn chunk(&self, field: &str, chunk: impl Into<String>) {
805        self.chunk_shared(&Arc::from(field), chunk);
806    }
807
808    /// Stream an incremental chunk for output `field`, sharing the field name
809    /// (no allocation besides the chunk text itself).
810    ///
811    /// ```
812    /// # use std::sync::Arc;
813    /// # let ctx = graphrt_core::NodeContext::for_test("n", graphrt_core::VariablePool::new());
814    /// let field: Arc<str> = Arc::from("text");
815    /// for token in ["Hel", "lo"] {
816    ///     ctx.chunk_shared(&field, token);
817    /// }
818    /// ```
819    pub fn chunk_shared(&self, field: &Arc<str>, chunk: impl Into<String>) {
820        (self.sink)(Event::NodeChunk {
821            frame: self.frame.clone(),
822            node_id: Arc::clone(&self.node_id),
823            exec_id: Arc::clone(&self.exec_id),
824            field: Arc::clone(field),
825            chunk: chunk.into(),
826        });
827    }
828
829    /// Report structured progress.
830    pub fn progress(&self, name: &str, data: Value) {
831        (self.sink)(Event::NodeProgress {
832            frame: self.frame.clone(),
833            node_id: Arc::clone(&self.node_id),
834            exec_id: Arc::clone(&self.exec_id),
835            name: name.to_owned(),
836            data,
837        });
838    }
839
840    /// Whether the host asked for content progress (see [`CaptureContent`]).
841    /// Check it before building content-bearing progress data.
842    pub fn captures_content(&self) -> bool {
843        self.services.get::<CaptureContent>().is_some()
844    }
845
846    /// Raw access to the event sink (used by container implementations).
847    pub fn sink(&self) -> &EventSink {
848        &self.sink
849    }
850}
851
852/// Builds a node from its document.
853pub type NodeFactory = Arc<dyn Fn(&NodeDoc) -> Result<Arc<dyn Node>, ConfigError> + Send + Sync>;
854
855/// Builds a node kind's catalog descriptor.
856pub type DescriptorFn = fn() -> crate::catalog::NodeDescriptor;
857
858/// A catalog descriptor, either given up front or built on first request.
859///
860/// Descriptors carry JSON Schemas and are only read by catalog consumers
861/// (`graphrt nodes`, `GET /v1/nodes`, builders), never while compiling or
862/// running a graph, so built-in kinds build theirs lazily: registering every
863/// built-in eagerly cost about half a millisecond of every process start.
864#[derive(Clone)]
865enum DescriptorSlot {
866    Ready(Box<crate::catalog::NodeDescriptor>),
867    Lazy(Arc<LazyDescriptor>),
868}
869
870struct LazyDescriptor {
871    build: DescriptorFn,
872    built: OnceLock<crate::catalog::NodeDescriptor>,
873}
874
875/// Maps node kinds (`llm`, `if-else`, ...) to factories.
876#[derive(Clone, Default)]
877pub struct Registry {
878    factories: HashMap<String, NodeFactory>,
879    descriptors: HashMap<String, DescriptorSlot>,
880}
881
882impl fmt::Debug for Registry {
883    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
884        let mut kinds: Vec<&String> = self.factories.keys().collect();
885        kinds.sort_unstable();
886        f.debug_struct("Registry").field("kinds", &kinds).finish()
887    }
888}
889
890impl Registry {
891    /// Empty registry.
892    pub fn new() -> Self {
893        Self::default()
894    }
895
896    /// Registry with every built-in core node.
897    pub fn with_builtins() -> Self {
898        let mut r = Self::new();
899        crate::nodes::register_builtins(&mut r);
900        r
901    }
902
903    /// Register (or replace) a factory for `kind`.
904    pub fn register<F>(&mut self, kind: &str, factory: F) -> &mut Self
905    where
906        F: Fn(&NodeDoc) -> Result<Arc<dyn Node>, ConfigError> + Send + Sync + 'static,
907    {
908        self.factories.insert(kind.to_owned(), Arc::new(factory));
909        self
910    }
911
912    /// Register (or replace) a factory together with its catalog descriptor.
913    /// The descriptor's `kind` is the registered node type.
914    pub fn register_described<F>(&mut self, descriptor: crate::catalog::NodeDescriptor, factory: F) -> &mut Self
915    where
916        F: Fn(&NodeDoc) -> Result<Arc<dyn Node>, ConfigError> + Send + Sync + 'static,
917    {
918        let kind = descriptor.kind.clone();
919        self.factories.insert(kind.clone(), Arc::new(factory));
920        self.descriptors.insert(kind, DescriptorSlot::Ready(Box::new(descriptor)));
921        self
922    }
923
924    /// Register a factory whose catalog descriptor is built by `descriptor` the
925    /// first time it is requested. Use this for kinds registered on every start
926    /// (built-ins), so processes that never list the catalog skip building it.
927    /// The built descriptor's `kind` must be `kind`.
928    pub fn register_lazily_described<F>(&mut self, kind: &str, descriptor: DescriptorFn, factory: F) -> &mut Self
929    where
930        F: Fn(&NodeDoc) -> Result<Arc<dyn Node>, ConfigError> + Send + Sync + 'static,
931    {
932        self.factories.insert(kind.to_owned(), Arc::new(factory));
933        let slot = LazyDescriptor { build: descriptor, built: OnceLock::new() };
934        self.descriptors.insert(kind.to_owned(), DescriptorSlot::Lazy(Arc::new(slot)));
935        self
936    }
937
938    /// Attach or replace the descriptor of an already-registered kind.
939    pub fn describe(&mut self, descriptor: crate::catalog::NodeDescriptor) -> &mut Self {
940        if self.factories.contains_key(&descriptor.kind) {
941            self.descriptors.insert(descriptor.kind.clone(), DescriptorSlot::Ready(Box::new(descriptor)));
942        }
943        self
944    }
945
946    /// Descriptor of a kind. Kinds registered without one get a bare descriptor.
947    pub fn descriptor(&self, kind: &str) -> Option<crate::catalog::NodeDescriptor> {
948        if !self.factories.contains_key(kind) {
949            return None;
950        }
951        let descriptor = match self.descriptors.get(kind) {
952            None => crate::catalog::NodeDescriptor::bare(kind),
953            Some(DescriptorSlot::Ready(descriptor)) => (**descriptor).clone(),
954            Some(DescriptorSlot::Lazy(slot)) => slot.built.get_or_init(slot.build).clone(),
955        };
956        Some(descriptor)
957    }
958
959    /// Borrowed descriptor of a kind registered with one (`None` for unknown
960    /// kinds and kinds registered without a descriptor). Builds a lazy
961    /// descriptor on first use.
962    pub fn descriptor_ref(&self, kind: &str) -> Option<&crate::catalog::NodeDescriptor> {
963        match self.descriptors.get(kind)? {
964            DescriptorSlot::Ready(descriptor) => Some(descriptor),
965            DescriptorSlot::Lazy(slot) => Some(slot.built.get_or_init(slot.build)),
966        }
967    }
968
969    /// Catalog of every registered kind, sorted by kind.
970    pub fn descriptors(&self) -> Vec<crate::catalog::NodeDescriptor> {
971        let mut kinds: Vec<&String> = self.factories.keys().collect();
972        kinds.sort_unstable();
973        kinds.into_iter().filter_map(|k| self.descriptor(k)).collect()
974    }
975
976    /// Register an alias resolving to an already-registered kind.
977    pub fn alias(&mut self, alias: &str, kind: &str) -> &mut Self {
978        if let Some(f) = self.factories.get(kind).cloned() {
979            self.factories.insert(alias.to_owned(), f);
980        }
981        self
982    }
983
984    pub fn contains(&self, kind: &str) -> bool {
985        self.factories.contains_key(kind)
986    }
987
988    pub fn kinds(&self) -> impl Iterator<Item = &str> {
989        self.factories.keys().map(String::as_str)
990    }
991
992    /// Build a node from its document.
993    pub fn build(&self, doc: &NodeDoc) -> Result<Arc<dyn Node>, ConfigError> {
994        let factory = self.factories.get(&doc.kind).ok_or_else(|| {
995            let suggestion = crate::validate::suggest(&doc.kind, self.kinds());
996            ConfigError::new(
997                doc,
998                format!("unknown node type `{}`{}", doc.kind, crate::validate::did_you_mean(&suggestion)),
999            )
1000        })?;
1001        factory(doc)
1002    }
1003}
1004
1005/// Helper for factories: parse the node config into `T`, mapping errors to [`ConfigError`].
1006pub fn parse_config<T: serde::de::DeserializeOwned>(doc: &NodeDoc) -> Result<T, ConfigError> {
1007    crate::dsl::parse_config_at(&doc.config).map_err(|(path, e)| {
1008        let error = ConfigError::new(doc, e.to_string());
1009        if path == "." { error } else { error.at_field(path) }
1010    })
1011}
1012
1013#[cfg(test)]
1014mod tests {
1015    use super::*;
1016
1017    #[test]
1018    fn idempotency_keys_name_the_run_and_the_node_execution() {
1019        let mut pool = VariablePool::new();
1020        pool.insert(crate::pool::SYS, "run_id", Value::from("run-7"));
1021        assert_eq!(NodeContext::for_test("h", pool).idempotency_key(), "run-7:h-exec");
1022        // A retry keeps the execution id, so the key.
1023        let mut pool = VariablePool::new();
1024        pool.insert(crate::pool::SYS, "run_id", Value::from("run-7"));
1025        let mut retry = NodeContext::for_test("h", pool);
1026        retry.attempt = 3;
1027        assert_eq!(retry.idempotency_key(), "run-7:h-exec");
1028        // Without a run id (a node run outside a run), the execution id alone.
1029        assert_eq!(NodeContext::for_test("h", VariablePool::new()).idempotency_key(), "h-exec");
1030    }
1031}