juncture 0.1.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
//! Subagent delegation system for multi-agent workflows.
//!
//! This module provides [`AgentRegistry`] and [`SubagentTool`] for building
//! multi-agent systems where an orchestrator agent can dispatch tasks to
//! specialized sub-agents. Each sub-agent is a compiled graph registered
//! with a unique name, and the orchestrator invokes them via a tool call.
//!
//! # Architecture
//!
//! ```text
//! Orchestrator Agent (LLM)
//!     |
//!     v tool call: {"subagent_type": "researcher", "task": "..."}
//! SubagentTool
//!     |
//!     v lookup in registry
//! Registered Sub-Agent Graphs
//!     - researcher: CompiledGraph
//!     - coder: CompiledGraph
//!     - analyst: CompiledGraph
//! ```
//!
//! # Example
//!
//! ```ignore
//! use juncture::prebuilt::{
//!     create_react_agent, InMemoryAgentRegistry, MessagesState,
//! };
//! use juncture::llm::MockChatModel;
//! use juncture::tools::Tool;
//!
//! // Create sub-agent graphs
//! let researcher = create_react_agent(
//!     MockChatModel::new("gpt-4").with_response("Research complete."),
//!     vec![],
//! )?;
//!
//! // Register sub-agents
//! let mut registry = InMemoryAgentRegistry::new();
//! registry.register("researcher".to_string(), researcher.into());
//!
//! // Create orchestrator with subagent tool
//! let subagent_tool = SubagentTool::new(registry);
//! let orchestrator = create_react_agent(
//!     MockChatModel::new("gpt-4").with_response("Task delegated."),
//!     vec![Box::new(subagent_tool)],
//! )?;
//! ```

use std::collections::HashMap;
use std::fmt;
use std::pin::Pin;
use std::sync::Arc;

use async_trait::async_trait;
use juncture_core::config::RunnableConfig;
use juncture_core::graph::CompiledGraph;
use juncture_core::state::messages::{Content, Message, Role};
use serde_json::json;
use tokio::sync::RwLock;

use crate::prebuilt::messages_state::MessagesState;
use crate::tools::{Tool, ToolError};

/// Boxed future for async agent invocation.
type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;

/// Type alias for the agent invocation function.
type AgentInvokeFn = dyn Fn(MessagesState, &RunnableConfig) -> BoxFuture<'static, Result<MessagesState, SubagentError>>
    + Send
    + Sync;

/// Error type for subagent operations.
///
/// Represents failures that can occur when delegating tasks to sub-agents.
#[derive(Debug, thiserror::Error)]
pub enum SubagentError {
    /// Agent not found in registry.
    ///
    /// Occurs when the orchestrator requests a sub-agent type that
    /// has not been registered.
    #[error("agent not found: {0}")]
    NotFound(String),

    /// Agent execution failed.
    ///
    /// Occurs when the sub-agent graph execution encounters an error.
    #[error("agent invocation failed: {0}")]
    InvocationFailed(String),

    /// No agents registered.
    ///
    /// Occurs when attempting to list agents from an empty registry.
    #[error("no agents registered")]
    Empty,
}

/// Trait for types that can be converted into an [`AgentEntry`].
///
/// This trait enables [`CompiledGraph`] instances to be stored in the
/// agent registry without requiring the registry to be generic over
/// the graph's internal types.
///
/// # Example
///
/// ```ignore
/// use juncture::prebuilt::{IntoAgentEntry, AgentEntry};
/// use juncture::prebuilt::MessagesState;
///
/// let graph: CompiledGraph<MessagesState> = create_react_agent(...)?;
/// let entry: AgentEntry = graph.into_agent_entry();
/// ```
pub trait IntoAgentEntry: Send + Sync + 'static {
    /// Get the agent description.
    ///
    /// Returns a human-readable description of what this agent does.
    fn description(&self) -> String;

    /// Invoke the agent with the given state and config.
    ///
    /// # Errors
    ///
    /// Returns [`SubagentError`] if the agent execution fails.
    fn invoke_boxed<'a>(
        &'a self,
        state: MessagesState,
        config: &'a RunnableConfig,
    ) -> BoxFuture<'a, Result<MessagesState, SubagentError>>;
}

/// Wrapper for a compiled graph that can be stored in an agent registry.
///
/// `AgentEntry` wraps a compiled graph with a type-erased invocation function.
/// This allows different graph types to be stored together in the same
/// registry without requiring the registry to be generic.
///
/// # Example
///
/// ```ignore
/// use juncture::prebuilt::{AgentEntry, IntoAgentEntry};
/// use std::sync::Arc;
///
/// let graph: CompiledGraph<MessagesState> = create_react_agent(...)?;
/// let entry = AgentEntry::from_graph(graph);
/// ```
pub struct AgentEntry {
    /// Human-readable description of what this agent does.
    pub description: String,

    /// Type-erased invocation function.
    ///
    /// This closure captures the compiled graph and invokes it when called.
    invoke_fn: Arc<AgentInvokeFn>,
}

impl AgentEntry {
    /// Create a new agent entry from an invocation function.
    ///
    /// # Arguments
    ///
    /// * `description` - Human-readable description of the agent.
    /// * `invoke_fn` - Async function that invokes the agent graph.
    #[must_use]
    pub fn new<F>(description: String, invoke_fn: Arc<F>) -> Self
    where
        F: Fn(
                MessagesState,
                &RunnableConfig,
            ) -> BoxFuture<'static, Result<MessagesState, SubagentError>>
            + Send
            + Sync
            + 'static,
    {
        Self {
            description,
            invoke_fn,
        }
    }

    /// Create an agent entry from a graph implementing [`IntoAgentEntry`].
    ///
    /// # Arguments
    ///
    /// * `graph` - A compiled graph or type implementing [`IntoAgentEntry`].
    ///
    /// # Example
    ///
    /// ```ignore
    /// use juncture::prebuilt::{AgentEntry, create_react_agent};
    ///
    /// let graph = create_react_agent(model, tools)?;
    /// let entry = AgentEntry::from_graph(graph);
    /// ```
    #[must_use]
    #[expect(
        clippy::type_complexity,
        reason = "Complex type is required for type-erased async function storage"
    )]
    pub fn from_graph<T: IntoAgentEntry + Clone + 'static>(graph: T) -> Self {
        let description = graph.description();

        let invoke_fn: Arc<
            dyn Fn(
                    MessagesState,
                    &RunnableConfig,
                )
                    -> Pin<Box<dyn Future<Output = Result<MessagesState, SubagentError>> + Send>>
                + Send
                + Sync,
        > = Arc::new(move |state: MessagesState, config: &RunnableConfig| {
            let graph = graph.clone();
            let config = config.clone();
            Box::pin(async move {
                graph
                    .invoke_boxed(state, &config)
                    .await
                    .map_err(|e| SubagentError::InvocationFailed(e.to_string()))
            })
        });

        Self {
            description,
            invoke_fn,
        }
    }

    /// Get the agent description.
    #[must_use]
    pub fn description(&self) -> &str {
        &self.description
    }

    /// Invoke the agent graph with the given state and configuration.
    ///
    /// # Errors
    ///
    /// Returns [`SubagentError::InvocationFailed`] if the graph execution fails.
    ///
    /// # Example
    ///
    /// ```ignore
    /// use juncture::prebuilt::{AgentEntry, MessagesState};
    /// use juncture_core::RunnableConfig;
    ///
    /// # async fn example(entry: AgentEntry) -> Result<(), Box<dyn std::error::Error>> {
    /// let state = MessagesState::default();
    /// let config = RunnableConfig::default();
    /// let result_state = entry.invoke(state, &config).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn invoke(
        &self,
        state: MessagesState,
        config: &RunnableConfig,
    ) -> Result<MessagesState, SubagentError> {
        (self.invoke_fn)(state, config).await
    }
}

impl fmt::Debug for AgentEntry {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("AgentEntry")
            .field("description", &self.description)
            .field("invoke_fn", &"<fn>")
            .finish()
    }
}

/// Trait for managing registered sub-agent graphs.
///
/// An agent registry maintains a collection of named sub-agent graphs
/// that can be dispatched to by an orchestrator agent. Implementations
/// can use in-memory storage, persistent storage, or remote registries.
///
/// # Example
///
/// ```ignore
/// use juncture::prebuilt::{AgentRegistry, InMemoryAgentRegistry, AgentEntry};
///
/// let mut registry = InMemoryAgentRegistry::new();
/// registry.register("researcher".to_string(), agent_entry);
///
/// if let Some(entry) = registry.get("researcher") {
///     let description = entry.description();
///     assert_eq!(description, "Researches topics");
/// }
///
/// let agents = registry.list();
/// assert!(agents.contains(&"researcher".to_string()));
/// ```
pub trait AgentRegistry: Send + Sync {
    /// Get an agent entry by name.
    ///
    /// Returns `None` if no agent with the given name is registered.
    ///
    /// # Arguments
    ///
    /// * `name` - The name of the agent to retrieve.
    ///
    /// # Returns
    ///
    /// `Some(AgentEntry)` if found, `None` otherwise.
    fn get(&self, name: &str) -> Option<AgentEntry>;

    /// List all registered agent names.
    ///
    /// Returns a vector of agent names in the registry. The order is
    /// implementation-dependent.
    ///
    /// # Returns
    ///
    /// A vector of registered agent names.
    ///
    /// # Errors
    ///
    /// Returns [`SubagentError::Empty`] if no agents are registered.
    fn list(&self) -> Vec<String>;

    /// Register a new agent.
    ///
    /// # Arguments
    ///
    /// * `name` - Unique name for this agent.
    /// * `entry` - The agent entry to register.
    ///
    /// # Note
    ///
    /// If an agent with the same name already exists, it should be
    /// replaced with the new entry.
    fn register(&mut self, name: String, entry: AgentEntry);
}

/// In-memory implementation of [`AgentRegistry`].
///
/// Stores agent entries in a `HashMap`. This is the default registry
/// implementation for single-process applications.
///
/// # Example
///
/// ```ignore
/// use juncture::prebuilt::{InMemoryAgentRegistry, AgentEntry};
///
/// let mut registry = InMemoryAgentRegistry::new();
/// registry.register("researcher".to_string(), agent_entry);
/// ```
#[derive(Debug, Default)]
pub struct InMemoryAgentRegistry {
    /// Map of agent name to agent entry.
    agents: HashMap<String, AgentEntry>,
}

impl InMemoryAgentRegistry {
    /// Create a new empty registry.
    ///
    /// # Example
    ///
    /// ```ignore
    /// use juncture::prebuilt::InMemoryAgentRegistry;
    ///
    /// let registry = InMemoryAgentRegistry::new();
    /// ```
    #[must_use]
    pub fn new() -> Self {
        Self {
            agents: HashMap::new(),
        }
    }
}

impl AgentRegistry for InMemoryAgentRegistry {
    fn get(&self, name: &str) -> Option<AgentEntry> {
        // Clone the Arc inside AgentEntry for thread safety
        self.agents.get(name).map(|entry| AgentEntry {
            description: entry.description.clone(),
            invoke_fn: Arc::clone(&entry.invoke_fn),
        })
    }

    fn list(&self) -> Vec<String> {
        let names: Vec<String> = self.agents.keys().cloned().collect();

        if names.is_empty() {
            // Return empty vector instead of error for list() operation
            // This is more ergonomic for callers
        }

        names
    }

    fn register(&mut self, name: String, entry: AgentEntry) {
        self.agents.insert(name, entry);
    }
}

/// Tool that delegates tasks to registered sub-agents.
///
/// When invoked by an LLM, this tool looks up the requested sub-agent
/// type in the registry, creates a fresh [`MessagesState`] with the
/// task as a human message, invokes the sub-agent graph, and returns
/// the last AI message content as the result.
///
/// The tool name is "task" following the deer-flow/deepagents convention.
///
/// # Example
///
/// ```ignore
/// use juncture::prebuilt::{InMemoryAgentRegistry, SubagentTool};
/// use juncture::tools::Tool;
///
/// let registry = InMemoryAgentRegistry::new();
/// // Register agents...
///
/// let tool = SubagentTool::new(registry);
/// let definition = tool.definition();
/// assert_eq!(definition.name, "task");
/// ```
pub struct SubagentTool {
    /// Registry of available sub-agents.
    registry: Arc<RwLock<dyn AgentRegistry>>,
}

impl SubagentTool {
    /// Create a new subagent tool.
    ///
    /// # Arguments
    ///
    /// * `registry` - The registry containing available sub-agents.
    ///
    /// # Example
    ///
    /// ```ignore
    /// use juncture::prebuilt::{InMemoryAgentRegistry, SubagentTool};
    ///
    /// let registry = InMemoryAgentRegistry::new();
    /// let tool = SubagentTool::new(registry);
    /// ```
    #[must_use]
    pub fn new<R: AgentRegistry + 'static>(registry: R) -> Self {
        Self {
            registry: Arc::new(RwLock::new(registry)),
        }
    }
}

impl fmt::Debug for SubagentTool {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("SubagentTool")
            .field("registry", &"<registry>")
            .finish()
    }
}

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

    fn description(&self) -> &'static str {
        "Delegate a task to a specialized sub-agent. Available agents are listed in the registry."
    }

    fn schema(&self) -> serde_json::Value {
        json!({
            "type": "object",
            "properties": {
                "subagent_type": {
                    "type": "string",
                    "description": "The type/name of the sub-agent to invoke"
                },
                "task": {
                    "type": "string",
                    "description": "The task description to delegate to the sub-agent"
                }
            },
            "required": ["subagent_type", "task"]
        })
    }

    async fn invoke(&self, input: serde_json::Value) -> Result<String, ToolError> {
        // Parse input
        let subagent_type = input["subagent_type"]
            .as_str()
            .ok_or_else(|| ToolError::invalid_input("Missing 'subagent_type' field".to_string()))?;

        let task = input["task"]
            .as_str()
            .ok_or_else(|| ToolError::invalid_input("Missing 'task' field".to_string()))?;

        // Get the agent from registry
        let entry = {
            let registry = self.registry.read().await;
            registry.get(subagent_type).ok_or_else(|| {
                ToolError::execution_failed(format!("Sub-agent not found: {subagent_type}"))
            })?
        };

        // Create initial state with task as human message
        let initial_state = MessagesState {
            messages: vec![Message::human(task)],
        };

        // Create config for sub-agent execution
        let config = RunnableConfig::default();

        // Invoke the sub-agent
        let result_state = entry
            .invoke(initial_state, &config)
            .await
            .map_err(|e| ToolError::execution_failed(e.to_string()))?;

        // Extract the last AI message content
        #[expect(
            clippy::map_unwrap_or,
            reason = "unwrap_or_else is needed because the default value constructs a new String"
        )]
        let result_text = result_state
            .messages
            .iter()
            .rev()
            .find(|m| matches!(m.role, Role::Ai))
            .map(|m| match &m.content {
                Content::Text(t) => t.clone(),
                Content::MultiPart(parts) => {
                    // For multi-part content, join all text parts
                    parts
                        .iter()
                        .filter_map(|p| match p {
                            juncture_core::state::messages::ContentPart::Text { text } => {
                                Some(text.as_str())
                            }
                            _ => None,
                        })
                        .collect::<Vec<_>>()
                        .join(" ")
                }
            })
            .unwrap_or_else(|| "Sub-agent completed with no output".to_string());

        Ok(result_text)
    }
}

// Implement IntoAgentEntry for CompiledGraph<MessagesState>
impl IntoAgentEntry for CompiledGraph<MessagesState> {
    fn description(&self) -> String {
        "Compiled agent graph".to_string()
    }

    fn invoke_boxed<'a>(
        &'a self,
        state: MessagesState,
        config: &'a RunnableConfig,
    ) -> BoxFuture<'a, Result<MessagesState, SubagentError>> {
        Box::pin(async move {
            let output = self
                .invoke_async(state, config)
                .await
                .map_err(|e| SubagentError::InvocationFailed(e.to_string()))?;
            Ok(output.value)
        })
    }
}

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

    /// Create a mock agent entry for testing.
    fn mock_agent_entry(response_text: &str) -> AgentEntry {
        let response = response_text.to_string();

        let invoke_fn = Arc::new(
            move |_state: MessagesState,
                  _config: &RunnableConfig|
                  -> BoxFuture<'static, Result<MessagesState, SubagentError>> {
                let response = response.clone();
                Box::pin(async move {
                    let mut state = MessagesState::default();
                    state.messages.push(Message::ai(&response));
                    Ok(state)
                })
            },
        );

        AgentEntry::new("Mock agent for testing".to_string(), invoke_fn)
    }

    #[test]
    fn test_in_memory_registry_new() {
        let registry = InMemoryAgentRegistry::new();
        assert!(registry.agents.is_empty());
    }

    #[test]
    fn test_in_memory_registry_register_and_get() {
        let mut registry = InMemoryAgentRegistry::new();
        let entry = mock_agent_entry("Test response");

        registry.register("test_agent".to_string(), entry);

        let retrieved = registry.get("test_agent");
        assert!(retrieved.is_some());
        assert_eq!(retrieved.unwrap().description, "Mock agent for testing");
    }

    #[test]
    fn test_in_memory_registry_list() {
        let mut registry = InMemoryAgentRegistry::new();
        let entry1 = mock_agent_entry("Response 1");
        let entry2 = mock_agent_entry("Response 2");

        registry.register("agent1".to_string(), entry1);
        registry.register("agent2".to_string(), entry2);

        let names = registry.list();
        assert_eq!(names.len(), 2);
        assert!(names.contains(&"agent1".to_string()));
        assert!(names.contains(&"agent2".to_string()));
    }

    #[test]
    fn test_in_memory_registry_not_found() {
        let registry = InMemoryAgentRegistry::new();
        let result = registry.get("nonexistent");
        assert!(result.is_none());
    }

    #[test]
    fn test_agent_entry_description() {
        let entry = mock_agent_entry("response");
        assert_eq!(entry.description(), "Mock agent for testing");
    }

    #[tokio::test]
    async fn test_agent_entry_invoke() {
        let entry = mock_agent_entry("Hello from agent");
        let state = MessagesState::default();
        let config = RunnableConfig::default();

        let result = entry.invoke(state, &config).await.unwrap();
        assert_eq!(result.messages.len(), 1);
        assert!(matches!(result.messages[0].role, Role::Ai));
    }

    #[test]
    fn test_subagent_tool_definition() {
        let registry = InMemoryAgentRegistry::new();
        let tool = SubagentTool::new(registry);

        let def = tool.definition();
        assert_eq!(def.name, "task");
        assert!(def.description.contains("Delegate"));

        // Verify schema structure
        assert_eq!(def.parameters["type"], "object");
        assert!(def.parameters["properties"]["subagent_type"]["type"] == "string");
        assert!(def.parameters["properties"]["task"]["type"] == "string");
    }

    #[tokio::test]
    async fn test_subagent_tool_invoke_success() {
        let mut registry = InMemoryAgentRegistry::new();
        registry.register(
            "test_agent".to_string(),
            mock_agent_entry("Agent completed task"),
        );

        let tool = SubagentTool::new(registry);
        let input = json!({
            "subagent_type": "test_agent",
            "task": "Do something"
        });

        let result = tool.invoke(input).await.unwrap();
        assert_eq!(result, "Agent completed task");
    }

    #[tokio::test]
    async fn test_subagent_tool_agent_not_found() {
        let registry = InMemoryAgentRegistry::new();
        let tool = SubagentTool::new(registry);

        let input = json!({
            "subagent_type": "nonexistent",
            "task": "Test"
        });

        let result = tool.invoke(input).await;
        let _ = result.unwrap_err();
    }

    #[tokio::test]
    async fn test_subagent_tool_missing_subagent_type() {
        let registry = InMemoryAgentRegistry::new();
        let tool = SubagentTool::new(registry);

        let input = json!({
            "task": "Test"
        });

        let result = tool.invoke(input).await;
        let _ = result.unwrap_err();
    }

    #[tokio::test]
    async fn test_subagent_tool_missing_task() {
        let registry = InMemoryAgentRegistry::new();
        let tool = SubagentTool::new(registry);

        let input = json!({
            "subagent_type": "test"
        });

        let result = tool.invoke(input).await;
        let _ = result.unwrap_err();
    }

    #[test]
    fn test_subagent_error_display() {
        let err = SubagentError::NotFound("test_agent".to_string());
        assert!(err.to_string().contains("agent not found"));
        assert!(err.to_string().contains("test_agent"));

        let err = SubagentError::InvocationFailed("execution error".to_string());
        assert!(err.to_string().contains("invocation failed"));

        let err = SubagentError::Empty;
        assert!(err.to_string().contains("no agents registered"));
    }

    #[test]
    fn test_agent_entry_from_graph_closure() {
        // Test that the closure capture works correctly
        let description = "Test agent".to_string();
        let response = "Test response".to_string();

        let invoke_fn = Arc::new(
            move |_state: MessagesState,
                  _config: &RunnableConfig|
                  -> BoxFuture<'static, Result<MessagesState, SubagentError>> {
                let response = response.clone();
                Box::pin(async move {
                    let mut state = MessagesState::default();
                    state.messages.push(Message::ai(&response));
                    Ok(state)
                })
            },
        );

        let entry = AgentEntry::new(description, invoke_fn);
        assert_eq!(entry.description(), "Test agent");
    }

    #[test]
    fn test_agent_entry_debug() {
        let entry = mock_agent_entry("response");
        let debug_str = format!("{entry:?}");
        assert!(debug_str.contains("AgentEntry"));
        assert!(debug_str.contains("description"));
        assert!(debug_str.contains("Mock agent for testing"));
    }

    #[test]
    fn test_subagent_tool_debug() {
        let registry = InMemoryAgentRegistry::new();
        let tool = SubagentTool::new(registry);
        let debug_str = format!("{tool:?}");
        assert!(debug_str.contains("SubagentTool"));
    }

    #[tokio::test]
    async fn test_subagent_tool_result_extraction_multi_part() {
        let mut registry = InMemoryAgentRegistry::new();

        // Create an agent that returns multi-part content
        let invoke_fn = Arc::new(
            |_state: MessagesState,
             _config: &RunnableConfig|
             -> BoxFuture<'static, Result<MessagesState, SubagentError>> {
                Box::pin(async move {
                    use juncture_core::state::messages::ContentPart;
                    let mut state = MessagesState::default();
                    state.messages.push(Message {
                        id: uuid::Uuid::new_v4().to_string(),
                        role: Role::Ai,
                        content: Content::MultiPart(vec![
                            ContentPart::Text {
                                text: "Part 1".to_string(),
                            },
                            ContentPart::Text {
                                text: "Part 2".to_string(),
                            },
                        ]),
                        tool_calls: vec![],
                        tool_call_id: None,
                        name: None,
                        usage: None,
                    });
                    Ok(state)
                })
            },
        );
        let entry = AgentEntry::new("Multi-part agent".to_string(), invoke_fn);
        registry.register("multi_agent".to_string(), entry);

        let tool = SubagentTool::new(registry);
        let input = json!({
            "subagent_type": "multi_agent",
            "task": "Test"
        });

        let result = tool.invoke(input).await.unwrap();
        assert!(result.contains("Part 1"));
        assert!(result.contains("Part 2"));
    }

    #[tokio::test]
    async fn test_subagent_tool_result_extraction_no_ai_message() {
        let mut registry = InMemoryAgentRegistry::new();

        // Create an agent that returns no AI messages
        let invoke_fn = Arc::new(
            |_state: MessagesState,
             _config: &RunnableConfig|
             -> BoxFuture<'static, Result<MessagesState, SubagentError>> {
                Box::pin(async move { Ok(MessagesState::default()) })
            },
        );
        let entry = AgentEntry::new("Empty agent".to_string(), invoke_fn);
        registry.register("empty_agent".to_string(), entry);

        let tool = SubagentTool::new(registry);
        let input = json!({
            "subagent_type": "empty_agent",
            "task": "Test"
        });

        let result = tool.invoke(input).await.unwrap();
        assert_eq!(result, "Sub-agent completed with no output");
    }
}

// Rust guideline compliant 2026-05-26