juncture 0.2.0

Typed state machine framework for LLM agents - Rust implementation of LangGraph
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
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
//! `ReAct` agent: a prebuilt agent that reasons and acts with tools.
//!
//! This module provides [`create_react_agent`] and related types for building
//! agent workflows that follow the Reason-Act (`ReAct`) pattern. The agent
//! calls an LLM, and if the LLM requests tool execution, the tools are run
//! and the results are fed back to the LLM for further reasoning.
//!
//! # Graph Structure
//!
//! ```text
//! START -> agent -> [conditional] -> tools -> agent
//!                        |
//!                        v
//!                       END
//! ```
//!
//! - The `agent` node calls the LLM model.
//! - If the LLM response contains tool calls, the `tools` node executes them.
//! - If the LLM response has no tool calls, execution ends.
//!
//! # Example
//!
//! ```ignore
//! use juncture::llm::{ChatModel, MockChatModel};
//! use juncture::prebuilt::{create_react_agent, MessagesState};
//! use juncture::tools::Tool;
//!
//! let model = MockChatModel::new("gpt-4").with_response("Done!");
//! let tools: Vec<Box<dyn Tool>> = vec![];
//!
//! let agent = create_react_agent(model, tools)?;
//! ```

use std::fmt;
use std::sync::Arc;

use juncture_core::edge::{END, PathMap, RouteResult, Router};
use juncture_core::error::JunctureError;
use juncture_core::graph::{CompiledGraph, StateGraph, TopologyError};
use juncture_core::node::{IntoNode, Node};
use juncture_core::state::messages::Message;
use juncture_core::store::Store;
use juncture_core::{Command, RunnableConfig};

use crate::llm::{CallOptions, ChatModel, ToolDefinition as LlmToolDefinition};
use crate::prebuilt::messages_state::{MessagesState, MessagesStateUpdate};
use crate::tools::{Tool, ToolDefinition, ToolNode};

/// Type alias for the dynamic prompt function signature.
///
/// Reduces type complexity in the [`PromptSource::Dynamic`] variant.
type DynamicPromptFn = Arc<dyn Fn(&[Message]) -> String + Send + Sync>;

/// Pre-model hook: transforms [`MessagesState`] before model invocation.
type PreModelHook = Arc<dyn Fn(&MessagesState) -> MessagesState + Send + Sync>;

/// Post-model hook: transforms the model response [`Message`] after invocation.
type PostModelHook = Arc<dyn Fn(&MessagesState, &Message) -> Message + Send + Sync>;

/// Model selector: returns per-call [`CallOptions`] based on current state.
type ModelSelector = Arc<dyn Fn(&MessagesState) -> CallOptions + Send + Sync>;

/// Convert tool definitions from the tools module format to the LLM module format.
///
/// The `tools` module defines [`ToolDefinition`] with `name`, `description`, and
/// `parameters` fields. The `llm` module defines its own [`LlmToolDefinition`] with
/// the same fields. This function converts between them.
pub(super) fn convert_tool_defs(defs: &[ToolDefinition]) -> Vec<LlmToolDefinition> {
    defs.iter()
        .map(|d| LlmToolDefinition {
            name: d.name.clone(),
            description: d.description.clone(),
            parameters: d.parameters.clone(),
        })
        .collect()
}

/// Create an agent with default configuration.
///
/// Builds a graph that alternates between LLM reasoning and tool execution.
/// The agent calls the LLM, and if the response contains tool calls, the
/// tools are executed and the results are fed back. This continues until
/// the LLM produces a response without tool calls.
///
/// This is the base factory. [`create_react_agent`] delegates to this function.
///
/// # Arguments
///
/// * `model` - The LLM model to use for reasoning.
/// * `tools` - The tools available to the agent.
///
/// # Errors
///
/// Returns [`TopologyError`] if the graph cannot be compiled, for example
/// if node names conflict.
///
/// # Example
///
/// ```ignore
/// use juncture::llm::MockChatModel;
/// use juncture::prebuilt::create_agent;
/// use juncture::tools::Tool;
///
/// let model = MockChatModel::new("gpt-4").with_response("Hello!");
/// let tools: Vec<Box<dyn Tool>> = vec![];
///
/// let graph = create_agent(model, tools)?;
/// ```
pub fn create_agent<M: ChatModel>(
    model: M,
    tools: Vec<Box<dyn Tool>>,
) -> Result<CompiledGraph<MessagesState>, TopologyError> {
    create_agent_with_config(model, tools, ReactAgentConfig::default())
}

/// Create a `ReAct` agent with default configuration.
///
/// Delegates to [`create_agent`]. Retained for backward compatibility and
/// semantic clarity when building ReAct-pattern agents.
///
/// # Arguments
///
/// * `model` - The LLM model to use for reasoning.
/// * `tools` - The tools available to the agent.
///
/// # Errors
///
/// Returns [`TopologyError`] if the graph cannot be compiled, for example
/// if node names conflict.
///
/// # Example
///
/// ```ignore
/// use juncture::llm::MockChatModel;
/// use juncture::prebuilt::create_react_agent;
/// use juncture::tools::Tool;
///
/// let model = MockChatModel::new("gpt-4").with_response("Hello!");
/// let tools: Vec<Box<dyn Tool>> = vec![];
///
/// let graph = create_react_agent(model, tools)?;
/// ```
pub fn create_react_agent<M: ChatModel>(
    model: M,
    tools: Vec<Box<dyn Tool>>,
) -> Result<CompiledGraph<MessagesState>, TopologyError> {
    create_agent(model, tools)
}

/// Create a `ReAct` agent with custom configuration.
///
/// Like [`create_agent`], but accepts a [`ReactAgentConfig`] for
/// additional options such as system prompts and interrupt settings.
///
/// # Arguments
///
/// * `model` - The LLM model to use for reasoning.
/// * `tools` - The tools available to the agent.
/// * `config` - Configuration options for the agent.
///
/// # Errors
///
/// Returns [`TopologyError`] if the graph cannot be compiled.
///
/// # Example
///
/// ```ignore
/// use juncture::llm::MockChatModel;
/// use juncture::prebuilt::{create_agent_with_config, ReactAgentConfig};
/// use juncture::tools::Tool;
///
/// let model = MockChatModel::new("gpt-4").with_response("Hello!");
/// let tools: Vec<Box<dyn Tool>> = vec![];
/// let config = ReactAgentConfig {
///     system_message: Some("You are a helpful assistant.".to_string()),
///     ..Default::default()
/// };
///
/// let graph = create_agent_with_config(model, tools, config)?;
/// ```
#[allow(
    clippy::needless_pass_by_value,
    reason = "model ownership is transferred into the graph"
)]
pub fn create_agent_with_config<M: ChatModel>(
    model: M,
    tools: Vec<Box<dyn Tool>>,
    config: ReactAgentConfig,
) -> Result<CompiledGraph<MessagesState>, TopologyError> {
    let tool_defs: Vec<ToolDefinition> = tools.iter().map(|t| t.definition()).collect();
    let llm_tool_defs = convert_tool_defs(&tool_defs);
    let model_with_tools = model.bind_tools(llm_tool_defs);

    let prompt = config.system_message.map(PromptSource::Static);
    let mut agent_node = AgentNode::new_with_prompt_option(model_with_tools, prompt);
    if let Some(hook) = config.pre_model_hook {
        agent_node = agent_node.with_pre_model_hook(hook);
    }
    if let Some(hook) = config.post_model_hook {
        agent_node = agent_node.with_post_model_hook(hook);
    }
    if let Some(selector) = config.model_selector {
        agent_node = agent_node.with_model_selector(selector);
    }

    let tool_node = Arc::new(ToolNode::new(tools));
    let tool_adapter = ToolNodeAdapter::new(tool_node, config.store);

    let mut graph = StateGraph::<MessagesState>::new();

    graph.add_node_simple("agent", agent_node)?;
    graph.add_node_simple("tools", tool_adapter)?;

    graph.set_entry_point("agent");

    let path_map = PathMap::from(&[("tools", "tools"), (END, END)][..]);
    graph.add_conditional_edges("agent", Arc::new(AgentRouter), path_map);

    graph.add_edge("tools", "agent");

    graph.compile()
}

/// Create a `ReAct` agent with custom configuration.
///
/// Delegates to [`create_agent_with_config`]. Retained for backward
/// compatibility and semantic clarity when building ReAct-pattern agents.
///
/// # Arguments
///
/// * `model` - The LLM model to use for reasoning.
/// * `tools` - The tools available to the agent.
/// * `config` - Configuration options for the agent.
///
/// # Errors
///
/// Returns [`TopologyError`] if the graph cannot be compiled.
///
/// # Example
///
/// ```ignore
/// use juncture::llm::MockChatModel;
/// use juncture::prebuilt::{create_react_agent_with_config, ReactAgentConfig};
/// use juncture::tools::Tool;
///
/// let model = MockChatModel::new("gpt-4").with_response("Hello!");
/// let tools: Vec<Box<dyn Tool>> = vec![];
/// let config = ReactAgentConfig {
///     system_message: Some("You are a helpful assistant.".to_string()),
///     ..Default::default()
/// };
///
/// let graph = create_react_agent_with_config(model, tools, config)?;
/// ```
#[allow(
    clippy::needless_pass_by_value,
    reason = "model ownership is transferred into the graph"
)]
pub fn create_react_agent_with_config<M: ChatModel>(
    model: M,
    tools: Vec<Box<dyn Tool>>,
    config: ReactAgentConfig,
) -> Result<CompiledGraph<MessagesState>, TopologyError> {
    create_agent_with_config(model, tools, config)
}

/// Source for system prompts in agent nodes.
///
/// Prompts can be either a static string injected on every invocation,
/// or a dynamic function that computes the prompt from the current messages.
#[derive(Clone)]
pub enum PromptSource {
    /// Static system prompt string.
    Static(String),

    /// Dynamic prompt computed from the current message list.
    Dynamic(DynamicPromptFn),
}

impl fmt::Debug for PromptSource {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Static(s) => f.debug_tuple("Static").field(s).finish(),
            Self::Dynamic(_) => f.debug_tuple("Dynamic").field(&"<fn>").finish(),
        }
    }
}

/// Configuration for [`create_react_agent_with_config`].
///
/// Controls optional behavior such as system prompt injection, iteration
/// limits, human-in-the-loop interrupt points, pre/post model hooks,
/// dynamic model selection, and cross-thread persistent store integration.
#[derive(Clone, Default)]
pub struct ReactAgentConfig {
    /// Optional system message injected before each LLM call.
    ///
    /// When set, the agent node prepends a system message to the conversation
    /// before invoking the model.
    pub system_message: Option<String>,

    /// Maximum number of agent-tool loop iterations.
    ///
    /// When set, limits how many times the agent can cycle through the
    /// reasoning-acting loop. This prevents infinite loops when the LLM
    /// keeps requesting tool calls.
    pub max_iterations: Option<usize>,

    /// Whether to interrupt execution before tool calls are executed.
    ///
    /// When true, execution pauses before the tools node runs, allowing
    /// a human to review and approve tool invocations before they proceed.
    pub interrupt_before_tools: bool,

    /// Hook called before each model invocation.
    ///
    /// Receives a reference to the current [`MessagesState`] and returns a
    /// (possibly modified) [`MessagesState`]. Useful for injecting context,
    /// trimming messages, or adding system instructions before the LLM call.
    pub pre_model_hook: Option<PreModelHook>,

    /// Hook called after each model invocation.
    ///
    /// Receives a reference to the current [`MessagesState`] and a reference
    /// to the model response [`Message`], returns a (possibly modified)
    /// response [`Message`]. Useful for post-processing, validation, or
    /// content filtering of LLM responses.
    pub post_model_hook: Option<PostModelHook>,

    /// Dynamic model selection strategy.
    ///
    /// Takes a reference to the current [`MessagesState`] and returns
    /// [`CallOptions`] for this invocation. Use this to switch models
    /// dynamically (via [`CallOptions::model_override`]), adjust
    /// temperature, set `tool_choice`, or customize other per-call options.
    pub model_selector: Option<ModelSelector>,

    /// Cross-thread persistent store for long-term memory.
    ///
    /// When set, the store is passed to the tool adapter and made available
    /// to stateful tools via [`ToolRuntime`](crate::tools::ToolRuntime).
    /// This enables tools to persist and retrieve knowledge across graph
    /// executions.
    pub store: Option<Arc<dyn Store>>,
}

impl fmt::Debug for ReactAgentConfig {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ReactAgentConfig")
            .field("system_message", &self.system_message)
            .field("max_iterations", &self.max_iterations)
            .field("interrupt_before_tools", &self.interrupt_before_tools)
            .field(
                "pre_model_hook",
                &self.pre_model_hook.as_ref().map(|_| "..."),
            )
            .field(
                "post_model_hook",
                &self.post_model_hook.as_ref().map(|_| "..."),
            )
            .field(
                "model_selector",
                &self.model_selector.as_ref().map(|_| "..."),
            )
            .field("store", &self.store.as_ref().map(|_| "..."))
            .finish()
    }
}

/// Agent node: calls an LLM and returns the response as a state update.
///
/// This node optionally injects a system prompt, then invokes the bound
/// LLM model with the current conversation messages. The LLM response
/// is returned as a state update that appends to the messages list.
///
/// Supports optional pre/post model hooks for state transformation and
/// response post-processing, and a `model_selector` for dynamic per-call
/// [`CallOptions`] (e.g., model override, temperature adjustment).
pub struct AgentNode<M: ChatModel> {
    model: M,
    prompt: Option<PromptSource>,
    /// Hook called before each model invocation.
    pre_model_hook: Option<PreModelHook>,
    /// Hook called after each model invocation.
    post_model_hook: Option<PostModelHook>,
    /// Dynamic model selection strategy returning per-call `CallOptions`.
    model_selector: Option<ModelSelector>,
}

impl<M: ChatModel> AgentNode<M> {
    /// Create a new agent node without a system prompt.
    #[must_use]
    pub fn new(model: M) -> Self {
        Self {
            model,
            prompt: None,
            pre_model_hook: None,
            post_model_hook: None,
            model_selector: None,
        }
    }

    /// Create a new agent node with a system prompt.
    #[must_use]
    pub fn with_prompt(model: M, prompt: PromptSource) -> Self {
        Self {
            model,
            prompt: Some(prompt),
            pre_model_hook: None,
            post_model_hook: None,
            model_selector: None,
        }
    }

    /// Create a new agent node with an optional prompt source.
    #[must_use]
    fn new_with_prompt_option(model: M, prompt: Option<PromptSource>) -> Self {
        Self {
            model,
            prompt,
            pre_model_hook: None,
            post_model_hook: None,
            model_selector: None,
        }
    }

    /// Set a pre-model hook on this agent node.
    ///
    /// The hook is called before each model invocation, receiving a reference
    /// to the current state and returning a (possibly modified) state.
    #[must_use]
    pub fn with_pre_model_hook(mut self, hook: PreModelHook) -> Self {
        self.pre_model_hook = Some(hook);
        self
    }

    /// Set a post-model hook on this agent node.
    ///
    /// The hook is called after each model invocation, receiving a reference
    /// to the current state and the model response, returning a (possibly
    /// modified) response message.
    #[must_use]
    pub fn with_post_model_hook(mut self, hook: PostModelHook) -> Self {
        self.post_model_hook = Some(hook);
        self
    }

    /// Set a model selector on this agent node.
    ///
    /// The selector receives a reference to the current state and returns
    /// [`CallOptions`] for this invocation (e.g., to switch models via
    /// `model_override`).
    #[must_use]
    pub fn with_model_selector(mut self, selector: ModelSelector) -> Self {
        self.model_selector = Some(selector);
        self
    }

    /// Build the message list to send to the LLM.
    ///
    /// If a prompt source is configured, a system message is prepended.
    fn build_messages(&self, state: &MessagesState) -> Vec<Message> {
        match &self.prompt {
            Some(PromptSource::Static(text)) => {
                let mut msgs = vec![Message::system(text)];
                msgs.extend_from_slice(&state.messages);
                msgs
            }
            Some(PromptSource::Dynamic(func)) => {
                let text = func(&state.messages);
                let mut msgs = vec![Message::system(&text)];
                msgs.extend_from_slice(&state.messages);
                msgs
            }
            None => state.messages.clone(),
        }
    }
}

impl<M: ChatModel> fmt::Debug for AgentNode<M> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("AgentNode")
            .field("model", &self.model.model_name())
            .field("prompt", &self.prompt)
            .field(
                "pre_model_hook",
                &self.pre_model_hook.as_ref().map(|_| "..."),
            )
            .field(
                "post_model_hook",
                &self.post_model_hook.as_ref().map(|_| "..."),
            )
            .field(
                "model_selector",
                &self.model_selector.as_ref().map(|_| "..."),
            )
            .finish()
    }
}

impl<M: ChatModel> Node<MessagesState> for AgentNode<M> {
    fn call(
        &self,
        state: &MessagesState,
        config: &RunnableConfig,
    ) -> std::pin::Pin<
        Box<
            dyn std::future::Future<Output = Result<Command<MessagesState>, JunctureError>>
                + Send
                + '_,
        >,
    > {
        // Clone the budget tracker Arc so it can be moved into the async block
        let budget_tracker = config.budget_tracker().cloned();

        // Apply pre_model_hook to transform state before building messages
        let state = self
            .pre_model_hook
            .as_ref()
            .map_or_else(|| state.clone(), |hook| hook(state));

        let messages = self.build_messages(&state);

        // Apply model_selector for per-call options (e.g., model override)
        let options = self.model_selector.as_ref().map(|sel| sel(&state));

        Box::pin(async move {
            // On WASM, ChatModel::invoke() returns !Send future; wrap with force_send.
            let response = juncture_core::wasm_send::force_send(
                self.model.invoke(&messages, options.as_ref()),
            )
            .await
            .map_err(|e| JunctureError::execution(e.to_string()))?;

            // Apply post_model_hook to transform the response
            let response = match &self.post_model_hook {
                Some(hook) => hook(&state, &response),
                None => response,
            };

            // Report token usage to the budget tracker, if configured
            if let Some(usage) = &response.usage
                && let Some(ref tracker) = budget_tracker
            {
                tracker.report_model_call(usage.input_tokens, usage.output_tokens);
            }

            let update = MessagesStateUpdate {
                messages: Some(vec![response]),
            };
            Ok(Command::update(update))
        })
    }

    fn name(&self) -> &'static str {
        "agent"
    }
}

impl<M: ChatModel> IntoNode<MessagesState> for AgentNode<M> {
    fn into_node(self, name: &str) -> Arc<dyn Node<MessagesState>> {
        Arc::new(NamedNodeWrapper {
            inner: self,
            name: name.to_string(),
        })
    }
}

/// Wrapper that pairs a node implementation with a name.
///
/// Used by [`IntoNode`] implementations to carry the graph-assigned
/// node name alongside the node logic.
struct NamedNodeWrapper<N> {
    inner: N,
    name: String,
}

impl<N: Node<MessagesState>> fmt::Debug for NamedNodeWrapper<N> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("NamedNodeWrapper")
            .field("name", &self.name)
            .finish_non_exhaustive()
    }
}

impl<N: Node<MessagesState>> Node<MessagesState> for NamedNodeWrapper<N> {
    fn call(
        &self,
        state: &MessagesState,
        config: &RunnableConfig,
    ) -> std::pin::Pin<
        Box<
            dyn std::future::Future<Output = Result<Command<MessagesState>, JunctureError>>
                + Send
                + '_,
        >,
    > {
        self.inner.call(state, config)
    }

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

/// Router that determines whether to proceed to tools or end.
///
/// Examines the last message in the state: if it contains tool calls,
/// routes to the "tools" node; otherwise routes to END.
struct AgentRouter;

impl Router<MessagesState> for AgentRouter {
    fn route(
        &self,
        state: &MessagesState,
    ) -> std::pin::Pin<
        Box<dyn std::future::Future<Output = Result<RouteResult, JunctureError>> + Send + '_>,
    > {
        let target = state
            .messages
            .last()
            .map_or(END, |m| if m.has_tool_calls() { "tools" } else { END });

        let result = RouteResult::One(target.to_string());
        Box::pin(async move { Ok(result) })
    }
}

/// Adapter that wraps a [`ToolNode`] to implement [`Node<MessagesState>`].
///
/// [`ToolNode`] has an `execute` method that takes `&[Message]` and returns
/// `Vec<Message>`, but does not directly implement the [`Node`] trait. This
/// adapter bridges the gap by extracting messages from the state, calling
/// `execute`, and returning the results as a state update.
///
/// The adapter also carries an optional cross-thread persistent [`Store`]
/// for stateful tool execution.
struct ToolNodeAdapter {
    tool_node: Arc<ToolNode<MessagesState>>,
    /// Optional cross-thread persistent store for long-term memory.
    store: Option<Arc<dyn Store>>,
}

impl ToolNodeAdapter {
    /// Create a new adapter wrapping the given tool node.
    #[must_use]
    fn new(tool_node: Arc<ToolNode<MessagesState>>, store: Option<Arc<dyn Store>>) -> Self {
        Self { tool_node, store }
    }
}

impl fmt::Debug for ToolNodeAdapter {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ToolNodeAdapter")
            .field("tool_node", &self.tool_node)
            .field("store", &self.store.as_ref().map(|_| "..."))
            .finish()
    }
}

impl Node<MessagesState> for ToolNodeAdapter {
    fn call(
        &self,
        state: &MessagesState,
        _config: &RunnableConfig,
    ) -> std::pin::Pin<
        Box<
            dyn std::future::Future<Output = Result<Command<MessagesState>, JunctureError>>
                + Send
                + '_,
        >,
    > {
        // Clone messages and optionally state to avoid lifetime issues in async block
        let messages = state.messages.clone();
        let tool_node = Arc::clone(&self.tool_node);

        // Clone state for stateful tools (expensive but necessary for lifetime safety)
        let state_owned = state.clone();

        Box::pin(async move {
            // Execute tools with state access for stateful tools
            let results = tool_node
                .execute_with_state(&messages, Some(&state_owned))
                .await
                .map_err(|e| JunctureError::execution(e.to_string()))?;

            let update = MessagesStateUpdate {
                messages: Some(results),
            };
            Ok(Command::update(update))
        })
    }

    fn name(&self) -> &'static str {
        "tools"
    }
}

impl IntoNode<MessagesState> for ToolNodeAdapter {
    fn into_node(self, name: &str) -> Arc<dyn Node<MessagesState>> {
        Arc::new(NamedNodeWrapper {
            inner: self,
            name: name.to_string(),
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::llm::MockChatModel;
    use crate::tools::ToolError;
    use async_trait::async_trait;
    use juncture_core::State as _;
    use juncture_core::state::messages::Content;
    use juncture_core::state::messages::ToolCall;
    use serde_json::json;

    /// Simple echo tool for testing
    struct EchoTool;

    #[async_trait]
    impl Tool for EchoTool {
        fn name(&self) -> &'static str {
            "echo"
        }

        fn description(&self) -> &'static str {
            "Echoes back the input message"
        }

        fn schema(&self) -> serde_json::Value {
            json!({
                "type": "object",
                "properties": {
                    "message": {"type": "string"}
                },
                "required": ["message"]
            })
        }

        async fn invoke(&self, input: serde_json::Value) -> Result<String, ToolError> {
            input["message"]
                .as_str()
                .map(std::string::ToString::to_string)
                .ok_or_else(|| ToolError::invalid_input("Missing 'message' field".to_string()))
        }
    }

    #[test]
    fn test_react_agent_config_default() {
        let config = ReactAgentConfig::default();
        assert!(config.system_message.is_none());
        assert!(config.max_iterations.is_none());
        assert!(!config.interrupt_before_tools);
    }

    #[test]
    fn test_prompt_source_static_debug() {
        let prompt = PromptSource::Static("You are helpful.".to_string());
        let debug = format!("{prompt:?}");
        assert!(debug.contains("Static"));
        assert!(debug.contains("You are helpful."));
    }

    #[test]
    fn test_prompt_source_dynamic_debug() {
        let prompt = PromptSource::Dynamic(Arc::new(|_msgs: &[Message]| "dynamic".to_string()));
        let debug = format!("{prompt:?}");
        assert!(debug.contains("Dynamic"));
        assert!(debug.contains("<fn>"));
    }

    #[test]
    fn test_agent_node_debug() {
        let model = MockChatModel::new("gpt-4");
        let node = AgentNode::new(model);
        let debug = format!("{node:?}");
        assert!(debug.contains("AgentNode"));
        assert!(debug.contains("gpt-4"));
    }

    #[test]
    fn test_agent_node_with_prompt_debug() {
        let model = MockChatModel::new("gpt-4");
        let prompt = PromptSource::Static("You are a calculator.".to_string());
        let node = AgentNode::with_prompt(model, prompt);
        let debug = format!("{node:?}");
        assert!(debug.contains("AgentNode"));
        assert!(debug.contains("prompt"));
    }

    #[test]
    fn test_messages_state_update_default() {
        let update = MessagesStateUpdate::default();
        assert!(update.messages.is_none());
    }

    #[test]
    fn test_messages_state_apply_append() {
        let mut state = MessagesState {
            messages: vec![Message::human("Hello")],
        };
        let update = MessagesStateUpdate {
            messages: Some(vec![Message::ai("Hi there!")]),
        };
        let changed = state.apply(update);
        assert!(!changed.is_empty());
        assert_eq!(state.messages.len(), 2);
    }

    #[test]
    fn test_messages_state_apply_no_change() {
        let mut state = MessagesState {
            messages: vec![Message::human("Hello")],
        };
        let update = MessagesStateUpdate { messages: None };
        let changed = state.apply(update);
        assert!(changed.is_empty());
        assert_eq!(state.messages.len(), 1);
    }

    #[tokio::test]
    async fn test_agent_node_call_without_prompt() {
        let model = MockChatModel::new("gpt-4").with_response("Hello back!");
        let node = AgentNode::new(model);

        let state = MessagesState {
            messages: vec![Message::human("Hello")],
        };

        let result = node.call(&state, &RunnableConfig::default()).await;

        let cmd = result.unwrap();
        assert!(cmd.update.is_some());
    }

    #[tokio::test]
    async fn test_agent_node_call_with_static_prompt() {
        let model = MockChatModel::new("gpt-4").with_response("Calculated!");
        let prompt = PromptSource::Static("You are a calculator.".to_string());
        let node = AgentNode::with_prompt(model, prompt);

        let state = MessagesState {
            messages: vec![Message::human("What is 2+2?")],
        };

        let result = node.call(&state, &RunnableConfig::default()).await;
        result.unwrap();
    }

    #[tokio::test]
    async fn test_agent_node_call_with_dynamic_prompt() {
        let model = MockChatModel::new("gpt-4").with_response("Response");
        let prompt = PromptSource::Dynamic(Arc::new(|msgs: &[Message]| {
            format!("Context: {} messages", msgs.len())
        }));
        let node = AgentNode::with_prompt(model, prompt);

        let state = MessagesState {
            messages: vec![Message::human("Hello")],
        };

        let result = node.call(&state, &RunnableConfig::default()).await;
        result.unwrap();
    }

    #[tokio::test]
    async fn test_agent_node_call_model_error() {
        let model = MockChatModel::new("gpt-4").with_error();
        let node = AgentNode::new(model);

        let state = MessagesState {
            messages: vec![Message::human("Hello")],
        };

        let result = node.call(&state, &RunnableConfig::default()).await;
        result.unwrap_err();
    }

    #[tokio::test]
    async fn test_tool_node_adapter() {
        let tool_node = Arc::new(ToolNode::new(vec![Box::new(EchoTool)]));
        let adapter = ToolNodeAdapter::new(tool_node, None);

        let state = MessagesState {
            messages: vec![Message::ai_with_tool_calls(
                "Echo this",
                vec![ToolCall {
                    id: "call_1".to_string(),
                    name: "echo".to_string(),
                    arguments: json!({"message": "hello"}),
                }],
            )],
        };

        let result = adapter.call(&state, &RunnableConfig::default()).await;
        assert!(result.is_ok());

        let cmd = result.unwrap();
        assert!(cmd.update.is_some());

        let update = cmd.update.unwrap();
        assert!(update.messages.is_some());
        let tool_messages = update.messages.unwrap();
        assert_eq!(tool_messages.len(), 1);
    }

    #[tokio::test]
    async fn test_tool_node_adapter_no_tool_calls() {
        let tool_node = Arc::new(ToolNode::new(vec![Box::new(EchoTool)]));
        let adapter = ToolNodeAdapter::new(tool_node, None);

        let state = MessagesState {
            messages: vec![Message::ai("No tools here")],
        };

        let result = adapter.call(&state, &RunnableConfig::default()).await;
        result.unwrap_err();
    }

    #[test]
    fn test_create_react_agent_basic() {
        let model = MockChatModel::new("gpt-4").with_response("Hello!");
        let tools: Vec<Box<dyn Tool>> = vec![];

        let result = create_react_agent(model, tools);
        result.unwrap();
    }

    #[test]
    fn test_create_react_agent_with_tools() {
        let model = MockChatModel::new("gpt-4").with_response("Let me search for that.");
        let tools: Vec<Box<dyn Tool>> = vec![Box::new(EchoTool)];

        let result = create_react_agent(model, tools);
        result.unwrap();
    }

    #[test]
    fn test_create_react_agent_with_config() {
        let model = MockChatModel::new("gpt-4").with_response("Done!");
        let tools: Vec<Box<dyn Tool>> = vec![];

        let config = ReactAgentConfig {
            system_message: Some("You are a helpful assistant.".to_string()),
            max_iterations: Some(10),
            interrupt_before_tools: false,
            ..Default::default()
        };

        let result = create_react_agent_with_config(model, tools, config);
        result.unwrap();
    }

    #[test]
    fn test_react_agent_config_new_fields_default() {
        let config = ReactAgentConfig::default();
        assert!(config.system_message.is_none());
        assert!(config.max_iterations.is_none());
        assert!(!config.interrupt_before_tools);
        assert!(config.pre_model_hook.is_none());
        assert!(config.post_model_hook.is_none());
        assert!(config.model_selector.is_none());
        assert!(config.store.is_none());
    }

    #[test]
    fn test_react_agent_config_debug_with_new_fields() {
        let config = ReactAgentConfig::default();
        let debug = format!("{config:?}");
        assert!(debug.contains("ReactAgentConfig"));
        assert!(debug.contains("pre_model_hook"));
        assert!(debug.contains("post_model_hook"));
        assert!(debug.contains("model_selector"));
        assert!(debug.contains("store"));
    }

    #[test]
    #[allow(
        clippy::redundant_clone,
        reason = "intentional clone to verify Clone impl preserves all fields including Arc-wrapped function types"
    )]
    fn test_react_agent_config_clone_with_all_fields() {
        use juncture_core::store::MemoryStore;

        let store = Arc::new(MemoryStore::new()) as Arc<dyn Store>;
        let config = ReactAgentConfig {
            system_message: Some("Hello".to_string()),
            max_iterations: Some(5),
            interrupt_before_tools: true,
            pre_model_hook: Some(Arc::new(|s: &MessagesState| s.clone())),
            post_model_hook: Some(Arc::new(|_s: &MessagesState, r: &Message| r.clone())),
            model_selector: Some(Arc::new(|_s: &MessagesState| CallOptions {
                model_override: Some("gpt-4-turbo".to_string()),
                ..Default::default()
            })),
            store: Some(store),
        };

        // Verify all fields are preserved after clone
        assert_eq!(config.system_message, Some("Hello".to_string()));
        assert_eq!(config.max_iterations, Some(5));
        assert!(config.interrupt_before_tools);
        assert!(config.pre_model_hook.is_some());
        assert!(config.post_model_hook.is_some());
        assert!(config.model_selector.is_some());
        assert!(config.store.is_some());

        // Verify clone produces a separate instance with same values.
        let cloned = config.clone();
        assert!(cloned.pre_model_hook.is_some());
        assert!(cloned.post_model_hook.is_some());
        assert!(cloned.model_selector.is_some());
        assert!(cloned.store.is_some());
    }

    #[tokio::test]
    async fn test_agent_node_call_with_model_selector() {
        let model = MockChatModel::new("gpt-4").with_response("Response");
        let selector: ModelSelector = Arc::new(|_state: &MessagesState| CallOptions {
            model_override: Some("gpt-4-turbo".to_string()),
            temperature: Some(0.5),
            ..Default::default()
        });
        let node = AgentNode::new(model).with_model_selector(selector);

        let state = MessagesState {
            messages: vec![Message::human("Hello")],
        };

        let result = node.call(&state, &RunnableConfig::default()).await;
        result.unwrap();
    }

    #[tokio::test]
    async fn test_agent_node_call_with_pre_model_hook() {
        let model = MockChatModel::new("gpt-4").with_response("Response");
        let hook: PreModelHook = Arc::new(|state: &MessagesState| {
            let mut new_state = state.clone();
            new_state
                .messages
                .push(Message::system("Hook added context"));
            new_state
        });
        let node = AgentNode::new(model).with_pre_model_hook(hook);

        let state = MessagesState {
            messages: vec![Message::human("Hello")],
        };

        let result = node.call(&state, &RunnableConfig::default()).await;
        result.unwrap();
    }

    #[tokio::test]
    async fn test_agent_node_call_with_post_model_hook() {
        let model = MockChatModel::new("gpt-4").with_response("Initial response");
        // Post-model hook that wraps the response with a prefix annotation.
        // Uses `Message::ai` to create a new message from the response text.
        let hook: PostModelHook = Arc::new(|_state: &MessagesState, response: &Message| {
            let text = match &response.content {
                Content::Text(t) => format!("[Post-processed] {t}"),
                Content::MultiPart(_) => "[Post-processed multi-part]".to_string(),
            };
            Message::ai(&text)
        });
        let node = AgentNode::new(model).with_post_model_hook(hook);

        let state = MessagesState {
            messages: vec![Message::human("Hello")],
        };

        let result = node.call(&state, &RunnableConfig::default()).await;
        result.unwrap();
    }

    #[test]
    fn test_tool_node_adapter_with_store() {
        use juncture_core::store::MemoryStore;

        let store = Arc::new(MemoryStore::new()) as Arc<dyn Store>;
        let tool_node = Arc::new(ToolNode::new(vec![Box::new(EchoTool)]));
        let adapter = ToolNodeAdapter::new(tool_node, Some(store));

        let debug = format!("{adapter:?}");
        assert!(debug.contains("ToolNodeAdapter"));
        assert!(debug.contains("store"));
        assert!(debug.contains("..."));
    }

    #[test]
    fn test_react_agent_config_builder_default_store_missing() {
        let config = ReactAgentConfig::default();
        // Builder methods should not exist on the config; users set fields directly.
        // Verify store defaults to None.
        assert!(config.store.is_none());
    }

    #[test]
    fn test_agent_router_with_tool_calls() {
        let state = MessagesState {
            messages: vec![Message::ai_with_tool_calls(
                "Let me look that up",
                vec![ToolCall {
                    id: "call_1".to_string(),
                    name: "search".to_string(),
                    arguments: json!({}),
                }],
            )],
        };

        let router = AgentRouter;
        let rt = tokio::runtime::Runtime::new().expect("Failed to create runtime");
        let result = rt.block_on(router.route(&state)).unwrap();

        assert_eq!(result, RouteResult::One("tools".to_string()));
    }

    #[test]
    fn test_agent_router_without_tool_calls() {
        let state = MessagesState {
            messages: vec![Message::ai("Here is the answer.")],
        };

        let router = AgentRouter;
        let rt = tokio::runtime::Runtime::new().expect("Failed to create runtime");
        let result = rt.block_on(router.route(&state)).unwrap();

        assert_eq!(result, RouteResult::One(END.to_string()));
    }

    #[test]
    fn test_agent_router_empty_messages() {
        let state = MessagesState { messages: vec![] };

        let router = AgentRouter;
        let rt = tokio::runtime::Runtime::new().expect("Failed to create runtime");
        let result = rt.block_on(router.route(&state)).unwrap();

        assert_eq!(result, RouteResult::One(END.to_string()));
    }

    #[test]
    fn test_build_messages_without_prompt() {
        let model = MockChatModel::new("gpt-4");
        let node = AgentNode::new(model);

        let state = MessagesState {
            messages: vec![Message::human("Hello")],
        };

        let msgs = node.build_messages(&state);
        assert_eq!(msgs.len(), 1);
    }

    #[test]
    fn test_build_messages_with_static_prompt() {
        let model = MockChatModel::new("gpt-4");
        let prompt = PromptSource::Static("You are helpful.".to_string());
        let node = AgentNode::with_prompt(model, prompt);

        let state = MessagesState {
            messages: vec![Message::human("Hello")],
        };

        let msgs = node.build_messages(&state);
        assert_eq!(msgs.len(), 2);
        assert_eq!(msgs[0].role, juncture_core::state::messages::Role::System);
    }

    #[test]
    fn test_build_messages_with_dynamic_prompt() {
        let model = MockChatModel::new("gpt-4");
        let prompt =
            PromptSource::Dynamic(Arc::new(|_msgs: &[Message]| "Dynamic prompt".to_string()));
        let node = AgentNode::with_prompt(model, prompt);

        let state = MessagesState {
            messages: vec![Message::human("Hello")],
        };

        let msgs = node.build_messages(&state);
        assert_eq!(msgs.len(), 2);
        assert_eq!(msgs[0].role, juncture_core::state::messages::Role::System);
    }

    #[test]
    fn test_tool_node_adapter_debug() {
        let tool_node = Arc::new(ToolNode::new(vec![Box::new(EchoTool)]));
        let adapter = ToolNodeAdapter::new(tool_node, None);
        let debug = format!("{adapter:?}");
        assert!(debug.contains("ToolNodeAdapter"));
    }

    #[test]
    fn test_convert_tool_defs() {
        let defs = vec![ToolDefinition::new(
            "search",
            "Search the web",
            json!({"type": "object"}),
        )];
        let llm_defs = convert_tool_defs(&defs);

        assert_eq!(llm_defs.len(), 1);
        assert_eq!(llm_defs[0].name, "search");
        assert_eq!(llm_defs[0].description, "Search the web");
    }
}

// Rust guideline compliant 2026-05-19