Skip to main content

gemini_adk_rs/text/
mod.rs

1//! Text-based agent execution — request/response LLM pipelines.
2//!
3//! While `Agent::run_live()` operates over a Gemini Live WebSocket session,
4//! `TextAgent::run()` makes standard `BaseLlm::generate()` calls. This enables
5//! dispatching text-based agent pipelines from Live session event hooks.
6//!
7//! # Agent types
8//!
9//! | Type | Purpose |
10//! |------|---------|
11//! | `LlmTextAgent` | Core agent — generate → tool dispatch → loop |
12//! | `FnTextAgent` | Zero-cost state transform (no LLM call) |
13//! | `SequentialTextAgent` | Run children in order, state flows forward |
14//! | `ParallelTextAgent` | Run children concurrently via `tokio::spawn` |
15//! | `LoopTextAgent` | Repeat until max iterations or predicate |
16//! | `FallbackTextAgent` | Try each child, first success wins |
17//! | `RouteTextAgent` | State-driven deterministic branching |
18//! | `RaceTextAgent` | Run concurrently, first to finish wins |
19//! | `TimeoutTextAgent` | Wrap an agent with a time limit |
20//! | `MapOverTextAgent` | Iterate an agent over a list in state |
21//! | `TapTextAgent` | Read-only observation (no mutation) |
22//! | `DispatchTextAgent` | Fire-and-forget background tasks |
23//! | `JoinTextAgent` | Wait for dispatched tasks |
24
25use async_trait::async_trait;
26
27use crate::error::AgentError;
28use crate::state::State;
29
30mod run;
31pub use run::{Chat, RunEvent, RunRequest, RunResult, ToolCallRecord};
32
33mod dispatch;
34mod fallback;
35mod fn_agent;
36mod llm;
37mod loop_agent;
38mod map_over;
39mod parallel;
40mod race;
41mod route;
42mod sequential;
43mod tap;
44mod timeout;
45
46pub use dispatch::{DispatchTextAgent, JoinTextAgent, TaskRegistry};
47pub use fallback::FallbackTextAgent;
48pub use fn_agent::FnTextAgent;
49pub use llm::LlmTextAgent;
50pub use loop_agent::LoopTextAgent;
51pub use map_over::MapOverTextAgent;
52pub use parallel::ParallelTextAgent;
53pub use race::RaceTextAgent;
54pub use route::{RouteRule, RouteTextAgent};
55pub use sequential::SequentialTextAgent;
56pub use tap::TapTextAgent;
57pub use timeout::TimeoutTextAgent;
58
59// ── TextAgent trait ────────────────────────────────────────────────────────
60
61/// A text-based agent that runs via `BaseLlm::generate()` (request/response).
62///
63/// Unlike `Agent` (which requires a Live WebSocket session), `TextAgent` can be
64/// dispatched from anywhere — event hooks, background tasks, CLI tools.
65///
66/// Ask a question, get a typed answer, or hold a conversation:
67///
68/// ```
69/// use gemini_adk_rs::llm::{LlmResponse, MockLlm};
70/// use gemini_adk_rs::text::{LlmTextAgent, TextAgent};
71///
72/// #[derive(serde::Deserialize, schemars::JsonSchema)]
73/// struct City {
74///     name: String,
75///     country: String,
76/// }
77///
78/// # tokio_test::block_on(async {
79/// let llm = MockLlm::script([
80///     LlmResponse::from_text("Paris."),
81///     LlmResponse::from_text(r#"{"name":"Paris","country":"France"}"#),
82/// ]);
83/// let agent = LlmTextAgent::new("geo", llm);
84///
85/// assert_eq!(agent.ask("Capital of France?").await.unwrap(), "Paris.");
86///
87/// let city: City = agent.ask_as("Describe the capital of France.").await.unwrap();
88/// assert_eq!(city.country, "France");
89/// # });
90/// ```
91///
92/// [`run_with`](Self::run_with) is the primitive the others are built on;
93/// [`run`](Self::run) is the state-in, state-out form combinators use, reading
94/// the prompt from the `"input"` state key.
95#[async_trait]
96pub trait TextAgent: Send + Sync {
97    /// Human-readable name for logging and debugging.
98    fn name(&self) -> &str;
99
100    /// Execute this agent. Reads/writes `state`. Returns the final text output.
101    ///
102    /// The prompt is read from the `"input"` state key; prefer
103    /// [`run_with`](Self::run_with) or [`ask`](Self::ask), which take it
104    /// directly.
105    async fn run(&self, state: &State) -> Result<String, AgentError>;
106
107    /// Run one request and report everything it produced: the reply, the
108    /// turns to append to a conversation, token usage and tool calls.
109    ///
110    /// The default writes the request's text to the `"input"` state key and
111    /// calls [`run`](Self::run), so every agent supports it; history and a
112    /// response schema are honoured by agents that call a model
113    /// ([`LlmTextAgent`]).
114    async fn run_with(&self, request: RunRequest, state: &State) -> Result<RunResult, AgentError> {
115        state.set("input", request.input_text())?;
116        let text = self.run(state).await?;
117        Ok(RunResult {
118            messages: vec![request.input, run::model_turn(text.clone())],
119            ..RunResult::from_text(text)
120        })
121    }
122
123    /// Run one request as a stream of [`RunEvent`]s: text as the model writes
124    /// it, each tool call and result, then [`RunEvent::Finished`].
125    ///
126    /// The default emits the reply of [`run_with`](Self::run_with) as a single
127    /// delta. [`LlmTextAgent`] streams from the model; when it has middleware
128    /// (which may rewrite a reply, e.g. to redact it), each model turn is
129    /// emitted only after the middleware has seen it.
130    fn run_stream<'a>(
131        &'a self,
132        request: RunRequest,
133        state: State,
134    ) -> futures_util::stream::BoxStream<'a, Result<RunEvent, AgentError>> {
135        use futures_util::StreamExt;
136
137        futures_util::stream::once(async move { self.run_with(request, &state).await })
138            .flat_map(|outcome| {
139                let events = match outcome {
140                    Ok(result) if result.text.is_empty() => vec![Ok(RunEvent::Finished(result))],
141                    Ok(result) => vec![
142                        Ok(RunEvent::TextDelta(result.text.clone())),
143                        Ok(RunEvent::Finished(result)),
144                    ],
145                    Err(e) => vec![Err(e)],
146                };
147                futures_util::stream::iter(events)
148            })
149            .boxed()
150    }
151
152    /// Stream the reply to one question, with no history and fresh state.
153    ///
154    /// ```
155    /// use futures_util::StreamExt;
156    /// use gemini_adk_rs::llm::MockLlm;
157    /// use gemini_adk_rs::text::{LlmTextAgent, RunEvent, TextAgent};
158    ///
159    /// # tokio_test::block_on(async {
160    /// let agent = LlmTextAgent::new("storyteller", MockLlm::text("Once upon a time"));
161    /// let mut events = agent.stream("Tell me a story.");
162    /// let mut story = String::new();
163    /// while let Some(event) = events.next().await {
164    ///     if let RunEvent::TextDelta(text) = event.unwrap() {
165    ///         story.push_str(&text);
166    ///     }
167    /// }
168    /// assert_eq!(story, "Once upon a time");
169    /// # });
170    /// ```
171    fn stream(
172        &self,
173        prompt: impl Into<String>,
174    ) -> futures_util::stream::BoxStream<'_, Result<RunEvent, AgentError>>
175    where
176        Self: Sized,
177    {
178        self.run_stream(RunRequest::new(prompt), State::new())
179    }
180
181    /// Ask one question, with no history and fresh state, and get the reply.
182    async fn ask(&self, prompt: impl Into<String> + Send) -> Result<String, AgentError>
183    where
184        Self: Sized,
185    {
186        Ok(self
187            .run_with(RunRequest::new(prompt), &State::new())
188            .await?
189            .text)
190    }
191
192    /// Ask one question and get the reply as a `T`.
193    ///
194    /// `T`'s JSON Schema is sent as the response schema. If the reply still
195    /// does not parse, the model is shown the error and asked once more;
196    /// a second failure is [`AgentError::InvalidOutput`].
197    async fn ask_as<T>(&self, prompt: impl Into<String> + Send) -> Result<T, AgentError>
198    where
199        Self: Sized,
200        T: serde::de::DeserializeOwned + schemars::JsonSchema + Send,
201    {
202        let schema = crate::tool::wire_schema::<T>();
203        let state = State::new();
204        let first = self
205            .run_with(
206                RunRequest::new(prompt).response_schema(schema.clone()),
207                &state,
208            )
209            .await?;
210        let reason = match first.parse::<T>() {
211            Err(AgentError::InvalidOutput { reason, .. }) => reason,
212            parsed => return parsed,
213        };
214        let repair = RunRequest::new(format!(
215            "That reply could not be read as the requested JSON ({reason}). \
216             Reply again with only JSON that matches the schema."
217        ))
218        .history(first.messages)
219        .response_schema(schema);
220        self.run_with(repair, &state).await?.parse::<T>()
221    }
222
223    /// Start a conversation that remembers its turns. See [`Chat`].
224    fn chat(&self) -> Chat<&Self>
225    where
226        Self: Sized,
227    {
228        Chat::new(self)
229    }
230}
231
232// Verify object safety at compile time.
233const _: () = {
234    fn _assert_object_safe(_: &dyn TextAgent) {}
235};
236
237/// Forward every required method, so a wrapper behaves exactly like the agent
238/// it holds (including an overridden `run_with`).
239macro_rules! forward_text_agent {
240    ($($wrapper:ty),*) => {$(
241        #[async_trait]
242        impl<A: TextAgent + ?Sized> TextAgent for $wrapper {
243            fn name(&self) -> &str {
244                (**self).name()
245            }
246
247            async fn run(&self, state: &State) -> Result<String, AgentError> {
248                (**self).run(state).await
249            }
250
251            async fn run_with(
252                &self,
253                request: RunRequest,
254                state: &State,
255            ) -> Result<RunResult, AgentError> {
256                (**self).run_with(request, state).await
257            }
258
259            fn run_stream<'a>(
260                &'a self,
261                request: RunRequest,
262                state: State,
263            ) -> futures_util::stream::BoxStream<'a, Result<RunEvent, AgentError>> {
264                (**self).run_stream(request, state)
265            }
266        }
267    )*};
268}
269
270// A shared agent is an agent, so a built `Arc<dyn TextAgent>` can be passed
271// straight back into any combinator or `agent_tool` without a cast; a borrow
272// is one too, which is what `chat()` holds.
273forward_text_agent!(std::sync::Arc<A>, Box<A>, &A);
274
275// ── Tests ─────────────────────────────────────────────────────────────────
276
277#[cfg(test)]
278mod tests {
279    use super::*;
280    use crate::llm::{BaseLlm, LlmError, LlmResponse, MockLlm};
281    use gemini_genai_rs::prelude::Part;
282    use std::sync::Arc;
283    use std::time::Duration;
284
285    /// A model that echoes every text part it was sent, after `prefix`.
286    fn echo(prefix: &'static str) -> MockLlm {
287        MockLlm::from_fn(move |req| {
288            let input: Vec<&str> = req
289                .contents
290                .iter()
291                .flat_map(|c| &c.parts)
292                .filter_map(|p| match p {
293                    Part::Text { text } => Some(text.as_str()),
294                    _ => None,
295                })
296                .collect();
297            Ok(LlmResponse::from_text(format!(
298                "{prefix}{}",
299                input.join(" ")
300            )))
301        })
302    }
303
304    /// A model whose every call fails.
305    fn failing() -> MockLlm {
306        MockLlm::from_fn(|_| Err(LlmError::RequestFailed("intentional failure".into())))
307    }
308
309    // ── TextAgent trait ──
310
311    #[test]
312    fn text_agent_is_object_safe() {
313        fn _assert(_: &dyn TextAgent) {}
314    }
315
316    /// A built agent is handed around as `Arc<dyn TextAgent>`; it must satisfy
317    /// a generic `impl TextAgent` bound without a cast or a second API.
318    #[tokio::test]
319    async fn shared_and_boxed_agents_are_agents() {
320        async fn run_it(agent: impl TextAgent) -> String {
321            agent.run(&State::new()).await.unwrap()
322        }
323        let built: Arc<dyn TextAgent> = Arc::new(LlmTextAgent::new("a", MockLlm::text("from arc")));
324        assert_eq!(built.name(), "a");
325        assert_eq!(run_it(built).await, "from arc");
326        let boxed: Box<dyn TextAgent> = Box::new(FnTextAgent::new("b", |_| Ok("from box".into())));
327        assert_eq!(run_it(boxed).await, "from box");
328    }
329
330    // ── run_with, ask, ask_as, chat ──
331
332    #[tokio::test]
333    async fn run_with_reports_messages_usage_and_tool_calls() {
334        let llm = MockLlm::script([
335            LlmResponse::tool_call("get_weather", serde_json::json!({"city": "Oslo"}))
336                .with_usage(10, 2),
337            LlmResponse::from_text("Cold.").with_usage(20, 1),
338        ]);
339        let mut dispatcher = crate::tool::ToolDispatcher::new();
340        dispatcher.register_function(Arc::new(crate::tool::SimpleTool::new(
341            "get_weather",
342            "Get weather",
343            None,
344            |_| async { Ok(serde_json::json!({"temp": -3})) },
345        )));
346        let agent = LlmTextAgent::new("weather", llm).tools(Arc::new(dispatcher));
347
348        let result = agent
349            .run_with(RunRequest::new("Weather in Oslo?"), &State::new())
350            .await
351            .unwrap();
352        assert_eq!(result.text, "Cold.");
353        assert_eq!(result.model_calls, 2);
354        assert_eq!(result.usage, crate::llm::TokenUsage::new(30, 3));
355        assert_eq!(result.tool_calls.len(), 1);
356        assert_eq!(result.tool_calls[0].name, "get_weather");
357        assert_eq!(result.tool_calls[0].outcome.as_ref().unwrap()["temp"], -3);
358        // user, model(call), user(tool response), model(text)
359        assert_eq!(result.messages.len(), 4);
360    }
361
362    #[tokio::test]
363    async fn ask_as_repairs_once_then_gives_up() {
364        #[derive(serde::Deserialize, schemars::JsonSchema, Debug)]
365        #[allow(
366            dead_code,
367            reason = "the field is only deserialized and schema-derived in this test"
368        )]
369        struct Answer {
370            value: u32,
371        }
372
373        let fixed = MockLlm::script([
374            LlmResponse::from_text("forty-two"),
375            LlmResponse::from_text(r#"{"value": 42}"#),
376        ]);
377        let agent = LlmTextAgent::new("a", fixed.clone());
378        let answer: Answer = agent.ask_as("What is 6 x 7?").await.unwrap();
379        assert_eq!(answer.value, 42);
380        let repair = fixed.last_request().unwrap();
381        assert_eq!(
382            repair.contents.len(),
383            3,
384            "the bad reply is shown to the model"
385        );
386        assert!(repair.response_json_schema.is_some());
387
388        let stubborn = MockLlm::text("no");
389        let agent = LlmTextAgent::new("b", stubborn.clone());
390        let err = agent.ask_as::<Answer>("?").await.unwrap_err();
391        assert!(matches!(err, AgentError::InvalidOutput { .. }), "{err}");
392        assert_eq!(stubborn.call_count(), 2, "one repair, not a loop");
393    }
394
395    #[tokio::test]
396    async fn any_agent_can_ask_and_chat() {
397        let upper = FnTextAgent::new("upper", |state| {
398            Ok(state
399                .get::<String>("input")
400                .unwrap_or_default()
401                .to_uppercase())
402        });
403        assert_eq!(upper.ask("hi").await.unwrap(), "HI");
404        let shared: Arc<dyn TextAgent> = Arc::new(upper);
405        let mut chat = shared.chat();
406        assert_eq!(chat.send("one").await.unwrap(), "ONE");
407        assert_eq!(chat.send("two").await.unwrap(), "TWO");
408        assert_eq!(chat.history().len(), 4);
409    }
410
411    #[tokio::test]
412    async fn a_failed_turn_is_not_added_to_the_history() {
413        let llm = MockLlm::script([LlmResponse::from_text("first")]).then_fail(LlmError::Api {
414            status: 503,
415            message: "overloaded".into(),
416        });
417        let agent = LlmTextAgent::new("a", llm);
418        let mut chat = Chat::new(&agent);
419        chat.send("1").await.unwrap();
420        let err = chat.send("2").await.unwrap_err();
421        assert!(err.as_llm().is_some_and(LlmError::is_retryable), "{err}");
422        assert_eq!(chat.history().len(), 2);
423    }
424
425    /// A model that calls a tool on an agent with no tools is told so, instead
426    /// of receiving an empty turn and calling again until the round limit.
427    #[tokio::test]
428    async fn a_tool_call_without_tools_is_answered_not_found() {
429        let llm = MockLlm::script([
430            LlmResponse::tool_call("imaginary", serde_json::json!({})),
431            LlmResponse::from_text("Sorry, I cannot do that."),
432        ]);
433        let agent = LlmTextAgent::new("toolless", llm.clone());
434        let result = agent
435            .run_with(RunRequest::new("Use your tool."), &State::new())
436            .await
437            .unwrap();
438        assert_eq!(result.text, "Sorry, I cannot do that.");
439        assert!(matches!(
440            result.tool_calls[0].outcome,
441            Err(crate::error::ToolError::NotFound(_))
442        ));
443    }
444
445    // ── Streaming ──
446
447    async fn collect(
448        mut events: futures_util::stream::BoxStream<'_, Result<RunEvent, AgentError>>,
449    ) -> Vec<RunEvent> {
450        use futures_util::StreamExt;
451        let mut out = Vec::new();
452        while let Some(event) = events.next().await {
453            out.push(event.unwrap());
454        }
455        out
456    }
457
458    fn deltas(events: &[RunEvent]) -> String {
459        events
460            .iter()
461            .filter_map(|e| match e {
462                RunEvent::TextDelta(t) => Some(t.as_str()),
463                _ => None,
464            })
465            .collect()
466    }
467
468    /// Text arrives as the model writes it, tool calls and results in between,
469    /// and `Finished` carries the same result `run_with` would return.
470    #[tokio::test]
471    async fn stream_reports_text_tools_and_the_result_in_order() {
472        let llm = MockLlm::script([
473            LlmResponse::tool_call("get_weather", serde_json::json!({"city": "Oslo"})),
474            LlmResponse::from_text("It is cold today").with_usage(9, 4),
475        ]);
476        let mut dispatcher = crate::tool::ToolDispatcher::new();
477        dispatcher.register_function(Arc::new(crate::tool::SimpleTool::new(
478            "get_weather",
479            "Get weather",
480            None,
481            |_| async { Ok(serde_json::json!({"temp": -3})) },
482        )));
483        let agent = LlmTextAgent::new("weather", llm).tools(Arc::new(dispatcher));
484
485        let events = collect(agent.stream("Weather in Oslo?")).await;
486        assert!(matches!(&events[0], RunEvent::ToolCall { name, .. } if name == "get_weather"));
487        assert!(matches!(&events[1], RunEvent::ToolResult(r) if r.outcome.is_ok()));
488        let text_deltas = events
489            .iter()
490            .filter(|e| matches!(e, RunEvent::TextDelta(_)))
491            .count();
492        assert_eq!(text_deltas, 4, "one per word from the mock: {events:?}");
493        assert_eq!(deltas(&events), "It is cold today");
494        match events.last() {
495            Some(RunEvent::Finished(result)) => {
496                assert_eq!(result.text, "It is cold today");
497                assert_eq!(result.usage, crate::llm::TokenUsage::new(9, 4));
498                assert_eq!(result.tool_calls.len(), 1);
499            }
500            other => panic!("the last event must be Finished, got {other:?}"),
501        }
502    }
503
504    /// A middleware that rewrites replies must see a turn before any of it is
505    /// streamed, or a redaction could be bypassed through the deltas.
506    #[tokio::test]
507    async fn middleware_sees_a_reply_before_it_is_streamed() {
508        struct Redact;
509        #[async_trait]
510        impl crate::middleware::Middleware for Redact {
511            fn name(&self) -> &str {
512                "redact"
513            }
514            async fn after_model(
515                &self,
516                _request: &crate::llm::LlmRequest,
517                _response: &LlmResponse,
518            ) -> Result<Option<LlmResponse>, AgentError> {
519                Ok(Some(LlmResponse::from_text("[redacted]")))
520            }
521        }
522        let agent = LlmTextAgent::new("guarded", MockLlm::text("the secret is 42"))
523            .add_middleware(Arc::new(Redact));
524        let events = collect(agent.stream("?")).await;
525        assert_eq!(deltas(&events), "[redacted]", "{events:?}");
526    }
527
528    #[tokio::test]
529    async fn any_agent_streams_and_chat_streams_into_its_history() {
530        let echo = FnTextAgent::new("echo", |state| {
531            Ok(state.get::<String>("input").unwrap_or_default())
532        });
533        let events = collect(echo.stream("hi")).await;
534        assert_eq!(deltas(&events), "hi");
535
536        let agent = LlmTextAgent::new("a", MockLlm::text("hello there"));
537        let mut chat = agent.chat();
538        let events = collect(chat.send_stream("hi")).await;
539        assert_eq!(deltas(&events), "hello there");
540        assert_eq!(chat.history().len(), 2);
541    }
542
543    #[tokio::test]
544    async fn a_failed_stream_ends_with_the_error() {
545        use futures_util::StreamExt;
546        let agent = LlmTextAgent::new("a", failing());
547        let mut events = agent.stream("?");
548        let last = events.next().await.expect("one event");
549        assert!(matches!(last, Err(AgentError::Llm(_))), "{last:?}");
550        assert!(events.next().await.is_none());
551    }
552
553    // ── LlmTextAgent ──
554
555    #[tokio::test]
556    async fn llm_text_agent_returns_text() {
557        let llm = Arc::new(MockLlm::text("Hello world"));
558        let agent = LlmTextAgent::new("greeter", llm).instruction("Say hello");
559        let state = State::new();
560        let result = agent.run(&state).await.unwrap();
561        assert_eq!(result, "Hello world");
562        assert_eq!(state.get::<String>("output"), Some("Hello world".into()));
563    }
564
565    #[tokio::test]
566    async fn llm_text_agent_reads_input_from_state() {
567        let llm = Arc::new(echo("Echo: "));
568        let agent = LlmTextAgent::new("echoer", llm);
569        let state = State::new();
570        let _ = state.set("input", "test message");
571        let result = agent.run(&state).await.unwrap();
572        assert!(result.contains("test message"));
573    }
574
575    #[tokio::test]
576    async fn llm_text_agent_dispatches_tools() {
577        let llm = MockLlm::script([
578            LlmResponse::tool_call("get_weather", serde_json::json!({"city": "London"})),
579            LlmResponse::from_text("The weather is sunny"),
580        ]);
581
582        let mut dispatcher = crate::tool::ToolDispatcher::new();
583        dispatcher.register_function(Arc::new(crate::tool::SimpleTool::new(
584            "get_weather",
585            "Get weather",
586            None,
587            |_args| async { Ok(serde_json::json!({"temp": 22})) },
588        )));
589
590        let agent = LlmTextAgent::new("weather", llm.clone()).tools(Arc::new(dispatcher));
591        let state = State::new();
592        let result = agent.run(&state).await.unwrap();
593        assert_eq!(result, "The weather is sunny");
594
595        // The second model call carries the tool's result back.
596        let followup = llm.last_request().expect("two model calls");
597        let returned = followup
598            .contents
599            .iter()
600            .flat_map(|c| &c.parts)
601            .find_map(|p| match p {
602                Part::FunctionResponse { function_response } => Some(function_response),
603                _ => None,
604            })
605            .expect("the tool result is sent back to the model");
606        assert_eq!(returned.name, "get_weather");
607        assert_eq!(returned.response["temp"], 22);
608    }
609
610    #[tokio::test]
611    async fn llm_text_agent_propagates_llm_error() {
612        let llm = Arc::new(failing());
613        let agent = LlmTextAgent::new("failer", llm);
614        let state = State::new();
615        let result = agent.run(&state).await;
616        assert!(result.is_err());
617    }
618
619    // ── FnTextAgent ──
620
621    #[tokio::test]
622    async fn fn_agent_transforms_state() {
623        let agent = FnTextAgent::new("upper", |state: &State| {
624            let input = state.get::<String>("input").unwrap_or_default();
625            let upper = input.to_uppercase();
626            let _ = state.set("output", &upper);
627            Ok(upper)
628        });
629
630        let state = State::new();
631        let _ = state.set("input", "hello");
632        let result = agent.run(&state).await.unwrap();
633        assert_eq!(result, "HELLO");
634        assert_eq!(state.get::<String>("output"), Some("HELLO".into()));
635    }
636
637    #[tokio::test]
638    async fn fn_agent_can_fail() {
639        let agent = FnTextAgent::new("failer", |_state: &State| {
640            Err(AgentError::Other("nope".into()))
641        });
642        let state = State::new();
643        assert!(agent.run(&state).await.is_err());
644    }
645
646    // ── SequentialTextAgent ──
647
648    #[tokio::test]
649    async fn sequential_chains_agents() {
650        let llm1: Arc<dyn BaseLlm> = Arc::new(MockLlm::text("step1 done"));
651        let llm2: Arc<dyn BaseLlm> = Arc::new(echo("step2: "));
652
653        let children: Vec<Arc<dyn TextAgent>> = vec![
654            Arc::new(LlmTextAgent::new("step1", llm1)),
655            Arc::new(LlmTextAgent::new("step2", llm2)),
656        ];
657
658        let pipeline = SequentialTextAgent::new("pipeline", children);
659        let state = State::new();
660        let result = pipeline.run(&state).await.unwrap();
661        // step2 should receive step1's output as input
662        assert!(result.contains("step2:"));
663        assert!(result.contains("step1 done"));
664    }
665
666    #[tokio::test]
667    async fn sequential_stops_on_error() {
668        let children: Vec<Arc<dyn TextAgent>> = vec![
669            Arc::new(LlmTextAgent::new("ok", Arc::new(MockLlm::text("fine")))),
670            Arc::new(LlmTextAgent::new("fail", Arc::new(failing()))),
671            Arc::new(LlmTextAgent::new(
672                "never",
673                Arc::new(MockLlm::text("unreachable")),
674            )),
675        ];
676
677        let pipeline = SequentialTextAgent::new("pipeline", children);
678        let state = State::new();
679        assert!(pipeline.run(&state).await.is_err());
680    }
681
682    #[tokio::test]
683    async fn sequential_empty_returns_empty() {
684        let pipeline = SequentialTextAgent::new("empty", vec![]);
685        let state = State::new();
686        let result = pipeline.run(&state).await.unwrap();
687        assert_eq!(result, "");
688    }
689
690    // ── ParallelTextAgent ──
691
692    #[tokio::test]
693    async fn parallel_runs_concurrently() {
694        let branches: Vec<Arc<dyn TextAgent>> = vec![
695            Arc::new(FnTextAgent::new("a", |state: &State| {
696                let _ = state.set("key_a", "val_a");
697                Ok("result_a".into())
698            })),
699            Arc::new(FnTextAgent::new("b", |state: &State| {
700                let _ = state.set("key_b", "val_b");
701                Ok("result_b".into())
702            })),
703        ];
704
705        let par = ParallelTextAgent::new("parallel", branches);
706        let state = State::new();
707        let result = par.run(&state).await.unwrap();
708        assert!(result.contains("result_a"));
709        assert!(result.contains("result_b"));
710        assert_eq!(state.get::<String>("key_a"), Some("val_a".into()));
711        assert_eq!(state.get::<String>("key_b"), Some("val_b".into()));
712    }
713
714    #[tokio::test]
715    async fn parallel_fails_if_any_fails() {
716        let branches: Vec<Arc<dyn TextAgent>> = vec![
717            Arc::new(FnTextAgent::new("ok", |_| Ok("fine".into()))),
718            Arc::new(FnTextAgent::new("fail", |_| {
719                Err(AgentError::Other("boom".into()))
720            })),
721        ];
722
723        let par = ParallelTextAgent::new("parallel", branches);
724        let state = State::new();
725        assert!(par.run(&state).await.is_err());
726    }
727
728    // ── LoopTextAgent ──
729
730    #[tokio::test]
731    async fn loop_runs_max_iterations() {
732        let counter = Arc::new(std::sync::atomic::AtomicU32::new(0));
733        let counter_clone = counter.clone();
734
735        let body = Arc::new(FnTextAgent::new("counter", move |_state: &State| {
736            counter_clone.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
737            Ok("tick".into())
738        }));
739
740        let loop_agent = LoopTextAgent::new("loop", body, 5);
741        let state = State::new();
742        loop_agent.run(&state).await.unwrap();
743        assert_eq!(counter.load(std::sync::atomic::Ordering::SeqCst), 5);
744    }
745
746    #[tokio::test]
747    async fn loop_breaks_on_predicate() {
748        let body = Arc::new(FnTextAgent::new("incrementer", |state: &State| {
749            let n = state.get::<i32>("n").unwrap_or(0);
750            let _ = state.set("n", n + 1);
751            Ok(format!("n={}", n + 1))
752        }));
753
754        let loop_agent = LoopTextAgent::new("loop", body, 100)
755            .until(|state: &State| state.get::<i32>("n").unwrap_or(0) >= 3);
756
757        let state = State::new();
758        loop_agent.run(&state).await.unwrap();
759        assert_eq!(state.get::<i32>("n"), Some(3));
760    }
761
762    // ── FallbackTextAgent ──
763
764    #[tokio::test]
765    async fn fallback_returns_first_success() {
766        let candidates: Vec<Arc<dyn TextAgent>> = vec![
767            Arc::new(FnTextAgent::new("fail1", |_| {
768                Err(AgentError::Other("fail1".into()))
769            })),
770            Arc::new(FnTextAgent::new("ok", |_| Ok("success".into()))),
771            Arc::new(FnTextAgent::new("never", |_| Ok("unreachable".into()))),
772        ];
773
774        let fallback = FallbackTextAgent::new("fallback", candidates);
775        let state = State::new();
776        let result = fallback.run(&state).await.unwrap();
777        assert_eq!(result, "success");
778    }
779
780    #[tokio::test]
781    async fn fallback_returns_last_error() {
782        let candidates: Vec<Arc<dyn TextAgent>> = vec![
783            Arc::new(FnTextAgent::new("fail1", |_| {
784                Err(AgentError::Other("fail1".into()))
785            })),
786            Arc::new(FnTextAgent::new("fail2", |_| {
787                Err(AgentError::Other("fail2".into()))
788            })),
789        ];
790
791        let fallback = FallbackTextAgent::new("fallback", candidates);
792        let state = State::new();
793        let err = fallback.run(&state).await.unwrap_err();
794        assert!(err.to_string().contains("fail2"));
795    }
796
797    #[tokio::test]
798    async fn fallback_empty_returns_error() {
799        let fallback = FallbackTextAgent::new("fallback", vec![]);
800        let state = State::new();
801        assert!(fallback.run(&state).await.is_err());
802    }
803
804    // ── RouteTextAgent ──
805
806    #[tokio::test]
807    async fn route_dispatches_matching_rule() {
808        let agent_a: Arc<dyn TextAgent> = Arc::new(FnTextAgent::new("a", |_| Ok("route_a".into())));
809        let agent_b: Arc<dyn TextAgent> = Arc::new(FnTextAgent::new("b", |_| Ok("route_b".into())));
810        let default: Arc<dyn TextAgent> =
811            Arc::new(FnTextAgent::new("default", |_| Ok("default".into())));
812
813        let router = RouteTextAgent::new(
814            "router",
815            vec![
816                RouteRule::new(
817                    |s: &State| s.get::<String>("mode") == Some("a".into()),
818                    agent_a,
819                ),
820                RouteRule::new(
821                    |s: &State| s.get::<String>("mode") == Some("b".into()),
822                    agent_b,
823                ),
824            ],
825            default,
826        );
827
828        let state = State::new();
829        let _ = state.set("mode", "b");
830        let result = router.run(&state).await.unwrap();
831        assert_eq!(result, "route_b");
832    }
833
834    #[tokio::test]
835    async fn route_uses_default_when_no_match() {
836        let default: Arc<dyn TextAgent> =
837            Arc::new(FnTextAgent::new("default", |_| Ok("fallback".into())));
838
839        let router = RouteTextAgent::new(
840            "router",
841            vec![RouteRule::new(|_: &State| false, default.clone())],
842            default,
843        );
844
845        let state = State::new();
846        let result = router.run(&state).await.unwrap();
847        assert_eq!(result, "fallback");
848    }
849
850    // ── Async test helper ──
851
852    /// A test agent that sleeps asynchronously (cooperative with tokio timeout).
853    struct AsyncSleepAgent {
854        delay: Duration,
855    }
856
857    #[async_trait]
858    impl TextAgent for AsyncSleepAgent {
859        fn name(&self) -> &str {
860            "async-sleeper"
861        }
862        async fn run(&self, _state: &State) -> Result<String, AgentError> {
863            tokio::time::sleep(self.delay).await;
864            Ok("too late".into())
865        }
866    }
867
868    // ── RaceTextAgent ──
869
870    #[tokio::test]
871    async fn race_returns_first_to_complete() {
872        // Fast agent completes immediately, slow agent sleeps async.
873        let fast: Arc<dyn TextAgent> = Arc::new(FnTextAgent::new("fast", |_| Ok("winner".into())));
874        let slow: Arc<dyn TextAgent> = Arc::new(AsyncSleepAgent {
875            delay: Duration::from_millis(500),
876        });
877
878        let race = RaceTextAgent::new("race", vec![fast, slow]);
879        let state = State::new();
880        let result = race.run(&state).await.unwrap();
881        assert_eq!(result, "winner");
882    }
883
884    #[tokio::test]
885    async fn race_empty_returns_error() {
886        let race = RaceTextAgent::new("race", vec![]);
887        let state = State::new();
888        assert!(race.run(&state).await.is_err());
889    }
890
891    // ── TimeoutTextAgent ──
892
893    #[tokio::test]
894    async fn timeout_returns_result_within_limit() {
895        let fast: Arc<dyn TextAgent> = Arc::new(FnTextAgent::new("fast", |_| Ok("done".into())));
896        let timeout = TimeoutTextAgent::new("timeout", fast, Duration::from_secs(5));
897        let state = State::new();
898        let result = timeout.run(&state).await.unwrap();
899        assert_eq!(result, "done");
900    }
901
902    #[tokio::test]
903    async fn timeout_returns_error_when_exceeded() {
904        let slow: Arc<dyn TextAgent> = Arc::new(AsyncSleepAgent {
905            delay: Duration::from_secs(2),
906        });
907        let timeout = TimeoutTextAgent::new("timeout", slow, Duration::from_millis(50));
908        let state = State::new();
909        let err = timeout.run(&state).await.unwrap_err();
910        assert!(matches!(err, AgentError::Timeout));
911    }
912
913    // ── MapOverTextAgent ──
914
915    #[tokio::test]
916    async fn map_over_iterates_items() {
917        let agent: Arc<dyn TextAgent> = Arc::new(FnTextAgent::new("upper", |state: &State| {
918            let item: String = state
919                .get::<serde_json::Value>("_item")
920                .map(|v| v.as_str().unwrap_or("").to_string())
921                .unwrap_or_default();
922            Ok(item.to_uppercase())
923        }));
924
925        let map = MapOverTextAgent::new("mapper", agent, "items");
926        let state = State::new();
927        let _ = state.set(
928            "items",
929            vec![
930                serde_json::Value::String("hello".into()),
931                serde_json::Value::String("world".into()),
932            ],
933        );
934
935        let result = map.run(&state).await.unwrap();
936        assert!(result.contains("HELLO"));
937        assert!(result.contains("WORLD"));
938
939        let results: Vec<String> = state.get("_results").unwrap();
940        assert_eq!(results.len(), 2);
941        assert_eq!(results[0], "HELLO");
942        assert_eq!(results[1], "WORLD");
943    }
944
945    #[tokio::test]
946    async fn map_over_empty_list() {
947        let agent: Arc<dyn TextAgent> = Arc::new(FnTextAgent::new("noop", |_| Ok("x".into())));
948        let map = MapOverTextAgent::new("mapper", agent, "items");
949        let state = State::new();
950        // no "items" key → empty Vec
951        let result = map.run(&state).await.unwrap();
952        assert_eq!(result, "");
953    }
954
955    // ── TapTextAgent ──
956
957    #[tokio::test]
958    async fn tap_observes_state() {
959        let observed = Arc::new(std::sync::Mutex::new(String::new()));
960        let observed_clone = observed.clone();
961
962        let tap = TapTextAgent::new("observer", move |state: &State| {
963            let val = state.get::<String>("input").unwrap_or_default();
964            *observed_clone.lock().unwrap() = val;
965        });
966
967        let state = State::new();
968        let _ = state.set("input", "hello");
969        let result = tap.run(&state).await.unwrap();
970        assert_eq!(result, ""); // Tap returns empty string
971        assert_eq!(*observed.lock().unwrap(), "hello");
972    }
973
974    // ── DispatchTextAgent + JoinTextAgent ──
975
976    #[tokio::test]
977    async fn dispatch_and_join_round_trip() {
978        let registry = TaskRegistry::new();
979        let budget = Arc::new(tokio::sync::Semaphore::new(10));
980
981        let agent_a: Arc<dyn TextAgent> =
982            Arc::new(FnTextAgent::new("task_a", |_| Ok("result_a".into())));
983        let agent_b: Arc<dyn TextAgent> =
984            Arc::new(FnTextAgent::new("task_b", |_| Ok("result_b".into())));
985
986        let dispatch = DispatchTextAgent::new(
987            "dispatch",
988            vec![("task_a".into(), agent_a), ("task_b".into(), agent_b)],
989            registry.clone(),
990            budget,
991        );
992
993        let state = State::new();
994        let dispatch_result = dispatch.run(&state).await.unwrap();
995        assert_eq!(dispatch_result, ""); // Fire-and-forget returns empty
996
997        let join = JoinTextAgent::new("joiner", registry);
998        let join_result = join.run(&state).await.unwrap();
999        assert!(join_result.contains("result_a"));
1000        assert!(join_result.contains("result_b"));
1001    }
1002
1003    #[tokio::test]
1004    async fn join_with_target_names() {
1005        let registry = TaskRegistry::new();
1006        let budget = Arc::new(tokio::sync::Semaphore::new(10));
1007
1008        let children: Vec<(String, Arc<dyn TextAgent>)> = vec![
1009            (
1010                "x".into(),
1011                Arc::new(FnTextAgent::new("x", |_| Ok("rx".into()))),
1012            ),
1013            (
1014                "y".into(),
1015                Arc::new(FnTextAgent::new("y", |_| Ok("ry".into()))),
1016            ),
1017            (
1018                "z".into(),
1019                Arc::new(FnTextAgent::new("z", |_| Ok("rz".into()))),
1020            ),
1021        ];
1022
1023        let dispatch = DispatchTextAgent::new("dispatch", children, registry.clone(), budget);
1024        let state = State::new();
1025        dispatch.run(&state).await.unwrap();
1026
1027        // Only join x and z
1028        let join =
1029            JoinTextAgent::new("joiner", registry.clone()).targets(vec!["x".into(), "z".into()]);
1030        let result = join.run(&state).await.unwrap();
1031        assert!(result.contains("rx"));
1032        assert!(result.contains("rz"));
1033
1034        // y should still be in registry
1035        let remaining = registry.inner.lock().await;
1036        assert!(remaining.contains_key("y"));
1037    }
1038
1039    #[tokio::test]
1040    async fn join_with_timeout() {
1041        let registry = TaskRegistry::new();
1042        let budget = Arc::new(tokio::sync::Semaphore::new(10));
1043
1044        let slow: Arc<dyn TextAgent> = Arc::new(AsyncSleepAgent {
1045            delay: Duration::from_secs(2),
1046        });
1047
1048        let dispatch = DispatchTextAgent::new(
1049            "dispatch",
1050            vec![("slow".into(), slow)],
1051            registry.clone(),
1052            budget,
1053        );
1054        let state = State::new();
1055        dispatch.run(&state).await.unwrap();
1056
1057        let join = JoinTextAgent::new("joiner", registry).timeout(Duration::from_millis(50));
1058        let err = join.run(&state).await.unwrap_err();
1059        assert!(matches!(err, AgentError::Timeout));
1060    }
1061}