Skip to main content

adk_graph/
agent.rs

1//! GraphAgent - ADK Agent integration for graph workflows
2//!
3//! Provides a builder pattern similar to LlmAgent and RealtimeAgent.
4
5use crate::checkpoint::Checkpointer;
6use crate::deferred::DeferredNodeConfig;
7use crate::edge::{END, Edge, EdgeTarget, START};
8use crate::error::{GraphError, Result};
9use crate::graph::{CompiledGraph, StateGraph};
10use crate::node::{ExecutionConfig, FunctionNode, Node, NodeContext, NodeOutput};
11use crate::state::{State, StateSchema};
12use crate::stream::{StreamEvent, StreamMode};
13use crate::timeout::TimeoutPolicy;
14use adk_core::{
15    Agent, AgentCapabilities, AgentRelationshipKind, AgentTopology, AgentTopologyMember,
16    AgentTopologyRelationship, Content, Event, EventStream, InvocationContext,
17};
18use async_trait::async_trait;
19use serde_json::json;
20use std::collections::HashMap;
21use std::future::Future;
22use std::pin::Pin;
23use std::sync::Arc;
24
25/// Type alias for callbacks
26pub type BeforeAgentCallback = Arc<
27    dyn Fn(Arc<dyn InvocationContext>) -> Pin<Box<dyn Future<Output = adk_core::Result<()>> + Send>>
28        + Send
29        + Sync,
30>;
31
32pub type AfterAgentCallback = Arc<
33    dyn Fn(
34            Arc<dyn InvocationContext>,
35            Event,
36        ) -> Pin<Box<dyn Future<Output = adk_core::Result<()>> + Send>>
37        + Send
38        + Sync,
39>;
40
41/// Type alias for input mapper function
42pub type InputMapper = Arc<dyn Fn(&dyn InvocationContext) -> State + Send + Sync>;
43
44/// Type alias for output mapper function
45pub type OutputMapper = Arc<dyn Fn(&State) -> Vec<Event> + Send + Sync>;
46
47/// Maps a turn to the answer for the graph's paused nodes.
48///
49/// See [`GraphAgentBuilder::resume_mapper`].
50pub type ResumeMapper =
51    Arc<dyn Fn(&dyn InvocationContext) -> Option<serde_json::Value> + Send + Sync>;
52
53/// GraphAgent wraps a CompiledGraph as an ADK Agent
54///
55/// # Turns and checkpoints
56///
57/// Each [`Agent::run`] call is one turn on the session's thread, whose id
58/// [`session_thread_id`] derives from the app name, user id, and session id, so
59/// two users who choose the same session id never share checkpoints. With a
60/// checkpointer configured:
61///
62/// | Thread's latest checkpoint | What the turn does |
63/// |----------------------------|--------------------|
64/// | None | Runs the graph from its entry nodes. |
65/// | Paused (non-empty frontier) | Resumes the paused run, with the turn's input merged into its state. |
66/// | Finished (empty frontier) | Runs the graph again from its entry nodes, starting from the previous turn's final state with the turn's input merged on top. |
67///
68/// The recursion limit applies to each turn separately. [`GraphAgent::invoke`]
69/// keeps the direct-graph behaviour, where re-invoking a finished thread returns
70/// its final state without running anything.
71///
72/// # Events
73///
74/// A turn yields the events of the agents inside the graph as they produce them,
75/// each on its node's branch, then the events the output mapper builds from the
76/// final state, or one event per pause when the graph paused. A runner therefore
77/// streams the inner agents' work and records it in the session. Every event
78/// carries the turn's invocation id.
79///
80/// # Answering a pause
81///
82/// When a turn resumes a node that paused with a dynamic interrupt, the node
83/// reads the turn's answer with [`NodeContext::resume_value`]: by default the
84/// turn's text, or what [`GraphAgentBuilder::resume_mapper`] returns. The answer
85/// is not written to state, so a later pause asks again.
86pub struct GraphAgent {
87    name: String,
88    description: String,
89    graph: Arc<CompiledGraph>,
90    /// Map InvocationContext to graph input state
91    input_mapper: InputMapper,
92    /// Map graph output state to ADK Events
93    output_mapper: OutputMapper,
94    /// Before agent callback
95    before_callback: Option<BeforeAgentCallback>,
96    /// After agent callback
97    after_callback: Option<AfterAgentCallback>,
98    /// Map the turn to the answer for paused nodes
99    resume_mapper: ResumeMapper,
100}
101
102impl GraphAgent {
103    /// Create a new GraphAgent builder
104    pub fn builder(name: &str) -> GraphAgentBuilder {
105        GraphAgentBuilder::new(name)
106    }
107
108    /// Create directly from a compiled graph
109    pub fn from_graph(name: &str, graph: CompiledGraph) -> Self {
110        Self {
111            name: name.to_string(),
112            description: String::new(),
113            graph: Arc::new(graph),
114            input_mapper: Arc::new(default_input_mapper),
115            output_mapper: Arc::new(default_output_mapper),
116            before_callback: None,
117            after_callback: None,
118            resume_mapper: Arc::new(default_resume_mapper),
119        }
120    }
121
122    /// Build a `GraphAgent` from a `WorkflowSchema`.
123    ///
124    /// Delegates to `schema.build_graph()` to construct the graph from the
125    /// workflow schema's action nodes, edges, and conditions.
126    #[cfg(feature = "action")]
127    pub fn from_workflow_schema(
128        name: &str,
129        schema: &crate::workflow::WorkflowSchema,
130    ) -> Result<Self> {
131        schema.build_graph(name)
132    }
133
134    /// Get the underlying compiled graph
135    pub fn graph(&self) -> &CompiledGraph {
136        &self.graph
137    }
138
139    /// Execute the graph directly (bypassing Agent trait)
140    pub async fn invoke(&self, input: State, config: ExecutionConfig) -> Result<State> {
141        self.graph.invoke(input, config).await
142    }
143
144    /// Stream execution
145    pub fn stream(
146        &self,
147        input: State,
148        config: ExecutionConfig,
149        mode: StreamMode,
150    ) -> impl futures::Stream<Item = Result<StreamEvent>> + '_ {
151        self.graph.stream(input, config, mode)
152    }
153}
154
155#[async_trait]
156impl Agent for GraphAgent {
157    fn name(&self) -> &str {
158        &self.name
159    }
160
161    fn description(&self) -> &str {
162        &self.description
163    }
164
165    fn sub_agents(&self) -> &[Arc<dyn Agent>] {
166        &[]
167    }
168
169    fn supports_agent_transfer(&self) -> bool {
170        false
171    }
172
173    fn capabilities(&self) -> AgentCapabilities {
174        AgentCapabilities {
175            checkpoint_resume: self.graph.has_checkpointer(),
176            shared_state: true,
177            invocation_metadata: true,
178            ..AgentCapabilities::default()
179        }
180    }
181
182    fn topology(&self) -> Option<AgentTopology> {
183        let mut nodes = self.graph.nodes.values().collect::<Vec<_>>();
184        nodes.sort_by_key(|node| node.name().to_string());
185        let mut members = vec![AgentTopologyMember {
186            name: self.name.clone(),
187            description: self.description.clone(),
188            coordinator: true,
189            capabilities: self.capabilities(),
190        }];
191        members.extend(nodes.into_iter().map(|node| AgentTopologyMember {
192            name: node.name().to_string(),
193            description: node.description().to_string(),
194            coordinator: false,
195            capabilities: node.capabilities(),
196        }));
197
198        let mut relationships = self
199            .graph
200            .get_entry_nodes()
201            .into_iter()
202            .map(|entry| AgentTopologyRelationship {
203                from: self.name.clone(),
204                to: entry,
205                kind: AgentRelationshipKind::Flow,
206            })
207            .collect::<Vec<_>>();
208        for edge in &self.graph.edges {
209            match edge {
210                Edge::Direct { source, target: EdgeTarget::Node(target) } => {
211                    relationships.push(AgentTopologyRelationship {
212                        from: source.clone(),
213                        to: target.clone(),
214                        kind: AgentRelationshipKind::Flow,
215                    });
216                }
217                Edge::Conditional { source, targets, .. } => {
218                    relationships.extend(targets.values().filter_map(|target| {
219                        target.node_name().map(|target| AgentTopologyRelationship {
220                            from: source.clone(),
221                            to: target.to_string(),
222                            kind: AgentRelationshipKind::Flow,
223                        })
224                    }));
225                }
226                Edge::Direct { target: EdgeTarget::End, .. } | Edge::Entry { .. } => {}
227            }
228        }
229        relationships.sort_by(|left, right| (&left.from, &left.to).cmp(&(&right.from, &right.to)));
230        relationships.dedup_by(|left, right| left.from == right.from && left.to == right.to);
231
232        Some(AgentTopology {
233            root: self.name.clone(),
234            coordinator: self.name.clone(),
235            members,
236            relationships,
237        })
238    }
239
240    async fn run(&self, ctx: Arc<dyn InvocationContext>) -> adk_core::Result<EventStream> {
241        // A call a person asked for needs an agent that holds it for their decision itself,
242        // so a graph that starts the run refuses it before any node runs (spec 3.3 §7.4 rule 5).
243        if let Some(call) = ctx.run_config().requested_call.as_ref()
244            && ctx.agent_name() == self.name()
245            && !call.taken_in(&ctx.session().conversation_history())
246        {
247            let events = call.refusal_events(
248                ctx.invocation_id(),
249                ctx.branch(),
250                self.name(),
251                "this agent runs a graph and cannot hold a call for a person's decision",
252            );
253            return Ok(Box::pin(futures::stream::iter(events.into_iter().map(Ok))));
254        }
255        // Call before callback
256        if let Some(callback) = &self.before_callback {
257            callback(ctx.clone()).await?;
258        }
259
260        // Map context to input state
261        let input = (self.input_mapper)(ctx.as_ref());
262
263        // Create execution config from context, carrying the invocation so an
264        // `AgentNode` inside the graph presents this run's identity, services, and
265        // cancellation rather than a synthetic standalone context. Agent nodes send
266        // their agents' events to `node_events` as they run.
267        let thread_id = session_thread_id(ctx.app_name(), ctx.user_id(), ctx.session_id());
268        let (sink, mut node_events) = tokio::sync::mpsc::unbounded_channel();
269        let mut config =
270            ExecutionConfig::new(&thread_id).with_parent_context(ctx.clone()).with_event_sink(sink);
271        // Offered to every node; the executor hands it only to a node resuming its
272        // own pause.
273        if let Some(answer) = (self.resume_mapper)(ctx.as_ref()) {
274            for node in self.graph.nodes.keys() {
275                config = config.with_resume_value(node.clone(), answer.clone());
276            }
277        }
278
279        // Execute graph
280        let graph = self.graph.clone();
281        let output_mapper = self.output_mapper.clone();
282        let after_callback = self.after_callback.clone();
283        let ctx_clone = ctx.clone();
284        let name = self.name.clone();
285
286        let stream = async_stream::stream! {
287            // Events this agent builds are the turn's, whatever the mapper set.
288            let stamp = |mut event: Event| {
289                event.invocation_id = ctx_clone.invocation_id().to_string();
290                if event.author.is_empty() {
291                    event.author = name.clone();
292                }
293                if event.branch.is_empty() {
294                    event.branch = ctx_clone.branch().to_string();
295                }
296                event
297            };
298
299            // Each call is one turn on the session's thread: a paused thread
300            // resumes, and a finished one runs again from its entry nodes with the
301            // previous turn's state carried over.
302            let mut executor =
303                crate::executor::PregelExecutor::new(&graph, config).restarting_completed_threads();
304            let outcome = {
305                let run = executor.run(input);
306                tokio::pin!(run);
307                loop {
308                    let next = tokio::select! {
309                        biased;
310                        Some(event) = node_events.recv() => Next::Event(Box::new(event)),
311                        outcome = &mut run => Next::Done(outcome),
312                    };
313                    match next {
314                        Next::Event(event) => yield Ok(*event),
315                        Next::Done(outcome) => break outcome,
316                    }
317                }
318            };
319            // Whatever a node sent as the run finished.
320            while let Ok(event) = node_events.try_recv() {
321                yield Ok(event);
322            }
323
324            match outcome {
325                Ok(state) => {
326                    let events = output_mapper(&state);
327                    for event in events {
328                        let event = stamp(event);
329                        // Call after callback for each event
330                        if let Some(callback) = &after_callback
331                            && let Err(e) = callback(ctx_clone.clone(), event.clone()).await {
332                                yield Err(e);
333                                return;
334                            }
335                        yield Ok(event);
336                    }
337                }
338                Err(GraphError::Interrupted(interrupt)) => {
339                    // The `Agent` trait yields events, so an interrupt cannot be
340                    // returned as an error without ending the invocation. Emit one
341                    // event per pause of the step, each carrying its structured
342                    // pause so a caller can read the node, the payload, and the
343                    // checkpoint to resume from.
344                    for paused in &interrupt.interrupts {
345                        let tool_confirmation =
346                            crate::interrupt::GraphToolConfirmationPause::from_interrupt(
347                                paused,
348                                &interrupt.thread_id,
349                                &interrupt.checkpoint_id,
350                            );
351                        let payload = tool_confirmation.clone().map_or_else(
352                            || crate::interrupt::GraphInterruptPayload::new(
353                                paused,
354                                &interrupt.thread_id,
355                                &interrupt.checkpoint_id,
356                            ),
357                            crate::interrupt::GraphInterruptPayload::from_tool_confirmation_pause,
358                        );
359                        let mut event = Event::new("graph_interrupted");
360                        if let Some(pause) = tool_confirmation {
361                            event.llm_response.interrupted = true;
362                            event.llm_response.turn_complete = true;
363                            event.actions.tool_confirmation = Some(pause.request);
364                        }
365                        event.set_content(Content::new("assistant").with_text(paused.to_string()));
366                        event.provider_metadata.insert(
367                            crate::interrupt::INTERRUPT_METADATA_KEY.to_string(),
368                            payload.to_metadata_value(),
369                        );
370                        yield Ok(stamp(event));
371                    }
372                }
373                Err(e) => {
374                    // Converted, not re-wrapped, so an agent node's failure keeps the
375                    // agent's category and a node timeout stays a timeout.
376                    yield Err(e.into());
377                }
378            }
379        };
380
381        Ok(Box::pin(stream))
382    }
383}
384
385/// What a running turn produced next: an agent node's event, or the run's outcome.
386enum Next {
387    Event(Box<Event>),
388    Done(Result<State>),
389}
390
391/// Returns the checkpoint thread id for an ADK session.
392///
393/// [`GraphAgent`] keys its checkpoints by this id. It joins the app name, user
394/// id, and session id with `:`, and percent-encodes `%` and `:` inside each part,
395/// so distinct identities never produce the same thread id. Use it to find a
396/// session's checkpoints with [`Checkpointer::load`] or [`Checkpointer::list`].
397///
398/// # Example
399///
400/// ```
401/// use adk_graph::agent::session_thread_id;
402///
403/// assert_eq!(session_thread_id("shop", "alice", "s-1"), "shop:alice:s-1");
404/// assert_eq!(session_thread_id("shop", "a:b", "c"), "shop:a%3Ab:c");
405/// assert_ne!(session_thread_id("shop", "alice", "s-1"), session_thread_id("shop", "bob", "s-1"));
406/// ```
407pub fn session_thread_id(app_name: &str, user_id: &str, session_id: &str) -> String {
408    let mut thread_id =
409        String::with_capacity(app_name.len() + user_id.len() + session_id.len() + 2);
410    for (index, part) in [app_name, user_id, session_id].into_iter().enumerate() {
411        if index > 0 {
412            thread_id.push(':');
413        }
414        push_thread_part(&mut thread_id, part);
415    }
416    thread_id
417}
418
419/// Returns the checkpoint thread id of one graph tool call.
420///
421/// [`NodeTool`](crate::tool::NodeTool) runs each call on its own thread: the
422/// session's [`session_thread_id`] with the function call id appended as a fourth
423/// `:`-separated part, encoded the same way. A second call in the same session
424/// therefore runs the graph again, and the same call dispatched again, as when a
425/// held call resumes, continues its own thread.
426///
427/// # Example
428///
429/// ```
430/// use adk_graph::agent::{session_thread_id, tool_call_thread_id};
431///
432/// assert_eq!(tool_call_thread_id("shop", "alice", "s-1", "call-7"), "shop:alice:s-1:call-7");
433/// assert_ne!(
434///     tool_call_thread_id("shop", "alice", "s-1", "call-7"),
435///     tool_call_thread_id("shop", "alice", "s-1", "call-8")
436/// );
437/// assert_ne!(tool_call_thread_id("shop", "alice", "s", "1"), session_thread_id("shop", "alice", "s:1"));
438/// ```
439pub fn tool_call_thread_id(
440    app_name: &str,
441    user_id: &str,
442    session_id: &str,
443    function_call_id: &str,
444) -> String {
445    let mut thread_id = session_thread_id(app_name, user_id, session_id);
446    thread_id.push(':');
447    push_thread_part(&mut thread_id, function_call_id);
448    thread_id
449}
450
451/// Appends one part of a thread id, percent-encoding the separator and `%`.
452fn push_thread_part(thread_id: &mut String, part: &str) {
453    for c in part.chars() {
454        match c {
455            '%' => thread_id.push_str("%25"),
456            ':' => thread_id.push_str("%3A"),
457            other => thread_id.push(other),
458        }
459    }
460}
461
462/// Default input mapper - extracts content from InvocationContext
463fn default_input_mapper(ctx: &dyn InvocationContext) -> State {
464    let mut state = State::new();
465
466    // Get user content
467    let content = ctx.user_content();
468    let text: String = content.parts.iter().filter_map(|p| p.text()).collect::<Vec<_>>().join("\n");
469
470    if !text.is_empty() {
471        state.insert("input".to_string(), json!(text));
472        state.insert("messages".to_string(), json!([{"role": "user", "content": text}]));
473    }
474
475    // Add session ID
476    state.insert("session_id".to_string(), json!(ctx.session_id()));
477
478    state
479}
480
481/// Default resume mapper - the turn's text, when it has any
482fn default_resume_mapper(ctx: &dyn InvocationContext) -> Option<serde_json::Value> {
483    let text: String =
484        ctx.user_content().parts.iter().filter_map(|p| p.text()).collect::<Vec<_>>().join("\n");
485    (!text.is_empty()).then(|| json!(text))
486}
487
488/// Default output mapper - creates events from state
489fn default_output_mapper(state: &State) -> Vec<Event> {
490    let mut events = Vec::new();
491
492    // Try to get output from common fields
493    let output_text = state
494        .get("output")
495        .and_then(|v| v.as_str())
496        .or_else(|| state.get("result").and_then(|v| v.as_str()))
497        .or_else(|| {
498            state
499                .get("messages")
500                .and_then(|v| v.as_array())
501                .and_then(|arr| arr.last())
502                .and_then(|msg| msg.get("content"))
503                .and_then(|c| c.as_str())
504        });
505
506    let text = if let Some(text) = output_text {
507        text.to_string()
508    } else {
509        // Return the full state as JSON
510        serde_json::to_string_pretty(state).unwrap_or_default()
511    };
512
513    let mut event = Event::new("graph_output");
514    event.set_content(Content::new("assistant").with_text(&text));
515    events.push(event);
516
517    events
518}
519
520/// Builder for GraphAgent
521pub struct GraphAgentBuilder {
522    name: String,
523    description: String,
524    schema: StateSchema,
525    nodes: Vec<Arc<dyn Node>>,
526    edges: Vec<Edge>,
527    checkpointer: Option<Arc<dyn Checkpointer>>,
528    interrupt_before: Vec<String>,
529    interrupt_after: Vec<String>,
530    recursion_limit: usize,
531    max_concurrency: Option<usize>,
532    input_mapper: Option<InputMapper>,
533    output_mapper: Option<OutputMapper>,
534    before_callback: Option<BeforeAgentCallback>,
535    after_callback: Option<AfterAgentCallback>,
536    resume_mapper: Option<ResumeMapper>,
537    timeout_policies: HashMap<String, TimeoutPolicy>,
538    default_timeout: Option<TimeoutPolicy>,
539    deferred_configs: HashMap<String, DeferredNodeConfig>,
540    governed_nodes: HashMap<String, crate::governed::GovernedNode>,
541    #[cfg(feature = "node-cache")]
542    cache_policies: HashMap<String, crate::cache::NodeCachePolicy>,
543}
544
545impl GraphAgentBuilder {
546    /// Create a new builder
547    pub fn new(name: &str) -> Self {
548        Self {
549            name: name.to_string(),
550            description: String::new(),
551            schema: StateSchema::simple(&["input", "output", "messages"]),
552            nodes: vec![],
553            edges: vec![],
554            checkpointer: None,
555            interrupt_before: vec![],
556            interrupt_after: vec![],
557            recursion_limit: 100,
558            max_concurrency: None,
559            input_mapper: None,
560            output_mapper: None,
561            before_callback: None,
562            after_callback: None,
563            resume_mapper: None,
564            timeout_policies: HashMap::new(),
565            default_timeout: None,
566            deferred_configs: HashMap::new(),
567            governed_nodes: HashMap::new(),
568            #[cfg(feature = "node-cache")]
569            cache_policies: HashMap::new(),
570        }
571    }
572
573    /// Set description
574    pub fn description(mut self, desc: &str) -> Self {
575        self.description = desc.to_string();
576        self
577    }
578
579    /// Set state schema
580    pub fn state_schema(mut self, schema: StateSchema) -> Self {
581        self.schema = schema;
582        self
583    }
584
585    /// Add channels to state schema
586    pub fn channels(mut self, channels: &[&str]) -> Self {
587        self.schema = StateSchema::simple(channels);
588        self
589    }
590
591    /// Add a node
592    pub fn node<N: Node + 'static>(mut self, node: N) -> Self {
593        self.nodes.push(Arc::new(node));
594        self
595    }
596
597    /// Add a function as a node
598    pub fn node_fn<F, Fut>(mut self, name: &str, func: F) -> Self
599    where
600        F: Fn(NodeContext) -> Fut + Send + Sync + 'static,
601        Fut: Future<Output = Result<NodeOutput>> + Send + 'static,
602    {
603        self.nodes.push(Arc::new(FunctionNode::new(name, func)));
604        self
605    }
606
607    /// Add a direct edge
608    pub fn edge(mut self, source: &str, target: &str) -> Self {
609        let target =
610            if target == END { EdgeTarget::End } else { EdgeTarget::Node(target.to_string()) };
611
612        if source == START {
613            let entry_idx = self.edges.iter().position(|e| matches!(e, Edge::Entry { .. }));
614            match entry_idx {
615                Some(idx) => {
616                    if let Edge::Entry { targets } = &mut self.edges[idx]
617                        && let EdgeTarget::Node(node) = &target
618                        && !targets.contains(node)
619                    {
620                        targets.push(node.clone());
621                    }
622                }
623                None => {
624                    if let EdgeTarget::Node(node) = target {
625                        self.edges.push(Edge::Entry { targets: vec![node] });
626                    }
627                }
628            }
629        } else {
630            self.edges.push(Edge::Direct { source: source.to_string(), target });
631        }
632
633        self
634    }
635
636    /// Add a conditional edge
637    pub fn conditional_edge<F, I>(mut self, source: &str, router: F, targets: I) -> Self
638    where
639        F: Fn(&State) -> String + Send + Sync + 'static,
640        I: IntoIterator<Item = (&'static str, &'static str)>,
641    {
642        let targets_map: HashMap<String, EdgeTarget> = targets
643            .into_iter()
644            .map(|(k, v)| {
645                let target =
646                    if v == END { EdgeTarget::End } else { EdgeTarget::Node(v.to_string()) };
647                (k.to_string(), target)
648            })
649            .collect();
650
651        self.edges.push(Edge::Conditional {
652            source: source.to_string(),
653            router: Arc::new(router),
654            targets: targets_map,
655        });
656
657        self
658    }
659
660    /// Set checkpointer
661    pub fn checkpointer<C: Checkpointer + 'static>(mut self, checkpointer: C) -> Self {
662        self.checkpointer = Some(Arc::new(checkpointer));
663        self
664    }
665
666    /// Set checkpointer with Arc
667    pub fn checkpointer_arc(mut self, checkpointer: Arc<dyn Checkpointer>) -> Self {
668        self.checkpointer = Some(checkpointer);
669        self
670    }
671
672    /// Set nodes to interrupt before
673    pub fn interrupt_before(mut self, nodes: &[&str]) -> Self {
674        self.interrupt_before = nodes.iter().map(|s| s.to_string()).collect();
675        self
676    }
677
678    /// Set nodes to interrupt after
679    pub fn interrupt_after(mut self, nodes: &[&str]) -> Self {
680        self.interrupt_after = nodes.iter().map(|s| s.to_string()).collect();
681        self
682    }
683
684    /// Cap how many nodes execute concurrently within one super-step.
685    ///
686    /// See [`CompiledGraph::with_max_concurrency`](crate::graph::CompiledGraph::with_max_concurrency).
687    pub fn max_concurrency(mut self, limit: usize) -> Self {
688        self.max_concurrency = Some(limit.max(1));
689        self
690    }
691
692    /// Sets how many super-steps each turn may take; 100 when unset.
693    ///
694    /// See [`CompiledGraph::with_recursion_limit`](crate::graph::CompiledGraph::with_recursion_limit).
695    pub fn recursion_limit(mut self, limit: usize) -> Self {
696        self.recursion_limit = limit;
697        self
698    }
699
700    /// Set a timeout policy for a specific node.
701    ///
702    /// The policy is applied when the named node executes, enforcing
703    /// wall-clock and/or idle timeouts with the configured recovery action.
704    ///
705    /// # Example
706    ///
707    /// ```rust,ignore
708    /// use std::time::Duration;
709    /// use adk_graph::timeout::{TimeoutPolicy, OnTimeout};
710    ///
711    /// let agent = GraphAgent::builder("my_graph")
712    ///     .node_timeout("slow_node", TimeoutPolicy {
713    ///         run_timeout: Some(Duration::from_secs(10)),
714    ///         idle_timeout: None,
715    ///         on_timeout: OnTimeout::Fail,
716    ///     })
717    ///     .build()?;
718    /// ```
719    pub fn node_timeout(mut self, node_name: &str, policy: TimeoutPolicy) -> Self {
720        self.timeout_policies.insert(node_name.to_string(), policy);
721        self
722    }
723
724    /// Set a default timeout policy applied to all nodes without an explicit override.
725    ///
726    /// Nodes that have a per-node policy set via [`node_timeout`](Self::node_timeout)
727    /// will use their specific policy instead of this default.
728    ///
729    /// # Example
730    ///
731    /// ```rust,ignore
732    /// use std::time::Duration;
733    /// use adk_graph::timeout::{TimeoutPolicy, OnTimeout};
734    ///
735    /// let agent = GraphAgent::builder("my_graph")
736    ///     .default_timeout(TimeoutPolicy {
737    ///         run_timeout: Some(Duration::from_secs(30)),
738    ///         idle_timeout: Some(Duration::from_secs(5)),
739    ///         on_timeout: OnTimeout::Skip,
740    ///     })
741    ///     .build()?;
742    /// ```
743    pub fn default_timeout(mut self, policy: TimeoutPolicy) -> Self {
744        self.default_timeout = Some(policy);
745        self
746    }
747
748    /// Add a deferred (fan-in barrier) node to the graph.
749    ///
750    /// A deferred node waits for all upstream parallel paths to complete before
751    /// executing. The provided function is wrapped as a [`FunctionNode`] and the
752    /// [`DeferredNodeConfig`] controls how upstream outputs are merged and how
753    /// long the node waits for all paths.
754    ///
755    /// # Arguments
756    ///
757    /// * `name` - The name of the deferred node.
758    /// * `func` - The async function to execute once all upstream paths complete.
759    /// * `config` - Configuration controlling merge strategy and fan-in timeout.
760    ///
761    /// # Example
762    ///
763    /// ```rust,ignore
764    /// use std::time::Duration;
765    /// use adk_graph::deferred::{DeferredNodeConfig, MergeStrategy};
766    /// use adk_graph::node::NodeOutput;
767    ///
768    /// let agent = GraphAgent::builder("scatter_gather")
769    ///     .deferred_node("aggregator", |_ctx| async {
770    ///         Ok(NodeOutput::new().with_update("status", serde_json::json!("merged")))
771    ///     }, DeferredNodeConfig {
772    ///         merge_strategy: MergeStrategy::Collect,
773    ///         fan_in_timeout: Some(Duration::from_secs(30)),
774    ///     })
775    ///     .build()?;
776    /// ```
777    /// Configure fan-in for a node already added with [`node`](Self::node).
778    ///
779    /// [`deferred_node`](Self::deferred_node) both adds and configures a node, so
780    /// a custom `Node` added through `node` had no way to set a merge strategy or
781    /// a fan-in timeout.
782    ///
783    /// A node reached by more than one unconditional edge is deferred
784    /// automatically; this overrides that default.
785    pub fn mark_deferred(mut self, name: &str, config: DeferredNodeConfig) -> Self {
786        self.deferred_configs.insert(name.to_string(), config);
787        self
788    }
789
790    pub fn deferred_node<F, Fut>(mut self, name: &str, func: F, config: DeferredNodeConfig) -> Self
791    where
792        F: Fn(NodeContext) -> Fut + Send + Sync + 'static,
793        Fut: Future<Output = Result<NodeOutput>> + Send + 'static,
794    {
795        self.nodes.push(Arc::new(FunctionNode::new(name, func)));
796        self.deferred_configs.insert(name.to_string(), config);
797        self
798    }
799
800    /// Puts a node's calls on the governed path (spec 3.3 §12).
801    ///
802    /// See [`CompiledGraph::with_governed_node`](crate::graph::CompiledGraph::with_governed_node)
803    /// and the [`governed`](crate::governed) module.
804    ///
805    /// # Example
806    ///
807    /// ```
808    /// use adk_graph::agent::GraphAgent;
809    /// use adk_graph::edge::{END, START};
810    /// use adk_graph::governed::GovernedNode;
811    /// use adk_graph::node::NodeOutput;
812    ///
813    /// let agent = GraphAgent::builder("invoice-run")
814    ///     .channels(&["charge"])
815    ///     .node_fn("pay", |_ctx| async { Ok(NodeOutput::new()) })
816    ///     .edge(START, "pay")
817    ///     .edge("pay", END)
818    ///     .governed_node("pay", GovernedNode::new().with_approval().spending_money())
819    ///     .build()?;
820    /// assert!(agent.graph().shape().nodes[0].governed.is_some());
821    /// # Ok::<(), adk_graph::GraphError>(())
822    /// ```
823    pub fn governed_node(mut self, name: &str, governed: crate::governed::GovernedNode) -> Self {
824        self.governed_nodes.insert(name.to_string(), governed);
825        self
826    }
827
828    /// Set a cache policy for a specific node.
829    ///
830    /// When a node has a cache policy, its execution results are cached keyed
831    /// by a blake3 hash of the node name and input state. Subsequent executions
832    /// with identical inputs return the cached result without re-executing the
833    /// node.
834    ///
835    /// # Arguments
836    ///
837    /// * `name` — the name of the node to cache
838    /// * `policy` — the cache policy specifying backend and TTL
839    ///
840    /// # Example
841    ///
842    /// ```rust,ignore
843    /// use std::time::Duration;
844    /// use adk_graph::cache::{CacheBackend, NodeCachePolicy};
845    ///
846    /// let agent = GraphAgent::builder("cached_graph")
847    ///     .node_cache("expensive_node", NodeCachePolicy {
848    ///         backend: CacheBackend::InMemory { max_entries: 128 },
849    ///         ttl: Some(Duration::from_secs(300)),
850    ///     })
851    ///     .build()?;
852    /// ```
853    #[cfg(feature = "node-cache")]
854    pub fn node_cache(mut self, name: &str, policy: crate::cache::NodeCachePolicy) -> Self {
855        self.cache_policies.insert(name.to_string(), policy);
856        self
857    }
858
859    /// Set custom input mapper
860    pub fn input_mapper<F>(mut self, mapper: F) -> Self
861    where
862        F: Fn(&dyn InvocationContext) -> State + Send + Sync + 'static,
863    {
864        self.input_mapper = Some(Arc::new(mapper));
865        self
866    }
867
868    /// Set custom output mapper
869    pub fn output_mapper<F>(mut self, mapper: F) -> Self
870    where
871        F: Fn(&State) -> Vec<Event> + Send + Sync + 'static,
872    {
873        self.output_mapper = Some(Arc::new(mapper));
874        self
875    }
876
877    /// Maps a turn to the answer a paused node reads with
878    /// [`NodeContext::resume_value`].
879    ///
880    /// Called on every turn; the answer reaches only a node that the turn resumes
881    /// from its own dynamic interrupt. Return `None` to resume without one. The
882    /// default answers with the turn's text.
883    ///
884    /// # Example
885    ///
886    /// ```
887    /// use adk_graph::agent::GraphAgent;
888    /// use serde_json::json;
889    ///
890    /// let builder = GraphAgent::builder("refunds").resume_mapper(|ctx| {
891    ///     let text: String = ctx.user_content().parts.iter().filter_map(|p| p.text()).collect();
892    ///     Some(json!({ "approved": text.trim().eq_ignore_ascii_case("approve") }))
893    /// });
894    /// # let _ = builder;
895    /// ```
896    pub fn resume_mapper<F>(mut self, mapper: F) -> Self
897    where
898        F: Fn(&dyn InvocationContext) -> Option<serde_json::Value> + Send + Sync + 'static,
899    {
900        self.resume_mapper = Some(Arc::new(mapper));
901        self
902    }
903
904    /// Set before agent callback
905    pub fn before_agent_callback<F, Fut>(mut self, callback: F) -> Self
906    where
907        F: Fn(Arc<dyn InvocationContext>) -> Fut + Send + Sync + 'static,
908        Fut: Future<Output = adk_core::Result<()>> + Send + 'static,
909    {
910        self.before_callback = Some(Arc::new(move |ctx| Box::pin(callback(ctx))));
911        self
912    }
913
914    /// Set after agent callback
915    ///
916    /// Note: The callback receives a cloned Event to avoid lifetime issues.
917    pub fn after_agent_callback<F, Fut>(mut self, callback: F) -> Self
918    where
919        F: Fn(Arc<dyn InvocationContext>, Event) -> Fut + Send + Sync + 'static,
920        Fut: Future<Output = adk_core::Result<()>> + Send + 'static,
921    {
922        self.after_callback = Some(Arc::new(move |ctx, event| {
923            let event_clone = event.clone();
924            Box::pin(callback(ctx, event_clone))
925        }));
926        self
927    }
928
929    /// Add an action node to the graph.
930    ///
931    /// Wraps the `ActionNodeConfig` in an `ActionNodeExecutor` and registers it
932    /// as a node. If the config is a `SwitchNodeConfig`, conditional edges are
933    /// also auto-registered from the switch conditions.
934    #[cfg(feature = "action")]
935    pub fn action_node(mut self, config: adk_action::ActionNodeConfig) -> Self {
936        use crate::action::ActionNodeExecutor;
937
938        // If this is a Switch node, register conditional edges
939        if let adk_action::ActionNodeConfig::Switch(ref switch_config) = config {
940            let conditions = switch_config.conditions.clone();
941            let eval_mode = switch_config.evaluation_mode.clone();
942            let default_branch = switch_config.default_branch.clone();
943            let source = config.standard().id.clone();
944
945            let mut targets_map: HashMap<String, EdgeTarget> = HashMap::new();
946            for condition in &conditions {
947                targets_map.insert(
948                    condition.output_port.clone(),
949                    EdgeTarget::Node(condition.output_port.clone()),
950                );
951            }
952            if let Some(ref default) = default_branch {
953                let target = if default == END {
954                    EdgeTarget::End
955                } else {
956                    EdgeTarget::Node(default.clone())
957                };
958                targets_map.insert(default.clone(), target);
959            }
960            targets_map.insert(END.to_string(), EdgeTarget::End);
961
962            let router = Arc::new(move |state: &State| -> String {
963                match crate::action::switch::evaluate_switch_conditions(
964                    &conditions,
965                    state,
966                    &eval_mode,
967                    default_branch.as_deref(),
968                ) {
969                    Ok(ports) => ports.into_iter().next().unwrap_or_else(|| END.to_string()),
970                    Err(_) => END.to_string(),
971                }
972            });
973
974            self.edges.push(Edge::Conditional { source, router, targets: targets_map });
975        }
976
977        let executor = ActionNodeExecutor::new(config);
978        self.nodes.push(Arc::new(executor));
979        self
980    }
981
982    /// Build the GraphAgent
983    pub fn build(self) -> Result<GraphAgent> {
984        // Build the graph
985        let mut graph = StateGraph::new(self.schema);
986
987        // Add nodes
988        for node in self.nodes {
989            graph.nodes.insert(node.name().to_string(), node);
990        }
991
992        // Add edges
993        graph.edges = self.edges;
994
995        // Explicit fan-in configurations go in before compiling, so a node with
996        // several incoming edges and no configuration is still deferred.
997        graph.deferred_configs = self.deferred_configs;
998
999        // Compile
1000        let mut compiled = graph.compile()?;
1001
1002        // Configure
1003        if let Some(cp) = self.checkpointer {
1004            compiled.checkpointer = Some(cp);
1005        }
1006        compiled.interrupt_before = self.interrupt_before.into_iter().collect();
1007        compiled.interrupt_after = self.interrupt_after.into_iter().collect();
1008        compiled.recursion_limit = self.recursion_limit;
1009        compiled.max_concurrency = self.max_concurrency;
1010        compiled.timeout_policies = self.timeout_policies;
1011        compiled.default_timeout = self.default_timeout;
1012        compiled.governed_nodes = self.governed_nodes;
1013        compiled.check_governed_nodes()?;
1014
1015        #[cfg(feature = "node-cache")]
1016        {
1017            compiled.node_caches = self
1018                .cache_policies
1019                .iter()
1020                .map(|(name, policy)| {
1021                    (name.clone(), Arc::new(crate::cache::NodeCache::from_policy(policy)))
1022                })
1023                .collect();
1024            compiled.cache_policies = self.cache_policies;
1025        }
1026
1027        Ok(GraphAgent {
1028            name: self.name,
1029            description: self.description,
1030            graph: Arc::new(compiled),
1031            input_mapper: self.input_mapper.unwrap_or(Arc::new(default_input_mapper)),
1032            output_mapper: self.output_mapper.unwrap_or(Arc::new(default_output_mapper)),
1033            before_callback: self.before_callback,
1034            after_callback: self.after_callback,
1035            resume_mapper: self.resume_mapper.unwrap_or(Arc::new(default_resume_mapper)),
1036        })
1037    }
1038}
1039
1040#[cfg(test)]
1041mod tests {
1042    use super::*;
1043    use serde_json::json;
1044
1045    #[tokio::test]
1046    async fn test_graph_agent_builder() {
1047        let agent = GraphAgent::builder("test")
1048            .description("Test agent")
1049            .channels(&["value"])
1050            .node_fn("set", |_ctx| async { Ok(NodeOutput::new().with_update("value", json!(42))) })
1051            .edge(START, "set")
1052            .edge("set", END)
1053            .build()
1054            .unwrap();
1055
1056        assert_eq!(agent.name(), "test");
1057        assert_eq!(agent.description(), "Test agent");
1058
1059        // Test direct invocation
1060        let result = agent.invoke(State::new(), ExecutionConfig::new("test")).await.unwrap();
1061
1062        assert_eq!(result.get("value"), Some(&json!(42)));
1063
1064        let topology = agent.topology().expect("graph topology");
1065        assert_eq!(topology.root, "test");
1066        assert_eq!(topology.coordinator, "test");
1067        assert_eq!(topology.members.len(), 2);
1068        assert_eq!(topology.relationships.len(), 1);
1069        assert_eq!(topology.relationships[0].from, "test");
1070        assert_eq!(topology.relationships[0].to, "set");
1071        assert_eq!(topology.relationships[0].kind, AgentRelationshipKind::Flow);
1072    }
1073}