adk-graph 3.0.0

Graph-based workflow orchestration for ADK-Rust agents
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
//! GraphAgent - ADK Agent integration for graph workflows
//!
//! Provides a builder pattern similar to LlmAgent and RealtimeAgent.

use crate::checkpoint::Checkpointer;
use crate::deferred::DeferredNodeConfig;
use crate::edge::{END, Edge, EdgeTarget, START};
use crate::error::{GraphError, Result};
use crate::graph::{CompiledGraph, StateGraph};
use crate::node::{ExecutionConfig, FunctionNode, Node, NodeContext, NodeOutput};
use crate::state::{State, StateSchema};
use crate::stream::{StreamEvent, StreamMode};
use crate::timeout::TimeoutPolicy;
use adk_core::{
    Agent, AgentCapabilities, AgentRelationshipKind, AgentTopology, AgentTopologyMember,
    AgentTopologyRelationship, Content, Event, EventStream, InvocationContext,
};
use async_trait::async_trait;
use serde_json::json;
use std::collections::HashMap;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;

/// Type alias for callbacks
pub type BeforeAgentCallback = Arc<
    dyn Fn(Arc<dyn InvocationContext>) -> Pin<Box<dyn Future<Output = adk_core::Result<()>> + Send>>
        + Send
        + Sync,
>;

pub type AfterAgentCallback = Arc<
    dyn Fn(
            Arc<dyn InvocationContext>,
            Event,
        ) -> Pin<Box<dyn Future<Output = adk_core::Result<()>> + Send>>
        + Send
        + Sync,
>;

/// Type alias for input mapper function
pub type InputMapper = Arc<dyn Fn(&dyn InvocationContext) -> State + Send + Sync>;

/// Type alias for output mapper function
pub type OutputMapper = Arc<dyn Fn(&State) -> Vec<Event> + Send + Sync>;

/// Maps a turn to the answer for the graph's paused nodes.
///
/// See [`GraphAgentBuilder::resume_mapper`].
pub type ResumeMapper =
    Arc<dyn Fn(&dyn InvocationContext) -> Option<serde_json::Value> + Send + Sync>;

/// GraphAgent wraps a CompiledGraph as an ADK Agent
///
/// # Turns and checkpoints
///
/// Each [`Agent::run`] call is one turn on the session's thread, whose id
/// [`session_thread_id`] derives from the app name, user id, and session id, so
/// two users who choose the same session id never share checkpoints. With a
/// checkpointer configured:
///
/// | Thread's latest checkpoint | What the turn does |
/// |----------------------------|--------------------|
/// | None | Runs the graph from its entry nodes. |
/// | Paused (non-empty frontier) | Resumes the paused run, with the turn's input merged into its state. |
/// | 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. |
///
/// The recursion limit applies to each turn separately. [`GraphAgent::invoke`]
/// keeps the direct-graph behaviour, where re-invoking a finished thread returns
/// its final state without running anything.
///
/// # Events
///
/// A turn yields the events of the agents inside the graph as they produce them,
/// each on its node's branch, then the events the output mapper builds from the
/// final state, or one event per pause when the graph paused. A runner therefore
/// streams the inner agents' work and records it in the session. Every event
/// carries the turn's invocation id.
///
/// # Answering a pause
///
/// When a turn resumes a node that paused with a dynamic interrupt, the node
/// reads the turn's answer with [`NodeContext::resume_value`]: by default the
/// turn's text, or what [`GraphAgentBuilder::resume_mapper`] returns. The answer
/// is not written to state, so a later pause asks again.
pub struct GraphAgent {
    name: String,
    description: String,
    graph: Arc<CompiledGraph>,
    /// Map InvocationContext to graph input state
    input_mapper: InputMapper,
    /// Map graph output state to ADK Events
    output_mapper: OutputMapper,
    /// Before agent callback
    before_callback: Option<BeforeAgentCallback>,
    /// After agent callback
    after_callback: Option<AfterAgentCallback>,
    /// Map the turn to the answer for paused nodes
    resume_mapper: ResumeMapper,
}

impl GraphAgent {
    /// Create a new GraphAgent builder
    pub fn builder(name: &str) -> GraphAgentBuilder {
        GraphAgentBuilder::new(name)
    }

    /// Create directly from a compiled graph
    pub fn from_graph(name: &str, graph: CompiledGraph) -> Self {
        Self {
            name: name.to_string(),
            description: String::new(),
            graph: Arc::new(graph),
            input_mapper: Arc::new(default_input_mapper),
            output_mapper: Arc::new(default_output_mapper),
            before_callback: None,
            after_callback: None,
            resume_mapper: Arc::new(default_resume_mapper),
        }
    }

    /// Build a `GraphAgent` from a `WorkflowSchema`.
    ///
    /// Delegates to `schema.build_graph()` to construct the graph from the
    /// workflow schema's action nodes, edges, and conditions.
    #[cfg(feature = "action")]
    pub fn from_workflow_schema(
        name: &str,
        schema: &crate::workflow::WorkflowSchema,
    ) -> Result<Self> {
        schema.build_graph(name)
    }

    /// Get the underlying compiled graph
    pub fn graph(&self) -> &CompiledGraph {
        &self.graph
    }

    /// Execute the graph directly (bypassing Agent trait)
    pub async fn invoke(&self, input: State, config: ExecutionConfig) -> Result<State> {
        self.graph.invoke(input, config).await
    }

    /// Stream execution
    pub fn stream(
        &self,
        input: State,
        config: ExecutionConfig,
        mode: StreamMode,
    ) -> impl futures::Stream<Item = Result<StreamEvent>> + '_ {
        self.graph.stream(input, config, mode)
    }
}

#[async_trait]
impl Agent for GraphAgent {
    fn name(&self) -> &str {
        &self.name
    }

    fn description(&self) -> &str {
        &self.description
    }

    fn sub_agents(&self) -> &[Arc<dyn Agent>] {
        &[]
    }

    fn supports_agent_transfer(&self) -> bool {
        false
    }

    fn capabilities(&self) -> AgentCapabilities {
        AgentCapabilities {
            checkpoint_resume: self.graph.has_checkpointer(),
            shared_state: true,
            invocation_metadata: true,
            ..AgentCapabilities::default()
        }
    }

    fn topology(&self) -> Option<AgentTopology> {
        let mut nodes = self.graph.nodes.values().collect::<Vec<_>>();
        nodes.sort_by_key(|node| node.name().to_string());
        let mut members = vec![AgentTopologyMember {
            name: self.name.clone(),
            description: self.description.clone(),
            coordinator: true,
            capabilities: self.capabilities(),
        }];
        members.extend(nodes.into_iter().map(|node| AgentTopologyMember {
            name: node.name().to_string(),
            description: node.description().to_string(),
            coordinator: false,
            capabilities: node.capabilities(),
        }));

        let mut relationships = self
            .graph
            .get_entry_nodes()
            .into_iter()
            .map(|entry| AgentTopologyRelationship {
                from: self.name.clone(),
                to: entry,
                kind: AgentRelationshipKind::Flow,
            })
            .collect::<Vec<_>>();
        for edge in &self.graph.edges {
            match edge {
                Edge::Direct { source, target: EdgeTarget::Node(target) } => {
                    relationships.push(AgentTopologyRelationship {
                        from: source.clone(),
                        to: target.clone(),
                        kind: AgentRelationshipKind::Flow,
                    });
                }
                Edge::Conditional { source, targets, .. } => {
                    relationships.extend(targets.values().filter_map(|target| {
                        target.node_name().map(|target| AgentTopologyRelationship {
                            from: source.clone(),
                            to: target.to_string(),
                            kind: AgentRelationshipKind::Flow,
                        })
                    }));
                }
                Edge::Direct { target: EdgeTarget::End, .. } | Edge::Entry { .. } => {}
            }
        }
        relationships.sort_by(|left, right| (&left.from, &left.to).cmp(&(&right.from, &right.to)));
        relationships.dedup_by(|left, right| left.from == right.from && left.to == right.to);

        Some(AgentTopology {
            root: self.name.clone(),
            coordinator: self.name.clone(),
            members,
            relationships,
        })
    }

    async fn run(&self, ctx: Arc<dyn InvocationContext>) -> adk_core::Result<EventStream> {
        // A call a person asked for needs an agent that holds it for their decision itself,
        // so a graph that starts the run refuses it before any node runs (spec 3.3 §7.4 rule 5).
        if let Some(call) = ctx.run_config().requested_call.as_ref()
            && ctx.agent_name() == self.name()
            && !call.taken_in(&ctx.session().conversation_history())
        {
            let events = call.refusal_events(
                ctx.invocation_id(),
                ctx.branch(),
                self.name(),
                "this agent runs a graph and cannot hold a call for a person's decision",
            );
            return Ok(Box::pin(futures::stream::iter(events.into_iter().map(Ok))));
        }
        // Call before callback
        if let Some(callback) = &self.before_callback {
            callback(ctx.clone()).await?;
        }

        // Map context to input state
        let input = (self.input_mapper)(ctx.as_ref());

        // Create execution config from context, carrying the invocation so an
        // `AgentNode` inside the graph presents this run's identity, services, and
        // cancellation rather than a synthetic standalone context. Agent nodes send
        // their agents' events to `node_events` as they run.
        let thread_id = session_thread_id(ctx.app_name(), ctx.user_id(), ctx.session_id());
        let (sink, mut node_events) = tokio::sync::mpsc::unbounded_channel();
        let mut config =
            ExecutionConfig::new(&thread_id).with_parent_context(ctx.clone()).with_event_sink(sink);
        // Offered to every node; the executor hands it only to a node resuming its
        // own pause.
        if let Some(answer) = (self.resume_mapper)(ctx.as_ref()) {
            for node in self.graph.nodes.keys() {
                config = config.with_resume_value(node.clone(), answer.clone());
            }
        }

        // Execute graph
        let graph = self.graph.clone();
        let output_mapper = self.output_mapper.clone();
        let after_callback = self.after_callback.clone();
        let ctx_clone = ctx.clone();
        let name = self.name.clone();

        let stream = async_stream::stream! {
            // Events this agent builds are the turn's, whatever the mapper set.
            let stamp = |mut event: Event| {
                event.invocation_id = ctx_clone.invocation_id().to_string();
                if event.author.is_empty() {
                    event.author = name.clone();
                }
                if event.branch.is_empty() {
                    event.branch = ctx_clone.branch().to_string();
                }
                event
            };

            // Each call is one turn on the session's thread: a paused thread
            // resumes, and a finished one runs again from its entry nodes with the
            // previous turn's state carried over.
            let mut executor =
                crate::executor::PregelExecutor::new(&graph, config).restarting_completed_threads();
            let outcome = {
                let run = executor.run(input);
                tokio::pin!(run);
                loop {
                    let next = tokio::select! {
                        biased;
                        Some(event) = node_events.recv() => Next::Event(Box::new(event)),
                        outcome = &mut run => Next::Done(outcome),
                    };
                    match next {
                        Next::Event(event) => yield Ok(*event),
                        Next::Done(outcome) => break outcome,
                    }
                }
            };
            // Whatever a node sent as the run finished.
            while let Ok(event) = node_events.try_recv() {
                yield Ok(event);
            }

            match outcome {
                Ok(state) => {
                    let events = output_mapper(&state);
                    for event in events {
                        let event = stamp(event);
                        // Call after callback for each event
                        if let Some(callback) = &after_callback
                            && let Err(e) = callback(ctx_clone.clone(), event.clone()).await {
                                yield Err(e);
                                return;
                            }
                        yield Ok(event);
                    }
                }
                Err(GraphError::Interrupted(interrupt)) => {
                    // The `Agent` trait yields events, so an interrupt cannot be
                    // returned as an error without ending the invocation. Emit one
                    // event per pause of the step, each carrying its structured
                    // pause so a caller can read the node, the payload, and the
                    // checkpoint to resume from.
                    for paused in &interrupt.interrupts {
                        let tool_confirmation =
                            crate::interrupt::GraphToolConfirmationPause::from_interrupt(
                                paused,
                                &interrupt.thread_id,
                                &interrupt.checkpoint_id,
                            );
                        let payload = tool_confirmation.clone().map_or_else(
                            || crate::interrupt::GraphInterruptPayload::new(
                                paused,
                                &interrupt.thread_id,
                                &interrupt.checkpoint_id,
                            ),
                            crate::interrupt::GraphInterruptPayload::from_tool_confirmation_pause,
                        );
                        let mut event = Event::new("graph_interrupted");
                        if let Some(pause) = tool_confirmation {
                            event.llm_response.interrupted = true;
                            event.llm_response.turn_complete = true;
                            event.actions.tool_confirmation = Some(pause.request);
                        }
                        event.set_content(Content::new("assistant").with_text(paused.to_string()));
                        event.provider_metadata.insert(
                            crate::interrupt::INTERRUPT_METADATA_KEY.to_string(),
                            payload.to_metadata_value(),
                        );
                        yield Ok(stamp(event));
                    }
                }
                Err(e) => {
                    // Converted, not re-wrapped, so an agent node's failure keeps the
                    // agent's category and a node timeout stays a timeout.
                    yield Err(e.into());
                }
            }
        };

        Ok(Box::pin(stream))
    }
}

/// What a running turn produced next: an agent node's event, or the run's outcome.
enum Next {
    Event(Box<Event>),
    Done(Result<State>),
}

/// Returns the checkpoint thread id for an ADK session.
///
/// [`GraphAgent`] keys its checkpoints by this id. It joins the app name, user
/// id, and session id with `:`, and percent-encodes `%` and `:` inside each part,
/// so distinct identities never produce the same thread id. Use it to find a
/// session's checkpoints with [`Checkpointer::load`] or [`Checkpointer::list`].
///
/// # Example
///
/// ```
/// use adk_graph::agent::session_thread_id;
///
/// assert_eq!(session_thread_id("shop", "alice", "s-1"), "shop:alice:s-1");
/// assert_eq!(session_thread_id("shop", "a:b", "c"), "shop:a%3Ab:c");
/// assert_ne!(session_thread_id("shop", "alice", "s-1"), session_thread_id("shop", "bob", "s-1"));
/// ```
pub fn session_thread_id(app_name: &str, user_id: &str, session_id: &str) -> String {
    let mut thread_id =
        String::with_capacity(app_name.len() + user_id.len() + session_id.len() + 2);
    for (index, part) in [app_name, user_id, session_id].into_iter().enumerate() {
        if index > 0 {
            thread_id.push(':');
        }
        push_thread_part(&mut thread_id, part);
    }
    thread_id
}

/// Returns the checkpoint thread id of one graph tool call.
///
/// [`NodeTool`](crate::tool::NodeTool) runs each call on its own thread: the
/// session's [`session_thread_id`] with the function call id appended as a fourth
/// `:`-separated part, encoded the same way. A second call in the same session
/// therefore runs the graph again, and the same call dispatched again, as when a
/// held call resumes, continues its own thread.
///
/// # Example
///
/// ```
/// use adk_graph::agent::{session_thread_id, tool_call_thread_id};
///
/// assert_eq!(tool_call_thread_id("shop", "alice", "s-1", "call-7"), "shop:alice:s-1:call-7");
/// assert_ne!(
///     tool_call_thread_id("shop", "alice", "s-1", "call-7"),
///     tool_call_thread_id("shop", "alice", "s-1", "call-8")
/// );
/// assert_ne!(tool_call_thread_id("shop", "alice", "s", "1"), session_thread_id("shop", "alice", "s:1"));
/// ```
pub fn tool_call_thread_id(
    app_name: &str,
    user_id: &str,
    session_id: &str,
    function_call_id: &str,
) -> String {
    let mut thread_id = session_thread_id(app_name, user_id, session_id);
    thread_id.push(':');
    push_thread_part(&mut thread_id, function_call_id);
    thread_id
}

/// Appends one part of a thread id, percent-encoding the separator and `%`.
fn push_thread_part(thread_id: &mut String, part: &str) {
    for c in part.chars() {
        match c {
            '%' => thread_id.push_str("%25"),
            ':' => thread_id.push_str("%3A"),
            other => thread_id.push(other),
        }
    }
}

/// Default input mapper - extracts content from InvocationContext
fn default_input_mapper(ctx: &dyn InvocationContext) -> State {
    let mut state = State::new();

    // Get user content
    let content = ctx.user_content();
    let text: String = content.parts.iter().filter_map(|p| p.text()).collect::<Vec<_>>().join("\n");

    if !text.is_empty() {
        state.insert("input".to_string(), json!(text));
        state.insert("messages".to_string(), json!([{"role": "user", "content": text}]));
    }

    // Add session ID
    state.insert("session_id".to_string(), json!(ctx.session_id()));

    state
}

/// Default resume mapper - the turn's text, when it has any
fn default_resume_mapper(ctx: &dyn InvocationContext) -> Option<serde_json::Value> {
    let text: String =
        ctx.user_content().parts.iter().filter_map(|p| p.text()).collect::<Vec<_>>().join("\n");
    (!text.is_empty()).then(|| json!(text))
}

/// Default output mapper - creates events from state
fn default_output_mapper(state: &State) -> Vec<Event> {
    let mut events = Vec::new();

    // Try to get output from common fields
    let output_text = state
        .get("output")
        .and_then(|v| v.as_str())
        .or_else(|| state.get("result").and_then(|v| v.as_str()))
        .or_else(|| {
            state
                .get("messages")
                .and_then(|v| v.as_array())
                .and_then(|arr| arr.last())
                .and_then(|msg| msg.get("content"))
                .and_then(|c| c.as_str())
        });

    let text = if let Some(text) = output_text {
        text.to_string()
    } else {
        // Return the full state as JSON
        serde_json::to_string_pretty(state).unwrap_or_default()
    };

    let mut event = Event::new("graph_output");
    event.set_content(Content::new("assistant").with_text(&text));
    events.push(event);

    events
}

/// Builder for GraphAgent
pub struct GraphAgentBuilder {
    name: String,
    description: String,
    schema: StateSchema,
    nodes: Vec<Arc<dyn Node>>,
    edges: Vec<Edge>,
    checkpointer: Option<Arc<dyn Checkpointer>>,
    interrupt_before: Vec<String>,
    interrupt_after: Vec<String>,
    recursion_limit: usize,
    max_concurrency: Option<usize>,
    input_mapper: Option<InputMapper>,
    output_mapper: Option<OutputMapper>,
    before_callback: Option<BeforeAgentCallback>,
    after_callback: Option<AfterAgentCallback>,
    resume_mapper: Option<ResumeMapper>,
    timeout_policies: HashMap<String, TimeoutPolicy>,
    default_timeout: Option<TimeoutPolicy>,
    deferred_configs: HashMap<String, DeferredNodeConfig>,
    governed_nodes: HashMap<String, crate::governed::GovernedNode>,
    #[cfg(feature = "node-cache")]
    cache_policies: HashMap<String, crate::cache::NodeCachePolicy>,
}

impl GraphAgentBuilder {
    /// Create a new builder
    pub fn new(name: &str) -> Self {
        Self {
            name: name.to_string(),
            description: String::new(),
            schema: StateSchema::simple(&["input", "output", "messages"]),
            nodes: vec![],
            edges: vec![],
            checkpointer: None,
            interrupt_before: vec![],
            interrupt_after: vec![],
            recursion_limit: 100,
            max_concurrency: None,
            input_mapper: None,
            output_mapper: None,
            before_callback: None,
            after_callback: None,
            resume_mapper: None,
            timeout_policies: HashMap::new(),
            default_timeout: None,
            deferred_configs: HashMap::new(),
            governed_nodes: HashMap::new(),
            #[cfg(feature = "node-cache")]
            cache_policies: HashMap::new(),
        }
    }

    /// Set description
    pub fn description(mut self, desc: &str) -> Self {
        self.description = desc.to_string();
        self
    }

    /// Set state schema
    pub fn state_schema(mut self, schema: StateSchema) -> Self {
        self.schema = schema;
        self
    }

    /// Add channels to state schema
    pub fn channels(mut self, channels: &[&str]) -> Self {
        self.schema = StateSchema::simple(channels);
        self
    }

    /// Add a node
    pub fn node<N: Node + 'static>(mut self, node: N) -> Self {
        self.nodes.push(Arc::new(node));
        self
    }

    /// Add a function as a node
    pub fn node_fn<F, Fut>(mut self, name: &str, func: F) -> Self
    where
        F: Fn(NodeContext) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<NodeOutput>> + Send + 'static,
    {
        self.nodes.push(Arc::new(FunctionNode::new(name, func)));
        self
    }

    /// Add a direct edge
    pub fn edge(mut self, source: &str, target: &str) -> Self {
        let target =
            if target == END { EdgeTarget::End } else { EdgeTarget::Node(target.to_string()) };

        if source == START {
            let entry_idx = self.edges.iter().position(|e| matches!(e, Edge::Entry { .. }));
            match entry_idx {
                Some(idx) => {
                    if let Edge::Entry { targets } = &mut self.edges[idx]
                        && let EdgeTarget::Node(node) = &target
                        && !targets.contains(node)
                    {
                        targets.push(node.clone());
                    }
                }
                None => {
                    if let EdgeTarget::Node(node) = target {
                        self.edges.push(Edge::Entry { targets: vec![node] });
                    }
                }
            }
        } else {
            self.edges.push(Edge::Direct { source: source.to_string(), target });
        }

        self
    }

    /// Add a conditional edge
    pub fn conditional_edge<F, I>(mut self, source: &str, router: F, targets: I) -> Self
    where
        F: Fn(&State) -> String + Send + Sync + 'static,
        I: IntoIterator<Item = (&'static str, &'static str)>,
    {
        let targets_map: HashMap<String, EdgeTarget> = targets
            .into_iter()
            .map(|(k, v)| {
                let target =
                    if v == END { EdgeTarget::End } else { EdgeTarget::Node(v.to_string()) };
                (k.to_string(), target)
            })
            .collect();

        self.edges.push(Edge::Conditional {
            source: source.to_string(),
            router: Arc::new(router),
            targets: targets_map,
        });

        self
    }

    /// Set checkpointer
    pub fn checkpointer<C: Checkpointer + 'static>(mut self, checkpointer: C) -> Self {
        self.checkpointer = Some(Arc::new(checkpointer));
        self
    }

    /// Set checkpointer with Arc
    pub fn checkpointer_arc(mut self, checkpointer: Arc<dyn Checkpointer>) -> Self {
        self.checkpointer = Some(checkpointer);
        self
    }

    /// Set nodes to interrupt before
    pub fn interrupt_before(mut self, nodes: &[&str]) -> Self {
        self.interrupt_before = nodes.iter().map(|s| s.to_string()).collect();
        self
    }

    /// Set nodes to interrupt after
    pub fn interrupt_after(mut self, nodes: &[&str]) -> Self {
        self.interrupt_after = nodes.iter().map(|s| s.to_string()).collect();
        self
    }

    /// Cap how many nodes execute concurrently within one super-step.
    ///
    /// See [`CompiledGraph::with_max_concurrency`](crate::graph::CompiledGraph::with_max_concurrency).
    pub fn max_concurrency(mut self, limit: usize) -> Self {
        self.max_concurrency = Some(limit.max(1));
        self
    }

    /// Sets how many super-steps each turn may take; 100 when unset.
    ///
    /// See [`CompiledGraph::with_recursion_limit`](crate::graph::CompiledGraph::with_recursion_limit).
    pub fn recursion_limit(mut self, limit: usize) -> Self {
        self.recursion_limit = limit;
        self
    }

    /// Set a timeout policy for a specific node.
    ///
    /// The policy is applied when the named node executes, enforcing
    /// wall-clock and/or idle timeouts with the configured recovery action.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use std::time::Duration;
    /// use adk_graph::timeout::{TimeoutPolicy, OnTimeout};
    ///
    /// let agent = GraphAgent::builder("my_graph")
    ///     .node_timeout("slow_node", TimeoutPolicy {
    ///         run_timeout: Some(Duration::from_secs(10)),
    ///         idle_timeout: None,
    ///         on_timeout: OnTimeout::Fail,
    ///     })
    ///     .build()?;
    /// ```
    pub fn node_timeout(mut self, node_name: &str, policy: TimeoutPolicy) -> Self {
        self.timeout_policies.insert(node_name.to_string(), policy);
        self
    }

    /// Set a default timeout policy applied to all nodes without an explicit override.
    ///
    /// Nodes that have a per-node policy set via [`node_timeout`](Self::node_timeout)
    /// will use their specific policy instead of this default.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use std::time::Duration;
    /// use adk_graph::timeout::{TimeoutPolicy, OnTimeout};
    ///
    /// let agent = GraphAgent::builder("my_graph")
    ///     .default_timeout(TimeoutPolicy {
    ///         run_timeout: Some(Duration::from_secs(30)),
    ///         idle_timeout: Some(Duration::from_secs(5)),
    ///         on_timeout: OnTimeout::Skip,
    ///     })
    ///     .build()?;
    /// ```
    pub fn default_timeout(mut self, policy: TimeoutPolicy) -> Self {
        self.default_timeout = Some(policy);
        self
    }

    /// Add a deferred (fan-in barrier) node to the graph.
    ///
    /// A deferred node waits for all upstream parallel paths to complete before
    /// executing. The provided function is wrapped as a [`FunctionNode`] and the
    /// [`DeferredNodeConfig`] controls how upstream outputs are merged and how
    /// long the node waits for all paths.
    ///
    /// # Arguments
    ///
    /// * `name` - The name of the deferred node.
    /// * `func` - The async function to execute once all upstream paths complete.
    /// * `config` - Configuration controlling merge strategy and fan-in timeout.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use std::time::Duration;
    /// use adk_graph::deferred::{DeferredNodeConfig, MergeStrategy};
    /// use adk_graph::node::NodeOutput;
    ///
    /// let agent = GraphAgent::builder("scatter_gather")
    ///     .deferred_node("aggregator", |_ctx| async {
    ///         Ok(NodeOutput::new().with_update("status", serde_json::json!("merged")))
    ///     }, DeferredNodeConfig {
    ///         merge_strategy: MergeStrategy::Collect,
    ///         fan_in_timeout: Some(Duration::from_secs(30)),
    ///     })
    ///     .build()?;
    /// ```
    /// Configure fan-in for a node already added with [`node`](Self::node).
    ///
    /// [`deferred_node`](Self::deferred_node) both adds and configures a node, so
    /// a custom `Node` added through `node` had no way to set a merge strategy or
    /// a fan-in timeout.
    ///
    /// A node reached by more than one unconditional edge is deferred
    /// automatically; this overrides that default.
    pub fn mark_deferred(mut self, name: &str, config: DeferredNodeConfig) -> Self {
        self.deferred_configs.insert(name.to_string(), config);
        self
    }

    pub fn deferred_node<F, Fut>(mut self, name: &str, func: F, config: DeferredNodeConfig) -> Self
    where
        F: Fn(NodeContext) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<NodeOutput>> + Send + 'static,
    {
        self.nodes.push(Arc::new(FunctionNode::new(name, func)));
        self.deferred_configs.insert(name.to_string(), config);
        self
    }

    /// Puts a node's calls on the governed path (spec 3.3 §12).
    ///
    /// See [`CompiledGraph::with_governed_node`](crate::graph::CompiledGraph::with_governed_node)
    /// and the [`governed`](crate::governed) module.
    ///
    /// # Example
    ///
    /// ```
    /// use adk_graph::agent::GraphAgent;
    /// use adk_graph::edge::{END, START};
    /// use adk_graph::governed::GovernedNode;
    /// use adk_graph::node::NodeOutput;
    ///
    /// let agent = GraphAgent::builder("invoice-run")
    ///     .channels(&["charge"])
    ///     .node_fn("pay", |_ctx| async { Ok(NodeOutput::new()) })
    ///     .edge(START, "pay")
    ///     .edge("pay", END)
    ///     .governed_node("pay", GovernedNode::new().with_approval().spending_money())
    ///     .build()?;
    /// assert!(agent.graph().shape().nodes[0].governed.is_some());
    /// # Ok::<(), adk_graph::GraphError>(())
    /// ```
    pub fn governed_node(mut self, name: &str, governed: crate::governed::GovernedNode) -> Self {
        self.governed_nodes.insert(name.to_string(), governed);
        self
    }

    /// Set a cache policy for a specific node.
    ///
    /// When a node has a cache policy, its execution results are cached keyed
    /// by a blake3 hash of the node name and input state. Subsequent executions
    /// with identical inputs return the cached result without re-executing the
    /// node.
    ///
    /// # Arguments
    ///
    /// * `name` — the name of the node to cache
    /// * `policy` — the cache policy specifying backend and TTL
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use std::time::Duration;
    /// use adk_graph::cache::{CacheBackend, NodeCachePolicy};
    ///
    /// let agent = GraphAgent::builder("cached_graph")
    ///     .node_cache("expensive_node", NodeCachePolicy {
    ///         backend: CacheBackend::InMemory { max_entries: 128 },
    ///         ttl: Some(Duration::from_secs(300)),
    ///     })
    ///     .build()?;
    /// ```
    #[cfg(feature = "node-cache")]
    pub fn node_cache(mut self, name: &str, policy: crate::cache::NodeCachePolicy) -> Self {
        self.cache_policies.insert(name.to_string(), policy);
        self
    }

    /// Set custom input mapper
    pub fn input_mapper<F>(mut self, mapper: F) -> Self
    where
        F: Fn(&dyn InvocationContext) -> State + Send + Sync + 'static,
    {
        self.input_mapper = Some(Arc::new(mapper));
        self
    }

    /// Set custom output mapper
    pub fn output_mapper<F>(mut self, mapper: F) -> Self
    where
        F: Fn(&State) -> Vec<Event> + Send + Sync + 'static,
    {
        self.output_mapper = Some(Arc::new(mapper));
        self
    }

    /// Maps a turn to the answer a paused node reads with
    /// [`NodeContext::resume_value`].
    ///
    /// Called on every turn; the answer reaches only a node that the turn resumes
    /// from its own dynamic interrupt. Return `None` to resume without one. The
    /// default answers with the turn's text.
    ///
    /// # Example
    ///
    /// ```
    /// use adk_graph::agent::GraphAgent;
    /// use serde_json::json;
    ///
    /// let builder = GraphAgent::builder("refunds").resume_mapper(|ctx| {
    ///     let text: String = ctx.user_content().parts.iter().filter_map(|p| p.text()).collect();
    ///     Some(json!({ "approved": text.trim().eq_ignore_ascii_case("approve") }))
    /// });
    /// # let _ = builder;
    /// ```
    pub fn resume_mapper<F>(mut self, mapper: F) -> Self
    where
        F: Fn(&dyn InvocationContext) -> Option<serde_json::Value> + Send + Sync + 'static,
    {
        self.resume_mapper = Some(Arc::new(mapper));
        self
    }

    /// Set before agent callback
    pub fn before_agent_callback<F, Fut>(mut self, callback: F) -> Self
    where
        F: Fn(Arc<dyn InvocationContext>) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = adk_core::Result<()>> + Send + 'static,
    {
        self.before_callback = Some(Arc::new(move |ctx| Box::pin(callback(ctx))));
        self
    }

    /// Set after agent callback
    ///
    /// Note: The callback receives a cloned Event to avoid lifetime issues.
    pub fn after_agent_callback<F, Fut>(mut self, callback: F) -> Self
    where
        F: Fn(Arc<dyn InvocationContext>, Event) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = adk_core::Result<()>> + Send + 'static,
    {
        self.after_callback = Some(Arc::new(move |ctx, event| {
            let event_clone = event.clone();
            Box::pin(callback(ctx, event_clone))
        }));
        self
    }

    /// Add an action node to the graph.
    ///
    /// Wraps the `ActionNodeConfig` in an `ActionNodeExecutor` and registers it
    /// as a node. If the config is a `SwitchNodeConfig`, conditional edges are
    /// also auto-registered from the switch conditions.
    #[cfg(feature = "action")]
    pub fn action_node(mut self, config: adk_action::ActionNodeConfig) -> Self {
        use crate::action::ActionNodeExecutor;

        // If this is a Switch node, register conditional edges
        if let adk_action::ActionNodeConfig::Switch(ref switch_config) = config {
            let conditions = switch_config.conditions.clone();
            let eval_mode = switch_config.evaluation_mode.clone();
            let default_branch = switch_config.default_branch.clone();
            let source = config.standard().id.clone();

            let mut targets_map: HashMap<String, EdgeTarget> = HashMap::new();
            for condition in &conditions {
                targets_map.insert(
                    condition.output_port.clone(),
                    EdgeTarget::Node(condition.output_port.clone()),
                );
            }
            if let Some(ref default) = default_branch {
                let target = if default == END {
                    EdgeTarget::End
                } else {
                    EdgeTarget::Node(default.clone())
                };
                targets_map.insert(default.clone(), target);
            }
            targets_map.insert(END.to_string(), EdgeTarget::End);

            let router = Arc::new(move |state: &State| -> String {
                match crate::action::switch::evaluate_switch_conditions(
                    &conditions,
                    state,
                    &eval_mode,
                    default_branch.as_deref(),
                ) {
                    Ok(ports) => ports.into_iter().next().unwrap_or_else(|| END.to_string()),
                    Err(_) => END.to_string(),
                }
            });

            self.edges.push(Edge::Conditional { source, router, targets: targets_map });
        }

        let executor = ActionNodeExecutor::new(config);
        self.nodes.push(Arc::new(executor));
        self
    }

    /// Build the GraphAgent
    pub fn build(self) -> Result<GraphAgent> {
        // Build the graph
        let mut graph = StateGraph::new(self.schema);

        // Add nodes
        for node in self.nodes {
            graph.nodes.insert(node.name().to_string(), node);
        }

        // Add edges
        graph.edges = self.edges;

        // Explicit fan-in configurations go in before compiling, so a node with
        // several incoming edges and no configuration is still deferred.
        graph.deferred_configs = self.deferred_configs;

        // Compile
        let mut compiled = graph.compile()?;

        // Configure
        if let Some(cp) = self.checkpointer {
            compiled.checkpointer = Some(cp);
        }
        compiled.interrupt_before = self.interrupt_before.into_iter().collect();
        compiled.interrupt_after = self.interrupt_after.into_iter().collect();
        compiled.recursion_limit = self.recursion_limit;
        compiled.max_concurrency = self.max_concurrency;
        compiled.timeout_policies = self.timeout_policies;
        compiled.default_timeout = self.default_timeout;
        compiled.governed_nodes = self.governed_nodes;
        compiled.check_governed_nodes()?;

        #[cfg(feature = "node-cache")]
        {
            compiled.node_caches = self
                .cache_policies
                .iter()
                .map(|(name, policy)| {
                    (name.clone(), Arc::new(crate::cache::NodeCache::from_policy(policy)))
                })
                .collect();
            compiled.cache_policies = self.cache_policies;
        }

        Ok(GraphAgent {
            name: self.name,
            description: self.description,
            graph: Arc::new(compiled),
            input_mapper: self.input_mapper.unwrap_or(Arc::new(default_input_mapper)),
            output_mapper: self.output_mapper.unwrap_or(Arc::new(default_output_mapper)),
            before_callback: self.before_callback,
            after_callback: self.after_callback,
            resume_mapper: self.resume_mapper.unwrap_or(Arc::new(default_resume_mapper)),
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    #[tokio::test]
    async fn test_graph_agent_builder() {
        let agent = GraphAgent::builder("test")
            .description("Test agent")
            .channels(&["value"])
            .node_fn("set", |_ctx| async { Ok(NodeOutput::new().with_update("value", json!(42))) })
            .edge(START, "set")
            .edge("set", END)
            .build()
            .unwrap();

        assert_eq!(agent.name(), "test");
        assert_eq!(agent.description(), "Test agent");

        // Test direct invocation
        let result = agent.invoke(State::new(), ExecutionConfig::new("test")).await.unwrap();

        assert_eq!(result.get("value"), Some(&json!(42)));

        let topology = agent.topology().expect("graph topology");
        assert_eq!(topology.root, "test");
        assert_eq!(topology.coordinator, "test");
        assert_eq!(topology.members.len(), 2);
        assert_eq!(topology.relationships.len(), 1);
        assert_eq!(topology.relationships[0].from, "test");
        assert_eq!(topology.relationships[0].to, "set");
        assert_eq!(topology.relationships[0].kind, AgentRelationshipKind::Flow);
    }
}