Skip to main content

adk_graph/
node.rs

1//! Node types for graph execution
2//!
3//! Nodes are the computational units in a graph. They receive state and return updates.
4
5use crate::error::Result;
6use crate::interrupt::Interrupt;
7use crate::state::State;
8use crate::stream::StreamEvent;
9use crate::timeout::ProgressHandle;
10use async_trait::async_trait;
11use serde_json::Value;
12use std::collections::HashMap;
13use std::future::Future;
14use std::pin::Pin;
15use std::sync::Arc;
16
17/// Configuration passed to nodes during execution
18#[derive(Clone)]
19pub struct ExecutionConfig {
20    /// Thread identifier for checkpointing
21    pub thread_id: String,
22    /// Resume from a specific checkpoint
23    pub resume_from: Option<String>,
24    /// Answers to pauses, keyed by what paused.
25    ///
26    /// | Key | Who reads the value |
27    /// |-----|---------------------|
28    /// | A continuation key such as `interrupt-1` | The `#[entrypoint]` interrupt site with that key, which returns it instead of suspending |
29    /// | The name of a graph node that paused with a dynamic interrupt | That node, through [`NodeContext::resume_value`], in the step that resumes it |
30    ///
31    /// A graph node's answer is not written to state, so it answers one pause: a
32    /// node that runs again later, such as in the next pass of a loop or on the
33    /// next turn of a [`GraphAgent`](crate::agent::GraphAgent), pauses again.
34    pub resume_values: HashMap<String, Value>,
35    /// Answers bind to interrupt ids only (LangGraph's strict resume).
36    ///
37    /// With it, every key of [`resume_values`](Self::resume_values) must be the id of a
38    /// pause pending in the thread ([`Interrupt::id`](crate::interrupt::Interrupt::id)):
39    /// an answer to a pause already answered, to a node by name, or to a question the
40    /// node no longer asks is refused with
41    /// [`GraphError::ResumeRejected`](crate::error::GraphError::ResumeRejected) before any
42    /// node runs. Off by default, where a node name answers that node's pause too.
43    pub strict_resume: bool,
44    /// How many super-steps one run may take before it fails with
45    /// [`GraphError::RecursionLimitExceeded`](crate::error::GraphError::RecursionLimitExceeded).
46    ///
47    /// `None` uses the graph's own limit, set with
48    /// [`CompiledGraph::with_recursion_limit`](crate::graph::CompiledGraph::with_recursion_limit)
49    /// or [`GraphAgentBuilder::recursion_limit`](crate::agent::GraphAgentBuilder::recursion_limit)
50    /// (100 when neither is set); a value here overrides it for this run.
51    pub recursion_limit: Option<usize>,
52    /// Additional configuration
53    pub metadata: HashMap<String, Value>,
54    /// The invocation this graph run belongs to, when it has one.
55    ///
56    /// An [`AgentNode`] runs a real agent, and that agent expects the identity,
57    /// services, and cancellation of the run it belongs to. Without a parent the node
58    /// has to fabricate them, which makes an agent behave differently inside a graph
59    /// than outside it. Set this with
60    /// [`ExecutionConfig::with_parent_context`] to carry them through; leaving it
61    /// unset is standalone mode and is what a graph invoked outside a `Runner` gets.
62    pub parent_context: Option<Arc<dyn adk_core::InvocationContext>>,
63    /// When the run writes each super-step's checkpoint. Defaults to
64    /// [`Durability::Sync`](crate::checkpoint::Durability::Sync).
65    pub durability: crate::checkpoint::Durability,
66    /// Cancels a functional-API run.
67    ///
68    /// An `#[entrypoint]` run hands this token to its `TaskContext` and stops when
69    /// it is cancelled: the task running at that moment is abandoned, no later task
70    /// starts, and the run returns
71    /// [`GraphError::Cancelled`](crate::error::GraphError::Cancelled). Unset, the
72    /// run gets a token nobody else holds.
73    #[cfg(feature = "functional")]
74    pub cancellation_token: Option<tokio_util::sync::CancellationToken>,
75    /// Where agent nodes forward their agents' events as the agents produce them.
76    ///
77    /// Set by [`GraphAgent`](crate::agent::GraphAgent), which streams these events
78    /// to its caller, so a runner shows and records them while the graph runs.
79    pub(crate) event_sink: Option<tokio::sync::mpsc::UnboundedSender<adk_core::Event>>,
80    /// The lineage root a subgraph's run keys its governed nodes' records by, derived from
81    /// the parent's, so a fork of the parent finds the records its source wrote.
82    pub(crate) lineage_root: Option<String>,
83}
84
85impl ExecutionConfig {
86    /// Create a new config with the given thread ID
87    pub fn new(thread_id: &str) -> Self {
88        Self {
89            thread_id: thread_id.to_string(),
90            resume_from: None,
91            resume_values: HashMap::new(),
92            strict_resume: false,
93            recursion_limit: None,
94            metadata: HashMap::new(),
95            parent_context: None,
96            durability: crate::checkpoint::Durability::default(),
97            #[cfg(feature = "functional")]
98            cancellation_token: None,
99            event_sink: None,
100            lineage_root: None,
101        }
102    }
103
104    /// Lets the caller cancel a functional-API run with `token`.
105    ///
106    /// See [`ExecutionConfig::cancellation_token`].
107    ///
108    /// # Example
109    ///
110    /// ```
111    /// use adk_graph::node::ExecutionConfig;
112    /// use tokio_util::sync::CancellationToken;
113    ///
114    /// let token = CancellationToken::new();
115    /// let config = ExecutionConfig::new("triage-7").with_cancellation_token(token.clone());
116    /// token.cancel();
117    /// assert!(config.cancellation_token.is_some_and(|token| token.is_cancelled()));
118    /// ```
119    #[cfg(feature = "functional")]
120    #[must_use]
121    pub fn with_cancellation_token(mut self, token: tokio_util::sync::CancellationToken) -> Self {
122        self.cancellation_token = Some(token);
123        self
124    }
125
126    /// Forwards agent nodes' events to `sink` as their agents produce them.
127    pub(crate) fn with_event_sink(
128        mut self,
129        sink: tokio::sync::mpsc::UnboundedSender<adk_core::Event>,
130    ) -> Self {
131        self.event_sink = Some(sink);
132        self
133    }
134
135    /// Sets when the run writes each super-step's checkpoint.
136    ///
137    /// # Example
138    ///
139    /// ```
140    /// use adk_graph::checkpoint::Durability;
141    /// use adk_graph::node::ExecutionConfig;
142    ///
143    /// let config = ExecutionConfig::new("thread").with_durability(Durability::Exit);
144    /// assert_eq!(config.durability, Durability::Exit);
145    /// ```
146    pub fn with_durability(mut self, durability: crate::checkpoint::Durability) -> Self {
147        self.durability = durability;
148        self
149    }
150
151    /// Carry the invocation this graph run belongs to into its nodes.
152    ///
153    /// An [`AgentNode`] then presents the caller's identity, services, request
154    /// context, and cancellation to the agent it runs, instead of a synthetic
155    /// standalone context.
156    #[must_use]
157    pub fn with_parent_context(mut self, parent: Arc<dyn adk_core::InvocationContext>) -> Self {
158        self.parent_context = Some(parent);
159        self
160    }
161
162    /// Overrides the graph's recursion limit for this run.
163    ///
164    /// # Example
165    ///
166    /// ```
167    /// use adk_graph::node::ExecutionConfig;
168    ///
169    /// let config = ExecutionConfig::new("thread").with_recursion_limit(500);
170    /// assert_eq!(config.recursion_limit, Some(500));
171    /// assert_eq!(ExecutionConfig::new("thread").recursion_limit, None);
172    /// ```
173    pub fn with_recursion_limit(mut self, limit: usize) -> Self {
174        self.recursion_limit = Some(limit);
175        self
176    }
177
178    /// Resume from a specific checkpoint
179    pub fn with_resume_from(mut self, checkpoint_id: &str) -> Self {
180        self.resume_from = Some(checkpoint_id.to_string());
181        self
182    }
183
184    /// Supplies the answer to a pause.
185    ///
186    /// `key` is the key a suspended `#[entrypoint]` run reported, such as
187    /// `interrupt-1`, or the name of a graph node that paused with a dynamic
188    /// interrupt. See [`ExecutionConfig::resume_values`].
189    ///
190    /// # Example
191    ///
192    /// ```
193    /// use adk_graph::node::ExecutionConfig;
194    /// use serde_json::json;
195    ///
196    /// // A functional-API interrupt site.
197    /// let config = ExecutionConfig::new("refund-42")
198    ///     .with_resume_from("checkpoint-id")
199    ///     .with_resume_value("interrupt-1", json!({ "approved": true }));
200    /// assert_eq!(config.resume_values.get("interrupt-1"), Some(&json!({ "approved": true })));
201    ///
202    /// // A graph node named `review` that paused.
203    /// let config = ExecutionConfig::new("refund-42").with_resume_value("review", json!("approve"));
204    /// assert_eq!(config.resume_values.get("review"), Some(&json!("approve")));
205    /// ```
206    #[must_use]
207    pub fn with_resume_value(mut self, key: impl Into<String>, value: Value) -> Self {
208        self.resume_values.insert(key.into(), value);
209        self
210    }
211
212    /// Accepts answers only under the ids of pending pauses; see
213    /// [`ExecutionConfig::strict_resume`].
214    ///
215    /// # Example
216    ///
217    /// ```
218    /// use adk_graph::node::ExecutionConfig;
219    /// use serde_json::json;
220    ///
221    /// let config = ExecutionConfig::new("refund-42")
222    ///     .strict_resume()
223    ///     .with_resume_value("int_3f2a9c0d41b7e6a85c1d2e3f4a5b6c7d", json!({ "approved": true }));
224    /// assert!(config.strict_resume);
225    /// ```
226    #[must_use]
227    pub fn strict_resume(mut self) -> Self {
228        self.strict_resume = true;
229        self
230    }
231
232    /// Add metadata
233    pub fn with_metadata(mut self, key: &str, value: Value) -> Self {
234        self.metadata.insert(key.to_string(), value);
235        self
236    }
237}
238
239impl Default for ExecutionConfig {
240    fn default() -> Self {
241        Self::new(&uuid::Uuid::new_v4().to_string())
242    }
243}
244
245/// Context passed to nodes during execution
246#[derive(Clone)]
247pub struct NodeContext {
248    /// Current graph state (read-only view)
249    pub state: State,
250    /// Configuration for this execution
251    pub config: ExecutionConfig,
252    /// Current step number
253    pub step: usize,
254    /// Optional progress handle for idle timeout tracking.
255    /// When present, calling [`report_progress()`](Self::report_progress) resets the idle timeout counter.
256    progress_handle: Option<ProgressHandle>,
257    /// Set by the executor when this node may invoke other nodes.
258    children: Option<std::sync::Arc<crate::child::ChildInvoker>>,
259    /// The schema of the graph running this node, for a node that projects state.
260    parent_schema: Option<std::sync::Arc<crate::state::StateSchema>>,
261    /// ADK configuration supplied through an additive `CompiledGraph` API.
262    run_config: Option<adk_core::RunConfig>,
263    /// The answer to this node's own pause, in the step that resumes it.
264    resume_value: Option<Value>,
265    /// Whether the node runs through the governed bracket, which sends its call once.
266    governed: bool,
267}
268
269impl NodeContext {
270    /// Create a new node context
271    pub fn new(state: State, config: ExecutionConfig, step: usize) -> Self {
272        Self {
273            state,
274            config,
275            step,
276            progress_handle: None,
277            children: None,
278            parent_schema: None,
279            run_config: None,
280            resume_value: None,
281            governed: false,
282        }
283    }
284
285    /// Whether this execution is a governed node's call, which runs once: an action node
286    /// neither retries it nor hides its failure (spec 3.3 ยง12).
287    pub(crate) fn governed_call(&self) -> bool {
288        self.governed
289    }
290
291    /// Marks this execution as a governed node's call.
292    pub(crate) fn set_governed_call(&mut self) {
293        self.governed = true;
294    }
295
296    /// The answer to this node's pause, when this execution resumes it.
297    ///
298    /// Present only in the step that resumes a node that paused with a dynamic
299    /// interrupt, and only when the caller supplied an answer under the node's
300    /// name with [`ExecutionConfig::with_resume_value`]. A
301    /// [`GraphAgent`](crate::agent::GraphAgent) supplies the turn's text. The
302    /// answer is not written to state, so the next pause asks again.
303    ///
304    /// # Example
305    ///
306    /// ```
307    /// use adk_graph::node::{NodeContext, NodeOutput};
308    ///
309    /// async fn review(ctx: NodeContext) -> adk_graph::Result<NodeOutput> {
310    ///     match ctx.resume_value().and_then(|answer| answer.as_str()) {
311    ///         Some("approve") => Ok(NodeOutput::new()),
312    ///         Some(_) => Ok(NodeOutput::new().with_goto(["rejected"])),
313    ///         None => Ok(NodeOutput::interrupt("approve this refund?")),
314    ///     }
315    /// }
316    /// ```
317    pub fn resume_value(&self) -> Option<&Value> {
318        self.resume_value.as_ref()
319    }
320
321    /// Attaches the answer to this node's pause.
322    pub(crate) fn set_resume_value(&mut self, value: Value) {
323        self.resume_value = Some(value);
324    }
325
326    /// The machinery for invoking other nodes, if this context has it.
327    /// The schema of the graph running this node.
328    ///
329    /// Attached by the executor. A node that projects state between two schemas
330    /// needs it; most nodes do not.
331    pub fn parent_schema(&self) -> Option<std::sync::Arc<crate::state::StateSchema>> {
332        self.parent_schema.clone()
333    }
334
335    /// Attaches the running graph's schema.
336    pub fn set_parent_schema(&mut self, schema: std::sync::Arc<crate::state::StateSchema>) {
337        self.parent_schema = Some(schema);
338    }
339
340    /// Attach per-run ADK configuration for an agent node.
341    pub(crate) fn set_run_config(&mut self, run_config: adk_core::RunConfig) {
342        self.run_config = Some(run_config);
343    }
344
345    pub(crate) fn run_config(&self) -> Option<adk_core::RunConfig> {
346        self.run_config.clone()
347    }
348
349    /// Who the run executing this node acts as, and for whom.
350    ///
351    /// `Some` when the graph runs with a [`RunConfig`](adk_core::RunConfig), such as a
352    /// graph agent under a runner, or a call to
353    /// [`CompiledGraph::invoke_with_run_config`](crate::CompiledGraph::invoke_with_run_config).
354    /// Agent nodes give their agents the resolved context through
355    /// [`ReadonlyContext::acting_context`](adk_core::ReadonlyContext::acting_context).
356    pub fn acting(&self) -> Option<&adk_core::ActingConfig> {
357        self.run_config.as_ref().map(|config| &config.acting)
358    }
359
360    pub(crate) fn child_invoker(&self) -> Option<std::sync::Arc<crate::child::ChildInvoker>> {
361        self.children.clone()
362    }
363
364    /// Attach the machinery for invoking other nodes.
365    pub(crate) fn set_child_invoker(
366        &mut self,
367        invoker: std::sync::Arc<crate::child::ChildInvoker>,
368    ) {
369        self.children = Some(invoker);
370    }
371
372    /// Invoke another node and await its output.
373    ///
374    /// The child sees this node's state with `input` merged over it, and returns
375    /// its updates as one object. Nothing is applied to the graph's state: the
376    /// caller decides what to do with the result.
377    ///
378    /// A child that already completed under the same identity is not run again
379    /// after a resume. See [`crate::child`] for how that identity is formed, and
380    /// why a resumable parent should pass its own run id.
381    ///
382    /// # Errors
383    ///
384    /// Returns [`GraphError::NodeNotFound`](crate::error::GraphError::NodeNotFound)
385    /// when no node has that name, whatever the child returns, and
386    /// [`GraphError::Interrupted`](crate::error::GraphError::Interrupted) when the
387    /// child pauses.
388    pub async fn run_node(&self, child: &str, input: Value) -> Result<Value> {
389        self.run_node_with(child, input, crate::child::RunNodeOptions::default()).await
390    }
391
392    /// Invoke another node with an explicit run id.
393    ///
394    /// # Errors
395    ///
396    /// As [`run_node`](Self::run_node), and additionally when this node was not
397    /// given the ability to invoke children.
398    pub async fn run_node_with(
399        &self,
400        child: &str,
401        input: Value,
402        options: crate::child::RunNodeOptions,
403    ) -> Result<Value> {
404        let invoker = self.children.as_ref().ok_or_else(|| {
405            crate::error::GraphError::InvalidGraph(
406                "this node cannot invoke other nodes: no child invoker was attached".to_string(),
407            )
408        })?;
409        invoker.run(child, input, options, self).await
410    }
411
412    /// Get a value from state
413    pub fn get(&self, key: &str) -> Option<&Value> {
414        self.state.get(key)
415    }
416
417    /// Get a value from state as a specific type
418    pub fn get_as<T: serde::de::DeserializeOwned>(&self, key: &str) -> Option<T> {
419        self.state.get(key).and_then(|v| serde_json::from_value(v.clone()).ok())
420    }
421
422    /// Report progress, resetting the idle timeout counter.
423    ///
424    /// Nodes performing long-running work should call this periodically to
425    /// prevent the idle timeout from firing. If no progress handle is attached
426    /// (e.g., when no idle timeout is configured), this is a no-op.
427    ///
428    /// # Example
429    ///
430    /// ```rust,ignore
431    /// async fn execute(&self, ctx: &NodeContext) -> Result<NodeOutput> {
432    ///     for chunk in large_dataset.chunks(100) {
433    ///         process(chunk).await;
434    ///         ctx.report_progress(); // reset idle timeout
435    ///     }
436    ///     Ok(NodeOutput::new())
437    /// }
438    /// ```
439    pub fn report_progress(&self) {
440        if let Some(handle) = &self.progress_handle {
441            handle.report_progress();
442        }
443    }
444
445    /// Attach a progress handle for idle timeout tracking.
446    ///
447    /// This is called by the executor before running a node with an idle timeout
448    /// policy. Nodes do not need to call this directly.
449    pub fn set_progress_handle(&mut self, handle: ProgressHandle) {
450        self.progress_handle = Some(handle);
451    }
452
453    /// Get a reference to the attached progress handle, if any.
454    pub fn progress_handle(&self) -> Option<&ProgressHandle> {
455        self.progress_handle.as_ref()
456    }
457}
458
459/// Output from a node execution
460#[derive(Default)]
461pub struct NodeOutput {
462    /// State updates to apply
463    pub updates: HashMap<String, Value>,
464    /// Optional interrupt request
465    pub interrupt: Option<Interrupt>,
466    /// Custom stream events
467    pub events: Vec<StreamEvent>,
468    /// Nodes to run next, replacing this node's declared outgoing edges.
469    pub goto: Option<Vec<String>>,
470    /// Nodes of the *parent* graph to run next, when this graph is a subgraph.
471    ///
472    /// A node deep in a nested graph can end its own graph and hand control to a
473    /// node of the graph that holds it.
474    pub goto_parent: Option<Vec<String>>,
475}
476
477impl NodeOutput {
478    /// Create a new empty output
479    pub fn new() -> Self {
480        Self::default()
481    }
482
483    /// Names the nodes to run next, replacing this node's declared edges.
484    ///
485    /// A conditional edge fixes its targets when the graph is built. This does
486    /// not: a node reads state and names any node in the graph, including one it
487    /// has no edge to. Naming [`END`](crate::edge::END) stops the branch.
488    ///
489    /// The declared edges from this node do not also fire. Setting no goto leaves
490    /// the declared edges in charge, which is the default.
491    ///
492    /// # Example
493    ///
494    /// ```
495    /// use adk_graph::node::NodeOutput;
496    /// use serde_json::json;
497    ///
498    /// // Write state and choose the next node in one step.
499    /// let output = NodeOutput::new()
500    ///     .with_update("risk", json!("high"))
501    ///     .with_goto(["escalate"]);
502    /// assert_eq!(output.goto.as_deref(), Some(&["escalate".to_string()][..]));
503    /// ```
504    /// Names nodes of the *parent* graph to run next.
505    ///
506    /// Only meaningful inside a [`SubgraphNode`](crate::subgraph::SubgraphNode).
507    /// The subgraph finishes, its output channels are projected out as usual, and
508    /// the parent continues at the named nodes rather than following the
509    /// subgraph node's own edges. This is the counterpart to LangGraph's
510    /// `Command(goto=..., graph=Command.PARENT)`.
511    ///
512    /// A name the parent does not hold fails the run with
513    /// [`GraphError::UnknownRouteTarget`](crate::error::GraphError::UnknownRouteTarget),
514    /// checked by the parent, which is the only side that knows its own nodes.
515    ///
516    /// # Example
517    ///
518    /// ```
519    /// use adk_graph::node::NodeOutput;
520    /// use serde_json::json;
521    ///
522    /// // Inside a subgraph: give up, and let the parent's escalation path run.
523    /// let output = NodeOutput::new()
524    ///     .with_update("reason", json!("no confident answer"))
525    ///     .with_goto_parent(["escalate"]);
526    /// assert_eq!(output.goto_parent.as_deref(), Some(&["escalate".to_string()][..]));
527    /// ```
528    pub fn with_goto_parent<I, S>(mut self, targets: I) -> Self
529    where
530        I: IntoIterator<Item = S>,
531        S: Into<String>,
532    {
533        self.goto_parent = Some(targets.into_iter().map(Into::into).collect());
534        self
535    }
536
537    pub fn with_goto<I, S>(mut self, targets: I) -> Self
538    where
539        I: IntoIterator<Item = S>,
540        S: Into<String>,
541    {
542        self.goto = Some(targets.into_iter().map(Into::into).collect());
543        self
544    }
545
546    /// Add a state update
547    pub fn with_update(mut self, key: &str, value: impl Into<Value>) -> Self {
548        self.updates.insert(key.to_string(), value.into());
549        self
550    }
551
552    /// Add multiple state updates
553    pub fn with_updates(mut self, updates: HashMap<String, Value>) -> Self {
554        self.updates.extend(updates);
555        self
556    }
557
558    /// Set an interrupt
559    pub fn with_interrupt(mut self, interrupt: Interrupt) -> Self {
560        self.interrupt = Some(interrupt);
561        self
562    }
563
564    /// Add a custom stream event
565    pub fn with_event(mut self, event: StreamEvent) -> Self {
566        self.events.push(event);
567        self
568    }
569
570    /// Create output that triggers a dynamic interrupt
571    pub fn interrupt(message: &str) -> Self {
572        Self::new().with_interrupt(crate::interrupt::interrupt(message))
573    }
574
575    /// Create output that triggers a dynamic interrupt with data
576    pub fn interrupt_with_data(message: &str, data: Value) -> Self {
577        Self::new().with_interrupt(crate::interrupt::interrupt_with_data(message, data))
578    }
579
580    /// Declares the JSON Schema the answer to this output's dynamic interrupt must
581    /// satisfy; checked when the run resumes, before the node runs again.
582    ///
583    /// # Example
584    ///
585    /// ```
586    /// use adk_graph::node::{NodeContext, NodeOutput};
587    /// use serde_json::json;
588    ///
589    /// async fn review(ctx: NodeContext) -> adk_graph::Result<NodeOutput> {
590    ///     match ctx.resume_value() {
591    ///         Some(answer) if answer["approved"] == true => Ok(NodeOutput::new()),
592    ///         Some(_) => Ok(NodeOutput::new().with_goto(["rejected"])),
593    ///         None => Ok(NodeOutput::interrupt("approve this refund?").with_response_schema(json!({
594    ///             "type": "object",
595    ///             "properties": { "approved": { "type": "boolean" } },
596    ///             "required": ["approved"]
597    ///         }))),
598    ///     }
599    /// }
600    /// ```
601    #[must_use]
602    pub fn with_response_schema(mut self, schema: Value) -> Self {
603        self.interrupt = self.interrupt.map(|interrupt| interrupt.with_response_schema(schema));
604        self
605    }
606}
607
608/// A node in the graph
609#[async_trait]
610pub trait Node: Send + Sync {
611    /// Node identifier
612    fn name(&self) -> &str;
613
614    /// Human-readable purpose shown by generic workflow inspectors.
615    fn description(&self) -> &str {
616        "Graph workflow node"
617    }
618
619    /// Runtime capabilities inherited by portable graph topology metadata.
620    fn capabilities(&self) -> adk_core::AgentCapabilities {
621        adk_core::AgentCapabilities::default()
622    }
623
624    /// What kind of step this node is, as a workflow observer labels it in
625    /// [`CompiledGraph::shape`](crate::graph::CompiledGraph::shape) (spec 3.3 ยง12).
626    ///
627    /// Defaults to [`NodeKind::Other`](crate::shape::NodeKind::Other).
628    ///
629    /// # Example
630    ///
631    /// ```
632    /// use adk_graph::node::{FunctionNode, Node, NodeOutput};
633    /// use adk_graph::shape::NodeKind;
634    ///
635    /// let node = FunctionNode::new("receipt", |_ctx| async { Ok(NodeOutput::new()) });
636    /// assert_eq!(node.kind(), NodeKind::Function);
637    /// ```
638    fn kind(&self) -> crate::shape::NodeKind {
639        crate::shape::NodeKind::Other
640    }
641
642    /// The call this node makes, as an approver sees it and as its record binds it, when
643    /// the node is governed (spec 3.3 ยง12, ยง7.1).
644    ///
645    /// The value is shown in full on the decision and its
646    /// [`json_digest`](adk_core::json_digest) is part of the call's action-ledger key, so a
647    /// fork whose call is unchanged is answered from the record. `None`, the default,
648    /// binds the call to the whole state the node reads.
649    ///
650    /// # Example
651    ///
652    /// ```
653    /// use adk_graph::node::{Node, NodeContext, NodeOutput};
654    /// use serde_json::{Value, json};
655    ///
656    /// struct Charge;
657    ///
658    /// #[async_trait::async_trait]
659    /// impl Node for Charge {
660    ///     fn name(&self) -> &str {
661    ///         "pay"
662    ///     }
663    ///     fn call_args(&self, ctx: &NodeContext) -> Option<Value> {
664    ///         Some(json!({ "amountCents": ctx.get("amountCents").cloned()? }))
665    ///     }
666    ///     async fn execute(&self, _ctx: &NodeContext) -> adk_graph::Result<NodeOutput> {
667    ///         Ok(NodeOutput::new())
668    ///     }
669    /// }
670    /// ```
671    fn call_args(&self, _ctx: &NodeContext) -> Option<Value> {
672        None
673    }
674
675    /// Whether this node acts in `ctx`, asked before a governed node's call is authorized
676    /// (spec 3.3 ยง12, ยง7.4).
677    ///
678    /// `Ok(false)` means the node does nothing here, such as an action node whose condition
679    /// is false: a governed node then completes with no writes, and no decision is created
680    /// for a call that would not run. An error means the node cannot act, such as an HTTP
681    /// node whose request cannot be built: a governed node then fails with that error
682    /// without asking anyone. The default is `Ok(true)`.
683    ///
684    /// # Errors
685    ///
686    /// Returns why the node cannot act in `ctx`.
687    ///
688    /// # Example
689    ///
690    /// ```
691    /// use adk_graph::node::{Node, NodeContext, NodeOutput};
692    ///
693    /// struct Refund;
694    ///
695    /// #[async_trait::async_trait]
696    /// impl Node for Refund {
697    ///     fn name(&self) -> &str {
698    ///         "refund"
699    ///     }
700    ///     fn will_act(&self, ctx: &NodeContext) -> adk_graph::Result<bool> {
701    ///         Ok(ctx.get("refund_due").and_then(|due| due.as_bool()).unwrap_or(false))
702    ///     }
703    ///     async fn execute(&self, _ctx: &NodeContext) -> adk_graph::Result<NodeOutput> {
704    ///         Ok(NodeOutput::new())
705    ///     }
706    /// }
707    /// ```
708    fn will_act(&self, _ctx: &NodeContext) -> Result<bool> {
709        Ok(true)
710    }
711
712    /// The graph this node runs, when it is a subgraph, so a workflow observer finds the
713    /// governed nodes inside it (spec 3.3 ยง12). The default is `None`.
714    ///
715    /// # Example
716    ///
717    /// ```
718    /// use adk_graph::node::{FunctionNode, Node, NodeOutput};
719    ///
720    /// let node = FunctionNode::new("receipt", |_ctx| async { Ok(NodeOutput::new()) });
721    /// assert!(node.subgraph().is_none());
722    /// ```
723    fn subgraph(&self) -> Option<&crate::graph::CompiledGraph> {
724        None
725    }
726
727    /// Runs exactly `args`: an approver's edit of [`Node::call_args`] (spec 3.3 ยง7.1, ยง7.5).
728    ///
729    /// Called instead of [`Node::execute`] when an approver edited a governed node's call.
730    /// It must send the call it is given and nothing else.
731    ///
732    /// # Errors
733    ///
734    /// The default returns [`GovernedError::EditUnsupported`](crate::governed::GovernedError::EditUnsupported):
735    /// the node cannot run an edited call, so the edited call is refused and nothing runs.
736    ///
737    /// # Example
738    ///
739    /// ```
740    /// use adk_graph::node::{Node, NodeContext, NodeOutput};
741    /// use serde_json::Value;
742    ///
743    /// struct Charge;
744    ///
745    /// #[async_trait::async_trait]
746    /// impl Node for Charge {
747    ///     fn name(&self) -> &str {
748    ///         "pay"
749    ///     }
750    ///     async fn execute(&self, _ctx: &NodeContext) -> adk_graph::Result<NodeOutput> {
751    ///         Ok(NodeOutput::new())
752    ///     }
753    ///     async fn run_call(&self, _ctx: &NodeContext, args: Value) -> adk_graph::Result<NodeOutput> {
754    ///         Ok(NodeOutput::new().with_update("charged", args["amountCents"].clone()))
755    ///     }
756    /// }
757    /// ```
758    async fn run_call(&self, _ctx: &NodeContext, _args: Value) -> Result<NodeOutput> {
759        Err(crate::governed::GovernedError::EditUnsupported { node: self.name().to_string() }
760            .into())
761    }
762
763    /// Execute the node and return state updates
764    async fn execute(&self, ctx: &NodeContext) -> Result<NodeOutput>;
765
766    /// Rejects a node that cannot execute, before the graph runs.
767    ///
768    /// Called for every node by [`StateGraph::compile`](crate::graph::StateGraph::compile), so a configuration whose
769    /// backend is unavailable fails while the graph is being built rather than
770    /// part-way through a run, when earlier nodes may already have had side effects.
771    ///
772    /// # Errors
773    ///
774    /// Returns an error describing what is unavailable. The default accepts the node.
775    /// Checks this node against the schema of the graph that holds it.
776    ///
777    /// Called by [`StateGraph::compile`](crate::graph::StateGraph::compile) for
778    /// every node, so a node that has requirements on its parent states them
779    /// before anything runs. Defaults to accepting any parent.
780    ///
781    /// [`SubgraphNode`](crate::subgraph::SubgraphNode) uses this to reject a
782    /// channel mapping that names a channel neither side declares.
783    fn validate_against(&self, _parent: &crate::state::StateSchema) -> Result<()> {
784        Ok(())
785    }
786
787    fn validate(&self) -> Result<()> {
788        Ok(())
789    }
790
791    /// Streams execution events for this node.
792    ///
793    /// An implementation must report the node's state updates by yielding a
794    /// [`StreamEvent::Updates`] event, because a streaming executor takes the
795    /// updates from this stream rather than executing the node a second time.
796    /// The default implementation wraps [`Node::execute`] and does so.
797    fn execute_stream<'a>(
798        &'a self,
799        ctx: &'a NodeContext,
800    ) -> Pin<Box<dyn futures::Stream<Item = Result<StreamEvent>> + Send + 'a>> {
801        let name = self.name().to_string();
802        Box::pin(async_stream::stream! {
803            match self.execute(ctx).await {
804                Ok(output) => {
805                    for event in output.events {
806                        yield Ok(event);
807                    }
808                    // A goto and an interrupt have no other way through: this path
809                    // yields events, not a NodeOutput, so the executor reads both
810                    // back off the stream.
811                    if let Some(targets) = output.goto {
812                        yield Ok(StreamEvent::route_dispatched(&name, targets));
813                    }
814                    if let Some(interrupt) = output.interrupt {
815                        yield Ok(match interrupt {
816                            crate::interrupt::Interrupt::Dynamic {
817                                message, data, response_schema, ..
818                            } => StreamEvent::NodeInterrupt { node: name.clone(), message, data, response_schema },
819                            other => StreamEvent::node_interrupt(&name, &other.to_string(), None),
820                        });
821                    }
822                    yield Ok(StreamEvent::Updates { node: name, updates: output.updates });
823                }
824                Err(e) => yield Err(e),
825            }
826        })
827    }
828}
829
830/// Type alias for boxed node
831pub type BoxedNode = Box<dyn Node>;
832
833/// Type alias for async function signature
834pub type AsyncNodeFn = Box<
835    dyn Fn(NodeContext) -> Pin<Box<dyn Future<Output = Result<NodeOutput>> + Send>> + Send + Sync,
836>;
837
838/// Function node - wraps an async function as a node
839pub struct FunctionNode {
840    name: String,
841    func: AsyncNodeFn,
842}
843
844impl FunctionNode {
845    /// Create a new function node
846    pub fn new<F, Fut>(name: &str, func: F) -> Self
847    where
848        F: Fn(NodeContext) -> Fut + Send + Sync + 'static,
849        Fut: Future<Output = Result<NodeOutput>> + Send + 'static,
850    {
851        Self { name: name.to_string(), func: Box::new(move |ctx| Box::pin(func(ctx))) }
852    }
853}
854
855#[async_trait]
856impl Node for FunctionNode {
857    fn name(&self) -> &str {
858        &self.name
859    }
860
861    fn kind(&self) -> crate::shape::NodeKind {
862        crate::shape::NodeKind::Function
863    }
864
865    async fn execute(&self, ctx: &NodeContext) -> Result<NodeOutput> {
866        // The closure takes an owned context, so everything the executor attached
867        // is carried across by cloning it.
868        (self.func)(ctx.clone()).await
869    }
870}
871
872/// Passthrough node - just passes state through unchanged
873pub struct PassthroughNode {
874    name: String,
875}
876
877impl PassthroughNode {
878    /// Create a new passthrough node
879    pub fn new(name: &str) -> Self {
880        Self { name: name.to_string() }
881    }
882}
883
884#[async_trait]
885impl Node for PassthroughNode {
886    fn name(&self) -> &str {
887        &self.name
888    }
889
890    async fn execute(&self, _ctx: &NodeContext) -> Result<NodeOutput> {
891        Ok(NodeOutput::new())
892    }
893}
894
895/// Type alias for agent node input mapper
896pub type AgentInputMapper = Box<dyn Fn(&State) -> adk_core::Content + Send + Sync>;
897
898/// Type alias for agent node output mapper
899pub type AgentOutputMapper =
900    Box<dyn Fn(&[adk_core::Event]) -> HashMap<String, Value> + Send + Sync>;
901
902/// Chooses an [`AgentNode`]'s successors from the updates it just produced.
903///
904/// Returning `None` leaves the node's declared edges in charge.
905pub type AgentGotoMapper =
906    Box<dyn Fn(&HashMap<String, Value>) -> Option<Vec<String>> + Send + Sync>;
907
908/// Wrapper to use an existing ADK Agent as a graph node
909pub struct AgentNode {
910    name: String,
911    #[allow(dead_code)]
912    agent: Arc<dyn adk_core::Agent>,
913    /// Map state to agent input content
914    input_mapper: AgentInputMapper,
915    /// Map agent events to state updates
916    output_mapper: AgentOutputMapper,
917    /// Choose successors from the mapped updates, replacing declared edges.
918    goto_mapper: Option<AgentGotoMapper>,
919}
920
921impl AgentNode {
922    /// Create a new agent node
923    ///
924    /// Without mappers, the agent's input is the last `messages` entry, or else the
925    /// `input` channel, and its output is a `messages` update with one entry per
926    /// response it completes, whole whether the model streamed it or not.
927    pub fn new(agent: Arc<dyn adk_core::Agent>) -> Self {
928        let name = agent.name().to_string();
929        Self {
930            name,
931            agent,
932            input_mapper: Box::new(default_input_mapper),
933            output_mapper: Box::new(default_output_mapper),
934            goto_mapper: None,
935        }
936    }
937
938    /// Names the node `name` instead of the agent's name, so one agent can back several
939    /// nodes, or a node id that differs from the agent's name.
940    ///
941    /// # Example
942    ///
943    /// ```no_run
944    /// # use adk_graph::node::AgentNode;
945    /// # fn wire(node: AgentNode) -> AgentNode {
946    /// node.with_name("first_draft")
947    /// # }
948    /// ```
949    #[must_use]
950    pub fn with_name(mut self, name: impl Into<String>) -> Self {
951        self.name = name.into();
952        self
953    }
954
955    /// Set custom input mapper
956    pub fn with_input_mapper<F>(mut self, mapper: F) -> Self
957    where
958        F: Fn(&State) -> adk_core::Content + Send + Sync + 'static,
959    {
960        self.input_mapper = Box::new(mapper);
961        self
962    }
963
964    /// Set custom output mapper
965    ///
966    /// The mapper receives every event the agent yielded, in order: a streamed
967    /// response's partial chunks, then the non-partial event that carries its complete
968    /// content. Skip the events whose `llm_response.partial` is set to read each
969    /// response once, whole.
970    pub fn with_output_mapper<F>(mut self, mapper: F) -> Self
971    where
972        F: Fn(&[adk_core::Event]) -> HashMap<String, Value> + Send + Sync + 'static,
973    {
974        self.output_mapper = Box::new(mapper);
975        self
976    }
977
978    /// Chooses this node's successors from the updates the output mapper produced.
979    ///
980    /// An agent's answer often decides where control goes next. The output mapper
981    /// turns the agent's events into state; this turns that state into a route,
982    /// so the classification is parsed once.
983    ///
984    /// Returning `None` leaves the declared edges in charge. Returning targets
985    /// replaces them, exactly as [`NodeOutput::with_goto`] does for a plain node.
986    ///
987    /// # Example
988    ///
989    /// ```no_run
990    /// # use adk_graph::node::AgentNode;
991    /// # use std::collections::HashMap;
992    /// # fn wire(node: AgentNode) -> AgentNode {
993    /// node.with_goto_mapper(|updates: &HashMap<String, serde_json::Value>| {
994    ///     match updates.get("category").and_then(|v| v.as_str()) {
995    ///         Some("refund") => Some(vec!["refund_desk".to_string()]),
996    ///         Some(_) => Some(vec!["general_desk".to_string()]),
997    ///         None => None,
998    ///     }
999    /// })
1000    /// # }
1001    /// ```
1002    pub fn with_goto_mapper<F>(mut self, mapper: F) -> Self
1003    where
1004        F: Fn(&HashMap<String, Value>) -> Option<Vec<String>> + Send + Sync + 'static,
1005    {
1006        self.goto_mapper = Some(Box::new(mapper));
1007        self
1008    }
1009}
1010
1011/// Default input mapper - looks for "messages" or "input" in state
1012fn default_input_mapper(state: &State) -> adk_core::Content {
1013    // Try to get messages first
1014    if let Some(messages) = state.get("messages")
1015        && let Some(arr) = messages.as_array()
1016        && let Some(last) = arr.last()
1017        && let Some(content) = last.get("content").and_then(|c| c.as_str())
1018    {
1019        return adk_core::Content::new("user").with_text(content);
1020    }
1021
1022    // Try input field
1023    if let Some(input) = state.get("input")
1024        && let Some(text) = input.as_str()
1025    {
1026        return adk_core::Content::new("user").with_text(text);
1027    }
1028
1029    adk_core::Content::new("user")
1030}
1031
1032/// Default output mapper - one "messages" entry per response the agent completes.
1033///
1034/// A streamed response is partial chunks followed by one non-partial event carrying
1035/// its complete content, so only non-partial events are read, as the runner persists
1036/// them. As there, a non-partial event without content takes the chunks streamed
1037/// under its id.
1038fn default_output_mapper(events: &[adk_core::Event]) -> HashMap<String, Value> {
1039    let text_of = |content: &adk_core::Content| -> String {
1040        content.parts.iter().filter_map(adk_core::Part::text).collect()
1041    };
1042    let mut streamed: HashMap<(&str, &str), String> = HashMap::new();
1043    let mut messages = Vec::new();
1044    for event in events {
1045        let key = (event.invocation_id.as_str(), event.id.as_str());
1046        if event.llm_response.partial {
1047            if let Some(content) = event.content() {
1048                streamed.entry(key).or_default().push_str(&text_of(content));
1049            }
1050            continue;
1051        }
1052        let chunks = streamed.remove(&key);
1053        let text = match event.content() {
1054            Some(content) => text_of(content),
1055            None => chunks.unwrap_or_default(),
1056        };
1057        if !text.is_empty() {
1058            messages.push(serde_json::json!({"role": "assistant", "content": text}));
1059        }
1060    }
1061
1062    let mut updates = HashMap::new();
1063    if !messages.is_empty() {
1064        updates.insert("messages".to_string(), Value::Array(messages));
1065    }
1066    updates
1067}
1068
1069#[async_trait]
1070impl Node for AgentNode {
1071    fn name(&self) -> &str {
1072        &self.name
1073    }
1074
1075    fn description(&self) -> &str {
1076        self.agent.description()
1077    }
1078
1079    fn capabilities(&self) -> adk_core::AgentCapabilities {
1080        self.agent.capabilities()
1081    }
1082
1083    fn kind(&self) -> crate::shape::NodeKind {
1084        crate::shape::NodeKind::ModelStep
1085    }
1086
1087    async fn execute(&self, ctx: &NodeContext) -> Result<NodeOutput> {
1088        use futures::StreamExt;
1089
1090        // Map state to input content
1091        let content = (self.input_mapper)(&ctx.state);
1092
1093        // Create a graph invocation context with the agent
1094        let invocation_ctx = Arc::new(GraphInvocationContext::with_parent(
1095            ctx.config.thread_id.clone(),
1096            content,
1097            self.agent.clone(),
1098            ctx.config.parent_context.clone(),
1099            ctx.run_config(),
1100            ctx.state.clone(),
1101        ));
1102
1103        // Run the agent and collect events
1104        let branch = adk_core::ReadonlyContext::branch(invocation_ctx.as_ref()).to_string();
1105        let stream = self.agent.run(invocation_ctx).await.map_err(|e| {
1106            crate::error::GraphError::AgentFailed { node: self.name.clone(), source: Box::new(e) }
1107        })?;
1108
1109        // The first error the agent yields fails the node, as on the streaming
1110        // path, so a model failure is not a successful node with no answer: a
1111        // retry policy applies, and the nodes after it do not run.
1112        let mut stream = stream;
1113        let mut events: Vec<adk_core::Event> = Vec::new();
1114        while let Some(item) = stream.next().await {
1115            match item {
1116                Ok(event) => {
1117                    forward_agent_event(&ctx.config, &branch, &event);
1118                    events.push(event);
1119                }
1120                Err(e) => {
1121                    return Err(crate::error::GraphError::AgentFailed {
1122                        node: self.name.clone(),
1123                        source: Box::new(e),
1124                    });
1125                }
1126            }
1127        }
1128
1129        if let Some(request) =
1130            events.iter().find_map(|event| event.actions.tool_confirmation.clone())
1131        {
1132            return Ok(NodeOutput::new().with_interrupt(
1133                crate::interrupt::GraphToolConfirmationPause::pending_interrupt(
1134                    self.name.clone(),
1135                    request,
1136                ),
1137            ));
1138        }
1139
1140        // Map events to state updates
1141        let updates = (self.output_mapper)(&events);
1142        let goto = self.goto_mapper.as_ref().and_then(|mapper| mapper(&updates));
1143
1144        // Convert agent events to stream events for tracing
1145        let mut output = NodeOutput::new().with_updates(updates);
1146        if let Some(targets) = goto {
1147            output = output.with_goto(targets);
1148        }
1149        for event in &events {
1150            if let Ok(json) = serde_json::to_value(event) {
1151                output = output.with_event(StreamEvent::custom(&self.name, "agent_event", json));
1152            }
1153        }
1154
1155        Ok(output)
1156    }
1157
1158    fn execute_stream<'a>(
1159        &'a self,
1160        ctx: &'a NodeContext,
1161    ) -> Pin<Box<dyn futures::Stream<Item = Result<StreamEvent>> + Send + 'a>> {
1162        use futures::StreamExt;
1163        let name = self.name.clone();
1164        let agent = self.agent.clone();
1165        let input_mapper = &self.input_mapper;
1166        let output_mapper = &self.output_mapper;
1167        let goto_mapper = &self.goto_mapper;
1168        let parent_context = ctx.config.parent_context.clone();
1169        let thread_id = ctx.config.thread_id.clone();
1170        let content = (input_mapper)(&ctx.state);
1171
1172        Box::pin(async_stream::stream! {
1173            tracing::debug!("AgentNode::execute_stream called for {}", name);
1174            let invocation_ctx = Arc::new(GraphInvocationContext::with_parent(
1175                thread_id,
1176                content,
1177                agent.clone(),
1178                parent_context,
1179                ctx.run_config(),
1180                ctx.state.clone(),
1181            ));
1182
1183            let branch = adk_core::ReadonlyContext::branch(invocation_ctx.as_ref()).to_string();
1184            let stream = match agent.run(invocation_ctx).await {
1185                Ok(s) => s,
1186                Err(e) => {
1187                    yield Err(crate::error::GraphError::AgentFailed {
1188                        node: name.clone(),
1189                        source: Box::new(e),
1190                    });
1191                    return;
1192                }
1193            };
1194
1195            tokio::pin!(stream);
1196            let mut all_events = Vec::new();
1197            let mut text_deltas = adk_core::EventTextDeltas::default();
1198
1199            while let Some(result) = stream.next().await {
1200                match result {
1201                    Ok(event) => {
1202                        forward_agent_event(&ctx.config, &branch, &event);
1203                        if let Some(request) = event.actions.tool_confirmation.clone() {
1204                            yield Ok(StreamEvent::node_interrupt(
1205                                &name,
1206                                crate::interrupt::GraphToolConfirmationPause::KIND,
1207                                Some(crate::interrupt::GraphToolConfirmationPause::pending_data(
1208                                    name.clone(),
1209                                    request,
1210                                )),
1211                            ));
1212                            return;
1213                        }
1214                        // Emit streaming event immediately
1215                        if let Some(content) = text_deltas.push(&event).content() {
1216                            let text: String = content.parts.iter().filter_map(|p| p.text()).collect();
1217                            if !text.is_empty() {
1218                                yield Ok(StreamEvent::Message {
1219                                    node: name.clone(),
1220                                    content: text,
1221                                    is_final: false,
1222                                });
1223                            }
1224                        }
1225                        all_events.push(event);
1226                    }
1227                    Err(e) => {
1228                        yield Err(crate::error::GraphError::AgentFailed {
1229                            node: name.clone(),
1230                            source: Box::new(e),
1231                        });
1232                        return;
1233                    }
1234                }
1235            }
1236
1237            // Emit final events
1238            for event in &all_events {
1239                if let Ok(json) = serde_json::to_value(event) {
1240                    yield Ok(StreamEvent::custom(&name, "agent_event", json));
1241                }
1242            }
1243
1244            // Report state updates from this run. Without this the streaming
1245            // executor has no updates to apply and would have to run the agent
1246            // a second time to obtain them.
1247            let updates = (output_mapper)(&all_events);
1248            // Same route the plain path uses: this yields events, not a NodeOutput.
1249            if let Some(targets) = goto_mapper.as_ref().and_then(|mapper| mapper(&updates)) {
1250                yield Ok(StreamEvent::route_dispatched(&name, targets));
1251            }
1252            yield Ok(StreamEvent::Updates { node: name.clone(), updates });
1253        })
1254    }
1255}
1256
1257/// Sends an agent node's event to the run's event sink, when it has one, on the
1258/// node's `branch` unless the agent set one.
1259///
1260/// A confirmation request is not forwarded: the graph reports the pause itself,
1261/// with the checkpoint to resume from, so the caller sees the request once. A
1262/// transfer the agent asks for names an agent of the node's own tree, not the
1263/// caller's, so the forwarded event does not carry it.
1264fn forward_agent_event(config: &ExecutionConfig, branch: &str, event: &adk_core::Event) {
1265    if let Some(sink) = &config.event_sink
1266        && event.actions.tool_confirmation.is_none()
1267    {
1268        let mut event = event.clone();
1269        if event.branch.is_empty() {
1270            event.branch = branch.to_string();
1271        }
1272        event.actions.transfer_to_agent = None;
1273        // The receiver is gone only once the run has finished reporting.
1274        let _ = sink.send(event);
1275    }
1276}
1277
1278/// Full InvocationContext implementation for running agents within graph nodes
1279struct GraphInvocationContext {
1280    invocation_id: String,
1281    user_content: adk_core::Content,
1282    agent: Arc<dyn adk_core::Agent>,
1283    session: Arc<GraphSession>,
1284    run_config: adk_core::RunConfig,
1285    ended: std::sync::atomic::AtomicBool,
1286    /// The invocation this graph run belongs to, when it has one.
1287    ///
1288    /// Present: identity, services, request context, and cancellation come from the
1289    /// caller, so an agent behaves the same inside a graph as outside it.
1290    /// Absent: standalone mode, with the synthetic identity below.
1291    parent: Option<Arc<dyn adk_core::InvocationContext>>,
1292    /// Identity strings, owned because the trait returns them by reference.
1293    user_id: String,
1294    app_name: String,
1295    branch: String,
1296}
1297
1298/// Identity used when a graph runs with no parent invocation.
1299pub(crate) const STANDALONE_USER_ID: &str = "graph_user";
1300/// Application name used when a graph runs with no parent invocation.
1301pub(crate) const STANDALONE_APP_NAME: &str = "graph_app";
1302
1303impl GraphInvocationContext {
1304    /// `thread_id` identifies the session only in standalone mode; with a parent,
1305    /// the agent sees the parent's session, invocation, and identity.
1306    fn with_parent(
1307        thread_id: String,
1308        user_content: adk_core::Content,
1309        agent: Arc<dyn adk_core::Agent>,
1310        parent: Option<Arc<dyn adk_core::InvocationContext>>,
1311        explicit_run_config: Option<adk_core::RunConfig>,
1312        graph_state: State,
1313    ) -> Self {
1314        // The node's events belong to the caller's invocation, as a workflow
1315        // sub-agent's do, so a runner records them under it.
1316        let invocation_id = parent.as_ref().map_or_else(
1317            || uuid::Uuid::new_v4().to_string(),
1318            |parent| parent.invocation_id().to_string(),
1319        );
1320        let session = Arc::new(GraphSession::new(thread_id, parent.clone(), graph_state));
1321        // Add user content to history
1322        session.append_content(user_content.clone());
1323
1324        // A node runs on its own branch below the caller's, so events it produces are
1325        // attributable and do not read as the parent agent's own turn.
1326        let (user_id, app_name, branch, inherited_run_config) = match parent.as_ref() {
1327            Some(parent) => (
1328                parent.user_id().to_string(),
1329                parent.app_name().to_string(),
1330                match parent.branch() {
1331                    "" => agent.name().to_string(),
1332                    existing => format!("{existing}.{}", agent.name()),
1333                },
1334                parent.run_config().clone(),
1335            ),
1336            None => (
1337                STANDALONE_USER_ID.to_string(),
1338                STANDALONE_APP_NAME.to_string(),
1339                "main".to_string(),
1340                adk_core::RunConfig::default(),
1341            ),
1342        };
1343
1344        Self {
1345            invocation_id,
1346            user_content,
1347            agent,
1348            session,
1349            run_config: explicit_run_config.unwrap_or(inherited_run_config),
1350            ended: std::sync::atomic::AtomicBool::new(false),
1351            parent,
1352            user_id,
1353            app_name,
1354            branch,
1355        }
1356    }
1357}
1358
1359// Implement ReadonlyContext (required by CallbackContext)
1360impl adk_core::ReadonlyContext for GraphInvocationContext {
1361    fn invocation_id(&self) -> &str {
1362        &self.invocation_id
1363    }
1364
1365    fn agent_name(&self) -> &str {
1366        self.agent.name()
1367    }
1368
1369    fn user_id(&self) -> &str {
1370        &self.user_id
1371    }
1372
1373    fn app_name(&self) -> &str {
1374        &self.app_name
1375    }
1376
1377    fn session_id(&self) -> &str {
1378        adk_core::Session::id(self.session.as_ref())
1379    }
1380
1381    fn branch(&self) -> &str {
1382        &self.branch
1383    }
1384
1385    fn user_content(&self) -> &adk_core::Content {
1386        &self.user_content
1387    }
1388
1389    fn acting_context(&self) -> adk_core::ActingContext {
1390        self.run_config.acting_context_for(&self.app_name, self.agent.name(), &self.user_id)
1391    }
1392
1393    fn is_authenticated(&self) -> bool {
1394        self.parent.as_ref().is_some_and(|parent| parent.is_authenticated())
1395    }
1396}
1397
1398// Implement CallbackContext (required by InvocationContext)
1399#[async_trait]
1400impl adk_core::CallbackContext for GraphInvocationContext {
1401    fn artifacts(&self) -> Option<Arc<dyn adk_core::Artifacts>> {
1402        self.parent.as_ref().and_then(|parent| parent.artifacts())
1403    }
1404
1405    fn shared_state(&self) -> Option<Arc<adk_core::SharedState>> {
1406        self.parent.as_ref().and_then(|parent| parent.shared_state())
1407    }
1408}
1409
1410// Implement InvocationContext
1411#[async_trait]
1412impl adk_core::InvocationContext for GraphInvocationContext {
1413    fn agent(&self) -> Arc<dyn adk_core::Agent> {
1414        self.agent.clone()
1415    }
1416
1417    fn memory(&self) -> Option<Arc<dyn adk_core::Memory>> {
1418        self.parent.as_ref().and_then(|parent| parent.memory())
1419    }
1420
1421    fn session(&self) -> &dyn adk_core::Session {
1422        self.session.as_ref()
1423    }
1424
1425    fn run_config(&self) -> &adk_core::RunConfig {
1426        &self.run_config
1427    }
1428
1429    fn end_invocation(&self) {
1430        self.ended.store(true, std::sync::atomic::Ordering::SeqCst);
1431        if let Some(parent) = &self.parent {
1432            parent.end_invocation();
1433        }
1434    }
1435
1436    fn ended(&self) -> bool {
1437        self.ended.load(std::sync::atomic::Ordering::SeqCst)
1438            || self.parent.as_ref().is_some_and(|parent| parent.ended())
1439    }
1440
1441    fn is_cancelled(&self) -> bool {
1442        self.parent.as_ref().is_some_and(|parent| parent.is_cancelled())
1443    }
1444
1445    fn user_scopes(&self) -> Vec<String> {
1446        self.parent.as_ref().map(|parent| parent.user_scopes()).unwrap_or_default()
1447    }
1448
1449    fn request_metadata(&self) -> std::collections::HashMap<String, Value> {
1450        self.parent.as_ref().map(|parent| parent.request_metadata()).unwrap_or_default()
1451    }
1452
1453    async fn get_secret(&self, name: &str) -> adk_core::Result<Option<String>> {
1454        match &self.parent {
1455            Some(parent) => parent.get_secret(name).await,
1456            None => Ok(None),
1457        }
1458    }
1459
1460    async fn get_secret_for(
1461        &self,
1462        request: &adk_core::SecretRequest,
1463    ) -> adk_core::Result<Option<String>> {
1464        match &self.parent {
1465            Some(parent) => parent.get_secret_for(request).await,
1466            None => Ok(None),
1467        }
1468    }
1469}
1470
1471/// The session an agent node's agent sees.
1472///
1473/// With a parent invocation it is a view of the caller's session: the same id,
1474/// app, and user, and the session's state, read live, with the graph's state
1475/// layered on top, so an instruction template resolves both. Its conversation is
1476/// the node's own: the input the node's mapper built and what the agent adds.
1477/// Writes through [`adk_core::State::set`] stay in the view. Standalone, the
1478/// session is the graph's thread.
1479struct GraphSession {
1480    /// The thread id, the session id when there is no parent.
1481    thread_id: String,
1482    parent: Option<Arc<dyn adk_core::InvocationContext>>,
1483    state: GraphState,
1484    history: std::sync::RwLock<Vec<adk_core::Content>>,
1485}
1486
1487impl GraphSession {
1488    fn new(
1489        thread_id: String,
1490        parent: Option<Arc<dyn adk_core::InvocationContext>>,
1491        graph_state: State,
1492    ) -> Self {
1493        Self {
1494            thread_id,
1495            state: GraphState::new(parent.clone(), graph_state),
1496            parent,
1497            history: std::sync::RwLock::new(Vec::new()),
1498        }
1499    }
1500
1501    fn append_content(&self, content: adk_core::Content) {
1502        if let Ok(mut h) = self.history.write() {
1503            h.push(content);
1504        }
1505    }
1506}
1507
1508impl adk_core::Session for GraphSession {
1509    fn id(&self) -> &str {
1510        self.parent.as_ref().map_or(self.thread_id.as_str(), |parent| parent.session().id())
1511    }
1512
1513    fn app_name(&self) -> &str {
1514        self.parent.as_ref().map_or(STANDALONE_APP_NAME, |parent| parent.session().app_name())
1515    }
1516
1517    fn user_id(&self) -> &str {
1518        self.parent.as_ref().map_or(STANDALONE_USER_ID, |parent| parent.session().user_id())
1519    }
1520
1521    fn state(&self) -> &dyn adk_core::State {
1522        &self.state
1523    }
1524
1525    fn conversation_history(&self) -> Vec<adk_core::Content> {
1526        self.history.read().ok().map(|h| h.clone()).unwrap_or_default()
1527    }
1528
1529    fn append_to_history(&self, content: adk_core::Content) {
1530        self.append_content(content);
1531    }
1532}
1533
1534/// Session state for an agent node: its own writes, over the graph's state, over
1535/// the caller's session state.
1536struct GraphState {
1537    parent: Option<Arc<dyn adk_core::InvocationContext>>,
1538    graph: State,
1539    data: std::sync::RwLock<std::collections::HashMap<String, serde_json::Value>>,
1540}
1541
1542impl GraphState {
1543    fn new(parent: Option<Arc<dyn adk_core::InvocationContext>>, graph: State) -> Self {
1544        Self { parent, graph, data: std::sync::RwLock::new(std::collections::HashMap::new()) }
1545    }
1546}
1547
1548impl adk_core::State for GraphState {
1549    fn get(&self, key: &str) -> Option<serde_json::Value> {
1550        if let Some(value) = self.data.read().ok().and_then(|data| data.get(key).cloned()) {
1551            return Some(value);
1552        }
1553        if let Some(value) = self.graph.get(key) {
1554            return Some(value.clone());
1555        }
1556        self.parent.as_ref().and_then(|parent| parent.session().state().get(key))
1557    }
1558
1559    fn set(&mut self, key: String, value: serde_json::Value) {
1560        if let Err(msg) = adk_core::validate_state_key(&key) {
1561            tracing::warn!(key = %key, "rejecting invalid state key: {msg}");
1562            return;
1563        }
1564        if let Ok(mut data) = self.data.write() {
1565            data.insert(key, value);
1566        }
1567    }
1568
1569    fn all(&self) -> std::collections::HashMap<String, serde_json::Value> {
1570        let mut all =
1571            self.parent.as_ref().map(|parent| parent.session().state().all()).unwrap_or_default();
1572        all.extend(self.graph.iter().map(|(key, value)| (key.clone(), value.clone())));
1573        if let Ok(data) = self.data.read() {
1574            all.extend(data.iter().map(|(key, value)| (key.clone(), value.clone())));
1575        }
1576        all
1577    }
1578}
1579
1580#[cfg(test)]
1581mod tests {
1582    use super::*;
1583
1584    #[tokio::test]
1585    async fn test_function_node() {
1586        let node = FunctionNode::new("test", |_ctx| async {
1587            Ok(NodeOutput::new().with_update("result", serde_json::json!("success")))
1588        });
1589
1590        assert_eq!(node.name(), "test");
1591
1592        let ctx = NodeContext::new(State::new(), ExecutionConfig::default(), 0);
1593        let output = node.execute(&ctx).await.unwrap();
1594
1595        assert_eq!(output.updates.get("result"), Some(&serde_json::json!("success")));
1596    }
1597
1598    #[tokio::test]
1599    async fn test_passthrough_node() {
1600        let node = PassthroughNode::new("pass");
1601        let ctx = NodeContext::new(State::new(), ExecutionConfig::default(), 0);
1602        let output = node.execute(&ctx).await.unwrap();
1603
1604        assert!(output.updates.is_empty());
1605        assert!(output.interrupt.is_none());
1606    }
1607
1608    #[test]
1609    fn default_output_mapper_writes_each_complete_response_once() {
1610        let event = |id: &str, text: Option<&str>, partial: bool| {
1611            let mut event = adk_core::Event::with_id(id, "invocation");
1612            event.llm_response.partial = partial;
1613            if let Some(text) = text {
1614                event.set_content(adk_core::Content::new("model").with_text(text));
1615            }
1616            event
1617        };
1618        let chunk = |id: &str, text: &str| event(id, Some(text), true);
1619        let mut complete = event("r1", Some("Hello world."), false);
1620        complete.llm_response.provider_metadata =
1621            Some(serde_json::json!({"content_complete": true}));
1622        let mut preamble = event("r1", Some("Let me check."), false);
1623        preamble.llm_response.content.as_mut().unwrap().parts.push(adk_core::Part::FunctionCall {
1624            name: "lookup".to_string(),
1625            args: serde_json::json!({}),
1626            id: Some("call-1".to_string()),
1627            thought_signature: None,
1628        });
1629        let cases = [
1630            // A streamed response ends with one event carrying its complete content.
1631            vec![chunk("r1", "Hello"), chunk("r1", " world"), chunk("r1", "."), complete],
1632            // An ending without content carries the chunks streamed under its id.
1633            vec![chunk("r1", "Hello"), chunk("r1", " world."), event("r1", None, false)],
1634            // A response beside a tool call, tool progress, then the answer.
1635            vec![
1636                chunk("r1", "Let me check."),
1637                preamble,
1638                adk_core::Event::tool_progress("invocation", "agent", "call-1", "stdout", "log\n"),
1639                chunk("r2", "Done"),
1640                event("r2", Some("Done."), false),
1641            ],
1642            // A remote agent streams each chunk under an id of its own, then joins them.
1643            vec![
1644                chunk("a", "Hello"),
1645                chunk("b", " world."),
1646                event("c", Some("Hello world."), false),
1647            ],
1648        ];
1649
1650        let written: Vec<_> =
1651            cases.iter().map(|events| default_output_mapper(events).remove("messages")).collect();
1652
1653        let assistant = |texts: &[&str]| {
1654            Some(serde_json::json!(
1655                texts
1656                    .iter()
1657                    .map(|text| serde_json::json!({"role": "assistant", "content": text}))
1658                    .collect::<Vec<_>>()
1659            ))
1660        };
1661        assert_eq!(
1662            written,
1663            vec![
1664                assistant(&["Hello world."]),
1665                assistant(&["Hello world."]),
1666                assistant(&["Let me check.", "Done."]),
1667                assistant(&["Hello world."]),
1668            ]
1669        );
1670    }
1671
1672    #[test]
1673    fn test_node_output_builder() {
1674        let output = NodeOutput::new().with_update("a", 1).with_update("b", "hello");
1675
1676        assert_eq!(output.updates.get("a"), Some(&serde_json::json!(1)));
1677        assert_eq!(output.updates.get("b"), Some(&serde_json::json!("hello")));
1678    }
1679}